weapp-tailwindcss 5.4.1 → 5.5.0

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/v4-generation-core.d.ts +1 -0
  4. package/dist/bundlers/vite/capability-profile.d.ts +1 -0
  5. package/dist/bundlers/vite/css-finalizer/web-plugin.d.ts +3 -0
  6. package/dist/bundlers/vite/css-handler-options.d.ts +32 -0
  7. package/dist/bundlers/vite/{generate-bundle/css-output.d.ts → css-output.d.ts} +1 -1
  8. package/dist/bundlers/vite/frameworks/generic/web.d.ts +2 -0
  9. package/dist/bundlers/vite/generate-bundle/css-handler-options.d.ts +2 -32
  10. package/dist/bundlers/vite/generate-bundle/finalize/root-import-shell.d.ts +1 -1
  11. package/dist/bundlers/vite/generate-bundle/remembered-css-replay.d.ts +2 -2
  12. package/dist/bundlers/vite/generate-bundle/runtime.d.ts +1 -1
  13. package/dist/bundlers/vite/generate-bundle/uni-app-x-postprocess.d.ts +1 -1
  14. package/dist/bundlers/vite/generate-bundle.d.ts +1 -1
  15. package/dist/bundlers/vite/runtime-class-set.d.ts +1 -5
  16. package/dist/bundlers/vite/shared/create-css-only-plugins-runtime.d.ts +3 -0
  17. package/dist/cache-CBJFB1HN.cjs +223 -0
  18. package/dist/compiler/events.d.ts +32 -0
  19. package/dist/compiler/host.d.ts +13 -0
  20. package/dist/compiler/index.d.ts +3 -0
  21. package/dist/compiler/runtime-state.d.ts +17 -0
  22. package/dist/compiler-B0YSc0DY.js +4877 -0
  23. package/dist/{wxml-o-CUulAM.cjs → compiler-SwMb3lOX.cjs} +3649 -283
  24. package/dist/core.cjs +6 -3
  25. package/dist/core.d.ts +2 -0
  26. package/dist/core.js +4 -4
  27. package/dist/defaults-B5ep0ojb.js +120 -0
  28. package/dist/defaults-BI9j1znS.cjs +156 -0
  29. package/dist/defaults.cjs +5 -121
  30. package/dist/defaults.js +1 -116
  31. package/dist/final-css-cleanup-BMlUDzik.cjs +112 -0
  32. package/dist/final-css-cleanup-CmVYbXPr.js +282 -0
  33. package/dist/framework.cjs +22 -2
  34. package/dist/framework.js +22 -2
  35. package/dist/{generator-WlhrtNa3.cjs → generator-DsrQ9txU.cjs} +62 -5
  36. package/dist/{generator-BjK5PRR-.js → generator-DyXTBPmE.js} +47 -2
  37. package/dist/generator.cjs +1 -1
  38. package/dist/generator.js +1 -1
  39. package/dist/{gulp-BbMMp7vY.js → gulp-CVUiPXPy.js} +7 -7
  40. package/dist/{gulp-CBu_waef.cjs → gulp-Dtc01FdI.cjs} +30 -28
  41. package/dist/gulp.cjs +1 -1
  42. package/dist/gulp.js +1 -1
  43. package/dist/{hmr-timing-CYhNto2U.cjs → hmr-timing-3SdRVfZx.cjs} +6 -229
  44. package/dist/{hmr-timing-B_4sAvsk.js → hmr-timing-DNxQm-bN.js} +6 -1258
  45. package/dist/index.cjs +4 -4
  46. package/dist/index.js +4 -4
  47. package/dist/{pipeline-helpers-Du8eAtMG.cjs → pipeline-helpers-DVrgv1HS.cjs} +6 -5
  48. package/dist/postcss.cjs +1 -1
  49. package/dist/postcss.js +1 -1
  50. package/dist/presets.cjs +4 -4
  51. package/dist/presets.js +2 -2
  52. package/dist/rspack.cjs +2 -2
  53. package/dist/rspack.js +2 -2
  54. package/dist/runtime-state-BBQcA0n5.cjs +54 -0
  55. package/dist/{source-candidate-scan-signature-ZOm0O17V.cjs → scoped-generator-B7thnzzm.cjs} +5 -123
  56. package/dist/{source-candidate-scan-signature-wieibgE7.js → scoped-generator-kRj_5Axx.js} +4 -92
  57. package/dist/source-candidate-scan-signature-B7cUxqqX.cjs +129 -0
  58. package/dist/source-candidate-scan-signature-CsP4BQNa.js +92 -0
  59. package/dist/style-injector/internal.d.ts +1 -1
  60. package/dist/style-injector/vite-web.d.ts +3 -0
  61. package/dist/{tailwindcss-9xmoCkaR.js → tailwindcss-BK9S7zuq.js} +1 -2
  62. package/dist/{tailwindcss-D3jltF7M.cjs → tailwindcss-C-jBBQfw.cjs} +8 -9
  63. package/dist/{transform-DQhgAarN.js → transform-C0rWZblB.js} +3 -3
  64. package/dist/{transform-C6k9zTQR.cjs → transform-C7QxW-fV.cjs} +27 -27
  65. package/dist/{v4-generation-core-BhYkeoZ4.cjs → v4-generation-core-DuIVZvRz.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-Fu6GTjIY.js → vite-0PsttwuR.js} +269 -3581
  70. package/dist/{vite-B0cvyfSY.cjs → vite-CJbO-7AQ.cjs} +519 -3791
  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-BFOkkJ-8.cjs +4357 -0
  77. package/dist/web-D8HSs56R.js +3792 -0
  78. package/dist/{webpack-Amn5lmnx.cjs → webpack-BWknqSDV.cjs} +51 -49
  79. package/dist/{webpack-BKHO-WSM.js → webpack-DVtKeBq1.js} +13 -12
  80. package/dist/webpack.cjs +1 -1
  81. package/dist/webpack.js +1 -1
  82. package/package.json +12 -3
  83. package/dist/cache-options-DavPxrhC.cjs +0 -16
  84. package/dist/cache-options-DwBtLwQe.js +0 -5
  85. package/dist/compiler-CDAz4SwJ.cjs +0 -2302
  86. package/dist/compiler-DWcUgi3A.js +0 -2049
  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,2302 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-Ctb5zv51.cjs");
