weapp-tailwindcss 5.4.2 → 5.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +13 -1
  2. package/README.zh-CN.md +13 -1
  3. package/dist/bundlers/shared/final-css-cleanup.d.ts +1 -1
  4. package/dist/bundlers/shared/v4-generation-core.d.ts +1 -0
  5. package/dist/bundlers/vite/capability-profile.d.ts +1 -0
  6. package/dist/bundlers/vite/css-finalizer/web-plugin.d.ts +3 -0
  7. package/dist/bundlers/vite/css-handler-options.d.ts +32 -0
  8. package/dist/bundlers/vite/{generate-bundle/css-output.d.ts → css-output.d.ts} +1 -1
  9. package/dist/bundlers/vite/frameworks/generic/web.d.ts +2 -0
  10. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +2 -32
  11. package/dist/bundlers/vite/generate-bundle/finalize/root-import-shell.d.ts +1 -1
  12. package/dist/bundlers/vite/generate-bundle/remembered-css-replay.d.ts +2 -2
  13. package/dist/bundlers/vite/generate-bundle/runtime.d.ts +1 -1
  14. package/dist/bundlers/vite/generate-bundle/uni-app-x-postprocess.d.ts +1 -1
  15. package/dist/bundlers/vite/generate-bundle.d.ts +1 -1
  16. package/dist/bundlers/vite/runtime-class-set.d.ts +1 -5
  17. package/dist/bundlers/vite/shared/create-css-only-plugins-runtime.d.ts +3 -0
  18. package/dist/cache-CBJFB1HN.cjs +223 -0
  19. package/dist/compiler/events.d.ts +32 -0
  20. package/dist/compiler/host.d.ts +13 -0
  21. package/dist/compiler/index.d.ts +3 -0
  22. package/dist/compiler/runtime-state.d.ts +17 -0
  23. package/dist/compiler-B0YSc0DY.js +4877 -0
  24. package/dist/{wxml-o-CUulAM.cjs → compiler-D2ZJc3uA.cjs} +3649 -283
  25. package/dist/core.cjs +6 -3
  26. package/dist/core.d.ts +2 -0
  27. package/dist/core.js +4 -4
  28. package/dist/defaults-B5ep0ojb.js +120 -0
  29. package/dist/defaults-BI9j1znS.cjs +156 -0
  30. package/dist/defaults.cjs +5 -121
  31. package/dist/defaults.js +1 -116
  32. package/dist/final-css-cleanup-B0HUBtiE.js +308 -0
  33. package/dist/final-css-cleanup-DSjczga3.cjs +138 -0
  34. package/dist/{generator-WlhrtNa3.cjs → generator-DsrQ9txU.cjs} +62 -5
  35. package/dist/{generator-BjK5PRR-.js → generator-DyXTBPmE.js} +47 -2
  36. package/dist/generator.cjs +1 -1
  37. package/dist/generator.js +1 -1
  38. package/dist/{gulp-ChecVI6A.cjs → gulp-C9ENAx3f.cjs} +30 -28
  39. package/dist/{gulp-D6LcfRz_.js → gulp-DXeQfvVC.js} +7 -7
  40. package/dist/gulp.cjs +1 -1
  41. package/dist/gulp.js +1 -1
  42. package/dist/{hmr-timing-afnWvy7u.cjs → hmr-timing-Cz4IesEM.cjs} +6 -229
  43. package/dist/{hmr-timing-CqDfjvqE.js → hmr-timing-DNxQm-bN.js} +6 -1258
  44. package/dist/index.cjs +4 -4
  45. package/dist/index.js +4 -4
  46. package/dist/{pipeline-helpers-DxPFMGxz.cjs → pipeline-helpers-CSGnR5gh.cjs} +6 -5
  47. package/dist/postcss.cjs +1 -1
  48. package/dist/postcss.js +1 -1
  49. package/dist/presets.cjs +4 -4
  50. package/dist/presets.js +2 -2
  51. package/dist/rspack.cjs +2 -2
  52. package/dist/rspack.js +2 -2
  53. package/dist/runtime-state-BBQcA0n5.cjs +54 -0
  54. package/dist/{source-candidate-scan-signature-FywFU3Rg.cjs → scoped-generator-TVjEaOeP.cjs} +5 -123
  55. package/dist/{source-candidate-scan-signature-BVScymyM.js → scoped-generator-kRj_5Axx.js} +4 -92
  56. package/dist/source-candidate-scan-signature-B7cUxqqX.cjs +129 -0
  57. package/dist/source-candidate-scan-signature-CsP4BQNa.js +92 -0
  58. package/dist/style-injector/internal.d.ts +1 -1
  59. package/dist/style-injector/vite-web.d.ts +3 -0
  60. package/dist/{tailwindcss-9xmoCkaR.js → tailwindcss-BK9S7zuq.js} +1 -2
  61. package/dist/{tailwindcss-D3jltF7M.cjs → tailwindcss-C-jBBQfw.cjs} +8 -9
  62. package/dist/{transform-DQhgAarN.js → transform-CfOzh007.js} +3 -3
  63. package/dist/{transform-C6k9zTQR.cjs → transform-DUPOPZ54.cjs} +27 -27
  64. package/dist/uni-app-x/vite/style-source.d.ts +11 -0
  65. package/dist/{v4-generation-core-CPKNwzjz.cjs → v4-generation-core-CRNUU_Rr.cjs} +29 -1172
  66. package/dist/vite/web.cjs +27 -0
  67. package/dist/vite/web.d.ts +1 -0
  68. package/dist/vite/web.js +25 -0
  69. package/dist/{vite-D3aCtpmv.js → vite-BXe-axax.js} +263 -3587
  70. package/dist/{vite-D-gmOkPN.cjs → vite-D_mAIfTU.cjs} +514 -3798
  71. package/dist/vite-web.d.ts +4 -0
  72. package/dist/vite.cjs +1 -1
  73. package/dist/vite.js +1 -1
  74. package/dist/weapp-tw-css-generation-loader.cjs +1 -1
  75. package/dist/weapp-tw-css-import-rewrite-loader.cjs +5 -5
  76. package/dist/web-B2Ea9K4B.cjs +4361 -0
  77. package/dist/web-Cv7ualrU.js +3796 -0
  78. package/dist/{webpack-B-6a8Z8F.js → webpack-7Um2GFtx.js} +13 -12
  79. package/dist/{webpack-yAne9ZYu.cjs → webpack-Ce04-btG.cjs} +51 -49
  80. package/dist/webpack.cjs +1 -1
  81. package/dist/webpack.js +1 -1
  82. package/package.json +13 -4
  83. package/dist/cache-options-DavPxrhC.cjs +0 -16
  84. package/dist/cache-options-DwBtLwQe.js +0 -5
  85. package/dist/compiler-B-m9VGqj.cjs +0 -2316
  86. package/dist/compiler-BgMj2E5l.js +0 -2051
  87. package/dist/local-style-matcher-DRpFEu1s.cjs +0 -34
  88. package/dist/local-style-matcher-DsiI2wIc.js +0 -17
  89. package/dist/object-B-8IHefx.js +0 -47
  90. package/dist/object-DbHtAXRk.cjs +0 -58
  91. package/dist/wxml-CvKyV69S.js +0 -1822
@@ -1,216 +1,29 @@
1
1
  import { resolveImplicitAppTypeFromViteRoot } from "./framework.js";
2
- import { $ as hasTailwindSourceDirectives, B as stripMiniProgramCssSpecificityPlaceholders, D as resolveTailwindcssOptions, Ft as filterUnsupportedMiniProgramTailwindV4Candidates, K as hasUserCssLayerBlocks, L as hasMiniProgramCssSpecificityPlaceholders, Ot as resolveSourceScanPath, Pt as getTailwindV4IncrementalGenerateCacheStats, Q as hasTailwindRootDirectives, S as findNearestPackageRoot, U as normalizeEmptyTailwindCustomVariants, X as hasTailwindApplyDirective, Y as hasLocalCssImport, Z as hasTailwindNonRootGenerationDirectives, _ as upsertTailwindV4CssSource, a as resolveGeneratorRuntimeBranch, b as isTailwindV4CssEntry, c as shouldUseNativeAppCssBranch, et as normalizeTailwindConfigDirectives, h as hasConfiguredTailwindV4CssRoots, i as normalizeWeappTailwindcssGeneratorOptions, it as removeTailwindSourceDirectives, kt as resolveTailwindV4CssSourceBase, l as resolveUniUtsPlatform, lt as hasTailwindGeneratedCss, m as filterTailwindV4CssSourceRoots, mt as stripGeneratorPlaceholderMarkers, nt as normalizeTailwindSourceForGenerator, q as splitUserCssLayerBlocks, rt as parseImportRequest, s as shouldUseMiniProgramCssBranch, ut as hasTailwindGeneratedCssMarkers, wt as isFileMatchedByTailwindSourceEntries, x as normalizeCssEntries } from "./generator-BjK5PRR-.js";
3
- import { t as omitUndefined } from "./object-B-8IHefx.js";
4
- import { a as findTailwindConfig, f as resolveSourceScanEntries, g as resolveTailwindV4EntriesFromCssCached, i as resolveUniAppXOptions, l as getRuntimeClassSetSignature, m as resolveTailwindV4CssDependencies, p as discoverTailwindV4CssEntries, r as isUniAppXEnabled } from "./tailwindcss-9xmoCkaR.js";
2
+ import { $ as hasTailwindRootDirectives, At as resolveTailwindV4CssSourceBase, It as getTailwindV4IncrementalGenerateCacheStats, J as splitUserCssLayerBlocks, Lt as filterUnsupportedMiniProgramTailwindV4Candidates, O as resolveTailwindcssOptions, R as hasMiniProgramCssSpecificityPlaceholders, T as omitUndefined, Tt as isFileMatchedByTailwindSourceEntries, V as stripMiniProgramCssSpecificityPlaceholders, W as normalizeEmptyTailwindCustomVariants, Z as hasTailwindApplyDirective, _ as upsertTailwindV4CssSource, a as resolveGeneratorRuntimeBranch, at as removeTailwindSourceDirectives, b as isTailwindV4CssEntry, c as shouldUseNativeAppCssBranch, dt as hasTailwindGeneratedCssMarkers, et as hasTailwindSourceDirectives, h as hasConfiguredTailwindV4CssRoots, i as normalizeWeappTailwindcssGeneratorOptions, it as parseImportRequest, l as resolveUniUtsPlatform, m as filterTailwindV4CssSourceRoots, q as hasUserCssLayerBlocks, rt as normalizeTailwindSourceForGenerator, s as shouldUseMiniProgramCssBranch, tt as normalizeTailwindConfigDirectives, x as normalizeCssEntries } from "./generator-DyXTBPmE.js";
3
+ import { g as resolveTailwindV4EntriesFromCssCached, i as resolveUniAppXOptions, l as getRuntimeClassSetSignature, m as resolveTailwindV4CssDependencies, p as discoverTailwindV4CssEntries, r as isUniAppXEnabled } from "./tailwindcss-BK9S7zuq.js";
5
4
  import "./utils-MVwpU07P.js";
6
- import { $ as AssetEmissionPlan, A as hasEmptyAtRuleBlockCandidate, C as isSourceStyleRequest, D as parseBundlerGeneratedCssMarkerBlocks, E as hasBundlerGeneratedCssMarker, F as processCachedTask, G as createRuntimeCompilationBuildState, H as finalizeCompilerShadowRun, I as createRuntimeClassSetManager, J as updateRuntimeCompilationBuildState, M as createCssSourceTraceCacheSignature, N as createCssTokenSourceMap, O as stripBundlerGeneratedCssMarkers, P as isCssSourceTraceEnabled, S as isSourcePreprocessorRequest, T as createBundlerGeneratedCssMarker, U as buildRuntimeCompilationSnapshot, X as disposeCompilerOwner, Y as createRuntimeAffectingSourceSignature, Z as beginCompilerShadowRun, a as extractMarkedUserLayerComponentsCss, ct as createSourceCandidateEligibilityMatcher, d as runWithConcurrency, f as normalizeMiniProgramGeneratorCssSource, g as captureFrameworkPostcssOptions, i as validateCandidatesByGenerator, it as createSourceCandidateCollector, j as annotateCssSourceTrace, k as finalizeMiniProgramCssStructure, m as scoreTailwindV4CssSourceFileMatch, nt as recordCompilationDependencyChanges, o as mergeMarkedUserLayerComponentsCss, ot as isSourceCandidateRequest, p as normalizeMiniProgramImportShell, r as generateTailwindV4Css, rt as createCompilationDependencyChanges, s as collectGeneratedRawSourceCandidatesFromCss, st as extractCandidatesFromSource, t as createHmrTimingRecorder, w as stripRequestQuery, z as isPureLocalCssImportWrapper } from "./hmr-timing-CqDfjvqE.js";
7
- import { m as createDebug, p as replaceWxml } from "./wxml-CvKyV69S.js";
8
- import { c as toCustomAttributesEntities, d as collectRuntimeClassSet, f as createTailwindRuntimeReadyPromise, h as normalizeFrameworkStylePlatform, l as logTailwindcssTarget, m as refreshTailwindRuntimeState, n as getCompilerContext, o as vitePluginName, r as normalizeStyleHandlerMajorVersion, s as shouldSkipJsTransform, u as logRuntimeTailwindcssVersion } from "./compiler-BgMj2E5l.js";
9
- import { _ as createBuiltinViteStyleInjectorPlugins, a as createCandidateSignature, c as getSnapshotHash, d as classifyRuntimeEntry, f as resolvePackageDir, g as toAbsoluteOutputPath, h as resolveOutputSpecifier, i as createScopedGeneratorSourceTraceMap, l as hasRuntimeAffectingSourceChanges, m as normalizeOutputPathKey, n as createScopedGeneratorCandidateSignature, o as createJsHashSalt, p as resolvePluginDisabledState, r as createScopedGeneratorRuntime, s as createLinkedImpactSignature, t as createSourceCandidateScanSignature, u as summarizeStringDiff, x as resolveViteFrameworkProfile, y as viteStyleInjectorDelegates } from "./source-candidate-scan-signature-BVScymyM.js";
10
- import { n as shouldEnableComponentLocalStyle, r as shouldEnablePageLocalStyle, t as normalizeUniAppXLocalStyleId } from "./local-style-matcher-DsiI2wIc.js";
5
+ import { A as createCssSourceTraceCacheSignature, B as createSourceCandidateCollector, C as isSourceStyleRequest, D as parseBundlerGeneratedCssMarkerBlocks, E as hasBundlerGeneratedCssMarker, H as isSourceCandidateRequest, I as isPureLocalCssImportWrapper, M as isCssSourceTraceEnabled, O as stripBundlerGeneratedCssMarkers, S as isSourcePreprocessorRequest, T as createBundlerGeneratedCssMarker, U as extractCandidatesFromSource, a as extractMarkedUserLayerComponentsCss, d as runWithConcurrency, f as normalizeMiniProgramGeneratorCssSource, i as validateCandidatesByGenerator, j as createCssTokenSourceMap, k as annotateCssSourceTrace, m as scoreTailwindV4CssSourceFileMatch, o as mergeMarkedUserLayerComponentsCss, p as normalizeMiniProgramImportShell, r as generateTailwindV4Css, s as collectGeneratedRawSourceCandidatesFromCss, t as createHmrTimingRecorder, z as finalizeCompilerShadowRun } from "./hmr-timing-DNxQm-bN.js";
6
+ import { E as normalizeFrameworkStylePlatform, G as replaceWxml, K as createDebug, L as createCompilationDependencyChanges, N as recordCompilationDependencyChanges, O as AssetEmissionPlan, a as beginCompilerShadowRun, b as logTailwindcssTarget, f as getCompilerContext, g as vitePluginName, i as disposeCompilerOwner, n as createRuntimeAffectingSourceSignature, v as shouldSkipJsTransform, x as logRuntimeTailwindcssVersion, y as toCustomAttributesEntities } from "./compiler-B0YSc0DY.js";
7
+ import { i as buildRuntimeCompilationSnapshot, l as updateRuntimeCompilationBuildState, n as hasEmptyCssBlockCandidate, o as createRuntimeCompilationBuildState, r as processCachedTask, t as finalizeMiniProgramCssStructure } from "./final-css-cleanup-B0HUBtiE.js";
8
+ import { a as createJsHashSalt, c as hasRuntimeAffectingSourceChanges, d as resolvePluginDisabledState, f as createBuiltinViteStyleInjectorPlugins, g as resolveViteFrameworkProfile, i as createCandidateSignature, l as summarizeStringDiff, m as viteStyleInjectorDelegates, n as createScopedGeneratorRuntime, o as createLinkedImpactSignature, r as createScopedGeneratorSourceTraceMap, s as getSnapshotHash, t as createScopedGeneratorCandidateSignature, u as classifyRuntimeEntry } from "./scoped-generator-kRj_5Axx.js";
9
+ import { $ as isMatchingCssSourceFile, A as createGenericWebProductionSourceCandidatesApply, At as resolveViteCssPipelineOutputFileFromSourceFile, B as parseVueRequest, Bt as createViteCssAssetIdentityResolver, C as collectViteProcessedCssSources, Ct as SOURCE_STYLE_OUTPUT_EXT_RE, D as registerGeneratorDependencies$1, Dt as resolveReplayCssOutputFile, E as inferPlatformFromViteOutDir$1, Et as resolveMiniProgramStyleOutputExtension, F as resolveHotSourceModulesByIds, Ft as normalizePath, G as hasSfcStyleSources, Gt as frameworkViteCapabilityProfile, H as shouldApplyViteWebCssCompat, Ht as getActiveViteSourceOutputRelationOwner, I as resolveHotTailwindCssModules, It as resolveViteCssPipelineRequestFile, J as normalizeSfcSourceFileForCompare, K as hasTailwindGenerationSource, L as sendFullReloadForUnresolvedHotUpdate, Lt as slash, M as hasSelfAcceptingNonStyleHotModule, Mt as formatPostcssSourceMap, N as mergeHotModulesByIdentity, Nt as isCSSRequest, O as shouldGenerateCssByGenerator, Ot as resolveViteCssOutputFile, P as resolveHotSourceModules, Pt as isHTMLRequest, Q as hasMatchingStyleFileBase, R as sendSupplementalCssHotUpdates, Rt as createCssHandlerOptionsCache, S as tryFinalizeGenericWebCss, St as CSS_SOURCE_OUTPUT_EXT_RE, T as finalizeWebCss, Tt as normalizeCssSourceForCompare, U as collectChunkModuleIds$3, Ut as withViteSourceOutputRelationOwner, V as resolveViteWebCssCompatOptions, Vt as createViteSourceOutputRelationOwner, W as extractSfcStyleBlocks, Wt as createGenericWebViteCapabilityProfile, X as resolveSfcStyleSourceFromOutputFile, Y as resolveSfcStyleRequestFromKnownSource, Z as resolveSourceStyleSourceFromOutputFile, _ as summarizeStringCache, _t as resolveViteProcessedCssAssetSource, a as createFrameworkProcessedCssRegistry, at as createCssAssetPipelineContext, b as touchMapEntry, bt as isRootStyleOutputFile, c as createViteHmrCssModuleVersionTracker, ct as hasNonCommentCss, d as createViteCssGenerationPlugins, dt as normalizeInjectableCssForTarget, et as appendCss$1, f as createViteRuntimeClassSet, ft as normalizeInjectableCssForTargetWithImports, g as normalizeVitePersistentCacheKey, gt as removeTailwindEntryDirectivesFromCss, h as isMissingInternalCssSource, ht as removeDuplicateUnlinkedRootCssAssetsReferencedByHtml, i as syncFrameworkSourceCandidatesForHotUpdate, it as collectRootStyleBundleCssSources, j as shouldSkipGenericWebProductionSourceCandidates, jt as cleanUrl$1, k as createGenericWebProductionBundleHooks, kt as resolveViteCssPipelineOutputFile, l as createViteHmrCandidateState, lt as isMatchingGeneratedCssMarkerFile, m as hasVitePipelineTailwindGenerationDirective, mt as readAssetSource$2, n as createFrameworkTailwindRootCss, nt as collectImportedStyleFiles, o as createFrameworkPostPlugin, ot as dedupeViteCssResults, p as createRewriteCssImportsPlugins, pt as normalizeMarkerOutputFile, q as isSfcStyleSourceFile, r as createFrameworkSourceScanSession, rt as collectMatchingGeneratedCssMarkerFiles, s as createViteHmrCssModuleVersionFilterPlugin, st as getAssetFile$1, t as createGenericWebVitePlugins, tt as clearAssetSource, u as createFrameworkCssGenerationQueue, ut as isStyleImportRequest, v as createViteCssMemory, vt as isCssOutputFile, w as createCssHandlerOptions, wt as canProcessViteSourceStyleAsCss, x as createViteWebCssFinalizerOutputPlugin, xt as posix, y as shouldCollectTransformedSourceCandidates, yt as isMiniProgramStyleOutputFile, z as resolveViteModuleIdentity, zt as resolveViteCssHandlerExtraOptions } from "./web-Cv7ualrU.js";
10
+ import { a as toAbsoluteOutputPath, i as resolveOutputSpecifier, n as resolvePackageDir, r as normalizeOutputPathKey } from "./source-candidate-scan-signature-CsP4BQNa.js";
11
11
  import { t as logger$1 } from "./logger-BNzxZbZj.js";
12
- import fs, { existsSync, readFileSync, realpathSync } from "node:fs";
12
+ import fs, { existsSync, readFileSync } from "node:fs";
13
13
  import path from "node:path";
14
- import process$1 from "node:process";
14
+ import process from "node:process";
15
15
  import { splitCandidateTokens } from "@tailwindcss-mangle/engine";
16
- import { collectCssImportRequestsRoot, compileCssMacroConditionalComments, containsCssAfterMinify, filterExistingCssRules, isMiniProgramLocalCssImportRequest, mergeCoveredCssRuleDeclarations, mergeMiniProgramPreflightRuleDeclarations, mergeMiniProgramThemeScopeRuleDeclarations, normalizeTailwindcssV4InfinityCalcCss, normalizeUniAppXImportantApplyForSass, parseTailwindCssDirectiveRequest, postcss, removeTailwindPostcssPlugins, removeTailwindSourceDirectivesRoot, removeUnsupportedMiniProgramCssImportsRoot, resolvePostcssConfig, restoreUniAppXImportantApplyMarker, transformWebCssCompat, transformWebCssSafeSelectors, unwrapUnsupportedCascadeLayers } from "@weapp-tailwindcss/postcss";
16
+ import { compileCssMacroConditionalComments, containsCssAfterMinify, filterExistingCssRules, isMiniProgramLocalCssImportRequest, mergeCoveredCssRuleDeclarations, mergeMiniProgramPreflightRuleDeclarations, mergeMiniProgramThemeScopeRuleDeclarations, normalizeTailwindcssV4InfinityCalcCss, normalizeUniAppXImportantApplyForSass, parseTailwindCssDirectiveRequest, postcss, restoreUniAppXImportantApplyMarker, transformWebCssCompat, transformWebCssSafeSelectors, unwrapUnsupportedCascadeLayers } from "@weapp-tailwindcss/postcss";
17
17
  import { LRUCache } from "lru-cache";
18
18
  import { readFile } from "node:fs/promises";
19
19
  import micromatch from "micromatch";
20
- import { cleanUrl as cleanUrl$1, ensurePosix } from "@weapp-tailwindcss/shared";
20
+ import { cleanUrl, ensurePosix } from "@weapp-tailwindcss/shared";
21
21
  import { Buffer } from "node:buffer";
22
22
  import { logger } from "@weapp-tailwindcss/logger";
23
- import { fileURLToPath } from "node:url";
24
23
  import { AsyncLocalStorage } from "node:async_hooks";
25
24
  import { parse } from "comment-json";
