styled-components-to-stylex-codemod 0.0.46 → 0.0.48

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";
@@ -252,6 +251,21 @@ const STYLEX_STRING_ONLY_CSS_PROPS = new Set([
252
251
  "gridColumnEnd",
253
252
  "outlineOffset"
254
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
+ ]);
255
269
  /**
256
270
  * Returns true if the CSS property is a shorthand that StyleX cannot express directly
257
271
  * and requires expansion (e.g., `padding`, `margin`, `border`, `background`).
@@ -259,6 +273,9 @@ const STYLEX_STRING_ONLY_CSS_PROPS = new Set([
259
273
  function isCssShorthandProperty(cssProp) {
260
274
  return cssProp in DIRECTIONAL_SHORTHAND_MAP || cssProp === "border" || /^border-(top|right|bottom|left)$/.test(cssProp) || cssProp === "background";
261
275
  }
276
+ function isUnsupportedStylexProperty(cssProp) {
277
+ return UNSUPPORTED_STYLEX_CSS_PROPS.has(cssProp.trim());
278
+ }
262
279
  function isUnsupportedBackgroundShorthandValue(rawValue) {
263
280
  const value = rawValue.trim();
264
281
  return value !== "none" && !isSingleBackgroundComponent(value);
@@ -929,7 +946,7 @@ function isAstNode(v) {
929
946
  /**
930
947
  * Type guard for function-like nodes including class/object methods.
931
948
  */