2
- const require_framework = require("./framework.cjs");
3
- const require_generator = require("./generator-WlhrtNa3.cjs");
4
- const require_object = require("./object-DbHtAXRk.cjs");
5
- const require_tailwindcss = require("./tailwindcss-D3jltF7M.cjs");
6
- require("./utils-CuKLf1Zv.cjs");
7
- const require_wxml = require("./wxml-o-CUulAM.cjs");
8
- const require_defaults = require("./defaults.cjs");
9
- let node_path = require("node:path");
10
- node_path = require_rolldown_runtime.__toESM(node_path, 1);
11
- let node_process = require("node:process");
12
- node_process = require_rolldown_runtime.__toESM(node_process, 1);
13
- let _tailwindcss_mangle_engine = require("@tailwindcss-mangle/engine");
14
- let _weapp_tailwindcss_postcss = require("@weapp-tailwindcss/postcss");
15
- let lru_cache = require("lru-cache");
16
- let node_module = require("node:module");
17
- let node_fs_promises = require("node:fs/promises");
18
- let node_buffer = require("node:buffer");
19
- let _weapp_tailwindcss_logger = require("@weapp-tailwindcss/logger");
20
- let _weapp_tailwindcss_shared_node = require("@weapp-tailwindcss/shared/node");
21
- let _weapp_tailwindcss_shared = require("@weapp-tailwindcss/shared");
22
- //#region src/compiler/candidate-index.ts
23
- var CandidateIndex = class {
24
- constructor() {
25
- require_object._defineProperty(this, "candidatesBySource", /* @__PURE__ */ new Map());
26
- }
27
- sync(sourceId, candidates) {
28
- const previous = this.candidatesBySource.get(sourceId) ?? /* @__PURE__ */ new Set();
29
- const next = new Set(candidates);
30
- const addedCandidates = new Set([...next].filter((candidate) => !previous.has(candidate)));
31
- const removedCandidates = new Set([...previous].filter((candidate) => !next.has(candidate)));
32
- this.candidatesBySource.set(sourceId, next);
33
- return {
34
- sourceId,
35
- addedCandidates,
36
- removedCandidates
37
- };
38
- }
39
- remove(sourceId) {
40
- const previous = this.candidatesBySource.get(sourceId) ?? /* @__PURE__ */ new Set();
41
- this.candidatesBySource.delete(sourceId);
42
- return {
43
- sourceId,
44
- addedCandidates: /* @__PURE__ */ new Set(),
45
- removedCandidates: new Set(previous)
46
- };
47
- }
48
- values() {
49
- const values = /* @__PURE__ */ new Set();
50
- for (const candidates of this.candidatesBySource.values()) for (const candidate of candidates) values.add(candidate);
51
- return values;
52
- }
53
- get(sourceId) {
54
- return new Set(this.candidatesBySource.get(sourceId) ?? []);
55
- }
56
- entries() {
57
- return new Map([...this.candidatesBySource].map(([sourceId, candidates]) => [sourceId, new Set(candidates)]));
58
- }
59
- clear() {
60
- this.candidatesBySource.clear();
61
- }
62
- };
63
- //#endregion
64
- //#region src/compiler/invalidation.ts
65
- function resolveInvalidatedScopes(graph, changes) {
66
- const invalidatedScopes = /* @__PURE__ */ new Set();
67
- const visit = (sourceId, visited) => {
68
- if (visited.has(sourceId)) return;
69
- visited.add(sourceId);
70
- const node = graph.getNode(sourceId);
71
- if (node) invalidatedScopes.add(node.scope.id);
72
- for (const dependent of graph.getDependents(sourceId)) visit(dependent, visited);
73
- };
74
- for (const change of changes) visit(change.sourceId, /* @__PURE__ */ new Set());
75
- return invalidatedScopes;
76
- }
77
- //#endregion
78
- //#region src/compiler/source-graph.ts
79
- var SourceGraph = class {
80
- constructor() {
81
- require_object._defineProperty(this, "edges", /* @__PURE__ */ new Map());
82
- require_object._defineProperty(this, "nodes", /* @__PURE__ */ new Map());
83
- }
84
- replace(nodes, edges) {
85
- this.clear();
86
- for (const node of nodes) this.nodes.set(node.id, {
87
- ...node,
88
- scope: { ...node.scope }
89
- });
90
- for (const edge of edges) {
91
- if (!this.nodes.has(edge.from) || !this.nodes.has(edge.to)) throw new Error(`编译图边引用了不存在的节点:${edge.from} -> ${edge.to}`);
92
- this.edges.set(this.edgeKey(edge), { ...edge });
93
- }
94
- }
95
- getNode(id) {
96
- const node = this.nodes.get(id);
97
- return node ? {
98
- ...node,
99
- scope: { ...node.scope }
100
- } : void 0;
101
- }
102
- getNodes() {
103
- return [...this.nodes.values()].map((node) => ({
104
- ...node,
105
- scope: { ...node.scope }
106
- }));
107
- }
108
- getEdges() {
109
- return [...this.edges.values()].map((edge) => ({ ...edge }));
110
- }
111
- getDependents(id) {
112
- return this.getEdges().filter((edge) => edge.to === id).map((edge) => edge.from);
113
- }
114
- clear() {
115
- this.edges.clear();
116
- this.nodes.clear();
117
- }
118
- edgeKey(edge) {
119
- return `${edge.kind}\0${edge.from}\0${edge.to}`;
120
- }
121
- };
122
- //#endregion
123
- //#region src/compiler/session.ts
124
- var DefaultCompilationSession = class {
125
- constructor() {
126
- require_object._defineProperty(this, "candidateIndex", new CandidateIndex());
127
- require_object._defineProperty(this, "graph", new SourceGraph());
128
- require_object._defineProperty(this, "retainedCandidates", /* @__PURE__ */ new Set());
129
- require_object._defineProperty(this, "validatedClassSet", /* @__PURE__ */ new Set());
130
- require_object._defineProperty(this, "invalidatedScopes", /* @__PURE__ */ new Set());
131
- require_object._defineProperty(this, "revision", 0);
132
- }
133
- update(snapshot) {
134
- const changes = [...snapshot.changes ?? []];
135
- const invalidatedScopes = resolveInvalidatedScopes(this.graph, changes);
136
- this.graph.replace(snapshot.nodes, snapshot.edges);
137
- for (const [sourceId, candidates] of snapshot.candidatesBySource ?? []) {
138
- const change = this.candidateIndex.sync(sourceId, candidates);
139
- if (change.addedCandidates.size > 0 || change.removedCandidates.size > 0) changes.push(change);
140
- }
141
- for (const change of changes) if ("type" in change && change.type === "source-removed") this.candidateIndex.remove(change.sourceId);
142
- const currentCandidates = this.candidateIndex.values();
143
- if (snapshot.preserveDeletedCss) for (const candidate of currentCandidates) this.retainedCandidates.add(candidate);
144
- else {
145
- this.retainedCandidates.clear();
146
- for (const candidate of currentCandidates) this.retainedCandidates.add(candidate);
147
- }
148
- if (snapshot.validatedClassSet !== void 0) this.validatedClassSet = new Set(snapshot.validatedClassSet);
149
- else if (!snapshot.preserveDeletedCss) this.validatedClassSet = new Set([...this.validatedClassSet].filter((candidate) => this.retainedCandidates.has(candidate)));
150
- this.revision += 1;
151
- for (const scopeId of resolveInvalidatedScopes(this.graph, changes)) invalidatedScopes.add(scopeId);
152
- this.invalidatedScopes = invalidatedScopes;
153
- return this.createResult();
154
- }
155
- commitValidation(revision, validatedClassSet, graph) {
156
- if (revision !== this.revision) throw new Error(`不能向编译 revision ${this.revision} 提交 revision ${revision} 的 classSet。`);
157
- if (graph) this.graph.replace(graph.nodes, graph.edges);
158
- this.validatedClassSet = new Set(validatedClassSet);
159
- return this.createResult();
160
- }
161
- createResult() {
162
- return {
163
- revision: this.revision,
164
- candidates: new Set(this.retainedCandidates),
165
- candidatesBySource: this.candidateIndex.entries(),
166
- validatedClassSet: new Set(this.validatedClassSet),
167
- invalidatedScopes: new Set(this.invalidatedScopes),
168
- graphEdges: this.graph.getEdges(),
169
- graphNodes: this.graph.getNodes()
170
- };
171
- }
172
- dispose() {
173
- this.candidateIndex.clear();
174
- this.graph.clear();
175
- this.retainedCandidates.clear();
176
- this.validatedClassSet.clear();
177
- this.invalidatedScopes.clear();
178
- this.revision = 0;
179
- }
180
- };
181
- //#endregion
182
- //#region src/core/compiler/source-fingerprint.ts
183
- function stableSerialize(value, stack = /* @__PURE__ */ new WeakSet()) {
184
- if (value == null || typeof value === "number" || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
185
- if (typeof value === "function") return `[Function:${value.name}]`;
186
- if (typeof value !== "object") return String(value);
187
- if (stack.has(value)) return "[Circular]";
188
- stack.add(value);
189
- const serialized = Array.isArray(value) ? `[${value.map((item) => stableSerialize(item, stack)).join(",")}]` : `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableSerialize(value[key], stack)}`).join(",")}}`;
190
- stack.delete(value);
191
- return serialized;
192
- }
193
- function createSourceFingerprint(source) {
194
- return createCompilerValueFingerprint(source);
195
- }
196
- function createCompilerValueFingerprint(value) {
197
- return (0, _weapp_tailwindcss_shared_node.md5)(stableSerialize(value));
198
- }
199
- //#endregion
200
- //#region src/core/compiler/generation-cache.ts
201
- function createCompilerGenerationCacheKey(request, candidates, target) {
202
- return {
203
- bareArbitraryValues: request.bareArbitraryValues,
204
- candidateSignature: [...candidates].sort().join("\0"),
205
- incrementalCache: request.incrementalCache,
206
- scanSources: request.scanSources,
207
- sourcesFingerprint: request.sources === void 0 ? void 0 : createCompilerValueFingerprint(request.sources),
208
- styleOptionsFingerprint: request.styleOptions === void 0 ? void 0 : createCompilerValueFingerprint(request.styleOptions),
209
- target
210
- };
211
- }
212
- function isSameCompilerGenerationCacheKey(left, right) {
213
- return left.bareArbitraryValues === right.bareArbitraryValues && left.candidateSignature === right.candidateSignature && left.incrementalCache === right.incrementalCache && left.scanSources === right.scanSources && left.sourcesFingerprint === right.sourcesFingerprint && left.styleOptionsFingerprint === right.styleOptionsFingerprint && left.target === right.target;
214
- }
215
- function reuseCompilerGenerationResult(result) {
216
- return {
217
- ...result,
218
- incrementalCss: "",
219
- incrementalRawCss: ""
220
- };
221
- }
222
- //#endregion
223
- //#region src/core/compiler/generation-state.ts
224
- function createGenerationGraph(rootId, source, dependencies) {
225
- const scope = {
226
- id: rootId,
227
- kind: "global"
228
- };
229
- const dependencyIds = [...new Set(dependencies)].filter((id) => id !== rootId).sort();
230
- const nodes = [{
231
- content: source.css,
232
- id: rootId,
233
- kind: "css",
234
- scope
235
- }, ...dependencyIds.map((id) => ({
236
- id,
237
- kind: "config",
238
- scope
239
- }))];
240
- return {
241
- edges: dependencyIds.map((id) => ({
242
- from: rootId,
243
- kind: "depends-on",
244
- to: id
245
- })),
246
- nodes
247
- };
248
- }
249
- function prepareCompilerGeneration(entry, request, source, sourceChanged) {
250
- const explicitCandidates = request.candidates !== void 0;
251
- const candidates = explicitCandidates ? [...request.candidates] : [];
252
- const candidateSignature = [...candidates].sort().join("\0");
253
- if (!sourceChanged && entry.compilationCache?.candidateSignature === candidateSignature && entry.compilationCache.compilation.revision === entry.compilationRevision) return {
254
- ...entry.compilationCache,
255
- explicitCandidates
256
- };
257
- const graph = createGenerationGraph(entry.id, source, source.dependencies);
258
- const compilation = entry.compilation.update({
259
- ...graph,
260
- candidatesBySource: [[entry.id, candidates]],
261
- changes: sourceChanged ? [{
262
- sourceId: entry.id,
263
- type: "dependency-changed"
264
- }] : void 0
265
- });
266
- entry.compilationRevision = compilation.revision;
267
- return {
268
- candidateSignature,
269
- compilation,
270
- explicitCandidates,
271
- graph
272
- };
273
- }
274
- function commitCompilerGeneration(entry, prepared, source, dependencies, classSet) {
275
- const graph = createGenerationGraph(entry.id, source, dependencies);
276
- const compilation = entry.compilation.commitValidation(prepared.compilation.revision, classSet, graph);
277
- entry.compilationCache = {
278
- candidateSignature: prepared.candidateSignature,
279
- compilation,
280
- graph
281
- };
282
- }
283
- //#endregion
284
- //#region src/core/compiler/root-store.ts
285
- function disposeGenerator(generator) {
286
- generator?.dispose?.();
287
- }
288
- var CompilerRootStore = class {
289
- constructor(maxRoots, onRootEvicted) {
290
- this.maxRoots = maxRoots;
291
- this.onRootEvicted = onRootEvicted;
292
- require_object._defineProperty(this, "dependencyRoots", /* @__PURE__ */ new Map());
293
- require_object._defineProperty(this, "releasing", /* @__PURE__ */ new Map());
294
- require_object._defineProperty(this, "roots", /* @__PURE__ */ new Map());
295
- }
296
- get(id) {
297
- if (!id) throw new Error("Compiler root id 不能为空。");
298
- if (this.releasing.has(id)) throw new Error(`Compiler root 正在移除:${id}`);
299
- const cached = this.roots.get(id);
300
- if (cached) {
301
- if (!cached.accepting) throw new Error(`Compiler root 正在移除:${id}`);
302
- this.roots.delete(id);
303
- this.roots.set(id, cached);
304
- return cached;
305
- }
306
- if (this.roots.size >= this.maxRoots) {
307
- const oldest = [...this.roots.values()].find((entry) => entry.pendingCount === 0);
308
- if (oldest) this.remove(oldest.id, true);
309
- }
310
- const entry = {
311
- accepting: true,
312
- active: true,
313
- appliedInvalidation: 0,
314
- compilation: new DefaultCompilationSession(),
315
- compilationRevision: 0,
316
- dependencies: /* @__PURE__ */ new Set(),
317
- id,
318
- invalidation: 0,
319
- pending: Promise.resolve(),
320
- pendingCount: 0,
321
- sources: []
322
- };
323
- this.roots.set(id, entry);
324
- return entry;
325
- }
326
- attachDependencies(entry, dependencies) {
327
- this.detachDependencies(entry);
328
- if (!entry.accepting) return;
329
- for (const dependency of dependencies) {
330
- entry.dependencies.add(dependency);
331
- let owners = this.dependencyRoots.get(dependency);
332
- if (!owners) {
333
- owners = /* @__PURE__ */ new Set();
334
- this.dependencyRoots.set(dependency, owners);
335
- }
336
- owners.add(entry.id);
337
- }
338
- }
339
- attachSources(entry, sources) {
340
- entry.sources = [...sources];
341
- }
342
- invalidate(ids) {
343
- const affected = /* @__PURE__ */ new Set();
344
- for (const id of ids) {
345
- const root = this.roots.get(id);
346
- if (root?.accepting) affected.add(root.id);
347
- for (const rootId of this.dependencyRoots.get(id) ?? []) affected.add(rootId);
348
- const sourcePath = stripSourceQuery(id);
349
- for (const sourceRoot of this.roots.values()) if (sourceRoot.accepting && sourceRoot.sources.length > 0 && require_generator.isFileMatchedByTailwindSourceEntries(sourcePath, sourceRoot.sources)) affected.add(sourceRoot.id);
350
- }
351
- for (const rootId of affected) {
352
- const entry = this.roots.get(rootId);
353
- if (entry?.accepting) entry.invalidation += 1;
354
- }
355
- return Object.freeze([...affected].sort());
356
- }
357
- trim() {
358
- while (this.roots.size > this.maxRoots) {
359
- const oldest = [...this.roots.values()].find((entry) => entry.pendingCount === 0);
360
- if (!oldest) return;
361
- this.remove(oldest.id, true);
362
- }
363
- }
364
- remove(id, notifyEvicted = false) {
365
- const pendingRelease = this.releasing.get(id);
366
- if (pendingRelease) return pendingRelease;
367
- const entry = this.roots.get(id);
368
- if (!entry) return Promise.resolve();
369
- entry.accepting = false;
370
- this.roots.delete(id);
371
- this.detachDependencies(entry);
372
- const release = entry.pending.then(() => {
373
- entry.active = false;
374
- entry.compilation.dispose();
375
- entry.compilationCache = void 0;
376
- disposeGenerator(entry.generator);
377
- entry.generator = void 0;
378
- entry.generationCache = void 0;
379
- entry.latestSnapshot = void 0;
380
- entry.source = void 0;
381
- entry.sourceInput = void 0;
382
- entry.sourceFingerprint = void 0;
383
- entry.sources = [];
384
- if (notifyEvicted) this.onRootEvicted?.(id);
385
- }).finally(() => {
386
- this.releasing.delete(id);
387
- });
388
- this.releasing.set(id, release);
389
- return release;
390
- }
391
- async dispose() {
392
- await Promise.all([...[...this.roots.keys()].map((id) => this.remove(id)), ...this.releasing.values()]);
393
- this.dependencyRoots.clear();
394
- }
395
- detachDependencies(entry) {
396
- for (const dependency of entry.dependencies) {
397
- const owners = this.dependencyRoots.get(dependency);
398
- owners?.delete(entry.id);
399
- if (owners?.size === 0) this.dependencyRoots.delete(dependency);
400
- }
401
- entry.dependencies.clear();
402
- }
403
- };
404
- function stripSourceQuery(id) {
405
- return id.replace(/[?#].*$/, "");
406
- }
407
- //#endregion
408
- //#region src/core/compiler/snapshot.ts
409
- const readonlySetValues = /* @__PURE__ */ new WeakMap();
410
- const snapshotRegistry = /* @__PURE__ */ new WeakMap();
411
- var ImmutableSetView = class {
412
- constructor(values) {
413
- readonlySetValues.set(this, new Set(values));
414
- Object.freeze(this);
415
- }
416
- get size() {
417
- return this.valuesSet.size;
418
- }
419
- get [Symbol.toStringTag]() {
420
- return "Set";
421
- }
422
- has(value) {
423
- return this.valuesSet.has(value);
424
- }
425
- entries() {
426
- return this.valuesSet.entries();
427
- }
428
- keys() {
429
- return this.valuesSet.keys();
430
- }
431
- values() {
432
- return this.valuesSet.values();
433
- }
434
- forEach(callbackfn, thisArg) {
435
- for (const value of this.valuesSet) callbackfn.call(thisArg, value, value, this);
436
- }
437
- [Symbol.iterator]() {
438
- return this.values();
439
- }
440
- get valuesSet() {
441
- return readonlySetValues.get(this);
442
- }
443
- };
444
- function uniqueSorted(values) {
445
- return Object.freeze([...new Set(values)].sort());
446
- }
447
- function sourceKey(source) {
448
- return `${source.base}\0${source.pattern}\0${source.negated ? "1" : "0"}`;
449
- }
450
- function uniqueSortedSources(sources) {
451
- const values = /* @__PURE__ */ new Map();
452
- for (const source of sources) {
453
- const cloned = Object.freeze({ ...source });
454
- values.set(sourceKey(cloned), cloned);
455
- }
456
- return Object.freeze([...values.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([, value]) => value));
457
- }
458
- function createRootFingerprint(root, target, classSet, dependencies, sources) {
459
- return [
460
- root.id,
461
- String(root.revision),
462
- target,
463
- ...[...classSet].sort(),
464
- ...dependencies,
465
- ...[...sources].map(sourceKey)
466
- ].join("\0");
467
- }
468
- function createSnapshotFromState(state, reusableClassSet, reusableClassSetView) {
469
- const roots = Object.freeze([...state.roots.values()].sort((left, right) => left.id.localeCompare(right.id)).map(({ id, revision }) => Object.freeze({
470
- id,
471
- revision
472
- })));
473
- const classSet = reusableClassSet ?? new Set(state.classSet);
474
- const fingerprint = [
475
- state.target,
476
- ...[...state.roots.values()].map((root) => `${root.id}\0${root.revision}\0${root.fingerprint}`).sort(),
477
- ...[...classSet].sort(),
478
- ...state.dependencies,
479
- ...state.sources.map(sourceKey)
480
- ].join("\0");
481
- const snapshot = Object.freeze({
482
- classSet: reusableClassSetView ?? new ImmutableSetView(classSet),
483
- dependencies: state.dependencies,
484
- roots,
485
- sources: state.sources,
486
- target: state.target
487
- });
488
- snapshotRegistry.set(snapshot, {
489
- ...state,
490
- classSet,
491
- fingerprint
492
- });
493
- return snapshot;
494
- }
495
- function createRegisteredCompilerSnapshot(request, reusableClassSet, reusableClassSetView) {
496
- if (!request.id) throw new Error("Compiler snapshot 的 root id 不能为空。");
497
- const revision = request.revision ?? 0;
498
- if (!Number.isSafeInteger(revision) || revision < 0) throw new Error(`Compiler snapshot revision 必须是非负安全整数:${revision}`);
499
- const target = request.target ?? "weapp";
500
- const classSet = new Set(request.classSet);
501
- const dependencies = uniqueSorted(request.dependencies ?? []);
502
- const sources = uniqueSortedSources(request.sources ?? []);
503
- const root = {
504
- id: request.id,
505
- revision
506
- };
507
- const internalRoot = {
508
- ...root,
509
- fingerprint: createRootFingerprint(root, target, classSet, dependencies, sources)
510
- };
511
- return createSnapshotFromState({
512
- classSet,
513
- dependencies,
514
- roots: /* @__PURE__ */ new Map([[root.id, internalRoot]]),
515
- sources,
516
- target
517
- }, reusableClassSet, reusableClassSetView);
518
- }
519
- function getInternalCompilerSnapshot(snapshot) {
520
- const state = snapshotRegistry.get(snapshot);
521
- if (!state) throw new Error("Compiler snapshot 必须由 createSnapshot()、generate() 或 mergeSnapshots() 创建。");
522
- return state;
523
- }
524
- function mergeRegisteredCompilerSnapshots(snapshots) {
525
- const states = [...snapshots].map(getInternalCompilerSnapshot);
526
- if (states.length === 0) throw new Error("mergeSnapshots() 至少需要一个 snapshot。");
527
- const target = states[0].target;
528
- const roots = /* @__PURE__ */ new Map();
529
- const classSet = /* @__PURE__ */ new Set();
530
- const dependencies = [];
531
- const sources = [];
532
- for (const state of states) {
533
- if (state.target !== target) throw new Error(`不能合并不同 target 的 snapshot:${target} 与 ${state.target}`);
534
- for (const root of state.roots.values()) {
535
- const current = roots.get(root.id);
536
- if (current && current.revision !== root.revision) throw new Error(`同一 root 不能合并不同 revision:${root.id} (${current.revision} / ${root.revision})`);
537
- if (current && current.fingerprint !== root.fingerprint) throw new Error(`同一 root revision 的 snapshot 内容冲突:${root.id}@${root.revision}`);
538
- roots.set(root.id, root);
539
- }
540
- for (const candidate of state.classSet) classSet.add(candidate);
541
- dependencies.push(...state.dependencies);
542
- sources.push(...state.sources);
543
- }
544
- return createSnapshotFromState({
545
- classSet: new Set([...classSet].sort()),
546
- dependencies: uniqueSorted(dependencies),
547
- roots,
548
- sources: uniqueSortedSources(sources),
549
- target
550
- });
551
- }
552
- function createImmutableSet(values) {
553
- return new ImmutableSetView(values);
554
- }
555
- //#endregion
556
- //#region src/cache/index.ts
557
- function isProcessResult(value) {
558
- return typeof value === "object" && value !== null && "result" in value;
559
- }
560
- function createCache(options) {
561
- const disabled = options === false;
562
- const hashMap = /* @__PURE__ */ new Map();
563
- const instance = new lru_cache.LRUCache({
564
- max: 1024,
565
- ttl: 0,
566
- ttlAutopurge: false
567
- });
568
- const cache = {
569
- hashMap,
570
- instance,
571
- hasHashKey(key) {
572
- return hashMap.has(key);
573
- },
574
- getHashValue(key) {
575
- return hashMap.get(key);
576
- },
577
- setHashValue(key, value) {
578
- return hashMap.set(key, value);
579
- },
580
- get(key) {
581
- return instance.get(key);
582
- },
583
- set(key, value) {
584
- return instance.set(key, value);
585
- },
586
- computeHash(message) {
587
- return (0, _weapp_tailwindcss_shared_node.md5)(message);
588
- },
589
- calcHashValueChanged(key, hash) {
590
- const hit = hashMap.get(key);
591
- if (hit) hashMap.set(key, {
592
- changed: hash !== hit.hash,
593
- hash
594
- });
595
- else hashMap.set(key, {
596
- changed: true,
597
- hash
598
- });
599
- return cache;
600
- },
601
- pruneHashKeys(hashKeys) {
602
- const activeHashKeys = new Set(hashKeys);
603
- for (const key of hashMap.keys()) if (!activeHashKeys.has(key)) hashMap.delete(key);
604
- },
605
- prune(options) {
606
- if (options.cacheKeys) {
607
- const cacheKeys = new Set(options.cacheKeys);
608
- for (const key of instance.keys()) if (!cacheKeys.has(key)) instance.delete(key);
609
- }
610
- if (options.hashKeys) cache.pruneHashKeys?.(options.hashKeys);
611
- },
612
- has(key) {
613
- return instance.has(key);
614
- },
615
- async process({ key, hashKey, rawSource, hash, resolveCache, transform, onCacheHit }) {
616
- if (disabled) {
617
- const value = await transform();
618
- return isProcessResult(value) ? value.result : value;
619
- }
620
- const cacheHashKey = hashKey ?? key;
621
- let hasChanged = true;
622
- if (hash != null || rawSource != null) {
623
- const nextHash = hash ?? cache.computeHash(rawSource);
624
- cache.calcHashValueChanged(cacheHashKey, nextHash);
625
- hasChanged = cache.getHashValue(cacheHashKey)?.changed ?? true;
626
- }
627
- const readCache = resolveCache ?? (() => cache.get(key));
628
- if (!hasChanged) {
629
- const cached = readCache();
630
- if (cached !== void 0) {
631
- await onCacheHit?.(cached);
632
- return cached;
633
- }
634
- }
635
- const value = await transform();
636
- const normalized = isProcessResult(value) ? value : { result: value };
637
- const stored = normalized.cacheValue ?? normalized.result;
638
- cache.set(key, stored);
639
- return normalized.result;
640
- }
641
- };
642
- return cache;
643
- }
644
- function initializeCache(cacheConfig) {
645
- if (typeof cacheConfig === "boolean" || cacheConfig === void 0) return createCache(cacheConfig);
646
- return cacheConfig;
647
- }
648
- //#endregion
649
- //#region src/framework/platform.ts
650
- const MPX_TO_UNI_PLATFORM = {
651
- ali: "mp-alipay",
652
- dd: "mp-dingtalk",
653
- jd: "mp-jd",
654
- qq: "mp-qq",
655
- swan: "mp-baidu",
656
- tt: "mp-toutiao",
657
- wx: "mp-weixin"
658
- };
659
- function normalizeFrameworkStylePlatform(platform, appType) {
660
- const normalized = platform?.trim().toLowerCase();
661
- if (!normalized) return;
662
- if (appType === "mpx") return MPX_TO_UNI_PLATFORM[normalized] ?? normalized;
663
- return normalized;
664
- }
665
- //#endregion
666
- //#region src/tailwindcss/runtime.ts
667
- const debug = require_wxml.createDebug("[tailwindcss:runtime] ");
668
- const refreshTailwindcssRuntimeSymbol = Symbol.for("weapp-tailwindcss.refreshTailwindcssRuntime");
669
- function createTailwindRuntimeReadyPromise(tailwindRuntime) {
670
- return Promise.resolve().then(async () => {
671
- require_tailwindcss.invalidateRuntimeClassSet(tailwindRuntime);
672
- });
673
- }
674
- const runtimeClassSetStateCache = /* @__PURE__ */ new WeakMap();
675
- function getRuntimeClassSetStateEntry(state) {
676
- let entry = runtimeClassSetStateCache.get(state);
677
- if (!entry) {
678
- entry = {};
679
- runtimeClassSetStateCache.set(state, entry);
680
- }
681
- return entry;
682
- }
683
- function getTailwindRuntime(state) {
684
- return state.tailwindRuntime;
685
- }
686
- function setTailwindRuntime(state, runtime) {
687
- state.tailwindRuntime = runtime;
688
- }
689
- function getRefreshTailwindRuntime(state) {
690
- return state.refreshTailwindcssRuntime;
691
- }
692
- async function refreshTailwindRuntimeState(state, forceOrOptions) {
693
- const normalizedOptions = typeof forceOrOptions === "boolean" ? { force: forceOrOptions } : forceOrOptions;
694
- const force = normalizedOptions.force;
695
- const clearCache = normalizedOptions.clearCache === true;
696
- if (!force) return false;
697
- const currentRuntime = getTailwindRuntime(state);
698
- debug("refresh runtime state start, clearCache=%s major=%s", clearCache, currentRuntime.majorVersion ?? "unknown");
699
- await state.readyPromise;
700
- let refreshed = false;
701
- const refreshTailwindRuntime = getRefreshTailwindRuntime(state);
702
- if (typeof refreshTailwindRuntime === "function") {
703
- const next = await refreshTailwindRuntime({ clearCache });
704
- if (next !== getTailwindRuntime(state)) setTailwindRuntime(state, next);
705
- refreshed = true;
706
- }
707
- if (refreshed) state.readyPromise = createTailwindRuntimeReadyPromise(getTailwindRuntime(state));
708
- debug("refresh runtime state end, refreshed=%s major=%s", refreshed, getTailwindRuntime(state).majorVersion ?? "unknown");
709
- return refreshed;
710
- }
711
- async function ensureRuntimeClassSet(state, options = {}) {
712
- const forceRefresh = options.forceRefresh === true;
713
- const forceCollect = options.forceCollect === true;
714
- const clearCache = options.clearCache === true;
715
- const allowEmpty = options.allowEmpty === true;
716
- if (forceRefresh) await refreshTailwindRuntimeState(state, {
717
- force: true,
718
- clearCache
719
- });
720
- await state.readyPromise;
721
- const entry = getRuntimeClassSetStateEntry(state);
722
- const signature = await require_tailwindcss.getRuntimeClassSetSignatureWithSources(getTailwindRuntime(state));
723
- const signatureChanged = entry.signature !== signature;
724
- const shouldForceCollect = forceCollect || forceRefresh || signatureChanged;
725
- if (!shouldForceCollect) {
726
- if (entry.value && (allowEmpty || entry.value.size > 0)) return entry.value;
727
- if (entry.promise) return entry.promise;
728
- }
729
- const task = (async () => {
730
- const collected = await collectRuntimeClassSet(getTailwindRuntime(state), {
731
- force: shouldForceCollect,
732
- skipRefresh: true,
733
- clearCache
734
- });
735
- if (allowEmpty || collected.size > 0) return collected;
736
- await refreshTailwindRuntimeState(state, {
737
- force: true,
738
- clearCache: true
739
- });
740
- await state.readyPromise;
741
- return collectRuntimeClassSet(getTailwindRuntime(state), {
742
- force: true,
743
- skipRefresh: true,
744
- clearCache: true
745
- });
746
- })();
747
- entry.promise = task;
748
- try {
749
- const runtimeSet = await task;
750
- entry.value = runtimeSet;
751
- entry.signature = await require_tailwindcss.getRuntimeClassSetSignatureWithSources(getTailwindRuntime(state));
752
- return runtimeSet;
753
- } finally {
754
- if (entry.promise === task) entry.promise = void 0;
755
- }
756
- }
757
- function tryGetRuntimeClassSetSync(tailwindRuntime) {
758
- if (typeof tailwindRuntime.getClassSetSync !== "function") return;
759
- try {
760
- const set = tailwindRuntime.getClassSetSync();
761
- if (set && set.size === 0) return;
762
- return set;
763
- } catch (error) {
764
- debug("getClassSetSync() unavailable for tailwindcss v4, fallback to async getClassSet(): %O", error);
765
- return;
766
- }
767
- }
768
- async function collectTailwindV4GeneratorClassSet(tailwindRuntime) {
769
- if (typeof tailwindRuntime.collectContentTokens !== "function") return;
770
- try {
771
- const source = require_generator.resolveCssMacroTailwindV4Source(await require_generator.resolveTailwindV4SourceFromRuntime(tailwindRuntime));
772
- const generated = await require_generator.createTailwindV4Engine(source).generate({
773
- scanSources: true,
774
- target: "web"
775
- });
776
- const designSystem = await (0, _tailwindcss_mangle_engine.loadTailwindV4DesignSystem)(source);
777
- const classSet = (0, _tailwindcss_mangle_engine.resolveValidTailwindV4Candidates)(designSystem, generated.classSet, { ...source.bareArbitraryValues === void 0 ? {} : { bareArbitraryValues: source.bareArbitraryValues } });
778
- debug("runtime class set resolved via tailwindcss v4 generator source scan, raw=%d valid=%d", generated.classSet.size, classSet.size);
779
- return classSet;
780
- } catch (error) {
781
- debug("tailwindcss v4 generator source scan failed, continuing fallback chain: %O", error);
782
- return;
783
- }
784
- }
785
- async function mergeTailwindV4GeneratorClassSet(tailwindRuntime, classSet) {
786
- const generatorClassSet = await collectTailwindV4GeneratorClassSet(tailwindRuntime).catch(() => void 0);
787
- if (!generatorClassSet || generatorClassSet.size === 0) return classSet;
788
- return /* @__PURE__ */ new Set([...classSet, ...generatorClassSet]);
789
- }
790
- async function collectRuntimeClassSet(tailwindRuntime, options = {}) {
791
- let activeRuntime = tailwindRuntime;
792
- if (options.force && !options.skipRefresh) {
793
- const refresh = activeRuntime[refreshTailwindcssRuntimeSymbol];
794
- if (typeof refresh === "function") try {
795
- const refreshed = await refresh({ clearCache: options.clearCache === true });
796
- if (refreshed) activeRuntime = refreshed;
797
- } catch (error) {
798
- debug("refreshTailwindcssRuntime failed, continuing with existing runtime: %O", error);
799
- }
800
- }
801
- const entry = require_tailwindcss.getRuntimeClassSetCacheEntry(activeRuntime);
802
- const signature = await require_tailwindcss.getRuntimeClassSetSignatureWithSources(activeRuntime);
803
- if (!options.force) {
804
- if (entry.value && entry.signature === signature) return entry.value;
805
- if (entry.promise) return entry.promise;
806
- } else entry.value = void 0;
807
- const task = (async () => {
808
- const preferExtract = options.force === true;
809
- try {
810
- const result = await activeRuntime.extract({ write: false });
811
- if (result?.classSet) {
812
- if (result.classSet.size > 0) {
813
- const merged = await mergeTailwindV4GeneratorClassSet(activeRuntime, result.classSet);
814
- debug("runtime class set resolved via extract() + tailwindcss v4 source scan, extract=%d merged=%d", result.classSet.size, merged.size);
815
- return merged;
816
- }
817
- if (preferExtract) debug("runtime class set from extract() is empty on force collect, fallback to generator/sync/async class set");
818
- else debug("runtime class set from extract() is empty, fallback to sync/async class set");
819
- }
820
- } catch (error) {
821
- debug("extract() failed, fallback to getClassSet(): %O", error);
822
- }
823
- const generatorClassSet = await collectTailwindV4GeneratorClassSet(activeRuntime);
824
- if (generatorClassSet && generatorClassSet.size > 0) return generatorClassSet;
825
- const syncSet = tryGetRuntimeClassSetSync(activeRuntime);
826
- if (syncSet) {
827
- debug("runtime class set resolved via getClassSetSync(), size=%d", syncSet.size);
828
- return syncSet;
829
- }
830
- try {
831
- const fallbackSet = await Promise.resolve(activeRuntime.getClassSet());
832
- if (fallbackSet) {
833
- debug("runtime class set resolved via getClassSet(), size=%d", fallbackSet.size);
834
- return fallbackSet;
835
- }
836
- } catch (error) {
837
- debug("getClassSet() failed, returning empty set: %O", error);
838
- }
839
- return /* @__PURE__ */ new Set();
840
- })();
841
- entry.promise = task;
842
- entry.signature = signature;
843
- try {
844
- const resolved = await task;
845
- entry.value = resolved;
846
- entry.promise = void 0;
847
- entry.signature = signature;
848
- return resolved;
849
- } catch (error) {
850
- entry.promise = void 0;
851
- throw error;
852
- }
853
- }
854
- //#endregion
855
- //#region src/tailwindcss/runtime-logs.ts
856
- const runtimeLogDedupeHolder = globalThis;
857
- const runtimeLogDedupe = runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ ?? (runtimeLogDedupeHolder.__WEAPP_TW_RUNTIME_LOG_DEDUPE__ = /* @__PURE__ */ new Set());
858
- function createRuntimeLogKey(category, baseDir, rootPath, version) {
859
- return JSON.stringify([
860
- category,
861
- baseDir ?? node_process.default.cwd(),
862
- rootPath ?? "",
863
- version ?? ""
864
- ]);
865
- }
866
- function markRuntimeLog(category, baseDir, rootPath, version) {
867
- const key = createRuntimeLogKey(category, baseDir, rootPath, version);
868
- if (runtimeLogDedupe.has(key)) return false;
869
- runtimeLogDedupe.add(key);
870
- return true;
871
- }
872
- function logRuntimeTailwindcssTarget(baseDir, rootPath, version) {
873
- if (!markRuntimeLog("target", baseDir, rootPath, version)) return;
874
- const versionText = version ? ` (v${version})` : "";
875
- _weapp_tailwindcss_logger.logger.info("%s 使用 Tailwind CSS%s", "Weapp-tailwindcss", versionText);
876
- }
877
- function logRuntimeTailwindcssVersion(baseDir, rootPath, version) {
878
- if (version) {
879
- if (!markRuntimeLog("version", baseDir, rootPath, version)) return;
880
- _weapp_tailwindcss_logger.logger.success(`当前使用 ${_weapp_tailwindcss_logger.pc.cyanBright("Tailwind CSS")} 版本为: ${_weapp_tailwindcss_logger.pc.underline(_weapp_tailwindcss_logger.pc.bold(_weapp_tailwindcss_logger.pc.green(version)))}`);
881
- return;
882
- }
883
- if (!markRuntimeLog("missing", baseDir, rootPath, version)) return;
884
- _weapp_tailwindcss_logger.logger.warn(`${_weapp_tailwindcss_logger.pc.cyanBright("Tailwind CSS")} 未安装,已跳过版本检测与运行时初始化。`);
885
- }
886
- //#endregion
887
- //#region src/tailwindcss/targets.ts
888
- function formatRelativeToBase(targetPath, baseDir) {
889
- const normalized = node_path.default.normalize(targetPath);
890
- if (!baseDir) return normalized.replace(/\\/g, "/");
891
- const relative = node_path.default.relative(baseDir, normalized);
892
- if (!relative || relative === ".") return ".";
893
- if (relative.startsWith("..")) return normalized.replace(/\\/g, "/");
894
- return node_path.default.join(".", relative).replace(/\\/g, "/");
895
- }
896
- function logTailwindcssTarget(tailwindRuntime, baseDir) {
897
- const packageInfo = tailwindRuntime?.packageInfo;
898
- const label = "Weapp-tailwindcss";
899
- if (!packageInfo?.rootPath) {
900
- _weapp_tailwindcss_logger.logger.warn("%s 未找到 Tailwind CSS 依赖,请检查在 %s 是否已安装 tailwindcss", label, baseDir ?? node_process.default.cwd());
901
- return;
902
- }
903
- const displayPath = formatRelativeToBase(packageInfo.rootPath, baseDir);
904
- const version = packageInfo.version ? ` (v${packageInfo.version})` : "";
905
- logRuntimeTailwindcssTarget(baseDir, packageInfo.rootPath, packageInfo.version);
906
- _weapp_tailwindcss_logger.logger.debug("%s 解析 Tailwind CSS -> %s%s", label, displayPath, version);
907
- }
908
- //#endregion
909
- //#region src/unocss/index.ts
910
- function normalizeUnocssOptions(unocss) {
911
- return require_generator.resolveBooleanObjectOption(unocss, {});
912
- }
913
- function resolveUnocssBareArbitraryValues(arbitraryValues, unocss) {
914
- const baseArbitraryValues = arbitraryValues ?? {};
915
- const options = normalizeUnocssOptions(unocss);
916
- if (!options) return baseArbitraryValues;
917
- if (baseArbitraryValues.bareArbitraryValues !== void 0 && baseArbitraryValues.bareArbitraryValues !== false) return baseArbitraryValues;
918
- const bareArbitraryValues = options.bareArbitraryValues ?? true;
919
- if (bareArbitraryValues === false) return baseArbitraryValues;
920
- return {
921
- ...baseArbitraryValues,
922
- bareArbitraryValues
923
- };
924
- }
925
- //#endregion
926
- //#region src/context/compiler-context-cache.ts
927
- const PAREN_CONTENT_RE = /\(([^)]+)\)/u;
928
- const AT_LOCATION_RE = /at\s+(\S.*)$/u;
929
- const TRAILING_LINE_COL_RE = /:\d+(?::\d+)?$/u;
930
- const DEFAULT_COMPILER_CONTEXT_CACHE_MAX = 32;
931
- const DEFAULT_COMPILER_CONTEXT_KEY_CACHE_MAX = 64;
932
- const globalCacheHolder = globalThis;
933
- const compilerContextCache = globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ ?? (globalCacheHolder.__WEAPP_TW_COMPILER_CONTEXT_CACHE__ = /* @__PURE__ */ new Map());
934
- const compilerContextKeyCacheByOptions = /* @__PURE__ */ new WeakMap();
935
- const compilerContextKeyCacheWithoutOptions = /* @__PURE__ */ new Map();
936
- function resolveCompilerContextCacheMax(defaultValue) {
937
- const raw = Number.parseInt(node_process.default.env["WEAPP_TW_COMPILER_CONTEXT_CACHE_MAX"] ?? "", 10);
938
- if (!Number.isFinite(raw) || raw <= 0) return defaultValue;
939
- return Math.floor(raw);
940
- }
941
- function touchMapValue(map, key, value) {
942
- map.delete(key);
943
- map.set(key, value);
944
- }
945
- function pruneMapToMaxSize(map, maxSize) {
946
- while (map.size > maxSize) {
947
- const firstKey = map.keys().next().value;
948
- if (firstKey === void 0) break;
949
- map.delete(firstKey);
950
- }
951
- }
952
- function withCircularGuard(value, stack, factory) {
953
- if (stack.has(value)) throw new TypeError("Cannot serialize circular structure in compiler context options");
954
- stack.add(value);
955
- try {
956
- return factory();
957
- } finally {
958
- stack.delete(value);
959
- }
960
- }
961
- function encodeTaggedValue(type, value) {
962
- const record = { __type: type };
963
- if (value !== void 0) record["value"] = value;
964
- return record;
965
- }
966
- function hasExplicitOptionBasedir(opts) {
967
- return typeof opts?.tailwindcssBasedir === "string" && opts.tailwindcssBasedir.length > 0;
968
- }
969
- function shouldProbeCallerLocation(opts) {
970
- if (hasExplicitOptionBasedir(opts)) return false;
971
- return !(node_process.default.env["WEAPP_TAILWINDCSS_BASEDIR"] || node_process.default.env["WEAPP_TAILWINDCSS_BASE_DIR"] || node_process.default.env["TAILWINDCSS_BASEDIR"] || node_process.default.env["TAILWINDCSS_BASE_DIR"]);
972
- }
973
- function detectCallerLocation() {
974
- const stack = (/* @__PURE__ */ new Error("compiler-context-cache stack probe")).stack;
975
- if (!stack) return;
976
- const lines = stack.split("\n");
977
- for (const line of lines) {
978
- const location = (line.match(PAREN_CONTENT_RE) ?? line.match(AT_LOCATION_RE))?.[1];
979
- if (!location) continue;
980
- const candidatePath = location.replace(TRAILING_LINE_COL_RE, "");
981
- if (!candidatePath || !node_path.default.isAbsolute(candidatePath)) continue;
982
- if (candidatePath.includes(`${node_path.default.sep}weapp-tailwindcss${node_path.default.sep}src${node_path.default.sep}`) || candidatePath.includes(`${node_path.default.sep}weapp-tailwindcss${node_path.default.sep}dist${node_path.default.sep}`) || candidatePath.includes(`${node_path.default.sep}node_modules${node_path.default.sep}weapp-tailwindcss${node_path.default.sep}`)) continue;
983
- return candidatePath;
984
- }
985
- }
986
- function getRuntimeCacheScope(opts) {
987
- if (hasExplicitOptionBasedir(opts)) return { caller: void 0 };
988
- const runtimeScope = {
989
- caller: void 0,
990
- cwd: node_process.default.cwd(),
991
- init_cwd: node_process.default.env["INIT_CWD"],
992
- npm_config_local_prefix: node_process.default.env["npm_config_local_prefix"],
993
- npm_package_json: node_process.default.env["npm_package_json"],
994
- pnpm_package_name: node_process.default.env["PNPM_PACKAGE_NAME"],
995
- pwd: node_process.default.env["PWD"],
996
- tailwindcss_base_dir: node_process.default.env["TAILWINDCSS_BASE_DIR"],
997
- tailwindcss_basedir: node_process.default.env["TAILWINDCSS_BASEDIR"],
998
- uni_app_input_dir: node_process.default.env["UNI_APP_INPUT_DIR"],
999
- uni_cli_root: node_process.default.env["UNI_CLI_ROOT"],
1000
- uni_input_dir: node_process.default.env["UNI_INPUT_DIR"],
1001
- uni_input_root: node_process.default.env["UNI_INPUT_ROOT"],
1002
- weapp_tailwindcss_base_dir: node_process.default.env["WEAPP_TAILWINDCSS_BASE_DIR"],
1003
- weapp_tailwindcss_basedir: node_process.default.env["WEAPP_TAILWINDCSS_BASEDIR"]
1004
- };
1005
- if (shouldProbeCallerLocation(opts)) runtimeScope.caller = detectCallerLocation();
1006
- return runtimeScope;
1007
- }
1008
- function serializeNormalizedValue(value) {
1009
- return JSON.stringify(value);
1010
- }
1011
- function createRuntimeCacheScopeKey(opts) {
1012
- return serializeNormalizedValue(normalizeOptionsValue(getRuntimeCacheScope(opts)));
1013
- }
1014
- function getCompilerContextKeyCacheStore(opts) {
1015
- if (!opts) return compilerContextKeyCacheWithoutOptions;
1016
- let store = compilerContextKeyCacheByOptions.get(opts);
1017
- if (!store) {
1018
- store = /* @__PURE__ */ new Map();
1019
- compilerContextKeyCacheByOptions.set(opts, store);
1020
- }
1021
- return store;
1022
- }
1023
- function createComparableNormalizedValue(rawValue, stack) {
1024
- const normalized = normalizeOptionsValue(rawValue, stack);
1025
- return {
1026
- normalized,
1027
- sortKey: serializeNormalizedValue(normalized)
1028
- };
1029
- }
1030
- function getRuntimeCacheScopeValue(opts) {
1031
- return {
1032
- options: opts ?? {},
1033
- runtime: getRuntimeCacheScope(opts)
1034
- };
1035
- }
1036
- function normalizeOptionsValue(rawValue, stack = /* @__PURE__ */ new WeakSet()) {
1037
- if (rawValue === null) return null;
1038
- if (rawValue === void 0) return encodeTaggedValue("Undefined");
1039
- const type = typeof rawValue;
1040
- if (type === "string") return rawValue;
1041
- if (type === "boolean") return rawValue;
1042
- if (type === "number") {
1043
- const numericValue = rawValue;
1044
- if (Number.isNaN(numericValue)) return encodeTaggedValue("Number", "NaN");
1045
- if (!Number.isFinite(numericValue)) return encodeTaggedValue("Number", numericValue > 0 ? "Infinity" : "-Infinity");
1046
- if (Object.is(numericValue, -0)) return encodeTaggedValue("Number", "-0");
1047
- return numericValue;
1048
- }
1049
- if (type === "bigint") return encodeTaggedValue("BigInt", rawValue.toString());
1050
- if (type === "symbol") {
1051
- const symbolValue = rawValue;
1052
- return encodeTaggedValue("Symbol", symbolValue.description ?? String(symbolValue));
1053
- }
1054
- if (type === "function") return encodeTaggedValue("Function", rawValue.toString());
1055
- if (Array.isArray(rawValue)) return withCircularGuard(rawValue, stack, () => rawValue.map((item) => normalizeOptionsValue(item, stack)));
1056
- if (rawValue instanceof Date) return encodeTaggedValue("Date", rawValue.toISOString());
1057
- if (rawValue instanceof RegExp) return {
1058
- __type: "RegExp",
1059
- source: rawValue.source,
1060
- flags: rawValue.flags
1061
- };
1062
- if (typeof node_buffer.Buffer !== "undefined" && node_buffer.Buffer.isBuffer(rawValue)) return encodeTaggedValue("Buffer", rawValue.toString("base64"));
1063
- if (ArrayBuffer.isView(rawValue)) {
1064
- const view = rawValue;
1065
- const buffer = node_buffer.Buffer.from(view.buffer, view.byteOffset, view.byteLength);
1066
- return encodeTaggedValue(view.constructor?.name ?? "ArrayBufferView", buffer.toString("base64"));
1067
- }
1068
- if (rawValue instanceof ArrayBuffer) return encodeTaggedValue("ArrayBuffer", node_buffer.Buffer.from(rawValue).toString("base64"));
1069
- if (rawValue instanceof Set) return withCircularGuard(rawValue, stack, () => {
1070
- const normalizedEntries = Array.from(rawValue, (element) => createComparableNormalizedValue(element, stack));
1071
- normalizedEntries.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
1072
- return {
1073
- __type: "Set",
1074
- value: normalizedEntries.map((entry) => entry.normalized)
1075
- };
1076
- });
1077
- if (rawValue instanceof Map) return withCircularGuard(rawValue, stack, () => {
1078
- const normalizedEntries = Array.from(rawValue.entries(), ([key, entryValue]) => {
1079
- const normalizedKey = createComparableNormalizedValue(key, stack);
1080
- return {
1081
- key: normalizedKey.normalized,
1082
- sortKey: normalizedKey.sortKey,
1083
- value: normalizeOptionsValue(entryValue, stack)
1084
- };
1085
- });
1086
- normalizedEntries.sort((a, b) => a.sortKey.localeCompare(b.sortKey));
1087
- return {
1088
- __type: "Map",
1089
- value: normalizedEntries.map((entry) => [entry.key, entry.value])
1090
- };
1091
- });
1092
- if (typeof URL !== "undefined" && rawValue instanceof URL) return encodeTaggedValue("URL", rawValue.toString());
1093
- if (rawValue instanceof Error) {
1094
- const errorValue = rawValue;
1095
- return {
1096
- __type: "Error",
1097
- name: errorValue.name,
1098
- message: errorValue.message,
1099
- stack: errorValue.stack ?? ""
1100
- };
1101
- }
1102
- if (rawValue instanceof Promise) return encodeTaggedValue("Promise");
1103
- if (rawValue instanceof WeakMap) return encodeTaggedValue("WeakMap");
1104
- if (rawValue instanceof WeakSet) return encodeTaggedValue("WeakSet");
1105
- if (rawValue && typeof rawValue === "object") return withCircularGuard(rawValue, stack, () => {
1106
- const result = {};
1107
- const entries = Object.entries(rawValue);
1108
- entries.sort(([a], [b]) => a.localeCompare(b));
1109
- for (const [key, entryValue] of entries) result[key] = normalizeOptionsValue(entryValue, stack);
1110
- return result;
1111
- });
1112
- return encodeTaggedValue(typeof rawValue, String(rawValue));
1113
- }
1114
- function createCompilerContextCacheKey(opts) {
1115
- try {
1116
- const runtimeCacheScopeKey = createRuntimeCacheScopeKey(opts);
1117
- const keyStore = getCompilerContextKeyCacheStore(opts);
1118
- const cached = keyStore.get(runtimeCacheScopeKey);
1119
- if (cached !== void 0) return cached;
1120
- const normalized = normalizeOptionsValue(getRuntimeCacheScopeValue(opts));
1121
- const cacheKey = (0, _weapp_tailwindcss_shared_node.md5)(serializeNormalizedValue(normalized));
1122
- touchMapValue(keyStore, runtimeCacheScopeKey, cacheKey);
1123
- pruneMapToMaxSize(keyStore, resolveCompilerContextCacheMax(DEFAULT_COMPILER_CONTEXT_KEY_CACHE_MAX));
1124
- return cacheKey;
1125
- } catch (error) {
1126
- _weapp_tailwindcss_logger.logger.debug("skip compiler context cache: %O", error);
1127
- return;
1128
- }
1129
- }
1130
- function withCompilerContextCache(opts, factory) {
1131
- const cacheKey = createCompilerContextCacheKey(opts);
1132
- if (cacheKey) {
1133
- const cached = compilerContextCache.get(cacheKey);
1134
- if (cached) {
1135
- touchMapValue(compilerContextCache, cacheKey, cached);
1136
- return cached;
1137
- }
1138
- }
1139
- const ctx = factory();
1140
- if (cacheKey) {
1141
- touchMapValue(compilerContextCache, cacheKey, ctx);
1142
- pruneMapToMaxSize(compilerContextCache, resolveCompilerContextCacheMax(DEFAULT_COMPILER_CONTEXT_CACHE_MAX));
1143
- }
1144
- return ctx;
1145
- }
1146
- //#endregion
1147
- //#region src/context/custom-attributes.ts
1148
- function toCustomAttributesEntities(customAttributes) {
1149
- if (!customAttributes) return [];
1150
- if ((0, _weapp_tailwindcss_shared.isMap)(customAttributes)) return [...customAttributes.entries()];
1151
- return Object.entries(customAttributes);
1152
- }
1153
- //#endregion
1154
- //#region ../../node_modules/.pnpm/oxc-walker@1.1.1_@oxc-project+types@0.147.0_oxc-parser@0.147.0_rolldown@1.2.3/node_modules/oxc-walker/dist/index.mjs
1155
- function isNode(v) {
1156
- return v !== null && typeof v === "object" && typeof v.type === "string";
1157
- }
1158
- var WalkerBase = class {
1159
- constructor(handler, options) {
1160
- require_object._defineProperty(this, "scopeTracker", void 0);
1161
- require_object._defineProperty(this, "enter", void 0);
1162
- require_object._defineProperty(this, "leave", void 0);
1163
- require_object._defineProperty(this, "contextEnter", {
1164
- skip: () => {
1165
- this._skip = true;
1166
- },
1167
- remove: () => {
1168
- this._remove = true;
1169
- },
1170
- replace: (node) => {
1171
- this._replacement = node;
1172
- }
1173
- });
1174
- require_object._defineProperty(this, "contextLeave", {
1175
- remove: this.contextEnter.remove,
1176
- replace: this.contextEnter.replace
1177
- });
1178
- require_object._defineProperty(this, "_skip", false);
1179
- require_object._defineProperty(this, "_remove", false);
1180
- require_object._defineProperty(this, "_replacement", null);
1181
- this.enter = handler.enter;
1182
- this.leave = handler.leave;
1183
- this.scopeTracker = options?.scopeTracker;
1184
- }
1185
- replace(parent, key, index, node) {
1186
- if (!parent || key === null) return;
1187
- if (index !== null) parent[key][index] = node;
1188
- else parent[key] = node;
1189
- }
1190
- insert(parent, key, index, node) {
1191
- if (!parent || key === null) return;
1192
- if (index !== null) parent[key].splice(index, 0, node);
1193
- else parent[key] = node;
1194
- }
1195
- remove(parent, key, index) {
1196
- if (!parent || key === null) return;
1197
- if (index !== null) parent[key].splice(index, 1);
1198
- else delete parent[key];
1199
- }
1200
- };
1201
- var WalkerSync = class extends WalkerBase {
1202
- constructor(handler, options) {
1203
- super(handler, options);
1204
- }
1205
- traverse(input, key, index, parent) {
1206
- const ctx = {
1207
- key: null,
1208
- index: index ?? null,
1209
- ast: input
1210
- };
1211
- const scopeTracker = this.scopeTracker;
1212
- const enter = this.enter;
1213
- const leave = this.leave;
1214
- const contextEnter = this.contextEnter;
1215
- const contextLeave = this.contextLeave;
1216
- const _walk = (input, parent, key, index, skip) => {
1217
- if (scopeTracker) scopeTracker.processNodeEnter(input);
1218
- let currentNode = input;
1219
- let removedInEnter = false;
1220
- let replacedInEnter = false;
1221
- let skipChildren = skip;
1222
- if (enter && !skip) {
1223
- const _skip = this._skip;
1224
- const _remove = this._remove;
1225
- const _replacement = this._replacement;
1226
- this._skip = false;
1227
- this._remove = false;
1228
- this._replacement = null;
1229
- ctx.key = key;
1230
- ctx.index = index;
1231
- enter.call(contextEnter, input, parent, ctx);
1232
- if (this._replacement && !this._remove) {
1233
- currentNode = this._replacement;
1234
- replacedInEnter = true;
1235
- this.replace(parent, key, index, this._replacement);
1236
- if (scopeTracker) scopeTracker.processNodeEnter(currentNode);
1237
- }
1238
- if (this._remove) {
1239
- removedInEnter = true;
1240
- currentNode = null;
1241
- this.remove(parent, key, index);
1242
- }
1243
- if (this._skip) skipChildren = true;
1244
- this._skip = _skip;
1245
- this._remove = _remove;
1246
- this._replacement = _replacement;
1247
- }
1248
- if ((!skipChildren || scopeTracker) && currentNode) for (const k in currentNode) {
1249
- if (k === "type" || k === "start" || k === "end") continue;
1250
- const node = currentNode[k];
1251
- if (!node || typeof node !== "object") continue;
1252
- if (Array.isArray(node)) for (let i = 0; i < node.length; i++) {
1253
- const child = node[i];
1254
- if (isNode(child)) {
1255
- if (_walk(child, currentNode, k, i, skipChildren) === null) i--;
1256
- }
1257
- }
1258
- else if (typeof node.type === "string") _walk(node, currentNode, k, null, skipChildren);
1259
- }
1260
- if (scopeTracker) {
1261
- if (replacedInEnter) scopeTracker.processNodeLeave(currentNode);
1262
- scopeTracker.processNodeLeave(input);
1263
- }
1264
- if (leave && !skip) {
1265
- const _replacement = this._replacement;
1266
- const _remove = this._remove;
1267
- this._replacement = null;
1268
- this._remove = false;
1269
- ctx.key = key;
1270
- ctx.index = index;
1271
- leave.call(contextLeave, input, parent, ctx);
1272
- if (this._replacement && !this._remove) {
1273
- currentNode = this._replacement;
1274
- if (removedInEnter) this.insert(parent, key, index, this._replacement);
1275
- else this.replace(parent, key, index, this._replacement);
1276
- }
1277
- if (this._remove) {
1278
- currentNode = null;
1279
- this.remove(parent, key, index);
1280
- }
1281
- this._replacement = _replacement;
1282
- this._remove = _remove;
1283
- }
1284
- return currentNode;
1285
- };
1286
- if (!isNode(input)) return null;
1287
- if (scopeTracker) scopeTracker.onWalkStart(input);
1288
- if (scopeTracker && !enter && !leave) {
1289
- const _walkScopesOnly = (input) => {
1290
- scopeTracker.processNodeEnter(input);
1291
- for (const k in input) {
1292
- if (k === "type" || k === "start" || k === "end") continue;
1293
- const node = input[k];
1294
- if (!node || typeof node !== "object") continue;
1295
- if (Array.isArray(node)) for (let i = 0; i < node.length; i++) {
1296
- const child = node[i];
1297
- if (isNode(child)) _walkScopesOnly(child);
1298
- }
1299
- else if (typeof node.type === "string") _walkScopesOnly(node);
1300
- }
1301
- scopeTracker.processNodeLeave(input);
1302
- };
1303
- _walkScopesOnly(input);
1304
- return input;
1305
- }
1306
- return _walk(input, parent ?? null, key ?? null, index ?? null, false);
1307
- }
1308
- };
1309
- /**
1310
- * Walk the AST with the given options.
1311
- * @param input The AST to walk.
1312
- * @param options The options to be used when walking the AST. Here you can specify the callbacks for entering and leaving nodes, as well as other options.
1313
- */
1314
- function walk(input, options) {
1315
- return new WalkerSync({
1316
- enter: options.enter,
1317
- leave: options.leave
1318
- }, { scopeTracker: options.scopeTracker }).traverse(input);
1319
- }
1320
- //#endregion
1321
- //#region src/js/literal-transform.ts
1322
- function transformLiteralText(literal, options, classContext = true) {
1323
- if (!options.alwaysEscape && (!options.classNameSet || options.classNameSet.size === 0)) return;
1324
- const source = options.unescapeUnicode && literal.includes("\\u") ? require_wxml.decodeUnicode2(literal) : literal;
1325
- const candidates = (0, _tailwindcss_mangle_engine.splitCandidateTokens)(source);
1326
- if (candidates.length === 0) return;
1327
- const transformOptions = {
1328
- ...options,
1329
- classContext
1330
- };
1331
- const replacementCache = require_wxml.getReplacementCacheStore(options.escapeMap);
1332
- let transformed = source;
1333
- let mutated = false;
1334
- for (const candidate of candidates) {
1335
- const result = require_wxml.resolveClassNameTransformWithResult(candidate, transformOptions);
1336
- if (result.decision === "skip" || !transformed.includes(candidate)) continue;
1337
- const replacement = result.decision === "escaped" && result.escapedValue ? result.escapedValue : require_wxml.getReplacement(candidate, options.escapeMap, replacementCache);
1338
- const replaced = transformed.replace(candidate, replacement);
1339
- if (replaced !== transformed) {
1340
- transformed = replaced;
1341
- mutated = true;
1342
- }
1343
- }
1344
- return mutated ? transformed : void 0;
1345
- }
1346
- //#endregion
1347
- //#region src/js/fast-path/oxc.ts
1348
- const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
1349
- let oxcParser;
1350
- function isOxcParserRuntimeSupported(version = node_process.default.versions.node) {
1351
- const match = /^(\d+)\.(\d+)(?:\.|$)/.exec(version);
1352
- if (!match) return false;
1353
- const major = Number(match[1]);
1354
- const minor = Number(match[2]);
1355
- if (major === 20) return minor >= 19;
1356
- if (major === 21) return false;
1357
- if (major === 22) return minor >= 12;
1358
- return major > 22;
1359
- }
1360
- function loadOxcParser() {
1361
- if (!isOxcParserRuntimeSupported()) return;
1362
- if (oxcParser === false) return;
1363
- if (oxcParser) return oxcParser;
1364
- try {
1365
- oxcParser = require$1("oxc-parser");
1366
- } catch {
1367
- oxcParser = false;
1368
- return;
1369
- }
1370
- return oxcParser;
1371
- }
1372
- function hasValues(values) {
1373
- return Array.isArray(values) && values.length > 0;
1374
- }
1375
- function hasUnsupportedSourceMarker(rawSource) {
1376
- return rawSource.includes("eval(") || rawSource.includes("weapp-tw") && rawSource.includes("ignore");
1377
- }
1378
- function hasSupportedClassMatchSource(options) {
1379
- return options.alwaysEscape === true || Boolean(options.classNameSet && options.classNameSet.size > 0);
1380
- }
1381
- function canAttemptOxcJsFastPath(options) {
1382
- if (options.experimentalJsFastPath !== true && options.experimentalJsFastPath !== "oxc") return false;
1383
- return !options.generateMap && !options.wrapExpression && !options.moduleGraph && !options.moduleSpecifierReplacements && hasSupportedClassMatchSource(options) && !hasValues(options.ignoreCallExpressionIdentifiers);
1384
- }
1385
- function getParserLang(filename) {
1386
- if (filename?.endsWith(".ts") || filename?.endsWith(".mts") || filename?.endsWith(".cts")) return "ts";
1387
- if (filename?.endsWith(".tsx")) return "tsx";
1388
- if (filename?.endsWith(".jsx")) return "jsx";
1389
- return "js";
1390
- }
1391
- function getParserSourceType(sourceType) {
1392
- return sourceType === "script" || sourceType === "module" ? sourceType : "module";
1393
- }
1394
- function isRangeValid(start, end) {
1395
- return typeof start === "number" && typeof end === "number" && start < end;
1396
- }
1397
- function getMagicString(rawSource, context) {
1398
- if (!context.ms) context.ms = new require_wxml.MagicString(rawSource);
1399
- return context.ms;
1400
- }
1401
- function addStringLiteralReplacement(rawSource, node, transformOptions, context) {
1402
- if (typeof node.value !== "string" || typeof node.raw !== "string" || !isRangeValid(node.start, node.end)) return false;
1403
- const transformed = transformLiteralText(node.value, transformOptions, false);
1404
- if (!transformed) return false;
1405
- const start = node.start + 1;
1406
- const end = node.end - 1;
1407
- if (start >= end || transformed === rawSource.slice(start, end)) return false;
1408
- getMagicString(rawSource, context).update(start, end, require_wxml.jsStringEscape(transformed));
1409
- return true;
1410
- }
1411
- function addTemplateElementReplacement(rawSource, node, transformOptions, context) {
1412
- const raw = node.value?.raw;
1413
- if (typeof raw !== "string" || !isRangeValid(node.start, node.end)) return false;
1414
- const transformed = transformLiteralText(raw, transformOptions, false);
1415
- if (!transformed || transformed === raw) return false;
1416
- const first = rawSource[node.start];
1417
- const last = rawSource[node.end - 1];
1418
- const start = node.start + (first === "`" || first === "}" ? 1 : 0);
1419
- const end = node.end - (last === "`" ? 1 : last === "{" ? 2 : 0);
1420
- if (start >= end) return false;
1421
- getMagicString(rawSource, context).update(start, end, transformed);
1422
- return true;
1423
- }
1424
- function applyReplacements(rawSource, program, stringLiteralOptions, templateLiteralOptions, context) {
1425
- let changed = false;
1426
- walk(program, { enter(node) {
1427
- if (node.type === "Literal") {
1428
- changed = addStringLiteralReplacement(rawSource, node, stringLiteralOptions, context) || changed;
1429
- return;
1430
- }
1431
- if (node.type === "TemplateElement") {
1432
- changed = addTemplateElementReplacement(rawSource, node, templateLiteralOptions, context) || changed;
1433
- this.skip();
1434
- }
1435
- } });
1436
- return changed;
1437
- }
1438
- function hasTaggedTemplateExpression(program) {
1439
- let found = false;
1440
- walk(program, { enter(node) {
1441
- if (node.type === "TaggedTemplateExpression") {
1442
- found = true;
1443
- this.skip();
1444
- }
1445
- } });
1446
- return found;
1447
- }
1448
- function oxcJsHandler(rawSource, options) {
1449
- if (!canAttemptOxcJsFastPath(options)) return;
1450
- if (hasUnsupportedSourceMarker(rawSource)) return;
1451
- const parser = loadOxcParser();
1452
- if (!parser) return;
1453
- let result;
1454
- try {
1455
- result = parser.parseSync(options.filename ?? "weapp-tailwindcss.js", rawSource, {
1456
- sourceType: getParserSourceType(options.babelParserOptions?.sourceType),
1457
- lang: getParserLang(options.filename)
1458
- });
1459
- } catch {
1460
- return;
1461
- }
1462
- if (!result.program || Array.isArray(result.errors) && result.errors.length > 0) return;
1463
- if (hasValues(options.ignoreTaggedTemplateExpressionIdentifiers) && hasTaggedTemplateExpression(result.program)) return;
1464
- const stringLiteralOptions = options.needEscaped === true ? options : {
1465
- ...options,
1466
- needEscaped: true
1467
- };
1468
- const templateLiteralOptions = options.needEscaped === false ? options : {
1469
- ...options,
1470
- needEscaped: false
1471
- };
1472
- const replacementContext = {};
1473
- if (!applyReplacements(rawSource, result.program, stringLiteralOptions, templateLiteralOptions, replacementContext)) return { code: rawSource };
1474
- return { code: replacementContext.ms.toString() };
1475
- }
1476
- //#endregion
1477
- //#region src/js/precheck.ts
1478
- /** 用于检测源码中是否包含类名相关模式的正则表达式 */
1479
- const FAST_JS_TRANSFORM_HINT_RE = /className\b|class\s*=|classList\.|\b(?:twMerge|clsx|classnames|cn|cva)\b|\[["'`]class["'`]\]|text-\[|bg-\[|\b(?:[whpm]|px|py|mx|my|rounded|flex|grid|gap)-/;
1480
- /** 用于检测源码中是否包含 import/export/require 语句的正则表达式 */
1481
- const DEPENDENCY_HINT_RE = /\bimport\s*(?:["'`{]|\*\s+as\b)|\brequire\s*\(|\bexport\s+\*\s+from\s+["'`]|\bexport\s*\{[^}]*\}\s*from\s+["'`]/;
1482
- /**
1483
- * 判断源码是否可能声明跨模块依赖。
1484
- *
1485
- * 该检查只作为性能预筛:返回 `true` 时必须保守走 AST 模块图分析;
1486
- * 返回 `false` 时源码中没有可被当前模块图消费的静态 import/export/require 形态。
1487
- */
1488
- function hasDependencyHint(rawSource) {
1489
- return DEPENDENCY_HINT_RE.test(rawSource);
1490
- }
1491
- /**
1492
- * 判断是否可以跳过 JS 转换。
1493
- * 通过正则快速检测源码内容,避免不必要的 Babel AST 解析。
1494
- *
1495
- * @param rawSource - 原始 JS 源码字符串
1496
- * @param options - 可选的 JS 处理器配置选项
1497
- * @returns 如果可以跳过转换返回 `true`,否则返回 `false`
1498
- */
1499
- function shouldSkipJsTransform(rawSource, options) {
1500
- if (node_process.default.env["WEAPP_TW_DISABLE_JS_PRECHECK"] === "1") return false;
1501
- if (!rawSource) return true;
1502
- if (options?.alwaysEscape) return false;
1503
- if (options?.moduleSpecifierReplacements && Object.keys(options.moduleSpecifierReplacements).length > 0) return false;
1504
- if (options?.wrapExpression) return false;
1505
- if (hasDependencyHint(rawSource)) return false;
1506
- return !FAST_JS_TRANSFORM_HINT_RE.test(rawSource);
1507
- }
1508
- //#endregion
1509
- //#region src/js/index.ts
1510
- /** 默认 LRU 缓存最大条目数 */
1511
- const RESULT_CACHE_MAX = 512;
1512
- /** 仅对短片段做内层结果缓存,避免 bundler 热路径重复 hash 大块 JS。 */
1513
- const CACHEABLE_SOURCE_MAX_LENGTH = 512;
1514
- /** 为每个 ClassNameSet 实例分配递增 ID */
1515
- const classNameSetIds = /* @__PURE__ */ new WeakMap();
1516
- let nextClassNameSetId = 0;
1517
- /**
1518
- * 获取 ClassNameSet 的唯一身份 ID。
1519
- * 每个 Set 引用分配一个递增整数,用于指纹计算。
1520
- */
1521
- function getClassNameSetId(set) {
1522
- if (!set) return "none";
1523
- const existing = classNameSetIds.get(set);
1524
- if (existing !== void 0) return String(existing);
1525
- const id = nextClassNameSetId++;
1526
- classNameSetIds.set(set, id);
1527
- return String(id);
1528
- }
1529
- /** 缓存 IJsHandlerOptions -> fingerprint 的映射 */
1530
- const fingerprintCache = /* @__PURE__ */ new WeakMap();
1531
- /**
1532
- * 计算选项指纹,包含所有影响转译结果的字段。
1533
- * 不包含 filename、moduleGraph、jsPreserveClass。
1534
- */
1535
- function getOptionsFingerprint(options) {
1536
- const cached = fingerprintCache.get(options);
1537
- if (cached) return cached;
1538
- const fingerprint = [
1539
- getClassNameSetId(options.classNameSet),
1540
- JSON.stringify(options.escapeMap ?? null),
1541
- options.needEscaped ? "1" : "0",
1542
- options.alwaysEscape ? "1" : "0",
1543
- options.unescapeUnicode ? "1" : "0",
1544
- options.generateMap ? "1" : "0",
1545
- options.uniAppX ? "1" : "0",
1546
- options.wrapExpression ? "1" : "0",
1547
- JSON.stringify(options.arbitraryValues ?? null),
1548
- JSON.stringify(options.ignoreCallExpressionIdentifiers ?? null),
1549
- JSON.stringify(options.ignoreTaggedTemplateExpressionIdentifiers?.map((v) => v instanceof RegExp ? v.source : v) ?? null),
1550
- JSON.stringify(options.moduleSpecifierReplacements ?? null),
1551
- String(options.experimentalJsFastPath ?? ""),
1552
- JSON.stringify(options.babelParserOptions ?? null)
1553
- ].join("|");
1554
- fingerprintCache.set(options, fingerprint);
1555
- return fingerprint;
1556
- }
1557
- function hasDefinedOverrides(options) {
1558
- if (!options) return false;
1559
- for (const key in options) if (options[key] !== void 0) return true;
1560
- return false;
1561
- }
1562
- function shouldCacheJsResult(rawSource, options) {
1563
- if (rawSource.length === 0 || rawSource.length > CACHEABLE_SOURCE_MAX_LENGTH) return false;
1564
- if (options.moduleGraph || options.filename) return false;
1565
- return true;
1566
- }
1567
- function resolveFastPathOptions(rawSource, options) {
1568
- if (!options.moduleGraph) return options;
1569
- if (options.moduleSpecifierReplacements && Object.keys(options.moduleSpecifierReplacements).length > 0) return options;
1570
- if (hasDependencyHint(rawSource)) return options;
1571
- const { moduleGraph: _moduleGraph, ...fastPathOptions } = options;
1572
- return fastPathOptions;
1573
- }
1574
- function createJsHandler(options) {
1575
- const defaults = {
1576
- escapeMap: options.escapeMap,
1577
- jsArbitraryValueFallback: options.jsArbitraryValueFallback,
1578
- tailwindcssMajorVersion: options.tailwindcssMajorVersion,
1579
- arbitraryValues: options.arbitraryValues,
1580
- jsPreserveClass: options.jsPreserveClass,
1581
- generateMap: options.generateMap,
1582
- needEscaped: options.needEscaped,
1583
- alwaysEscape: options.alwaysEscape,
1584
- unescapeUnicode: options.unescapeUnicode,
1585
- babelParserOptions: options.babelParserOptions,
1586
- experimentalJsFastPath: options.experimentalJsFastPath,
1587
- ignoreCallExpressionIdentifiers: options.ignoreCallExpressionIdentifiers,
1588
- ignoreTaggedTemplateExpressionIdentifiers: options.ignoreTaggedTemplateExpressionIdentifiers,
1589
- uniAppX: options.uniAppX,
1590
- moduleSpecifierReplacements: options.moduleSpecifierReplacements
1591
- };
1592
- /** 层1: 无 override 时,classNameSet -> resolvedOptions */
1593
- const defaultOptionsCache = /* @__PURE__ */ new WeakMap();
1594
- let resolvedOptionsWithoutClassNameSet;
1595
- /** 层2: 有 override 时,overrideOptions -> { bySet, noSet } */
1596
- const overrideOptionsCache = /* @__PURE__ */ new WeakMap();
1597
- const resultCache = new lru_cache.LRUCache({ max: RESULT_CACHE_MAX });
1598
- function resolveDefaultOptions(classNameSet) {
1599
- if (!classNameSet) {
1600
- if (!resolvedOptionsWithoutClassNameSet) resolvedOptionsWithoutClassNameSet = {
1601
- ...defaults,
1602
- classNameSet
1603
- };
1604
- return resolvedOptionsWithoutClassNameSet;
1605
- }
1606
- const cached = defaultOptionsCache.get(classNameSet);
1607
- if (cached) return cached;
1608
- const created = {
1609
- ...defaults,
1610
- classNameSet
1611
- };
1612
- defaultOptionsCache.set(classNameSet, created);
1613
- return created;
1614
- }
1615
- function getCachedJsResult(rawSource, resolvedOptions) {
1616
- if (!shouldCacheJsResult(rawSource, resolvedOptions)) return;
1617
- const key = `${getOptionsFingerprint(resolvedOptions)}:${(0, _weapp_tailwindcss_shared_node.md5)(rawSource)}`;
1618
- return resultCache.get(key);
1619
- }
1620
- function setCachedJsResult(rawSource, resolvedOptions, result) {
1621
- if (!shouldCacheJsResult(rawSource, resolvedOptions) || result.error || result.linked) return result;
1622
- const key = `${getOptionsFingerprint(resolvedOptions)}:${(0, _weapp_tailwindcss_shared_node.md5)(rawSource)}`;
1623
- resultCache.set(key, result);
1624
- return result;
1625
- }
1626
- function resolveOptions(classNameSet, overrideOptions) {
1627
- if (!hasDefinedOverrides(overrideOptions)) return resolveDefaultOptions(classNameSet);
1628
- let entry = overrideOptionsCache.get(overrideOptions);
1629
- if (!entry) {
1630
- entry = { bySet: /* @__PURE__ */ new WeakMap() };
1631
- overrideOptionsCache.set(overrideOptions, entry);
1632
- }
1633
- if (!classNameSet) {
1634
- if (entry.noSet) return entry.noSet;
1635
- const created = (0, _weapp_tailwindcss_shared.defuOverrideArray)({
1636
- ...overrideOptions,
1637
- classNameSet
1638
- }, defaults);
1639
- entry.noSet = created;
1640
- return created;
1641
- }
1642
- const cached = entry.bySet.get(classNameSet);
1643
- if (cached) return cached;
1644
- const created = (0, _weapp_tailwindcss_shared.defuOverrideArray)({
1645
- ...overrideOptions,
1646
- classNameSet
1647
- }, defaults);
1648
- entry.bySet.set(classNameSet, created);
1649
- return created;
1650
- }
1651
- function handler(rawSource, classNameSet, options) {
1652
- const resolvedOptions = resolveOptions(classNameSet, options);
1653
- const cached = getCachedJsResult(rawSource, resolvedOptions);
1654
- if (cached) return cached;
1655
- return setCachedJsResult(rawSource, resolvedOptions, oxcJsHandler(rawSource, resolveFastPathOptions(rawSource, resolvedOptions)) ?? require_wxml.jsHandler(rawSource, resolvedOptions));
1656
- }
1657
- return handler;
1658
- }
1659
- //#endregion
1660
- //#region src/constants.ts
1661
- const pluginName = "weapp-tailwindcss";
1662
- const vitePluginName = "weapp-tailwindcss:adaptor";
1663
- const DEFAULT_RUNTIME_PACKAGE_REPLACEMENTS = {
1664
- "tailwind-merge": "@weapp-tailwindcss/merge",
1665
- "class-variance-authority": "@weapp-tailwindcss/cva",
1666
- "tailwind-variants": "@weapp-tailwindcss/variants"
1667
- };
1668
- //#endregion
1669
- //#region src/context/runtime-package-replacements.ts
1670
- function resolveRuntimePackageReplacements(option) {
1671
- const mapping = require_generator.resolveBooleanObjectOption(option, DEFAULT_RUNTIME_PACKAGE_REPLACEMENTS);
1672
- if (!mapping) return;
1673
- const normalized = {};
1674
- for (const [from, to] of Object.entries(mapping)) {
1675
- if (!from || typeof to !== "string" || to.length === 0) continue;
1676
- normalized[from] = to;
1677
- }
1678
- return Object.keys(normalized).length > 0 ? normalized : void 0;
1679
- }
1680
- //#endregion
1681
- //#region src/context/style-options.ts
1682
- function normalizeStyleHandlerMajorVersion(majorVersion) {
1683
- return majorVersion === 4 ? 4 : void 0;
1684
- }
1685
- function resolveStyleOptionsFromContext(ctx, tailwindcssMajorVersion) {
1686
- const resolvedUniAppXOptions = require_tailwindcss.resolveUniAppXOptions(ctx.uniAppX);
1687
- const generatorOptions = require_generator.normalizeWeappTailwindcssGeneratorOptions(ctx.generator, {
1688
- appType: ctx.appType,
1689
- platform: ctx.cssOptions?.platform ?? ctx.platform,
1690
- tailwindcssMajorVersion,
1691
- uniAppX: resolvedUniAppXOptions
1692
- });
1693
- const branch = require_generator.resolveGeneratorRuntimeBranch(generatorOptions, {
1694
- appType: ctx.appType,
1695
- platform: ctx.cssOptions?.platform ?? ctx.platform,
1696
- tailwindcssMajorVersion,
1697
- uniAppX: resolvedUniAppXOptions
1698
- });
1699
- const hasCssOptions = ctx.cssOptions !== void 0;
1700
- const configuredRem2rpx = ctx.cssOptions?.rem2rpx ?? ctx.rem2rpx;
1701
- const rem2rpx = branch.isWeb && require_generator.shouldUseUniAppWebRpxCompatibility(ctx.appType) ? false : configuredRem2rpx;
1702
- const cssOptions = {
1703
- cssPreflight: ctx.cssOptions?.cssPreflight ?? ctx.cssPreflight,
1704
- cssPreflightRange: ctx.cssOptions?.cssPreflightRange ?? ctx.cssPreflightRange,
1705
- cssChildCombinatorReplaceValue: ctx.cssOptions?.cssChildCombinatorReplaceValue ?? ctx.cssChildCombinatorReplaceValue,
1706
- cssSelectorReplacement: ctx.cssOptions?.cssSelectorReplacement ?? ctx.cssSelectorReplacement,
1707
- rem2rpx,
1708
- cssRemoveProperty: ctx.cssOptions?.cssRemoveProperty ?? ctx.cssRemoveProperty,
1709
- cssRemoveActivePseudoClass: ctx.cssOptions?.cssRemoveActivePseudoClass ?? ctx.cssRemoveActivePseudoClass,
1710
- cssRemoveHoverPseudoClass: ctx.cssOptions?.cssRemoveHoverPseudoClass ?? ctx.cssRemoveHoverPseudoClass,
1711
- cssRemoveFocusPseudoClass: ctx.cssOptions?.cssRemoveFocusPseudoClass ?? ctx.cssRemoveFocusPseudoClass,
1712
- tailwindcssV4GradientFallback: ctx.cssOptions?.tailwindcssV4GradientFallback ?? ctx.tailwindcssV4GradientFallback,
1713
- cssPresetEnv: ctx.cssOptions?.cssPresetEnv ?? ctx.cssPresetEnv,
1714
- atRules: ctx.cssOptions?.atRules ?? ctx.atRules,
1715
- autoprefixer: ctx.cssOptions?.autoprefixer ?? ctx.autoprefixer,
1716
- cssCalc: ctx.cssOptions?.cssCalc ?? ctx.cssCalc,
1717
- platform: branch.platform ?? ctx.cssOptions?.platform ?? ctx.platform,
1718
- px2rpx: ctx.cssOptions?.px2rpx ?? ctx.px2rpx,
1719
- unitsToPx: ctx.cssOptions?.unitsToPx ?? ctx.unitsToPx,
1720
- unitConversion: ctx.cssOptions?.unitConversion ?? ctx.unitConversion,
1721
- injectAdditionalCssVarScope: ctx.cssOptions?.injectAdditionalCssVarScope ?? ctx.injectAdditionalCssVarScope
1722
- };
1723
- return {
1724
- appType: ctx.appType,
1725
- postcssOptions: ctx.postcssOptions,
1726
- cssPreflight: cssOptions.cssPreflight,
1727
- cssPreflightRange: cssOptions.cssPreflightRange,
1728
- cssChildCombinatorReplaceValue: cssOptions.cssChildCombinatorReplaceValue,
1729
- cssSelectorReplacement: cssOptions.cssSelectorReplacement,
1730
- rem2rpx: cssOptions.rem2rpx,
1731
- ...hasCssOptions ? { cssOptions } : {},
1732
- cssRemoveProperty: cssOptions.cssRemoveProperty,
1733
- cssRemoveActivePseudoClass: cssOptions.cssRemoveActivePseudoClass,
1734
- cssRemoveHoverPseudoClass: cssOptions.cssRemoveHoverPseudoClass,
1735
- cssRemoveFocusPseudoClass: cssOptions.cssRemoveFocusPseudoClass,
1736
- tailwindcssV4GradientFallback: cssOptions.tailwindcssV4GradientFallback,
1737
- cssPresetEnv: cssOptions.cssPresetEnv,
1738
- atRules: cssOptions.atRules,
1739
- autoprefixer: cssOptions.autoprefixer,
1740
- cssCalc: cssOptions.cssCalc,
1741
- uniAppX: branch.isNativeApp,
1742
- platform: cssOptions.platform,
1743
- px2rpx: cssOptions.px2rpx,
1744
- unitsToPx: cssOptions.unitsToPx,
1745
- unitConversion: cssOptions.unitConversion
1746
- };
1747
- }
1748
- //#endregion
1749
- //#region src/context/handlers.ts
1750
- function createHandlersFromContext(ctx, customAttributesEntities, cssCalcOptions, tailwindcssMajorVersion) {
1751
- const { escapeMap, injectAdditionalCssVarScope, postcssOptions, uniAppX, arbitraryValues, jsPreserveClass, babelParserOptions, experimentalJsFastPath, ignoreCallExpressionIdentifiers, ignoreTaggedTemplateExpressionIdentifiers, inlineWxs, disabledDefaultTemplateHandler, replaceRuntimePackages } = ctx;
1752
- const resolvedUniAppXOptions = require_tailwindcss.resolveUniAppXOptions(uniAppX);
1753
- const styleOptions = resolveStyleOptionsFromContext(ctx, tailwindcssMajorVersion);
1754
- const resolvedInjectAdditionalCssVarScope = styleOptions.cssOptions?.injectAdditionalCssVarScope ?? injectAdditionalCssVarScope;
1755
- const uniAppXEnabled = styleOptions.uniAppX === true;
1756
- const moduleSpecifierReplacements = resolveRuntimePackageReplacements(replaceRuntimePackages);
1757
- const styleHandler = (0, _weapp_tailwindcss_postcss.createStyleHandler)({
1758
- ...styleOptions,
1759
- escapeMap,
1760
- injectAdditionalCssVarScope: resolvedInjectAdditionalCssVarScope,
1761
- postcssOptions,
1762
- uniAppXUnsupported: resolvedUniAppXOptions.uvueUnsupported,
1763
- cssCalc: cssCalcOptions,
1764
- majorVersion: normalizeStyleHandlerMajorVersion(tailwindcssMajorVersion)
1765
- });
1766
- const jsHandler = createJsHandler({
1767
- escapeMap,
1768
- arbitraryValues,
1769
- jsPreserveClass,
1770
- generateMap: true,
1771
- babelParserOptions,
1772
- experimentalJsFastPath,
1773
- ignoreCallExpressionIdentifiers,
1774
- ignoreTaggedTemplateExpressionIdentifiers,
1775
- uniAppX: uniAppXEnabled,
1776
- moduleSpecifierReplacements
1777
- });
1778
- return {
1779
- styleHandler,
1780
- jsHandler,
1781
- templateHandler: require_wxml.createTemplateHandler({
1782
- customAttributesEntities,
1783
- escapeMap,
1784
- inlineWxs,
1785
- jsHandler,
1786
- disabledDefaultTemplateHandler
1787
- })
1788
- };
1789
- }
1790
- //#endregion
1791
- //#region src/context/logger.ts
1792
- const loggerLevelMap = {
1793
- error: 0,
1794
- warn: 1,
1795
- info: 3,
1796
- silent: -999
1797
- };
1798
- function applyLoggerLevel(logLevel) {
1799
- _weapp_tailwindcss_logger.logger.level = loggerLevelMap[logLevel ?? "info"] ?? loggerLevelMap.info;
1800
- }
1801
- //#endregion
1802
- //#region src/context/index.ts
1803
- function resolveContextCssPreflight(opts, ctx, majorVersion) {
1804
- const userCssPreflight = opts?.cssOptions?.cssPreflight ?? opts?.cssPreflight;
1805
- const cssPreflight = require_defaults.resolveDefaultCssPreflight(userCssPreflight, majorVersion);
1806
- const shouldUseUniAppXPreflight = ctx.appType === "uni-app-x" || require_tailwindcss.resolveUniAppXOptions(ctx.uniAppX).enabled;
1807
- if (cssPreflight === false || !shouldUseUniAppXPreflight) return cssPreflight;
1808
- const userCssPreflightObject = userCssPreflight && typeof userCssPreflight === "object" ? userCssPreflight : void 0;
1809
- return {
1810
- ...cssPreflight,
1811
- "border-width": userCssPreflightObject && "border-width" in userCssPreflightObject ? cssPreflight["border-width"] ?? false : "0",
1812
- "border-style": userCssPreflightObject && "border-style" in userCssPreflightObject ? cssPreflight["border-style"] ?? false : false,
1813
- "border": userCssPreflightObject && "border" in userCssPreflightObject ? cssPreflight["border"] ?? false : false
1814
- };
1815
- }
1816
- function syncCssOptionsToLegacyFields(ctx) {
1817
- if (!ctx.cssOptions) return;
1818
- const cssOptions = ctx.cssOptions;
1819
- ctx.cssPreflight = cssOptions.cssPreflight ?? ctx.cssPreflight;
1820
- ctx.cssPreflightRange = cssOptions.cssPreflightRange ?? ctx.cssPreflightRange;
1821
- ctx.cssChildCombinatorReplaceValue = cssOptions.cssChildCombinatorReplaceValue ?? ctx.cssChildCombinatorReplaceValue;
1822
- ctx.cssSelectorReplacement = cssOptions.cssSelectorReplacement ?? ctx.cssSelectorReplacement;
1823
- ctx.rem2rpx = cssOptions.rem2rpx ?? ctx.rem2rpx;
1824
- ctx.cssRemoveProperty = cssOptions.cssRemoveProperty ?? ctx.cssRemoveProperty;
1825
- ctx.cssRemoveActivePseudoClass = cssOptions.cssRemoveActivePseudoClass ?? ctx.cssRemoveActivePseudoClass;
1826
- ctx.cssRemoveHoverPseudoClass = cssOptions.cssRemoveHoverPseudoClass ?? ctx.cssRemoveHoverPseudoClass;
1827
- ctx.cssRemoveFocusPseudoClass = cssOptions.cssRemoveFocusPseudoClass ?? ctx.cssRemoveFocusPseudoClass;
1828
- ctx.tailwindcssV4GradientFallback = cssOptions.tailwindcssV4GradientFallback ?? ctx.tailwindcssV4GradientFallback;
1829
- ctx.cssPresetEnv = cssOptions.cssPresetEnv ?? ctx.cssPresetEnv;
1830
- ctx.atRules = cssOptions.atRules ?? ctx.atRules;
1831
- ctx.autoprefixer = cssOptions.autoprefixer ?? ctx.autoprefixer;
1832
- ctx.cssCalc = cssOptions.cssCalc ?? ctx.cssCalc;
1833
- ctx.platform = cssOptions.platform ?? ctx.platform;
1834
- ctx.px2rpx = cssOptions.px2rpx ?? ctx.px2rpx;
1835
- ctx.unitsToPx = cssOptions.unitsToPx ?? ctx.unitsToPx;
1836
- ctx.unitConversion = cssOptions.unitConversion ?? ctx.unitConversion;
1837
- ctx.injectAdditionalCssVarScope = cssOptions.injectAdditionalCssVarScope ?? ctx.injectAdditionalCssVarScope;
1838
- }
1839
- function syncLegacyFieldsToCssOptions(ctx) {
1840
- if (!ctx.cssOptions) return;
1841
- ctx.cssOptions = {
1842
- ...ctx.cssOptions ?? {},
1843
- cssPreflight: ctx.cssPreflight,
1844
- cssPreflightRange: ctx.cssPreflightRange,
1845
- cssChildCombinatorReplaceValue: ctx.cssChildCombinatorReplaceValue,
1846
- cssSelectorReplacement: ctx.cssSelectorReplacement,
1847
- rem2rpx: ctx.rem2rpx,
1848
- cssRemoveProperty: ctx.cssRemoveProperty,
1849
- cssRemoveActivePseudoClass: ctx.cssRemoveActivePseudoClass,
1850
- cssRemoveHoverPseudoClass: ctx.cssRemoveHoverPseudoClass,
1851
- cssRemoveFocusPseudoClass: ctx.cssRemoveFocusPseudoClass,
1852
- tailwindcssV4GradientFallback: ctx.tailwindcssV4GradientFallback,
1853
- cssPresetEnv: ctx.cssPresetEnv,
1854
- atRules: ctx.atRules,
1855
- autoprefixer: ctx.autoprefixer,
1856
- cssCalc: ctx.cssCalc,
1857
- platform: ctx.platform,
1858
- px2rpx: ctx.px2rpx,
1859
- unitsToPx: ctx.unitsToPx,
1860
- unitConversion: ctx.unitConversion,
1861
- injectAdditionalCssVarScope: ctx.injectAdditionalCssVarScope
1862
- };
1863
- }
1864
- function applyFrameworkPlatformDefaults(ctx) {
1865
- if (ctx.cssOptions?.platform || ctx.platform) {
1866
- ctx.platform = normalizeFrameworkStylePlatform(ctx.cssOptions?.platform ?? ctx.platform, ctx.appType);
1867
- return;
1868
- }
1869
- if (ctx.appType === "mpx") ctx.platform = normalizeFrameworkStylePlatform(require_framework.resolveMpxPlatform().normalized, ctx.appType);
1870
- }
1871
- async function clearTailwindcssRuntimeCache(tailwindRuntime, options) {
1872
- if (!tailwindRuntime) return;
1873
- const cacheOptions = tailwindRuntime.options?.cache;
1874
- if (cacheOptions == null || typeof cacheOptions === "object" && cacheOptions.enabled === false) return;
1875
- if (typeof tailwindRuntime.clearCache === "function") try {
1876
- await tailwindRuntime.clearCache({ scope: "all" });
1877
- } catch (error) {
1878
- _weapp_tailwindcss_logger.logger.debug("failed to clear tailwindcss runtime cache via clearCache(): %O", error);
1879
- }
1880
- if (!options?.removeDirectory) return;
1881
- const cachePaths = /* @__PURE__ */ new Map();
1882
- const normalizedCacheOptions = typeof cacheOptions === "object" ? cacheOptions : void 0;
1883
- const privateCachePath = tailwindRuntime?.cacheStore?.options?.path;
1884
- if (privateCachePath) cachePaths.set(privateCachePath, false);
1885
- if (normalizedCacheOptions?.path) cachePaths.set(normalizedCacheOptions.path, false);
1886
- if (options?.removeDirectory && normalizedCacheOptions?.dir) cachePaths.set(normalizedCacheOptions.dir, true);
1887
- if (!cachePaths.size) return;
1888
- for (const [cachePath, recursive] of cachePaths.entries()) try {
1889
- await (0, node_fs_promises.rm)(cachePath, {
1890
- force: true,
1891
- recursive
1892
- });
1893
- } catch (error) {
1894
- const err = error;
1895
- if (err?.code === "ENOENT") continue;
1896
- _weapp_tailwindcss_logger.logger.debug("failed to clear tailwindcss runtime cache: %s %O", cachePath, err);
1897
- }
1898
- }
1899
- function createInternalCompilerContext(opts) {
1900
- const ctx = (0, _weapp_tailwindcss_shared.defuOverrideArray)(opts, require_defaults.getDefaultOptions(), {});
1901
- ctx.arbitraryValues = resolveUnocssBareArbitraryValues(ctx.arbitraryValues, ctx.unocss);
1902
- ctx.escapeMap = ctx.customReplaceDictionary;
1903
- syncCssOptionsToLegacyFields(ctx);
1904
- applyFrameworkPlatformDefaults(ctx);
1905
- applyLoggerLevel(ctx.logLevel);
1906
- const tailwindRuntime = require_tailwindcss.createTailwindcssRuntimeFromContext(ctx);
1907
- logTailwindcssTarget(tailwindRuntime, ctx.tailwindcssBasedir);
1908
- logRuntimeTailwindcssVersion(ctx.tailwindcssBasedir, tailwindRuntime.packageInfo?.rootPath, tailwindRuntime.packageInfo?.version);
1909
- if (opts?.__internalDeferMissingCssEntriesWarning !== true) require_tailwindcss.warnMissingCssEntries(ctx, tailwindRuntime);
1910
- ctx.cssPreflight = resolveContextCssPreflight(opts, ctx, tailwindRuntime.majorVersion);
1911
- const cssCalcOptions = require_tailwindcss.applyV4CssCalcDefaults(ctx.cssCalc, tailwindRuntime);
1912
- ctx.cssCalc = cssCalcOptions;
1913
- syncLegacyFieldsToCssOptions(ctx);
1914
- const customAttributesEntities = toCustomAttributesEntities(ctx.customAttributes);
1915
- ctx.customAttributesEntities = customAttributesEntities;
1916
- const { styleHandler, jsHandler, templateHandler } = createHandlersFromContext(ctx, customAttributesEntities, cssCalcOptions, tailwindRuntime.majorVersion);
1917
- ctx.styleHandler = styleHandler;
1918
- ctx.jsHandler = jsHandler;
1919
- ctx.templateHandler = templateHandler;
1920
- ctx.cache = initializeCache(ctx.cache);
1921
- ctx.tailwindRuntime = tailwindRuntime;
1922
- const refreshTailwindcssRuntime = async (options) => {
1923
- const previousRuntime = ctx.tailwindRuntime;
1924
- if (options?.clearCache !== false) await clearTailwindcssRuntimeCache(previousRuntime);
1925
- require_tailwindcss.invalidateRuntimeClassSet(previousRuntime);
1926
- const nextRuntime = require_tailwindcss.createTailwindcssRuntimeFromContext(ctx);
1927
- Object.assign(previousRuntime, nextRuntime);
1928
- ctx.tailwindRuntime = previousRuntime;
1929
- return previousRuntime;
1930
- };
1931
- ctx.refreshTailwindcssRuntime = refreshTailwindcssRuntime;
1932
- Object.defineProperty(ctx.tailwindRuntime, refreshTailwindcssRuntimeSymbol, {
1933
- value: refreshTailwindcssRuntime,
1934
- configurable: true
1935
- });
1936
- return ctx;
1937
- }
1938
- /**
1939
- * 获取用户定义选项的内部表示,并初始化相关的处理程序和 Tailwind 运行时。
1940
- * @param opts - 用户定义的选项,可选。
1941
- * @returns 返回一个包含内部用户定义选项的对象,包括样式、JS 和模板处理程序,以及 Tailwind CSS 运行时。
1942
- */
1943
- function getCompilerContext(opts) {
1944
- return withCompilerContextCache(opts, () => createInternalCompilerContext(opts));
1945
- }
1946
- //#endregion
1947
- //#region src/core/compiler/transforms.ts
1948
- const DEFAULT_JS_OPTIONS = Object.freeze({ tailwindcssMajorVersion: 4 });
1949
- const DEFAULT_STYLE_OPTIONS = Object.freeze({ isMainChunk: true });
1950
- function clonePostcssResult(result) {
1951
- return Object.assign(Object.create(Object.getPrototypeOf(result)), result, {
1952
- messages: [...result.messages],
1953
- root: result.root.clone()
1954
- });
1955
- }
1956
- function resolveStyleOptions(options) {
1957
- if (!options) return DEFAULT_STYLE_OPTIONS;
1958
- return options?.isMainChunk === void 0 ? {
1959
- ...options,
1960
- isMainChunk: true
1961
- } : options;
1962
- }
1963
- function resolveCssTransformOptions(options) {
1964
- const { finalize: _finalize, ...styleOptions } = options ?? {};
1965
- return {
1966
- finalize: _finalize,
1967
- styleOptions: resolveStyleOptions(styleOptions)
1968
- };
1969
- }
1970
- function finalizeResultRoot(result, snapshot, shouldFinalize) {
1971
- if (!shouldFinalize || result.root.type !== "root") return;
1972
- (0, _weapp_tailwindcss_postcss.finalizeMiniProgramCssRoot)(result.root, { isTailwindcssV4: snapshot.target === "weapp" });
1973
- result.css = result.root.toString();
1974
- }
1975
- function createCompilerTransforms({ ensureActive, track, userOptions }) {
1976
- const context = getCompilerContext({
1977
- ...userOptions,
1978
- __internalDeferMissingCssEntriesWarning: true
1979
- });
1980
- const styleHandler = context.styleHandler;
1981
- let cachedTemplateClassSet;
1982
- let cachedTemplateOptions;
1983
- function clearCache() {
1984
- cachedTemplateClassSet = void 0;
1985
- cachedTemplateOptions = void 0;
1986
- }
1987
- function createTemplateOptions(classSet, options) {
1988
- const isDefault = !options || Object.keys(options).length === 0;
1989
- if (isDefault && cachedTemplateClassSet === classSet && cachedTemplateOptions) return cachedTemplateOptions;
1990
- const resolved = {
1991
- ...options,
1992
- classSetMode: "exact",
1993
- jsHandler: (jsSource, _runtimeSet, jsOptions) => context.jsHandler(jsSource, classSet, {
1994
- ...jsOptions,
1995
- tailwindcssMajorVersion: jsOptions?.tailwindcssMajorVersion ?? 4
1996
- }),
1997
- runtimeSet: classSet
1998
- };
1999
- if (isDefault) {
2000
- cachedTemplateClassSet = classSet;
2001
- cachedTemplateOptions = resolved;
2002
- }
2003
- return resolved;
2004
- }
2005
- function transformCss(css, snapshot, options) {
2006
- ensureActive();
2007
- getInternalCompilerSnapshot(snapshot);
2008
- const resolved = resolveCssTransformOptions(options);
2009
- const shouldFinalize = resolved.finalize ?? snapshot.target === "weapp";
2010
- return track(styleHandler(css, resolved.styleOptions).then((result) => {
2011
- const cloned = clonePostcssResult(result);
2012
- finalizeResultRoot(cloned, snapshot, shouldFinalize);
2013
- return cloned;
2014
- }));
2015
- }
2016
- function transformCssRoot(root, snapshot, options) {
2017
- ensureActive();
2018
- getInternalCompilerSnapshot(snapshot);
2019
- const resolved = resolveCssTransformOptions(options);
2020
- const shouldFinalize = resolved.finalize ?? snapshot.target === "weapp";
2021
- return track(styleHandler.transformRoot(root, resolved.styleOptions).then((result) => {
2022
- finalizeResultRoot(result, snapshot, shouldFinalize);
2023
- return result;
2024
- }));
2025
- }
2026
- function transformJavaScript(source, snapshot, options) {
2027
- ensureActive();
2028
- const classSet = getInternalCompilerSnapshot(snapshot).classSet;
2029
- const resolvedOptions = options?.tailwindcssMajorVersion === void 0 ? options ? {
2030
- ...options,
2031
- tailwindcssMajorVersion: 4
2032
- } : DEFAULT_JS_OPTIONS : options;
2033
- return track(Promise.resolve(shouldSkipJsTransform(source, resolvedOptions) ? { code: source } : context.jsHandler(source, classSet, resolvedOptions)));
2034
- }
2035
- function transformTemplate(source, snapshot, options) {
2036
- ensureActive();
2037
- const classSet = getInternalCompilerSnapshot(snapshot).classSet;
2038
- return track(context.templateHandler(source, createTemplateOptions(classSet, options)));
2039
- }
2040
- return {
2041
- clearCache,
2042
- transformCss,
2043
- transformCssRoot,
2044
- transformJavaScript,
2045
- transformTemplate
2046
- };
2047
- }
2048
- //#endregion
2049
- //#region src/core/compiler/compiler.ts
2050
- const DEFAULT_MAX_ROOTS = 128;
2051
- function createCompiler(options = {}) {
2052
- const { compiler: compilerOptions, ...userOptions } = options;
2053
- const rootStore = new CompilerRootStore(Math.max(1, Math.floor(compilerOptions?.maxRoots ?? DEFAULT_MAX_ROOTS)), compilerOptions?.onRootEvicted);
2054
- const activeTasks = /* @__PURE__ */ new Set();
2055
- let lifecycle = "active";
2056
- let disposePromise;
2057
- function ensureActive() {
2058
- if (lifecycle !== "active") throw new Error(lifecycle === "disposing" ? "Compiler 正在释放,不能接受新任务。" : "Compiler 已释放。");
2059
- }
2060
- function track(task) {
2061
- activeTasks.add(task);
2062
- task.then(() => activeTasks.delete(task), () => activeTasks.delete(task));
2063
- return task;
2064
- }
2065
- const { clearCache: clearTransformCache, ...transforms } = createCompilerTransforms({
2066
- ensureActive,
2067
- track,
2068
- userOptions
2069
- });
2070
- async function resolveRequestSource(entry, request) {
2071
- if (request.source && request.sourceOptions) throw new Error("generate() 的 source 与 sourceOptions 互斥。");
2072
- if (!request.source && !request.sourceOptions) throw new Error("generate() 必须提供 source 或 sourceOptions。");
2073
- const sourceInput = request.source ?? request.sourceOptions;
2074
- return {
2075
- source: entry.source !== void 0 && entry.sourceInput === sourceInput && entry.appliedInvalidation === entry.invalidation ? entry.source : request.source ?? await require_generator.resolveTailwindV4Source(request.sourceOptions),
2076
- sourceInput
2077
- };
2078
- }
2079
- async function runGenerate(entry, request) {
2080
- if (!entry.active) throw new Error(`Compiler root 已被移除:${entry.id}`);
2081
- const invalidation = entry.invalidation;
2082
- const { source, sourceInput } = await resolveRequestSource(entry, request);
2083
- const sourceFingerprint = entry.sourceInput === sourceInput && entry.sourceFingerprint !== void 0 && entry.appliedInvalidation === invalidation ? entry.sourceFingerprint : createSourceFingerprint(source);
2084
- const sourceReused = entry.sourceFingerprint === sourceFingerprint;
2085
- const engineReused = sourceReused && entry.generator !== void 0 && entry.appliedInvalidation === invalidation;
2086
- const generator = engineReused ? entry.generator : require_generator.createWeappTailwindcssGenerator(source);
2087
- const target = request.target ?? "weapp";
2088
- const { id: _id, source: _source, sourceOptions: _sourceOptions, target: _target, ...generateOptions } = request;
2089
- const prepared = prepareCompilerGeneration(entry, request, source, !sourceReused || entry.appliedInvalidation !== invalidation);
2090
- const generationCacheKey = createCompilerGenerationCacheKey(request, prepared.compilation.candidates, target);
2091
- const reusableGeneration = engineReused && entry.generationCache && isSameCompilerGenerationCacheKey(entry.generationCache.key, generationCacheKey) ? entry.generationCache.result : void 0;
2092
- try {
2093
- const generated = reusableGeneration ? reuseCompilerGenerationResult(reusableGeneration) : await generator.generate({
2094
- ...generateOptions,
2095
- candidates: prepared.explicitCandidates ? prepared.compilation.candidates : void 0,
2096
- incrementalCache: generateOptions.incrementalCache ?? true,
2097
- target: target === "tailwind" ? "web" : target
2098
- });
2099
- if (!entry.active) throw new Error(`Compiler root 已被移除:${entry.id}`);
2100
- const revision = (getLatestRevision(entry) ?? 0) + 1;
2101
- const dependencies = [.../* @__PURE__ */ new Set([...source.dependencies, ...generated.dependencies])].sort();
2102
- const sources = generated.sources ?? source.sources ?? [];
2103
- const previousSnapshotState = entry.latestSnapshot ? getInternalCompilerSnapshot(entry.latestSnapshot) : void 0;
2104
- const reusableClassSet = engineReused && generated.incrementalCss === "" && previousSnapshotState && previousSnapshotState.classSet.size === generated.classSet.size && [...generated.classSet].every((candidate) => previousSnapshotState.classSet.has(candidate)) ? previousSnapshotState.classSet : void 0;
2105
- const reusableClassSetView = reusableClassSet ? entry.latestSnapshot?.classSet : void 0;
2106
- const snapshot = createRegisteredCompilerSnapshot({
2107
- classSet: generated.classSet,
2108
- dependencies,
2109
- id: entry.id,
2110
- revision,
2111
- sources,
2112
- target
2113
- }, reusableClassSet, reusableClassSetView);
2114
- const internalSnapshot = getInternalCompilerSnapshot(snapshot);
2115
- const previousGenerator = entry.generator;
2116
- commitCompilerGeneration(entry, prepared, source, dependencies, generated.classSet);
2117
- entry.generator = generator;
2118
- entry.generationCache = {
2119
- key: generationCacheKey,
2120
- result: generated
2121
- };
2122
- entry.source = source;
2123
- entry.sourceFingerprint = sourceFingerprint;
2124
- entry.sourceInput = sourceInput;
2125
- entry.appliedInvalidation = invalidation;
2126
- entry.latestSnapshot = snapshot;
2127
- rootStore.attachDependencies(entry, dependencies);
2128
- rootStore.attachSources(entry, sources);
2129
- if (!engineReused && previousGenerator !== generator) previousGenerator?.dispose?.();
2130
- const css = target === "tailwind" ? generated.rawCss : generated.css;
2131
- const incrementalCss = target === "tailwind" ? generated.incrementalRawCss : generated.incrementalCss;
2132
- return {
2133
- ...generated,
2134
- cache: Object.freeze({
2135
- engine: engineReused,
2136
- output: reusableGeneration !== void 0 || engineReused && incrementalCss === "",
2137
- source: sourceReused
2138
- }),
2139
- classSet: snapshot.classSet,
2140
- css,
2141
- dependencies: snapshot.dependencies,
2142
- incrementalCss,
2143
- rawCandidates: createImmutableSet(generated.rawCandidates),
2144
- revision,
2145
- snapshot,
2146
- sources: internalSnapshot.sources,
2147
- target
2148
- };
2149
- } catch (error) {
2150
- if (!engineReused) generator.dispose?.();
2151
- throw error;
2152
- }
2153
- }
2154
- function getLatestRevision(entry) {
2155
- return entry.latestSnapshot?.roots[0]?.revision;
2156
- }
2157
- function generate(request) {
2158
- ensureActive();
2159
- const entry = rootStore.get(request.id);
2160
- entry.pendingCount += 1;
2161
- const execution = entry.pending.then(() => runGenerate(entry, request));
2162
- entry.pending = execution.finally(() => {
2163
- entry.pendingCount -= 1;
2164
- rootStore.trim();
2165
- }).then(() => void 0, () => void 0);
2166
- return track(execution);
2167
- }
2168
- function createSnapshot(request) {
2169
- ensureActive();
2170
- return createRegisteredCompilerSnapshot(request);
2171
- }
2172
- function finalizeCss(css, options) {
2173
- ensureActive();
2174
- return (0, _weapp_tailwindcss_postcss.finalizeMiniProgramCss)(css, options);
2175
- }
2176
- function finalizeCssRoot(root, options) {
2177
- ensureActive();
2178
- const cloned = root.clone();
2179
- (0, _weapp_tailwindcss_postcss.finalizeMiniProgramCssRoot)(cloned, options);
2180
- return cloned;
2181
- }
2182
- function mergeSnapshots(snapshots) {
2183
- ensureActive();
2184
- return mergeRegisteredCompilerSnapshots(snapshots);
2185
- }
2186
- function invalidate(ids) {
2187
- ensureActive();
2188
- return rootStore.invalidate(ids);
2189
- }
2190
- async function remove(id) {
2191
- if (lifecycle === "disposed") return;
2192
- clearTransformCache();
2193
- await rootStore.remove(id);
2194
- }
2195
- function dispose() {
2196
- if (disposePromise) return disposePromise;
2197
- lifecycle = "disposing";
2198
- disposePromise = (async () => {
2199
- await Promise.allSettled([...activeTasks]);
2200
- clearTransformCache();
2201
- await rootStore.dispose();
2202
- lifecycle = "disposed";
2203
- })();
2204
- return disposePromise;
2205
- }
2206
- return {
2207
- createSnapshot,
2208
- dispose,
2209
- finalizeCss,
2210
- finalizeCssRoot,
2211
- generate,
2212
- invalidate,
2213
- mergeSnapshots,
2214
- remove,
2215
- ...transforms
2216
- };
2217
- }
2218
- //#endregion
2219
- Object.defineProperty(exports, "DefaultCompilationSession", {
2220
- enumerable: true,
2221
- get: function() {
2222
- return DefaultCompilationSession;
2223
- }
2224
- });
2225
- Object.defineProperty(exports, "collectRuntimeClassSet", {
2226
- enumerable: true,
2227
- get: function() {
2228
- return collectRuntimeClassSet;
2229
- }
2230
- });
2231
- Object.defineProperty(exports, "createCompiler", {
2232
- enumerable: true,
2233
- get: function() {
2234
- return createCompiler;
2235
- }
2236
- });
2237
- Object.defineProperty(exports, "createTailwindRuntimeReadyPromise", {
2238
- enumerable: true,
2239
- get: function() {
2240
- return createTailwindRuntimeReadyPromise;
2241
- }
2242
- });
2243
- Object.defineProperty(exports, "ensureRuntimeClassSet", {
2244
- enumerable: true,
2245
- get: function() {
2246
- return ensureRuntimeClassSet;
2247
- }
2248
- });
2249
- Object.defineProperty(exports, "getCompilerContext", {
2250
- enumerable: true,
2251
- get: function() {
2252
- return getCompilerContext;
2253
- }
2254
- });
2255
- Object.defineProperty(exports, "normalizeFrameworkStylePlatform", {
2256
- enumerable: true,
2257
- get: function() {
2258
- return normalizeFrameworkStylePlatform;
2259
- }
2260
- });
2261
- Object.defineProperty(exports, "normalizeStyleHandlerMajorVersion", {
2262
- enumerable: true,
2263
- get: function() {
2264
- return normalizeStyleHandlerMajorVersion;
2265
- }
2266
- });
2267
- Object.defineProperty(exports, "pluginName", {
2268
- enumerable: true,
2269
- get: function() {
2270
- return pluginName;
2271
- }
2272
- });
2273
- Object.defineProperty(exports, "refreshTailwindRuntimeState", {
2274
- enumerable: true,
2275
- get: function() {
2276
- return refreshTailwindRuntimeState;
2277
- }
2278
- });
2279
- Object.defineProperty(exports, "resolveStyleOptionsFromContext", {
2280
- enumerable: true,
2281
- get: function() {
2282
- return resolveStyleOptionsFromContext;
2283
- }
2284
- });
2285
- Object.defineProperty(exports, "shouldSkipJsTransform", {
2286
- enumerable: true,
2287
- get: function() {
2288
- return shouldSkipJsTransform;
2289
- }
2290
- });
2291
- Object.defineProperty(exports, "toCustomAttributesEntities", {
2292
- enumerable: true,
2293
- get: function() {
2294
- return toCustomAttributesEntities;
2295
- }
2296
- });
2297
- Object.defineProperty(exports, "vitePluginName", {
2298
- enumerable: true,
2299
- get: function() {
2300
- return vitePluginName;
2301
- }
2302
- });