styled-components-to-stylex-codemod 0.0.45 → 0.0.47

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.
@@ -1,11 +1,10 @@
1
1
  import { t as createModuleResolver } from "./resolve-imports-DgSAddIF.mjs";
2
- import { a as isDirectionalResult, n as mergeMarkerDeclarations, o as assertValidAdapter, r as DEFAULT_THEME_HOOK, t as transformedComponentAcceptsSx } from "./sx-surface-DBy6tOUv.mjs";
3
- import { i as getReExportedSourceName, o as resolveBarrelReExportBinding, r as findImportSource, s as Logger, t as fileExports } from "./extract-external-interface-B61N1a6q.mjs";
4
- import { n as toRealPath, t as isRelativeSpecifier } from "./path-utils-BIpoL4Ue.mjs";
5
- import { a as isBackgroundImageValue, c as isSingleBackgroundComponent, d as kebabToCamelCase, f as looksLikeLength, h as sanitizeIdentifier, i as getCommentBody, l as isStyleSectionMarkerComment, m as normalizeWhitespace, n as capitalize, o as isJSDocBlockComment, p as lowerFirst, r as escapeRegex, s as isPrettierIgnoreComment, t as camelToKebabCase, u as isValidIdentifierName$1 } from "./string-utils-DD9wdRHW.mjs";
6
- import { n as findTypeScriptComponentMetadata, t as applyTypeScriptMetadataToDecl } from "./typescript-metadata-Dubr-x2i.mjs";
7
- import { a as PLACEHOLDER_RE, i as readStaticJsxLiteral, n as createComponentPropUsageInfo, o as parseStyledTemplateLiteral, r as mergeComponentPropUsage, s as terminateStandaloneInterpolationStatements, t as KNOWN_NON_ELEMENT_PROPS } from "./prop-usage-B6z4WOPr.mjs";
8
- import { t as isSelectorContext } from "./selector-context-heuristic-CGggN74M.mjs";
2
+ import { a as isDirectionalResult, n as mergeMarkerDeclarations, o as assertValidAdapter, r as DEFAULT_THEME_HOOK, t as transformedComponentAcceptsSx } from "./sx-surface-BzqO3hcC.mjs";
3
+ import { c as UNSUPPORTED_SHOULD_FORWARD_PROP_WARNING, i as getReExportedSourceName, o as resolveBarrelReExportBinding, r as findImportSource, s as Logger, t as fileExports } from "./extract-external-interface-CvkkJZb1.mjs";
4
+ import { n as resolveExistingFilePath, r as toRealPath, t as isRelativeSpecifier } from "./path-utils-BC4U8X_q.mjs";
5
+ import { a as isBackgroundImageValue, c as isSingleBackgroundComponent, d as kebabToCamelCase, f as looksLikeLength, h as sanitizeIdentifier, i as getCommentBody, l as isStyleSectionMarkerComment, m as normalizeWhitespace, n as capitalize, o as isJSDocBlockComment, p as lowerFirst, r as escapeRegex, s as isPrettierIgnoreComment, t as camelToKebabCase, u as isValidIdentifierName } from "./string-utils-DD9wdRHW.mjs";
6
+ import { a as terminateStandaloneInterpolationStatements, i as parseStyledTemplateLiteral, n as isTemplatePlaceholderInSelectorContext, r as PLACEHOLDER_RE } from "./selector-context-heuristic-LVizWWOR.mjs";
7
+ import { i as readStaticJsxLiteral, n as createComponentPropUsageInfo, r as mergeComponentPropUsage, t as KNOWN_NON_ELEMENT_PROPS } from "./prop-usage-Bz3z0V2F.mjs";
9
8
  import { createRequire } from "node:module";
10
9
  import jscodeshift from "jscodeshift";
11
10
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
@@ -30,6 +29,50 @@ const STYLEX_LONGHAND_ONLY_SHORTHANDS = new Set([
30
29
  "scroll-margin",
31
30
  "scroll-padding"
32
31
  ]);
32
+ /** Mapping from CSS shorthand to the longhands that conflict with it. */
33
+ const SHORTHAND_LONGHANDS = {
34
+ margin: {
35
+ physical: [
36
+ "marginTop",
37
+ "marginRight",
38
+ "marginBottom",
39
+ "marginLeft"
40
+ ],
41
+ logical: ["marginBlock", "marginInline"]
42
+ },
43
+ padding: {
44
+ physical: [
45
+ "paddingTop",
46
+ "paddingRight",
47
+ "paddingBottom",
48
+ "paddingLeft"
49
+ ],
50
+ logical: ["paddingBlock", "paddingInline"]
51
+ },
52
+ scrollMargin: {
53
+ physical: [
54
+ "scrollMarginTop",
55
+ "scrollMarginRight",
56
+ "scrollMarginBottom",
57
+ "scrollMarginLeft"
58
+ ],
59
+ logical: ["scrollMarginBlock", "scrollMarginInline"]
60
+ },
61
+ scrollPadding: {
62
+ physical: [
63
+ "scrollPaddingTop",
64
+ "scrollPaddingRight",
65
+ "scrollPaddingBottom",
66
+ "scrollPaddingLeft"
67
+ ],
68
+ logical: ["scrollPaddingBlock", "scrollPaddingInline"]
69
+ }
70
+ };
71
+ /**
72
+ * Mapping from logical longhands to their physical equivalents, derived from SHORTHAND_LONGHANDS.
73
+ * `marginBlock` -> `["marginTop", "marginBottom"]`
74
+ */
75
+ const LOGICAL_TO_PHYSICAL = Object.fromEntries(Object.values(SHORTHAND_LONGHANDS).flatMap(({ physical, logical }) => [[logical[0], [physical[0], physical[2]]], [logical[1], [physical[1], physical[3]]]]));
33
76
  function isStylexLonghandOnlyShorthand(prop) {
34
77
  return STYLEX_LONGHAND_ONLY_SHORTHANDS.has(prop);
35
78
  }
@@ -208,6 +251,21 @@ const STYLEX_STRING_ONLY_CSS_PROPS = new Set([
208
251
  "gridColumnEnd",
209
252
  "outlineOffset"
210
253
  ]);
254
+ const UNSUPPORTED_STYLEX_CSS_PROPS = new Set([
255
+ "all",
256
+ "scroll-margin-block",
257
+ "scroll-margin-block-start",
258
+ "scroll-margin-block-end",
259
+ "scroll-margin-inline",
260
+ "scroll-margin-inline-start",
261
+ "scroll-margin-inline-end",
262
+ "scroll-padding-block",
263
+ "scroll-padding-block-start",
264
+ "scroll-padding-block-end",
265
+ "scroll-padding-inline",
266
+ "scroll-padding-inline-start",
267
+ "scroll-padding-inline-end"
268
+ ]);
211
269
  /**
212
270
  * Returns true if the CSS property is a shorthand that StyleX cannot express directly
213
271
  * and requires expansion (e.g., `padding`, `margin`, `border`, `background`).
@@ -215,6 +273,9 @@ const STYLEX_STRING_ONLY_CSS_PROPS = new Set([
215
273
  function isCssShorthandProperty(cssProp) {
216
274
  return cssProp in DIRECTIONAL_SHORTHAND_MAP || cssProp === "border" || /^border-(top|right|bottom|left)$/.test(cssProp) || cssProp === "background";
217
275
  }
276
+ function isUnsupportedStylexProperty(cssProp) {
277
+ return UNSUPPORTED_STYLEX_CSS_PROPS.has(cssProp.trim());
278
+ }
218
279
  function isUnsupportedBackgroundShorthandValue(rawValue) {
219
280
  const value = rawValue.trim();
220
281
  return value !== "none" && !isSingleBackgroundComponent(value);
@@ -885,7 +946,7 @@ function isAstNode(v) {
885
946
  /**
886
947
  * Type guard for function-like nodes including class/object methods.
887
948
  */