932
- function isFunctionNode(node) {
949
+ function isFunctionNode$1(node) {
933
950
  if (!node || typeof node !== "object") return false;
934
951
  const type = node.type;
935
952
  return type === "FunctionDeclaration" || type === "FunctionExpression" || type === "ArrowFunctionExpression" || type === "ObjectMethod" || type === "ClassMethod";
@@ -951,7 +968,7 @@ function getDeclaratorId(decl) {
951
968
  function getArrowFnSingleParamName(fn) {
952
969
  if (fn.params.length !== 1) return null;
953
970
  const p = fn.params[0];
954
- return isIdentifier(p) ? p.name : null;
971
+ return isIdentifier$2(p) ? p.name : null;
955
972
  }
956
973
  /**
957
974
  * Extracts parameter binding information from an arrow function.
@@ -971,7 +988,7 @@ function getArrowFnSingleParamName(fn) {
971
988
  function getArrowFnParamBindings(fn) {
972
989
  if (fn.params.length !== 1) return null;
973
990
  const p = fn.params[0];
974
- if (isIdentifier(p)) return {
991
+ if (isIdentifier$2(p)) return {
975
992
  kind: "simple",
976
993
  paramName: p.name
977
994
  };
@@ -1130,6 +1147,7 @@ function collectIdentifiers(node, out) {
1130
1147
  * - Literal (ESTree/recast AST)
1131
1148
  * - TemplateLiteral without expressions (static template strings)
1132
1149
  * - TaggedTemplateExpression with css tag (styled-components css helper)
1150
+ * - TSAsExpression and TSSatisfiesExpression wrapping static values
1133
1151
  * - ArrowFunctionExpression with no params and a static body (e.g., `() => "value"` or `() => \`value\``)
1134
1152
  *
1135
1153
  * Returns null for non-literal or dynamic nodes.
@@ -1137,6 +1155,7 @@ function collectIdentifiers(node, out) {
1137
1155
  function literalToStaticValue(node) {
1138
1156
  if (!node || typeof node !== "object") return null;
1139
1157
  const type = node.type;
1158
+ if (type === "TSAsExpression" || type === "TSSatisfiesExpression") return literalToStaticValue(node.expression);
1140
1159
  if (type === "StringLiteral") return node.value;
1141
1160
  if (type === "BooleanLiteral") return node.value;
1142
1161
  if (type === "Literal") {
@@ -1420,7 +1439,7 @@ function buildStyleFnConditionExpr(args) {
1420
1439
  if (condition === "always" || isRequired) return call;
1421
1440
  return j.logicalExpression("&&", j.binaryExpression("!=", propExpr, j.nullLiteral()), call);
1422
1441
  }
1423
- function isIdentifier(node, name) {
1442
+ function isIdentifier$2(node, name) {
1424
1443
  return isIdentifierNode(node) && (name ? node.name === name : true);
1425
1444
  }
1426
1445
  function isJsxIdentifierNode(node) {
@@ -2397,6 +2416,17 @@ function hasInlineableStyleFnOnly(decl) {
2397
2416
  return true;
2398
2417
  }
2399
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
+ /**
2400
2430
  * Returns true if any JSX usage of a component has spread attributes
2401
2431
  * (e.g., `<Comp {...props} />`). The inline path can only consume explicit
2402
2432
  * JSX attributes, so spreads require a wrapper for prop extraction.
@@ -2575,8 +2605,76 @@ function typeContainsPolymorphicAs(args) {
2575
2605
  return visit(args.typeNode);
2576
2606
  }
2577
2607
  //#endregion
2608
+ //#region src/internal/utilities/typescript-metadata.ts
2609
+ function findTypeScriptComponentMetadata(metadata, filePath, componentNames) {
2610
+ if (!metadata) return;
2611
+ const names = new Set(componentNames);
2612
+ const resolvedFilePath = resolveExistingFilePath(filePath);
2613
+ return metadata.files.find((file) => file.filePath === resolvedFilePath)?.components.find((component) => names.has(component.name) || defaultExportMatches(component, names));
2614
+ }
2615
+ function applyTypeScriptMetadataToDecl(ctx, decl, names) {
2616
+ const typedComponent = findTypeScriptComponentMetadata(ctx.options.crossFileInfo?.typeScriptMetadata, ctx.file.path, names);
2617
+ if (!typedComponent) return;
2618
+ decl.typeScriptPropNames = new Set(typedComponent.props.map((prop) => prop.name));
2619
+ decl.typeScriptExplicitPropNames = new Set(typedComponent.explicitPropNames);
2620
+ decl.typeScriptPropTypes = new Map(typedComponent.props.map((prop) => [prop.name, prop.type]));
2621
+ decl.typeScriptOptionalProps = new Set(typedComponent.props.filter((prop) => prop.optional).map((prop) => prop.name));
2622
+ decl.typeScriptHasIndexSignature = typedComponent.hasIndexSignature;
2623
+ decl.typeScriptSupportsSxProp = typedComponent.supportsSxProp;
2624
+ }
2625
+ function defaultExportMatches(component, names) {
2626
+ return component.defaultExport && names.has("default");
2627
+ }
2628
+ //#endregion
2629
+ //#region src/internal/utilities/wrapped-component-interface.ts
2630
+ function wrappedComponentInterfaceFor(ctx, componentLocalName) {
2631
+ if (!ctx.adapter.useSxProp) return;
2632
+ const importInfo = ctx.importMap?.get(componentLocalName);
2633
+ if (importInfo) {
2634
+ const typedInterface = importInfo.source.kind === "absolutePath" ? typedComponentInterfaceFor(ctx, importInfo.source.value, importInfo.importedName === "default" ? [componentLocalName, importInfo.importedName] : [importInfo.importedName]) : void 0;
2635
+ const adapterResult = ctx.adapter.wrappedComponentInterface?.({
2636
+ localName: componentLocalName,
2637
+ importSource: importInfo.source.value,
2638
+ importedName: importInfo.importedName,
2639
+ filePath: ctx.file.path
2640
+ });
2641
+ if (adapterResult !== void 0) {
2642
+ if (adapterResult.acceptsSx && hasTypedSxConstraints(typedInterface)) return {
2643
+ ...adapterResult,
2644
+ sxExcludedProperties: mergeUniqueStrings(adapterResult.sxExcludedProperties, typedInterface.sxExcludedProperties ?? []),
2645
+ sxAllowedProperties: mergeAllowedPropertyLists(adapterResult.sxAllowedProperties, typedInterface.sxAllowedProperties)
2646
+ };
2647
+ return adapterResult;
2648
+ }
2649
+ return typedInterface;
2650
+ }
2651
+ return typedComponentInterfaceFor(ctx, ctx.file.path, [componentLocalName]);
2652
+ }
2653
+ function hasTypedSxConstraints(typedInterface) {
2654
+ return typedInterface !== void 0 && ((typedInterface.sxExcludedProperties?.length ?? 0) > 0 || typedInterface.sxAllowedProperties !== void 0);
2655
+ }
2656
+ function typedComponentInterfaceFor(ctx, filePath, componentNames) {
2657
+ const typedComponent = findTypeScriptComponentMetadata(ctx.options.crossFileInfo?.typeScriptMetadata, filePath, componentNames);
2658
+ if (typedComponent?.supportsSxProp) return {
2659
+ acceptsSx: true,
2660
+ sxExcludedProperties: typedComponent.sxExcludedProperties,
2661
+ sxAllowedProperties: typedComponent.sxAllowedProperties
2662
+ };
2663
+ }
2664
+ function mergeAllowedPropertyLists(first, second) {
2665
+ if (first === void 0) return second === void 0 ? void 0 : [...second];
2666
+ if (second === void 0) return [...first];
2667
+ const secondSet = new Set(second);
2668
+ return first.filter((name) => secondSet.has(name));
2669
+ }
2670
+ function mergeUniqueStrings(first, second) {
2671
+ return [...new Set([...first ?? [], ...second])];
2672
+ }
2673
+ //#endregion
2578
2674
  //#region src/internal/transform-steps/analyze-after-emit.ts
2579
2675
  const INLINE_USAGE_THRESHOLD$1 = 1;
2676
+ const AS_ATTR = new Set(["as"]);
2677
+ const FORWARDED_AS_ATTR = new Set(["forwardedAs"]);
2580
2678
  /**
2581
2679
  * Finalizes wrapper decisions, polymorphic handling, and base flattening after style emission.
2582
2680
  */
@@ -2630,8 +2728,7 @@ function analyzeAfterEmitStep(ctx) {
2630
2728
  decl.needsWrapperComponent = true;
2631
2729
  if (decl.base.kind === "intrinsic") decl.isPolymorphicIntrinsicWrapper = true;
2632
2730
  }
2633
- const resolverOnlyShouldForwardProp = !!decl.inlinedBaseComponent && !decl.shouldForwardPropFromWithConfig;
2634
- if (decl.shouldForwardProp && !resolverOnlyShouldForwardProp) decl.needsWrapperComponent = true;
2731
+ if (needsShouldForwardPropWrapper(decl)) decl.needsWrapperComponent = true;
2635
2732
  if (decl.base.kind === "component") {
2636
2733
  const baseDecl = declByLocal.get(decl.base.ident);
2637
2734
  if (baseDecl) {
@@ -2661,8 +2758,7 @@ function analyzeAfterEmitStep(ctx) {
2661
2758
  });
2662
2759
  const hasWrapperSemantics = (d) => {
2663
2760
  if (hasAttrsAsOverride(d.attrsInfo)) return true;
2664
- const resolverOnlyShouldForwardProp = !!d.inlinedBaseComponent && !d.shouldForwardPropFromWithConfig;
2665
- if (d.shouldForwardProp && !resolverOnlyShouldForwardProp) return true;
2761
+ if (needsShouldForwardPropWrapper(d)) return true;
2666
2762
  if (d.isPolymorphicIntrinsicWrapper) return true;
2667
2763
  return false;
2668
2764
  };
@@ -2734,6 +2830,16 @@ function analyzeAfterEmitStep(ctx) {
2734
2830
  if (!canDowngradeStyleFnIntrinsicWrapper(decl, exportedComponents, extendedBy, root, j)) continue;
2735
2831
  decl.needsWrapperComponent = false;
2736
2832
  }
2833
+ for (const decl of styledDecls) {
2834
+ if (!canInlineSingleUseSxAwareComponentWrapper({
2835
+ ctx,
2836
+ decl,
2837
+ exportedComponents,
2838
+ extendedBy,
2839
+ wrapperNames
2840
+ })) continue;
2841
+ decl.needsWrapperComponent = false;
2842
+ }
2737
2843
  ctx.wrapperNames = wrapperNames;
2738
2844
  return CONTINUE;
2739
2845
  }
@@ -2767,6 +2873,60 @@ function canDowngradeStyleFnIntrinsicWrapper(decl, exportedComponents, extendedB
2767
2873
  if (decl.receivesClassNameOrStyleInJsx) return false;
2768
2874
  return true;
2769
2875
  }
2876
+ function canInlineSingleUseSxAwareComponentWrapper(args) {
2877
+ const { ctx, decl, exportedComponents, extendedBy, wrapperNames } = args;
2878
+ const { root, j } = ctx;
2879
+ if (!decl.needsWrapperComponent || decl.isCssHelper || decl.isDirectJsxResolution) return false;
2880
+ if (decl.base.kind !== "component") return false;
2881
+ if (exportedComponents.has(decl.localName)) return false;
2882
+ if (wrapperNames.has(decl.localName) && !hasOnlyForwardedAsPolymorphicUsage(root, j, decl)) return false;
2883
+ if (extendedBy.has(decl.localName) || decl.usedAsValue) return false;
2884
+ if (countComponentJsxUsages(root, j, decl.localName) !== INLINE_USAGE_THRESHOLD$1) return false;
2885
+ if (hasJsxNamespaceUsage(root, j, decl.localName)) return false;
2886
+ if (hasSpreadInJsx(root, j, decl.localName)) return false;
2887
+ if (hasAttrsAsOverride(decl.attrsInfo) || hasAttrsPayload(decl.attrsInfo)) return false;
2888
+ if (needsShouldForwardPropWrapper(decl) || decl.attrWrapper || decl.bridgeClassName || decl.enumVariant || (decl.inlineStyleProps?.length ?? 0) > 0 || (decl.styleFnFromProps?.length ?? 0) > 0 || (decl.variantDimensions?.length ?? 0) > 0 || Object.keys(decl.variantStyleKeys ?? {}).length > 0 || (decl.compoundVariants?.length ?? 0) > 0 || (decl.pseudoAliasSelectors?.length ?? 0) > 0 || (decl.pseudoExpandSelectors?.length ?? 0) > 0 || (decl.localElementOverrides?.length ?? 0) > 0 || (decl.needsUseThemeHook?.length ?? 0) > 0 || (decl.extraStylexPropsArgs?.some((arg) => arg.when) ?? false)) return false;
2889
+ const componentInterface = wrappedComponentInterfaceFor(ctx, decl.base.ident);
2890
+ return componentInterface?.acceptsSx === true && (componentInterface.sxExcludedProperties?.length ?? 0) === 0 && componentInterface.sxAllowedProperties === void 0;
2891
+ }
2892
+ function hasAttrsPayload(attrsInfo) {
2893
+ return !!(Object.keys(attrsInfo?.staticAttrs ?? {}).length > 0 || (attrsInfo?.conditionalAttrs?.length ?? 0) > 0 || (attrsInfo?.defaultAttrs?.length ?? 0) > 0 || (attrsInfo?.dynamicAttrs?.length ?? 0) > 0 || (attrsInfo?.invertedBoolAttrs?.length ?? 0) > 0 || Object.keys(attrsInfo?.attrsStaticStyles ?? {}).length > 0 || attrsInfo?.attrsStaticStyleExpr || (attrsInfo?.attrsDynamicStyles?.length ?? 0) > 0);
2894
+ }
2895
+ function hasOnlyForwardedAsPolymorphicUsage(root, j, decl) {
2896
+ return decl.base.kind === "component" && hasAnyJsxAttribute(root, j, decl.localName, FORWARDED_AS_ATTR) && !hasAnyJsxAttribute(root, j, decl.localName, AS_ATTR);
2897
+ }
2898
+ function hasJsxNamespaceUsage(root, j, localName) {
2899
+ let found = false;
2900
+ root.find(j.JSXMemberExpression).forEach((p) => {
2901
+ if (getRootJsxIdentifierName(p.node) === localName) found = true;
2902
+ });
2903
+ return found;
2904
+ }
2905
+ function hasAnyJsxAttribute(root, j, name, attrNames) {
2906
+ let found = false;
2907
+ const checkOpening = (opening) => {
2908
+ for (const attr of opening.attributes ?? []) {
2909
+ const attrName = attr.name?.name;
2910
+ if (attr.type === "JSXAttribute" && attrName && attrNames.has(attrName)) {
2911
+ found = true;
2912
+ return;
2913
+ }
2914
+ }
2915
+ };
2916
+ root.find(j.JSXElement, { openingElement: { name: {
2917
+ type: "JSXIdentifier",
2918
+ name
2919
+ } } }).forEach((p) => {
2920
+ if (!found) checkOpening(p.node.openingElement);
2921
+ });
2922
+ root.find(j.JSXSelfClosingElement, { name: {
2923
+ type: "JSXIdentifier",
2924
+ name
2925
+ } }).forEach((p) => {
2926
+ if (!found) checkOpening(p.node);
2927
+ });
2928
+ return found;
2929
+ }
2770
2930
  //#endregion
2771
2931
  //#region src/internal/analyze-before-emit/exported-components.ts
2772
2932
  function collectExportedComponents(root, j, declByLocal) {
@@ -3023,7 +3183,7 @@ function parseVariantWhenToAst(j, when, booleanProps) {
3023
3183
  const buildMemberExpr = (raw) => {
3024
3184
  if (!raw.includes(".")) return null;
3025
3185
  const parts = raw.split(".").map((part) => part.trim()).filter(Boolean);
3026
- if (parts.length < 2 || parts.some((part) => !isValidIdentifierName$1(part))) return null;
3186
+ if (parts.length < 2 || parts.some((part) => !isValidIdentifierName(part))) return null;
3027
3187
  return parts.slice(1).reduce((acc, part) => j.memberExpression(acc, j.identifier(part)), j.identifier(parts[0]));
3028
3188
  };
3029
3189
  const parsePropRef = (raw) => {
@@ -3035,14 +3195,14 @@ function parseVariantWhenToAst(j, when, booleanProps) {
3035
3195
  if (trimmedRaw.includes(".")) {
3036
3196
  const parts = trimmedRaw.split(".").map((part) => part.trim()).filter(Boolean);
3037
3197
  const last = parts[parts.length - 1];
3038
- if (!last || !isValidIdentifierName$1(last)) return {
3198
+ if (!last || !isValidIdentifierName(last)) return {
3039
3199
  propName: null,
3040
3200
  expr: j.identifier(trimmedRaw)
3041
3201
  };
3042
3202
  const root = parts[0];
3043
3203
  if (root === "props" || root === "p") {
3044
3204
  const propRoot = parts[1];
3045
- if (!propRoot || !isValidIdentifierName$1(propRoot)) return {
3205
+ if (!propRoot || !isValidIdentifierName(propRoot)) return {
3046
3206
  propName: null,
3047
3207
  expr: j.identifier(trimmedRaw)
3048
3208
  };
@@ -3225,6 +3385,27 @@ function buildExtraStylexPropsExprs(j, args) {
3225
3385
  return result;
3226
3386
  }
3227
3387
  /**
3388
+ * Merges adjacent `cond && styleA, !cond && styleB` expressions into
3389
+ * `cond ? styleA : styleB` without reordering other style args.
3390
+ */
3391
+ function mergeAdjacentComplementaryStyleExprs(j, styleArgs) {
3392
+ const result = [];
3393
+ for (let i = 0; i < styleArgs.length; i++) {
3394
+ const current = styleArgs[i];
3395
+ const next = styleArgs[i + 1];
3396
+ if (next) {
3397
+ const merged = mergeComplementaryLogicalPair(j, current, next);
3398
+ if (merged) {
3399
+ result.push(merged);
3400
+ i++;
3401
+ continue;
3402
+ }
3403
+ }
3404
+ result.push(current);
3405
+ }
3406
+ return result;
3407
+ }
3408
+ /**
3228
3409
  * Finds the next unconsumed entry in sorted variant entries (as `[when, key]` tuples)
3229
3410
  * that has a complementary "when" condition to the entry at `index`.
3230
3411
  * Used by both intrinsic-simple and component emitters for ternary merging.
@@ -3255,6 +3436,33 @@ function findComplementaryEntry(entries, index, consumed) {
3255
3436
  if (otherWhen && getPositiveWhen(when, otherWhen) !== null) return next;
3256
3437
  return null;
3257
3438
  }
3439
+ function mergeComplementaryLogicalPair(j, leftExpr, rightExpr) {
3440
+ const left = getConditionalStyleParts(j, leftExpr);
3441
+ const right = getConditionalStyleParts(j, rightExpr);
3442
+ if (!left || !right) return null;
3443
+ const positiveWhen = getPositiveWhen(left.when, right.when);
3444
+ if (!positiveWhen) return null;
3445
+ const isLeftPositive = areEquivalentWhen(left.when, positiveWhen);
3446
+ return j.conditionalExpression(isLeftPositive ? left.cond : right.cond, isLeftPositive ? left.style : right.style, isLeftPositive ? right.style : left.style);
3447
+ }
3448
+ function getConditionalStyleParts(j, expr) {
3449
+ if (expr.type !== "LogicalExpression" || expr.operator !== "&&") return null;
3450
+ const cond = expr.left;
3451
+ const when = printCondition(j, cond);
3452
+ if (!when) return null;
3453
+ return {
3454
+ when,
3455
+ cond,
3456
+ style: expr.right
3457
+ };
3458
+ }
3459
+ function printCondition(j, cond) {
3460
+ try {
3461
+ return j(cond).toSource();
3462
+ } catch {
3463
+ return null;
3464
+ }
3465
+ }
3258
3466
  /**
3259
3467
  * Detects if two "when" strings differ only in === vs !==.
3260
3468
  * Returns the "===" variant (the positive one) or null if they're not inverses.
@@ -3262,20 +3470,61 @@ function findComplementaryEntry(entries, index, consumed) {
3262
3470
  function areComparisonInverses(a, b) {
3263
3471
  const aNorm = normalizeWhenForComparison(a);
3264
3472
  const bNorm = normalizeWhenForComparison(b);
3265
- const eqOp = "===";
3266
- const neqOp = "!==";
3267
- const aHasNeq = aNorm.includes(neqOp);
3268
- const aHasEq = !aHasNeq && aNorm.includes(eqOp);
3269
- const bHasNeq = bNorm.includes(neqOp);
3270
- const bHasEq = !bHasNeq && bNorm.includes(eqOp);
3271
- if (aHasEq && !aHasNeq && bHasNeq && !bHasEq) {
3272
- if (aNorm.replace(eqOp, neqOp) === bNorm) return a.trim();
3273
- }
3274
- if (bHasEq && !bHasNeq && aHasNeq && !aHasEq) {
3275
- if (bNorm.replace(eqOp, neqOp) === aNorm) return b.trim();
3276
- }
3473
+ const aComparison = parseSingleComparison(aNorm);
3474
+ const bComparison = parseSingleComparison(bNorm);
3475
+ if (!aComparison || !bComparison) return null;
3476
+ if (aComparison.left !== bComparison.left || aComparison.right !== bComparison.right) return null;
3477
+ if (aComparison.operator === "===" && bComparison.operator === "!==") return a.trim();
3478
+ if (aComparison.operator === "!==" && bComparison.operator === "===") return b.trim();
3277
3479
  return null;
3278
3480
  }
3481
+ function parseSingleComparison(expr) {
3482
+ const neqIndex = findTopLevelOperator(expr, "!==");
3483
+ const eqIndex = findTopLevelOperator(expr, "===");
3484
+ if (neqIndex >= 0 && eqIndex >= 0 || neqIndex < 0 && eqIndex < 0) return null;
3485
+ const operator = neqIndex >= 0 ? "!==" : "===";
3486
+ const index = neqIndex >= 0 ? neqIndex : eqIndex;
3487
+ const left = expr.slice(0, index);
3488
+ const right = expr.slice(index + operator.length);
3489
+ if (!left || !right || hasTopLevelLogicalOperator(left) || hasTopLevelLogicalOperator(right)) return null;
3490
+ return {
3491
+ left,
3492
+ operator,
3493
+ right
3494
+ };
3495
+ }
3496
+ function hasTopLevelLogicalOperator(expr) {
3497
+ return findTopLevelOperator(expr, "&&") >= 0 || findTopLevelOperator(expr, "||") >= 0;
3498
+ }
3499
+ function findTopLevelOperator(expr, operator) {
3500
+ let depth = 0;
3501
+ let quote = null;
3502
+ for (let i = 0; i <= expr.length - operator.length; i++) {
3503
+ const ch = expr[i];
3504
+ if (quote) {
3505
+ if (ch === "\\") {
3506
+ i++;
3507
+ continue;
3508
+ }
3509
+ if (ch === quote) quote = null;
3510
+ continue;
3511
+ }
3512
+ if (ch === "\"" || ch === "'" || ch === "`") {
3513
+ quote = ch;
3514
+ continue;
3515
+ }
3516
+ if (ch === "(") {
3517
+ depth++;
3518
+ continue;
3519
+ }
3520
+ if (ch === ")") {
3521
+ depth--;
3522
+ continue;
3523
+ }
3524
+ if (depth === 0 && expr.slice(i, i + operator.length) === operator) return i;
3525
+ }
3526
+ return -1;
3527
+ }
3279
3528
  function isNegationOf(candidate, base) {
3280
3529
  const candidateNormalized = normalizeWhenForComparison(candidate);
3281
3530
  const baseNormalized = normalizeWhenForComparison(base);
@@ -3285,7 +3534,34 @@ function isNegationOf(candidate, base) {
3285
3534
  return normalizeWhenForComparison(candidateNormalized.slice(2, -1)) === baseNormalized;
3286
3535
  }
3287
3536
  function normalizeWhenForComparison(when) {
3288
- return stripOuterParens(String(when ?? "").replace(/\s+/g, ""));
3537
+ return stripOuterParens(removeWhitespaceOutsideLiterals(String(when ?? "")));
3538
+ }
3539
+ function removeWhitespaceOutsideLiterals(expr) {
3540
+ let result = "";
3541
+ let quote = null;
3542
+ for (let i = 0; i < expr.length; i++) {
3543
+ const ch = expr[i];
3544
+ if (quote) {
3545
+ result += ch;
3546
+ if (ch === "\\") {
3547
+ const next = expr[i + 1];
3548
+ if (next !== void 0) {
3549
+ result += next;
3550
+ i++;
3551
+ }
3552
+ continue;
3553
+ }
3554
+ if (ch === quote) quote = null;
3555
+ continue;
3556
+ }
3557
+ if (ch === "\"" || ch === "'" || ch === "`") {
3558
+ quote = ch;
3559
+ result += ch;
3560
+ continue;
3561
+ }
3562
+ if (!/\s/.test(ch)) result += ch;
3563
+ }
3564
+ return result;
3289
3565
  }
3290
3566
  function stripOuterParens(expr) {
3291
3567
  let current = expr;
@@ -3962,17 +4238,17 @@ function registerImports(imports, resolverImports) {
3962
4238
  function isMemberExpression(node) {
3963
4239
  return isMemberExpressionNode(node);
3964
4240
  }
3965
- /** Returns true for at-rules the codemod can transform (`@media`, `@container`). */
4241
+ /** Returns true for at-rules the codemod can transform as StyleX condition keys. */
3966
4242
  function isSupportedAtRule(atRule) {
3967
- return atRule.startsWith("@media") || atRule.startsWith("@container");
4243
+ return atRule.startsWith("@media") || atRule.startsWith("@container") || atRule.startsWith("@supports");
3968
4244
  }
3969
- /** Finds the first supported at-rule (`@media` or `@container`) in the stack, if any. */
4245
+ /** Finds the supported StyleX condition key for an at-rule stack, if representable. */
3970
4246
  function findSupportedAtRule(atRuleStack) {
3971
- return atRuleStack.find(isSupportedAtRule);
4247
+ return resolveSupportedAtRule(atRuleStack) ?? void 0;
3972
4248
  }
3973
4249
  /** Returns true when any at-rule in the stack cannot be represented by StyleX. */
3974
4250
  function hasUnsupportedAtRule(atRuleStack) {
3975
- return atRuleStack.some((atRule) => !isSupportedAtRule(atRule));
4251
+ return resolveSupportedAtRule(atRuleStack) === null;
3976
4252
  }
3977
4253
  /**
3978
4254
  * Resolves a media/container at-rule string that may contain `__SC_EXPR_N__` placeholders.
@@ -4048,8 +4324,8 @@ function getMediaFeatureContext(before, after) {
4048
4324
  } };
4049
4325
  }
4050
4326
  /** Returns true if the key looks like a StyleX style condition (pseudo, media, container). */
4051
- function isStyleConditionKey(key) {
4052
- return key.startsWith(":") || key.startsWith("::") || key.startsWith("@media") || key.startsWith("@container");
4327
+ function isStyleConditionKey$1(key) {
4328
+ return key.startsWith(":") || key.startsWith("::") || key.startsWith("@media") || key.startsWith("@container") || key.startsWith("@supports");
4053
4329
  }
4054
4330
  /**
4055
4331
  * Merges tracked @media values into a base style object as nested StyleX objects.
@@ -4156,6 +4432,20 @@ function parseStaticExprString(expr) {
4156
4432
  if (trimmed.startsWith("\"") && trimmed.endsWith("\"") || trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1);
4157
4433
  return null;
4158
4434
  }
4435
+ function resolveSupportedAtRule(atRuleStack) {
4436
+ if (atRuleStack.length === 0) return;
4437
+ if (atRuleStack.some((atRule) => !isSupportedAtRule(atRule))) return null;
4438
+ if (atRuleStack.length === 1) return atRuleStack[0];
4439
+ if (atRuleStack.every((atRule) => atRule.startsWith("@supports"))) return combineSupportsAtRules(atRuleStack);
4440
+ return null;
4441
+ }
4442
+ function combineSupportsAtRules(atRuleStack) {
4443
+ return `@supports ${atRuleStack.map((atRule) => parenthesizeSupportsCondition(atRule.slice(9).trim())).join(" and ")}`;
4444
+ }
4445
+ function parenthesizeSupportsCondition(condition) {
4446
+ if (condition.includes(" and ") || condition.includes(" or ")) return `(${condition})`;
4447
+ return condition.startsWith("(") && condition.endsWith(")") ? condition : `(${condition})`;
4448
+ }
4159
4449
  /**
4160
4450
  * Recursively walk an AST tree and return `true` if the predicate matches any node.
4161
4451
  * Skips `loc` and `comments` keys. Short-circuits on first match.
@@ -4542,42 +4832,1053 @@ function buildChildStyleObjectList(childKeys, resolvedStyleObjects) {
4542
4832
  return childStyleObjects;
4543
4833
  }
4544
4834
  //#endregion
4545
- //#region src/internal/utilities/wrapped-component-interface.ts
4546
- function wrappedComponentInterfaceFor(ctx, componentLocalName) {
4547
- if (!ctx.adapter.useSxProp) return;
4835
+ //#region src/internal/utilities/style-composition-plan.ts
4836
+ function buildStyleKeySequence(ctx, decl, options) {
4837
+ const entries = [];
4838
+ const afterBase = new Set(decl.extraStyleKeysAfterBase ?? []);
4839
+ if (options?.includeLocalBase !== false) for (const styleKey of localBaseStyleKeys(ctx, decl)) entries.push({
4840
+ styleKey,
4841
+ patchable: false,
4842
+ source: "base"
4843
+ });
4844
+ for (const styleKey of decl.extraStyleKeys ?? []) if (!afterBase.has(styleKey)) entries.push({
4845
+ styleKey,
4846
+ patchable: false,
4847
+ source: "mixin"
4848
+ });
4849
+ if (!decl.skipBaseStyleRef) entries.push({
4850
+ styleKey: decl.styleKey,
4851
+ patchable: true,
4852
+ source: "base"
4853
+ });
4854
+ for (const styleKey of decl.extraStyleKeysAfterBase ?? []) entries.push({
4855
+ styleKey,
4856
+ patchable: true,
4857
+ source: "mixin"
4858
+ });
4859
+ const variantAndStyleFnEntries = buildVariantAndStyleFnEntries(decl);
4860
+ const variantDimensionEntries = buildVariantDimensionEntries(decl);
4861
+ entries.push(...variantAndStyleFnEntries.immediate);
4862
+ entries.push(...variantDimensionEntries.immediate);
4863
+ entries.push(...buildExtraStylexPropsArgEntries(decl));
4864
+ entries.push(...buildThemeEntries(decl));
4865
+ entries.push(...buildAttrWrapperEntries(decl));
4866
+ entries.push(...buildPseudoExpandEntries(decl));
4867
+ entries.push(...buildPseudoAliasEntries(decl));
4868
+ entries.push(...buildCompoundVariantEntries(decl));
4869
+ entries.push(...mergeOrderedEntries$1([variantDimensionEntries.ordered, variantAndStyleFnEntries.ordered]));
4870
+ entries.push(...buildEnumVariantEntries(decl));
4871
+ entries.push(...buildCallSiteCombinedEntries(decl));
4872
+ entries.push(...buildPromotedStyleEntries(decl));
4873
+ if (decl.adjacentSiblingStyleKey) entries.push({
4874
+ styleKey: decl.adjacentSiblingStyleKey,
4875
+ patchable: true,
4876
+ source: "adjacent"
4877
+ });
4878
+ return entries;
4879
+ }
4880
+ function buildExtraStylexPropsArgEntries(decl) {
4881
+ return (decl.extraStylexPropsArgs ?? []).map((_, index) => ({
4882
+ styleKey: `${decl.styleKey}ExtraStylexPropsArg${index}`,
4883
+ patchable: false,
4884
+ contributesDynamic: true,
4885
+ source: "propsArg"
4886
+ }));
4887
+ }
4888
+ function localBaseStyleKeys(ctx, decl) {
4889
+ if (decl.extendsStyleKey) return [decl.extendsStyleKey];
4890
+ const keys = [];
4891
+ const visited = new Set([decl.localName]);
4892
+ let currentBase = decl.base;
4893
+ while (currentBase.kind === "component") {
4894
+ if (visited.has(currentBase.ident)) break;
4895
+ visited.add(currentBase.ident);
4896
+ const baseDecl = ctx.declByLocal?.get(currentBase.ident);
4897
+ if (!baseDecl || baseDecl.skipTransform) break;
4898
+ keys.push(baseDecl.styleKey);
4899
+ currentBase = baseDecl.base;
4900
+ }
4901
+ return keys.reverse();
4902
+ }
4903
+ function buildVariantAndStyleFnEntries(decl) {
4904
+ const variantEntries = Object.entries(decl.variantStyleKeys ?? {}).map(([when, styleKey]) => ({
4905
+ when,
4906
+ entry: {
4907
+ styleKey,
4908
+ patchable: true,
4909
+ contributes: false,
4910
+ source: "variant"
4911
+ }
4912
+ }));
4913
+ const styleFnEntries = (decl.styleFnFromProps ?? []).map((styleFn) => ({
4914
+ sourceOrder: styleFn.sourceOrder,
4915
+ entry: {
4916
+ styleKey: styleFn.fnKey,
4917
+ patchable: true,
4918
+ source: "styleFn"
4919
+ }
4920
+ }));
4921
+ if (!(Object.keys(decl.variantSourceOrder ?? {}).length > 0 || styleFnEntries.some((entry) => entry.sourceOrder !== void 0))) return {
4922
+ immediate: [...variantEntries.map((entry) => entry.entry), ...styleFnEntries.map((entry) => entry.entry)],
4923
+ ordered: []
4924
+ };
4925
+ 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)];
4926
+ const ordered = [];
4927
+ let index = 0;
4928
+ for (const variant of variantEntries) {
4929
+ const order = decl.variantSourceOrder?.[variant.when];
4930
+ if (order === void 0) continue;
4931
+ ordered.push({
4932
+ order,
4933
+ index,
4934
+ entry: variant.entry
4935
+ });
4936
+ index += 1;
4937
+ }
4938
+ for (const styleFn of styleFnEntries) {
4939
+ if (styleFn.sourceOrder === void 0) continue;
4940
+ ordered.push({
4941
+ order: styleFn.sourceOrder,
4942
+ index,
4943
+ entry: styleFn.entry
4944
+ });
4945
+ index += 1;
4946
+ }
4947
+ return {
4948
+ immediate,
4949
+ ordered
4950
+ };
4951
+ }
4952
+ function buildVariantDimensionEntries(decl) {
4953
+ const immediate = [];
4954
+ const ordered = [];
4955
+ let index = 0;
4956
+ for (const dimension of decl.variantDimensions ?? []) {
4957
+ const entries = Object.entries(dimension.variants).map(([variantKey, styleObj]) => ({
4958
+ styleKey: `${dimension.variantObjectName}.${variantKey}`,
4959
+ styleObj,
4960
+ patchable: true,
4961
+ contributes: false,
4962
+ source: "variant"
4963
+ }));
4964
+ if (dimension.fallbackFnKey) entries.push({
4965
+ styleKey: dimension.fallbackFnKey,
4966
+ patchable: true,
4967
+ source: "styleFn"
4968
+ });
4969
+ if (dimension.sourceOrder === void 0) {
4970
+ immediate.push(...entries);
4971
+ continue;
4972
+ }
4973
+ for (const entry of entries) {
4974
+ ordered.push({
4975
+ order: dimension.sourceOrder,
4976
+ index,
4977
+ entry
4978
+ });
4979
+ index += 1;
4980
+ }
4981
+ }
4982
+ return {
4983
+ immediate,
4984
+ ordered
4985
+ };
4986
+ }
4987
+ function mergeOrderedEntries$1(groups) {
4988
+ return groups.flat().sort((a, b) => a.order - b.order || a.index - b.index).map((orderedEntry) => orderedEntry.entry);
4989
+ }
4990
+ function buildPseudoExpandEntries(decl) {
4991
+ return (decl.pseudoExpandSelectors ?? []).map((entry) => ({
4992
+ styleKey: entry.styleKey,
4993
+ patchable: true,
4994
+ source: "pseudo"
4995
+ }));
4996
+ }
4997
+ function buildThemeEntries(decl) {
4998
+ const entries = [];
4999
+ for (const hook of decl.needsUseThemeHook ?? []) {
5000
+ if (hook.trueStyleKey) entries.push({
5001
+ styleKey: hook.trueStyleKey,
5002
+ patchable: true,
5003
+ contributes: false,
5004
+ source: "theme"
5005
+ });
5006
+ if (hook.falseStyleKey) entries.push({
5007
+ styleKey: hook.falseStyleKey,
5008
+ patchable: true,
5009
+ contributes: false,
5010
+ source: "theme"
5011
+ });
5012
+ }
5013
+ return entries;
5014
+ }
5015
+ function buildPseudoAliasEntries(decl) {
5016
+ return (decl.pseudoAliasSelectors ?? []).flatMap((entry) => entry.styleKeys.map((styleKey) => ({
5017
+ styleKey,
5018
+ patchable: true,
5019
+ contributes: false,
5020
+ source: "pseudo"
5021
+ })));
5022
+ }
5023
+ function buildCompoundVariantEntries(decl) {
5024
+ return (decl.compoundVariants ?? []).flatMap((entry) => {
5025
+ if (entry.kind === "3branch") return [
5026
+ entry.outerTruthyKey,
5027
+ entry.innerTruthyKey,
5028
+ entry.innerFalsyKey
5029
+ ].map((styleKey) => ({
5030
+ styleKey,
5031
+ patchable: true,
5032
+ contributes: false,
5033
+ source: "variant"
5034
+ }));
5035
+ return [
5036
+ entry.outerTruthyInnerTruthyKey,
5037
+ entry.outerTruthyInnerFalsyKey,
5038
+ entry.outerFalsyInnerTruthyKey,
5039
+ entry.outerFalsyInnerFalsyKey
5040
+ ].map((styleKey) => ({
5041
+ styleKey,
5042
+ patchable: true,
5043
+ contributes: false,
5044
+ source: "variant"
5045
+ }));
5046
+ });
5047
+ }
5048
+ function buildAttrWrapperEntries(decl) {
5049
+ const attrWrapper = decl.attrWrapper;
5050
+ if (!attrWrapper) return [];
5051
+ return [
5052
+ attrWrapper.checkboxKey,
5053
+ attrWrapper.radioKey,
5054
+ attrWrapper.readonlyKey,
5055
+ attrWrapper.externalKey,
5056
+ attrWrapper.httpsKey,
5057
+ attrWrapper.pdfKey
5058
+ ].filter((styleKey) => typeof styleKey === "string").map((styleKey) => ({
5059
+ styleKey,
5060
+ patchable: true,
5061
+ source: "attr"
5062
+ }));
5063
+ }
5064
+ function buildCallSiteCombinedEntries(decl) {
5065
+ return (decl.callSiteCombinedStyles ?? []).map((entry) => ({
5066
+ styleKey: entry.styleKey,
5067
+ patchable: true,
5068
+ source: "combined"
5069
+ }));
5070
+ }
5071
+ function buildPromotedStyleEntries(decl) {
5072
+ return (decl.promotedStyleProps ?? []).filter((entry) => !entry.mergeIntoBase).map((entry) => ({
5073
+ styleKey: entry.styleKey,
5074
+ patchable: true,
5075
+ source: "promoted"
5076
+ }));
5077
+ }
5078
+ function buildEnumVariantEntries(decl) {
5079
+ const enumVariant = decl.enumVariant;
5080
+ if (!enumVariant) return [];
5081
+ return [{
5082
+ styleKey: enumVariant.baseKey,
5083
+ patchable: true,
5084
+ source: "enum"
5085
+ }, ...enumVariant.cases.map((entry) => ({
5086
+ styleKey: entry.styleKey,
5087
+ patchable: true,
5088
+ source: "enum"
5089
+ }))];
5090
+ }
5091
+ //#endregion
5092
+ //#region src/internal/utilities/conditional-style-defaults.ts
5093
+ const CONDITIONAL_DEFAULT_WARNING = "Conditional StyleX default would override an unproven earlier style for the same property";
5094
+ function guardGeneratedConditionalDefaults(ctx, styledDecls) {
5095
+ if (!ctx.resolvedStyleObjects) return "ok";
5096
+ for (const decl of styledDecls) {
5097
+ if (decl.skipTransform || decl.isCssHelper) continue;
5098
+ if (patchConditionalDefaultsForSequence({
5099
+ ctx,
5100
+ decl,
5101
+ entries: buildStyleKeySequence(ctx, decl)
5102
+ }) === "bail") return "bail";
5103
+ }
5104
+ return "ok";
5105
+ }
5106
+ function propertiesWithNullConditionalDefault(styleObj) {
5107
+ const props = [];
5108
+ for (const [prop, value] of Object.entries(styleObj)) {
5109
+ if (isMetadataOrConditionKey(prop) || !isPlainStyleObject$1(value)) continue;
5110
+ if (isConditionalStyleMap(value) && value.default === null) props.push(prop);
5111
+ }
5112
+ return props;
5113
+ }
5114
+ function propertiesWithUnsafeNullConditionalDefault(styleObj) {
5115
+ const props = new Set(propertiesWithNullConditionalDefault(styleObj));
5116
+ for (const [prop, value] of Object.entries(styleObj)) {
5117
+ if (isMetadataOrConditionKey(prop) || !isPlainStyleObject$1(value)) continue;
5118
+ if (hasNestedNullConditionalDefault(value)) props.add(prop);
5119
+ }
5120
+ return [...props];
5121
+ }
5122
+ function patchNullConditionalDefaultsForProp(styleObj, prop, earlier) {
5123
+ const value = styleObj[prop];
5124
+ if (!isPlainStyleObject$1(value) || !isConditionalStyleMap(value)) return "safe";
5125
+ let inheritedDefault = inferDefaultFromValue(value);
5126
+ if (value.default === null && earlier.kind === "static" && earlier.value !== null) {
5127
+ value.default = earlier.value;
5128
+ inheritedDefault = earlier;
5129
+ } else if (value.default === null && earlier.kind === "dynamic") return "bail";
5130
+ else if (value.default === null) inheritedDefault = earlier;
5131
+ if (!hasNestedNullConditionalDefault(value)) return "safe";
5132
+ if (inheritedDefault.kind === "static" && inheritedDefault.value !== null) {
5133
+ patchNestedNullConditionalDefaults(value, inheritedDefault.value);
5134
+ return "patched";
5135
+ }
5136
+ return inheritedDefault.kind === "dynamic" ? "bail" : "safe";
5137
+ }
5138
+ function patchConditionalDefaultsForSequence(args) {
5139
+ const { ctx, decl, entries } = args;
5140
+ const defaults = /* @__PURE__ */ new Map();
5141
+ let hasDynamicUnknownContributor = false;
5142
+ for (const entry of entries) {
5143
+ const source = entry.styleObj ?? ctx.resolvedStyleObjects?.get(entry.styleKey);
5144
+ if (entry.patchable && isPlainStyleObject$1(source)) for (const prop of propertiesWithUnsafeNullConditionalDefault(source)) {
5145
+ const patchResult = patchNullConditionalDefaultsForProp(source, prop, hasDynamicUnknownContributor ? { kind: "dynamic" } : defaults.get(prop) ?? { kind: "absent" });
5146
+ if (patchResult === "patched" || patchResult === "safe") continue;
5147
+ ctx.warnings.push({
5148
+ severity: "warning",
5149
+ type: CONDITIONAL_DEFAULT_WARNING,
5150
+ loc: decl.loc,
5151
+ context: {
5152
+ component: decl.localName,
5153
+ styleKey: entry.styleKey,
5154
+ property: prop,
5155
+ source: entry.source,
5156
+ reason: "an earlier generated style for this property can vary at runtime",
5157
+ 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.`
5158
+ }
5159
+ });
5160
+ return "bail";
5161
+ }
5162
+ else if (entry.patchable) for (const prop of functionPropertiesWithNullConditionalDefault$1(source)) {
5163
+ if ((defaults.get(prop) ?? { kind: "absent" }).kind === "absent") continue;
5164
+ ctx.warnings.push({
5165
+ severity: "warning",
5166
+ type: CONDITIONAL_DEFAULT_WARNING,
5167
+ loc: decl.loc,
5168
+ context: {
5169
+ component: decl.localName,
5170
+ styleKey: entry.styleKey,
5171
+ property: prop,
5172
+ source: entry.source,
5173
+ reason: "a generated dynamic style function would clear an earlier default",
5174
+ todo: `TODO: merge the ${prop} base value into ${entry.styleKey}'s dynamic conditional default.`
5175
+ }
5176
+ });
5177
+ return "bail";
5178
+ }
5179
+ if (entry.contributesDynamic) {
5180
+ hasDynamicUnknownContributor = true;
5181
+ continue;
5182
+ }
5183
+ if (entry.contributes !== false) for (const [prop, inference] of inferDefaultContributions(source)) if (inference.kind === "absent") defaults.delete(prop);
5184
+ else defaults.set(prop, inference);
5185
+ }
5186
+ return "ok";
5187
+ }
5188
+ function inferDefaultContributions(source) {
5189
+ if (isPlainStyleObject$1(source)) return inferStyleObjectContributions(source);
5190
+ return inferStyleFunctionContributions(source);
5191
+ }
5192
+ function inferStyleObjectContributions(styleObj) {
5193
+ const contributions = /* @__PURE__ */ new Map();
5194
+ for (const [prop, value] of Object.entries(styleObj)) {
5195
+ if (isMetadataOrConditionKey(prop)) continue;
5196
+ contributions.set(prop, inferDefaultFromValue(value));
5197
+ }
5198
+ return contributions;
5199
+ }
5200
+ function inferStyleFunctionContributions(source) {
5201
+ const returnedObject = readFunctionReturnedObject$1(source);
5202
+ const contributions = /* @__PURE__ */ new Map();
5203
+ if (!returnedObject) return contributions;
5204
+ for (const property of getObjectProperties$1(returnedObject)) {
5205
+ const key = readPropertyKey$1(property);
5206
+ if (!key || isMetadataOrConditionKey(key)) continue;
5207
+ contributions.set(key, { kind: "dynamic" });
5208
+ }
5209
+ return contributions;
5210
+ }
5211
+ function functionPropertiesWithNullConditionalDefault$1(source) {
5212
+ const returnedObject = readFunctionReturnedObject$1(source);
5213
+ if (!returnedObject) return [];
5214
+ const props = [];
5215
+ for (const property of getObjectProperties$1(returnedObject)) {
5216
+ const key = readPropertyKey$1(property);
5217
+ if (!key || isMetadataOrConditionKey(key)) continue;
5218
+ if (astObjectHasNullConditionalDefault(property.value)) props.push(key);
5219
+ }
5220
+ return props;
5221
+ }
5222
+ function inferDefaultFromValue(value) {
5223
+ if (isStaticStyleValue(value)) return value === null ? { kind: "absent" } : {
5224
+ kind: "static",
5225
+ value
5226
+ };
5227
+ if (isPlainStyleObject$1(value) && isConditionalStyleMap(value)) {
5228
+ const defaultValue = value.default;
5229
+ return isStaticStyleValue(defaultValue) ? defaultValue === null ? { kind: "absent" } : {
5230
+ kind: "static",
5231
+ value: defaultValue
5232
+ } : { kind: "dynamic" };
5233
+ }
5234
+ return { kind: "dynamic" };
5235
+ }
5236
+ function isConditionalStyleMap(value) {
5237
+ return Object.keys(value).some((key) => key === "default" || isStyleConditionKey(key));
5238
+ }
5239
+ function astObjectHasNullConditionalDefault(value) {
5240
+ if (!isObjectExpression$2(value)) return false;
5241
+ let hasCondition = false;
5242
+ let hasNullDefault = false;
5243
+ for (const property of getObjectProperties$1(value)) {
5244
+ const key = readPropertyKey$1(property);
5245
+ if (!key) continue;
5246
+ hasCondition ||= key === "default" || isStyleConditionKey(key);
5247
+ if (key === "default" && isNullLiteral$2(property.value)) hasNullDefault = true;
5248
+ if (isObjectExpression$2(property.value) && astObjectHasNullConditionalDefault(property.value)) return true;
5249
+ }
5250
+ return hasCondition && hasNullDefault;
5251
+ }
5252
+ function hasNestedNullConditionalDefault(value) {
5253
+ for (const [key, nested] of Object.entries(value)) {
5254
+ if (key === "__computedKeys" && computedEntriesHaveNullConditionalDefault(nested)) return true;
5255
+ if (key === "default" || !isPlainStyleObject$1(nested)) continue;
5256
+ if (isConditionalStyleMap(nested) && nested.default === null) return true;
5257
+ if (hasNestedNullConditionalDefault(nested)) return true;
5258
+ }
5259
+ return false;
5260
+ }
5261
+ function patchNestedNullConditionalDefaults(value, inheritedDefault) {
5262
+ for (const [key, nested] of Object.entries(value)) {
5263
+ if (key === "__computedKeys") {
5264
+ patchComputedEntryDefaults(nested, inheritedDefault);
5265
+ continue;
5266
+ }
5267
+ if (key === "default" || !isPlainStyleObject$1(nested)) continue;
5268
+ let nextDefault = inheritedDefault;
5269
+ if (isConditionalStyleMap(nested)) if (nested.default === null) nested.default = inheritedDefault;
5270
+ else {
5271
+ const nestedDefault = inferDefaultFromValue(nested);
5272
+ if (nestedDefault.kind === "static" && nestedDefault.value !== null) nextDefault = nestedDefault.value;
5273
+ }
5274
+ patchNestedNullConditionalDefaults(nested, nextDefault);
5275
+ }
5276
+ }
5277
+ function computedEntriesHaveNullConditionalDefault(value) {
5278
+ return getComputedEntryValues(value).some((entryValue) => isPlainStyleObject$1(entryValue) && (isConditionalStyleMap(entryValue) && entryValue.default === null || hasNestedNullConditionalDefault(entryValue)) || astObjectHasNullConditionalDefault(entryValue));
5279
+ }
5280
+ function patchComputedEntryDefaults(value, inheritedDefault) {
5281
+ for (const entryValue of getComputedEntryValues(value)) {
5282
+ if (isObjectExpression$2(entryValue)) {
5283
+ patchAstObjectNullConditionalDefaults(entryValue, inheritedDefault);
5284
+ continue;
5285
+ }
5286
+ if (!isPlainStyleObject$1(entryValue)) continue;
5287
+ let nextDefault = inheritedDefault;
5288
+ if (isConditionalStyleMap(entryValue)) if (entryValue.default === null) entryValue.default = inheritedDefault;
5289
+ else {
5290
+ const entryDefault = inferDefaultFromValue(entryValue);
5291
+ if (entryDefault.kind === "static" && entryDefault.value !== null) nextDefault = entryDefault.value;
5292
+ }
5293
+ patchNestedNullConditionalDefaults(entryValue, nextDefault);
5294
+ }
5295
+ }
5296
+ function getComputedEntryValues(value) {
5297
+ if (!Array.isArray(value)) return [];
5298
+ return value.map((entry) => isAstRecord(entry) ? entry.value : void 0);
5299
+ }
5300
+ function patchAstObjectNullConditionalDefaults(value, inheritedDefault) {
5301
+ let nextDefault = inheritedDefault;
5302
+ for (const property of getObjectProperties$1(value)) {
5303
+ if (readPropertyKey$1(property) === "default") {
5304
+ if (isNullLiteral$2(property.value)) property.value = astLiteral(inheritedDefault);
5305
+ else {
5306
+ const staticDefault = readStaticAstLiteral(property.value);
5307
+ if (staticDefault !== void 0 && staticDefault !== null) nextDefault = staticDefault;
5308
+ }
5309
+ continue;
5310
+ }
5311
+ if (isObjectExpression$2(property.value)) patchAstObjectNullConditionalDefaults(property.value, nextDefault);
5312
+ }
5313
+ }
5314
+ function astLiteral(value) {
5315
+ return {
5316
+ type: "Literal",
5317
+ value
5318
+ };
5319
+ }
5320
+ function readStaticAstLiteral(value) {
5321
+ if (!isAstRecord(value)) return;
5322
+ 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;
5323
+ if (value.type === "NullLiteral") return null;
5324
+ }
5325
+ function isStyleConditionKey(key) {
5326
+ return key.startsWith(":") || key.startsWith("@");
5327
+ }
5328
+ function isMetadataOrConditionKey(key) {
5329
+ return key.startsWith("__") || isStyleConditionKey(key);
5330
+ }
5331
+ function isStaticStyleValue(value) {
5332
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null;
5333
+ }
5334
+ function isPlainStyleObject$1(value) {
5335
+ return !!value && typeof value === "object" && !Array.isArray(value) && !isAstNode(value);
5336
+ }
5337
+ function readFunctionReturnedObject$1(node) {
5338
+ if (!isAstRecord(node)) return null;
5339
+ if (node.type !== "ArrowFunctionExpression" && node.type !== "FunctionExpression" && node.type !== "FunctionDeclaration") return null;
5340
+ const body = node.body;
5341
+ if (isObjectExpression$2(body)) return body;
5342
+ if (!isAstRecord(body) || body.type !== "BlockStatement") return null;
5343
+ for (const statement of Array.isArray(body.body) ? body.body : []) if (isAstRecord(statement) && statement.type === "ReturnStatement" && isObjectExpression$2(statement.argument)) return statement.argument;
5344
+ return null;
5345
+ }
5346
+ function getObjectProperties$1(node) {
5347
+ return Array.isArray(node.properties) ? node.properties.filter(isAstRecord) : [];
5348
+ }
5349
+ function readPropertyKey$1(property) {
5350
+ const key = property.key;
5351
+ if (isIdentifier$1(key)) return key.name;
5352
+ if (isAstRecord(key) && (key.type === "StringLiteral" || key.type === "Literal")) return typeof key.value === "string" ? key.value : null;
5353
+ return null;
5354
+ }
5355
+ function isObjectExpression$2(node) {
5356
+ return isAstRecord(node) && node.type === "ObjectExpression";
5357
+ }
5358
+ function isIdentifier$1(node) {
5359
+ return isAstRecord(node) && node.type === "Identifier" && typeof node.name === "string";
5360
+ }
5361
+ function isNullLiteral$2(node) {
5362
+ return isAstRecord(node) && (node.type === "NullLiteral" || node.type === "Literal" && node.value === null);
5363
+ }
5364
+ function isAstRecord(value) {
5365
+ return !!value && typeof value === "object";
5366
+ }
5367
+ //#endregion
5368
+ //#region src/internal/utilities/forwarded-sx-defaults.ts
5369
+ /**
5370
+ * Guards conditional StyleX defaults forwarded through wrapped component `sx`.
5371
+ * Core concepts: sx composition, conditional defaults, and static base proofs.
5372
+ */
5373
+ function guardForwardedSxConditionalDefaults(ctx, styledDecls) {
5374
+ if (!ctx.adapter.useSxProp || !ctx.resolvedStyleObjects) return "ok";
5375
+ for (const decl of styledDecls) {
5376
+ if (decl.base.kind !== "component" || !wrappedComponentForwardsSx(ctx, decl.base.ident)) continue;
5377
+ for (const entry of buildStyleKeySequence(ctx, decl, { includeLocalBase: false })) {
5378
+ const styleObj = entry.styleObj ?? ctx.resolvedStyleObjects.get(entry.styleKey);
5379
+ if (!isRecord(styleObj)) continue;
5380
+ if (guardForwardedSxStyleObject(ctx, decl, styleObj) === "bail") return "bail";
5381
+ for (const prop of functionPropertiesWithNullConditionalDefault(styleObj)) {
5382
+ if (applyForwardedSxDefault({
5383
+ ctx,
5384
+ decl,
5385
+ prop,
5386
+ applyInference: (inferred) => {
5387
+ if (inferred.kind === "static") {
5388
+ setFunctionConditionalDefault(styleObj, prop, inferred.value);
5389
+ return "patched";
5390
+ }
5391
+ return inferred.kind === "absent" ? "safe" : "bail";
5392
+ }
5393
+ }) === "ok") continue;
5394
+ return "bail";
5395
+ }
5396
+ }
5397
+ }
5398
+ return "ok";
5399
+ }
5400
+ function guardForwardedSxStyleObject(ctx, decl, styleObj) {
5401
+ for (const prop of propertiesWithUnsafeNullConditionalDefault(styleObj)) if (applyForwardedSxDefault({
5402
+ ctx,
5403
+ decl,
5404
+ prop,
5405
+ applyInference: (inferred) => {
5406
+ if (inferred.kind !== "static" && inferred.kind !== "absent") return "bail";
5407
+ return patchNullConditionalDefaultsForProp(styleObj, prop, toDefaultInference(inferred));
5408
+ }
5409
+ }) !== "ok") return "bail";
5410
+ return "ok";
5411
+ }
5412
+ function applyForwardedSxDefault(args) {
5413
+ const { ctx, decl, prop, applyInference } = args;
5414
+ const wrappedComponent = decl.base.kind === "component" ? decl.base.ident : "";
5415
+ const inferred = inferWrappedComponentSxProperty(ctx, wrappedComponent, prop);
5416
+ const applied = applyInference(inferred);
5417
+ if (applied === "patched" || applied === "safe") return "ok";
5418
+ ctx.warnings.push({
5419
+ severity: "warning",
5420
+ type: FORWARDED_SX_DEFAULT_WARNING,
5421
+ loc: decl.loc,
5422
+ context: {
5423
+ localName: decl.localName,
5424
+ wrappedComponent,
5425
+ property: prop,
5426
+ reason: inferred.kind === "variable" ? "wrapped component base property can vary before sx is applied" : "wrapped component base default could not be proven",
5427
+ todo: `TODO: set an explicit default for ${prop} or avoid forwarding this conditional override through sx.`
5428
+ }
5429
+ });
5430
+ return "bail";
5431
+ }
5432
+ function toDefaultInference(inferred) {
5433
+ if (inferred.kind === "static") return inferred;
5434
+ if (inferred.kind === "absent") return inferred;
5435
+ return { kind: "dynamic" };
5436
+ }
5437
+ const FORWARDED_SX_DEFAULT_WARNING = "Forwarded sx conditional default would override an unproven wrapped component base style";
5438
+ function wrappedComponentForwardsSx(ctx, componentLocalName) {
5439
+ return wrappedComponentInterfaceFor(ctx, componentLocalName)?.acceptsSx === true;
5440
+ }
5441
+ function inferWrappedComponentSxProperty(ctx, componentLocalName, prop) {
5442
+ const source = readComponentSource(ctx, componentLocalName);
5443
+ if (!source) return { kind: "unknown" };
5444
+ const root = parseSource(ctx.api.jscodeshift, source.source);
5445
+ if (!root) return { kind: "unknown" };
5446
+ const styleMaps = collectStylexCreateMaps(root.ast);
5447
+ const component = findComponentFunction(root.ast, source.componentNames);
5448
+ if (!component) return { kind: "unknown" };
5449
+ const observations = collectSxCompositionObservations(component, collectSxBindings(component), styleMaps, prop);
5450
+ if (observations.length === 0) return { kind: "unknown" };
5451
+ return mergePropertyInferences(observations);
5452
+ }
5453
+ function readComponentSource(ctx, componentLocalName) {
4548
5454
  const importInfo = ctx.importMap?.get(componentLocalName);
4549
- if (importInfo) {
4550
- const typedInterface = importInfo.source.kind === "absolutePath" ? typedComponentInterfaceFor(ctx, importInfo.source.value, importInfo.importedName === "default" ? [componentLocalName, importInfo.importedName] : [importInfo.importedName]) : void 0;
4551
- const adapterResult = ctx.adapter.wrappedComponentInterface?.({
4552
- localName: componentLocalName,
4553
- importSource: importInfo.source.value,
4554
- importedName: importInfo.importedName,
4555
- filePath: ctx.file.path
5455
+ if (!importInfo) return {
5456
+ source: ctx.file.source,
5457
+ componentNames: [componentLocalName]
5458
+ };
5459
+ const absolutePath = importInfo.source.kind === "absolutePath" ? importInfo.source.value : isRelativeSpecifier(importInfo.source.value) ? resolve(dirname(ctx.file.path), importInfo.source.value) : null;
5460
+ if (!absolutePath) return null;
5461
+ const source = readSourceFile(ctx, absolutePath);
5462
+ if (!source) return null;
5463
+ return {
5464
+ source,
5465
+ componentNames: importInfo.importedName === "default" ? [componentLocalName, importInfo.importedName] : [importInfo.importedName]
5466
+ };
5467
+ }
5468
+ function readSourceFile(ctx, absolutePath) {
5469
+ for (const candidate of sourcePathCandidates(absolutePath)) {
5470
+ const override = ctx.options.transformedFileSources?.get(toRealPath(candidate));
5471
+ if (override !== void 0) return override;
5472
+ if (existsSync(candidate)) try {
5473
+ return readFileSync(candidate, "utf8");
5474
+ } catch {
5475
+ continue;
5476
+ }
5477
+ }
5478
+ return null;
5479
+ }
5480
+ function sourcePathCandidates(absolutePath) {
5481
+ return [
5482
+ "",
5483
+ ".tsx",
5484
+ ".ts",
5485
+ ".jsx",
5486
+ ".js",
5487
+ "/index.tsx",
5488
+ "/index.ts",
5489
+ "/index.jsx",
5490
+ "/index.js"
5491
+ ].map((ext) => absolutePath + ext);
5492
+ }
5493
+ function parseSource(jscodeshift, source) {
5494
+ try {
5495
+ return { ast: jscodeshift.withParser("tsx")(source).get().node };
5496
+ } catch {
5497
+ return null;
5498
+ }
5499
+ }
5500
+ function collectStylexCreateMaps(ast) {
5501
+ const maps = /* @__PURE__ */ new Map();
5502
+ walk(ast, (node) => {
5503
+ if (node.type !== "VariableDeclarator") return;
5504
+ const id = node.id;
5505
+ const init = node.init;
5506
+ if (!isIdentifier(id) || !isRecord(init) || !isStylexCreateCall$1(init)) return;
5507
+ const stylesArg = getCallArguments(init)[0];
5508
+ if (!isObjectExpression$1(stylesArg)) return;
5509
+ maps.set(id.name, readStyleEntries(stylesArg));
5510
+ });
5511
+ return maps;
5512
+ }
5513
+ function readStyleEntries(stylexCreateArg) {
5514
+ const entries = /* @__PURE__ */ new Map();
5515
+ for (const property of getObjectProperties(stylexCreateArg)) {
5516
+ const key = readPropertyKey(property);
5517
+ const value = property.value;
5518
+ if (!key || !value) continue;
5519
+ if (isObjectExpression$1(value)) {
5520
+ entries.set(key, {
5521
+ kind: "object",
5522
+ props: readStyleObjectProps(value)
5523
+ });
5524
+ continue;
5525
+ }
5526
+ const returnedObject = readFunctionReturnedObject(value);
5527
+ if (returnedObject) entries.set(key, {
5528
+ kind: "function",
5529
+ props: new Set(readStyleObjectProps(returnedObject).keys())
4556
5530
  });
4557
- if (adapterResult !== void 0) {
4558
- if (adapterResult.acceptsSx && typedInterface?.sxExcludedProperties?.length) return {
4559
- ...adapterResult,
4560
- sxExcludedProperties: mergeUniqueStrings(adapterResult.sxExcludedProperties, typedInterface.sxExcludedProperties)
4561
- };
4562
- return adapterResult;
5531
+ }
5532
+ return entries;
5533
+ }
5534
+ function readStyleObjectProps(styleObject) {
5535
+ const props = /* @__PURE__ */ new Map();
5536
+ for (const property of getObjectProperties(styleObject)) {
5537
+ const key = readPropertyKey(property);
5538
+ if (!key || !property.value) continue;
5539
+ const value = readStaticStyleValue(property.value);
5540
+ props.set(key, value.found ? {
5541
+ kind: "static",
5542
+ value: value.value
5543
+ } : { kind: "dynamic" });
5544
+ }
5545
+ return props;
5546
+ }
5547
+ function readStaticStyleValue(node) {
5548
+ if (!isRecord(node)) return { found: false };
5549
+ if (node.type === "StringLiteral" || node.type === "NumericLiteral" || node.type === "BooleanLiteral") return {
5550
+ found: true,
5551
+ value: node.value
5552
+ };
5553
+ if (node.type === "Literal") {
5554
+ const value = node.value;
5555
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null ? {
5556
+ found: true,
5557
+ value
5558
+ } : { found: false };
5559
+ }
5560
+ if (node.type === "NullLiteral") return {
5561
+ found: true,
5562
+ value: null
5563
+ };
5564
+ if (isObjectExpression$1(node)) {
5565
+ const defaultProp = getObjectProperties(node).find((prop) => readPropertyKey(prop) === "default");
5566
+ return defaultProp?.value ? readStaticStyleValue(defaultProp.value) : { found: false };
5567
+ }
5568
+ return { found: false };
5569
+ }
5570
+ function readFunctionReturnedObject(node) {
5571
+ if (!isRecord(node)) return null;
5572
+ if (node.type !== "ArrowFunctionExpression" && node.type !== "FunctionExpression" && node.type !== "FunctionDeclaration") return null;
5573
+ const body = node.body;
5574
+ if (isObjectExpression$1(body)) return body;
5575
+ if (!isRecord(body) || body.type !== "BlockStatement") return null;
5576
+ const statements = Array.isArray(body.body) ? body.body : [];
5577
+ for (const statement of statements) if (isRecord(statement) && statement.type === "ReturnStatement" && isObjectExpression$1(statement.argument)) return statement.argument;
5578
+ return null;
5579
+ }
5580
+ function functionPropertiesWithNullConditionalDefault(node) {
5581
+ const returnedObject = readFunctionReturnedObject(node);
5582
+ if (!returnedObject) return [];
5583
+ const props = [];
5584
+ for (const property of getObjectProperties(returnedObject)) {
5585
+ const key = readPropertyKey(property);
5586
+ if (!key || !isObjectExpression$1(property.value)) continue;
5587
+ if (objectExpressionHasNullDefault(property.value)) props.push(key);
5588
+ }
5589
+ return props;
5590
+ }
5591
+ function setFunctionConditionalDefault(node, propName, value) {
5592
+ const returnedObject = readFunctionReturnedObject(node);
5593
+ if (!returnedObject) return;
5594
+ for (const property of getObjectProperties(returnedObject)) {
5595
+ if (readPropertyKey(property) !== propName || !isObjectExpression$1(property.value)) continue;
5596
+ setObjectExpressionDefault(property.value, value);
5597
+ }
5598
+ }
5599
+ function objectExpressionHasNullDefault(node) {
5600
+ return getObjectProperties(node).some((property) => {
5601
+ if (readPropertyKey(property) !== "default") return false;
5602
+ return isNullLiteral$1(property.value);
5603
+ });
5604
+ }
5605
+ function setObjectExpressionDefault(node, value) {
5606
+ for (const property of getObjectProperties(node)) if (readPropertyKey(property) === "default") property.value = staticStyleValueToAst(value);
5607
+ }
5608
+ function staticStyleValueToAst(value) {
5609
+ return value === null ? {
5610
+ type: "Literal",
5611
+ value: null
5612
+ } : {
5613
+ type: "Literal",
5614
+ value
5615
+ };
5616
+ }
5617
+ function findComponentFunction(ast, componentNames) {
5618
+ const names = new Set([...componentNames, ...defaultExportedIdentifierNames(ast)]);
5619
+ let found = null;
5620
+ walk(ast, (node) => {
5621
+ if (found) return;
5622
+ if (node.type === "ExportDefaultDeclaration") {
5623
+ const declaration = node.declaration;
5624
+ if (isFunctionLike$1(declaration)) {
5625
+ const declarationId = declaration.id;
5626
+ if (names.has("default") || isIdentifier(declarationId) && names.has(declarationId.name)) found = declaration;
5627
+ return;
5628
+ }
5629
+ if (isIdentifier(declaration)) names.add(declaration.name);
5630
+ return;
4563
5631
  }
4564
- return typedInterface;
5632
+ if (node.type === "FunctionDeclaration" && isIdentifier(node.id) && names.has(node.id.name)) {
5633
+ found = node;
5634
+ return;
5635
+ }
5636
+ if (node.type !== "VariableDeclarator" || !isIdentifier(node.id) || !names.has(node.id.name)) return;
5637
+ if (isFunctionLike$1(node.init)) found = node.init;
5638
+ });
5639
+ return found;
5640
+ }
5641
+ function defaultExportedIdentifierNames(ast) {
5642
+ const names = [];
5643
+ walk(ast, (node) => {
5644
+ if (node.type !== "ExportDefaultDeclaration") return;
5645
+ const declaration = node.declaration;
5646
+ if (isIdentifier(declaration)) names.push(declaration.name);
5647
+ });
5648
+ return names;
5649
+ }
5650
+ function collectSxBindings(component) {
5651
+ const localNames = new Set(["sx"]);
5652
+ const propsNames = /* @__PURE__ */ new Set();
5653
+ for (const param of getFunctionParams(component)) if (isIdentifier(param)) propsNames.add(param.name);
5654
+ else if (isObjectPattern(param)) collectObjectPatternBinding(param, "sx", localNames);
5655
+ walk(component.body, (node) => {
5656
+ if (node.type !== "VariableDeclarator" || !isObjectPattern(node.id) || !isIdentifier(node.init)) return;
5657
+ if (propsNames.has(node.init.name)) collectObjectPatternBinding(node.id, "sx", localNames);
5658
+ });
5659
+ return {
5660
+ localNames,
5661
+ propsNames
5662
+ };
5663
+ }
5664
+ function collectObjectPatternBinding(pattern, propName, out) {
5665
+ const properties = Array.isArray(pattern.properties) ? pattern.properties : [];
5666
+ for (const property of properties) {
5667
+ if (!isRecord(property) || property.type !== "Property") continue;
5668
+ if (readPropertyKey(property) !== propName) continue;
5669
+ const value = unwrapAssignmentPattern(property.value);
5670
+ if (isIdentifier(value)) out.add(value.name);
4565
5671
  }
4566
- return typedComponentInterfaceFor(ctx, ctx.file.path, [componentLocalName]);
4567
5672
  }
4568
- function typedComponentInterfaceFor(ctx, filePath, componentNames) {
4569
- const typedComponent = findTypeScriptComponentMetadata(ctx.options.crossFileInfo?.typeScriptMetadata, filePath, componentNames);
4570
- if (typedComponent?.supportsSxProp) return {
4571
- acceptsSx: true,
4572
- sxExcludedProperties: typedComponent.sxExcludedProperties
5673
+ function collectSxCompositionObservations(component, sxBindings, styleMaps, prop) {
5674
+ const observations = [];
5675
+ walkTopLevelComponentBody(component.body, (node) => {
5676
+ if (node.type === "CallExpression" && isStylexPropsCall(node)) {
5677
+ const beforeSx = argsBeforeSx(getCallArguments(node), sxBindings);
5678
+ if (beforeSx) observations.push(analyzeStyleSequence(beforeSx, styleMaps, prop));
5679
+ return;
5680
+ }
5681
+ if (node.type === "CallExpression" && isMergedSxCall(node)) {
5682
+ const firstArg = getCallArguments(node)[0];
5683
+ const beforeSx = argsBeforeSx(isArrayExpression(firstArg) ? getArrayElements(firstArg) : [], sxBindings);
5684
+ if (beforeSx) observations.push(analyzeStyleSequence(beforeSx, styleMaps, prop));
5685
+ return;
5686
+ }
5687
+ if (node.type === "JSXAttribute" && getJsxAttributeName(node) === "sx") {
5688
+ const expression = readJsxExpression(node.value);
5689
+ const beforeSx = argsBeforeSx(isArrayExpression(expression) ? getArrayElements(expression) : [expression], sxBindings);
5690
+ if (beforeSx) observations.push(analyzeStyleSequence(beforeSx, styleMaps, prop));
5691
+ }
5692
+ });
5693
+ return observations;
5694
+ }
5695
+ function walkTopLevelComponentBody(node, visit) {
5696
+ walk(node, (current) => {
5697
+ if (current !== node && isFunctionLike$1(current)) return "skip";
5698
+ visit(current);
5699
+ });
5700
+ }
5701
+ function argsBeforeSx(args, sxBindings) {
5702
+ const index = args.findIndex((arg) => isSxExpression(arg, sxBindings));
5703
+ return index === -1 ? null : args.slice(0, index);
5704
+ }
5705
+ function analyzeStyleSequence(styleArgs, styleMaps, prop) {
5706
+ let current = { kind: "absent" };
5707
+ for (const arg of styleArgs) {
5708
+ const next = analyzeStyleArg(arg, styleMaps, prop);
5709
+ if (next.kind === "absent") continue;
5710
+ if (next.kind === "unknown" || next.kind === "variable") return next;
5711
+ current = next;
5712
+ }
5713
+ return current;
5714
+ }
5715
+ function analyzeStyleArg(arg, styleMaps, prop) {
5716
+ const node = unwrapExpression(arg);
5717
+ if (!isRecord(node)) return { kind: "absent" };
5718
+ if (isNullishOrBooleanFalse(node)) return { kind: "absent" };
5719
+ const styleRef = readStyleReference(node);
5720
+ if (styleRef) return analyzeStyleReference(styleRef, styleMaps, prop, false);
5721
+ if (node.type === "LogicalExpression" && node.operator === "&&") {
5722
+ const right = analyzeStyleArg(node.right, styleMaps, prop);
5723
+ return right.kind === "absent" ? right : { kind: "variable" };
5724
+ }
5725
+ if (node.type === "ConditionalExpression") {
5726
+ const consequent = analyzeStyleArg(node.consequent, styleMaps, prop);
5727
+ const alternate = analyzeStyleArg(node.alternate, styleMaps, prop);
5728
+ return consequent.kind === "absent" && alternate.kind === "absent" ? { kind: "absent" } : { kind: "variable" };
5729
+ }
5730
+ if (isArrayExpression(node)) return analyzeStyleSequence(getArrayElements(node), styleMaps, prop);
5731
+ if (node.type === "CallExpression") {
5732
+ const callNode = node;
5733
+ const calleeRef = readStyleReference(callNode.callee);
5734
+ if (calleeRef) return analyzeStyleReference(calleeRef, styleMaps, prop, true);
5735
+ if (isStylexDefaultMarkerCall(callNode)) return { kind: "absent" };
5736
+ }
5737
+ return { kind: "unknown" };
5738
+ }
5739
+ function analyzeStyleReference(ref, styleMaps, prop, called) {
5740
+ const styleEntry = styleMaps.get(ref.objectName)?.get(ref.styleKey);
5741
+ if (!styleEntry) return { kind: "unknown" };
5742
+ if (styleEntry.kind === "function") return styleEntry.props.has(prop) ? { kind: "variable" } : { kind: "absent" };
5743
+ const value = styleEntry.props.get(prop);
5744
+ if (!value) return { kind: "absent" };
5745
+ if (called || value.kind === "dynamic") return { kind: "variable" };
5746
+ return {
5747
+ kind: "static",
5748
+ value: value.value
5749
+ };
5750
+ }
5751
+ function mergePropertyInferences(inferences) {
5752
+ let merged = { kind: "absent" };
5753
+ let sawAbsent = false;
5754
+ let sawStatic = false;
5755
+ for (const inference of inferences) {
5756
+ if (inference.kind === "unknown" || inference.kind === "variable") return inference;
5757
+ if (inference.kind === "absent") {
5758
+ if (sawStatic) return { kind: "variable" };
5759
+ sawAbsent = true;
5760
+ continue;
5761
+ }
5762
+ if (sawAbsent) return { kind: "variable" };
5763
+ if (merged.kind === "static" && merged.value !== inference.value) return { kind: "variable" };
5764
+ sawStatic = true;
5765
+ merged = inference;
5766
+ }
5767
+ return merged;
5768
+ }
5769
+ function isStylexCreateCall$1(node) {
5770
+ return isMemberCall(node, "stylex", "create");
5771
+ }
5772
+ function isStylexPropsCall(node) {
5773
+ return isMemberCall(node, "stylex", "props");
5774
+ }
5775
+ function isStylexDefaultMarkerCall(node) {
5776
+ return isMemberCall(node, "stylex", "defaultMarker");
5777
+ }
5778
+ function isMergedSxCall(node) {
5779
+ const callee = isRecord(node) ? node.callee : null;
5780
+ return isIdentifier(callee) && callee.name === "mergedSx";
5781
+ }
5782
+ function isMemberCall(node, objectName, propertyName) {
5783
+ if (!isRecord(node) || node.type !== "CallExpression") return false;
5784
+ const callee = node.callee;
5785
+ return isRecord(callee) && callee.type === "MemberExpression" && isIdentifier(callee.object) && callee.object.name === objectName && isIdentifier(callee.property) && callee.property.name === propertyName;
5786
+ }
5787
+ function readStyleReference(node) {
5788
+ const unwrapped = unwrapExpression(node);
5789
+ if (!isRecord(unwrapped) || unwrapped.type !== "MemberExpression" || unwrapped.computed === true) return null;
5790
+ if (!isIdentifier(unwrapped.object) || !isIdentifier(unwrapped.property)) return null;
5791
+ return {
5792
+ objectName: unwrapped.object.name,
5793
+ styleKey: unwrapped.property.name
4573
5794
  };
4574
5795
  }
4575
- function mergeUniqueStrings(first, second) {
4576
- return [...new Set([...first ?? [], ...second])];
5796
+ function isSxExpression(node, sxBindings) {
5797
+ const unwrapped = unwrapExpression(node);
5798
+ if (isIdentifier(unwrapped)) return sxBindings.localNames.has(unwrapped.name);
5799
+ return isRecord(unwrapped) && unwrapped.type === "MemberExpression" && isIdentifier(unwrapped.object) && sxBindings.propsNames.has(unwrapped.object.name) && isIdentifier(unwrapped.property) && unwrapped.property.name === "sx";
5800
+ }
5801
+ function unwrapExpression(node) {
5802
+ let current = node;
5803
+ while (isRecord(current) && (current.type === "TSAsExpression" || current.type === "TSTypeAssertion" || current.type === "ParenthesizedExpression")) current = current.expression;
5804
+ return current;
5805
+ }
5806
+ function unwrapAssignmentPattern(node) {
5807
+ return isRecord(node) && node.type === "AssignmentPattern" ? node.left : node;
5808
+ }
5809
+ function isNullishOrBooleanFalse(node) {
5810
+ 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);
5811
+ }
5812
+ function isNullLiteral$1(node) {
5813
+ return isRecord(node) && (node.type === "NullLiteral" || node.type === "Literal" && node.value === null);
5814
+ }
5815
+ function isFunctionLike$1(node) {
5816
+ return isRecord(node) && (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression");
5817
+ }
5818
+ function isObjectPattern(node) {
5819
+ return isRecord(node) && node.type === "ObjectPattern";
5820
+ }
5821
+ function isObjectExpression$1(node) {
5822
+ return isRecord(node) && node.type === "ObjectExpression";
5823
+ }
5824
+ function isArrayExpression(node) {
5825
+ return isRecord(node) && node.type === "ArrayExpression";
5826
+ }
5827
+ function isIdentifier(node) {
5828
+ return isRecord(node) && node.type === "Identifier" && typeof node.name === "string";
5829
+ }
5830
+ function isRecord(value) {
5831
+ return !!value && typeof value === "object";
5832
+ }
5833
+ function getCallArguments(node) {
5834
+ return Array.isArray(node.arguments) ? node.arguments : [];
5835
+ }
5836
+ function getArrayElements(node) {
5837
+ return Array.isArray(node.elements) ? node.elements.filter((element) => element != null) : [];
5838
+ }
5839
+ function getObjectProperties(node) {
5840
+ return Array.isArray(node.properties) ? node.properties.filter(isRecord) : [];
5841
+ }
5842
+ function getFunctionParams(node) {
5843
+ return Array.isArray(node.params) ? node.params : [];
5844
+ }
5845
+ function readPropertyKey(property) {
5846
+ const key = property.key;
5847
+ if (isIdentifier(key)) return key.name;
5848
+ if (isRecord(key) && (key.type === "StringLiteral" || key.type === "Literal")) return typeof key.value === "string" ? key.value : null;
5849
+ return null;
5850
+ }
5851
+ function getJsxAttributeName(node) {
5852
+ const name = node.name;
5853
+ return isRecord(name) && name.type === "JSXIdentifier" && typeof name.name === "string" ? name.name : null;
5854
+ }
5855
+ function readJsxExpression(value) {
5856
+ return isRecord(value) && value.type === "JSXExpressionContainer" ? value.expression : value;
5857
+ }
5858
+ function walk(node, visit, seen = /* @__PURE__ */ new WeakSet()) {
5859
+ if (!isRecord(node)) return;
5860
+ if (seen.has(node)) return;
5861
+ seen.add(node);
5862
+ if (visit(node) === "skip") return;
5863
+ for (const [key, value] of Object.entries(node)) {
5864
+ if (key === "loc" || key === "comments" || key === "tokens") continue;
5865
+ if (Array.isArray(value)) for (const child of value) walk(child, visit, seen);
5866
+ else if (isRecord(value)) walk(value, visit, seen);
5867
+ }
4577
5868
  }
4578
5869
  //#endregion
4579
5870
  //#region src/internal/transform-steps/analyze-before-emit.ts
4580
5871
  const INLINE_USAGE_THRESHOLD = 1;
5872
+ const REACT_WINDOW_SOURCE = "react-window";
5873
+ const REACT_WINDOW_ELEMENT_TYPE_PROPS = new Set(["innerElementType", "outerElementType"]);
5874
+ const REACT_WINDOW_COMPONENT_EXPORTS = new Set([
5875
+ "FixedSizeGrid",
5876
+ "FixedSizeList",
5877
+ "Grid",
5878
+ "List",
5879
+ "VariableSizeGrid",
5880
+ "VariableSizeList"
5881
+ ]);
4581
5882
  /**
4582
5883
  * Analyzes declarations to determine wrappers, exports, usage patterns, and import aliasing before emit.
4583
5884
  */
@@ -4625,8 +5926,7 @@ function analyzeBeforeEmitStep(ctx) {
4625
5926
  if (decl.base.kind === "intrinsic" && (decl.attrsInfo?.conditionalAttrs?.length ?? 0) > 0) decl.needsWrapperComponent = true;
4626
5927
  if (decl.base.kind === "intrinsic" && (decl.attrsInfo?.defaultAttrs?.length ?? 0) > 0) decl.needsWrapperComponent = true;
4627
5928
  if (decl.base.kind === "intrinsic" && (decl.attrsInfo?.dynamicAttrs?.length ?? 0) > 0) decl.needsWrapperComponent = true;
4628
- const resolverOnlyShouldForwardProp = !!decl.inlinedBaseComponent && !decl.shouldForwardPropFromWithConfig;
4629
- if (decl.shouldForwardProp && !resolverOnlyShouldForwardProp) decl.needsWrapperComponent = true;
5929
+ if (needsShouldForwardPropWrapper(decl)) decl.needsWrapperComponent = true;
4630
5930
  if (decl.base.kind === "intrinsic" && decl.withConfig?.componentId) decl.needsWrapperComponent = true;
4631
5931
  if (extendedBy.has(decl.localName) && componentsWithStaticProps.has(decl.localName)) decl.needsWrapperComponent = true;
4632
5932
  if (exportedComponents.has(decl.localName)) decl.needsWrapperComponent = true;
@@ -4730,7 +6030,7 @@ function analyzeBeforeEmitStep(ctx) {
4730
6030
  const { className, style, ref } = getJsxAttributeUsage(targetDecl.localName);
4731
6031
  return targetDecl.base.kind === "intrinsic" && !targetDecl.isExported && !targetDecl.needsWrapperComponent && !className && !style && !ref && !hasSpreadInJsx(root, j, targetDecl.localName);
4732
6032
  };
4733
- const hasNonJsxComponentValueReference = (name) => root.find(j.Identifier, { name }).filter((p) => {
6033
+ const nonJsxComponentValueReferences = (name) => root.find(j.Identifier, { name }).filter((p) => {
4734
6034
  if (p.parentPath?.node?.type === "VariableDeclarator" && p.parentPath.node.id === p.node) return false;
4735
6035
  if (p.parentPath?.node?.type === "JSXOpeningElement" || p.parentPath?.node?.type === "JSXClosingElement") return false;
4736
6036
  if (p.parentPath?.node?.type === "JSXMemberExpression" && p.parentPath.node.object === p.node) return false;
@@ -4743,7 +6043,20 @@ function analyzeBeforeEmitStep(ctx) {
4743
6043
  if (p.parentPath?.node?.type === "CallExpression" && p.parentPath.parentPath?.node?.type === "TaggedTemplateExpression") return false;
4744
6044
  if (p.parentPath?.node?.type === "TemplateLiteral") return false;
4745
6045
  return true;
4746
- }).size() > 0;
6046
+ });
6047
+ const hasNonJsxComponentValueReference = (name) => nonJsxComponentValueReferences(name).size() > 0;
6048
+ const hasOnlyVirtualListElementTypeValueReferences = (name) => {
6049
+ const refs = nonJsxComponentValueReferences(name);
6050
+ if (refs.size() === 0) return false;
6051
+ let onlyVirtualListElementType = true;
6052
+ refs.forEach((p) => {
6053
+ const expressionContainer = p.parentPath?.node;
6054
+ const attr = p.parentPath?.parentPath?.node;
6055
+ const attrName = attr?.name;
6056
+ 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;
6057
+ });
6058
+ return onlyVirtualListElementType;
6059
+ };
4747
6060
  for (const decl of styledDecls) {
4748
6061
  if (!decl.adjacentSiblingStyleKey) continue;
4749
6062
  const { className, style, ref } = getJsxAttributeUsage(decl.localName);
@@ -5014,6 +6327,7 @@ function analyzeBeforeEmitStep(ctx) {
5014
6327
  if (decl.isDirectJsxResolution) continue;
5015
6328
  if (hasNonJsxComponentValueReference(decl.localName)) {
5016
6329
  decl.usedAsValue = true;
6330
+ if (hasOnlyVirtualListElementTypeValueReferences(decl.localName)) decl.valueUsageKind = "virtualListElementType";
5017
6331
  decl.needsWrapperComponent = true;
5018
6332
  }
5019
6333
  }
@@ -5110,7 +6424,7 @@ function analyzeBeforeEmitStep(ctx) {
5110
6424
  let cur = p.parentPath;
5111
6425
  while (cur) {
5112
6426
  const node = cur.node;
5113
- if (isFunctionNode(node) || node?.type === "MethodDefinition") return true;
6427
+ if (isFunctionNode$1(node) || node?.type === "MethodDefinition") return true;
5114
6428
  cur = cur.parentPath;
5115
6429
  }
5116
6430
  return false;
@@ -5151,6 +6465,18 @@ function analyzeBeforeEmitStep(ctx) {
5151
6465
  code: null,
5152
6466
  warnings: ctx.warnings
5153
6467
  }, "bail");
6468
+ if (!validateWrappedComponentStyleChannels(ctx, styledDecls)) return returnResult({
6469
+ code: null,
6470
+ warnings: ctx.warnings
6471
+ }, "bail");
6472
+ if (guardGeneratedConditionalDefaults(ctx, styledDecls) === "bail") return returnResult({
6473
+ code: null,
6474
+ warnings: ctx.warnings
6475
+ }, "bail");
6476
+ if (guardForwardedSxConditionalDefaults(ctx, styledDecls) === "bail") return returnResult({
6477
+ code: null,
6478
+ warnings: ctx.warnings
6479
+ }, "bail");
5154
6480
  const existingStylexTarget = findExistingStylexStylesTarget({
5155
6481
  ctx,
5156
6482
  styledDeclNames,
@@ -6088,6 +7414,11 @@ function coerceToStringForStyleX(cssProp, value) {
6088
7414
  */
6089
7415
  function inferTypeForCssProp(cssProp, expr) {
6090
7416
  if (isStylexStringOnlyCssProp(cssProp)) return "string";
7417
+ const conditionalType = inferTypeFromConditionalBranches(expr);
7418
+ if (conditionalType) {
7419
+ if (conditionalType === "number" && LENGTH_LIKE_CSS_PROP_RE.test(cssProp)) return "numberOrString";
7420
+ return conditionalType;
7421
+ }
6091
7422
  const staticVal = literalToStaticValue(expr);
6092
7423
  if (typeof staticVal === "number") return "number";
6093
7424
  if (typeof staticVal === "string") return "string";
@@ -6095,6 +7426,25 @@ function inferTypeForCssProp(cssProp, expr) {
6095
7426
  if (LENGTH_LIKE_CSS_PROP_RE.test(cssProp)) return "numberOrString";
6096
7427
  return "string";
6097
7428
  }
7429
+ function inferTypeFromConditionalBranches(expr) {
7430
+ if (!expr || typeof expr !== "object") return null;
7431
+ const node = expr;
7432
+ if (node.type !== "ConditionalExpression") return null;
7433
+ const consequent = inferTypeFromExpressionValue(node.consequent);
7434
+ const alternate = inferTypeFromExpressionValue(node.alternate);
7435
+ if (!consequent || !alternate) return null;
7436
+ if (consequent === alternate) return consequent;
7437
+ return "numberOrString";
7438
+ }
7439
+ function inferTypeFromExpressionValue(expr) {
7440
+ const nested = inferTypeFromConditionalBranches(expr);
7441
+ if (nested) return nested;
7442
+ if (expr && typeof expr === "object" && expr.type === "TemplateLiteral") return "string";
7443
+ const value = literalToStaticValue(expr);
7444
+ if (typeof value === "string") return "string";
7445
+ if (typeof value === "number") return "number";
7446
+ return null;
7447
+ }
6098
7448
  /**
6099
7449
  * Analyzes JSX call-site `style={{ ... }}` objects for all intrinsic styled components
6100
7450
  * and promotes analyzable style objects to proper `stylex.create` entries.
@@ -6182,7 +7532,7 @@ function analyzePromotableStyleProps(root, j, styledDecls, allStyledDecls, declB
6182
7532
  siteBail = true;
6183
7533
  break;
6184
7534
  }
6185
- if (!isValidIdentifierName$1(keyName)) {
7535
+ if (!isValidIdentifierName(keyName)) {
6186
7536
  siteBail = true;
6187
7537
  break;
6188
7538
  }
@@ -6949,13 +8299,47 @@ function validateSxRestrictedWrappedComponentStyles(ctx, styledDecls) {
6949
8299
  if (decl.skipTransform || decl.base.kind !== "component") continue;
6950
8300
  const componentInterface = wrappedComponentInterfaceFor(ctx, decl.base.ident);
6951
8301
  const excludedProperties = componentInterface?.sxExcludedProperties;
6952
- if (componentInterface?.acceptsSx !== true || !excludedProperties?.length) continue;
6953
- const excluded = new Set(excludedProperties);
8302
+ const allowedProperties = componentInterface?.sxAllowedProperties;
8303
+ const hasAllowedProperties = allowedProperties !== void 0;
8304
+ if (componentInterface?.acceptsSx !== true || !excludedProperties?.length && !hasAllowedProperties && !componentInterface.rootOnlyProperties?.length) continue;
8305
+ const excluded = new Set(excludedProperties ?? []);
8306
+ const allowed = hasAllowedProperties ? new Set(allowedProperties) : null;
8307
+ const rootOnly = componentInterface.sxTarget === "inner" && componentInterface.rootOnlyProperties?.length ? new Set(componentInterface.rootOnlyProperties) : null;
6954
8308
  for (const styleKey of collectAllStyleKeysForDecl(decl)) {
6955
8309
  const style = ctx.resolvedStyleObjects.get(styleKey);
6956
8310
  if (!style || typeof style !== "object") continue;
6957
- const rejectedProperty = findSxExcludedStyleProperty(style, excluded);
6958
- if (!rejectedProperty) continue;
8311
+ const rootOnlyProperty = rootOnly ? findSxExcludedStyleProperty(style, rootOnly) : null;
8312
+ if (rootOnlyProperty) {
8313
+ ctx.warnings.push({
8314
+ severity: "error",
8315
+ type: "Wrapped component sx prop targets an inner element for a root style property",
8316
+ loc: decl.loc,
8317
+ context: {
8318
+ localName: decl.localName,
8319
+ wrappedComponent: decl.base.ident,
8320
+ styleKey,
8321
+ property: rootOnlyProperty
8322
+ }
8323
+ });
8324
+ return false;
8325
+ }
8326
+ const rejectedProperty = excluded.size > 0 ? findSxExcludedStyleProperty(style, excluded) : null;
8327
+ if (!rejectedProperty) {
8328
+ const disallowedProperty = allowed ? findSxDisallowedStyleProperty(style, allowed) : null;
8329
+ if (!disallowedProperty) continue;
8330
+ ctx.warnings.push({
8331
+ severity: "error",
8332
+ type: "Wrapped component sx prop does not accept generated StyleX property",
8333
+ loc: decl.loc,
8334
+ context: {
8335
+ localName: decl.localName,
8336
+ wrappedComponent: decl.base.ident,
8337
+ styleKey,
8338
+ property: disallowedProperty
8339
+ }
8340
+ });
8341
+ return false;
8342
+ }
6959
8343
  ctx.warnings.push({
6960
8344
  severity: "error",
6961
8345
  type: "Wrapped component sx prop rejects logical CSS properties that cannot be preserved losslessly",
@@ -6972,6 +8356,70 @@ function validateSxRestrictedWrappedComponentStyles(ctx, styledDecls) {
6972
8356
  }
6973
8357
  return true;
6974
8358
  }
8359
+ function validateWrappedComponentStyleChannels(ctx, styledDecls) {
8360
+ if (!ctx.resolvedStyleObjects) return true;
8361
+ for (const decl of styledDecls) {
8362
+ if (decl.skipTransform || decl.base.kind !== "component") continue;
8363
+ const baseIdent = decl.base.ident;
8364
+ if (styledDecls.some((candidate) => candidate.localName === baseIdent)) continue;
8365
+ const importInfo = ctx.importMap?.get(baseIdent);
8366
+ const isLocalNonStyledWrappedComponent = !importInfo && isLocalFunctionComponent(ctx.root, ctx.j, baseIdent);
8367
+ if (!importInfo && !isLocalNonStyledWrappedComponent) continue;
8368
+ if (importInfo?.source.kind === "absolutePath" && ctx.options.transformedFileSources?.has(resolveExistingFilePath(importInfo.source.value))) continue;
8369
+ if (!declHasEmittedStyle(ctx, decl)) continue;
8370
+ if (wrappedComponentInterfaceFor(ctx, baseIdent)?.acceptsSx === true) continue;
8371
+ const metadata = findWrappedComponentMetadata(ctx, baseIdent);
8372
+ if (!metadata || componentAcceptsStylexClassName(metadata)) continue;
8373
+ if (isLocalNonStyledWrappedComponent && !hasInlineObjectPropType(metadata)) continue;
8374
+ ctx.warnings.push({
8375
+ severity: "error",
8376
+ type: "Wrapped component does not accept className or sx for generated StyleX styles",
8377
+ loc: decl.loc,
8378
+ context: {
8379
+ localName: decl.localName,
8380
+ wrappedComponent: decl.base.ident
8381
+ }
8382
+ });
8383
+ return false;
8384
+ }
8385
+ return true;
8386
+ }
8387
+ function declHasEmittedStyle(ctx, decl) {
8388
+ for (const styleKey of collectAllStyleKeysForDecl(decl)) if (ctx.resolvedStyleObjects?.has(styleKey)) return true;
8389
+ return false;
8390
+ }
8391
+ function findWrappedComponentMetadata(ctx, componentLocalName) {
8392
+ const metadata = ctx.options.crossFileInfo?.typeScriptMetadata;
8393
+ const importInfo = ctx.importMap?.get(componentLocalName);
8394
+ if (importInfo?.source.kind === "absolutePath") return findTypeScriptComponentMetadata(metadata, importInfo.source.value, [importInfo.importedName, componentLocalName]);
8395
+ return findTypeScriptComponentMetadata(metadata, ctx.file.path, [componentLocalName]);
8396
+ }
8397
+ function componentAcceptsStylexClassName(metadata) {
8398
+ if (metadata.propType && isIntrinsicReactPropsTypeText(metadata.propType.text)) return true;
8399
+ if (metadata.hasIndexSignature) return true;
8400
+ if (metadata.explicitPropNames.includes("className")) return true;
8401
+ return metadata.props.some((prop) => prop.name === "className");
8402
+ }
8403
+ function isIntrinsicReactPropsTypeText(typeText) {
8404
+ return /^(?:[$A-Z_a-z][$\w]*\.)*ComponentProps(?:WithRef|WithoutRef)?\s*<\s*(['"])[^'"]+\1\s*>$/.test(typeText.trim());
8405
+ }
8406
+ function hasInlineObjectPropType(metadata) {
8407
+ return metadata.propType?.text.trim().startsWith("{") === true;
8408
+ }
8409
+ function findSxDisallowedStyleProperty(style, allowedProperties) {
8410
+ if (isAstNode(style)) return findSxDisallowedStylePropertyInAstNode(style, allowedProperties);
8411
+ for (const [key, value] of Object.entries(style)) {
8412
+ if (isStylexConditionKey(key)) {
8413
+ if (value && typeof value === "object") {
8414
+ const nested = findSxDisallowedStyleProperty(value, allowedProperties);
8415
+ if (nested) return nested;
8416
+ }
8417
+ continue;
8418
+ }
8419
+ if (!allowedProperties.has(key)) return key;
8420
+ }
8421
+ return null;
8422
+ }
6975
8423
  function staticObjectPropertyName(prop) {
6976
8424
  if (!prop || typeof prop !== "object") return null;
6977
8425
  const p = prop;
@@ -6982,6 +8430,29 @@ function staticObjectPropertyName(prop) {
6982
8430
  if (key.type === "Literal" || key.type === "StringLiteral") return typeof key.value === "string" ? key.value : null;
6983
8431
  return null;
6984
8432
  }
8433
+ function isKnownReactWindowElementTypeAttribute(attrPath, importMap) {
8434
+ const openingElement = attrPath?.parentPath?.node;
8435
+ if (openingElement?.type !== "JSXOpeningElement") return false;
8436
+ return jsxNameIsKnownReactWindowComponent(openingElement.name, importMap);
8437
+ }
8438
+ function jsxNameIsKnownReactWindowComponent(jsxName, importMap) {
8439
+ const name = jsxName;
8440
+ if (name.type === "JSXIdentifier") return localNameIsReactWindowComponent(name.name, importMap);
8441
+ if (name.type !== "JSXMemberExpression") return false;
8442
+ const namespace = name.object;
8443
+ const member = name.property;
8444
+ if (namespace?.type !== "JSXIdentifier" || member?.type !== "JSXIdentifier" || !REACT_WINDOW_COMPONENT_EXPORTS.has(member.name ?? "")) return false;
8445
+ const importInfo = namespace.name ? importMap?.get(namespace.name) : void 0;
8446
+ return importInfo?.source.value === REACT_WINDOW_SOURCE && importInfo.importedName === "*";
8447
+ }
8448
+ function localNameIsReactWindowComponent(localName, importMap) {
8449
+ if (!localName) return false;
8450
+ const importInfo = importMap?.get(localName);
8451
+ return importInfo?.source.value === REACT_WINDOW_SOURCE && REACT_WINDOW_COMPONENT_EXPORTS.has(importInfo.importedName);
8452
+ }
8453
+ function isStylexConditionKey(key) {
8454
+ return key === "default" || key === "__computedKeys" || key.startsWith(":") || key.startsWith("@") || key.startsWith("stylex.when");
8455
+ }
6985
8456
  function findSxExcludedStyleProperty(style, excludedProperties) {
6986
8457
  if (isAstNode(style)) return findSxExcludedStylePropertyInAstNode(style, excludedProperties);
6987
8458
  for (const [key, value] of Object.entries(style)) {
@@ -7017,6 +8488,34 @@ function findSxExcludedStylePropertyInAstNode(node, excludedProperties) {
7017
8488
  }
7018
8489
  return null;
7019
8490
  }
8491
+ function findSxDisallowedStylePropertyInAstNode(node, allowedProperties) {
8492
+ const n = node;
8493
+ if (n.type === "ObjectExpression") {
8494
+ for (const prop of n.properties ?? []) {
8495
+ const name = staticObjectPropertyName(prop);
8496
+ const value = prop.value;
8497
+ if (!name) {
8498
+ if (value && typeof value === "object") {
8499
+ const nested = findSxDisallowedStylePropertyInAstNode(value, allowedProperties);
8500
+ if (nested) return nested;
8501
+ }
8502
+ continue;
8503
+ }
8504
+ if (isStylexConditionKey(name)) {
8505
+ if (value && typeof value === "object") {
8506
+ const nested = findSxDisallowedStylePropertyInAstNode(value, allowedProperties);
8507
+ if (nested) return nested;
8508
+ }
8509
+ continue;
8510
+ }
8511
+ if (!allowedProperties.has(name)) return name;
8512
+ }
8513
+ return null;
8514
+ }
8515
+ if (n.type === "ArrowFunctionExpression" && n.body && typeof n.body === "object") return findSxDisallowedStylePropertyInAstNode(n.body, allowedProperties);
8516
+ if (n.type === "ParenthesizedExpression" && n.expression && typeof n.expression === "object") return findSxDisallowedStylePropertyInAstNode(n.expression, allowedProperties);
8517
+ return null;
8518
+ }
7020
8519
  //#endregion
7021
8520
  //#region src/internal/policy.ts
7022
8521
  function collectCreateGlobalStyleWarnings(styledImports) {
@@ -7955,6 +9454,32 @@ function findEnclosingFunction(path) {
7955
9454
  }
7956
9455
  return null;
7957
9456
  }
9457
+ function collectStyledComponentLocalNames(root, j, styledLocalNames) {
9458
+ const names = /* @__PURE__ */ new Set();
9459
+ root.find(j.VariableDeclarator).forEach((path) => {
9460
+ if (path.node.id?.type !== "Identifier") return;
9461
+ const init = path.node.init;
9462
+ if (!init) return;
9463
+ if (init.type === "TaggedTemplateExpression" && isStyledTag(styledLocalNames, init.tag)) {
9464
+ names.add(path.node.id.name);
9465
+ return;
9466
+ }
9467
+ if (init.type === "CallExpression" && init.callee?.type === "TaggedTemplateExpression" && isStyledTag(styledLocalNames, init.callee.tag)) names.add(path.node.id.name);
9468
+ });
9469
+ return names;
9470
+ }
9471
+ function templateReferencesStyledComponentSelector(template, styledLocalNames) {
9472
+ const parsed = parseStyledTemplateLiteral(template);
9473
+ for (const slot of parsed.slots) {
9474
+ const expr = slot.expression;
9475
+ if (expr.type !== "Identifier" || !expr.name || !styledLocalNames.has(expr.name)) continue;
9476
+ const after = parsed.rawCss.slice(slot.endOffset);
9477
+ const nextBlockStart = after.indexOf("{");
9478
+ const nextDeclarationEnd = after.indexOf(";");
9479
+ if (nextBlockStart >= 0 && (nextDeclarationEnd < 0 || nextBlockStart < nextDeclarationEnd)) return true;
9480
+ }
9481
+ return false;
9482
+ }
7958
9483
  /**
7959
9484
  * Checks a CSS template for closure variable references and returns an UnsupportedCssUsage
7960
9485
  * if any are found. Returns null if no closure variables are detected.
@@ -8100,8 +9625,11 @@ function detectUnsupportedCssHelperUsage(args) {
8100
9625
  return unsupportedUsages;
8101
9626
  }
8102
9627
  function extractAndRemoveCssHelpers(args) {
8103
- const { root, j, styledImports, cssLocal, toStyleKey, preserveDeclarationOnlyNames } = args;
9628
+ const { root, j, styledImports, cssLocal, toStyleKey, preserveDeclarationOnlyNames, preservedStyledComponentSelectorNames } = args;
8104
9629
  const styledLocalNames = collectStyledDefaultImportLocalNames(styledImports);
9630
+ const styledComponentLocalNames = collectStyledComponentLocalNames(root, j, styledLocalNames);
9631
+ const preservedSelectorNames = preservedStyledComponentSelectorNames ?? /* @__PURE__ */ new Set();
9632
+ const rewrittenStyledComponentLocalNames = new Set([...styledComponentLocalNames].filter((name) => !preservedSelectorNames.has(name)));
8105
9633
  const exportedLocalNames = buildExportedLocalNames(root, j);
8106
9634
  const cssHelperFunctions = /* @__PURE__ */ new Map();
8107
9635
  const cssHelperNames = /* @__PURE__ */ new Set();
@@ -8157,12 +9685,20 @@ function extractAndRemoveCssHelpers(args) {
8157
9685
  const styleKey = toStyleKey(localName);
8158
9686
  const placementHints = getCssHelperPlacementHints(root, p);
8159
9687
  const isExported = exportedLocalNames.has(localName);
8160
- const preserveDeclarationOnly = preserveDeclarationOnlyNames?.has(localName) ?? false;
8161
9688
  const template = init.quasi;
8162
9689
  const { rules, rawCss, templateExpressions } = parseCssHelperTemplate({
8163
9690
  template,
8164
9691
  noteUniversalSelector: noteCssHelperUniversalSelector
8165
9692
  });
9693
+ if (isExported && templateReferencesStyledComponentSelector(template, rewrittenStyledComponentLocalNames)) {
9694
+ unsupportedCssUsages.push({
9695
+ loc: getNodeLocStart(template),
9696
+ reason: "outside-styled-template"
9697
+ });
9698
+ return;
9699
+ }
9700
+ if (isExported && templateReferencesStyledComponentSelector(template, preservedSelectorNames)) return;
9701
+ const preserveDeclarationOnly = preserveDeclarationOnlyNames?.has(localName) ?? false;
8166
9702
  cssHelperDecls.push({
8167
9703
  ...placementHints,
8168
9704
  localName,
@@ -8205,6 +9741,18 @@ function extractAndRemoveCssHelpers(args) {
8205
9741
  }
8206
9742
  changed = true;
8207
9743
  });
9744
+ if (unsupportedCssUsages.length > 0) return {
9745
+ unsupportedCssUsages,
9746
+ cssHelperFunctions,
9747
+ cssHelperNames,
9748
+ cssHelperObjectMembers,
9749
+ cssHelperDecls,
9750
+ cssHelperHasUniversalSelectors,
9751
+ cssHelperUniversalSelectorLoc,
9752
+ cssHelperReplacements,
9753
+ cssHelperTemplateReplacements,
9754
+ changed
9755
+ };
8208
9756
  root.find(j.VariableDeclarator, { init: { type: "ArrowFunctionExpression" } }).forEach((p) => {
8209
9757
  if (p.node.id.type !== "Identifier") return;
8210
9758
  const name = p.node.id.name;
@@ -8456,10 +10004,6 @@ function cleanupCssImportStep(ctx) {
8456
10004
  //#endregion
8457
10005
  //#region src/internal/transform-steps/collect-static-props.ts
8458
10006
  /**
8459
- * Step: collect static property assignments on styled components.
8460
- * Core concepts: static metadata capture and inheritance generation.
8461
- */
8462
- /**
8463
10007
  * Collects static property assignments and generates inheritance statements.
8464
10008
  */
8465
10009
  function collectStaticPropsStep(ctx) {
@@ -8470,9 +10014,10 @@ function collectStaticPropsStep(ctx) {
8470
10014
  const staticPropertyAssignments = /* @__PURE__ */ new Map();
8471
10015
  const staticPropertyNames = /* @__PURE__ */ new Map();
8472
10016
  const styledNames = new Set(styledDecls.map((d) => d.localName));
10017
+ const objectExpressionByName = collectObjectExpressionVariables(root, j);
8473
10018
  const baseComponentNames = /* @__PURE__ */ new Set();
8474
10019
  for (const decl of styledDecls) {
8475
- const baseIdent = decl.originalBaseIdent ?? (decl.base.kind === "component" ? decl.base.ident : null);
10020
+ const baseIdent = getEffectiveBaseIdent(decl);
8476
10021
  if (baseIdent && !styledNames.has(baseIdent)) baseComponentNames.add(baseIdent);
8477
10022
  }
8478
10023
  root.find(j.ExpressionStatement).filter((p) => {
@@ -8486,12 +10031,8 @@ function collectStaticPropsStep(ctx) {
8486
10031
  }).forEach((p) => {
8487
10032
  const expr = p.node.expression;
8488
10033
  const componentName = expr.left.object.name;
8489
- const propName = expr.left.property?.name ?? expr.left.property?.value;
8490
- if (propName) {
8491
- const names = staticPropertyNames.get(componentName) ?? [];
8492
- names.push(propName);
8493
- staticPropertyNames.set(componentName, names);
8494
- }
10034
+ const propName = getStaticPropertyNameFromMemberExpression(expr.left);
10035
+ if (propName) addStaticPropertyName(staticPropertyNames, componentName, propName);
8495
10036
  if (baseComponentNames.has(componentName)) return;
8496
10037
  if (ctx.exportedComponents?.has(componentName) || ctx.extendedBy?.has(componentName)) {
8497
10038
  const existing = staticPropertyAssignments.get(componentName) ?? [];
@@ -8500,23 +10041,37 @@ function collectStaticPropsStep(ctx) {
8500
10041
  }
8501
10042
  j(p).remove();
8502
10043
  });
10044
+ root.find(j.CallExpression).forEach((path) => {
10045
+ const callee = path.node.callee;
10046
+ if (callee?.type !== "MemberExpression" || callee.object?.type !== "Identifier" || callee.object.name !== "Object" || callee.property?.type !== "Identifier" || callee.property.name !== "assign") return;
10047
+ const parent = path.parentPath?.node;
10048
+ const assignedName = parent?.type === "VariableDeclarator" && parent.id?.type === "Identifier" ? parent.id.name : null;
10049
+ const target = path.node.arguments?.[0];
10050
+ if (target?.type !== "Identifier") return;
10051
+ const componentNames = [target.name, ...assignedName ? [assignedName] : []].filter((name, index, names) => names.indexOf(name) === index && baseComponentNames.has(name));
10052
+ if (componentNames.length === 0) return;
10053
+ for (const componentName of componentNames) for (const source of path.node.arguments.slice(1)) {
10054
+ const statics = getObjectAssignStaticSource(source, objectExpressionByName);
10055
+ if (!statics) continue;
10056
+ for (const prop of statics.properties ?? []) {
10057
+ const propName = getStaticPropertyNameFromObjectProperty(prop);
10058
+ if (propName) addStaticPropertyName(staticPropertyNames, componentName, propName);
10059
+ }
10060
+ }
10061
+ });
8503
10062
  for (const decl of styledDecls) {
8504
- const baseIdent = decl.originalBaseIdent ?? (decl.base.kind === "component" ? decl.base.ident : null);
10063
+ const baseIdent = getEffectiveBaseIdent(decl);
8505
10064
  if (!baseIdent) continue;
8506
10065
  const baseComponentName = ctx.declByLocal.get(baseIdent)?.localName ?? baseIdent;
8507
10066
  const baseProps = staticPropertyNames.get(baseComponentName);
8508
10067
  if (!baseProps || baseProps.length === 0) continue;
8509
10068
  if ((staticPropertyAssignments.get(decl.localName) ?? []).length > 0) continue;
8510
10069
  const inheritanceStatements = [];
8511
- for (const propName of baseProps) {
8512
- const rhs = ctx.j(`const __x = (${baseComponentName} as any).${propName};`).get().node.program.body[0].declarations[0].init;
8513
- const stmt = ctx.j.expressionStatement(ctx.j.assignmentExpression("=", ctx.j.memberExpression(ctx.j.identifier(decl.localName), ctx.j.identifier(propName)), rhs));
8514
- inheritanceStatements.push(stmt);
8515
- }
10070
+ for (const propName of baseProps) inheritanceStatements.push(buildStaticInheritanceStatement(ctx.j, decl.localName, baseComponentName, propName));
8516
10071
  if (inheritanceStatements.length > 0) staticPropertyAssignments.set(decl.localName, inheritanceStatements);
8517
10072
  }
8518
10073
  for (const decl of styledDecls) {
8519
- const baseIdent = decl.originalBaseIdent ?? (decl.base.kind === "component" ? decl.base.ident : null);
10074
+ const baseIdent = getEffectiveBaseIdent(decl);
8520
10075
  if (!baseIdent) continue;
8521
10076
  if (ctx.declByLocal.has(baseIdent)) continue;
8522
10077
  if (staticPropertyNames.has(baseIdent)) continue;
@@ -8558,6 +10113,46 @@ function collectStaticPropsStep(ctx) {
8558
10113
  ctx.staticPropertyNames = staticPropertyNames;
8559
10114
  return CONTINUE;
8560
10115
  }
10116
+ function collectObjectExpressionVariables(root, j) {
10117
+ const objectExpressionByName = /* @__PURE__ */ new Map();
10118
+ root.find(j.VariableDeclarator).forEach((path) => {
10119
+ if (path.node.id?.type === "Identifier" && path.node.init?.type === "ObjectExpression") objectExpressionByName.set(path.node.id.name, path.node.init);
10120
+ });
10121
+ return objectExpressionByName;
10122
+ }
10123
+ function getObjectAssignStaticSource(source, objectExpressionByName) {
10124
+ if (source?.type === "ObjectExpression") return source;
10125
+ if (source?.type === "Identifier" && source.name) return objectExpressionByName.get(source.name) ?? null;
10126
+ return null;
10127
+ }
10128
+ function addStaticPropertyName(staticPropertyNames, componentName, propName) {
10129
+ const names = staticPropertyNames.get(componentName) ?? [];
10130
+ if (!names.includes(propName)) {
10131
+ names.push(propName);
10132
+ staticPropertyNames.set(componentName, names);
10133
+ }
10134
+ }
10135
+ function getStaticPropertyNameFromMemberExpression(memberExpression) {
10136
+ const property = memberExpression.property;
10137
+ if (!memberExpression.computed && property?.type === "Identifier") return property.name ?? null;
10138
+ if ((property?.type === "Literal" || property?.type === "StringLiteral") && typeof property.value === "string") return property.value;
10139
+ return null;
10140
+ }
10141
+ function getStaticPropertyNameFromObjectProperty(prop) {
10142
+ if (!prop || typeof prop !== "object") return null;
10143
+ const property = prop;
10144
+ if (property.type === "SpreadElement" || property.type === "SpreadProperty") return null;
10145
+ const key = property.key;
10146
+ if (!property.computed && key?.type === "Identifier") return key.name ?? null;
10147
+ if ((key?.type === "Literal" || key?.type === "StringLiteral") && typeof key.value === "string") return key.value;
10148
+ return null;
10149
+ }
10150
+ function buildStaticInheritanceStatement(j, componentName, baseComponentName, propName) {
10151
+ return j(`${isIdentifierPropertyName(propName) ? `${componentName}.${propName}` : `(${componentName} as any)[${JSON.stringify(propName)}]`} = ${isIdentifierPropertyName(propName) ? `(${baseComponentName} as any).${propName}` : `(${baseComponentName} as any)[${JSON.stringify(propName)}]`};`).get().node.program.body[0];
10152
+ }
10153
+ function isIdentifierPropertyName(propName) {
10154
+ return /^[$A-Z_a-z][$\w]*$/.test(propName);
10155
+ }
8561
10156
  //#endregion
8562
10157
  //#region src/internal/utilities/ast-safety.ts
8563
10158
  /**
@@ -9603,10 +11198,12 @@ function getAttrsParamInfo(params) {
9603
11198
  };
9604
11199
  }
9605
11200
  function literalStaticValueFromNode(node) {
9606
- if (node?.type === "StringLiteral" || node?.type === "NumericLiteral") return node.value;
9607
- if (node?.type === "BooleanLiteral") return node.value;
9608
- if (node?.type === "Literal" && (typeof node.value === "string" || typeof node.value === "number" || typeof node.value === "boolean")) return node.value;
9609
- if (node?.type === "TSAsExpression" || node?.type === "TSSatisfiesExpression") return literalStaticValueFromNode(node.expression);
11201
+ if (!node || typeof node !== "object") return;
11202
+ const typed = node;
11203
+ if (typed.type === "StringLiteral" || typed.type === "NumericLiteral") return typeof typed.value === "string" || typeof typed.value === "number" ? typed.value : void 0;
11204
+ if (typed.type === "BooleanLiteral") return typeof typed.value === "boolean" ? typed.value : void 0;
11205
+ if (typed.type === "Literal" && (typeof typed.value === "string" || typeof typed.value === "number" || typeof typed.value === "boolean")) return typed.value;
11206
+ if (typed.type === "TSAsExpression" || typed.type === "TSSatisfiesExpression") return literalStaticValueFromNode(typed.expression);
9610
11207
  }
9611
11208
  function isStaticAttrExpression$1(node, attrsParamInfo) {
9612
11209
  if (!node || typeof node !== "object") return false;
@@ -9620,9 +11217,6 @@ function getStaticAttrExpressionRootName(node) {
9620
11217
  if (node.property?.type !== "Identifier" && node.property?.type !== "PrivateName") return null;
9621
11218
  return getStaticAttrExpressionRootName(node.object);
9622
11219
  }
9623
- function isValidIdentifierName(name) {
9624
- return /^[$A-Z_a-z][$\w]*$/.test(name);
9625
- }
9626
11220
  function staticAttrExpressionToReference(node, attrsParamInfo) {
9627
11221
  if (!isStaticAttrExpression$1(node, attrsParamInfo)) return null;
9628
11222
  if (node?.type === "TSAsExpression" || node?.type === "TSSatisfiesExpression") return staticAttrExpressionToReference(node.expression, attrsParamInfo);
@@ -9942,7 +11536,7 @@ function collectStyledDeclsStep(ctx) {
9942
11536
  if (unparseableSfpDecl && ctx.options.transformMode !== "leavesOnly") {
9943
11537
  ctx.warnings.push({
9944
11538
  severity: "warning",
9945
- type: "Unsupported shouldForwardProp pattern (only !prop.startsWith(), ![].includes(prop), and prop !== are supported)",
11539
+ type: UNSUPPORTED_SHOULD_FORWARD_PROP_WARNING,
9946
11540
  loc: unparseableSfpDecl.loc
9947
11541
  });
9948
11542
  return returnResult({
@@ -11150,7 +12744,7 @@ function evaluateStaticKeyframesExpression(expr, scopePath, seenIdentifiers = /*
11150
12744
  if (expr.operator === "+") return value;
11151
12745
  return null;
11152
12746
  }
11153
- if (expr.type === "BinaryExpression") return evaluateStaticBinaryExpression(expr, scopePath, seenIdentifiers);
12747
+ if (expr.type === "BinaryExpression") return evaluateStaticBinaryExpression$1(expr, scopePath, seenIdentifiers);
11154
12748
  if (expr.type === "LogicalExpression") {
11155
12749
  const left = evaluateStaticKeyframesExpression(expr.left, scopePath, seenIdentifiers);
11156
12750
  if (expr.operator === "&&") return left ? evaluateStaticKeyframesExpression(expr.right, scopePath) : left;
@@ -11180,7 +12774,7 @@ function evaluateStaticKeyframesExpression(expr, scopePath, seenIdentifiers = /*
11180
12774
  if (expr.type === "TSAsExpression" || expr.type === "TSTypeAssertion" || expr.type === "TSSatisfiesExpression") return evaluateStaticKeyframesExpression(expr.expression, scopePath, seenIdentifiers);
11181
12775
  return null;
11182
12776
  }
11183
- function evaluateStaticBinaryExpression(expr, scopePath, seenIdentifiers) {
12777
+ function evaluateStaticBinaryExpression$1(expr, scopePath, seenIdentifiers) {
11184
12778
  if (expr.type !== "BinaryExpression") return null;
11185
12779
  const left = evaluateStaticKeyframesExpression(expr.left, scopePath, seenIdentifiers);
11186
12780
  const right = evaluateStaticKeyframesExpression(expr.right, scopePath, seenIdentifiers);
@@ -12103,7 +13697,7 @@ function detectUnsupportedPatternsStep(ctx) {
12103
13697
  const parent = cur.parentPath.node;
12104
13698
  if (parent?.type === "VariableDeclarator" && parent.init === cur.node) return true;
12105
13699
  if (parent?.type === "AssignmentExpression" && parent.right === cur.node) return true;
12106
- if (isFunctionNode(parent)) break;
13700
+ if (isFunctionNode$1(parent)) break;
12107
13701
  cur = cur.parentPath;
12108
13702
  }
12109
13703
  return false;
@@ -12112,7 +13706,7 @@ function detectUnsupportedPatternsStep(ctx) {
12112
13706
  let cur = path;
12113
13707
  while (cur?.parentPath) {
12114
13708
  cur = cur.parentPath;
12115
- if (isFunctionNode(cur?.node)) return true;
13709
+ if (isFunctionNode$1(cur?.node)) return true;
12116
13710
  }
12117
13711
  return false;
12118
13712
  };
@@ -12938,7 +14532,7 @@ function resolveDirectJsxUsages(ctx, styledDecls) {
12938
14532
  for (const name of jsxComponentNames) {
12939
14533
  if (styledDeclNames.has(name)) continue;
12940
14534
  if (isUsedAsNonJsxValue(ctx, name)) continue;
12941
- if (hasSpreadInJsxForComponent(ctx, name)) continue;
14535
+ if (hasSpreadInJsx(ctx.root, ctx.j, name)) continue;
12942
14536
  const importInfo = importMap.get(name);
12943
14537
  if (!importInfo) continue;
12944
14538
  const importSourceStr = importSourceToString(importInfo.source);
@@ -13035,27 +14629,6 @@ function isUsedAsNonJsxValue(ctx, localName) {
13035
14629
  return true;
13036
14630
  }).size() > 0;
13037
14631
  }
13038
- /** Returns true if any JSX call site of `localName` has a spread attribute. */
13039
- function hasSpreadInJsxForComponent(ctx, localName) {
13040
- const { root, j } = ctx;
13041
- let found = false;
13042
- const checkAttrs = (attributes) => {
13043
- if (found) return;
13044
- for (const attr of attributes ?? []) if (attr.type === "JSXSpreadAttribute") {
13045
- found = true;
13046
- return;
13047
- }
13048
- };
13049
- root.find(j.JSXElement, { openingElement: { name: {
13050
- type: "JSXIdentifier",
13051
- name: localName
13052
- } } }).forEach((p) => checkAttrs(p.node.openingElement?.attributes));
13053
- root.find(j.JSXSelfClosingElement, { name: {
13054
- type: "JSXIdentifier",
13055
- name: localName
13056
- } }).forEach((p) => checkAttrs(p.node.attributes));
13057
- return found;
13058
- }
13059
14632
  /** Returns a styleKey that doesn't collide with existing keys. */
13060
14633
  function deduplicateStyleKey(base, usedKeys) {
13061
14634
  if (!usedKeys.has(base)) return base;
@@ -13092,7 +14665,7 @@ function applyLeavesOnlyPolicyStep(ctx) {
13092
14665
  decl.skipTransform = true;
13093
14666
  ctx.warnings.push({
13094
14667
  severity: "warning",
13095
- type: "Unsupported shouldForwardProp pattern (only !prop.startsWith(), ![].includes(prop), and prop !== are supported)",
14668
+ type: UNSUPPORTED_SHOULD_FORWARD_PROP_WARNING,
13096
14669
  loc: decl.loc
13097
14670
  });
13098
14671
  continue;
@@ -13631,7 +15204,7 @@ function emitStylesAndImports(ctx) {
13631
15204
  const kfDecl = j.variableDeclaration("const", [j.variableDeclarator(j.identifier(name), j.callExpression(j.memberExpression(j.identifier("stylex"), j.identifier("keyframes")), [objectToAst(j, frames)]))]);
13632
15205
  inlineKeyframeDecls.push(kfDecl);
13633
15206
  }
13634
- emitLocalDefineVarsSidecars(ctx);
15207
+ emitLocalDefineVarsSidecars(ctx, [...nonEmptyStyleEntries.map(([, value]) => value), ...styledDecls.flatMap((decl) => (decl.inlineStyleProps ?? []).flatMap((prop) => [prop.expr, ...prop.keyExpr ? [prop.keyExpr] : []]))]);
13635
15208
  const programBody = root.get().node.program.body;
13636
15209
  const insertNodes = [...inlineKeyframeDecls, ...stylesDecl ? [stylesDecl] : []];
13637
15210
  if (insertNodes.length > 0) if (stylesInsertPosition === "afterImports") {
@@ -13917,9 +15490,9 @@ function tokenizeShorthandValue(value) {
13917
15490
  if (current.trim()) tokens.push(current.trim());
13918
15491
  return tokens;
13919
15492
  }
13920
- function emitLocalDefineVarsSidecars(ctx) {
15493
+ function emitLocalDefineVarsSidecars(ctx, emittedStyleValues) {
13921
15494
  const j = ctx.j;
13922
- const vars = [...ctx.localStylexVars?.values() ?? []].sort((a, b) => a.sourceOrder - b.sourceOrder);
15495
+ const vars = [...ctx.localStylexVars?.values() ?? []].filter((ref) => emittedStyleValues.some((value) => containsLocalStylexVarRef(value, ref))).sort((a, b) => a.sourceOrder - b.sourceOrder);
13923
15496
  if (vars.length === 0) return;
13924
15497
  ctx.sidecarFiles ??= [];
13925
15498
  const groups = groupLocalStylexVars(vars);
@@ -13930,6 +15503,25 @@ function emitLocalDefineVarsSidecars(ctx) {
13930
15503
  const specifiers = [...groups.keys()].map((groupName) => j.importSpecifier(j.identifier(groupName)));
13931
15504
  insertImportDeclarationNearStylex(ctx.root, j.importDeclaration(specifiers, j.literal(`./${vars[0]?.sidecarFileName ?? "vars.stylex"}`)));
13932
15505
  }
15506
+ function containsLocalStylexVarRef(value, ref) {
15507
+ if (!value || typeof value !== "object") return false;
15508
+ if (Array.isArray(value)) return value.some((item) => containsLocalStylexVarRef(item, ref));
15509
+ const record = value;
15510
+ if (record.type === "MemberExpression") {
15511
+ const object = record.object;
15512
+ const property = record.property;
15513
+ if (object?.type === "Identifier" && object.name === ref.groupName) {
15514
+ if (property?.type === "Identifier" && property.name === ref.keyName) return true;
15515
+ if (property?.type === "Literal" && property.value === ref.keyName) return true;
15516
+ if (property?.type === "StringLiteral" && property.value === ref.keyName) return true;
15517
+ }
15518
+ }
15519
+ for (const [key, child] of Object.entries(record)) {
15520
+ if (key === "loc" || key === "comments") continue;
15521
+ if (containsLocalStylexVarRef(child, ref)) return true;
15522
+ }
15523
+ return false;
15524
+ }
13933
15525
  function groupLocalStylexVars(vars) {
13934
15526
  const groups = /* @__PURE__ */ new Map();
13935
15527
  for (const ref of vars) {
@@ -14107,12 +15699,12 @@ function emitBridgeExportsStep(ctx) {
14107
15699
  function emitStyleMerging(args) {
14108
15700
  const { j, emitter, styleArgs: rawStyleArgs, classNameId, styleId, allowClassNameProp, allowStyleProp, allowSxProp, inlineStyleProps = [], staticStyleExpr, staticClassNameExpr, isIntrinsicElement = true, wrappedAcceptsSxProp = false, keepStylePropSeparate = false } = args;
14109
15701
  const { styleMerger, emptyStyleKeys, stylesIdentifier, ancestorSelectorParents, crossFileMarkers, parentsNeedingDefaultMarker, emitTypes } = emitter;
14110
- const styleArgs = filterEmptyStyleArgs({
15702
+ const styleArgs = mergeAdjacentComplementaryStyleExprs(j, filterEmptyStyleArgs({
14111
15703
  styleArgs: rawStyleArgs,
14112
15704
  emptyStyleKeys,
14113
15705
  stylesIdentifier,
14114
15706
  ancestorSelectorParents
14115
- });
15707
+ }));
14116
15708
  if (ancestorSelectorParents && ancestorSelectorParents.size > 0) {
14117
15709
  let needsDefaultMarker = false;
14118
15710
  const pendingMarkers = [];
@@ -15060,6 +16652,13 @@ function buildShorthandDefaultPatternProp(j, name, defaultVal) {
15060
16652
  shorthand: true
15061
16653
  });
15062
16654
  }
16655
+ function shouldPassChildrenThroughRest(args) {
16656
+ const { includeChildren, includeRest = false, restId, destructureProps = [], defaultAttrs = [], dynamicAttrs = [], staticAttrs = {} } = args;
16657
+ if (!includeChildren || !includeRest || !restId) return false;
16658
+ if (destructureProps.some((name) => name === "children")) return false;
16659
+ if ([...defaultAttrs, ...dynamicAttrs].some((attr) => attr.attrName === "children" || attr.jsxProp === "children")) return false;
16660
+ return !Object.hasOwn(staticAttrs, "children");
16661
+ }
15063
16662
  function buildDestructurePatternProps(j, patternProp, args) {
15064
16663
  const { baseProps, destructureProps, propDefaults, includeRest = false, restId } = args;
15065
16664
  const patternProps = [...baseProps];
@@ -15395,7 +16994,7 @@ function buildVariantDimensionLookups(j, args) {
15395
16994
  pushExpr(j.logicalExpression("??", lookup, defaultAccess), dim);
15396
16995
  } else {
15397
16996
  if (dim.defaultValue && dim.isOptional && propDefaults) propDefaults.set(dim.propName, dim.defaultValue);
15398
- const lookup = dim.fallbackFnKey ? buildFallbackExpr(dim, propId) : j.memberExpression(variantsId, propId, true);
16997
+ const lookup = dim.fallbackFnKey ? buildFallbackExpr(dim, propId) : j.memberExpression(variantsId, dim.forceKeyofLookupCast ? buildKeyofTypeofCast(j, propId, dim.variantObjectName) : propId, true);
15399
16998
  if (dim.isOptional && !dim.defaultValue) {
15400
16999
  const guard = j.binaryExpression("!=", j.identifier(dim.propName), j.literal(null));
15401
17000
  pushExpr(j.logicalExpression("&&", guard, lookup), dim);
@@ -15858,7 +17457,8 @@ var WrapperEmitter = class {
15858
17457
  if (typedComponent) {
15859
17458
  if (typedComponent.supportsSxProp) return {
15860
17459
  acceptsSx: true,
15861
- sxExcludedProperties: typedComponent.sxExcludedProperties
17460
+ sxExcludedProperties: typedComponent.sxExcludedProperties,
17461
+ sxAllowedProperties: typedComponent.sxAllowedProperties
15862
17462
  };
15863
17463
  if (!this.hasSourceOverrideFor(componentLocalName)) return { acceptsSx: false };
15864
17464
  }
@@ -15966,6 +17566,9 @@ var WrapperEmitter = class {
15966
17566
  isUsedAsValue(d) {
15967
17567
  return Boolean(d.usedAsValue) || this.isUsedAsValueInFile(d.localName);
15968
17568
  }
17569
+ isBroadValueUsage(d) {
17570
+ return this.isUsedAsValue(d) && d.valueUsageKind !== "virtualListElementType";
17571
+ }
15969
17572
  requiresRestForValueUsage(d) {
15970
17573
  return this.isUsedAsValueInFile(d.localName) || this.hasAliasedJsxSpreadUsage(d.localName);
15971
17574
  }
@@ -16000,18 +17603,20 @@ var WrapperEmitter = class {
16000
17603
  shouldAllowClassNameProp(d) {
16001
17604
  if (d.consumerUsesClassName ?? d.supportsExternalStyles) return true;
16002
17605
  if (d.consumerUsesSpread) return this.spreadMayContainProp(d, "className");
16003
- if (this.isUsedAsValue(d)) return true;
17606
+ if (this.isBroadValueUsage(d)) return true;
16004
17607
  const used = this.getUsedAttrs(d.localName);
16005
17608
  return used.has("*") || used.has("className");
16006
17609
  }
16007
17610
  shouldAllowStyleProp(d) {
16008
17611
  if (d.consumerUsesStyle ?? d.supportsExternalStyles) return true;
16009
17612
  if (d.consumerUsesSpread) return this.spreadMayContainProp(d, "style");
16010
- if (this.isUsedAsValue(d)) return true;
17613
+ if (d.valueUsageKind === "virtualListElementType") return true;
17614
+ if (this.isBroadValueUsage(d)) return true;
16011
17615
  const used = this.getUsedAttrs(d.localName);
16012
17616
  return used.has("*") || used.has("style");
16013
17617
  }
16014
17618
  shouldAllowSxProp(d) {
17619
+ if (d.valueUsageKind === "virtualListElementType") return (d.supportsExternalStyles ?? false) || d.typeScriptSupportsSxProp === true;
16015
17620
  return (d.supportsExternalStyles ?? false) || d.typeScriptSupportsSxProp === true || this.shouldAllowClassNameProp(d) || this.shouldAllowStyleProp(d);
16016
17621
  }
16017
17622
  typedComponentHasProp(componentLocalName, propName) {
@@ -16059,7 +17664,7 @@ var WrapperEmitter = class {
16059
17664
  }
16060
17665
  hasSourceOverrideFor(componentLocalName) {
16061
17666
  const importInfo = this.importMap.get(componentLocalName);
16062
- return importInfo?.source.kind === "absolutePath" && this.sourceOverrides?.has(toRealPath(importInfo.source.value)) === true;
17667
+ return importInfo?.source.kind === "absolutePath" && this.sourceOverrides?.has(resolveExistingFilePath(importInfo.source.value)) === true;
16063
17668
  }
16064
17669
  typeScriptComponentMetadataFor(componentLocalName) {
16065
17670
  const importInfo = this.importMap.get(componentLocalName);
@@ -16319,7 +17924,7 @@ var WrapperEmitter = class {
16319
17924
  emitted.push(stmt);
16320
17925
  return true;
16321
17926
  }
16322
- annotatePropsParam(propsId, localName, inlineTypeText) {
17927
+ annotatePropsParam(propsParam, localName, inlineTypeText) {
16323
17928
  const { j } = this;
16324
17929
  if (!this.emitTypes) return;
16325
17930
  if (inlineTypeText) {
@@ -16334,11 +17939,12 @@ var WrapperEmitter = class {
16334
17939
  ].join("\n"));
16335
17940
  }
16336
17941
  if (!typeNode) throw new Error(`Failed to parse inline props param type for ${localName} (${this.filePath}).`);
16337
- propsId.typeAnnotation = j.tsTypeAnnotation(typeNode);
16338
- } else propsId.typeAnnotation = j.tsTypeAnnotation(j.tsTypeReference(j.identifier(this.propsTypeNameFor(localName))));
17942
+ propsParam.typeAnnotation = j.tsTypeAnnotation(typeNode);
17943
+ } else propsParam.typeAnnotation = j.tsTypeAnnotation(j.tsTypeReference(j.identifier(this.propsTypeNameFor(localName))));
16339
17944
  }
16340
17945
  withChildren(innerTypeText) {
16341
17946
  const t = innerTypeText.trim();
17947
+ if (t === "{}") return "{ children?: React.ReactNode }";
16342
17948
  if (t.startsWith("React.PropsWithChildren<")) return t;
16343
17949
  if (/(?:^|&\s*)(?:React\.ComponentProps(?:WithRef)?<|(?:Omit|Pick|Partial|Required|Readonly|ReadonlyArray|NonNullable|Extract|Exclude)<\s*React\.ComponentProps(?:WithRef)?<)/.test(t)) return t;
16344
17950
  return `React.PropsWithChildren<${t}>`;
@@ -16561,7 +18167,7 @@ var WrapperEmitter = class {
16561
18167
  inferredIntrinsicPropsTypeText(args) {
16562
18168
  const { d, tagName, allowClassNameProp, allowStyleProp, allowSxProp, skipProps, includeRef, forceNarrow } = args;
16563
18169
  const used = this.getUsedAttrs(d.localName);
16564
- const needsBroadAttrs = used.has("*") || this.isUsedAsValue(d);
18170
+ const needsBroadAttrs = used.has("*") || this.isBroadValueUsage(d);
16565
18171
  const lines = [];
16566
18172
  const pickedAttrKeys = [];
16567
18173
  if (!needsBroadAttrs) {
@@ -16604,6 +18210,7 @@ var WrapperEmitter = class {
16604
18210
  const intrinsicBaseOmitted = [];
16605
18211
  if (!allowClassNameProp) intrinsicBaseOmitted.push("\"className\"");
16606
18212
  if (!allowStyleProp) intrinsicBaseOmitted.push("\"style\"");
18213
+ if (!allowSxProp) intrinsicBaseOmitted.push("\"sx\"");
16607
18214
  const intrinsicBaseMaybeOmitted = intrinsicBaseOmitted.length ? `Omit<${intrinsicBase}, ${intrinsicBaseOmitted.join(" | ")}>` : intrinsicBase;
16608
18215
  const pickExpr = pickedAttrKeys.length > 0 ? `Pick<${intrinsicBase}, ${pickedAttrKeys.map((k) => `"${k}"`).join(" | ")}>` : void 0;
16609
18216
  if (!needsBroadAttrs) {
@@ -16781,27 +18388,18 @@ var WrapperEmitter = class {
16781
18388
  for (const arg of styleArgs) if (arg?.type === "LogicalExpression" && arg.operator === "&&") collectCondIdentifiers(arg.left);
16782
18389
  const isVoidTag = VOID_TAGS.has(tagName);
16783
18390
  const allowForwardedAsProp = this.getUsedAttrs(localName).has("forwardedAs");
16784
- const propsParamId = j.identifier("props");
16785
18391
  const needsPolymorphicTypeParams = this.emitTypes && (allowAsProp || inlineTypeNeedsElementGeneric(inlineTypeText));
16786
- if (this.emitTypes) if (inlineTypeText) {
16787
- let typeNode = null;
16788
- try {
16789
- typeNode = j(`const x: ${inlineTypeText} = null`).get().node.program.body[0].declarations[0].id.typeAnnotation.typeAnnotation;
16790
- } catch (e) {
16791
- throw new Error([
16792
- `Failed to parse inline wrapper props type for ${localName} (${tagName}).`,
16793
- `Inline type: ${inlineTypeText}`,
16794
- `Error: ${e instanceof Error ? e.message : String(e)}`
16795
- ].join("\n"));
16796
- }
16797
- if (!typeNode) throw new Error(`Failed to parse inline wrapper props type for ${localName} (${tagName}).`);
16798
- propsParamId.typeAnnotation = j.tsTypeAnnotation(typeNode);
16799
- } else {
16800
- if (!propsTypeName) throw new Error(`Missing propsTypeName for ${localName} (${tagName}).`);
16801
- if (needsPolymorphicTypeParams) propsParamId.typeAnnotation = j(`const x: ${propsTypeName}<C> = null`).get().node.program.body[0].declarations[0].id.typeAnnotation;
16802
- else propsParamId.typeAnnotation = j.tsTypeAnnotation(j.tsTypeReference(j.identifier(propsTypeName)));
16803
- }
16804
18392
  const propsId = j.identifier("props");
18393
+ let restId = includeRest ? j.identifier("rest") : null;
18394
+ const passChildrenThroughRest = shouldPassChildrenThroughRest({
18395
+ includeChildren: !isVoidTag,
18396
+ includeRest,
18397
+ restId,
18398
+ destructureProps,
18399
+ defaultAttrs,
18400
+ dynamicAttrs,
18401
+ staticAttrs
18402
+ });
16805
18403
  const patternProps = [];
16806
18404
  if (allowAsProp) patternProps.push(j.property.from({
16807
18405
  kind: "init",
@@ -16810,8 +18408,9 @@ var WrapperEmitter = class {
16810
18408
  shorthand: false
16811
18409
  }));
16812
18410
  if (allowForwardedAsProp) patternProps.push(this.patternProp("forwardedAs"));
16813
- if (!isVoidTag) patternProps.push(this.patternProp("children"));
16814
- if (includeRefProp) patternProps.push(this.patternProp("ref"));
18411
+ if (!isVoidTag && !passChildrenThroughRest) patternProps.push(this.patternProp("children"));
18412
+ const shouldForwardRefExplicitly = includeRefProp && !includeRest;
18413
+ if (shouldForwardRefExplicitly) patternProps.push(this.patternProp("ref"));
16815
18414
  if (allowClassNameProp) patternProps.push(this.patternProp("className"));
16816
18415
  if (allowStyleProp) patternProps.push(this.patternProp("style"));
16817
18416
  for (const name of expandedDestructureProps) if (name !== "children" && name !== "style" && name !== "className" && name !== "forwardedAs" && name !== "ref") {
@@ -16821,11 +18420,18 @@ var WrapperEmitter = class {
16821
18420
  }
16822
18421
  for (const a of defaultAttrs) if (!expandedDestructureProps.has(a.jsxProp)) patternProps.push(this.patternProp(a.jsxProp));
16823
18422
  for (const attr of dynamicAttrs) if (!expandedDestructureProps.has(attr.jsxProp)) patternProps.push(this.patternProp(attr.jsxProp));
16824
- let restId = includeRest ? j.identifier("rest") : null;
16825
18423
  if (includeRest && restId) patternProps.push(j.restElement(restId));
16826
18424
  const usePropsDirectlyForRest = includeRest && patternProps.length === 1 && patternProps[0]?.type === "RestElement";
16827
- const usePropsChildrenDirectly = this.isChildrenOnlyDestructurePattern(patternProps);
18425
+ const useChildrenParamDestructure = this.isChildrenOnlyDestructurePattern(patternProps);
16828
18426
  if (usePropsDirectlyForRest) restId = propsId;
18427
+ const propsParam = useChildrenParamDestructure ? this.buildChildrenOnlyParam(inlineTypeText ?? (propsTypeName ? `${propsTypeName}${needsPolymorphicTypeParams ? "<C>" : ""}` : void 0)) : j.identifier("props");
18428
+ if (!useChildrenParamDestructure) this.annotateMinimalWrapperParam(propsParam, {
18429
+ localName,
18430
+ tagName,
18431
+ inlineTypeText,
18432
+ propsTypeName,
18433
+ needsPolymorphicTypeParams
18434
+ });
16829
18435
  const classNameId = j.identifier("className");
16830
18436
  const styleId = j.identifier("style");
16831
18437
  const staticClassName = staticAttrs.className;
@@ -16860,7 +18466,7 @@ var WrapperEmitter = class {
16860
18466
  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")))));
16861
18467
  }
16862
18468
  for (const inv of invertedBoolAttrs) jsxAttrs.push(j.jsxAttribute(j.jsxIdentifier(inv.attrName), j.jsxExpressionContainer(j.binaryExpression("!==", j.identifier(inv.jsxProp), j.booleanLiteral(true)))));
16863
- if (includeRefProp) jsxAttrs.push(j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(j.identifier("ref"))));
18469
+ if (shouldForwardRefExplicitly) jsxAttrs.push(j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(j.identifier("ref"))));
16864
18470
  if (includeRest && restId) jsxAttrs.push(j.jsxSpreadAttribute(restId));
16865
18471
  jsxAttrs.push(...buildDynamicAttrsFromProps(j, {
16866
18472
  dynamicAttrs,
@@ -16877,15 +18483,15 @@ var WrapperEmitter = class {
16877
18483
  if (merging.classNameAttr) jsxAttrs.push(j.jsxAttribute(j.jsxIdentifier("className"), j.jsxExpressionContainer(merging.classNameAttr)));
16878
18484
  if (merging.styleAttr) jsxAttrs.push(j.jsxAttribute(j.jsxIdentifier("style"), j.jsxExpressionContainer(merging.styleAttr)));
16879
18485
  const renderedJsxName = jsxNameFromString(j, allowAsProp ? "Component" : attrsAsTag ?? tagName);
16880
- const openingEl = j.jsxOpeningElement(renderedJsxName, jsxAttrs, isVoidTag);
16881
- const childrenExpr = usePropsChildrenDirectly ? j.memberExpression(propsId, j.identifier("children")) : j.identifier("children");
16882
- const jsx = j.jsxElement(openingEl, isVoidTag ? null : j.jsxClosingElement(renderedJsxName), isVoidTag ? [] : [j.jsxExpressionContainer(childrenExpr)]);
18486
+ const openingEl = j.jsxOpeningElement(renderedJsxName, jsxAttrs, isVoidTag || passChildrenThroughRest);
18487
+ const childrenExpr = j.identifier("children");
18488
+ const jsx = j.jsxElement(openingEl, isVoidTag || passChildrenThroughRest ? null : j.jsxClosingElement(renderedJsxName), isVoidTag || passChildrenThroughRest ? [] : [j.jsxExpressionContainer(childrenExpr)]);
16883
18489
  const bodyStmts = [];
16884
- if (!usePropsDirectlyForRest && !usePropsChildrenDirectly) bodyStmts.push(j.variableDeclaration("const", [j.variableDeclarator(j.objectPattern(patternProps), propsId)]));
18490
+ if (!usePropsDirectlyForRest && !useChildrenParamDestructure) bodyStmts.push(j.variableDeclaration("const", [j.variableDeclarator(j.objectPattern(patternProps), propsId)]));
16885
18491
  if (merging.sxDecl) bodyStmts.push(merging.sxDecl);
16886
18492
  bodyStmts.push(j.returnStatement(jsx));
16887
18493
  const filteredBody = bodyStmts.filter((stmt) => stmt && stmt.type !== "EmptyStatement");
16888
- const fn = j.functionDeclaration(j.identifier(localName), [propsParamId], j.blockStatement(filteredBody));
18494
+ const fn = j.functionDeclaration(j.identifier(localName), [propsParam], j.blockStatement(filteredBody));
16889
18495
  if (needsPolymorphicTypeParams) fn.typeParameters = buildPolymorphicTypeParams(j, tagName);
16890
18496
  return [fn];
16891
18497
  }
@@ -16934,9 +18540,42 @@ var WrapperEmitter = class {
16934
18540
  buildWrapperFunction(args) {
16935
18541
  return buildWrapperFunction(this.j, args);
16936
18542
  }
18543
+ buildChildrenOnlyParam(typeText) {
18544
+ if (!this.emitTypes) return this.j.objectPattern([this.patternProp("children")]);
18545
+ if (!typeText) throw new Error("Missing props type for children-only wrapper parameter.");
18546
+ return this.j(`function _({ children }: ${typeText}) {}`).get().node.program.body[0].params[0];
18547
+ }
18548
+ annotateMinimalWrapperParam(propsParam, args) {
18549
+ const { localName, tagName, inlineTypeText, propsTypeName, needsPolymorphicTypeParams } = args;
18550
+ if (!this.emitTypes) return;
18551
+ if (inlineTypeText) {
18552
+ let typeNode = null;
18553
+ try {
18554
+ typeNode = this.j(`const x: ${inlineTypeText} = null`).get().node.program.body[0].declarations[0].id.typeAnnotation.typeAnnotation;
18555
+ } catch (e) {
18556
+ throw new Error([
18557
+ `Failed to parse inline wrapper props type for ${localName} (${tagName}).`,
18558
+ `Inline type: ${inlineTypeText}`,
18559
+ `Error: ${e instanceof Error ? e.message : String(e)}`
18560
+ ].join("\n"));
18561
+ }
18562
+ if (!typeNode) throw new Error(`Failed to parse inline wrapper props type for ${localName} (${tagName}).`);
18563
+ propsParam.typeAnnotation = this.j.tsTypeAnnotation(typeNode);
18564
+ return;
18565
+ }
18566
+ if (!propsTypeName) throw new Error(`Missing propsTypeName for ${localName} (${tagName}).`);
18567
+ if (needsPolymorphicTypeParams) {
18568
+ propsParam.typeAnnotation = this.j(`const x: ${propsTypeName}<C> = null`).get().node.program.body[0].declarations[0].id.typeAnnotation;
18569
+ return;
18570
+ }
18571
+ propsParam.typeAnnotation = this.j.tsTypeAnnotation(this.j.tsTypeReference(this.j.identifier(propsTypeName)));
18572
+ }
16937
18573
  buildDestructurePatternProps(args) {
16938
18574
  return buildDestructurePatternProps(this.j, this.patternProp, args);
16939
18575
  }
18576
+ shouldPassChildrenThroughRest(args) {
18577
+ return shouldPassChildrenThroughRest(args);
18578
+ }
16940
18579
  isChildrenOnlyDestructurePattern(patternProps) {
16941
18580
  return isChildrenOnlyDestructurePattern(patternProps);
16942
18581
  }
@@ -17297,7 +18936,7 @@ function emitComponentWrappers(emitter) {
17297
18936
  });
17298
18937
  if (varDecl.size() > 0) {
17299
18938
  const init = varDecl.get().node.init;
17300
- if (isFunctionNode(init)) return firstParamType(init);
18939
+ if (isFunctionNode$1(init)) return firstParamType(init);
17301
18940
  }
17302
18941
  return null;
17303
18942
  };
@@ -17561,6 +19200,9 @@ function emitComponentWrappers(emitter) {
17561
19200
  const namespaceBooleanProps = [];
17562
19201
  const styleOnlyConditionProps = /* @__PURE__ */ new Set();
17563
19202
  const styleFnValueProps = /* @__PURE__ */ new Set();
19203
+ const styleValueVariantProps = new Set(d.styleValueVariantProps ?? []);
19204
+ const observedExpressionConditionDropProps = new Set(d.observedExpressionConditionDropProps ?? []);
19205
+ for (const prop of styleValueVariantProps) styleFnValueProps.add(prop);
17564
19206
  const propsArgExprs = d.extraStylexPropsArgs ? emitter.buildExtraStylexPropsExprs({
17565
19207
  entries: d.extraStylexPropsArgs,
17566
19208
  destructureProps
@@ -17735,6 +19377,19 @@ function emitComponentWrappers(emitter) {
17735
19377
  node: arg,
17736
19378
  propNames: splicedStyleFnProps
17737
19379
  });
19380
+ const localOnlyPropsTypeText = localOnlyComponentWrapperPropsTypeText({
19381
+ d,
19382
+ emitter,
19383
+ allowClassNameProp,
19384
+ allowStyleProp,
19385
+ exposeSxProp,
19386
+ forceClassNameOptional,
19387
+ forceStyleOptional,
19388
+ functionParamTypeName,
19389
+ isPolymorphicComponentWrapper,
19390
+ shouldLowerForwardedAs
19391
+ });
19392
+ if (localOnlyPropsTypeText) inlineTypeText = localOnlyPropsTypeText;
17738
19393
  const propsParamId = j.identifier("props");
17739
19394
  let polymorphicFnTypeParams = null;
17740
19395
  if (isPolymorphicComponentWrapper && emitTypes) {
@@ -17767,15 +19422,14 @@ function emitComponentWrappers(emitter) {
17767
19422
  const staticAttrsForJsx = attrsSxExpr ? omitStaticAttr(staticAttrs, "sx") : staticAttrs;
17768
19423
  const attrsStaticStyleExpr = attrsInfo?.attrsStaticStyleExpr;
17769
19424
  const needsSxVar = allowClassNameProp || allowStyleProp || wrappedAcceptsSx || !!d.inlineStyleProps?.length || !!attrsStaticStyleExpr || !!staticClassNameExpr;
17770
- const needsDestructure = destructureProps.length > 0 || needsSxVar || isPolymorphicComponentWrapper || defaultAttrs.length > 0 || dynamicAttrs.length > 0 || shouldLowerForwardedAs || (d.supportsRefProp ?? false);
19425
+ const needsDestructure = destructureProps.length > 0 || needsSxVar || isPolymorphicComponentWrapper || defaultAttrs.length > 0 || dynamicAttrs.length > 0 || shouldLowerForwardedAs;
17771
19426
  const includeChildren = !isPolymorphicComponentWrapper && emitter.hasJsxChildrenUsage(d.localName);
17772
19427
  if (needsDestructure) {
17773
19428
  const childrenId = j.identifier("children");
17774
19429
  const classNameId = j.identifier("className");
17775
19430
  const styleId = j.identifier("style");
17776
19431
  const sxId = j.identifier("sx");
17777
- const refId = j.identifier("ref");
17778
- const restId = j.identifier("rest");
19432
+ let restId = j.identifier("rest");
17779
19433
  const componentId = j.identifier("Component");
17780
19434
  const forwardedAsId = j.identifier("forwardedAs");
17781
19435
  const wrappedComponentExpr = buildWrappedComponentExpr();
@@ -17788,14 +19442,22 @@ function emitComponentWrappers(emitter) {
17788
19442
  const destructureStyle = allowStyleProp && !canForwardClassNameStyleThroughRest;
17789
19443
  const destructureSx = exposeSxProp;
17790
19444
  const destructurePropsForPattern = needsUseTheme ? destructureProps.filter((name) => name !== "theme") : destructureProps;
19445
+ const passChildrenThroughRest = emitter.shouldPassChildrenThroughRest({
19446
+ includeChildren,
19447
+ includeRest: true,
19448
+ restId,
19449
+ destructureProps: destructurePropsForPattern,
19450
+ defaultAttrs,
19451
+ dynamicAttrs,
19452
+ staticAttrs: staticAttrsForJsx
19453
+ });
17791
19454
  const patternProps = emitter.buildDestructurePatternProps({
17792
19455
  baseProps: [
17793
19456
  ...isPolymorphicComponentWrapper ? [j.property("init", j.identifier("as"), j.assignmentPattern(componentId, wrappedComponentExpr))] : [],
17794
19457
  ...destructureClassName ? [patternProp("className", classNameId)] : [],
17795
- ...includeChildren ? [patternProp("children", childrenId)] : [],
19458
+ ...includeChildren && !passChildrenThroughRest ? [patternProp("children", childrenId)] : [],
17796
19459
  ...destructureStyle ? [patternProp("style", styleId)] : [],
17797
19460
  ...destructureSx ? [patternProp("sx", sxId)] : [],
17798
- ...d.supportsRefProp ?? false ? [patternProp("ref", refId)] : [],
17799
19461
  ...shouldLowerForwardedAs ? [patternProp("forwardedAs", forwardedAsId)] : []
17800
19462
  ],
17801
19463
  destructureProps: destructurePropsForPattern,
@@ -17803,7 +19465,9 @@ function emitComponentWrappers(emitter) {
17803
19465
  includeRest: true,
17804
19466
  restId
17805
19467
  });
17806
- const declStmt = j.variableDeclaration("const", [j.variableDeclarator(j.objectPattern(patternProps), propsId)]);
19468
+ const usePropsDirectlyForRest = patternProps.length === 1 && patternProps[0]?.type === "RestElement";
19469
+ if (usePropsDirectlyForRest) restId = propsId;
19470
+ const declStmt = usePropsDirectlyForRest ? null : j.variableDeclaration("const", [j.variableDeclarator(j.objectPattern(patternProps), propsId)]);
17807
19471
  const merging = emitStyleMerging({
17808
19472
  j,
17809
19473
  emitter,
@@ -17820,7 +19484,8 @@ function emitComponentWrappers(emitter) {
17820
19484
  wrappedAcceptsSxProp: wrappedAcceptsSx,
17821
19485
  keepStylePropSeparate: shouldKeepStylePropSeparate(renderedComponent)
17822
19486
  });
17823
- const stmts = [declStmt];
19487
+ const stmts = [];
19488
+ if (declStmt) stmts.push(declStmt);
17824
19489
  if (needsUseTheme) stmts.push(buildUseThemeDeclaration(j, emitter.themeHookLocalName));
17825
19490
  if (merging.sxDecl) stmts.push(merging.sxDecl);
17826
19491
  const openingAttrs = [];
@@ -17836,7 +19501,6 @@ function emitComponentWrappers(emitter) {
17836
19501
  defaultAttrs,
17837
19502
  propExprFor: (prop) => j.identifier(prop)
17838
19503
  }));
17839
- if (d.supportsRefProp ?? false) openingAttrs.push(j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId)));
17840
19504
  const forwardedProps = /* @__PURE__ */ new Set();
17841
19505
  for (const attr of defaultAttrs) forwardedProps.add(attr.attrName);
17842
19506
  for (const attr of dynamicAttrs) forwardedProps.add(attr.attrName);
@@ -17864,6 +19528,7 @@ function emitComponentWrappers(emitter) {
17864
19528
  }
17865
19529
  const baseExplicitProps = baseComponentPropsType ? emitter.getExplicitPropNames(baseComponentPropsType) : null;
17866
19530
  for (const propName of destructureProps) if (propName && propName !== "children" && !propName.startsWith("$") && !renamedFromTransient.has(propName)) {
19531
+ if (observedExpressionConditionDropProps.has(propName) && !baseExplicitProps?.has(propName)) continue;
17867
19532
  if (styleOnlyConditionProps.has(propName)) {
17868
19533
  if (!baseExplicitProps || baseExplicitProps.has(propName)) pushForwardedProp(propName);
17869
19534
  continue;
@@ -17890,7 +19555,7 @@ function emitComponentWrappers(emitter) {
17890
19555
  const jsx = emitter.buildJsxElement({
17891
19556
  tagName: jsxTagName,
17892
19557
  attrs: openingAttrs,
17893
- includeChildren,
19558
+ includeChildren: includeChildren && !passChildrenThroughRest,
17894
19559
  childrenExpr: childrenId
17895
19560
  });
17896
19561
  stmts.push(j.returnStatement(jsx));
@@ -17936,6 +19601,24 @@ function emitComponentWrappers(emitter) {
17936
19601
  function shouldKeepStylePropSeparate(componentName) {
17937
19602
  return componentName.startsWith("motion.") || componentName.startsWith("animated.");
17938
19603
  }
19604
+ function localOnlyComponentWrapperPropsTypeText(args) {
19605
+ const { d, emitter, allowClassNameProp, allowStyleProp, exposeSxProp, forceClassNameOptional, forceStyleOptional, functionParamTypeName, isPolymorphicComponentWrapper, shouldLowerForwardedAs } = args;
19606
+ if (!emitter.emitTypes || d.isExported || emitter.exportedComponents.has(d.localName) || d.propsType || d.consumerUsesSpread || emitter.isBroadValueUsage(d) || functionParamTypeName || isPolymorphicComponentWrapper || allowClassNameProp || allowStyleProp || exposeSxProp || forceClassNameOptional || forceStyleOptional || shouldLowerForwardedAs || !hasStaticComponentAttrs(d) || hasPropDrivenComponentWrapperBehavior(d) || hasRuntimeAttrsProps(d)) return null;
19607
+ const usedAttrs = emitter.getUsedAttrs(d.localName);
19608
+ if (usedAttrs.has("*") || [...usedAttrs].some((attr) => attr !== "children")) return null;
19609
+ if (!usedAttrs.has("children") && !emitter.hasJsxChildrenUsage(d.localName)) return null;
19610
+ return "{ children?: React.ReactNode }";
19611
+ }
19612
+ function hasStaticComponentAttrs(d) {
19613
+ return Object.keys(d.attrsInfo?.staticAttrs ?? {}).length > 0;
19614
+ }
19615
+ function hasRuntimeAttrsProps(d) {
19616
+ const attrsInfo = d.attrsInfo;
19617
+ return !!((attrsInfo?.defaultAttrs?.length ?? 0) > 0 || (attrsInfo?.dynamicAttrs?.length ?? 0) > 0 || (attrsInfo?.conditionalAttrs?.length ?? 0) > 0 || (attrsInfo?.invertedBoolAttrs?.length ?? 0) > 0 || (attrsInfo?.attrsDynamicStyles?.length ?? 0) > 0 || attrsInfo?.attrsStaticStyleExpr);
19618
+ }
19619
+ function hasPropDrivenComponentWrapperBehavior(d) {
19620
+ return !!(d.enumVariant || d.shouldForwardProp || (d.inlineStyleProps?.length ?? 0) > 0 || (d.styleFnFromProps?.length ?? 0) > 0 || (d.variantDimensions?.length ?? 0) > 0 || (d.compoundVariants?.length ?? 0) > 0 || Object.keys(d.variantStyleKeys ?? {}).length > 0 || (d.transientPropRenames?.size ?? 0) > 0 || (d.observedExpressionConditionDropProps?.size ?? 0) > 0 || (d.styleValueVariantProps?.size ?? 0) > 0);
19621
+ }
17939
19622
  function getExplicitAttrsOmitUnion(args) {
17940
19623
  const { attrsProvidedPropNames, emitter, propsType } = args;
17941
19624
  if (!propsType || attrsProvidedPropNames.size === 0) return null;
@@ -18786,6 +20469,7 @@ function createEmitIntrinsicHelpers(env) {
18786
20469
  const omitted = [];
18787
20470
  if (!allowClassNameProp) omitted.push("\"className\"");
18788
20471
  if (!allowStyleProp) omitted.push("\"style\"");
20472
+ if (!allowSxProp) omitted.push("\"sx\"");
18789
20473
  const base = omitted.length > 0 ? `Omit<React.ComponentPropsWithRef<C>, ${omitted.join(" | ")}>` : "React.ComponentPropsWithRef<C>";
18790
20474
  const forwardedAsPart = includeForwardedAs ? ` & ${FORWARDED_AS_TYPE}` : "";
18791
20475
  const sxPropPart = allowSxProp ? `${SX_PROP_TYPE_TEXT}; ` : "";
@@ -18893,11 +20577,16 @@ function buildAttrWrapperBody(ctx, args) {
18893
20577
  const { d, tagName, allowClassNameProp, allowAsProp, includesForwardedAs, includeChildren, styleArgs, extraDestructureProps, extraBodyStatements, extraJsxAttrs, pseudoGuardProps } = args;
18894
20578
  const classNameId = j.identifier("className");
18895
20579
  const childrenId = j.identifier("children");
18896
- const refId = j.identifier("ref");
18897
20580
  const restId = j.identifier("rest");
18898
20581
  const forwardedAsId = j.identifier("forwardedAs");
18899
20582
  const componentId = j.identifier("Component");
18900
20583
  const sxId = j.identifier("sx");
20584
+ const passChildrenThroughRest = emitter.shouldPassChildrenThroughRest({
20585
+ includeChildren,
20586
+ includeRest: true,
20587
+ restId,
20588
+ destructureProps: [...extraDestructureProps, ...pseudoGuardProps]
20589
+ });
18901
20590
  const baseProps = [
18902
20591
  ...allowAsProp ? [j.property.from({
18903
20592
  kind: "init",
@@ -18908,8 +20597,7 @@ function buildAttrWrapperBody(ctx, args) {
18908
20597
  ...includesForwardedAs ? [ctx.patternProp("forwardedAs", forwardedAsId)] : [],
18909
20598
  ...extraDestructureProps.map((name) => ctx.patternProp(name, j.identifier(name))),
18910
20599
  ...allowClassNameProp ? [ctx.patternProp("className", classNameId)] : [],
18911
- ...includeChildren ? [ctx.patternProp("children", childrenId)] : [],
18912
- ...d.supportsRefProp ?? false ? [ctx.patternProp("ref", refId)] : []
20600
+ ...includeChildren && !passChildrenThroughRest ? [ctx.patternProp("children", childrenId)] : []
18913
20601
  ];
18914
20602
  const patternProps = emitter.buildDestructurePatternProps({
18915
20603
  baseProps,
@@ -18925,10 +20613,8 @@ function buildAttrWrapperBody(ctx, args) {
18925
20613
  openingAttrs.push(j.jsxSpreadAttribute(sxId));
18926
20614
  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(" ")]))));
18927
20615
  openingAttrs.push(...extraJsxAttrs);
18928
- if (d.supportsRefProp ?? false) openingAttrs.push(j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId)));
18929
20616
  openingAttrs.push(j.jsxSpreadAttribute(restId));
18930
20617
  } else {
18931
- if (d.supportsRefProp ?? false) openingAttrs.push(j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId)));
18932
20618
  openingAttrs.push(...extraJsxAttrs);
18933
20619
  openingAttrs.push(j.jsxSpreadAttribute(restId));
18934
20620
  openingAttrs.push(j.jsxSpreadAttribute(sxId));
@@ -18937,7 +20623,7 @@ function buildAttrWrapperBody(ctx, args) {
18937
20623
  const jsx = emitter.buildJsxElement({
18938
20624
  tagName: jsxTag,
18939
20625
  attrs: openingAttrs,
18940
- includeChildren,
20626
+ includeChildren: includeChildren && !passChildrenThroughRest,
18941
20627
  childrenExpr: childrenId
18942
20628
  });
18943
20629
  const fnBodyStmts = [
@@ -18970,6 +20656,7 @@ function emitInputWrappers(ctx) {
18970
20656
  const omitted = [];
18971
20657
  if (!allowClassNameProp) omitted.push("\"className\"");
18972
20658
  if (!allowStyleProp) omitted.push("\"style\"");
20659
+ omitted.push("\"sx\"");
18973
20660
  return omitted.length > 0 ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
18974
20661
  })(), includesForwardedAs);
18975
20662
  emitPropsType({
@@ -19033,6 +20720,7 @@ function emitLinkWrappers(ctx) {
19033
20720
  const omitted = [];
19034
20721
  if (!allowClassNameProp) omitted.push("\"className\"");
19035
20722
  if (!allowStyleProp) omitted.push("\"style\"");
20723
+ omitted.push("\"sx\"");
19036
20724
  return omitted.length > 0 ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
19037
20725
  })()), includesForwardedAs);
19038
20726
  emitPropsType({
@@ -19114,7 +20802,7 @@ function emitEnumVariantWrappers(ctx) {
19114
20802
  const hasNeq = cases.some((c) => c.kind === "neq");
19115
20803
  const values = [...new Set(cases.map((c) => c.whenValue))].filter(Boolean);
19116
20804
  const union = hasNeq ? "string" : values.length > 0 ? values.map((v) => JSON.stringify(v)).join(" | ") : "string";
19117
- const typeText = emitter.withChildren(`React.HTMLAttributes<HTMLDivElement> & { ${propName}?: ${union} }`);
20805
+ const typeText = emitter.withChildren(`Omit<React.HTMLAttributes<HTMLDivElement>, "sx"> & { ${propName}?: ${union} }`);
19118
20806
  emitPropsType({
19119
20807
  localName: d.localName,
19120
20808
  tagName,
@@ -19245,6 +20933,7 @@ function emitIntrinsicPolymorphicWrappers(ctx) {
19245
20933
  const omitted = [];
19246
20934
  if (!allowClassNameProp) omitted.push("\"className\"");
19247
20935
  if (!allowStyleProp) omitted.push("\"style\"");
20936
+ if (!allowSxProp) omitted.push("\"sx\"");
19248
20937
  if (explicit) {
19249
20938
  const keyofExpr = emitter.keyofExprForType(d.propsType, explicit);
19250
20939
  if (keyofExpr) omitted.push(keyofExpr);
@@ -19291,6 +20980,15 @@ function emitIntrinsicPolymorphicWrappers(ctx) {
19291
20980
  const sxId = j.identifier("sx");
19292
20981
  const forwardedAsId = j.identifier("forwardedAs");
19293
20982
  if (allowSxProp) styleArgs.push(sxId);
20983
+ const passChildrenThroughRest = emitter.shouldPassChildrenThroughRest({
20984
+ includeChildren,
20985
+ includeRest: true,
20986
+ restId,
20987
+ destructureProps,
20988
+ defaultAttrs: d.attrsInfo?.defaultAttrs ?? [],
20989
+ dynamicAttrs: d.attrsInfo?.dynamicAttrs ?? [],
20990
+ staticAttrs: d.attrsInfo?.staticAttrs ?? {}
20991
+ });
19294
20992
  const patternProps = emitter.buildDestructurePatternProps({
19295
20993
  baseProps: [
19296
20994
  ...allowAsProp ? [j.property.from({
@@ -19301,7 +20999,7 @@ function emitIntrinsicPolymorphicWrappers(ctx) {
19301
20999
  })] : [],
19302
21000
  ...includesForwardedAs ? [ctx.patternProp("forwardedAs", forwardedAsId)] : [],
19303
21001
  ...allowClassNameProp ? [ctx.patternProp("className", classNameId)] : [],
19304
- ...includeChildren ? [ctx.patternProp("children", childrenId)] : [],
21002
+ ...includeChildren && !passChildrenThroughRest ? [ctx.patternProp("children", childrenId)] : [],
19305
21003
  ...allowStyleProp ? [ctx.patternProp("style", styleId)] : [],
19306
21004
  ...allowSxProp ? [ctx.patternProp("sx", sxId)] : []
19307
21005
  ],
@@ -19346,7 +21044,7 @@ function emitIntrinsicPolymorphicWrappers(ctx) {
19346
21044
  const jsx = emitter.buildJsxElement({
19347
21045
  tagName: allowAsProp ? "Component" : tagName,
19348
21046
  attrs,
19349
- includeChildren,
21047
+ includeChildren: includeChildren && !passChildrenThroughRest,
19350
21048
  childrenExpr: childrenId
19351
21049
  });
19352
21050
  const fnBodyStmts = [declStmt];
@@ -19405,10 +21103,10 @@ function emitShouldForwardPropWrappers(ctx) {
19405
21103
  const dropPrefixFromFilter = d.shouldForwardProp?.dropPrefix;
19406
21104
  const usedAttrs = emitter.getUsedAttrs(d.localName);
19407
21105
  const shouldAllowAnyPrefixProps = !!dropPrefixFromFilter && (usedAttrs.has("*") || [...usedAttrs].some((n) => n.startsWith(dropPrefixFromFilter) && !extraProps.has(n)));
19408
- const knownPrefixProps = dropPrefixFromFilter ? [...extraProps].filter((p) => p.startsWith(dropPrefixFromFilter) && isValidIdentifierName$1(p)) : [];
21106
+ const knownPrefixProps = dropPrefixFromFilter ? [...extraProps].filter((p) => p.startsWith(dropPrefixFromFilter) && isValidIdentifierName(p)) : [];
19409
21107
  const knownPrefixPropsSet = new Set(knownPrefixProps);
19410
21108
  const isExportedComponent = d.isExported ?? false;
19411
- const useSlimType = !isExportedComponent && !(d.supportsExternalStyles ?? false) && !d.usedAsValue;
21109
+ const useSlimType = !isExportedComponent && !(d.supportsExternalStyles ?? false) && !emitter.isBroadValueUsage(d);
19412
21110
  const explicit = emitter.stringifyTsType(d.propsType);
19413
21111
  const explicitPropNames = d.propsType ? emitter.getExplicitPropNames(d.propsType) : /* @__PURE__ */ new Set();
19414
21112
  const skipProps = new Set([...explicitPropNames, ...extraProps]);
@@ -19448,6 +21146,7 @@ function emitShouldForwardPropWrappers(ctx) {
19448
21146
  const omitted = [];
19449
21147
  if (!allowClassNameProp) omitted.push("\"className\"");
19450
21148
  if (!allowStyleProp) omitted.push("\"style\"");
21149
+ if (!allowSxProp) omitted.push("\"sx\"");
19451
21150
  const baseWithOmit = omitted.length ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
19452
21151
  return emitter.joinIntersection(extrasTypeText, consumedPropsTypeText, baseWithOmit);
19453
21152
  }
@@ -19488,6 +21187,7 @@ function emitShouldForwardPropWrappers(ctx) {
19488
21187
  const omitted = [];
19489
21188
  if (!allowClassNameProp) omitted.push("\"className\"");
19490
21189
  if (!allowStyleProp) omitted.push("\"style\"");
21190
+ if (!allowSxProp) omitted.push("\"sx\"");
19491
21191
  return omitted.length ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
19492
21192
  })();
19493
21193
  if (explicitIsExistingTypeRef) if (useSlimType) sfpInlineTypeText = finalTypeTextWithForwardedAs;
@@ -19625,19 +21325,29 @@ function emitShouldForwardPropWrappers(ctx) {
19625
21325
  });
19626
21326
  const shouldOmitRestSpread = !isExportedComponent && !dropPrefix && dropProps.length > 0 && dropProps.every((p) => p.startsWith("$")) && !usedAttrs.has("*") && [...usedAttrs].every((n) => n === "children" || dropProps.includes(n));
19627
21327
  const includeRest = d.shouldForwardPropFromWithConfig || d.variantDimensions?.some((dim) => dim.namespaceBooleanProp) || isExportedComponent || (d.supportsExternalStyles ?? false) || !shouldOmitRestSpread && shouldIncludeRest;
21328
+ const shouldForwardRefExplicitly = (d.supportsRefProp ?? false) && !includeRest;
19628
21329
  const isVoid = VOID_TAGS.has(tagName);
19629
21330
  const includeChildren = allowAsProp || !isVoid;
19630
21331
  const sxId = j.identifier("sx");
19631
21332
  if (allowSxProp) styleArgs.push(sxId);
19632
21333
  const destructurePartsForPattern = needsUseTheme ? destructureParts.filter((name) => name !== "theme") : destructureParts;
21334
+ const passChildrenThroughRest = emitter.shouldPassChildrenThroughRest({
21335
+ includeChildren,
21336
+ includeRest,
21337
+ restId,
21338
+ destructureProps: destructurePartsForPattern,
21339
+ defaultAttrs: d.attrsInfo?.defaultAttrs ?? [],
21340
+ dynamicAttrs: d.attrsInfo?.dynamicAttrs ?? [],
21341
+ staticAttrs: d.attrsInfo?.staticAttrs ?? {}
21342
+ });
19633
21343
  const patternProps = emitter.buildDestructurePatternProps({
19634
21344
  baseProps: [
19635
21345
  ...allowAsProp ? [asDestructureProp(tagName)] : [],
19636
21346
  ...includesForwardedAs ? [ctx.patternProp("forwardedAs", forwardedAsId)] : [],
19637
21347
  ...allowClassNameProp ? [ctx.patternProp("className", classNameId)] : [],
19638
- ...includeChildren ? [ctx.patternProp("children", childrenId)] : [],
21348
+ ...includeChildren && !passChildrenThroughRest ? [ctx.patternProp("children", childrenId)] : [],
19639
21349
  ...allowStyleProp ? [ctx.patternProp("style", styleId)] : [],
19640
- ...d.supportsRefProp ?? false ? [ctx.patternProp("ref", refId)] : [],
21350
+ ...shouldForwardRefExplicitly ? [ctx.patternProp("ref", refId)] : [],
19641
21351
  ...allowSxProp ? [ctx.patternProp("sx", sxId)] : []
19642
21352
  ],
19643
21353
  destructureProps: destructurePartsForPattern,
@@ -19677,7 +21387,7 @@ function emitShouldForwardPropWrappers(ctx) {
19677
21387
  attrsInfo: attrsInfoForJsx,
19678
21388
  propExprFor: (prop) => j.identifier(prop)
19679
21389
  }) : [],
19680
- ...d.supportsRefProp ?? false ? [j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId))] : [],
21390
+ ...shouldForwardRefExplicitly ? [j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId))] : [],
19681
21391
  ...includeRest ? [j.jsxSpreadAttribute(restId)] : [],
19682
21392
  ...emitter.buildDynamicAttrsFromProps({
19683
21393
  dynamicAttrs: attrsInfoForJsx?.dynamicAttrs ?? [],
@@ -19689,7 +21399,7 @@ function emitShouldForwardPropWrappers(ctx) {
19689
21399
  const jsx = emitter.buildJsxElement({
19690
21400
  tagName: allowAsProp ? "Component" : tagName,
19691
21401
  attrs: openingAttrs,
19692
- includeChildren,
21402
+ includeChildren: includeChildren && !passChildrenThroughRest,
19693
21403
  childrenExpr: childrenId
19694
21404
  });
19695
21405
  const fnBodyStmts = [declStmt];
@@ -19738,7 +21448,7 @@ function buildExtraPropTypeLines(d, extraProps, skip) {
19738
21448
  const staticVariantPropTypes = buildStaticVariantPropTypes(d);
19739
21449
  const lines = [];
19740
21450
  for (const p of extraProps) {
19741
- if (!isValidIdentifierName$1(p) || skip?.(p)) continue;
21451
+ if (!isValidIdentifierName(p) || skip?.(p)) continue;
19742
21452
  const variantType = variantDimByProp.get(p);
19743
21453
  if (variantType) {
19744
21454
  lines.push(` ${p}?: ${variantType};`);
@@ -19778,7 +21488,7 @@ function emitSimpleWithConfigWrappers(ctx) {
19778
21488
  const allowStyleProp = emitter.shouldAllowStyleProp(d);
19779
21489
  const allowSxProp = emitter.shouldAllowSxProp(d);
19780
21490
  const allowAsProp = shouldAllowAsProp(d, tagName);
19781
- const useSlimType = !(d.isExported ?? false) && !supportsExternalStyles && !d.usedAsValue;
21491
+ const useSlimType = !(d.isExported ?? false) && !supportsExternalStyles && !emitter.isBroadValueUsage(d);
19782
21492
  const willForwardRef = (d.supportsRefProp ?? false) || allowClassNameProp || allowStyleProp || (() => {
19783
21493
  const used = emitter.getUsedAttrs(d.localName);
19784
21494
  return used.has("*") || !!d.usedAsValue || (d.isExported ?? false) || used.size > 0 || hasElementPropsInDefaultAttrs(d);
@@ -19789,7 +21499,7 @@ function emitSimpleWithConfigWrappers(ctx) {
19789
21499
  if (d.consumerUsesSpread === true || d.consumerUsesElementProps === true || d.consumerUsesSpread === void 0 && d.consumerUsesElementProps === void 0 && supportsExternalStyles) return true;
19790
21500
  if (allowClassNameProp || allowStyleProp || allowSxProp) return true;
19791
21501
  const used = emitter.getUsedAttrs(d.localName);
19792
- if (used.has("*")) return true;
21502
+ if (used.has("*") || d.valueUsageKind === "virtualListElementType") return true;
19793
21503
  return used.size > 0;
19794
21504
  })();
19795
21505
  const baseTypeText = shouldUseIntrinsicProps ? emitter.inferredIntrinsicPropsTypeText({
@@ -19844,12 +21554,11 @@ function emitSimpleWithConfigWrappers(ctx) {
19844
21554
  const classNameId = j.identifier("className");
19845
21555
  const childrenId = j.identifier("children");
19846
21556
  const styleId = j.identifier("style");
19847
- const refId = j.identifier("ref");
19848
21557
  const restId = j.identifier("rest");
19849
21558
  const isVoidTag = VOID_TAGS.has(tagName);
19850
21559
  if (!allowClassNameProp && !allowStyleProp && !needsUseThemeWithConfig) {
19851
21560
  const usedAttrs = emitter.getUsedAttrs(d.localName);
19852
- const includeRest = usedAttrs.has("*") || !!d.usedAsValue || (d.isExported ?? false) || usedAttrs.size > 0 || hasElementPropsInDefaultAttrs(d);
21561
+ const includeRest = usedAttrs.has("*") || emitter.isBroadValueUsage(d) || (d.isExported ?? false) || usedAttrs.size > 0 || hasElementPropsInDefaultAttrs(d);
19853
21562
  const variantProps = /* @__PURE__ */ new Set();
19854
21563
  if (d.variantStyleKeys) for (const [when] of Object.entries(d.variantStyleKeys)) {
19855
21564
  const { props } = emitter.collectConditionProps({ when });
@@ -19905,13 +21614,21 @@ function emitSimpleWithConfigWrappers(ctx) {
19905
21614
  }
19906
21615
  const sxId = j.identifier("sx");
19907
21616
  if (allowSxProp) styleArgs.push(sxId);
21617
+ const passChildrenThroughRest = emitter.shouldPassChildrenThroughRest({
21618
+ includeChildren: !isVoidTag,
21619
+ includeRest: true,
21620
+ restId,
21621
+ destructureProps: [...pseudoGuardProps],
21622
+ defaultAttrs: d.attrsInfo?.defaultAttrs ?? [],
21623
+ dynamicAttrs: d.attrsInfo?.dynamicAttrs ?? [],
21624
+ staticAttrs: d.attrsInfo?.staticAttrs ?? {}
21625
+ });
19908
21626
  const patternProps = emitter.buildDestructurePatternProps({
19909
21627
  baseProps: [
19910
21628
  ...allowAsProp ? [asDestructureProp(tagName)] : [],
19911
21629
  emitter.patternProp("className", classNameId),
19912
- ...isVoidTag ? [] : [emitter.patternProp("children", childrenId)],
21630
+ ...!isVoidTag && !passChildrenThroughRest ? [emitter.patternProp("children", childrenId)] : [],
19913
21631
  emitter.patternProp("style", styleId),
19914
- ...d.supportsRefProp ?? false ? [emitter.patternProp("ref", refId)] : [],
19915
21632
  ...allowSxProp ? [emitter.patternProp("sx", sxId)] : []
19916
21633
  ],
19917
21634
  destructureProps: [...pseudoGuardProps],
@@ -19939,7 +21656,6 @@ function emitSimpleWithConfigWrappers(ctx) {
19939
21656
  attrsInfo,
19940
21657
  propExprFor: (prop) => j.identifier(prop)
19941
21658
  }),
19942
- ...d.supportsRefProp ?? false ? [j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId))] : [],
19943
21659
  j.jsxSpreadAttribute(restId),
19944
21660
  ...emitter.buildDynamicAttrsFromProps({
19945
21661
  dynamicAttrs: attrsInfo?.dynamicAttrs ?? [],
@@ -19947,8 +21663,8 @@ function emitSimpleWithConfigWrappers(ctx) {
19947
21663
  })
19948
21664
  ];
19949
21665
  emitter.appendMergingAttrs(openingAttrs, merging);
19950
- const openingEl = j.jsxOpeningElement(j.jsxIdentifier(allowAsProp ? "Component" : tagName), openingAttrs, false);
19951
- const jsx = isVoidTag ? {
21666
+ const openingEl = j.jsxOpeningElement(j.jsxIdentifier(allowAsProp ? "Component" : tagName), openingAttrs, isVoidTag || passChildrenThroughRest);
21667
+ const jsx = isVoidTag || passChildrenThroughRest ? {
19952
21668
  type: "JSXElement",
19953
21669
  openingElement: {
19954
21670
  ...openingEl,
@@ -19999,8 +21715,8 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
19999
21715
  let inlineTypeText;
20000
21716
  const isExportedComponent = d.isExported ?? false;
20001
21717
  const usePolymorphicPattern = allowAsProp && isExportedComponent;
20002
- const willForwardRef = (d.supportsRefProp ?? false) || isExportedComponent || hasComplementaryVariantPairs(d) || !!d.variantDimensions?.some((dim) => dim.namespaceBooleanProp);
20003
- const useSlimType = !isExportedComponent && !(d.supportsExternalStyles ?? false) && !d.usedAsValue && !hasElementPropsInDefaultAttrs(d);
21718
+ const willForwardRef = (d.supportsRefProp ?? false) || isExportedComponent || d.valueUsageKind === "virtualListElementType" || hasComplementaryVariantPairs(d) || !!d.variantDimensions?.some((dim) => dim.namespaceBooleanProp);
21719
+ const useSlimType = !isExportedComponent && !(d.supportsExternalStyles ?? false) && !emitter.isBroadValueUsage(d) && !hasElementPropsInDefaultAttrs(d);
20004
21720
  {
20005
21721
  const explicit = emitter.stringifyTsType(d.propsType);
20006
21722
  const explicitPropNames = d.propsType ? emitter.getExplicitPropNames(d.propsType) : /* @__PURE__ */ new Set();
@@ -20038,7 +21754,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20038
21754
  forceNarrow: useSlimType
20039
21755
  });
20040
21756
  const supportsExternalStyles = d.supportsExternalStyles ?? false;
20041
- 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) => {
21757
+ 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) => {
20042
21758
  if (n === "children" || n === "className" || n === "style" || n === "as" || n === "forwardedAs" || n.startsWith("$")) return false;
20043
21759
  return !handledProps.has(n);
20044
21760
  });
@@ -20047,6 +21763,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20047
21763
  const omitted = [];
20048
21764
  if (!allowClassNameProp) omitted.push("\"className\"");
20049
21765
  if (!allowStyleProp) omitted.push("\"style\"");
21766
+ if (!allowSxProp) omitted.push("\"sx\"");
20050
21767
  return omitted.length ? `Omit<${base}, ${omitted.join(" | ")}>` : base;
20051
21768
  })();
20052
21769
  const customStyleDrivingPropsTypeText = (() => {
@@ -20062,7 +21779,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20062
21779
  const compoundVariantWhenKeys = collectCompoundVariantKeys(d.compoundVariants, { syntheticOnly: true });
20063
21780
  for (const k of compoundVariantWhenKeys) keys.delete(k);
20064
21781
  const variantDimByProp = buildVariantDimPropTypeMap(d);
20065
- 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)));
21782
+ 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)));
20066
21783
  if (filtered.length === 0) return "{}";
20067
21784
  const staticVariantPropTypes = buildStaticVariantPropTypes(d);
20068
21785
  return `{\n${filtered.map((k) => {
@@ -20079,7 +21796,8 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20079
21796
  propsType: d.propsType,
20080
21797
  typeText: explicit,
20081
21798
  allowClassNameProp,
20082
- allowStyleProp
21799
+ allowStyleProp,
21800
+ allowSxProp
20083
21801
  }) : void 0;
20084
21802
  const explicitTypeIncludesIntrinsicProps = !!d.propsType && explicitTypeMayContainExternalStyleProps({
20085
21803
  ctx,
@@ -20231,8 +21949,6 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20231
21949
  if (useAsProp || allowClassNameProp || allowStyleProp || needsUseTheme) {
20232
21950
  const isVoidTag = VOID_TAGS.has(tagName);
20233
21951
  const includeChildren = useAsProp || !isVoidTag;
20234
- const propsParamId = j.identifier("props");
20235
- emitter.annotatePropsParam(propsParamId, d.localName, inlineTypeText);
20236
21952
  const propsId = j.identifier("props");
20237
21953
  const componentId = j.identifier("Component");
20238
21954
  const classNameId = j.identifier("className");
@@ -20240,12 +21956,22 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20240
21956
  const styleId = j.identifier("style");
20241
21957
  const sxId = j.identifier("sx");
20242
21958
  const refId = j.identifier("ref");
20243
- const restId = shouldIncludeRest ? j.identifier("rest") : null;
21959
+ let restId = shouldIncludeRest ? j.identifier("rest") : null;
21960
+ const shouldForwardRefExplicitly = !restId && ((d.supportsRefProp ?? false) || willForwardRef);
20244
21961
  const forwardedAsId = j.identifier("forwardedAs");
20245
21962
  if (allowSxProp) styleArgs.push(sxId);
20246
21963
  for (const attr of d.attrsInfo?.defaultAttrs ?? []) if (!destructureProps.includes(attr.jsxProp)) destructureProps.push(attr.jsxProp);
20247
21964
  for (const attr of d.attrsInfo?.dynamicAttrs ?? []) if (!destructureProps.includes(attr.jsxProp)) destructureProps.push(attr.jsxProp);
20248
21965
  const destructurePropsForPattern = needsUseTheme ? destructureProps.filter((name) => name !== "theme") : destructureProps;
21966
+ const passChildrenThroughRest = emitter.shouldPassChildrenThroughRest({
21967
+ includeChildren,
21968
+ includeRest: Boolean(restId),
21969
+ restId,
21970
+ destructureProps: destructurePropsForPattern,
21971
+ defaultAttrs: d.attrsInfo?.defaultAttrs ?? [],
21972
+ dynamicAttrs: d.attrsInfo?.dynamicAttrs ?? [],
21973
+ staticAttrs: d.attrsInfo?.staticAttrs ?? {}
21974
+ });
20249
21975
  const patternProps = emitter.buildDestructurePatternProps({
20250
21976
  baseProps: [
20251
21977
  ...useAsProp ? [j.property.from({
@@ -20256,9 +21982,9 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20256
21982
  })] : [],
20257
21983
  ...includesForwardedAs ? [ctx.patternProp("forwardedAs", forwardedAsId)] : [],
20258
21984
  ...allowClassNameProp ? [ctx.patternProp("className", classNameId)] : [],
20259
- ...includeChildren ? [ctx.patternProp("children", childrenId)] : [],
21985
+ ...includeChildren && !passChildrenThroughRest ? [ctx.patternProp("children", childrenId)] : [],
20260
21986
  ...allowStyleProp ? [ctx.patternProp("style", styleId)] : [],
20261
- ...(d.supportsRefProp ?? false) || !restId && willForwardRef ? [ctx.patternProp("ref", refId)] : [],
21987
+ ...shouldForwardRefExplicitly ? [ctx.patternProp("ref", refId)] : [],
20262
21988
  ...allowSxProp ? [ctx.patternProp("sx", sxId)] : []
20263
21989
  ],
20264
21990
  destructureProps: destructurePropsForPattern,
@@ -20266,8 +21992,12 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20266
21992
  includeRest: Boolean(restId),
20267
21993
  restId: restId ?? void 0
20268
21994
  });
21995
+ const usePropsDirectlyForRest = Boolean(restId) && patternProps.length === 1 && patternProps[0]?.type === "RestElement";
21996
+ if (usePropsDirectlyForRest) restId = propsId;
20269
21997
  const usePropsChildrenDirectly = emitter.isChildrenOnlyDestructurePattern(patternProps);
20270
- const declStmt = usePropsChildrenDirectly ? null : j.variableDeclaration("const", [j.variableDeclarator(j.objectPattern(patternProps), propsId)]);
21998
+ const propsParam = usePropsChildrenDirectly ? emitter.buildChildrenOnlyParam(inlineTypeText ?? emitter.propsTypeNameFor(d.localName)) : j.identifier("props");
21999
+ if (!usePropsChildrenDirectly) emitter.annotatePropsParam(propsParam, d.localName, inlineTypeText);
22000
+ const declStmt = usePropsChildrenDirectly || usePropsDirectlyForRest ? null : j.variableDeclaration("const", [j.variableDeclarator(j.objectPattern(patternProps), propsId)]);
20271
22001
  const { attrsInfo, staticClassNameExpr } = emitter.splitAttrsInfo(d.attrsInfo, getBridgeClassVar(d), d.extraClassNames);
20272
22002
  const { attrsInfo: attrsInfoWithoutForwardedAsStatic, forwardedAsStaticFallback } = splitForwardedAsStaticAttrs({
20273
22003
  attrsInfo,
@@ -20292,7 +22022,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20292
22022
  attrsInfo: attrsInfoWithoutForwardedAsStatic,
20293
22023
  propExprFor: (prop) => j.identifier(prop)
20294
22024
  }),
20295
- ...(d.supportsRefProp ?? false) || !restId && willForwardRef ? [j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId))] : [],
22025
+ ...shouldForwardRefExplicitly ? [j.jsxAttribute(j.jsxIdentifier("ref"), j.jsxExpressionContainer(refId))] : [],
20296
22026
  ...restId ? [j.jsxSpreadAttribute(restId)] : [],
20297
22027
  ...emitter.buildDynamicAttrsFromProps({
20298
22028
  dynamicAttrs: attrsInfoWithoutForwardedAsStatic?.dynamicAttrs ?? [],
@@ -20304,8 +22034,8 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20304
22034
  const jsx = emitter.buildJsxElement({
20305
22035
  tagName: useAsProp ? "Component" : tagName,
20306
22036
  attrs: openingAttrs,
20307
- includeChildren,
20308
- childrenExpr: usePropsChildrenDirectly ? j.memberExpression(propsId, j.identifier("children")) : childrenId
22037
+ includeChildren: includeChildren && !passChildrenThroughRest,
22038
+ childrenExpr: childrenId
20309
22039
  });
20310
22040
  const bodyStmts = [];
20311
22041
  if (declStmt) bodyStmts.push(declStmt);
@@ -20315,7 +22045,7 @@ function emitSimpleExportedIntrinsicWrappers(ctx) {
20315
22045
  const shouldAddTypeParams = allowAsProp && emitTypes;
20316
22046
  emitted.push(...withLeadingCommentsOnFirstFunction([emitter.buildWrapperFunction({
20317
22047
  localName: d.localName,
20318
- params: [propsParamId],
22048
+ params: [propsParam],
20319
22049
  bodyStmts,
20320
22050
  typeParameters: shouldAddTypeParams ? buildPolymorphicTypeParams(j, tagName) : void 0
20321
22051
  })], d));
@@ -20390,6 +22120,7 @@ function maybeOmitExternalStylePropsFromExplicitTypeText(args) {
20390
22120
  const omitted = [];
20391
22121
  if (!args.allowClassNameProp) omitted.push("\"className\"");
20392
22122
  if (!args.allowStyleProp) omitted.push("\"style\"");
22123
+ if (!args.allowSxProp) omitted.push("\"sx\"");
20393
22124
  return omitted.length > 0 ? `Omit<${args.typeText}, ${omitted.join(" | ")}>` : args.typeText;
20394
22125
  }
20395
22126
  function explicitTypeMayContainExternalStyleProps(args) {
@@ -20955,7 +22686,8 @@ function extractCssHelpersStep(ctx) {
20955
22686
  styledImports,
20956
22687
  cssLocal,
20957
22688
  toStyleKey,
20958
- preserveDeclarationOnlyNames: collectCssHelpersUsedBySkippedImportedRoots(ctx)
22689
+ preserveDeclarationOnlyNames: collectCssHelpersUsedBySkippedImportedRoots(ctx),
22690
+ preservedStyledComponentSelectorNames: collectSkippedImportedRootStyledComponentNames(ctx)
20959
22691
  });
20960
22692
  if (cssHelpers.unsupportedCssUsages.length > 0) return returnResult({
20961
22693
  code: null,
@@ -20965,6 +22697,26 @@ function extractCssHelpersStep(ctx) {
20965
22697
  if (cssHelpers.changed) ctx.markChanged();
20966
22698
  return CONTINUE;
20967
22699
  }
22700
+ function collectSkippedImportedRootStyledComponentNames(ctx) {
22701
+ if (ctx.options.allowPartialMigration !== true || ctx.options.transformMode === "leavesOnly") return /* @__PURE__ */ new Set();
22702
+ const names = /* @__PURE__ */ new Set();
22703
+ ctx.root.find(ctx.j.VariableDeclarator).forEach((path) => {
22704
+ const id = path.node.id;
22705
+ if (id.type !== "Identifier") return;
22706
+ if (initializerWrapsImportedComponent(ctx, path.node.init)) names.add(id.name);
22707
+ });
22708
+ return names;
22709
+ }
22710
+ function initializerWrapsImportedComponent(ctx, init) {
22711
+ const node = init;
22712
+ if (!node) return false;
22713
+ if (node.type === "TaggedTemplateExpression") return tagWrapsImportedComponent(ctx, node.tag);
22714
+ if (node.type === "CallExpression") {
22715
+ const callee = node.callee;
22716
+ return callee?.type === "TaggedTemplateExpression" && tagWrapsImportedComponent(ctx, callee.tag);
22717
+ }
22718
+ return false;
22719
+ }
20968
22720
  function collectCssHelpersUsedBySkippedImportedRoots(ctx) {
20969
22721
  if (ctx.options.allowPartialMigration !== true || ctx.options.transformMode === "leavesOnly") return /* @__PURE__ */ new Set();
20970
22722
  if ((ctx.importMap ?? /* @__PURE__ */ new Map()).size === 0) return /* @__PURE__ */ new Set();
@@ -23443,6 +25195,7 @@ function tryDecomposeConditionalBranches(condBody, paramName) {
23443
25195
  conditionProp,
23444
25196
  staticValue,
23445
25197
  dynamicBranchExpr: dynamicBranch,
25198
+ paramName,
23446
25199
  dynamicProps,
23447
25200
  isStaticWhenFalse
23448
25201
  };
@@ -24586,7 +26339,7 @@ function createCssHelperResolver(args) {
24586
26339
  const path = getMemberPathFromIdentifier(test, paramName);
24587
26340
  return path && path[0] === "theme" && path.length > 1 ? path.slice(1).join(".") : null;
24588
26341
  };
24589
- const resolveCssHelperTemplate = (template, paramName, loc) => {
26342
+ const resolveCssHelperTemplate = (template, paramName, loc, options) => {
24590
26343
  const bail = (type, context, exprLoc) => {
24591
26344
  warnings.push({
24592
26345
  severity: "warning",
@@ -24605,7 +26358,7 @@ function createCssHelperResolver(args) {
24605
26358
  const lookupImport = (localName) => importMap.get(localName) ?? null;
24606
26359
  for (const rule of rules) {
24607
26360
  const rawMedia = findSupportedAtRule(rule.atRuleStack);
24608
- if (hasUnsupportedAtRule(rule.atRuleStack)) return bail("Conditional `css` block: @-rules (e.g., @media, @supports) are not supported");
26361
+ if (hasUnsupportedAtRule(rule.atRuleStack)) return bail("Conditional `css` block: unsupported or mixed @-rules require manual handling");
24609
26362
  let media = rawMedia;
24610
26363
  let computedMediaKey = null;
24611
26364
  if (rawMedia) {
@@ -24627,6 +26380,7 @@ function createCssHelperResolver(args) {
24627
26380
  const rawSelector = (rule.selector ?? "").trim();
24628
26381
  const specificityResult = normalizeSpecificityHacks(rawSelector);
24629
26382
  if (specificityResult.hasHigherTier) return bail("Styled-components specificity hacks like `&&` / `&&&` are not representable in StyleX");
26383
+ 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);
24630
26384
  const selector = specificityResult.normalized.trim();
24631
26385
  const specificityStripped = specificityResult.wasStripped;
24632
26386
  const allowDynamicValues = selector === "&";
@@ -24765,6 +26519,17 @@ function createCssHelperResolver(args) {
24765
26519
  if (!resolved && hasThemeAccessInExpr(expr, paramName)) return bail("Conditional `css` block: failed to parse expression", { property: d.property }, exprLoc);
24766
26520
  if (resolved) if (hasStaticParts) {
24767
26521
  const { prefix, suffix } = extractPrefixSuffix(parts);
26522
+ const borderParts = parseInterpolatedBorderStaticParts({
26523
+ prop: d.property.trim(),
26524
+ prefix,
26525
+ suffix
26526
+ });
26527
+ if (borderParts) {
26528
+ if (borderParts.width) target[borderParts.widthProp] = mergeIntoContext(borderParts.width, borderParts.widthProp, target);
26529
+ if (borderParts.style) target[borderParts.styleProp] = mergeIntoContext(borderParts.style, borderParts.styleProp, target);
26530
+ target[borderParts.colorProp] = mergeIntoContext(resolved.ast, borderParts.colorProp, target);
26531
+ continue;
26532
+ }
24768
26533
  const templateAst = parseExpr(wrapExprWithStaticParts(resolved.exprString, prefix, suffix));
24769
26534
  if (templateAst) {
24770
26535
  for (const mapped of cssDeclarationToStylexDeclarations(d)) target[mapped.prop] = mergeIntoContext(templateAst, mapped.prop, target);
@@ -24869,7 +26634,7 @@ function resolveTemplateLiteralBranch(ctx, args) {
24869
26634
  if (hasUnsupportedAtRule(rule.atRuleStack)) {
24870
26635
  ctx.warnings?.push({
24871
26636
  severity: "warning",
24872
- type: "CSS block contains unsupported at-rule (only @media and @container are supported; @supports, etc. require manual handling)",
26637
+ type: "CSS block contains unsupported at-rule (only @media, @container, and @supports are supported; mixed nested at-rules require manual handling)",
24873
26638
  loc: null
24874
26639
  });
24875
26640
  return null;
@@ -25380,7 +27145,7 @@ function resolveStaticTemplateExpressionAst(args) {
25380
27145
  return null;
25381
27146
  }
25382
27147
  function buildPropAccessExpr(j, propName, defaultValue) {
25383
- const baseExpr = isValidIdentifierName$1(propName) ? j.identifier(propName) : j.memberExpression(j.identifier("props"), j.literal(propName), true);
27148
+ const baseExpr = isValidIdentifierName(propName) ? j.identifier(propName) : j.memberExpression(j.identifier("props"), j.literal(propName), true);
25384
27149
  if (defaultValue !== void 0) return j.logicalExpression("??", baseExpr, cloneAstNode(defaultValue));
25385
27150
  return baseExpr;
25386
27151
  }
@@ -25388,6 +27153,7 @@ function buildPropAccessExpr(j, propName, defaultValue) {
25388
27153
  //#region src/internal/lower-rules/css-helper-handlers.ts
25389
27154
  const createCssHelperHandlers = (ctx) => {
25390
27155
  const { j, filePath, decl, warnings, styleObj, variantBuckets, variantStyleKeys, cssHelperFunctions, usedCssHelperFunctions, parseExpr, resolveValue, resolveCall, resolveImportInScope, resolverImports, isCssHelperTaggedTemplate, resolveCssHelperTemplate, applyVariant, dropAllTestInfoProps, componentInfo, handlerContext, markBail } = ctx;
27156
+ const cssHelperTemplateOptions = { rejectStrippedSpecificity: decl.base.kind === "component" };
25391
27157
  const tplCtx = {
25392
27158
  j,
25393
27159
  filePath,
@@ -25584,7 +27350,7 @@ const createCssHelperHandlers = (ctx) => {
25584
27350
  markBail();
25585
27351
  return true;
25586
27352
  }
25587
- const defaultResolved = resolveCssHelperTemplate(parsed.defaultCssTemplate.quasi, null, helperFn.loc ?? decl.loc);
27353
+ const defaultResolved = resolveCssHelperTemplate(parsed.defaultCssTemplate.quasi, null, helperFn.loc ?? decl.loc, cssHelperTemplateOptions);
25588
27354
  if (!defaultResolved || defaultResolved.dynamicProps.length > 0) {
25589
27355
  warnings.push({
25590
27356
  severity: "warning",
@@ -25597,7 +27363,7 @@ const createCssHelperHandlers = (ctx) => {
25597
27363
  }
25598
27364
  mergeStyleObjects(baseFromHelper, defaultResolved.style);
25599
27365
  for (const [caseValue, tpl] of parsed.caseCssTemplates.entries()) {
25600
- const res = resolveCssHelperTemplate(tpl.quasi, null, helperFn.loc ?? decl.loc);
27366
+ const res = resolveCssHelperTemplate(tpl.quasi, null, helperFn.loc ?? decl.loc, cssHelperTemplateOptions);
25601
27367
  if (!res || res.dynamicProps.length > 0) {
25602
27368
  warnings.push({
25603
27369
  severity: "warning",
@@ -25633,10 +27399,241 @@ const createCssHelperHandlers = (ctx) => {
25633
27399
  };
25634
27400
  };
25635
27401
  //#endregion
27402
+ //#region src/internal/lower-rules/static-evaluator.ts
27403
+ const MAX_STATIC_CALL_DEPTH = 20;
27404
+ function evaluateLocalCallValueTransform(args) {
27405
+ const callStack = args.callStack ?? /* @__PURE__ */ new Set();
27406
+ if (callStack.has(args.calleeName) || callStack.size >= MAX_STATIC_CALL_DEPTH) return null;
27407
+ const fn = findLocalSingleParamFunction(args);
27408
+ if (!fn) return null;
27409
+ const nextCallStack = new Set(callStack);
27410
+ nextCallStack.add(args.calleeName);
27411
+ const result = evaluateFunctionBody(fn.body, fn.paramName, args.argValue, {
27412
+ j: args.j,
27413
+ root: args.root,
27414
+ callStack: nextCallStack
27415
+ });
27416
+ return result.supported && result.returned ? result.value : null;
27417
+ }
27418
+ function evaluateObservedDynamicExpression(args) {
27419
+ const result = evaluateStaticExpression(args.expression, args.propName, args.propValue, {
27420
+ j: args.j,
27421
+ root: args.root,
27422
+ paramName: args.paramName ?? null,
27423
+ callStack: /* @__PURE__ */ new Set()
27424
+ });
27425
+ return result.supported ? result.value : null;
27426
+ }
27427
+ function findLocalSingleParamFunction(args) {
27428
+ const { j, root, calleeName } = args;
27429
+ const candidates = [];
27430
+ let matchingBindings = 0;
27431
+ root.find(j.FunctionDeclaration, { id: { name: calleeName } }).forEach((path) => {
27432
+ matchingBindings += 1;
27433
+ const fnNode = path.node;
27434
+ const paramName = getSingleIdentifierParamName(fnNode.params);
27435
+ if (paramName) candidates.push({
27436
+ paramName,
27437
+ body: fnNode.body
27438
+ });
27439
+ });
27440
+ root.find(j.VariableDeclarator, { id: { name: calleeName } }).forEach((path) => {
27441
+ matchingBindings += 1;
27442
+ const init = path.node.init;
27443
+ if (!init || init.type !== "ArrowFunctionExpression" && init.type !== "FunctionExpression") return;
27444
+ const paramName = getSingleIdentifierParamName(init.params);
27445
+ if (paramName) candidates.push({
27446
+ paramName,
27447
+ body: init.body
27448
+ });
27449
+ });
27450
+ const [candidate] = candidates;
27451
+ return matchingBindings === 1 && candidate ? candidate : null;
27452
+ }
27453
+ function getSingleIdentifierParamName(params) {
27454
+ if (!params || params.length !== 1) return null;
27455
+ const param = params[0];
27456
+ return param.type === "Identifier" && param.name ? param.name : null;
27457
+ }
27458
+ function evaluateFunctionBody(body, propName, propValue, ctx) {
27459
+ const bodyNode = body;
27460
+ if (!bodyNode) return { supported: false };
27461
+ if (bodyNode.type !== "BlockStatement") {
27462
+ const result = evaluateStaticExpression(bodyNode, propName, propValue, ctx);
27463
+ return result.supported ? {
27464
+ supported: true,
27465
+ returned: true,
27466
+ value: result.value
27467
+ } : { supported: false };
27468
+ }
27469
+ const statements = bodyNode.body;
27470
+ if (!Array.isArray(statements)) return { supported: false };
27471
+ for (const statement of statements) {
27472
+ const result = evaluateStaticStatement(statement, propName, propValue, ctx);
27473
+ if (!result.supported || result.returned) return result;
27474
+ }
27475
+ return {
27476
+ supported: true,
27477
+ returned: false
27478
+ };
27479
+ }
27480
+ function evaluateStaticStatement(statement, propName, propValue, ctx) {
27481
+ const node = statement;
27482
+ if (!node) return { supported: false };
27483
+ if (node.type === "ReturnStatement") {
27484
+ if (node.argument === null || node.argument === void 0) return {
27485
+ supported: true,
27486
+ returned: true,
27487
+ value: void 0
27488
+ };
27489
+ const result = evaluateStaticExpression(node.argument, propName, propValue, ctx);
27490
+ return result.supported ? {
27491
+ supported: true,
27492
+ returned: true,
27493
+ value: result.value
27494
+ } : { supported: false };
27495
+ }
27496
+ if (node.type === "IfStatement") {
27497
+ const test = evaluateStaticExpression(node.test, propName, propValue, ctx);
27498
+ if (!test.supported || typeof test.value !== "boolean") return { supported: false };
27499
+ if (test.value) return evaluateStaticBranch(node.consequent, propName, propValue, ctx);
27500
+ return node.alternate ? evaluateStaticBranch(node.alternate, propName, propValue, ctx) : {
27501
+ supported: true,
27502
+ returned: false
27503
+ };
27504
+ }
27505
+ return { supported: false };
27506
+ }
27507
+ function evaluateStaticBranch(branch, propName, propValue, ctx) {
27508
+ const node = branch;
27509
+ if (node?.type === "BlockStatement") return evaluateFunctionBody(node, propName, propValue, ctx);
27510
+ return evaluateStaticStatement(branch, propName, propValue, ctx);
27511
+ }
27512
+ function evaluateStaticExpression(expression, propName, propValue, ctx) {
27513
+ const node = expression;
27514
+ if (!node) return { supported: false };
27515
+ if (node.type === "Identifier") return node.name === propName ? {
27516
+ supported: true,
27517
+ value: propValue
27518
+ } : { supported: false };
27519
+ if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
27520
+ const info = extractRootAndPath(node);
27521
+ if (info && ctx.paramName && info.rootName === ctx.paramName && info.path[0] === propName) return info.path.length === 1 ? {
27522
+ supported: true,
27523
+ value: propValue
27524
+ } : { supported: false };
27525
+ return { supported: false };
27526
+ }
27527
+ if (node.type === "CallExpression") {
27528
+ const callee = node.callee;
27529
+ if (callee?.type !== "Identifier" || !callee.name || (node.arguments?.length ?? 0) !== 1) return { supported: false };
27530
+ const callArg = evaluateStaticExpression(node.arguments?.[0], propName, propValue, ctx);
27531
+ if (!callArg.supported) return { supported: false };
27532
+ const value = evaluateLocalCallValueTransform({
27533
+ j: ctx.j,
27534
+ root: ctx.root,
27535
+ calleeName: callee.name,
27536
+ argValue: callArg.value,
27537
+ callStack: ctx.callStack
27538
+ });
27539
+ return isStaticEvalValue(value) ? {
27540
+ supported: true,
27541
+ value
27542
+ } : { supported: false };
27543
+ }
27544
+ if (node.type === "Literal") return isStaticEvalValue(node.value) ? {
27545
+ supported: true,
27546
+ value: node.value
27547
+ } : { supported: false };
27548
+ if (node.type === "StringLiteral" || node.type === "NumericLiteral" || node.type === "BooleanLiteral") return isStaticEvalValue(node.value) ? {
27549
+ supported: true,
27550
+ value: node.value
27551
+ } : { supported: false };
27552
+ if (node.type === "NullLiteral") return {
27553
+ supported: true,
27554
+ value: null
27555
+ };
27556
+ if (node.type === "ParenthesizedExpression" || node.type === "TSAsExpression" || node.type === "TSTypeAssertion") return evaluateStaticExpression(node.expression, propName, propValue, ctx);
27557
+ if (node.type === "UnaryExpression") {
27558
+ const argument = evaluateStaticExpression(node.argument, propName, propValue, ctx);
27559
+ if (!argument.supported) return { supported: false };
27560
+ if (node.operator === "!") return {
27561
+ supported: true,
27562
+ value: !argument.value
27563
+ };
27564
+ if (node.operator === "typeof") return {
27565
+ supported: true,
27566
+ value: typeof argument.value
27567
+ };
27568
+ return { supported: false };
27569
+ }
27570
+ if (node.type === "LogicalExpression") {
27571
+ const left = evaluateStaticExpression(node.left, propName, propValue, ctx);
27572
+ if (!left.supported) return { supported: false };
27573
+ if (node.operator === "||") return left.value ? left : evaluateStaticExpression(node.right, propName, propValue, ctx);
27574
+ if (node.operator === "&&") return left.value ? evaluateStaticExpression(node.right, propName, propValue, ctx) : left;
27575
+ if (node.operator === "??") return left.value === null || left.value === void 0 ? evaluateStaticExpression(node.right, propName, propValue, ctx) : left;
27576
+ return { supported: false };
27577
+ }
27578
+ if (node.type === "BinaryExpression") return evaluateStaticBinaryExpression(node, propName, propValue, ctx);
27579
+ if (node.type === "ConditionalExpression") {
27580
+ const test = evaluateStaticExpression(node.test, propName, propValue, ctx);
27581
+ if (!test.supported || typeof test.value !== "boolean") return { supported: false };
27582
+ return evaluateStaticExpression(test.value ? node.consequent : node.alternate, propName, propValue, ctx);
27583
+ }
27584
+ if (node.type === "TemplateLiteral" && node.quasis && node.expressions) return evaluateStaticTemplateLiteral({
27585
+ quasis: node.quasis,
27586
+ expressions: node.expressions
27587
+ }, propName, propValue, ctx);
27588
+ return { supported: false };
27589
+ }
27590
+ function evaluateStaticBinaryExpression(node, propName, propValue, ctx) {
27591
+ const left = evaluateStaticExpression(node.left, propName, propValue, ctx);
27592
+ const right = evaluateStaticExpression(node.right, propName, propValue, ctx);
27593
+ if (!left.supported || !right.supported) return { supported: false };
27594
+ switch (node.operator) {
27595
+ case "===": return {
27596
+ supported: true,
27597
+ value: left.value === right.value
27598
+ };
27599
+ case "!==": return {
27600
+ supported: true,
27601
+ value: left.value !== right.value
27602
+ };
27603
+ case "+": return typeof left.value === "number" && typeof right.value === "number" ? {
27604
+ supported: true,
27605
+ value: left.value + right.value
27606
+ } : {
27607
+ supported: true,
27608
+ value: `${String(left.value)}${String(right.value)}`
27609
+ };
27610
+ default: return { supported: false };
27611
+ }
27612
+ }
27613
+ function evaluateStaticTemplateLiteral(node, propName, propValue, ctx) {
27614
+ let value = "";
27615
+ for (let i = 0; i < node.quasis.length; i++) {
27616
+ value += node.quasis[i]?.value?.cooked ?? node.quasis[i]?.value?.raw ?? "";
27617
+ if (i < node.expressions.length) {
27618
+ const expressionValue = evaluateStaticExpression(node.expressions[i], propName, propValue, ctx);
27619
+ if (!expressionValue.supported) return { supported: false };
27620
+ value += String(expressionValue.value);
27621
+ }
27622
+ }
27623
+ return {
27624
+ supported: true,
27625
+ value
27626
+ };
27627
+ }
27628
+ function isStaticEvalValue(value) {
27629
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null || value === void 0;
27630
+ }
27631
+ //#endregion
25636
27632
  //#region src/internal/lower-rules/css-helper-conditional.ts
25637
27633
  function createCssHelperConditionalHandler(ctx) {
25638
- 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;
27634
+ 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;
25639
27635
  const avoidNames = new Set(importMap.keys());
27636
+ const cssHelperTemplateOptions = { rejectStrippedSpecificity: decl.base.kind === "component" };
25640
27637
  /**
25641
27638
  * Resolve the TS type node for a prop used in a style function parameter.
25642
27639
  * Uses the component's type annotation to infer the correct type (e.g. `number | string`).
@@ -25883,10 +27880,11 @@ function createCssHelperConditionalHandler(ctx) {
25883
27880
  return entries;
25884
27881
  };
25885
27882
  const wrapValueWithResolvedPseudos = (prop, value, pseudoEntries) => {
25886
- const properties = [j.property("init", j.identifier("default"), styleObj[prop] !== void 0 ? styleValueToExpression(j, styleObj[prop]) : j.literal(null))];
27883
+ const defaultExpr = styleObj[prop] !== void 0 ? styleValueToExpression(j, styleObj[prop]) : j.literal(null);
27884
+ const properties = [j.property("init", j.identifier("default"), cloneAstNode(defaultExpr))];
25887
27885
  for (const entry of pseudoEntries) {
25888
27886
  let entryValue = value;
25889
- if (entry.conditionExpr) entryValue = j.objectExpression([j.property("init", j.identifier("default"), j.literal(null)), (() => {
27887
+ if (entry.conditionExpr) entryValue = j.objectExpression([j.property("init", j.identifier("default"), cloneAstNode(defaultExpr)), (() => {
25890
27888
  const p = j.property("init", entry.conditionExpr, value);
25891
27889
  p.computed = true;
25892
27890
  return p;
@@ -26006,7 +28004,7 @@ function createCssHelperConditionalHandler(ctx) {
26006
28004
  if (!testInfo) return false;
26007
28005
  if (isCssHelperTaggedTemplate(body.right)) {
26008
28006
  const cssNode = body.right;
26009
- const resolved = resolveCssHelperTemplate(cssNode.quasi, paramName, decl.loc);
28007
+ const resolved = resolveCssHelperTemplate(cssNode.quasi, paramName, decl.loc, cssHelperTemplateOptions);
26010
28008
  if (!resolved) {
26011
28009
  markBail();
26012
28010
  return true;
@@ -26171,6 +28169,52 @@ function createCssHelperConditionalHandler(ctx) {
26171
28169
  }
26172
28170
  if (entries.length > 0) decl.needsWrapperComponent = true;
26173
28171
  };
28172
+ const tryApplyFiniteUnionStaticMap = (args) => {
28173
+ const unionValues = extractUnionLiteralValues(findJsxPropTsType(args.propName));
28174
+ if (!unionValues || unionValues.length < 2 || unionValues.length > 20) return false;
28175
+ const buckets = [];
28176
+ for (const propValue of unionValues) {
28177
+ const testValue = evaluateObservedDynamicExpression({
28178
+ j,
28179
+ root,
28180
+ expression: args.test,
28181
+ propName: args.propName,
28182
+ propValue,
28183
+ paramName: args.paramName
28184
+ });
28185
+ if (typeof testValue !== "boolean") return false;
28186
+ if (!testValue) continue;
28187
+ const style = {};
28188
+ for (const [stylexProp, valueExpr] of args.map) {
28189
+ const cssValue = evaluateObservedDynamicExpression({
28190
+ j,
28191
+ root,
28192
+ expression: valueExpr,
28193
+ propName: args.propName,
28194
+ propValue,
28195
+ paramName: args.paramName
28196
+ });
28197
+ if (typeof cssValue !== "string" && typeof cssValue !== "number") return false;
28198
+ style[stylexProp] = cssValue;
28199
+ }
28200
+ if (Object.keys(style).length > 0) buckets.push({
28201
+ propValue,
28202
+ style
28203
+ });
28204
+ }
28205
+ if (buckets.length === 0) return false;
28206
+ for (const { propValue, style } of buckets) {
28207
+ const propValueExpr = typeof propValue === "number" ? String(propValue) : JSON.stringify(propValue);
28208
+ applyVariant({
28209
+ when: `${args.propName} === ${propValueExpr}`,
28210
+ propName: args.propName
28211
+ }, style);
28212
+ }
28213
+ decl.variantLookupCastProps ??= /* @__PURE__ */ new Set();
28214
+ decl.variantLookupCastProps.add(args.propName);
28215
+ ensureShouldForwardPropDrop(decl, args.propName);
28216
+ return true;
28217
+ };
26174
28218
  if (body?.type === "TemplateLiteral") {
26175
28219
  const resolved = resolveTemplateLiteralBranch(tplCtx, {
26176
28220
  node: body,
@@ -26434,6 +28478,15 @@ function createCssHelperConditionalHandler(ctx) {
26434
28478
  collectPropsFromExpressions([...consMap.values(), ...altMap.values()], propsUsed);
26435
28479
  const valuePropParams = Array.from(propsUsed);
26436
28480
  if (consMap.size === 0 && altMap.size === 0) return true;
28481
+ if (valuePropParams.length === 1 && consMap.size > 0 && altMap.size === 0 && tryApplyFiniteUnionStaticMap({
28482
+ map: consMap,
28483
+ test: conditional.test,
28484
+ propName: valuePropParams[0],
28485
+ paramName
28486
+ })) {
28487
+ decl.needsWrapperComponent = true;
28488
+ return true;
28489
+ }
26437
28490
  const useSingleParam = valuePropParams.length === 1;
26438
28491
  const singlePropName = useSingleParam ? valuePropParams[0] : "";
26439
28492
  const singleParamName = useSingleParam ? singlePropName.startsWith("$") ? singlePropName.slice(1) : singlePropName : "";
@@ -26494,7 +28547,7 @@ function createCssHelperConditionalHandler(ctx) {
26494
28547
  if (!(consIsCss || altIsCss || consIsTpl || altIsTpl || consIsCall || altIsCall || consIsStr || altIsStr)) return false;
26495
28548
  const resolveCssBranch = (node) => {
26496
28549
  if (!isCssHelperTaggedTemplate(node)) return null;
26497
- return resolveCssHelperTemplate(node.quasi, paramName, decl.loc);
28550
+ return resolveCssHelperTemplate(node.quasi, paramName, decl.loc, cssHelperTemplateOptions);
26498
28551
  };
26499
28552
  const applyConditionalVariants = applyConditionalVariantsInline;
26500
28553
  const resolveTplBranch = (node) => resolveTemplateLiteralBranch(tplCtx, {
@@ -26930,7 +28983,7 @@ function buildFallbackPropSuffix(consMap, altMap) {
26930
28983
  //#endregion
26931
28984
  //#region src/internal/lower-rules/import-resolution.ts
26932
28985
  const buildSafeIndexedParamName = (preferred, containerExpr) => {
26933
- if (!isValidIdentifierName$1(preferred)) return "propValue";
28986
+ if (!isValidIdentifierName(preferred)) return "propValue";
26934
28987
  if (containerExpr?.type === "Identifier" && containerExpr.name === preferred) return `${preferred}Value`;
26935
28988
  return preferred;
26936
28989
  };
@@ -26978,7 +29031,7 @@ const createImportResolver = (args) => {
26978
29031
  const getNearestFunctionNode = (path) => {
26979
29032
  let cur = path;
26980
29033
  while (cur) {
26981
- if (isFunctionNode(cur.node)) return cur.node;
29034
+ if (isFunctionNode$1(cur.node)) return cur.node;
26982
29035
  cur = cur.parentPath ?? null;
26983
29036
  }
26984
29037
  return null;
@@ -27049,7 +29102,7 @@ const createImportResolver = (args) => {
27049
29102
  let cur = path;
27050
29103
  while (cur) {
27051
29104
  const node = cur.node;
27052
- if (isFunctionNode(node) && functionDeclaresName(node, name)) {
29105
+ if (isFunctionNode$1(node) && functionDeclaresName(node, name)) {
27053
29106
  shadowedIdentCache.set(identNode, true);
27054
29107
  return true;
27055
29108
  }
@@ -27258,7 +29311,7 @@ const createValuePatternHandlers = (ctx) => {
27258
29311
  const consTheme = resolveThemeAst(body.consequent);
27259
29312
  const altTheme = resolveThemeAst(body.alternate);
27260
29313
  const buildPropAccess = (prop) => {
27261
- return isValidIdentifierName$1(prop) ? j.memberExpression(j.identifier("props"), j.identifier(prop)) : j.memberExpression(j.identifier("props"), j.literal(prop), true);
29314
+ return isValidIdentifierName(prop) ? j.memberExpression(j.identifier("props"), j.identifier(prop)) : j.memberExpression(j.identifier("props"), j.literal(prop), true);
27262
29315
  };
27263
29316
  let nullishPropName = null;
27264
29317
  let baseTheme = null;
@@ -27294,7 +29347,7 @@ const createValuePatternHandlers = (ctx) => {
27294
29347
  styleFnDecls.set(fnKey, j.arrowFunctionExpression([param], bodyExpr));
27295
29348
  }
27296
29349
  if (!styleFnFromProps.some((p) => p.fnKey === fnKey)) {
27297
- const baseArg = isValidIdentifierName$1(nullishPropName) ? j.identifier(nullishPropName) : buildPropAccess(nullishPropName);
29350
+ const baseArg = isValidIdentifierName(nullishPropName) ? j.identifier(nullishPropName) : buildPropAccess(nullishPropName);
27298
29351
  const callArg = j.logicalExpression("??", baseArg, fallbackTheme);
27299
29352
  styleFnFromProps.push({
27300
29353
  fnKey,
@@ -27757,7 +29810,7 @@ function createDeclProcessingState(state, decl) {
27757
29810
  if (hasUnsupportedAtRule(rule.atRuleStack)) {
27758
29811
  warnings.push({
27759
29812
  severity: "warning",
27760
- type: "CSS block contains unsupported at-rule (only @media and @container are supported; @supports, etc. require manual handling)",
29813
+ type: "CSS block contains unsupported at-rule (only @media, @container, and @supports are supported; mixed nested at-rules require manual handling)",
27761
29814
  loc: decl.loc
27762
29815
  });
27763
29816
  return null;
@@ -27846,6 +29899,7 @@ function createDeclProcessingState(state, decl) {
27846
29899
  tryHandleCssHelperConditionalBlock: createCssHelperConditionalHandler({
27847
29900
  ...sharedFromState,
27848
29901
  importMap,
29902
+ root,
27849
29903
  decl,
27850
29904
  componentInfo,
27851
29905
  handlerContext,
@@ -28088,7 +30142,7 @@ function finalizeDeclProcessing(ctx) {
28088
30142
  if (!v || typeof v !== "object" || Array.isArray(v) || isAstNode(v)) return false;
28089
30143
  const keys = Object.keys(v);
28090
30144
  if (keys.length === 0) return false;
28091
- return keys.includes("default") || keys.some(isStyleConditionKey);
30145
+ return keys.includes("default") || keys.some(isStyleConditionKey$1);
28092
30146
  };
28093
30147
  if (!(() => {
28094
30148
  const disabledBucket = variantBuckets.get("disabled");
@@ -28150,6 +30204,7 @@ function finalizeDeclProcessing(ctx) {
28150
30204
  const observedFallbackFnKey = observedVariantFallbackFns.get(dim.propName);
28151
30205
  if (observedFallbackFnKey) dim.fallbackFnKey = observedFallbackFnKey;
28152
30206
  if (!observedFallbackFnKey && hasFiniteNumericVariantKey(dim)) dim.propTypeFromKeyof = true;
30207
+ if (decl.variantLookupCastProps?.has(dim.propName)) dim.forceKeyofLookupCast = true;
28153
30208
  }
28154
30209
  decl.variantDimensions = mergeVariantDimensions(decl.variantDimensions, dimensions);
28155
30210
  decl.needsWrapperComponent = true;
@@ -28738,7 +30793,7 @@ function expressionContainsStyleConditionKey(expr) {
28738
30793
  return;
28739
30794
  }
28740
30795
  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;
28741
- if (key && isStyleConditionKey(key)) {
30796
+ if (key && isStyleConditionKey$1(key)) {
28742
30797
  found = true;
28743
30798
  return;
28744
30799
  }
@@ -29100,7 +31155,7 @@ function liftFlatVariantsToPseudoMaps(variantBuckets) {
29100
31155
  const compoundValue = compoundBucket[cssProp];
29101
31156
  if (!isMediaOrPseudoMap(compoundValue)) continue;
29102
31157
  const liftedMap = { default: flatValue };
29103
- for (const condKey of Object.keys(compoundValue)) if (condKey !== "default" && isStyleConditionKey(condKey)) liftedMap[condKey] = flatValue;
31158
+ for (const condKey of Object.keys(compoundValue)) if (condKey !== "default" && isStyleConditionKey$1(condKey)) liftedMap[condKey] = flatValue;
29104
31159
  simpleBucket[cssProp] = liftedMap;
29105
31160
  compoundValue.default = flatValue;
29106
31161
  break;
@@ -30116,26 +32171,23 @@ function tryHandleInterpolatedBorder(ctx, args) {
30116
32171
  if (!hasStaticWidthOrStyle) {
30117
32172
  const parsedTpl = parseTemplateLiteralBorderShorthand(resolved.exprAst);
30118
32173
  if (parsedTpl) {
30119
- if (selector.trim() !== "&" || (atRuleStack ?? []).length > 0) {
30120
- if (parsedTpl.width) applyResolvedPropValue(widthProp, parsedTpl.width);
30121
- if (parsedTpl.style) applyResolvedPropValue(styleProp, parsedTpl.style);
30122
- applyResolvedPropValue(colorProp, parsedTpl.colorExpr);
30123
- return true;
30124
- }
30125
- const fullProp = direction ? `border${direction}` : "border";
30126
- const extraKey = styleKeyWithSuffix(decl.styleKey, fullProp);
30127
- const bucket = extraStyleObjects.get(extraKey) ?? {};
30128
- if (parsedTpl.width) bucket[widthProp] = parsedTpl.width;
30129
- if (parsedTpl.style) bucket[styleProp] = parsedTpl.style;
30130
- bucket[colorProp] = parsedTpl.colorExpr;
30131
- extraStyleObjects.set(extraKey, bucket);
30132
- decl.extraStylexPropsArgs ??= [];
30133
- const afterVariants = Object.keys(variantStyleKeys).length > 0;
30134
- decl.extraStylexPropsArgs.push({
30135
- expr: j.memberExpression(j.identifier("styles"), j.identifier(extraKey)),
30136
- ...afterVariants ? { afterVariants } : {}
30137
- });
30138
- decl.needsWrapperComponent = true;
32174
+ const expandedBorderEntries = [];
32175
+ if (parsedTpl.width) expandedBorderEntries.push([widthProp, parsedTpl.width]);
32176
+ if (parsedTpl.style) expandedBorderEntries.push([styleProp, parsedTpl.style]);
32177
+ expandedBorderEntries.push([colorProp, parsedTpl.colorExpr]);
32178
+ if (selector.trim() === "&" && (atRuleStack ?? []).length === 0 && hasConflictingEarlierVariant(Array.from(variantBuckets.values()), expandedBorderEntries)) {
32179
+ const fullProp = direction ? `border${direction}` : "border";
32180
+ const extraKey = styleKeyWithSuffix(decl.styleKey, fullProp);
32181
+ const bucket = extraStyleObjects.get(extraKey) ?? {};
32182
+ for (const [entryProp, entryValue] of expandedBorderEntries) bucket[entryProp] = entryValue;
32183
+ extraStyleObjects.set(extraKey, bucket);
32184
+ decl.extraStylexPropsArgs ??= [];
32185
+ decl.extraStylexPropsArgs.push({
32186
+ expr: j.memberExpression(j.identifier("styles"), j.identifier(extraKey)),
32187
+ afterVariants: true
32188
+ });
32189
+ decl.needsWrapperComponent = true;
32190
+ } else for (const [entryProp, entryValue] of expandedBorderEntries) applyResolvedPropValue(entryProp, entryValue);
30139
32191
  bumpResolverImportToEnd((spec) => {
30140
32192
  const from = spec?.from;
30141
32193
  const names = spec?.names;
@@ -30219,6 +32271,25 @@ function classifyBorderSlotRole(ast) {
30219
32271
  if ((node.type === "StringLiteral" || node.type === "Literal") && typeof node.value === "string") return looksLikeLength(node.value) ? "width" : "color";
30220
32272
  return null;
30221
32273
  }
32274
+ function hasConflictingEarlierVariant(variantBuckets, borderEntries) {
32275
+ const borderProps = borderEntries.map(([prop]) => prop);
32276
+ return variantBuckets.some((bucket) => Object.keys(bucket).some((variantProp) => borderProps.some((borderProp) => borderLonghandsConflict(variantProp, borderProp))));
32277
+ }
32278
+ function borderLonghandsConflict(left, right) {
32279
+ if (left === right) return true;
32280
+ const leftParts = parseBorderLonghand(left);
32281
+ const rightParts = parseBorderLonghand(right);
32282
+ if (!leftParts || !rightParts || leftParts.aspect !== rightParts.aspect) return false;
32283
+ return leftParts.side === null || rightParts.side === null || leftParts.side === rightParts.side;
32284
+ }
32285
+ function parseBorderLonghand(prop) {
32286
+ const match = prop.match(/^border(?:(Top|Right|Bottom|Left))?(Width|Style|Color)$/);
32287
+ if (!match) return null;
32288
+ return {
32289
+ side: match[1] ?? null,
32290
+ aspect: match[2]
32291
+ };
32292
+ }
30222
32293
  //#endregion
30223
32294
  //#region src/internal/lower-rules/interpolated-variant-resolvers.ts
30224
32295
  function handleSplitVariantsResolvedValue(ctx) {
@@ -30766,14 +32837,14 @@ function handleInlineStyleValueFromProps(ctx) {
30766
32837
  const valueExpr = prefix || suffix ? buildTemplateWithStaticParts(j, baseExpr, prefix, suffix) : baseExpr;
30767
32838
  const outs = cssDeclarationToStylexDeclarations(d);
30768
32839
  if (outs.every((out) => out.prop && !isStylexShorthandCamelCase(out.prop))) {
30769
- const baseKeyAvailable = outs.length === 1 && Object.keys(styleObj).length === 0 && !styleFnDecls.has(decl.styleKey);
32840
+ const baseKeyAvailable = outs.length === 1 && Object.keys(styleObj).length === 0 && !declarationHasFollowingStaticBaseStyles(decl, d) && !styleFnDecls.has(decl.styleKey);
30770
32841
  for (const out of outs) {
30771
32842
  if (!out.prop) continue;
30772
32843
  const fnKey = baseKeyAvailable ? decl.styleKey : styleKeyWithSuffix(decl.styleKey, out.prop);
30773
32844
  if (!styleFnDecls.has(fnKey)) {
30774
32845
  const paramName = cssPropertyToIdentifier(out.prop, ctx.avoidNames);
30775
32846
  const param = j.identifier(paramName);
30776
- if (/\.(ts|tsx)$/.test(filePath)) param.typeAnnotation = j.tsTypeAnnotation(j.tsUnionType([j.tsStringKeyword(), j.tsUndefinedKeyword()]));
32847
+ if (/\.(ts|tsx)$/.test(filePath)) param.typeAnnotation = j.tsTypeAnnotation(inferStyleFnParamType(j, out.prop, valueExpr));
30777
32848
  const propKey = makeCssPropKey(j, out.prop);
30778
32849
  const p = j.property("init", propKey, j.identifier(paramName));
30779
32850
  p.shorthand = propKey.type === "Identifier" && paramName === out.prop;
@@ -30842,6 +32913,54 @@ function handleInlineStyleValueFromProps(ctx) {
30842
32913
  function hasSimpleIdentifierParam(expr) {
30843
32914
  return expr.params?.length === 1 && expr.params[0]?.type === "Identifier";
30844
32915
  }
32916
+ function declarationHasFollowingStaticBaseStyles(decl, current) {
32917
+ for (const rule of decl.rules ?? []) {
32918
+ const index = rule.declarations.indexOf(current);
32919
+ if (index < 0) continue;
32920
+ return rule.declarations.slice(index + 1).some((next) => next.value.kind === "static");
32921
+ }
32922
+ return false;
32923
+ }
32924
+ function inferStyleFnParamType(j, stylexProp, callArg) {
32925
+ if (callArg.type === "TemplateLiteral" && expressionHasNullishFallback(callArg)) return j.tsStringKeyword();
32926
+ if (expressionHasNullishFallback(callArg) && NUMERIC_STYLEX_PROPS.has(stylexProp)) {
32927
+ if (getNullishFallbackType(callArg) !== "number") return j.tsUnionType([j.tsNumberKeyword(), j.tsStringKeyword()]);
32928
+ return j.tsNumberKeyword();
32929
+ }
32930
+ return j.tsUnionType([j.tsStringKeyword(), j.tsUndefinedKeyword()]);
32931
+ }
32932
+ const NUMERIC_STYLEX_PROPS = new Set([
32933
+ "zIndex",
32934
+ "opacity",
32935
+ "flexGrow",
32936
+ "flexShrink",
32937
+ "order"
32938
+ ]);
32939
+ function getNullishFallbackType(expr) {
32940
+ if (!expr || typeof expr !== "object") return null;
32941
+ const node = expr;
32942
+ if (node.type === "LogicalExpression" && node.operator === "??") return getExpressionPrimitiveType(node.right);
32943
+ if (node.type === "TemplateLiteral") for (const templateExpr of node.expressions ?? []) {
32944
+ const fallbackType = getNullishFallbackType(templateExpr);
32945
+ if (fallbackType) return fallbackType;
32946
+ }
32947
+ return null;
32948
+ }
32949
+ function getExpressionPrimitiveType(expr) {
32950
+ if (!expr || typeof expr !== "object") return "unknown";
32951
+ const node = expr;
32952
+ if (node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number") return "number";
32953
+ if (node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string") return "string";
32954
+ if (node.type === "TemplateLiteral") return "string";
32955
+ return "unknown";
32956
+ }
32957
+ function expressionHasNullishFallback(expr) {
32958
+ if (!expr || typeof expr !== "object") return false;
32959
+ const node = expr;
32960
+ if (node.type === "LogicalExpression" && node.operator === "??") return true;
32961
+ if (node.type === "TemplateLiteral") return (node.expressions ?? []).some(expressionHasNullishFallback);
32962
+ return false;
32963
+ }
30845
32964
  /**
30846
32965
  * Emit one `${key}FromProps` style function entry per longhand expansion of
30847
32966
  * `d`, keyed by the StyleX prop name and wrapped in pseudo/media buckets.
@@ -30894,6 +33013,10 @@ function handleInterpolatedDeclaration(args) {
30894
33013
  const avoidNames = new Set(importMap.keys());
30895
33014
  if (state.bail) return;
30896
33015
  if (d.value.kind !== "interpolated") return;
33016
+ if (d.property && isUnsupportedStylexProperty(d.property)) {
33017
+ state.bailUnsupported(decl, `Unsupported CSS property "${d.property}" cannot be emitted in StyleX`);
33018
+ return;
33019
+ }
30897
33020
  let bail = false;
30898
33021
  const getRootIdentifierInfo = extractRootAndPath;
30899
33022
  const bailUnsupportedLocal = (declArg, type) => {
@@ -30918,7 +33041,7 @@ function handleInterpolatedDeclaration(args) {
30918
33041
  if (!usage) return null;
30919
33042
  const propUsage = usage.props[jsxProp];
30920
33043
  if (!propUsage || propUsage.values.length < 2) return null;
30921
- const values = propUsage.values.filter((value) => typeof value === "number");
33044
+ const values = propUsage.values.filter((value) => typeof value === "string" || typeof value === "number");
30922
33045
  if (values.length !== propUsage.values.length) return null;
30923
33046
  return values;
30924
33047
  };
@@ -31037,7 +33160,7 @@ function handleInterpolatedDeclaration(args) {
31037
33160
  const unionValues = extractUnionLiteralValues(findJsxPropTsTypeForVariantExtraction(jsxProp));
31038
33161
  const observedValues = unionValues ? null : getObservedStaticVariantValues(jsxProp);
31039
33162
  const hasStaticText = staticParts.prefix !== "" || staticParts.suffix !== "";
31040
- if (observedValues && getNumericCssEmissionMode(stylexProp) === "cssText" && !hasStaticText) {
33163
+ if (observedValues && observedValues.some((value) => typeof value === "number") && getNumericCssEmissionMode(stylexProp) === "cssText" && !hasStaticText) {
31041
33164
  observedNumericCssTextProps.add(jsxProp);
31042
33165
  return false;
31043
33166
  }
@@ -31050,15 +33173,110 @@ function handleInterpolatedDeclaration(args) {
31050
33173
  propName: jsxProp
31051
33174
  }, { [stylexProp]: emitStaticObservedValue(value, stylexProp, observedValues !== null, staticParts) });
31052
33175
  }
31053
- if (observedValues) observedVariantFallbackFns.set(jsxProp, ensureObservedVariantFallbackFn(jsxProp, stylexProp, staticParts));
31054
- if (jsxProp.startsWith("$")) ensureShouldForwardPropDrop(decl, jsxProp);
33176
+ if (observedValues) {
33177
+ const fallbackFnKey = ensureObservedVariantFallbackFn(jsxProp, stylexProp, (param) => buildRuntimeObservedValueExpr(j, stylexProp, param, staticParts));
33178
+ if (fallbackFnKey) {
33179
+ observedVariantFallbackFns.set(jsxProp, fallbackFnKey);
33180
+ markStyleValueVariantProp(jsxProp);
33181
+ }
33182
+ }
33183
+ ensureObservedVariantPropDrop(jsxProp);
33184
+ return true;
33185
+ };
33186
+ const tryEmitTransformedObservedVariantBuckets = (jsxProp, stylexProp, valueTransform) => {
33187
+ if (!valueTransform || valueTransform.kind !== "call" || valueTransform.resolvedExpr || valueTransform.resolvedUsage || media || pseudos?.length) return false;
33188
+ const observedValues = getObservedStaticVariantValues(jsxProp);
33189
+ if (!observedValues || observedValues.length < 2 || observedValues.length > 20) return false;
33190
+ const transformedValues = [];
33191
+ for (const propValue of observedValues) {
33192
+ const cssValue = evaluateLocalCallValueTransform({
33193
+ j,
33194
+ root: state.root,
33195
+ calleeName: valueTransform.calleeIdent,
33196
+ argValue: propValue
33197
+ });
33198
+ if (typeof cssValue !== "string" && typeof cssValue !== "number") return false;
33199
+ transformedValues.push({
33200
+ propValue,
33201
+ cssValue
33202
+ });
33203
+ }
33204
+ for (const { propValue, cssValue } of transformedValues) applyVariant({
33205
+ when: `${jsxProp} === ${typeof propValue === "number" ? String(propValue) : JSON.stringify(propValue)}`,
33206
+ propName: jsxProp
33207
+ }, { [stylexProp]: cssValue });
33208
+ const fallbackFnKey = ensureObservedVariantFallbackFn(jsxProp, stylexProp, (param) => j.callExpression(j.identifier(valueTransform.calleeIdent), [param]));
33209
+ if (!fallbackFnKey) return false;
33210
+ observedVariantFallbackFns.set(jsxProp, fallbackFnKey);
33211
+ markStyleValueVariantProp(jsxProp);
33212
+ ensureObservedVariantPropDrop(jsxProp);
31055
33213
  return true;
31056
33214
  };
31057
- const ensureObservedVariantFallbackFn = (jsxProp, stylexProp, staticParts) => {
33215
+ const tryEmitObservedExpressionVariantBuckets = (jsxProp, stylexProp, expression, paramName, conditionWhen, conditionProp, prefix, suffix) => {
33216
+ if (media || pseudos?.length) return false;
33217
+ const observedValues = getObservedStaticVariantValues(jsxProp);
33218
+ if (!observedValues || observedValues.length < 2 || observedValues.length > 20) return false;
33219
+ const transformedValues = [];
33220
+ for (const propValue of observedValues) {
33221
+ const evaluatedValue = evaluateObservedDynamicExpression({
33222
+ j,
33223
+ root: state.root,
33224
+ expression,
33225
+ propName: jsxProp,
33226
+ propValue,
33227
+ paramName
33228
+ });
33229
+ if (typeof evaluatedValue !== "string" && typeof evaluatedValue !== "number") return false;
33230
+ const cssValue = prefix || suffix ? `${prefix}${String(evaluatedValue)}${suffix}` : evaluatedValue;
33231
+ transformedValues.push({
33232
+ propValue,
33233
+ cssValue
33234
+ });
33235
+ }
33236
+ const ensuredFallbackFnKey = ensureObservedVariantFallbackFn(jsxProp, stylexProp, (param) => buildObservedExpressionFallbackValueExpr({
33237
+ j,
33238
+ expression,
33239
+ jsxProp,
33240
+ paramName,
33241
+ param,
33242
+ prefix,
33243
+ suffix
33244
+ }), observedExpressionFallbackFnKey(jsxProp, conditionWhen));
33245
+ if (!ensuredFallbackFnKey) return false;
33246
+ if (!styleFnFromProps.some((entry) => entry.fnKey === ensuredFallbackFnKey && entry.jsxProp === jsxProp && entry.conditionWhen === conditionWhen)) styleFnFromProps.push({
33247
+ fnKey: ensuredFallbackFnKey,
33248
+ jsxProp,
33249
+ conditionWhen
33250
+ });
33251
+ for (const { propValue, cssValue } of transformedValues) applyVariant({
33252
+ when: `${conditionWhen} && ${jsxProp} === ${typeof propValue === "number" ? String(propValue) : JSON.stringify(propValue)}`,
33253
+ propName: jsxProp,
33254
+ allPropNames: [conditionProp, jsxProp]
33255
+ }, { [stylexProp]: cssValue });
33256
+ markStyleValueVariantProp(jsxProp);
33257
+ ensureObservedVariantPropDrop(jsxProp);
33258
+ return true;
33259
+ };
33260
+ const observedExpressionFallbackFnKey = (jsxProp, conditionWhen) => {
33261
+ const normalizedJsxProp = jsxProp.startsWith("$") ? jsxProp.slice(1) : jsxProp;
33262
+ const baseFnKey = styleKeyWithSuffix(decl.styleKey, normalizedJsxProp);
33263
+ const existingForCondition = styleFnFromProps.find((entry) => entry.jsxProp === jsxProp && entry.conditionWhen === conditionWhen);
33264
+ if (existingForCondition) return existingForCondition.fnKey;
33265
+ return styleFnFromProps.some((entry) => entry.fnKey === baseFnKey && entry.jsxProp === jsxProp && entry.conditionWhen !== conditionWhen) ? styleKeyWithSuffix(baseFnKey, conditionWhen) : baseFnKey;
33266
+ };
33267
+ const ensureObservedVariantPropDrop = (jsxProp) => {
33268
+ if (jsxProp.startsWith("$") || decl.base.kind !== "component") ensureShouldForwardPropDrop(decl, jsxProp);
33269
+ };
33270
+ const markStyleValueVariantProp = (jsxProp) => {
33271
+ decl.styleValueVariantProps ??= /* @__PURE__ */ new Set();
33272
+ decl.styleValueVariantProps.add(jsxProp);
33273
+ };
33274
+ const ensureObservedVariantFallbackFn = (jsxProp, stylexProp, buildValueExpr, fnKeyOverride) => {
31058
33275
  const normalizedJsxProp = jsxProp.startsWith("$") ? jsxProp.slice(1) : jsxProp;
31059
- const fnKey = styleKeyWithSuffix(decl.styleKey, normalizedJsxProp);
33276
+ const fnKey = fnKeyOverride ?? styleKeyWithSuffix(decl.styleKey, normalizedJsxProp);
31060
33277
  const paramName = cssPropertyToIdentifier(normalizedJsxProp || stylexProp, avoidNames);
31061
- const valueExpr = buildRuntimeObservedValueExpr(j, stylexProp, j.identifier(paramName), staticParts);
33278
+ const valueExpr = buildValueExpr(j.identifier(paramName), paramName);
33279
+ if (!valueExpr) return null;
31062
33280
  const property = j.property("init", makeCssPropKey(j, stylexProp), valueExpr);
31063
33281
  const existing = styleFnDecls.get(fnKey);
31064
33282
  if (existing?.type === "ArrowFunctionExpression" && existing.body?.type === "ObjectExpression") {
@@ -32205,15 +34423,27 @@ function handleInterpolatedDeclaration(args) {
32205
34423
  continue;
32206
34424
  }
32207
34425
  if (res && res.type === "splitConditionalWithDynamicBranch") if (!d.property) {} else {
32208
- const { conditionProp, staticValue, dynamicBranchExpr, dynamicProps, isStaticWhenFalse } = res;
34426
+ const { conditionProp, staticValue, dynamicBranchExpr, paramName, dynamicProps, isStaticWhenFalse } = res;
32209
34427
  const { prefix, suffix } = extractStaticPartsForDecl(d);
32210
34428
  const cssValueStr = `${prefix}${staticValue}${suffix}`;
32211
34429
  for (const out of cssDeclarationToStylexDeclarations(d)) styleObj[out.prop] = cssValueStr;
34430
+ const conditionWhen = isStaticWhenFalse ? conditionProp : `!${conditionProp}`;
32212
34431
  const clonedDynamic = cloneAstNode(dynamicBranchExpr);
32213
34432
  const dynamicValueExpr = prefix || suffix ? buildTemplateWithStaticParts(j, clonedDynamic, prefix, suffix) : clonedDynamic;
34433
+ const existingBucket = variantBuckets.get(conditionProp);
34434
+ if (!existingBucket && dynamicProps.length === 1) {
34435
+ const out = cssDeclarationToStylexDeclarations(d)[0];
34436
+ const dynamicProp = dynamicProps[0];
34437
+ if (out && dynamicProp && tryEmitObservedExpressionVariantBuckets(dynamicProp, out.prop, clonedDynamic, paramName, conditionWhen, conditionProp, prefix, suffix)) {
34438
+ ensureShouldForwardPropDrop(decl, conditionProp);
34439
+ decl.observedExpressionConditionDropProps ??= /* @__PURE__ */ new Set();
34440
+ decl.observedExpressionConditionDropProps.add(conditionProp);
34441
+ decl.needsWrapperComponent = true;
34442
+ continue;
34443
+ }
34444
+ }
32214
34445
  for (const propName of dynamicProps) ensureShouldForwardPropDrop(decl, propName);
32215
34446
  ensureShouldForwardPropDrop(decl, conditionProp);
32216
- const conditionWhen = isStaticWhenFalse ? conditionProp : `!${conditionProp}`;
32217
34447
  const scalarDynamic = shouldUseScalarDynamicArgs(d.property, d.valueRaw) && dynamicProps.length > 0 ? scalarizePropsObjectDynamicValue({
32218
34448
  j,
32219
34449
  valueExpr: dynamicValueExpr,
@@ -32228,7 +34458,6 @@ function handleInterpolatedDeclaration(args) {
32228
34458
  prop.shorthand = true;
32229
34459
  return prop;
32230
34460
  }));
32231
- const existingBucket = variantBuckets.get(conditionProp);
32232
34461
  if (existingBucket) {
32233
34462
  const existingFnKey = variantStyleKeys[conditionProp];
32234
34463
  if (!existingFnKey) break;
@@ -32478,134 +34707,132 @@ function handleInterpolatedDeclaration(args) {
32478
34707
  }
32479
34708
  if (res && res.type === "emitStyleFunction") {
32480
34709
  const jsxProp = res.call;
34710
+ const outs = cssDeclarationToStylexDeclarations(d);
34711
+ const valueTransform = res.valueTransform;
32481
34712
  if (!res.valueTransform && !res.wrapValueInTemplateLiteral && !media && (!pseudos || pseudos.length === 0)) {
32482
- const outs = cssDeclarationToStylexDeclarations(d);
32483
34713
  if (outs.length === 1 && tryEmitIdentityVariantBuckets(jsxProp, outs[0].prop)) continue;
32484
34714
  }
32485
- {
32486
- const outs = cssDeclarationToStylexDeclarations(d);
32487
- for (let i = 0; i < outs.length; i++) {
32488
- const out = outs[i];
32489
- const fnKey = styleKeyWithSuffix(decl.styleKey, out.prop);
32490
- const valueTransform = res.valueTransform;
32491
- const resolvedCallArg = buildResolvedValueTransformCallArg({
32492
- j,
32493
- jsxProp,
32494
- valueTransform,
32495
- parseExpr,
32496
- addResolverImports
32497
- });
32498
- const outParamName = resolvedCallArg || valueTransform ? cssPropertyToIdentifier(out.prop, avoidNames) : styleFnParamNameForJsxProp(jsxProp, out.prop, avoidNames);
32499
- const scalarCallArg = valueTransform ? void 0 : scalarCallArgForParamName(j, jsxProp, outParamName, decl.transientPropRenames?.get(jsxProp));
32500
- const callArg = resolvedCallArg ?? scalarCallArg;
32501
- const hasExplicitType = !!decl.propsType;
32502
- const isOptional = ctx.isJsxPropOptional(jsxProp);
32503
- styleFnFromProps.push({
32504
- fnKey,
32505
- jsxProp,
32506
- ...callArg ? { callArg } : {},
32507
- ...hasExplicitType && !isOptional ? { condition: "always" } : {}
32508
- });
32509
- if (!styleFnDecls.has(fnKey)) {
32510
- const param = j.identifier(outParamName);
32511
- const valueId = j.identifier(outParamName);
32512
- if (jsxProp !== "__props") annotateParamFromJsxProp(param, jsxProp);
32513
- if (resolvedCallArg && /\.(ts|tsx)$/.test(filePath)) param.typeAnnotation = j.tsTypeAnnotation(j.tsStringKeyword());
32514
- if (jsxProp?.startsWith?.("$")) ensureShouldForwardPropDrop(decl, jsxProp);
32515
- const buildValueExpr = () => {
32516
- const transformed = (() => {
32517
- const vt = callArg ? void 0 : valueTransform;
32518
- if (vt?.kind === "call" && typeof vt.calleeIdent === "string") {
32519
- addResolverImports(vt.resolvedImports);
32520
- if (vt.resolvedExpr) {
32521
- const resolvedCallee = parseExpr(vt.resolvedExpr);
32522
- if (vt.resolvedUsage === "memberAccess") return j.memberExpression(resolvedCallee, valueId, true);
32523
- return j.callExpression(resolvedCallee, [valueId]);
32524
- }
32525
- return j.callExpression(j.identifier(vt.calleeIdent), [valueId]);
34715
+ if (!res.wrapValueInTemplateLiteral && outs.length === 1 && tryEmitTransformedObservedVariantBuckets(jsxProp, outs[0].prop, valueTransform)) continue;
34716
+ for (let i = 0; i < outs.length; i++) {
34717
+ const out = outs[i];
34718
+ const fnKey = styleKeyWithSuffix(decl.styleKey, out.prop);
34719
+ const resolvedCallArg = buildResolvedValueTransformCallArg({
34720
+ j,
34721
+ jsxProp,
34722
+ valueTransform,
34723
+ parseExpr,
34724
+ addResolverImports
34725
+ });
34726
+ const outParamName = resolvedCallArg || valueTransform ? cssPropertyToIdentifier(out.prop, avoidNames) : styleFnParamNameForJsxProp(jsxProp, out.prop, avoidNames);
34727
+ const scalarCallArg = valueTransform ? void 0 : scalarCallArgForParamName(j, jsxProp, outParamName, decl.transientPropRenames?.get(jsxProp));
34728
+ const callArg = resolvedCallArg ?? scalarCallArg;
34729
+ const hasExplicitType = !!decl.propsType;
34730
+ const isOptional = ctx.isJsxPropOptional(jsxProp);
34731
+ styleFnFromProps.push({
34732
+ fnKey,
34733
+ jsxProp,
34734
+ ...callArg ? { callArg } : {},
34735
+ ...hasExplicitType && !isOptional ? { condition: "always" } : {}
34736
+ });
34737
+ if (!styleFnDecls.has(fnKey)) {
34738
+ const param = j.identifier(outParamName);
34739
+ const valueId = j.identifier(outParamName);
34740
+ if (jsxProp !== "__props") annotateParamFromJsxProp(param, jsxProp);
34741
+ if (resolvedCallArg && /\.(ts|tsx)$/.test(filePath)) param.typeAnnotation = j.tsTypeAnnotation(j.tsStringKeyword());
34742
+ if (jsxProp?.startsWith?.("$")) ensureShouldForwardPropDrop(decl, jsxProp);
34743
+ const buildValueExpr = () => {
34744
+ const transformed = (() => {
34745
+ const vt = callArg ? void 0 : valueTransform;
34746
+ if (vt?.kind === "call" && typeof vt.calleeIdent === "string") {
34747
+ addResolverImports(vt.resolvedImports);
34748
+ if (vt.resolvedExpr) {
34749
+ const resolvedCallee = parseExpr(vt.resolvedExpr);
34750
+ if (vt.resolvedUsage === "memberAccess") return j.memberExpression(resolvedCallee, valueId, true);
34751
+ return j.callExpression(resolvedCallee, [valueId]);
32526
34752
  }
32527
- return valueId;
32528
- })();
32529
- const transformedValue = !!res.wrapValueInTemplateLiteral ? j.templateLiteral([j.templateElement({
34753
+ return j.callExpression(j.identifier(vt.calleeIdent), [valueId]);
34754
+ }
34755
+ return valueId;
34756
+ })();
34757
+ const transformedValue = !!res.wrapValueInTemplateLiteral ? j.templateLiteral([j.templateElement({
34758
+ raw: "",
34759
+ cooked: ""
34760
+ }, false), j.templateElement({
34761
+ raw: "",
34762
+ cooked: ""
34763
+ }, true)], [transformed]) : transformed;
34764
+ const v = d.value;
34765
+ if (!v || v.kind !== "interpolated") return transformedValue;
34766
+ const parts = v.parts ?? [];
34767
+ const slotParts = parts.filter((p) => p?.kind === "slot");
34768
+ if (slotParts.length !== 1) return transformedValue;
34769
+ if (slotParts[0].slotId !== slotId) return transformedValue;
34770
+ if (!parts.some((p) => p?.kind === "static" && p.value !== "")) {
34771
+ if (shouldPreserveNumericCssTextForProp(jsxProp, out.prop)) return j.templateLiteral([j.templateElement({
32530
34772
  raw: "",
32531
34773
  cooked: ""
32532
34774
  }, false), j.templateElement({
32533
34775
  raw: "",
32534
34776
  cooked: ""
32535
- }, true)], [transformed]) : transformed;
32536
- const v = d.value;
32537
- if (!v || v.kind !== "interpolated") return transformedValue;
32538
- const parts = v.parts ?? [];
32539
- const slotParts = parts.filter((p) => p?.kind === "slot");
32540
- if (slotParts.length !== 1) return transformedValue;
32541
- if (slotParts[0].slotId !== slotId) return transformedValue;
32542
- if (!parts.some((p) => p?.kind === "static" && p.value !== "")) {
32543
- if (shouldPreserveNumericCssTextForProp(jsxProp, out.prop)) return j.templateLiteral([j.templateElement({
32544
- raw: "",
32545
- cooked: ""
32546
- }, false), j.templateElement({
32547
- raw: "",
32548
- cooked: ""
32549
- }, true)], [transformed]);
32550
- return transformedValue;
34777
+ }, true)], [transformed]);
34778
+ return transformedValue;
34779
+ }
34780
+ const quasis = [];
34781
+ const exprs = [];
34782
+ let q = "";
34783
+ for (const part of parts) {
34784
+ if (part?.kind === "static") {
34785
+ q += String(part.value ?? "");
34786
+ continue;
32551
34787
  }
32552
- const quasis = [];
32553
- const exprs = [];
32554
- let q = "";
32555
- for (const part of parts) {
32556
- if (part?.kind === "static") {
32557
- q += String(part.value ?? "");
32558
- continue;
32559
- }
32560
- if (part?.kind === "slot") {
32561
- quasis.push(j.templateElement({
32562
- raw: q,
32563
- cooked: q
32564
- }, false));
32565
- q = "";
32566
- exprs.push(transformed);
32567
- continue;
32568
- }
34788
+ if (part?.kind === "slot") {
34789
+ quasis.push(j.templateElement({
34790
+ raw: q,
34791
+ cooked: q
34792
+ }, false));
34793
+ q = "";
34794
+ exprs.push(transformed);
34795
+ continue;
32569
34796
  }
32570
- quasis.push(j.templateElement({
32571
- raw: q,
32572
- cooked: q
32573
- }, true));
32574
- return j.templateLiteral(quasis, exprs);
32575
- };
32576
- const valueExpr = buildValueExpr();
32577
- const getPropValue = () => {
32578
- if (!media) return valueExpr;
32579
- const existingFn = styleFnDecls.get(fnKey);
32580
- let existingValue = null;
32581
- if (existingFn?.type === "ArrowFunctionExpression") {
32582
- const body = existingFn.body;
32583
- if (body?.type === "ObjectExpression") {
32584
- const prop = body.properties.find((propNode) => {
32585
- if (!propNode || typeof propNode !== "object") return false;
32586
- if (propNode.type !== "Property") return false;
32587
- const key = propNode.key;
32588
- if (!key || typeof key !== "object") return false;
32589
- const keyType = key.type;
32590
- if (keyType === "Identifier") return key.name === out.prop;
32591
- if (keyType === "Literal") return key.value === out.prop;
32592
- return false;
32593
- });
32594
- if (prop && prop.type === "Property") existingValue = prop.value;
32595
- }
34797
+ }
34798
+ quasis.push(j.templateElement({
34799
+ raw: q,
34800
+ cooked: q
34801
+ }, true));
34802
+ return j.templateLiteral(quasis, exprs);
34803
+ };
34804
+ const valueExpr = buildValueExpr();
34805
+ const getPropValue = () => {
34806
+ if (!media) return valueExpr;
34807
+ const existingFn = styleFnDecls.get(fnKey);
34808
+ let existingValue = null;
34809
+ if (existingFn?.type === "ArrowFunctionExpression") {
34810
+ const body = existingFn.body;
34811
+ if (body?.type === "ObjectExpression") {
34812
+ const prop = body.properties.find((propNode) => {
34813
+ if (!propNode || typeof propNode !== "object") return false;
34814
+ if (propNode.type !== "Property") return false;
34815
+ const key = propNode.key;
34816
+ if (!key || typeof key !== "object") return false;
34817
+ const keyType = key.type;
34818
+ if (keyType === "Identifier") return key.name === out.prop;
34819
+ if (keyType === "Literal") return key.value === out.prop;
34820
+ return false;
34821
+ });
34822
+ if (prop && prop.type === "Property") existingValue = prop.value;
32596
34823
  }
32597
- const defaultValue = existingValue ?? j.literal(null);
32598
- return j.objectExpression([j.property("init", j.identifier("default"), defaultValue), j.property("init", j.literal(media), valueExpr)]);
32599
- };
32600
- const propKey = makeCssPropKey(j, out.prop);
32601
- const p = j.property("init", propKey, getPropValue());
32602
- const paramName = outParamName;
32603
- p.shorthand = propKey.type === "Identifier" && valueExpr?.type === "Identifier" && valueExpr.name === paramName;
32604
- const body = j.objectExpression([p]);
32605
- styleFnDecls.set(fnKey, j.arrowFunctionExpression([param], body));
32606
- }
32607
- if (i === 0) {}
34824
+ }
34825
+ const defaultValue = existingValue ?? j.literal(null);
34826
+ return j.objectExpression([j.property("init", j.identifier("default"), defaultValue), j.property("init", j.literal(media), valueExpr)]);
34827
+ };
34828
+ const propKey = makeCssPropKey(j, out.prop);
34829
+ const p = j.property("init", propKey, getPropValue());
34830
+ const paramName = outParamName;
34831
+ p.shorthand = propKey.type === "Identifier" && valueExpr?.type === "Identifier" && valueExpr.name === paramName;
34832
+ const body = j.objectExpression([p]);
34833
+ styleFnDecls.set(fnKey, j.arrowFunctionExpression([param], body));
32608
34834
  }
34835
+ if (i === 0) {}
32609
34836
  }
32610
34837
  continue;
32611
34838
  }
@@ -32958,9 +35185,40 @@ function isUnchangedImportedHelperStyleCall(res, exprAst, originalExpr) {
32958
35185
  const resolveResult = res.resolveCallResult;
32959
35186
  const resolveContext = res.resolveCallContext;
32960
35187
  const typedResult = resolveResult && typeof resolveResult === "object" ? resolveResult : null;
32961
- if (!typedResult || !resolveContext || typedResult.cssText || (typedResult.imports?.length ?? 0) > 0) return false;
35188
+ if (!typedResult || !resolveContext || typedResult.cssText) return false;
32962
35189
  if (!isCallExpressionLike(exprAst) || !isCallExpressionLike(originalExpr)) return false;
32963
- return calleeKey(exprAst.callee) === calleeKey(originalExpr.callee);
35190
+ if (calleeKey(exprAst.callee) !== calleeKey(originalExpr.callee)) return false;
35191
+ return !redirectsOriginalCalleeToDifferentSource(res, resolveContext);
35192
+ }
35193
+ function redirectsOriginalCalleeToDifferentSource(res, resolveContext) {
35194
+ 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));
35195
+ return Boolean(matchingImport && !sourcesReferToSameImport(matchingImport.from, resolveContext));
35196
+ }
35197
+ function sourcesReferToSameImport(left, resolveContext) {
35198
+ const right = resolveContext.calleeSource;
35199
+ if (left.value === right.value) return true;
35200
+ return specifierMatchesAbsolutePath(left, right, resolveContext.callSiteFilePath) || specifierMatchesAbsolutePath(right, left, resolveContext.callSiteFilePath);
35201
+ }
35202
+ function specifierMatchesAbsolutePath(maybeSpecifier, maybeAbsolute, callSiteFilePath) {
35203
+ if (maybeSpecifier.kind !== "specifier" || maybeAbsolute.kind !== "absolutePath") return false;
35204
+ const specifier = maybeSpecifier.value.replace(/\\/g, "/");
35205
+ if (!isRelativeSpecifier(specifier)) return false;
35206
+ const resolvedSpecifier = resolve(dirname(callSiteFilePath), specifier).replace(/\\/g, "/");
35207
+ const absolutePath = maybeAbsolute.value.replace(/\\/g, "/");
35208
+ return importPathCandidates(resolvedSpecifier).some((candidate) => absolutePath === candidate);
35209
+ }
35210
+ function importPathCandidates(resolvedSpecifier) {
35211
+ return [
35212
+ "",
35213
+ ".ts",
35214
+ ".tsx",
35215
+ ".js",
35216
+ ".jsx",
35217
+ ".mts",
35218
+ ".mjs",
35219
+ ".cts",
35220
+ ".cjs"
35221
+ ].flatMap((extension) => [`${resolvedSpecifier}${extension}`, `${resolvedSpecifier}/index${extension}`]);
32964
35222
  }
32965
35223
  function isCallExpressionLike(node) {
32966
35224
  return !!node && typeof node === "object" && node.type === "CallExpression";
@@ -32989,6 +35247,28 @@ function buildRuntimeObservedValueExpr(j, stylexProp, valueExpr, staticParts) {
32989
35247
  cooked: staticParts.suffix
32990
35248
  }, true)], [valueExpr]);
32991
35249
  }
35250
+ function buildObservedExpressionFallbackValueExpr(args) {
35251
+ const { j, expression, jsxProp, paramName, param, prefix, suffix } = args;
35252
+ const propNames = new Set([jsxProp, jsxProp.startsWith("$") ? jsxProp.slice(1) : jsxProp]);
35253
+ let replaced = false;
35254
+ const rewritten = mapAst(cloneAstNode(expression), (node) => {
35255
+ if (isMemberExpression(node)) {
35256
+ const memberPath = extractRootAndPath(node);
35257
+ const propName = memberPath?.path[0];
35258
+ if (memberPath?.rootName === paramName && memberPath.path.length === 1 && propName && propNames.has(propName)) {
35259
+ replaced = true;
35260
+ return cloneAstNode(param);
35261
+ }
35262
+ return;
35263
+ }
35264
+ if (node.type === "Identifier" && propNames.has(node.name)) {
35265
+ replaced = true;
35266
+ return cloneAstNode(param);
35267
+ }
35268
+ });
35269
+ if (!replaced) return null;
35270
+ return prefix || suffix ? buildTemplateWithStaticParts(j, rewritten, prefix, suffix) : rewritten;
35271
+ }
32992
35272
  function isNumberLikeTsType(tsType) {
32993
35273
  if (!tsType || typeof tsType !== "object") return false;
32994
35274
  const type = tsType;
@@ -33942,6 +36222,9 @@ function resolveExpressionToStaticString(expr, state) {
33942
36222
  const direct = literalToStaticValue(expr);
33943
36223
  if (typeof direct === "string") return direct;
33944
36224
  if (!isIdentifierNode(expr)) return null;
36225
+ const scoped = resolveScopedConstStringInit(expr, state);
36226
+ if (scoped?.kind === "found") return scoped.value;
36227
+ if (scoped?.kind === "blocked") return null;
33945
36228
  if (state.isIdentifierShadowed(expr, expr.name)) return null;
33946
36229
  const fromImport = resolveImportedConstStringInit(expr.name, state);
33947
36230
  if (fromImport !== null) return fromImport;
@@ -34138,6 +36421,203 @@ function findTopLevelConstStringInit(name, state) {
34138
36421
  });
34139
36422
  return resolved;
34140
36423
  }
36424
+ function resolveScopedConstStringInit(expr, state) {
36425
+ const identPath = findIdentifierPath(expr, state);
36426
+ const exprStart = getNodeStart(expr);
36427
+ if (!identPath || exprStart === null) return null;
36428
+ const ancestorScopes = getAncestorScopeNodes(identPath);
36429
+ let best = null;
36430
+ state.root.find(state.j.VariableDeclarator).forEach((p) => {
36431
+ const declarator = p.node;
36432
+ if (declarator.id?.type !== "Identifier" || declarator.id.name !== expr.name) return;
36433
+ const start = getNodeStart(declarator);
36434
+ if (start === null || start >= exprStart) return;
36435
+ const path = p;
36436
+ const scopeNode = getDeclarationScopeNode(path, getVariableDeclarationKind(path));
36437
+ if (!scopeNode || !ancestorScopes.has(scopeNode)) return;
36438
+ if (isProgramNode(scopeNode) || hasInnerBindingBetween(identPath, scopeNode, expr.name)) return;
36439
+ const value = getVariableDeclarationKind(path) === "const" ? literalToStaticValue(declarator.init) : null;
36440
+ const candidate = {
36441
+ start,
36442
+ value: typeof value === "string" ? value : null
36443
+ };
36444
+ if (!best || candidate.start > best.start) best = candidate;
36445
+ });
36446
+ const resolved = best;
36447
+ if (!resolved) return null;
36448
+ return resolved.value === null ? { kind: "blocked" } : {
36449
+ kind: "found",
36450
+ value: resolved.value
36451
+ };
36452
+ }
36453
+ function findIdentifierPath(expr, state) {
36454
+ return state.root.find(state.j.Identifier).filter((p) => p.node === expr).paths()[0] ?? null;
36455
+ }
36456
+ function getNodeStart(node) {
36457
+ const start = node.start;
36458
+ return typeof start === "number" ? start : null;
36459
+ }
36460
+ function getAncestorScopeNodes(path) {
36461
+ const scopes = /* @__PURE__ */ new Set();
36462
+ let cur = path;
36463
+ while (cur) {
36464
+ if (isScopeNode(cur.node)) scopes.add(cur.node);
36465
+ cur = cur.parentPath ?? null;
36466
+ }
36467
+ return scopes;
36468
+ }
36469
+ function getDeclarationScopeNode(path, declarationKind) {
36470
+ const declarationParent = path.parentPath?.parentPath;
36471
+ if (declarationKind !== "var" && declarationParent && isLoopNode(declarationParent.node)) return declarationParent.node;
36472
+ let cur = path.parentPath;
36473
+ while (cur) {
36474
+ if (declarationKind === "var" && isFunctionOrProgramNode(cur.node)) return cur.node;
36475
+ if (declarationKind !== "var" && isLoopNode(cur.node)) return cur.node;
36476
+ if (declarationKind !== "var" && isScopeNode(cur.node)) return cur.node;
36477
+ cur = cur.parentPath ?? null;
36478
+ }
36479
+ return null;
36480
+ }
36481
+ function hasInnerBindingBetween(identPath, outerScopeNode, name) {
36482
+ let cur = identPath.parentPath;
36483
+ while (cur && cur.node !== outerScopeNode) {
36484
+ if (isFunctionNode(cur.node) && functionDeclaresName(cur.node, name)) return true;
36485
+ if (isCatchClauseNode(cur.node) && catchClauseDeclaresName(cur.node, name)) return true;
36486
+ if (isBlockStatementNode(cur.node) && blockDeclaresName(cur.node, name)) return true;
36487
+ if (isSwitchStatementNode(cur.node) && switchStatementDeclaresName(cur.node, name)) return true;
36488
+ if (isLoopNode(cur.node) && loopDeclaresName(cur.node, name)) return true;
36489
+ cur = cur.parentPath ?? null;
36490
+ }
36491
+ return false;
36492
+ }
36493
+ function functionDeclaresName(node, name) {
36494
+ const fn = node;
36495
+ const ids = /* @__PURE__ */ new Set();
36496
+ collectPatternIdentifiers(fn.id, ids);
36497
+ for (const param of fn.params ?? []) collectPatternIdentifiers(param, ids);
36498
+ collectFunctionVarBindings(node, ids);
36499
+ return ids.has(name);
36500
+ }
36501
+ function collectFunctionVarBindings(node, out) {
36502
+ const visit = (current, isRoot = false) => {
36503
+ if (!current || typeof current !== "object") return;
36504
+ if (Array.isArray(current)) {
36505
+ for (const child of current) visit(child);
36506
+ return;
36507
+ }
36508
+ if (!isRoot && isFunctionNode(current)) return;
36509
+ const astNode = current;
36510
+ if (astNode.type === "VariableDeclaration" && astNode.kind === "var") {
36511
+ for (const declarator of astNode.declarations ?? []) collectPatternIdentifiers(declarator.id, out);
36512
+ return;
36513
+ }
36514
+ for (const key of Object.keys(astNode)) {
36515
+ if (key === "loc" || key === "comments") continue;
36516
+ visit(astNode[key]);
36517
+ }
36518
+ };
36519
+ visit(node, true);
36520
+ }
36521
+ function catchClauseDeclaresName(node, name) {
36522
+ const catchClause = node;
36523
+ const ids = /* @__PURE__ */ new Set();
36524
+ collectPatternIdentifiers(catchClause.param, ids);
36525
+ return ids.has(name);
36526
+ }
36527
+ function blockDeclaresName(node, name) {
36528
+ const block = node;
36529
+ for (const statement of block.body ?? []) {
36530
+ if (!statement || typeof statement !== "object") continue;
36531
+ const stmt = statement;
36532
+ if (stmt.type === "VariableDeclaration" && (stmt.kind === "let" || stmt.kind === "const")) for (const declarator of stmt.declarations ?? []) {
36533
+ const ids = /* @__PURE__ */ new Set();
36534
+ collectPatternIdentifiers(declarator.id, ids);
36535
+ if (ids.has(name)) return true;
36536
+ }
36537
+ if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
36538
+ const ids = /* @__PURE__ */ new Set();
36539
+ collectPatternIdentifiers(stmt.id, ids);
36540
+ if (ids.has(name)) return true;
36541
+ }
36542
+ }
36543
+ return false;
36544
+ }
36545
+ function switchStatementDeclaresName(node, name) {
36546
+ const switchStatement = node;
36547
+ for (const switchCase of switchStatement.cases ?? []) if (blockDeclaresName({ body: switchCase.consequent ?? [] }, name)) return true;
36548
+ return false;
36549
+ }
36550
+ function loopDeclaresName(node, name) {
36551
+ const loop = node;
36552
+ const binding = loop.init ?? loop.left;
36553
+ if (!binding || typeof binding !== "object") return false;
36554
+ const declaration = binding;
36555
+ if (declaration.type !== "VariableDeclaration" || declaration.kind !== "let" && declaration.kind !== "const") return false;
36556
+ for (const declarator of declaration.declarations ?? []) {
36557
+ const ids = /* @__PURE__ */ new Set();
36558
+ collectPatternIdentifiers(declarator.id, ids);
36559
+ if (ids.has(name)) return true;
36560
+ }
36561
+ return false;
36562
+ }
36563
+ function collectPatternIdentifiers(pattern, out) {
36564
+ if (!pattern || typeof pattern !== "object") return;
36565
+ const node = pattern;
36566
+ switch (node.type) {
36567
+ case "Identifier":
36568
+ if (node.name) out.add(node.name);
36569
+ return;
36570
+ case "RestElement":
36571
+ collectPatternIdentifiers(node.argument, out);
36572
+ return;
36573
+ case "AssignmentPattern":
36574
+ collectPatternIdentifiers(node.left, out);
36575
+ return;
36576
+ case "ObjectPattern":
36577
+ for (const prop of node.properties ?? []) {
36578
+ const property = prop;
36579
+ collectPatternIdentifiers(property?.type === "RestElement" ? property.argument : property?.value, out);
36580
+ }
36581
+ return;
36582
+ case "ArrayPattern":
36583
+ for (const element of node.elements ?? []) collectPatternIdentifiers(element, out);
36584
+ return;
36585
+ case "TSParameterProperty":
36586
+ collectPatternIdentifiers(node.parameter, out);
36587
+ return;
36588
+ default: return;
36589
+ }
36590
+ }
36591
+ function getVariableDeclarationKind(path) {
36592
+ const parentNode = path.parentPath?.node;
36593
+ return parentNode?.type === "VariableDeclaration" && typeof parentNode.kind === "string" ? parentNode.kind : null;
36594
+ }
36595
+ function isScopeNode(node) {
36596
+ return isProgramNode(node) || isBlockStatementNode(node);
36597
+ }
36598
+ function isProgramNode(node) {
36599
+ return node.type === "Program";
36600
+ }
36601
+ function isFunctionOrProgramNode(node) {
36602
+ return isProgramNode(node) || isFunctionNode(node);
36603
+ }
36604
+ function isFunctionNode(node) {
36605
+ const type = node.type;
36606
+ return type === "FunctionDeclaration" || type === "FunctionExpression" || type === "ArrowFunctionExpression";
36607
+ }
36608
+ function isCatchClauseNode(node) {
36609
+ return node.type === "CatchClause";
36610
+ }
36611
+ function isBlockStatementNode(node) {
36612
+ return node.type === "BlockStatement";
36613
+ }
36614
+ function isSwitchStatementNode(node) {
36615
+ return node.type === "SwitchStatement";
36616
+ }
36617
+ function isLoopNode(node) {
36618
+ const type = node.type;
36619
+ return type === "ForStatement" || type === "ForInStatement" || type === "ForOfStatement";
36620
+ }
34141
36621
  /**
34142
36622
  * Tries to follow re-exports for `<exportedName>` from `<program>`:
34143
36623
  * - `export { exportedName } from "./other"` (direct)
@@ -34324,6 +36804,12 @@ function processRuleDeclarations(args) {
34324
36804
  state.bail = true;
34325
36805
  break;
34326
36806
  }
36807
+ if (d.property && isUnsupportedStylexProperty(d.property)) {
36808
+ state.bailUnsupported(ctx.decl, `Unsupported CSS property "${d.property}" cannot be emitted in StyleX`);
36809
+ if (state.currentDecl === ctx.decl) break;
36810
+ state.bail = true;
36811
+ break;
36812
+ }
34327
36813
  const outs = cssDeclarationToStylexDeclarations(d);
34328
36814
  for (let i = 0; i < outs.length; i++) {
34329
36815
  const out = outs[i];
@@ -34477,6 +36963,15 @@ function processDeclRules(ctx) {
34477
36963
  });
34478
36964
  break;
34479
36965
  }
36966
+ if (specificityResult.wasStripped && decl.base.kind === "component") {
36967
+ state.markBail();
36968
+ warnings.push({
36969
+ severity: "warning",
36970
+ type: "Styled-components specificity hacks like `&&` / `&&&` are not representable in StyleX",
36971
+ loc: computeSelectorWarningLoc(decl.loc, decl.rawCss, rule.selector)
36972
+ });
36973
+ break;
36974
+ }
34480
36975
  const selectorForAnalysis = specificityResult.normalized;
34481
36976
  const s = normalizeInterpolatedSelector(selectorForAnalysis).trim();
34482
36977
  const hasComponentExpr = rule.selector.includes("__SC_EXPR_");
@@ -34856,7 +37351,7 @@ function processDeclRules(ctx) {
34856
37351
  state.markBail();
34857
37352
  warnings.push({
34858
37353
  severity: "warning",
34859
- type: "CSS block contains unsupported at-rule (only @media and @container are supported; @supports, etc. require manual handling)",
37354
+ type: "CSS block contains unsupported at-rule (only @media, @container, and @supports are supported; mixed nested at-rules require manual handling)",
34860
37355
  loc: computeSelectorWarningLoc(decl.loc, decl.rawCss, rule.selector)
34861
37356
  });
34862
37357
  break;
@@ -35037,22 +37532,38 @@ function processDeclRules(ctx) {
35037
37532
  }
35038
37533
  if (prop && prop.startsWith("--") && typeof value === "string") localVarValues.set(prop, value);
35039
37534
  if (media && pseudos?.length) {
35040
- perPropPseudo[prop] ??= {};
35041
- const existing = perPropPseudo[prop];
35042
- noteSourceCssProperty(existing);
35043
- if (!("default" in existing)) {
35044
- const existingVal = styleObj[prop];
35045
- if (existingVal !== void 0) existing.default = existingVal;
35046
- else if (cssHelperPropValues.has(prop)) existing.default = getComposedDefaultValue(prop);
35047
- else existing.default = null;
35048
- }
35049
- for (const ps of pseudos) {
35050
- const current = existing[ps];
35051
- if (!current || typeof current !== "object") {
35052
- const fallbackDefault = cssHelperPropValues.has(prop) ? getComposedDefaultValue(prop) : null;
35053
- existing[ps] = { default: current !== void 0 ? current : fallbackDefault };
35054
- } else if (!("default" in current)) current.default = cssHelperPropValues.has(prop) ? getComposedDefaultValue(prop) : null;
35055
- existing[ps][media] = value;
37535
+ if (media.startsWith("@supports")) {
37536
+ perPropMedia[prop] ??= {};
37537
+ const existing = perPropMedia[prop];
37538
+ noteSourceCssProperty(existing);
37539
+ if (!("default" in existing)) {
37540
+ const existingVal = styleObj[prop];
37541
+ if (existingVal !== void 0) existing.default = existingVal;
37542
+ else if (cssHelperPropValues.has(prop)) existing.default = getComposedDefaultValue(prop);
37543
+ else existing.default = null;
37544
+ }
37545
+ const current = existing[media];
37546
+ const mediaMap = current && typeof current === "object" && !Array.isArray(current) && !isAstNode(current) ? current : { default: current ?? null };
37547
+ for (const ps of pseudos) mediaMap[ps] = value;
37548
+ existing[media] = mediaMap;
37549
+ } else {
37550
+ perPropPseudo[prop] ??= {};
37551
+ const existing = perPropPseudo[prop];
37552
+ noteSourceCssProperty(existing);
37553
+ if (!("default" in existing)) {
37554
+ const existingVal = styleObj[prop];
37555
+ if (existingVal !== void 0) existing.default = existingVal;
37556
+ else if (cssHelperPropValues.has(prop)) existing.default = getComposedDefaultValue(prop);
37557
+ else existing.default = null;
37558
+ }
37559
+ for (const ps of pseudos) {
37560
+ const current = existing[ps];
37561
+ if (!current || typeof current !== "object") {
37562
+ const fallbackDefault = cssHelperPropValues.has(prop) ? getComposedDefaultValue(prop) : null;
37563
+ existing[ps] = { default: current !== void 0 ? current : fallbackDefault };
37564
+ } else if (!("default" in current)) current.default = cssHelperPropValues.has(prop) ? getComposedDefaultValue(prop) : null;
37565
+ existing[ps][media] = value;
37566
+ }
35056
37567
  }
35057
37568
  return;
35058
37569
  }
@@ -35131,7 +37642,9 @@ function processDeclRules(ctx) {
35131
37642
  else if (cssHelperPropValues.has(prop)) existing.default = getComposedDefaultValue(prop);
35132
37643
  else existing.default = null;
35133
37644
  }
35134
- existing[media] = value;
37645
+ const currentMediaValue = existing[media];
37646
+ if (currentMediaValue && typeof currentMediaValue === "object" && !Array.isArray(currentMediaValue) && !isAstNode(currentMediaValue)) currentMediaValue.default = value;
37647
+ else existing[media] = value;
35135
37648
  patchEarlierDynamicConditionValues(prop, media, value);
35136
37649
  return;
35137
37650
  }
@@ -35570,7 +38083,7 @@ function handlePseudoExpand(result, importedName, rule, ctx, prefixPseudo) {
35570
38083
  const existing = target[pseudo];
35571
38084
  if (existing && typeof existing === "object" && "__computedKeys" in existing) existing.__computedKeys.push(newEntry);
35572
38085
  else target[pseudo] = {
35573
- default: null,
38086
+ default: target.default ?? null,
35574
38087
  __computedKeys: [newEntry]
35575
38088
  };
35576
38089
  } else target[pseudo] = cloneAstNode(value);
@@ -35840,6 +38353,15 @@ function registerReferencedMarker(styleKey, localName, state, ancestorSelectorPa
35840
38353
  function resolveMediaAndEmitComputedKeys(bucket, makeKeyExpr, rule, ctx, computedMediaWarningType, entryExtra) {
35841
38354
  const { state, decl } = ctx;
35842
38355
  const { warnings } = state;
38356
+ if (hasUnsupportedAtRule(rule.atRuleStack)) {
38357
+ state.markBail();
38358
+ warnings.push({
38359
+ severity: "warning",
38360
+ type: "CSS block contains unsupported at-rule (only @media, @container, and @supports are supported; mixed nested at-rules require manual handling)",
38361
+ loc: computeSelectorWarningLoc(decl.loc, decl.rawCss, rule.selector)
38362
+ });
38363
+ return "break";
38364
+ }
35843
38365
  let media = findSupportedAtRule(rule.atRuleStack);
35844
38366
  if (media) {
35845
38367
  const resolved = resolveMediaAtRulePlaceholders(media, (slotId) => decl.templateExpressions[slotId], {
@@ -35940,6 +38462,15 @@ function handleAdjacentSiblingSelector(rule, ctx) {
35940
38462
  });
35941
38463
  return "break";
35942
38464
  }
38465
+ if (hasUnsupportedAtRule(rule.atRuleStack)) {
38466
+ state.markBail();
38467
+ state.warnings.push({
38468
+ severity: "warning",
38469
+ type: "CSS block contains unsupported at-rule (only @media, @container, and @supports are supported; mixed nested at-rules require manual handling)",
38470
+ loc: computeSelectorWarningLoc(decl.loc, decl.rawCss, rule.selector)
38471
+ });
38472
+ return "break";
38473
+ }
35943
38474
  let media = findSupportedAtRule(rule.atRuleStack);
35944
38475
  if (media) {
35945
38476
  const resolved = resolveMediaAtRulePlaceholders(media, (slotId) => decl.templateExpressions[slotId], {
@@ -36804,10 +39335,6 @@ function collectTemplateSelectorIdentifiers(decl) {
36804
39335
  }
36805
39336
  return identifiers;
36806
39337
  }
36807
- function isTemplatePlaceholderInSelectorContext(rawCss, pos, length) {
36808
- const after = rawCss.slice(pos + length).trimStart();
36809
- return isSelectorContext(rawCss.slice(0, pos).trimEnd().replace(PLACEHOLDER_RE_G, "hover"), after);
36810
- }
36811
39338
  function collectCssHelperFunctionSelectorIdentifiers(state, cssLocal) {
36812
39339
  const selectorIdentifiers = /* @__PURE__ */ new Map();
36813
39340
  for (const [name, helperFn] of state.cssHelperFunctions) selectorIdentifiers.set(name, collectTemplateSelectorIdentifiersFromParts(helperFn.rawCss, helperFn.templateExpressions));
@@ -38167,8 +40694,15 @@ function substituteStyleFnCallArg(callArg, propNames, valueExpr) {
38167
40694
  };
38168
40695
  return visit(cloneAstNode(callArg));
38169
40696
  }
38170
- function wrappedComponentAcceptsSxProp(ctx, componentLocalName) {
40697
+ function wrappedComponentAcceptsSxProp(ctx, componentLocalName, visiting = /* @__PURE__ */ new Set()) {
38171
40698
  if (!ctx.adapter.useSxProp) return false;
40699
+ if (visiting.has(componentLocalName)) return false;
40700
+ visiting.add(componentLocalName);
40701
+ const localStyledDecl = ctx.styledDecls?.find((decl) => decl.localName === componentLocalName);
40702
+ if (localStyledDecl?.needsWrapperComponent && localStyledDecl.base.kind === "component" && wrappedComponentAcceptsSxProp(ctx, localStyledDecl.base.ident, visiting)) {
40703
+ visiting.delete(componentLocalName);
40704
+ return true;
40705
+ }
38172
40706
  const importInfo = ctx.importMap?.get(componentLocalName);
38173
40707
  if (importInfo) {
38174
40708
  const adapterResult = ctx.adapter.wrappedComponentInterface?.({
@@ -38177,7 +40711,10 @@ function wrappedComponentAcceptsSxProp(ctx, componentLocalName) {
38177
40711
  importedName: importInfo.importedName,
38178
40712
  filePath: ctx.file.path
38179
40713
  });
38180
- if (adapterResult !== void 0) return adapterResult.acceptsSx === true;
40714
+ if (adapterResult !== void 0) {
40715
+ visiting.delete(componentLocalName);
40716
+ return adapterResult.acceptsSx === true;
40717
+ }
38181
40718
  }
38182
40719
  const typedComponent = (() => {
38183
40720
  if (importInfo?.source.kind === "absolutePath") {
@@ -38187,14 +40724,22 @@ function wrappedComponentAcceptsSxProp(ctx, componentLocalName) {
38187
40724
  return findTypeScriptComponentMetadata(ctx.options.crossFileInfo?.typeScriptMetadata, ctx.file.path, [componentLocalName]);
38188
40725
  })();
38189
40726
  if (typedComponent) {
38190
- if (typedComponent.supportsSxProp) return true;
38191
- if (importInfo?.source.kind !== "absolutePath" || ctx.options.transformedFileSources?.has(toRealPath(importInfo.source.value)) !== true) return false;
40727
+ if (typedComponent.supportsSxProp) {
40728
+ visiting.delete(componentLocalName);
40729
+ return true;
40730
+ }
40731
+ if (importInfo?.source.kind !== "absolutePath" || ctx.options.transformedFileSources?.has(resolveExistingFilePath(importInfo.source.value)) !== true) {
40732
+ visiting.delete(componentLocalName);
40733
+ return false;
40734
+ }
38192
40735
  }
38193
- return importInfo?.source.kind === "absolutePath" && transformedComponentAcceptsSx({
40736
+ const accepts = importInfo?.source.kind === "absolutePath" && transformedComponentAcceptsSx({
38194
40737
  absolutePath: importInfo.source.value,
38195
40738
  componentNames: importInfo.importedName === "default" ? [componentLocalName, importInfo.importedName] : [importInfo.importedName],
38196
40739
  sourceOverrides: ctx.options.transformedFileSources
38197
40740
  });
40741
+ visiting.delete(componentLocalName);
40742
+ return accepts;
38198
40743
  }
38199
40744
  /**
38200
40745
  * Rewrites JSX usages and removes styled declarations when wrappers are not required.
@@ -38542,15 +41087,16 @@ function rewriteJsxStep(ctx) {
38542
41087
  const hasRestSpreadAttr = keptRestAfterVariants.some((attr) => attr.type === "JSXSpreadAttribute");
38543
41088
  const needsMerge = effectiveClassNameAttr !== null || styleAttr !== null && !(staticInlineStyleExpr !== null && styleAttr !== null && effectiveClassNameAttr === null && !hasCallerStyleAttr && !hasRestSpreadAttr);
38544
41089
  const stylesId = ctx.stylesIdentifier ?? "styles";
38545
- const hasLocalStyleRef = styleArgs.some((arg) => j([arg]).find(j.Identifier, { name: stylesId }).size() > 0);
41090
+ const mergedStyleArgs = mergeAdjacentComplementaryStyleExprs(j, styleArgs);
41091
+ const hasLocalStyleRef = mergedStyleArgs.some((arg) => j([arg]).find(j.Identifier, { name: stylesId }).size() > 0);
38546
41092
  const useSxPropForWrapped = ctx.adapter.useSxProp && wrappedAcceptsSxProp && hasLocalStyleRef;
38547
41093
  const useSxProp = useSxPropForWrapped || ctx.adapter.useSxProp && !needsMerge && isIntrinsicTag && hasLocalStyleRef;
38548
41094
  const callerSxExpr = sxAttr && sxAttr.type === "JSXAttribute" && sxAttr.value?.type === "JSXExpressionContainer" ? sxAttr.value.expression : null;
38549
41095
  const stylexAttr = useSxProp ? (() => {
38550
- const allArgs = callerSxExpr ? [...styleArgs, callerSxExpr] : [...styleArgs];
41096
+ const allArgs = callerSxExpr ? [...mergedStyleArgs, callerSxExpr] : [...mergedStyleArgs];
38551
41097
  const sxExpr = allArgs.length === 1 && allArgs[0] ? allArgs[0] : j.arrayExpression(allArgs);
38552
41098
  return j.jsxAttribute(j.jsxIdentifier("sx"), j.jsxExpressionContainer(sxExpr));
38553
- })() : j.jsxSpreadAttribute(needsMerge ? buildInlineMergeCall(j, styleArgs, effectiveClassNameAttr, styleAttr, ctx.adapter.styleMerger?.functionName) : j.callExpression(j.memberExpression(j.identifier("stylex"), j.identifier("props")), [...styleArgs]));
41099
+ })() : j.jsxSpreadAttribute(needsMerge ? buildInlineMergeCall(j, mergedStyleArgs, effectiveClassNameAttr, styleAttr, ctx.adapter.styleMerger?.functionName) : j.callExpression(j.memberExpression(j.identifier("stylex"), j.identifier("props")), [...mergedStyleArgs]));
38554
41100
  const extraClassNameAttrs = [];
38555
41101
  if (extraClassNameExpr && useSxProp) extraClassNameAttrs.push(j.jsxAttribute(j.jsxIdentifier("className"), j.jsxExpressionContainer(extraClassNameExpr)));
38556
41102
  const passThroughClassName = useSxPropForWrapped && classNameAttr ? [classNameAttr] : [];