26
- //#region src/bundlers/vite/capability-profile.ts
27
- const frameworkViteCapabilityProfile = {
28
- name: "framework",
29
- frameworkName: "generic",
30
- generatorTarget: void 0,
31
- platformFamily: "unknown",
32
- sourceCandidates: true,
33
- frameworkExtras: true,
34
- serveJsTransform: true,
35
- styleInjector: true
36
- };
37
- function createGenericWebViteCapabilityProfile(options) {
38
- return {
39
- name: "generic-web",
40
- frameworkName: "generic",
41
- generatorTarget: "web",
42
- platformFamily: "web",
43
- sourceCandidates: options.cssSourceTrace === true || typeof options.cssSourceTrace === "object",
44
- frameworkExtras: false,
45
- serveJsTransform: false,
46
- styleInjector: options.styleInjector !== void 0
47
- };
48
- }
49
- //#endregion
50
- //#region src/bundlers/vite/source-output-relations.ts
51
- const activeRelationOwnerStorage = new AsyncLocalStorage();
52
- function normalizeSourceFile$1(sourceFile) {
53
- return normalizeOutputPathKey(sourceFile.replace(/[?#].*$/, ""));
54
- }
55
- function normalizeOutputFile(outputFile) {
56
- return normalizeOutputPathKey(outputFile);
57
- }
58
- function collectOwnedSources(output) {
59
- if (output.type === "chunk") {
60
- if (output.facadeModuleId) return [output.facadeModuleId];
61
- const moduleIds = Array.isArray(output.moduleIds) ? output.moduleIds : [];
62
- return moduleIds.length === 1 ? moduleIds : [];
63
- }
64
- return [output.originalFileName, ...Array.isArray(output.originalFileNames) ? output.originalFileNames : []].filter((sourceFile) => typeof sourceFile === "string" && sourceFile.length > 0);
65
- }
66
- function createViteSourceOutputRelationOwner() {
67
- const outputsBySource = /* @__PURE__ */ new Map();
68
- const sourcesByOutput = /* @__PURE__ */ new Map();
69
- const deletedSources = /* @__PURE__ */ new Set();
70
- const dirtySources = /* @__PURE__ */ new Set();
71
- const consumers = /* @__PURE__ */ new Set();
72
- let disposed = false;
73
- const unlinkSourceFromOutput = (sourceFile, outputFile) => {
74
- const outputs = outputsBySource.get(sourceFile);
75
- outputs?.delete(outputFile);
76
- if (outputs?.size === 0) outputsBySource.delete(sourceFile);
77
- const sources = sourcesByOutput.get(outputFile);
78
- sources?.delete(sourceFile);
79
- if (sources?.size === 0) sourcesByOutput.delete(outputFile);
80
- };
81
- const unlinkSource = (sourceFile) => {
82
- const outputs = [...outputsBySource.get(sourceFile) ?? []];
83
- for (const outputFile of outputs) unlinkSourceFromOutput(sourceFile, outputFile);
84
- return outputs;
85
- };
86
- const queueRemovedOutputs = (outputFiles) => {
87
- for (const outputFile of outputFiles) {
88
- if (sourcesByOutput.has(outputFile)) continue;
89
- for (const consumer of consumers) consumer.pending.add(outputFile);
90
- }
91
- };
92
- const recordOwnedOutput = (sourceFile, outputFile) => {
93
- if (disposed) return;
94
- const sourceKey = normalizeSourceFile$1(sourceFile);
95
- const outputKey = normalizeOutputFile(outputFile);
96
- if (!sourceKey || !outputKey || deletedSources.has(sourceKey)) return;
97
- if (dirtySources.delete(sourceKey)) queueRemovedOutputs(unlinkSource(sourceKey));
98
- const outputs = outputsBySource.get(sourceKey) ?? /* @__PURE__ */ new Set();
99
- outputs.add(outputKey);
100
- outputsBySource.set(sourceKey, outputs);
101
- const sources = sourcesByOutput.get(outputKey) ?? /* @__PURE__ */ new Set();
102
- sources.add(sourceKey);
103
- sourcesByOutput.set(outputKey, sources);
104
- };
105
- const replaceOutputOwners = (outputFile, sourceFiles) => {
106
- const outputKey = normalizeOutputFile(outputFile);
107
- for (const sourceFile of [...sourcesByOutput.get(outputKey) ?? []]) unlinkSourceFromOutput(sourceFile, outputKey);
108
- for (const sourceFile of sourceFiles) {
109
- deletedSources.delete(normalizeSourceFile$1(sourceFile));
110
- recordOwnedOutput(sourceFile, outputKey);
111
- }
112
- };
113
- return {
114
- createRemovalConsumer() {
115
- const state = { pending: /* @__PURE__ */ new Set() };
116
- consumers.add(state);
117
- return { consume(currentBundleFiles) {
118
- if (disposed || state.pending.size === 0) return [];
119
- const currentFiles = new Set([...currentBundleFiles].map(normalizeOutputFile));
120
- const removedFiles = [...state.pending].filter((file) => !currentFiles.has(file));
121
- state.pending.clear();
122
- return removedFiles;
123
- } };
124
- },
125
- dispose() {
126
- disposed = true;
127
- outputsBySource.clear();
128
- sourcesByOutput.clear();
129
- deletedSources.clear();
130
- dirtySources.clear();
131
- consumers.clear();
132
- },
133
- getStats() {
134
- return {
135
- consumers: consumers.size,
136
- dirtySources: dirtySources.size,
137
- outputs: sourcesByOutput.size,
138
- pendingOutputs: new Set([...consumers].flatMap((consumer) => [...consumer.pending])).size,
139
- sources: outputsBySource.size
140
- };
141
- },
142
- getOutputSources(outputFile) {
143
- return new Set(sourcesByOutput.get(normalizeOutputFile(outputFile)) ?? []);
144
- },
145
- getOwnedOutputs(sourceFile) {
146
- return new Set(outputsBySource.get(normalizeSourceFile$1(sourceFile)) ?? []);
147
- },
148
- observeSource(sourceFile) {
149
- if (!disposed) {
150
- const sourceKey = normalizeSourceFile$1(sourceFile);
151
- deletedSources.delete(sourceKey);
152
- if (outputsBySource.has(sourceKey)) dirtySources.add(sourceKey);
153
- }
154
- },
155
- recordBundle(bundle) {
156
- if (disposed) return;
157
- for (const [bundleFile, output] of Object.entries(bundle)) {
158
- const ownedSources = collectOwnedSources(output);
159
- if (ownedSources.length > 0) replaceOutputOwners(output.fileName || bundleFile, ownedSources);
160
- }
161
- },
162
- recordOwnedOutput,
163
- removeSource(sourceFile) {
164
- if (disposed) return /* @__PURE__ */ new Set();
165
- const sourceKey = normalizeSourceFile$1(sourceFile);
166
- deletedSources.add(sourceKey);
167
- dirtySources.delete(sourceKey);
168
- const removedOutputs = /* @__PURE__ */ new Set();
169
- for (const outputFile of unlinkSource(sourceKey)) if (!sourcesByOutput.has(outputFile)) removedOutputs.add(outputFile);
170
- queueRemovedOutputs(removedOutputs);
171
- return removedOutputs;
172
- }
173
- };
174
- }
175
- function getActiveViteSourceOutputRelationOwner() {
176
- return activeRelationOwnerStorage.getStore();
177
- }
178
- function withViteSourceOutputRelationOwner(owner, run) {
179
- return activeRelationOwnerStorage.run(owner, run);
180
- }
181
- //#endregion
182
- //#region src/bundlers/vite/css-asset-identity.ts
183
- function createViteCssAssetIdentityResolver(options) {
184
- const identityByAsset = /* @__PURE__ */ new WeakMap();
185
- const placeholderFile = normalizeOutputPathKey(path.resolve(options.generatorPlaceholderFile));
186
- return (asset, file) => {
187
- const cached = identityByAsset.get(asset);
188
- if (cached) return cached;
189
- const candidates = [
190
- file,
191
- asset.originalFileName,
192
- ...asset.originalFileNames ?? []
193
- ].filter((candidate) => typeof candidate === "string" && candidate.length > 0);
194
- const placeholderSourceFile = candidates.find((candidate) => normalizeOutputPathKey(path.resolve(candidate.replace(/[?#].*$/, ""))) === placeholderFile);
195
- let identity;
196
- if (placeholderSourceFile) identity = {
197
- kind: "generator-placeholder",
198
- sourceFile: placeholderSourceFile
199
- };
200
- else {
201
- const processedSourceFile = candidates.find(options.isKnownProcessedSource);
202
- identity = processedSourceFile ? {
203
- kind: "bundler-generated",
204
- sourceFile: processedSourceFile
205
- } : { kind: "user" };
206
- }
207
- identityByAsset.set(asset, identity);
208
- return identity;
209
- };
210
- }
211
- //#endregion
212
25
  //#region src/uni-app-x/style-asset/harmony-apply.ts
213
- const SFC_STYLE_BLOCK_RE$3 = /(<style\b[^>]*>)([\s\S]*?)(<\/style>)/gi;
26
+ const SFC_STYLE_BLOCK_RE$1 = /(<style\b[^>]*>)([\s\S]*?)(<\/style>)/gi;
214
27
  function createGeneratedRuleMap(css) {
215
28
  let root;
216
29
  try {
@@ -228,7 +41,7 @@ function expandUniAppXHarmonyApplyStyles(source, generatedCss) {
228
41
  if (!source.includes("@apply")) return source;
229
42
  const generatedRules = createGeneratedRuleMap(generatedCss);
230
43
  if (!generatedRules) return source;
231
- return source.replace(SFC_STYLE_BLOCK_RE$3, (block, open, styleSource, close) => {
44
+ return source.replace(SFC_STYLE_BLOCK_RE$1, (block, open, styleSource, close) => {
232
45
  if (!styleSource.includes("@apply")) return block;
233
46
  let root;
234
47
  try {
@@ -251,11 +64,26 @@ function expandUniAppXHarmonyApplyStyles(source, generatedCss) {
251
64
  });
252
65
  }
253
66
  //#endregion
67
+ //#region src/uni-app-x/local-style-matcher.ts
68
+ const COMPONENT_RE = /(?:^|\/)components(?:\/.+)?\.(?:uvue|nvue)$/;
69
+ const PAGE_RE = /(?:^|\/)pages(?:\/.+)?\.(?:uvue|nvue)$/;
70
+ function normalizeUniAppXLocalStyleId(id) {
71
+ return ensurePosix(cleanUrl(id));
72
+ }
73
+ function shouldEnableComponentLocalStyle(id, matcher) {
74
+ const normalizedId = normalizeUniAppXLocalStyleId(id);
75
+ return matcher ? matcher(normalizedId) : COMPONENT_RE.test(normalizedId);
76
+ }
77
+ function shouldEnablePageLocalStyle(id, matcher) {
78
+ const normalizedId = normalizeUniAppXLocalStyleId(id);
79
+ return matcher ? matcher(normalizedId) : PAGE_RE.test(normalizedId);
80
+ }
81
+ //#endregion
254
82
  //#region src/uni-app-x/style-asset/style-value.ts
255
83
  const GEN_APP_STYLES_RE = /const\s+GenAppStyles\s*=\s*\[_uM\(\[([\s\S]*?)\]\)\]/;
256
84
  const STYLE_ENTRY_RE = /\[\s*("((?:\\.|[^"\\])+)")\s*,\s*(_pS\(_uM\(\[[\s\S]*?\]\)\))\s*\]/g;
257
85
  const STRING_LITERAL_RE = /(['"`])((?:\\.|(?!\1)[\s\S])*?)\1/g;
258
- const SFC_STYLE_BLOCK_RE$2 = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
86
+ const SFC_STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
259
87
  const STYLE_EXPORT_PREFIX_RE = /^\s*export\s+default\s+/;
260
88
  const CLASS_SELECTOR_PREFIX_RE = /^\.((?:\\[^\n\r\f]|[\w-])+)(?=$|[.:#[])/;
261
89
  const STRING_STYLE_PROPERTIES = /* @__PURE__ */ new Set(["lineHeight"]);
@@ -405,7 +233,7 @@ function createStyleValueFromApplySources(sources, utilityStyles) {
405
233
  if (!utilityStyles) return;
406
234
  const result = {};
407
235
  for (const source of sources) {
408
- const styleSources = source.includes("<style") ? [...source.matchAll(SFC_STYLE_BLOCK_RE$2)].map((styleBlock) => styleBlock[1] ?? "") : [source];
236
+ const styleSources = source.includes("<style") ? [...source.matchAll(SFC_STYLE_BLOCK_RE)].map((styleBlock) => styleBlock[1] ?? "") : [source];
409
237
  for (const styleSource of styleSources) {
410
238
  let root;
411
239
  try {
@@ -459,7 +287,7 @@ function resolveReferencePaths(styleSource, sourceId) {
459
287
  return root.toString();
460
288
  }
461
289
  function collectUniAppXHarmonyApplyStyleSourcesFromSource(source, sourceId) {
462
- return (source.includes("<style") ? [...source.matchAll(SFC_STYLE_BLOCK_RE$2)].map((styleBlock) => styleBlock[1] ?? "") : [source]).map((styleSource) => resolveReferencePaths(styleSource.trim(), sourceId)).filter((styleSource) => styleSource.length > 0 && styleSource.includes("@apply"));
290
+ return (source.includes("<style") ? [...source.matchAll(SFC_STYLE_BLOCK_RE)].map((styleBlock) => styleBlock[1] ?? "") : [source]).map((styleSource) => resolveReferencePaths(styleSource.trim(), sourceId)).filter((styleSource) => styleSource.length > 0 && styleSource.includes("@apply"));
463
291
  }
464
292
  function collectUniAppXHarmonyApplyUtilitiesFromSources(sources) {
465
293
  const utilities = /* @__PURE__ */ new Set();
@@ -877,7 +705,7 @@ function isDependencyModuleId(id) {
877
705
  const normalized = toPosixPath(id);
878
706
  return normalized.includes("/node_modules/") || normalized.includes("/.pnpm/") || normalized.includes("/node_modules_");
879
707
  }
880
- function collectChunkModuleIds$3(output) {
708
+ function collectChunkModuleIds$2(output) {
881
709
  return [...output.moduleIds ?? [], ...Object.keys(output.modules ?? {})].filter((id, index, ids) => ids.indexOf(id) === index);
882
710
  }
883
711
  function isKnownVendorChunkFile(file) {
@@ -887,7 +715,7 @@ function isKnownVendorChunkFile(file) {
887
715
  }
888
716
  function isDependencyOnlyChunk(output) {
889
717
  if (output.isEntry || output.isDynamicEntry || output.isImplicitEntry) return false;
890
- const moduleIds = collectChunkModuleIds$3(output);
718
+ const moduleIds = collectChunkModuleIds$2(output);
891
719
  return moduleIds.length > 0 && moduleIds.every(isDependencyModuleId);
892
720
  }
893
721
  function isRuntimeCandidateBundleEntry(entry) {
@@ -897,7 +725,7 @@ function isRuntimeCandidateBundleEntry(entry) {
897
725
  if (!isKnownVendorChunkFile(entry.file)) return true;
898
726
  if (entry.output.type !== "chunk") return false;
899
727
  if (entry.output.facadeModuleId && !isDependencyModuleId(entry.output.facadeModuleId)) return true;
900
- return collectChunkModuleIds$3(entry.output).some((id) => !isDependencyModuleId(id));
728
+ return collectChunkModuleIds$2(entry.output).some((id) => !isDependencyModuleId(id));
901
729
  }
902
730
  //#endregion
903
731
  //#region src/bundlers/vite/bundle-state.ts
@@ -975,692 +803,6 @@ function updateBundleBuildState(state, snapshot, linkedByEntry, options = {}) {
975
803
  }
976
804
  }
977
805
  //#endregion
978
- //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
979
- let _lazyMatch = () => {
980
- var __lib__ = (() => {
981
- var m = Object.defineProperty, V = Object.getOwnPropertyDescriptor, G = Object.getOwnPropertyNames, T = Object.prototype.hasOwnProperty, q = (r, e) => {
982
- for (var n in e) m(r, n, {
983
- get: e[n],
984
- enumerable: true
985
- });
986
- }, H = (r, e, n, a) => {
987
- if (e && typeof e == "object" || typeof e == "function") for (let t of G(e)) !T.call(r, t) && t !== n && m(r, t, {
988
- get: () => e[t],
989
- enumerable: !(a = V(e, t)) || a.enumerable
990
- });
991
- return r;
992
- }, J = (r) => H(m({}, "__esModule", { value: true }), r), w = {};
993
- q(w, { default: () => re });
994
- var A = (r) => Array.isArray(r), d = (r) => typeof r == "function", Q = (r) => r.length === 0, W = (r) => typeof r == "number", K = (r) => typeof r == "object" && r !== null, X = (r) => r instanceof RegExp, b = (r) => typeof r == "string", h = (r) => r === void 0, Y = (r) => {
995
- const e = /* @__PURE__ */ new Map();
996
- return (n) => {
997
- const a = e.get(n);
998
- if (a) return a;
999
- const t = r(n);
1000
- return e.set(n, t), t;
1001
- };
1002
- }, rr = (r, e, n = {}) => {
1003
- const a = {
1004
- cache: {},
1005
- input: r,
1006
- index: 0,
1007
- indexMax: 0,
1008
- options: n,
1009
- output: []
1010
- };
1011
- if (v(e)(a) && a.index === r.length) return a.output;
1012
- throw new Error(`Failed to parse at index ${a.indexMax}`);
1013
- }, i = (r, e) => A(r) ? er(r, e) : b(r) ? ar(r, e) : nr(r, e), er = (r, e) => {
1014
- const n = {};
1015
- for (const a of r) {
1016
- if (a.length !== 1) throw new Error(`Invalid character: "${a}"`);
1017
- const t = a.charCodeAt(0);
1018
- n[t] = true;
1019
- }
1020
- return (a) => {
1021
- const t = a.index, o = a.input;
1022
- for (; a.index < o.length && o.charCodeAt(a.index) in n;) a.index += 1;
1023
- const u = a.index;
1024
- if (u > t) {
1025
- if (!h(e) && !a.options.silent) {
1026
- const s = a.input.slice(t, u), c = d(e) ? e(s, o, String(t)) : e;
1027
- h(c) || a.output.push(c);
1028
- }
1029
- a.indexMax = Math.max(a.indexMax, a.index);
1030
- }
1031
- return true;
1032
- };
1033
- }, nr = (r, e) => {
1034
- const n = r.source, a = r.flags.replace(/y|$/, "y"), t = new RegExp(n, a);
1035
- return g((o) => {
1036
- t.lastIndex = o.index;
1037
- const u = t.exec(o.input);
1038
- if (u) {
1039
- if (!h(e) && !o.options.silent) {
1040
- const s = d(e) ? e(...u, o.input, String(o.index)) : e;
1041
- h(s) || o.output.push(s);
1042
- }
1043
- return o.index += u[0].length, o.indexMax = Math.max(o.indexMax, o.index), true;
1044
- } else return false;
1045
- });
1046
- }, ar = (r, e) => (n) => {
1047
- if (n.input.startsWith(r, n.index)) {
1048
- if (!h(e) && !n.options.silent) {
1049
- const t = d(e) ? e(r, n.input, String(n.index)) : e;
1050
- h(t) || n.output.push(t);
1051
- }
1052
- return n.index += r.length, n.indexMax = Math.max(n.indexMax, n.index), true;
1053
- } else return false;
1054
- }, C = (r, e, n, a) => {
1055
- const t = v(r);
1056
- return g(_(M((o) => {
1057
- let u = 0;
1058
- for (; u < n;) {
1059
- const s = o.index;
1060
- if (!t(o) || (u += 1, o.index === s)) break;
1061
- }
1062
- return u >= e;
1063
- })));
1064
- }, tr = (r, e) => C(r, 0, 1), f = (r, e) => C(r, 0, 1 / 0), x = (r, e) => {
1065
- const n = r.map(v);
1066
- return g(_(M((a) => {
1067
- for (let t = 0, o = n.length; t < o; t++) if (!n[t](a)) return false;
1068
- return true;
1069
- })));
1070
- }, l = (r, e) => {
1071
- const n = r.map(v);
1072
- return g(_((a) => {
1073
- for (let t = 0, o = n.length; t < o; t++) if (n[t](a)) return true;
1074
- return false;
1075
- }));
1076
- }, M = (r, e = false) => {
1077
- const n = v(r);
1078
- return (a) => {
1079
- const t = a.index, o = a.output.length, u = n(a);
1080
- return (!u || e) && (a.index = t, a.output.length !== o && (a.output.length = o)), u;
1081
- };
1082
- }, _ = (r, e) => {
1083
- return v(r);
1084
- }, g = (() => {
1085
- let r = 0;
1086
- return (e) => {
1087
- const n = v(e), a = r += 1;
1088
- return (t) => {
1089
- var o;
1090
- if (t.options.memoization === false) return n(t);
1091
- const u = t.index, s = (o = t.cache)[a] || (o[a] = /* @__PURE__ */ new Map()), c = s.get(u);
1092
- if (c === false) return false;
1093
- if (W(c)) return t.index = c, true;
1094
- if (c) return t.index = c.index, c.output?.length && t.output.push(...c.output), true;
1095
- {
1096
- const Z = t.output.length;
1097
- if (n(t)) {
1098
- const D = t.index, U = t.output.length;
1099
- if (U > Z) {
1100
- const ee = t.output.slice(Z, U);
1101
- s.set(u, {
1102
- index: D,
1103
- output: ee
1104
- });
1105
- } else s.set(u, D);
1106
- return true;
1107
- } else return s.set(u, false), false;
1108
- }
1109
- };
1110
- };
1111
- })(), E = (r) => {
1112
- let e;
1113
- return (n) => (e || (e = v(r())), e(n));
1114
- }, v = Y((r) => {
1115
- if (d(r)) return Q(r) ? E(r) : r;
1116
- if (b(r) || X(r)) return i(r);
1117
- if (A(r)) return x(r);
1118
- if (K(r)) return l(Object.values(r));
1119
- throw new Error("Invalid rule");
1120
- }), P = "abcdefghijklmnopqrstuvwxyz", ir = (r) => {
1121
- let e = "";
1122
- for (; r > 0;) e = P[(r - 1) % 26] + e, r = Math.floor((r - 1) / 26);
1123
- return e;
1124
- }, O = (r) => {
1125
- let e = 0;
1126
- for (let n = 0, a = r.length; n < a; n++) e = e * 26 + P.indexOf(r[n]) + 1;
1127
- return e;
1128
- }, S = (r, e) => {
1129
- if (e < r) return S(e, r);
1130
- const n = [];
1131
- for (; r <= e;) n.push(r++);
1132
- return n;
1133
- }, or = (r, e, n) => S(r, e).map((a) => String(a).padStart(n, "0")), R = (r, e) => S(O(r), O(e)).map(ir), p = (r) => r, z = (r) => ur((e) => rr(e, r, { memoization: false }).join("")), ur = (r) => {
1134
- const e = {};
1135
- return (n) => e[n] ?? (e[n] = r(n));
1136
- }, sr = i(/^\*\*\/\*$/, ".*"), cr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]+)$/, (r, e, n) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}`), lr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]*)\{([ a-zA-Z0-9._-]+(?:,[ a-zA-Z0-9._-]+)*)\}$/, (r, e, n, a) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}(?:${a.replaceAll(",", "|").replaceAll(".", "\\.")})`), y = i(/\\./, p), pr = i(/[$.*+?^(){}[\]\|]/, (r) => `\\${r}`), vr = i(/./, p), fr = l([i(/^(?:!!)*!(.*)$/, (r, e) => `(?!^${L(e)}$).*?`), i(/^(!!)+/, "")]), j = l([
1137
- i(/\/(\*\*\/)+/, "(?:/.+/|/)"),
1138
- i(/^(\*\*\/)+/, "(?:^|.*/)"),
1139
- i(/\/(\*\*)$/, "(?:/.*|$)"),
1140
- i(/\*\*/, ".*")
1141
- ]), N = l([i(/\*\/(?!\*\*\/)/, "[^/]*/"), i(/\*/, "[^/]*")]), k = i("?", "[^/]"), $r = i("[", p), wr = i("]", p), Ar = i(/[!^]/, "^/"), br = i(/[a-z]-[a-z]|[0-9]-[0-9]/i, p), Er = l([
1142
- y,
1143
- i(/[$.*+?^(){}[\|]/, (r) => `\\${r}`),
1144
- br,
1145
- i(/[^\]]/, p)
1146
- ]), B = x([
1147
- $r,
1148
- tr(Ar),
1149
- f(Er),
1150
- wr
1151
- ]), Pr = i("{", "(?:"), Or = i("}", ")"), I = x([
1152
- Pr,
1153
- l([
1154
- i(/(\d+)\.\.(\d+)/, (r, e, n) => or(+e, +n, Math.min(e.length, n.length)).join("|")),
1155
- i(/([a-z]+)\.\.([a-z]+)/, (r, e, n) => R(e, n).join("|")),
1156
- i(/([A-Z]+)\.\.([A-Z]+)/, (r, e, n) => R(e.toLowerCase(), n.toLowerCase()).join("|").toUpperCase())
1157
- ]),
1158
- Or
1159
- ]), kr = i("{", "(?:"), Br = i("}", ")"), Ir = i(",", "|"), Fr = i(/[$.*+?^(){[\]\|]/, (r) => `\\${r}`), Lr = i(/[^}]/, p), F = x([
1160
- kr,
1161
- f(l([
1162
- j,
1163
- N,
1164
- k,
1165
- B,
1166
- I,
1167
- E(() => F),
1168
- y,
1169
- Fr,
1170
- Ir,
1171
- Lr
1172
- ])),
1173
- Br
1174
- ]), L = z(f(l([
1175
- sr,
1176
- cr,
1177
- lr,
1178
- fr,
1179
- j,
1180
- N,
1181
- k,
1182
- B,
1183
- I,
1184
- F,
1185
- y,
1186
- pr,
1187
- vr
1188
- ]))), Tr = i(/\\./, p), qr = i(/./, p), Yr = z(f(l([
1189
- Tr,
1190
- i(/\*\*\*+/, "*"),
1191
- i(/([^/{[(!])\*\*/, (r, e) => `${e}*`),
1192
- i(/(^|.)\*\*(?=[^*/)\]}])/, (r, e) => `${e}*`),
1193
- qr
1194
- ]))), $ = (r, e) => {
1195
- const n = Array.isArray(r) ? r : [r];
1196
- if (!n.length) return false;
1197
- const a = n.map($.compile), t = n.every((s) => /(\/(?:\*\*)?|\[\/\])$/.test(s)), o = e.replace(/[\\\/]+/g, "/").replace(/\/$/, t ? "/" : "");
1198
- return a.some((s) => s.test(o));
1199
- };
1200
- $.compile = (r) => new RegExp(`^${L(Yr(r))}$`, "s");
1201
- var re = $;
1202
- return J(w);
1203
- })();
1204
- return __lib__.default || __lib__;
1205
- };
1206
- let _match;
1207
- const zeptomatch = (path, pattern) => {
1208
- if (!_match) {
1209
- _match = _lazyMatch();
1210
- _lazyMatch = null;
1211
- }
1212
- return _match(path, pattern);
1213
- };
1214
- const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
1215
- function normalizeWindowsPath(input = "") {
1216
- if (!input) return input;
1217
- return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
1218
- }
1219
- const _UNC_REGEX = /^[/\\]{2}/;
1220
- const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
1221
- const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
1222
- const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
1223
- const _EXTNAME_RE = /.(\.[^./]+|\.)$/;
1224
- const _PATH_ROOT_RE = /^[/\\]|^[a-zA-Z]:[/\\]/;
1225
- const normalize = function(path) {
1226
- if (path.length === 0) return ".";
1227
- path = normalizeWindowsPath(path);
1228
- const isUNCPath = path.match(_UNC_REGEX);
1229
- const isPathAbsolute = isAbsolute(path);
1230
- const trailingSeparator = path[path.length - 1] === "/";
1231
- path = normalizeString(path, !isPathAbsolute);
1232
- if (path.length === 0) {
1233
- if (isPathAbsolute) return "/";
1234
- return trailingSeparator ? "./" : ".";
1235
- }
1236
- if (trailingSeparator) path += "/";
1237
- if (_DRIVE_LETTER_RE.test(path)) path += "/";
1238
- if (isUNCPath) {
1239
- if (!isPathAbsolute) return `//./${path}`;
1240
- return `//${path}`;
1241
- }
1242
- return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path;
1243
- };
1244
- const join = function(...segments) {
1245
- let path = "";
1246
- for (const seg of segments) {
1247
- if (!seg) continue;
1248
- if (path.length > 0) {
1249
- const pathTrailing = path[path.length - 1] === "/";
1250
- const segLeading = seg[0] === "/";
1251
- if (pathTrailing && segLeading) path += seg.slice(1);
1252
- else path += pathTrailing || segLeading ? seg : `/${seg}`;
1253
- } else path += seg;
1254
- }
1255
- return normalize(path);
1256
- };
1257
- function cwd() {
1258
- if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
1259
- return "/";
1260
- }
1261
- const resolve = function(...arguments_) {
1262
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
1263
- let resolvedPath = "";
1264
- let resolvedAbsolute = false;
1265
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
1266
- const path = index >= 0 ? arguments_[index] : cwd();
1267
- if (!path || path.length === 0) continue;
1268
- resolvedPath = `${path}/${resolvedPath}`;
1269
- resolvedAbsolute = isAbsolute(path);
1270
- }
1271
- resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
1272
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
1273
- return resolvedPath.length > 0 ? resolvedPath : ".";
1274
- };
1275
- function normalizeString(path, allowAboveRoot) {
1276
- let res = "";
1277
- let lastSegmentLength = 0;
1278
- let lastSlash = -1;
1279
- let dots = 0;
1280
- let char = null;
1281
- for (let index = 0; index <= path.length; ++index) {
1282
- if (index < path.length) char = path[index];
1283
- else if (char === "/") break;
1284
- else char = "/";
1285
- if (char === "/") {
1286
- if (lastSlash === index - 1 || dots === 1);
1287
- else if (dots === 2) {
1288
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
1289
- if (res.length > 2) {
1290
- const lastSlashIndex = res.lastIndexOf("/");
1291
- if (lastSlashIndex === -1) {
1292
- res = "";
1293
- lastSegmentLength = 0;
1294
- } else {
1295
- res = res.slice(0, lastSlashIndex);
1296
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
1297
- }
1298
- lastSlash = index;
1299
- dots = 0;
1300
- continue;
1301
- } else if (res.length > 0) {
1302
- res = "";
1303
- lastSegmentLength = 0;
1304
- lastSlash = index;
1305
- dots = 0;
1306
- continue;
1307
- }
1308
- }
1309
- if (allowAboveRoot) {
1310
- res += res.length > 0 ? "/.." : "..";
1311
- lastSegmentLength = 2;
1312
- }
1313
- } else {
1314
- if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
1315
- else res = path.slice(lastSlash + 1, index);
1316
- lastSegmentLength = index - lastSlash - 1;
1317
- }
1318
- lastSlash = index;
1319
- dots = 0;
1320
- } else if (char === "." && dots !== -1) ++dots;
1321
- else dots = -1;
1322
- }
1323
- return res;
1324
- }
1325
- const isAbsolute = function(p) {
1326
- return _IS_ABSOLUTE_RE.test(p);
1327
- };
1328
- const toNamespacedPath = function(p) {
1329
- return normalizeWindowsPath(p);
1330
- };
1331
- const extname = function(p) {
1332
- if (p === "..") return "";
1333
- const match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
1334
- return match && match[1] || "";
1335
- };
1336
- const relative = function(from, to) {
1337
- const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
1338
- const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
1339
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
1340
- const _fromCopy = [..._from];
1341
- for (const segment of _fromCopy) {
1342
- if (_to[0] !== segment) break;
1343
- _from.shift();
1344
- _to.shift();
1345
- }
1346
- return [..._from.map(() => ".."), ..._to].join("/");
1347
- };
1348
- const dirname = function(p) {
1349
- const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
1350
- if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
1351
- return segments.join("/") || (isAbsolute(p) ? "/" : ".");
1352
- };
1353
- const format = function(p) {
1354
- const ext = p.ext ? p.ext.startsWith(".") ? p.ext : `.${p.ext}` : "";
1355
- const segments = [
1356
- p.root,
1357
- p.dir,
1358
- p.base ?? (p.name ?? "") + ext
1359
- ].filter(Boolean);
1360
- return normalizeWindowsPath(p.root ? resolve(...segments) : segments.join("/"));
1361
- };
1362
- const basename = function(p, extension) {
1363
- const segments = normalizeWindowsPath(p).split("/");
1364
- let lastSegment = "";
1365
- for (let i = segments.length - 1; i >= 0; i--) {
1366
- const val = segments[i];
1367
- if (val) {
1368
- lastSegment = val;
1369
- break;
1370
- }
1371
- }
1372
- return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
1373
- };
1374
- const parse$1 = function(p) {
1375
- const root = _PATH_ROOT_RE.exec(p)?.[0]?.replace(/\\/g, "/") || "";
1376
- const base = basename(p);
1377
- const extension = extname(base);
1378
- return {
1379
- root,
1380
- dir: dirname(p),
1381
- base,
1382
- ext: extension,
1383
- name: base.slice(0, base.length - extension.length)
1384
- };
1385
- };
1386
- const matchesGlob = (path, pattern) => {
1387
- return zeptomatch(pattern, normalize(path));
1388
- };
1389
- const _path = {
1390
- __proto__: null,
1391
- basename,
1392
- dirname,
1393
- extname,
1394
- format,
1395
- isAbsolute,
1396
- join,
1397
- matchesGlob,
1398
- normalize,
1399
- normalizeString,
1400
- parse: parse$1,
1401
- relative,
1402
- resolve,
1403
- sep: "/",
1404
- toNamespacedPath
1405
- };
1406
- //#endregion
1407
- //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/index.mjs
1408
- const delimiter = /* @__PURE__ */ (() => globalThis.process?.platform === "win32" ? ";" : ":")();
1409
- const _platforms = {
1410
- posix: void 0,
1411
- win32: void 0
1412
- };
1413
- const mix = (del = delimiter) => {
1414
- return new Proxy(_path, { get(_, prop) {
1415
- if (prop === "delimiter") return del;
1416
- if (prop === "posix") return posix;
1417
- if (prop === "win32") return win32;
1418
- return _platforms[prop] || _path[prop];
1419
- } });
1420
- };
1421
- const posix = /* @__PURE__ */ mix(":");
1422
- const win32 = /* @__PURE__ */ mix(";");
1423
- //#endregion
1424
- //#region src/bundlers/vite/processed-css-assets/style-files.ts
1425
- const CSS_OUTPUT_FILE_RE = /\.(?:css|wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i;
1426
- function isCssOutputFile(file) {
1427
- return CSS_OUTPUT_FILE_RE.test(file);
1428
- }
1429
- function isRootStyleOutputFile(file) {
1430
- const normalized = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1431
- return isCssOutputFile(normalized) && !normalized.includes("/");
1432
- }
1433
- function isMiniProgramStyleOutputFile(file) {
1434
- return /\.(?:wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i.test(file);
1435
- }
1436
- //#endregion
1437
- //#region src/bundlers/vite/processed-css-assets/markers-imports.ts
1438
- function createCssAssetPipelineContext(options, file, bundle) {
1439
- const context = options.createCssPipelineContext?.(file);
1440
- return context ? {
1441
- ...context,
1442
- bundle
1443
- } : void 0;
1444
- }
1445
- function getAssetFile$1(bundleFile, asset) {
1446
- return asset.fileName || bundleFile;
1447
- }
1448
- function readAssetSource$3(asset) {
1449
- return typeof asset.source === "string" ? asset.source : asset.source.toString();
1450
- }
1451
- function clearAssetSource(asset) {
1452
- asset.source = "";
1453
- }
1454
- function appendCss$1(baseCss, css) {
1455
- if (baseCss.length === 0) return css;
1456
- if (css.length === 0) return baseCss;
1457
- return `${baseCss}\n${css}`;
1458
- }
1459
- function normalizeCssRecordIdentity(css) {
1460
- return css.trim();
1461
- }
1462
- function hasNonCommentCss(css) {
1463
- return css.replace(/\/\*[\s\S]*?\*\//g, "").trim().length > 0;
1464
- }
1465
- function dedupeViteCssResults(records) {
1466
- const seen = /* @__PURE__ */ new Set();
1467
- return records.filter((record) => {
1468
- const key = `${normalizeOutputPathKey(record.outputFile ?? "")}\0${normalizeCssRecordIdentity(record.css)}`;
1469
- if (seen.has(key)) return false;
1470
- seen.add(key);
1471
- return true;
1472
- });
1473
- }
1474
- function removeTailwindSourceMediaWrappersRoot(root) {
1475
- let changed = false;
1476
- root.walkAtRules("media", (atRule) => {
1477
- if (!atRule.params.startsWith("source(")) return;
1478
- if (atRule.nodes && atRule.nodes.length > 0) atRule.replaceWith(...atRule.nodes);
1479
- else atRule.remove();
1480
- changed = true;
1481
- });
1482
- if (changed) root.walkAtRules((atRule) => {
1483
- if (atRule.nodes && atRule.nodes.length === 0) atRule.remove();
1484
- });
1485
- return changed;
1486
- }
1487
- function removeTailwindSourceMediaWrappersFallback(css) {
1488
- return css.replace(/@media\s+source\([^)]*\)\s*\{\s*\/\*!\s*weapp-tailwindcss generator-placeholder\s*\*\/?\s*\}/gi, "").replace(/@media\s+source\([^)]*\)\s*\{\s*\}/gi, "");
1489
- }
1490
- function removeTailwindEntryDirectivesFromCss(css) {
1491
- try {
1492
- const source = stripGeneratorPlaceholderMarkers(css);
1493
- const root = postcss.parse(source);
1494
- const removedMediaWrappers = removeTailwindSourceMediaWrappersRoot(root);
1495
- const removedTailwindDirectives = removeTailwindSourceDirectivesRoot(root);
1496
- return removedMediaWrappers || removedTailwindDirectives ? root.toString() : source;
1497
- } catch {
1498
- return removeTailwindSourceDirectives(removeTailwindSourceMediaWrappersFallback(css));
1499
- }
1500
- }
1501
- function removeUnsupportedMiniProgramCssImportsFallback(css, file) {
1502
- if (!isMiniProgramStyleOutputFile(file) || !css.includes("@import")) return css;
1503
- return css.split(/\r?\n/).filter((line) => {
1504
- const trimmed = line.trim();
1505
- if (!trimmed.startsWith("@import")) return true;
1506
- const params = trimmed.slice(7).trim().replace(/;$/, "").trim();
1507
- const request = parseTailwindCssDirectiveRequest(params);
1508
- return request === void 0 || isMiniProgramLocalCssImportRequest(request);
1509
- }).join("\n");
1510
- }
1511
- function normalizeInjectableCssForTarget(css, file) {
1512
- return normalizeInjectableCssForTargetWithImports(css, file).css;
1513
- }
1514
- function normalizeInjectableCssForTargetWithImports(css, file) {
1515
- if (!css.includes("@import")) return {
1516
- css,
1517
- importedStyleFiles: /* @__PURE__ */ new Set()
1518
- };
1519
- try {
1520
- const root = postcss.parse(css);
1521
- const changed = isMiniProgramStyleOutputFile(file) ? removeUnsupportedMiniProgramCssImportsRoot(root) : false;
1522
- const importedStyleFiles = collectImportedStyleFilesRoot(root, file);
1523
- return {
1524
- css: changed ? root.toString() : css,
1525
- importedStyleFiles: importedStyleFiles.size > 0 ? importedStyleFiles : collectImportedStyleFilesFallback(css, file)
1526
- };
1527
- } catch {
1528
- const fallbackCss = removeUnsupportedMiniProgramCssImportsFallback(css, file);
1529
- return {
1530
- css: fallbackCss,
1531
- importedStyleFiles: collectImportedStyleFiles(fallbackCss, file)
1532
- };
1533
- }
1534
- }
1535
- function stripStyleExtension(file) {
1536
- return file.replace(/[?#].*$/, "").replace(/\.(?:css|wxss|acss|ttss|qss|jxss|tyss|scss|sass|less|styl|stylus|pcss|postcss)$/i, "");
1537
- }
1538
- function isStyleImportRequest(request) {
1539
- return typeof request === "string" && request.length > 0 && !/^(?:https?:)?\/\//i.test(request) && /\.(?:css|wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i.test(request);
1540
- }
1541
- function resolveImportedStyleFile(targetFile, request) {
1542
- if (!isStyleImportRequest(request)) return;
1543
- const cleanRequest = request.replace(/[?#].*$/, "");
1544
- if (cleanRequest.startsWith("/")) return normalizeOutputPathKey(cleanRequest.slice(1));
1545
- const targetDir = posix.posix.dirname(normalizeOutputPathKey(targetFile));
1546
- return normalizeOutputPathKey(posix.posix.join(targetDir === "." ? "" : targetDir, cleanRequest));
1547
- }
1548
- function collectImportedStyleFilesFromRequests(requests, targetFile) {
1549
- const imports = /* @__PURE__ */ new Set();
1550
- for (const request of requests) {
1551
- const importedFile = resolveImportedStyleFile(targetFile, request);
1552
- if (importedFile) imports.add(importedFile);
1553
- }
1554
- return imports;
1555
- }
1556
- function collectImportedStyleFilesRoot(root, targetFile) {
1557
- return collectImportedStyleFilesFromRequests(collectCssImportRequestsRoot(root), targetFile);
1558
- }
1559
- function collectImportedStyleFilesFallback(css, targetFile) {
1560
- return collectImportedStyleFilesFromRequests([...css.matchAll(/@import\s+(?:url\(\s*)?(?:"([^"]+)"|'([^']+)'|([^\s;)]+))/g)].map((match) => match[1] ?? match[2] ?? match[3]).filter((request) => typeof request === "string" && request.length > 0), targetFile);
1561
- }
1562
- function collectImportedStyleFiles(css, targetFile) {
1563
- if (!css.includes("@import")) return /* @__PURE__ */ new Set();
1564
- try {
1565
- const imports = collectImportedStyleFilesRoot(postcss.parse(css), targetFile);
1566
- return imports.size > 0 ? imports : collectImportedStyleFilesFallback(css, targetFile);
1567
- } catch {}
1568
- return collectImportedStyleFilesFallback(css, targetFile);
1569
- }
1570
- function normalizeMarkerOutputFile(markerFile, resolveViteProcessedCssOutputFile) {
1571
- return resolveViteProcessedCssOutputFile?.(markerFile) ?? markerFile;
1572
- }
1573
- function isMatchingGeneratedCssMarkerFile(targetFile, markerFile, resolveViteProcessedCssOutputFile) {
1574
- if (!markerFile) return false;
1575
- return normalizeOutputPathKey(stripStyleExtension(targetFile)) === normalizeOutputPathKey(stripStyleExtension(normalizeMarkerOutputFile(markerFile, resolveViteProcessedCssOutputFile)));
1576
- }
1577
- function resolveViteProcessedCssAssetSource(file, rawSource, resolveViteProcessedCssOutputFile) {
1578
- const blocks = parseBundlerGeneratedCssMarkerBlocks(rawSource).filter((block) => block.bundler === "vite");
1579
- if (blocks.length <= 1) return stripBundlerGeneratedCssMarkers(rawSource);
1580
- const matchedCss = blocks.filter((block) => isMatchingGeneratedCssMarkerFile(file, block.file, resolveViteProcessedCssOutputFile)).map((block) => block.css);
1581
- return matchedCss.length > 0 ? matchedCss.join("\n") : stripBundlerGeneratedCssMarkers(rawSource);
1582
- }
1583
- function collectMatchingGeneratedCssMarkerFiles(file, rawSource, resolveViteProcessedCssOutputFile) {
1584
- return parseBundlerGeneratedCssMarkerBlocks(rawSource).filter((block) => block.bundler === "vite").filter((block) => isMatchingGeneratedCssMarkerFile(file, block.file, resolveViteProcessedCssOutputFile)).map((block) => block.file).filter((markerFile) => typeof markerFile === "string" && markerFile.length > 0);
1585
- }
1586
- function collectRootStyleBundleCssSources(bundle, excludedFile) {
1587
- const sources = [];
1588
- const excludedFileKey = normalizeOutputPathKey(excludedFile);
1589
- for (const [bundleFile, output] of Object.entries(bundle)) {
1590
- if (output.type !== "asset") continue;
1591
- const file = normalizeOutputPathKey(getAssetFile$1(bundleFile, output));
1592
- if (file === excludedFileKey || !isRootStyleOutputFile(file)) continue;
1593
- const source = stripBundlerGeneratedCssMarkers(readAssetSource$3(output)).trim();
1594
- if (source.length > 0) sources.push(source);
1595
- }
1596
- return sources;
1597
- }
1598
- function isHtmlOutputFile(file) {
1599
- return /\.html(?:$|[?#])/i.test(file);
1600
- }
1601
- function stripQueryAndHash(file) {
1602
- return file.replace(/[?#].*$/, "");
1603
- }
1604
- function resolveHtmlLinkedStyleFile(htmlFile, request) {
1605
- if (!isStyleImportRequest(request)) return;
1606
- const cleanRequest = stripQueryAndHash(request);
1607
- if (cleanRequest.startsWith("/")) return normalizeOutputPathKey(cleanRequest.slice(1));
1608
- const htmlDir = posix.posix.dirname(normalizeOutputPathKey(stripQueryAndHash(htmlFile)));
1609
- return normalizeOutputPathKey(posix.posix.join(htmlDir === "." ? "" : htmlDir, cleanRequest));
1610
- }
1611
- function collectHtmlLinkedStyleFiles(bundle) {
1612
- const linkedFiles = /* @__PURE__ */ new Set();
1613
- const linkedBasenames = /* @__PURE__ */ new Set();
1614
- const linkHrefRE = /<link\s[^>]*href\s*=\s*(["'])([^"']+)\1[^>]*>/gi;
1615
- for (const [bundleFile, output] of Object.entries(bundle)) {
1616
- if (output.type !== "asset") continue;
1617
- const htmlFile = getAssetFile$1(bundleFile, output);
1618
- if (!isHtmlOutputFile(htmlFile)) continue;
1619
- const html = readAssetSource$3(output);
1620
- for (const match of html.matchAll(linkHrefRE)) {
1621
- const href = match[2];
1622
- if (!href) continue;
1623
- const linkedFile = resolveHtmlLinkedStyleFile(htmlFile, href);
1624
- if (!linkedFile || !isRootStyleOutputFile(linkedFile)) continue;
1625
- linkedFiles.add(linkedFile);
1626
- linkedBasenames.add(posix.posix.basename(linkedFile));
1627
- }
1628
- }
1629
- return {
1630
- linkedBasenames,
1631
- linkedFiles
1632
- };
1633
- }
1634
- function isLinkedStyleFile(file, linked) {
1635
- const fileKey = normalizeOutputPathKey(stripQueryAndHash(file));
1636
- return linked.linkedFiles.has(fileKey) || isRootStyleOutputFile(fileKey) && linked.linkedBasenames.has(posix.posix.basename(fileKey));
1637
- }
1638
- function removeDuplicateUnlinkedRootCssAssetsReferencedByHtml(bundle, options = {}) {
1639
- const linked = collectHtmlLinkedStyleFiles(bundle);
1640
- if (linked.linkedFiles.size === 0 && linked.linkedBasenames.size === 0) return 0;
1641
- const linkedSources = /* @__PURE__ */ new Set();
1642
- for (const [bundleFile, output] of Object.entries(bundle)) {
1643
- if (output.type !== "asset") continue;
1644
- const file = getAssetFile$1(bundleFile, output);
1645
- if (!isCssOutputFile(file) || isMiniProgramStyleOutputFile(file) || !isLinkedStyleFile(file, linked)) continue;
1646
- const source = stripBundlerGeneratedCssMarkers(readAssetSource$3(output)).trim();
1647
- if (source.length > 0) linkedSources.add(source);
1648
- }
1649
- if (linkedSources.size === 0) return 0;
1650
- let removed = 0;
1651
- for (const [bundleFile, output] of Object.entries(bundle)) {
1652
- if (output.type !== "asset") continue;
1653
- const file = getAssetFile$1(bundleFile, output);
1654
- if (!isRootStyleOutputFile(file) || isMiniProgramStyleOutputFile(file) || isLinkedStyleFile(file, linked)) continue;
1655
- const source = stripBundlerGeneratedCssMarkers(readAssetSource$3(output)).trim();
1656
- if (!linkedSources.has(source)) continue;
1657
- delete bundle[bundleFile];
1658
- options.debug?.("remove duplicate unlinked root css asset referenced by html: %s", file);
1659
- removed++;
1660
- }
1661
- return removed;
1662
- }
1663
- //#endregion
1664
806
  //#region src/bundlers/vite/processed-css-assets/cleanup.ts
1665
807
  function collectCssImportAtRuleCss(css) {
1666
808
  if (!css.includes("@import")) return [];
@@ -1698,7 +840,7 @@ function restoreCssImportAtRules(source, filtered, file) {
1698
840
  return appendCss$1(missingImports.join("\n"), filtered);
1699
841
  }
1700
842
  function removeCommentOnlyAtRules(css) {
1701
- if (!hasEmptyAtRuleBlockCandidate(css)) return css;
843
+ if (!hasEmptyCssBlockCandidate(css)) return css;
1702
844
  try {
1703
845
  const root = postcss.parse(css);
1704
846
  let changed = false;
@@ -1721,7 +863,7 @@ function collectImportedBundleCssSources(bundle, importedStyleFiles) {
1721
863
  if (output.type !== "asset") continue;
1722
864
  const file = normalizeOutputPathKey(getAssetFile$1(bundleFile, output));
1723
865
  if (!(importedStyleFiles.has(file) || !file.includes("/") && importedFileNames.has(posix.posix.basename(file)))) continue;
1724
- importedSources.push(readAssetSource$3(output));
866
+ importedSources.push(readAssetSource$2(output));
1725
867
  }
1726
868
  return importedSources;
1727
869
  }
@@ -1817,571 +959,53 @@ function isSourceRootPrefixedOutputFile(file, outputFile) {
1817
959
  return fileKey !== outputFileKey && fileKey.endsWith(`/${outputFileKey}`);
1818
960
  }
1819
961
  //#endregion
1820
- //#region src/bundlers/vite/utils.ts
1821
- function slash(p) {
1822
- return ensurePosix(p);
1823
- }
1824
- const isWindows = process$1.platform === "win32";
1825
- const cssLangRE = new RegExp(`\\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)(?:$|\\?)`);
1826
- const htmlLangRE = /\.html?(?:$|\?)/;
1827
- function isCSSRequest(request) {
1828
- return cssLangRE.test(request) || isSourceStyleRequest(request);
1829
- }
1830
- function isWeappViteSidecarRequest(request) {
1831
- const queryIndex = request.indexOf("?");
1832
- if (queryIndex < 0) return false;
1833
- const hashIndex = request.indexOf("#", queryIndex);
1834
- const query = request.slice(queryIndex + 1, hashIndex < 0 ? void 0 : hashIndex);
1835
- return new URLSearchParams(query).has("weapp-vite-sidecar");
1836
- }
1837
- function resolveViteCssPipelineRequestFile(request) {
1838
- return isWeappViteSidecarRequest(request) ? cleanUrl$1(request) : request;
1839
- }
1840
- function isHTMLRequest(request) {
1841
- return htmlLangRE.test(request);
1842
- }
1843
- function normalizePath(id) {
1844
- return path.posix.normalize(isWindows ? ensurePosix(id) : id);
1845
- }
1846
- async function formatPostcssSourceMap(rawMap, file) {
1847
- const inputFileDir = path.dirname(file);
1848
- const sources = rawMap.sources.map((source) => {
1849
- const cleanSource = cleanUrl$1(decodeURIComponent(source));
1850
- if (cleanSource[0] === "<" && cleanSource.endsWith(">")) return `\0${cleanSource}`;
1851
- return normalizePath(path.resolve(inputFileDir, cleanSource));
1852
- });
1853
- return {
1854
- file,
1855
- mappings: rawMap.mappings,
1856
- names: rawMap.names,
1857
- sources,
1858
- sourcesContent: rawMap.sourcesContent,
1859
- version: rawMap.version
1860
- };
1861
- }
1862
- //#endregion
1863
- //#region src/bundlers/vite/generate-bundle/css-output.ts
1864
- const SOURCE_STYLE_OUTPUT_EXT_RE = /\.(?:less|sass|scss|styl|stylus|pcss|postcss)$/i;
1865
- const CSS_SOURCE_OUTPUT_EXT_RE = /\.(?:css|less|sass|scss|styl|stylus|pcss|postcss)$/i;
1866
- const SOURCE_STYLE_NON_CSS_SYNTAX_RE = /(?:^|\n)\s*(?:\/\/|\$[\w-]+\s*:|@(?:use|forward|mixin|include|function)\b)/;
1867
- const FALLBACK_STYLE_OUTPUT_EXTENSION = ".css";
1868
- const COMMON_MINI_PROGRAM_STYLE_OUTPUT_EXTENSIONS = [
1869
- ".wxss",
1870
- ".acss",
1871
- ".ttss",
1872
- ".qss",
1873
- ".jxss",
1874
- ".tyss"
1875
- ];
1876
- function resolveCssOutputRealPath(value) {
1877
- const resolved = path.resolve(value);
1878
- let current = resolved;
1879
- const pendingSegments = [];
1880
- while (!existsSync(current)) {
1881
- const parent = path.dirname(current);
1882
- if (parent === current) return resolved;
1883
- pendingSegments.unshift(path.basename(current));
1884
- current = parent;
1885
- }
1886
- try {
1887
- const realPath = realpathSync.native(current);
1888
- return pendingSegments.length > 0 ? path.join(realPath, ...pendingSegments) : realPath;
1889
- } catch {
1890
- return resolved;
962
+ //#region src/bundlers/vite/generate-bundle/subpackages.ts
963
+ function readBundleAssetSource(output) {
964
+ if ("type" in output && output.type !== "asset") return;
965
+ const source = output.source;
966
+ if (typeof source === "string") return source;
967
+ if (typeof source === "function") {
968
+ const value = source.call(output);
969
+ return typeof value === "string" ? value : value?.toString();
1891
970
  }
971
+ if (source != null && typeof source.toString === "function") return source.toString();
1892
972
  }
1893
- function normalizeStyleOutputExtension(value) {
1894
- if (typeof value !== "string" || value.trim().length === 0) return;
1895
- const normalized = value.trim().toLowerCase();
1896
- return normalized.startsWith(".") ? normalized : `.${normalized}`;
1897
- }
1898
- function getMatchedStyleOutputExtension(file, cssMatcher) {
1899
- const cleanFile = file.replace(/[?#].*$/, "");
1900
- if (!cssMatcher?.(cleanFile)) return;
1901
- const ext = path.extname(cleanFile);
1902
- if (!ext || ext === ".css") return;
1903
- return ext;
1904
- }
1905
- function resolveStyleOutputExtensionFromFiles(files, cssMatcher, stem) {
1906
- let extension;
1907
- for (const file of files ?? []) {
1908
- const cleanFile = file.replace(/[?#].*$/, "");
1909
- const matchedExtension = getMatchedStyleOutputExtension(cleanFile, cssMatcher);
1910
- if (!matchedExtension) continue;
1911
- if (stem && cleanFile.slice(0, -matchedExtension.length) !== stem) continue;
1912
- if (extension && extension !== matchedExtension) return;
1913
- extension = matchedExtension;
1914
- }
1915
- return extension;
1916
- }
1917
- function resolveStyleOutputExtensionFromMatcher(cssMatcher, stem) {
1918
- if (!cssMatcher || !stem) return;
1919
- return COMMON_MINI_PROGRAM_STYLE_OUTPUT_EXTENSIONS.find((extension) => cssMatcher(`${stem}${extension}`));
1920
- }
1921
- function resolveStyleOutputFileFromFiles(files, cssMatcher, stem) {
1922
- const cleanStem = normalizeOutputPathKey(stem);
1923
- const stemSuffix = `/${cleanStem}`;
1924
- const matchedFiles = /* @__PURE__ */ new Set();
1925
- for (const file of files ?? []) {
1926
- const cleanFile = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
1927
- if (!cssMatcher?.(cleanFile)) continue;
1928
- const extension = path.extname(cleanFile);
1929
- if (!extension || extension === ".css") continue;
1930
- const outputStem = cleanFile.slice(0, -extension.length);
1931
- const outputStemSuffix = `/${outputStem}`;
1932
- if (outputStem === cleanStem || outputStem.endsWith(stemSuffix) || cleanStem.endsWith(outputStemSuffix) || cleanStem.endsWith(`/${outputStem}`)) matchedFiles.add(cleanFile);
1933
- }
1934
- return matchedFiles.size === 1 ? [...matchedFiles][0] : void 0;
1935
- }
1936
- function resolveMiniProgramStyleOutputExtension(options = {}) {
1937
- return resolveStyleOutputExtensionFromFiles(options.files, options.cssMatcher, options.stem) ?? resolveStyleOutputExtensionFromFiles(options.files, options.cssMatcher) ?? resolveStyleOutputExtensionFromMatcher(options.cssMatcher, options.stem) ?? normalizeStyleOutputExtension(options.fallback) ?? FALLBACK_STYLE_OUTPUT_EXTENSION;
1938
- }
1939
- function resolveReplayCssOutputFile(rootDir, file) {
1940
- const cleanFile = file.replace(/[?#].*$/, "");
1941
- const nextFile = path.isAbsolute(cleanFile) ? path.relative(resolveCssOutputRealPath(rootDir), resolveCssOutputRealPath(cleanFile)) : cleanFile;
1942
- const normalizedFile = normalizeOutputPathKey(nextFile);
1943
- if (normalizedFile.length === 0 || normalizedFile === "." || normalizedFile === ".." || normalizedFile.startsWith("../")) return normalizeOutputPathKey(path.basename(cleanFile));
1944
- return normalizedFile;
1945
- }
1946
- function normalizeViteSourceRoot(rootDir, sourceRoot) {
1947
- if (typeof sourceRoot !== "string" || sourceRoot.trim().length === 0) return;
1948
- return normalizeOutputPathKey(path.isAbsolute(sourceRoot) ? path.relative(rootDir, sourceRoot) : sourceRoot).replace(/\/+$/, "");
1949
- }
1950
- function resolveReplayCssOutputFileFromSourceRoot(rootDir, file, sourceRoot) {
1951
- const outputFile = resolveReplayCssOutputFile(rootDir, file);
1952
- const normalizedSourceRoot = normalizeViteSourceRoot(rootDir, sourceRoot);
1953
- if (!normalizedSourceRoot) return outputFile;
1954
- if (outputFile === normalizedSourceRoot) return path.posix.basename(outputFile);
1955
- if (outputFile.startsWith(`${normalizedSourceRoot}/`)) return outputFile.slice(normalizedSourceRoot.length + 1);
1956
- return outputFile;
1957
- }
1958
- function resolveViteCssOutputFile(file, opts, isWebGeneratorTarget, preserveCssExtension = false, styleOutputExtension, styleOutputFiles) {
1959
- const cleanFile = file.replace(/[?#].*$/, "");
1960
- if (isWebGeneratorTarget || preserveCssExtension || opts.cssMatcher(cleanFile) || !CSS_SOURCE_OUTPUT_EXT_RE.test(cleanFile) || !isCSSRequest(file)) return cleanFile;
1961
- const stem = cleanFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, "");
1962
- return cleanFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, resolveMiniProgramStyleOutputExtension({
1963
- cssMatcher: opts.cssMatcher,
1964
- fallback: styleOutputExtension,
1965
- files: styleOutputFiles,
1966
- stem
1967
- }));
973
+ function normalizePackageRoot(root) {
974
+ return normalizeOutputPathKey(root).replace(/\/+$/, "");
1968
975
  }
1969
- function resolveViteCssPipelineOutputFile(file, opts, rootDir, isWebGeneratorTarget = false, preserveCssExtension = false, sourceRoot, styleOutputExtension, styleOutputFiles) {
1970
- const sourceStyleRequest = isCSSRequest(file);
1971
- const cleanFile = resolveReplayCssOutputFileFromSourceRoot(rootDir, file, sourceRoot).replace(/[?#].*$/, "");
1972
- const sourceExtension = path.extname(cleanFile);
1973
- if (sourceStyleRequest && !isWebGeneratorTarget && !preserveCssExtension && sourceExtension.length > 0 && !CSS_SOURCE_OUTPUT_EXT_RE.test(cleanFile)) {
1974
- const stem = cleanFile.slice(0, -sourceExtension.length);
1975
- return `${stem}${resolveMiniProgramStyleOutputExtension({
1976
- cssMatcher: opts.cssMatcher,
1977
- fallback: styleOutputExtension,
1978
- files: styleOutputFiles,
1979
- stem
1980
- })}`;
1981
- }
1982
- const stem = cleanFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, "");
1983
- const matchedStyleExtension = !isWebGeneratorTarget && !preserveCssExtension ? resolveStyleOutputExtensionFromFiles(styleOutputFiles, opts.cssMatcher, stem) : void 0;
1984
- if (matchedStyleExtension && CSS_SOURCE_OUTPUT_EXT_RE.test(cleanFile) && sourceStyleRequest) return cleanFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, matchedStyleExtension);
1985
- if (isWebGeneratorTarget || preserveCssExtension || opts.cssMatcher(cleanFile) || !CSS_SOURCE_OUTPUT_EXT_RE.test(cleanFile) || !sourceStyleRequest) return cleanFile;
1986
- const fallbackExtension = normalizeStyleOutputExtension(styleOutputExtension);
1987
- if (!fallbackExtension && !SOURCE_STYLE_OUTPUT_EXT_RE.test(cleanFile)) return cleanFile;
1988
- return cleanFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, fallbackExtension ?? FALLBACK_STYLE_OUTPUT_EXTENSION);
1989
- }
1990
- function resolveViteCssPipelineOutputFileFromSourceFile(sourceFile, opts, rootDir, isWebGeneratorTarget = false, preserveCssExtension = false, sourceRoot, styleOutputExtension, styleOutputFiles) {
1991
- const sourceStyleRequest = isCSSRequest(sourceFile);
1992
- const cleanFile = resolveReplayCssOutputFileFromSourceRoot(rootDir, sourceFile, sourceRoot).replace(/[?#].*$/, "");
1993
- const sourceExtension = path.extname(cleanFile);
1994
- if (sourceStyleRequest && !isWebGeneratorTarget && !preserveCssExtension && sourceExtension.length > 0 && !CSS_SOURCE_OUTPUT_EXT_RE.test(cleanFile)) {
1995
- const stem = cleanFile.slice(0, -sourceExtension.length);
1996
- return resolveStyleOutputFileFromFiles(styleOutputFiles, opts.cssMatcher, stem) ?? `${stem}${resolveMiniProgramStyleOutputExtension({
1997
- cssMatcher: opts.cssMatcher,
1998
- fallback: styleOutputExtension,
1999
- files: styleOutputFiles,
2000
- stem
2001
- })}`;
2002
- }
2003
- if (isWebGeneratorTarget || preserveCssExtension || !CSS_SOURCE_OUTPUT_EXT_RE.test(cleanFile) || !sourceStyleRequest) return cleanFile;
2004
- const stem = cleanFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, "");
2005
- const matchedStyleFile = resolveStyleOutputFileFromFiles(styleOutputFiles, opts.cssMatcher, stem);
2006
- if (matchedStyleFile) return matchedStyleFile;
2007
- const styleExtension = resolveStyleOutputExtensionFromFiles(styleOutputFiles, opts.cssMatcher, stem) ?? resolveMiniProgramStyleOutputExtension({
2008
- cssMatcher: opts.cssMatcher,
2009
- fallback: styleOutputExtension,
2010
- files: styleOutputFiles,
2011
- stem
2012
- }) ?? normalizeStyleOutputExtension(styleOutputExtension);
2013
- return cleanFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, styleExtension);
2014
- }
2015
- function canProcessViteSourceStyleAsCss(source, file) {
2016
- if (SOURCE_STYLE_NON_CSS_SYNTAX_RE.test(source)) return false;
2017
- try {
2018
- postcss.parse(source, { from: file });
2019
- return true;
2020
- } catch {
2021
- return false;
976
+ function collectMiniProgramSubpackageRoots(bundle) {
977
+ let hasAppJson = false;
978
+ const roots = /* @__PURE__ */ new Set();
979
+ for (const [file, output] of Object.entries(bundle)) {
980
+ const outputFile = output.fileName || file;
981
+ if (path.basename(outputFile) !== "app.json") continue;
982
+ const source = readBundleAssetSource(output);
983
+ if (!source) continue;
984
+ hasAppJson = true;
985
+ try {
986
+ const appJson = JSON.parse(source);
987
+ const subPackages = Array.isArray(appJson.subPackages) ? appJson.subPackages : Array.isArray(appJson.subpackages) ? appJson.subpackages : [];
988
+ for (const subPackage of subPackages) {
989
+ if (typeof subPackage.root !== "string" || subPackage.root.length === 0) continue;
990
+ roots.add(normalizePackageRoot(subPackage.root));
991
+ }
992
+ } catch {}
2022
993
  }
994
+ return hasAppJson ? roots : void 0;
2023
995
  }
2024
- function normalizeCssSourceForCompare(css) {
2025
- return css.trim();
996
+ function isSubpackageOutputFile(file, subpackageRoots) {
997
+ const normalizedFile = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
998
+ for (const root of subpackageRoots) if (root.length > 0 && (normalizedFile === root || normalizedFile.startsWith(`${root}/`) || normalizedFile.endsWith(`/${root}`) || normalizedFile.includes(`/${root}/`))) return true;
999
+ return false;
2026
1000
  }
2027
- function stripStyleFileExtension(file) {
2028
- const normalized = file.replace(/[?#].*$/, "");
2029
- const ext = path.extname(normalized);
2030
- return ext ? normalized.slice(0, -ext.length) : normalized;
2031
- }
2032
- //#endregion
2033
- //#region src/bundlers/vite/generate-bundle/style-matching.ts
2034
- function resolveStyleMatchingRealPath(value) {
2035
- const resolved = path.resolve(value);
2036
- let current = resolved;
2037
- const pendingSegments = [];
2038
- while (!existsSync(current)) {
2039
- const parent = path.dirname(current);
2040
- if (parent === current) return resolved;
2041
- pendingSegments.unshift(path.basename(current));
2042
- current = parent;
2043
- }
2044
- try {
2045
- const realPath = realpathSync.native(current);
2046
- return pendingSegments.length > 0 ? path.join(realPath, ...pendingSegments) : realPath;
2047
- } catch {
2048
- return resolved;
2049
- }
2050
- }
2051
- function isMatchingCssSourceFile(outputFile, cssSourceFile, outputRoot) {
2052
- return stripStyleFileExtension(path.resolve(outputRoot, outputFile)) === stripStyleFileExtension(path.resolve(cssSourceFile));
2053
- }
2054
- function collectStyleFileMatchBases(file, roots) {
2055
- const normalizedFile = file.replace(/[?#].*$/, "");
2056
- const bases = /* @__PURE__ */ new Set();
2057
- const addBase = (candidate) => {
2058
- const base = slash(stripStyleFileExtension(candidate));
2059
- if (base.length > 0) bases.add(base);
2060
- };
2061
- addBase(normalizedFile);
2062
- const resolvedRoots = roots.filter((root) => typeof root === "string" && root.length > 0).map((root) => path.resolve(root));
2063
- if (path.isAbsolute(normalizedFile)) for (const root of resolvedRoots) {
2064
- const relative = path.relative(resolveStyleMatchingRealPath(root), resolveStyleMatchingRealPath(normalizedFile));
2065
- if (relative && !relative.startsWith("..") && !path.isAbsolute(relative)) addBase(relative);
2066
- }
2067
- else for (const root of resolvedRoots) addBase(path.resolve(root, normalizedFile));
2068
- return bases;
2069
- }
2070
- function collectParentDirectories(file) {
2071
- const directories = [];
2072
- let current = path.dirname(path.resolve(file.replace(/[?#].*$/, "")));
2073
- while (true) {
2074
- directories.push(current);
2075
- const parent = path.dirname(current);
2076
- if (parent === current) break;
2077
- current = parent;
2078
- }
2079
- return directories;
2080
- }
2081
- function hasMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot) {
2082
- return scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot) > 0;
2083
- }
2084
- function scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot) {
2085
- const outputBases = collectStyleFileMatchBases(outputFile, [outputRoot]);
2086
- const sourceBases = collectStyleFileMatchBases(sourceFile, [sourceRoot, ...collectParentDirectories(sourceFile)]);
2087
- let bestScore = 0;
2088
- const hasDirectorySegment = (value) => slash(value).includes("/");
2089
- for (const outputBase of outputBases) for (const sourceBase of sourceBases) if (outputBase === sourceBase) bestScore = Math.max(bestScore, 1e5 + outputBase.length);
2090
- else if (hasDirectorySegment(sourceBase) && outputBase.endsWith(`/${sourceBase}`)) bestScore = Math.max(bestScore, 5e4 + sourceBase.length);
2091
- else if (hasDirectorySegment(outputBase) && sourceBase.endsWith(`/${outputBase}`)) bestScore = Math.max(bestScore, 1e3 + outputBase.length);
2092
- return bestScore;
2093
- }
2094
- //#endregion
2095
- //#region src/bundlers/vite/generate-bundle/sfc-style-source.ts
2096
- const SFC_STYLE_SOURCE_EXTENSIONS = [
2097
- ".vue",
2098
- ".uvue",
2099
- ".nvue",
2100
- ".svelte",
2101
- ".mpx"
2102
- ];
2103
- const SFC_STYLE_BLOCK_RE$1 = /<style\b([^>]*)>([\s\S]*?)<\/style>/gi;
2104
- const SFC_SCOPED_STYLE_ATTR_RE = /(?:^|\s)scoped(?:\s|=|$)/i;
2105
- const SFC_LANG_STYLE_ATTR_RE = /(?:^|\s)lang(?:=(?:"([^"]+)"|'([^']+)'|([^\s"'=<>`]+)))?/i;
2106
- function isSfcStyleSourceFile(file) {
2107
- const normalizedFile = file.replace(/[?#].*$/, "");
2108
- return SFC_STYLE_SOURCE_EXTENSIONS.some((extension) => normalizedFile.endsWith(extension));
2109
- }
2110
- function extractSfcStyleBlocks(source) {
2111
- const styleSources = [];
2112
- SFC_STYLE_BLOCK_RE$1.lastIndex = 0;
2113
- let index = 0;
2114
- let match = SFC_STYLE_BLOCK_RE$1.exec(source);
2115
- while (match !== null) {
2116
- const attrs = match[1] ?? "";
2117
- styleSources.push({
2118
- attrs,
2119
- index,
2120
- scoped: SFC_SCOPED_STYLE_ATTR_RE.test(attrs),
2121
- source: match[2] ?? ""
2122
- });
2123
- index += 1;
2124
- match = SFC_STYLE_BLOCK_RE$1.exec(source);
2125
- }
2126
- return styleSources;
2127
- }
2128
- function extractSfcStyleSources(source) {
2129
- return extractSfcStyleBlocks(source).map((style) => style.source);
2130
- }
2131
- function hasSfcStyleSources(source) {
2132
- return extractSfcStyleSources(source).length > 0;
2133
- }
2134
- function resolveSfcStyleBlockLang(attrs) {
2135
- const match = SFC_LANG_STYLE_ATTR_RE.exec(attrs);
2136
- return match?.[1] ?? match?.[2] ?? match?.[3];
2137
- }
2138
- function resolveSfcStyleHandlerSourceFile(sourceFile, styleBlocks) {
2139
- const scopedStyleBlock = styleBlocks.find((style) => style.scoped);
2140
- return scopedStyleBlock ? [`${sourceFile}?vue&type=style&index=${scopedStyleBlock.index}&scoped=true`, ...resolveSfcStyleBlockLang(scopedStyleBlock.attrs) ? [`lang=${encodeURIComponent(resolveSfcStyleBlockLang(scopedStyleBlock.attrs))}`] : []].join("&") : sourceFile;
2141
- }
2142
- function normalizeSfcStyleSourceForCompare(source) {
2143
- return source.replace(/\r\n?/g, "\n").trim();
2144
- }
2145
- function createSfcStyleRequest(sourceFile, styleBlock) {
2146
- const params = new URLSearchParams();
2147
- params.set("vue", "");
2148
- params.set("type", "style");
2149
- params.set("index", String(styleBlock.index));
2150
- if (styleBlock.scoped) params.set("scoped", "true");
2151
- const lang = resolveSfcStyleBlockLang(styleBlock.attrs);
2152
- if (lang) params.set("lang", lang);
2153
- return `${sourceFile}?${params.toString()}`;
2154
- }
2155
- function resolveSfcStyleRequestFromKnownSource(sourceFile, sfcSource, styleSource, currentRequest) {
2156
- if (!sfcSource) return sourceFile;
2157
- const styleBlocks = extractSfcStyleBlocks(sfcSource);
2158
- if (styleBlocks.length === 0) return sourceFile;
2159
- const normalizedStyleSource = normalizeSfcStyleSourceForCompare(styleSource);
2160
- const matchedBlocks = styleBlocks.filter((styleBlock) => {
2161
- const normalizedBlockSource = normalizeSfcStyleSourceForCompare(styleBlock.source);
2162
- return normalizedBlockSource === normalizedStyleSource || normalizedBlockSource.includes(normalizedStyleSource) || normalizedStyleSource.includes(normalizedBlockSource);
2163
- });
2164
- const requestIndex = currentRequest ? Number.parseInt(new URLSearchParams(currentRequest.split("?", 2)[1] ?? "").get("index") ?? "", 10) : NaN;
2165
- const styleBlock = (Number.isInteger(requestIndex) ? styleBlocks.find((styleBlock) => styleBlock.index === requestIndex) : void 0) ?? (matchedBlocks.length === 1 ? matchedBlocks[0] : styleBlocks.length === 1 ? styleBlocks[0] : void 0);
2166
- return styleBlock ? createSfcStyleRequest(sourceFile, styleBlock) : sourceFile;
2167
- }
2168
- function hasTailwindGenerationSource(source, options = {}) {
2169
- const allowRootDirectives = options.allowRootDirectives !== false;
2170
- return hasTailwindNonRootGenerationDirectives(source, { importFallback: true }) || allowRootDirectives && hasTailwindSourceDirectives(source, { importFallback: true }) || allowRootDirectives && hasTailwindRootDirectives(source, { importFallback: true }) || hasTailwindApplyDirective(source);
2171
- }
2172
- function hasTailwindGenerationSourceForFile(file, source) {
2173
- if (isTailwindV4CssEntry(file)) return hasTailwindGenerationSource(source);
2174
- return hasTailwindGenerationSource(source, { allowRootDirectives: false });
2175
- }
2176
- async function resolveSfcStyleSourceFromOutputFile(outputFile, snapshot, outputRoot, sourceRoot, cssMatcher, getSfcSource, debug) {
2177
- const sourceFile = resolveSfcStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, cssMatcher, debug);
2178
- if (!sourceFile) {
2179
- debug("sfc style source infer skipped: no source file for %s", outputFile);
2180
- return;
2181
- }
2182
- const source = getSfcSource?.(sourceFile);
2183
- if (source == null) {
2184
- debug("sfc style source infer skipped: missing known source for %s -> %s", outputFile, sourceFile);
2185
- return;
2186
- }
2187
- const styleBlocks = extractSfcStyleBlocks(source);
2188
- const rawSource = styleBlocks.map((style) => style.source).join("\n");
2189
- if (!rawSource || !hasTailwindGenerationSourceForFile(sourceFile, rawSource)) {
2190
- debug("sfc style source infer skipped: no tailwind generation source for %s -> %s", outputFile, sourceFile);
2191
- return;
2192
- }
2193
- debug("sfc style source inferred: %s -> %s", outputFile, sourceFile);
2194
- return {
2195
- outputFile,
2196
- rawSource,
2197
- sourceFile: resolveSfcStyleHandlerSourceFile(sourceFile, styleBlocks)
2198
- };
2199
- }
2200
- function normalizeSfcSourceFileForCompare(file) {
2201
- return normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
2202
- }
2203
- function collectChunkModuleIds$2(output) {
2204
- const moduleIds = Array.isArray(output.moduleIds) ? output.moduleIds : [];
2205
- return [
2206
- output.facadeModuleId,
2207
- ...moduleIds,
2208
- ...Object.keys(output.modules ?? {})
2209
- ].filter((id, index, ids) => typeof id === "string" && id.length > 0 && ids.indexOf(id) === index);
2210
- }
2211
- function normalizeSourceStyleModuleId(id) {
2212
- const file = id.replace(/[?#].*$/, "");
2213
- if (!CSS_SOURCE_OUTPUT_EXT_RE.test(file)) return;
2214
- if (!path.isAbsolute(file)) return;
2215
- return path.resolve(file);
2216
- }
2217
- function resolveSiblingJsChunkFile(outputFile, cssMatcher) {
2218
- const normalizedOutputFile = outputFile.replace(/[?#].*$/, "");
2219
- if (cssMatcher?.(normalizedOutputFile)) {
2220
- const extension = path.extname(normalizedOutputFile);
2221
- return extension ? `${normalizedOutputFile.slice(0, -extension.length)}.js` : void 0;
2222
- }
2223
- if (CSS_SOURCE_OUTPUT_EXT_RE.test(normalizedOutputFile)) return normalizedOutputFile.replace(CSS_SOURCE_OUTPUT_EXT_RE, ".js");
2224
- }
2225
- function normalizeSfcModuleId(id) {
2226
- const file = id.replace(/[?#].*$/, "");
2227
- if (!isSfcStyleSourceFile(file)) return;
2228
- if (!path.isAbsolute(file)) return;
2229
- return path.resolve(file);
2230
- }
2231
- function resolveSfcStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, cssMatcher, debug) {
2232
- const siblingJsFile = resolveSiblingJsChunkFile(outputFile, cssMatcher);
2233
- if (!siblingJsFile) {
2234
- debug("sfc style sibling chunk skipped: no sibling js for %s", outputFile);
2235
- return;
2236
- }
2237
- const normalizedSiblingJsFile = normalizeOutputPathKey(siblingJsFile);
2238
- const siblingChunk = snapshot.entries.find((entry) => entry.type === "js" && entry.output.type === "chunk" && normalizeOutputPathKey(entry.file) === normalizedSiblingJsFile);
2239
- if (!siblingChunk || siblingChunk.output.type !== "chunk") {
2240
- debug("sfc style sibling chunk skipped: missing chunk for %s -> %s", outputFile, siblingJsFile);
2241
- return;
2242
- }
2243
- const sourceFiles = collectChunkModuleIds$2(siblingChunk.output).map(normalizeSfcModuleId).filter((file, index, files) => Boolean(file) && files.indexOf(file) === index);
2244
- if (sourceFiles.length === 0) {
2245
- debug("sfc style sibling chunk skipped: no sfc modules for %s -> %s", outputFile, siblingJsFile);
2246
- return;
2247
- }
2248
- const scoredSources = sourceFiles.map((sourceFile) => ({
2249
- sourceFile,
2250
- score: scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot)
2251
- })).filter((item) => item.score > 0).sort((a, b) => b.score - a.score);
2252
- debug("sfc style sibling chunk candidates: %s -> %s %O", outputFile, siblingJsFile, scoredSources);
2253
- const bestScore = scoredSources[0]?.score;
2254
- if (!bestScore) return;
2255
- const bestSources = scoredSources.filter((item) => item.score === bestScore);
2256
- if (bestSources.length !== 1) {
2257
- debug("sfc style sibling chunk skipped: ambiguous best sources for %s %O", outputFile, bestSources);
2258
- return;
2259
- }
2260
- return bestSources[0]?.sourceFile;
2261
- }
2262
- function resolveSourceStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, debug) {
2263
- const siblingJsFile = resolveSiblingJsChunkFile(outputFile, void 0);
2264
- if (!siblingJsFile) {
2265
- debug("source style sibling chunk skipped: no sibling js for %s", outputFile);
2266
- return;
2267
- }
2268
- const normalizedSiblingJsFile = normalizeOutputPathKey(siblingJsFile);
2269
- const siblingChunk = snapshot.entries.find((entry) => entry.type === "js" && entry.output.type === "chunk" && normalizeOutputPathKey(entry.file) === normalizedSiblingJsFile);
2270
- if (!siblingChunk || siblingChunk.output.type !== "chunk") {
2271
- debug("source style sibling chunk skipped: missing chunk for %s -> %s", outputFile, siblingJsFile);
2272
- return;
2273
- }
2274
- const sourceFiles = collectChunkModuleIds$2(siblingChunk.output).map(normalizeSourceStyleModuleId).filter((file, index, files) => Boolean(file) && files.indexOf(file) === index);
2275
- if (sourceFiles.length === 0) {
2276
- debug("source style sibling chunk skipped: no source style modules for %s -> %s", outputFile, siblingJsFile);
2277
- return;
2278
- }
2279
- if (sourceFiles.length === 1) {
2280
- debug("source style sibling chunk inferred from single css module: %s -> %s", outputFile, sourceFiles[0]);
2281
- return sourceFiles[0];
2282
- }
2283
- const scoredSources = sourceFiles.map((sourceFile) => ({
2284
- sourceFile,
2285
- score: scoreMatchingStyleFileBase(outputFile, sourceFile, outputRoot, sourceRoot)
2286
- })).filter((item) => item.score > 0).sort((a, b) => b.score - a.score);
2287
- debug("source style sibling chunk candidates: %s -> %s %O", outputFile, siblingJsFile, scoredSources);
2288
- const bestScore = scoredSources[0]?.score;
2289
- if (!bestScore) return;
2290
- const bestSources = scoredSources.filter((item) => item.score === bestScore);
2291
- if (bestSources.length !== 1) {
2292
- debug("source style sibling chunk skipped: ambiguous best sources for %s %O", outputFile, bestSources);
2293
- return;
2294
- }
2295
- return bestSources[0]?.sourceFile;
2296
- }
2297
- function resolveSourceStyleSourceFromOutputFile(outputFile, snapshot, outputRoot, sourceRoot, getSourceStyleSource, getSourceStyleSources, configuredSourceEntries, debug) {
2298
- let sourceFile = resolveSourceStyleFileFromSiblingChunk(outputFile, snapshot, outputRoot, sourceRoot, debug);
2299
- let rawSource = sourceFile ? getSourceStyleSource?.(sourceFile) : void 0;
2300
- if (!sourceFile || !rawSource || !hasTailwindGenerationSourceForFile(sourceFile, rawSource)) {
2301
- const cachedSources = [...getSourceStyleSources?.() ?? []].filter(([file, source]) => CSS_SOURCE_OUTPUT_EXT_RE.test(file) && hasTailwindGenerationSourceForFile(file, source)).map(([file, source]) => ({
2302
- file,
2303
- source,
2304
- score: scoreTailwindV4CssSourceFileMatch(outputFile, file, {
2305
- outputRoot,
2306
- projectRoot: sourceRoot
2307
- })
2308
- }));
2309
- const configuredSources = [...configuredSourceEntries ?? []].filter(([file, source]) => CSS_SOURCE_OUTPUT_EXT_RE.test(file) && hasTailwindGenerationSourceForFile(file, source)).map(([file, source]) => ({
2310
- file,
2311
- source,
2312
- score: scoreTailwindV4CssSourceFileMatch(outputFile, file, {
2313
- outputRoot,
2314
- projectRoot: sourceRoot
2315
- })
2316
- }));
2317
- const scoredSources = [...cachedSources, ...configuredSources].filter((item) => item.score > 0).sort((a, b) => b.score - a.score);
2318
- const bestScore = scoredSources[0]?.score;
2319
- const bestSources = bestScore ? scoredSources.filter((item) => item.score === bestScore) : [];
2320
- if (bestSources.length === 1) {
2321
- sourceFile = bestSources[0].file;
2322
- rawSource = bestSources[0].source;
2323
- debug("source style source inferred from cache: %s -> %s", outputFile, sourceFile);
2324
- }
2325
- }
2326
- if (!sourceFile || !rawSource) return;
2327
- if (!hasTailwindGenerationSourceForFile(sourceFile, rawSource)) {
2328
- debug("source style source infer skipped: no tailwind generation source for %s -> %s", outputFile, sourceFile);
2329
- return;
2330
- }
2331
- return {
2332
- outputFile,
2333
- rawSource,
2334
- sourceFile
2335
- };
2336
- }
2337
- //#endregion
2338
- //#region src/bundlers/vite/generate-bundle/subpackages.ts
2339
- function readBundleAssetSource(output) {
2340
- if ("type" in output && output.type !== "asset") return;
2341
- const source = output.source;
2342
- if (typeof source === "string") return source;
2343
- if (typeof source === "function") {
2344
- const value = source.call(output);
2345
- return typeof value === "string" ? value : value?.toString();
2346
- }
2347
- if (source != null && typeof source.toString === "function") return source.toString();
2348
- }
2349
- function normalizePackageRoot(root) {
2350
- return normalizeOutputPathKey(root).replace(/\/+$/, "");
2351
- }
2352
- function collectMiniProgramSubpackageRoots(bundle) {
2353
- let hasAppJson = false;
2354
- const roots = /* @__PURE__ */ new Set();
2355
- for (const [file, output] of Object.entries(bundle)) {
2356
- const outputFile = output.fileName || file;
2357
- if (path.basename(outputFile) !== "app.json") continue;
2358
- const source = readBundleAssetSource(output);
2359
- if (!source) continue;
2360
- hasAppJson = true;
2361
- try {
2362
- const appJson = JSON.parse(source);
2363
- const subPackages = Array.isArray(appJson.subPackages) ? appJson.subPackages : Array.isArray(appJson.subpackages) ? appJson.subpackages : [];
2364
- for (const subPackage of subPackages) {
2365
- if (typeof subPackage.root !== "string" || subPackage.root.length === 0) continue;
2366
- roots.add(normalizePackageRoot(subPackage.root));
2367
- }
2368
- } catch {}
2369
- }
2370
- return hasAppJson ? roots : void 0;
2371
- }
2372
- function isSubpackageOutputFile(file, subpackageRoots) {
2373
- const normalizedFile = normalizeOutputPathKey(file.replace(/[?#].*$/, ""));
2374
- for (const root of subpackageRoots) if (root.length > 0 && (normalizedFile === root || normalizedFile.startsWith(`${root}/`) || normalizedFile.endsWith(`/${root}`) || normalizedFile.includes(`/${root}/`))) return true;
2375
- return false;
2376
- }
2377
- function resolveSubpackageSourceRootFromModuleId(moduleId, subpackageRoot) {
2378
- const file = slash(path.resolve(moduleId.replace(/[?#].*$/, "")));
2379
- const normalizedRoot = normalizePackageRoot(subpackageRoot);
2380
- const rootSegment = `/${normalizedRoot}/`;
2381
- const rootIndex = file.lastIndexOf(rootSegment);
2382
- if (rootIndex >= 0) return file.slice(0, rootIndex + rootSegment.length - 1);
2383
- const rootSuffix = `/${normalizedRoot}`;
2384
- if (file.endsWith(rootSuffix)) return file;
1001
+ function resolveSubpackageSourceRootFromModuleId(moduleId, subpackageRoot) {
1002
+ const file = slash(path.resolve(moduleId.replace(/[?#].*$/, "")));
1003
+ const normalizedRoot = normalizePackageRoot(subpackageRoot);
1004
+ const rootSegment = `/${normalizedRoot}/`;
1005
+ const rootIndex = file.lastIndexOf(rootSegment);
1006
+ if (rootIndex >= 0) return file.slice(0, rootIndex + rootSegment.length - 1);
1007
+ const rootSuffix = `/${normalizedRoot}`;
1008
+ if (file.endsWith(rootSuffix)) return file;
2385
1009
  }
2386
1010
  function collectMiniProgramSubpackageSourceEntries(snapshot, subpackageRoots, sourceBaseRoots) {
2387
1011
  const sourceRoots = /* @__PURE__ */ new Set();
@@ -2390,7 +1014,7 @@ function collectMiniProgramSubpackageSourceEntries(snapshot, subpackageRoots, so
2390
1014
  if (entry.output.type !== "chunk" || !isSubpackageOutputFile(entry.file, subpackageRoots)) continue;
2391
1015
  const matchedSubpackageRoot = [...subpackageRoots].find((root) => isSubpackageOutputFile(entry.file, /* @__PURE__ */ new Set([root])));
2392
1016
  if (!matchedSubpackageRoot) continue;
2393
- for (const moduleId of collectChunkModuleIds$2(entry.output)) {
1017
+ for (const moduleId of collectChunkModuleIds$3(entry.output)) {
2394
1018
  if (!path.isAbsolute(moduleId.replace(/[?#].*$/, ""))) continue;
2395
1019
  const sourceRoot = resolveSubpackageSourceRootFromModuleId(moduleId, matchedSubpackageRoot);
2396
1020
  if (sourceRoot) sourceRoots.add(sourceRoot);
@@ -2687,7 +1311,8 @@ function collectSingleViteGeneratedCssMarkerFile(rawSource) {
2687
1311
  }
2688
1312
  function shouldFilterRootGeneratedCssMarkerForScopedAsset(targetFile, markerFile, resolveViteProcessedCssOutputFile) {
2689
1313
  const resolvedTargetFile = normalizeMarkerOutputFile(targetFile, resolveViteProcessedCssOutputFile);
2690
- if (!isRootStyleOutputFile(normalizeMarkerOutputFile(markerFile, resolveViteProcessedCssOutputFile)) || isRootStyleOutputFile(resolvedTargetFile)) return false;
1314
+ const resolvedMarkerFile = normalizeMarkerOutputFile(markerFile, resolveViteProcessedCssOutputFile);
1315
+ if (!isRootStyleOutputFile(resolvedMarkerFile) || isRootStyleOutputFile(resolvedTargetFile)) return false;
2691
1316
  return !isMatchingGeneratedCssMarkerFile(targetFile, markerFile, resolveViteProcessedCssOutputFile);
2692
1317
  }
2693
1318
  function removeCssCoveredByRootStyleBundleSources(bundle, file, css) {
@@ -2756,7 +1381,7 @@ function removeCssCoveredByRootStyleAssets(bundle, options) {
2756
1381
  for (const [bundleFile, output] of Object.entries(bundle)) {
2757
1382
  if (output.type !== "asset") continue;
2758
1383
  const file = getAssetFile$1(bundleFile, output);
2759
- const rawSource = readAssetSource$3(output);
1384
+ const rawSource = readAssetSource$2(output);
2760
1385
  const hasScopedCss = hasVueScopedAttr(rawSource);
2761
1386
  const hasTailwindGeneratedCss = /tailwindcss v\d/i.test(rawSource);
2762
1387
  const shouldIncludeTailwindGeneratedCssAsset = options.includeTailwindGeneratedCssAssets === true && hasTailwindGeneratedCss && isCssOutputFile(file) && !isMiniProgramStyleOutputFile(file);
@@ -3020,7 +1645,7 @@ function isViteProcessedRootStyleImportingTargets(bundle, file, targetFiles) {
3020
1645
  const targetFileSet = new Set(targetFiles.map(normalizeOutputPathKey));
3021
1646
  for (const [bundleFile, output] of Object.entries(bundle)) {
3022
1647
  if (output.type !== "asset" || normalizeOutputPathKey(getAssetFile$1(bundleFile, output)) !== normalizeOutputPathKey(file)) continue;
3023
- return [...collectImportedStyleFiles(readAssetSource$3(output), file)].some((importedFile) => targetFileSet.has(normalizeOutputPathKey(importedFile)));
1648
+ return [...collectImportedStyleFiles(readAssetSource$2(output), file)].some((importedFile) => targetFileSet.has(normalizeOutputPathKey(importedFile)));
3024
1649
  }
3025
1650
  return false;
3026
1651
  }
@@ -3050,7 +1675,7 @@ function removeCoveredInjectedSourceAssets(bundle, targetFile, targetCss, record
3050
1675
  if (candidateKey === targetFileKey || !isCssOutputFile(candidateKey)) continue;
3051
1676
  const candidateIsRootWebStyle = isRootStyleOutputFile(candidateKey) && !isMiniProgramStyleOutputFile(candidateKey);
3052
1677
  if (candidateIsRootWebStyle && !targetIsRootWebStyle) continue;
3053
- const candidateSource = readAssetSource$3(candidateOutput).trim();
1678
+ const candidateSource = readAssetSource$2(candidateOutput).trim();
3054
1679
  if (!(recordFileKeys.has(candidateKey) || candidateSource.length > 0 && (recordCss.has(candidateSource) || containsCssAfterMinify(targetCss, candidateSource) || targetIsRootWebStyle && candidateIsRootWebStyle && !hasNonCommentCss(filterExistingCssRules(targetCss, candidateSource).trim())))) continue;
3055
1680
  if (candidateIsRootWebStyle) delete bundle[candidateFile];
3056
1681
  else clearAssetSource(candidateOutput);
@@ -3089,7 +1714,7 @@ function collectViteProcessedCssAssetResults(bundle, options) {
3089
1714
  if (output.type !== "asset") continue;
3090
1715
  const file = getAssetFile$1(bundleFile, output);
3091
1716
  if (!isCssOutputFile(file) || !options.isViteProcessedCssAsset?.(output, file)) continue;
3092
- const rawSource = readAssetSource$3(output);
1717
+ const rawSource = readAssetSource$2(output);
3093
1718
  let nextCss = resolveViteProcessedCssAssetSource(file, rawSource, options.resolveViteProcessedCssOutputFile);
3094
1719
  const singleMarkerFile = collectSingleViteGeneratedCssMarkerFile(rawSource);
3095
1720
  if (singleMarkerFile && (options.subpackageRoots == null || !isSubpackageOutputFile(file, options.subpackageRoots)) && shouldFilterRootGeneratedCssMarkerForScopedAsset(file, singleMarkerFile, options.resolveViteProcessedCssOutputFile)) nextCss = removeCssCoveredByRootStyleBundleSources(bundle, file, nextCss);
@@ -3106,8 +1731,9 @@ function collectViteProcessedCssAssetResults(bundle, options) {
3106
1731
  if (singleMarkerFile && normalizeOutputPathKey(resolvedOutputFile) !== normalizeOutputPathKey(file) && !isRootStyleOutputFile(resolvedOutputFile) && existingAssetFiles.has(normalizeOutputPathKey(resolvedOutputFile))) {
3107
1732
  const targetAsset = findBundleAssetByOutputFile(bundle, resolvedOutputFile);
3108
1733
  if (targetAsset) {
3109
- const targetRawSource = readAssetSource$3(targetAsset);
3110
- const targetNextCss = appendCss$1(targetRawSource, filterExistingCssRules(targetRawSource, nextCss).trim());
1734
+ const targetRawSource = readAssetSource$2(targetAsset);
1735
+ const missingCss = filterExistingCssRules(targetRawSource, nextCss).trim();
1736
+ const targetNextCss = appendCss$1(targetRawSource, missingCss);
3111
1737
  if (targetNextCss !== targetRawSource) {
3112
1738
  targetAsset.source = targetNextCss;
3113
1739
  options.onAssetWrite?.(resolvedOutputFile);
@@ -3184,7 +1810,7 @@ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
3184
1810
  if (output.type !== "asset") continue;
3185
1811
  let file = getAssetFile$1(bundleFile, output);
3186
1812
  if (!options.opts.cssMatcher(file) || !shouldUseCssAssetAsMainInjectionTarget(options.opts, file, viteCssResults, options, bundle)) continue;
3187
- let originalSource = readAssetSource$3(output);
1813
+ let originalSource = readAssetSource$2(output);
3188
1814
  if (shouldPreserveMiniProgramImportShell(options, bundle, file, originalSource)) {
3189
1815
  const importedTargetFile = resolvePreservedImportShellInjectionTarget(options, bundle, file, originalSource);
3190
1816
  if (typeof importedTargetFile === "string") {
@@ -3193,7 +1819,7 @@ function injectViteProcessedCssIntoMainCssAssets(bundle, options) {
3193
1819
  if (importedOutput?.type === "asset") {
3194
1820
  output = importedOutput;
3195
1821
  file = importedTargetFile;
3196
- originalSource = readAssetSource$3(output);
1822
+ originalSource = readAssetSource$2(output);
3197
1823
  } else continue;
3198
1824
  } else {
3199
1825
  options.debug?.("preserve mini-program css import shell asset: %s", file);
@@ -3280,10 +1906,10 @@ function resolveSourceRootCandidate(root, value) {
3280
1906
  }
3281
1907
  function resolveWeappViteSourceRoot(config, _appType) {
3282
1908
  const viteConfig = config;
3283
- const root = typeof viteConfig?.root === "string" && viteConfig.root.length > 0 ? path.resolve(viteConfig.root) : process$1.cwd();
1909
+ const root = typeof viteConfig?.root === "string" && viteConfig.root.length > 0 ? path.resolve(viteConfig.root) : process.cwd();
3284
1910
  const configuredSrcRoot = resolveSourceRootCandidate(root, viteConfig?.weapp?.srcRoot);
3285
1911
  if (configuredSrcRoot) return configuredSrcRoot;
3286
- const envSrcRoot = resolveSourceRootCandidate(root, process$1.env["UNI_INPUT_DIR"]) ?? resolveSourceRootCandidate(root, process$1.env["UNI_INPUT_ROOT"]) ?? resolveSourceRootCandidate(root, process$1.env["UNI_APP_INPUT_DIR"]);
1912
+ const envSrcRoot = resolveSourceRootCandidate(root, process.env["UNI_INPUT_DIR"]) ?? resolveSourceRootCandidate(root, process.env["UNI_INPUT_ROOT"]) ?? resolveSourceRootCandidate(root, process.env["UNI_APP_INPUT_DIR"]);
3287
1913
  if (envSrcRoot) return envSrcRoot;
3288
1914
  }
3289
1915
  function stripFileExtension(file) {
@@ -3316,7 +1942,7 @@ function resolveSourceRootFromChunk(root, fileName, chunk) {
3316
1942
  }
3317
1943
  function resolveSourceRootFromBundleGraph(config, bundle) {
3318
1944
  const viteConfig = config;
3319
- const root = typeof viteConfig?.root === "string" && viteConfig.root.length > 0 ? path.resolve(viteConfig.root) : process$1.cwd();
1945
+ const root = typeof viteConfig?.root === "string" && viteConfig.root.length > 0 ? path.resolve(viteConfig.root) : process.cwd();
3320
1946
  const sourceRoots = /* @__PURE__ */ new Set();
3321
1947
  for (const output of Object.values(bundle)) {
3322
1948
  if (output.type !== "chunk") continue;
@@ -3326,19 +1952,6 @@ function resolveSourceRootFromBundleGraph(config, bundle) {
3326
1952
  return sourceRoots.size === 1 ? [...sourceRoots][0] : void 0;
3327
1953
  }
3328
1954
  //#endregion
3329
- //#region src/bundlers/vite/web-css-compat.ts
3330
- /**
3331
- * Web target 的 Tailwind 兼容转换由 generator-css 负责;Vite 外层只处理非 Web 生成目标
3332
- * 落到 WebView 产物时的最终兼容需求,避免同一份 CSS 在 dev/build 中被重复解析转换。
3333
- */
3334
- function shouldApplyViteWebCssCompat(context, strategy) {
3335
- if (strategy?.shouldApplyWebCssCompat?.(context) !== true) return false;
3336
- return !context.currentGeneratorBranch.isWeb || context.currentGeneratorOptions.webCompat !== void 0;
3337
- }
3338
- function resolveViteWebCssCompatOptions(context) {
3339
- return context.currentGeneratorBranch.isWeb ? context.currentGeneratorOptions.webCompat : context.currentGeneratorOptions.webCompat ?? true;
3340
- }
3341
- //#endregion
3342
1955
  //#region src/bundlers/vite/generate-bundle/bundle-file-names.ts
3343
1956
  function normalizeBundleFileNameKeysForTest(bundle) {
3344
1957
  for (const [file, output] of Object.entries(bundle)) {
@@ -3484,16 +2097,16 @@ function createReplayCssAsset(fileName, source) {
3484
2097
  originalFileNames: []
3485
2098
  };
3486
2099
  }
3487
- function isAddWatchFileInvalidRollupPhaseError$1(error) {
2100
+ function isAddWatchFileInvalidRollupPhaseError(error) {
3488
2101
  const candidate = error;
3489
2102
  return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
3490
2103
  }
3491
- function registerGeneratorDependencies$1(ctx, dependencies) {
2104
+ function registerGeneratorDependencies(ctx, dependencies) {
3492
2105
  if (typeof ctx.addWatchFile !== "function") return;
3493
2106
  for (const dependency of dependencies ?? []) try {
3494
2107
  ctx.addWatchFile(dependency);
3495
2108
  } catch (error) {
3496
- if (isAddWatchFileInvalidRollupPhaseError$1(error)) {
2109
+ if (isAddWatchFileInvalidRollupPhaseError(error)) {
3497
2110
  logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
3498
2111
  continue;
3499
2112
  }
@@ -3528,7 +2141,7 @@ function resolveAssetSourceFile(asset, fallbackFile) {
3528
2141
  //#region src/bundlers/vite/generate-bundle/vite-css-cache.ts
3529
2142
  const VITE_LAST_CSS_RESULT_CACHE_MAX = 64;
3530
2143
  function resolveViteCssTaskConcurrency(_useIncrementalMode, _majorVersion) {
3531
- const configured = Number.parseInt(process$1.env["WEAPP_TW_VITE_CSS_CONCURRENCY"] ?? "", 10);
2144
+ const configured = Number.parseInt(process.env["WEAPP_TW_VITE_CSS_CONCURRENCY"] ?? "", 10);
3532
2145
  if (Number.isFinite(configured) && configured > 0) return configured;
3533
2146
  return 1;
3534
2147
  }
@@ -4332,58 +2945,6 @@ async function processViteCssBundleEntry(options) {
4332
2945
  });
4333
2946
  }
4334
2947
  //#endregion
4335
- //#region src/bundlers/vite/generate-bundle/css-handler-options.ts
4336
- function resolveViteCssHandlerExtraOptions(file) {
4337
- return normalizeOutputPathKey(file.replace(/[?#].*$/, "")).includes("/") ? { isMainChunk: false } : {};
4338
- }
4339
- function createCssHandlerOptionsCache(options) {
4340
- const cssHandlerOptionsCache = /* @__PURE__ */ new Map();
4341
- const cssUserHandlerOptionsCache = /* @__PURE__ */ new Map();
4342
- const getCssHandlerOptions = (file) => {
4343
- const majorVersion = options.getMajorVersion();
4344
- const appType = options.getAppType();
4345
- const isMainChunk = options.mainCssChunkMatcher(file, appType);
4346
- const outputRoot = options.getOutputRoot?.();
4347
- const sourceFile = stripRequestQuery(file);
4348
- const from = path.isAbsolute(sourceFile) ? sourceFile : outputRoot ? path.resolve(outputRoot, sourceFile) : sourceFile;
4349
- const extraOptions = options.getExtraOptions?.(file) ?? {};
4350
- const dynamicCssOptions = options.getDynamicCssOptions?.() ?? {};
4351
- const cacheKey = `${majorVersion ?? "unknown"}:${appType ?? "unknown"}:${isMainChunk ? "1" : "0"}:${outputRoot ?? ""}:${file}:${JSON.stringify(extraOptions)}:${JSON.stringify(dynamicCssOptions)}`;
4352
- const cached = cssHandlerOptionsCache.get(cacheKey);
4353
- if (cached) return cached;
4354
- const created = {
4355
- isMainChunk,
4356
- ...extraOptions,
4357
- ...dynamicCssOptions,
4358
- postcssOptions: { options: { from } },
4359
- majorVersion: normalizeStyleHandlerMajorVersion(majorVersion),
4360
- sourceOptions: {
4361
- outputRoot,
4362
- ...sourceFile === file ? {} : { requestFile: file }
4363
- }
4364
- };
4365
- cssHandlerOptionsCache.set(cacheKey, created);
4366
- return created;
4367
- };
4368
- const getCssUserHandlerOptions = (file) => {
4369
- const majorVersion = options.getMajorVersion();
4370
- const outputRoot = options.getOutputRoot?.();
4371
- const cacheKey = `${majorVersion ?? "unknown"}:${outputRoot ?? ""}:${file}`;
4372
- const cached = cssUserHandlerOptionsCache.get(cacheKey);
4373
- if (cached) return cached;
4374
- const created = {
4375
- ...getCssHandlerOptions(file),
4376
- isMainChunk: false
4377
- };
4378
- cssUserHandlerOptionsCache.set(cacheKey, created);
4379
- return created;
4380
- };
4381
- return {
4382
- getCssHandlerOptions,
4383
- getCssUserHandlerOptions
4384
- };
4385
- }
4386
- //#endregion
4387
2948
  //#region src/bundlers/vite/generate-bundle/css-output-helpers.ts
4388
2949
  function resolveCssBundleOutputFile(options) {
4389
2950
  const { bundleFiles, defaultStyleOutputExtension, file, isWebGeneratorTarget, opts, pipelineContext, cssPipelineStrategy, shouldPreserveAppCssExtension } = options;
@@ -4916,7 +3477,7 @@ function resolveViteCssLinkedImpactSignature(options) {
4916
3477
  //#region src/bundlers/vite/generate-bundle/css-transform-result.ts
4917
3478
  function applyViteCssTransformTaskResult(options) {
4918
3479
  const { result } = options;
4919
- registerGeneratorDependencies$1({ addWatchFile: options.addWatchFile }, result.dependencies);
3480
+ registerGeneratorDependencies({ addWatchFile: options.addWatchFile }, result.dependencies);
4920
3481
  if (options.debugCssDiff && result.diffSource != null) options.debug("css diff %s: %s", options.generatorSourceFile, summarizeStringDiff(result.diffSource, result.css));
4921
3482
  if (result.shouldRecordCssAsset) options.recordCssAssetResult?.(options.outputFile, result.css);
4922
3483
  if (result.kind === "tailwind") {
@@ -5009,18 +3570,18 @@ function hasOmittedKnownBundleFiles(currentBundleFiles, previousBundleFiles) {
5009
3570
  //#endregion
5010
3571
  //#region src/bundlers/vite/generate-bundle/env-flags.ts
5011
3572
  function resolveGenerateBundleEnvFlags() {
5012
- const slowJsAstWarnMs = Number(process$1.env["WEAPP_TW_VITE_SLOW_JS_AST_WARN_MS"] ?? 1e3);
3573
+ const slowJsAstWarnMs = Number(process.env["WEAPP_TW_VITE_SLOW_JS_AST_WARN_MS"] ?? 1e3);
5013
3574
  return {
5014
- forceRuntimeRefreshByEnv: process$1.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1",
5015
- disableDirtyOptimization: process$1.env["WEAPP_TW_VITE_DISABLE_DIRTY"] === "1",
5016
- disableJsPrecheck: process$1.env["WEAPP_TW_VITE_DISABLE_JS_PRECHECK"] === "1",
5017
- debugCssDiff: process$1.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1",
3575
+ forceRuntimeRefreshByEnv: process.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1",
3576
+ disableDirtyOptimization: process.env["WEAPP_TW_VITE_DISABLE_DIRTY"] === "1",
3577
+ disableJsPrecheck: process.env["WEAPP_TW_VITE_DISABLE_JS_PRECHECK"] === "1",
3578
+ debugCssDiff: process.env["WEAPP_TW_VITE_DEBUG_CSS_DIFF"] === "1",
5018
3579
  slowJsAstWarnMs: Number.isFinite(slowJsAstWarnMs) && slowJsAstWarnMs >= 0 ? slowJsAstWarnMs : 1e3
5019
3580
  };
5020
3581
  }
5021
3582
  //#endregion
5022
3583
  //#region src/bundlers/vite/generate-bundle/final-css-assets.ts
5023
- function readAssetSource$2(output) {
3584
+ function readAssetSource$1(output) {
5024
3585
  return typeof output.source === "string" ? output.source : output.source.toString();
5025
3586
  }
5026
3587
  function shouldFinalizeMiniProgramCssAsset(source) {
@@ -5035,7 +3596,7 @@ function finalizeMiniProgramCssAssetStructures(bundle, options) {
5035
3596
  if (output.type !== "asset") continue;
5036
3597
  const file = output.fileName || bundleFile;
5037
3598
  if (!options.cssMatcher(file) || options.files && !options.files.has(file)) continue;
5038
- const rawSource = readAssetSource$2(output);
3599
+ const rawSource = readAssetSource$1(output);
5039
3600
  const outputCss = finalizeMiniProgramCssStructure(rawSource);
5040
3601
  if (outputCss === rawSource) continue;
5041
3602
  plan.write(file, outputCss);
@@ -5060,7 +3621,7 @@ async function finalizeMiniProgramCssAssets(bundle, options) {
5060
3621
  if (output.type !== "asset") continue;
5061
3622
  const file = output.fileName || bundleFile;
5062
3623
  if (!options.cssMatcher(file)) continue;
5063
- const rawSource = readAssetSource$2(output);
3624
+ const rawSource = readAssetSource$1(output);
5064
3625
  if (rawSource.trim().length === 0) continue;
5065
3626
  if (options.lastCssResultByFile?.has(file)) {
5066
3627
  const structurallyCleanSource = finalizeMiniProgramCssStructure(rawSource);
@@ -5116,21 +3677,21 @@ async function finalizeMiniProgramCssAssets(bundle, options) {
5116
3677
  }
5117
3678
  //#endregion
5118
3679
  //#region src/bundlers/vite/generate-bundle/memory-debug.ts
5119
- function toMb$2(bytes) {
3680
+ function toMb(bytes) {
5120
3681
  return Math.round(bytes / 1024 / 1024);
5121
3682
  }
5122
- function summarizeStringMapCache$1(map) {
3683
+ function summarizeStringMapCache(map) {
5123
3684
  let bytes = 0;
5124
3685
  for (const value of map.values()) bytes += value.length;
5125
3686
  return {
5126
3687
  bytes,
5127
- mb: toMb$2(bytes),
3688
+ mb: toMb(bytes),
5128
3689
  size: map.size
5129
3690
  };
5130
3691
  }
5131
3692
  function resolveViteMemoryDebugStats(context) {
5132
- if (process$1.env["WEAPP_TW_HMR_MEMORY_DEBUG"] !== "1") return;
5133
- const memory = process$1.memoryUsage();
3693
+ if (process.env["WEAPP_TW_HMR_MEMORY_DEBUG"] !== "1") return;
3694
+ const memory = process.memoryUsage();
5134
3695
  const processCacheInstanceSize = context.cache.instance.size;
5135
3696
  const processCacheHashMapSize = context.cache.hashMap.size;
5136
3697
  return {
@@ -5138,11 +3699,11 @@ function resolveViteMemoryDebugStats(context) {
5138
3699
  mode: context.useIncrementalMode ? "incremental" : "full",
5139
3700
  bundle: { hasOmittedKnownFiles: context.hasOmittedKnownFiles },
5140
3701
  process: {
5141
- rssMb: toMb$2(memory.rss),
5142
- heapTotalMb: toMb$2(memory.heapTotal),
5143
- heapUsedMb: toMb$2(memory.heapUsed),
5144
- externalMb: toMb$2(memory.external),
5145
- arrayBuffersMb: toMb$2(memory.arrayBuffers)
3702
+ rssMb: toMb(memory.rss),
3703
+ heapTotalMb: toMb(memory.heapTotal),
3704
+ heapUsedMb: toMb(memory.heapUsed),
3705
+ externalMb: toMb(memory.external),
3706
+ arrayBuffersMb: toMb(memory.arrayBuffers)
5146
3707
  },
5147
3708
  runtime: {
5148
3709
  sourceCandidates: context.sourceCandidatesSize,
@@ -5163,7 +3724,7 @@ function resolveViteMemoryDebugStats(context) {
5163
3724
  },
5164
3725
  viteCss: {
5165
3726
  ...context.getViteCssCacheStats?.(),
5166
- lastCssResultByFile: summarizeStringMapCache$1(context.lastCssResultByFile)
3727
+ lastCssResultByFile: summarizeStringMapCache(context.lastCssResultByFile)
5167
3728
  },
5168
3729
  tailwind: { v4: getTailwindV4IncrementalGenerateCacheStats() }
5169
3730
  };
@@ -5302,7 +3863,7 @@ async function handleUniAppXPostCssTasks(options) {
5302
3863
  }
5303
3864
  //#endregion
5304
3865
  //#region src/bundlers/vite/generate-bundle/finalize/root-import-shell.ts
5305
- function readAssetSource$1(asset) {
3866
+ function readAssetSource(asset) {
5306
3867
  return typeof asset.source === "string" ? asset.source : asset.source.toString();
5307
3868
  }
5308
3869
  function getAssetFile(bundleFile, asset) {
@@ -5318,7 +3879,7 @@ function finalizeWebviewCssCompat(bundle, options) {
5318
3879
  if (output.type !== "asset") continue;
5319
3880
  const file = getAssetFile(bundleFile, output);
5320
3881
  if (!options.opts.cssMatcher(file) || !/\.css(?:$|[?#])/i.test(file)) continue;
5321
- const rawSource = readAssetSource$1(output);
3882
+ const rawSource = readAssetSource(output);
5322
3883
  const nextCss = transformWebCssSafeSelectors(transformWebCssCompat(rawSource, generatorOptions.webCompat ?? true), { escapeMap: options.opts.escapeMap });
5323
3884
  if (nextCss === rawSource) continue;
5324
3885
  plan.write(file, nextCss);
@@ -5368,7 +3929,7 @@ function normalizeRootMiniProgramImportShellAssets(bundle, options) {
5368
3929
  if (!originFile || !options.cssMatcher(originFile)) continue;
5369
3930
  const originOutput = Object.entries(bundle).find(([bundleFile, output]) => output.type === "asset" && normalizeOutputPathKey(getAssetFile(bundleFile, output)) === normalizeOutputPathKey(originFile))?.[1];
5370
3931
  if (originOutput?.type !== "asset") continue;
5371
- const rootSource = readAssetSource$1(rootOutput);
3932
+ const rootSource = readAssetSource(rootOutput);
5372
3933
  const importedRootFile = resolveSingleCssImportOutputFile(rootFile, rootSource);
5373
3934
  if (importedRootFile && normalizeOutputPathKey(importedRootFile) === normalizeOutputPathKey(originFile)) {
5374
3935
  const nextRootSource = createCssImportShell(rootFile, originFile);
@@ -5382,7 +3943,7 @@ function normalizeRootMiniProgramImportShellAssets(bundle, options) {
5382
3943
  continue;
5383
3944
  }
5384
3945
  if (isPureLocalCssImportWrapper(rootSource)) continue;
5385
- const originSource = readAssetSource$1(originOutput);
3946
+ const originSource = readAssetSource(originOutput);
5386
3947
  if (isPureLocalCssImportWrapper(originSource)) {
5387
3948
  const importedFile = resolveSingleCssImportOutputFile(originFile, originSource);
5388
3949
  if (importedFile && normalizeOutputPathKey(importedFile) !== normalizeOutputPathKey(rootFile)) continue;
@@ -5776,25 +4337,6 @@ function collectLinkedFileNames(linked, getJsEntry, linkedSet) {
5776
4337
  }
5777
4338
  }
5778
4339
  //#endregion
5779
- //#region src/bundlers/vite/query.ts
5780
- function parseVueRequest(id) {
5781
- const [filename = id, rawQuery] = id.split(`?`, 2);
5782
- const searchParams = new URLSearchParams(rawQuery);
5783
- const query = Object.fromEntries(searchParams);
5784
- if (query.vue != null) query.vue = true;
5785
- if (query.index != null) query.index = Number(query.index);
5786
- if (query.raw != null) query.raw = true;
5787
- if (query.url != null) query.url = true;
5788
- if (query.scoped != null) query.scoped = true;
5789
- const langTypeMatch = [...searchParams.keys()].find((key) => key.startsWith("lang."));
5790
- const langType = query.lang || (langTypeMatch ? langTypeMatch.slice(5) : void 0);
5791
- if (langType) query.lang = langType;
5792
- return {
5793
- filename,
5794
- query
5795
- };
5796
- }
5797
- //#endregion
5798
4340
  //#region src/uni-app-x/harmony.ts
5799
4341
  function isUniAppXHarmonyOutDir(outDir) {
5800
4342
  return typeof outDir === "string" && /(?:^|[/\\])\.?app-harmony(?:[/\\]|$)/.test(outDir);
@@ -5910,7 +4452,7 @@ function createUniAppXHarmonyApplyExpander(options) {
5910
4452
  const sources = collectUniAppXHarmonyApplyStyleSourcesFromSource(prepareStyles(code, id), id);
5911
4453
  const sourceUtilities = collectUniAppXHarmonyApplyUtilitiesFromSources(sources);
5912
4454
  if (sources.length === 0 || sourceUtilities.size === 0) return code;
5913
- const cssFile = path.resolve(options.getResolvedConfig()?.root ?? process$1.cwd(), `uni-app-x-harmony-apply-${createStableHash(normalizePath(cleanUrl$1(id)))}.css`);
4455
+ const cssFile = path.resolve(options.getResolvedConfig()?.root ?? process.cwd(), `uni-app-x-harmony-apply-${createStableHash(normalizePath(cleanUrl$1(id)))}.css`);
5914
4456
  const generatorSource = createUniAppXHarmonyApplyGeneratorSource(sources, sourceUtilities);
5915
4457
  const generatedCss = await options.generateCss?.(cssFile, generatorSource, {
5916
4458
  addWatchFile: hookContext.addWatchFile?.bind(hookContext),
@@ -5930,315 +4472,6 @@ function createUniAppXHarmonyApplyExpander(options) {
5930
4472
  };
5931
4473
  }
5932
4474
  //#endregion
5933
- //#region src/bundlers/vite/module-identity.ts
5934
- const WINDOWS_DRIVE_RE = /^\/?[a-z]:[\\/]/i;
5935
- const WINDOWS_UNC_RE = /^(?:\\\\|\/\/)/;
5936
- function unique(values) {
5937
- return [...new Set([...values].filter((value) => typeof value === "string" && value.length > 0))];
5938
- }
5939
- function decodeFileId(id) {
5940
- try {
5941
- return decodeURIComponent(id);
5942
- } catch {
5943
- return id;
5944
- }
5945
- }
5946
- function stripViteFsPrefix(id) {
5947
- if (!id.startsWith("/@fs/")) return id;
5948
- const file = id.slice(5);
5949
- return file.startsWith("/") || WINDOWS_DRIVE_RE.test(file) ? file : `/${file}`;
5950
- }
5951
- function stripFileProtocol(id) {
5952
- if (!id.startsWith("file://")) return id;
5953
- try {
5954
- return fileURLToPath(id);
5955
- } catch {
5956
- return id;
5957
- }
5958
- }
5959
- function isWindowsFile(file) {
5960
- return WINDOWS_DRIVE_RE.test(file) || WINDOWS_UNC_RE.test(file);
5961
- }
5962
- function normalizeWindowsFile(file) {
5963
- const withoutDriveSlash = /^\/[a-z]:[\\/]/i.test(file) ? file.slice(1) : file;
5964
- return slash(path.win32.resolve(withoutDriveSlash));
5965
- }
5966
- function normalizeFile(file, root) {
5967
- if (isWindowsFile(file) || isWindowsFile(root)) return normalizeWindowsFile(isWindowsFile(file) ? file : path.win32.resolve(root, file.replace(/^\//, "")));
5968
- if (path.isAbsolute(file)) {
5969
- if (file === root || file.startsWith(`${root}${path.sep}`) || existsSync(file) || existsSync(path.dirname(file))) return slash(path.resolve(file));
5970
- const rootRelativeFile = path.resolve(root, file.slice(1));
5971
- return existsSync(rootRelativeFile) || existsSync(path.dirname(rootRelativeFile)) ? slash(rootRelativeFile) : slash(path.resolve(file));
5972
- }
5973
- return slash(path.resolve(root, file));
5974
- }
5975
- function resolveRealFile(file) {
5976
- if (process$1.platform !== "win32" && isWindowsFile(file)) return file;
5977
- let current = file;
5978
- const missingSegments = [];
5979
- try {
5980
- while (true) try {
5981
- const resolvedParent = realpathSync.native(current);
5982
- return slash(path.join(resolvedParent, ...missingSegments));
5983
- } catch {
5984
- const parent = path.dirname(current);
5985
- if (parent === current) return file;
5986
- missingSegments.unshift(path.basename(current));
5987
- current = parent;
5988
- }
5989
- } catch {
5990
- return file;
5991
- }
5992
- }
5993
- function normalizeIdentityKey(file) {
5994
- return isWindowsFile(file) || process$1.platform === "win32" ? file.toLowerCase() : file;
5995
- }
5996
- /**
5997
- * 将 Vite URL、文件路径和 Windows 的等价路径收敛为同一个模块身份。
5998
- */
5999
- function resolveViteModuleIdentity(id, root = process$1.cwd()) {
6000
- const cleanId = decodeFileId(cleanUrl$1(id));
6001
- const decodedRoot = decodeFileId(cleanUrl$1(root));
6002
- const normalizedRoot = isWindowsFile(decodedRoot) ? normalizeWindowsFile(decodedRoot) : slash(path.resolve(decodedRoot));
6003
- const unwrappedId = stripFileProtocol(stripViteFsPrefix(cleanId));
6004
- const file = unwrappedId.startsWith("\0") ? void 0 : normalizeFile(unwrappedId, normalizedRoot);
6005
- const realFile = file ? resolveRealFile(file) : void 0;
6006
- const key = realFile ? normalizeIdentityKey(realFile) : cleanId;
6007
- const pathApi = isWindowsFile(normalizedRoot) ? path.win32 : path.posix;
6008
- const relativeUrl = realFile && normalizeIdentityKey(realFile).startsWith(`${normalizeIdentityKey(normalizedRoot)}/`) ? `/${slash(pathApi.relative(normalizedRoot, realFile))}` : void 0;
6009
- return {
6010
- cleanId,
6011
- file: realFile,
6012
- key,
6013
- lookupFiles: unique([file, realFile]),
6014
- lookupIds: unique([
6015
- id,
6016
- cleanId,
6017
- unwrappedId,
6018
- file,
6019
- realFile,
6020
- realFile ? `/@fs/${realFile}` : void 0,
6021
- relativeUrl
6022
- ])
6023
- };
6024
- }
6025
- function hasSameViteModuleIdentity(left, right, root = process$1.cwd()) {
6026
- if (!left || !right) return false;
6027
- return resolveViteModuleIdentity(left, root).key === resolveViteModuleIdentity(right, root).key;
6028
- }
6029
- //#endregion
6030
- //#region src/bundlers/vite/hot-css-modules.ts
6031
- async function resolveHotModulesByIds(ctx, ids, acceptModule) {
6032
- const modules = [];
6033
- const seenModules = /* @__PURE__ */ new Set();
6034
- const seenModuleIds = /* @__PURE__ */ new Set();
6035
- const seenFileIdentities = /* @__PURE__ */ new Set();
6036
- const root = ctx.server.config?.root ?? process$1.cwd();
6037
- const collectModule = (mod) => {
6038
- if (mod == null || seenModules.has(mod) || !acceptModule(mod)) return;
6039
- seenModules.add(mod);
6040
- modules.push(mod);
6041
- };
6042
- for (const id of ids) {
6043
- if (typeof id !== "string" || id.length === 0) continue;
6044
- const identity = resolveViteModuleIdentity(id, root);
6045
- for (const moduleId of identity.lookupIds) {
6046
- if (seenModuleIds.has(moduleId)) continue;
6047
- seenModuleIds.add(moduleId);
6048
- collectModule(ctx.server.moduleGraph.getModuleById?.(moduleId));
6049
- if (moduleId.startsWith("/")) collectModule(await ctx.server.moduleGraph.getModuleByUrl?.(moduleId));
6050
- }
6051
- if (seenFileIdentities.has(identity.key)) continue;
6052
- seenFileIdentities.add(identity.key);
6053
- for (const file of identity.lookupFiles) for (const mod of ctx.server.moduleGraph.getModulesByFile?.(file) ?? []) collectModule(mod);
6054
- }
6055
- return modules;
6056
- }
6057
- async function resolveHotTailwindCssModules(ctx, tailwindRootCssModuleIds, selectModules) {
6058
- const root = ctx.server.config?.root ?? process$1.cwd();
6059
- const outDir = ctx.server.config?.build?.outDir ? resolveViteModuleIdentity(ctx.server.config.build.outDir, root) : void 0;
6060
- const isHotSourceStyleModule = (id) => {
6061
- if (!isSourceStyleRequest(id)) return false;
6062
- const file = cleanUrl$1(id);
6063
- if (isRootMiniProgramStyleUrl(file) || !isAbsoluteFilePath(file) && !file.startsWith("/")) return false;
6064
- if (outDir) {
6065
- const identity = resolveViteModuleIdentity(file, root);
6066
- if (identity.key === outDir.key || identity.key.startsWith(`${outDir.key}/`)) return false;
6067
- }
6068
- return true;
6069
- };
6070
- const modules = await resolveHotModulesByIds(ctx, tailwindRootCssModuleIds, (mod) => {
6071
- const modId = mod.id ?? mod.url;
6072
- return isHotSourceStyleModule(modId);
6073
- });
6074
- const seenHotModules = new Set(modules);
6075
- for (let index = 0; index < modules.length; index++) for (const importer of modules[index]?.importers ?? []) {
6076
- const importerId = importer.id ?? importer.url;
6077
- if (!seenHotModules.has(importer) && isHotSourceStyleModule(importerId)) {
6078
- seenHotModules.add(importer);
6079
- modules.push(importer);
6080
- }
6081
- }
6082
- const selectedModules = selectModules?.(modules) ?? modules;
6083
- for (const mod of selectedModules) ctx.server.moduleGraph.invalidateModule(mod);
6084
- return selectedModules;
6085
- }
6086
- async function resolveHotSourceModulesByIds(ctx, ids) {
6087
- const root = ctx.server.config?.root ?? process$1.cwd();
6088
- const sourceIds = new Set(ids);
6089
- for (const id of ids) {
6090
- if (typeof id !== "string" || !/\.(?:uvue|nvue|vue|tsx?|jsx?)(?:$|[?#])/i.test(id)) continue;
6091
- const identity = resolveViteModuleIdentity(id, root);
6092
- for (const lookupId of identity.lookupIds) if (!/[?&]import(?:[=&]|$)/.test(lookupId)) sourceIds.add(`${cleanUrl$1(lookupId)}?import`);
6093
- }
6094
- return resolveHotModulesByIds(ctx, sourceIds, (mod) => {
6095
- const modId = mod.id ?? mod.url;
6096
- return !isSourceStyleRequest(modId);
6097
- });
6098
- }
6099
- async function resolveHotSourceModules(ctx) {
6100
- const modules = [];
6101
- const seenModules = /* @__PURE__ */ new Set();
6102
- const collectModule = (mod) => {
6103
- if (mod == null || seenModules.has(mod)) return;
6104
- const modId = mod.id ?? mod.url;
6105
- if (isSourceStyleRequest(modId)) return;
6106
- seenModules.add(mod);
6107
- modules.push(mod);
6108
- };
6109
- for (const mod of ctx.modules) collectModule(mod);
6110
- for (const mod of await resolveHotSourceModulesByIds(ctx, [ctx.file])) collectModule(mod);
6111
- return modules;
6112
- }
6113
- function mergeHotModulesByIdentity(root, ...groups) {
6114
- const modules = [];
6115
- const seenModules = /* @__PURE__ */ new Set();
6116
- const seenIdentities = /* @__PURE__ */ new Set();
6117
- for (const mod of groups.flat()) {
6118
- if (seenModules.has(mod)) continue;
6119
- const ids = [
6120
- mod.id,
6121
- mod.url,
6122
- mod.file
6123
- ].filter((id) => typeof id === "string" && id.length > 0);
6124
- const moduleKind = ids.some(isSourceStyleRequest) ? "style" : "source";
6125
- const keys = ids.map((id) => `${moduleKind}:${resolveViteModuleIdentity(id, root).key}`);
6126
- if (keys.some((key) => seenIdentities.has(key))) continue;
6127
- seenModules.add(mod);
6128
- keys.forEach((key) => seenIdentities.add(key));
6129
- modules.push(mod);
6130
- }
6131
- return modules;
6132
- }
6133
- function resolveModuleHotUrl(mod) {
6134
- if (typeof mod.url === "string" && mod.url.length > 0) return mod.url;
6135
- if (typeof mod.id === "string" && mod.id.startsWith("/")) return mod.id;
6136
- }
6137
- function isAbsoluteFilePath(file) {
6138
- return path.isAbsolute(file) || /^[A-Z]:[\\/]/i.test(file) || file.startsWith("\\\\");
6139
- }
6140
- function normalizeAbsoluteFilePath(file) {
6141
- if (/^[A-Z]:[\\/]/i.test(file) || file.startsWith("\\\\")) return slash(path.win32.resolve(file));
6142
- return slash(path.resolve(file));
6143
- }
6144
- function isRootMiniProgramStyleUrl(file) {
6145
- return /^\/[^/]+\.(?:wxss|acss|ttss|qss|jxss|tyss)(?:$|[?#])/i.test(file);
6146
- }
6147
- function resolveCssHotUrl(id, root) {
6148
- const suffix = /[?#]/.test(id) ? id.slice(id.search(/[?#]/)) : "";
6149
- const cleanId = cleanUrl$1(id);
6150
- if (/^\/(?!@fs\/|[A-Z]:)/i.test(cleanId) && !cleanId.startsWith(slash(root))) {
6151
- if (isRootMiniProgramStyleUrl(cleanId)) return;
6152
- return `${cleanId}${suffix}`;
6153
- }
6154
- const file = resolveViteModuleIdentity(id, root).file ?? cleanId;
6155
- if (!isAbsoluteFilePath(file)) return;
6156
- const normalizedRoot = normalizeAbsoluteFilePath(root);
6157
- const normalizedFile = normalizeAbsoluteFilePath(file);
6158
- if (!normalizedFile.startsWith(`${normalizedRoot}/`)) return;
6159
- return `/${slash(path.relative(normalizedRoot, normalizedFile))}${suffix}`;
6160
- }
6161
- function includesHotModule(modules, target, root) {
6162
- const targetUrl = resolveModuleHotUrl(target);
6163
- const targetId = target.id;
6164
- return modules.some((mod) => {
6165
- if (mod === target) return true;
6166
- return targetUrl !== void 0 && resolveModuleHotUrl(mod) === targetUrl || typeof targetId === "string" && targetId.length > 0 && mod.id === targetId || [
6167
- target.id,
6168
- target.url,
6169
- target.file
6170
- ].some((targetIdentity) => [
6171
- mod.id,
6172
- mod.url,
6173
- mod.file
6174
- ].some((moduleIdentity) => hasSameViteModuleIdentity(targetIdentity, moduleIdentity, root)));
6175
- });
6176
- }
6177
- function includesHotId(modules, targetId, root) {
6178
- return modules.some((mod) => [
6179
- mod.id,
6180
- mod.url,
6181
- mod.file
6182
- ].some((moduleId) => hasSameViteModuleIdentity(targetId, moduleId, root)));
6183
- }
6184
- function createSupplementalHotUpdate(hotUrl, timestamp) {
6185
- return {
6186
- type: "js-update",
6187
- timestamp,
6188
- path: hotUrl,
6189
- acceptedPath: hotUrl,
6190
- explicitImportRequired: false,
6191
- isWithinCircularImport: false
6192
- };
6193
- }
6194
- function hasSelfAcceptingNonStyleHotModule(modules) {
6195
- return modules.some((mod) => {
6196
- const modId = mod.id ?? mod.url;
6197
- return !isSourceStyleRequest(modId) && mod.isSelfAccepting === true;
6198
- });
6199
- }
6200
- function sendSupplementalCssHotUpdates(ctx, cssModules, fallbackCssIds = [], fallbackSourceIds = [], handledModules = ctx.modules) {
6201
- const seenUrls = /* @__PURE__ */ new Set();
6202
- const root = ctx.server.config?.root ?? process$1.cwd();
6203
- const updates = [];
6204
- for (const id of fallbackSourceIds) {
6205
- if (includesHotId(handledModules, id, root)) continue;
6206
- const hotUrl = resolveCssHotUrl(id, root);
6207
- if (!hotUrl || seenUrls.has(hotUrl)) continue;
6208
- seenUrls.add(hotUrl);
6209
- updates.push(createSupplementalHotUpdate(hotUrl, ctx.timestamp));
6210
- }
6211
- for (const id of fallbackCssIds) {
6212
- if (!isSourceStyleRequest(id) || includesHotId(handledModules, id, root)) continue;
6213
- const hotUrl = resolveCssHotUrl(id, root);
6214
- if (!hotUrl || seenUrls.has(hotUrl)) continue;
6215
- seenUrls.add(hotUrl);
6216
- updates.push(createSupplementalHotUpdate(hotUrl, ctx.timestamp));
6217
- }
6218
- for (const mod of cssModules) {
6219
- if (includesHotModule(handledModules, mod, root)) continue;
6220
- const moduleHotUrl = resolveModuleHotUrl(mod);
6221
- const hotUrl = moduleHotUrl ? resolveCssHotUrl(moduleHotUrl, root) : void 0;
6222
- if (!hotUrl || seenUrls.has(hotUrl)) continue;
6223
- seenUrls.add(hotUrl);
6224
- updates.push(createSupplementalHotUpdate(hotUrl, ctx.timestamp));
6225
- }
6226
- if (updates.length === 0) return;
6227
- queueMicrotask(() => {
6228
- ctx.server.ws?.send?.({
6229
- type: "update",
6230
- updates
6231
- });
6232
- });
6233
- }
6234
- function sendFullReloadForUnresolvedHotUpdate(ctx) {
6235
- ctx.server.ws?.send?.({
6236
- type: "full-reload",
6237
- path: "*",
6238
- triggeredBy: ctx.file
6239
- });
6240
- }
6241
- //#endregion
6242
4475
  //#region src/uni-app-x/vite/native-hmr.ts
6243
4476
  function createUniAppXNativeHmrReloader(options) {
6244
4477
  let previousRuntimeClassSet;
@@ -6324,6 +4557,20 @@ function resolvePreprocessorTransform(code, id, lang, options) {
6324
4557
  if (!options.isNativeAppStyleTarget) return { result: void 0 };
6325
4558
  }
6326
4559
  //#endregion
4560
+ //#region src/uni-app-x/vite/style-source.ts
4561
+ const VITE_CSS_HMR_MODULE_RE = /\b(?:const\s+__vite__css\s*=|__vite__updateStyle\s*\()/;
4562
+ function resolveUniAppXStyleSource(code, query) {
4563
+ if (!query.vue || query.type !== "style") return { code };
4564
+ if (VITE_CSS_HMR_MODULE_RE.test(code)) return { skip: true };
4565
+ const styleBlocks = extractSfcStyleBlocks(code);
4566
+ if (styleBlocks.length === 0) return { code };
4567
+ const style = styleBlocks[query.index ?? 0];
4568
+ return style ? { code: style.source } : { skip: true };
4569
+ }
4570
+ function hasUniAppXImportantApply(source, normalize) {
4571
+ return extractSfcStyleBlocks(source).some((style) => normalize(style.source) !== style.source);
4572
+ }
4573
+ //#endregion
6327
4574
  //#region src/uni-app-x/vite/web-local-style.ts
6328
4575
  function isStyleModule(mod) {
6329
4576
  const request = mod.id ?? mod.url;
@@ -6339,7 +4586,7 @@ function createUniAppXWebLocalStyleBridge(isEnabled, hmrCssModuleVersions) {
6339
4586
  },
6340
4587
  handleHotUpdate(ctx) {
6341
4588
  if (!isEnabled() || !/\.(?:uvue|nvue)$/i.test(cleanUrl$1(ctx.file))) return;
6342
- const root = ctx.server.config?.root ?? process$1.cwd();
4589
+ const root = ctx.server.config?.root ?? process.cwd();
6343
4590
  const sourceModules = ctx.modules.filter((mod) => !isStyleModule(mod));
6344
4591
  const contextStyleModules = ctx.modules.filter(isStyleModule);
6345
4592
  const currentContextStyleModules = hmrCssModuleVersions?.filterModules(contextStyleModules, ctx.timestamp, root) ?? contextStyleModules;
@@ -6399,14 +4646,11 @@ function createUniAppXAssetTask(file, originalSource, outDir, options) {
6399
4646
  //#region src/uni-app-x/vite.ts
6400
4647
  let transformUVuePromise;
6401
4648
  function loadTransformUVue() {
6402
- transformUVuePromise ?? (transformUVuePromise = import("./transform-DQhgAarN.js").then((mod) => mod.transformUVue));
4649
+ transformUVuePromise ?? (transformUVuePromise = import("./transform-CfOzh007.js").then((mod) => mod.transformUVue));
6403
4650
  return transformUVuePromise;
6404
4651
  }
6405
4652
  const UVUE_NVUE_QUERY_RE = /\.(?:uvue|nvue)(?:\?.*)?$/;
6406
4653
  const UVUE_NVUE_RE = /\.(?:uvue|nvue)$/;
6407
- function hasUniAppXImportantApply(source) {
6408
- return extractSfcStyleBlocks(source).some((style) => normalizeUniAppXImportantApplyForSass(style.source) !== style.source);
6409
- }
6410
4654
  function createUniAppXPlugins(options) {
6411
4655
  const { appType, customAttributesEntities, disabledDefaultTemplateHandler, isIosPlatform: providedIosPlatform, mainCssChunkMatcher, registerModuleGraphCandidates, runtimeState, styleHandler, syncSourceCandidatesForHotUpdate, tailwindRootCssModuleIds = [], generateCss, hmrCssModuleVersions, jsHandler, ensureRuntimeClassSet, getResolvedConfig, isEnabled = () => true, isNativeAppStyleTarget = () => false, isWebGeneratorTarget = () => resolveUniUtsPlatform().isWeb, uniAppX, viteProcessedCssSourceFiles = [], webCssEntryDiagnostics } = options;
6412
4656
  const resolvedUniAppXOptions = resolveUniAppXOptions(uniAppX);
@@ -6478,6 +4722,9 @@ function createUniAppXPlugins(options) {
6478
4722
  async function transformStyle(code, id, query, hookContext) {
6479
4723
  const isNativeStyle = isNativeAppBuildTarget(id);
6480
4724
  const parsed = query ?? parseVueRequest(id).query;
4725
+ const resolvedSource = resolveUniAppXStyleSource(code, parsed);
4726
+ if (resolvedSource.skip) return;
4727
+ code = resolvedSource.code;
6481
4728
  if (isCSSRequest(id) || parsed.vue && parsed.type === "style") {
6482
4729
  if (isCssModuleExport(code)) return;
6483
4730
  const sourceCode = normalizeRelativeTailwindReferences(restoreUniAppXImportantApplyMarker(code), id);
@@ -6497,7 +4744,8 @@ function createUniAppXPlugins(options) {
6497
4744
  const styleHandlerOptions = getStyleHandlerOptions(id, isNativeStyle && hasTailwindRoot ? "tailwind-root" : isNativeStyle ? "author-apply" : void 0);
6498
4745
  const postcssResult = await styleHandler(styleCode, styleHandlerOptions);
6499
4746
  reportStyleWarnings(postcssResult);
6500
- const postcssMap = await formatPostcssSourceMap(postcssResult.map.toJSON(), normalizePath(cleanUrl$1(id)));
4747
+ const rawPostcssMap = postcssResult.map.toJSON();
4748
+ const postcssMap = await formatPostcssSourceMap(rawPostcssMap, normalizePath(cleanUrl$1(id)));
6501
4749
  return {
6502
4750
  code: postcssResult.css,
6503
4751
  map: postcssMap
@@ -6544,7 +4792,9 @@ function createUniAppXPlugins(options) {
6544
4792
  await runtimeState.readyPromise;
6545
4793
  const { filename, query } = parseVueRequest(id);
6546
4794
  if (query.vue && query.type === "style") await pendingSfcTransforms.get(cleanUrl$1(filename));
6547
- const styleCode = query.vue && query.type === "style" ? webLocalStyle.appendToStyle(code, id) : code;
4795
+ const resolvedSource = resolveUniAppXStyleSource(code, query);
4796
+ if (resolvedSource.skip) return;
4797
+ const styleCode = query.vue && query.type === "style" ? webLocalStyle.appendToStyle(resolvedSource.code, id) : resolvedSource.code;
6548
4798
  const preprocessorCode = query.vue && query.type === "style" ? normalizeUniAppXImportantApplyForSass(styleCode) : styleCode;
6549
4799
  const preprocessor = resolvePreprocessorTransform(preprocessorCode, id, query.lang, {
6550
4800
  isIosPlatform,
@@ -6628,7 +4878,7 @@ function createUniAppXPlugins(options) {
6628
4878
  if (!UVUE_NVUE_RE.test(ctx.file) && !isCSSRequest(ctx.file)) return;
6629
4879
  if (isWebGeneratorTarget() && UVUE_NVUE_RE.test(ctx.file) && typeof ctx.read === "function") {
6630
4880
  const source = await ctx.read();
6631
- if (hasUniAppXImportantApply(source)) {
4881
+ if (hasUniAppXImportantApply(source, normalizeUniAppXImportantApplyForSass)) {
6632
4882
  ctx.server.ws.send({
6633
4883
  type: "full-reload",
6634
4884
  path: ctx.file
@@ -6671,7 +4921,7 @@ function createUniAppXPlugins(options) {
6671
4921
  const applyStyleSources = harmonyApply.styleSources.size > 0 ? [...harmonyApply.styleSources] : collectUniAppXHarmonyApplyStyleSources(bundle);
6672
4922
  const applyUtilities = /* @__PURE__ */ new Set([...harmonyApply.utilities, ...collectUniAppXHarmonyApplyUtilities(bundle)]);
6673
4923
  if (applyStyleSources.length > 0 && applyUtilities.size > 0) {
6674
- const harmonyApplyCssFile = path.resolve(getResolvedConfig()?.root ?? process$1.cwd(), "uni-app-x-harmony-apply.css");
4924
+ const harmonyApplyCssFile = path.resolve(getResolvedConfig()?.root ?? process.cwd(), "uni-app-x-harmony-apply.css");
6675
4925
  const generatedCss = await generateCss?.(harmonyApplyCssFile, createUniAppXHarmonyApplyGeneratorSource(applyStyleSources, applyUtilities), {
6676
4926
  addWatchFile: this?.addWatchFile?.bind(this),
6677
4927
  disableSourceScan: true,
@@ -7006,7 +5256,7 @@ async function processRememberedCssReplay(options) {
7006
5256
  rememberLastCssResult(lastCssResultByFile, lastCssSourceHashByFile, outputFile, css, cssRuntimeAffectingHash);
7007
5257
  for (const key of rememberedKeys) setRememberedCssSignature?.(key, rememberedCssRuntimeSignature);
7008
5258
  if (generated) {
7009
- registerGeneratorDependencies$1({ addWatchFile }, generated.dependencies);
5259
+ registerGeneratorDependencies({ addWatchFile }, generated.dependencies);
7010
5260
  recordCssAssetResult?.(outputFile, css);
7011
5261
  const shouldInjectReplayCssIntoMain = shouldInjectCssIntoMainFromOutput(outputFile, sourceFile, outputCssHandlerOptions);
7012
5262
  const injectIntoMain = shouldMergeReplayIntoFrameworkRootTarget ? true : outputCssHandlerOptions.isMainChunk ? false : shouldInjectReplayCssIntoMain;
@@ -7538,7 +5788,7 @@ async function validateRuntimeCandidates(options) {
7538
5788
  }
7539
5789
  //#endregion
7540
5790
  //#region src/bundlers/vite/generate-bundle/runtime.ts
7541
- function inferPlatformFromViteOutDir$1(outDir) {
5791
+ function inferPlatformFromViteOutDir(outDir) {
7542
5792
  const segment = outDir ? path.basename(path.normalize(outDir)) : void 0;
7543
5793
  if (!segment) return;
7544
5794
  const normalized = segment.trim().toLowerCase();
@@ -7554,7 +5804,7 @@ function createGenerateBundleHook$1(context) {
7554
5804
  let currentSubpackageRoots;
7555
5805
  const createInitialCssPipelineContext = (file) => {
7556
5806
  const resolvedConfig = context.getResolvedConfig();
7557
- const platform = context.opts.cssOptions?.platform ?? context.opts.platform ?? inferPlatformFromViteOutDir$1(resolvedConfig?.build?.outDir);
5807
+ const platform = context.opts.cssOptions?.platform ?? context.opts.platform ?? inferPlatformFromViteOutDir(resolvedConfig?.build?.outDir);
7558
5808
  const currentGeneratorOptions = normalizeWeappTailwindcssGeneratorOptions(context.opts.generator, {
7559
5809
  appType: context.opts.appType,
7560
5810
  platform,
@@ -7604,7 +5854,7 @@ function createGenerateBundleHook$1(context) {
7604
5854
  const { cache, onEnd, onStart, onUpdate, styleHandler, templateHandler, jsHandler, uniAppX } = opts;
7605
5855
  const resolvedConfig = getResolvedConfig();
7606
5856
  const uniUtsPlatform = resolveUniUtsPlatform();
7607
- const generatorPlatform = opts.cssOptions?.platform ?? opts.platform ?? inferPlatformFromViteOutDir$1(resolvedConfig?.build?.outDir);
5857
+ const generatorPlatform = opts.cssOptions?.platform ?? opts.platform ?? inferPlatformFromViteOutDir(resolvedConfig?.build?.outDir);
7608
5858
  const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator, {
7609
5859
  appType: opts.appType,
7610
5860
  platform: generatorPlatform,
@@ -7642,7 +5892,7 @@ function createGenerateBundleHook$1(context) {
7642
5892
  const shouldPreserveAppCssExtension = context.cssPipelineStrategy?.shouldPreserveStyleOutputExtension?.(cssPipelineContext) ?? (isNativeAppStyleTarget || isHarmonyAppStyleTarget);
7643
5893
  const shouldGenerateWebCssByGenerator = isWebGeneratorTarget;
7644
5894
  const { getCssHandlerOptions, getCssUserHandlerOptions } = cssHandlerOptions;
7645
- const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process$1.cwd();
5895
+ const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process.cwd();
7646
5896
  const sourceRoot = resolveWeappViteSourceRoot(resolvedConfig, opts.appType) ?? resolveSourceRootFromBundleGraph(resolvedConfig, bundle);
7647
5897
  const outDir = resolvedConfig?.build?.outDir ? path.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
7648
5898
  const defaultStyleOutputExtension = resolveMiniProgramStyleOutputExtension({ files: Object.keys(bundle) });
@@ -8271,230 +6521,14 @@ function createGenerateBundleHook(context) {
8271
6521
  };
8272
6522
  }
8273
6523
  //#endregion
8274
- //#region src/bundlers/vite/shared/generic-web-production-fast-path.ts
8275
- /**
8276
- * Generic Web 非 watch 生产构建由 Tailwind Scanner 直接提供候选,不需要重复维护小程序候选状态。
8277
- */
8278
- function shouldSkipGenericWebProductionSourceCandidates(options) {
8279
- return options.frameworkName === "generic" && options.command === "build" && options.watch == null && options.isWebGeneratorTarget && options.requiresSourceCandidateState !== true;
8280
- }
8281
- /**
8282
- * 在 Vite 解析插件列表时排除无需维护的候选层,避免其 hooks 进入模块图。
8283
- */
8284
- function createGenericWebProductionSourceCandidatesApply(options) {
8285
- return (config, env) => !shouldSkipGenericWebProductionSourceCandidates({
8286
- command: env.command,
8287
- frameworkName: options.frameworkName,
8288
- isWebGeneratorTarget: options.getIsWebGeneratorTarget(),
8289
- requiresSourceCandidateState: options.requiresSourceCandidateState,
8290
- watch: config.build?.watch
8291
- });
8292
- }
8293
- /**
8294
- * Generic Web 生产构建的 CSS 已在 Vite transform 阶段生成时,不需要再建立面向小程序的完整产物快照。
8295
- */
8296
- function shouldUseGenericWebProductionFastPath(options) {
8297
- return shouldSkipGenericWebProductionSourceCandidates(options) && options.hasProcessedCss;
8298
- }
8299
- /**
8300
- * Finalizer fast path 只处理无小程序结构语义的 Generic Web 生产产物。
8301
- */
8302
- function shouldUseGenericWebFinalizerFastPath(options) {
8303
- return shouldUseGenericWebProductionFastPath(options) && !options.hasFrameworkRootImportShells && !options.isHarmonyAppStyleTarget && !options.isNativeAppStyleTarget;
8304
- }
8305
- /**
8306
- * 将 Generic Web fast path 的判定和跳过生命周期集中起来,供 generateBundle hook 直接消费。
8307
- */
8308
- function createGenericWebProductionBundleHooks(options) {
6524
+ //#region src/bundlers/vite/css-finalizer/plugin.ts
6525
+ function createViteCssFinalizerOutputPlugin(context) {
8309
6526
  return {
8310
- onSkipProcessBundle: () => {
8311
- options.onStart();
8312
- options.onEnd();
8313
- },
8314
- shouldProcessBundle: () => {
8315
- const config = options.getResolvedConfig();
8316
- return !shouldUseGenericWebProductionFastPath({
8317
- command: config?.command,
8318
- frameworkName: options.frameworkName,
8319
- hasProcessedCss: options.getHasProcessedCss(),
8320
- isWebGeneratorTarget: options.getIsWebGeneratorTarget(),
8321
- watch: config?.build?.watch
8322
- });
8323
- }
8324
- };
8325
- }
8326
- //#endregion
8327
- //#region src/bundlers/vite/css-finalizer/options.ts
8328
- function inferPlatformFromViteOutDir(outDir) {
8329
- const segment = outDir ? path.basename(path.normalize(outDir)) : void 0;
8330
- if (!segment) return;
8331
- const normalized = segment.trim().toLowerCase();
8332
- if (normalized === "h5" || normalized === "web" || normalized === "app" || normalized === "app-plus" || normalized.startsWith("app-") || normalized.startsWith("mp-") || normalized.startsWith("quickapp-webview")) return normalized;
8333
- }
8334
- function isAddWatchFileInvalidRollupPhaseError(error) {
8335
- const candidate = error;
8336
- return candidate?.code === "INVALID_ROLLUP_PHASE" || candidate?.pluginCode === "INVALID_ROLLUP_PHASE" || candidate?.message?.includes("Cannot call \"addWatchFile\" after the build has finished.") === true;
8337
- }
8338
- function registerGeneratorDependencies(ctx, dependencies) {
8339
- if (typeof ctx.addWatchFile !== "function") return;
8340
- for (const dependency of dependencies ?? []) try {
8341
- ctx.addWatchFile(dependency);
8342
- } catch (error) {
8343
- if (isAddWatchFileInvalidRollupPhaseError(error)) {
8344
- logger.debug("跳过生成模式依赖监听注册,当前 Rollup 阶段不允许 addWatchFile: %s", dependency);
8345
- continue;
8346
- }
8347
- throw error;
8348
- }
8349
- }
8350
- function createCssHandlerOptions(opts, majorVersion, file, outputRoot, extraOptions = {}) {
8351
- const from = path.isAbsolute(file) ? file : outputRoot ? path.resolve(outputRoot, file) : file;
8352
- return {
8353
- ...extraOptions,
8354
- cssPreflight: opts.cssPreflight,
8355
- isMainChunk: opts.mainCssChunkMatcher(file, opts.appType),
8356
- postcssOptions: { options: { from } },
8357
- ...normalizeStyleHandlerMajorVersion(majorVersion) === void 0 ? {} : { majorVersion: 4 }
8358
- };
8359
- }
8360
- function shouldGenerateCssByGenerator(opts, majorVersion, file, rawSource, processed) {
8361
- const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator, {
8362
- appType: opts.appType,
8363
- platform: opts.cssOptions?.platform ?? opts.platform,
8364
- tailwindcssMajorVersion: majorVersion,
8365
- uniAppX: opts.uniAppX
8366
- });
8367
- if (!generatorOptions.enabled) return false;
8368
- if (hasLocalCssImport(rawSource)) return false;
8369
- if (hasTailwindGeneratedCssMarkers(rawSource)) return true;
8370
- if (hasTailwindRootDirectives(rawSource, { importFallback: generatorOptions.importFallback })) return true;
8371
- return processed && hasTailwindApplyDirective(rawSource) && shouldFinalizeProcessedCssAsset(opts, file);
8372
- }
8373
- function shouldFinalizeProcessedCssAsset(opts, file) {
8374
- return opts.mainCssChunkMatcher(file, opts.appType);
8375
- }
8376
- function collectViteProcessedCssSources(getViteProcessedCssAssetResults) {
8377
- return [...getViteProcessedCssAssetResults?.() ?? []].map(([, record]) => typeof record === "string" ? record : record.css);
8378
- }
8379
- function finalizeWebCss(css, context, cssPipelineStrategy) {
8380
- const shouldApplyWebCssCompat = shouldApplyViteWebCssCompat(context, cssPipelineStrategy);
8381
- const defaultWebCssCompat = (value) => transformWebCssCompat(value, resolveViteWebCssCompatOptions(context));
8382
- return cssPipelineStrategy?.transformGeneratedCss?.(css, {
8383
- ...context,
8384
- defaultWebCssCompat,
8385
- removeScopedPreflight: (value) => value,
8386
- shouldApplyWebCssCompat
8387
- }) ?? (shouldApplyWebCssCompat ? defaultWebCssCompat(css) : css);
8388
- }
8389
- //#endregion
8390
- //#region src/bundlers/vite/css-finalizer/generic-web-fast-path.ts
8391
- function readAssetSource(asset) {
8392
- return typeof asset.source === "string" ? asset.source : asset.source.toString();
8393
- }
8394
- function collectCssAssets(bundle, context) {
8395
- const assets = /* @__PURE__ */ new Map();
8396
- for (const [bundleFile, output] of Object.entries(bundle)) {
8397
- if (output.type !== "asset") continue;
8398
- const file = output.fileName || bundleFile;
8399
- if (!context.opts.cssMatcher(file) || context.opts.htmlMatcher(file)) continue;
8400
- assets.set(normalizeOutputPathKey(file), {
8401
- asset: output,
8402
- file,
8403
- original: readAssetSource(output)
8404
- });
8405
- }
8406
- return assets;
8407
- }
8408
- function resolveProcessedCssOutputFile(file, options, bundleFiles) {
8409
- return resolveViteCssPipelineOutputFile(file, options.context.opts, options.rootDir, true, false, options.sourceRoot, ".css", bundleFiles);
8410
- }
8411
- function resolveProcessedCssAssets(cssAssets, records, options, bundleFiles) {
8412
- const assetBySourceFile = /* @__PURE__ */ new Map();
8413
- for (const output of cssAssets.values()) {
8414
- const identity = options.context.resolveCssAssetIdentity?.(output.asset, output.file);
8415
- if (identity?.kind === "bundler-generated" && identity.sourceFile) assetBySourceFile.set(normalizeOutputPathKey(identity.sourceFile), output);
8416
- for (const sourceFile of collectMatchingGeneratedCssMarkerFiles(output.file, output.original, (file) => resolveProcessedCssOutputFile(file, options, bundleFiles))) assetBySourceFile.set(normalizeOutputPathKey(sourceFile), output);
8417
- }
8418
- const processedAssets = /* @__PURE__ */ new Map();
8419
- const htmlOwnedAssets = [...cssAssets.values()].filter((output) => [output.asset.originalFileName, ...output.asset.originalFileNames ?? []].some((file) => typeof file === "string" && /\.html(?:$|[?#])/i.test(file)));
8420
- for (const [file, record] of records) {
8421
- const recordCss = typeof record === "string" ? record : record.css;
8422
- const outputFile = typeof record === "string" ? resolveProcessedCssOutputFile(file, options, bundleFiles) : record.outputFile ?? resolveProcessedCssOutputFile(file, options, bundleFiles);
8423
- let output = assetBySourceFile.get(normalizeOutputPathKey(file)) ?? (outputFile ? cssAssets.get(normalizeOutputPathKey(outputFile)) : void 0);
8424
- let useAssetSource = output !== void 0;
8425
- if (!output) {
8426
- const matchingAssets = [...cssAssets.values()].filter((candidate) => options.context.isCssAssetProcessed(candidate.asset, candidate.file) && resolveViteProcessedCssAssetSource(candidate.file, candidate.original, (sourceFile) => resolveProcessedCssOutputFile(sourceFile, options, bundleFiles)) === recordCss);
8427
- if (matchingAssets.length === 1) {
8428
- output = matchingAssets[0];
8429
- useAssetSource = true;
8430
- }
8431
- }
8432
- if (!output && records.length === 1 && htmlOwnedAssets.length === 1) {
8433
- output = htmlOwnedAssets[0];
8434
- useAssetSource = hasTailwindGeneratedCss(output.original) || hasTailwindGeneratedCssMarkers(output.original);
8435
- }
8436
- if (!output) return;
8437
- const existing = processedAssets.get(output);
8438
- if (existing !== void 0 && existing.css !== recordCss) return;
8439
- processedAssets.set(output, {
8440
- css: recordCss,
8441
- useAssetSource
8442
- });
8443
- }
8444
- return processedAssets;
8445
- }
8446
- /**
8447
- * Generic Web 的 transform 结果能唯一映射到最终 CSS asset 时,只做一次 marker 清理和 Web 兼容收尾。
8448
- */
8449
- function tryFinalizeGenericWebCss(options) {
8450
- const { bundle, context } = options;
8451
- const resolvedConfig = context.getResolvedConfig();
8452
- const collectStartedAt = performance.now();
8453
- const processedCssResults = [...context.getViteProcessedCssAssetResults?.() ?? []];
8454
- if (!shouldUseGenericWebFinalizerFastPath({
8455
- command: resolvedConfig?.command,
8456
- frameworkName: context.frameworkName ?? "",
8457
- hasFrameworkRootImportShells: (context.frameworkRootImportShellTargetByFile?.size ?? 0) > 0,
8458
- hasProcessedCss: processedCssResults.length > 0,
8459
- isHarmonyAppStyleTarget: options.isHarmonyAppStyleTarget,
8460
- isNativeAppStyleTarget: options.isNativeAppStyleTarget,
8461
- isWebGeneratorTarget: options.isWebGeneratorTarget,
8462
- watch: resolvedConfig?.build?.watch
8463
- })) return false;
8464
- const enumerateStartedAt = performance.now();
8465
- const cssAssets = collectCssAssets(bundle, context);
8466
- const bundleFiles = [...cssAssets.values()].map((item) => item.file);
8467
- options.recordTiming("assets.enumerate", enumerateStartedAt);
8468
- const processedAssets = resolveProcessedCssAssets(cssAssets, processedCssResults, options, bundleFiles);
8469
- options.recordTiming("processedCss.collect", collectStartedAt);
8470
- if (!processedAssets) return false;
8471
- const writeStartedAt = performance.now();
8472
- for (const [{ asset, file, original }, processed] of processedAssets) {
8473
- const finalizeStartedAt = performance.now();
8474
- const finalCssSource = processed.useAssetSource ? original : processed.css;
8475
- const generated = finalizeWebCss(stripBundlerGeneratedCssMarkers(finalCssSource), {
8476
- ...options.createCssPipelineContext(file),
8477
- file
8478
- }, context.cssPipelineStrategy);
8479
- options.recordTiming("finalizeWebCss", finalizeStartedAt);
8480
- asset.source = generated;
8481
- context.markCssAssetProcessed(asset, file);
8482
- context.recordCssAssetResult?.(file, generated);
8483
- if (generated !== original) context.opts.onUpdate(file, original, generated);
8484
- }
8485
- options.recordTiming("processedCss.inject", performance.now());
8486
- options.recordTiming("assets.markerCleanupWrite", writeStartedAt);
8487
- return true;
8488
- }
8489
- //#endregion
8490
- //#region src/bundlers/vite/css-finalizer/plugin.ts
8491
- function createViteCssFinalizerOutputPlugin(context) {
8492
- return {
8493
- name: "weapp-tailwindcss:adaptor:css-finalizer",
8494
- enforce: "post",
8495
- async closeBundle() {
8496
- if (context.getResolvedConfig()?.build?.watch != null) return;
8497
- await disposeCompilerOwner(context.runtimeState);
6527
+ name: "weapp-tailwindcss:adaptor:css-finalizer",
6528
+ enforce: "post",
6529
+ async closeBundle() {
6530
+ if (context.getResolvedConfig()?.build?.watch != null) return;
6531
+ await disposeCompilerOwner(context.runtimeState);
8498
6532
  },
8499
6533
  async closeWatcher() {
8500
6534
  await disposeCompilerOwner(context.runtimeState);
@@ -8505,7 +6539,7 @@ function createViteCssFinalizerOutputPlugin(context) {
8505
6539
  const { opts, runtimeState, ensureRuntimeClassSet, cssPipelineStrategy, isCssAssetProcessed, markCssAssetProcessed, debug, getResolvedConfig, recordCssAssetResult, recordViteProcessedCssAssetResult, getViteProcessedCssAssetResults, getRecordedGeneratorCandidates, getSourceCandidates, getSourceCandidatesForEntries, getSourceCandidateSourcesForEntries, waitForSourceCandidateSyncs, rememberMainCssSource, getRememberedMainCssSource, isViteProcessedCssAsset, frameworkRootImportShellTargetByFile } = context;
8506
6540
  const resolvedConfig = getResolvedConfig();
8507
6541
  const uniUtsPlatform = resolveUniUtsPlatform();
8508
- const generatorPlatform = opts.cssOptions?.platform ?? opts.platform ?? inferPlatformFromViteOutDir(resolvedConfig?.build?.outDir);
6542
+ const generatorPlatform = opts.cssOptions?.platform ?? opts.platform ?? inferPlatformFromViteOutDir$1(resolvedConfig?.build?.outDir);
8509
6543
  const generatorOptions = normalizeWeappTailwindcssGeneratorOptions(opts.generator, {
8510
6544
  appType: opts.appType,
8511
6545
  platform: generatorPlatform,
@@ -8549,7 +6583,7 @@ function createViteCssFinalizerOutputPlugin(context) {
8549
6583
  const isHarmonyAppStyleTarget = cssPipelineStrategy?.isHarmonyAppStyleTarget?.(createCssPipelineContext("")) === true;
8550
6584
  const isNativeAppStyleTarget = cssPipelineStrategy?.isNativeAppStyleTarget?.(createCssPipelineContext("")) === true;
8551
6585
  if (resolvedConfig?.command !== "build" && !isNativeAppStyleTarget) return;
8552
- const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process$1.cwd();
6586
+ const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process.cwd();
8553
6587
  const outDir = resolvedConfig?.build?.outDir ? path.resolve(rootDir, resolvedConfig.build.outDir) : rootDir;
8554
6588
  const sourceRoot = resolveWeappViteSourceRoot(resolvedConfig, opts.appType) ?? resolveSourceRootFromBundleGraph(resolvedConfig, bundle);
8555
6589
  const finalizerStartedAt = performance.now();
@@ -8759,680 +6793,71 @@ function createViteCssFinalizerOutputPlugin(context) {
8759
6793
  const generatorTransformRawSource = generatorRawSource;
8760
6794
  const generated = shouldGenerateCssByGenerator(opts, runtimeState.tailwindRuntime.majorVersion, file, generatorTransformRawSource, processed) ? await generateTailwindV4Css({
8761
6795
  opts,
8762
- runtimeState,
8763
- runtime: generatorRuntime,
8764
- rawSource: generatorTransformRawSource,
8765
- file: generatorSourceFile,
8766
- outputFile: file,
8767
- cssHandlerOptions: generatorCssHandlerOptions,
8768
- cssUserHandlerOptions: generatorCssUserHandlerOptions,
8769
- cssStage: "framework-processed",
8770
- getSourceCandidatesForEntries,
8771
- generatorPlatform,
8772
- styleHandler: opts.styleHandler,
8773
- debug
8774
- }) : void 0;
8775
- if (!generated && !generatorBranch.isWeb && isPureLocalCssImportWrapper(generatorTransformRawSource)) {
8776
- const nextCss = generatorTransformRawSource;
8777
- if (nextCss !== rawSource) {
8778
- writeCssAsset(file, output, nextCss);
8779
- opts.onUpdate(file, rawSource, nextCss);
8780
- }
8781
- markCssAssetProcessed(output, file);
8782
- recordCssAssetResult?.(file, nextCss);
8783
- debug("css finalizer preserve mini-program import shell: %s", file);
8784
- return;
8785
- }
8786
- const nextCss = annotateCss(generated?.css ?? (generatorBranch.isWeb ? finalizeWebCssAsset(cleanRawSource, file) : (await opts.styleHandler(generatorTransformRawSource, cssHandlerOptions)).css));
8787
- if (generated) {
8788
- registerGeneratorDependencies(this, generated.dependencies);
8789
- debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
8790
- recordCssAssetResult?.(file, nextCss);
8791
- if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, generatorRawSource);
8792
- }
8793
- writeCssAsset(file, output, nextCss);
8794
- markCssAssetProcessed(output, file);
8795
- opts.onUpdate(file, rawSource, nextCss);
8796
- debug("css finalizer handle: %s", file);
8797
- }));
8798
- const writeStartedAt = performance.now();
8799
- applyViteAssetEmissionPlan(emissionPlan, {
8800
- bundle,
8801
- writeTargets
8802
- });
8803
- await injectHarmonyBundleStyles();
8804
- collectViteProcessedCssAssets();
8805
- injectViteProcessedCssIntoMainCss();
8806
- normalizeRootMiniProgramImportShellAssets(bundle, {
8807
- cssMatcher: opts.cssMatcher,
8808
- debug,
8809
- enabled: cssPipelineStrategy?.shouldNormalizeRootMiniProgramImportShell?.(createCssPipelineContext("")) === true,
8810
- onUpdate: trackFinalCssAssetUpdate,
8811
- recordCssAssetResult
8812
- });
8813
- finalizeMiniProgramCssAssetStructures(bundle, {
8814
- cssMatcher: opts.cssMatcher,
8815
- debug,
8816
- files: finalCssAssetFiles,
8817
- isWebGeneratorTarget,
8818
- onUpdate: opts.onUpdate,
8819
- recordCssAssetResult
8820
- });
8821
- finalizeCompilerShadowRun(runtimeState);
8822
- recordTiming("assets.write", writeStartedAt);
8823
- finishTiming();
8824
- }
8825
- }
8826
- };
8827
- }
8828
- //#endregion
8829
- //#region src/bundlers/vite/map-cache.ts
8830
- function touchMapEntry(map, key, value) {
8831
- map.delete(key);
8832
- map.set(key, value);
8833
- }
8834
- function pruneMapToMaxSize(map, maxSize, onDelete) {
8835
- while (map.size > maxSize) {
8836
- const key = map.keys().next().value;
8837
- if (key === void 0) break;
8838
- map.delete(key);
8839
- onDelete?.(key);
8840
- }
8841
- }
8842
- //#endregion
8843
- //#region src/bundlers/vite/css-memory.ts
8844
- const VITE_REMEMBERED_CSS_CACHE_MAX = 96;
8845
- const VITE_KNOWN_SFC_SOURCE_CACHE_MAX = 128;
8846
- const SFC_STYLE_BLOCK_RE = /<style\b[^>]*>([\s\S]*?)<\/style>/gi;
8847
- const SFC_COMPONENT_FILE_RE = /\.(?:vue|uvue|nvue|svelte|mpx)$/i;
8848
- function toMb$1(bytes) {
8849
- return Math.round(bytes / 1024 / 1024);
8850
- }
8851
- function summarizeStringMapCache(map) {
8852
- let bytes = 0;
8853
- for (const value of map.values()) bytes += value.length;
8854
- return {
8855
- bytes,
8856
- mb: toMb$1(bytes),
8857
- size: map.size
8858
- };
8859
- }
8860
- function summarizeRememberedCssSources(map) {
8861
- let bytes = 0;
8862
- for (const value of map.values()) bytes += value.rawSource.length;
8863
- return {
8864
- bytes,
8865
- mb: toMb$1(bytes),
8866
- size: map.size
8867
- };
8868
- }
8869
- function stripSourceHash(sourceFile) {
8870
- const hashIndex = sourceFile.indexOf("#");
8871
- return hashIndex === -1 ? sourceFile : sourceFile.slice(0, hashIndex);
8872
- }
8873
- function normalizeCssSourceIdentity(sourceFile) {
8874
- const cleanSourceFile = stripSourceHash(sourceFile);
8875
- const { filename, query } = parseVueRequest(cleanSourceFile);
8876
- const normalizedFile = normalizeOutputPathKey(filename);
8877
- if (query.type === "style") return `${normalizedFile}?type=style&index=${query.index ?? 0}`;
8878
- return normalizeOutputPathKey(stripRequestQuery(cleanSourceFile));
8879
- }
8880
- function hasSfcStyleBlocks(source) {
8881
- SFC_STYLE_BLOCK_RE.lastIndex = 0;
8882
- return SFC_STYLE_BLOCK_RE.test(source);
8883
- }
8884
- function extractSfcStyleBlock(source, index) {
8885
- const targetIndex = index ?? 0;
8886
- SFC_STYLE_BLOCK_RE.lastIndex = 0;
8887
- let currentIndex = 0;
8888
- let match = SFC_STYLE_BLOCK_RE.exec(source);
8889
- while (match !== null) {
8890
- if (currentIndex === targetIndex) return match[1] ?? "";
8891
- currentIndex++;
8892
- match = SFC_STYLE_BLOCK_RE.exec(source);
8893
- }
8894
- }
8895
- function extractSfcStyleSource(source, index) {
8896
- if (index !== void 0) return extractSfcStyleBlock(source, index);
8897
- const styleSources = [];
8898
- SFC_STYLE_BLOCK_RE.lastIndex = 0;
8899
- let match = SFC_STYLE_BLOCK_RE.exec(source);
8900
- while (match !== null) {
8901
- styleSources.push(match[1] ?? "");
8902
- match = SFC_STYLE_BLOCK_RE.exec(source);
8903
- }
8904
- return styleSources.length > 0 ? styleSources.join("\n") : void 0;
8905
- }
8906
- function normalizeKnownSfcSourceKey(file) {
8907
- return normalizeOutputPathKey(path.resolve(cleanUrl$1(file)));
8908
- }
8909
- function shouldCollectTransformedSourceCandidates(id) {
8910
- if (isWeappViteSidecarRequest(id)) return false;
8911
- if (id.search(/[?#]/) < 0) return true;
8912
- const file = cleanUrl$1(id);
8913
- return !SFC_COMPONENT_FILE_RE.test(file);
8914
- }
8915
- function createViteCssMemory(options) {
8916
- const rememberedCssSources = /* @__PURE__ */ new Map();
8917
- const rememberedCssSignatureByFile = /* @__PURE__ */ new Map();
8918
- const knownCssSources = /* @__PURE__ */ new Map();
8919
- const knownSfcSources = /* @__PURE__ */ new Map();
8920
- const rememberKnownSfcSource = (id, code) => {
8921
- if (id.search(/[?#]/) >= 0) return;
8922
- const file = cleanUrl$1(id);
8923
- if (!SFC_COMPONENT_FILE_RE.test(file)) return;
8924
- if (!hasSfcStyleBlocks(code)) return;
8925
- touchMapEntry(knownSfcSources, normalizeKnownSfcSourceKey(file), code);
8926
- pruneMapToMaxSize(knownSfcSources, VITE_KNOWN_SFC_SOURCE_CACHE_MAX);
8927
- };
8928
- const getKnownSfcSource = (file) => {
8929
- const scanSource = options.getSourceCandidateSource(file);
8930
- if (scanSource && hasSfcStyleBlocks(scanSource)) return scanSource;
8931
- const key = normalizeKnownSfcSourceKey(file);
8932
- const source = knownSfcSources.get(key);
8933
- if (source != null) touchMapEntry(knownSfcSources, key, source);
8934
- return source;
8935
- };
8936
- const getKnownCssSource = (file) => {
8937
- const source = knownCssSources.get(normalizeCssSourceIdentity(file));
8938
- if (source != null) touchMapEntry(knownCssSources, normalizeCssSourceIdentity(file), source);
8939
- return source;
8940
- };
8941
- const rememberCssSource = (entry, cssRuntimeSignature) => {
8942
- getActiveViteSourceOutputRelationOwner()?.recordOwnedOutput(entry.sourceFile, entry.outputFile);
8943
- const outputKey = normalizeOutputPathKey(entry.outputFile);
8944
- const normalizedSourceFile = normalizeCssSourceIdentity(entry.sourceFile);
8945
- const previousOutputEntry = rememberedCssSources.get(outputKey);
8946
- const key = previousOutputEntry != null && normalizeCssSourceIdentity(previousOutputEntry.sourceFile) !== normalizedSourceFile ? `${outputKey}\0${normalizedSourceFile}` : outputKey;
8947
- const previous = rememberedCssSources.get(key);
8948
- touchMapEntry(rememberedCssSources, key, entry);
8949
- const relatedRememberedEntries = [...rememberedCssSources].filter(([rememberedKey, remembered]) => rememberedKey !== key && normalizeCssSourceIdentity(remembered.sourceFile) === normalizedSourceFile);
8950
- for (const [rememberedKey, remembered] of relatedRememberedEntries) {
8951
- touchMapEntry(rememberedCssSources, rememberedKey, {
8952
- ...remembered,
8953
- outputFile: entry.outputFile,
8954
- rawSource: entry.rawSource,
8955
- sourceFile: entry.sourceFile
8956
- });
8957
- rememberedCssSignatureByFile.delete(rememberedKey);
8958
- }
8959
- if (cssRuntimeSignature) rememberedCssSignatureByFile.set(key, cssRuntimeSignature);
8960
- else if (previous?.rawSource !== entry.rawSource || previous?.sourceFile !== entry.sourceFile) rememberedCssSignatureByFile.delete(key);
8961
- pruneMapToMaxSize(rememberedCssSources, VITE_REMEMBERED_CSS_CACHE_MAX, (rememberedKey) => {
8962
- rememberedCssSignatureByFile.delete(String(rememberedKey));
8963
- });
8964
- };
8965
- const refreshRememberedCssSourceEntry = (rememberedKey, remembered, sourceFile, rawSource) => {
8966
- if (remembered.rawSource === rawSource && remembered.sourceFile === sourceFile) return remembered;
8967
- const nextRemembered = {
8968
- ...remembered,
8969
- rawSource,
8970
- sourceFile
8971
- };
8972
- touchMapEntry(rememberedCssSources, rememberedKey, nextRemembered);
8973
- rememberedCssSignatureByFile.delete(rememberedKey);
8974
- return nextRemembered;
8975
- };
8976
- const refreshRememberedCssSourceBySourceFile = (sourceFile, rawSource) => {
8977
- touchMapEntry(knownCssSources, normalizeCssSourceIdentity(sourceFile), rawSource);
8978
- const normalizedSourceFile = normalizeCssSourceIdentity(sourceFile);
8979
- const relatedRememberedEntries = [...rememberedCssSources].filter(([, remembered]) => normalizeCssSourceIdentity(remembered.sourceFile) === normalizedSourceFile);
8980
- for (const [rememberedKey, remembered] of relatedRememberedEntries) refreshRememberedCssSourceEntry(rememberedKey, remembered, sourceFile, rawSource);
8981
- };
8982
- const resolveCachedStyleSource = (sourceFile) => {
8983
- const file = cleanUrl$1(stripRequestQuery(sourceFile));
8984
- if (SFC_COMPONENT_FILE_RE.test(file)) return getKnownSfcSource(file);
8985
- if (isSourceStyleRequest(file)) return options.getSourceCandidateSource(file);
8986
- };
8987
- const resolveCurrentStyleSource = (sourceFile) => {
8988
- const cached = resolveCachedStyleSource(sourceFile);
8989
- if (cached != null) return cached;
8990
- const file = cleanUrl$1(stripRequestQuery(sourceFile));
8991
- const knownSource = knownCssSources.get(normalizeCssSourceIdentity(sourceFile));
8992
- if (knownSource != null) return knownSource;
8993
- const candidateSource = options.getSourceCandidateSource(file);
8994
- if (candidateSource != null) return candidateSource;
8995
- };
8996
- const refreshRememberedCssSourceByCurrentFile = async (sourceFile) => {
8997
- const file = cleanUrl$1(sourceFile);
8998
- const normalizedSourceFile = normalizeOutputPathKey(file);
8999
- const matchedRememberedSources = [...rememberedCssSources.values()].filter((remembered) => normalizeOutputPathKey(stripRequestQuery(cleanUrl$1(remembered.sourceFile))) === normalizedSourceFile);
9000
- if (matchedRememberedSources.length === 0) return;
9001
- const source = await resolveCurrentStyleSource(file);
9002
- if (source == null) {
9003
- options.debug("refresh remembered css source skipped: missing cached source for %s", file);
9004
- return;
9005
- }
9006
- if (SFC_COMPONENT_FILE_RE.test(file)) {
9007
- for (const remembered of matchedRememberedSources) {
9008
- const { query } = parseVueRequest(remembered.sourceFile);
9009
- const styleSource = extractSfcStyleSource(source, query.type === "style" ? query.index : void 0);
9010
- if (styleSource !== void 0) refreshRememberedCssSourceBySourceFile(remembered.sourceFile, styleSource);
9011
- }
9012
- return;
9013
- }
9014
- if (isSourceStyleRequest(file)) refreshRememberedCssSourceBySourceFile(file, source);
9015
- };
9016
- const prune = (pruneOptions) => {
9017
- const activeFiles = new Set([...pruneOptions.activeFiles].map(normalizeOutputPathKey));
9018
- for (const [key, remembered] of rememberedCssSources) {
9019
- const outputKey = normalizeOutputPathKey(remembered.outputFile);
9020
- const sourceKey = normalizeOutputPathKey(remembered.sourceFile);
9021
- if (!activeFiles.has(key) && !activeFiles.has(outputKey) && !activeFiles.has(sourceKey)) {
9022
- rememberedCssSources.delete(key);
9023
- rememberedCssSignatureByFile.delete(key);
9024
- }
9025
- }
9026
- if (pruneOptions.activeKnownSfcFiles) {
9027
- const activeKnownSfcFiles = new Set([...pruneOptions.activeKnownSfcFiles].map((file) => normalizeKnownSfcSourceKey(file)).filter((file) => SFC_COMPONENT_FILE_RE.test(file)));
9028
- for (const key of knownSfcSources.keys()) if (!activeKnownSfcFiles.has(key)) knownSfcSources.delete(key);
9029
- }
9030
- pruneMapToMaxSize(rememberedCssSources, VITE_REMEMBERED_CSS_CACHE_MAX, (rememberedKey) => {
9031
- rememberedCssSignatureByFile.delete(String(rememberedKey));
9032
- });
9033
- pruneMapToMaxSize(knownCssSources, VITE_REMEMBERED_CSS_CACHE_MAX);
9034
- pruneMapToMaxSize(knownSfcSources, VITE_KNOWN_SFC_SOURCE_CACHE_MAX);
9035
- };
9036
- return {
9037
- getKnownSfcSource,
9038
- getKnownCssSource,
9039
- getRememberedCssSignature: (file) => rememberedCssSignatureByFile.get(normalizeOutputPathKey(file)),
9040
- getRememberedCssSourceEntry: (file) => rememberedCssSources.get(normalizeOutputPathKey(file)),
9041
- getRememberedCssSources: () => rememberedCssSources,
9042
- getStats: () => ({
9043
- rememberedCssSources: rememberedCssSources.size,
9044
- rememberedCssSourcesRaw: summarizeRememberedCssSources(rememberedCssSources),
9045
- rememberedCssSignatureByFile: rememberedCssSignatureByFile.size,
9046
- knownCssSources: knownCssSources.size,
9047
- knownCssSourcesRaw: summarizeStringMapCache(knownCssSources),
9048
- knownSfcSources: knownSfcSources.size,
9049
- knownSfcSourcesRaw: summarizeStringMapCache(knownSfcSources)
9050
- }),
9051
- rememberCssSource,
9052
- rememberKnownSfcSource,
9053
- refreshRememberedCssSourceByCurrentFile,
9054
- refreshRememberedCssSourceBySourceFile,
9055
- setRememberedCssSignature: (file, cssRuntimeSignature) => {
9056
- rememberedCssSignatureByFile.set(normalizeOutputPathKey(file), cssRuntimeSignature);
9057
- },
9058
- prune
9059
- };
9060
- }
9061
- //#endregion
9062
- //#region src/bundlers/vite/plugin-cache.ts
9063
- function isMissingInternalCssSource(file, packageDir) {
9064
- return !existsSync(file) && path.resolve(file).startsWith(`${packageDir}${path.sep}`);
9065
- }
9066
- function normalizeVitePersistentCacheKey(file) {
9067
- return normalizeOutputPathKey(file);
9068
- }
9069
- function toMb(bytes) {
9070
- return Math.round(bytes / 1024 / 1024);
9071
- }
9072
- function summarizeStringCache(map) {
9073
- let bytes = 0;
9074
- for (const value of map.values()) bytes += value.length;
9075
- return {
9076
- bytes,
9077
- mb: toMb(bytes),
9078
- size: map.size
9079
- };
9080
- }
9081
- function summarizeViteProcessedCssResults(map) {
9082
- let bytes = 0;
9083
- for (const record of map.values()) bytes += record.css.length;
9084
- return {
9085
- bytes,
9086
- mb: toMb(bytes),
9087
- size: map.size
9088
- };
9089
- }
9090
- //#endregion
9091
- //#region src/bundlers/shared/css-imports.ts
9092
- const tailwindcssImportRE = /^(?:tailwindcss|weapp-tailwindcss)(?:\/.*)?$/;
9093
- const tailwindcssCssImportStatementRE = /(@import\s+(?:url\(\s*)?)(["'])((?:tailwindcss|weapp-tailwindcss)(?:\/[^"']*)?\$?)(\2\s*\)?)/gi;
9094
- function normalizeTailwindcssSpecifier(specifier) {
9095
- if (specifier === "tailwindcss$" || specifier === "weapp-tailwindcss$") return specifier.slice(0, -1);
9096
- return specifier;
9097
- }
9098
- function getTailwindcssSubpath(specifier) {
9099
- if (specifier === "tailwindcss" || specifier === "weapp-tailwindcss") return "index.css";
9100
- return specifier.replace(/^(?:tailwindcss|weapp-tailwindcss)\//, "");
9101
- }
9102
- function resolveTailwindcssImport(specifier, pkgDir, options) {
9103
- const normalized = normalizeTailwindcssSpecifier(specifier);
9104
- if (!tailwindcssImportRE.test(normalized)) return null;
9105
- if (normalized === "tailwindcss" || normalized === "weapp-tailwindcss") return options?.rootImport ?? (options?.join ?? path.join)(pkgDir, "index.css");
9106
- return (options?.join ?? path.join)(pkgDir, getTailwindcssSubpath(normalized));
9107
- }
9108
- function rewriteTailwindcssImportsInCode(code, pkgDir, options) {
9109
- let hasReplacements = false;
9110
- const rewritten = code.replace(tailwindcssCssImportStatementRE, (full, prefix, quote, specifier, suffix) => {
9111
- const replacement = resolveTailwindcssImport(specifier, pkgDir, options);
9112
- if (!replacement) return full;
9113
- hasReplacements = true;
9114
- return `${prefix}${quote}${replacement}${suffix}`;
9115
- });
9116
- return hasReplacements ? rewritten : void 0;
9117
- }
9118
- //#endregion
9119
- //#region src/bundlers/vite/rewrite-css-imports.ts
9120
- function joinPosixPath(base, subpath) {
9121
- if (base.endsWith("/")) return `${base}${subpath}`;
9122
- return `${base}/${subpath}`;
9123
- }
9124
- function isCssLikeImporter(importer) {
9125
- if (!importer) return false;
9126
- const normalized = cleanUrl$1(importer);
9127
- return isSourceStyleRequest(importer) || isCSSRequest(normalized) || normalized.endsWith("/*");
9128
- }
9129
- function stripTailwindConfigDirectives(code) {
9130
- return code.replace(/^\s*@config\s+(?:"[^"]+"|'[^']+')[^;\n]*;\s*$/gm, "");
9131
- }
9132
- function createRewriteCssImportsPlugins(options) {
9133
- if (!options.shouldRewrite && !options.shouldOwnTailwindGeneration) return [];
9134
- const { appType, getAppType, rootImport, shouldOwnTailwindGeneration, weappTailwindcssDirPosix } = options;
9135
- const resolveAppType = () => getAppType?.() ?? appType;
9136
- return [{
9137
- name: `${vitePluginName}:rewrite-css-imports`,
9138
- enforce: "pre",
9139
- resolveId(id, importer) {
9140
- if (!options.shouldRewrite) return null;
9141
- const replacement = resolveTailwindcssImport(id, weappTailwindcssDirPosix, {
9142
- join: joinPosixPath,
9143
- appType: resolveAppType(),
9144
- rootImport
9145
- });
9146
- if (!replacement) return null;
9147
- if (importer && !isCssLikeImporter(importer)) return null;
9148
- return replacement;
9149
- },
9150
- async transform(code, id) {
9151
- if (!isCSSRequest(id)) return null;
9152
- const file = cleanUrl$1(id);
9153
- const normalizedCode = !isSfcStyleSourceFile(file) && (hasTailwindRootDirectives(code) || code.includes("@config")) ? normalizeTailwindConfigDirectives(code, path.dirname(file)) : code;
9154
- await options.onCssSourceTransform?.(id, normalizedCode);
9155
- const hasTailwindRoot = hasTailwindRootDirectives(normalizedCode, { importFallback: true });
9156
- if (hasTailwindRoot) await options.onTailwindRootCss?.(id, normalizedCode);
9157
- const shouldGenerateInPreTransform = !options.shouldDeferGeneration?.(id, normalizedCode) && (hasTailwindRoot || options.shouldGenerateCss?.(id, normalizedCode));
9158
- if (options.shouldOwnTailwindGeneration && shouldGenerateInPreTransform) {
9159
- const generatedCss = await options.generateTailwindCss?.(id, normalizedCode, {
9160
- ...this.addWatchFile ? { addWatchFile: this.addWatchFile.bind(this) } : {},
9161
- ...this.emitFile ? { emitFile: this.emitFile.bind(this) } : {},
9162
- cssStage: "raw"
9163
- });
9164
- if (generatedCss !== void 0) return {
9165
- code: generatedCss,
9166
- map: null
9167
- };
9168
- }
9169
- if (!options.shouldRewrite) {
9170
- if (normalizedCode !== code) return {
9171
- code: normalizedCode,
9172
- map: null
9173
- };
9174
- return null;
9175
- }
9176
- const rewritten = rewriteTailwindcssImportsInCode(normalizedCode, weappTailwindcssDirPosix, {
9177
- join: joinPosixPath,
9178
- appType: resolveAppType(),
9179
- rootImport
9180
- });
9181
- const nextCode = shouldOwnTailwindGeneration ? stripTailwindConfigDirectives(rewritten ?? normalizedCode) : rewritten;
9182
- if (!nextCode || nextCode === code) return null;
9183
- return {
9184
- code: nextCode,
9185
- map: null
9186
- };
9187
- }
9188
- }];
9189
- }
9190
- function hasVitePipelineTailwindGenerationDirective(code) {
9191
- return hasTailwindRootDirectives(code) || hasTailwindApplyDirective(code);
9192
- }
9193
- //#endregion
9194
- //#region src/bundlers/vite/runtime-class-set.ts
9195
- function createViteRuntimeClassSet(options) {
9196
- const { opts, initialTailwindRuntime, refreshTailwindcssRuntime, uniAppXEnabled, customAttributesEntities, disabledDefaultTemplateHandler, debug } = options;
9197
- const runtimeState = {
9198
- tailwindRuntime: initialTailwindRuntime,
9199
- readyPromise: createTailwindRuntimeReadyPromise(initialTailwindRuntime),
9200
- refreshTailwindcssRuntime
9201
- };
9202
- const bundleRuntimeClassSetManager = createRuntimeClassSetManager({
9203
- bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues,
9204
- escapeMap: opts.escapeMap
9205
- });
9206
- const transformRuntimeClassSetManager = createRuntimeClassSetManager({
9207
- bareArbitraryValues: opts.arbitraryValues?.bareArbitraryValues,
9208
- escapeMap: opts.escapeMap
9209
- });
9210
- let runtimeSet;
9211
- let runtimeSetPromise;
9212
- let runtimeRefreshSignature;
9213
- let runtimeRefreshOptionsKey;
9214
- function resolveRuntimeRefreshOptions() {
9215
- const configPath = resolveTailwindcssOptions(runtimeState.tailwindRuntime.options)?.config;
9216
- const signature = getRuntimeClassSetSignature(runtimeState.tailwindRuntime);
9217
- const optionsKey = JSON.stringify({
9218
- appType: opts.appType,
9219
- uniAppX: uniAppXEnabled,
9220
- customAttributesEntities,
9221
- disabledDefaultTemplateHandler,
9222
- configPath
9223
- });
9224
- const changed = signature !== runtimeRefreshSignature || optionsKey !== runtimeRefreshOptionsKey;
9225
- runtimeRefreshSignature = signature;
9226
- runtimeRefreshOptionsKey = optionsKey;
9227
- return {
9228
- changed,
9229
- signature,
9230
- optionsKey
9231
- };
9232
- }
9233
- async function refreshRuntimeState(force) {
9234
- const invalidation = resolveRuntimeRefreshOptions();
9235
- const shouldRefresh = force || invalidation.changed;
9236
- const refreshed = await refreshTailwindRuntimeState(runtimeState, {
9237
- force: shouldRefresh,
9238
- clearCache: force || invalidation.changed
9239
- });
9240
- if (invalidation.changed) debug("runtime signature changed, refresh triggered. signature: %s", invalidation.signature);
9241
- if (refreshed) {
9242
- runtimeSet = void 0;
9243
- runtimeSetPromise = void 0;
9244
- }
9245
- }
9246
- async function ensureRuntimeClassSet(force = false) {
9247
- const forceRuntimeRefresh = force || process$1.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
9248
- await refreshRuntimeState(force);
9249
- await runtimeState.readyPromise;
9250
- if (!forceRuntimeRefresh && runtimeSet) return runtimeSet;
9251
- if (forceRuntimeRefresh || !runtimeSetPromise) {
9252
- const invalidation = resolveRuntimeRefreshOptions();
9253
- runtimeSetPromise = collectRuntimeClassSet(runtimeState.tailwindRuntime, {
9254
- force: forceRuntimeRefresh || invalidation.changed,
9255
- skipRefresh: forceRuntimeRefresh,
9256
- clearCache: forceRuntimeRefresh || invalidation.changed
9257
- });
9258
- }
9259
- const task = runtimeSetPromise;
9260
- try {
9261
- runtimeSet = await task;
9262
- return runtimeSet;
9263
- } finally {
9264
- if (runtimeSetPromise === task) runtimeSetPromise = void 0;
9265
- }
9266
- }
9267
- async function ensureBundleRuntimeClassSet(snapshot, forceRefresh = false, options = {}) {
9268
- const forceRuntimeRefresh = forceRefresh || process$1.env["WEAPP_TW_VITE_FORCE_RUNTIME_REFRESH"] === "1";
9269
- const invalidation = resolveRuntimeRefreshOptions();
9270
- const shouldRefreshRuntime = forceRuntimeRefresh || invalidation.changed;
9271
- const forceCollectBySource = snapshot.runtimeAffectingChangedByType.html.size > 0 || snapshot.runtimeAffectingChangedByType.js.size > 0;
9272
- await refreshRuntimeState(shouldRefreshRuntime);
9273
- await runtimeState.readyPromise;
9274
- if (shouldRefreshRuntime) {
9275
- runtimeSet = void 0;
9276
- runtimeSetPromise = void 0;
9277
- await bundleRuntimeClassSetManager.reset();
9278
- await transformRuntimeClassSetManager.reset();
9279
- }
9280
- if (!forceRuntimeRefresh) try {
9281
- const baseClassSet = options.baseClassSet ?? runtimeSet ?? await collectRuntimeClassSet(runtimeState.tailwindRuntime, {
9282
- force: invalidation.changed,
9283
- clearCache: invalidation.changed
9284
- });
9285
- const nextRuntimeSet = await bundleRuntimeClassSetManager.sync(runtimeState.tailwindRuntime, snapshot, {
9286
- baseClassSet,
9287
- skipInitialFullScanWithBase: options.allowBaselineOnlyInitialSync
9288
- });
9289
- runtimeSet = nextRuntimeSet;
9290
- return nextRuntimeSet;
9291
- } catch (error) {
9292
- debug("incremental runtime set sync failed, fallback to full collect: %O", error);
9293
- await bundleRuntimeClassSetManager.reset();
9294
- }
9295
- if (!forceRuntimeRefresh && !invalidation.changed && !forceCollectBySource && runtimeSet) return runtimeSet;
9296
- const task = collectRuntimeClassSet(runtimeState.tailwindRuntime, {
9297
- force: forceRuntimeRefresh || invalidation.changed || forceCollectBySource,
9298
- skipRefresh: forceRuntimeRefresh,
9299
- clearCache: forceRuntimeRefresh || invalidation.changed
9300
- });
9301
- runtimeSetPromise = task;
9302
- try {
9303
- runtimeSet = await task;
9304
- return runtimeSet;
9305
- } finally {
9306
- if (runtimeSetPromise === task) runtimeSetPromise = void 0;
9307
- }
9308
- }
9309
- return {
9310
- runtimeState,
9311
- refreshRuntimeState,
9312
- ensureRuntimeClassSet,
9313
- ensureBundleRuntimeClassSet
9314
- };
9315
- }
9316
- //#endregion
9317
- //#region src/bundlers/vite/serve-css-generation.ts
9318
- const SPECIAL_QUERY_RE$1 = /[?&](?:worker|sharedworker|raw|url)\b/;
9319
- const COMMON_JS_PROXY_RE = /\?commonjs-proxy/;
9320
- const VITE_CSS_HMR_MODULE_RE = /\b__vite__updateStyle\s*\(/;
9321
- const VITE_CSS_CONST_RE = /\bconst\s+__vite__css\s*=\s*("(?:\\[\s\S]|[^"])*")/;
9322
- const DEFERRED_CSS_HMR_QUERY_RE = /[?&](?:hmr(?:[=&]|$)|t=\d+)/;
9323
- function decodeJsStringLiteral(literal) {
9324
- try {
9325
- return JSON.parse(literal);
9326
- } catch {
9327
- return;
9328
- }
9329
- }
9330
- function encodeJsStringLiteral(value) {
9331
- return JSON.stringify(value);
9332
- }
9333
- function extractViteCssHmrModuleCss(code) {
9334
- const match = VITE_CSS_CONST_RE.exec(code);
9335
- if (!match?.[1]) return;
9336
- const css = decodeJsStringLiteral(match[1]);
9337
- if (typeof css !== "string") return;
9338
- return {
9339
- css,
9340
- start: match.index + match[0].lastIndexOf(match[1]),
9341
- end: match.index + match[0].length
9342
- };
9343
- }
9344
- function replaceViteCssHmrModuleCss(code, css) {
9345
- const extracted = extractViteCssHmrModuleCss(code);
9346
- if (!extracted) return;
9347
- return `${code.slice(0, extracted.start)}${encodeJsStringLiteral(css)}${code.slice(extracted.end)}`;
9348
- }
9349
- function isViteServeStyleRequest(id, command) {
9350
- return command === "serve" && isSourceStyleRequest(id) && !SPECIAL_QUERY_RE$1.test(id) && !COMMON_JS_PROXY_RE.test(id);
9351
- }
9352
- function isViteServeCssRootRequest(id, command) {
9353
- return command === "serve" && isSourceStyleRequest(id) && !SPECIAL_QUERY_RE$1.test(id) && !COMMON_JS_PROXY_RE.test(id);
9354
- }
9355
- function isViteBuildStyleRequest(id, command) {
9356
- return command === "build" && isSourceStyleRequest(id) && !SPECIAL_QUERY_RE$1.test(id) && !COMMON_JS_PROXY_RE.test(id);
9357
- }
9358
- function isViteCssHmrModule(code, id, command) {
9359
- return isViteServeStyleRequest(id, command) && VITE_CSS_HMR_MODULE_RE.test(code) && (/[?&](?:direct|vue)(?:&|$)/.test(id) || DEFERRED_CSS_HMR_QUERY_RE.test(id));
9360
- }
9361
- function hasViteCssGenerationDirective(code) {
9362
- return hasTailwindRootDirectives(code) || hasTailwindSourceDirectives(code, { importFallback: true }) || hasTailwindApplyDirective(code);
9363
- }
9364
- function hasViteServeCssRootDirective(code) {
9365
- return hasTailwindRootDirectives(code);
9366
- }
9367
- function createViteCssGenerationPlugins(options) {
9368
- return [
9369
- {
9370
- name: `${vitePluginName}:generate:serve`,
9371
- apply: "serve",
9372
- enforce: "pre",
9373
- async transform(code, id) {
9374
- if (!options.shouldGenerate() || !isViteServeCssRootRequest(id, options.getCommand())) return;
9375
- if (!hasTailwindRootDirectives(code)) return;
9376
- if (DEFERRED_CSS_HMR_QUERY_RE.test(id)) return;
9377
- await options.onTailwindRootCss?.(id, code);
9378
- const generatedCss = await options.generateCss(id, code, {
9379
- ...this.addWatchFile ? { addWatchFile: this.addWatchFile.bind(this) } : {},
9380
- ...this.emitFile ? { emitFile: this.emitFile.bind(this) } : {},
9381
- cssStage: "raw"
6796
+ runtimeState,
6797
+ runtime: generatorRuntime,
6798
+ rawSource: generatorTransformRawSource,
6799
+ file: generatorSourceFile,
6800
+ outputFile: file,
6801
+ cssHandlerOptions: generatorCssHandlerOptions,
6802
+ cssUserHandlerOptions: generatorCssUserHandlerOptions,
6803
+ cssStage: "framework-processed",
6804
+ getSourceCandidatesForEntries,
6805
+ generatorPlatform,
6806
+ styleHandler: opts.styleHandler,
6807
+ debug
6808
+ }) : void 0;
6809
+ if (!generated && !generatorBranch.isWeb && isPureLocalCssImportWrapper(generatorTransformRawSource)) {
6810
+ const nextCss = generatorTransformRawSource;
6811
+ if (nextCss !== rawSource) {
6812
+ writeCssAsset(file, output, nextCss);
6813
+ opts.onUpdate(file, rawSource, nextCss);
6814
+ }
6815
+ markCssAssetProcessed(output, file);
6816
+ recordCssAssetResult?.(file, nextCss);
6817
+ debug("css finalizer preserve mini-program import shell: %s", file);
6818
+ return;
6819
+ }
6820
+ const nextCss = annotateCss(generated?.css ?? (generatorBranch.isWeb ? finalizeWebCssAsset(cleanRawSource, file) : (await opts.styleHandler(generatorTransformRawSource, cssHandlerOptions)).css));
6821
+ if (generated) {
6822
+ registerGeneratorDependencies$1(this, generated.dependencies);
6823
+ debug("css finalizer generated result: %s bytes=%d", file, nextCss.length);
6824
+ recordCssAssetResult?.(file, nextCss);
6825
+ if (cssHandlerOptions.isMainChunk) rememberMainCssSource?.(file, generatorRawSource);
6826
+ }
6827
+ writeCssAsset(file, output, nextCss);
6828
+ markCssAssetProcessed(output, file);
6829
+ opts.onUpdate(file, rawSource, nextCss);
6830
+ debug("css finalizer handle: %s", file);
6831
+ }));
6832
+ const writeStartedAt = performance.now();
6833
+ applyViteAssetEmissionPlan(emissionPlan, {
6834
+ bundle,
6835
+ writeTargets
9382
6836
  });
9383
- if (generatedCss === void 0 || generatedCss === code) return;
9384
- return {
9385
- code: generatedCss,
9386
- map: null
9387
- };
9388
- }
9389
- },
9390
- {
9391
- name: `${vitePluginName}:generate:build`,
9392
- apply: "build",
9393
- enforce: "pre",
9394
- async transform(code, id) {
9395
- if (!options.shouldGenerate() || options.shouldGenerateBuild?.() === false || !isViteBuildStyleRequest(id, options.getCommand())) return;
9396
- if (!hasViteCssGenerationDirective(code)) return;
9397
- if (options.shouldDeferGeneration?.(id, code)) return;
9398
- if (hasViteServeCssRootDirective(code)) await options.onTailwindRootCss?.(id, code);
9399
- const generatedCss = await options.generateCss(id, code, {
9400
- ...this.addWatchFile ? { addWatchFile: this.addWatchFile.bind(this) } : {},
9401
- ...this.emitFile ? { emitFile: this.emitFile.bind(this) } : {},
9402
- cssStage: "raw"
6837
+ await injectHarmonyBundleStyles();
6838
+ collectViteProcessedCssAssets();
6839
+ injectViteProcessedCssIntoMainCss();
6840
+ normalizeRootMiniProgramImportShellAssets(bundle, {
6841
+ cssMatcher: opts.cssMatcher,
6842
+ debug,
6843
+ enabled: cssPipelineStrategy?.shouldNormalizeRootMiniProgramImportShell?.(createCssPipelineContext("")) === true,
6844
+ onUpdate: trackFinalCssAssetUpdate,
6845
+ recordCssAssetResult
9403
6846
  });
9404
- if (generatedCss === void 0 || generatedCss === code) return;
9405
- return {
9406
- code: generatedCss,
9407
- map: null
9408
- };
9409
- }
9410
- },
9411
- {
9412
- name: `${vitePluginName}:generate:serve-hmr`,
9413
- apply: "serve",
9414
- enforce: "post",
9415
- async transform(code, id) {
9416
- if (!options.shouldGenerate() || !isViteCssHmrModule(code, id, options.getCommand())) return;
9417
- const extracted = extractViteCssHmrModuleCss(code);
9418
- if (!extracted) return;
9419
- if (!hasViteCssGenerationDirective(extracted.css)) return;
9420
- if (hasViteServeCssRootDirective(extracted.css)) await options.onTailwindRootCss?.(id, extracted.css);
9421
- const generatedCss = await options.generateCss(id, extracted.css, {
9422
- ...this.addWatchFile ? { addWatchFile: this.addWatchFile.bind(this) } : {},
9423
- ...this.emitFile ? { emitFile: this.emitFile.bind(this) } : {},
9424
- cssStage: "framework-processed"
6847
+ finalizeMiniProgramCssAssetStructures(bundle, {
6848
+ cssMatcher: opts.cssMatcher,
6849
+ debug,
6850
+ files: finalCssAssetFiles,
6851
+ isWebGeneratorTarget,
6852
+ onUpdate: opts.onUpdate,
6853
+ recordCssAssetResult
9425
6854
  });
9426
- if (generatedCss === void 0 || generatedCss === extracted.css) return;
9427
- const nextCode = replaceViteCssHmrModuleCss(code, generatedCss);
9428
- if (nextCode === void 0 || nextCode === code) return;
9429
- return {
9430
- code: nextCode,
9431
- map: null
9432
- };
6855
+ finalizeCompilerShadowRun(runtimeState);
6856
+ recordTiming("assets.write", writeStartedAt);
6857
+ finishTiming();
9433
6858
  }
9434
6859
  }
9435
- ];
6860
+ };
9436
6861
  }
9437
6862
  //#endregion
9438
6863
  //#region src/bundlers/vite/serve-js-transform.ts
@@ -9586,225 +7011,6 @@ function createConfiguredCssEntryDiagnostics(options) {
9586
7011
  };
9587
7012
  }
9588
7013
  //#endregion
9589
- //#region src/bundlers/vite/shared/framework-css-generation-queue.ts
9590
- function createFrameworkCssGenerationQueue(normalizeId, generate) {
9591
- const pendingByFile = /* @__PURE__ */ new Map();
9592
- return (id, ...args) => {
9593
- const fileKey = normalizeId(id);
9594
- const task = (pendingByFile.get(fileKey) ?? Promise.resolve()).then(() => generate(id, ...args));
9595
- const tail = task.then(() => void 0, () => void 0);
9596
- pendingByFile.set(fileKey, tail);
9597
- tail.then(() => {
9598
- if (pendingByFile.get(fileKey) === tail) pendingByFile.delete(fileKey);
9599
- });
9600
- return task;
9601
- };
9602
- }
9603
- //#endregion
9604
- //#region src/bundlers/vite/shared/framework-hmr-candidate-state.ts
9605
- function createViteHmrCandidateState(options) {
9606
- let pendingChange;
9607
- let pendingCssTargetFiles;
9608
- let pendingTargetsArmed = false;
9609
- let pendingFullRegeneration = false;
9610
- const normalizeCssTargetFile = (file) => normalizeVitePersistentCacheKey(cleanUrl$1(file));
9611
- const clear = () => {
9612
- pendingChange = void 0;
9613
- pendingCssTargetFiles = void 0;
9614
- pendingTargetsArmed = false;
9615
- pendingFullRegeneration = false;
9616
- };
9617
- const queueFullRegeneration = () => {
9618
- pendingChange = void 0;
9619
- pendingCssTargetFiles = void 0;
9620
- pendingTargetsArmed = false;
9621
- pendingFullRegeneration = true;
9622
- };
9623
- const queueChange = (change) => {
9624
- var _pendingChange;
9625
- if (pendingFullRegeneration) return;
9626
- pendingFullRegeneration = false;
9627
- if (!pendingChange) {
9628
- pendingChange = {
9629
- file: change.file,
9630
- runtimeAffecting: change.runtimeAffecting,
9631
- addedCandidates: new Set(change.addedCandidates),
9632
- removedCandidates: new Set(change.removedCandidates)
9633
- };
9634
- return;
9635
- }
9636
- for (const candidate of change.addedCandidates) {
9637
- pendingChange.addedCandidates.add(candidate);
9638
- pendingChange.removedCandidates.delete(candidate);
9639
- }
9640
- for (const candidate of change.removedCandidates) if (!pendingChange.addedCandidates.delete(candidate)) pendingChange.removedCandidates.add(candidate);
9641
- (_pendingChange = pendingChange).runtimeAffecting || (_pendingChange.runtimeAffecting = change.runtimeAffecting);
9642
- pendingChange.file = change.file;
9643
- };
9644
- const createChange = (file, change, changeOptions = {}) => ({
9645
- ...change,
9646
- file,
9647
- runtimeAffecting: changeOptions.runtimeAffecting === true || options.isRuntimeAffectingSource?.(file) === true || isSourceStyleRequest(file)
9648
- });
9649
- const apply = (change) => {
9650
- if (isSourceStyleRequest(change.file)) {
9651
- clear();
9652
- return change;
9653
- }
9654
- if (change.runtimeAffecting) {
9655
- queueFullRegeneration();
9656
- return change;
9657
- }
9658
- const preserveDeletedCss = options.getGeneratorOptions().hmr.preserveDeletedCss;
9659
- if (preserveDeletedCss) {
9660
- if (change.addedCandidates.size > 0) queueChange(change);
9661
- else if (!pendingChange && !pendingFullRegeneration) clear();
9662
- return change;
9663
- }
9664
- clear();
9665
- if (!preserveDeletedCss) queueFullRegeneration();
9666
- return change;
9667
- };
9668
- const resolve = (generatorCode, file) => {
9669
- const fileKey = normalizeCssTargetFile(file);
9670
- if (options.getCommand() !== "serve" || !pendingChange || pendingChange.runtimeAffecting || pendingChange.addedCandidates.size === 0 || options.getGeneratorOptions().target === "weapp" && hasUserCssLayerBlocks(generatorCode) || !options.cleanGeneratedCssByFile.has(fileKey) || !options.generatedClassSetByFile.has(fileKey) || pendingTargetsArmed && !pendingCssTargetFiles?.has(fileKey)) return;
9671
- return pendingChange;
9672
- };
9673
- const finishTarget = (file) => {
9674
- if (!pendingChange && !pendingFullRegeneration) return;
9675
- if (!pendingTargetsArmed || !pendingCssTargetFiles) return;
9676
- pendingCssTargetFiles.delete(normalizeCssTargetFile(file));
9677
- if (pendingCssTargetFiles.size === 0) clear();
9678
- };
9679
- const armTargets = (cssModules, fallbackCssIds) => {
9680
- if (!pendingChange && !pendingFullRegeneration) {
9681
- pendingCssTargetFiles = void 0;
9682
- pendingTargetsArmed = false;
9683
- return;
9684
- }
9685
- const targets = /* @__PURE__ */ new Set();
9686
- const addTarget = (file) => {
9687
- if (!file) return;
9688
- const key = normalizeCssTargetFile(file);
9689
- if (pendingFullRegeneration || options.cleanGeneratedCssByFile.has(key)) targets.add(key);
9690
- };
9691
- for (const module of cssModules) {
9692
- addTarget(module.id);
9693
- addTarget(module.file);
9694
- addTarget(module.url);
9695
- }
9696
- for (const id of fallbackCssIds) addTarget(id);
9697
- pendingCssTargetFiles = targets;
9698
- pendingTargetsArmed = true;
9699
- };
9700
- const reconcileRuntimeCandidates = (file, candidates, rootCssIds) => {
9701
- if (options.getCommand() !== "serve" || pendingFullRegeneration) return;
9702
- const generatedClassSets = [];
9703
- const seenFiles = /* @__PURE__ */ new Set();
9704
- for (const id of rootCssIds) {
9705
- const fileKey = normalizeCssTargetFile(id);
9706
- if (seenFiles.has(fileKey)) continue;
9707
- seenFiles.add(fileKey);
9708
- const classSet = options.generatedClassSetByFile.get(fileKey);
9709
- if (classSet) generatedClassSets.push(classSet);
9710
- }
9711
- if (generatedClassSets.length === 0) return;
9712
- const addedCandidates = /* @__PURE__ */ new Set();
9713
- for (const candidate of candidates) if (generatedClassSets.some((classSet) => !classSet.has(candidate))) addedCandidates.add(candidate);
9714
- if (addedCandidates.size === 0) return;
9715
- apply(createChange(file, {
9716
- addedCandidates,
9717
- removedCandidates: /* @__PURE__ */ new Set()
9718
- }));
9719
- };
9720
- return {
9721
- apply,
9722
- armTargets,
9723
- clear,
9724
- createChange,
9725
- finishTarget,
9726
- hasPendingCandidateAppend: () => pendingChange != null && !pendingChange.runtimeAffecting && pendingChange.addedCandidates.size > 0,
9727
- hasPendingChange: () => pendingChange != null || pendingFullRegeneration,
9728
- queueFullRegeneration,
9729
- reconcileRuntimeCandidates,
9730
- resolve,
9731
- shouldForceFullRegeneration: (file, resolved) => {
9732
- if (options.getCommand() !== "serve") return false;
9733
- if (pendingFullRegeneration) return pendingTargetsArmed && pendingCssTargetFiles?.has(normalizeCssTargetFile(file)) === true;
9734
- return pendingChange != null && !resolved && pendingTargetsArmed && pendingCssTargetFiles?.has(normalizeCssTargetFile(file)) === true;
9735
- },
9736
- snapshotDebugState: () => ({
9737
- pendingAddedCandidates: pendingChange?.addedCandidates.size ?? 0,
9738
- pendingCssTargets: pendingCssTargetFiles?.size ?? 0,
9739
- pendingFullRegeneration
9740
- })
9741
- };
9742
- }
9743
- //#endregion
9744
- //#region src/bundlers/vite/shared/framework-hmr-module-version.ts
9745
- function acceptVersion(versions, keys, timestamp) {
9746
- if (keys.some((key) => (versions.get(key) ?? 0) > timestamp)) return false;
9747
- for (const key of keys) versions.set(key, Math.max(versions.get(key) ?? 0, timestamp));
9748
- return true;
9749
- }
9750
- function createViteHmrCssModuleVersionTracker() {
9751
- const versions = /* @__PURE__ */ new Map();
9752
- const keysForId = (id, root) => [resolveViteModuleIdentity(id, root).key];
9753
- const keysForModule = (mod, root) => [...new Set([
9754
- mod.id,
9755
- mod.url,
9756
- mod.file
9757
- ].filter((id) => typeof id === "string" && id.length > 0).flatMap((id) => keysForId(id, root)))];
9758
- return {
9759
- clear() {
9760
- versions.clear();
9761
- },
9762
- filterIds(ids, timestamp, root) {
9763
- return [...ids].filter((id) => acceptVersion(versions, keysForId(id, root), timestamp));
9764
- },
9765
- filterModules(modules, timestamp, root) {
9766
- return modules.filter((mod) => {
9767
- const keys = keysForModule(mod, root);
9768
- return keys.length === 0 || acceptVersion(versions, keys, timestamp);
9769
- });
9770
- },
9771
- reserveRefreshTimestamp(modules, timestamp, root) {
9772
- const moduleKeys = modules.flatMap((mod) => keysForModule(mod, root));
9773
- const latestTimestamp = moduleKeys.reduce((latest, key) => Math.max(latest, versions.get(key) ?? 0), 0);
9774
- const refreshTimestamp = Math.max(Date.now(), timestamp + 1, latestTimestamp + 1);
9775
- for (const key of moduleKeys) versions.set(key, refreshTimestamp);
9776
- return refreshTimestamp;
9777
- }
9778
- };
9779
- }
9780
- function createViteHmrCssModuleVersionFilterPlugin(tracker) {
9781
- return {
9782
- name: "weapp-tailwindcss:hmr-css-module-version",
9783
- enforce: "post",
9784
- handleHotUpdate: {
9785
- order: "post",
9786
- handler(ctx) {
9787
- const styleModules = ctx.modules.filter((mod) => {
9788
- const request = mod.id ?? mod.url;
9789
- return isSourceStyleRequest(request);
9790
- });
9791
- if (styleModules.length === 0) return;
9792
- const root = ctx.server.config?.root ?? process$1.cwd();
9793
- const currentStyleModules = tracker.filterModules(styleModules, ctx.timestamp, root);
9794
- if (currentStyleModules.length === styleModules.length) return;
9795
- const droppedStyleModules = styleModules.filter((mod) => !currentStyleModules.includes(mod));
9796
- for (const mod of droppedStyleModules) ctx.server.moduleGraph.invalidateModule(mod);
9797
- const refreshTimestamp = tracker.reserveRefreshTimestamp(droppedStyleModules, ctx.timestamp, root);
9798
- sendSupplementalCssHotUpdates({
9799
- ...ctx,
9800
- timestamp: refreshTimestamp
9801
- }, droppedStyleModules, [], [], []);
9802
- return [...ctx.modules.filter((mod) => !styleModules.includes(mod)), ...currentStyleModules];
9803
- }
9804
- }
9805
- };
9806
- }
9807
- //#endregion
9808
7014
  //#region src/bundlers/vite/shared/framework-module-candidates.ts
9809
7015
  function createFrameworkModuleCandidateRegistrar(options) {
9810
7016
  return async (id, source) => {
@@ -9844,207 +7050,6 @@ function orderFrameworkSourceCandidatePlugins(extraPlugins, rewritePlugins, sour
9844
7050
  ];
9845
7051
  }
9846
7052
  //#endregion
9847
- //#region src/bundlers/vite/official-tailwind-plugins.ts
9848
- function isTailwindVitePlugin(plugin) {
9849
- if (!plugin || typeof plugin !== "object" || !("name" in plugin)) return false;
9850
- const { name } = plugin;
9851
- return typeof name === "string" && name.startsWith("@tailwindcss/vite");
9852
- }
9853
- function removeTailwindVitePlugins(plugins) {
9854
- let removed = 0;
9855
- for (let i = plugins.length - 1; i >= 0; i--) if (isTailwindVitePlugin(plugins[i])) {
9856
- plugins.splice(i, 1);
9857
- removed++;
9858
- }
9859
- return removed;
9860
- }
9861
- function disableTailwindVitePlugin(plugin) {
9862
- if (!isTailwindVitePlugin(plugin)) return false;
9863
- const mutablePlugin = plugin;
9864
- for (const hook of [
9865
- "configResolved",
9866
- "configureServer",
9867
- "transform",
9868
- "hotUpdate",
9869
- "handleHotUpdate"
9870
- ]) delete mutablePlugin[hook];
9871
- return true;
9872
- }
9873
- function disableAndRemoveTailwindVitePlugins(plugins) {
9874
- let removed = 0;
9875
- for (let i = plugins.length - 1; i >= 0; i--) {
9876
- const plugin = plugins[i];
9877
- if (Array.isArray(plugin)) {
9878
- removed += disableAndRemoveTailwindVitePlugins(plugin);
9879
- if (plugin.length === 0) plugins.splice(i, 1);
9880
- continue;
9881
- }
9882
- if (disableTailwindVitePlugin(plugin)) {
9883
- plugins.splice(i, 1);
9884
- removed++;
9885
- }
9886
- }
9887
- return removed;
9888
- }
9889
- //#endregion
9890
- //#region src/bundlers/vite/tailwind-basedir.ts
9891
- const PACKAGE_JSON_FILE = "package.json";
9892
- function resolveImplicitTailwindcssBasedirFromViteRoot(root) {
9893
- const resolvedRoot = path.resolve(root);
9894
- if (!existsSync(resolvedRoot)) return resolvedRoot;
9895
- const searchRoots = [];
9896
- let current = resolvedRoot;
9897
- while (true) {
9898
- searchRoots.push(current);
9899
- const parent = path.dirname(current);
9900
- if (parent === current) break;
9901
- current = parent;
9902
- }
9903
- const tailwindConfigPath = findTailwindConfig(searchRoots);
9904
- if (tailwindConfigPath) return path.dirname(tailwindConfigPath);
9905
- const packageRoot = findNearestPackageRoot(resolvedRoot);
9906
- if (packageRoot && existsSync(path.join(packageRoot, PACKAGE_JSON_FILE))) return packageRoot;
9907
- return resolvedRoot;
9908
- }
9909
- //#endregion
9910
- //#region src/bundlers/vite/shared/framework-post-plugin.ts
9911
- function createFrameworkPostPlugin(options) {
9912
- const plugin = {
9913
- name: `${vitePluginName}:post`,
9914
- enforce: "post",
9915
- config(config) {
9916
- if (!options.shouldOwnTailwindGeneration) return;
9917
- if (Array.isArray(config.plugins)) {
9918
- const removed = disableAndRemoveTailwindVitePlugins(config.plugins);
9919
- if (removed > 0) {
9920
- logger.warn("检测到 @tailwindcss/vite,生成模式下已移除该插件以避免 Tailwind CSS 重复生成。");
9921
- options.debug("disable official tailwind vite plugins in generator mode: %d", removed);
9922
- }
9923
- }
9924
- const root = config.root ? path.resolve(config.root) : process$1.cwd();
9925
- const baseConfig = { resolve: { alias: [{
9926
- find: /^tailwindcss$/,
9927
- replacement: options.generatorPlaceholderCssFile
9928
- }] } };
9929
- if (config.css?.postcss !== void 0) return baseConfig;
9930
- return resolvePostcssConfig(root).then((postcssConfig) => {
9931
- if (!postcssConfig) return baseConfig;
9932
- const plugins = [...postcssConfig.plugins];
9933
- const removed = removeTailwindPostcssPlugins(plugins);
9934
- if (removed > 0) options.debug("inline filtered postcss config without official tailwind plugins in generator mode: %d", removed);
9935
- return {
9936
- ...baseConfig,
9937
- css: { postcss: {
9938
- ...postcssConfig.options,
9939
- plugins
9940
- } }
9941
- };
9942
- });
9943
- },
9944
- async configResolved(config) {
9945
- await options.hmrTimingRecorder.measure("configResolved", async () => {
9946
- options.setResolvedConfig(config);
9947
- if (options.shouldOwnTailwindGeneration) {
9948
- const removed = Array.isArray(config.plugins) ? removeTailwindVitePlugins(config.plugins) : 0;
9949
- if (removed > 0) options.debug("remove official tailwind vite plugins in generator mode: %d", removed);
9950
- }
9951
- const resolvedRoot = config.root ? path.resolve(config.root) : void 0;
9952
- let shouldRefreshRuntime = false;
9953
- if (!options.hasExplicitTailwindcssBasedir && resolvedRoot) {
9954
- const nextTailwindcssBasedir = resolveImplicitTailwindcssBasedirFromViteRoot(resolvedRoot);
9955
- if (options.opts.tailwindcssBasedir !== nextTailwindcssBasedir) {
9956
- const previousBasedir = options.opts.tailwindcssBasedir;
9957
- options.opts.tailwindcssBasedir = nextTailwindcssBasedir;
9958
- shouldRefreshRuntime = options.syncCssEntriesFromAnchor(nextTailwindcssBasedir) || shouldRefreshRuntime;
9959
- options.debug("align tailwindcss basedir with vite root: %s -> %s", previousBasedir ?? "undefined", nextTailwindcssBasedir);
9960
- shouldRefreshRuntime = true;
9961
- }
9962
- }
9963
- if (options.shouldInferAppType && resolvedRoot) {
9964
- const nextAppType = resolveImplicitAppTypeFromViteRoot(resolvedRoot, { searchUp: false });
9965
- if (nextAppType && options.opts.appType !== nextAppType) {
9966
- const previousAppType = options.opts.appType;
9967
- options.opts.appType = nextAppType;
9968
- logger.debug("根据 Vite 项目根目录自动推断 appType -> %s", nextAppType);
9969
- options.debug("align appType with vite root: %s -> %s", previousAppType ?? "undefined", nextAppType);
9970
- shouldRefreshRuntime = true;
9971
- }
9972
- }
9973
- if (options.frameworkName === "generic" && !options.hasExplicitGeneratorTarget && options.opts.generator !== false && options.opts.appType === void 0 && options.opts.platform === void 0 && options.opts.cssOptions?.platform === void 0 && !options.resolveViteStylePlatform()) {
9974
- const generator = options.opts.generator && typeof options.opts.generator === "object" ? options.opts.generator : {};
9975
- options.opts.generator = {
9976
- ...generator,
9977
- target: "web"
9978
- };
9979
- logger.debug("Generic Vite 项目未指定目标,自动使用 generator.target -> web");
9980
- options.debug("default generic vite generator target to web after configResolved");
9981
- shouldRefreshRuntime = true;
9982
- }
9983
- if (shouldRefreshRuntime) await options.refreshRuntimeState(true);
9984
- if (typeof config.css.postcss === "object" && Array.isArray(config.css.postcss.plugins)) {
9985
- const postcssPlugins = config.css.postcss.plugins;
9986
- if (options.shouldOwnTailwindGeneration) {
9987
- const removed = removeTailwindPostcssPlugins(postcssPlugins);
9988
- if (removed > 0) {
9989
- logger.warn("检测到 @tailwindcss/postcss,生成模式下已移除该插件以避免 Tailwind CSS 重复生成。");
9990
- options.debug("remove official tailwind postcss plugins in generator mode: %d", removed);
9991
- }
9992
- }
9993
- }
9994
- captureFrameworkPostcssOptions(options.opts, config.css?.postcss && typeof config.css.postcss === "object" ? config.css.postcss : void 0);
9995
- }, { emit: false });
9996
- },
9997
- generateBundle: {
9998
- order: "post",
9999
- handler: options.generateBundleHook
10000
- }
10001
- };
10002
- if (options.api) plugin.api = options.api;
10003
- return plugin;
10004
- }
10005
- //#endregion
10006
- //#region src/bundlers/vite/shared/framework-processed-css-registry.ts
10007
- function createFrameworkProcessedCssRegistry() {
10008
- const results = /* @__PURE__ */ new Map();
10009
- const sourceFiles = /* @__PURE__ */ new Set();
10010
- const markSource = (file) => {
10011
- sourceFiles.add(path.resolve(cleanUrl$1(file)));
10012
- };
10013
- const record = (file, css, options = {}) => {
10014
- const key = normalizeVitePersistentCacheKey(file);
10015
- const previous = results.get(key);
10016
- const injectIntoMain = previous?.injectIntoMain === true ? true : options.injectIntoMain ?? previous?.injectIntoMain;
10017
- touchMapEntry(results, key, {
10018
- css,
10019
- injectIntoMain,
10020
- outputFile: options.outputFile ?? previous?.outputFile
10021
- });
10022
- };
10023
- const get = (file) => results.get(normalizeVitePersistentCacheKey(file));
10024
- const matchesIdentity = (candidate) => {
10025
- return sourceFiles.has(path.resolve(cleanUrl$1(candidate)));
10026
- };
10027
- const prune = (activeFiles) => {
10028
- for (const [key, result] of results) {
10029
- const outputKey = result.outputFile ? normalizeVitePersistentCacheKey(result.outputFile) : void 0;
10030
- if (!activeFiles.has(key) && (outputKey == null || !activeFiles.has(outputKey))) results.delete(key);
10031
- }
10032
- };
10033
- return {
10034
- entries: () => results.entries(),
10035
- get,
10036
- getStats: () => ({
10037
- viteProcessedCssAssetResults: results.size,
10038
- viteProcessedCssAssetResultsRaw: summarizeViteProcessedCssResults(results)
10039
- }),
10040
- markSource,
10041
- matchesIdentity,
10042
- prune,
10043
- record,
10044
- sourceFiles
10045
- };
10046
- }
10047
- //#endregion
10048
7053
  //#region src/bundlers/vite/shared/framework-runtime-options.ts
10049
7054
  function sameStringList(first, second) {
10050
7055
  if (first === second) return true;
@@ -10091,7 +7096,7 @@ function createFrameworkSourceCandidatesPlugin(options, apply) {
10091
7096
  return typeof request === "string" && /\.(?:uvue|nvue)(?:\?import)?$/i.test(request);
10092
7097
  });
10093
7098
  const sendSupplementalSourceHotUpdates = (ctx, modules) => {
10094
- const root = ctx.server.config?.root ?? process$1.cwd();
7099
+ const root = ctx.server.config?.root ?? process.cwd();
10095
7100
  const updates = modules.flatMap((mod) => [mod, ...mod.importedModules ?? []]).filter((mod) => !isSourceStyleRequest(mod.id ?? mod.url)).map((mod) => {
10096
7101
  let hotPath;
10097
7102
  if (typeof mod.id === "string" && path.isAbsolute(mod.id)) {
@@ -10245,7 +7250,7 @@ function createFrameworkSourceCandidatesPlugin(options, apply) {
10245
7250
  if (isSourceCandidateHotUpdate) await options.sourceScanSession.waitForPendingSyncs();
10246
7251
  if (isSourceCandidateHotUpdate && !isSourceStyleRequest(ctx.file)) options.hmrCandidateState.reconcileRuntimeCandidates(ctx.file, options.sourceCandidateCollector.values(), options.tailwindRootCssModuleIds);
10247
7252
  const hotTailwindCssModuleIds = isSourceStyleRequest(ctx.file) ? [ctx.file] : options.tailwindRootCssModuleIds;
10248
- const hotRoot = ctx.server.config?.root ?? process$1.cwd();
7253
+ const hotRoot = ctx.server.config?.root ?? process.cwd();
10249
7254
  const cssModules = await resolveHotTailwindCssModules(ctx, hotTailwindCssModuleIds, options.hmrCssModuleVersions ? (modules) => options.hmrCssModuleVersions.filterModules(modules, ctx.timestamp, hotRoot) : void 0);
10250
7255
  const sourceModules = isSourceCandidateHotUpdate && !isSourceStyleRequest(ctx.file) ? await resolveHotSourceModules(ctx) : ctx.modules;
10251
7256
  if (isWebLikeHotUpdate && isSourceCandidateHotUpdate && !isSourceStyleRequest(ctx.file)) {
@@ -10296,348 +7301,6 @@ function createFrameworkSourceCandidatesPlugin(options, apply) {
10296
7301
  };
10297
7302
  }
10298
7303
  //#endregion
10299
- //#region src/bundlers/vite/shared/framework-hmr-runtime-signature.ts
10300
- const WEB_HMR_RUNTIME_AFFECTING_DIRECTIVE_RE = /@(?:theme|source|config|plugin|apply)\b/;
10301
- function createFrameworkHmrRuntimeSignature(file, source) {
10302
- if (!source || !WEB_HMR_RUNTIME_AFFECTING_DIRECTIVE_RE.test(source)) return "";
10303
- return (isSfcStyleSourceFile(cleanUrl$1(file)) ? extractSfcStyleSources(source).filter((styleSource) => WEB_HMR_RUNTIME_AFFECTING_DIRECTIVE_RE.test(styleSource)) : [source]).map((styleSource) => createRuntimeAffectingSourceSignature(styleSource, "css")).join("\0");
10304
- }
10305
- function hasFrameworkHmrRuntimeSourceChange(file, previousSource, nextSource) {
10306
- return createFrameworkHmrRuntimeSignature(file, previousSource) !== createFrameworkHmrRuntimeSignature(file, nextSource);
10307
- }
10308
- //#endregion
10309
- //#region src/bundlers/vite/shared/framework-source-scan-session.ts
10310
- const SOURCE_CANDIDATE_SCAN_CACHE_MAX = 8;
10311
- const sourceCandidateScanSnapshotCache = new LRUCache({ max: SOURCE_CANDIDATE_SCAN_CACHE_MAX });
10312
- async function syncFrameworkSourceCandidatesForHotUpdate(sourceScanSession, ctx) {
10313
- const source = typeof ctx.read === "function" ? await ctx.read().catch(() => void 0) : void 0;
10314
- await sourceScanSession.syncChangedFile(ctx.file, source);
10315
- await sourceScanSession.waitForPendingSyncs();
10316
- }
10317
- function createFrameworkSourceScanSession(options) {
10318
- const sourceCandidateScanCache = new LRUCache({ max: SOURCE_CANDIDATE_SCAN_CACHE_MAX });
10319
- let sourceScanEntries;
10320
- let sourceScanMatcher;
10321
- let sourceScanBoundaryMatcher;
10322
- let sourceScanRoots = [];
10323
- let sourceScanOutDir;
10324
- let sourceScanEligibleFiles = /* @__PURE__ */ new Set();
10325
- let sourceScanEligibleFilesRefresh;
10326
- const sourceScanIneligibleFiles = /* @__PURE__ */ new Set();
10327
- let sourceScanDependencies = /* @__PURE__ */ new Set();
10328
- let sourceScanExplicit = false;
10329
- let sourceCandidateScanSignature;
10330
- let sourceCandidateScanInvalidated = true;
10331
- const pendingSourceCandidateSyncs = /* @__PURE__ */ new Set();
10332
- const pendingSourceCandidateSyncByFile = /* @__PURE__ */ new Map();
10333
- const pendingHotUpdateChangeByFile = /* @__PURE__ */ new Map();
10334
- const pendingChangedFiles = /* @__PURE__ */ new Map();
10335
- let pendingChangedFilesFlush;
10336
- let isFlushingChangedFiles = false;
10337
- let cacheDirty = false;
10338
- let cachedCollectorRevision;
10339
- const normalizeDependency = (file) => path.normalize(path.resolve(cleanUrl$1(file)));
10340
- const isDependency = (file) => sourceScanDependencies.has(normalizeDependency(file));
10341
- const invalidate = () => {
10342
- sourceCandidateScanInvalidated = true;
10343
- sourceScanIneligibleFiles.clear();
10344
- };
10345
- const hasState = () => sourceCandidateScanSignature !== void 0;
10346
- const collectRoots = (root, entries) => {
10347
- if (entries?.length) return [{
10348
- entries,
10349
- explicit: sourceScanExplicit,
10350
- root
10351
- }];
10352
- if (sourceScanExplicit && entries !== void 0) return [];
10353
- const roots = [{
10354
- entries,
10355
- root
10356
- }];
10357
- const seenRoots = /* @__PURE__ */ new Set([path.resolve(root)]);
10358
- const basedir = options.opts.tailwindcssBasedir ? path.resolve(options.opts.tailwindcssBasedir) : void 0;
10359
- if (basedir && !seenRoots.has(basedir)) {
10360
- roots.push({ root: basedir });
10361
- seenRoots.add(basedir);
10362
- }
10363
- for (const cssEntry of options.opts.tailwindcss?.v4?.cssEntries ?? []) {
10364
- if (!isTailwindV4CssEntry(cssEntry)) continue;
10365
- const cssEntryRoot = path.dirname(path.resolve(cssEntry));
10366
- if (seenRoots.has(cssEntryRoot)) continue;
10367
- roots.push({ root: cssEntryRoot });
10368
- seenRoots.add(cssEntryRoot);
10369
- }
10370
- return roots;
10371
- };
10372
- const cacheCurrent = () => {
10373
- if (!sourceCandidateScanSignature) return;
10374
- if (isFlushingChangedFiles) {
10375
- cacheDirty = true;
10376
- return;
10377
- }
10378
- const collectorRevision = options.sourceCandidateCollector.getRevision?.();
10379
- if (!cacheDirty && cachedCollectorRevision !== void 0 && collectorRevision === cachedCollectorRevision) return;
10380
- const entry = {
10381
- eligibleFiles: [...sourceScanEligibleFiles],
10382
- snapshot: options.sourceCandidateCollector.snapshot()
10383
- };
10384
- sourceCandidateScanCache.set(sourceCandidateScanSignature, entry);
10385
- sourceCandidateScanSnapshotCache.set(sourceCandidateScanSignature, entry);
10386
- cachedCollectorRevision = collectorRevision;
10387
- cacheDirty = false;
10388
- };
10389
- const updateSourceScanMatchers = (eligibleFiles) => {
10390
- sourceScanEligibleFiles = new Set(eligibleFiles);
10391
- const matcherRoots = sourceScanRoots.map((scanRoot) => ({
10392
- ...scanRoot,
10393
- outDir: sourceScanOutDir
10394
- }));
10395
- sourceScanBoundaryMatcher = createSourceCandidateEligibilityMatcher(matcherRoots);
10396
- sourceScanMatcher = createSourceCandidateEligibilityMatcher(matcherRoots, sourceScanEligibleFiles);
10397
- };
10398
- const refreshSourceScanEligibleFiles = async () => {
10399
- sourceScanEligibleFilesRefresh ?? (sourceScanEligibleFilesRefresh = Promise.all(sourceScanRoots.map((scanRoot) => options.sourceCandidateCollector.resolveScanFiles({
10400
- entries: scanRoot.entries,
10401
- explicit: scanRoot.explicit,
10402
- root: scanRoot.root,
10403
- outDir: sourceScanOutDir
10404
- }))).then((files) => updateSourceScanMatchers(files.flat())).finally(() => {
10405
- sourceScanEligibleFilesRefresh = void 0;
10406
- }));
10407
- await sourceScanEligibleFilesRefresh;
10408
- };
10409
- const shouldDiscoverAutoCssSources = (autoCssSourcesDiscovered) => {
10410
- if (!autoCssSourcesDiscovered || !options.isWatchLikeBuild()) return true;
10411
- return sourceCandidateScanInvalidated;
10412
- };
10413
- const sync = async (syncOptions = {}) => {
10414
- if (!options.shouldOwnTailwindGeneration) return;
10415
- if (!syncOptions.force && options.isWatchLikeBuild() && hasState() && !sourceCandidateScanInvalidated) {
10416
- options.debug("reuse vite source candidate scan definition for watch rebuild");
10417
- return;
10418
- }
10419
- const resolvedConfig = options.getResolvedConfig();
10420
- const root = resolvedConfig?.root ?? process$1.cwd();
10421
- const outDir = resolvedConfig?.build?.outDir;
10422
- const sourceScan = await resolveSourceScanEntries(options.opts, options.runtimeState.tailwindRuntime, {
10423
- outDir,
10424
- root
10425
- });
10426
- sourceScanEntries = sourceScan?.entries;
10427
- sourceScanExplicit = sourceScan?.explicit ?? false;
10428
- sourceScanDependencies = new Set((sourceScan?.dependencies ?? []).map(normalizeDependency));
10429
- const roots = collectRoots(root, sourceScanEntries);
10430
- sourceScanRoots = roots;
10431
- sourceScanOutDir = outDir;
10432
- const nextScanSignature = createSourceCandidateScanSignature({
10433
- inlineCandidates: sourceScan?.inlineCandidates,
10434
- outDir,
10435
- roots,
10436
- scanAllSources: !sourceScanExplicit
10437
- });
10438
- if (hasState() && sourceCandidateScanSignature === nextScanSignature) {
10439
- options.sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
10440
- cacheCurrent();
10441
- options.debug("reuse vite source candidate scan for watch rebuild");
10442
- sourceCandidateScanInvalidated = false;
10443
- return;
10444
- }
10445
- const cachedScan = options.isWatchLikeBuild() ? sourceCandidateScanCache.get(nextScanSignature) ?? sourceCandidateScanSnapshotCache.get(nextScanSignature) : void 0;
10446
- if (cachedScan) {
10447
- options.sourceCandidateCollector.restore(cachedScan.snapshot);
10448
- sourceScanIneligibleFiles.clear();
10449
- updateSourceScanMatchers(cachedScan.eligibleFiles);
10450
- sourceCandidateScanSignature = nextScanSignature;
10451
- options.debug("reuse cached vite source candidate scan for watch rebuild");
10452
- sourceCandidateScanInvalidated = false;
10453
- return;
10454
- }
10455
- if (options.isWatchLikeBuild()) options.sourceCandidateCollector.resetScan();
10456
- else options.sourceCandidateCollector.clearScan();
10457
- options.sourceCandidateCollector.syncInline(sourceScan?.inlineCandidates);
10458
- const eligibleFiles = /* @__PURE__ */ new Set();
10459
- sourceScanIneligibleFiles.clear();
10460
- await Promise.all(roots.map((scanRoot) => options.sourceCandidateCollector.scanRoot({
10461
- entries: scanRoot.entries,
10462
- explicit: scanRoot.explicit,
10463
- root: scanRoot.root,
10464
- outDir,
10465
- onFilesResolved: (files) => files.forEach((file) => eligibleFiles.add(file))
10466
- })));
10467
- updateSourceScanMatchers(eligibleFiles);
10468
- sourceCandidateScanSignature = nextScanSignature;
10469
- sourceCandidateScanInvalidated = false;
10470
- if (options.isWatchLikeBuild()) cacheCurrent();
10471
- };
10472
- const waitForPendingSyncs = async () => {
10473
- while (true) {
10474
- if (!pendingChangedFilesFlush && pendingChangedFiles.size === 0 && pendingSourceCandidateSyncs.size === 0) break;
10475
- await pendingChangedFilesFlush;
10476
- if (pendingChangedFiles.size > 0) await flushChangedFiles();
10477
- if (pendingSourceCandidateSyncs.size > 0) await Promise.all(pendingSourceCandidateSyncs);
10478
- }
10479
- };
10480
- const rememberHotUpdateChange = (change) => {
10481
- if (!change) return;
10482
- const previous = pendingHotUpdateChangeByFile.get(change.file);
10483
- if (!previous) {
10484
- const remembered = {
10485
- ...change,
10486
- addedCandidates: new Set(change.addedCandidates),
10487
- removedCandidates: new Set(change.removedCandidates)
10488
- };
10489
- pendingHotUpdateChangeByFile.set(change.file, remembered);
10490
- return remembered;
10491
- }
10492
- for (const candidate of change.addedCandidates) {
10493
- previous.addedCandidates.add(candidate);
10494
- previous.removedCandidates.delete(candidate);
10495
- }
10496
- for (const candidate of change.removedCandidates) if (!previous.addedCandidates.delete(candidate)) previous.removedCandidates.add(candidate);
10497
- previous.runtimeAffecting || (previous.runtimeAffecting = change.runtimeAffecting);
10498
- return previous;
10499
- };
10500
- const syncChangedFileNow = async (id, sourceOverride, event = "update") => {
10501
- if (!options.shouldOwnTailwindGeneration || !options.isCandidateRequest(id)) return;
10502
- const file = cleanUrl$1(id);
10503
- const runtimeAffectingByDependency = isDependency(file);
10504
- if (runtimeAffectingByDependency) invalidate();
10505
- const resolvedFile = resolveSourceScanPath(file);
10506
- if (sourceScanMatcher && !sourceScanMatcher(file) && sourceScanBoundaryMatcher?.(file) && !sourceScanIneligibleFiles.has(resolvedFile)) {
10507
- await refreshSourceScanEligibleFiles();
10508
- if (!sourceScanMatcher(file)) sourceScanIneligibleFiles.add(resolvedFile);
10509
- }
10510
- if (sourceScanMatcher && !sourceScanMatcher(file)) {
10511
- const change = options.sourceCandidateCollector.remove(file);
10512
- cacheCurrent();
10513
- return (isSourceStyleRequest(file) ? readFile(file, "utf8").then((source) => options.cssMemory.refreshRememberedCssSourceBySourceFile(file, source)).catch((error) => {
10514
- if ((typeof error === "object" && error !== null && "code" in error ? error.code : void 0) !== "ENOENT") options.debug("remembered css source watch refresh failed: %s %O", file, error);
10515
- }) : Promise.resolve()).then(() => options.cssMemory.refreshRememberedCssSourceByCurrentFile(file)).then(() => rememberHotUpdateChange(options.hmrCandidateState.apply(options.hmrCandidateState.createChange(file, change, { runtimeAffecting: true }))));
10516
- }
10517
- const existingTask = pendingSourceCandidateSyncByFile.get(file);
10518
- if (existingTask) {
10519
- await existingTask;
10520
- return syncChangedFile(id, sourceOverride);
10521
- }
10522
- const previousSource = options.sourceCandidateCollector.source(file);
10523
- if (event === "delete") {
10524
- const change = options.sourceCandidateCollector.remove(file);
10525
- cacheDirty = true;
10526
- const appliedChange = options.hmrCandidateState.apply(options.hmrCandidateState.createChange(file, change, { runtimeAffecting: runtimeAffectingByDependency }));
10527
- return rememberHotUpdateChange(appliedChange);
10528
- }
10529
- const task = (sourceOverride === void 0 ? options.sourceCandidateCollector.syncCurrentFile(id) : options.sourceCandidateCollector.syncCurrentSource(id, sourceOverride)).catch((error) => {
10530
- options.debug("source candidate watch sync failed: %s %O", id, error);
10531
- }).then((change) => {
10532
- cacheDirty = true;
10533
- if (!isFlushingChangedFiles) cacheCurrent();
10534
- const runtimeAffectingBySource = hasFrameworkHmrRuntimeSourceChange(file, previousSource, options.sourceCandidateCollector.source(file));
10535
- const appliedChange = change ? options.hmrCandidateState.apply(options.hmrCandidateState.createChange(file, change, { runtimeAffecting: runtimeAffectingByDependency || runtimeAffectingBySource })) : void 0;
10536
- return rememberHotUpdateChange(appliedChange) ?? pendingHotUpdateChangeByFile.get(file);
10537
- }).finally(() => {
10538
- pendingSourceCandidateSyncs.delete(task);
10539
- pendingSourceCandidateSyncByFile.delete(file);
10540
- });
10541
- pendingSourceCandidateSyncs.add(task);
10542
- pendingSourceCandidateSyncByFile.set(file, task);
10543
- return task.then(async (change) => {
10544
- await options.cssMemory.refreshRememberedCssSourceByCurrentFile(file);
10545
- return change;
10546
- });
10547
- };
10548
- const queueChangedFile = (change) => {
10549
- const file = cleanUrl$1(change.id);
10550
- const previous = pendingChangedFiles.get(file);
10551
- if (!previous) {
10552
- pendingChangedFiles.set(file, {
10553
- ...change,
10554
- file
10555
- });
10556
- return;
10557
- }
10558
- previous.event = change.event;
10559
- if (change.source !== void 0) previous.source = change.source;
10560
- };
10561
- const flushChangedFiles = async () => {
10562
- if (pendingChangedFilesFlush) {
10563
- const result = await pendingChangedFilesFlush;
10564
- return pendingChangedFiles.size > 0 ? flushChangedFiles() : result;
10565
- }
10566
- if (pendingChangedFiles.size === 0) return /* @__PURE__ */ new Map();
10567
- const changes = [...pendingChangedFiles.values()];
10568
- pendingChangedFiles.clear();
10569
- isFlushingChangedFiles = true;
10570
- pendingChangedFilesFlush = Promise.all(changes.map(async (change) => [change.file, await syncChangedFileNow(change.file, change.source, change.event)])).then((entries) => new Map(entries)).finally(() => {
10571
- isFlushingChangedFiles = false;
10572
- pendingChangedFilesFlush = void 0;
10573
- cacheCurrent();
10574
- });
10575
- return pendingChangedFilesFlush;
10576
- };
10577
- const syncChangedFile = async (id, sourceOverride) => {
10578
- const file = cleanUrl$1(id);
10579
- const existingTask = pendingSourceCandidateSyncByFile.get(file);
10580
- if (existingTask) {
10581
- await existingTask;
10582
- return syncChangedFile(id, sourceOverride);
10583
- }
10584
- return syncChangedFileNow(file, sourceOverride);
10585
- };
10586
- return {
10587
- cacheCurrent,
10588
- consumeHotUpdateChange: (id) => pendingHotUpdateChangeByFile.delete(cleanUrl$1(id)),
10589
- getStats: () => ({
10590
- pendingSourceCandidateSyncByFile: pendingSourceCandidateSyncByFile.size,
10591
- pendingSourceCandidateSyncs: pendingSourceCandidateSyncs.size,
10592
- pendingChangedFiles: pendingChangedFiles.size,
10593
- pendingHotUpdateChangeByFile: pendingHotUpdateChangeByFile.size,
10594
- sourceCandidateScanCache: sourceCandidateScanCache.size
10595
- }),
10596
- invalidate,
10597
- isDependency,
10598
- matches: (file) => sourceScanMatcher?.(file) ?? true,
10599
- queueChangedFile,
10600
- flushChangedFiles,
10601
- shouldDiscoverAutoCssSources,
10602
- sync,
10603
- syncChangedFile,
10604
- waitForPendingSyncs
10605
- };
10606
- }
10607
- //#endregion
10608
- //#region src/bundlers/vite/shared/framework-tailwind-root-css.ts
10609
- function createFrameworkTailwindRootCss(options) {
10610
- const hotSourceByFile = /* @__PURE__ */ new Map();
10611
- const moduleIds = /* @__PURE__ */ new Set();
10612
- const normalizeSourceFile = (id) => resolveViteModuleIdentity(id).key;
10613
- const rememberModule = (id) => {
10614
- if (!options.shouldOwnTailwindGeneration || typeof id !== "string" || id.length === 0) return;
10615
- moduleIds.add(id);
10616
- const identity = resolveViteModuleIdentity(id);
10617
- if (isSourceStyleRequest(identity.cleanId)) for (const moduleId of identity.lookupIds) moduleIds.add(moduleId);
10618
- };
10619
- const register = async (id, code) => {
10620
- rememberModule(id);
10621
- const hotSource = hotSourceByFile.get(normalizeSourceFile(id));
10622
- await options.registerAutoCssSource(id, hotSource ?? code);
10623
- };
10624
- const refreshSource = async (id, code) => {
10625
- const file = cleanUrl$1(id);
10626
- if (!moduleIds.has(id) && !moduleIds.has(file) && !hasTailwindRootDirectives(code, { importFallback: options.getImportFallback() })) return;
10627
- hotSourceByFile.set(normalizeSourceFile(id), code);
10628
- await register(id, code);
10629
- options.sourceScanSession.invalidate();
10630
- await options.refreshRuntimeState(true);
10631
- await options.sourceScanSession.sync({ force: true });
10632
- };
10633
- return {
10634
- refreshSource,
10635
- register,
10636
- rememberModule,
10637
- moduleIds
10638
- };
10639
- }
10640
- //#endregion
10641
7304
  //#region src/bundlers/vite/shared/create-framework-plugins-runtime.ts
10642
7305
  const debug = createDebug();
10643
7306
  const weappTailwindcssPackageDir = resolvePackageDir("weapp-tailwindcss");
@@ -10663,7 +7326,7 @@ function createViteFrameworkPlugins$1(options = {}, frameworkBranch) {
10663
7326
  });
10664
7327
  const syncCssEntriesFromAnchor = (anchor) => {
10665
7328
  var _opts$tailwindcss;
10666
- const normalizedCssEntries = normalizeCssEntries(rawCssEntries, anchor ?? process$1.cwd());
7329
+ const normalizedCssEntries = normalizeCssEntries(rawCssEntries, anchor ?? process.cwd());
10667
7330
  if (!normalizedCssEntries) return false;
10668
7331
  const changed = !sameStringList(opts.cssEntries, normalizedCssEntries);
10669
7332
  opts.cssEntries = normalizedCssEntries;
@@ -10696,7 +7359,7 @@ function createViteFrameworkPlugins$1(options = {}, frameworkBranch) {
10696
7359
  const explicit = normalizeFrameworkStylePlatform(opts.cssOptions?.platform ?? opts.platform, opts.appType);
10697
7360
  if (explicit) return explicit;
10698
7361
  for (const key of ENV_PLATFORM_KEYS) {
10699
- const envPlatform = normalizeFrameworkStylePlatform(process$1.env[key], opts.appType);
7362
+ const envPlatform = normalizeFrameworkStylePlatform(process.env[key], opts.appType);
10700
7363
  if (envPlatform) return envPlatform;
10701
7364
  }
10702
7365
  return inferPlatformFromOutDir(resolvedConfig?.build?.outDir);
@@ -10885,7 +7548,7 @@ function createViteFrameworkPlugins$1(options = {}, frameworkBranch) {
10885
7548
  const getSourceCandidatesForEntries = (entries, options2) => sourceCandidateCollector.valuesForEntries(entries, options2);
10886
7549
  const getSourceCandidateSourcesForEntries = (entries, options2) => sourceCandidateCollector.sourcesForEntries(entries, options2);
10887
7550
  const isWatchBuild = () => resolvedConfig?.command === "build" && resolvedConfig.build.watch != null;
10888
- const isWatchLikeBuild = () => isWatchBuild() || resolvedConfig?.command === "serve" || process$1.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || process$1.env["WEAPP_TW_HMR_TIMING"] === "1";
7551
+ const isWatchLikeBuild = () => isWatchBuild() || resolvedConfig?.command === "serve" || process.env["WEAPP_TW_WATCH_REGRESSION"] === "1" || process.env["WEAPP_TW_HMR_TIMING"] === "1";
10889
7552
  const shouldSkipSourceCandidateState = () => shouldSkipGenericWebProductionSourceCandidates({
10890
7553
  command: resolvedConfig?.command,
10891
7554
  frameworkName: frameworkBranch.frameworkName,
@@ -10996,7 +7659,7 @@ function createViteFrameworkPlugins$1(options = {}, frameworkBranch) {
10996
7659
  const requestFile = isCSSRequest(id) ? inferredSfcStyleRequest === file ? resolveViteCssPipelineRequestFile(id) : inferredSfcStyleRequest : inferredSfcStyleRequest;
10997
7660
  if (!isCSSRequest(requestFile) || opts.htmlMatcher(file) || isHTMLRequest(file)) return;
10998
7661
  const generatorCode = normalizeEmptyTailwindCustomVariants(code);
10999
- const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process$1.cwd();
7662
+ const rootDir = resolvedConfig?.root ? path.resolve(resolvedConfig.root) : process.cwd();
11000
7663
  const currentGeneratorOptions = resolveCurrentGeneratorOptions();
11001
7664
  const currentGeneratorBranch = resolveCurrentGeneratorBranch();
11002
7665
  const cssPipelineContext = createCssPipelineContext({
@@ -11219,12 +7882,12 @@ ${tracedCss}`;
11219
7882
  frameworkRootImportShellTargetByFile
11220
7883
  };
11221
7884
  const shouldSplitGenerateBundlePhases = () => opts.appType === "weapp-vite" && getResolvedConfig()?.mode !== "production";
11222
- const preGenerateBundleHook = createGenerateBundleHook({
7885
+ const preGenerateBundleHook = capability.cssOnly ? void 0 : createGenerateBundleHook({
11223
7886
  ...generateBundleContext,
11224
7887
  processMarkupAndScripts: false,
11225
7888
  shouldProcessBundle: shouldSplitGenerateBundlePhases
11226
7889
  });
11227
- const generateBundleHook = createGenerateBundleHook({
7890
+ const generateBundleHook = capability.cssOnly ? void 0 : createGenerateBundleHook({
11228
7891
  ...generateBundleContext,
11229
7892
  ...createGenericWebProductionBundleHooks({
11230
7893
  frameworkName: frameworkBranch.frameworkName,
@@ -11236,7 +7899,7 @@ ${tracedCss}`;
11236
7899
  }),
11237
7900
  shouldProcessStyles: () => !shouldSplitGenerateBundlePhases()
11238
7901
  });
11239
- const cssFinalizerOutputPlugin = createViteCssFinalizerOutputPlugin({
7902
+ const cssFinalizerContext = {
11240
7903
  opts,
11241
7904
  runtimeState,
11242
7905
  ensureRuntimeClassSet,
@@ -11264,7 +7927,8 @@ ${tracedCss}`;
11264
7927
  sourceFile: file
11265
7928
  }),
11266
7929
  getRememberedMainCssSource: cssMemory.getRememberedCssSourceEntry
11267
- });
7930
+ };
7931
+ const cssFinalizerOutputPlugin = capability.cssOnly ? createViteWebCssFinalizerOutputPlugin(cssFinalizerContext) : createViteCssFinalizerOutputPlugin(cssFinalizerContext);
11268
7932
  const extraPluginPlatform = frameworkBranch.getExtraPluginPlatform?.() ?? {};
11269
7933
  const syncSourceCandidatesForHotUpdate = (ctx) => syncFrameworkSourceCandidatesForHotUpdate(sourceScanSession, ctx);
11270
7934
  const registerModuleGraphCandidates = createFrameworkModuleCandidateRegistrar({
@@ -11401,18 +8065,18 @@ ${tracedCss}`;
11401
8065
  shouldGenerateBuild: () => resolveCurrentGeneratorBranch().isWeb
11402
8066
  }),
11403
8067
  ...serveJsPlugin ? [serveJsPlugin] : [],
11404
- {
8068
+ ...capability.cssOnly ? [] : [{
11405
8069
  name: `${vitePluginName}:watch-css-cache`,
11406
8070
  configResolved: {
11407
8071
  order: "post",
11408
8072
  handler: installFrameworkWatchCssCacheAdapter
11409
8073
  }
11410
- },
8074
+ }],
11411
8075
  postPlugin
11412
8076
  ];
11413
8077
  plugins.push(cssFinalizerOutputPlugin);
11414
8078
  plugins.push(createViteHmrCssModuleVersionFilterPlugin(hmrCssModuleVersions));
11415
- if (capability.styleInjector) plugins.push(...createBuiltinViteStyleInjectorPlugins(styleInjector, () => frameworkBranch.styleInjectorDelegate));
8079
+ if (capability.styleInjector) plugins.push(...capability.cssOnly && typeof options.__internalViteWebStyleInjectorFactory === "function" ? options.__internalViteWebStyleInjectorFactory(styleInjector) : createBuiltinViteStyleInjectorPlugins(styleInjector, () => frameworkBranch.styleInjectorDelegate));
11416
8080
  return plugins;
11417
8081
  }
11418
8082
  //#endregion
@@ -11498,7 +8162,7 @@ function createTaroAlipayBrowserslistAssetPlugin() {
11498
8162
  name: "weapp-tailwindcss:taro-alipay-browserslist-asset",
11499
8163
  enforce: "pre",
11500
8164
  generateBundle(_options, bundle) {
11501
- if (process$1.env.TARO_ENV !== "alipay") return;
8165
+ if (process.env.TARO_ENV !== "alipay") return;
11502
8166
  bundle[".browserslistrc"] = {
11503
8167
  type: "asset",
11504
8168
  fileName: ".browserslistrc",
@@ -11792,22 +8456,26 @@ function resolveEnvironmentName(context) {
11792
8456
  return typeof name === "string" && name.length > 0 ? name : "default";
11793
8457
  }
11794
8458
  function resolveViteProfile(options, config, environmentName) {
8459
+ const forceGenericWeb = options.__internalViteForceGenericWeb === true;
11795
8460
  const rawTarget = options.generator && typeof options.generator === "object" ? options.generator.target : void 0;
11796
8461
  const explicitPlatform = options.cssOptions?.platform ?? options.platform;
11797
- const envPlatform = process$1.env["UNI_PLATFORM"] ?? process$1.env["UNI_UTS_PLATFORM"];
8462
+ const envPlatform = process.env["UNI_PLATFORM"] ?? process.env["UNI_UTS_PLATFORM"];
11798
8463
  const selectedPlatform = explicitPlatform ?? envPlatform;
11799
8464
  const explicitAppType = options.appType;
11800
- const root = config.root ? path.resolve(config.root) : process$1.cwd();
8465
+ const root = config.root ? path.resolve(config.root) : process.cwd();
11801
8466
  let frameworkName = "generic";
11802
8467
  let appType = explicitAppType;
11803
- if (explicitAppType) frameworkName = resolveViteFrameworkProfile({
8468
+ if (forceGenericWeb) {
8469
+ frameworkName = "generic";
8470
+ appType = void 0;
8471
+ } else if (explicitAppType) frameworkName = resolveViteFrameworkProfile({
11804
8472
  appType: explicitAppType,
11805
8473
  uniAppX: options.uniAppX
11806
8474
  }).frameworkName;
11807
8475
  else {
11808
8476
  const detected = resolveViteFrameworkProfile({
11809
8477
  detectEnv: true,
11810
- env: process$1.env,
8478
+ env: process.env,
11811
8479
  root,
11812
8480
  searchUp: false,
11813
8481
  uniAppX: options.uniAppX
@@ -11824,9 +8492,11 @@ function resolveViteProfile(options, config, environmentName) {
11824
8492
  }
11825
8493
  const family = platformFamily(selectedPlatform ?? (config.build?.outDir ? path.basename(path.normalize(config.build.outDir)) : void 0));
11826
8494
  if (!explicitAppType && !(rawTarget !== "web" && family !== "web")) appType = void 0;
11827
- const isGenericWeb = frameworkName === "generic" && !explicitAppType && rawTarget !== "weapp" && rawTarget !== "app" && !(Array.isArray(options.cssEntries) && options.cssEntries.length > 0) && family !== "mini-program";
8495
+ const isGenericWeb = frameworkName === "generic" && (forceGenericWeb || !explicitAppType) && rawTarget !== "weapp" && rawTarget !== "app" && family !== "mini-program";
8496
+ const cssOnlyGenericWeb = isGenericWeb && (forceGenericWeb || rawTarget === void 0 && explicitAppType === void 0 && selectedPlatform === void 0);
11828
8497
  const capability = isGenericWeb ? {
11829
8498
  ...createGenericWebViteCapabilityProfile(options),
8499
+ cssOnly: cssOnlyGenericWeb,
11830
8500
  sourceCandidates: options.generator && typeof options.generator === "object" && options.generator.target === "web" ? true : createGenericWebViteCapabilityProfile(options).sourceCandidates
11831
8501
  } : {
11832
8502
  ...frameworkViteCapabilityProfile,
@@ -11867,16 +8537,17 @@ function createDispatcher(options) {
11867
8537
  opts.__internalViteRawExplicitAppType = typeof options.appType === "string" && options.appType.trim().length > 0;
11868
8538
  opts.__internalViteRawExplicitTailwindcssBasedir = typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0;
11869
8539
  opts.__internalViteRawExplicitGeneratorTarget = Boolean(options.generator && typeof options.generator === "object" && Object.hasOwn(options.generator, "target"));
8540
+ const forceGenericWeb = options.__internalViteForceGenericWeb === true;
11870
8541
  const initialProfile = resolveViteFrameworkProfile({
11871
- appType: opts.appType,
8542
+ appType: forceGenericWeb ? void 0 : opts.appType,
11872
8543
  detectEnv: true,
11873
- env: process$1.env,
8544
+ env: process.env,
11874
8545
  root: typeof options.tailwindcssBasedir === "string" && options.tailwindcssBasedir.trim().length > 0 ? path.resolve(options.tailwindcssBasedir) : void 0,
11875
8546
  searchUp: false,
11876
8547
  uniAppX: opts.uniAppX
11877
8548
  });
11878
- const initialFramework = initialProfile.frameworkName;
11879
- opts.__internalViteCapabilityProfile = { ...frameworkViteCapabilityProfile };
8549
+ const initialFramework = forceGenericWeb ? "generic" : initialProfile.frameworkName;
8550
+ opts.__internalViteCapabilityProfile = forceGenericWeb ? createGenericWebViteCapabilityProfile(options) : { ...frameworkViteCapabilityProfile };
11880
8551
  const initialFactory = {
11881
8552
  "generic": createGenericVitePlugins,
11882
8553
  "taro": createTaroVitePlugins,
@@ -11929,7 +8600,12 @@ function createDispatcher(options) {
11929
8600
  }
11930
8601
  ];
11931
8602
  const initialNames = new Set(initialPlugins.map((plugin) => plugin.name));
11932
- const pluginTemplates = [...initialPlugins, ...initialFramework === "generic" && !opts.appType && initialPlugins.length > 1 ? knownFrameworkPlugins.filter((plugin) => !initialNames.has(plugin.name)) : []];
8603
+ const genericWebPlugins = initialFramework === "generic" && !forceGenericWeb && !opts.appType ? createGenericWebVitePlugins(opts) ?? [] : [];
8604
+ const pluginTemplates = [
8605
+ ...initialPlugins,
8606
+ ...genericWebPlugins,
8607
+ ...initialFramework === "generic" && !forceGenericWeb && !opts.appType && initialPlugins.length > 1 ? knownFrameworkPlugins.filter((plugin) => !initialNames.has(plugin.name)) : []
8608
+ ].filter((plugin, index, plugins) => plugins.findIndex((candidate) => candidate.name === plugin.name) === index);
11933
8609
  let activePlugins = initialPlugins;
11934
8610
  let resolved = false;
11935
8611
  const ensureBranch = (config, context) => {
@@ -11951,18 +8627,18 @@ function createDispatcher(options) {
11951
8627
  opts.appType = profile.appType;
11952
8628
  logger.debug("根据 Vite 项目根目录自动推断 appType -> %s", profile.appType);
11953
8629
  }
11954
- if (profile.isGenericWeb && !opts.generator && opts.generator !== false && !options.platform && !options.cssOptions?.platform && !process$1.env["UNI_PLATFORM"] && !process$1.env["UNI_UTS_PLATFORM"]) opts.generator = { target: "web" };
8630
+ if (profile.isGenericWeb && (opts.generator === void 0 || typeof opts.generator === "object" && !Object.hasOwn(opts.generator, "target")) && opts.generator !== false && !options.platform && !options.cssOptions?.platform && !process.env["UNI_PLATFORM"] && !process.env["UNI_UTS_PLATFORM"]) opts.generator = { target: "web" };
11955
8631
  const capability = opts.__internalViteCapabilityProfile;
11956
8632
  if (capability) Object.assign(capability, profile.capability);
11957
8633
  else opts.__internalViteCapabilityProfile = profile.capability;
11958
- const factory = {
8634
+ const factory = profile.capability.cssOnly ? createGenericWebVitePlugins : {
11959
8635
  "generic": createGenericVitePlugins,
11960
8636
  "taro": createTaroVitePlugins,
11961
8637
  "uni-app": createUniAppVitePlugins,
11962
8638
  "uni-app-x": createUniAppXVitePlugins,
11963
8639
  "weapp-vite": createWeappVitePlugins
11964
8640
  }[profile.frameworkName];
11965
- if (profile.frameworkName !== initialFramework) activePlugins = factory(opts) ?? [];
8641
+ if (profile.frameworkName !== initialFramework || profile.capability.cssOnly) activePlugins = factory(opts) ?? [];
11966
8642
  };
11967
8643
  const byName = (name) => activePlugins.find((plugin) => plugin.name === name);
11968
8644
  return pluginTemplates.map((template) => {
@@ -11987,4 +8663,4 @@ function WeappTailwindcss(options = {}) {
11987
8663
  return createDispatcher(options);
11988
8664
  }
11989
8665
  //#endregion
11990
- export { WeappTailwindcss as t };
8666
+ export { shouldEnableComponentLocalStyle as n, shouldEnablePageLocalStyle as r, WeappTailwindcss as t };