@bamboocss/vite 1.45.4 → 1.46.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.
@@ -0,0 +1,2483 @@
1
+ import { compact, createCssUncached, createMergeCss, memo, viewTransitionClassName } from "@bamboocss/shared";
2
+ import { dirname, relative, resolve } from "node:path";
3
+ import MagicString from "magic-string";
4
+ import { resolveTsPathPattern } from "@bamboocss/config/ts-path";
5
+ import { box, maybeBoxNode } from "@bamboocss/extractor";
6
+ import { Node, SyntaxKind, VariableDeclarationKind, ts } from "ts-morph";
7
+ //#region src/fold-analysis.ts
8
+ /**
9
+ * Nodes that *compose* a value out of their children rather than computing one.
10
+ *
11
+ * The boundary of the walk below, and the whole of its precision. Climbing through these
12
+ * keeps a value's provenance: `'red.300'` inside `{ color: 'red.300' }` inside a default is
13
+ * still the default's. Anything else — a call, a function body, a JSX element — produces its
14
+ * value by being evaluated, so what is written inside it is an argument to that evaluation
15
+ * and not the enclosing default's value.
16
+ *
17
+ * Without the boundary, `({ cls = css({ color: 'red.300' }) }) => cls` is rejected: the call's
18
+ * own literal argument is syntactically inside a default, so an unbounded walk calls it one.
19
+ * That is correct code, and rejecting it fails the build.
20
+ */
21
+ const composesValue = (node) => Node.isObjectLiteralExpression(node) || Node.isArrayLiteralExpression(node) || Node.isPropertyAssignment(node) || Node.isShorthandPropertyAssignment(node) || Node.isSpreadAssignment(node) || Node.isSpreadElement(node) || Node.isAsExpression(node) || Node.isParenthesizedExpression(node) || Node.isNonNullExpression(node) || Node.isTypeAssertion(node) || Node.isSatisfiesExpression(node);
22
+ /** Is `inner` written within `outer`? Positions rather than a walk, so it is O(1). */
23
+ const contains = (outer, inner) => outer.getSourceFile() === inner.getSourceFile() && outer.getStart() <= inner.getStart() && inner.getEnd() <= outer.getEnd();
24
+ /**
25
+ * Did this value come from the `= …` of a destructuring binding?
26
+ *
27
+ * `const { tone = 'red.300' } = source` boxes as the literal `'red.300'`: the extractor's
28
+ * `maybeDefinitionValue` tests for an initializer first and returns the boxed default, never
29
+ * reaching the branch that would read `source`. So the default is reported as the value whether
30
+ * or not it is the one that applies.
31
+ *
32
+ * For extraction that is merely optimistic, and deliberately so: a CLI or PostCSS build ships a
33
+ * runtime `css()`, where the default genuinely does apply when the caller omits the key, and it
34
+ * needs a rule behind it. Folding is where the same resolution turns into a wrong answer,
35
+ * because the call is *replaced* by that value.
36
+ *
37
+ * Stops at the first non-composing parent, so a call written inside a default keeps its own
38
+ * provenance, and checks that the binding element was reached through its initializer, so
39
+ * `{ tone = X }`'s name node is not mistaken for its default.
40
+ */
41
+ const isBindingElementDefault = (node) => {
42
+ if (node && Node.isCallExpression(node)) return false;
43
+ let current = node;
44
+ while (current) {
45
+ const parent = current.getParent();
46
+ if (!parent) return false;
47
+ if (Node.isBindingElement(parent)) return parent.getInitializer() === current;
48
+ if (!composesValue(parent)) return false;
49
+ current = parent;
50
+ }
51
+ return false;
52
+ };
53
+ /**
54
+ * The same question asked of a whole box, including how it was resolved.
55
+ *
56
+ * The node a box reports is not always the one its value came from — an empty `{}` default
57
+ * boxes against the call rather than against the `{}` — so the resolution stack is consulted
58
+ * too. A binding element reaches that stack by having been resolved *through*, which is the
59
+ * signal the extractor itself reads when one of these is a conditional's test.
60
+ *
61
+ * Only the entries that are binding elements are examined. Walking up from every other entry
62
+ * was tried and never once changed a verdict across the default spellings or the sandbox's own
63
+ * modules, while accounting for most of the parent hops this does — the stack carries nodes
64
+ * that were never resolved through, including a call's own arguments, so walking from them is
65
+ * both the expensive half and the one that reaches conclusions it has no basis for.
66
+ *
67
+ * A binding element without an initializer carries no default to mistrust: `const { tone } =
68
+ * source` either resolves from `source` or does not resolve at all.
69
+ */
70
+ const isFromBindingDefault = (node) => {
71
+ const own = node.getNode?.();
72
+ if (isBindingElementDefault(own)) return true;
73
+ for (const entry of node.getStack?.() ?? []) {
74
+ if (!Node.isBindingElement(entry) || !entry.getInitializer()) continue;
75
+ if (own && contains(entry, own)) continue;
76
+ return true;
77
+ }
78
+ return false;
79
+ };
80
+ /**
81
+ * Statically resolvable means: every box in the tree carries a known value.
82
+ *
83
+ * `unresolvable` is the extractor saying it could not evaluate a node.
84
+ * `conditional` is a ternary — two possible values, so there is no single string to
85
+ * fold to. `box.fallback` produces an object with no `type` at all, which is likewise
86
+ * not something we can trust.
87
+ */
88
+ const isStaticBox = (node, seen = /* @__PURE__ */ new Set()) => {
89
+ if (!node) return false;
90
+ if (seen.has(node)) return true;
91
+ seen.add(node);
92
+ if (box.isUnresolvable(node) || box.isConditional(node)) return false;
93
+ if (!("type" in node) || node.type == null) return false;
94
+ if (isFromBindingDefault(node)) return false;
95
+ if (box.isLiteral(node) && node.value === void 0) {
96
+ const source = node.getNode?.();
97
+ return Boolean(source && Node.isIdentifier(source) && source.getText() === "undefined");
98
+ }
99
+ if (box.isMap(node)) {
100
+ for (const child of node.value.values()) if (!isStaticBox(child, seen)) return false;
101
+ return true;
102
+ }
103
+ if (box.isArray(node)) {
104
+ for (const child of node.value) if (!isStaticBox(child, seen)) return false;
105
+ return true;
106
+ }
107
+ return true;
108
+ };
109
+ /**
110
+ * Strip the wrappers the extractor strips before it builds a box, so the source node
111
+ * compared against a box is the same node the box was built from.
112
+ *
113
+ * A local copy of the extractor's `unwrapExpression`, which is not part of its public
114
+ * surface. Recognising fewer wrappers than it does is not a cosmetic difference: an
115
+ * unrecognised one leaves an object literal wrapped, and the object checks below skip it.
116
+ */
117
+ const unwrapExpression = (node) => Node.isAsExpression(node) || Node.isParenthesizedExpression(node) || Node.isNonNullExpression(node) || Node.isTypeAssertion(node) || Node.isSatisfiesExpression(node) ? unwrapExpression(node.getExpression()) : node;
118
+ /**
119
+ * Mirrors the parser's evaluator environment, so re-boxing an operand here gets the same
120
+ * answer the extraction did. Left to its default, ts-evaluator presets to `NODE` and
121
+ * would resolve expressions the parser cannot see — making this check *more* permissive
122
+ * than the extraction it is auditing, which is the one thing it must never be.
123
+ */
124
+ const REBOXED = { getEvaluateOptions: () => ({ environment: { preset: "ECMA" } }) };
125
+ const rebox = (node) => maybeBoxNode(unwrapExpression(node), [], REBOXED);
126
+ /**
127
+ * Did this operand resolve to a value the program will actually produce?
128
+ *
129
+ * Producing a box is not enough when the operand is itself a choice: `a || b || c` parses
130
+ * as `(a || b) || c`, so the outer operator is handed whatever the inner one answered —
131
+ * including an arm the extractor invented. Asking only "is there a box" reads that
132
+ * invention as an ordinary literal.
133
+ */
134
+ const resolvesExactly = (node) => {
135
+ const inner = unwrapExpression(node);
136
+ if (!rebox(inner)) return false;
137
+ return Node.isConditionalExpression(inner) || isCollapsedBinary(inner) ? decidedAtBuildTime(inner) : true;
138
+ };
139
+ /**
140
+ * Is this operand's value written here, rather than named?
141
+ *
142
+ * A box records what the extractor resolved a name *through* — a `let`'s initializer, a
143
+ * parameter's default — none of which is what the operand holds when the call runs.
144
+ * `let m = '1'; m = undefined` still boxes as `'1'`, and `({ c = 'red.300' })` still boxes
145
+ * as `'red.300'` for a caller that passed something else. Only a value written at the call
146
+ * site is what it appears to be, so only that can be judged truthy or nullish here.
147
+ */
148
+ const isWrittenHere = (node) => {
149
+ const inner = unwrapExpression(node);
150
+ return Node.isStringLiteral(inner) || Node.isNumericLiteral(inner) || Node.isNoSubstitutionTemplateLiteral(inner) || Node.isObjectLiteralExpression(inner) || Node.isArrayLiteralExpression(inner) || Node.isTrueLiteral(inner) || Node.isFalseLiteral(inner) || inner.getKind() === SyntaxKind.NullKeyword || Node.isPrefixUnaryExpression(inner) && Node.isNumericLiteral(inner.getOperand());
151
+ };
152
+ /** An inline value's truthiness, which its box carries directly. */
153
+ const isTruthy = (boxNode) => box.isLiteral(boxNode) ? Boolean(boxNode.value) : box.isMap(boxNode) || box.isArray(boxNode) || box.isObject(boxNode);
154
+ /**
155
+ * Did the extractor *decide* this choice, or guess at it?
156
+ *
157
+ * `a ? b : c`, `a || b` and `a && b` are asked "what styles could this produce", and when
158
+ * one arm does not evaluate the extractor answers with the other rather than refusing
159
+ * (`maybe-box-node.ts`, `whenTrueValue && !whenFalseValue`). That is right for generating
160
+ * CSS — emit rules for whatever might be used — and wrong for rewriting source, where the
161
+ * arm it kept becomes the only one that runs.
162
+ *
163
+ * For a ternary the tell is the arms: it guessed exactly when one produced a box and the
164
+ * other did not. For a short-circuit the answer is always the left operand, so what has to
165
+ * be established is that the left is the side that wins.
166
+ */
167
+ const decidedAtBuildTime = (node) => {
168
+ if (Node.isConditionalExpression(node)) return resolvesExactly(node.getWhenTrue()) && resolvesExactly(node.getWhenFalse());
169
+ const operator = node.getOperatorToken().getKind();
170
+ if (!SHORT_CIRCUIT.includes(operator)) return false;
171
+ if (!isWrittenHere(node.getLeft())) return false;
172
+ const left = rebox(node.getLeft());
173
+ if (!left) return false;
174
+ if (operator === SyntaxKind.BarBarToken) return isTruthy(left);
175
+ if (operator === SyntaxKind.QuestionQuestionToken) return !box.isLiteral(left) || left.value != null;
176
+ return isTruthy(left) ? resolvesExactly(node.getRight()) : true;
177
+ };
178
+ const SHORT_CIRCUIT = [
179
+ SyntaxKind.AmpersandAmpersandToken,
180
+ SyntaxKind.BarBarToken,
181
+ SyntaxKind.QuestionQuestionToken
182
+ ];
183
+ /**
184
+ * Every binary form the extractor collapses to one operand — the short-circuits plus the
185
+ * comparisons, which `isLogicalSyntax` sends down the same path even though their value is
186
+ * a boolean rather than either side.
187
+ *
188
+ * Hoisted rather than built per call: `accountsForSource` asks this for every property of
189
+ * every candidate, and rebuilding a thirteen-element list each time is not free.
190
+ */
191
+ const COLLAPSED_BINARY = new Set([
192
+ ...SHORT_CIRCUIT,
193
+ SyntaxKind.EqualsEqualsToken,
194
+ SyntaxKind.EqualsEqualsEqualsToken,
195
+ SyntaxKind.ExclamationEqualsToken,
196
+ SyntaxKind.ExclamationEqualsEqualsToken,
197
+ SyntaxKind.GreaterThanToken,
198
+ SyntaxKind.GreaterThanEqualsToken,
199
+ SyntaxKind.LessThanToken,
200
+ SyntaxKind.LessThanEqualsToken,
201
+ SyntaxKind.InKeyword,
202
+ SyntaxKind.InstanceOfKeyword
203
+ ]);
204
+ const isCollapsedBinary = (node) => Node.isBinaryExpression(node) && COLLAPSED_BINARY.has(node.getOperatorToken().getKind());
205
+ /**
206
+ * Does the extracted box account for every property the source declares?
207
+ *
208
+ * `isStaticBox` is not sufficient on its own. The extractor *omits* what it cannot
209
+ * evaluate rather than marking it unresolvable, so `css({ color: 'red.300', ...rest })`
210
+ * yields a perfectly static-looking map holding only `color`. Folding that produces
211
+ * `"c_red.300"` and silently drops everything `rest` contributed.
212
+ *
213
+ * So the source is the authority on what the call contains, and anything the box does
214
+ * not account for disqualifies the fold:
215
+ *
216
+ * - a declared property missing from the map (its value did not evaluate)
217
+ * - a computed key, which we cannot match against the map by name
218
+ * - a spread, unless it is an inline object literal
219
+ *
220
+ * Spreads are the conservative case. `{ ...base }` where `base` is a static local
221
+ * object *is* resolved by the extractor, but a resolved spread and an unresolved one
222
+ * are indistinguishable once flattened into the map — both just contribute keys, or
223
+ * fail to. Rather than guess and erase evaluation the compiler cannot reproduce, the call
224
+ * is rejected.
225
+ */
226
+ /**
227
+ * What a property's value is written as. A shorthand names it, so the name *is* the
228
+ * expression — reading an initializer that is not there reports the property as having no
229
+ * source, and everything hidden behind the name goes unchecked.
230
+ */
231
+ const valueOf = (property) => Node.isPropertyAssignment(property) ? property.getInitializer() : Node.isShorthandPropertyAssignment(property) ? property.getNameNode() : void 0;
232
+ const accountsForSource = (node, boxNode) => {
233
+ if (!node) return true;
234
+ const unwrapped = unwrapExpression(node);
235
+ if ((Node.isConditionalExpression(unwrapped) || isCollapsedBinary(unwrapped)) && !box.isConditional(boxNode) && !decidedAtBuildTime(unwrapped)) return false;
236
+ if (Node.isArrayLiteralExpression(unwrapped)) {
237
+ if (!box.isArray(boxNode)) return false;
238
+ const elements = unwrapped.getElements();
239
+ if (elements.length !== boxNode.value.length) return false;
240
+ return elements.every((element, index) => accountsForSource(element, boxNode.value[index]));
241
+ }
242
+ if (!Node.isObjectLiteralExpression(unwrapped)) {
243
+ const origin = box.isMap(boxNode) ? boxNode.getNode() : void 0;
244
+ return !origin || origin === unwrapped || !Node.isObjectLiteralExpression(origin) ? true : accountsForSource(origin, boxNode);
245
+ }
246
+ if (!box.isMap(boxNode)) return false;
247
+ for (const property of unwrapped.getProperties()) {
248
+ if (Node.isSpreadAssignment(property)) {
249
+ const expression = unwrapExpression(property.getExpression());
250
+ if (Node.isObjectLiteralExpression(expression)) continue;
251
+ const walked = boxNode.resolvedSpreads?.find((entry) => entry.node === expression);
252
+ if (!walked) return false;
253
+ if (!accountsForSource(walked.box.getNode(), walked.box)) return false;
254
+ continue;
255
+ }
256
+ if (Node.isMethodDeclaration(property) || Node.isGetAccessorDeclaration(property) || Node.isSetAccessorDeclaration(property)) return false;
257
+ if (!Node.isPropertyAssignment(property) && !Node.isShorthandPropertyAssignment(property)) return false;
258
+ const nameNode = property.getNameNode();
259
+ if (Node.isComputedPropertyName(nameNode)) return false;
260
+ const key = Node.isStringLiteral(nameNode) || Node.isNumericLiteral(nameNode) ? String(nameNode.getLiteralValue()) : nameNode.getText();
261
+ const value = valueOf(property);
262
+ if (value && Node.isIdentifier(value) && value.getText() === "undefined") continue;
263
+ if (!boxNode.value.has(key)) return false;
264
+ if (!accountsForSource(value, boxNode.value.get(key))) return false;
265
+ }
266
+ return true;
267
+ };
268
+ /**
269
+ * Memo keyed on a file, thrown away when its text is replaced.
270
+ *
271
+ * A plain `WeakMap<SourceFile, …>` is wrong here: ts-morph reuses the wrapper when a path
272
+ * is re-added with new text — which is what a watch rebuild does — so it would answer for
273
+ * the previous revision. Comparing against the text it was computed from costs a
274
+ * reference check while the file is unchanged, since `getFullText()` hands back the same
275
+ * string instance.
276
+ */
277
+ const byText = (cache, sourceFile, compute) => {
278
+ const text = sourceFile.getFullText();
279
+ const hit = cache.get(sourceFile);
280
+ if (hit && hit.text === text) return hit.value;
281
+ const value = compute();
282
+ cache.set(sourceFile, {
283
+ text,
284
+ value
285
+ });
286
+ return value;
287
+ };
288
+ /**
289
+ * Every name declared at module scope, which is what an added import could collide with.
290
+ *
291
+ * This replaced `sourceFile.getLocals()`. That was precise, but it goes through the
292
+ * compiler's symbol table, and reaching for it binds the program — including every
293
+ * `.d.ts` the module's imports pull in. It cost ~8ms on a ten-line file and grew with the
294
+ * project, which was invisible while only a partial split reached it and became the
295
+ * dominant cost once open-ended values started lowering too.
296
+ *
297
+ * A syntactic walk answers the same question: a binding in a nested *function* cannot
298
+ * collide with a module-scope import, and one that shadows it *at the call site* is what
299
+ * `isShadowed` is for. Memoized against the file's text rather than the file, since
300
+ * ts-morph reuses the wrapper across a re-add and a plain `WeakMap` would answer for the
301
+ * previous revision. Uncached it is re-walked per candidate, which is quadratic in a
302
+ * module of many elements.
303
+ */
304
+ const moduleScopeCache = /* @__PURE__ */ new WeakMap();
305
+ const declaredAtModuleScope = (sourceFile) => byText(moduleScopeCache, sourceFile, () => collectModuleScopeNames(sourceFile));
306
+ const collectModuleScopeNames = (sourceFile) => {
307
+ const names = /* @__PURE__ */ new Set();
308
+ const addBinding = (node) => {
309
+ if (!node) return;
310
+ if (Node.isObjectBindingPattern(node) || Node.isArrayBindingPattern(node)) {
311
+ for (const element of node.getElements()) if (Node.isBindingElement(element)) addBinding(element.getNameNode());
312
+ return;
313
+ }
314
+ if (Node.isIdentifier(node)) names.add(node.getText());
315
+ };
316
+ const addDeclarations = (list) => {
317
+ if (Node.isVariableStatement(list)) {
318
+ for (const declaration of list.getDeclarations()) addBinding(declaration.getNameNode());
319
+ return;
320
+ }
321
+ if (Node.isVariableDeclarationList(list)) for (const declaration of list.getDeclarations()) addBinding(declaration.getNameNode());
322
+ };
323
+ const isVar = (node) => (Node.isVariableStatement(node) || Node.isVariableDeclarationList(node)) && node.getDeclarationKind() === VariableDeclarationKind.Var;
324
+ /**
325
+ * `var` is scoped to the enclosing *function*, not the enclosing block, so one written
326
+ * inside any statement at the top level still binds at module scope. Walking only the
327
+ * top-level statements missed every one of them, and each emitted a duplicate binding.
328
+ *
329
+ * Only statement containers are followed. A function or class body opens a new variable
330
+ * scope, so a `var` inside one cannot collide with a module-level import.
331
+ */
332
+ const addHoistedVars = (node) => {
333
+ if (isVar(node)) {
334
+ addDeclarations(node);
335
+ return;
336
+ }
337
+ if (Node.isBlock(node)) {
338
+ for (const statement of node.getStatements()) addHoistedVars(statement);
339
+ return;
340
+ }
341
+ if (Node.isIfStatement(node)) {
342
+ addHoistedVars(node.getThenStatement());
343
+ const otherwise = node.getElseStatement();
344
+ if (otherwise) addHoistedVars(otherwise);
345
+ return;
346
+ }
347
+ if (Node.isForStatement(node)) {
348
+ const initializer = node.getInitializer();
349
+ if (initializer) addHoistedVars(initializer);
350
+ addHoistedVars(node.getStatement());
351
+ return;
352
+ }
353
+ if (Node.isForInStatement(node) || Node.isForOfStatement(node)) {
354
+ addHoistedVars(node.getInitializer());
355
+ addHoistedVars(node.getStatement());
356
+ return;
357
+ }
358
+ if (Node.isWhileStatement(node) || Node.isDoStatement(node) || Node.isWithStatement(node)) {
359
+ addHoistedVars(node.getStatement());
360
+ return;
361
+ }
362
+ if (Node.isLabeledStatement(node)) {
363
+ addHoistedVars(node.getStatement());
364
+ return;
365
+ }
366
+ if (Node.isTryStatement(node)) {
367
+ addHoistedVars(node.getTryBlock());
368
+ const caught = node.getCatchClause();
369
+ if (caught) addHoistedVars(caught.getBlock());
370
+ const finally_ = node.getFinallyBlock();
371
+ if (finally_) addHoistedVars(finally_);
372
+ return;
373
+ }
374
+ if (Node.isSwitchStatement(node)) for (const clause of node.getCaseBlock().getClauses()) for (const statement of clause.getStatements()) addHoistedVars(statement);
375
+ };
376
+ for (const statement of sourceFile.getStatements()) {
377
+ if (Node.isVariableStatement(statement)) {
378
+ addDeclarations(statement);
379
+ continue;
380
+ }
381
+ if (Node.isImportDeclaration(statement)) {
382
+ addBinding(statement.getDefaultImport());
383
+ addBinding(statement.getNamespaceImport());
384
+ for (const named of statement.getNamedImports()) addBinding(named.getAliasNode() ?? named.getNameNode());
385
+ continue;
386
+ }
387
+ if (Node.isImportEqualsDeclaration(statement)) {
388
+ addBinding(statement.getNameNode());
389
+ continue;
390
+ }
391
+ if (Node.isFunctionDeclaration(statement) || Node.isClassDeclaration(statement) || Node.isEnumDeclaration(statement) || Node.isModuleDeclaration(statement) || Node.isTypeAliasDeclaration(statement) || Node.isInterfaceDeclaration(statement)) {
392
+ addBinding(statement.getNameNode());
393
+ continue;
394
+ }
395
+ addHoistedVars(statement);
396
+ }
397
+ return names;
398
+ };
399
+ /**
400
+ * Every identifier in the module, grouped by the name it spells.
401
+ *
402
+ * Built once per pass and handed to each lookup, because walking the whole tree per binding
403
+ * made that O(bindings x identifiers): a module declaring ten recipes walked its identifiers
404
+ * ten times.
405
+ *
406
+ * ## Why this is a raw walk rather than `getDescendantsOfKind`
407
+ *
408
+ * `SyntaxKind.Identifier` sorts *below* `SyntaxKind.FirstNode`, which is what ts-morph tests to
409
+ * decide whether it may search the parse tree. For a kind below that line it falls back to
410
+ * materialising the whole **token** tree — every brace, comma and keyword becomes a ts-morph node
411
+ * on the way to collecting the identifiers. On 55 KB of real tsx that measured 22ms against
412
+ * 0.22ms for the same collection over compiler nodes, and the node cache does not help: a second
413
+ * call cost the same 22ms.
414
+ *
415
+ * Wrapping is what costs, so only the buckets a caller actually reads are wrapped, on the first
416
+ * read and cached after. Nothing enumerates this index — both callers ask for one name — so the
417
+ * rest is never built. `_getNodeFromCompilerNode` is ts-morph's own memoized wrapper factory, so
418
+ * a node handed back here is the very object `getDescendantsOfKind` would have returned, which
419
+ * `localReferencesTo` depends on: it compares against the declaration by identity.
420
+ *
421
+ * JSDoc is walked explicitly. `ts.forEachChild` does not descend into it, while the token path
422
+ * this replaces does, so a name mentioned only in a `@type` annotation was previously found and
423
+ * would otherwise stop being — a silent narrowing of what counts as a surviving reference.
424
+ * Keyed on `escapedText` because that is what ts-morph's `Identifier.getText()` returns: the name
425
+ * as the compiler resolves it, so `\u0062adge` and `badge` share a bucket exactly as before.
426
+ *
427
+ * Deliberately *not* memoized across passes, unlike the module-scope names beside it. That
428
+ * cache holds strings, which outlive anything; this one holds nodes, and a node does not
429
+ * survive its source file being replaced — `addSourceFile` overwrites, which forgets every
430
+ * node previously taken from it. Keying on the source text does not help, because identical
431
+ * text re-parsed is a fresh tree: the cache hits and returns nodes that throw
432
+ * `Attempted to get information from a node that was removed or forgotten` on the next read.
433
+ */
434
+ const identifierIndex = (sourceFile) => {
435
+ const compilerNodes = /* @__PURE__ */ new Map();
436
+ const collect = (node) => {
437
+ if (node.kind === ts.SyntaxKind.Identifier) {
438
+ const name = String(node.escapedText);
439
+ const known = compilerNodes.get(name);
440
+ if (known) known.push(node);
441
+ else compilerNodes.set(name, [node]);
442
+ }
443
+ const jsDoc = node.jsDoc;
444
+ if (jsDoc) for (const doc of jsDoc) collect(doc);
445
+ ts.forEachChild(node, collect);
446
+ };
447
+ ts.forEachChild(sourceFile.compilerNode, collect);
448
+ const wrapped = /* @__PURE__ */ new Map();
449
+ const wrap = sourceFile;
450
+ return { get: (name) => {
451
+ const known = wrapped.get(name);
452
+ if (known) return known;
453
+ const nodes = (compilerNodes.get(name) ?? []).map((node) => wrap._getNodeFromCompilerNode(node));
454
+ wrapped.set(name, nodes);
455
+ return nodes;
456
+ } };
457
+ };
458
+ const localReferencesTo = (index, name, declaration) => {
459
+ const references = [];
460
+ for (const identifier of index.get(name)) {
461
+ if (identifier === declaration) continue;
462
+ const parent = identifier.getParent();
463
+ if (!parent) continue;
464
+ if (Node.isPropertyAccessExpression(parent) && parent.getNameNode() === identifier) continue;
465
+ if (Node.isPropertyAssignment(parent) && parent.getNameNode() === identifier) continue;
466
+ if (Node.isBindingElement(parent) && parent.getPropertyNameNode() === identifier) continue;
467
+ if ((Node.isJsxOpeningElement(parent) || Node.isJsxSelfClosingElement(parent) || Node.isJsxClosingElement(parent)) && parent.getTagNameNode() === identifier) continue;
468
+ if (Node.isJsxAttribute(parent) && parent.getNameNode() === identifier) continue;
469
+ if ((Node.isMethodDeclaration(parent) || Node.isPropertyDeclaration(parent) || Node.isGetAccessorDeclaration(parent) || Node.isSetAccessorDeclaration(parent) || Node.isMethodSignature(parent) || Node.isPropertySignature(parent) || Node.isEnumMember(parent)) && parent.getNameNode() === identifier) continue;
470
+ if ((Node.isVariableDeclaration(parent) || Node.isParameterDeclaration(parent) || Node.isFunctionDeclaration(parent) || Node.isClassDeclaration(parent) || Node.isBindingElement(parent)) && parent.getNameNode() === identifier) continue;
471
+ if (Node.isImportSpecifier(parent) || Node.isExportSpecifier(parent)) {
472
+ if (parent.getNameNode() !== identifier) continue;
473
+ if (Node.isExportSpecifier(parent)) {
474
+ references.push(identifier);
475
+ continue;
476
+ }
477
+ continue;
478
+ }
479
+ references.push(identifier);
480
+ }
481
+ return references;
482
+ };
483
+ //#endregion
484
+ //#region src/fold-recipe.ts
485
+ /**
486
+ * Binding name → the config it was declared with.
487
+ *
488
+ * Built from the definitions the parser already recorded, walking each one to the declaration
489
+ * that names it. The parser records a definition under the name it was *imported* as (`cva`),
490
+ * and a call under the name the file *bound* (`badge`); this is what joins the two.
491
+ *
492
+ * Slot and ordinary recipes share one representation.
493
+ */
494
+ const collectRecipeConfigs = (parserResult) => {
495
+ const configs = /* @__PURE__ */ new Map();
496
+ const definitions = [...parserResult.cva, ...parserResult.sva];
497
+ for (const definition of definitions) {
498
+ const node = definition.box?.getNode?.();
499
+ if (!node) continue;
500
+ const nameNode = ((Node.isCallExpression(node) ? node : node.getFirstAncestorByKind(SyntaxKind.CallExpression))?.getFirstAncestorByKind(SyntaxKind.VariableDeclaration))?.getNameNode();
501
+ if (!nameNode || !Node.isIdentifier(nameNode)) continue;
502
+ if (definition.data?.length !== 1) {
503
+ configs.set(nameNode.getText(), AMBIGUOUS);
504
+ continue;
505
+ }
506
+ const config = definition.data[0];
507
+ if (!config || typeof config !== "object") continue;
508
+ if (configs.has(nameNode.getText())) {
509
+ configs.set(nameNode.getText(), AMBIGUOUS);
510
+ continue;
511
+ }
512
+ configs.set(nameNode.getText(), {
513
+ config,
514
+ box: definition.box
515
+ });
516
+ }
517
+ return configs;
518
+ };
519
+ /** Pick a complete precompiled StyleSet for one or more runtime recipe axes. */
520
+ const RECIPE_MAP_HELPER = "cvaMap";
521
+ /** Guard the exact compiler against accidentally materialising an enormous Cartesian product. */
522
+ const DEFAULT_MAX_RECIPE_STATES = 65536;
523
+ /** What `recipe.splitVariantProps` calls, reached directly once the call is lowered. */
524
+ const SPLIT_PROPS_HELPER = "splitProps";
525
+ /** Marker for a binding the fold must never resolve — declared twice, or unresolvable. */
526
+ const AMBIGUOUS = Object.freeze({
527
+ config: {},
528
+ box: void 0
529
+ });
530
+ /** `.size`, or `["x-large"]` when the variant is not a valid identifier. */
531
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
532
+ const propertyAccess = (key) => IDENTIFIER.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
533
+ const LITERAL_KINDS = new Set([
534
+ SyntaxKind.StringLiteral,
535
+ SyntaxKind.NoSubstitutionTemplateLiteral,
536
+ SyntaxKind.NumericLiteral,
537
+ SyntaxKind.TrueKeyword,
538
+ SyntaxKind.FalseKeyword
539
+ ]);
540
+ /**
541
+ * The value a literal node denotes, or `undefined` for anything else.
542
+ *
543
+ * Read off the node rather than from the extractor's resolved data, because that data is lossy
544
+ * in the direction that matters: a property it could not resolve is *dropped*, so `badge({ tone })`
545
+ * and `badge({})` are identical there. Folding the first as if it were the second emits a class
546
+ * string missing the variant — the element renders, wrongly, with no report.
547
+ */
548
+ const literalValue = (node) => {
549
+ if (!node || !LITERAL_KINDS.has(node.getKind())) return void 0;
550
+ if (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) return node.getLiteralValue();
551
+ if (Node.isNumericLiteral(node)) return node.getLiteralValue();
552
+ if (node.getKind() === SyntaxKind.TrueKeyword) return true;
553
+ if (node.getKind() === SyntaxKind.FalseKeyword) return false;
554
+ };
555
+ /**
556
+ * The property name a key node denotes.
557
+ *
558
+ * Read off the node rather than unquoted from its text. `{ '\\u0074one': 'a' }` names the
559
+ * variant `tone`, and stripping the surrounding quotes leaves the escape uninterpreted — so
560
+ * the variant did not match, its class was dropped, and the element rendered without it. A
561
+ * numeric key normalises the same way: `{ 0x10: 'a' }` is the key `16`.
562
+ */
563
+ const propertyKey = (nameNode) => {
564
+ if (Node.isIdentifier(nameNode)) return nameNode.getText();
565
+ if (Node.isStringLiteral(nameNode) || Node.isNoSubstitutionTemplateLiteral(nameNode)) return nameNode.getLiteralValue();
566
+ if (Node.isNumericLiteral(nameNode)) return String(nameNode.getLiteralValue());
567
+ };
568
+ /**
569
+ * Make a generated compile helper callable at this call site, by whatever name the file gives it.
570
+ *
571
+ * Unlike `cx`, an inline recipe's callee is a local binding, so
572
+ * there is nothing to match — the host here is any import of the generated css module, which
573
+ * a file defining a recipe necessarily has, since `cva` came from it.
574
+ */
575
+ const ensureRecipeHelperImport = (imported, call, isBambooCssModule, isGeneratedCssModule, isShadowed, newImportModule, helperModuleFromSubpath) => {
576
+ const sourceFile = call.getSourceFile();
577
+ let host;
578
+ let subpathModule;
579
+ for (const declaration of sourceFile.getImportDeclarations()) {
580
+ const mod = declaration.getModuleSpecifierValue();
581
+ if (declaration.isTypeOnly()) continue;
582
+ for (const named of declaration.getNamedImports()) {
583
+ if (named.isTypeOnly()) continue;
584
+ if (named.getNameNode().getText() === imported) {
585
+ if (!isBambooCssModule(mod)) return void 0;
586
+ const local = (named.getAliasNode() ?? named.getNameNode()).getText();
587
+ return isShadowed(call, local) ? void 0 : { name: local };
588
+ }
589
+ }
590
+ if (!host && isGeneratedCssModule(mod) && declaration.getNamedImports().length > 0) host = declaration;
591
+ if (!subpathModule) subpathModule = helperModuleFromSubpath?.(mod);
592
+ }
593
+ const fallbackModule = newImportModule ?? subpathModule;
594
+ if (!host && !fallbackModule) return void 0;
595
+ if (declaredAtModuleScope(sourceFile).has(imported)) return void 0;
596
+ if (isShadowed(call, imported)) return void 0;
597
+ if (!host) {
598
+ const anchor = sourceFile.getImportDeclarations().at(-1);
599
+ if (!anchor) return void 0;
600
+ return {
601
+ name: imported,
602
+ insert: {
603
+ pos: anchor.getEnd(),
604
+ names: [imported],
605
+ module: fallbackModule
606
+ }
607
+ };
608
+ }
609
+ const last = host.getNamedImports().at(-1);
610
+ if (!last) return void 0;
611
+ return {
612
+ name: imported,
613
+ insert: {
614
+ pos: last.getEnd(),
615
+ names: [imported]
616
+ }
617
+ };
618
+ };
619
+ /**
620
+ * Lower one invocation, or say why not.
621
+ *
622
+ * Every property written at the call site has to be a literal. A selection is not additive —
623
+ * an unresolved variant does not merely omit a class, it can change which of several the
624
+ * recipe applies — so a partially-known selection is not foldable at all.
625
+ */
626
+ const lowerRecipeCall = (call, entry, styleCompiler, isInert, resolvedSelection, slot, maxRecipeStates = DEFAULT_MAX_RECIPE_STATES) => {
627
+ if (!entry || entry === AMBIGUOUS) return {
628
+ kind: "decline",
629
+ reason: "unknown-recipe"
630
+ };
631
+ const { config } = entry;
632
+ if (config.slots !== void 0) {
633
+ if (!Array.isArray(config.slots) || slot !== void 0 && !config.slots.includes(slot)) return {
634
+ kind: "decline",
635
+ reason: "unsupported-shape"
636
+ };
637
+ } else if (slot) return {
638
+ kind: "decline",
639
+ reason: "unsupported-shape"
640
+ };
641
+ if (!config.base && !config.variants && !config.className) return {
642
+ kind: "decline",
643
+ reason: "unknown-recipe"
644
+ };
645
+ if (!Node.isCallExpression(call)) return {
646
+ kind: "decline",
647
+ reason: "unsupported-shape"
648
+ };
649
+ const args = call.getArguments();
650
+ if (args.length > 1) return {
651
+ kind: "decline",
652
+ reason: "unsupported-shape"
653
+ };
654
+ const selection = {};
655
+ /** Variant → the source expression selecting it, for axes that stay runtime decisions. */
656
+ const dynamicAxes = /* @__PURE__ */ new Map();
657
+ /**
658
+ * Variants whose expression could run something, in the order the source evaluates them.
659
+ *
660
+ * The text is kept, not just the key: a later property writing the same key replaces the
661
+ * entry in `dynamicAxes`, and the expression recorded here would then never be emitted.
662
+ */
663
+ const effectful = [];
664
+ if (args.length === 1) {
665
+ const arg = args[0];
666
+ if (!arg) return {
667
+ kind: "decline",
668
+ reason: "dynamic"
669
+ };
670
+ /**
671
+ * `input(variantProps)` — a selection the build cannot see inside.
672
+ *
673
+ * The compiled recipe contract accepts scalar declared variant values. A conditional
674
+ * object is not a finite selection value; responsiveness belongs inside a variant's style
675
+ * declaration, where the compiler can materialize its conditions ahead of time.
676
+ *
677
+ * The complete StyleSets are knowable: the config declares every scalar value each axis
678
+ * accepts. This is the shape a wrapper component takes, where variants are its public API
679
+ * and therefore cannot be literals by definition.
680
+ *
681
+ * An identifier only. Each variant reads the binding again, and re-reading anything else —
682
+ * a call, a property access — would evaluate it once per axis instead of once.
683
+ */
684
+ if (Node.isIdentifier(arg)) {
685
+ const binding = arg.getText();
686
+ for (const key of Object.keys(config.variants ?? {})) dynamicAxes.set(key, `${binding}${propertyAccess(key)}`);
687
+ } else if (!Node.isObjectLiteralExpression(arg)) return {
688
+ kind: "decline",
689
+ reason: "dynamic"
690
+ };
691
+ else for (const property of arg.getProperties()) {
692
+ if (Node.isSpreadAssignment(property)) return {
693
+ kind: "decline",
694
+ reason: "dynamic"
695
+ };
696
+ if (Node.isShorthandPropertyAssignment(property)) {
697
+ dynamicAxes.set(property.getName(), property.getName());
698
+ delete selection[property.getName()];
699
+ continue;
700
+ }
701
+ if (!Node.isPropertyAssignment(property)) return {
702
+ kind: "decline",
703
+ reason: "dynamic"
704
+ };
705
+ const nameNode = property.getNameNode();
706
+ if (Node.isComputedPropertyName(nameNode)) return {
707
+ kind: "decline",
708
+ reason: "dynamic"
709
+ };
710
+ const key = propertyKey(nameNode);
711
+ if (key === void 0) return {
712
+ kind: "decline",
713
+ reason: "dynamic"
714
+ };
715
+ const initializer = property.getInitializer();
716
+ if (initializer && !isInert(initializer)) {
717
+ if (!Object.hasOwn(config.variants ?? {}, key)) return {
718
+ kind: "decline",
719
+ reason: "dynamic"
720
+ };
721
+ effectful.push({
722
+ key,
723
+ text: initializer.getText()
724
+ });
725
+ dynamicAxes.set(key, initializer.getText());
726
+ delete selection[key];
727
+ continue;
728
+ }
729
+ const literal = literalValue(initializer);
730
+ if (literal !== void 0) {
731
+ selection[key] = literal;
732
+ dynamicAxes.delete(key);
733
+ continue;
734
+ }
735
+ if (!resolvedSelection || !Object.hasOwn(resolvedSelection, key)) {
736
+ if (!initializer) return {
737
+ kind: "decline",
738
+ reason: "dynamic"
739
+ };
740
+ dynamicAxes.set(key, initializer.getText());
741
+ delete selection[key];
742
+ continue;
743
+ }
744
+ const value = resolvedSelection[key];
745
+ if (value !== null && typeof value === "object") return {
746
+ kind: "decline",
747
+ reason: "dynamic"
748
+ };
749
+ selection[key] = value;
750
+ dynamicAxes.delete(key);
751
+ }
752
+ }
753
+ /**
754
+ * Every expression that could run something has to reach the output carrying its own text.
755
+ *
756
+ * A later property writing the same key replaces it in `dynamicAxes` — `badge({ tone: a(),
757
+ * tone: 'b' })` is last-wins for the *value*, but `a()` still runs, and emitting only the
758
+ * literal would delete it. Duplicate keys are a type error in TypeScript; the fold does not
759
+ * typecheck and does transform `.js`, so this is reachable.
760
+ */
761
+ const everyEffectSurvives = () => effectful.every(({ key, text }) => dynamicAxes.get(key) === text);
762
+ const compiledSelection = (selected) => {
763
+ if (Array.isArray(config.slots) && slot === void 0) {
764
+ const slots = {};
765
+ const classNames = /* @__PURE__ */ new Set();
766
+ for (const slotName of config.slots) {
767
+ const styles = styleCompiler.resolveRecipe(config, selected, slotName);
768
+ if (!styles) return void 0;
769
+ const className = styleCompiler.className(styles);
770
+ slots[slotName] = className;
771
+ for (const token of className.split(" ")) if (token) classNames.add(token);
772
+ }
773
+ return {
774
+ value: slots,
775
+ classNames: [...classNames]
776
+ };
777
+ }
778
+ const styles = styleCompiler.resolveRecipe(config, selected, slot);
779
+ if (!styles) return void 0;
780
+ const className = styleCompiler.className(styles);
781
+ return {
782
+ value: className,
783
+ classNames: className.split(" ").filter(Boolean),
784
+ styles
785
+ };
786
+ };
787
+ if (dynamicAxes.size === 0) {
788
+ if (!everyEffectSurvives()) return {
789
+ kind: "decline",
790
+ reason: "dynamic"
791
+ };
792
+ const compiled = compiledSelection(selection);
793
+ if (!compiled) return {
794
+ kind: "decline",
795
+ reason: "dynamic"
796
+ };
797
+ if (typeof compiled.value === "string") return {
798
+ kind: "class",
799
+ className: compiled.value,
800
+ styles: compiled.styles
801
+ };
802
+ return {
803
+ kind: "slots",
804
+ expression: JSON.stringify(compiled.value),
805
+ classNames: compiled.classNames,
806
+ dynamic: false
807
+ };
808
+ }
809
+ if (!everyEffectSurvives()) return {
810
+ kind: "decline",
811
+ reason: "dynamic"
812
+ };
813
+ if (effectful.length > 1) {
814
+ const variantOrder = Object.keys(config.variants ?? {});
815
+ const keys = effectful.map((entry) => entry.key);
816
+ if ([...keys].sort((a, b) => variantOrder.indexOf(a) - variantOrder.indexOf(b)).join("\0") !== keys.join("\0")) return {
817
+ kind: "decline",
818
+ reason: "dynamic"
819
+ };
820
+ }
821
+ for (const key of [...dynamicAxes.keys()]) if (!Object.hasOwn(config.variants ?? {}, key)) dynamicAxes.delete(key);
822
+ if (dynamicAxes.size === 0) {
823
+ const compiled = compiledSelection(selection);
824
+ if (!compiled) return {
825
+ kind: "decline",
826
+ reason: "dynamic"
827
+ };
828
+ if (typeof compiled.value === "string") return {
829
+ kind: "class",
830
+ className: compiled.value,
831
+ styles: compiled.styles
832
+ };
833
+ return {
834
+ kind: "slots",
835
+ expression: JSON.stringify(compiled.value),
836
+ classNames: compiled.classNames,
837
+ dynamic: false
838
+ };
839
+ }
840
+ /**
841
+ * Compile the finite recipe state space into a reduced decision table.
842
+ *
843
+ * Each leaf is a *complete* final StyleSet. This matters for declarations overridden by
844
+ * variants and compounds: selecting independent per-axis atoms would put both values in
845
+ * the utility layer and let stylesheet order, rather than the recipe's merge order, pick
846
+ * the winner. Complete leaves retain the same precedence while sharing their atoms with
847
+ * every `css()` and recipe in the build.
848
+ *
849
+ * `undefined` is its own edge because it restores a default variant. `null` and any
850
+ * undeclared value take the miss edge and explicitly suppress that default. Declared
851
+ * values use string keys, matching JavaScript's property-key coercion in the recipe
852
+ * runtime. A flat alternating key/value array avoids the special `__proto__` semantics
853
+ * of an object literal.
854
+ */
855
+ const axes = Object.keys(config.variants ?? {}).filter((key) => dynamicAxes.has(key));
856
+ const stateCount = axes.reduce((product, axis) => product * (Object.keys(config.variants?.[axis] ?? {}).length + 2), 1);
857
+ if (stateCount > maxRecipeStates) throw new Error(`Static recipe compilation would inspect ${stateCount.toLocaleString("en-US")} selections across ${axes.length} runtime variant axes, above maxRecipeStates=${maxRecipeStates.toLocaleString("en-US")}. Make one or more axes statically known, split the recipe, or raise the limit explicitly.`);
858
+ const expressions = axes.map((axis) => dynamicAxes.get(axis));
859
+ const wholeSlots = Array.isArray(config.slots) && slot === void 0;
860
+ return {
861
+ kind: "dynamic-style",
862
+ map: {
863
+ outputKind: wholeSlots ? "slots" : "class",
864
+ compile(before = [], after = []) {
865
+ const nodes = [];
866
+ const nodeByShape = /* @__PURE__ */ new Map();
867
+ const leaves = [];
868
+ const leafByShape = /* @__PURE__ */ new Map();
869
+ const emittedClasses = /* @__PURE__ */ new Set();
870
+ const leaf = (dynamicSelection) => {
871
+ const selected = {
872
+ ...selection,
873
+ ...dynamicSelection
874
+ };
875
+ if (wholeSlots) {
876
+ const compiled = compiledSelection(selected);
877
+ if (!compiled || typeof compiled.value === "string") return internLeaf("");
878
+ for (const token of compiled.classNames) emittedClasses.add(token);
879
+ return internLeaf(compiled.value);
880
+ }
881
+ const styles = styleCompiler.resolveRecipe(config, selected, slot);
882
+ if (!styles) return internLeaf("");
883
+ const className = styleCompiler.className(styleCompiler.compose(...before, styles, ...after));
884
+ for (const token of className.split(" ")) if (token) emittedClasses.add(token);
885
+ return internLeaf(className);
886
+ };
887
+ function internLeaf(value) {
888
+ const shape = JSON.stringify(value);
889
+ const known = leafByShape.get(shape);
890
+ if (known !== void 0) return ~known;
891
+ const id = leaves.length;
892
+ leaves.push(value);
893
+ leafByShape.set(shape, id);
894
+ return ~id;
895
+ }
896
+ const buildNode = (index, dynamicSelection) => {
897
+ if (index === axes.length) return leaf(dynamicSelection);
898
+ const axis = axes[index];
899
+ const values = Object.keys(config.variants?.[axis] ?? {});
900
+ const miss = buildNode(index + 1, {
901
+ ...dynamicSelection,
902
+ [axis]: null
903
+ });
904
+ const absentSelection = { ...dynamicSelection };
905
+ delete absentSelection[axis];
906
+ const absent = buildNode(index + 1, absentSelection);
907
+ const byValue = [];
908
+ for (const value of values) byValue.push(value, buildNode(index + 1, {
909
+ ...dynamicSelection,
910
+ [axis]: value
911
+ }));
912
+ const refs = [
913
+ miss,
914
+ absent,
915
+ ...byValue.filter((_, valueIndex) => valueIndex % 2 === 1)
916
+ ];
917
+ if (refs.every((ref) => ref === refs[0])) return refs[0];
918
+ const node = [
919
+ miss,
920
+ absent,
921
+ byValue
922
+ ];
923
+ const shape = JSON.stringify(node);
924
+ const known = nodeByShape.get(shape);
925
+ if (known !== void 0) return known;
926
+ const id = nodes.length;
927
+ nodes.push(node);
928
+ nodeByShape.set(shape, id);
929
+ return id;
930
+ };
931
+ const root = buildNode(0, {});
932
+ const staticLeaf = root < 0 ? leaves[~root] : void 0;
933
+ return {
934
+ expression: root < 0 && effectful.length === 0 ? JSON.stringify(staticLeaf) : `${RECIPE_MAP_HELPER}([${expressions.join(", ")}], ${JSON.stringify(nodes)}, ${JSON.stringify(leaves)}, ${root})`,
935
+ classNames: [...emittedClasses],
936
+ staticClasses: typeof staticLeaf === "string" ? staticLeaf : "",
937
+ outputKind: wholeSlots ? "slots" : "class",
938
+ usesHelper: !(root < 0 && effectful.length === 0)
939
+ };
940
+ }
941
+ }
942
+ };
943
+ };
944
+ //#endregion
945
+ //#region src/runtime-css.ts
946
+ /** The shape `createCss` and `createMergeCss` both take, derived from a resolved context. */
947
+ const createCssContext = (ctx) => ({
948
+ hash: Boolean(ctx.hash.className),
949
+ conditions: {
950
+ shift: ctx.conditions.shift,
951
+ finalize: ctx.conditions.finalize
952
+ },
953
+ utility: {
954
+ prefix: ctx.utility.prefix,
955
+ hasShorthand: ctx.utility.hasShorthand,
956
+ resolveShorthand: ctx.utility.resolveShorthand.bind(ctx.utility),
957
+ transform: ctx.utility.transform.bind(ctx.utility),
958
+ toHash: ctx.utility.toHash.bind(ctx.utility)
959
+ }
960
+ });
961
+ const createRuntimeCss = (ctx) => {
962
+ const cssContext = createCssContext(ctx);
963
+ const cssFn = createCssUncached(cssContext);
964
+ const { mergeCssUncached } = createMergeCss(cssContext);
965
+ return memo((...styles) => cssFn(mergeCssUncached(...styles)));
966
+ };
967
+ /**
968
+ * The map is every token in the project, so it is built once per context and shared by
969
+ * every module in the build — not once per `foldSource`, which would price a whole token
970
+ * table into each of the overwhelming majority of modules that call `token()` zero times.
971
+ * Keyed weakly so a context that goes out of scope takes its table with it.
972
+ *
973
+ * Both halves of the generated entry are stored, because `token()` and `token.value()` read
974
+ * different ones and building a second table would pay the same per-project cost twice.
975
+ */
976
+ const tokenValues = /* @__PURE__ */ new WeakMap();
977
+ const tokenValuesFor = (ctx) => {
978
+ let values = tokenValues.get(ctx);
979
+ if (values) return values;
980
+ values = /* @__PURE__ */ new Map();
981
+ for (const token of ctx.tokens.allTokens) {
982
+ const { varRef, isVirtual, condition } = token.extensions;
983
+ values.set(token.name, {
984
+ value: ctx.tokens.view.get(token.name) ?? (isVirtual || condition !== "base" ? varRef : token.value),
985
+ variable: ctx.tokens.view.getVar(token.name) ?? varRef
986
+ });
987
+ }
988
+ tokenValues.set(ctx, values);
989
+ return values;
990
+ };
991
+ const createRuntimeTokenValue = (ctx) => (path) => {
992
+ const value = tokenValuesFor(ctx).get(path)?.value;
993
+ return typeof value === "string" ? value : void 0;
994
+ };
995
+ /**
996
+ * The generated runtime's `token()`, rebuilt in-process.
997
+ *
998
+ * Reads the `variable` half of the same entry `token.value()` reads the `value` half of.
999
+ * That half is `varRef` for every token regardless of condition, so unlike
1000
+ * `createRuntimeTokenValue` there is no split to get wrong and no non-string case to
1001
+ * decline: a `var()` reference is a string or the token does not exist. Which is what makes
1002
+ * the default form the trivially foldable one.
1003
+ */
1004
+ const createRuntimeToken = (ctx) => (path) => tokenValuesFor(ctx).get(path)?.variable || void 0;
1005
+ //#endregion
1006
+ //#region src/fold.ts
1007
+ /**
1008
+ * `cva`/`sva` return a function, so their definitions are compile-time declarations rather
1009
+ * than class-producing calls; once their uses are lowered, the factory calls are erased.
1010
+ * `token` also resolves to no class, but it does resolve to a literal, so it compiles through
1011
+ * its own path rather than being declined outright. A static `viewTransition` bag resolves to
1012
+ * its extracted class and uses the ordinary class candidate path.
1013
+ *
1014
+ * Recipe invocations compile through `fold-recipe`. Inline calls
1015
+ * are recorded under the name the file bound; config calls arrive as `recipe`. Routing both
1016
+ * through one exact finite-state lowering keeps their selection contract identical.
1017
+ */
1018
+ const FOLDABLE_TYPES = new Set([
1019
+ "css",
1020
+ "pattern",
1021
+ "viewTransition"
1022
+ ]);
1023
+ /**
1024
+ * The skip reasons that leave a `css()`-family call in the output.
1025
+ *
1026
+ * `overlapping` is handled by the enclosing fold, and `not-imported` is somebody else's
1027
+ * function of the same name — neither leaves a call of ours.
1028
+ */
1029
+ const SURVIVES_TO_RUNTIME = new Set([
1030
+ "dynamic",
1031
+ "runtime-binding",
1032
+ "raw-call",
1033
+ "unsupported-kind",
1034
+ "no-call-expression",
1035
+ "unresolved-token",
1036
+ "compile-failed"
1037
+ ]);
1038
+ /**
1039
+ * A call of a recipe the file bound itself: `const badge = cva(...)`, then `badge({ tone })`.
1040
+ *
1041
+ * Folded when the whole selection resolves, reported under this reason when it does not.
1042
+ * Deliberately all-or-nothing: an unresolved variant does not merely omit its own class, so a
1043
+ * partially-known selection is not foldable at all.
1044
+ *
1045
+ * Visible at all because it used to not be. The parser matched calls by imported name, so a
1046
+ * local binding was never recorded, and an unfoldable invocation looked identical to code
1047
+ * nothing had parsed.
1048
+ */
1049
+ const RECIPE_CALL_TYPE = "cva-call";
1050
+ /**
1051
+ * An identifier that actually reads the binding.
1052
+ *
1053
+ * `getDescendantsOfKind(Identifier)` yields every name in the file, and most of them bind or
1054
+ * label rather than read: a JSX tag (`<button/>` against a recipe called `button`), an object
1055
+ * key, a property name, a declaration. Counting those failed builds on modules that had
1056
+ * folded completely — and `button`, `input`, `label`, `select`, `table`, `dialog` and `form`
1057
+ * are all ordinary recipe names as well as intrinsic elements.
1058
+ *
1059
+ * A type position is excluded for a different reason: it is erased, and with it the import.
1060
+ */
1061
+ const isValueReference = (identifier) => {
1062
+ const parent = identifier.getParent();
1063
+ if (!parent) return false;
1064
+ if (Node.isImportSpecifier(parent) || Node.isExportSpecifier(parent)) return false;
1065
+ if (Node.isImportClause(parent) || Node.isNamespaceImport(parent)) return false;
1066
+ if (Node.isPropertyAccessExpression(parent) && parent.getNameNode() === identifier) return false;
1067
+ if (Node.isQualifiedName(parent) && parent.getRight() === identifier) return false;
1068
+ if (Node.isPropertyAssignment(parent) && parent.getNameNode() === identifier) return false;
1069
+ if (Node.isMethodDeclaration(parent) || Node.isPropertyDeclaration(parent) || Node.isGetAccessorDeclaration(parent) || Node.isSetAccessorDeclaration(parent) || Node.isMethodSignature(parent) || Node.isPropertySignature(parent) || Node.isEnumMember(parent)) {
1070
+ if (parent.getNameNode() === identifier) return false;
1071
+ }
1072
+ if (Node.isLabeledStatement(parent) || Node.isBreakStatement(parent) || Node.isContinueStatement(parent)) return false;
1073
+ if (Node.isJsxOpeningElement(parent) || Node.isJsxSelfClosingElement(parent) || Node.isJsxClosingElement(parent)) {
1074
+ if (parent.getTagNameNode() === identifier) return identifier.getText()[0] === identifier.getText()[0]?.toUpperCase();
1075
+ }
1076
+ if (Node.isJsxAttribute(parent)) return false;
1077
+ if (Node.isBindingElement(parent) && parent.getPropertyNameNode() === identifier) return false;
1078
+ if ((Node.isVariableDeclaration(parent) || Node.isParameterDeclaration(parent) || Node.isBindingElement(parent) || Node.isFunctionDeclaration(parent) || Node.isClassDeclaration(parent)) && parent.getNameNode() === identifier) return false;
1079
+ return !identifier.getFirstAncestor((ancestor) => Node.isTypeNode(ancestor) || Node.isTypeAliasDeclaration(ancestor) || Node.isInterfaceDeclaration(ancestor));
1080
+ };
1081
+ /**
1082
+ * Imports a surviving reference to is not a failure.
1083
+ *
1084
+ * These are what the compiler itself writes; all live in `cx` and pull no engine, so a
1085
+ * reference to one is the fold having worked.
1086
+ */
1087
+ const PERMITTED_BINDINGS = new Set([
1088
+ "cx",
1089
+ RECIPE_MAP_HELPER,
1090
+ SPLIT_PROPS_HELPER
1091
+ ]);
1092
+ /**
1093
+ * Whether a module's text could hold a `splitVariantProps` property access.
1094
+ *
1095
+ * A necessary condition, deliberately not a sufficient one: the name inside a string or a
1096
+ * comment opens the walk, which costs what the walk always cost. What it must never do is
1097
+ * close on a module that has one, and an identifier may be spelled with unicode escapes —
1098
+ * `badge.splitVariantProps(p)` reads as the name to the compiler and contains none of it
1099
+ * as text. Both escape forms start `\u`, so one test covers every spelling.
1100
+ */
1101
+ const mayNameSplitVariantProps = (text) => text.includes("splitVariantProps") || text.includes("\\u");
1102
+ /**
1103
+ * The pieces `trim` reduces a module specifier by, hoisted because a regex literal
1104
+ * constructs a new object every time it is evaluated and `trim` runs per specifier per
1105
+ * import declaration per module.
1106
+ */
1107
+ const LEADING_RELATIVE = /^(?:\.\.?\/)+/;
1108
+ const TRAILING_SLASH = /\/$/;
1109
+ const MODULE_EXTENSION = /\.[mc]?[jt]sx?$/;
1110
+ const TRAILING_INDEX = /\/index$/;
1111
+ /**
1112
+ * An argument that cannot run anything when it is evaluated.
1113
+ *
1114
+ * `token()` takes one argument, but javascript evaluates every argument a call site passes
1115
+ * before the call — so a fold that drops an extra one also drops whatever evaluating it would
1116
+ * have done. `token('x', compute())` is pathological and no longer type-checks, and the fold's
1117
+ * contract is behaviour preservation regardless: a literal is the cheap way to prove it, since
1118
+ * it means no call, no property read, no getter.
1119
+ */
1120
+ const isInertArgument = (node) => Node.isStringLiteral(node) || Node.isNumericLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node) || node.getKind() === SyntaxKind.TrueKeyword || node.getKind() === SyntaxKind.FalseKeyword || node.getKind() === SyntaxKind.NullKeyword || Node.isIdentifier(node) && node.getText() === "undefined";
1121
+ /**
1122
+ * An expression whose evaluation cannot do anything observable, so deleting it preserves
1123
+ * behaviour.
1124
+ *
1125
+ * `isInertArgument` covers the leaves; this walks the object and array literals a recipe
1126
+ * call is actually written with. A spread runs the source's getters, a computed key runs an
1127
+ * expression, a getter or method definition is a function — none of those are safe to
1128
+ * delete, so they are declined rather than enumerated.
1129
+ */
1130
+ const isInertExpression = (node) => {
1131
+ if (isInertArgument(node)) return true;
1132
+ if (Node.isIdentifier(node)) return true;
1133
+ if (Node.isAsExpression(node) || Node.isSatisfiesExpression(node) || Node.isNonNullExpression(node) || Node.isTypeAssertion(node) || Node.isParenthesizedExpression(node)) return isInertExpression(node.getExpression());
1134
+ if (Node.isArrowFunction(node) || Node.isFunctionExpression(node)) return true;
1135
+ if (Node.isRegularExpressionLiteral(node) || Node.isBigIntLiteral(node)) return true;
1136
+ if (Node.isPrefixUnaryExpression(node)) {
1137
+ const operator = node.getOperatorToken();
1138
+ return (operator === SyntaxKind.MinusToken || operator === SyntaxKind.PlusToken || operator === SyntaxKind.ExclamationToken || operator === SyntaxKind.TildeToken) && isInertExpression(node.getOperand());
1139
+ }
1140
+ if (Node.isBinaryExpression(node)) {
1141
+ const operator = node.getOperatorToken().getKind();
1142
+ return (operator === SyntaxKind.QuestionQuestionToken || operator === SyntaxKind.BarBarToken || operator === SyntaxKind.AmpersandAmpersandToken) && isInertExpression(node.getLeft()) && isInertExpression(node.getRight());
1143
+ }
1144
+ if (Node.isObjectLiteralExpression(node)) return node.getProperties().every((property) => {
1145
+ if (Node.isShorthandPropertyAssignment(property)) return true;
1146
+ if (!Node.isPropertyAssignment(property)) return false;
1147
+ if (Node.isComputedPropertyName(property.getNameNode())) return false;
1148
+ const initializer = property.getInitializer();
1149
+ return initializer !== void 0 && isInertExpression(initializer);
1150
+ });
1151
+ if (Node.isArrayLiteralExpression(node)) return node.getElements().every(isInertExpression);
1152
+ return false;
1153
+ };
1154
+ /**
1155
+ * Source files a box tree reaches, other than the one being folded.
1156
+ *
1157
+ * When the extractor resolves an imported identifier it boxes the *declaration's*
1158
+ * node, which lives in the defining module. Walking the tree and reading each node's
1159
+ * source file therefore recovers exactly the files a fold depended on — narrower and
1160
+ * more accurate than treating every import of the module as a dependency.
1161
+ */
1162
+ const collectSourceFiles = (node, ctx, seen = /* @__PURE__ */ new Set()) => {
1163
+ if (!node || seen.has(node)) return;
1164
+ seen.add(node);
1165
+ ctx.record(node.getNode?.());
1166
+ if (box.isMap(node)) {
1167
+ for (const child of node.value.values()) collectSourceFiles(child, ctx, seen);
1168
+ return;
1169
+ }
1170
+ if (box.isArray(node)) for (const child of node.value) collectSourceFiles(child, ctx, seen);
1171
+ };
1172
+ const createDependencyScan = (ownFile) => {
1173
+ const results = /* @__PURE__ */ new Set();
1174
+ const paths = /* @__PURE__ */ new Map();
1175
+ return {
1176
+ results,
1177
+ record(node) {
1178
+ if (!node) return;
1179
+ const sourceFile = node.getSourceFile();
1180
+ if (sourceFile === ownFile) return;
1181
+ let path = paths.get(sourceFile);
1182
+ if (path === void 0) {
1183
+ path = sourceFile.getFilePath();
1184
+ paths.set(sourceFile, path);
1185
+ }
1186
+ if (path) results.add(path);
1187
+ }
1188
+ };
1189
+ };
1190
+ /**
1191
+ * The call expression to replace.
1192
+ *
1193
+ * `extractCallExpressionArguments` boxes the argument list against the call node and
1194
+ * pushes `[callNode, argNode]` onto each argument's stack, so the call is reachable
1195
+ * from either shape the parser stores: the argument array (multi-arg) or the first
1196
+ * argument's map (single-arg).
1197
+ */
1198
+ const findCallExpression = (node) => {
1199
+ const own = node.getNode?.();
1200
+ if (own && Node.isCallExpression(own)) return own;
1201
+ const stack = node.getStack?.() ?? [];
1202
+ for (const entry of stack) if (Node.isCallExpression(entry)) return entry;
1203
+ let current = own;
1204
+ for (let depth = 0; current && depth < 3; depth++) {
1205
+ if (Node.isCallExpression(current)) return current;
1206
+ current = current.getParent();
1207
+ }
1208
+ };
1209
+ /**
1210
+ * `css.raw(...)` must keep returning a style object — folding it to a class string
1211
+ * breaks every caller composing those styles. The file matcher strips `.raw` when it
1212
+ * normalizes function names, so the parser result cannot tell us; the callee text can.
1213
+ */
1214
+ const isRawCall = (call) => {
1215
+ if (!Node.isCallExpression(call)) return false;
1216
+ const callee = call.getExpression().getText();
1217
+ return callee === "raw" || callee.endsWith(".raw");
1218
+ };
1219
+ /** The identifier a callee is rooted at: `css` for `css(…)`, `panda` for `panda.css(…)`. */
1220
+ const calleeRootName = (call) => {
1221
+ if (!Node.isCallExpression(call)) return void 0;
1222
+ let current = call.getExpression();
1223
+ while (Node.isPropertyAccessExpression(current)) current = current.getExpression();
1224
+ return Node.isIdentifier(current) ? current.getText() : void 0;
1225
+ };
1226
+ /**
1227
+ * Local names a module binds to an import of bamboo's own generated system.
1228
+ *
1229
+ * The parser matches by name and asks neither question this does — deliberately, since
1230
+ * for CSS extraction the worst case is a few unused rules. A transform cannot be that
1231
+ * relaxed, and it needs both halves:
1232
+ *
1233
+ * - imported at all, or a user's `const css = (s) => JSON.stringify(s)` gets rewritten
1234
+ * - imported *from bamboo*, or `import { css } from '@emotion/css'` does, which is the
1235
+ * likelier accident of the two since a migrating project has both in the tree
1236
+ *
1237
+ * Answered together and once per file, because the scan is the expensive part and both
1238
+ * answers fall out of the same pass. Per call site instead of per file, this scan
1239
+ * measured +74% on the largest sandbox module.
1240
+ */
1241
+ const bambooImportedNames = (sourceFile, ctx) => {
1242
+ const names = /* @__PURE__ */ new Set();
1243
+ for (const declaration of sourceFile.getImportDeclarations()) {
1244
+ const mod = declaration.getModuleSpecifierValue();
1245
+ for (const named of declaration.getNamedImports()) {
1246
+ const name = named.getNameNode().getText();
1247
+ const alias = named.getAliasNode()?.getText() ?? name;
1248
+ if (ctx.imports.match({
1249
+ mod,
1250
+ name,
1251
+ alias
1252
+ })) names.add(alias);
1253
+ }
1254
+ const namespace = declaration.getNamespaceImport();
1255
+ if (namespace) {
1256
+ const alias = namespace.getText();
1257
+ if (ctx.imports.match({
1258
+ mod,
1259
+ name: alias,
1260
+ alias,
1261
+ kind: "namespace"
1262
+ })) names.add(alias);
1263
+ }
1264
+ }
1265
+ return names;
1266
+ };
1267
+ /**
1268
+ * Is the callee the imported binding, or a local one that shadows it?
1269
+ *
1270
+ * A block-scoped binding of the same name is legal alongside the import, and it is
1271
+ * the one the call actually reaches. Walking ancestors is the precise answer; the
1272
+ * cost is kept off the common path by only inspecting the two node kinds that can
1273
+ * introduce a binding. Ancestors of a call in JSX are overwhelmingly elements and
1274
+ * attributes, which match neither and cost nothing.
1275
+ */
1276
+ const isShadowed = (call, name) => {
1277
+ for (let node = call.getParent(); node; node = node.getParent()) {
1278
+ if (Node.isSourceFile(node)) return false;
1279
+ if (bindsName(node, name)) return true;
1280
+ }
1281
+ return false;
1282
+ };
1283
+ /**
1284
+ * Does a binding name introduce `name`?
1285
+ *
1286
+ * A plain identifier check is not enough: destructuring is the likeliest way a
1287
+ * same-named local reaches a call, since `({ css }) => css(…)` is what a component
1288
+ * taking a `css` prop looks like. Nested and rest elements bind too, so the pattern
1289
+ * is walked rather than inspected at the top level.
1290
+ */
1291
+ const bindingIntroduces = (nameNode, name) => {
1292
+ if (!nameNode) return false;
1293
+ if (Node.isIdentifier(nameNode)) return nameNode.getText() === name;
1294
+ if (Node.isObjectBindingPattern(nameNode) || Node.isArrayBindingPattern(nameNode)) return nameNode.getElements().some((element) => Node.isBindingElement(element) && bindingIntroduces(element.getNameNode(), name));
1295
+ return false;
1296
+ };
1297
+ const declarationsBind = (list, name) => Node.isVariableDeclarationList(list) && list.getDeclarations().some((declaration) => bindingIntroduces(declaration.getNameNode(), name));
1298
+ const bindsName = (scope, name) => {
1299
+ if (Node.isBlock(scope)) return scope.getStatements().some((statement) => statementBinds(statement, name));
1300
+ if (Node.isFunctionDeclaration(scope) || Node.isArrowFunction(scope) || Node.isFunctionExpression(scope) || Node.isMethodDeclaration(scope)) return scope.getParameters().some((parameter) => bindingIntroduces(parameter.getNameNode(), name));
1301
+ if (Node.isCatchClause(scope)) return bindingIntroduces(scope.getVariableDeclaration()?.getNameNode(), name);
1302
+ if (Node.isForStatement(scope) || Node.isForOfStatement(scope) || Node.isForInStatement(scope)) return declarationsBind(scope.getInitializer(), name);
1303
+ return false;
1304
+ };
1305
+ const statementBinds = (statement, name) => {
1306
+ if (Node.isVariableStatement(statement)) return statement.getDeclarations().some((declaration) => bindingIntroduces(declaration.getNameNode(), name));
1307
+ if (Node.isFunctionDeclaration(statement) || Node.isClassDeclaration(statement)) return statement.getNameNode()?.getText() === name;
1308
+ return false;
1309
+ };
1310
+ const hasStyles = (data) => data.length > 0 && data.every((entry) => entry != null && typeof entry === "object");
1311
+ /**
1312
+ * Pair each source argument with the box the parser stored for it, and require the
1313
+ * box to account for all of it. The parser keeps either the whole argument array
1314
+ * (multi-arg calls) or just the first argument's map (single-arg calls).
1315
+ */
1316
+ const argumentsAccountedFor = (call, boxNode) => {
1317
+ if (!Node.isCallExpression(call)) return false;
1318
+ const args = call.getArguments();
1319
+ if (args.length === 0) return true;
1320
+ if (box.isArray(boxNode) && boxNode.getNode() === call) {
1321
+ if (boxNode.value.length !== args.length) return false;
1322
+ return args.every((arg, index) => accountsForSource(arg, boxNode.value[index]));
1323
+ }
1324
+ if (args.length !== 1) return false;
1325
+ return accountsForSource(args[0], boxNode);
1326
+ };
1327
+ const foldSource = (options) => {
1328
+ const { ctx, code, parserResult, runtimeCss = createRuntimeCss(ctx), styleCompiler, maxRecipeStates, parseModule, recipeConfigCache, reportSurvivors, sourceFile: ownSourceFile } = options;
1329
+ const runtimeToken = createRuntimeToken(ctx);
1330
+ const runtimeTokenValue = createRuntimeTokenValue(ctx);
1331
+ /**
1332
+ * Does this specifier name a module that exports the css API, exactly?
1333
+ *
1334
+ * `ImportMap.match` is substring-based, which is right for deciding whether a call is
1335
+ * bamboo's and wrong for deciding whether a module can be imported *from*:
1336
+ * `styled-system/css/css` matches while exporting no `cx`. So the comparison is
1337
+ * equality, not containment.
1338
+ *
1339
+ * A tsconfig path alias is resolved first, the same way `ImportMap.match` does. Without
1340
+ * that, `@site/styled-system/css` — the spelling this repo's own website uses — fails
1341
+ * the check and silently loses helper lowering, which is indistinguishable in the
1342
+ * diagnostics from a genuinely dynamic call.
1343
+ */
1344
+ const cssModules = ctx.imports.matchers.css?.mods ?? [];
1345
+ /**
1346
+ * The generated css module, the only one whose exports are known.
1347
+ *
1348
+ * A configured `importMap.css` points at the user's own wrapper, and a wrapper that
1349
+ * re-exports `css` need not re-export `cx` — adding one there imports a binding that
1350
+ * may not exist. Reusing a `cx` the user already imported from it stays fine, since
1351
+ * that binding demonstrably resolves; only *adding* one is restricted.
1352
+ */
1353
+ const generatedCssModule = [ctx.imports.outdir, "css"].join("/");
1354
+ const pathMappings = ctx.conf.tsOptions?.pathMappings;
1355
+ /**
1356
+ * The spelling reduced to the module it names.
1357
+ *
1358
+ * The extension and `/index` are stripped because bamboo's own output makes a file
1359
+ * import them: `outExtension: 'js'` under NodeNext resolution is written
1360
+ * `styled-system/css/index.js`, which is neither equal to `styled-system/css` nor a
1361
+ * tail of it. Extraction admitted such a file anyway — `ImportMap.match` is
1362
+ * substring-based — so the call was folded while the *insert* was refused, and the
1363
+ * result was reported as `dynamic`: the same silent downgrade the alias case above
1364
+ * describes, reached through the extension instead.
1365
+ *
1366
+ * This does not weaken the equality the comment above insists on. `styled-system/css/css`
1367
+ * still names neither, because only a trailing `/index` is a module's own directory.
1368
+ *
1369
+ * `.d.ts` is deliberately not stripped. A declaration file exports no runtime binding, so
1370
+ * matching one would authorise inserting an import that resolves to nothing — and a value
1371
+ * import cannot name one anyway, which is what makes leaving it out free.
1372
+ */
1373
+ const trim = (value) => value.replaceAll("\\", "/").replace(LEADING_RELATIVE, "").replace(TRAILING_SLASH, "").replace(MODULE_EXTENSION, "").replace(TRAILING_INDEX, "");
1374
+ const matchesModule = (mod, entries) => {
1375
+ const candidates = [mod];
1376
+ if (pathMappings) {
1377
+ const resolved = resolveTsPathPattern(pathMappings, mod);
1378
+ if (resolved) candidates.push(resolved);
1379
+ }
1380
+ return candidates.some((candidate) => {
1381
+ const normalized = trim(candidate);
1382
+ return entries.some((entry) => {
1383
+ const target = trim(entry);
1384
+ return normalized === target || normalized.endsWith(`/${target}`);
1385
+ });
1386
+ });
1387
+ };
1388
+ const isBambooCssModule = (mod) => matchesModule(mod, cssModules);
1389
+ const isGeneratedCssModule = (mod) => matchesModule(mod, [generatedCssModule]);
1390
+ /**
1391
+ * Where the compiler's helpers can be imported from, for a file that imports the generated
1392
+ * css module by *subpath* rather than through its barrel.
1393
+ *
1394
+ * `styled-system/css/cva.js` is a real spelling, and it cannot host the helper: that module
1395
+ * exports `cva`, not `cvaMap`. Matching only the barrel meant no host was found and every
1396
+ * runtime recipe selection in the file declined — a failure whose reported reason said
1397
+ * nothing about import spelling, and whose suggested remedies all pointed elsewhere.
1398
+ *
1399
+ * The sibling `cx` module is what actually exports them. The prefix is verified against the
1400
+ * configured output before anything is derived, so an unrelated `foo/css/bar.js` is left
1401
+ * alone, and the caller's extension is preserved rather than guessed at.
1402
+ */
1403
+ const helperModuleFromSubpath = (mod) => {
1404
+ const normalized = mod.replaceAll("\\", "/");
1405
+ const at = normalized.lastIndexOf("/css/");
1406
+ if (at < 0) return void 0;
1407
+ const prefix = normalized.slice(0, at + 5 - 1);
1408
+ if (!isGeneratedCssModule(prefix)) return void 0;
1409
+ const rest = normalized.slice(at + 5);
1410
+ if (!rest || rest.includes("/")) return void 0;
1411
+ const dot = rest.lastIndexOf(".");
1412
+ const extension = dot > 0 ? rest.slice(dot) : "";
1413
+ if (rest === `cx${extension}`) return void 0;
1414
+ return `${prefix}/cx${extension}`;
1415
+ };
1416
+ /**
1417
+ * The generated css entry as spelled beside an imported config recipe.
1418
+ *
1419
+ * A decision table needs only `cvaMap`, but a module importing a config recipe often has
1420
+ * no css import to extend. Preserve a relative/aliased styled-system spelling by replacing
1421
+ * its `/recipes` suffix; falling back to the configured generated entry covers bare imports.
1422
+ */
1423
+ const configRecipeCssSpecifier = (call, binding) => {
1424
+ for (const declaration of call.getSourceFile().getImportDeclarations()) {
1425
+ if (declaration.isTypeOnly()) continue;
1426
+ if (!declaration.getNamedImports().some((named) => {
1427
+ if (named.isTypeOnly()) return false;
1428
+ return (named.getAliasNode() ?? named.getNameNode()).getText() === binding;
1429
+ })) continue;
1430
+ const mod = declaration.getModuleSpecifierValue().replaceAll("\\", "/");
1431
+ const at = mod.lastIndexOf("/recipes");
1432
+ if (at >= 0) return `${mod.slice(0, at)}/css`;
1433
+ }
1434
+ return generatedCssModule;
1435
+ };
1436
+ /**
1437
+ * How *this* module would have to spell the css module, learnt from one that already does.
1438
+ *
1439
+ * A file calling an imported recipe need not import the css module at all, so when the
1440
+ * lowering needs a decision-table helper there is no spelling in the file to copy. The declaring module
1441
+ * necessarily has one — `cva` came from it — and that is the spelling reused here.
1442
+ *
1443
+ * A bare or aliased specifier resolves identically from any file, so it is taken as
1444
+ * written. A relative one is re-based: resolved against the module that wrote it, then
1445
+ * expressed from the module being folded.
1446
+ */
1447
+ const cssModuleSpecifierFrom = (declaring) => {
1448
+ for (const declaration of declaring.getImportDeclarations()) {
1449
+ if (declaration.isTypeOnly()) continue;
1450
+ const mod = declaration.getModuleSpecifierValue();
1451
+ if (isGeneratedCssModule(mod)) return mod;
1452
+ }
1453
+ };
1454
+ /**
1455
+ * That spelling, said from the module being folded.
1456
+ *
1457
+ * A bare or aliased specifier resolves identically from any file, so it is taken as
1458
+ * written. A relative one is re-based: resolved against the module that wrote it, then
1459
+ * expressed from the module being folded. Pure path arithmetic, so it holds a string
1460
+ * rather than a node — a cached node does not survive the next `addSourceFile`, which
1461
+ * ts-morph implements by forgetting the file's whole tree.
1462
+ */
1463
+ const rebaseSpecifier = (specifier, declaringPath, consumingPath) => {
1464
+ if (!specifier.startsWith(".")) return specifier;
1465
+ const absolute = resolve(dirname(declaringPath), specifier);
1466
+ const rebased = relative(dirname(consumingPath), absolute).replaceAll("\\", "/");
1467
+ if (!rebased) return void 0;
1468
+ return rebased.startsWith(".") ? rebased : `./${rebased}`;
1469
+ };
1470
+ /**
1471
+ * Configs of one foreign module, parsed once however many of its recipes are called.
1472
+ *
1473
+ * Falls back to a per-call map when the caller supplies none, so the fold stays correct
1474
+ * standalone — only repeated, which is what the shared cache exists to avoid.
1475
+ */
1476
+ const configsByModule = recipeConfigCache ?? /* @__PURE__ */ new Map();
1477
+ /** The specifier each imported recipe's module used for the css module, when it needs one. */
1478
+ const helperModules = /* @__PURE__ */ new Map();
1479
+ /** Declaring modules a fold read, recorded as paths because their nodes do not persist. */
1480
+ const foreignDependencies = /* @__PURE__ */ new Set();
1481
+ /** Resolutions for this module's own call sites, keyed by the name the call site writes. */
1482
+ const importedRecipes = /* @__PURE__ */ new Map();
1483
+ /**
1484
+ * The config of a recipe this module imports.
1485
+ *
1486
+ * The binding is followed with ts-morph's symbol aliasing rather than by re-reading import
1487
+ * declarations, because that is what already understands the shapes these are reached
1488
+ * through: `export { badge } from './styles'`, `export * from './styles'`, and an alias at
1489
+ * either end. Each hop is an alias symbol, so following them to a non-alias lands on the
1490
+ * declaration wherever it lives.
1491
+ *
1492
+ * The selected declarations do not depend on which module the call is in. A recipe lowered
1493
+ * here therefore reaches the same globally shared atoms as a call in its declaring module.
1494
+ */
1495
+ const resolveImportedRecipe = (call, name, origin) => {
1496
+ if (importedRecipes.has(name)) return importedRecipes.get(name);
1497
+ const resolve = () => {
1498
+ if (!parseModule) return void 0;
1499
+ const consuming = call.getSourceFile();
1500
+ if (origin.filePath === consuming.getFilePath()) return void 0;
1501
+ let foreign = configsByModule.get(origin.filePath);
1502
+ if (!foreign) {
1503
+ const result = parseModule(origin.filePath);
1504
+ if (!result) return void 0;
1505
+ const collected = collectRecipeConfigs(result);
1506
+ const declaring = [...collected.values()].find((entry) => entry.box)?.box?.getNode?.()?.getSourceFile();
1507
+ const configs = /* @__PURE__ */ new Map();
1508
+ for (const [key, entry] of collected) configs.set(key, entry === AMBIGUOUS ? entry : {
1509
+ config: entry.config,
1510
+ box: void 0
1511
+ });
1512
+ foreign = {
1513
+ configs,
1514
+ cssSpecifier: declaring ? cssModuleSpecifierFrom(declaring) : void 0
1515
+ };
1516
+ configsByModule.set(origin.filePath, foreign);
1517
+ }
1518
+ const entry = foreign.configs.get(origin.name);
1519
+ if (!entry || entry === AMBIGUOUS) return void 0;
1520
+ foreignDependencies.add(origin.filePath);
1521
+ helperModules.set(name, foreign.cssSpecifier ? rebaseSpecifier(foreign.cssSpecifier, origin.filePath, consuming.getFilePath()) : void 0);
1522
+ return entry;
1523
+ };
1524
+ const resolved = resolve();
1525
+ importedRecipes.set(name, resolved);
1526
+ return resolved;
1527
+ };
1528
+ const folded = [];
1529
+ const skipped = [];
1530
+ const candidates = [];
1531
+ const seenRanges = /* @__PURE__ */ new Set();
1532
+ const recipeConfigs = collectRecipeConfigs(parserResult);
1533
+ const recipeDefinitions = [];
1534
+ for (const [name, entry] of recipeConfigs) {
1535
+ if (entry === AMBIGUOUS) continue;
1536
+ const definition = entry.box?.getNode?.();
1537
+ if (!definition) continue;
1538
+ const call = Node.isCallExpression(definition) ? definition : definition.getFirstAncestorByKind(SyntaxKind.CallExpression);
1539
+ if (!call || code.slice(call.getStart(), call.getEnd()) !== call.getText()) continue;
1540
+ recipeDefinitions.push({
1541
+ name,
1542
+ call
1543
+ });
1544
+ }
1545
+ /** Ranges already reported as declined, so one call is never counted twice. */
1546
+ const reportedRanges = /* @__PURE__ */ new Set();
1547
+ const importCache = /* @__PURE__ */ new Map();
1548
+ const importsFor = (sourceFile) => {
1549
+ let names = importCache.get(sourceFile);
1550
+ if (!names) {
1551
+ names = bambooImportedNames(sourceFile, ctx);
1552
+ importCache.set(sourceFile, names);
1553
+ }
1554
+ return names;
1555
+ };
1556
+ for (const item of parserResult.toArray()) {
1557
+ const type = item.type ?? "";
1558
+ const name = item.name ?? type;
1559
+ if (!item.box) continue;
1560
+ const call = findCallExpression(item.box);
1561
+ if (type === "token" || type === "tokenValue") {
1562
+ if (!call) {
1563
+ skipped.push({
1564
+ name,
1565
+ reason: "no-call-expression",
1566
+ start: 0,
1567
+ end: 0
1568
+ });
1569
+ continue;
1570
+ }
1571
+ const start = call.getStart();
1572
+ const end = call.getEnd();
1573
+ if (code.slice(start, end) !== call.getText()) {
1574
+ skipped.push({
1575
+ name,
1576
+ reason: "no-call-expression",
1577
+ start: 0,
1578
+ end: 0
1579
+ });
1580
+ continue;
1581
+ }
1582
+ const rangeKey = `${start}:${end}`;
1583
+ if (seenRanges.has(rangeKey)) continue;
1584
+ seenRanges.add(rangeKey);
1585
+ const rootName = calleeRootName(call);
1586
+ if (!rootName || !importsFor(call.getSourceFile()).has(rootName) || isShadowed(call, rootName)) {
1587
+ skipped.push({
1588
+ name,
1589
+ reason: "not-imported",
1590
+ start,
1591
+ end
1592
+ });
1593
+ continue;
1594
+ }
1595
+ const callee = Node.isCallExpression(call) ? call.getExpression() : void 0;
1596
+ const propertyName = Node.isPropertyAccessExpression(callee) ? callee.getNameNode().getText() : void 0;
1597
+ const wantsValue = type === "tokenValue";
1598
+ if (wantsValue !== (propertyName === "value")) {
1599
+ skipped.push({
1600
+ name,
1601
+ reason: "unsupported-kind",
1602
+ start,
1603
+ end
1604
+ });
1605
+ continue;
1606
+ }
1607
+ if (!wantsValue && propertyName !== void 0 && !ctx.imports.matchers.tokens.match(propertyName)) {
1608
+ skipped.push({
1609
+ name,
1610
+ reason: "unsupported-kind",
1611
+ start,
1612
+ end
1613
+ });
1614
+ continue;
1615
+ }
1616
+ if (!isStaticBox(item.box) || item.data.length !== 1) {
1617
+ skipped.push({
1618
+ name,
1619
+ reason: "dynamic",
1620
+ start,
1621
+ end
1622
+ });
1623
+ continue;
1624
+ }
1625
+ const path = item.data[0];
1626
+ if (typeof path !== "string") {
1627
+ skipped.push({
1628
+ name,
1629
+ reason: "dynamic",
1630
+ start,
1631
+ end
1632
+ });
1633
+ continue;
1634
+ }
1635
+ if (!(Node.isCallExpression(call) ? call.getArguments().slice(1) : []).every(isInertArgument)) {
1636
+ skipped.push({
1637
+ name,
1638
+ reason: "dynamic",
1639
+ start,
1640
+ end
1641
+ });
1642
+ continue;
1643
+ }
1644
+ const value = wantsValue ? runtimeTokenValue(path) : runtimeToken(path);
1645
+ if (!value) {
1646
+ skipped.push({
1647
+ name,
1648
+ reason: "unresolved-token",
1649
+ start,
1650
+ end
1651
+ });
1652
+ continue;
1653
+ }
1654
+ candidates.push({
1655
+ item,
1656
+ call,
1657
+ node: call,
1658
+ start,
1659
+ end,
1660
+ value
1661
+ });
1662
+ continue;
1663
+ }
1664
+ if (!FOLDABLE_TYPES.has(type)) {
1665
+ if (call && (type === RECIPE_CALL_TYPE || type === "recipe") && !isShadowed(call, name)) {
1666
+ const start = call.getStart();
1667
+ const end = call.getEnd();
1668
+ const rangeKey = `${start}:${end}`;
1669
+ if (!reportedRanges.has(rangeKey)) {
1670
+ reportedRanges.add(rangeKey);
1671
+ if (code.slice(start, end) !== call.getText()) {
1672
+ skipped.push({
1673
+ name,
1674
+ reason: "no-call-expression",
1675
+ start: 0,
1676
+ end: 0
1677
+ });
1678
+ continue;
1679
+ }
1680
+ if (isRawCall(call)) {
1681
+ skipped.push({
1682
+ name,
1683
+ reason: "raw-call",
1684
+ start,
1685
+ end
1686
+ });
1687
+ continue;
1688
+ }
1689
+ if (!recipeConfigs.has(name)) {
1690
+ if (type === "recipe") {
1691
+ const config = ctx.recipes.getConfig(name);
1692
+ if (config) {
1693
+ recipeConfigs.set(name, {
1694
+ config,
1695
+ box: void 0
1696
+ });
1697
+ helperModules.set(name, configRecipeCssSpecifier(call, name));
1698
+ }
1699
+ } else if (item.origin) {
1700
+ const imported = resolveImportedRecipe(call, name, item.origin);
1701
+ if (imported) recipeConfigs.set(name, imported);
1702
+ }
1703
+ }
1704
+ const resolvedSelection = item.data?.length === 1 ? item.data[0] : void 0;
1705
+ const entry = recipeConfigs.get(name);
1706
+ let inlineSlot;
1707
+ let inlineEnd = end;
1708
+ if (Array.isArray(entry?.config.slots)) {
1709
+ const parent = call.getParent();
1710
+ if (Node.isPropertyAccessExpression(parent) && parent.getExpression() === call) {
1711
+ const accessed = parent.getName();
1712
+ if (entry.config.slots.includes(accessed)) {
1713
+ inlineSlot = accessed;
1714
+ inlineEnd = parent.getEnd();
1715
+ }
1716
+ } else if (Node.isElementAccessExpression(parent) && parent.getExpression() === call) {
1717
+ const argument = parent.getArgumentExpression();
1718
+ const accessed = argument && (Node.isStringLiteral(argument) || Node.isNoSubstitutionTemplateLiteral(argument)) ? argument.getLiteralValue() : void 0;
1719
+ if (typeof accessed === "string" && entry.config.slots.includes(accessed)) {
1720
+ inlineSlot = accessed;
1721
+ inlineEnd = parent.getEnd();
1722
+ }
1723
+ }
1724
+ }
1725
+ const lowered = lowerRecipeCall(call, entry, styleCompiler, isInertExpression, resolvedSelection, inlineSlot, maxRecipeStates);
1726
+ if (lowered.kind === "dynamic-style") {
1727
+ const helper = ensureRecipeHelperImport(RECIPE_MAP_HELPER, call, isBambooCssModule, isGeneratedCssModule, isShadowed, helperModules.get(name), helperModuleFromSubpath);
1728
+ if (helper) {
1729
+ candidates.push({
1730
+ item,
1731
+ call,
1732
+ node: call,
1733
+ start,
1734
+ end: inlineEnd,
1735
+ className: "",
1736
+ classNames: [],
1737
+ styleMap: lowered.map,
1738
+ mapHelperName: helper.name,
1739
+ insert: helper.insert,
1740
+ configBox: entry?.box,
1741
+ outputKind: lowered.map.outputKind === "slots" ? "slots" : void 0
1742
+ });
1743
+ continue;
1744
+ }
1745
+ skipped.push({
1746
+ name,
1747
+ reason: "recipe-call",
1748
+ start,
1749
+ end
1750
+ });
1751
+ continue;
1752
+ }
1753
+ if (lowered.kind === "slots") {
1754
+ const helper = lowered.helper ? ensureRecipeHelperImport(lowered.helper, call, isBambooCssModule, isGeneratedCssModule, isShadowed, helperModules.get(name), helperModuleFromSubpath) : void 0;
1755
+ if (!lowered.helper || helper) {
1756
+ const replacement = lowered.helper && helper && helper.name !== lowered.helper ? lowered.expression.replaceAll(`${lowered.helper}(`, `${helper.name}(`) : lowered.expression;
1757
+ candidates.push({
1758
+ item,
1759
+ call,
1760
+ node: call,
1761
+ start,
1762
+ end: inlineEnd,
1763
+ replacement,
1764
+ className: "",
1765
+ classNames: lowered.classNames,
1766
+ insert: helper?.insert,
1767
+ configBox: entry?.box,
1768
+ outputKind: "slots"
1769
+ });
1770
+ continue;
1771
+ }
1772
+ skipped.push({
1773
+ name,
1774
+ reason: "recipe-call",
1775
+ start,
1776
+ end
1777
+ });
1778
+ continue;
1779
+ }
1780
+ if (lowered.kind === "class") {
1781
+ candidates.push({
1782
+ item,
1783
+ call,
1784
+ node: call,
1785
+ start,
1786
+ end: inlineEnd,
1787
+ replacement: JSON.stringify(lowered.className),
1788
+ className: lowered.className,
1789
+ classNames: lowered.className.split(" ").filter(Boolean),
1790
+ styleSet: lowered.styles,
1791
+ configBox: entry?.box
1792
+ });
1793
+ continue;
1794
+ }
1795
+ skipped.push({
1796
+ name,
1797
+ reason: "recipe-call",
1798
+ start,
1799
+ end
1800
+ });
1801
+ }
1802
+ }
1803
+ continue;
1804
+ }
1805
+ if (!call) {
1806
+ skipped.push({
1807
+ name,
1808
+ reason: "no-call-expression",
1809
+ start: 0,
1810
+ end: 0
1811
+ });
1812
+ continue;
1813
+ }
1814
+ const start = call.getStart();
1815
+ const end = call.getEnd();
1816
+ const memberParent = call.getParent();
1817
+ const accessed = type === "recipe" && Node.isPropertyAccessExpression(memberParent) && memberParent.getExpression() === call ? memberParent : void 0;
1818
+ const accessedName = accessed?.getNameNode().getText();
1819
+ const declaredSlots = accessed ? ctx.recipes.getConfig(name)?.slots ?? [] : [];
1820
+ const memberAccess = accessedName && declaredSlots.includes(accessedName) ? accessed : void 0;
1821
+ const slot = memberAccess ? accessedName : void 0;
1822
+ const foldEnd = memberAccess ? memberAccess.getEnd() : end;
1823
+ if (code.slice(start, end) !== call.getText()) {
1824
+ skipped.push({
1825
+ name,
1826
+ reason: "no-call-expression",
1827
+ start: 0,
1828
+ end: 0
1829
+ });
1830
+ continue;
1831
+ }
1832
+ const rangeKey = `${start}:${foldEnd}`;
1833
+ if (seenRanges.has(rangeKey)) continue;
1834
+ seenRanges.add(rangeKey);
1835
+ if (isRawCall(call)) {
1836
+ skipped.push({
1837
+ name,
1838
+ reason: "raw-call",
1839
+ start,
1840
+ end
1841
+ });
1842
+ continue;
1843
+ }
1844
+ const rootName = calleeRootName(call);
1845
+ if (!rootName || !importsFor(call.getSourceFile()).has(rootName) || isShadowed(call, rootName)) {
1846
+ skipped.push({
1847
+ name,
1848
+ reason: "not-imported",
1849
+ start,
1850
+ end
1851
+ });
1852
+ continue;
1853
+ }
1854
+ if (!(Node.isCallExpression(call) && call.getArguments().length === 0 && item.data.length === 1) && !isStaticBox(item.box) || !hasStyles(item.data) || !argumentsAccountedFor(call, item.box)) {
1855
+ skipped.push({
1856
+ name,
1857
+ reason: "dynamic",
1858
+ start,
1859
+ end
1860
+ });
1861
+ continue;
1862
+ }
1863
+ candidates.push({
1864
+ item,
1865
+ call,
1866
+ node: call,
1867
+ start,
1868
+ end: foldEnd,
1869
+ slot
1870
+ });
1871
+ }
1872
+ /**
1873
+ * Resolve every fully static candidate to symbolic declarations before allocating a class.
1874
+ *
1875
+ * The normal fold can wait until the rewrite loop to compute a class string. Semantic
1876
+ * composition cannot: an enclosing `cx()` needs the declarations of its arguments so it can
1877
+ * discard overridden values before any string exists.
1878
+ */
1879
+ {
1880
+ for (const candidate of candidates) {
1881
+ if (candidate.styleSet || candidate.value !== void 0 || candidate.replacement) continue;
1882
+ const { item } = candidate;
1883
+ if (item.type === "css") {
1884
+ candidate.styleSet = styleCompiler.compose(...item.data);
1885
+ continue;
1886
+ }
1887
+ if (item.type === "pattern") {
1888
+ candidate.styleSet = styleCompiler.compose(...item.data.map((entry) => ctx.patterns.transform(item.name ?? "", entry)));
1889
+ continue;
1890
+ }
1891
+ if (item.type === "viewTransition") {
1892
+ const semantic = viewTransitionClassName(item.data[0], ctx.utility.prefix);
1893
+ candidate.className = styleCompiler.allocateClassString(semantic);
1894
+ candidate.classNames = [candidate.className];
1895
+ candidate.replacement = JSON.stringify(candidate.className);
1896
+ continue;
1897
+ }
1898
+ }
1899
+ const sourceFile = ownSourceFile ?? candidates[0]?.node.getSourceFile();
1900
+ if (sourceFile) {
1901
+ const cxBindings = /* @__PURE__ */ new Set();
1902
+ for (const declaration of sourceFile.getImportDeclarations()) {
1903
+ if (declaration.isTypeOnly() || !isBambooCssModule(declaration.getModuleSpecifierValue())) continue;
1904
+ for (const named of declaration.getNamedImports()) {
1905
+ if (named.isTypeOnly() || named.getNameNode().getText() !== "cx") continue;
1906
+ cxBindings.add((named.getAliasNode() ?? named.getNameNode()).getText());
1907
+ }
1908
+ }
1909
+ const byRange = new Map(candidates.map((candidate) => [`${candidate.start}:${candidate.end}`, candidate]));
1910
+ for (const call of cxBindings.size ? sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression) : []) {
1911
+ const callee = call.getExpression();
1912
+ if (!Node.isIdentifier(callee) || !cxBindings.has(callee.getText()) || isShadowed(call, callee.getText())) continue;
1913
+ const matched = [];
1914
+ const parts = [];
1915
+ const dynamic = [];
1916
+ const constantCandidates = [];
1917
+ let supported = true;
1918
+ const take = (arg) => {
1919
+ const candidate = byRange.get(`${arg.getStart()}:${arg.getEnd()}`);
1920
+ if (candidate?.styleMap?.outputKind === "class") {
1921
+ dynamic.push(candidate);
1922
+ parts.push({
1923
+ kind: "dynamic",
1924
+ candidate
1925
+ });
1926
+ return true;
1927
+ }
1928
+ if (candidate?.styleSet) {
1929
+ matched.push(candidate);
1930
+ parts.push({
1931
+ kind: "style",
1932
+ candidate
1933
+ });
1934
+ return true;
1935
+ }
1936
+ if (candidate?.item.type === "viewTransition" && candidate.replacement && candidate.className) {
1937
+ constantCandidates.push(candidate);
1938
+ parts.push({
1939
+ kind: "class",
1940
+ value: candidate.className,
1941
+ candidate
1942
+ });
1943
+ return true;
1944
+ }
1945
+ if (Node.isStringLiteral(arg) || Node.isNoSubstitutionTemplateLiteral(arg)) {
1946
+ parts.push({
1947
+ kind: "class",
1948
+ value: arg.getLiteralValue()
1949
+ });
1950
+ return true;
1951
+ }
1952
+ if (Node.isArrayLiteralExpression(arg)) {
1953
+ for (const element of arg.getElements()) if (Node.isSpreadElement(element) || !take(element)) return false;
1954
+ return true;
1955
+ }
1956
+ if (arg.getKind() === SyntaxKind.FalseKeyword || arg.getKind() === SyntaxKind.TrueKeyword || Node.isNumericLiteral(arg) || arg.getKind() === SyntaxKind.NullKeyword || Node.isIdentifier(arg) && arg.getText() === "undefined") return true;
1957
+ return false;
1958
+ };
1959
+ for (const arg of call.getArguments()) {
1960
+ if (take(arg)) continue;
1961
+ supported = false;
1962
+ break;
1963
+ }
1964
+ if (dynamic.length > 1) {
1965
+ skipped.push({
1966
+ name: "cx",
1967
+ reason: "dynamic",
1968
+ start: call.getStart(),
1969
+ end: call.getEnd()
1970
+ });
1971
+ continue;
1972
+ }
1973
+ if (!supported) {
1974
+ skipped.push({
1975
+ name: "cx",
1976
+ reason: "dynamic",
1977
+ start: call.getStart(),
1978
+ end: call.getEnd()
1979
+ });
1980
+ continue;
1981
+ }
1982
+ if (dynamic.length === 1 && matched.length > 0) {
1983
+ const dynamicCandidate = dynamic[0];
1984
+ const styleParts = parts.filter((part) => part.kind !== "class");
1985
+ const dynamicIndex = styleParts.findIndex((part) => part.kind === "dynamic");
1986
+ const before = styleParts.slice(0, dynamicIndex).filter((part) => part.kind === "style").map((part) => part.candidate.styleSet);
1987
+ const after = styleParts.slice(dynamicIndex + 1).filter((part) => part.kind === "style").map((part) => part.candidate.styleSet);
1988
+ const compiled = dynamicCandidate.styleMap.compile(before, after);
1989
+ const expression = compiled.usesHelper && dynamicCandidate.mapHelperName && dynamicCandidate.mapHelperName !== "cvaMap" ? compiled.expression.replaceAll(`${RECIPE_MAP_HELPER}(`, `${dynamicCandidate.mapHelperName}(`) : compiled.expression;
1990
+ const arguments_ = [];
1991
+ let wroteCompiled = false;
1992
+ for (const part of parts) {
1993
+ if (part.kind === "class") {
1994
+ if (part.value) arguments_.push(JSON.stringify(part.value));
1995
+ continue;
1996
+ }
1997
+ if (!wroteCompiled) {
1998
+ arguments_.push(expression);
1999
+ wroteCompiled = true;
2000
+ }
2001
+ }
2002
+ dynamicCandidate.subsumed = true;
2003
+ const first = styleParts[0].candidate;
2004
+ candidates.push({
2005
+ ...first,
2006
+ call,
2007
+ node: call,
2008
+ start: call.getStart(),
2009
+ end: call.getEnd(),
2010
+ displayName: "cx",
2011
+ replacement: arguments_.length === 1 ? arguments_[0] : `${callee.getText()}(${arguments_.join(", ")})`,
2012
+ className: "",
2013
+ classNames: [...compiled.classNames, ...parts.filter((part) => part.kind === "class").flatMap((part) => part.value.split(" "))].filter(Boolean),
2014
+ styleSet: void 0,
2015
+ styleMap: void 0,
2016
+ outputKind: void 0,
2017
+ insert: compiled.usesHelper ? dynamicCandidate.insert : void 0,
2018
+ sourceBoxes: styleParts.flatMap((part) => [part.candidate.item.box, part.candidate.configBox]).concat(constantCandidates.map((candidate) => candidate.item.box)).filter(Boolean)
2019
+ });
2020
+ continue;
2021
+ }
2022
+ if (matched.length === 0) {
2023
+ if (constantCandidates.length === 0) continue;
2024
+ const className = parts.filter((part) => part.kind === "class").map((part) => part.value).filter(Boolean).join(" ");
2025
+ const first = constantCandidates[0];
2026
+ candidates.push({
2027
+ ...first,
2028
+ call,
2029
+ node: call,
2030
+ start: call.getStart(),
2031
+ end: call.getEnd(),
2032
+ displayName: "cx",
2033
+ replacement: JSON.stringify(className),
2034
+ className,
2035
+ classNames: className.split(" ").filter(Boolean),
2036
+ sourceBoxes: constantCandidates.map((candidate) => candidate.item.box).filter(Boolean)
2037
+ });
2038
+ continue;
2039
+ }
2040
+ const merged = styleCompiler.compose(...matched.map((candidate) => candidate.styleSet));
2041
+ const compiled = styleCompiler.className(merged);
2042
+ const classParts = [];
2043
+ let wroteCompiled = false;
2044
+ for (const part of parts) {
2045
+ if (part.kind === "class") {
2046
+ if (part.value) classParts.push(part.value);
2047
+ continue;
2048
+ }
2049
+ if (!wroteCompiled && compiled) {
2050
+ classParts.push(compiled);
2051
+ wroteCompiled = true;
2052
+ }
2053
+ }
2054
+ const first = matched[0];
2055
+ candidates.push({
2056
+ ...first,
2057
+ call,
2058
+ node: call,
2059
+ start: call.getStart(),
2060
+ end: call.getEnd(),
2061
+ displayName: "cx",
2062
+ replacement: JSON.stringify(classParts.join(" ")),
2063
+ className: classParts.join(" "),
2064
+ classNames: classParts.flatMap((part) => part.split(" ")).filter(Boolean),
2065
+ styleSet: merged,
2066
+ sourceBoxes: [...matched.flatMap((candidate) => [candidate.item.box, candidate.configBox]), ...constantCandidates.map((candidate) => candidate.item.box)].filter(Boolean)
2067
+ });
2068
+ }
2069
+ }
2070
+ for (const candidate of candidates) {
2071
+ if (!candidate.styleMap || candidate.subsumed || candidate.replacement) continue;
2072
+ const compiled = candidate.styleMap.compile();
2073
+ candidate.replacement = compiled.usesHelper && candidate.mapHelperName && candidate.mapHelperName !== "cvaMap" ? compiled.expression.replaceAll(`${RECIPE_MAP_HELPER}(`, `${candidate.mapHelperName}(`) : compiled.expression;
2074
+ if (!compiled.usesHelper) candidate.insert = void 0;
2075
+ candidate.className = compiled.staticClasses;
2076
+ candidate.classNames = compiled.classNames;
2077
+ candidate.outputKind = compiled.outputKind === "slots" ? "slots" : void 0;
2078
+ }
2079
+ }
2080
+ /**
2081
+ * Ranges the rewrite actually replaced. Declared before the early return below, because
2082
+ * that return is now also a reporting point: a module with nothing to fold is exactly the
2083
+ * shape `reportSurvivors` exists to catch.
2084
+ */
2085
+ const applied = [];
2086
+ if (candidates.length === 0 && recipeDefinitions.length === 0) {
2087
+ if (reportSurvivors) reportRuntimeBindings();
2088
+ return {
2089
+ code,
2090
+ map: null,
2091
+ folded,
2092
+ skipped,
2093
+ dependencies: []
2094
+ };
2095
+ }
2096
+ const rewriteSourceFile = ownSourceFile ?? candidates[0]?.node.getSourceFile() ?? recipeDefinitions[0]?.call.getSourceFile();
2097
+ if (!rewriteSourceFile) return {
2098
+ code,
2099
+ map: null,
2100
+ folded,
2101
+ skipped,
2102
+ dependencies: []
2103
+ };
2104
+ const dependencyScan = createDependencyScan(rewriteSourceFile);
2105
+ candidates.sort((a, b) => a.start - b.start || b.end - a.end);
2106
+ const magic = new MagicString(code);
2107
+ const insertedNames = /* @__PURE__ */ new Set();
2108
+ const applyInsert = (insert) => {
2109
+ if (!insert) return;
2110
+ const missing = insert.names.filter((name) => !insertedNames.has(name));
2111
+ if (!missing.length) return;
2112
+ magic.appendLeft(insert.pos, insert.module ? `\nimport { ${missing.join(", ")} } from '${insert.module}'` : missing.map((name) => `, ${name}`).join(""));
2113
+ for (const name of missing) insertedNames.add(name);
2114
+ };
2115
+ const collides = (edits) => edits.some(([start, end]) => applied.some(([from, to]) => start < to && from < end));
2116
+ for (const candidate of candidates) {
2117
+ const { item, start, end } = candidate;
2118
+ const name = candidate.displayName ?? item.name ?? item.type ?? "";
2119
+ const ranges = [[start, end]];
2120
+ if (collides(ranges)) {
2121
+ skipped.push({
2122
+ name,
2123
+ reason: "overlapping",
2124
+ start,
2125
+ end
2126
+ });
2127
+ continue;
2128
+ }
2129
+ if (candidate.value !== void 0) {
2130
+ magic.overwrite(start, end, JSON.stringify(candidate.value));
2131
+ applied.push(...ranges);
2132
+ folded.push({
2133
+ name,
2134
+ kind: "value",
2135
+ className: "",
2136
+ classNames: [],
2137
+ value: candidate.value,
2138
+ start,
2139
+ end
2140
+ });
2141
+ collectSourceFiles(item.box, dependencyScan);
2142
+ continue;
2143
+ }
2144
+ if (candidate.replacement) {
2145
+ magic.overwrite(start, end, candidate.replacement);
2146
+ applyInsert(candidate.insert);
2147
+ applied.push(...ranges);
2148
+ folded.push({
2149
+ name,
2150
+ kind: candidate.outputKind ?? "class",
2151
+ className: candidate.className,
2152
+ classNames: (candidate.classNames ?? [candidate.className]).filter(Boolean),
2153
+ start,
2154
+ end
2155
+ });
2156
+ collectSourceFiles(item.box, dependencyScan);
2157
+ if (candidate.configBox) collectSourceFiles(candidate.configBox, dependencyScan);
2158
+ for (const box of candidate.sourceBoxes ?? []) collectSourceFiles(box, dependencyScan);
2159
+ continue;
2160
+ }
2161
+ let className;
2162
+ try {
2163
+ if (item.type === "pattern") className = runtimeCss(...item.data.map((entry) => ctx.patterns.transform(name, entry)));
2164
+ else className = runtimeCss(...item.data);
2165
+ } catch {
2166
+ skipped.push({
2167
+ name,
2168
+ reason: "dynamic",
2169
+ start,
2170
+ end
2171
+ });
2172
+ continue;
2173
+ }
2174
+ magic.overwrite(start, end, JSON.stringify(className));
2175
+ applied.push(...ranges);
2176
+ folded.push({
2177
+ name,
2178
+ kind: "class",
2179
+ className,
2180
+ classNames: className ? [className] : [],
2181
+ start,
2182
+ end
2183
+ });
2184
+ collectSourceFiles(item.box, dependencyScan);
2185
+ }
2186
+ const recipeSourceFile = candidates[0]?.node.getSourceFile();
2187
+ if (recipeSourceFile && mayNameSplitVariantProps(recipeSourceFile.getFullText())) for (const access of recipeSourceFile.getDescendantsOfKind(SyntaxKind.PropertyAccessExpression)) {
2188
+ if (access.getName() !== "splitVariantProps") continue;
2189
+ const target = access.getExpression();
2190
+ if (!Node.isIdentifier(target)) continue;
2191
+ if (isShadowed(access, target.getText())) continue;
2192
+ const local = recipeConfigs?.get(target.getText());
2193
+ const importedConfig = !local && importsFor(recipeSourceFile).has(target.getText()) ? ctx.recipes.getConfig(target.getText()) : void 0;
2194
+ const entry = local && local !== AMBIGUOUS ? local : importedConfig ? {
2195
+ config: importedConfig,
2196
+ box: void 0
2197
+ } : void 0;
2198
+ if (!entry) continue;
2199
+ const call = access.getParent();
2200
+ if (!Node.isCallExpression(call) || call.getExpression() !== access) continue;
2201
+ const args = call.getArguments();
2202
+ if (args.length !== 1) continue;
2203
+ const start = call.getStart();
2204
+ const end = call.getEnd();
2205
+ if (code.slice(start, end) !== call.getText()) continue;
2206
+ if (collides([[start, end]])) continue;
2207
+ const helper = ensureRecipeHelperImport(SPLIT_PROPS_HELPER, call, isBambooCssModule, isGeneratedCssModule, isShadowed, helperModules.get(target.getText()), helperModuleFromSubpath);
2208
+ if (!helper) continue;
2209
+ const keys = Object.keys(entry.config.variants ?? {});
2210
+ magic.overwrite(start, end, `${helper.name}(${args[0].getText()}, ${JSON.stringify(keys)})`);
2211
+ applyInsert(helper.insert);
2212
+ applied.push([start, end]);
2213
+ }
2214
+ for (const { name, call } of recipeDefinitions) {
2215
+ const start = call.getStart();
2216
+ const end = call.getEnd();
2217
+ if (collides([[start, end]])) continue;
2218
+ magic.overwrite(start, end, "undefined");
2219
+ applied.push([start, end]);
2220
+ folded.push({
2221
+ name,
2222
+ kind: "definition",
2223
+ className: "",
2224
+ classNames: [],
2225
+ start,
2226
+ end
2227
+ });
2228
+ }
2229
+ /**
2230
+ * Bindings from a bamboo module still referenced once every rewrite is applied.
2231
+ *
2232
+ * Deliberately not driven by `parserResult`: that is the recogniser, and the point here is
2233
+ * to catch what it did not see. A namespace import called as `s.cva(...)`, a default
2234
+ * import, a specifier that resolved to nothing — each leaves a live reference and no ledger
2235
+ * entry at all, which used to let a build silently ship the engine.
2236
+ *
2237
+ * The helpers the compiler writes are excluded because they pull no style engine. `cx` is
2238
+ * also allowed to remain when it joins an arbitrary external class; only fully analyzable
2239
+ * arguments receive Bamboo's semantic composition guarantee.
2240
+ */
2241
+ /** The specifier this module imported `binding` through, if it did. */
2242
+ function importSpecifierFor(sourceFile, binding) {
2243
+ for (const declaration of sourceFile.getImportDeclarations()) {
2244
+ if (declaration.isTypeOnly()) continue;
2245
+ for (const named of declaration.getNamedImports()) {
2246
+ if (named.isTypeOnly()) continue;
2247
+ if ((named.getAliasNode() ?? named.getNameNode()).getText() === binding) return named.getAliasNode() ?? named.getNameNode();
2248
+ }
2249
+ }
2250
+ }
2251
+ function reportRuntimeBindings() {
2252
+ const sourceFile = ownSourceFile ?? candidates[0]?.node.getSourceFile() ?? recipeDefinitions[0]?.call.getSourceFile();
2253
+ if (!sourceFile) return;
2254
+ const importedRecipeBindings = new Set(parserResult.importedRecipes?.keys() ?? []);
2255
+ /**
2256
+ * Every identifier in the module, grouped by the name it spells — built at most once per
2257
+ * pass, and only when something below has a name to look up.
2258
+ *
2259
+ * One index answers for every binding, rather than a walk per binding. Built here rather
2260
+ * than cached across passes: it holds nodes, and a node does not outlive its source file
2261
+ * being replaced.
2262
+ *
2263
+ * Deferred because most modules in an app neither declare nor import a recipe, and the
2264
+ * walk is not cheap — `getDescendantsOfKind` wraps every identifier in the file in a
2265
+ * ts-morph node to answer a question those modules never ask. It was 11% of a 6,307-file
2266
+ * build, most of it spent producing an index nothing read.
2267
+ */
2268
+ let identifiers;
2269
+ const identifiersByName = () => identifiers ??= identifierIndex(sourceFile);
2270
+ for (const binding of new Set([...recipeConfigs.keys(), ...importedRecipeBindings])) {
2271
+ const entry = recipeConfigs.get(binding);
2272
+ if (entry === AMBIGUOUS) continue;
2273
+ if (!entry && !importedRecipeBindings.has(binding)) continue;
2274
+ const definition = entry?.box?.getNode?.();
2275
+ const nameNode = definition?.getSourceFile() === sourceFile ? definition?.getFirstAncestorByKind(SyntaxKind.VariableDeclaration)?.getNameNode() : importSpecifierFor(sourceFile, binding);
2276
+ if (!nameNode || !Node.isIdentifier(nameNode)) continue;
2277
+ const references = localReferencesTo(identifiersByName(), binding, nameNode);
2278
+ if (skipped.filter((item) => SURVIVES_TO_RUNTIME.has(item.reason) && item.end > item.start).some((item) => references.some((ref) => ref.getStart() >= item.start && ref.getStart() < item.end))) continue;
2279
+ const survivor = references.find((ref) => !applied.some(([from, to]) => ref.getStart() >= from && ref.getStart() < to));
2280
+ if (!survivor) continue;
2281
+ skipped.push({
2282
+ name: binding,
2283
+ reason: "runtime-binding",
2284
+ start: survivor.getStart(),
2285
+ end: survivor.getEnd()
2286
+ });
2287
+ }
2288
+ const bambooModules = [
2289
+ ...cssModules,
2290
+ ...ctx.imports.matchers.recipe?.mods ?? [],
2291
+ ...ctx.imports.matchers.pattern?.mods ?? [],
2292
+ ...ctx.imports.matchers.tokens?.mods ?? []
2293
+ ];
2294
+ const runtimeCalls = [];
2295
+ const importEquals = [];
2296
+ sourceFile.forEachDescendant((node) => {
2297
+ if (Node.isCallExpression(node)) runtimeCalls.push(node);
2298
+ else if (Node.isImportEqualsDeclaration(node)) importEquals.push(node);
2299
+ });
2300
+ for (const call of runtimeCalls) {
2301
+ const callee = call.getExpression();
2302
+ const argument = call.getArguments()[0];
2303
+ if (!argument || !Node.isStringLiteral(argument) && !Node.isNoSubstitutionTemplateLiteral(argument)) continue;
2304
+ if (!matchesModule(argument.getLiteralValue(), bambooModules)) continue;
2305
+ const isDynamicImport = callee.getKind() === SyntaxKind.ImportKeyword;
2306
+ const isRequire = Node.isIdentifier(callee) && callee.getText() === "require" && !isShadowed(call, "require");
2307
+ if (!isDynamicImport && !isRequire) continue;
2308
+ skipped.push({
2309
+ name: isDynamicImport ? "import" : "require",
2310
+ reason: "runtime-binding",
2311
+ start: call.getStart(),
2312
+ end: call.getEnd()
2313
+ });
2314
+ }
2315
+ for (const declaration of importEquals) {
2316
+ if (declaration.isTypeOnly()) continue;
2317
+ const reference = declaration.getModuleReference();
2318
+ if (!Node.isExternalModuleReference(reference)) continue;
2319
+ const expression = reference.getExpression();
2320
+ if (!expression || !Node.isStringLiteral(expression) || !matchesModule(expression.getLiteralValue(), bambooModules)) continue;
2321
+ skipped.push({
2322
+ name: declaration.getName(),
2323
+ reason: "runtime-binding",
2324
+ start: declaration.getStart(),
2325
+ end: declaration.getEnd()
2326
+ });
2327
+ }
2328
+ /** Local name -> what to call it in the report. */
2329
+ const watched = /* @__PURE__ */ new Map();
2330
+ for (const declaration of sourceFile.getImportDeclarations()) {
2331
+ if (declaration.isTypeOnly()) continue;
2332
+ if (!matchesModule(declaration.getModuleSpecifierValue(), bambooModules)) continue;
2333
+ for (const named of declaration.getNamedImports()) {
2334
+ if (named.isTypeOnly()) continue;
2335
+ const imported = named.getNameNode().getText();
2336
+ if (PERMITTED_BINDINGS.has(imported)) continue;
2337
+ watched.set((named.getAliasNode() ?? named.getNameNode()).getText(), imported);
2338
+ }
2339
+ const namespace = declaration.getNamespaceImport();
2340
+ if (namespace) watched.set(namespace.getText(), `${namespace.getText()}.*`);
2341
+ const defaultImport = declaration.getDefaultImport();
2342
+ if (defaultImport) watched.set(defaultImport.getText(), defaultImport.getText());
2343
+ }
2344
+ for (const declaration of sourceFile.getExportDeclarations()) {
2345
+ if (declaration.isTypeOnly()) continue;
2346
+ if (!matchesModule(declaration.getModuleSpecifierValue() ?? "", bambooModules)) continue;
2347
+ if (declaration.isNamespaceExport()) {
2348
+ skipped.push({
2349
+ name: declaration.getNamespaceExport()?.getName() ?? "*",
2350
+ reason: "runtime-binding",
2351
+ start: declaration.getStart(),
2352
+ end: declaration.getEnd()
2353
+ });
2354
+ continue;
2355
+ }
2356
+ for (const named of declaration.getNamedExports()) {
2357
+ if (named.isTypeOnly()) continue;
2358
+ const imported = named.getNameNode().getText();
2359
+ if (PERMITTED_BINDINGS.has(imported)) continue;
2360
+ skipped.push({
2361
+ name: imported,
2362
+ reason: "runtime-binding",
2363
+ start: named.getStart(),
2364
+ end: named.getEnd()
2365
+ });
2366
+ }
2367
+ }
2368
+ for (const declaration of sourceFile.getExportDeclarations()) {
2369
+ if (declaration.isTypeOnly() || declaration.getModuleSpecifier()) continue;
2370
+ for (const named of declaration.getNamedExports()) {
2371
+ if (named.isTypeOnly()) continue;
2372
+ const imported = watched.get(named.getNameNode().getText());
2373
+ if (imported === void 0) continue;
2374
+ skipped.push({
2375
+ name: imported,
2376
+ reason: "runtime-binding",
2377
+ start: named.getStart(),
2378
+ end: named.getEnd()
2379
+ });
2380
+ }
2381
+ }
2382
+ if (watched.size === 0) return;
2383
+ const declined = skipped.filter((entry) => SURVIVES_TO_RUNTIME.has(entry.reason) && entry.end > entry.start).map((entry) => [entry.start, entry.end]);
2384
+ const survivors = [];
2385
+ for (const [local, imported] of watched) for (const identifier of identifiersByName().get(local)) {
2386
+ const start = identifier.getStart();
2387
+ if (identifier.getFirstAncestorByKind(SyntaxKind.ImportDeclaration)) continue;
2388
+ if (applied.some(([from, to]) => start >= from && start < to)) continue;
2389
+ if (declined.some(([from, to]) => start >= from && start < to)) continue;
2390
+ if (!isValueReference(identifier)) continue;
2391
+ if (isShadowed(identifier, local)) continue;
2392
+ survivors.push({
2393
+ name: imported,
2394
+ reason: "runtime-binding",
2395
+ start,
2396
+ end: identifier.getEnd()
2397
+ });
2398
+ break;
2399
+ }
2400
+ survivors.sort((a, b) => a.start - b.start);
2401
+ skipped.push(...survivors);
2402
+ }
2403
+ if (reportSurvivors) reportRuntimeBindings();
2404
+ if (folded.length === 0) return {
2405
+ code,
2406
+ map: null,
2407
+ folded,
2408
+ skipped,
2409
+ dependencies: []
2410
+ };
2411
+ return {
2412
+ code: magic.toString(),
2413
+ map: magic.generateMap({
2414
+ source: options.filePath,
2415
+ hires: true,
2416
+ includeContent: true
2417
+ }),
2418
+ folded,
2419
+ skipped,
2420
+ dependencies: [...dependencyScan.results, ...foreignDependencies]
2421
+ };
2422
+ };
2423
+ //#endregion
2424
+ //#region src/style-set.ts
2425
+ const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
2426
+ /** A compound selector matches only through variant classes the recipe actually emits. */
2427
+ const matchesCompound = (compound, selection, variants) => {
2428
+ for (const [key, expected] of Object.entries(compound)) {
2429
+ if (key === "css") continue;
2430
+ const declared = variants?.[key];
2431
+ const selected = selection[key];
2432
+ if (selected == null || !declared || !Object.hasOwn(declared, String(selected))) return false;
2433
+ if (!(Array.isArray(expected) ? expected : [expected]).some((value) => value != null && String(selected) === String(value))) return false;
2434
+ }
2435
+ return true;
2436
+ };
2437
+ /**
2438
+ * Resolve the style fragments one recipe call contributes, in emitted-rule precedence.
2439
+ *
2440
+ * This intentionally rejects conditional variant *selections*. A scalar selects a style
2441
+ * object; an object such as `{ base: 'sm', md: 'lg' }` selects several objects under
2442
+ * conditions and needs a separate lowering. Returning `undefined` rejects that call instead
2443
+ * of silently compiling only one branch.
2444
+ */
2445
+ const createStaticStyleSetCompiler = (ctx, runtimeCss, allocateClassString = (className) => className) => {
2446
+ const { mergeCssUncached } = createMergeCss(createCssContext(ctx));
2447
+ const compose = (...styles) => mergeCssUncached(...styles);
2448
+ const resolveRecipe = (config, input = {}, slot) => {
2449
+ const slots = Array.isArray(config.slots) ? config.slots : void 0;
2450
+ if (Boolean(slots) !== Boolean(slot)) return void 0;
2451
+ if (slot && !slots?.includes(slot)) return void 0;
2452
+ const selection = {
2453
+ ...config.defaultVariants ?? {},
2454
+ ...compact(input)
2455
+ };
2456
+ if (Object.values(selection).some((value) => isRecord(value))) return void 0;
2457
+ const fragments = [];
2458
+ const take = (candidate) => {
2459
+ if (!isRecord(candidate)) return;
2460
+ const styles = slot ? candidate[slot] : candidate;
2461
+ if (isRecord(styles)) fragments.push(styles);
2462
+ };
2463
+ take(config.base);
2464
+ for (const variant of Object.keys(config.variants ?? {})) {
2465
+ const value = selection[variant];
2466
+ if (value == null) continue;
2467
+ take(config.variants?.[variant]?.[String(value)]);
2468
+ }
2469
+ for (const compound of config.compoundVariants ?? []) {
2470
+ if (!isRecord(compound) || !matchesCompound(compound, selection, config.variants)) continue;
2471
+ take(compound.css);
2472
+ }
2473
+ return compose(...fragments);
2474
+ };
2475
+ return {
2476
+ compose,
2477
+ resolveRecipe,
2478
+ className: (...styles) => runtimeCss(...styles),
2479
+ allocateClassString
2480
+ };
2481
+ };
2482
+ //#endregion
2483
+ export { createRuntimeCss, createStaticStyleSetCompiler, foldSource };