888
- function isFunctionNode(node) {
949
+ function isFunctionNode$1(node) {
889
950
  if (!node || typeof node !== "object") return false;
890
951
  const type = node.type;
891
952
  return type === "FunctionDeclaration" || type === "FunctionExpression" || type === "ArrowFunctionExpression" || type === "ObjectMethod" || type === "ClassMethod";
@@ -907,7 +968,7 @@ function getDeclaratorId(decl) {
907
968
  function getArrowFnSingleParamName(fn) {
908
969
  if (fn.params.length !== 1) return null;
909
970
  const p = fn.params[0];
910
- return isIdentifier(p) ? p.name : null;
971
+ return isIdentifier$2(p) ? p.name : null;
911
972
  }
912
973
  /**
913
974
  * Extracts parameter binding information from an arrow function.
@@ -927,7 +988,7 @@ function getArrowFnSingleParamName(fn) {
927
988
  function getArrowFnParamBindings(fn) {
928
989
  if (fn.params.length !== 1) return null;
929
990
  const p = fn.params[0];
930
- if (isIdentifier(p)) return {
991
+ if (isIdentifier$2(p)) return {
931
992
  kind: "simple",
932
993
  paramName: p.name
933
994
  };
@@ -1086,6 +1147,7 @@ function collectIdentifiers(node, out) {
1086
1147
  * - Literal (ESTree/recast AST)
1087
1148
  * - TemplateLiteral without expressions (static template strings)
1088
1149
  * - TaggedTemplateExpression with css tag (styled-components css helper)
1150
+ * - TSAsExpression and TSSatisfiesExpression wrapping static values
1089
1151
  * - ArrowFunctionExpression with no params and a static body (e.g., `() => "value"` or `() => \`value\``)
1090
1152
  *
1091
1153
  * Returns null for non-literal or dynamic nodes.
@@ -1093,6 +1155,7 @@ function collectIdentifiers(node, out) {
1093
1155
  function literalToStaticValue(node) {
1094
1156
  if (!node || typeof node !== "object") return null;
1095
1157
  const type = node.type;
1158
+ if (type === "TSAsExpression" || type === "TSSatisfiesExpression") return literalToStaticValue(node.expression);
1096
1159
  if (type === "StringLiteral") return node.value;
1097
1160
  if (type === "BooleanLiteral") return node.value;
1098
1161
  if (type === "Literal") {
@@ -1376,7 +1439,7 @@ function buildStyleFnConditionExpr(args) {
1376
1439
  if (condition === "always" || isRequired) return call;
1377
1440
  return j.logicalExpression("&&", j.binaryExpression("!=", propExpr, j.nullLiteral()), call);
1378
1441
  }
1379
- function isIdentifier(node, name) {
1442
+ function isIdentifier$2(node, name) {
1380
1443
  return isIdentifierNode(node) && (name ? node.name === name : true);
1381
1444
  }
1382
1445
  function isJsxIdentifierNode(node) {
@@ -2353,6 +2416,17 @@ function hasInlineableStyleFnOnly(decl) {
2353
2416
  return true;
2354
2417
  }
2355
2418
  /**
2419
+ * Returns true when `shouldForwardProp` must be preserved by a wrapper boundary.
2420
+ * Resolver-added drops for inlined base components are applied directly during JSX rewrite.
2421
+ */
2422
+ function needsShouldForwardPropWrapper(decl) {
2423
+ const resolverOnlyShouldForwardProp = !!decl.inlinedBaseComponent && !decl.shouldForwardPropFromWithConfig;
2424
+ return !!decl.shouldForwardProp && !resolverOnlyShouldForwardProp;
2425
+ }
2426
+ function getEffectiveBaseIdent(decl) {
2427
+ return decl.originalBaseIdent ?? (decl.base.kind === "component" ? decl.base.ident : null);
2428
+ }
2429
+ /**
2356
2430
  * Returns true if any JSX usage of a component has spread attributes
2357
2431
  * (e.g., `<Comp {...props} />`). The inline path can only consume explicit
2358
2432
  * JSX attributes, so spreads require a wrapper for prop extraction.
@@ -2586,8 +2660,7 @@ function analyzeAfterEmitStep(ctx) {
2586
2660
  decl.needsWrapperComponent = true;
2587
2661
  if (decl.base.kind === "intrinsic") decl.isPolymorphicIntrinsicWrapper = true;
2588
2662
  }
2589
- const resolverOnlyShouldForwardProp = !!decl.inlinedBaseComponent && !decl.shouldForwardPropFromWithConfig;
2590
- if (decl.shouldForwardProp && !resolverOnlyShouldForwardProp) decl.needsWrapperComponent = true;
2663
+ if (needsShouldForwardPropWrapper(decl)) decl.needsWrapperComponent = true;
2591
2664
  if (decl.base.kind === "component") {
2592
2665
  const baseDecl = declByLocal.get(decl.base.ident);
2593
2666
  if (baseDecl) {
@@ -2617,8 +2690,7 @@ function analyzeAfterEmitStep(ctx) {
2617
2690
  });
2618
2691
  const hasWrapperSemantics = (d) => {
2619
2692
  if (hasAttrsAsOverride(d.attrsInfo)) return true;
2620
- const resolverOnlyShouldForwardProp = !!d.inlinedBaseComponent && !d.shouldForwardPropFromWithConfig;
2621
- if (d.shouldForwardProp && !resolverOnlyShouldForwardProp) return true;
2693
+ if (needsShouldForwardPropWrapper(d)) return true;
2622
2694
  if (d.isPolymorphicIntrinsicWrapper) return true;
2623
2695
  return false;
2624
2696
  };
@@ -2963,6 +3035,27 @@ function specifierExportedName(spec) {
2963
3035
  return null;
2964
3036
  }
2965
3037
  //#endregion
3038
+ //#region src/internal/utilities/typescript-metadata.ts
3039
+ function findTypeScriptComponentMetadata(metadata, filePath, componentNames) {
3040
+ if (!metadata) return;
3041
+ const names = new Set(componentNames);
3042
+ const resolvedFilePath = resolveExistingFilePath(filePath);
3043
+ return metadata.files.find((file) => file.filePath === resolvedFilePath)?.components.find((component) => names.has(component.name) || defaultExportMatches(component, names));
3044
+ }
3045
+ function applyTypeScriptMetadataToDecl(ctx, decl, names) {
3046
+ const typedComponent = findTypeScriptComponentMetadata(ctx.options.crossFileInfo?.typeScriptMetadata, ctx.file.path, names);
3047
+ if (!typedComponent) return;
3048
+ decl.typeScriptPropNames = new Set(typedComponent.props.map((prop) => prop.name));
3049
+ decl.typeScriptExplicitPropNames = new Set(typedComponent.explicitPropNames);
3050
+ decl.typeScriptPropTypes = new Map(typedComponent.props.map((prop) => [prop.name, prop.type]));
3051
+ decl.typeScriptOptionalProps = new Set(typedComponent.props.filter((prop) => prop.optional).map((prop) => prop.name));
3052
+ decl.typeScriptHasIndexSignature = typedComponent.hasIndexSignature;
3053
+ decl.typeScriptSupportsSxProp = typedComponent.supportsSxProp;
3054
+ }
3055
+ function defaultExportMatches(component, names) {
3056
+ return component.defaultExport && names.has("default");
3057
+ }
3058
+ //#endregion
2966
3059
  //#region src/internal/emit-wrappers/variant-condition.ts
2967
3060
  /**
2968
3061
  * Parse a variant "when" string into an AST condition expression.
@@ -2979,7 +3072,7 @@ function parseVariantWhenToAst(j, when, booleanProps) {
2979
3072
  const buildMemberExpr = (raw) => {
2980
3073
  if (!raw.includes(".")) return null;
2981
3074
  const parts = raw.split(".").map((part) => part.trim()).filter(Boolean);
2982
- if (parts.length < 2 || parts.some((part) => !isValidIdentifierName$1(part))) return null;
3075
+ if (parts.length < 2 || parts.some((part) => !isValidIdentifierName(part))) return null;
2983
3076
  return parts.slice(1).reduce((acc, part) => j.memberExpression(acc, j.identifier(part)), j.identifier(parts[0]));
2984
3077
  };
2985
3078
  const parsePropRef = (raw) => {
@@ -2991,14 +3084,14 @@ function parseVariantWhenToAst(j, when, booleanProps) {
2991
3084
  if (trimmedRaw.includes(".")) {
2992
3085
  const parts = trimmedRaw.split(".").map((part) => part.trim()).filter(Boolean);
2993
3086
  const last = parts[parts.length - 1];
2994
- if (!last || !isValidIdentifierName$1(last)) return {
3087
+ if (!last || !isValidIdentifierName(last)) return {
2995
3088
  propName: null,
2996
3089
  expr: j.identifier(trimmedRaw)
2997
3090
  };
2998
3091
  const root = parts[0];
2999
3092
  if (root === "props" || root === "p") {
3000
3093
  const propRoot = parts[1];
3001
- if (!propRoot || !isValidIdentifierName$1(propRoot)) return {
3094
+ if (!propRoot || !isValidIdentifierName(propRoot)) return {
3002
3095
  propName: null,
3003
3096
  expr: j.identifier(trimmedRaw)
3004
3097
  };
@@ -3181,6 +3274,27 @@ function buildExtraStylexPropsExprs(j, args) {
3181
3274
  return result;
3182
3275
  }
3183
3276
  /**
3277
+ * Merges adjacent `cond && styleA, !cond && styleB` expressions into
3278
+ * `cond ? styleA : styleB` without reordering other style args.
3279
+ */
3280
+ function mergeAdjacentComplementaryStyleExprs(j, styleArgs) {
3281
+ const result = [];
3282
+ for (let i = 0; i < styleArgs.length; i++) {
3283
+ const current = styleArgs[i];
3284
+ const next = styleArgs[i + 1];
3285
+ if (next) {
3286
+ const merged = mergeComplementaryLogicalPair(j, current, next);
3287
+ if (merged) {
3288
+ result.push(merged);
3289
+ i++;
3290
+ continue;
3291
+ }
3292
+ }
3293
+ result.push(current);
3294
+ }
3295
+ return result;
3296
+ }
3297
+ /**
3184
3298
  * Finds the next unconsumed entry in sorted variant entries (as `[when, key]` tuples)
3185
3299
  * that has a complementary "when" condition to the entry at `index`.
3186
3300
  * Used by both intrinsic-simple and component emitters for ternary merging.
@@ -3211,6 +3325,33 @@ function findComplementaryEntry(entries, index, consumed) {
3211
3325
  if (otherWhen && getPositiveWhen(when, otherWhen) !== null) return next;
3212
3326
  return null;
3213
3327
  }
3328
+ function mergeComplementaryLogicalPair(j, leftExpr, rightExpr) {
3329
+ const left = getConditionalStyleParts(j, leftExpr);
3330
+ const right = getConditionalStyleParts(j, rightExpr);
3331
+ if (!left || !right) return null;
3332
+ const positiveWhen = getPositiveWhen(left.when, right.when);
3333
+ if (!positiveWhen) return null;
3334
+ const isLeftPositive = areEquivalentWhen(left.when, positiveWhen);
3335
+ return j.conditionalExpression(isLeftPositive ? left.cond : right.cond, isLeftPositive ? left.style : right.style, isLeftPositive ? right.style : left.style);
3336
+ }
3337
+ function getConditionalStyleParts(j, expr) {
3338
+ if (expr.type !== "LogicalExpression" || expr.operator !== "&&") return null;
3339
+ const cond = expr.left;
3340
+ const when = printCondition(j, cond);
3341
+ if (!when) return null;
3342
+ return {
3343
+ when,
3344
+ cond,
3345
+ style: expr.right
3346
+ };
3347
+ }
3348
+ function printCondition(j, cond) {
3349
+ try {
3350
+ return j(cond).toSource();
3351
+ } catch {
3352
+ return null;
3353
+ }
3354
+ }
3214
3355
  /**
3215
3356
  * Detects if two "when" strings differ only in === vs !==.
3216
3357
  * Returns the "===" variant (the positive one) or null if they're not inverses.
@@ -3218,20 +3359,61 @@ function findComplementaryEntry(entries, index, consumed) {
3218
3359
  function areComparisonInverses(a, b) {
3219
3360
  const aNorm = normalizeWhenForComparison(a);
3220
3361
  const bNorm = normalizeWhenForComparison(b);
3221
- const eqOp = "===";
3222
- const neqOp = "!==";
3223
- const aHasNeq = aNorm.includes(neqOp);
3224
- const aHasEq = !aHasNeq && aNorm.includes(eqOp);
3225
- const bHasNeq = bNorm.includes(neqOp);
3226
- const bHasEq = !bHasNeq && bNorm.includes(eqOp);
3227
- if (aHasEq && !aHasNeq && bHasNeq && !bHasEq) {
3228
- if (aNorm.replace(eqOp, neqOp) === bNorm) return a.trim();
3229
- }
3230
- if (bHasEq && !bHasNeq && aHasNeq && !aHasEq) {
3231
- if (bNorm.replace(eqOp, neqOp) === aNorm) return b.trim();
3232
- }
3362
+ const aComparison = parseSingleComparison(aNorm);
3363
+ const bComparison = parseSingleComparison(bNorm);
3364
+ if (!aComparison || !bComparison) return null;
3365
+ if (aComparison.left !== bComparison.left || aComparison.right !== bComparison.right) return null;
3366
+ if (aComparison.operator === "===" && bComparison.operator === "!==") return a.trim();
3367
+ if (aComparison.operator === "!==" && bComparison.operator === "===") return b.trim();
3233
3368
  return null;
3234
3369
  }
3370
+ function parseSingleComparison(expr) {
3371
+ const neqIndex = findTopLevelOperator(expr, "!==");
3372
+ const eqIndex = findTopLevelOperator(expr, "===");
3373
+ if (neqIndex >= 0 && eqIndex >= 0 || neqIndex < 0 && eqIndex < 0) return null;
3374
+ const operator = neqIndex >= 0 ? "!==" : "===";
3375
+ const index = neqIndex >= 0 ? neqIndex : eqIndex;
3376
+ const left = expr.slice(0, index);
3377
+ const right = expr.slice(index + operator.length);
3378
+ if (!left || !right || hasTopLevelLogicalOperator(left) || hasTopLevelLogicalOperator(right)) return null;
3379
+ return {
3380
+ left,
3381
+ operator,
3382
+ right
3383
+ };
3384
+ }
3385
+ function hasTopLevelLogicalOperator(expr) {
3386
+ return findTopLevelOperator(expr, "&&") >= 0 || findTopLevelOperator(expr, "||") >= 0;
3387
+ }
3388
+ function findTopLevelOperator(expr, operator) {
3389
+ let depth = 0;
3390
+ let quote = null;
3391
+ for (let i = 0; i <= expr.length - operator.length; i++) {
3392
+ const ch = expr[i];
3393
+ if (quote) {
3394
+ if (ch === "\\") {
3395
+ i++;
3396
+ continue;
3397
+ }
3398
+ if (ch === quote) quote = null;
3399
+ continue;
3400
+ }
3401
+ if (ch === "\"" || ch === "'" || ch === "`") {
3402
+ quote = ch;
3403
+ continue;
3404
+ }
3405
+ if (ch === "(") {
3406
+ depth++;
3407
+ continue;
3408
+ }
3409
+ if (ch === ")") {
3410
+ depth--;
3411
+ continue;
3412
+ }
3413
+ if (depth === 0 && expr.slice(i, i + operator.length) === operator) return i;
3414
+ }
3415
+ return -1;
3416
+ }
3235
3417
  function isNegationOf(candidate, base) {
3236
3418
  const candidateNormalized = normalizeWhenForComparison(candidate);
3237
3419
  const baseNormalized = normalizeWhenForComparison(base);
@@ -3241,7 +3423,34 @@ function isNegationOf(candidate, base) {
3241
3423
  return normalizeWhenForComparison(candidateNormalized.slice(2, -1)) === baseNormalized;
3242
3424
  }
3243
3425
  function normalizeWhenForComparison(when) {
3244
- return stripOuterParens(String(when ?? "").replace(/\s+/g, ""));
3426
+ return stripOuterParens(removeWhitespaceOutsideLiterals(String(when ?? "")));
3427
+ }
3428
+ function removeWhitespaceOutsideLiterals(expr) {
3429
+ let result = "";
3430
+ let quote = null;
3431
+ for (let i = 0; i < expr.length; i++) {
3432
+ const ch = expr[i];
3433
+ if (quote) {
3434
+ result += ch;
3435
+ if (ch === "\\") {
3436
+ const next = expr[i + 1];
3437
+ if (next !== void 0) {
3438
+ result += next;
3439
+ i++;
3440
+ }
3441
+ continue;
3442
+ }
3443
+ if (ch === quote) quote = null;
3444
+ continue;
3445
+ }
3446
+ if (ch === "\"" || ch === "'" || ch === "`") {
3447
+ quote = ch;
3448
+ result += ch;
3449
+ continue;
3450
+ }
3451
+ if (!/\s/.test(ch)) result += ch;
3452
+ }
3453
+ return result;
3245
3454
  }
3246
3455
  function stripOuterParens(expr) {
3247
3456
  let current = expr;
@@ -3918,17 +4127,17 @@ function registerImports(imports, resolverImports) {
3918
4127
  function isMemberExpression(node) {
3919
4128
  return isMemberExpressionNode(node);
3920
4129
  }
3921
- /** Returns true for at-rules the codemod can transform (`@media`, `@container`). */
4130
+ /** Returns true for at-rules the codemod can transform as StyleX condition keys. */
3922
4131
  function isSupportedAtRule(atRule) {
3923
- return atRule.startsWith("@media") || atRule.startsWith("@container");
4132
+ return atRule.startsWith("@media") || atRule.startsWith("@container") || atRule.startsWith("@supports");
3924
4133
  }
3925
- /** Finds the first supported at-rule (`@media` or `@container`) in the stack, if any. */
4134
+ /** Finds the supported StyleX condition key for an at-rule stack, if representable. */
3926
4135
  function findSupportedAtRule(atRuleStack) {
3927
- return atRuleStack.find(isSupportedAtRule);
4136
+ return resolveSupportedAtRule(atRuleStack) ?? void 0;
3928
4137
  }
3929
4138
  /** Returns true when any at-rule in the stack cannot be represented by StyleX. */
3930
4139
  function hasUnsupportedAtRule(atRuleStack) {
3931
- return atRuleStack.some((atRule) => !isSupportedAtRule(atRule));
4140
+ return resolveSupportedAtRule(atRuleStack) === null;
3932
4141
  }
3933
4142
  /**
3934
4143
  * Resolves a media/container at-rule string that may contain `__SC_EXPR_N__` placeholders.
@@ -4004,8 +4213,8 @@ function getMediaFeatureContext(before, after) {
4004
4213
  } };
4005
4214
  }
4006
4215
  /** Returns true if the key looks like a StyleX style condition (pseudo, media, container). */
4007
- function isStyleConditionKey(key) {
4008
- return key.startsWith(":") || key.startsWith("::") || key.startsWith("@media") || key.startsWith("@container");
4216
+ function isStyleConditionKey$1(key) {
4217
+ return key.startsWith(":") || key.startsWith("::") || key.startsWith("@media") || key.startsWith("@container") || key.startsWith("@supports");
4009
4218
  }
4010
4219
  /**
4011
4220
  * Merges tracked @media values into a base style object as nested StyleX objects.
@@ -4112,6 +4321,20 @@ function parseStaticExprString(expr) {
4112
4321
  if (trimmed.startsWith("\"") && trimmed.endsWith("\"") || trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1);
4113
4322
  return null;
4114
4323
  }
4324
+ function resolveSupportedAtRule(atRuleStack) {
4325
+ if (atRuleStack.length === 0) return;
4326
+ if (atRuleStack.some((atRule) => !isSupportedAtRule(atRule))) return null;
4327
+ if (atRuleStack.length === 1) return atRuleStack[0];
4328
+ if (atRuleStack.every((atRule) => atRule.startsWith("@supports"))) return combineSupportsAtRules(atRuleStack);
4329
+ return null;
4330
+ }
4331
+ function combineSupportsAtRules(atRuleStack) {
4332
+ return `@supports ${atRuleStack.map((atRule) => parenthesizeSupportsCondition(atRule.slice(9).trim())).join(" and ")}`;
4333
+ }
4334
+ function parenthesizeSupportsCondition(condition) {
4335
+ if (condition.includes(" and ") || condition.includes(" or ")) return `(${condition})`;
4336
+ return condition.startsWith("(") && condition.endsWith(")") ? condition : `(${condition})`;
4337
+ }
4115
4338
  /**
4116
4339
  * Recursively walk an AST tree and return `true` if the predicate matches any node.
4117
4340
  * Skips `loc` and `comments` keys. Short-circuits on first match.
@@ -4498,8 +4721,1098 @@ function buildChildStyleObjectList(childKeys, resolvedStyleObjects) {
4498
4721
  return childStyleObjects;
4499
4722
  }
4500
4723
  //#endregion
4724
+ //#region src/internal/utilities/wrapped-component-interface.ts
4725
+ function wrappedComponentInterfaceFor(ctx, componentLocalName) {
4726
+ if (!ctx.adapter.useSxProp) return;
4727
+ const importInfo = ctx.importMap?.get(componentLocalName);
4728
+ if (importInfo) {
4729
+ const typedInterface = importInfo.source.kind === "absolutePath" ? typedComponentInterfaceFor(ctx, importInfo.source.value, importInfo.importedName === "default" ? [componentLocalName, importInfo.importedName] : [importInfo.importedName]) : void 0;
4730
+ const adapterResult = ctx.adapter.wrappedComponentInterface?.({
4731
+ localName: componentLocalName,
4732
+ importSource: importInfo.source.value,
4733
+ importedName: importInfo.importedName,
4734
+ filePath: ctx.file.path
4735
+ });
4736
+ if (adapterResult !== void 0) {
4737
+ if (adapterResult.acceptsSx && hasTypedSxConstraints(typedInterface)) return {
4738
+ ...adapterResult,
4739
+ sxExcludedProperties: mergeUniqueStrings(adapterResult.sxExcludedProperties, typedInterface.sxExcludedProperties ?? []),
4740
+ sxAllowedProperties: mergeAllowedPropertyLists(adapterResult.sxAllowedProperties, typedInterface.sxAllowedProperties)
4741
+ };
4742
+ return adapterResult;
4743
+ }
4744
+ return typedInterface;
4745
+ }
4746
+ return typedComponentInterfaceFor(ctx, ctx.file.path, [componentLocalName]);
4747
+ }
4748
+ function hasTypedSxConstraints(typedInterface) {
4749
+ return typedInterface !== void 0 && ((typedInterface.sxExcludedProperties?.length ?? 0) > 0 || typedInterface.sxAllowedProperties !== void 0);
4750
+ }
4751
+ function typedComponentInterfaceFor(ctx, filePath, componentNames) {
4752
+ const typedComponent = findTypeScriptComponentMetadata(ctx.options.crossFileInfo?.typeScriptMetadata, filePath, componentNames);
4753
+ if (typedComponent?.supportsSxProp) return {
4754
+ acceptsSx: true,
4755
+ sxExcludedProperties: typedComponent.sxExcludedProperties,
4756
+ sxAllowedProperties: typedComponent.sxAllowedProperties
4757
+ };
4758
+ }
4759
+ function mergeAllowedPropertyLists(first, second) {
4760
+ if (first === void 0) return second === void 0 ? void 0 : [...second];
4761
+ if (second === void 0) return [...first];
4762
+ const secondSet = new Set(second);
4763
+ return first.filter((name) => secondSet.has(name));
4764
+ }
4765
+ function mergeUniqueStrings(first, second) {
4766
+ return [...new Set([...first ?? [], ...second])];
4767
+ }
4768
+ //#endregion
4769
+ //#region src/internal/utilities/style-composition-plan.ts
4770
+ function buildStyleKeySequence(ctx, decl, options) {
4771
+ const entries = [];
4772
+ const afterBase = new Set(decl.extraStyleKeysAfterBase ?? []);
4773
+ if (options?.includeLocalBase !== false) for (const styleKey of localBaseStyleKeys(ctx, decl)) entries.push({
4774
+ styleKey,
4775
+ patchable: false,
4776
+ source: "base"
4777
+ });
4778
+ for (const styleKey of decl.extraStyleKeys ?? []) if (!afterBase.has(styleKey)) entries.push({
4779
+ styleKey,
4780
+ patchable: false,
4781
+ source: "mixin"
4782
+ });
4783
+ if (!decl.skipBaseStyleRef) entries.push({
4784
+ styleKey: decl.styleKey,
4785
+ patchable: true,
4786
+ source: "base"
4787
+ });
4788
+ for (const styleKey of decl.extraStyleKeysAfterBase ?? []) entries.push({
4789
+ styleKey,
4790
+ patchable: true,
4791
+ source: "mixin"
4792
+ });
4793
+ const variantAndStyleFnEntries = buildVariantAndStyleFnEntries(decl);
4794
+ const variantDimensionEntries = buildVariantDimensionEntries(decl);
4795
+ entries.push(...variantAndStyleFnEntries.immediate);
4796
+ entries.push(...variantDimensionEntries.immediate);
4797
+ entries.push(...buildExtraStylexPropsArgEntries(decl));
4798
+ entries.push(...buildThemeEntries(decl));
4799
+ entries.push(...buildAttrWrapperEntries(decl));
4800
+ entries.push(...buildPseudoExpandEntries(decl));
4801
+ entries.push(...buildPseudoAliasEntries(decl));
4802
+ entries.push(...buildCompoundVariantEntries(decl));
4803
+ entries.push(...mergeOrderedEntries$1([variantDimensionEntries.ordered, variantAndStyleFnEntries.ordered]));
4804
+ entries.push(...buildEnumVariantEntries(decl));
4805
+ entries.push(...buildCallSiteCombinedEntries(decl));
4806
+ entries.push(...buildPromotedStyleEntries(decl));
4807
+ if (decl.adjacentSiblingStyleKey) entries.push({
4808
+ styleKey: decl.adjacentSiblingStyleKey,
4809
+ patchable: true,
4810
+ source: "adjacent"
4811
+ });
4812
+ return entries;
4813
+ }
4814
+ function buildExtraStylexPropsArgEntries(decl) {
4815
+ return (decl.extraStylexPropsArgs ?? []).map((_, index) => ({
4816
+ styleKey: `${decl.styleKey}ExtraStylexPropsArg${index}`,
4817
+ patchable: false,
4818
+ contributesDynamic: true,
4819
+ source: "propsArg"
4820
+ }));
4821
+ }
4822
+ function localBaseStyleKeys(ctx, decl) {
4823
+ if (decl.extendsStyleKey) return [decl.extendsStyleKey];
4824
+ const keys = [];
4825
+ const visited = new Set([decl.localName]);
4826
+ let currentBase = decl.base;
4827
+ while (currentBase.kind === "component") {
4828
+ if (visited.has(currentBase.ident)) break;
4829
+ visited.add(currentBase.ident);
4830
+ const baseDecl = ctx.declByLocal?.get(currentBase.ident);
4831
+ if (!baseDecl || baseDecl.skipTransform) break;
4832
+ keys.push(baseDecl.styleKey);
4833
+ currentBase = baseDecl.base;
4834
+ }
4835
+ return keys.reverse();
4836
+ }
4837
+ function buildVariantAndStyleFnEntries(decl) {
4838
+ const variantEntries = Object.entries(decl.variantStyleKeys ?? {}).map(([when, styleKey]) => ({
4839
+ when,
4840
+ entry: {
4841
+ styleKey,
4842
+ patchable: true,
4843
+ contributes: false,
4844
+ source: "variant"
4845
+ }
4846
+ }));
4847
+ const styleFnEntries = (decl.styleFnFromProps ?? []).map((styleFn) => ({
4848
+ sourceOrder: styleFn.sourceOrder,
4849
+ entry: {
4850
+ styleKey: styleFn.fnKey,
4851
+ patchable: true,
4852
+ source: "styleFn"
4853
+ }
4854
+ }));
4855
+ if (!(Object.keys(decl.variantSourceOrder ?? {}).length > 0 || styleFnEntries.some((entry) => entry.sourceOrder !== void 0))) return {
4856
+ immediate: [...variantEntries.map((entry) => entry.entry), ...styleFnEntries.map((entry) => entry.entry)],
4857
+ ordered: []
4858
+ };
4859
+ const immediate = [...variantEntries.filter((entry) => decl.variantSourceOrder?.[entry.when] === void 0).map((entry) => entry.entry), ...styleFnEntries.filter((entry) => entry.sourceOrder === void 0).map((entry) => entry.entry)];
4860
+ const ordered = [];
4861
+ let index = 0;
4862
+ for (const variant of variantEntries) {
4863
+ const order = decl.variantSourceOrder?.[variant.when];
4864
+ if (order === void 0) continue;
4865
+ ordered.push({
4866
+ order,
4867
+ index,
4868
+ entry: variant.entry
4869
+ });
4870
+ index += 1;
4871
+ }
4872
+ for (const styleFn of styleFnEntries) {
4873
+ if (styleFn.sourceOrder === void 0) continue;
4874
+ ordered.push({
4875
+ order: styleFn.sourceOrder,
4876
+ index,
4877
+ entry: styleFn.entry
4878
+ });
4879
+ index += 1;
4880
+ }
4881
+ return {
4882
+ immediate,
4883
+ ordered
4884
+ };
4885
+ }
4886
+ function buildVariantDimensionEntries(decl) {
4887
+ const immediate = [];
4888
+ const ordered = [];
4889
+ let index = 0;
4890
+ for (const dimension of decl.variantDimensions ?? []) {
4891
+ const entries = Object.entries(dimension.variants).map(([variantKey, styleObj]) => ({
4892
+ styleKey: `${dimension.variantObjectName}.${variantKey}`,
4893
+ styleObj,
4894
+ patchable: true,
4895
+ contributes: false,
4896
+ source: "variant"
4897
+ }));
4898
+ if (dimension.fallbackFnKey) entries.push({
4899
+ styleKey: dimension.fallbackFnKey,
4900
+ patchable: true,
4901
+ source: "styleFn"
4902
+ });
4903
+ if (dimension.sourceOrder === void 0) {
4904
+ immediate.push(...entries);
4905
+ continue;
4906
+ }
4907
+ for (const entry of entries) {
4908
+ ordered.push({
4909
+ order: dimension.sourceOrder,
4910
+ index,
4911
+ entry
4912
+ });
4913
+ index += 1;
4914
+ }
4915
+ }
4916
+ return {
4917
+ immediate,
4918
+ ordered
4919
+ };
4920
+ }
4921
+ function mergeOrderedEntries$1(groups) {
4922
+ return groups.flat().sort((a, b) => a.order - b.order || a.index - b.index).map((orderedEntry) => orderedEntry.entry);
4923
+ }
4924
+ function buildPseudoExpandEntries(decl) {
4925
+ return (decl.pseudoExpandSelectors ?? []).map((entry) => ({
4926
+ styleKey: entry.styleKey,
4927
+ patchable: true,
4928
+ source: "pseudo"
4929
+ }));
4930
+ }
4931
+ function buildThemeEntries(decl) {
4932
+ const entries = [];
4933
+ for (const hook of decl.needsUseThemeHook ?? []) {
4934
+ if (hook.trueStyleKey) entries.push({
4935
+ styleKey: hook.trueStyleKey,
4936
+ patchable: true,
4937
+ contributes: false,
4938
+ source: "theme"
4939
+ });
4940
+ if (hook.falseStyleKey) entries.push({
4941
+ styleKey: hook.falseStyleKey,
4942
+ patchable: true,
4943
+ contributes: false,
4944
+ source: "theme"
4945
+ });
4946
+ }
4947
+ return entries;
4948
+ }
4949
+ function buildPseudoAliasEntries(decl) {
4950
+ return (decl.pseudoAliasSelectors ?? []).flatMap((entry) => entry.styleKeys.map((styleKey) => ({
4951
+ styleKey,
4952
+ patchable: true,
4953
+ contributes: false,
4954
+ source: "pseudo"
4955
+ })));
4956
+ }
4957
+ function buildCompoundVariantEntries(decl) {
4958
+ return (decl.compoundVariants ?? []).flatMap((entry) => {
4959
+ if (entry.kind === "3branch") return [
4960
+ entry.outerTruthyKey,
4961
+ entry.innerTruthyKey,
4962
+ entry.innerFalsyKey
4963
+ ].map((styleKey) => ({
4964
+ styleKey,
4965
+ patchable: true,
4966
+ contributes: false,
4967
+ source: "variant"
4968
+ }));
4969
+ return [
4970
+ entry.outerTruthyInnerTruthyKey,
4971
+ entry.outerTruthyInnerFalsyKey,
4972
+ entry.outerFalsyInnerTruthyKey,
4973
+ entry.outerFalsyInnerFalsyKey
4974
+ ].map((styleKey) => ({
4975
+ styleKey,
4976
+ patchable: true,
4977
+ contributes: false,
4978
+ source: "variant"
4979
+ }));
4980
+ });
4981
+ }
4982
+ function buildAttrWrapperEntries(decl) {
4983
+ const attrWrapper = decl.attrWrapper;
4984
+ if (!attrWrapper) return [];
4985
+ return [
4986
+ attrWrapper.checkboxKey,
4987
+ attrWrapper.radioKey,
4988
+ attrWrapper.readonlyKey,
4989
+ attrWrapper.externalKey,
4990
+ attrWrapper.httpsKey,
4991
+ attrWrapper.pdfKey
4992
+ ].filter((styleKey) => typeof styleKey === "string").map((styleKey) => ({
4993
+ styleKey,
4994
+ patchable: true,
4995
+ source: "attr"
4996
+ }));
4997
+ }
4998
+ function buildCallSiteCombinedEntries(decl) {
4999
+ return (decl.callSiteCombinedStyles ?? []).map((entry) => ({
5000
+ styleKey: entry.styleKey,
5001
+ patchable: true,
5002
+ source: "combined"
5003
+ }));
5004
+ }
5005
+ function buildPromotedStyleEntries(decl) {
5006
+ return (decl.promotedStyleProps ?? []).filter((entry) => !entry.mergeIntoBase).map((entry) => ({
5007
+ styleKey: entry.styleKey,
5008
+ patchable: true,
5009
+ source: "promoted"
5010
+ }));
5011
+ }
5012
+ function buildEnumVariantEntries(decl) {
5013
+ const enumVariant = decl.enumVariant;
5014
+ if (!enumVariant) return [];
5015
+ return [{
5016
+ styleKey: enumVariant.baseKey,
5017
+ patchable: true,
5018
+ source: "enum"
5019
+ }, ...enumVariant.cases.map((entry) => ({
5020
+ styleKey: entry.styleKey,
5021
+ patchable: true,
5022
+ source: "enum"
5023
+ }))];
5024
+ }
5025
+ //#endregion
5026
+ //#region src/internal/utilities/conditional-style-defaults.ts
5027
+ const CONDITIONAL_DEFAULT_WARNING = "Conditional StyleX default would override an unproven earlier style for the same property";
5028
+ function guardGeneratedConditionalDefaults(ctx, styledDecls) {
5029
+ if (!ctx.resolvedStyleObjects) return "ok";
5030
+ for (const decl of styledDecls) {
5031
+ if (decl.skipTransform || decl.isCssHelper) continue;
5032
+ if (patchConditionalDefaultsForSequence({
5033
+ ctx,
5034
+ decl,
5035
+ entries: buildStyleKeySequence(ctx, decl)
5036
+ }) === "bail") return "bail";
5037
+ }
5038
+ return "ok";
5039
+ }
5040
+ function propertiesWithNullConditionalDefault(styleObj) {
5041
+ const props = [];
5042
+ for (const [prop, value] of Object.entries(styleObj)) {
5043
+ if (isMetadataOrConditionKey(prop) || !isPlainStyleObject$1(value)) continue;
5044
+ if (isConditionalStyleMap(value) && value.default === null) props.push(prop);
5045
+ }
5046
+ return props;
5047
+ }
5048
+ function propertiesWithUnsafeNullConditionalDefault(styleObj) {
5049
+ const props = new Set(propertiesWithNullConditionalDefault(styleObj));
5050
+ for (const [prop, value] of Object.entries(styleObj)) {
5051
+ if (isMetadataOrConditionKey(prop) || !isPlainStyleObject$1(value)) continue;
5052
+ if (hasNestedNullConditionalDefault(value)) props.add(prop);
5053
+ }
5054
+ return [...props];
5055
+ }
5056
+ function patchNullConditionalDefaultsForProp(styleObj, prop, earlier) {
5057
+ const value = styleObj[prop];
5058
+ if (!isPlainStyleObject$1(value) || !isConditionalStyleMap(value)) return "safe";
5059
+ let inheritedDefault = inferDefaultFromValue(value);
5060
+ if (value.default === null && earlier.kind === "static" && earlier.value !== null) {
5061
+ value.default = earlier.value;
5062
+ inheritedDefault = earlier;
5063
+ } else if (value.default === null && earlier.kind === "dynamic") return "bail";
5064
+ else if (value.default === null) inheritedDefault = earlier;
5065
+ if (!hasNestedNullConditionalDefault(value)) return "safe";
5066
+ if (inheritedDefault.kind === "static" && inheritedDefault.value !== null) {
5067
+ patchNestedNullConditionalDefaults(value, inheritedDefault.value);
5068
+ return "patched";
5069
+ }
5070
+ return inheritedDefault.kind === "dynamic" ? "bail" : "safe";
5071
+ }
5072
+ function patchConditionalDefaultsForSequence(args) {
5073
+ const { ctx, decl, entries } = args;
5074
+ const defaults = /* @__PURE__ */ new Map();
5075
+ let hasDynamicUnknownContributor = false;
5076
+ for (const entry of entries) {
5077
+ const source = entry.styleObj ?? ctx.resolvedStyleObjects?.get(entry.styleKey);
5078
+ if (entry.patchable && isPlainStyleObject$1(source)) for (const prop of propertiesWithUnsafeNullConditionalDefault(source)) {
5079
+ const patchResult = patchNullConditionalDefaultsForProp(source, prop, hasDynamicUnknownContributor ? { kind: "dynamic" } : defaults.get(prop) ?? { kind: "absent" });
5080
+ if (patchResult === "patched" || patchResult === "safe") continue;
5081
+ ctx.warnings.push({
5082
+ severity: "warning",
5083
+ type: CONDITIONAL_DEFAULT_WARNING,
5084
+ loc: decl.loc,
5085
+ context: {
5086
+ component: decl.localName,
5087
+ styleKey: entry.styleKey,
5088
+ property: prop,
5089
+ source: entry.source,
5090
+ reason: "an earlier generated style for this property can vary at runtime",
5091
+ todo: `TODO: make the ${prop} default explicit in ${entry.styleKey}, or keep the conditional override in the same dynamic style function as the base value.`
5092
+ }
5093
+ });
5094
+ return "bail";
5095
+ }
5096
+ else if (entry.patchable) for (const prop of functionPropertiesWithNullConditionalDefault$1(source)) {
5097
+ if ((defaults.get(prop) ?? { kind: "absent" }).kind === "absent") continue;
5098
+ ctx.warnings.push({
5099
+ severity: "warning",
5100
+ type: CONDITIONAL_DEFAULT_WARNING,
5101
+ loc: decl.loc,
5102
+ context: {
5103
+ component: decl.localName,
5104
+ styleKey: entry.styleKey,
5105
+ property: prop,
5106
+ source: entry.source,
5107
+ reason: "a generated dynamic style function would clear an earlier default",
5108
+ todo: `TODO: merge the ${prop} base value into ${entry.styleKey}'s dynamic conditional default.`
5109
+ }
5110
+ });
5111
+ return "bail";
5112
+ }
5113
+ if (entry.contributesDynamic) {
5114
+ hasDynamicUnknownContributor = true;
5115
+ continue;
5116
+ }
5117
+ if (entry.contributes !== false) for (const [prop, inference] of inferDefaultContributions(source)) if (inference.kind === "absent") defaults.delete(prop);
5118
+ else defaults.set(prop, inference);
5119
+ }
5120
+ return "ok";
5121
+ }
5122
+ function inferDefaultContributions(source) {
5123
+ if (isPlainStyleObject$1(source)) return inferStyleObjectContributions(source);
5124
+ return inferStyleFunctionContributions(source);
5125
+ }
5126
+ function inferStyleObjectContributions(styleObj) {
5127
+ const contributions = /* @__PURE__ */ new Map();
5128
+ for (const [prop, value] of Object.entries(styleObj)) {
5129
+ if (isMetadataOrConditionKey(prop)) continue;
5130
+ contributions.set(prop, inferDefaultFromValue(value));
5131
+ }
5132
+ return contributions;
5133
+ }
5134
+ function inferStyleFunctionContributions(source) {
5135
+ const returnedObject = readFunctionReturnedObject$1(source);
5136
+ const contributions = /* @__PURE__ */ new Map();
5137
+ if (!returnedObject) return contributions;
5138
+ for (const property of getObjectProperties$1(returnedObject)) {
5139
+ const key = readPropertyKey$1(property);
5140
+ if (!key || isMetadataOrConditionKey(key)) continue;
5141
+ contributions.set(key, { kind: "dynamic" });
5142
+ }
5143
+ return contributions;
5144
+ }
5145
+ function functionPropertiesWithNullConditionalDefault$1(source) {
5146
+ const returnedObject = readFunctionReturnedObject$1(source);
5147
+ if (!returnedObject) return [];
5148
+ const props = [];
5149
+ for (const property of getObjectProperties$1(returnedObject)) {
5150
+ const key = readPropertyKey$1(property);
5151
+ if (!key || isMetadataOrConditionKey(key)) continue;
5152
+ if (astObjectHasNullConditionalDefault(property.value)) props.push(key);
5153
+ }
5154
+ return props;
5155
+ }
5156
+ function inferDefaultFromValue(value) {
5157
+ if (isStaticStyleValue(value)) return value === null ? { kind: "absent" } : {
5158
+ kind: "static",
5159
+ value
5160
+ };
5161
+ if (isPlainStyleObject$1(value) && isConditionalStyleMap(value)) {
5162
+ const defaultValue = value.default;
5163
+ return isStaticStyleValue(defaultValue) ? defaultValue === null ? { kind: "absent" } : {
5164
+ kind: "static",
5165
+ value: defaultValue
5166
+ } : { kind: "dynamic" };
5167
+ }
5168
+ return { kind: "dynamic" };
5169
+ }
5170
+ function isConditionalStyleMap(value) {
5171
+ return Object.keys(value).some((key) => key === "default" || isStyleConditionKey(key));
5172
+ }
5173
+ function astObjectHasNullConditionalDefault(value) {
5174
+ if (!isObjectExpression$2(value)) return false;
5175
+ let hasCondition = false;
5176
+ let hasNullDefault = false;
5177
+ for (const property of getObjectProperties$1(value)) {
5178
+ const key = readPropertyKey$1(property);
5179
+ if (!key) continue;
5180
+ hasCondition ||= key === "default" || isStyleConditionKey(key);
5181
+ if (key === "default" && isNullLiteral$2(property.value)) hasNullDefault = true;
5182
+ if (isObjectExpression$2(property.value) && astObjectHasNullConditionalDefault(property.value)) return true;
5183
+ }
5184
+ return hasCondition && hasNullDefault;
5185
+ }
5186
+ function hasNestedNullConditionalDefault(value) {
5187
+ for (const [key, nested] of Object.entries(value)) {
5188
+ if (key === "__computedKeys" && computedEntriesHaveNullConditionalDefault(nested)) return true;
5189
+ if (key === "default" || !isPlainStyleObject$1(nested)) continue;
5190
+ if (isConditionalStyleMap(nested) && nested.default === null) return true;
5191
+ if (hasNestedNullConditionalDefault(nested)) return true;
5192
+ }
5193
+ return false;
5194
+ }
5195
+ function patchNestedNullConditionalDefaults(value, inheritedDefault) {
5196
+ for (const [key, nested] of Object.entries(value)) {
5197
+ if (key === "__computedKeys") {
5198
+ patchComputedEntryDefaults(nested, inheritedDefault);
5199
+ continue;
5200
+ }
5201
+ if (key === "default" || !isPlainStyleObject$1(nested)) continue;
5202
+ let nextDefault = inheritedDefault;
5203
+ if (isConditionalStyleMap(nested)) if (nested.default === null) nested.default = inheritedDefault;
5204
+ else {
5205
+ const nestedDefault = inferDefaultFromValue(nested);
5206
+ if (nestedDefault.kind === "static" && nestedDefault.value !== null) nextDefault = nestedDefault.value;
5207
+ }
5208
+ patchNestedNullConditionalDefaults(nested, nextDefault);
5209
+ }
5210
+ }
5211
+ function computedEntriesHaveNullConditionalDefault(value) {
5212
+ return getComputedEntryValues(value).some((entryValue) => isPlainStyleObject$1(entryValue) && (isConditionalStyleMap(entryValue) && entryValue.default === null || hasNestedNullConditionalDefault(entryValue)) || astObjectHasNullConditionalDefault(entryValue));
5213
+ }
5214
+ function patchComputedEntryDefaults(value, inheritedDefault) {
5215
+ for (const entryValue of getComputedEntryValues(value)) {
5216
+ if (isObjectExpression$2(entryValue)) {
5217
+ patchAstObjectNullConditionalDefaults(entryValue, inheritedDefault);
5218
+ continue;
5219
+ }
5220
+ if (!isPlainStyleObject$1(entryValue)) continue;
5221
+ let nextDefault = inheritedDefault;
5222
+ if (isConditionalStyleMap(entryValue)) if (entryValue.default === null) entryValue.default = inheritedDefault;
5223
+ else {
5224
+ const entryDefault = inferDefaultFromValue(entryValue);
5225
+ if (entryDefault.kind === "static" && entryDefault.value !== null) nextDefault = entryDefault.value;
5226
+ }
5227
+ patchNestedNullConditionalDefaults(entryValue, nextDefault);
5228
+ }
5229
+ }
5230
+ function getComputedEntryValues(value) {
5231
+ if (!Array.isArray(value)) return [];
5232
+ return value.map((entry) => isAstRecord(entry) ? entry.value : void 0);
5233
+ }
5234
+ function patchAstObjectNullConditionalDefaults(value, inheritedDefault) {
5235
+ let nextDefault = inheritedDefault;
5236
+ for (const property of getObjectProperties$1(value)) {
5237
+ if (readPropertyKey$1(property) === "default") {
5238
+ if (isNullLiteral$2(property.value)) property.value = astLiteral(inheritedDefault);
5239
+ else {
5240
+ const staticDefault = readStaticAstLiteral(property.value);
5241
+ if (staticDefault !== void 0 && staticDefault !== null) nextDefault = staticDefault;
5242
+ }
5243
+ continue;
5244
+ }
5245
+ if (isObjectExpression$2(property.value)) patchAstObjectNullConditionalDefaults(property.value, nextDefault);
5246
+ }
5247
+ }
5248
+ function astLiteral(value) {
5249
+ return {
5250
+ type: "Literal",
5251
+ value
5252
+ };
5253
+ }
5254
+ function readStaticAstLiteral(value) {
5255
+ if (!isAstRecord(value)) return;
5256
+ if (value.type === "StringLiteral" || value.type === "NumericLiteral" || value.type === "BooleanLiteral" || value.type === "Literal") return typeof value.value === "string" || typeof value.value === "number" || typeof value.value === "boolean" || value.value === null ? value.value : void 0;
5257
+ if (value.type === "NullLiteral") return null;
5258
+ }
5259
+ function isStyleConditionKey(key) {
5260
+ return key.startsWith(":") || key.startsWith("@");
5261
+ }
5262
+ function isMetadataOrConditionKey(key) {
5263
+ return key.startsWith("__") || isStyleConditionKey(key);
5264
+ }
5265
+ function isStaticStyleValue(value) {
5266
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null;
5267
+ }
5268
+ function isPlainStyleObject$1(value) {
5269
+ return !!value && typeof value === "object" && !Array.isArray(value) && !isAstNode(value);
5270
+ }
5271
+ function readFunctionReturnedObject$1(node) {
5272
+ if (!isAstRecord(node)) return null;
5273
+ if (node.type !== "ArrowFunctionExpression" && node.type !== "FunctionExpression" && node.type !== "FunctionDeclaration") return null;
5274
+ const body = node.body;
5275
+ if (isObjectExpression$2(body)) return body;
5276
+ if (!isAstRecord(body) || body.type !== "BlockStatement") return null;
5277
+ for (const statement of Array.isArray(body.body) ? body.body : []) if (isAstRecord(statement) && statement.type === "ReturnStatement" && isObjectExpression$2(statement.argument)) return statement.argument;
5278
+ return null;
5279
+ }
5280
+ function getObjectProperties$1(node) {
5281
+ return Array.isArray(node.properties) ? node.properties.filter(isAstRecord) : [];
5282
+ }
5283
+ function readPropertyKey$1(property) {
5284
+ const key = property.key;
5285
+ if (isIdentifier$1(key)) return key.name;
5286
+ if (isAstRecord(key) && (key.type === "StringLiteral" || key.type === "Literal")) return typeof key.value === "string" ? key.value : null;
5287
+ return null;
5288
+ }
5289
+ function isObjectExpression$2(node) {
5290
+ return isAstRecord(node) && node.type === "ObjectExpression";
5291
+ }
5292
+ function isIdentifier$1(node) {
5293
+ return isAstRecord(node) && node.type === "Identifier" && typeof node.name === "string";
5294
+ }
5295
+ function isNullLiteral$2(node) {
5296
+ return isAstRecord(node) && (node.type === "NullLiteral" || node.type === "Literal" && node.value === null);
5297
+ }
5298
+ function isAstRecord(value) {
5299
+ return !!value && typeof value === "object";
5300
+ }
5301
+ //#endregion
5302
+ //#region src/internal/utilities/forwarded-sx-defaults.ts
5303
+ /**
5304
+ * Guards conditional StyleX defaults forwarded through wrapped component `sx`.
5305
+ * Core concepts: sx composition, conditional defaults, and static base proofs.
5306
+ */
5307
+ function guardForwardedSxConditionalDefaults(ctx, styledDecls) {
5308
+ if (!ctx.adapter.useSxProp || !ctx.resolvedStyleObjects) return "ok";
5309
+ for (const decl of styledDecls) {
5310
+ if (decl.base.kind !== "component" || !wrappedComponentForwardsSx(ctx, decl.base.ident)) continue;
5311
+ for (const entry of buildStyleKeySequence(ctx, decl, { includeLocalBase: false })) {
5312
+ const styleObj = entry.styleObj ?? ctx.resolvedStyleObjects.get(entry.styleKey);
5313
+ if (!isRecord(styleObj)) continue;
5314
+ if (guardForwardedSxStyleObject(ctx, decl, styleObj) === "bail") return "bail";
5315
+ for (const prop of functionPropertiesWithNullConditionalDefault(styleObj)) {
5316
+ if (applyForwardedSxDefault({
5317
+ ctx,
5318
+ decl,
5319
+ prop,
5320
+ applyInference: (inferred) => {
5321
+ if (inferred.kind === "static") {
5322
+ setFunctionConditionalDefault(styleObj, prop, inferred.value);
5323
+ return "patched";
5324
+ }
5325
+ return inferred.kind === "absent" ? "safe" : "bail";
5326
+ }
5327
+ }) === "ok") continue;
5328
+ return "bail";
5329
+ }
5330
+ }
5331
+ }
5332
+ return "ok";
5333
+ }
5334
+ function guardForwardedSxStyleObject(ctx, decl, styleObj) {
5335
+ for (const prop of propertiesWithUnsafeNullConditionalDefault(styleObj)) if (applyForwardedSxDefault({
5336
+ ctx,
5337
+ decl,
5338
+ prop,
5339
+ applyInference: (inferred) => {
5340
+ if (inferred.kind !== "static" && inferred.kind !== "absent") return "bail";
5341
+ return patchNullConditionalDefaultsForProp(styleObj, prop, toDefaultInference(inferred));
5342
+ }
5343
+ }) !== "ok") return "bail";
5344
+ return "ok";
5345
+ }
5346
+ function applyForwardedSxDefault(args) {
5347
+ const { ctx, decl, prop, applyInference } = args;
5348
+ const wrappedComponent = decl.base.kind === "component" ? decl.base.ident : "";
5349
+ const inferred = inferWrappedComponentSxProperty(ctx, wrappedComponent, prop);
5350
+ const applied = applyInference(inferred);
5351
+ if (applied === "patched" || applied === "safe") return "ok";
5352
+ ctx.warnings.push({
5353
+ severity: "warning",
5354
+ type: FORWARDED_SX_DEFAULT_WARNING,
5355
+ loc: decl.loc,
5356
+ context: {
5357
+ localName: decl.localName,
5358
+ wrappedComponent,
5359
+ property: prop,
5360
+ reason: inferred.kind === "variable" ? "wrapped component base property can vary before sx is applied" : "wrapped component base default could not be proven",
5361
+ todo: `TODO: set an explicit default for ${prop} or avoid forwarding this conditional override through sx.`
5362
+ }
5363
+ });
5364
+ return "bail";
5365
+ }
5366
+ function toDefaultInference(inferred) {
5367
+ if (inferred.kind === "static") return inferred;
5368
+ if (inferred.kind === "absent") return inferred;
5369
+ return { kind: "dynamic" };
5370
+ }
5371
+ const FORWARDED_SX_DEFAULT_WARNING = "Forwarded sx conditional default would override an unproven wrapped component base style";
5372
+ function wrappedComponentForwardsSx(ctx, componentLocalName) {
5373
+ return wrappedComponentInterfaceFor(ctx, componentLocalName)?.acceptsSx === true;
5374
+ }
5375
+ function inferWrappedComponentSxProperty(ctx, componentLocalName, prop) {
5376
+ const source = readComponentSource(ctx, componentLocalName);
5377
+ if (!source) return { kind: "unknown" };
5378
+ const root = parseSource(ctx.api.jscodeshift, source.source);
5379
+ if (!root) return { kind: "unknown" };
5380
+ const styleMaps = collectStylexCreateMaps(root.ast);
5381
+ const component = findComponentFunction(root.ast, source.componentNames);
5382
+ if (!component) return { kind: "unknown" };
5383
+ const observations = collectSxCompositionObservations(component, collectSxBindings(component), styleMaps, prop);
5384
+ if (observations.length === 0) return { kind: "unknown" };
5385
+ return mergePropertyInferences(observations);
5386
+ }
5387
+ function readComponentSource(ctx, componentLocalName) {
5388
+ const importInfo = ctx.importMap?.get(componentLocalName);
5389
+ if (!importInfo) return {
5390
+ source: ctx.file.source,
5391
+ componentNames: [componentLocalName]
5392
+ };
5393
+ const absolutePath = importInfo.source.kind === "absolutePath" ? importInfo.source.value : isRelativeSpecifier(importInfo.source.value) ? resolve(dirname(ctx.file.path), importInfo.source.value) : null;
5394
+ if (!absolutePath) return null;
5395
+ const source = readSourceFile(ctx, absolutePath);
5396
+ if (!source) return null;
5397
+ return {
5398
+ source,
5399
+ componentNames: importInfo.importedName === "default" ? [componentLocalName, importInfo.importedName] : [importInfo.importedName]
5400
+ };
5401
+ }
5402
+ function readSourceFile(ctx, absolutePath) {
5403
+ for (const candidate of sourcePathCandidates(absolutePath)) {
5404
+ const override = ctx.options.transformedFileSources?.get(toRealPath(candidate));
5405
+ if (override !== void 0) return override;
5406
+ if (existsSync(candidate)) try {
5407
+ return readFileSync(candidate, "utf8");
5408
+ } catch {
5409
+ continue;
5410
+ }
5411
+ }
5412
+ return null;
5413
+ }
5414
+ function sourcePathCandidates(absolutePath) {
5415
+ return [
5416
+ "",
5417
+ ".tsx",
5418
+ ".ts",
5419
+ ".jsx",
5420
+ ".js",
5421
+ "/index.tsx",
5422
+ "/index.ts",
5423
+ "/index.jsx",
5424
+ "/index.js"
5425
+ ].map((ext) => absolutePath + ext);
5426
+ }
5427
+ function parseSource(jscodeshift, source) {
5428
+ try {
5429
+ return { ast: jscodeshift.withParser("tsx")(source).get().node };
5430
+ } catch {
5431
+ return null;
5432
+ }
5433
+ }
5434
+ function collectStylexCreateMaps(ast) {
5435
+ const maps = /* @__PURE__ */ new Map();
5436
+ walk(ast, (node) => {
5437
+ if (node.type !== "VariableDeclarator") return;
5438
+ const id = node.id;
5439
+ const init = node.init;
5440
+ if (!isIdentifier(id) || !isRecord(init) || !isStylexCreateCall$1(init)) return;
5441
+ const stylesArg = getCallArguments(init)[0];
5442
+ if (!isObjectExpression$1(stylesArg)) return;
5443
+ maps.set(id.name, readStyleEntries(stylesArg));
5444
+ });
5445
+ return maps;
5446
+ }
5447
+ function readStyleEntries(stylexCreateArg) {
5448
+ const entries = /* @__PURE__ */ new Map();
5449
+ for (const property of getObjectProperties(stylexCreateArg)) {
5450
+ const key = readPropertyKey(property);
5451
+ const value = property.value;
5452
+ if (!key || !value) continue;
5453
+ if (isObjectExpression$1(value)) {
5454
+ entries.set(key, {
5455
+ kind: "object",
5456
+ props: readStyleObjectProps(value)
5457
+ });
5458
+ continue;
5459
+ }
5460
+ const returnedObject = readFunctionReturnedObject(value);
5461
+ if (returnedObject) entries.set(key, {
5462
+ kind: "function",
5463
+ props: new Set(readStyleObjectProps(returnedObject).keys())
5464
+ });
5465
+ }
5466
+ return entries;
5467
+ }
5468
+ function readStyleObjectProps(styleObject) {
5469
+ const props = /* @__PURE__ */ new Map();
5470
+ for (const property of getObjectProperties(styleObject)) {
5471
+ const key = readPropertyKey(property);
5472
+ if (!key || !property.value) continue;
5473
+ const value = readStaticStyleValue(property.value);
5474
+ props.set(key, value.found ? {
5475
+ kind: "static",
5476
+ value: value.value
5477
+ } : { kind: "dynamic" });
5478
+ }
5479
+ return props;
5480
+ }
5481
+ function readStaticStyleValue(node) {
5482
+ if (!isRecord(node)) return { found: false };
5483
+ if (node.type === "StringLiteral" || node.type === "NumericLiteral" || node.type === "BooleanLiteral") return {
5484
+ found: true,
5485
+ value: node.value
5486
+ };
5487
+ if (node.type === "Literal") {
5488
+ const value = node.value;
5489
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null ? {
5490
+ found: true,
5491
+ value
5492
+ } : { found: false };
5493
+ }
5494
+ if (node.type === "NullLiteral") return {
5495
+ found: true,
5496
+ value: null
5497
+ };
5498
+ if (isObjectExpression$1(node)) {
5499
+ const defaultProp = getObjectProperties(node).find((prop) => readPropertyKey(prop) === "default");
5500
+ return defaultProp?.value ? readStaticStyleValue(defaultProp.value) : { found: false };
5501
+ }
5502
+ return { found: false };
5503
+ }
5504
+ function readFunctionReturnedObject(node) {
5505
+ if (!isRecord(node)) return null;
5506
+ if (node.type !== "ArrowFunctionExpression" && node.type !== "FunctionExpression" && node.type !== "FunctionDeclaration") return null;
5507
+ const body = node.body;
5508
+ if (isObjectExpression$1(body)) return body;
5509
+ if (!isRecord(body) || body.type !== "BlockStatement") return null;
5510
+ const statements = Array.isArray(body.body) ? body.body : [];
5511
+ for (const statement of statements) if (isRecord(statement) && statement.type === "ReturnStatement" && isObjectExpression$1(statement.argument)) return statement.argument;
5512
+ return null;
5513
+ }
5514
+ function functionPropertiesWithNullConditionalDefault(node) {
5515
+ const returnedObject = readFunctionReturnedObject(node);
5516
+ if (!returnedObject) return [];
5517
+ const props = [];
5518
+ for (const property of getObjectProperties(returnedObject)) {
5519
+ const key = readPropertyKey(property);
5520
+ if (!key || !isObjectExpression$1(property.value)) continue;
5521
+ if (objectExpressionHasNullDefault(property.value)) props.push(key);
5522
+ }
5523
+ return props;
5524
+ }
5525
+ function setFunctionConditionalDefault(node, propName, value) {
5526
+ const returnedObject = readFunctionReturnedObject(node);
5527
+ if (!returnedObject) return;
5528
+ for (const property of getObjectProperties(returnedObject)) {
5529
+ if (readPropertyKey(property) !== propName || !isObjectExpression$1(property.value)) continue;
5530
+ setObjectExpressionDefault(property.value, value);
5531
+ }
5532
+ }
5533
+ function objectExpressionHasNullDefault(node) {
5534
+ return getObjectProperties(node).some((property) => {
5535
+ if (readPropertyKey(property) !== "default") return false;
5536
+ return isNullLiteral$1(property.value);
5537
+ });
5538
+ }
5539
+ function setObjectExpressionDefault(node, value) {
5540
+ for (const property of getObjectProperties(node)) if (readPropertyKey(property) === "default") property.value = staticStyleValueToAst(value);
5541
+ }
5542
+ function staticStyleValueToAst(value) {
5543
+ return value === null ? {
5544
+ type: "Literal",
5545
+ value: null
5546
+ } : {
5547
+ type: "Literal",
5548
+ value
5549
+ };
5550
+ }
5551
+ function findComponentFunction(ast, componentNames) {
5552
+ const names = new Set([...componentNames, ...defaultExportedIdentifierNames(ast)]);
5553
+ let found = null;
5554
+ walk(ast, (node) => {
5555
+ if (found) return;
5556
+ if (node.type === "ExportDefaultDeclaration") {
5557
+ const declaration = node.declaration;
5558
+ if (isFunctionLike$1(declaration)) {
5559
+ const declarationId = declaration.id;
5560
+ if (names.has("default") || isIdentifier(declarationId) && names.has(declarationId.name)) found = declaration;
5561
+ return;
5562
+ }
5563
+ if (isIdentifier(declaration)) names.add(declaration.name);
5564
+ return;
5565
+ }
5566
+ if (node.type === "FunctionDeclaration" && isIdentifier(node.id) && names.has(node.id.name)) {
5567
+ found = node;
5568
+ return;
5569
+ }
5570
+ if (node.type !== "VariableDeclarator" || !isIdentifier(node.id) || !names.has(node.id.name)) return;
5571
+ if (isFunctionLike$1(node.init)) found = node.init;
5572
+ });
5573
+ return found;
5574
+ }
5575
+ function defaultExportedIdentifierNames(ast) {
5576
+ const names = [];
5577
+ walk(ast, (node) => {
5578
+ if (node.type !== "ExportDefaultDeclaration") return;
5579
+ const declaration = node.declaration;
5580
+ if (isIdentifier(declaration)) names.push(declaration.name);
5581
+ });
5582
+ return names;
5583
+ }
5584
+ function collectSxBindings(component) {
5585
+ const localNames = new Set(["sx"]);
5586
+ const propsNames = /* @__PURE__ */ new Set();
5587
+ for (const param of getFunctionParams(component)) if (isIdentifier(param)) propsNames.add(param.name);
5588
+ else if (isObjectPattern(param)) collectObjectPatternBinding(param, "sx", localNames);
5589
+ walk(component.body, (node) => {
5590
+ if (node.type !== "VariableDeclarator" || !isObjectPattern(node.id) || !isIdentifier(node.init)) return;
5591
+ if (propsNames.has(node.init.name)) collectObjectPatternBinding(node.id, "sx", localNames);
5592
+ });
5593
+ return {
5594
+ localNames,
5595
+ propsNames
5596
+ };
5597
+ }
5598
+ function collectObjectPatternBinding(pattern, propName, out) {
5599
+ const properties = Array.isArray(pattern.properties) ? pattern.properties : [];
5600
+ for (const property of properties) {
5601
+ if (!isRecord(property) || property.type !== "Property") continue;
5602
+ if (readPropertyKey(property) !== propName) continue;
5603
+ const value = unwrapAssignmentPattern(property.value);
5604
+ if (isIdentifier(value)) out.add(value.name);
5605
+ }
5606
+ }
5607
+ function collectSxCompositionObservations(component, sxBindings, styleMaps, prop) {
5608
+ const observations = [];
5609
+ walkTopLevelComponentBody(component.body, (node) => {
5610
+ if (node.type === "CallExpression" && isStylexPropsCall(node)) {
5611
+ const beforeSx = argsBeforeSx(getCallArguments(node), sxBindings);
5612
+ if (beforeSx) observations.push(analyzeStyleSequence(beforeSx, styleMaps, prop));
5613
+ return;
5614
+ }
5615
+ if (node.type === "CallExpression" && isMergedSxCall(node)) {
5616
+ const firstArg = getCallArguments(node)[0];
5617
+ const beforeSx = argsBeforeSx(isArrayExpression(firstArg) ? getArrayElements(firstArg) : [], sxBindings);
5618
+ if (beforeSx) observations.push(analyzeStyleSequence(beforeSx, styleMaps, prop));
5619
+ return;
5620
+ }
5621
+ if (node.type === "JSXAttribute" && getJsxAttributeName(node) === "sx") {
5622
+ const expression = readJsxExpression(node.value);
5623
+ const beforeSx = argsBeforeSx(isArrayExpression(expression) ? getArrayElements(expression) : [expression], sxBindings);
5624
+ if (beforeSx) observations.push(analyzeStyleSequence(beforeSx, styleMaps, prop));
5625
+ }
5626
+ });
5627
+ return observations;
5628
+ }
5629
+ function walkTopLevelComponentBody(node, visit) {
5630
+ walk(node, (current) => {
5631
+ if (current !== node && isFunctionLike$1(current)) return "skip";
5632
+ visit(current);
5633
+ });
5634
+ }
5635
+ function argsBeforeSx(args, sxBindings) {
5636
+ const index = args.findIndex((arg) => isSxExpression(arg, sxBindings));
5637
+ return index === -1 ? null : args.slice(0, index);
5638
+ }
5639
+ function analyzeStyleSequence(styleArgs, styleMaps, prop) {
5640
+ let current = { kind: "absent" };
5641
+ for (const arg of styleArgs) {
5642
+ const next = analyzeStyleArg(arg, styleMaps, prop);
5643
+ if (next.kind === "absent") continue;
5644
+ if (next.kind === "unknown" || next.kind === "variable") return next;
5645
+ current = next;
5646
+ }
5647
+ return current;
5648
+ }
5649
+ function analyzeStyleArg(arg, styleMaps, prop) {
5650
+ const node = unwrapExpression(arg);
5651
+ if (!isRecord(node)) return { kind: "absent" };
5652
+ if (isNullishOrBooleanFalse(node)) return { kind: "absent" };
5653
+ const styleRef = readStyleReference(node);
5654
+ if (styleRef) return analyzeStyleReference(styleRef, styleMaps, prop, false);
5655
+ if (node.type === "LogicalExpression" && node.operator === "&&") {
5656
+ const right = analyzeStyleArg(node.right, styleMaps, prop);
5657
+ return right.kind === "absent" ? right : { kind: "variable" };
5658
+ }
5659
+ if (node.type === "ConditionalExpression") {
5660
+ const consequent = analyzeStyleArg(node.consequent, styleMaps, prop);
5661
+ const alternate = analyzeStyleArg(node.alternate, styleMaps, prop);
5662
+ return consequent.kind === "absent" && alternate.kind === "absent" ? { kind: "absent" } : { kind: "variable" };
5663
+ }
5664
+ if (isArrayExpression(node)) return analyzeStyleSequence(getArrayElements(node), styleMaps, prop);
5665
+ if (node.type === "CallExpression") {
5666
+ const callNode = node;
5667
+ const calleeRef = readStyleReference(callNode.callee);
5668
+ if (calleeRef) return analyzeStyleReference(calleeRef, styleMaps, prop, true);
5669
+ if (isStylexDefaultMarkerCall(callNode)) return { kind: "absent" };
5670
+ }
5671
+ return { kind: "unknown" };
5672
+ }
5673
+ function analyzeStyleReference(ref, styleMaps, prop, called) {
5674
+ const styleEntry = styleMaps.get(ref.objectName)?.get(ref.styleKey);
5675
+ if (!styleEntry) return { kind: "unknown" };
5676
+ if (styleEntry.kind === "function") return styleEntry.props.has(prop) ? { kind: "variable" } : { kind: "absent" };
5677
+ const value = styleEntry.props.get(prop);
5678
+ if (!value) return { kind: "absent" };
5679
+ if (called || value.kind === "dynamic") return { kind: "variable" };
5680
+ return {
5681
+ kind: "static",
5682
+ value: value.value
5683
+ };
5684
+ }
5685
+ function mergePropertyInferences(inferences) {
5686
+ let merged = { kind: "absent" };
5687
+ let sawAbsent = false;
5688
+ let sawStatic = false;
5689
+ for (const inference of inferences) {
5690
+ if (inference.kind === "unknown" || inference.kind === "variable") return inference;
5691
+ if (inference.kind === "absent") {
5692
+ if (sawStatic) return { kind: "variable" };
5693
+ sawAbsent = true;
5694
+ continue;
5695
+ }
5696
+ if (sawAbsent) return { kind: "variable" };
5697
+ if (merged.kind === "static" && merged.value !== inference.value) return { kind: "variable" };
5698
+ sawStatic = true;
5699
+ merged = inference;
5700
+ }
5701
+ return merged;
5702
+ }
5703
+ function isStylexCreateCall$1(node) {
5704
+ return isMemberCall(node, "stylex", "create");
5705
+ }
5706
+ function isStylexPropsCall(node) {
5707
+ return isMemberCall(node, "stylex", "props");
5708
+ }
5709
+ function isStylexDefaultMarkerCall(node) {
5710
+ return isMemberCall(node, "stylex", "defaultMarker");
5711
+ }
5712
+ function isMergedSxCall(node) {
5713
+ const callee = isRecord(node) ? node.callee : null;
5714
+ return isIdentifier(callee) && callee.name === "mergedSx";
5715
+ }
5716
+ function isMemberCall(node, objectName, propertyName) {
5717
+ if (!isRecord(node) || node.type !== "CallExpression") return false;
5718
+ const callee = node.callee;
5719
+ return isRecord(callee) && callee.type === "MemberExpression" && isIdentifier(callee.object) && callee.object.name === objectName && isIdentifier(callee.property) && callee.property.name === propertyName;
5720
+ }
5721
+ function readStyleReference(node) {
5722
+ const unwrapped = unwrapExpression(node);
5723
+ if (!isRecord(unwrapped) || unwrapped.type !== "MemberExpression" || unwrapped.computed === true) return null;
5724
+ if (!isIdentifier(unwrapped.object) || !isIdentifier(unwrapped.property)) return null;
5725
+ return {
5726
+ objectName: unwrapped.object.name,
5727
+ styleKey: unwrapped.property.name
5728
+ };
5729
+ }
5730
+ function isSxExpression(node, sxBindings) {
5731
+ const unwrapped = unwrapExpression(node);
5732
+ if (isIdentifier(unwrapped)) return sxBindings.localNames.has(unwrapped.name);
5733
+ return isRecord(unwrapped) && unwrapped.type === "MemberExpression" && isIdentifier(unwrapped.object) && sxBindings.propsNames.has(unwrapped.object.name) && isIdentifier(unwrapped.property) && unwrapped.property.name === "sx";
5734
+ }
5735
+ function unwrapExpression(node) {
5736
+ let current = node;
5737
+ while (isRecord(current) && (current.type === "TSAsExpression" || current.type === "TSTypeAssertion" || current.type === "ParenthesizedExpression")) current = current.expression;
5738
+ return current;
5739
+ }
5740
+ function unwrapAssignmentPattern(node) {
5741
+ return isRecord(node) && node.type === "AssignmentPattern" ? node.left : node;
5742
+ }
5743
+ function isNullishOrBooleanFalse(node) {
5744
+ return node.type === "NullLiteral" || node.type === "Identifier" && node.name === "undefined" || node.type === "BooleanLiteral" && node.value === false || node.type === "Literal" && (node.value === null || node.value === false);
5745
+ }
5746
+ function isNullLiteral$1(node) {
5747
+ return isRecord(node) && (node.type === "NullLiteral" || node.type === "Literal" && node.value === null);
5748
+ }
5749
+ function isFunctionLike$1(node) {
5750
+ return isRecord(node) && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression");
5751
+ }
5752
+ function isObjectPattern(node) {
5753
+ return isRecord(node) && node.type === "ObjectPattern";
5754
+ }
5755
+ function isObjectExpression$1(node) {
5756
+ return isRecord(node) && node.type === "ObjectExpression";
5757
+ }
5758
+ function isArrayExpression(node) {
5759
+ return isRecord(node) && node.type === "ArrayExpression";
5760
+ }
5761
+ function isIdentifier(node) {
5762
+ return isRecord(node) && node.type === "Identifier" && typeof node.name === "string";
5763
+ }
5764
+ function isRecord(value) {
5765
+ return !!value && typeof value === "object";
5766
+ }
5767
+ function getCallArguments(node) {
5768
+ return Array.isArray(node.arguments) ? node.arguments : [];
5769
+ }
5770
+ function getArrayElements(node) {
5771
+ return Array.isArray(node.elements) ? node.elements.filter((element) => element != null) : [];
5772
+ }
5773
+ function getObjectProperties(node) {
5774
+ return Array.isArray(node.properties) ? node.properties.filter(isRecord) : [];
5775
+ }
5776
+ function getFunctionParams(node) {
5777
+ return Array.isArray(node.params) ? node.params : [];
5778
+ }
5779
+ function readPropertyKey(property) {
5780
+ const key = property.key;
5781
+ if (isIdentifier(key)) return key.name;
5782
+ if (isRecord(key) && (key.type === "StringLiteral" || key.type === "Literal")) return typeof key.value === "string" ? key.value : null;
5783
+ return null;
5784
+ }
5785
+ function getJsxAttributeName(node) {
5786
+ const name = node.name;
5787
+ return isRecord(name) && name.type === "JSXIdentifier" && typeof name.name === "string" ? name.name : null;
5788
+ }
5789
+ function readJsxExpression(value) {
5790
+ return isRecord(value) && value.type === "JSXExpressionContainer" ? value.expression : value;
5791
+ }
5792
+ function walk(node, visit, seen = /* @__PURE__ */ new WeakSet()) {
5793
+ if (!isRecord(node)) return;
5794
+ if (seen.has(node)) return;
5795
+ seen.add(node);
5796
+ if (visit(node) === "skip") return;
5797
+ for (const [key, value] of Object.entries(node)) {
5798
+ if (key === "loc" || key === "comments" || key === "tokens") continue;
5799
+ if (Array.isArray(value)) for (const child of value) walk(child, visit, seen);
5800
+ else if (isRecord(value)) walk(value, visit, seen);
5801
+ }
5802
+ }
5803
+ //#endregion
4501
5804
  //#region src/internal/transform-steps/analyze-before-emit.ts
4502
5805
  const INLINE_USAGE_THRESHOLD = 1;
5806
+ const REACT_WINDOW_SOURCE = "react-window";
5807
+ const REACT_WINDOW_ELEMENT_TYPE_PROPS = new Set(["innerElementType", "outerElementType"]);
5808
+ const REACT_WINDOW_COMPONENT_EXPORTS = new Set([
5809
+ "FixedSizeGrid",
5810
+ "FixedSizeList",
5811
+ "Grid",
5812
+ "List",
5813
+ "VariableSizeGrid",
5814
+ "VariableSizeList"
5815
+ ]);
4503
5816
  /**
4504
5817
  * Analyzes declarations to determine wrappers, exports, usage patterns, and import aliasing before emit.
4505
5818
  */
@@ -4547,8 +5860,7 @@ function analyzeBeforeEmitStep(ctx) {
4547
5860
  if (decl.base.kind === "intrinsic" && (decl.attrsInfo?.conditionalAttrs?.length ?? 0) > 0) decl.needsWrapperComponent = true;
4548
5861
  if (decl.base.kind === "intrinsic" && (decl.attrsInfo?.defaultAttrs?.length ?? 0) > 0) decl.needsWrapperComponent = true;
4549
5862
  if (decl.base.kind === "intrinsic" && (decl.attrsInfo?.dynamicAttrs?.length ?? 0) > 0) decl.needsWrapperComponent = true;
4550
- const resolverOnlyShouldForwardProp = !!decl.inlinedBaseComponent && !decl.shouldForwardPropFromWithConfig;
4551
- if (decl.shouldForwardProp && !resolverOnlyShouldForwardProp) decl.needsWrapperComponent = true;
5863
+ if (needsShouldForwardPropWrapper(decl)) decl.needsWrapperComponent = true;
4552
5864
  if (decl.base.kind === "intrinsic" && decl.withConfig?.componentId) decl.needsWrapperComponent = true;
4553
5865
  if (extendedBy.has(decl.localName) && componentsWithStaticProps.has(decl.localName)) decl.needsWrapperComponent = true;
4554
5866
  if (exportedComponents.has(decl.localName)) decl.needsWrapperComponent = true;
@@ -4652,7 +5964,7 @@ function analyzeBeforeEmitStep(ctx) {
4652
5964
  const { className, style, ref } = getJsxAttributeUsage(targetDecl.localName);
4653
5965
  return targetDecl.base.kind === "intrinsic" && !targetDecl.isExported && !targetDecl.needsWrapperComponent && !className && !style && !ref && !hasSpreadInJsx(root, j, targetDecl.localName);
4654
5966
  };
4655
- const hasNonJsxComponentValueReference = (name) => root.find(j.Identifier, { name }).filter((p) => {
5967
+ const nonJsxComponentValueReferences = (name) => root.find(j.Identifier, { name }).filter((p) => {
4656
5968
  if (p.parentPath?.node?.type === "VariableDeclarator" && p.parentPath.node.id === p.node) return false;
4657
5969
  if (p.parentPath?.node?.type === "JSXOpeningElement" || p.parentPath?.node?.type === "JSXClosingElement") return false;
4658
5970
  if (p.parentPath?.node?.type === "JSXMemberExpression" && p.parentPath.node.object === p.node) return false;
@@ -4665,7 +5977,20 @@ function analyzeBeforeEmitStep(ctx) {
4665
5977
  if (p.parentPath?.node?.type === "CallExpression" && p.parentPath.parentPath?.node?.type === "TaggedTemplateExpression") return false;
4666
5978
  if (p.parentPath?.node?.type === "TemplateLiteral") return false;
4667
5979
  return true;
4668
- }).size() > 0;
5980
+ });
5981
+ const hasNonJsxComponentValueReference = (name) => nonJsxComponentValueReferences(name).size() > 0;
5982
+ const hasOnlyVirtualListElementTypeValueReferences = (name) => {
5983
+ const refs = nonJsxComponentValueReferences(name);
5984
+ if (refs.size() === 0) return false;
5985
+ let onlyVirtualListElementType = true;
5986
+ refs.forEach((p) => {
5987
+ const expressionContainer = p.parentPath?.node;
5988
+ const attr = p.parentPath?.parentPath?.node;
5989
+ const attrName = attr?.name;
5990
+ if (expressionContainer?.type !== "JSXExpressionContainer" || attr?.type !== "JSXAttribute" || attrName?.type !== "JSXIdentifier" || !REACT_WINDOW_ELEMENT_TYPE_PROPS.has(attrName.name) || !isKnownReactWindowElementTypeAttribute(p.parentPath?.parentPath, ctx.importMap)) onlyVirtualListElementType = false;
5991
+ });
5992
+ return onlyVirtualListElementType;
5993
+ };
4669
5994
  for (const decl of styledDecls) {
4670
5995
  if (!decl.adjacentSiblingStyleKey) continue;
4671
5996
  const { className, style, ref } = getJsxAttributeUsage(decl.localName);
@@ -4936,6 +6261,7 @@ function analyzeBeforeEmitStep(ctx) {
4936
6261
  if (decl.isDirectJsxResolution) continue;
4937
6262
  if (hasNonJsxComponentValueReference(decl.localName)) {
4938
6263
  decl.usedAsValue = true;
6264
+ if (hasOnlyVirtualListElementTypeValueReferences(decl.localName)) decl.valueUsageKind = "virtualListElementType";
4939
6265
  decl.needsWrapperComponent = true;
4940
6266
  }
4941
6267
  }
@@ -5032,7 +6358,7 @@ function analyzeBeforeEmitStep(ctx) {
5032
6358
  let cur = p.parentPath;
5033
6359
  while (cur) {
5034
6360
  const node = cur.node;
5035
- if (isFunctionNode(node) || node?.type === "MethodDefinition") return true;
6361
+ if (isFunctionNode$1(node) || node?.type === "MethodDefinition") return true;
5036
6362
  cur = cur.parentPath;
5037
6363
  }
5038
6364
  return false;
@@ -5069,6 +6395,22 @@ function analyzeBeforeEmitStep(ctx) {
5069
6395
  }
5070
6396
  else ctx.resolvedStyleObjects.set(entry.styleKey, entry.styleValue);
5071
6397
  }
6398
+ if (!validateSxRestrictedWrappedComponentStyles(ctx, styledDecls)) return returnResult({
6399
+ code: null,
6400
+ warnings: ctx.warnings
6401
+ }, "bail");
6402
+ if (!validateWrappedComponentStyleChannels(ctx, styledDecls)) return returnResult({
6403
+ code: null,
6404
+ warnings: ctx.warnings
6405
+ }, "bail");
6406
+ if (guardGeneratedConditionalDefaults(ctx, styledDecls) === "bail") return returnResult({
6407
+ code: null,
6408
+ warnings: ctx.warnings
6409
+ }, "bail");
6410
+ if (guardForwardedSxConditionalDefaults(ctx, styledDecls) === "bail") return returnResult({
6411
+ code: null,
6412
+ warnings: ctx.warnings
6413
+ }, "bail");
5072
6414
  const existingStylexTarget = findExistingStylexStylesTarget({
5073
6415
  ctx,
5074
6416
  styledDeclNames,
@@ -5682,6 +7024,7 @@ function renameStaticAttrKeys(attrs, renames) {
5682
7024
  */
5683
7025
  function collectAllStyleKeysForDecl(decl) {
5684
7026
  const keys = [decl.styleKey];
7027
+ if (decl.adjacentSiblingStyleKey) keys.push(decl.adjacentSiblingStyleKey);
5685
7028
  for (const key of Object.values(decl.variantStyleKeys ?? {})) keys.push(key);
5686
7029
  for (const sf of decl.styleFnFromProps ?? []) keys.push(sf.fnKey);
5687
7030
  for (const key of decl.extraStyleKeys ?? []) keys.push(key);
@@ -5692,7 +7035,21 @@ function collectAllStyleKeysForDecl(decl) {
5692
7035
  for (const c of decl.enumVariant.cases) keys.push(c.styleKey);
5693
7036
  }
5694
7037
  for (const sbv of decl.staticBooleanVariants ?? []) keys.push(sbv.styleKey);
7038
+ for (const cs of decl.callSiteCombinedStyles ?? []) keys.push(cs.styleKey);
7039
+ for (const ps of decl.promotedStyleProps ?? []) if (!ps.mergeIntoBase) keys.push(ps.styleKey);
5695
7040
  for (const pas of decl.pseudoAliasSelectors ?? []) keys.push(...pas.styleKeys);
7041
+ for (const pes of decl.pseudoExpandSelectors ?? []) keys.push(pes.styleKey);
7042
+ if (decl.attrWrapper) {
7043
+ const aw = decl.attrWrapper;
7044
+ for (const k of [
7045
+ aw.checkboxKey,
7046
+ aw.radioKey,
7047
+ aw.readonlyKey,
7048
+ aw.externalKey,
7049
+ aw.httpsKey,
7050
+ aw.pdfKey
7051
+ ]) if (k) keys.push(k);
7052
+ }
5696
7053
  return keys;
5697
7054
  }
5698
7055
  const AST_METADATA_KEYS = new Set([
@@ -6085,7 +7442,7 @@ function analyzePromotableStyleProps(root, j, styledDecls, allStyledDecls, declB
6085
7442
  siteBail = true;
6086
7443
  break;
6087
7444
  }
6088
- if (!isValidIdentifierName$1(keyName)) {
7445
+ if (!isValidIdentifierName(keyName)) {
6089
7446
  siteBail = true;
6090
7447
  break;
6091
7448
  }
@@ -6846,6 +8203,229 @@ function mergeAttrEntriesByAttrName(baseEntries, ownEntries) {
6846
8203
  for (const entry of ownEntries ?? []) byAttrName.set(entry.attrName, entry);
6847
8204
  return [...byAttrName.values()];
6848
8205
  }
8206
+ function validateSxRestrictedWrappedComponentStyles(ctx, styledDecls) {
8207
+ if (!ctx.adapter.useSxProp || !ctx.resolvedStyleObjects) return true;
8208
+ for (const decl of styledDecls) {
8209
+ if (decl.skipTransform || decl.base.kind !== "component") continue;
8210
+ const componentInterface = wrappedComponentInterfaceFor(ctx, decl.base.ident);
8211
+ const excludedProperties = componentInterface?.sxExcludedProperties;
8212
+ const allowedProperties = componentInterface?.sxAllowedProperties;
8213
+ const hasAllowedProperties = allowedProperties !== void 0;
8214
+ if (componentInterface?.acceptsSx !== true || !excludedProperties?.length && !hasAllowedProperties && !componentInterface.rootOnlyProperties?.length) continue;
8215
+ const excluded = new Set(excludedProperties ?? []);
8216
+ const allowed = hasAllowedProperties ? new Set(allowedProperties) : null;
8217
+ const rootOnly = componentInterface.sxTarget === "inner" && componentInterface.rootOnlyProperties?.length ? new Set(componentInterface.rootOnlyProperties) : null;
8218
+ for (const styleKey of collectAllStyleKeysForDecl(decl)) {
8219
+ const style = ctx.resolvedStyleObjects.get(styleKey);
8220
+ if (!style || typeof style !== "object") continue;
8221
+ const rootOnlyProperty = rootOnly ? findSxExcludedStyleProperty(style, rootOnly) : null;
8222
+ if (rootOnlyProperty) {
8223
+ ctx.warnings.push({
8224
+ severity: "error",
8225
+ type: "Wrapped component sx prop targets an inner element for a root style property",
8226
+ loc: decl.loc,
8227
+ context: {
8228
+ localName: decl.localName,
8229
+ wrappedComponent: decl.base.ident,
8230
+ styleKey,
8231
+ property: rootOnlyProperty
8232
+ }
8233
+ });
8234
+ return false;
8235
+ }
8236
+ const rejectedProperty = excluded.size > 0 ? findSxExcludedStyleProperty(style, excluded) : null;
8237
+ if (!rejectedProperty) {
8238
+ const disallowedProperty = allowed ? findSxDisallowedStyleProperty(style, allowed) : null;
8239
+ if (!disallowedProperty) continue;
8240
+ ctx.warnings.push({
8241
+ severity: "error",
8242
+ type: "Wrapped component sx prop does not accept generated StyleX property",
8243
+ loc: decl.loc,
8244
+ context: {
8245
+ localName: decl.localName,
8246
+ wrappedComponent: decl.base.ident,
8247
+ styleKey,
8248
+ property: disallowedProperty
8249
+ }
8250
+ });
8251
+ return false;
8252
+ }
8253
+ ctx.warnings.push({
8254
+ severity: "error",
8255
+ type: "Wrapped component sx prop rejects logical CSS properties that cannot be preserved losslessly",
8256
+ loc: decl.loc,
8257
+ context: {
8258
+ localName: decl.localName,
8259
+ wrappedComponent: decl.base.ident,
8260
+ styleKey,
8261
+ property: rejectedProperty
8262
+ }
8263
+ });
8264
+ return false;
8265
+ }
8266
+ }
8267
+ return true;
8268
+ }
8269
+ function validateWrappedComponentStyleChannels(ctx, styledDecls) {
8270
+ if (!ctx.resolvedStyleObjects) return true;
8271
+ for (const decl of styledDecls) {
8272
+ if (decl.skipTransform || decl.base.kind !== "component") continue;
8273
+ const baseIdent = decl.base.ident;
8274
+ if (styledDecls.some((candidate) => candidate.localName === baseIdent)) continue;
8275
+ const importInfo = ctx.importMap?.get(baseIdent);
8276
+ const isLocalNonStyledWrappedComponent = !importInfo && isLocalFunctionComponent(ctx.root, ctx.j, baseIdent);
8277
+ if (!importInfo && !isLocalNonStyledWrappedComponent) continue;
8278
+ if (importInfo?.source.kind === "absolutePath" && ctx.options.transformedFileSources?.has(resolveExistingFilePath(importInfo.source.value))) continue;
8279
+ if (!declHasEmittedStyle(ctx, decl)) continue;
8280
+ if (wrappedComponentInterfaceFor(ctx, baseIdent)?.acceptsSx === true) continue;
8281
+ const metadata = findWrappedComponentMetadata(ctx, baseIdent);
8282
+ if (!metadata || componentAcceptsStylexClassName(metadata)) continue;
8283
+ if (isLocalNonStyledWrappedComponent && !hasInlineObjectPropType(metadata)) continue;
8284
+ ctx.warnings.push({
8285
+ severity: "error",
8286
+ type: "Wrapped component does not accept className or sx for generated StyleX styles",
8287
+ loc: decl.loc,
8288
+ context: {
8289
+ localName: decl.localName,
8290
+ wrappedComponent: decl.base.ident
8291
+ }
8292
+ });
8293
+ return false;
8294
+ }
8295
+ return true;
8296
+ }
8297
+ function declHasEmittedStyle(ctx, decl) {
8298
+ for (const styleKey of collectAllStyleKeysForDecl(decl)) if (ctx.resolvedStyleObjects?.has(styleKey)) return true;
8299
+ return false;
8300
+ }
8301
+ function findWrappedComponentMetadata(ctx, componentLocalName) {
8302
+ const metadata = ctx.options.crossFileInfo?.typeScriptMetadata;
8303
+ const importInfo = ctx.importMap?.get(componentLocalName);
8304
+ if (importInfo?.source.kind === "absolutePath") return findTypeScriptComponentMetadata(metadata, importInfo.source.value, [importInfo.importedName, componentLocalName]);
8305
+ return findTypeScriptComponentMetadata(metadata, ctx.file.path, [componentLocalName]);
8306
+ }
8307
+ function componentAcceptsStylexClassName(metadata) {
8308
+ if (metadata.propType && isIntrinsicReactPropsTypeText(metadata.propType.text)) return true;
8309
+ if (metadata.hasIndexSignature) return true;
8310
+ if (metadata.explicitPropNames.includes("className")) return true;
8311
+ return metadata.props.some((prop) => prop.name === "className");
8312
+ }
8313
+ function isIntrinsicReactPropsTypeText(typeText) {
8314
+ return /^(?:[$A-Z_a-z][$\w]*\.)*ComponentProps(?:WithRef|WithoutRef)?\s*<\s*(['"])[^'"]+\1\s*>$/.test(typeText.trim());
8315
+ }
8316
+ function hasInlineObjectPropType(metadata) {
8317
+ return metadata.propType?.text.trim().startsWith("{") === true;
8318
+ }
8319
+ function findSxDisallowedStyleProperty(style, allowedProperties) {
8320
+ if (isAstNode(style)) return findSxDisallowedStylePropertyInAstNode(style, allowedProperties);
8321
+ for (const [key, value] of Object.entries(style)) {
8322
+ if (isStylexConditionKey(key)) {
8323
+ if (value && typeof value === "object") {
8324
+ const nested = findSxDisallowedStyleProperty(value, allowedProperties);
8325
+ if (nested) return nested;
8326
+ }
8327
+ continue;
8328
+ }
8329
+ if (!allowedProperties.has(key)) return key;
8330
+ }
8331
+ return null;
8332
+ }
8333
+ function staticObjectPropertyName(prop) {
8334
+ if (!prop || typeof prop !== "object") return null;
8335
+ const p = prop;
8336
+ if (p.type !== "Property" && p.type !== "ObjectProperty" || p.computed) return null;
8337
+ const key = p.key;
8338
+ if (!key) return null;
8339
+ if (key.type === "Identifier") return key.name ?? null;
8340
+ if (key.type === "Literal" || key.type === "StringLiteral") return typeof key.value === "string" ? key.value : null;
8341
+ return null;
8342
+ }
8343
+ function isKnownReactWindowElementTypeAttribute(attrPath, importMap) {
8344
+ const openingElement = attrPath?.parentPath?.node;
8345
+ if (openingElement?.type !== "JSXOpeningElement") return false;
8346
+ return jsxNameIsKnownReactWindowComponent(openingElement.name, importMap);
8347
+ }
8348
+ function jsxNameIsKnownReactWindowComponent(jsxName, importMap) {
8349
+ const name = jsxName;
8350
+ if (name.type === "JSXIdentifier") return localNameIsReactWindowComponent(name.name, importMap);
8351
+ if (name.type !== "JSXMemberExpression") return false;
8352
+ const namespace = name.object;
8353
+ const member = name.property;
8354
+ if (namespace?.type !== "JSXIdentifier" || member?.type !== "JSXIdentifier" || !REACT_WINDOW_COMPONENT_EXPORTS.has(member.name ?? "")) return false;
8355
+ const importInfo = namespace.name ? importMap?.get(namespace.name) : void 0;
8356
+ return importInfo?.source.value === REACT_WINDOW_SOURCE && importInfo.importedName === "*";
8357
+ }
8358
+ function localNameIsReactWindowComponent(localName, importMap) {
8359
+ if (!localName) return false;
8360
+ const importInfo = importMap?.get(localName);
8361
+ return importInfo?.source.value === REACT_WINDOW_SOURCE && REACT_WINDOW_COMPONENT_EXPORTS.has(importInfo.importedName);
8362
+ }
8363
+ function isStylexConditionKey(key) {
8364
+ return key === "default" || key === "__computedKeys" || key.startsWith(":") || key.startsWith("@") || key.startsWith("stylex.when");
8365
+ }
8366
+ function findSxExcludedStyleProperty(style, excludedProperties) {
8367
+ if (isAstNode(style)) return findSxExcludedStylePropertyInAstNode(style, excludedProperties);
8368
+ for (const [key, value] of Object.entries(style)) {
8369
+ if (excludedProperties.has(key)) return key;
8370
+ if (value && typeof value === "object") {
8371
+ const nested = findSxExcludedStyleProperty(value, excludedProperties);
8372
+ if (nested) return nested;
8373
+ }
8374
+ }
8375
+ return null;
8376
+ }
8377
+ function findSxExcludedStylePropertyInAstNode(node, excludedProperties) {
8378
+ const n = node;
8379
+ if (n.type === "ObjectExpression") {
8380
+ for (const prop of n.properties ?? []) {
8381
+ const name = staticObjectPropertyName(prop);
8382
+ if (name && excludedProperties.has(name)) return name;
8383
+ const value = prop.value;
8384
+ if (value && typeof value === "object") {
8385
+ const nested = findSxExcludedStylePropertyInAstNode(value, excludedProperties);
8386
+ if (nested) return nested;
8387
+ }
8388
+ }
8389
+ return null;
8390
+ }
8391
+ if (n.type === "ArrowFunctionExpression" && n.body && typeof n.body === "object") return findSxExcludedStylePropertyInAstNode(n.body, excludedProperties);
8392
+ if (n.type === "BlockStatement" && Array.isArray(n.body)) for (const statement of n.body ?? []) {
8393
+ const s = statement;
8394
+ if (s.type === "ReturnStatement" && s.argument && typeof s.argument === "object") {
8395
+ const nested = findSxExcludedStylePropertyInAstNode(s.argument, excludedProperties);
8396
+ if (nested) return nested;
8397
+ }
8398
+ }
8399
+ return null;
8400
+ }
8401
+ function findSxDisallowedStylePropertyInAstNode(node, allowedProperties) {
8402
+ const n = node;
8403
+ if (n.type === "ObjectExpression") {
8404
+ for (const prop of n.properties ?? []) {
8405
+ const name = staticObjectPropertyName(prop);
8406
+ const value = prop.value;
8407
+ if (!name) {
8408
+ if (value && typeof value === "object") {
8409
+ const nested = findSxDisallowedStylePropertyInAstNode(value, allowedProperties);
8410
+ if (nested) return nested;
8411
+ }
8412
+ continue;
8413
+ }
8414
+ if (isStylexConditionKey(name)) {
8415
+ if (value && typeof value === "object") {
8416
+ const nested = findSxDisallowedStylePropertyInAstNode(value, allowedProperties);
8417
+ if (nested) return nested;
8418
+ }
8419
+ continue;
8420
+ }
8421
+ if (!allowedProperties.has(name)) return name;
8422
+ }
8423
+ return null;
8424
+ }
8425
+ if (n.type === "ArrowFunctionExpression" && n.body && typeof n.body === "object") return findSxDisallowedStylePropertyInAstNode(n.body, allowedProperties);
8426
+ if (n.type === "ParenthesizedExpression" && n.expression && typeof n.expression === "object") return findSxDisallowedStylePropertyInAstNode(n.expression, allowedProperties);
8427
+ return null;
8428
+ }
6849
8429
  //#endregion
6850
8430
  //#region src/internal/policy.ts
6851
8431
  function collectCreateGlobalStyleWarnings(styledImports) {
@@ -8301,7 +9881,7 @@ function collectStaticPropsStep(ctx) {
8301
9881
  const styledNames = new Set(styledDecls.map((d) => d.localName));
8302
9882
  const baseComponentNames = /* @__PURE__ */ new Set();
8303
9883
  for (const decl of styledDecls) {
8304
- const baseIdent = decl.originalBaseIdent ?? (decl.base.kind === "component" ? decl.base.ident : null);
9884
+ const baseIdent = getEffectiveBaseIdent(decl);
8305
9885
  if (baseIdent && !styledNames.has(baseIdent)) baseComponentNames.add(baseIdent);
8306
9886
  }
8307
9887
  root.find(j.ExpressionStatement).filter((p) => {
@@ -8330,7 +9910,7 @@ function collectStaticPropsStep(ctx) {
8330
9910
  j(p).remove();
8331
9911
  });
8332
9912
  for (const decl of styledDecls) {
8333
- const baseIdent = decl.originalBaseIdent ?? (decl.base.kind === "component" ? decl.base.ident : null);
9913
+ const baseIdent = getEffectiveBaseIdent(decl);
8334
9914
  if (!baseIdent) continue;
8335
9915
  const baseComponentName = ctx.declByLocal.get(baseIdent)?.localName ?? baseIdent;
8336
9916
  const baseProps = staticPropertyNames.get(baseComponentName);
@@ -8345,7 +9925,7 @@ function collectStaticPropsStep(ctx) {
8345
9925
  if (inheritanceStatements.length > 0) staticPropertyAssignments.set(decl.localName, inheritanceStatements);
8346
9926
  }
8347
9927
  for (const decl of styledDecls) {
8348
- const baseIdent = decl.originalBaseIdent ?? (decl.base.kind === "component" ? decl.base.ident : null);
9928
+ const baseIdent = getEffectiveBaseIdent(decl);
8349
9929
  if (!baseIdent) continue;
8350
9930
  if (ctx.declByLocal.has(baseIdent)) continue;
8351
9931
  if (staticPropertyNames.has(baseIdent)) continue;
@@ -9432,10 +11012,12 @@ function getAttrsParamInfo(params) {
9432
11012
  };
9433
11013
  }
9434
11014
  function literalStaticValueFromNode(node) {
9435
- if (node?.type === "StringLiteral" || node?.type === "NumericLiteral") return node.value;
9436
- if (node?.type === "BooleanLiteral") return node.value;
9437
- if (node?.type === "Literal" && (typeof node.value === "string" || typeof node.value === "number" || typeof node.value === "boolean")) return node.value;
9438
- if (node?.type === "TSAsExpression" || node?.type === "TSSatisfiesExpression") return literalStaticValueFromNode(node.expression);
11015
+ if (!node || typeof node !== "object") return;
11016
+ const typed = node;
11017
+ if (typed.type === "StringLiteral" || typed.type === "NumericLiteral") return typeof typed.value === "string" || typeof typed.value === "number" ? typed.value : void 0;
11018
+ if (typed.type === "BooleanLiteral") return typeof typed.value === "boolean" ? typed.value : void 0;
11019
+ if (typed.type === "Literal" && (typeof typed.value === "string" || typeof typed.value === "number" || typeof typed.value === "boolean")) return typed.value;
11020
+ if (typed.type === "TSAsExpression" || typed.type === "TSSatisfiesExpression") return literalStaticValueFromNode(typed.expression);
9439
11021
  }
9440
11022
  function isStaticAttrExpression$1(node, attrsParamInfo) {
9441
11023
  if (!node || typeof node !== "object") return false;
@@ -9449,9 +11031,6 @@ function getStaticAttrExpressionRootName(node) {
9449
11031
  if (node.property?.type !== "Identifier" && node.property?.type !== "PrivateName") return null;
9450
11032
  return getStaticAttrExpressionRootName(node.object);
9451
11033
  }
9452
- function isValidIdentifierName(name) {
9453
- return /^[$A-Z_a-z][$\w]*$/.test(name);
9454
- }
9455
11034
  function staticAttrExpressionToReference(node, attrsParamInfo) {
9456
11035
  if (!isStaticAttrExpression$1(node, attrsParamInfo)) return null;
9457
11036
  if (node?.type === "TSAsExpression" || node?.type === "TSSatisfiesExpression") return staticAttrExpressionToReference(node.expression, attrsParamInfo);
@@ -9771,7 +11350,7 @@ function collectStyledDeclsStep(ctx) {
9771
11350
  if (unparseableSfpDecl && ctx.options.transformMode !== "leavesOnly") {
9772
11351
  ctx.warnings.push({
9773
11352
  severity: "warning",
9774
- type: "Unsupported shouldForwardProp pattern (only !prop.startsWith(), ![].includes(prop), and prop !== are supported)",
11353
+ type: UNSUPPORTED_SHOULD_FORWARD_PROP_WARNING,
9775
11354
  loc: unparseableSfpDecl.loc
9776
11355
  });
9777
11356
  return returnResult({
@@ -10979,7 +12558,7 @@ function evaluateStaticKeyframesExpression(expr, scopePath, seenIdentifiers = /*
10979
12558
  if (expr.operator === "+") return value;
10980
12559
  return null;
10981
12560
  }
10982
- if (expr.type === "BinaryExpression") return evaluateStaticBinaryExpression(expr, scopePath, seenIdentifiers);
12561
+ if (expr.type === "BinaryExpression") return evaluateStaticBinaryExpression$1(expr, scopePath, seenIdentifiers);
10983
12562
  if (expr.type === "LogicalExpression") {
10984
12563
  const left = evaluateStaticKeyframesExpression(expr.left, scopePath, seenIdentifiers);
10985
12564
  if (expr.operator === "&&") return left ? evaluateStaticKeyframesExpression(expr.right, scopePath) : left;
@@ -11009,7 +12588,7 @@ function evaluateStaticKeyframesExpression(expr, scopePath, seenIdentifiers = /*
11009
12588
  if (expr.type === "TSAsExpression" || expr.type === "TSTypeAssertion" || expr.type === "TSSatisfiesExpression") return evaluateStaticKeyframesExpression(expr.expression, scopePath, seenIdentifiers);
11010
12589
  return null;
11011
12590
  }
11012
- function evaluateStaticBinaryExpression(expr, scopePath, seenIdentifiers) {
12591
+ function evaluateStaticBinaryExpression$1(expr, scopePath, seenIdentifiers) {
11013
12592
  if (expr.type !== "BinaryExpression") return null;
11014
12593
  const left = evaluateStaticKeyframesExpression(expr.left, scopePath, seenIdentifiers);
11015
12594
  const right = evaluateStaticKeyframesExpression(expr.right, scopePath, seenIdentifiers);
@@ -11932,7 +13511,7 @@ function detectUnsupportedPatternsStep(ctx) {
11932
13511
  const parent = cur.parentPath.node;
11933
13512
  if (parent?.type === "VariableDeclarator" && parent.init === cur.node) return true;
11934
13513
  if (parent?.type === "AssignmentExpression" && parent.right === cur.node) return true;
11935
- if (isFunctionNode(parent)) break;
13514
+ if (isFunctionNode$1(parent)) break;
11936
13515
  cur = cur.parentPath;
11937
13516
  }
11938
13517
  return false;
@@ -11941,7 +13520,7 @@ function detectUnsupportedPatternsStep(ctx) {
11941
13520
  let cur = path;
11942
13521
  while (cur?.parentPath) {
11943
13522
  cur = cur.parentPath;
11944
- if (isFunctionNode(cur?.node)) return true;
13523
+ if (isFunctionNode$1(cur?.node)) return true;
11945
13524
  }
11946
13525
  return false;
11947
13526
  };
@@ -12767,7 +14346,7 @@ function resolveDirectJsxUsages(ctx, styledDecls) {
12767
14346
  for (const name of jsxComponentNames) {
12768
14347
  if (styledDeclNames.has(name)) continue;
12769
14348
  if (isUsedAsNonJsxValue(ctx, name)) continue;
12770
- if (hasSpreadInJsxForComponent(ctx, name)) continue;
14349
+ if (hasSpreadInJsx(ctx.root, ctx.j, name)) continue;
12771
14350
  const importInfo = importMap.get(name);
12772
14351
  if (!importInfo) continue;
12773
14352
  const importSourceStr = importSourceToString(importInfo.source);
@@ -12864,27 +14443,6 @@ function isUsedAsNonJsxValue(ctx, localName) {
12864
14443
  return true;
12865
14444
  }).size() > 0;
12866
14445
  }
12867
- /** Returns true if any JSX call site of `localName` has a spread attribute. */
12868
- function hasSpreadInJsxForComponent(ctx, localName) {
12869
- const { root, j } = ctx;
12870
- let found = false;
12871
- const checkAttrs = (attributes) => {
12872
- if (found) return;
12873
- for (const attr of attributes ?? []) if (attr.type === "JSXSpreadAttribute") {
12874
- found = true;
12875
- return;
12876
- }
12877
- };
12878
- root.find(j.JSXElement, { openingElement: { name: {
12879
- type: "JSXIdentifier",
12880
- name: localName
12881
- } } }).forEach((p) => checkAttrs(p.node.openingElement?.attributes));
12882
- root.find(j.JSXSelfClosingElement, { name: {
12883
- type: "JSXIdentifier",
12884
- name: localName
12885
- } }).forEach((p) => checkAttrs(p.node.attributes));
12886
- return found;
12887
- }
12888
14446
  /** Returns a styleKey that doesn't collide with existing keys. */
12889
14447
  function deduplicateStyleKey(base, usedKeys) {
12890
14448
  if (!usedKeys.has(base)) return base;
@@ -12921,7 +14479,7 @@ function applyLeavesOnlyPolicyStep(ctx) {
12921
14479
  decl.skipTransform = true;
12922
14480
  ctx.warnings.push({
12923
14481
  severity: "warning",
12924
- type: "Unsupported shouldForwardProp pattern (only !prop.startsWith(), ![].includes(prop), and prop !== are supported)",
14482
+ type: UNSUPPORTED_SHOULD_FORWARD_PROP_WARNING,
12925
14483
  loc: decl.loc
12926
14484
  });
12927
14485
  continue;
@@ -13460,7 +15018,7 @@ function emitStylesAndImports(ctx) {
13460
15018
  const kfDecl = j.variableDeclaration("const", [j.variableDeclarator(j.identifier(name), j.callExpression(j.memberExpression(j.identifier("stylex"), j.identifier("keyframes")), [objectToAst(j, frames)]))]);
13461
15019
  inlineKeyframeDecls.push(kfDecl);
13462
15020
  }
13463
- emitLocalDefineVarsSidecars(ctx);
15021
+ emitLocalDefineVarsSidecars(ctx, [...nonEmptyStyleEntries.map(([, value]) => value), ...styledDecls.flatMap((decl) => (decl.inlineStyleProps ?? []).flatMap((prop) => [prop.expr, ...prop.keyExpr ? [prop.keyExpr] : []]))]);
13464
15022
  const programBody = root.get().node.program.body;
13465
15023
  const insertNodes = [...inlineKeyframeDecls, ...stylesDecl ? [stylesDecl] : []];
13466
15024
  if (insertNodes.length > 0) if (stylesInsertPosition === "afterImports") {
@@ -13530,50 +15088,6 @@ function isFiniteNumericString(s) {
13530
15088
  const n = Number(s);
13531
15089
  return Number.isFinite(n) && String(n) === s;
13532
15090
  }
13533
- /** Mapping from CSS shorthand to the longhands that conflict with it */
13534
- const SHORTHAND_LONGHANDS = {
13535
- margin: {
13536
- physical: [
13537
- "marginTop",
13538
- "marginRight",
13539
- "marginBottom",
13540
- "marginLeft"
13541
- ],
13542
- logical: ["marginBlock", "marginInline"]
13543
- },
13544
- padding: {
13545
- physical: [
13546
- "paddingTop",
13547
- "paddingRight",
13548
- "paddingBottom",
13549
- "paddingLeft"
13550
- ],
13551
- logical: ["paddingBlock", "paddingInline"]
13552
- },
13553
- scrollMargin: {
13554
- physical: [
13555
- "scrollMarginTop",
13556
- "scrollMarginRight",
13557
- "scrollMarginBottom",
13558
- "scrollMarginLeft"
13559
- ],
13560
- logical: ["scrollMarginBlock", "scrollMarginInline"]
13561
- },
13562
- scrollPadding: {
13563
- physical: [
13564
- "scrollPaddingTop",
13565
- "scrollPaddingRight",
13566
- "scrollPaddingBottom",
13567
- "scrollPaddingLeft"
13568
- ],
13569
- logical: ["scrollPaddingBlock", "scrollPaddingInline"]
13570
- }
13571
- };
13572
- /**
13573
- * Mapping from logical longhands to their physical equivalents, derived from SHORTHAND_LONGHANDS.
13574
- * `marginBlock` → `["marginTop", "marginBottom"]`
13575
- */
13576
- const LOGICAL_TO_PHYSICAL = Object.fromEntries(Object.values(SHORTHAND_LONGHANDS).flatMap(({ physical, logical }) => [[logical[0], [physical[0], physical[2]]], [logical[1], [physical[1], physical[3]]]]));
13577
15091
  /** Type guard: value is a simple string or number (not a conditional object) */
13578
15092
  function isSimpleStyleValue(value) {
13579
15093
  return typeof value === "string" || typeof value === "number";
@@ -13790,9 +15304,9 @@ function tokenizeShorthandValue(value) {
13790
15304
  if (current.trim()) tokens.push(current.trim());
13791
15305
  return tokens;
13792
15306
  }
13793
- function emitLocalDefineVarsSidecars(ctx) {
15307
+ function emitLocalDefineVarsSidecars(ctx, emittedStyleValues) {
13794
15308
  const j = ctx.j;
13795
- const vars = [...ctx.localStylexVars?.values() ?? []].sort((a, b) => a.sourceOrder - b.sourceOrder);
15309
+ const vars = [...ctx.localStylexVars?.values() ?? []].filter((ref) => emittedStyleValues.some((value) => containsLocalStylexVarRef(value, ref))).sort((a, b) => a.sourceOrder - b.sourceOrder);
13796
15310
  if (vars.length === 0) return;
13797
15311
  ctx.sidecarFiles ??= [];
13798
15312
  const groups = groupLocalStylexVars(vars);
@@ -13803,6 +15317,25 @@ function emitLocalDefineVarsSidecars(ctx) {
13803
15317
  const specifiers = [...groups.keys()].map((groupName) => j.importSpecifier(j.identifier(groupName)));
13804
15318
  insertImportDeclarationNearStylex(ctx.root, j.importDeclaration(specifiers, j.literal(`./${vars[0]?.sidecarFileName ?? "vars.stylex"}`)));
13805
15319
  }
15320
+ function containsLocalStylexVarRef(value, ref) {
15321
+ if (!value || typeof value !== "object") return false;
15322
+ if (Array.isArray(value)) return value.some((item) => containsLocalStylexVarRef(item, ref));
15323
+ const record = value;
15324
+ if (record.type === "MemberExpression") {
15325
+ const object = record.object;
15326
+ const property = record.property;
15327
+ if (object?.type === "Identifier" && object.name === ref.groupName) {
15328
+ if (property?.type === "Identifier" && property.name === ref.keyName) return true;
15329
+ if (property?.type === "Literal" && property.value === ref.keyName) return true;
15330
+ if (property?.type === "StringLiteral" && property.value === ref.keyName) return true;
15331
+ }
15332
+ }
15333
+ for (const [key, child] of Object.entries(record)) {
15334
+ if (key === "loc" || key === "comments") continue;
15335
+ if (containsLocalStylexVarRef(child, ref)) return true;
15336
+ }
15337
+ return false;
15338
+ }
13806
15339
  function groupLocalStylexVars(vars) {
13807
15340
  const groups = /* @__PURE__ */ new Map();
13808
15341
  for (const ref of vars) {
@@ -13980,12 +15513,12 @@ function emitBridgeExportsStep(ctx) {
13980
15513
  function emitStyleMerging(args) {
13981
15514
  const { j, emitter, styleArgs: rawStyleArgs, classNameId, styleId, allowClassNameProp, allowStyleProp, allowSxProp, inlineStyleProps = [], staticStyleExpr, staticClassNameExpr, isIntrinsicElement = true, wrappedAcceptsSxProp = false, keepStylePropSeparate = false } = args;
13982
15515
  const { styleMerger, emptyStyleKeys, stylesIdentifier, ancestorSelectorParents, crossFileMarkers, parentsNeedingDefaultMarker, emitTypes } = emitter;
13983
- const styleArgs = filterEmptyStyleArgs({
15516
+ const styleArgs = mergeAdjacentComplementaryStyleExprs(j, filterEmptyStyleArgs({
13984
15517
  styleArgs: rawStyleArgs,
13985
15518
  emptyStyleKeys,
13986
15519
  stylesIdentifier,
13987
15520
  ancestorSelectorParents
13988
- });
15521
+ }));
13989
15522
  if (ancestorSelectorParents && ancestorSelectorParents.size > 0) {
13990
15523
  let needsDefaultMarker = false;
13991
15524
  const pendingMarkers = [];
@@ -15268,7 +16801,7 @@ function buildVariantDimensionLookups(j, args) {
15268
16801
  pushExpr(j.logicalExpression("??", lookup, defaultAccess), dim);
15269
16802
  } else {
15270
16803
  if (dim.defaultValue && dim.isOptional && propDefaults) propDefaults.set(dim.propName, dim.defaultValue);
15271
- const lookup = dim.fallbackFnKey ? buildFallbackExpr(dim, propId) : j.memberExpression(variantsId, propId, true);
16804
+ const lookup = dim.fallbackFnKey ? buildFallbackExpr(dim, propId) : j.memberExpression(variantsId, dim.forceKeyofLookupCast ? buildKeyofTypeofCast(j, propId, dim.variantObjectName) : propId, true);
15272
16805
  if (dim.isOptional && !dim.defaultValue) {
15273
16806
  const guard = j.binaryExpression("!=", j.identifier(dim.propName), j.literal(null));
15274
16807
  pushExpr(j.logicalExpression("&&", guard, lookup), dim);
@@ -15713,7 +17246,10 @@ var WrapperEmitter = class {
15713
17246
  * configure the hook.
15714
17247
  */
15715
17248
  wrappedComponentAcceptsSxProp(componentLocalName) {
15716
- if (!this.useSxProp) return false;
17249
+ return this.wrappedComponentInterfaceFor(componentLocalName)?.acceptsSx === true;
17250
+ }
17251
+ wrappedComponentInterfaceFor(componentLocalName) {
17252
+ if (!this.useSxProp) return;
15717
17253
  const importInfo = this.importMap.get(componentLocalName);
15718
17254
  if (importInfo) {
15719
17255
  const adapterResult = this.wrappedComponentInterface?.({
@@ -15722,18 +17258,22 @@ var WrapperEmitter = class {
15722
17258
  importedName: importInfo.importedName,
15723
17259
  filePath: this.filePath
15724
17260
  });
15725
- if (adapterResult !== void 0) return adapterResult.acceptsSx === true;
17261
+ if (adapterResult !== void 0) return adapterResult;
15726
17262
  }
15727
17263
  const typedComponent = this.typeScriptComponentMetadataFor(componentLocalName);
15728
17264
  if (typedComponent) {
15729
- if (typedComponent.supportsSxProp) return true;
15730
- if (!this.hasSourceOverrideFor(componentLocalName)) return false;
17265
+ if (typedComponent.supportsSxProp) return {
17266
+ acceptsSx: true,
17267
+ sxExcludedProperties: typedComponent.sxExcludedProperties,
17268
+ sxAllowedProperties: typedComponent.sxAllowedProperties
17269
+ };
17270
+ if (!this.hasSourceOverrideFor(componentLocalName)) return { acceptsSx: false };
15731
17271
  }
15732
17272
  return importInfo?.source.kind === "absolutePath" && transformedComponentAcceptsSx({
15733
17273
  absolutePath: importInfo.source.value,
15734
17274
  componentNames: importInfo.importedName === "default" ? [componentLocalName, importInfo.importedName] : [importInfo.importedName],
15735
17275
  sourceOverrides: this.sourceOverrides
15736
- });
17276
+ }) ? { acceptsSx: true } : void 0;
15737
17277
  }
15738
17278
  propsTypeNameFor(localName) {
15739
17279
  return `${localName}Props`;
@@ -15833,6 +17373,9 @@ var WrapperEmitter = class {
15833
17373
  isUsedAsValue(d) {
15834
17374
  return Boolean(d.usedAsValue) || this.isUsedAsValueInFile(d.localName);
15835
17375
  }
17376
+ isBroadValueUsage(d) {
17377
+ return this.isUsedAsValue(d) && d.valueUsageKind !== "virtualListElementType";
17378
+ }
15836
17379
  requiresRestForValueUsage(d) {
15837
17380
  return this.isUsedAsValueInFile(d.localName) || this.hasAliasedJsxSpreadUsage(d.localName);
15838
17381
  }
@@ -15867,18 +17410,20 @@ var WrapperEmitter = class {
15867
17410
  shouldAllowClassNameProp(d) {
15868
17411
  if (d.consumerUsesClassName ?? d.supportsExternalStyles) return true;
15869
17412
  if (d.consumerUsesSpread) return this.spreadMayContainProp(d, "className");
15870
- if (this.isUsedAsValue(d)) return true;
17413
+ if (this.isBroadValueUsage(d)) return true;
15871
17414
  const used = this.getUsedAttrs(d.localName);
15872
17415
  return used.has("*") || used.has("className");
15873
17416
  }
15874
17417
  shouldAllowStyleProp(d) {
15875
17418
  if (d.consumerUsesStyle ?? d.supportsExternalStyles) return true;
15876
17419
  if (d.consumerUsesSpread) return this.spreadMayContainProp(d, "style");
15877
- if (this.isUsedAsValue(d)) return true;
17420
+ if (d.valueUsageKind === "virtualListElementType") return true;
17421
+ if (this.isBroadValueUsage(d)) return true;
15878
17422
  const used = this.getUsedAttrs(d.localName);
15879
17423
  return used.has("*") || used.has("style");
15880
17424
  }
15881
17425
  shouldAllowSxProp(d) {
17426
+ if (d.valueUsageKind === "virtualListElementType") return (d.supportsExternalStyles ?? false) || d.typeScriptSupportsSxProp === true;
15882
17427
  return (d.supportsExternalStyles ?? false) || d.typeScriptSupportsSxProp === true || this.shouldAllowClassNameProp(d) || this.shouldAllowStyleProp(d);
15883
17428
  }
15884
17429
  typedComponentHasProp(componentLocalName, propName) {
@@ -15926,7 +17471,7 @@ var WrapperEmitter = class {
15926
17471
  }
15927
17472
  hasSourceOverrideFor(componentLocalName) {
15928
17473
  const importInfo = this.importMap.get(componentLocalName);
15929
- return importInfo?.source.kind === "absolutePath" && this.sourceOverrides?.has(toRealPath(importInfo.source.value)) === true;
17474
+ return importInfo?.source.kind === "absolutePath" && this.sourceOverrides?.has(resolveExistingFilePath(importInfo.source.value)) === true;
15930
17475
  }
15931
17476
  typeScriptComponentMetadataFor(componentLocalName) {
15932
17477
  const importInfo = this.importMap.get(componentLocalName);
@@ -16186,7 +17731,7 @@ var WrapperEmitter = class {
16186
17731
  emitted.push(stmt);
16187
17732
  return true;
16188
17733
  }
16189
- annotatePropsParam(propsId, localName, inlineTypeText) {
17734
+ annotatePropsParam(propsParam, localName, inlineTypeText) {
16190
17735
  const { j } = this;
16191
17736
  if (!this.emitTypes) return;
16192
17737
  if (inlineTypeText) {
@@ -16201,11 +17746,12 @@ var WrapperEmitter = class {
16201
17746
  ].join("\n"));
16202
17747
  }
16203
17748
  if (!typeNode) throw new Error(`Failed to parse inline props param type for ${localName} (${this.filePath}).`);
16204
- propsId.typeAnnotation = j.tsTypeAnnotation(typeNode);
16205
- } else propsId.typeAnnotation = j.tsTypeAnnotation(j.tsTypeReference(j.identifier(this.propsTypeNameFor(localName))));
17749
+ propsParam.typeAnnotation = j.tsTypeAnnotation(typeNode);
17750
+ } else propsParam.typeAnnotation = j.tsTypeAnnotation(j.tsTypeReference(j.identifier(this.propsTypeNameFor(localName))));
16206
17751
  }
16207
17752
  withChildren(innerTypeText) {
16208
17753
  const t = innerTypeText.trim();
17754
+ if (t === "{}") return "{ children?: React.ReactNode }";
16209
17755
  if (t.startsWith("React.PropsWithChildren<")) return t;
16210
17756
  if (/(?:^|&\s*)(?:React\.ComponentProps(?:WithRef)?<|(?:Omit|Pick|Partial|Required|Readonly|ReadonlyArray|NonNullable|Extract|Exclude)<\s*React\.ComponentProps(?:WithRef)?<)/.test(t)) return t;
16211
17757
  return `React.PropsWithChildren<${t}>`;
@@ -16428,7 +17974,7 @@ var WrapperEmitter = class {
16428
17974
  inferredIntrinsicPropsTypeText(args) {
16429
17975
  const { d, tagName, allowClassNameProp, allowStyleProp, allowSxProp, skipProps, includeRef, forceNarrow } = args;
16430
17976
  const used = this.getUsedAttrs(d.localName);
16431
- const needsBroadAttrs = used.has("*") || this.isUsedAsValue(d);
17977
+ const needsBroadAttrs = used.has("*") || this.isBroadValueUsage(d);
16432
17978
  const lines = [];
16433
17979
  const pickedAttrKeys = [];
16434
17980
  if (!needsBroadAttrs) {
@@ -16471,6 +18017,7 @@ var WrapperEmitter = class {
16471
18017
  const intrinsicBaseOmitted = [];
16472
18018
  if (!allowClassNameProp) intrinsicBaseOmitted.push("\"className\"");
16473
18019
  if (!allowStyleProp) intrinsicBaseOmitted.push("\"style\"");
18020
+ if (!allowSxProp) intrinsicBaseOmitted.push("\"sx\"");
16474
18021
  const intrinsicBaseMaybeOmitted = intrinsicBaseOmitted.length ? `Omit<${intrinsicBase}, ${intrinsicBaseOmitted.join(" | ")}>` : intrinsicBase;
16475
18022
  const pickExpr = pickedAttrKeys.length > 0 ? `Pick<${intrinsicBase}, ${pickedAttrKeys.map((k) => `"${k}"`).join(" | ")}>` : void 0;
16476
18023
  if (!needsBroadAttrs) {
@@ -16582,7 +18129,8 @@ var WrapperEmitter = class {
16582
18129
  }
16583
18130
  }
16584
18131
  const literal = lines.length > 0 ? `{ ${lines.join(", ")} }` : "{}";
16585
- const baseMaybeOmitted = omitted.length ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
18132
+ const omittedUnique = [...new Set(omitted)];
18133
+ const baseMaybeOmitted = omittedUnique.length ? `Omit<${base}, ${omittedUnique.join(" | ")}>` : base;
16586
18134
  return this.joinIntersection(literal !== "{}" ? literal : null, baseMaybeOmitted, ...renamedPropTypes);
16587
18135
  }
16588
18136
  isPropRequiredInPropsTypeLiteral(propsType, propName) {
@@ -16647,26 +18195,7 @@ var WrapperEmitter = class {
16647
18195
  for (const arg of styleArgs) if (arg?.type === "LogicalExpression" && arg.operator === "&&") collectCondIdentifiers(arg.left);
16648
18196
  const isVoidTag = VOID_TAGS.has(tagName);
16649
18197
  const allowForwardedAsProp = this.getUsedAttrs(localName).has("forwardedAs");
16650
- const propsParamId = j.identifier("props");
16651
18198
  const needsPolymorphicTypeParams = this.emitTypes && (allowAsProp || inlineTypeNeedsElementGeneric(inlineTypeText));
16652
- if (this.emitTypes) if (inlineTypeText) {
16653
- let typeNode = null;
16654
- try {
16655
- typeNode = j(`const x: ${inlineTypeText} = null`).get().node.program.body[0].declarations[0].id.typeAnnotation.typeAnnotation;
16656
- } catch (e) {
16657
- throw new Error([
16658
- `Failed to parse inline wrapper props type for ${localName} (${tagName}).`,
16659
- `Inline type: ${inlineTypeText}`,
16660
- `Error: ${e instanceof Error ? e.message : String(e)}`
16661
- ].join("\n"));
16662
- }
16663
- if (!typeNode) throw new Error(`Failed to parse inline wrapper props type for ${localName} (${tagName}).`);
16664
- propsParamId.typeAnnotation = j.tsTypeAnnotation(typeNode);
16665
- } else {
16666
- if (!propsTypeName) throw new Error(`Missing propsTypeName for ${localName} (${tagName}).`);
16667
- if (needsPolymorphicTypeParams) propsParamId.typeAnnotation = j(`const x: ${propsTypeName}<C> = null`).get().node.program.body[0].declarations[0].id.typeAnnotation;
16668
- else propsParamId.typeAnnotation = j.tsTypeAnnotation(j.tsTypeReference(j.identifier(propsTypeName)));
16669
- }
16670
18199
  const propsId = j.identifier("props");
16671
18200
  const patternProps = [];
16672
18201
  if (allowAsProp) patternProps.push(j.property.from({
@@ -16677,7 +18206,8 @@ var WrapperEmitter = class {
16677
18206
  }));
16678
18207
  if (allowForwardedAsProp) patternProps.push(this.patternProp("forwardedAs"));
16679
18208
  if (!isVoidTag) patternProps.push(this.patternProp("children"));
16680
- if (includeRefProp) patternProps.push(this.patternProp("ref"));
18209
+ const shouldForwardRefExplicitly = includeRefProp && !includeRest;
18210
+ if (shouldForwardRefExplicitly) patternProps.push(this.patternProp("ref"));
16681
18211
  if (allowClassNameProp) patternProps.push(this.patternProp("className"));
16682
18212
  if (allowStyleProp) patternProps.push(this.patternProp("style"));
16683
18213
  for (const name of expandedDestructureProps) if (name !== "children" && name !== "style" && name !== "className" && name !== "forwardedAs" && name !== "ref") {
@@ -16690,8 +18220,16 @@ var WrapperEmitter = class {
16690
18220
  let restId = includeRest ? j.identifier("rest") : null;
16691
18221
  if (includeRest && restId) patternProps.push(j.restElement(restId));
16692
18222
  const usePropsDirectlyForRest = includeRest && patternProps.length === 1 && patternProps[0]?.type === "RestElement";
16693
- const usePropsChildrenDirectly = this.isChildrenOnlyDestructurePattern(patternProps);
18223
+ const useChildrenParamDestructure = this.isChildrenOnlyDestructurePattern(patternProps);
16694
18224
  if (usePropsDirectlyForRest) restId = propsId;
18225
+ const propsParam = useChildrenParamDestructure ? this.buildChildrenOnlyParam(inlineTypeText ?? (propsTypeName ? `${propsTypeName}${needsPolymorphicTypeParams ? "<C>" : ""}` : void 0)) : j.identifier("props");
18226
+ if (!useChildrenParamDestructure) this.annotateMinimalWrapperParam(propsParam, {
18227
+ localName,
18228
+ tagName,
18229
+ inlineTypeText,
18230
+ propsTypeName,
18231
+ needsPolymorphicTypeParams
18232
+ });
16695
18233
  const classNameId = j.identifier("className");
16696
18234
  const styleId = j.identifier("style");
16697
18235
  const staticClassName = staticAttrs.className;
@@ -16726,7 +18264,7 @@ var WrapperEmitter = class {
16726
18264
  jsxAttrs.push(j.jsxAttribute(j.jsxIdentifier(cond.attrName), j.jsxExpressionContainer(j.conditionalExpression(j.identifier(cond.jsxProp), typeof literalValue === "boolean" ? j.booleanLiteral(literalValue) : j.literal(literalValue), j.identifier("undefined")))));
16727
18265
  }
16728
18266
  for (const inv of invertedBoolAttrs) jsxAttrs.push(j.jsxAttribute(j.jsxIdentifier(inv.attrName), j.jsxExpressionContainer(j.binaryExpression("!==", j.identifier(inv.jsxProp), j.booleanLiteral(true)))));
16729
- if (includeRefProp) jsxAttrs.push(j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(j.identifier("ref"))));
18267
+ if (shouldForwardRefExplicitly) jsxAttrs.push(j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(j.identifier("ref"))));
16730
18268
  if (includeRest && restId) jsxAttrs.push(j.jsxSpreadAttribute(restId));
16731
18269
  jsxAttrs.push(...buildDynamicAttrsFromProps(j, {
16732
18270
  dynamicAttrs,
@@ -16744,14 +18282,14 @@ var WrapperEmitter = class {
16744
18282
  if (merging.styleAttr) jsxAttrs.push(j.jsxAttribute(j.jsxIdentifier("style"), j.jsxExpressionContainer(merging.styleAttr)));
16745
18283
  const renderedJsxName = jsxNameFromString(j, allowAsProp ? "Component" : attrsAsTag ?? tagName);
16746
18284
  const openingEl = j.jsxOpeningElement(renderedJsxName, jsxAttrs, isVoidTag);
16747
- const childrenExpr = usePropsChildrenDirectly ? j.memberExpression(propsId, j.identifier("children")) : j.identifier("children");
18285
+ const childrenExpr = j.identifier("children");
16748
18286
  const jsx = j.jsxElement(openingEl, isVoidTag ? null : j.jsxClosingElement(renderedJsxName), isVoidTag ? [] : [j.jsxExpressionContainer(childrenExpr)]);
16749
18287
  const bodyStmts = [];
16750
- if (!usePropsDirectlyForRest && !usePropsChildrenDirectly) bodyStmts.push(j.variableDeclaration("const", [j.variableDeclarator(j.objectPattern(patternProps), propsId)]));
18288
+ if (!usePropsDirectlyForRest && !useChildrenParamDestructure) bodyStmts.push(j.variableDeclaration("const", [j.variableDeclarator(j.objectPattern(patternProps), propsId)]));
16751
18289
  if (merging.sxDecl) bodyStmts.push(merging.sxDecl);
16752
18290
  bodyStmts.push(j.returnStatement(jsx));
16753
18291
  const filteredBody = bodyStmts.filter((stmt) => stmt && stmt.type !== "EmptyStatement");
16754
- const fn = j.functionDeclaration(j.identifier(localName), [propsParamId], j.blockStatement(filteredBody));
18292
+ const fn = j.functionDeclaration(j.identifier(localName), [propsParam], j.blockStatement(filteredBody));
16755
18293
  if (needsPolymorphicTypeParams) fn.typeParameters = buildPolymorphicTypeParams(j, tagName);
16756
18294
  return [fn];
16757
18295
  }
@@ -16800,6 +18338,36 @@ var WrapperEmitter = class {
16800
18338
  buildWrapperFunction(args) {
16801
18339
  return buildWrapperFunction(this.j, args);
16802
18340
  }
18341
+ buildChildrenOnlyParam(typeText) {
18342
+ if (!this.emitTypes) return this.j.objectPattern([this.patternProp("children")]);
18343
+ if (!typeText) throw new Error("Missing props type for children-only wrapper parameter.");
18344
+ return this.j(`function _({ children }: ${typeText}) {}`).get().node.program.body[0].params[0];
18345
+ }
18346
+ annotateMinimalWrapperParam(propsParam, args) {
18347
+ const { localName, tagName, inlineTypeText, propsTypeName, needsPolymorphicTypeParams } = args;
18348
+ if (!this.emitTypes) return;
18349
+ if (inlineTypeText) {
18350
+ let typeNode = null;
18351
+ try {
18352
+ typeNode = this.j(`const x: ${inlineTypeText} = null`).get().node.program.body[0].declarations[0].id.typeAnnotation.typeAnnotation;
18353
+ } catch (e) {
18354
+ throw new Error([
18355
+ `Failed to parse inline wrapper props type for ${localName} (${tagName}).`,
18356
+ `Inline type: ${inlineTypeText}`,
18357
+ `Error: ${e instanceof Error ? e.message : String(e)}`
18358
+ ].join("\n"));
18359
+ }
18360
+ if (!typeNode) throw new Error(`Failed to parse inline wrapper props type for ${localName} (${tagName}).`);
18361
+ propsParam.typeAnnotation = this.j.tsTypeAnnotation(typeNode);
18362
+ return;
18363
+ }
18364
+ if (!propsTypeName) throw new Error(`Missing propsTypeName for ${localName} (${tagName}).`);
18365
+ if (needsPolymorphicTypeParams) {
18366
+ propsParam.typeAnnotation = this.j(`const x: ${propsTypeName}<C> = null`).get().node.program.body[0].declarations[0].id.typeAnnotation;
18367
+ return;
18368
+ }
18369
+ propsParam.typeAnnotation = this.j.tsTypeAnnotation(this.j.tsTypeReference(this.j.identifier(propsTypeName)));
18370
+ }
16803
18371
  buildDestructurePatternProps(args) {
16804
18372
  return buildDestructurePatternProps(this.j, this.patternProp, args);
16805
18373
  }
@@ -17163,7 +18731,7 @@ function emitComponentWrappers(emitter) {
17163
18731
  });
17164
18732
  if (varDecl.size() > 0) {
17165
18733
  const init = varDecl.get().node.init;
17166
- if (isFunctionNode(init)) return firstParamType(init);
18734
+ if (isFunctionNode$1(init)) return firstParamType(init);
17167
18735
  }
17168
18736
  return null;
17169
18737
  };
@@ -17427,6 +18995,9 @@ function emitComponentWrappers(emitter) {
17427
18995
  const namespaceBooleanProps = [];
17428
18996
  const styleOnlyConditionProps = /* @__PURE__ */ new Set();
17429
18997
  const styleFnValueProps = /* @__PURE__ */ new Set();
18998
+ const styleValueVariantProps = new Set(d.styleValueVariantProps ?? []);
18999
+ const observedExpressionConditionDropProps = new Set(d.observedExpressionConditionDropProps ?? []);
19000
+ for (const prop of styleValueVariantProps) styleFnValueProps.add(prop);
17430
19001
  const propsArgExprs = d.extraStylexPropsArgs ? emitter.buildExtraStylexPropsExprs({
17431
19002
  entries: d.extraStylexPropsArgs,
17432
19003
  destructureProps
@@ -17633,14 +19204,13 @@ function emitComponentWrappers(emitter) {
17633
19204
  const staticAttrsForJsx = attrsSxExpr ? omitStaticAttr(staticAttrs, "sx") : staticAttrs;
17634
19205
  const attrsStaticStyleExpr = attrsInfo?.attrsStaticStyleExpr;
17635
19206
  const needsSxVar = allowClassNameProp || allowStyleProp || wrappedAcceptsSx || !!d.inlineStyleProps?.length || !!attrsStaticStyleExpr || !!staticClassNameExpr;
17636
- const needsDestructure = destructureProps.length > 0 || needsSxVar || isPolymorphicComponentWrapper || defaultAttrs.length > 0 || dynamicAttrs.length > 0 || shouldLowerForwardedAs || (d.supportsRefProp ?? false);
19207
+ const needsDestructure = destructureProps.length > 0 || needsSxVar || isPolymorphicComponentWrapper || defaultAttrs.length > 0 || dynamicAttrs.length > 0 || shouldLowerForwardedAs;
17637
19208
  const includeChildren = !isPolymorphicComponentWrapper && emitter.hasJsxChildrenUsage(d.localName);
17638
19209
  if (needsDestructure) {
17639
19210
  const childrenId = j.identifier("children");
17640
19211
  const classNameId = j.identifier("className");
17641
19212
  const styleId = j.identifier("style");
17642
19213
  const sxId = j.identifier("sx");
17643
- const refId = j.identifier("ref");
17644
19214
  const restId = j.identifier("rest");
17645
19215
  const componentId = j.identifier("Component");
17646
19216
  const forwardedAsId = j.identifier("forwardedAs");
@@ -17661,7 +19231,6 @@ function emitComponentWrappers(emitter) {
17661
19231
  ...includeChildren ? [patternProp("children", childrenId)] : [],
17662
19232
  ...destructureStyle ? [patternProp("style", styleId)] : [],
17663
19233
  ...destructureSx ? [patternProp("sx", sxId)] : [],
17664
- ...d.supportsRefProp ?? false ? [patternProp("ref", refId)] : [],
17665
19234
  ...shouldLowerForwardedAs ? [patternProp("forwardedAs", forwardedAsId)] : []
17666
19235
  ],
17667
19236
  destructureProps: destructurePropsForPattern,
@@ -17702,7 +19271,6 @@ function emitComponentWrappers(emitter) {
17702
19271
  defaultAttrs,
17703
19272
  propExprFor: (prop) => j.identifier(prop)
17704
19273
  }));
17705
- if (d.supportsRefProp ?? false) openingAttrs.push(j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId)));
17706
19274
  const forwardedProps = /* @__PURE__ */ new Set();
17707
19275
  for (const attr of defaultAttrs) forwardedProps.add(attr.attrName);
17708
19276
  for (const attr of dynamicAttrs) forwardedProps.add(attr.attrName);
@@ -17730,6 +19298,7 @@ function emitComponentWrappers(emitter) {
17730
19298
  }
17731
19299
  const baseExplicitProps = baseComponentPropsType ? emitter.getExplicitPropNames(baseComponentPropsType) : null;
17732
19300
  for (const propName of destructureProps) if (propName && propName !== "children" && !propName.startsWith("$") && !renamedFromTransient.has(propName)) {
19301
+ if (observedExpressionConditionDropProps.has(propName) && !baseExplicitProps?.has(propName)) continue;
17733
19302
  if (styleOnlyConditionProps.has(propName)) {
17734
19303
  if (!baseExplicitProps || baseExplicitProps.has(propName)) pushForwardedProp(propName);
17735
19304
  continue;
@@ -18652,6 +20221,7 @@ function createEmitIntrinsicHelpers(env) {
18652
20221
  const omitted = [];
18653
20222
  if (!allowClassNameProp) omitted.push("\"className\"");
18654
20223
  if (!allowStyleProp) omitted.push("\"style\"");
20224
+ if (!allowSxProp) omitted.push("\"sx\"");
18655
20225
  const base = omitted.length > 0 ? `Omit<React.ComponentPropsWithRef<C>, ${omitted.join(" | ")}>` : "React.ComponentPropsWithRef<C>";
18656
20226
  const forwardedAsPart = includeForwardedAs ? ` & ${FORWARDED_AS_TYPE}` : "";
18657
20227
  const sxPropPart = allowSxProp ? `${SX_PROP_TYPE_TEXT}; ` : "";
@@ -18759,7 +20329,6 @@ function buildAttrWrapperBody(ctx, args) {
18759
20329
  const { d, tagName, allowClassNameProp, allowAsProp, includesForwardedAs, includeChildren, styleArgs, extraDestructureProps, extraBodyStatements, extraJsxAttrs, pseudoGuardProps } = args;
18760
20330
  const classNameId = j.identifier("className");
18761
20331
  const childrenId = j.identifier("children");
18762
- const refId = j.identifier("ref");
18763
20332
  const restId = j.identifier("rest");
18764
20333
  const forwardedAsId = j.identifier("forwardedAs");
18765
20334
  const componentId = j.identifier("Component");
@@ -18774,8 +20343,7 @@ function buildAttrWrapperBody(ctx, args) {
18774
20343
  ...includesForwardedAs ? [ctx.patternProp("forwardedAs", forwardedAsId)] : [],
18775
20344
  ...extraDestructureProps.map((name) => ctx.patternProp(name, j.identifier(name))),
18776
20345
  ...allowClassNameProp ? [ctx.patternProp("className", classNameId)] : [],
18777
- ...includeChildren ? [ctx.patternProp("children", childrenId)] : [],
18778
- ...d.supportsRefProp ?? false ? [ctx.patternProp("ref", refId)] : []
20346
+ ...includeChildren ? [ctx.patternProp("children", childrenId)] : []
18779
20347
  ];
18780
20348
  const patternProps = emitter.buildDestructurePatternProps({
18781
20349
  baseProps,
@@ -18791,10 +20359,8 @@ function buildAttrWrapperBody(ctx, args) {
18791
20359
  openingAttrs.push(j.jsxSpreadAttribute(sxId));
18792
20360
  openingAttrs.push(j.jsxAttribute(j.jsxIdentifier("className"), j.jsxExpressionContainer(j.callExpression(j.memberExpression(j.callExpression(j.memberExpression(j.arrayExpression([j.memberExpression(sxId, j.identifier("className")), classNameId]), j.identifier("filter")), [j.identifier("Boolean")]), j.identifier("join")), [j.literal(" ")]))));
18793
20361
  openingAttrs.push(...extraJsxAttrs);
18794
- if (d.supportsRefProp ?? false) openingAttrs.push(j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId)));
18795
20362
  openingAttrs.push(j.jsxSpreadAttribute(restId));
18796
20363
  } else {
18797
- if (d.supportsRefProp ?? false) openingAttrs.push(j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId)));
18798
20364
  openingAttrs.push(...extraJsxAttrs);
18799
20365
  openingAttrs.push(j.jsxSpreadAttribute(restId));
18800
20366
  openingAttrs.push(j.jsxSpreadAttribute(sxId));
@@ -18836,6 +20402,7 @@ function emitInputWrappers(ctx) {
18836
20402
  const omitted = [];
18837
20403
  if (!allowClassNameProp) omitted.push("\"className\"");
18838
20404
  if (!allowStyleProp) omitted.push("\"style\"");
20405
+ omitted.push("\"sx\"");
18839
20406
  return omitted.length > 0 ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
18840
20407
  })(), includesForwardedAs);
18841
20408
  emitPropsType({
@@ -18899,6 +20466,7 @@ function emitLinkWrappers(ctx) {
18899
20466
  const omitted = [];
18900
20467
  if (!allowClassNameProp) omitted.push("\"className\"");
18901
20468
  if (!allowStyleProp) omitted.push("\"style\"");
20469
+ omitted.push("\"sx\"");
18902
20470
  return omitted.length > 0 ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
18903
20471
  })()), includesForwardedAs);
18904
20472
  emitPropsType({
@@ -18980,7 +20548,7 @@ function emitEnumVariantWrappers(ctx) {
18980
20548
  const hasNeq = cases.some((c) => c.kind === "neq");
18981
20549
  const values = [...new Set(cases.map((c) => c.whenValue))].filter(Boolean);
18982
20550
  const union = hasNeq ? "string" : values.length > 0 ? values.map((v) => JSON.stringify(v)).join(" | ") : "string";
18983
- const typeText = emitter.withChildren(`React.HTMLAttributes<HTMLDivElement> & { ${propName}?: ${union} }`);
20551
+ const typeText = emitter.withChildren(`Omit<React.HTMLAttributes<HTMLDivElement>, "sx"> & { ${propName}?: ${union} }`);
18984
20552
  emitPropsType({
18985
20553
  localName: d.localName,
18986
20554
  tagName,
@@ -19111,6 +20679,7 @@ function emitIntrinsicPolymorphicWrappers(ctx) {
19111
20679
  const omitted = [];
19112
20680
  if (!allowClassNameProp) omitted.push("\"className\"");
19113
20681
  if (!allowStyleProp) omitted.push("\"style\"");
20682
+ if (!allowSxProp) omitted.push("\"sx\"");
19114
20683
  if (explicit) {
19115
20684
  const keyofExpr = emitter.keyofExprForType(d.propsType, explicit);
19116
20685
  if (keyofExpr) omitted.push(keyofExpr);
@@ -19271,10 +20840,10 @@ function emitShouldForwardPropWrappers(ctx) {
19271
20840
  const dropPrefixFromFilter = d.shouldForwardProp?.dropPrefix;
19272
20841
  const usedAttrs = emitter.getUsedAttrs(d.localName);
19273
20842
  const shouldAllowAnyPrefixProps = !!dropPrefixFromFilter && (usedAttrs.has("*") || [...usedAttrs].some((n) => n.startsWith(dropPrefixFromFilter) && !extraProps.has(n)));
19274
- const knownPrefixProps = dropPrefixFromFilter ? [...extraProps].filter((p) => p.startsWith(dropPrefixFromFilter) && isValidIdentifierName$1(p)) : [];
20843
+ const knownPrefixProps = dropPrefixFromFilter ? [...extraProps].filter((p) => p.startsWith(dropPrefixFromFilter) && isValidIdentifierName(p)) : [];
19275
20844
  const knownPrefixPropsSet = new Set(knownPrefixProps);
19276
20845
  const isExportedComponent = d.isExported ?? false;
19277
- const useSlimType = !isExportedComponent && !(d.supportsExternalStyles ?? false) && !d.usedAsValue;
20846
+ const useSlimType = !isExportedComponent && !(d.supportsExternalStyles ?? false) && !emitter.isBroadValueUsage(d);
19278
20847
  const explicit = emitter.stringifyTsType(d.propsType);
19279
20848
  const explicitPropNames = d.propsType ? emitter.getExplicitPropNames(d.propsType) : /* @__PURE__ */ new Set();
19280
20849
  const skipProps = new Set([...explicitPropNames, ...extraProps]);
@@ -19314,6 +20883,7 @@ function emitShouldForwardPropWrappers(ctx) {
19314
20883
  const omitted = [];
19315
20884
  if (!allowClassNameProp) omitted.push("\"className\"");
19316
20885
  if (!allowStyleProp) omitted.push("\"style\"");
20886
+ if (!allowSxProp) omitted.push("\"sx\"");
19317
20887
  const baseWithOmit = omitted.length ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
19318
20888
  return emitter.joinIntersection(extrasTypeText, consumedPropsTypeText, baseWithOmit);
19319
20889
  }
@@ -19354,6 +20924,7 @@ function emitShouldForwardPropWrappers(ctx) {
19354
20924
  const omitted = [];
19355
20925
  if (!allowClassNameProp) omitted.push("\"className\"");
19356
20926
  if (!allowStyleProp) omitted.push("\"style\"");
20927
+ if (!allowSxProp) omitted.push("\"sx\"");
19357
20928
  return omitted.length ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
19358
20929
  })();
19359
20930
  if (explicitIsExistingTypeRef) if (useSlimType) sfpInlineTypeText = finalTypeTextWithForwardedAs;
@@ -19491,6 +21062,7 @@ function emitShouldForwardPropWrappers(ctx) {
19491
21062
  });
19492
21063
  const shouldOmitRestSpread = !isExportedComponent && !dropPrefix && dropProps.length > 0 && dropProps.every((p) => p.startsWith("$")) && !usedAttrs.has("*") && [...usedAttrs].every((n) => n === "children" || dropProps.includes(n));
19493
21064
  const includeRest = d.shouldForwardPropFromWithConfig || d.variantDimensions?.some((dim) => dim.namespaceBooleanProp) || isExportedComponent || (d.supportsExternalStyles ?? false) || !shouldOmitRestSpread && shouldIncludeRest;
21065
+ const shouldForwardRefExplicitly = (d.supportsRefProp ?? false) && !includeRest;
19494
21066
  const isVoid = VOID_TAGS.has(tagName);
19495
21067
  const includeChildren = allowAsProp || !isVoid;
19496
21068
  const sxId = j.identifier("sx");
@@ -19503,7 +21075,7 @@ function emitShouldForwardPropWrappers(ctx) {
19503
21075
  ...allowClassNameProp ? [ctx.patternProp("className", classNameId)] : [],
19504
21076
  ...includeChildren ? [ctx.patternProp("children", childrenId)] : [],
19505
21077
  ...allowStyleProp ? [ctx.patternProp("style", styleId)] : [],
19506
- ...d.supportsRefProp ?? false ? [ctx.patternProp("ref", refId)] : [],
21078
+ ...shouldForwardRefExplicitly ? [ctx.patternProp("ref", refId)] : [],
19507
21079
  ...allowSxProp ? [ctx.patternProp("sx", sxId)] : []
19508
21080
  ],
19509
21081
  destructureProps: destructurePartsForPattern,
@@ -19543,7 +21115,7 @@ function emitShouldForwardPropWrappers(ctx) {
19543
21115
  attrsInfo: attrsInfoForJsx,
19544
21116
  propExprFor: (prop) => j.identifier(prop)
19545
21117
  }) : [],
19546
- ...d.supportsRefProp ?? false ? [j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId))] : [],
21118
+ ...shouldForwardRefExplicitly ? [j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId))] : [],
19547
21119
  ...includeRest ? [j.jsxSpreadAttribute(restId)] : [],
19548
21120
  ...emitter.buildDynamicAttrsFromProps({
19549
21121
  dynamicAttrs: attrsInfoForJsx?.dynamicAttrs ?? [],
@@ -19604,7 +21176,7 @@ function buildExtraPropTypeLines(d, extraProps, skip) {
19604
21176
  const staticVariantPropTypes = buildStaticVariantPropTypes(d);
19605
21177
  const lines = [];
19606
21178
  for (const p of extraProps) {
19607
- if (!isValidIdentifierName$1(p) || skip?.(p)) continue;
21179
+ if (!isValidIdentifierName(p) || skip?.(p)) continue;
19608
21180
  const variantType = variantDimByProp.get(p);
19609
21181
  if (variantType) {
19610
21182
  lines.push(` ${p}?: ${variantType};`);
@@ -19644,7 +21216,7 @@ function emitSimpleWithConfigWrappers(ctx) {
19644
21216
  const allowStyleProp = emitter.shouldAllowStyleProp(d);
19645
21217
  const allowSxProp = emitter.shouldAllowSxProp(d);
19646
21218
  const allowAsProp = shouldAllowAsProp(d, tagName);
19647
- const useSlimType = !(d.isExported ?? false) && !supportsExternalStyles && !d.usedAsValue;
21219
+ const useSlimType = !(d.isExported ?? false) && !supportsExternalStyles && !emitter.isBroadValueUsage(d);
19648
21220
  const willForwardRef = (d.supportsRefProp ?? false) || allowClassNameProp || allowStyleProp || (() => {
19649
21221
  const used = emitter.getUsedAttrs(d.localName);
19650
21222
  return used.has("*") || !!d.usedAsValue || (d.isExported ?? false) || used.size > 0 || hasElementPropsInDefaultAttrs(d);
@@ -19655,7 +21227,7 @@ function emitSimpleWithConfigWrappers(ctx) {
19655
21227
  if (d.consumerUsesSpread === true || d.consumerUsesElementProps === true || d.consumerUsesSpread === void 0 && d.consumerUsesElementProps === void 0 && supportsExternalStyles) return true;
19656
21228
  if (allowClassNameProp || allowStyleProp || allowSxProp) return true;
19657
21229
  const used = emitter.getUsedAttrs(d.localName);
19658
- if (used.has("*")) return true;
21230
+ if (used.has("*") || d.valueUsageKind === "virtualListElementType") return true;
19659
21231
  return used.size > 0;
19660
21232
  })();
19661
21233
  const baseTypeText = shouldUseIntrinsicProps ? emitter.inferredIntrinsicPropsTypeText({
@@ -19710,12 +21282,11 @@ function emitSimpleWithConfigWrappers(ctx) {
19710
21282
  const classNameId = j.identifier("className");
19711
21283
  const childrenId = j.identifier("children");
19712
21284
  const styleId = j.identifier("style");
19713
- const refId = j.identifier("ref");
19714
21285
  const restId = j.identifier("rest");
19715
21286
  const isVoidTag = VOID_TAGS.has(tagName);
19716
21287
  if (!allowClassNameProp && !allowStyleProp && !needsUseThemeWithConfig) {
19717
21288
  const usedAttrs = emitter.getUsedAttrs(d.localName);
19718
- const includeRest = usedAttrs.has("*") || !!d.usedAsValue || (d.isExported ?? false) || usedAttrs.size > 0 || hasElementPropsInDefaultAttrs(d);
21289
+ const includeRest = usedAttrs.has("*") || emitter.isBroadValueUsage(d) || (d.isExported ?? false) || usedAttrs.size > 0 || hasElementPropsInDefaultAttrs(d);
19719
21290
  const variantProps = /* @__PURE__ */ new Set();
19720
21291
  if (d.variantStyleKeys) for (const [when] of Object.entries(d.variantStyleKeys)) {
19721
21292
  const { props } = emitter.collectConditionProps({ when });
@@ -19777,7 +21348,6 @@ function emitSimpleWithConfigWrappers(ctx) {
19777
21348
  emitter.patternProp("className", classNameId),
19778
21349
  ...isVoidTag ? [] : [emitter.patternProp("children", childrenId)],
19779
21350
  emitter.patternProp("style", styleId),
19780
- ...d.supportsRefProp ?? false ? [emitter.patternProp("ref", refId)] : [],
19781
21351
  ...allowSxProp ? [emitter.patternProp("sx", sxId)] : []
19782
21352
  ],
19783
21353
  destructureProps: [...pseudoGuardProps],
@@ -19805,7 +21375,6 @@ function emitSimpleWithConfigWrappers(ctx) {
19805
21375
  attrsInfo,
19806
21376
  propExprFor: (prop) => j.identifier(prop)
19807
21377
  }),
19808
- ...d.supportsRefProp ?? false ? [j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId))] : [],
19809
21378
  j.jsxSpreadAttribute(restId),
19810
21379
  ...emitter.buildDynamicAttrsFromProps({
19811
21380
  dynamicAttrs: attrsInfo?.dynamicAttrs ?? [],
@@ -19865,8 +21434,8 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
19865
21434
  let inlineTypeText;
19866
21435
  const isExportedComponent = d.isExported ?? false;
19867
21436
  const usePolymorphicPattern = allowAsProp && isExportedComponent;
19868
- const willForwardRef = (d.supportsRefProp ?? false) || isExportedComponent || hasComplementaryVariantPairs(d) || !!d.variantDimensions?.some((dim) => dim.namespaceBooleanProp);
19869
- const useSlimType = !isExportedComponent && !(d.supportsExternalStyles ?? false) && !d.usedAsValue && !hasElementPropsInDefaultAttrs(d);
21437
+ const willForwardRef = (d.supportsRefProp ?? false) || isExportedComponent || d.valueUsageKind === "virtualListElementType" || hasComplementaryVariantPairs(d) || !!d.variantDimensions?.some((dim) => dim.namespaceBooleanProp);
21438
+ const useSlimType = !isExportedComponent && !(d.supportsExternalStyles ?? false) && !emitter.isBroadValueUsage(d) && !hasElementPropsInDefaultAttrs(d);
19870
21439
  {
19871
21440
  const explicit = emitter.stringifyTsType(d.propsType);
19872
21441
  const explicitPropNames = d.propsType ? emitter.getExplicitPropNames(d.propsType) : /* @__PURE__ */ new Set();
@@ -19904,7 +21473,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
19904
21473
  forceNarrow: useSlimType
19905
21474
  });
19906
21475
  const supportsExternalStyles = d.supportsExternalStyles ?? false;
19907
- const needsRestForType = !!d.usedAsValue || usedAttrsForType.has("*") || d.consumerUsesSpread === true || d.consumerUsesElementProps === true || d.consumerUsesSpread === void 0 && d.consumerUsesElementProps === void 0 && supportsExternalStyles || hasElementPropsInDefaultAttrs(d) || [...usedAttrsForType].some((n) => {
21476
+ const needsRestForType = emitter.isBroadValueUsage(d) || usedAttrsForType.has("*") || d.consumerUsesSpread === true || d.consumerUsesElementProps === true || d.consumerUsesSpread === void 0 && d.consumerUsesElementProps === void 0 && supportsExternalStyles || hasElementPropsInDefaultAttrs(d) || [...usedAttrsForType].some((n) => {
19908
21477
  if (n === "children" || n === "className" || n === "style" || n === "as" || n === "forwardedAs" || n.startsWith("$")) return false;
19909
21478
  return !handledProps.has(n);
19910
21479
  });
@@ -19913,6 +21482,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
19913
21482
  const omitted = [];
19914
21483
  if (!allowClassNameProp) omitted.push("\"className\"");
19915
21484
  if (!allowStyleProp) omitted.push("\"style\"");
21485
+ if (!allowSxProp) omitted.push("\"sx\"");
19916
21486
  return omitted.length ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
19917
21487
  })();
19918
21488
  const customStyleDrivingPropsTypeText = (() => {
@@ -19928,7 +21498,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
19928
21498
  const compoundVariantWhenKeys = collectCompoundVariantKeys(d.compoundVariants, { syntheticOnly: true });
19929
21499
  for (const k of compoundVariantWhenKeys) keys.delete(k);
19930
21500
  const variantDimByProp = buildVariantDimPropTypeMap(d);
19931
- const filtered = [...keys].filter((k) => k && isValidIdentifierName$1(k) && k !== "children" && k !== "className" && k !== "style" && k !== "as" && k !== "forwardedAs" && (!explicitPropNames.has(k) || variantDimByProp.has(k) && !d.typeScriptPropTypes?.has(k)));
21501
+ const filtered = [...keys].filter((k) => k && isValidIdentifierName(k) && k !== "children" && k !== "className" && k !== "style" && k !== "as" && k !== "forwardedAs" && (!explicitPropNames.has(k) || variantDimByProp.has(k) && !d.typeScriptPropTypes?.has(k)));
19932
21502
  if (filtered.length === 0) return "{}";
19933
21503
  const staticVariantPropTypes = buildStaticVariantPropTypes(d);
19934
21504
  return `{\n${filtered.map((k) => {
@@ -19945,7 +21515,8 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
19945
21515
  propsType: d.propsType,
19946
21516
  typeText: explicit,
19947
21517
  allowClassNameProp,
19948
- allowStyleProp
21518
+ allowStyleProp,
21519
+ allowSxProp
19949
21520
  }) : void 0;
19950
21521
  const explicitTypeIncludesIntrinsicProps = !!d.propsType && explicitTypeMayContainExternalStyleProps({
19951
21522
  ctx,
@@ -20097,8 +21668,6 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20097
21668
  if (useAsProp || allowClassNameProp || allowStyleProp || needsUseTheme) {
20098
21669
  const isVoidTag = VOID_TAGS.has(tagName);
20099
21670
  const includeChildren = useAsProp || !isVoidTag;
20100
- const propsParamId = j.identifier("props");
20101
- emitter.annotatePropsParam(propsParamId, d.localName, inlineTypeText);
20102
21671
  const propsId = j.identifier("props");
20103
21672
  const componentId = j.identifier("Component");
20104
21673
  const classNameId = j.identifier("className");
@@ -20107,6 +21676,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20107
21676
  const sxId = j.identifier("sx");
20108
21677
  const refId = j.identifier("ref");
20109
21678
  const restId = shouldIncludeRest ? j.identifier("rest") : null;
21679
+ const shouldForwardRefExplicitly = !restId && ((d.supportsRefProp ?? false) || willForwardRef);
20110
21680
  const forwardedAsId = j.identifier("forwardedAs");
20111
21681
  if (allowSxProp) styleArgs.push(sxId);
20112
21682
  for (const attr of d.attrsInfo?.defaultAttrs ?? []) if (!destructureProps.includes(attr.jsxProp)) destructureProps.push(attr.jsxProp);
@@ -20124,7 +21694,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20124
21694
  ...allowClassNameProp ? [ctx.patternProp("className", classNameId)] : [],
20125
21695
  ...includeChildren ? [ctx.patternProp("children", childrenId)] : [],
20126
21696
  ...allowStyleProp ? [ctx.patternProp("style", styleId)] : [],
20127
- ...(d.supportsRefProp ?? false) || !restId && willForwardRef ? [ctx.patternProp("ref", refId)] : [],
21697
+ ...shouldForwardRefExplicitly ? [ctx.patternProp("ref", refId)] : [],
20128
21698
  ...allowSxProp ? [ctx.patternProp("sx", sxId)] : []
20129
21699
  ],
20130
21700
  destructureProps: destructurePropsForPattern,
@@ -20133,6 +21703,8 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20133
21703
  restId: restId ?? void 0
20134
21704
  });
20135
21705
  const usePropsChildrenDirectly = emitter.isChildrenOnlyDestructurePattern(patternProps);
21706
+ const propsParam = usePropsChildrenDirectly ? emitter.buildChildrenOnlyParam(inlineTypeText ?? emitter.propsTypeNameFor(d.localName)) : j.identifier("props");
21707
+ if (!usePropsChildrenDirectly) emitter.annotatePropsParam(propsParam, d.localName, inlineTypeText);
20136
21708
  const declStmt = usePropsChildrenDirectly ? null : j.variableDeclaration("const", [j.variableDeclarator(j.objectPattern(patternProps), propsId)]);
20137
21709
  const { attrsInfo, staticClassNameExpr } = emitter.splitAttrsInfo(d.attrsInfo, getBridgeClassVar(d), d.extraClassNames);
20138
21710
  const { attrsInfo: attrsInfoWithoutForwardedAsStatic, forwardedAsStaticFallback } = splitForwardedAsStaticAttrs({
@@ -20158,7 +21730,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20158
21730
  attrsInfo: attrsInfoWithoutForwardedAsStatic,
20159
21731
  propExprFor: (prop) => j.identifier(prop)
20160
21732
  }),
20161
- ...(d.supportsRefProp ?? false) || !restId && willForwardRef ? [j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId))] : [],
21733
+ ...shouldForwardRefExplicitly ? [j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId))] : [],
20162
21734
  ...restId ? [j.jsxSpreadAttribute(restId)] : [],
20163
21735
  ...emitter.buildDynamicAttrsFromProps({
20164
21736
  dynamicAttrs: attrsInfoWithoutForwardedAsStatic?.dynamicAttrs ?? [],
@@ -20171,7 +21743,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20171
21743
  tagName: useAsProp ? "Component" : tagName,
20172
21744
  attrs: openingAttrs,
20173
21745
  includeChildren,
20174
- childrenExpr: usePropsChildrenDirectly ? j.memberExpression(propsId, j.identifier("children")) : childrenId
21746
+ childrenExpr: childrenId
20175
21747
  });
20176
21748
  const bodyStmts = [];
20177
21749
  if (declStmt) bodyStmts.push(declStmt);
@@ -20181,7 +21753,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20181
21753
  const shouldAddTypeParams = allowAsProp && emitTypes;
20182
21754
  emitted.push(...withLeadingCommentsOnFirstFunction([emitter.buildWrapperFunction({
20183
21755
  localName: d.localName,
20184
- params: [propsParamId],
21756
+ params: [propsParam],
20185
21757
  bodyStmts,
20186
21758
  typeParameters: shouldAddTypeParams ? buildPolymorphicTypeParams(j, tagName) : void 0
20187
21759
  })], d));
@@ -20256,6 +21828,7 @@ function maybeOmitExternalStylePropsFromExplicitTypeText(args) {
20256
21828
  const omitted = [];
20257
21829
  if (!args.allowClassNameProp) omitted.push("\"className\"");
20258
21830
  if (!args.allowStyleProp) omitted.push("\"style\"");
21831
+ if (!args.allowSxProp) omitted.push("\"sx\"");
20259
21832
  return omitted.length > 0 ? `Omit<${args.typeText}, ${omitted.join(" | ")}>` : args.typeText;
20260
21833
  }
20261
21834
  function explicitTypeMayContainExternalStyleProps(args) {
@@ -23309,6 +24882,7 @@ function tryDecomposeConditionalBranches(condBody, paramName) {
23309
24882
  conditionProp,
23310
24883
  staticValue,
23311
24884
  dynamicBranchExpr: dynamicBranch,
24885
+ paramName,
23312
24886
  dynamicProps,
23313
24887
  isStaticWhenFalse
23314
24888
  };
@@ -24452,7 +26026,7 @@ function createCssHelperResolver(args) {
24452
26026
  const path = getMemberPathFromIdentifier(test, paramName);
24453
26027
  return path && path[0] === "theme" && path.length > 1 ? path.slice(1).join(".") : null;
24454
26028
  };
24455
- const resolveCssHelperTemplate = (template, paramName, loc) => {
26029
+ const resolveCssHelperTemplate = (template, paramName, loc, options) => {
24456
26030
  const bail = (type, context, exprLoc) => {
24457
26031
  warnings.push({
24458
26032
  severity: "warning",
@@ -24471,7 +26045,7 @@ function createCssHelperResolver(args) {
24471
26045
  const lookupImport = (localName) => importMap.get(localName) ?? null;
24472
26046
  for (const rule of rules) {
24473
26047
  const rawMedia = findSupportedAtRule(rule.atRuleStack);
24474
- if (hasUnsupportedAtRule(rule.atRuleStack)) return bail("Conditional `css` block: @-rules (e.g., @media, @supports) are not supported");
26048
+ if (hasUnsupportedAtRule(rule.atRuleStack)) return bail("Conditional `css` block: unsupported or mixed @-rules require manual handling");
24475
26049
  let media = rawMedia;
24476
26050
  let computedMediaKey = null;
24477
26051
  if (rawMedia) {
@@ -24493,6 +26067,7 @@ function createCssHelperResolver(args) {
24493
26067
  const rawSelector = (rule.selector ?? "").trim();
24494
26068
  const specificityResult = normalizeSpecificityHacks(rawSelector);
24495
26069
  if (specificityResult.hasHigherTier) return bail("Styled-components specificity hacks like `&&` / `&&&` are not representable in StyleX");
26070
+ if (specificityResult.wasStripped && options?.rejectStrippedSpecificity) return bail("Styled-components specificity hacks like `&&` / `&&&` are not representable in StyleX", void 0, computeSelectorWarningLoc(templateLoc ?? void 0, rawCss, rawSelector) ?? templateLoc);
24496
26071
  const selector = specificityResult.normalized.trim();
24497
26072
  const specificityStripped = specificityResult.wasStripped;
24498
26073
  const allowDynamicValues = selector === "&";
@@ -24735,7 +26310,7 @@ function resolveTemplateLiteralBranch(ctx, args) {
24735
26310
  if (hasUnsupportedAtRule(rule.atRuleStack)) {
24736
26311
  ctx.warnings?.push({
24737
26312
  severity: "warning",
24738
- type: "CSS block contains unsupported at-rule (only @media and @container are supported; @supports, etc. require manual handling)",
26313
+ type: "CSS block contains unsupported at-rule (only @media, @container, and @supports are supported; mixed nested at-rules require manual handling)",
24739
26314
  loc: null
24740
26315
  });
24741
26316
  return null;
@@ -25246,7 +26821,7 @@ function resolveStaticTemplateExpressionAst(args) {
25246
26821
  return null;
25247
26822
  }
25248
26823
  function buildPropAccessExpr(j, propName, defaultValue) {
25249
- const baseExpr = isValidIdentifierName$1(propName) ? j.identifier(propName) : j.memberExpression(j.identifier("props"), j.literal(propName), true);
26824
+ const baseExpr = isValidIdentifierName(propName) ? j.identifier(propName) : j.memberExpression(j.identifier("props"), j.literal(propName), true);
25250
26825
  if (defaultValue !== void 0) return j.logicalExpression("??", baseExpr, cloneAstNode(defaultValue));
25251
26826
  return baseExpr;
25252
26827
  }
@@ -25254,6 +26829,7 @@ function buildPropAccessExpr(j, propName, defaultValue) {
25254
26829
  //#region src/internal/lower-rules/css-helper-handlers.ts
25255
26830
  const createCssHelperHandlers = (ctx) => {
25256
26831
  const { j, filePath, decl, warnings, styleObj, variantBuckets, variantStyleKeys, cssHelperFunctions, usedCssHelperFunctions, parseExpr, resolveValue, resolveCall, resolveImportInScope, resolverImports, isCssHelperTaggedTemplate, resolveCssHelperTemplate, applyVariant, dropAllTestInfoProps, componentInfo, handlerContext, markBail } = ctx;
26832
+ const cssHelperTemplateOptions = { rejectStrippedSpecificity: decl.base.kind === "component" };
25257
26833
  const tplCtx = {
25258
26834
  j,
25259
26835
  filePath,
@@ -25450,7 +27026,7 @@ const createCssHelperHandlers = (ctx) => {
25450
27026
  markBail();
25451
27027
  return true;
25452
27028
  }
25453
- const defaultResolved = resolveCssHelperTemplate(parsed.defaultCssTemplate.quasi, null, helperFn.loc ?? decl.loc);
27029
+ const defaultResolved = resolveCssHelperTemplate(parsed.defaultCssTemplate.quasi, null, helperFn.loc ?? decl.loc, cssHelperTemplateOptions);
25454
27030
  if (!defaultResolved || defaultResolved.dynamicProps.length > 0) {
25455
27031
  warnings.push({
25456
27032
  severity: "warning",
@@ -25463,7 +27039,7 @@ const createCssHelperHandlers = (ctx) => {
25463
27039
  }
25464
27040
  mergeStyleObjects(baseFromHelper, defaultResolved.style);
25465
27041
  for (const [caseValue, tpl] of parsed.caseCssTemplates.entries()) {
25466
- const res = resolveCssHelperTemplate(tpl.quasi, null, helperFn.loc ?? decl.loc);
27042
+ const res = resolveCssHelperTemplate(tpl.quasi, null, helperFn.loc ?? decl.loc, cssHelperTemplateOptions);
25467
27043
  if (!res || res.dynamicProps.length > 0) {
25468
27044
  warnings.push({
25469
27045
  severity: "warning",
@@ -25499,10 +27075,241 @@ const createCssHelperHandlers = (ctx) => {
25499
27075
  };
25500
27076
  };
25501
27077
  //#endregion
27078
+ //#region src/internal/lower-rules/static-evaluator.ts
27079
+ const MAX_STATIC_CALL_DEPTH = 20;
27080
+ function evaluateLocalCallValueTransform(args) {
27081
+ const callStack = args.callStack ?? /* @__PURE__ */ new Set();
27082
+ if (callStack.has(args.calleeName) || callStack.size >= MAX_STATIC_CALL_DEPTH) return null;
27083
+ const fn = findLocalSingleParamFunction(args);
27084
+ if (!fn) return null;
27085
+ const nextCallStack = new Set(callStack);
27086
+ nextCallStack.add(args.calleeName);
27087
+ const result = evaluateFunctionBody(fn.body, fn.paramName, args.argValue, {
27088
+ j: args.j,
27089
+ root: args.root,
27090
+ callStack: nextCallStack
27091
+ });
27092
+ return result.supported && result.returned ? result.value : null;
27093
+ }
27094
+ function evaluateObservedDynamicExpression(args) {
27095
+ const result = evaluateStaticExpression(args.expression, args.propName, args.propValue, {
27096
+ j: args.j,
27097
+ root: args.root,
27098
+ paramName: args.paramName ?? null,
27099
+ callStack: /* @__PURE__ */ new Set()
27100
+ });
27101
+ return result.supported ? result.value : null;
27102
+ }
27103
+ function findLocalSingleParamFunction(args) {
27104
+ const { j, root, calleeName } = args;
27105
+ const candidates = [];
27106
+ let matchingBindings = 0;
27107
+ root.find(j.FunctionDeclaration, { id: { name: calleeName } }).forEach((path) => {
27108
+ matchingBindings += 1;
27109
+ const fnNode = path.node;
27110
+ const paramName = getSingleIdentifierParamName(fnNode.params);
27111
+ if (paramName) candidates.push({
27112
+ paramName,
27113
+ body: fnNode.body
27114
+ });
27115
+ });
27116
+ root.find(j.VariableDeclarator, { id: { name: calleeName } }).forEach((path) => {
27117
+ matchingBindings += 1;
27118
+ const init = path.node.init;
27119
+ if (!init || init.type !== "ArrowFunctionExpression" && init.type !== "FunctionExpression") return;
27120
+ const paramName = getSingleIdentifierParamName(init.params);
27121
+ if (paramName) candidates.push({
27122
+ paramName,
27123
+ body: init.body
27124
+ });
27125
+ });
27126
+ const [candidate] = candidates;
27127
+ return matchingBindings === 1 && candidate ? candidate : null;
27128
+ }
27129
+ function getSingleIdentifierParamName(params) {
27130
+ if (!params || params.length !== 1) return null;
27131
+ const param = params[0];
27132
+ return param.type === "Identifier" && param.name ? param.name : null;
27133
+ }
27134
+ function evaluateFunctionBody(body, propName, propValue, ctx) {
27135
+ const bodyNode = body;
27136
+ if (!bodyNode) return { supported: false };
27137
+ if (bodyNode.type !== "BlockStatement") {
27138
+ const result = evaluateStaticExpression(bodyNode, propName, propValue, ctx);
27139
+ return result.supported ? {
27140
+ supported: true,
27141
+ returned: true,
27142
+ value: result.value
27143
+ } : { supported: false };
27144
+ }
27145
+ const statements = bodyNode.body;
27146
+ if (!Array.isArray(statements)) return { supported: false };
27147
+ for (const statement of statements) {
27148
+ const result = evaluateStaticStatement(statement, propName, propValue, ctx);
27149
+ if (!result.supported || result.returned) return result;
27150
+ }
27151
+ return {
27152
+ supported: true,
27153
+ returned: false
27154
+ };
27155
+ }
27156
+ function evaluateStaticStatement(statement, propName, propValue, ctx) {
27157
+ const node = statement;
27158
+ if (!node) return { supported: false };
27159
+ if (node.type === "ReturnStatement") {
27160
+ if (node.argument === null || node.argument === void 0) return {
27161
+ supported: true,
27162
+ returned: true,
27163
+ value: void 0
27164
+ };
27165
+ const result = evaluateStaticExpression(node.argument, propName, propValue, ctx);
27166
+ return result.supported ? {
27167
+ supported: true,
27168
+ returned: true,
27169
+ value: result.value
27170
+ } : { supported: false };
27171
+ }
27172
+ if (node.type === "IfStatement") {
27173
+ const test = evaluateStaticExpression(node.test, propName, propValue, ctx);
27174
+ if (!test.supported || typeof test.value !== "boolean") return { supported: false };
27175
+ if (test.value) return evaluateStaticBranch(node.consequent, propName, propValue, ctx);
27176
+ return node.alternate ? evaluateStaticBranch(node.alternate, propName, propValue, ctx) : {
27177
+ supported: true,
27178
+ returned: false
27179
+ };
27180
+ }
27181
+ return { supported: false };
27182
+ }
27183
+ function evaluateStaticBranch(branch, propName, propValue, ctx) {
27184
+ const node = branch;
27185
+ if (node?.type === "BlockStatement") return evaluateFunctionBody(node, propName, propValue, ctx);
27186
+ return evaluateStaticStatement(branch, propName, propValue, ctx);
27187
+ }
27188
+ function evaluateStaticExpression(expression, propName, propValue, ctx) {
27189
+ const node = expression;
27190
+ if (!node) return { supported: false };
27191
+ if (node.type === "Identifier") return node.name === propName ? {
27192
+ supported: true,
27193
+ value: propValue
27194
+ } : { supported: false };
27195
+ if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
27196
+ const info = extractRootAndPath(node);
27197
+ if (info && ctx.paramName && info.rootName === ctx.paramName && info.path[0] === propName) return info.path.length === 1 ? {
27198
+ supported: true,
27199
+ value: propValue
27200
+ } : { supported: false };
27201
+ return { supported: false };
27202
+ }
27203
+ if (node.type === "CallExpression") {
27204
+ const callee = node.callee;
27205
+ if (callee?.type !== "Identifier" || !callee.name || (node.arguments?.length ?? 0) !== 1) return { supported: false };
27206
+ const callArg = evaluateStaticExpression(node.arguments?.[0], propName, propValue, ctx);
27207
+ if (!callArg.supported) return { supported: false };
27208
+ const value = evaluateLocalCallValueTransform({
27209
+ j: ctx.j,
27210
+ root: ctx.root,
27211
+ calleeName: callee.name,
27212
+ argValue: callArg.value,
27213
+ callStack: ctx.callStack
27214
+ });
27215
+ return isStaticEvalValue(value) ? {
27216
+ supported: true,
27217
+ value
27218
+ } : { supported: false };
27219
+ }
27220
+ if (node.type === "Literal") return isStaticEvalValue(node.value) ? {
27221
+ supported: true,
27222
+ value: node.value
27223
+ } : { supported: false };
27224
+ if (node.type === "StringLiteral" || node.type === "NumericLiteral" || node.type === "BooleanLiteral") return isStaticEvalValue(node.value) ? {
27225
+ supported: true,
27226
+ value: node.value
27227
+ } : { supported: false };
27228
+ if (node.type === "NullLiteral") return {
27229
+ supported: true,
27230
+ value: null
27231
+ };
27232
+ if (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSTypeAssertion") return evaluateStaticExpression(node.expression, propName, propValue, ctx);
27233
+ if (node.type === "UnaryExpression") {
27234
+ const argument = evaluateStaticExpression(node.argument, propName, propValue, ctx);
27235
+ if (!argument.supported) return { supported: false };
27236
+ if (node.operator === "!") return {
27237
+ supported: true,
27238
+ value: !argument.value
27239
+ };
27240
+ if (node.operator === "typeof") return {
27241
+ supported: true,
27242
+ value: typeof argument.value
27243
+ };
27244
+ return { supported: false };
27245
+ }
27246
+ if (node.type === "LogicalExpression") {
27247
+ const left = evaluateStaticExpression(node.left, propName, propValue, ctx);
27248
+ if (!left.supported) return { supported: false };
27249
+ if (node.operator === "||") return left.value ? left : evaluateStaticExpression(node.right, propName, propValue, ctx);
27250
+ if (node.operator === "&&") return left.value ? evaluateStaticExpression(node.right, propName, propValue, ctx) : left;
27251
+ if (node.operator === "??") return left.value === null || left.value === void 0 ? evaluateStaticExpression(node.right, propName, propValue, ctx) : left;
27252
+ return { supported: false };
27253
+ }
27254
+ if (node.type === "BinaryExpression") return evaluateStaticBinaryExpression(node, propName, propValue, ctx);
27255
+ if (node.type === "ConditionalExpression") {
27256
+ const test = evaluateStaticExpression(node.test, propName, propValue, ctx);
27257
+ if (!test.supported || typeof test.value !== "boolean") return { supported: false };
27258
+ return evaluateStaticExpression(test.value ? node.consequent : node.alternate, propName, propValue, ctx);
27259
+ }
27260
+ if (node.type === "TemplateLiteral" && node.quasis && node.expressions) return evaluateStaticTemplateLiteral({
27261
+ quasis: node.quasis,
27262
+ expressions: node.expressions
27263
+ }, propName, propValue, ctx);
27264
+ return { supported: false };
27265
+ }
27266
+ function evaluateStaticBinaryExpression(node, propName, propValue, ctx) {
27267
+ const left = evaluateStaticExpression(node.left, propName, propValue, ctx);
27268
+ const right = evaluateStaticExpression(node.right, propName, propValue, ctx);
27269
+ if (!left.supported || !right.supported) return { supported: false };
27270
+ switch (node.operator) {
27271
+ case "===": return {
27272
+ supported: true,
27273
+ value: left.value === right.value
27274
+ };
27275
+ case "!==": return {
27276
+ supported: true,
27277
+ value: left.value !== right.value
27278
+ };
27279
+ case "+": return typeof left.value === "number" && typeof right.value === "number" ? {
27280
+ supported: true,
27281
+ value: left.value + right.value
27282
+ } : {
27283
+ supported: true,
27284
+ value: `${String(left.value)}${String(right.value)}`
27285
+ };
27286
+ default: return { supported: false };
27287
+ }
27288
+ }
27289
+ function evaluateStaticTemplateLiteral(node, propName, propValue, ctx) {
27290
+ let value = "";
27291
+ for (let i = 0; i < node.quasis.length; i++) {
27292
+ value += node.quasis[i]?.value?.cooked ?? node.quasis[i]?.value?.raw ?? "";
27293
+ if (i < node.expressions.length) {
27294
+ const expressionValue = evaluateStaticExpression(node.expressions[i], propName, propValue, ctx);
27295
+ if (!expressionValue.supported) return { supported: false };
27296
+ value += String(expressionValue.value);
27297
+ }
27298
+ }
27299
+ return {
27300
+ supported: true,
27301
+ value
27302
+ };
27303
+ }
27304
+ function isStaticEvalValue(value) {
27305
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || value === void 0;
27306
+ }
27307
+ //#endregion
25502
27308
  //#region src/internal/lower-rules/css-helper-conditional.ts
25503
27309
  function createCssHelperConditionalHandler(ctx) {
25504
- const { j, decl, filePath, warnings, parseExpr, resolveValue, resolveCall, resolveSelector, resolveImportInScope, resolverImports, componentInfo, handlerContext, styleObj, styleFnFromProps, styleFnDecls, inlineStyleProps, isCssHelperTaggedTemplate, resolveCssHelperTemplate, resolveStaticCssBlock, isPlainTemplateLiteral, isThemeAccessTest, applyVariant, dropAllTestInfoProps, annotateParamFromJsxProp, findJsxPropTsType, isJsxPropOptional, markBail, importMap, extraStyleObjects, resolvedStyleObjects } = ctx;
27310
+ const { j, decl, filePath, warnings, parseExpr, resolveValue, resolveCall, resolveSelector, resolveImportInScope, resolverImports, componentInfo, handlerContext, styleObj, styleFnFromProps, styleFnDecls, inlineStyleProps, isCssHelperTaggedTemplate, resolveCssHelperTemplate, resolveStaticCssBlock, isPlainTemplateLiteral, isThemeAccessTest, applyVariant, dropAllTestInfoProps, annotateParamFromJsxProp, findJsxPropTsType, isJsxPropOptional, markBail, importMap, root, extraStyleObjects, resolvedStyleObjects } = ctx;
25505
27311
  const avoidNames = new Set(importMap.keys());
27312
+ const cssHelperTemplateOptions = { rejectStrippedSpecificity: decl.base.kind === "component" };
25506
27313
  /**
25507
27314
  * Resolve the TS type node for a prop used in a style function parameter.
25508
27315
  * Uses the component's type annotation to infer the correct type (e.g. `number | string`).
@@ -25749,10 +27556,11 @@ function createCssHelperConditionalHandler(ctx) {
25749
27556
  return entries;
25750
27557
  };
25751
27558
  const wrapValueWithResolvedPseudos = (prop, value, pseudoEntries) => {
25752
- const properties = [j.property("init", j.identifier("default"), styleObj[prop] !== void 0 ? styleValueToExpression(j, styleObj[prop]) : j.literal(null))];
27559
+ const defaultExpr = styleObj[prop] !== void 0 ? styleValueToExpression(j, styleObj[prop]) : j.literal(null);
27560
+ const properties = [j.property("init", j.identifier("default"), cloneAstNode(defaultExpr))];
25753
27561
  for (const entry of pseudoEntries) {
25754
27562
  let entryValue = value;
25755
- if (entry.conditionExpr) entryValue = j.objectExpression([j.property("init", j.identifier("default"), j.literal(null)), (() => {
27563
+ if (entry.conditionExpr) entryValue = j.objectExpression([j.property("init", j.identifier("default"), cloneAstNode(defaultExpr)), (() => {
25756
27564
  const p = j.property("init", entry.conditionExpr, value);
25757
27565
  p.computed = true;
25758
27566
  return p;
@@ -25872,7 +27680,7 @@ function createCssHelperConditionalHandler(ctx) {
25872
27680
  if (!testInfo) return false;
25873
27681
  if (isCssHelperTaggedTemplate(body.right)) {
25874
27682
  const cssNode = body.right;
25875
- const resolved = resolveCssHelperTemplate(cssNode.quasi, paramName, decl.loc);
27683
+ const resolved = resolveCssHelperTemplate(cssNode.quasi, paramName, decl.loc, cssHelperTemplateOptions);
25876
27684
  if (!resolved) {
25877
27685
  markBail();
25878
27686
  return true;
@@ -26037,6 +27845,52 @@ function createCssHelperConditionalHandler(ctx) {
26037
27845
  }
26038
27846
  if (entries.length > 0) decl.needsWrapperComponent = true;
26039
27847
  };
27848
+ const tryApplyFiniteUnionStaticMap = (args) => {
27849
+ const unionValues = extractUnionLiteralValues(findJsxPropTsType(args.propName));
27850
+ if (!unionValues || unionValues.length < 2 || unionValues.length > 20) return false;
27851
+ const buckets = [];
27852
+ for (const propValue of unionValues) {
27853
+ const testValue = evaluateObservedDynamicExpression({
27854
+ j,
27855
+ root,
27856
+ expression: args.test,
27857
+ propName: args.propName,
27858
+ propValue,
27859
+ paramName: args.paramName
27860
+ });
27861
+ if (typeof testValue !== "boolean") return false;
27862
+ if (!testValue) continue;
27863
+ const style = {};
27864
+ for (const [stylexProp, valueExpr] of args.map) {
27865
+ const cssValue = evaluateObservedDynamicExpression({
27866
+ j,
27867
+ root,
27868
+ expression: valueExpr,
27869
+ propName: args.propName,
27870
+ propValue,
27871
+ paramName: args.paramName
27872
+ });
27873
+ if (typeof cssValue !== "string" && typeof cssValue !== "number") return false;
27874
+ style[stylexProp] = cssValue;
27875
+ }
27876
+ if (Object.keys(style).length > 0) buckets.push({
27877
+ propValue,
27878
+ style
27879
+ });
27880
+ }
27881
+ if (buckets.length === 0) return false;
27882
+ for (const { propValue, style } of buckets) {
27883
+ const propValueExpr = typeof propValue === "number" ? String(propValue) : JSON.stringify(propValue);
27884
+ applyVariant({
27885
+ when: `${args.propName} === ${propValueExpr}`,
27886
+ propName: args.propName
27887
+ }, style);
27888
+ }
27889
+ decl.variantLookupCastProps ??= /* @__PURE__ */ new Set();
27890
+ decl.variantLookupCastProps.add(args.propName);
27891
+ ensureShouldForwardPropDrop(decl, args.propName);
27892
+ return true;
27893
+ };
26040
27894
  if (body?.type === "TemplateLiteral") {
26041
27895
  const resolved = resolveTemplateLiteralBranch(tplCtx, {
26042
27896
  node: body,
@@ -26300,6 +28154,15 @@ function createCssHelperConditionalHandler(ctx) {
26300
28154
  collectPropsFromExpressions([...consMap.values(), ...altMap.values()], propsUsed);
26301
28155
  const valuePropParams = Array.from(propsUsed);
26302
28156
  if (consMap.size === 0 && altMap.size === 0) return true;
28157
+ if (valuePropParams.length === 1 && consMap.size > 0 && altMap.size === 0 && tryApplyFiniteUnionStaticMap({
28158
+ map: consMap,
28159
+ test: conditional.test,
28160
+ propName: valuePropParams[0],
28161
+ paramName
28162
+ })) {
28163
+ decl.needsWrapperComponent = true;
28164
+ return true;
28165
+ }
26303
28166
  const useSingleParam = valuePropParams.length === 1;
26304
28167
  const singlePropName = useSingleParam ? valuePropParams[0] : "";
26305
28168
  const singleParamName = useSingleParam ? singlePropName.startsWith("$") ? singlePropName.slice(1) : singlePropName : "";
@@ -26360,7 +28223,7 @@ function createCssHelperConditionalHandler(ctx) {
26360
28223
  if (!(consIsCss || altIsCss || consIsTpl || altIsTpl || consIsCall || altIsCall || consIsStr || altIsStr)) return false;
26361
28224
  const resolveCssBranch = (node) => {
26362
28225
  if (!isCssHelperTaggedTemplate(node)) return null;
26363
- return resolveCssHelperTemplate(node.quasi, paramName, decl.loc);
28226
+ return resolveCssHelperTemplate(node.quasi, paramName, decl.loc, cssHelperTemplateOptions);
26364
28227
  };
26365
28228
  const applyConditionalVariants = applyConditionalVariantsInline;
26366
28229
  const resolveTplBranch = (node) => resolveTemplateLiteralBranch(tplCtx, {
@@ -26796,7 +28659,7 @@ function buildFallbackPropSuffix(consMap, altMap) {
26796
28659
  //#endregion
26797
28660
  //#region src/internal/lower-rules/import-resolution.ts
26798
28661
  const buildSafeIndexedParamName = (preferred, containerExpr) => {
26799
- if (!isValidIdentifierName$1(preferred)) return "propValue";
28662
+ if (!isValidIdentifierName(preferred)) return "propValue";
26800
28663
  if (containerExpr?.type === "Identifier" && containerExpr.name === preferred) return `${preferred}Value`;
26801
28664
  return preferred;
26802
28665
  };
@@ -26844,7 +28707,7 @@ const createImportResolver = (args) => {
26844
28707
  const getNearestFunctionNode = (path) => {
26845
28708
  let cur = path;
26846
28709
  while (cur) {
26847
- if (isFunctionNode(cur.node)) return cur.node;
28710
+ if (isFunctionNode$1(cur.node)) return cur.node;
26848
28711
  cur = cur.parentPath ?? null;
26849
28712
  }
26850
28713
  return null;
@@ -26915,7 +28778,7 @@ const createImportResolver = (args) => {
26915
28778
  let cur = path;
26916
28779
  while (cur) {
26917
28780
  const node = cur.node;
26918
- if (isFunctionNode(node) && functionDeclaresName(node, name)) {
28781
+ if (isFunctionNode$1(node) && functionDeclaresName(node, name)) {
26919
28782
  shadowedIdentCache.set(identNode, true);
26920
28783
  return true;
26921
28784
  }
@@ -27124,7 +28987,7 @@ const createValuePatternHandlers = (ctx) => {
27124
28987
  const consTheme = resolveThemeAst(body.consequent);
27125
28988
  const altTheme = resolveThemeAst(body.alternate);
27126
28989
  const buildPropAccess = (prop) => {
27127
- return isValidIdentifierName$1(prop) ? j.memberExpression(j.identifier("props"), j.identifier(prop)) : j.memberExpression(j.identifier("props"), j.literal(prop), true);
28990
+ return isValidIdentifierName(prop) ? j.memberExpression(j.identifier("props"), j.identifier(prop)) : j.memberExpression(j.identifier("props"), j.literal(prop), true);
27128
28991
  };
27129
28992
  let nullishPropName = null;
27130
28993
  let baseTheme = null;
@@ -27160,7 +29023,7 @@ const createValuePatternHandlers = (ctx) => {
27160
29023
  styleFnDecls.set(fnKey, j.arrowFunctionExpression([param], bodyExpr));
27161
29024
  }
27162
29025
  if (!styleFnFromProps.some((p) => p.fnKey === fnKey)) {
27163
- const baseArg = isValidIdentifierName$1(nullishPropName) ? j.identifier(nullishPropName) : buildPropAccess(nullishPropName);
29026
+ const baseArg = isValidIdentifierName(nullishPropName) ? j.identifier(nullishPropName) : buildPropAccess(nullishPropName);
27164
29027
  const callArg = j.logicalExpression("??", baseArg, fallbackTheme);
27165
29028
  styleFnFromProps.push({
27166
29029
  fnKey,
@@ -27623,7 +29486,7 @@ function createDeclProcessingState(state, decl) {
27623
29486
  if (hasUnsupportedAtRule(rule.atRuleStack)) {
27624
29487
  warnings.push({
27625
29488
  severity: "warning",
27626
- type: "CSS block contains unsupported at-rule (only @media and @container are supported; @supports, etc. require manual handling)",
29489
+ type: "CSS block contains unsupported at-rule (only @media, @container, and @supports are supported; mixed nested at-rules require manual handling)",
27627
29490
  loc: decl.loc
27628
29491
  });
27629
29492
  return null;
@@ -27712,6 +29575,7 @@ function createDeclProcessingState(state, decl) {
27712
29575
  tryHandleCssHelperConditionalBlock: createCssHelperConditionalHandler({
27713
29576
  ...sharedFromState,
27714
29577
  importMap,
29578
+ root,
27715
29579
  decl,
27716
29580
  componentInfo,
27717
29581
  handlerContext,
@@ -27954,7 +29818,7 @@ function finalizeDeclProcessing(ctx) {
27954
29818
  if (!v || typeof v !== "object" || Array.isArray(v) || isAstNode(v)) return false;
27955
29819
  const keys = Object.keys(v);
27956
29820
  if (keys.length === 0) return false;
27957
- return keys.includes("default") || keys.some(isStyleConditionKey);
29821
+ return keys.includes("default") || keys.some(isStyleConditionKey$1);
27958
29822
  };
27959
29823
  if (!(() => {
27960
29824
  const disabledBucket = variantBuckets.get("disabled");
@@ -28016,6 +29880,7 @@ function finalizeDeclProcessing(ctx) {
28016
29880
  const observedFallbackFnKey = observedVariantFallbackFns.get(dim.propName);
28017
29881
  if (observedFallbackFnKey) dim.fallbackFnKey = observedFallbackFnKey;
28018
29882
  if (!observedFallbackFnKey && hasFiniteNumericVariantKey(dim)) dim.propTypeFromKeyof = true;
29883
+ if (decl.variantLookupCastProps?.has(dim.propName)) dim.forceKeyofLookupCast = true;
28019
29884
  }
28020
29885
  decl.variantDimensions = mergeVariantDimensions(decl.variantDimensions, dimensions);
28021
29886
  decl.needsWrapperComponent = true;
@@ -28604,7 +30469,7 @@ function expressionContainsStyleConditionKey(expr) {
28604
30469
  return;
28605
30470
  }
28606
30471
  const key = p.key?.type === "Identifier" ? p.key.name : (p.key?.type === "StringLiteral" || p.key?.type === "Literal") && typeof p.key.value === "string" ? p.key.value : null;
28607
- if (key && isStyleConditionKey(key)) {
30472
+ if (key && isStyleConditionKey$1(key)) {
28608
30473
  found = true;
28609
30474
  return;
28610
30475
  }
@@ -28966,7 +30831,7 @@ function liftFlatVariantsToPseudoMaps(variantBuckets) {
28966
30831
  const compoundValue = compoundBucket[cssProp];
28967
30832
  if (!isMediaOrPseudoMap(compoundValue)) continue;
28968
30833
  const liftedMap = { default: flatValue };
28969
- for (const condKey of Object.keys(compoundValue)) if (condKey !== "default" && isStyleConditionKey(condKey)) liftedMap[condKey] = flatValue;
30834
+ for (const condKey of Object.keys(compoundValue)) if (condKey !== "default" && isStyleConditionKey$1(condKey)) liftedMap[condKey] = flatValue;
28970
30835
  simpleBucket[cssProp] = liftedMap;
28971
30836
  compoundValue.default = flatValue;
28972
30837
  break;
@@ -30760,6 +32625,10 @@ function handleInterpolatedDeclaration(args) {
30760
32625
  const avoidNames = new Set(importMap.keys());
30761
32626
  if (state.bail) return;
30762
32627
  if (d.value.kind !== "interpolated") return;
32628
+ if (d.property && isUnsupportedStylexProperty(d.property)) {
32629
+ state.bailUnsupported(decl, `Unsupported CSS property "${d.property}" cannot be emitted in StyleX`);
32630
+ return;
32631
+ }
30763
32632
  let bail = false;
30764
32633
  const getRootIdentifierInfo = extractRootAndPath;
30765
32634
  const bailUnsupportedLocal = (declArg, type) => {
@@ -30784,7 +32653,7 @@ function handleInterpolatedDeclaration(args) {
30784
32653
  if (!usage) return null;
30785
32654
  const propUsage = usage.props[jsxProp];
30786
32655
  if (!propUsage || propUsage.values.length < 2) return null;
30787
- const values = propUsage.values.filter((value) => typeof value === "number");
32656
+ const values = propUsage.values.filter((value) => typeof value === "string" || typeof value === "number");
30788
32657
  if (values.length !== propUsage.values.length) return null;
30789
32658
  return values;
30790
32659
  };
@@ -30903,7 +32772,7 @@ function handleInterpolatedDeclaration(args) {
30903
32772
  const unionValues = extractUnionLiteralValues(findJsxPropTsTypeForVariantExtraction(jsxProp));
30904
32773
  const observedValues = unionValues ? null : getObservedStaticVariantValues(jsxProp);
30905
32774
  const hasStaticText = staticParts.prefix !== "" || staticParts.suffix !== "";
30906
- if (observedValues && getNumericCssEmissionMode(stylexProp) === "cssText" && !hasStaticText) {
32775
+ if (observedValues && observedValues.some((value) => typeof value === "number") && getNumericCssEmissionMode(stylexProp) === "cssText" && !hasStaticText) {
30907
32776
  observedNumericCssTextProps.add(jsxProp);
30908
32777
  return false;
30909
32778
  }
@@ -30916,15 +32785,110 @@ function handleInterpolatedDeclaration(args) {
30916
32785
  propName: jsxProp
30917
32786
  }, { [stylexProp]: emitStaticObservedValue(value, stylexProp, observedValues !== null, staticParts) });
30918
32787
  }
30919
- if (observedValues) observedVariantFallbackFns.set(jsxProp, ensureObservedVariantFallbackFn(jsxProp, stylexProp, staticParts));
30920
- if (jsxProp.startsWith("$")) ensureShouldForwardPropDrop(decl, jsxProp);
32788
+ if (observedValues) {
32789
+ const fallbackFnKey = ensureObservedVariantFallbackFn(jsxProp, stylexProp, (param) => buildRuntimeObservedValueExpr(j, stylexProp, param, staticParts));
32790
+ if (fallbackFnKey) {
32791
+ observedVariantFallbackFns.set(jsxProp, fallbackFnKey);
32792
+ markStyleValueVariantProp(jsxProp);
32793
+ }
32794
+ }
32795
+ ensureObservedVariantPropDrop(jsxProp);
32796
+ return true;
32797
+ };
32798
+ const tryEmitTransformedObservedVariantBuckets = (jsxProp, stylexProp, valueTransform) => {
32799
+ if (!valueTransform || valueTransform.kind !== "call" || valueTransform.resolvedExpr || valueTransform.resolvedUsage || media || pseudos?.length) return false;
32800
+ const observedValues = getObservedStaticVariantValues(jsxProp);
32801
+ if (!observedValues || observedValues.length < 2 || observedValues.length > 20) return false;
32802
+ const transformedValues = [];
32803
+ for (const propValue of observedValues) {
32804
+ const cssValue = evaluateLocalCallValueTransform({
32805
+ j,
32806
+ root: state.root,
32807
+ calleeName: valueTransform.calleeIdent,
32808
+ argValue: propValue
32809
+ });
32810
+ if (typeof cssValue !== "string" && typeof cssValue !== "number") return false;
32811
+ transformedValues.push({
32812
+ propValue,
32813
+ cssValue
32814
+ });
32815
+ }
32816
+ for (const { propValue, cssValue } of transformedValues) applyVariant({
32817
+ when: `${jsxProp} === ${typeof propValue === "number" ? String(propValue) : JSON.stringify(propValue)}`,
32818
+ propName: jsxProp
32819
+ }, { [stylexProp]: cssValue });
32820
+ const fallbackFnKey = ensureObservedVariantFallbackFn(jsxProp, stylexProp, (param) => j.callExpression(j.identifier(valueTransform.calleeIdent), [param]));
32821
+ if (!fallbackFnKey) return false;
32822
+ observedVariantFallbackFns.set(jsxProp, fallbackFnKey);
32823
+ markStyleValueVariantProp(jsxProp);
32824
+ ensureObservedVariantPropDrop(jsxProp);
32825
+ return true;
32826
+ };
32827
+ const tryEmitObservedExpressionVariantBuckets = (jsxProp, stylexProp, expression, paramName, conditionWhen, conditionProp, prefix, suffix) => {
32828
+ if (media || pseudos?.length) return false;
32829
+ const observedValues = getObservedStaticVariantValues(jsxProp);
32830
+ if (!observedValues || observedValues.length < 2 || observedValues.length > 20) return false;
32831
+ const transformedValues = [];
32832
+ for (const propValue of observedValues) {
32833
+ const evaluatedValue = evaluateObservedDynamicExpression({
32834
+ j,
32835
+ root: state.root,
32836
+ expression,
32837
+ propName: jsxProp,
32838
+ propValue,
32839
+ paramName
32840
+ });
32841
+ if (typeof evaluatedValue !== "string" && typeof evaluatedValue !== "number") return false;
32842
+ const cssValue = prefix || suffix ? `${prefix}${String(evaluatedValue)}${suffix}` : evaluatedValue;
32843
+ transformedValues.push({
32844
+ propValue,
32845
+ cssValue
32846
+ });
32847
+ }
32848
+ const ensuredFallbackFnKey = ensureObservedVariantFallbackFn(jsxProp, stylexProp, (param) => buildObservedExpressionFallbackValueExpr({
32849
+ j,
32850
+ expression,
32851
+ jsxProp,
32852
+ paramName,
32853
+ param,
32854
+ prefix,
32855
+ suffix
32856
+ }), observedExpressionFallbackFnKey(jsxProp, conditionWhen));
32857
+ if (!ensuredFallbackFnKey) return false;
32858
+ if (!styleFnFromProps.some((entry) => entry.fnKey === ensuredFallbackFnKey && entry.jsxProp === jsxProp && entry.conditionWhen === conditionWhen)) styleFnFromProps.push({
32859
+ fnKey: ensuredFallbackFnKey,
32860
+ jsxProp,
32861
+ conditionWhen
32862
+ });
32863
+ for (const { propValue, cssValue } of transformedValues) applyVariant({
32864
+ when: `${conditionWhen} && ${jsxProp} === ${typeof propValue === "number" ? String(propValue) : JSON.stringify(propValue)}`,
32865
+ propName: jsxProp,
32866
+ allPropNames: [conditionProp, jsxProp]
32867
+ }, { [stylexProp]: cssValue });
32868
+ markStyleValueVariantProp(jsxProp);
32869
+ ensureObservedVariantPropDrop(jsxProp);
30921
32870
  return true;
30922
32871
  };
30923
- const ensureObservedVariantFallbackFn = (jsxProp, stylexProp, staticParts) => {
32872
+ const observedExpressionFallbackFnKey = (jsxProp, conditionWhen) => {
30924
32873
  const normalizedJsxProp = jsxProp.startsWith("$") ? jsxProp.slice(1) : jsxProp;
30925
- const fnKey = styleKeyWithSuffix(decl.styleKey, normalizedJsxProp);
32874
+ const baseFnKey = styleKeyWithSuffix(decl.styleKey, normalizedJsxProp);
32875
+ const existingForCondition = styleFnFromProps.find((entry) => entry.jsxProp === jsxProp && entry.conditionWhen === conditionWhen);
32876
+ if (existingForCondition) return existingForCondition.fnKey;
32877
+ return styleFnFromProps.some((entry) => entry.fnKey === baseFnKey && entry.jsxProp === jsxProp && entry.conditionWhen !== conditionWhen) ? styleKeyWithSuffix(baseFnKey, conditionWhen) : baseFnKey;
32878
+ };
32879
+ const ensureObservedVariantPropDrop = (jsxProp) => {
32880
+ if (jsxProp.startsWith("$") || decl.base.kind !== "component") ensureShouldForwardPropDrop(decl, jsxProp);
32881
+ };
32882
+ const markStyleValueVariantProp = (jsxProp) => {
32883
+ decl.styleValueVariantProps ??= /* @__PURE__ */ new Set();
32884
+ decl.styleValueVariantProps.add(jsxProp);
32885
+ };
32886
+ const ensureObservedVariantFallbackFn = (jsxProp, stylexProp, buildValueExpr, fnKeyOverride) => {
32887
+ const normalizedJsxProp = jsxProp.startsWith("$") ? jsxProp.slice(1) : jsxProp;
32888
+ const fnKey = fnKeyOverride ?? styleKeyWithSuffix(decl.styleKey, normalizedJsxProp);
30926
32889
  const paramName = cssPropertyToIdentifier(normalizedJsxProp || stylexProp, avoidNames);
30927
- const valueExpr = buildRuntimeObservedValueExpr(j, stylexProp, j.identifier(paramName), staticParts);
32890
+ const valueExpr = buildValueExpr(j.identifier(paramName), paramName);
32891
+ if (!valueExpr) return null;
30928
32892
  const property = j.property("init", makeCssPropKey(j, stylexProp), valueExpr);
30929
32893
  const existing = styleFnDecls.get(fnKey);
30930
32894
  if (existing?.type === "ArrowFunctionExpression" && existing.body?.type === "ObjectExpression") {
@@ -32071,15 +34035,27 @@ function handleInterpolatedDeclaration(args) {
32071
34035
  continue;
32072
34036
  }
32073
34037
  if (res && res.type === "splitConditionalWithDynamicBranch") if (!d.property) {} else {
32074
- const { conditionProp, staticValue, dynamicBranchExpr, dynamicProps, isStaticWhenFalse } = res;
34038
+ const { conditionProp, staticValue, dynamicBranchExpr, paramName, dynamicProps, isStaticWhenFalse } = res;
32075
34039
  const { prefix, suffix } = extractStaticPartsForDecl(d);
32076
34040
  const cssValueStr = `${prefix}${staticValue}${suffix}`;
32077
34041
  for (const out of cssDeclarationToStylexDeclarations(d)) styleObj[out.prop] = cssValueStr;
34042
+ const conditionWhen = isStaticWhenFalse ? conditionProp : `!${conditionProp}`;
32078
34043
  const clonedDynamic = cloneAstNode(dynamicBranchExpr);
32079
34044
  const dynamicValueExpr = prefix || suffix ? buildTemplateWithStaticParts(j, clonedDynamic, prefix, suffix) : clonedDynamic;
34045
+ const existingBucket = variantBuckets.get(conditionProp);
34046
+ if (!existingBucket && dynamicProps.length === 1) {
34047
+ const out = cssDeclarationToStylexDeclarations(d)[0];
34048
+ const dynamicProp = dynamicProps[0];
34049
+ if (out && dynamicProp && tryEmitObservedExpressionVariantBuckets(dynamicProp, out.prop, clonedDynamic, paramName, conditionWhen, conditionProp, prefix, suffix)) {
34050
+ ensureShouldForwardPropDrop(decl, conditionProp);
34051
+ decl.observedExpressionConditionDropProps ??= /* @__PURE__ */ new Set();
34052
+ decl.observedExpressionConditionDropProps.add(conditionProp);
34053
+ decl.needsWrapperComponent = true;
34054
+ continue;
34055
+ }
34056
+ }
32080
34057
  for (const propName of dynamicProps) ensureShouldForwardPropDrop(decl, propName);
32081
34058
  ensureShouldForwardPropDrop(decl, conditionProp);
32082
- const conditionWhen = isStaticWhenFalse ? conditionProp : `!${conditionProp}`;
32083
34059
  const scalarDynamic = shouldUseScalarDynamicArgs(d.property, d.valueRaw) && dynamicProps.length > 0 ? scalarizePropsObjectDynamicValue({
32084
34060
  j,
32085
34061
  valueExpr: dynamicValueExpr,
@@ -32094,7 +34070,6 @@ function handleInterpolatedDeclaration(args) {
32094
34070
  prop.shorthand = true;
32095
34071
  return prop;
32096
34072
  }));
32097
- const existingBucket = variantBuckets.get(conditionProp);
32098
34073
  if (existingBucket) {
32099
34074
  const existingFnKey = variantStyleKeys[conditionProp];
32100
34075
  if (!existingFnKey) break;
@@ -32344,134 +34319,132 @@ function handleInterpolatedDeclaration(args) {
32344
34319
  }
32345
34320
  if (res && res.type === "emitStyleFunction") {
32346
34321
  const jsxProp = res.call;
34322
+ const outs = cssDeclarationToStylexDeclarations(d);
34323
+ const valueTransform = res.valueTransform;
32347
34324
  if (!res.valueTransform && !res.wrapValueInTemplateLiteral && !media && (!pseudos || pseudos.length === 0)) {
32348
- const outs = cssDeclarationToStylexDeclarations(d);
32349
34325
  if (outs.length === 1 && tryEmitIdentityVariantBuckets(jsxProp, outs[0].prop)) continue;
32350
34326
  }
32351
- {
32352
- const outs = cssDeclarationToStylexDeclarations(d);
32353
- for (let i = 0; i < outs.length; i++) {
32354
- const out = outs[i];
32355
- const fnKey = styleKeyWithSuffix(decl.styleKey, out.prop);
32356
- const valueTransform = res.valueTransform;
32357
- const resolvedCallArg = buildResolvedValueTransformCallArg({
32358
- j,
32359
- jsxProp,
32360
- valueTransform,
32361
- parseExpr,
32362
- addResolverImports
32363
- });
32364
- const outParamName = resolvedCallArg || valueTransform ? cssPropertyToIdentifier(out.prop, avoidNames) : styleFnParamNameForJsxProp(jsxProp, out.prop, avoidNames);
32365
- const scalarCallArg = valueTransform ? void 0 : scalarCallArgForParamName(j, jsxProp, outParamName, decl.transientPropRenames?.get(jsxProp));
32366
- const callArg = resolvedCallArg ?? scalarCallArg;
32367
- const hasExplicitType = !!decl.propsType;
32368
- const isOptional = ctx.isJsxPropOptional(jsxProp);
32369
- styleFnFromProps.push({
32370
- fnKey,
32371
- jsxProp,
32372
- ...callArg ? { callArg } : {},
32373
- ...hasExplicitType && !isOptional ? { condition: "always" } : {}
32374
- });
32375
- if (!styleFnDecls.has(fnKey)) {
32376
- const param = j.identifier(outParamName);
32377
- const valueId = j.identifier(outParamName);
32378
- if (jsxProp !== "__props") annotateParamFromJsxProp(param, jsxProp);
32379
- if (resolvedCallArg && /\.(ts|tsx)$/.test(filePath)) param.typeAnnotation = j.tsTypeAnnotation(j.tsStringKeyword());
32380
- if (jsxProp?.startsWith?.("$")) ensureShouldForwardPropDrop(decl, jsxProp);
32381
- const buildValueExpr = () => {
32382
- const transformed = (() => {
32383
- const vt = callArg ? void 0 : valueTransform;
32384
- if (vt?.kind === "call" && typeof vt.calleeIdent === "string") {
32385
- addResolverImports(vt.resolvedImports);
32386
- if (vt.resolvedExpr) {
32387
- const resolvedCallee = parseExpr(vt.resolvedExpr);
32388
- if (vt.resolvedUsage === "memberAccess") return j.memberExpression(resolvedCallee, valueId, true);
32389
- return j.callExpression(resolvedCallee, [valueId]);
32390
- }
32391
- return j.callExpression(j.identifier(vt.calleeIdent), [valueId]);
34327
+ if (!res.wrapValueInTemplateLiteral && outs.length === 1 && tryEmitTransformedObservedVariantBuckets(jsxProp, outs[0].prop, valueTransform)) continue;
34328
+ for (let i = 0; i < outs.length; i++) {
34329
+ const out = outs[i];
34330
+ const fnKey = styleKeyWithSuffix(decl.styleKey, out.prop);
34331
+ const resolvedCallArg = buildResolvedValueTransformCallArg({
34332
+ j,
34333
+ jsxProp,
34334
+ valueTransform,
34335
+ parseExpr,
34336
+ addResolverImports
34337
+ });
34338
+ const outParamName = resolvedCallArg || valueTransform ? cssPropertyToIdentifier(out.prop, avoidNames) : styleFnParamNameForJsxProp(jsxProp, out.prop, avoidNames);
34339
+ const scalarCallArg = valueTransform ? void 0 : scalarCallArgForParamName(j, jsxProp, outParamName, decl.transientPropRenames?.get(jsxProp));
34340
+ const callArg = resolvedCallArg ?? scalarCallArg;
34341
+ const hasExplicitType = !!decl.propsType;
34342
+ const isOptional = ctx.isJsxPropOptional(jsxProp);
34343
+ styleFnFromProps.push({
34344
+ fnKey,
34345
+ jsxProp,
34346
+ ...callArg ? { callArg } : {},
34347
+ ...hasExplicitType && !isOptional ? { condition: "always" } : {}
34348
+ });
34349
+ if (!styleFnDecls.has(fnKey)) {
34350
+ const param = j.identifier(outParamName);
34351
+ const valueId = j.identifier(outParamName);
34352
+ if (jsxProp !== "__props") annotateParamFromJsxProp(param, jsxProp);
34353
+ if (resolvedCallArg && /\.(ts|tsx)$/.test(filePath)) param.typeAnnotation = j.tsTypeAnnotation(j.tsStringKeyword());
34354
+ if (jsxProp?.startsWith?.("$")) ensureShouldForwardPropDrop(decl, jsxProp);
34355
+ const buildValueExpr = () => {
34356
+ const transformed = (() => {
34357
+ const vt = callArg ? void 0 : valueTransform;
34358
+ if (vt?.kind === "call" && typeof vt.calleeIdent === "string") {
34359
+ addResolverImports(vt.resolvedImports);
34360
+ if (vt.resolvedExpr) {
34361
+ const resolvedCallee = parseExpr(vt.resolvedExpr);
34362
+ if (vt.resolvedUsage === "memberAccess") return j.memberExpression(resolvedCallee, valueId, true);
34363
+ return j.callExpression(resolvedCallee, [valueId]);
32392
34364
  }
32393
- return valueId;
32394
- })();
32395
- const transformedValue = !!res.wrapValueInTemplateLiteral ? j.templateLiteral([j.templateElement({
34365
+ return j.callExpression(j.identifier(vt.calleeIdent), [valueId]);
34366
+ }
34367
+ return valueId;
34368
+ })();
34369
+ const transformedValue = !!res.wrapValueInTemplateLiteral ? j.templateLiteral([j.templateElement({
34370
+ raw: "",
34371
+ cooked: ""
34372
+ }, false), j.templateElement({
34373
+ raw: "",
34374
+ cooked: ""
34375
+ }, true)], [transformed]) : transformed;
34376
+ const v = d.value;
34377
+ if (!v || v.kind !== "interpolated") return transformedValue;
34378
+ const parts = v.parts ?? [];
34379
+ const slotParts = parts.filter((p) => p?.kind === "slot");
34380
+ if (slotParts.length !== 1) return transformedValue;
34381
+ if (slotParts[0].slotId !== slotId) return transformedValue;
34382
+ if (!parts.some((p) => p?.kind === "static" && p.value !== "")) {
34383
+ if (shouldPreserveNumericCssTextForProp(jsxProp, out.prop)) return j.templateLiteral([j.templateElement({
32396
34384
  raw: "",
32397
34385
  cooked: ""
32398
34386
  }, false), j.templateElement({
32399
34387
  raw: "",
32400
34388
  cooked: ""
32401
- }, true)], [transformed]) : transformed;
32402
- const v = d.value;
32403
- if (!v || v.kind !== "interpolated") return transformedValue;
32404
- const parts = v.parts ?? [];
32405
- const slotParts = parts.filter((p) => p?.kind === "slot");
32406
- if (slotParts.length !== 1) return transformedValue;
32407
- if (slotParts[0].slotId !== slotId) return transformedValue;
32408
- if (!parts.some((p) => p?.kind === "static" && p.value !== "")) {
32409
- if (shouldPreserveNumericCssTextForProp(jsxProp, out.prop)) return j.templateLiteral([j.templateElement({
32410
- raw: "",
32411
- cooked: ""
32412
- }, false), j.templateElement({
32413
- raw: "",
32414
- cooked: ""
32415
- }, true)], [transformed]);
32416
- return transformedValue;
34389
+ }, true)], [transformed]);
34390
+ return transformedValue;
34391
+ }
34392
+ const quasis = [];
34393
+ const exprs = [];
34394
+ let q = "";
34395
+ for (const part of parts) {
34396
+ if (part?.kind === "static") {
34397
+ q += String(part.value ?? "");
34398
+ continue;
32417
34399
  }
32418
- const quasis = [];
32419
- const exprs = [];
32420
- let q = "";
32421
- for (const part of parts) {
32422
- if (part?.kind === "static") {
32423
- q += String(part.value ?? "");
32424
- continue;
32425
- }
32426
- if (part?.kind === "slot") {
32427
- quasis.push(j.templateElement({
32428
- raw: q,
32429
- cooked: q
32430
- }, false));
32431
- q = "";
32432
- exprs.push(transformed);
32433
- continue;
32434
- }
34400
+ if (part?.kind === "slot") {
34401
+ quasis.push(j.templateElement({
34402
+ raw: q,
34403
+ cooked: q
34404
+ }, false));
34405
+ q = "";
34406
+ exprs.push(transformed);
34407
+ continue;
32435
34408
  }
32436
- quasis.push(j.templateElement({
32437
- raw: q,
32438
- cooked: q
32439
- }, true));
32440
- return j.templateLiteral(quasis, exprs);
32441
- };
32442
- const valueExpr = buildValueExpr();
32443
- const getPropValue = () => {
32444
- if (!media) return valueExpr;
32445
- const existingFn = styleFnDecls.get(fnKey);
32446
- let existingValue = null;
32447
- if (existingFn?.type === "ArrowFunctionExpression") {
32448
- const body = existingFn.body;
32449
- if (body?.type === "ObjectExpression") {
32450
- const prop = body.properties.find((propNode) => {
32451
- if (!propNode || typeof propNode !== "object") return false;
32452
- if (propNode.type !== "Property") return false;
32453
- const key = propNode.key;
32454
- if (!key || typeof key !== "object") return false;
32455
- const keyType = key.type;
32456
- if (keyType === "Identifier") return key.name === out.prop;
32457
- if (keyType === "Literal") return key.value === out.prop;
32458
- return false;
32459
- });
32460
- if (prop && prop.type === "Property") existingValue = prop.value;
32461
- }
34409
+ }
34410
+ quasis.push(j.templateElement({
34411
+ raw: q,
34412
+ cooked: q
34413
+ }, true));
34414
+ return j.templateLiteral(quasis, exprs);
34415
+ };
34416
+ const valueExpr = buildValueExpr();
34417
+ const getPropValue = () => {
34418
+ if (!media) return valueExpr;
34419
+ const existingFn = styleFnDecls.get(fnKey);
34420
+ let existingValue = null;
34421
+ if (existingFn?.type === "ArrowFunctionExpression") {
34422
+ const body = existingFn.body;
34423
+ if (body?.type === "ObjectExpression") {
34424
+ const prop = body.properties.find((propNode) => {
34425
+ if (!propNode || typeof propNode !== "object") return false;
34426
+ if (propNode.type !== "Property") return false;
34427
+ const key = propNode.key;
34428
+ if (!key || typeof key !== "object") return false;
34429
+ const keyType = key.type;
34430
+ if (keyType === "Identifier") return key.name === out.prop;
34431
+ if (keyType === "Literal") return key.value === out.prop;
34432
+ return false;
34433
+ });
34434
+ if (prop && prop.type === "Property") existingValue = prop.value;
32462
34435
  }
32463
- const defaultValue = existingValue ?? j.literal(null);
32464
- return j.objectExpression([j.property("init", j.identifier("default"), defaultValue), j.property("init", j.literal(media), valueExpr)]);
32465
- };
32466
- const propKey = makeCssPropKey(j, out.prop);
32467
- const p = j.property("init", propKey, getPropValue());
32468
- const paramName = outParamName;
32469
- p.shorthand = propKey.type === "Identifier" && valueExpr?.type === "Identifier" && valueExpr.name === paramName;
32470
- const body = j.objectExpression([p]);
32471
- styleFnDecls.set(fnKey, j.arrowFunctionExpression([param], body));
32472
- }
32473
- if (i === 0) {}
34436
+ }
34437
+ const defaultValue = existingValue ?? j.literal(null);
34438
+ return j.objectExpression([j.property("init", j.identifier("default"), defaultValue), j.property("init", j.literal(media), valueExpr)]);
34439
+ };
34440
+ const propKey = makeCssPropKey(j, out.prop);
34441
+ const p = j.property("init", propKey, getPropValue());
34442
+ const paramName = outParamName;
34443
+ p.shorthand = propKey.type === "Identifier" && valueExpr?.type === "Identifier" && valueExpr.name === paramName;
34444
+ const body = j.objectExpression([p]);
34445
+ styleFnDecls.set(fnKey, j.arrowFunctionExpression([param], body));
32474
34446
  }
34447
+ if (i === 0) {}
32475
34448
  }
32476
34449
  continue;
32477
34450
  }
@@ -32824,9 +34797,40 @@ function isUnchangedImportedHelperStyleCall(res, exprAst, originalExpr) {
32824
34797
  const resolveResult = res.resolveCallResult;
32825
34798
  const resolveContext = res.resolveCallContext;
32826
34799
  const typedResult = resolveResult && typeof resolveResult === "object" ? resolveResult : null;
32827
- if (!typedResult || !resolveContext || typedResult.cssText || (typedResult.imports?.length ?? 0) > 0) return false;
34800
+ if (!typedResult || !resolveContext || typedResult.cssText) return false;
32828
34801
  if (!isCallExpressionLike(exprAst) || !isCallExpressionLike(originalExpr)) return false;
32829
- return calleeKey(exprAst.callee) === calleeKey(originalExpr.callee);
34802
+ if (calleeKey(exprAst.callee) !== calleeKey(originalExpr.callee)) return false;
34803
+ return !redirectsOriginalCalleeToDifferentSource(res, resolveContext);
34804
+ }
34805
+ function redirectsOriginalCalleeToDifferentSource(res, resolveContext) {
34806
+ const matchingImport = (res.imports ?? (res.resolveCallResult && typeof res.resolveCallResult === "object" ? res.resolveCallResult.imports : void 0) ?? []).find((importSpec) => importSpec.names.some((name) => name.imported === resolveContext.calleeImportedName || name.local === resolveContext.calleeImportedName));
34807
+ return Boolean(matchingImport && !sourcesReferToSameImport(matchingImport.from, resolveContext));
34808
+ }
34809
+ function sourcesReferToSameImport(left, resolveContext) {
34810
+ const right = resolveContext.calleeSource;
34811
+ if (left.value === right.value) return true;
34812
+ return specifierMatchesAbsolutePath(left, right, resolveContext.callSiteFilePath) || specifierMatchesAbsolutePath(right, left, resolveContext.callSiteFilePath);
34813
+ }
34814
+ function specifierMatchesAbsolutePath(maybeSpecifier, maybeAbsolute, callSiteFilePath) {
34815
+ if (maybeSpecifier.kind !== "specifier" || maybeAbsolute.kind !== "absolutePath") return false;
34816
+ const specifier = maybeSpecifier.value.replace(/\\/g, "/");
34817
+ if (!isRelativeSpecifier(specifier)) return false;
34818
+ const resolvedSpecifier = resolve(dirname(callSiteFilePath), specifier).replace(/\\/g, "/");
34819
+ const absolutePath = maybeAbsolute.value.replace(/\\/g, "/");
34820
+ return importPathCandidates(resolvedSpecifier).some((candidate) => absolutePath === candidate);
34821
+ }
34822
+ function importPathCandidates(resolvedSpecifier) {
34823
+ return [
34824
+ "",
34825
+ ".ts",
34826
+ ".tsx",
34827
+ ".js",
34828
+ ".jsx",
34829
+ ".mts",
34830
+ ".mjs",
34831
+ ".cts",
34832
+ ".cjs"
34833
+ ].flatMap((extension) => [`${resolvedSpecifier}${extension}`, `${resolvedSpecifier}/index${extension}`]);
32830
34834
  }
32831
34835
  function isCallExpressionLike(node) {
32832
34836
  return !!node && typeof node === "object" && node.type === "CallExpression";
@@ -32855,6 +34859,28 @@ function buildRuntimeObservedValueExpr(j, stylexProp, valueExpr, staticParts) {
32855
34859
  cooked: staticParts.suffix
32856
34860
  }, true)], [valueExpr]);
32857
34861
  }
34862
+ function buildObservedExpressionFallbackValueExpr(args) {
34863
+ const { j, expression, jsxProp, paramName, param, prefix, suffix } = args;
34864
+ const propNames = new Set([jsxProp, jsxProp.startsWith("$") ? jsxProp.slice(1) : jsxProp]);
34865
+ let replaced = false;
34866
+ const rewritten = mapAst(cloneAstNode(expression), (node) => {
34867
+ if (isMemberExpression(node)) {
34868
+ const memberPath = extractRootAndPath(node);
34869
+ const propName = memberPath?.path[0];
34870
+ if (memberPath?.rootName === paramName && memberPath.path.length === 1 && propName && propNames.has(propName)) {
34871
+ replaced = true;
34872
+ return cloneAstNode(param);
34873
+ }
34874
+ return;
34875
+ }
34876
+ if (node.type === "Identifier" && propNames.has(node.name)) {
34877
+ replaced = true;
34878
+ return cloneAstNode(param);
34879
+ }
34880
+ });
34881
+ if (!replaced) return null;
34882
+ return prefix || suffix ? buildTemplateWithStaticParts(j, rewritten, prefix, suffix) : rewritten;
34883
+ }
32858
34884
  function isNumberLikeTsType(tsType) {
32859
34885
  if (!tsType || typeof tsType !== "object") return false;
32860
34886
  const type = tsType;
@@ -33808,6 +35834,9 @@ function resolveExpressionToStaticString(expr, state) {
33808
35834
  const direct = literalToStaticValue(expr);
33809
35835
  if (typeof direct === "string") return direct;
33810
35836
  if (!isIdentifierNode(expr)) return null;
35837
+ const scoped = resolveScopedConstStringInit(expr, state);
35838
+ if (scoped?.kind === "found") return scoped.value;
35839
+ if (scoped?.kind === "blocked") return null;
33811
35840
  if (state.isIdentifierShadowed(expr, expr.name)) return null;
33812
35841
  const fromImport = resolveImportedConstStringInit(expr.name, state);
33813
35842
  if (fromImport !== null) return fromImport;
@@ -34004,6 +36033,203 @@ function findTopLevelConstStringInit(name, state) {
34004
36033
  });
34005
36034
  return resolved;
34006
36035
  }
36036
+ function resolveScopedConstStringInit(expr, state) {
36037
+ const identPath = findIdentifierPath(expr, state);
36038
+ const exprStart = getNodeStart(expr);
36039
+ if (!identPath || exprStart === null) return null;
36040
+ const ancestorScopes = getAncestorScopeNodes(identPath);
36041
+ let best = null;
36042
+ state.root.find(state.j.VariableDeclarator).forEach((p) => {
36043
+ const declarator = p.node;
36044
+ if (declarator.id?.type !== "Identifier" || declarator.id.name !== expr.name) return;
36045
+ const start = getNodeStart(declarator);
36046
+ if (start === null || start >= exprStart) return;
36047
+ const path = p;
36048
+ const scopeNode = getDeclarationScopeNode(path, getVariableDeclarationKind(path));
36049
+ if (!scopeNode || !ancestorScopes.has(scopeNode)) return;
36050
+ if (isProgramNode(scopeNode) || hasInnerBindingBetween(identPath, scopeNode, expr.name)) return;
36051
+ const value = getVariableDeclarationKind(path) === "const" ? literalToStaticValue(declarator.init) : null;
36052
+ const candidate = {
36053
+ start,
36054
+ value: typeof value === "string" ? value : null
36055
+ };
36056
+ if (!best || candidate.start > best.start) best = candidate;
36057
+ });
36058
+ const resolved = best;
36059
+ if (!resolved) return null;
36060
+ return resolved.value === null ? { kind: "blocked" } : {
36061
+ kind: "found",
36062
+ value: resolved.value
36063
+ };
36064
+ }
36065
+ function findIdentifierPath(expr, state) {
36066
+ return state.root.find(state.j.Identifier).filter((p) => p.node === expr).paths()[0] ?? null;
36067
+ }
36068
+ function getNodeStart(node) {
36069
+ const start = node.start;
36070
+ return typeof start === "number" ? start : null;
36071
+ }
36072
+ function getAncestorScopeNodes(path) {
36073
+ const scopes = /* @__PURE__ */ new Set();
36074
+ let cur = path;
36075
+ while (cur) {
36076
+ if (isScopeNode(cur.node)) scopes.add(cur.node);
36077
+ cur = cur.parentPath ?? null;
36078
+ }
36079
+ return scopes;
36080
+ }
36081
+ function getDeclarationScopeNode(path, declarationKind) {
36082
+ const declarationParent = path.parentPath?.parentPath;
36083
+ if (declarationKind !== "var" && declarationParent && isLoopNode(declarationParent.node)) return declarationParent.node;
36084
+ let cur = path.parentPath;
36085
+ while (cur) {
36086
+ if (declarationKind === "var" && isFunctionOrProgramNode(cur.node)) return cur.node;
36087
+ if (declarationKind !== "var" && isLoopNode(cur.node)) return cur.node;
36088
+ if (declarationKind !== "var" && isScopeNode(cur.node)) return cur.node;
36089
+ cur = cur.parentPath ?? null;
36090
+ }
36091
+ return null;
36092
+ }
36093
+ function hasInnerBindingBetween(identPath, outerScopeNode, name) {
36094
+ let cur = identPath.parentPath;
36095
+ while (cur && cur.node !== outerScopeNode) {
36096
+ if (isFunctionNode(cur.node) && functionDeclaresName(cur.node, name)) return true;
36097
+ if (isCatchClauseNode(cur.node) && catchClauseDeclaresName(cur.node, name)) return true;
36098
+ if (isBlockStatementNode(cur.node) && blockDeclaresName(cur.node, name)) return true;
36099
+ if (isSwitchStatementNode(cur.node) && switchStatementDeclaresName(cur.node, name)) return true;
36100
+ if (isLoopNode(cur.node) && loopDeclaresName(cur.node, name)) return true;
36101
+ cur = cur.parentPath ?? null;
36102
+ }
36103
+ return false;
36104
+ }
36105
+ function functionDeclaresName(node, name) {
36106
+ const fn = node;
36107
+ const ids = /* @__PURE__ */ new Set();
36108
+ collectPatternIdentifiers(fn.id, ids);
36109
+ for (const param of fn.params ?? []) collectPatternIdentifiers(param, ids);
36110
+ collectFunctionVarBindings(node, ids);
36111
+ return ids.has(name);
36112
+ }
36113
+ function collectFunctionVarBindings(node, out) {
36114
+ const visit = (current, isRoot = false) => {
36115
+ if (!current || typeof current !== "object") return;
36116
+ if (Array.isArray(current)) {
36117
+ for (const child of current) visit(child);
36118
+ return;
36119
+ }
36120
+ if (!isRoot && isFunctionNode(current)) return;
36121
+ const astNode = current;
36122
+ if (astNode.type === "VariableDeclaration" && astNode.kind === "var") {
36123
+ for (const declarator of astNode.declarations ?? []) collectPatternIdentifiers(declarator.id, out);
36124
+ return;
36125
+ }
36126
+ for (const key of Object.keys(astNode)) {
36127
+ if (key === "loc" || key === "comments") continue;
36128
+ visit(astNode[key]);
36129
+ }
36130
+ };
36131
+ visit(node, true);
36132
+ }
36133
+ function catchClauseDeclaresName(node, name) {
36134
+ const catchClause = node;
36135
+ const ids = /* @__PURE__ */ new Set();
36136
+ collectPatternIdentifiers(catchClause.param, ids);
36137
+ return ids.has(name);
36138
+ }
36139
+ function blockDeclaresName(node, name) {
36140
+ const block = node;
36141
+ for (const statement of block.body ?? []) {
36142
+ if (!statement || typeof statement !== "object") continue;
36143
+ const stmt = statement;
36144
+ if (stmt.type === "VariableDeclaration" && (stmt.kind === "let" || stmt.kind === "const")) for (const declarator of stmt.declarations ?? []) {
36145
+ const ids = /* @__PURE__ */ new Set();
36146
+ collectPatternIdentifiers(declarator.id, ids);
36147
+ if (ids.has(name)) return true;
36148
+ }
36149
+ if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
36150
+ const ids = /* @__PURE__ */ new Set();
36151
+ collectPatternIdentifiers(stmt.id, ids);
36152
+ if (ids.has(name)) return true;
36153
+ }
36154
+ }
36155
+ return false;
36156
+ }
36157
+ function switchStatementDeclaresName(node, name) {
36158
+ const switchStatement = node;
36159
+ for (const switchCase of switchStatement.cases ?? []) if (blockDeclaresName({ body: switchCase.consequent ?? [] }, name)) return true;
36160
+ return false;
36161
+ }
36162
+ function loopDeclaresName(node, name) {
36163
+ const loop = node;
36164
+ const binding = loop.init ?? loop.left;
36165
+ if (!binding || typeof binding !== "object") return false;
36166
+ const declaration = binding;
36167
+ if (declaration.type !== "VariableDeclaration" || declaration.kind !== "let" && declaration.kind !== "const") return false;
36168
+ for (const declarator of declaration.declarations ?? []) {
36169
+ const ids = /* @__PURE__ */ new Set();
36170
+ collectPatternIdentifiers(declarator.id, ids);
36171
+ if (ids.has(name)) return true;
36172
+ }
36173
+ return false;
36174
+ }
36175
+ function collectPatternIdentifiers(pattern, out) {
36176
+ if (!pattern || typeof pattern !== "object") return;
36177
+ const node = pattern;
36178
+ switch (node.type) {
36179
+ case "Identifier":
36180
+ if (node.name) out.add(node.name);
36181
+ return;
36182
+ case "RestElement":
36183
+ collectPatternIdentifiers(node.argument, out);
36184
+ return;
36185
+ case "AssignmentPattern":
36186
+ collectPatternIdentifiers(node.left, out);
36187
+ return;
36188
+ case "ObjectPattern":
36189
+ for (const prop of node.properties ?? []) {
36190
+ const property = prop;
36191
+ collectPatternIdentifiers(property?.type === "RestElement" ? property.argument : property?.value, out);
36192
+ }
36193
+ return;
36194
+ case "ArrayPattern":
36195
+ for (const element of node.elements ?? []) collectPatternIdentifiers(element, out);
36196
+ return;
36197
+ case "TSParameterProperty":
36198
+ collectPatternIdentifiers(node.parameter, out);
36199
+ return;
36200
+ default: return;
36201
+ }
36202
+ }
36203
+ function getVariableDeclarationKind(path) {
36204
+ const parentNode = path.parentPath?.node;
36205
+ return parentNode?.type === "VariableDeclaration" && typeof parentNode.kind === "string" ? parentNode.kind : null;
36206
+ }
36207
+ function isScopeNode(node) {
36208
+ return isProgramNode(node) || isBlockStatementNode(node);
36209
+ }
36210
+ function isProgramNode(node) {
36211
+ return node.type === "Program";
36212
+ }
36213
+ function isFunctionOrProgramNode(node) {
36214
+ return isProgramNode(node) || isFunctionNode(node);
36215
+ }
36216
+ function isFunctionNode(node) {
36217
+ const type = node.type;
36218
+ return type === "FunctionDeclaration" || type === "FunctionExpression" || type === "ArrowFunctionExpression";
36219
+ }
36220
+ function isCatchClauseNode(node) {
36221
+ return node.type === "CatchClause";
36222
+ }
36223
+ function isBlockStatementNode(node) {
36224
+ return node.type === "BlockStatement";
36225
+ }
36226
+ function isSwitchStatementNode(node) {
36227
+ return node.type === "SwitchStatement";
36228
+ }
36229
+ function isLoopNode(node) {
36230
+ const type = node.type;
36231
+ return type === "ForStatement" || type === "ForInStatement" || type === "ForOfStatement";
36232
+ }
34007
36233
  /**
34008
36234
  * Tries to follow re-exports for `<exportedName>` from `<program>`:
34009
36235
  * - `export { exportedName } from "./other"` (direct)
@@ -34190,6 +36416,12 @@ function processRuleDeclarations(args) {
34190
36416
  state.bail = true;
34191
36417
  break;
34192
36418
  }
36419
+ if (d.property && isUnsupportedStylexProperty(d.property)) {
36420
+ state.bailUnsupported(ctx.decl, `Unsupported CSS property "${d.property}" cannot be emitted in StyleX`);
36421
+ if (state.currentDecl === ctx.decl) break;
36422
+ state.bail = true;
36423
+ break;
36424
+ }
34193
36425
  const outs = cssDeclarationToStylexDeclarations(d);
34194
36426
  for (let i = 0; i < outs.length; i++) {
34195
36427
  const out = outs[i];
@@ -34343,6 +36575,15 @@ function processDeclRules(ctx) {
34343
36575
  });
34344
36576
  break;
34345
36577
  }
36578
+ if (specificityResult.wasStripped && decl.base.kind === "component") {
36579
+ state.markBail();
36580
+ warnings.push({
36581
+ severity: "warning",
36582
+ type: "Styled-components specificity hacks like `&&` / `&&&` are not representable in StyleX",
36583
+ loc: computeSelectorWarningLoc(decl.loc, decl.rawCss, rule.selector)
36584
+ });
36585
+ break;
36586
+ }
34346
36587
  const selectorForAnalysis = specificityResult.normalized;
34347
36588
  const s = normalizeInterpolatedSelector(selectorForAnalysis).trim();
34348
36589
  const hasComponentExpr = rule.selector.includes("__SC_EXPR_");
@@ -34722,7 +36963,7 @@ function processDeclRules(ctx) {
34722
36963
  state.markBail();
34723
36964
  warnings.push({
34724
36965
  severity: "warning",
34725
- type: "CSS block contains unsupported at-rule (only @media and @container are supported; @supports, etc. require manual handling)",
36966
+ type: "CSS block contains unsupported at-rule (only @media, @container, and @supports are supported; mixed nested at-rules require manual handling)",
34726
36967
  loc: computeSelectorWarningLoc(decl.loc, decl.rawCss, rule.selector)
34727
36968
  });
34728
36969
  break;
@@ -34903,22 +37144,38 @@ function processDeclRules(ctx) {
34903
37144
  }
34904
37145
  if (prop && prop.startsWith("--") && typeof value === "string") localVarValues.set(prop, value);
34905
37146
  if (media && pseudos?.length) {
34906
- perPropPseudo[prop] ??= {};
34907
- const existing = perPropPseudo[prop];
34908
- noteSourceCssProperty(existing);
34909
- if (!("default" in existing)) {
34910
- const existingVal = styleObj[prop];
34911
- if (existingVal !== void 0) existing.default = existingVal;
34912
- else if (cssHelperPropValues.has(prop)) existing.default = getComposedDefaultValue(prop);
34913
- else existing.default = null;
34914
- }
34915
- for (const ps of pseudos) {
34916
- const current = existing[ps];
34917
- if (!current || typeof current !== "object") {
34918
- const fallbackDefault = cssHelperPropValues.has(prop) ? getComposedDefaultValue(prop) : null;
34919
- existing[ps] = { default: current !== void 0 ? current : fallbackDefault };
34920
- } else if (!("default" in current)) current.default = cssHelperPropValues.has(prop) ? getComposedDefaultValue(prop) : null;
34921
- existing[ps][media] = value;
37147
+ if (media.startsWith("@supports")) {
37148
+ perPropMedia[prop] ??= {};
37149
+ const existing = perPropMedia[prop];
37150
+ noteSourceCssProperty(existing);
37151
+ if (!("default" in existing)) {
37152
+ const existingVal = styleObj[prop];
37153
+ if (existingVal !== void 0) existing.default = existingVal;
37154
+ else if (cssHelperPropValues.has(prop)) existing.default = getComposedDefaultValue(prop);
37155
+ else existing.default = null;
37156
+ }
37157
+ const current = existing[media];
37158
+ const mediaMap = current && typeof current === "object" && !Array.isArray(current) && !isAstNode(current) ? current : { default: current ?? null };
37159
+ for (const ps of pseudos) mediaMap[ps] = value;
37160
+ existing[media] = mediaMap;
37161
+ } else {
37162
+ perPropPseudo[prop] ??= {};
37163
+ const existing = perPropPseudo[prop];
37164
+ noteSourceCssProperty(existing);
37165
+ if (!("default" in existing)) {
37166
+ const existingVal = styleObj[prop];
37167
+ if (existingVal !== void 0) existing.default = existingVal;
37168
+ else if (cssHelperPropValues.has(prop)) existing.default = getComposedDefaultValue(prop);
37169
+ else existing.default = null;
37170
+ }
37171
+ for (const ps of pseudos) {
37172
+ const current = existing[ps];
37173
+ if (!current || typeof current !== "object") {
37174
+ const fallbackDefault = cssHelperPropValues.has(prop) ? getComposedDefaultValue(prop) : null;
37175
+ existing[ps] = { default: current !== void 0 ? current : fallbackDefault };
37176
+ } else if (!("default" in current)) current.default = cssHelperPropValues.has(prop) ? getComposedDefaultValue(prop) : null;
37177
+ existing[ps][media] = value;
37178
+ }
34922
37179
  }
34923
37180
  return;
34924
37181
  }
@@ -34997,7 +37254,9 @@ function processDeclRules(ctx) {
34997
37254
  else if (cssHelperPropValues.has(prop)) existing.default = getComposedDefaultValue(prop);
34998
37255
  else existing.default = null;
34999
37256
  }
35000
- existing[media] = value;
37257
+ const currentMediaValue = existing[media];
37258
+ if (currentMediaValue && typeof currentMediaValue === "object" && !Array.isArray(currentMediaValue) && !isAstNode(currentMediaValue)) currentMediaValue.default = value;
37259
+ else existing[media] = value;
35001
37260
  patchEarlierDynamicConditionValues(prop, media, value);
35002
37261
  return;
35003
37262
  }
@@ -35436,7 +37695,7 @@ function handlePseudoExpand(result, importedName, rule, ctx, prefixPseudo) {
35436
37695
  const existing = target[pseudo];
35437
37696
  if (existing && typeof existing === "object" && "__computedKeys" in existing) existing.__computedKeys.push(newEntry);
35438
37697
  else target[pseudo] = {
35439
- default: null,
37698
+ default: target.default ?? null,
35440
37699
  __computedKeys: [newEntry]
35441
37700
  };
35442
37701
  } else target[pseudo] = cloneAstNode(value);
@@ -35706,6 +37965,15 @@ function registerReferencedMarker(styleKey, localName, state, ancestorSelectorPa
35706
37965
  function resolveMediaAndEmitComputedKeys(bucket, makeKeyExpr, rule, ctx, computedMediaWarningType, entryExtra) {
35707
37966
  const { state, decl } = ctx;
35708
37967
  const { warnings } = state;
37968
+ if (hasUnsupportedAtRule(rule.atRuleStack)) {
37969
+ state.markBail();
37970
+ warnings.push({
37971
+ severity: "warning",
37972
+ type: "CSS block contains unsupported at-rule (only @media, @container, and @supports are supported; mixed nested at-rules require manual handling)",
37973
+ loc: computeSelectorWarningLoc(decl.loc, decl.rawCss, rule.selector)
37974
+ });
37975
+ return "break";
37976
+ }
35709
37977
  let media = findSupportedAtRule(rule.atRuleStack);
35710
37978
  if (media) {
35711
37979
  const resolved = resolveMediaAtRulePlaceholders(media, (slotId) => decl.templateExpressions[slotId], {
@@ -35806,6 +38074,15 @@ function handleAdjacentSiblingSelector(rule, ctx) {
35806
38074
  });
35807
38075
  return "break";
35808
38076
  }
38077
+ if (hasUnsupportedAtRule(rule.atRuleStack)) {
38078
+ state.markBail();
38079
+ state.warnings.push({
38080
+ severity: "warning",
38081
+ type: "CSS block contains unsupported at-rule (only @media, @container, and @supports are supported; mixed nested at-rules require manual handling)",
38082
+ loc: computeSelectorWarningLoc(decl.loc, decl.rawCss, rule.selector)
38083
+ });
38084
+ return "break";
38085
+ }
35809
38086
  let media = findSupportedAtRule(rule.atRuleStack);
35810
38087
  if (media) {
35811
38088
  const resolved = resolveMediaAtRulePlaceholders(media, (slotId) => decl.templateExpressions[slotId], {
@@ -36405,7 +38682,7 @@ function lowerRules(ctx) {
36405
38682
  }
36406
38683
  const snapshot = snapshotStateForDecl(state);
36407
38684
  state.currentDecl = decl;
36408
- const outcome = processOneDecl(state, decl);
38685
+ const outcome = processOneDecl(ctx, state, decl);
36409
38686
  state.currentDecl = null;
36410
38687
  if (outcome === "skip") {
36411
38688
  restoreStateSnapshot(state, snapshot);
@@ -36461,16 +38738,24 @@ function lowerRules(ctx) {
36461
38738
  * Returns `"skip"` if the decl marked itself skipped (per-decl bail), `"bail"` if
36462
38739
  * something set the file-level bail, or `"ok"` on success.
36463
38740
  */
36464
- function processOneDecl(state, decl) {
36465
- const declState = createDeclProcessingState(state, decl);
36466
- if (!preScanCssHelperPlaceholders(declState)) return decl.skipTransform ? "skip" : "bail";
36467
- processDeclRules(declState);
36468
- if (decl.skipTransform) return "skip";
36469
- if (state.bail) return "bail";
36470
- finalizeDeclProcessing(declState);
36471
- if (decl.skipTransform) return "skip";
36472
- if (state.bail) return "bail";
36473
- return "ok";
38741
+ function processOneDecl(ctx, state, decl) {
38742
+ const previousUseLogicalProperties = getUseLogicalProperties();
38743
+ const componentInterface = decl.base.kind === "component" ? wrappedComponentInterfaceFor(ctx, decl.base.ident) : void 0;
38744
+ const forcePhysicalDirectionalShorthands = componentInterface?.acceptsSx === true && componentInterface.sxExcludedProperties?.some((prop) => LOGICAL_TO_PHYSICAL[prop]) === true;
38745
+ if (forcePhysicalDirectionalShorthands) setUseLogicalProperties(false);
38746
+ try {
38747
+ const declState = createDeclProcessingState(state, decl);
38748
+ if (!preScanCssHelperPlaceholders(declState)) return decl.skipTransform ? "skip" : "bail";
38749
+ processDeclRules(declState);
38750
+ if (decl.skipTransform) return "skip";
38751
+ if (state.bail) return "bail";
38752
+ finalizeDeclProcessing(declState);
38753
+ if (decl.skipTransform) return "skip";
38754
+ if (state.bail) return "bail";
38755
+ return "ok";
38756
+ } finally {
38757
+ if (forcePhysicalDirectionalShorthands) setUseLogicalProperties(previousUseLogicalProperties);
38758
+ }
36474
38759
  }
36475
38760
  function markPartialImportedComponentRoots(ctx, state) {
36476
38761
  for (const decl of state.styledDecls) if (shouldSkipPartialImportedComponentRoot(ctx, decl)) decl.skipTransform = true;
@@ -36662,10 +38947,6 @@ function collectTemplateSelectorIdentifiers(decl) {
36662
38947
  }
36663
38948
  return identifiers;
36664
38949
  }
36665
- function isTemplatePlaceholderInSelectorContext(rawCss, pos, length) {
36666
- const after = rawCss.slice(pos + length).trimStart();
36667
- return isSelectorContext(rawCss.slice(0, pos).trimEnd().replace(PLACEHOLDER_RE_G, "hover"), after);
36668
- }
36669
38950
  function collectCssHelperFunctionSelectorIdentifiers(state, cssLocal) {
36670
38951
  const selectorIdentifiers = /* @__PURE__ */ new Map();
36671
38952
  for (const [name, helperFn] of state.cssHelperFunctions) selectorIdentifiers.set(name, collectTemplateSelectorIdentifiersFromParts(helperFn.rawCss, helperFn.templateExpressions));
@@ -38025,8 +40306,15 @@ function substituteStyleFnCallArg(callArg, propNames, valueExpr) {
38025
40306
  };
38026
40307
  return visit(cloneAstNode(callArg));
38027
40308
  }
38028
- function wrappedComponentAcceptsSxProp(ctx, componentLocalName) {
40309
+ function wrappedComponentAcceptsSxProp(ctx, componentLocalName, visiting = /* @__PURE__ */ new Set()) {
38029
40310
  if (!ctx.adapter.useSxProp) return false;
40311
+ if (visiting.has(componentLocalName)) return false;
40312
+ visiting.add(componentLocalName);
40313
+ const localStyledDecl = ctx.styledDecls?.find((decl) => decl.localName === componentLocalName);
40314
+ if (localStyledDecl?.needsWrapperComponent && localStyledDecl.base.kind === "component" && wrappedComponentAcceptsSxProp(ctx, localStyledDecl.base.ident, visiting)) {
40315
+ visiting.delete(componentLocalName);
40316
+ return true;
40317
+ }
38030
40318
  const importInfo = ctx.importMap?.get(componentLocalName);
38031
40319
  if (importInfo) {
38032
40320
  const adapterResult = ctx.adapter.wrappedComponentInterface?.({
@@ -38035,7 +40323,10 @@ function wrappedComponentAcceptsSxProp(ctx, componentLocalName) {
38035
40323
  importedName: importInfo.importedName,
38036
40324
  filePath: ctx.file.path
38037
40325
  });
38038
- if (adapterResult !== void 0) return adapterResult.acceptsSx === true;
40326
+ if (adapterResult !== void 0) {
40327
+ visiting.delete(componentLocalName);
40328
+ return adapterResult.acceptsSx === true;
40329
+ }
38039
40330
  }
38040
40331
  const typedComponent = (() => {
38041
40332
  if (importInfo?.source.kind === "absolutePath") {
@@ -38045,14 +40336,22 @@ function wrappedComponentAcceptsSxProp(ctx, componentLocalName) {
38045
40336
  return findTypeScriptComponentMetadata(ctx.options.crossFileInfo?.typeScriptMetadata, ctx.file.path, [componentLocalName]);
38046
40337
  })();
38047
40338
  if (typedComponent) {
38048
- if (typedComponent.supportsSxProp) return true;
38049
- if (importInfo?.source.kind !== "absolutePath" || ctx.options.transformedFileSources?.has(toRealPath(importInfo.source.value)) !== true) return false;
40339
+ if (typedComponent.supportsSxProp) {
40340
+ visiting.delete(componentLocalName);
40341
+ return true;
40342
+ }
40343
+ if (importInfo?.source.kind !== "absolutePath" || ctx.options.transformedFileSources?.has(resolveExistingFilePath(importInfo.source.value)) !== true) {
40344
+ visiting.delete(componentLocalName);
40345
+ return false;
40346
+ }
38050
40347
  }
38051
- return importInfo?.source.kind === "absolutePath" && transformedComponentAcceptsSx({
40348
+ const accepts = importInfo?.source.kind === "absolutePath" && transformedComponentAcceptsSx({
38052
40349
  absolutePath: importInfo.source.value,
38053
40350
  componentNames: importInfo.importedName === "default" ? [componentLocalName, importInfo.importedName] : [importInfo.importedName],
38054
40351
  sourceOverrides: ctx.options.transformedFileSources
38055
40352
  });
40353
+ visiting.delete(componentLocalName);
40354
+ return accepts;
38056
40355
  }
38057
40356
  /**
38058
40357
  * Rewrites JSX usages and removes styled declarations when wrappers are not required.
@@ -38400,15 +40699,16 @@ function rewriteJsxStep(ctx) {
38400
40699
  const hasRestSpreadAttr = keptRestAfterVariants.some((attr) => attr.type === "JSXSpreadAttribute");
38401
40700
  const needsMerge = effectiveClassNameAttr !== null || styleAttr !== null && !(staticInlineStyleExpr !== null && styleAttr !== null && effectiveClassNameAttr === null && !hasCallerStyleAttr && !hasRestSpreadAttr);
38402
40701
  const stylesId = ctx.stylesIdentifier ?? "styles";
38403
- const hasLocalStyleRef = styleArgs.some((arg) => j([arg]).find(j.Identifier, { name: stylesId }).size() > 0);
40702
+ const mergedStyleArgs = mergeAdjacentComplementaryStyleExprs(j, styleArgs);
40703
+ const hasLocalStyleRef = mergedStyleArgs.some((arg) => j([arg]).find(j.Identifier, { name: stylesId }).size() > 0);
38404
40704
  const useSxPropForWrapped = ctx.adapter.useSxProp && wrappedAcceptsSxProp && hasLocalStyleRef;
38405
40705
  const useSxProp = useSxPropForWrapped || ctx.adapter.useSxProp && !needsMerge && isIntrinsicTag && hasLocalStyleRef;
38406
40706
  const callerSxExpr = sxAttr && sxAttr.type === "JSXAttribute" && sxAttr.value?.type === "JSXExpressionContainer" ? sxAttr.value.expression : null;
38407
40707
  const stylexAttr = useSxProp ? (() => {
38408
- const allArgs = callerSxExpr ? [...styleArgs, callerSxExpr] : [...styleArgs];
40708
+ const allArgs = callerSxExpr ? [...mergedStyleArgs, callerSxExpr] : [...mergedStyleArgs];
38409
40709
  const sxExpr = allArgs.length === 1 && allArgs[0] ? allArgs[0] : j.arrayExpression(allArgs);
38410
40710
  return j.jsxAttribute(j.jsxIdentifier("sx"), j.jsxExpressionContainer(sxExpr));
38411
- })() : j.jsxSpreadAttribute(needsMerge ? buildInlineMergeCall(j, styleArgs, effectiveClassNameAttr, styleAttr, ctx.adapter.styleMerger?.functionName) : j.callExpression(j.memberExpression(j.identifier("stylex"), j.identifier("props")), [...styleArgs]));
40711
+ })() : j.jsxSpreadAttribute(needsMerge ? buildInlineMergeCall(j, mergedStyleArgs, effectiveClassNameAttr, styleAttr, ctx.adapter.styleMerger?.functionName) : j.callExpression(j.memberExpression(j.identifier("stylex"), j.identifier("props")), [...mergedStyleArgs]));
38412
40712
  const extraClassNameAttrs = [];
38413
40713
  if (extraClassNameExpr && useSxProp) extraClassNameAttrs.push(j.jsxAttribute(j.jsxIdentifier("className"), j.jsxExpressionContainer(extraClassNameExpr)));
38414
40714
  const passThroughClassName = useSxPropForWrapped && classNameAttr ? [classNameAttr] : [];