@tamagui/static 2.0.0-rc.4 → 2.0.0-rc.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/dist/check-dep-versions.cjs +201 -96
  2. package/dist/checkDeps.cjs +250 -46
  3. package/dist/constants.cjs +32 -30
  4. package/dist/exports.cjs +18 -13
  5. package/dist/extractor/accessSafe.cjs +25 -23
  6. package/dist/extractor/babelParse.cjs +30 -28
  7. package/dist/extractor/buildClassName.cjs +59 -35
  8. package/dist/extractor/bundle.cjs +177 -101
  9. package/dist/extractor/bundleConfig.cjs +554 -167
  10. package/dist/extractor/concatClassName.cjs +41 -29
  11. package/dist/extractor/createEvaluator.cjs +54 -41
  12. package/dist/extractor/createExtractor.cjs +1400 -581
  13. package/dist/extractor/createLogger.cjs +30 -25
  14. package/dist/extractor/detectModuleFormat.cjs +55 -0
  15. package/dist/extractor/ensureImportingConcat.cjs +31 -25
  16. package/dist/extractor/errors.cjs +12 -10
  17. package/dist/extractor/esbuildAliasPlugin.cjs +28 -16
  18. package/dist/extractor/esbuildTsconfigPaths.cjs +60 -36
  19. package/dist/extractor/evaluateAstNode.cjs +104 -59
  20. package/dist/extractor/extractHelpers.cjs +130 -67
  21. package/dist/extractor/extractMediaStyle.cjs +110 -69
  22. package/dist/extractor/extractToClassNames.cjs +337 -229
  23. package/dist/extractor/extractToNative.cjs +248 -154
  24. package/dist/extractor/findTopmostFunction.cjs +22 -13
  25. package/dist/extractor/generatedUid.cjs +39 -28
  26. package/dist/extractor/getPrefixLogs.cjs +12 -10
  27. package/dist/extractor/getPropValueFromAttributes.cjs +52 -34
  28. package/dist/extractor/getSourceModule.cjs +73 -37
  29. package/dist/extractor/getStaticBindingsForScope.cjs +131 -68
  30. package/dist/extractor/getTamaguiConfigPathFromOptionsConfig.cjs +20 -14
  31. package/dist/extractor/hasTopLevelAwait.cjs +62 -0
  32. package/dist/extractor/hoistClassNames.cjs +46 -32
  33. package/dist/extractor/literalToAst.cjs +67 -42
  34. package/dist/extractor/loadFile.cjs +9 -3
  35. package/dist/extractor/loadTamagui.cjs +149 -104
  36. package/dist/extractor/logLines.cjs +27 -19
  37. package/dist/extractor/normalizeTernaries.cjs +66 -44
  38. package/dist/extractor/propsToFontFamilyCache.cjs +15 -11
  39. package/dist/extractor/regenerateConfig.cjs +109 -81
  40. package/dist/extractor/removeUnusedHooks.cjs +73 -41
  41. package/dist/extractor/timer.cjs +23 -14
  42. package/dist/extractor/validHTMLAttributes.cjs +61 -59
  43. package/dist/extractor/watchTamaguiConfig.cjs +35 -23
  44. package/dist/getPragmaOptions.cjs +38 -19
  45. package/dist/helpers/memoize.cjs +24 -16
  46. package/dist/helpers/requireTamaguiCore.cjs +22 -15
  47. package/dist/index.cjs +26 -24
  48. package/dist/registerRequire.cjs +167 -65
  49. package/dist/server.cjs +35 -28
  50. package/dist/types.cjs +7 -5
  51. package/dist/worker.cjs +62 -40
  52. package/package.json +26 -22
  53. package/src/checkDeps.ts +305 -68
  54. package/src/exports.ts +1 -0
  55. package/src/extractor/babelParse.ts +1 -0
  56. package/src/extractor/bundle.ts +140 -37
  57. package/src/extractor/bundleConfig.ts +435 -61
  58. package/src/extractor/createExtractor.ts +283 -48
  59. package/src/extractor/detectModuleFormat.ts +42 -0
  60. package/src/extractor/esbuildTsconfigPaths.ts +6 -1
  61. package/src/extractor/extractToClassNames.ts +15 -9
  62. package/src/extractor/extractToNative.ts +66 -33
  63. package/src/extractor/hasTopLevelAwait.ts +28 -0
  64. package/src/extractor/loadTamagui.ts +2 -2
  65. package/src/getPragmaOptions.ts +6 -1
  66. package/src/registerRequire.ts +88 -8
  67. package/types/checkDeps.d.ts.map +1 -1
  68. package/types/exports.d.ts +1 -0
  69. package/types/exports.d.ts.map +1 -1
  70. package/types/extractor/babelParse.d.ts.map +1 -1
  71. package/types/extractor/bundle.d.ts +83 -1
  72. package/types/extractor/bundle.d.ts.map +1 -1
  73. package/types/extractor/bundleConfig.d.ts +15 -2
  74. package/types/extractor/bundleConfig.d.ts.map +1 -1
  75. package/types/extractor/createExtractor.d.ts.map +1 -1
  76. package/types/extractor/detectModuleFormat.d.ts +5 -0
  77. package/types/extractor/detectModuleFormat.d.ts.map +1 -0
  78. package/types/extractor/esbuildTsconfigPaths.d.ts +8 -0
  79. package/types/extractor/esbuildTsconfigPaths.d.ts.map +1 -1
  80. package/types/extractor/extractToClassNames.d.ts.map +1 -1
  81. package/types/extractor/extractToNative.d.ts.map +1 -1
  82. package/types/extractor/hasTopLevelAwait.d.ts +2 -0
  83. package/types/extractor/hasTopLevelAwait.d.ts.map +1 -0
  84. package/types/getPragmaOptions.d.ts.map +1 -1
  85. package/types/registerRequire.d.ts.map +1 -1
  86. package/dist/check-dep-versions.js +0 -389
  87. package/dist/check-dep-versions.js.map +0 -6
  88. package/dist/checkDeps.js +0 -60
  89. package/dist/checkDeps.js.map +0 -6
  90. package/dist/constants.js +0 -34
  91. package/dist/constants.js.map +0 -6
  92. package/dist/exports.js +0 -34
  93. package/dist/exports.js.map +0 -6
  94. package/dist/extractor/accessSafe.js +0 -47
  95. package/dist/extractor/accessSafe.js.map +0 -6
  96. package/dist/extractor/babelParse.js +0 -59
  97. package/dist/extractor/babelParse.js.map +0 -6
  98. package/dist/extractor/buildClassName.js +0 -72
  99. package/dist/extractor/buildClassName.js.map +0 -6
  100. package/dist/extractor/bundle.js +0 -135
  101. package/dist/extractor/bundle.js.map +0 -6
  102. package/dist/extractor/bundleConfig.js +0 -352
  103. package/dist/extractor/bundleConfig.js.map +0 -6
  104. package/dist/extractor/concatClassName.js +0 -69
  105. package/dist/extractor/concatClassName.js.map +0 -6
  106. package/dist/extractor/createEvaluator.js +0 -66
  107. package/dist/extractor/createEvaluator.js.map +0 -6
  108. package/dist/extractor/createExtractor.js +0 -1215
  109. package/dist/extractor/createExtractor.js.map +0 -6
  110. package/dist/extractor/createLogger.js +0 -32
  111. package/dist/extractor/createLogger.js.map +0 -6
  112. package/dist/extractor/ensureImportingConcat.js +0 -50
  113. package/dist/extractor/ensureImportingConcat.js.map +0 -6
  114. package/dist/extractor/errors.js +0 -22
  115. package/dist/extractor/errors.js.map +0 -6
  116. package/dist/extractor/esbuildAliasPlugin.js +0 -36
  117. package/dist/extractor/esbuildAliasPlugin.js.map +0 -6
  118. package/dist/extractor/esbuildTsconfigPaths.js +0 -79
  119. package/dist/extractor/esbuildTsconfigPaths.js.map +0 -6
  120. package/dist/extractor/evaluateAstNode.js +0 -99
  121. package/dist/extractor/evaluateAstNode.js.map +0 -6
  122. package/dist/extractor/extractHelpers.js +0 -108
  123. package/dist/extractor/extractHelpers.js.map +0 -6
  124. package/dist/extractor/extractMediaStyle.js +0 -123
  125. package/dist/extractor/extractMediaStyle.js.map +0 -6
  126. package/dist/extractor/extractToClassNames.js +0 -351
  127. package/dist/extractor/extractToClassNames.js.map +0 -6
  128. package/dist/extractor/extractToNative.js +0 -286
  129. package/dist/extractor/extractToNative.js.map +0 -6
  130. package/dist/extractor/findTopmostFunction.js +0 -32
  131. package/dist/extractor/findTopmostFunction.js.map +0 -6
  132. package/dist/extractor/generatedUid.js +0 -42
  133. package/dist/extractor/generatedUid.js.map +0 -6
  134. package/dist/extractor/getPrefixLogs.js +0 -24
  135. package/dist/extractor/getPrefixLogs.js.map +0 -6
  136. package/dist/extractor/getPropValueFromAttributes.js +0 -65
  137. package/dist/extractor/getPropValueFromAttributes.js.map +0 -6
  138. package/dist/extractor/getSourceModule.js +0 -62
  139. package/dist/extractor/getSourceModule.js.map +0 -6
  140. package/dist/extractor/getStaticBindingsForScope.js +0 -145
  141. package/dist/extractor/getStaticBindingsForScope.js.map +0 -6
  142. package/dist/extractor/getTamaguiConfigPathFromOptionsConfig.js +0 -32
  143. package/dist/extractor/getTamaguiConfigPathFromOptionsConfig.js.map +0 -6
  144. package/dist/extractor/hoistClassNames.js +0 -63
  145. package/dist/extractor/hoistClassNames.js.map +0 -6
  146. package/dist/extractor/literalToAst.js +0 -90
  147. package/dist/extractor/literalToAst.js.map +0 -6
  148. package/dist/extractor/loadFile.js +0 -14
  149. package/dist/extractor/loadFile.js.map +0 -6
  150. package/dist/extractor/loadTamagui.js +0 -306
  151. package/dist/extractor/loadTamagui.js.map +0 -6
  152. package/dist/extractor/logLines.js +0 -30
  153. package/dist/extractor/logLines.js.map +0 -6
  154. package/dist/extractor/normalizeTernaries.js +0 -61
  155. package/dist/extractor/normalizeTernaries.js.map +0 -6
  156. package/dist/extractor/propsToFontFamilyCache.js +0 -33
  157. package/dist/extractor/propsToFontFamilyCache.js.map +0 -6
  158. package/dist/extractor/regenerateConfig.js +0 -123
  159. package/dist/extractor/regenerateConfig.js.map +0 -6
  160. package/dist/extractor/removeUnusedHooks.js +0 -72
  161. package/dist/extractor/removeUnusedHooks.js.map +0 -6
  162. package/dist/extractor/timer.js +0 -38
  163. package/dist/extractor/timer.js.map +0 -6
  164. package/dist/extractor/validHTMLAttributes.js +0 -72
  165. package/dist/extractor/validHTMLAttributes.js.map +0 -6
  166. package/dist/extractor/watchTamaguiConfig.js +0 -57
  167. package/dist/extractor/watchTamaguiConfig.js.map +0 -6
  168. package/dist/getPragmaOptions.js +0 -46
  169. package/dist/getPragmaOptions.js.map +0 -6
  170. package/dist/helpers/memoize.js +0 -33
  171. package/dist/helpers/memoize.js.map +0 -6
  172. package/dist/helpers/requireTamaguiCore.js +0 -30
  173. package/dist/helpers/requireTamaguiCore.js.map +0 -6
  174. package/dist/index.js +0 -30
  175. package/dist/index.js.map +0 -6
  176. package/dist/registerRequire.js +0 -100
  177. package/dist/registerRequire.js.map +0 -6
  178. package/dist/server.js +0 -58
  179. package/dist/server.js.map +0 -6
  180. package/dist/setup.js +0 -1
  181. package/dist/setup.js.map +0 -6
  182. package/dist/types.js +0 -14
  183. package/dist/types.js.map +0 -6
  184. package/dist/worker.js +0 -72
  185. package/dist/worker.js.map +0 -6
@@ -2,66 +2,72 @@ var __create = Object.create;
2
2
  var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf,
6
- __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
7
  var __export = (target, all) => {
8
- for (var name in all) __defProp(target, name, {
9
- get: all[name],
10
- enumerable: !0
11
- });
12
- },
13
- __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from == "object" || typeof from == "function") for (let key of __getOwnPropNames(from)) !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
8
+ for (var name in all) __defProp(target, name, {
9
+ get: all[name],
10
+ enumerable: true
11
+ });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
15
16
  get: () => from[key],
16
17
  enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
18
  });
18
- return to;
19
- };
19
+ }
20
+ return to;
21
+ };
20
22
  var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
26
- value: mod,
27
- enumerable: !0
28
- }) : target, mod)),
29
- __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
30
- value: !0
31
- }), mod);
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
28
+ value: mod,
29
+ enumerable: true
30
+ }) : target, mod));
31
+ var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", {
32
+ value: true
33
+ }), mod);
32
34
  var createExtractor_exports = {};
33
35
  __export(createExtractor_exports, {
34
36
  createExtractor: () => createExtractor
35
37
  });
36
38
  module.exports = __toCommonJS(createExtractor_exports);
37
- var import_traverse = __toESM(require("@babel/traverse")),
38
- t = __toESM(require("@babel/types")),
39
- import_cli_color = require("@tamagui/cli-color"),
40
- reactNativeWebInternals = __toESM(require("@tamagui/react-native-web-internals")),
41
- import_web = require("@tamagui/web"),
42
- import_node_path = require("node:path"),
43
- import_constants = require("../constants.cjs"),
44
- import_requireTamaguiCore = require("../helpers/requireTamaguiCore.cjs"),
45
- import_createEvaluator = require("./createEvaluator.cjs"),
46
- import_evaluateAstNode = require("./evaluateAstNode.cjs"),
47
- import_extractHelpers = require("./extractHelpers.cjs"),
48
- import_findTopmostFunction = require("./findTopmostFunction.cjs"),
49
- import_getStaticBindingsForScope = require("./getStaticBindingsForScope.cjs"),
50
- import_literalToAst = require("./literalToAst.cjs"),
51
- import_loadTamagui = require("./loadTamagui.cjs"),
52
- import_logLines = require("./logLines.cjs"),
53
- import_normalizeTernaries = require("./normalizeTernaries.cjs"),
54
- import_propsToFontFamilyCache = require("./propsToFontFamilyCache.cjs"),
55
- import_timer = require("./timer.cjs"),
56
- import_validHTMLAttributes = require("./validHTMLAttributes.cjs"),
57
- import_errors = require("./errors.cjs");
39
+ var import_traverse = __toESM(require("@babel/traverse"));
40
+ var t = __toESM(require("@babel/types"));
41
+ var import_cli_color = require("@tamagui/cli-color");
42
+ var reactNativeWebInternals = __toESM(require("@tamagui/react-native-web-internals"));
43
+ var import_web = require("@tamagui/web");
44
+ var import_node_fs = require("node:fs");
45
+ var import_node_path = require("node:path");
46
+ var import_typescript = require("typescript");
47
+ var import_constants = require("../constants.cjs");
48
+ var import_requireTamaguiCore = require("../helpers/requireTamaguiCore.cjs");
49
+ var import_createEvaluator = require("./createEvaluator.cjs");
50
+ var import_evaluateAstNode = require("./evaluateAstNode.cjs");
51
+ var import_extractHelpers = require("./extractHelpers.cjs");
52
+ var import_findTopmostFunction = require("./findTopmostFunction.cjs");
53
+ var import_getStaticBindingsForScope = require("./getStaticBindingsForScope.cjs");
54
+ var import_literalToAst = require("./literalToAst.cjs");
55
+ var import_loadTamagui = require("./loadTamagui.cjs");
56
+ var import_logLines = require("./logLines.cjs");
57
+ var import_normalizeTernaries = require("./normalizeTernaries.cjs");
58
+ var import_propsToFontFamilyCache = require("./propsToFontFamilyCache.cjs");
59
+ var import_timer = require("./timer.cjs");
60
+ var import_validHTMLAttributes = require("./validHTMLAttributes.cjs");
61
+ var import_errors = require("./errors.cjs");
62
+ var import_esbuildTsconfigPaths = require("./esbuildTsconfigPaths.cjs");
58
63
  const UNTOUCHED_PROPS = {
59
- key: !0,
60
- style: !0,
61
- className: !0
62
- },
63
- createTernary = x => x;
64
- let hasLoggedBaseInfo = !1;
64
+ key: true,
65
+ style: true,
66
+ className: true
67
+ };
68
+ const nativeOnlyPlatforms = /* @__PURE__ */new Set(["android", "ios", "tv", "androidtv", "tvos"]);
69
+ const createTernary = x => x;
70
+ let hasLoggedBaseInfo = false;
65
71
  function isFullyDisabled(props) {
66
72
  return props.disableExtraction && props.disableDebugAttr;
67
73
  }
@@ -72,40 +78,124 @@ function createExtractor({
72
78
  logger: console
73
79
  }) {
74
80
  const INLINE_EXTRACTABLE = {
75
- ref: "ref",
76
- key: "key",
77
- ...(platform === "web" && {
78
- onPress: "onClick",
79
- onHoverIn: "onMouseEnter",
80
- onHoverOut: "onMouseLeave",
81
- onPressIn: "onMouseDown",
82
- onPressOut: "onMouseUp"
83
- })
84
- },
85
- componentState = {
86
- focus: !1,
87
- focusVisible: !1,
88
- focusWithin: !1,
89
- hover: !1,
90
- unmounted: !0,
91
- press: !1,
92
- pressIn: !1,
93
- disabled: !1
94
- },
95
- styleProps = {
96
- resolveValues: "variable",
97
- noClass: !1,
98
- isAnimated: !1
99
- },
100
- shouldAddDebugProp =
101
- // really basic disable this for next.js because it messes with ssr
102
- !process.env.npm_package_dependencies_next && !0 && process.env.IDENTIFY_TAGS !== "false" && (process.env.NODE_ENV === "development" || process.env.IDENTIFY_TAGS);
81
+ ref: "ref",
82
+ key: "key",
83
+ ...(platform === "web" && {
84
+ onPress: "onClick",
85
+ onHoverIn: "onMouseEnter",
86
+ onHoverOut: "onMouseLeave",
87
+ onPressIn: "onMouseDown",
88
+ onPressOut: "onMouseUp"
89
+ }),
90
+ ...(platform === "native" && {
91
+ // native view props that should pass through without preventing flattening
92
+ testID: "testID",
93
+ nativeID: "nativeID",
94
+ accessibilityLabel: "accessibilityLabel",
95
+ accessibilityHint: "accessibilityHint",
96
+ accessibilityRole: "accessibilityRole",
97
+ accessibilityState: "accessibilityState",
98
+ accessibilityValue: "accessibilityValue",
99
+ accessibilityActions: "accessibilityActions",
100
+ accessibilityLabelledBy: "accessibilityLabelledBy",
101
+ accessibilityLiveRegion: "accessibilityLiveRegion",
102
+ accessibilityElementsHidden: "accessibilityElementsHidden",
103
+ accessibilityViewIsModal: "accessibilityViewIsModal",
104
+ importantForAccessibility: "importantForAccessibility",
105
+ collapsable: "collapsable",
106
+ needsOffscreenAlphaCompositing: "needsOffscreenAlphaCompositing",
107
+ removeClippedSubviews: "removeClippedSubviews",
108
+ renderToHardwareTextureAndroid: "renderToHardwareTextureAndroid",
109
+ shouldRasterizeIOS: "shouldRasterizeIOS",
110
+ hitSlop: "hitSlop",
111
+ pointerEvents: "pointerEvents"
112
+ })
113
+ };
114
+ const componentState = {
115
+ focus: false,
116
+ focusVisible: false,
117
+ focusWithin: false,
118
+ hover: false,
119
+ unmounted: true,
120
+ press: false,
121
+ pressIn: false,
122
+ disabled: false
123
+ };
124
+ const styleProps = {
125
+ resolveValues: platform === "native" ? "value" : "variable",
126
+ noClass: false,
127
+ isAnimated: false
128
+ };
129
+ const shouldAddDebugProp =
130
+ // really basic disable this for next.js because it messes with ssr
131
+ !process.env.npm_package_dependencies_next && platform !== "native" && process.env.IDENTIFY_TAGS !== "false" && (process.env.NODE_ENV === "development" || process.env.IDENTIFY_TAGS);
103
132
  let projectInfo = null;
133
+ const dynamicComponentCache = /* @__PURE__ */new Map();
134
+ const dynamicLoadingInProgress = /* @__PURE__ */new Set();
135
+ let _compilerOptions = null;
136
+ function getCompilerOptions() {
137
+ if (!_compilerOptions) {
138
+ try {
139
+ _compilerOptions = (0, import_esbuildTsconfigPaths.loadCompilerOptionsFromTsconfig)();
140
+ } catch {
141
+ _compilerOptions = {};
142
+ }
143
+ }
144
+ return _compilerOptions;
145
+ }
146
+ function resolveImportPath(fromFile, importPath) {
147
+ if (importPath.startsWith(".")) {
148
+ const dir = (0, import_node_path.dirname)(fromFile);
149
+ const base = (0, import_node_path.resolve)(dir, importPath);
150
+ const extensions = [".tsx", ".ts", ".jsx", ".js"];
151
+ for (const ext of extensions) {
152
+ const full = base + ext;
153
+ if ((0, import_node_fs.existsSync)(full)) return full;
154
+ }
155
+ for (const ext of extensions) {
156
+ const full = (0, import_node_path.resolve)(base, `index${ext}`);
157
+ if ((0, import_node_fs.existsSync)(full)) return full;
158
+ }
159
+ return null;
160
+ }
161
+ const compilerOptions = getCompilerOptions();
162
+ if (compilerOptions.paths) {
163
+ try {
164
+ const {
165
+ resolvedModule
166
+ } = (0, import_typescript.nodeModuleNameResolver)(importPath, fromFile, compilerOptions, import_typescript.sys);
167
+ if (resolvedModule && !resolvedModule.resolvedFileName.endsWith(".d.ts") && !resolvedModule.isExternalLibraryImport) {
168
+ return resolvedModule.resolvedFileName;
169
+ }
170
+ } catch {}
171
+ }
172
+ return null;
173
+ }
174
+ const styledCheckCache = /* @__PURE__ */new Map();
175
+ function mightHaveStyledComponents(filePath) {
176
+ const cached = styledCheckCache.get(filePath);
177
+ if (cached !== void 0) return cached;
178
+ try {
179
+ const content = (0, import_node_fs.readFileSync)(filePath, "utf-8");
180
+ const result = content.includes("styled(");
181
+ styledCheckCache.set(filePath, result);
182
+ return result;
183
+ } catch {
184
+ styledCheckCache.set(filePath, false);
185
+ return false;
186
+ }
187
+ }
104
188
  function loadSync(props) {
105
- return isFullyDisabled(props) ? null : projectInfo ||= (0, import_loadTamagui.loadTamaguiSync)(props);
189
+ if (isFullyDisabled(props)) {
190
+ return null;
191
+ }
192
+ return projectInfo ||= (0, import_loadTamagui.loadTamaguiSync)(props);
106
193
  }
107
194
  async function load(props) {
108
- return isFullyDisabled(props) ? null : projectInfo ||= await (0, import_loadTamagui.loadTamagui)(props);
195
+ if (isFullyDisabled(props)) {
196
+ return null;
197
+ }
198
+ return projectInfo ||= await (0, import_loadTamagui.loadTamagui)(props);
109
199
  }
110
200
  return {
111
201
  options: {
@@ -135,7 +225,7 @@ function createExtractor({
135
225
  const {
136
226
  config = "tamagui.config.ts",
137
227
  importsWhitelist = ["constants.js"],
138
- evaluateVars = !0,
228
+ evaluateVars = true,
139
229
  sourcePath = "",
140
230
  onExtractTag,
141
231
  onStyledDefinitionRule,
@@ -144,15 +234,21 @@ function createExtractor({
144
234
  disableExtraction,
145
235
  disableExtractVariables,
146
236
  disableDebugAttr,
147
- enableDynamicEvaluation = !1,
237
+ enableDynamicEvaluation = false,
148
238
  includeExtensions = [".ts", ".tsx", ".jsx"],
149
- extractStyledDefinitions = !1,
239
+ extractStyledDefinitions = false,
150
240
  prefixLogs,
151
241
  excludeProps,
152
242
  platform: platform2,
153
243
  ...restProps
154
244
  } = options;
155
- if (sourcePath.includes(".tamagui-dynamic-eval")) return null;
245
+ if (sourcePath && dynamicComponentCache.has(sourcePath)) {
246
+ dynamicComponentCache.delete(sourcePath);
247
+ styledCheckCache.delete(sourcePath);
248
+ }
249
+ if (sourcePath.includes(".tamagui-dynamic-eval")) {
250
+ return null;
251
+ }
156
252
  const {
157
253
  normalizeStyle,
158
254
  getSplitStyles,
@@ -162,31 +258,62 @@ function createExtractor({
162
258
  getDefaultProps,
163
259
  pseudoDescriptors
164
260
  } = (0, import_requireTamaguiCore.requireTamaguiCore)(platform2);
165
- let shouldPrintDebug = options.shouldPrintDebug || !1;
166
- if (disable === !0 || Array.isArray(disable) && disable.includes(sourcePath)) return null;
167
- if (!isFullyDisabled(options) && !components) throw new Error("Must provide components");
168
- if (sourcePath && includeExtensions && !includeExtensions.some(ext => sourcePath.endsWith(ext))) return shouldPrintDebug && logger.info(`Ignoring file due to includeExtensions: ${sourcePath}, includeExtensions: ${includeExtensions.join(", ")}`), null;
261
+ let shouldPrintDebug = options.shouldPrintDebug || false;
262
+ if (disable === true || Array.isArray(disable) && disable.includes(sourcePath)) {
263
+ return null;
264
+ }
265
+ if (!isFullyDisabled(options)) {
266
+ if (!components) {
267
+ throw new Error(`Must provide components`);
268
+ }
269
+ }
270
+ if (sourcePath && includeExtensions && !includeExtensions.some(ext => sourcePath.endsWith(ext))) {
271
+ if (shouldPrintDebug) {
272
+ logger.info(`Ignoring file due to includeExtensions: ${sourcePath}, includeExtensions: ${includeExtensions.join(", ")}`);
273
+ }
274
+ return null;
275
+ }
169
276
  function isValidStyleKey(name, staticConfig) {
170
- if (!projectInfo) throw new Error("Tamagui extractor not loaded yet");
171
- if (platform2 === "native" && name[0] === "$" && mediaQueryConfig[name.slice(1)]) return !1;
277
+ if (!projectInfo) {
278
+ throw new Error(`Tamagui extractor not loaded yet`);
279
+ }
280
+ if (platform2 === "native" && name[0] === "$" && mediaQueryConfig[name.slice(1)]) {
281
+ return false;
282
+ }
172
283
  if (name[0] === "$") {
173
284
  const mediaName = name.slice(1);
174
- if (mediaName.startsWith("theme-") || mediaName.startsWith("platform-") || mediaName.startsWith("group-") || mediaQueryConfig[mediaName]) return !0;
285
+ if (mediaName.startsWith("theme-") || mediaName.startsWith("platform-") || mediaName.startsWith("group-")) {
286
+ return true;
287
+ }
288
+ if (mediaQueryConfig[mediaName]) {
289
+ return true;
290
+ }
175
291
  }
176
292
  return !!(staticConfig.validStyles?.[name] || pseudoDescriptors[name] ||
177
293
  // don't disable variants or else you lose many things flattening
178
294
  staticConfig.variants?.[name] || projectInfo?.tamaguiConfig?.shorthands[name]);
179
295
  }
180
- const isTargetingHTML = platform2 === "web",
181
- ogDebug = shouldPrintDebug,
182
- tm = (0, import_timer.timer)(),
183
- propsWithFileInfo = {
184
- ...options,
185
- sourcePath,
186
- allLoadedComponents: components ? [...components] : []
187
- };
188
- hasLoggedBaseInfo || (hasLoggedBaseInfo = !0, shouldPrintDebug && logger.info(["loaded components:", propsWithFileInfo.allLoadedComponents.map(comp => Object.keys(comp.nameToInfo).join(", ")).join(", ")].join(" ")), process.env.DEBUG?.startsWith("tamagui") && logger.info(["loaded:", propsWithFileInfo.allLoadedComponents.map(x => x.moduleName)].join(`
189
- `))), tm.mark("load-tamagui", !!shouldPrintDebug), isFullyDisabled(options) || tamaguiConfig?.themes || (console.error(`\u26D4\uFE0F Error: Missing "themes" in your tamagui.config file:
296
+ const isTargetingHTML = platform2 === "web";
297
+ const ogDebug = shouldPrintDebug;
298
+ const tm = (0, import_timer.timer)();
299
+ const propsWithFileInfo = {
300
+ ...options,
301
+ sourcePath,
302
+ allLoadedComponents: components ? [...components] : []
303
+ };
304
+ if (!hasLoggedBaseInfo) {
305
+ hasLoggedBaseInfo = true;
306
+ if (shouldPrintDebug) {
307
+ logger.info(["loaded components:", propsWithFileInfo.allLoadedComponents.map(comp => Object.keys(comp.nameToInfo).join(", ")).join(", ")].join(" "));
308
+ }
309
+ if (process.env.DEBUG?.startsWith("tamagui")) {
310
+ logger.info(["loaded:", propsWithFileInfo.allLoadedComponents.map(x => x.moduleName)].join("\n"));
311
+ }
312
+ }
313
+ tm.mark("load-tamagui", !!shouldPrintDebug);
314
+ if (!isFullyDisabled(options)) {
315
+ if (!tamaguiConfig?.themes) {
316
+ console.error(`\u26D4\uFE0F Error: Missing "themes" in your tamagui.config file:
190
317
 
191
318
  You may not need the compiler! Remember you can run Tamagui with no configuration at all.
192
319
 
@@ -195,68 +322,125 @@ function createExtractor({
195
322
  Or this may be due to duplicated dependency versions:
196
323
  - try out https://github.com/bmish/check-dependency-version-consistency to see if there are mis-matches.
197
324
  - or search your lockfile for mis-matches.
198
- `), console.info(" Got config:", tamaguiConfig), process.exit(0));
199
- const firstThemeName = Object.keys(tamaguiConfig?.themes || {})[0],
200
- firstTheme = tamaguiConfig?.themes[firstThemeName] || {};
201
- if (!firstTheme || typeof firstTheme != "object") {
325
+ `);
326
+ console.info(` Got config:`, tamaguiConfig);
327
+ process.exit(0);
328
+ }
329
+ }
330
+ const firstThemeName = Object.keys(tamaguiConfig?.themes || {})[0];
331
+ const firstTheme = tamaguiConfig?.themes[firstThemeName] || {};
332
+ if (!firstTheme || typeof firstTheme !== "object") {
202
333
  const err = `Missing theme ${firstThemeName}, an error occurred when importing your config`;
203
- throw console.info(err, "Got config:", tamaguiConfig), console.info("Looking for theme:", firstThemeName), new Error(err);
334
+ console.info(err, `Got config:`, tamaguiConfig);
335
+ console.info(`Looking for theme:`, firstThemeName);
336
+ throw new Error(err);
204
337
  }
205
- const proxiedTheme = proxyThemeVariables(firstTheme),
206
- themeAccessListeners = /* @__PURE__ */new Set(),
207
- defaultTheme = new Proxy(proxiedTheme, {
208
- get(target, key) {
209
- return Reflect.has(target, key) && themeAccessListeners.forEach(cb => cb(String(key))), Reflect.get(target, key);
338
+ const proxiedTheme = proxyThemeVariables(firstTheme);
339
+ const themeAccessListeners = /* @__PURE__ */new Set();
340
+ const defaultTheme = new Proxy(proxiedTheme, {
341
+ get(target, key) {
342
+ if (Reflect.has(target, key)) {
343
+ themeAccessListeners.forEach(cb => cb(String(key)));
344
+ }
345
+ return Reflect.get(target, key);
346
+ }
347
+ });
348
+ const body = fileOrPath.type === "Program" ? fileOrPath.get("body") : fileOrPath.program.body;
349
+ if (!isFullyDisabled(options)) {
350
+ if (Object.keys(components || []).length === 0) {
351
+ console.warn(`Warning: Tamagui didn't find any valid components (DEBUG=tamagui for more)`);
352
+ if (process.env.DEBUG === "tamagui") {
353
+ console.info(`components`, Object.keys(components || []), components);
210
354
  }
211
- }),
212
- body = fileOrPath.type === "Program" ? fileOrPath.get("body") : fileOrPath.program.body;
213
- isFullyDisabled(options) || Object.keys(components || []).length === 0 && (console.warn("Warning: Tamagui didn't find any valid components (DEBUG=tamagui for more)"), process.env.DEBUG === "tamagui" && console.info("components", Object.keys(components || []), components)), shouldPrintDebug === "verbose" && (logger.info(`allLoadedComponent modules ${propsWithFileInfo.allLoadedComponents.map(k => k.moduleName).join(", ")}`), logger.info(`valid import paths: ${JSON.stringify((0, import_extractHelpers.getValidComponentsPaths)(propsWithFileInfo))}`));
214
- let doesUseValidImport = !1,
215
- hasImportedTheme = !1;
355
+ }
356
+ }
357
+ if (shouldPrintDebug === "verbose") {
358
+ logger.info(`allLoadedComponent modules ${propsWithFileInfo.allLoadedComponents.map(k => k.moduleName).join(", ")}`);
359
+ logger.info(`valid import paths: ${JSON.stringify((0, import_extractHelpers.getValidComponentsPaths)(propsWithFileInfo))}`);
360
+ }
361
+ let doesUseValidImport = false;
362
+ let hasImportedTheme = false;
216
363
  const importDeclarations = [];
217
364
  for (const bodyPath of body) {
218
365
  if (bodyPath.type !== "ImportDeclaration") continue;
219
- const node = "node" in bodyPath ? bodyPath.node : bodyPath,
220
- moduleName = node.source.value,
221
- valid = (0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName);
222
- if (valid && importDeclarations.push(node), shouldPrintDebug === "verbose" && logger.info(` - import via ${moduleName} ${valid}`), extractStyledDefinitions && valid && node.specifiers.some(specifier => specifier.local.name === "styled")) {
223
- doesUseValidImport = !0;
224
- break;
366
+ const node = "node" in bodyPath ? bodyPath.node : bodyPath;
367
+ const moduleName = node.source.value;
368
+ const valid = (0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName);
369
+ if (valid) {
370
+ importDeclarations.push(node);
371
+ }
372
+ if (shouldPrintDebug === "verbose") {
373
+ logger.info(` - import via ${moduleName} ${valid}`);
374
+ }
375
+ if (extractStyledDefinitions && enableDynamicEvaluation) {
376
+ if (node.specifiers.some(specifier => specifier.local.name === "styled")) {
377
+ doesUseValidImport = true;
378
+ }
225
379
  }
226
380
  if (valid) {
227
- const names = node.specifiers.map(specifier => specifier.local.name),
228
- isValidComponent = names.some(name => !!(0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName, name));
229
- if (shouldPrintDebug === "verbose" && logger.info(` - import ${isValidComponent ? "\u2705" : "\u21E3"} - ${names.join(", ")} via package '${moduleName}' - (valid: ${JSON.stringify((0, import_extractHelpers.getValidComponentsPaths)(propsWithFileInfo))})`), isValidComponent) {
230
- doesUseValidImport = !0;
381
+ const names = node.specifiers.map(specifier => specifier.local.name);
382
+ const isValidComponent = names.some(name => Boolean((0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName, name)));
383
+ if (shouldPrintDebug === "verbose") {
384
+ logger.info(` - import ${isValidComponent ? "\u2705" : "\u21E3"} - ${names.join(", ")} via package '${moduleName}' - (valid: ${JSON.stringify((0, import_extractHelpers.getValidComponentsPaths)(propsWithFileInfo))})`);
385
+ }
386
+ if (isValidComponent) {
387
+ doesUseValidImport = true;
388
+ if (!(extractStyledDefinitions && enableDynamicEvaluation)) break;
389
+ }
390
+ }
391
+ }
392
+ if (shouldPrintDebug) {
393
+ logger.info(`${JSON.stringify({
394
+ doesUseValidImport,
395
+ hasImportedTheme
396
+ }, null, 2)}
397
+ `);
398
+ }
399
+ if (!doesUseValidImport && extractStyledDefinitions && enableDynamicEvaluation && sourcePath) {
400
+ for (const bodyPath of body) {
401
+ if (bodyPath.type !== "ImportDeclaration") continue;
402
+ const node = "node" in bodyPath ? bodyPath.node : bodyPath;
403
+ const moduleName = node.source.value;
404
+ const resolved = resolveImportPath(sourcePath, moduleName);
405
+ if (!resolved) continue;
406
+ if (dynamicComponentCache.has(resolved)) {
407
+ doesUseValidImport = true;
408
+ break;
409
+ }
410
+ if (mightHaveStyledComponents(resolved)) {
411
+ doesUseValidImport = true;
231
412
  break;
232
413
  }
233
414
  }
234
415
  }
235
- if (shouldPrintDebug && logger.info(`${JSON.stringify({
236
- doesUseValidImport,
237
- hasImportedTheme
238
- }, null, 2)}
239
- `), !doesUseValidImport) return null;
416
+ if (!doesUseValidImport) {
417
+ return null;
418
+ }
240
419
  function getValidImportedComponent(componentName) {
241
420
  const importDeclaration = importDeclarations.find(dec => dec.specifiers.some(spec => spec.local.name === componentName));
242
- return importDeclaration ? (0, import_extractHelpers.getValidImport)(propsWithFileInfo, importDeclaration.source.value, componentName) : null;
421
+ if (!importDeclaration) {
422
+ return null;
423
+ }
424
+ return (0, import_extractHelpers.getValidImport)(propsWithFileInfo, importDeclaration.source.value, componentName);
243
425
  }
244
426
  tm.mark("import-check", !!shouldPrintDebug);
245
- let couldntParse = !1;
246
- const modifiedComponents = /* @__PURE__ */new Set(),
247
- bindingCache = {},
248
- callTraverse = a => fileOrPath.type === "File" ? (0, import_traverse.default)(fileOrPath, a) : fileOrPath.traverse(a),
249
- shouldDisableExtraction = disableExtraction === !0 || Array.isArray(disableExtraction) && disableExtraction.includes(sourcePath);
427
+ let couldntParse = false;
428
+ const modifiedComponents = /* @__PURE__ */new Set();
429
+ const bindingCache = {};
430
+ const callTraverse = a => {
431
+ return fileOrPath.type === "File" ? (0, import_traverse.default)(fileOrPath, a) : fileOrPath.traverse(a);
432
+ };
433
+ const shouldDisableExtraction = disableExtraction === true || Array.isArray(disableExtraction) && disableExtraction.includes(sourcePath);
250
434
  let programPath = null;
251
435
  const res = {
252
- styled: 0,
253
- flattened: 0,
254
- optimized: 0,
255
- modified: 0,
256
- found: 0
257
- },
258
- version = `${Math.random()}`;
259
- return callTraverse({
436
+ styled: 0,
437
+ flattened: 0,
438
+ optimized: 0,
439
+ modified: 0,
440
+ found: 0
441
+ };
442
+ const version = `${Math.random()}`;
443
+ callTraverse({
260
444
  // @ts-ignore
261
445
  Program: {
262
446
  enter(path) {
@@ -265,55 +449,89 @@ function createExtractor({
265
449
  },
266
450
  // styled() calls
267
451
  CallExpression(path) {
268
- if (disable || shouldDisableExtraction || extractStyledDefinitions === !1 || !t.isIdentifier(path.node.callee) || path.node.callee.name !== "styled") return;
269
- const variableName = t.isVariableDeclarator(path.parent) && t.isIdentifier(path.parent.id) ? path.parent.id.name : "unknown",
270
- parentNode = path.node.arguments[0];
271
- if (!t.isIdentifier(parentNode)) return;
272
- const parentName = parentNode.name,
273
- definition = path.node.arguments[1];
274
- if (!parentName || !definition || !t.isObjectExpression(definition)) return;
275
- let Component = getValidImportedComponent(variableName);
452
+ if (disable || shouldDisableExtraction || extractStyledDefinitions === false) {
453
+ return;
454
+ }
455
+ if (!t.isIdentifier(path.node.callee) || path.node.callee.name !== "styled") {
456
+ return;
457
+ }
458
+ const variableName = t.isVariableDeclarator(path.parent) && t.isIdentifier(path.parent.id) ? path.parent.id.name : "unknown";
459
+ if (shouldPrintDebug) {
460
+ logger.info(` [styled] Found styled(${variableName})`);
461
+ }
462
+ const parentNode = path.node.arguments[0];
463
+ if (!t.isIdentifier(parentNode)) {
464
+ return;
465
+ }
466
+ const parentName = parentNode.name;
467
+ const definition = path.node.arguments[1];
468
+ if (!parentName || !definition || !t.isObjectExpression(definition)) {
469
+ return;
470
+ }
471
+ let Component = getValidImportedComponent(parentName) || getValidImportedComponent(variableName);
276
472
  if (!Component) {
277
- if (enableDynamicEvaluation !== !0) return;
473
+ if (!enableDynamicEvaluation) {
474
+ return;
475
+ }
278
476
  try {
279
- shouldPrintDebug && logger.info(`Unknown component: ${variableName} = styled(${parentName}) attempting dynamic load: ${sourcePath}`);
477
+ if (shouldPrintDebug) {
478
+ logger.info(`Unknown component: ${variableName} = styled(${parentName}) attempting dynamic load: ${sourcePath}`);
479
+ }
280
480
  const out2 = (0, import_loadTamagui.loadTamaguiSync)({
281
- forceExports: !0,
481
+ forceExports: true,
282
482
  components: [sourcePath],
283
483
  cacheKey: version
284
484
  });
285
485
  if (!out2?.components) {
286
- shouldPrintDebug && logger.info(`Couldn't load, got ${out2}`);
486
+ if (shouldPrintDebug) {
487
+ logger.info(`Couldn't load, got ${out2}`);
488
+ }
287
489
  return;
288
490
  }
289
- if (propsWithFileInfo.allLoadedComponents = [...propsWithFileInfo.allLoadedComponents, ...out2.components], Component = out2.components.flatMap(x => x.nameToInfo[variableName] ?? [])[0], !out2.cached) {
491
+ propsWithFileInfo.allLoadedComponents = [...propsWithFileInfo.allLoadedComponents, ...out2.components];
492
+ Component = out2.components.flatMap(x => x.nameToInfo[variableName] ?? [])[0];
493
+ if (!out2.cached) {
290
494
  const foundNames = out2.components?.map(x => Object.keys(x.nameToInfo).join(", ")).join(", ").trim();
291
- foundNames && (0, import_cli_color.colorLog)(import_cli_color.Color.FgYellow, ` | Tamagui found dynamic components: ${foundNames}`);
495
+ if (foundNames) {
496
+ (0, import_cli_color.colorLog)(import_cli_color.Color.FgYellow, ` | Tamagui found dynamic components: ${foundNames}`);
497
+ }
498
+ }
499
+ } catch (err) {
500
+ if (shouldPrintDebug) {
501
+ logger.info(`skip optimize styled(${variableName}), unable to pre-process (DEBUG=tamagui for more)`);
292
502
  }
293
- } catch {
294
- shouldPrintDebug && logger.info(`skip optimize styled(${variableName}), unable to pre-process (DEBUG=tamagui for more)`);
295
503
  }
296
504
  }
297
505
  if (!Component) {
298
- shouldPrintDebug && logger.info(" No component found");
506
+ if (shouldPrintDebug) {
507
+ logger.info(` No component found`);
508
+ }
299
509
  return;
300
510
  }
301
511
  const componentSkipProps = /* @__PURE__ */new Set([...(Component.staticConfig.inlineWhenUnflattened || []), ...(Component.staticConfig.inlineProps || []),
302
- // for now skip variants, will return to them
303
- "variants", "defaultVariants",
304
- // skip fontFamily its basically a "variant", important for theme use to be value always
305
- "fontFamily", "name", "focusStyle", "focusVisibleStyle", "focusWithinStyle", "disabledStyle", "hoverStyle", "pressStyle"]),
306
- skipped = /* @__PURE__ */new Set(),
307
- styles = {},
308
- staticNamespace = (0, import_getStaticBindingsForScope.getStaticBindingsForScope)(path.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug),
309
- attemptEval = evaluateVars ? (0, import_createEvaluator.createEvaluator)({
310
- props: propsWithFileInfo,
311
- staticNamespace,
312
- sourcePath,
313
- shouldPrintDebug
314
- }) : import_evaluateAstNode.evaluateAstNode,
315
- attemptEvalSafe = (0, import_createEvaluator.createSafeEvaluator)(attemptEval);
512
+ // for now skip variants, will return to them
513
+ "variants", "defaultVariants",
514
+ // skip fontFamily its basically a "variant", important for theme use to be value always
515
+ "fontFamily", "name", "focusStyle", "focusVisibleStyle", "focusWithinStyle", "disabledStyle", "hoverStyle", "pressStyle"]);
516
+ const skipped = /* @__PURE__ */new Set();
517
+ const styles = {};
518
+ const staticDefaultProps = {};
519
+ const staticNamespace = (0, import_getStaticBindingsForScope.getStaticBindingsForScope)(path.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug);
520
+ const attemptEval = !evaluateVars ? import_evaluateAstNode.evaluateAstNode : (0, import_createEvaluator.createEvaluator)({
521
+ props: propsWithFileInfo,
522
+ staticNamespace,
523
+ sourcePath,
524
+ shouldPrintDebug
525
+ });
526
+ const attemptEvalSafe = (0, import_createEvaluator.createSafeEvaluator)(attemptEval);
316
527
  for (const property of definition.properties) {
528
+ if (t.isObjectProperty(property) && (t.isIdentifier(property.key) || t.isStringLiteral(property.key))) {
529
+ const key = t.isIdentifier(property.key) ? property.key.name : property.key.value;
530
+ const defaultPropValue = attemptEvalSafe(property.value);
531
+ if (defaultPropValue !== import_constants.FAILED_EVAL) {
532
+ staticDefaultProps[key] = defaultPropValue;
533
+ }
534
+ }
317
535
  if (!t.isObjectProperty(property) || !t.isIdentifier(property.key) || !isValidStyleKey(property.key.name, Component.staticConfig) ||
318
536
  // TODO make pseudos and variants work
319
537
  // skip pseudos
@@ -324,95 +542,247 @@ function createExtractor({
324
542
  continue;
325
543
  }
326
544
  const out2 = attemptEvalSafe(property.value);
327
- out2 === import_constants.FAILED_EVAL ? skipped.add(property) : styles[property.key.name] = out2;
545
+ if (out2 === import_constants.FAILED_EVAL) {
546
+ skipped.add(property);
547
+ } else {
548
+ styles[property.key.name] = out2;
549
+ }
550
+ }
551
+ const out = getSplitStyles(styles, Component.staticConfig, defaultTheme, "", componentState, styleProps, void 0, void 0, void 0, void 0, false, shouldPrintDebug);
552
+ const classNames = {
553
+ ...out.classNames
554
+ };
555
+ if (shouldPrintDebug) {
556
+ logger.info([`Extracted styled(${variableName})
557
+ `, JSON.stringify(styles, null, 2), "\n classNames:", JSON.stringify(classNames, null, 2), "\n rulesToInsert:", out.rulesToInsert].join(" "));
328
558
  }
329
- const out = getSplitStyles(styles, Component.staticConfig, defaultTheme, "", componentState, styleProps, void 0, void 0, void 0, void 0, !1, shouldPrintDebug),
330
- classNames = {
331
- ...out.classNames
559
+ if (out.rulesToInsert) {
560
+ for (const key in out.rulesToInsert) {
561
+ const styleObject = out.rulesToInsert[key];
562
+ onStyledDefinitionRule?.(styleObject[import_web.StyleObjectIdentifier], styleObject[import_web.StyleObjectRules]);
563
+ }
564
+ }
565
+ res.styled++;
566
+ if (extractStyledDefinitions && enableDynamicEvaluation && Component) {
567
+ const dynamicStaticConfig = {
568
+ ...Component.staticConfig,
569
+ defaultProps: {
570
+ ...Component.staticConfig.defaultProps,
571
+ ...staticDefaultProps
572
+ }
332
573
  };
333
- if (shouldPrintDebug && logger.info([`Extracted styled(${variableName})
334
- `, JSON.stringify(styles, null, 2), `
335
- classNames:`, JSON.stringify(classNames, null, 2), `
336
- rulesToInsert:`, out.rulesToInsert].join(" ")), definition.properties = definition.properties.map(prop => {
337
- if (skipped.has(prop) || !t.isObjectProperty(prop) || !t.isIdentifier(prop.key)) return prop;
338
- const key = prop.key.name,
339
- value = classNames[key];
340
- return value ? t.objectProperty(t.stringLiteral(key), t.stringLiteral(value)) : prop;
341
- }), out.rulesToInsert) for (const key in out.rulesToInsert) {
342
- const styleObject = out.rulesToInsert[key];
343
- onStyledDefinitionRule?.(styleObject[import_web.StyleObjectIdentifier], styleObject[import_web.StyleObjectRules]);
574
+ propsWithFileInfo.allLoadedComponents.push({
575
+ moduleName: "",
576
+ nameToInfo: {
577
+ [variableName]: {
578
+ staticConfig: dynamicStaticConfig
579
+ }
580
+ }
581
+ });
582
+ if (sourcePath) {
583
+ let existing = dynamicComponentCache.get(sourcePath);
584
+ if (!existing) {
585
+ existing = {
586
+ moduleName: sourcePath,
587
+ nameToInfo: {}
588
+ };
589
+ dynamicComponentCache.set(sourcePath, existing);
590
+ }
591
+ existing.nameToInfo[variableName] = {
592
+ staticConfig: dynamicStaticConfig
593
+ };
594
+ }
595
+ }
596
+ if (shouldPrintDebug) {
597
+ logger.info(`Extracted styled(${variableName})`);
344
598
  }
345
- res.styled++, shouldPrintDebug && logger.info(`Extracted styled(${variableName})`);
346
599
  },
347
600
  JSXElement(traversePath) {
348
601
  tm.mark("jsx-element", !!shouldPrintDebug);
349
- const node = traversePath.node.openingElement,
350
- ogAttributes = node.attributes.map(attr => ({
351
- ...attr
352
- })),
353
- componentName = (0, import_extractHelpers.findComponentName)(traversePath.scope),
354
- closingElement = traversePath.node.closingElement;
602
+ const node = traversePath.node.openingElement;
603
+ const ogAttributes = node.attributes.map(attr => ({
604
+ ...attr
605
+ }));
606
+ const componentName = (0, import_extractHelpers.findComponentName)(traversePath.scope);
607
+ const closingElement = traversePath.node.closingElement;
355
608
  if (closingElement && t.isJSXMemberExpression(closingElement?.name) || !t.isJSXIdentifier(node.name)) {
356
- shouldPrintDebug && logger.info(" skip non-identifier element");
609
+ if (shouldPrintDebug) {
610
+ logger.info(` skip non-identifier element`);
611
+ }
357
612
  return;
358
613
  }
359
614
  const binding = traversePath.scope.getBinding(node.name.name);
360
615
  let moduleName = "";
361
- if (binding && t.isImportDeclaration(binding.path.parent) && (moduleName = binding.path.parent.source.value, !(0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName, binding.identifier.name))) {
362
- shouldPrintDebug && logger.info(` - Binding in component ${componentName} not valid import: "${binding.identifier.name}" isn't in ${moduleName}
616
+ let dynamicComponent = null;
617
+ if (binding) {
618
+ if (t.isImportDeclaration(binding.path.parent)) {
619
+ moduleName = binding.path.parent.source.value;
620
+ if (!(0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName, binding.identifier.name)) {
621
+ if (enableDynamicEvaluation && sourcePath) {
622
+ const resolved = resolveImportPath(sourcePath, moduleName);
623
+ if (resolved) {
624
+ const cached = dynamicComponentCache.get(resolved);
625
+ if (cached?.nameToInfo[binding.identifier.name]) {
626
+ dynamicComponent = cached.nameToInfo[binding.identifier.name];
627
+ } else if (!dynamicLoadingInProgress.has(resolved) && mightHaveStyledComponents(resolved)) {
628
+ dynamicLoadingInProgress.add(resolved);
629
+ try {
630
+ const out = (0, import_loadTamagui.loadTamaguiSync)({
631
+ forceExports: true,
632
+ components: [resolved]
633
+ });
634
+ if (out?.components) {
635
+ for (const comp of out.components) {
636
+ let existing = dynamicComponentCache.get(resolved);
637
+ if (!existing) {
638
+ existing = {
639
+ moduleName: resolved,
640
+ nameToInfo: {}
641
+ };
642
+ dynamicComponentCache.set(resolved, existing);
643
+ }
644
+ Object.assign(existing.nameToInfo, comp.nameToInfo);
645
+ propsWithFileInfo.allLoadedComponents.push({
646
+ moduleName: resolved,
647
+ nameToInfo: comp.nameToInfo
648
+ });
649
+ }
650
+ const cachedNow = dynamicComponentCache.get(resolved);
651
+ if (cachedNow?.nameToInfo[binding.identifier.name]) {
652
+ dynamicComponent = cachedNow.nameToInfo[binding.identifier.name];
653
+ }
654
+ }
655
+ } catch (err) {
656
+ if (shouldPrintDebug) {
657
+ logger.info(` - Failed to dynamically load ${resolved}: ${err}`);
658
+ }
659
+ } finally {
660
+ dynamicLoadingInProgress.delete(resolved);
661
+ }
662
+ }
663
+ }
664
+ }
665
+ if (!dynamicComponent) {
666
+ if (shouldPrintDebug) {
667
+ logger.info(` - Binding in component ${componentName} not valid import: "${binding.identifier.name}" isn't in ${moduleName}
363
668
  `);
364
- return;
669
+ }
670
+ return;
671
+ }
672
+ }
673
+ }
365
674
  }
366
- const component = (0, import_extractHelpers.getValidComponent)(propsWithFileInfo, moduleName, node.name.name);
675
+ const component = dynamicComponent || (0, import_extractHelpers.getValidComponent)(propsWithFileInfo, moduleName, node.name.name);
367
676
  if (!component || !component.staticConfig) {
368
- shouldPrintDebug && logger.info(`
677
+ if (shouldPrintDebug) {
678
+ logger.info(`
369
679
  - No Tamagui conf for: ${node.name.name}
370
680
  `);
681
+ }
371
682
  return;
372
683
  }
373
684
  const originalNodeName = node.name.name;
374
685
  res.found++;
375
- const filePath = `./${(0, import_node_path.relative)(process.cwd(), sourcePath)}`,
376
- lineNumbers = node.loc ? node.loc.start.line + (node.loc.start.line !== node.loc.end.line ? `-${node.loc.end.line}` : "") : "",
377
- codePosition = `${filePath}:${lineNumbers}`,
378
- debugPropValue = node.attributes.filter(n => t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && n.name.name === "debug").map(n => n.value === null ? !0 : t.isStringLiteral(n.value) ? n.value.value : !1)[0];
379
- if (debugPropValue && (shouldPrintDebug = debugPropValue), shouldPrintDebug && (logger.info(`\x1B[33m\x1B[0m ${componentName} | ${codePosition} -------------------`), logger.info(["\x1B[1m", "\x1B[32m", `<${originalNodeName} />`, disableDebugAttr ? "" : "\u{1F41B}"].join(" "))), platform2 !== "native" && shouldAddDebugProp && !disableDebugAttr && (res.modified++, node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-is"), t.stringLiteral(node.name.name))), componentName && node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-in"), t.stringLiteral(componentName))), node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-at"), t.stringLiteral(`${(0, import_node_path.basename)(filePath)}:${lineNumbers}`)))), shouldDisableExtraction) {
380
- shouldPrintDebug === "verbose" && logger.info(` \u274C Extraction disabled: ${JSON.stringify(disableExtraction)}
686
+ const filePath = `./${(0, import_node_path.relative)(process.cwd(), sourcePath)}`;
687
+ const lineNumbers = node.loc ? node.loc.start.line + (node.loc.start.line !== node.loc.end.line ? `-${node.loc.end.line}` : "") : "";
688
+ const codePosition = `${filePath}:${lineNumbers}`;
689
+ const debugPropValue = node.attributes.filter(n => t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && n.name.name === "debug").map(n => {
690
+ if (n.value === null) return true;
691
+ if (t.isStringLiteral(n.value)) return n.value.value;
692
+ return false;
693
+ })[0];
694
+ if (debugPropValue) {
695
+ shouldPrintDebug = debugPropValue;
696
+ }
697
+ if (shouldPrintDebug) {
698
+ logger.info(`\x1B[33m\x1B[0m ${componentName} | ${codePosition} -------------------`);
699
+ logger.info(["\x1B[1m", "\x1B[32m", `<${originalNodeName} />`, disableDebugAttr ? "" : "\u{1F41B}"].join(" "));
700
+ }
701
+ if (platform2 !== "native") {
702
+ if (shouldAddDebugProp && !disableDebugAttr) {
703
+ res.modified++;
704
+ node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-is"), t.stringLiteral(node.name.name)));
705
+ if (componentName) {
706
+ node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-in"), t.stringLiteral(componentName)));
707
+ }
708
+ node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-at"), t.stringLiteral(`${(0, import_node_path.basename)(filePath)}:${lineNumbers}`)));
709
+ }
710
+ }
711
+ if (shouldDisableExtraction) {
712
+ if (shouldPrintDebug === "verbose") {
713
+ logger.info(` \u274C Extraction disabled: ${JSON.stringify(disableExtraction)}
381
714
  `);
715
+ }
382
716
  return;
383
717
  }
384
718
  try {
385
719
  let evaluateAttribute = function (path) {
386
- const attribute = path.node,
387
- attr = {
388
- type: "attr",
389
- value: attribute
390
- };
720
+ const attribute = path.node;
721
+ const attr = {
722
+ type: "attr",
723
+ value: attribute
724
+ };
391
725
  if (t.isJSXSpreadAttribute(attribute)) {
392
- const arg = attribute.argument,
393
- conditional = t.isConditionalExpression(arg) ?
394
- // <YStack {...isSmall ? { color: 'red } : { color: 'blue }}
395
- [arg.test, arg.consequent, arg.alternate] : t.isLogicalExpression(arg) && arg.operator === "&&" ?
396
- // <YStack {...isSmall && { color: 'red }}
397
- [arg.left, arg.right, null] : null;
726
+ const arg = attribute.argument;
727
+ const conditional = t.isConditionalExpression(arg) ?
728
+ // <YStack {...isSmall ? { color: 'red } : { color: 'blue }}
729
+ [arg.test, arg.consequent, arg.alternate] : t.isLogicalExpression(arg) && arg.operator === "&&" ?
730
+ // <YStack {...isSmall && { color: 'red }}
731
+ [arg.left, arg.right, null] : null;
398
732
  if (conditional) {
399
733
  const [test, alt, cons] = conditional;
400
- if (!test) throw new Error("no test");
401
- return [alt, cons].some(side => side && !isStaticObject(side)) ? (shouldPrintDebug && logger.info(`not extractable ${alt} ${cons}`), attr) : [...(flattenNestedTernaries(test, alt) || []), ...(cons && flattenNestedTernaries(t.unaryExpression("!", test), cons) || [])].map(ternary => ({
734
+ if (!test) throw new Error(`no test`);
735
+ if ([alt, cons].some(side => side && !isStaticObject(side))) {
736
+ if (shouldPrintDebug) {
737
+ logger.info(`not extractable ${alt} ${cons}`);
738
+ }
739
+ return attr;
740
+ }
741
+ return [...(flattenNestedTernaries(test, alt) || []), ...(cons && flattenNestedTernaries(t.unaryExpression("!", test), cons) || [])].map(ternary => ({
402
742
  type: "ternary",
403
743
  value: ternary
404
744
  }));
405
745
  }
406
746
  }
407
- if (t.isJSXSpreadAttribute(attribute) || !attribute.name || typeof attribute.name.name != "string") return shouldPrintDebug && logger.info(" ! inlining, spread attr"), inlined.set(`${Math.random()}`, "spread"), attr;
747
+ if (t.isJSXSpreadAttribute(attribute) || !attribute.name || typeof attribute.name.name !== "string") {
748
+ if (shouldPrintDebug) {
749
+ logger.info(" ! inlining, spread attr");
750
+ }
751
+ inlined.set(`${Math.random()}`, "spread");
752
+ return attr;
753
+ }
408
754
  const name = attribute.name.name;
409
- if (name === "style") return shouldDeopt = !0, null;
410
- if (excludeProps?.has(name)) return shouldPrintDebug && logger.info([" excluding prop", name].join(" ")), null;
411
- if (inlineProps.has(name)) return inlined.set(name, name), shouldPrintDebug && logger.info([" ! inlining, inline prop", name].join(" ")), attr;
412
- if (UNTOUCHED_PROPS[name]) return attr;
413
- if (INLINE_EXTRACTABLE[name]) return inlined.set(name, INLINE_EXTRACTABLE[name]), attr;
414
- if (name.startsWith("data-") || name.startsWith("aria-") || import_validHTMLAttributes.validHTMLAttributes[name]) return attr;
415
- if ((name === "enterStyle" || name === "exitStyle") && t.isJSXExpressionContainer(attribute?.value)) return shouldDeopt = !0, attr;
755
+ if (name === "style") {
756
+ shouldDeopt = true;
757
+ return null;
758
+ }
759
+ if (excludeProps?.has(name)) {
760
+ if (shouldPrintDebug) {
761
+ logger.info([" excluding prop", name].join(" "));
762
+ }
763
+ return null;
764
+ }
765
+ if (inlineProps.has(name)) {
766
+ inlined.set(name, name);
767
+ if (shouldPrintDebug) {
768
+ logger.info([" ! inlining, inline prop", name].join(" "));
769
+ }
770
+ return attr;
771
+ }
772
+ if (UNTOUCHED_PROPS[name]) {
773
+ return attr;
774
+ }
775
+ if (INLINE_EXTRACTABLE[name]) {
776
+ inlined.set(name, INLINE_EXTRACTABLE[name]);
777
+ return attr;
778
+ }
779
+ if (name.startsWith("data-") || name.startsWith("aria-") || import_validHTMLAttributes.validHTMLAttributes[name]) {
780
+ return attr;
781
+ }
782
+ if ((name === "enterStyle" || name === "exitStyle") && t.isJSXExpressionContainer(attribute?.value)) {
783
+ shouldDeopt = true;
784
+ return attr;
785
+ }
416
786
  if (name[0] === "$" && t.isJSXExpressionContainer(attribute?.value)) {
417
787
  const shortname = name.slice(1);
418
788
  if (mediaQueryConfig[shortname]) {
@@ -421,66 +791,161 @@ function createExtractor({
421
791
  const ternaries2 = flattenNestedTernaries(t.stringLiteral(shortname), expression, {
422
792
  inlineMediaQuery: shortname
423
793
  });
424
- if (ternaries2) return ternaries2.map(value2 => ({
425
- type: "ternary",
426
- value: value2
427
- }));
794
+ if (ternaries2) {
795
+ return ternaries2.map(value2 => ({
796
+ type: "ternary",
797
+ value: value2
798
+ }));
799
+ }
428
800
  }
429
801
  }
430
802
  }
431
- const [value, valuePath] = t.isJSXExpressionContainer(attribute?.value) ? [attribute.value.expression, path.get("value")] : [attribute.value, path.get("value")],
432
- remove = () => {
433
- Array.isArray(valuePath) ? valuePath.map(p => p.remove()) : valuePath.remove();
434
- };
435
- if (name === "ref") return shouldPrintDebug && logger.info([" ! inlining, ref", name].join(" ")), inlined.set("ref", "ref"), attr;
436
- if (name === "render") return (!value || value.type !== "StringLiteral") && (shouldPrintDebug && logger.info(" ! deopt on render prop (not a string literal)"), shouldDeopt = !0), {
437
- type: "attr",
438
- value: path.node
803
+ const [value, valuePath] = (() => {
804
+ if (t.isJSXExpressionContainer(attribute?.value)) {
805
+ return [attribute.value.expression, path.get("value")];
806
+ }
807
+ return [attribute.value, path.get("value")];
808
+ })();
809
+ const remove = () => {
810
+ Array.isArray(valuePath) ? valuePath.map(p => p.remove()) : valuePath.remove();
439
811
  };
440
- if (disableExtractVariables === !0 && value && value.type === "StringLiteral" && value.value[0] === "$") return shouldPrintDebug && logger.info([` ! inlining, native disable extract: ${name} =`, value.value].join(" ")), inlined.set(name, !0), attr;
441
- if (name === "theme") return inlined.set("theme", attr.value), attr;
812
+ if (name === "ref") {
813
+ if (shouldPrintDebug) {
814
+ logger.info([" ! inlining, ref", name].join(" "));
815
+ }
816
+ inlined.set("ref", "ref");
817
+ return attr;
818
+ }
819
+ if (name === "render") {
820
+ if (!value || value.type !== "StringLiteral") {
821
+ if (shouldPrintDebug) {
822
+ logger.info(` ! deopt on render prop (not a string literal)`);
823
+ }
824
+ shouldDeopt = true;
825
+ }
826
+ return {
827
+ type: "attr",
828
+ value: path.node
829
+ };
830
+ }
831
+ if (disableExtractVariables === true) {
832
+ if (value) {
833
+ if (value.type === "StringLiteral" && value.value[0] === "$") {
834
+ if (shouldPrintDebug) {
835
+ logger.info([` ! inlining, native disable extract: ${name} =`, value.value].join(" "));
836
+ }
837
+ inlined.set(name, true);
838
+ return attr;
839
+ }
840
+ }
841
+ }
842
+ if (name === "theme") {
843
+ inlined.set("theme", attr.value);
844
+ return attr;
845
+ }
442
846
  const styleValue = attemptEvalSafe(value);
443
847
  if (!variants[name] && !isValidStyleKey(name, staticConfig)) {
444
848
  let out = null;
445
- propMapper(name, styleValue, propMapperStyleState, !1, (key, val) => {
446
- out ||= {}, out[key] = val;
447
- }), out && isTargetingHTML && (out = reactNativeWebInternals.createDOMProps(isTextView ? "span" : "div", out), delete out.className);
448
- let didInline = !1;
849
+ propMapper(name, styleValue, propMapperStyleState, false, (key, val) => {
850
+ out ||= {};
851
+ out[key] = val;
852
+ });
853
+ if (out) {
854
+ if (isTargetingHTML) {
855
+ out = reactNativeWebInternals.createDOMProps(isTextView ? "span" : "div", out);
856
+ delete out.className;
857
+ }
858
+ }
859
+ let didInline = false;
449
860
  const attributes = Object.keys(out).map(key => {
450
861
  const val = out[key];
451
- return isValidStyleKey(key, staticConfig) ? {
452
- type: "style",
453
- value: {
454
- [key]: styleValue
455
- },
456
- name: key,
457
- attr: path.node
458
- } : import_validHTMLAttributes.validHTMLAttributes[key] || key.startsWith("aria-") || key.startsWith("data-") ||
862
+ const isStyle = isValidStyleKey(key, staticConfig);
863
+ if (isStyle) {
864
+ return {
865
+ type: "style",
866
+ value: {
867
+ [key]: styleValue
868
+ },
869
+ name: key,
870
+ attr: path.node
871
+ };
872
+ }
873
+ if (import_validHTMLAttributes.validHTMLAttributes[key] || key.startsWith("aria-") || key.startsWith("data-") ||
459
874
  // this is debug stuff added by vite / new jsx transform
460
- key === "__source" || key === "__self" ? attr : (shouldPrintDebug && logger.info(" ! inlining, non-static " + key), didInline = !0, inlined.set(key, val), val);
875
+ key === "__source" || key === "__self") {
876
+ return attr;
877
+ }
878
+ if (shouldPrintDebug) {
879
+ logger.info(" ! inlining, non-static " + key);
880
+ }
881
+ didInline = true;
882
+ inlined.set(key, val);
883
+ return val;
461
884
  });
462
- return didInline ? (shouldPrintDebug && logger.info(` bailing flattening due to attributes ${attributes.map(x => x.toString())}`), attr) : attributes;
885
+ if (didInline) {
886
+ if (shouldPrintDebug) {
887
+ logger.info(` bailing flattening due to attributes ${attributes.map(x => x.toString())}`);
888
+ }
889
+ return attr;
890
+ }
891
+ return attributes;
463
892
  }
464
893
  if (styleValue !== import_constants.FAILED_EVAL) {
465
- if (inlineWhenUnflattened.has(name) && (inlineWhenUnflattenedOGVals[name] = {
466
- styleValue,
467
- attr
468
- }), isValidStyleKey(name, staticConfig)) {
894
+ if (inlineWhenUnflattened.has(name)) {
895
+ inlineWhenUnflattenedOGVals[name] = {
896
+ styleValue,
897
+ attr
898
+ };
899
+ }
900
+ if (isValidStyleKey(name, staticConfig)) {
469
901
  if (name[0] === "$") {
470
- if (name.startsWith("$theme-") || name.startsWith("$group-")) return shouldPrintDebug && logger.info(` ! not flattening media-like style: ${name}`), inlined.set(name, !0), attr;
902
+ if (name.startsWith("$theme-") || name.startsWith("$group-")) {
903
+ if (shouldPrintDebug) {
904
+ logger.info(` ! not flattening media-like style: ${name}`);
905
+ }
906
+ inlined.set(name, true);
907
+ return attr;
908
+ }
471
909
  if (name.startsWith("$platform-")) {
472
910
  const platformName = name.slice(10);
473
- return (platformName === platform2 || platformName === "native" && platform2 === "native" || platformName === "web" && platform2 === "web") && typeof styleValue == "object" ? (shouldPrintDebug && logger.info(` flattening $platform-${platformName}: ${JSON.stringify(styleValue)}`), Object.entries(styleValue).map(([key, val]) => ({
474
- type: "style",
475
- value: {
476
- [key]: val
477
- },
478
- name: key,
479
- attr: path.node
480
- }))) : (shouldPrintDebug && logger.info(` ! skipping non-matching platform style: ${name}`), []);
911
+ const isMatchingPlatform = platformName === platform2 || platformName === "native" && platform2 === "native" || platformName === "web" && platform2 === "web";
912
+ if (isMatchingPlatform && typeof styleValue === "object") {
913
+ if (shouldPrintDebug) {
914
+ logger.info(` flattening $platform-${platformName}: ${JSON.stringify(styleValue)}`);
915
+ }
916
+ return Object.entries(styleValue).map(([key, val]) => ({
917
+ type: "style",
918
+ value: {
919
+ [key]: val
920
+ },
921
+ name: key,
922
+ attr: path.node
923
+ }));
924
+ } else {
925
+ if (platform2 === "native" && nativeOnlyPlatforms.has(platformName)) {
926
+ if (shouldPrintDebug) {
927
+ logger.info(` ! keeping platform-specific style for runtime evaluation: ${name}`);
928
+ }
929
+ inlined.set(name, true);
930
+ return attr;
931
+ }
932
+ if (shouldPrintDebug) {
933
+ logger.info(` ! skipping non-matching platform style: ${name}`);
934
+ }
935
+ return [];
936
+ }
481
937
  }
482
938
  }
483
- return shouldPrintDebug && logger.info(` style: ${name} = ${JSON.stringify(styleValue)}`), name in defaultProps || hasSetOptimized || (res.optimized++, hasSetOptimized = !0), {
939
+ if (shouldPrintDebug) {
940
+ logger.info(` style: ${name} = ${JSON.stringify(styleValue)}`);
941
+ }
942
+ if (!(name in defaultProps)) {
943
+ if (!hasSetOptimized) {
944
+ res.optimized++;
945
+ hasSetOptimized = true;
946
+ }
947
+ }
948
+ return {
484
949
  type: "style",
485
950
  value: {
486
951
  [name]: styleValue
@@ -489,18 +954,27 @@ function createExtractor({
489
954
  attr: path.node
490
955
  };
491
956
  }
492
- return variants[name] && variantValues.set(name, styleValue), inlined.set(name, !0), attr;
957
+ if (variants[name]) {
958
+ variantValues.set(name, styleValue);
959
+ }
960
+ inlined.set(name, true);
961
+ return attr;
493
962
  }
494
963
  if (t.isBinaryExpression(value)) {
495
- shouldPrintDebug && logger.info(` binary expression ${name} = ${value}`);
964
+ if (shouldPrintDebug) {
965
+ logger.info(` binary expression ${name} = ${value}`);
966
+ }
496
967
  const {
497
- operator,
498
- left,
499
- right
500
- } = value,
501
- lVal = attemptEvalSafe(left),
502
- rVal = attemptEvalSafe(right);
503
- if (shouldPrintDebug && logger.info(` evalBinaryExpression lVal ${String(lVal)}, rVal ${String(rVal)}`), lVal !== import_constants.FAILED_EVAL && t.isConditionalExpression(right)) {
968
+ operator,
969
+ left,
970
+ right
971
+ } = value;
972
+ const lVal = attemptEvalSafe(left);
973
+ const rVal = attemptEvalSafe(right);
974
+ if (shouldPrintDebug) {
975
+ logger.info(` evalBinaryExpression lVal ${String(lVal)}, rVal ${String(rVal)}`);
976
+ }
977
+ if (lVal !== import_constants.FAILED_EVAL && t.isConditionalExpression(right)) {
504
978
  const ternary = addBinaryConditional(operator, left, right);
505
979
  if (ternary) return ternary;
506
980
  }
@@ -508,24 +982,45 @@ function createExtractor({
508
982
  const ternary = addBinaryConditional(operator, right, left);
509
983
  if (ternary) return ternary;
510
984
  }
511
- return shouldPrintDebug && logger.info(" evalBinaryExpression cant extract"), inlined.set(name, !0), attr;
985
+ if (shouldPrintDebug) {
986
+ logger.info(` evalBinaryExpression cant extract`);
987
+ }
988
+ inlined.set(name, true);
989
+ return attr;
512
990
  }
513
991
  const staticConditional = getStaticConditional(value);
514
- if (staticConditional) return shouldPrintDebug === "verbose" && logger.info(` static conditional ${name} ${value}`), {
515
- type: "ternary",
516
- value: staticConditional
517
- };
992
+ if (staticConditional) {
993
+ if (shouldPrintDebug === "verbose") {
994
+ logger.info(` static conditional ${name} ${value}`);
995
+ }
996
+ return {
997
+ type: "ternary",
998
+ value: staticConditional
999
+ };
1000
+ }
518
1001
  const staticLogical = getStaticLogical(value);
519
- if (staticLogical) return shouldPrintDebug === "verbose" && logger.info(` static ternary ${name} = ${value}`), {
520
- type: "ternary",
521
- value: staticLogical
522
- };
523
- return inlined.set(name, !0), shouldPrintDebug && logger.info(` ! inline no match ${name} ${value}`), attr;
1002
+ if (staticLogical) {
1003
+ if (shouldPrintDebug === "verbose") {
1004
+ logger.info(` static ternary ${name} = ${value}`);
1005
+ }
1006
+ return {
1007
+ type: "ternary",
1008
+ value: staticLogical
1009
+ };
1010
+ }
1011
+ inlined.set(name, true);
1012
+ if (shouldPrintDebug) {
1013
+ logger.info(` ! inline no match ${name} ${value}`);
1014
+ }
1015
+ return attr;
524
1016
  function addBinaryConditional(operator, staticExpr, cond) {
525
1017
  if (getStaticConditional(cond)) {
526
- const alt = attemptEval(t.binaryExpression(operator, staticExpr, cond.alternate)),
527
- cons = attemptEval(t.binaryExpression(operator, staticExpr, cond.consequent));
528
- return shouldPrintDebug && logger.info([" binaryConditional", cond.test, cons, alt].join(" ")), {
1018
+ const alt = attemptEval(t.binaryExpression(operator, staticExpr, cond.alternate));
1019
+ const cons = attemptEval(t.binaryExpression(operator, staticExpr, cond.consequent));
1020
+ if (shouldPrintDebug) {
1021
+ logger.info([" binaryConditional", cond.test, cons, alt].join(" "));
1022
+ }
1023
+ return {
529
1024
  type: "ternary",
530
1025
  value: {
531
1026
  test: cond.test,
@@ -542,57 +1037,84 @@ function createExtractor({
542
1037
  return null;
543
1038
  }
544
1039
  function getStaticConditional(value2) {
545
- if (t.isConditionalExpression(value2)) try {
546
- const aVal = attemptEval(value2.alternate),
547
- cVal = attemptEval(value2.consequent);
548
- if (shouldPrintDebug) {
549
- const type = value2.test.type;
550
- logger.info([" static ternary", type, cVal, aVal].join(" "));
551
- }
552
- return {
553
- test: value2.test,
554
- remove,
555
- consequent: {
556
- [name]: cVal
557
- },
558
- alternate: {
559
- [name]: aVal
1040
+ if (t.isConditionalExpression(value2)) {
1041
+ try {
1042
+ const aVal = attemptEval(value2.alternate);
1043
+ const cVal = attemptEval(value2.consequent);
1044
+ if (shouldPrintDebug) {
1045
+ const type = value2.test.type;
1046
+ logger.info([" static ternary", type, cVal, aVal].join(" "));
560
1047
  }
561
- };
562
- } catch (err) {
563
- shouldPrintDebug && logger.info([" cant eval ternary", err.message].join(" "));
1048
+ return {
1049
+ test: value2.test,
1050
+ remove,
1051
+ consequent: {
1052
+ [name]: cVal
1053
+ },
1054
+ alternate: {
1055
+ [name]: aVal
1056
+ }
1057
+ };
1058
+ } catch (err) {
1059
+ if (shouldPrintDebug) {
1060
+ logger.info([" cant eval ternary", err.message].join(" "));
1061
+ }
1062
+ }
564
1063
  }
565
1064
  return null;
566
1065
  }
567
1066
  function getStaticLogical(value2) {
568
- if (t.isLogicalExpression(value2) && value2.operator === "&&") try {
569
- const val = attemptEval(value2.right);
570
- return shouldPrintDebug && logger.info([" staticLogical", value2.left, name, val].join(" ")), {
571
- test: value2.left,
572
- remove,
573
- consequent: {
574
- [name]: val
575
- },
576
- alternate: null
577
- };
578
- } catch (err) {
579
- shouldPrintDebug && logger.info([" cant static eval logical", err].join(" "));
1067
+ if (t.isLogicalExpression(value2)) {
1068
+ if (value2.operator === "&&") {
1069
+ try {
1070
+ const val = attemptEval(value2.right);
1071
+ if (shouldPrintDebug) {
1072
+ logger.info([" staticLogical", value2.left, name, val].join(" "));
1073
+ }
1074
+ return {
1075
+ test: value2.left,
1076
+ remove,
1077
+ consequent: {
1078
+ [name]: val
1079
+ },
1080
+ alternate: null
1081
+ };
1082
+ } catch (err) {
1083
+ if (shouldPrintDebug) {
1084
+ logger.info([" cant static eval logical", err].join(" "));
1085
+ }
1086
+ }
1087
+ }
580
1088
  }
581
1089
  return null;
582
1090
  }
583
1091
  },
584
1092
  isStaticObject = function (obj) {
585
1093
  return t.isObjectExpression(obj) && obj.properties.every(prop => {
586
- if (!t.isObjectProperty(prop)) return !1;
587
- const propName = prop.key.name;
588
- return !isValidStyleKey(propName, staticConfig) && propName !== "render" ? (shouldPrintDebug && logger.info([" not a valid style prop!", propName].join(" ")), !1) : !0;
1094
+ if (!t.isObjectProperty(prop)) {
1095
+ return false;
1096
+ }
1097
+ const propName = prop.key["name"];
1098
+ if (!isValidStyleKey(propName, staticConfig) && propName !== "render") {
1099
+ if (shouldPrintDebug) {
1100
+ logger.info([" not a valid style prop!", propName].join(" "));
1101
+ }
1102
+ return false;
1103
+ }
1104
+ return true;
589
1105
  });
590
1106
  },
591
1107
  flattenNestedTernaries = function (test, side, ternaryPartial = {}) {
592
- if (!side) return null;
593
- if (!isStaticObject(side)) throw new Error("not extractable");
1108
+ if (!side) {
1109
+ return null;
1110
+ }
1111
+ if (!isStaticObject(side)) {
1112
+ throw new Error("not extractable");
1113
+ }
594
1114
  return side.properties.flatMap(property => {
595
- if (!t.isObjectProperty(property)) throw new Error("expected object property");
1115
+ if (!t.isObjectProperty(property)) {
1116
+ throw new Error("expected object property");
1117
+ }
596
1118
  if (t.isConditionalExpression(property.value)) {
597
1119
  const [truthy, falsy] = [t.objectExpression([t.objectProperty(property.key, property.value.consequent)]), t.objectExpression([t.objectProperty(property.key, property.value.alternate)])].map(x => attemptEval(x));
598
1120
  return [createTernary({
@@ -609,8 +1131,8 @@ function createExtractor({
609
1131
  remove() {}
610
1132
  })];
611
1133
  }
612
- const obj = t.objectExpression([t.objectProperty(property.key, property.value)]),
613
- consequent = attemptEval(obj);
1134
+ const obj = t.objectExpression([t.objectProperty(property.key, property.value)]);
1135
+ const consequent = attemptEval(obj);
614
1136
  return createTernary({
615
1137
  remove() {},
616
1138
  ...ternaryPartial,
@@ -621,271 +1143,457 @@ function createExtractor({
621
1143
  });
622
1144
  },
623
1145
  mergeToEnd = function (obj, key, val) {
624
- key in obj && delete obj[key], obj[key] = val;
1146
+ if (key in obj) {
1147
+ delete obj[key];
1148
+ }
1149
+ obj[key] = val;
625
1150
  },
626
1151
  normalizeStyleWithoutVariants = function (style) {
627
1152
  let res2 = {};
628
- for (const key in style) if (staticConfig.variants && key in staticConfig.variants) mergeToEnd(res2, key, style[key]);else {
629
- const expanded = normalizeStyle({
630
- [key]: style[key]
631
- }, !0);
632
- for (const key2 in expanded) mergeToEnd(res2, key2, expanded[key2]);
1153
+ for (const key in style) {
1154
+ if (staticConfig.variants && key in staticConfig.variants) {
1155
+ mergeToEnd(res2, key, style[key]);
1156
+ } else {
1157
+ const expanded = normalizeStyle({
1158
+ [key]: style[key]
1159
+ }, true);
1160
+ for (const key2 in expanded) {
1161
+ mergeToEnd(res2, key2, expanded[key2]);
1162
+ }
1163
+ }
633
1164
  }
634
1165
  return res2;
635
1166
  },
636
1167
  mergeStyles = function (prev2, next) {
637
- for (const key in next) pseudoDescriptors[key] ? (prev2[key] = prev2[key] || {}, Object.assign(prev2[key], next[key])) : mergeToEnd(prev2, key, next[key]);
1168
+ for (const key in next) {
1169
+ if (pseudoDescriptors[key]) {
1170
+ prev2[key] = prev2[key] || {};
1171
+ Object.assign(prev2[key], next[key]);
1172
+ } else {
1173
+ mergeToEnd(prev2, key, next[key]);
1174
+ }
1175
+ }
638
1176
  };
639
1177
  const {
640
- staticConfig
641
- } = component,
642
- defaultProps = {
643
- ...getDefaultProps(staticConfig)
644
- },
645
- variants = staticConfig.variants || {},
646
- isTextView = staticConfig.isText || !1,
647
- validStyles = staticConfig?.validStyles ?? {};
648
- if (process.env.NODE_ENV === "production" && isTextView) return;
1178
+ staticConfig
1179
+ } = component;
1180
+ const defaultProps = {
1181
+ ...getDefaultProps(staticConfig)
1182
+ };
1183
+ const variants = staticConfig.variants || {};
1184
+ const isTextView = staticConfig.isText || false;
1185
+ const validStyles = staticConfig?.validStyles ?? {};
649
1186
  let tagName = defaultProps.render ?? (isTextView ? "span" : "div");
650
1187
  traversePath.get("openingElement").get("attributes").forEach(path => {
651
1188
  const attr = path.node;
652
- if (t.isJSXSpreadAttribute(attr) || attr.name.name !== "render") return;
1189
+ if (t.isJSXSpreadAttribute(attr)) return;
1190
+ if (attr.name.name !== "render") return;
653
1191
  const val = attr.value;
654
- t.isStringLiteral(val) && (tagName = val.value);
655
- }), shouldPrintDebug === "verbose" && console.info(` Start tag ${tagName}`);
1192
+ if (!t.isStringLiteral(val)) return;
1193
+ tagName = val.value;
1194
+ });
1195
+ if (shouldPrintDebug === "verbose") {
1196
+ console.info(` Start tag ${tagName}`);
1197
+ }
656
1198
  const flatNodeName = getFlattenedNode?.({
657
- isTextView,
658
- tag: tagName
659
- }),
660
- inlineProps = /* @__PURE__ */new Set([
661
- // adding some always inline props
662
- ...(restProps.inlineProps || []), ...(staticConfig.inlineProps || [])]),
663
- deoptProps = /* @__PURE__ */new Set([
664
- // always de-opt animation these
665
- "animation", "animateOnly", "animatePresence", "disableOptimization", ...(isTargetingHTML ? [] : ["pressStyle", "focusStyle", "focusVisibleStyle", "focusWithinStyle", "disabledStyle"]),
666
- // when using a non-CSS driver, de-opt on enterStyle/exitStyle
667
- ...(tamaguiConfig?.animations.isReactNative ? ["enterStyle", "exitStyle"] : [])]),
668
- inlineWhenUnflattened = new Set(staticConfig.inlineWhenUnflattened || []),
669
- staticNamespace = (0, import_getStaticBindingsForScope.getStaticBindingsForScope)(traversePath.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug),
670
- attemptEval = evaluateVars ? (0, import_createEvaluator.createEvaluator)({
671
- props: propsWithFileInfo,
672
- staticNamespace,
673
- sourcePath,
674
- traversePath,
675
- shouldPrintDebug
676
- }) : import_evaluateAstNode.evaluateAstNode,
677
- attemptEvalSafe = (0, import_createEvaluator.createSafeEvaluator)(attemptEval);
678
- if (shouldPrintDebug && logger.info(` staticNamespace ${Object.keys(staticNamespace).join(", ")}`), couldntParse) return;
1199
+ isTextView,
1200
+ tag: tagName
1201
+ });
1202
+ const inlineProps = /* @__PURE__ */new Set([
1203
+ // adding some always inline props
1204
+ ...(restProps.inlineProps || []), ...(staticConfig.inlineProps || [])]);
1205
+ const deoptProps = /* @__PURE__ */new Set([
1206
+ // always de-opt animation these
1207
+ "animation", "animateOnly", "animatePresence", "disableOptimization", ...(!isTargetingHTML ? ["pressStyle", "focusStyle", "focusVisibleStyle", "focusWithinStyle", "disabledStyle"] : []),
1208
+ // when using a non-CSS driver, de-opt on enterStyle/exitStyle
1209
+ ...(tamaguiConfig?.animations.isReactNative ? ["enterStyle", "exitStyle"] : [])]);
1210
+ const inlineWhenUnflattened = new Set(staticConfig.inlineWhenUnflattened || []);
1211
+ const staticNamespace = (0, import_getStaticBindingsForScope.getStaticBindingsForScope)(traversePath.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug);
1212
+ const attemptEval = !evaluateVars ? import_evaluateAstNode.evaluateAstNode : (0, import_createEvaluator.createEvaluator)({
1213
+ props: propsWithFileInfo,
1214
+ staticNamespace,
1215
+ sourcePath,
1216
+ traversePath,
1217
+ shouldPrintDebug
1218
+ });
1219
+ const attemptEvalSafe = (0, import_createEvaluator.createSafeEvaluator)(attemptEval);
1220
+ if (shouldPrintDebug) {
1221
+ logger.info(` staticNamespace ${Object.keys(staticNamespace).join(", ")}`);
1222
+ }
1223
+ if (couldntParse) {
1224
+ return;
1225
+ }
679
1226
  tm.mark("jsx-element-flattened", !!shouldPrintDebug);
680
- let attrs = [],
681
- shouldDeopt = !1;
682
- const inlined = /* @__PURE__ */new Map(),
683
- variantValues = /* @__PURE__ */new Map();
684
- let hasSetOptimized = !1;
685
- const inlineWhenUnflattenedOGVals = {},
686
- propMapperStyleState = {
687
- staticConfig,
688
- usedKeys: {},
689
- classNames: {},
690
- style: {},
691
- theme: defaultTheme,
692
- viewProps: defaultProps,
693
- conf: tamaguiConfig,
694
- props: defaultProps,
695
- componentState,
696
- styleProps: {
697
- ...styleProps,
698
- resolveValues: "auto"
699
- },
700
- debug: shouldPrintDebug
701
- };
702
- if (attrs = traversePath.get("openingElement").get("attributes").flatMap(path => {
703
- if (!shouldDeopt) try {
1227
+ let attrs = [];
1228
+ let shouldDeopt = false;
1229
+ const inlined = /* @__PURE__ */new Map();
1230
+ const variantValues = /* @__PURE__ */new Map();
1231
+ let hasSetOptimized = false;
1232
+ const inlineWhenUnflattenedOGVals = {};
1233
+ const propMapperStyleState = {
1234
+ staticConfig,
1235
+ usedKeys: {},
1236
+ classNames: {},
1237
+ style: {},
1238
+ theme: defaultTheme,
1239
+ viewProps: defaultProps,
1240
+ conf: tamaguiConfig,
1241
+ props: defaultProps,
1242
+ componentState,
1243
+ styleProps: {
1244
+ ...styleProps,
1245
+ resolveValues: "auto"
1246
+ },
1247
+ debug: shouldPrintDebug
1248
+ };
1249
+ attrs = traversePath.get("openingElement").get("attributes").flatMap(path => {
1250
+ if (shouldDeopt) {
1251
+ return;
1252
+ }
1253
+ try {
704
1254
  const res2 = evaluateAttribute(path);
705
- return res2 || path.remove(), res2;
1255
+ if (!res2) {
1256
+ path.remove();
1257
+ }
1258
+ return res2;
706
1259
  } catch (err) {
707
- return shouldPrintDebug && (logger.info(["Recoverable error extracting attribute", err.message, shouldPrintDebug === "verbose" ? err.stack : ""].join(" ")), shouldPrintDebug === "verbose" && logger.info(`node ${path.node?.type}`)), inlined.set(`${Math.random()}`, "spread"), {
1260
+ if (shouldPrintDebug) {
1261
+ logger.info(["Recoverable error extracting attribute", err.message, shouldPrintDebug === "verbose" ? err.stack : ""].join(" "));
1262
+ if (shouldPrintDebug === "verbose") {
1263
+ logger.info(`node ${path.node?.type}`);
1264
+ }
1265
+ }
1266
+ inlined.set(`${Math.random()}`, "spread");
1267
+ return {
708
1268
  type: "attr",
709
1269
  value: path.node
710
1270
  };
711
1271
  }
712
- }).flat(4).filter(import_extractHelpers.isPresent), shouldPrintDebug && logger.info([` - attrs (before):
713
- `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" ")), couldntParse || shouldDeopt) {
714
- shouldPrintDebug && logger.info([" avoid optimizing:", {
715
- couldntParse,
716
- shouldDeopt
717
- }].join(" ")), node.attributes = ogAttributes;
1272
+ }).flat(4).filter(import_extractHelpers.isPresent);
1273
+ if (shouldPrintDebug) {
1274
+ logger.info([" - attrs (before):\n", (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" "));
1275
+ }
1276
+ if (couldntParse || shouldDeopt) {
1277
+ if (shouldPrintDebug) {
1278
+ logger.info([` avoid optimizing:`, {
1279
+ couldntParse,
1280
+ shouldDeopt
1281
+ }].join(" "));
1282
+ }
1283
+ node.attributes = ogAttributes;
718
1284
  return;
719
1285
  }
720
1286
  const parentFn = (0, import_findTopmostFunction.findTopmostFunction)(traversePath);
721
- parentFn && modifiedComponents.add(parentFn);
722
- const hasSpread = attrs.some(x => x.type === "attr" && t.isJSXSpreadAttribute(x.value)),
723
- hasOnlyStringChildren = !hasSpread && (node.selfClosing || traversePath.node.children && traversePath.node.children.every(x => x.type === "JSXText"));
1287
+ if (parentFn) {
1288
+ modifiedComponents.add(parentFn);
1289
+ }
1290
+ const hasSpread = attrs.some(x => x.type === "attr" && t.isJSXSpreadAttribute(x.value));
1291
+ const hasOnlyStringChildren = !hasSpread && (node.selfClosing || traversePath.node.children && traversePath.node.children.every(x => x.type === "JSXText"));
724
1292
  let themeVal = inlined.get("theme");
725
- platform2 !== "native" && inlined.delete("theme");
1293
+ if (platform2 !== "native") {
1294
+ inlined.delete("theme");
1295
+ }
726
1296
  for (const [key] of inlined) {
727
1297
  const isStaticObjectVariant = staticConfig.variants?.[key] && variantValues.has(key);
728
- (INLINE_EXTRACTABLE[key] || isStaticObjectVariant) && inlined.delete(key);
1298
+ if (INLINE_EXTRACTABLE[key] || isStaticObjectVariant) {
1299
+ inlined.delete(key);
1300
+ }
729
1301
  }
730
1302
  const canFlattenProps = inlined.size === 0;
731
- let shouldFlatten = !!(flatNodeName && !shouldDeopt && canFlattenProps && !hasSpread && !staticConfig.isStyledHOC && !staticConfig.isHOC && !staticConfig.isReactNative && staticConfig.neverFlatten !== !0 && (staticConfig.neverFlatten !== "jsx" || hasOnlyStringChildren));
1303
+ let shouldFlatten = Boolean(flatNodeName && !shouldDeopt && canFlattenProps && !hasSpread && !staticConfig.isStyledHOC && !staticConfig.isHOC && !staticConfig.isReactNative && staticConfig.neverFlatten !== true && (staticConfig.neverFlatten === "jsx" ? hasOnlyStringChildren : true));
732
1304
  const usedThemeKeys = /* @__PURE__ */new Set();
733
- if (themeAccessListeners.add(key => {
734
- disableExtractVariables && (usedThemeKeys.add(key), shouldFlatten = !1, shouldPrintDebug === "verbose" && logger.info([" ! accessing theme key, avoid flatten", key].join(" ")));
735
- }), !shouldFlatten) {
736
- shouldPrintDebug && logger.info(`Deopting ${JSON.stringify({
737
- shouldFlatten,
738
- shouldDeopt,
739
- canFlattenProps,
740
- hasSpread,
741
- neverFlatten: staticConfig.neverFlatten
742
- })}`), node.attributes = ogAttributes;
1305
+ themeAccessListeners.add(key => {
1306
+ if (disableExtractVariables) {
1307
+ usedThemeKeys.add(key);
1308
+ shouldFlatten = false;
1309
+ if (shouldPrintDebug === "verbose") {
1310
+ logger.info([" ! accessing theme key, avoid flatten", key].join(" "));
1311
+ }
1312
+ }
1313
+ });
1314
+ if (!shouldFlatten) {
1315
+ if (shouldPrintDebug) {
1316
+ logger.info(`Deopting ${JSON.stringify({
1317
+ shouldFlatten,
1318
+ shouldDeopt,
1319
+ canFlattenProps,
1320
+ hasSpread,
1321
+ neverFlatten: staticConfig.neverFlatten
1322
+ })}`);
1323
+ }
1324
+ node.attributes = ogAttributes;
743
1325
  return;
744
1326
  }
745
- let skipMap = !1;
1327
+ let skipMap = false;
746
1328
  const defaultStyleAttrs = Object.keys(defaultProps).flatMap(key => {
747
1329
  if (skipMap) return [];
748
1330
  const value = defaultProps[key];
749
- if (key === "theme" && !themeVal) return platform2 === "native" && (shouldFlatten = !1, skipMap = !0, inlined.set("theme", {
750
- value: t.stringLiteral(value)
751
- })), themeVal = {
752
- value: t.stringLiteral(value)
753
- }, [];
754
- if (!isValidStyleKey(key, staticConfig)) return [];
1331
+ if (key === "theme" && !themeVal) {
1332
+ if (platform2 === "native") {
1333
+ shouldFlatten = false;
1334
+ skipMap = true;
1335
+ inlined.set("theme", {
1336
+ value: t.stringLiteral(value)
1337
+ });
1338
+ }
1339
+ themeVal = {
1340
+ value: t.stringLiteral(value)
1341
+ };
1342
+ return [];
1343
+ }
1344
+ if (!isValidStyleKey(key, staticConfig)) {
1345
+ return [];
1346
+ }
755
1347
  const name = tamaguiConfig?.shorthands[key] || key;
756
1348
  if (value === void 0) {
757
- logger.warn(`\u26A0\uFE0F Error evaluating default style for component, prop ${key} ${value}`), shouldDeopt = !0;
1349
+ logger.warn(`\u26A0\uFE0F Error evaluating default style for component, prop ${key} ${value}`);
1350
+ shouldDeopt = true;
758
1351
  return;
759
1352
  }
760
- return name[0] === "$" && mediaQueryConfig[name.slice(1)] ? (defaultProps[key] = void 0, evaluateAttribute({
761
- node: t.jsxAttribute(t.jsxIdentifier(name), t.jsxExpressionContainer(t.objectExpression(Object.keys(value).filter(k => typeof value[k] < "u").map(k => t.objectProperty(t.identifier(k), (0, import_literalToAst.literalToAst)(value[k]))))))
762
- })) : {
1353
+ if (name[0] === "$" && mediaQueryConfig[name.slice(1)]) {
1354
+ defaultProps[key] = void 0;
1355
+ return evaluateAttribute({
1356
+ node: t.jsxAttribute(t.jsxIdentifier(name), t.jsxExpressionContainer(t.objectExpression(Object.keys(value).filter(k => {
1357
+ return typeof value[k] !== "undefined";
1358
+ }).map(k => {
1359
+ return t.objectProperty(t.identifier(k), (0, import_literalToAst.literalToAst)(value[k]));
1360
+ }))))
1361
+ });
1362
+ }
1363
+ const attr = {
763
1364
  type: "style",
764
1365
  name,
765
1366
  value: {
766
1367
  [name]: value
767
1368
  }
768
1369
  };
1370
+ return attr;
769
1371
  });
770
- skipMap || defaultStyleAttrs.length && (attrs = [...defaultStyleAttrs, ...attrs]);
1372
+ if (!skipMap) {
1373
+ if (defaultStyleAttrs.length) {
1374
+ attrs = [...defaultStyleAttrs, ...attrs];
1375
+ }
1376
+ }
771
1377
  let ternaries = [];
772
1378
  attrs = attrs.reduce((out, cur) => {
773
1379
  const next = attrs[attrs.indexOf(cur) + 1];
774
- if (cur.type === "ternary" && ternaries.push(cur.value), (!next || next.type !== "ternary") && ternaries.length) {
1380
+ if (cur.type === "ternary") {
1381
+ ternaries.push(cur.value);
1382
+ }
1383
+ if ((!next || next.type !== "ternary") && ternaries.length) {
775
1384
  const normalized = (0, import_normalizeTernaries.normalizeTernaries)(ternaries).map(({
776
1385
  alternate,
777
1386
  consequent,
778
1387
  ...rest
779
- }) => ({
780
- type: "ternary",
781
- value: {
782
- ...rest,
783
- alternate: alternate || null,
784
- consequent: consequent || null
785
- }
786
- }));
1388
+ }) => {
1389
+ return {
1390
+ type: "ternary",
1391
+ value: {
1392
+ ...rest,
1393
+ alternate: alternate || null,
1394
+ consequent: consequent || null
1395
+ }
1396
+ };
1397
+ });
787
1398
  try {
788
1399
  return [...out, ...normalized];
789
1400
  } finally {
790
- shouldPrintDebug && logger.info(` normalizeTernaries (${ternaries.length} => ${normalized.length})`), ternaries = [];
1401
+ if (shouldPrintDebug) {
1402
+ logger.info(` normalizeTernaries (${ternaries.length} => ${normalized.length})`);
1403
+ }
1404
+ ternaries = [];
791
1405
  }
792
1406
  }
793
- return cur.type === "ternary" || out.push(cur), out;
794
- }, []).flat(), themeVal && (programPath ? (shouldPrintDebug && logger.info([" - wrapping theme", themeVal].join(" ")), attrs = attrs.filter(x => !(x.type === "attr" && t.isJSXAttribute(x.value) && x.value.name.name === "theme")), hasImportedTheme || (hasImportedTheme = !0, programPath.node.body.push(t.importDeclaration([t.importSpecifier(t.identifier("_TamaguiTheme"), t.identifier("Theme"))], t.stringLiteral("@tamagui/web")))), traversePath.replaceWith(t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier("_TamaguiTheme"), [t.jsxAttribute(t.jsxIdentifier("name"), themeVal.value)]), t.jsxClosingElement(t.jsxIdentifier("_TamaguiTheme")), [traversePath.node]))) : console.warn(`No program path found, avoiding importing flattening / importing theme in ${sourcePath}`)), shouldPrintDebug && logger.info([` - attrs (flattened):
795
- `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" "));
1407
+ if (cur.type === "ternary") {
1408
+ return out;
1409
+ }
1410
+ out.push(cur);
1411
+ return out;
1412
+ }, []).flat();
1413
+ if (themeVal) {
1414
+ if (!programPath) {
1415
+ console.warn(`No program path found, avoiding importing flattening / importing theme in ${sourcePath}`);
1416
+ } else {
1417
+ if (shouldPrintDebug) {
1418
+ logger.info([" - wrapping theme", themeVal].join(" "));
1419
+ }
1420
+ attrs = attrs.filter(x => !(x.type === "attr" && t.isJSXAttribute(x.value) && x.value.name.name === "theme"));
1421
+ if (!hasImportedTheme) {
1422
+ hasImportedTheme = true;
1423
+ programPath.node.body.push(t.importDeclaration([t.importSpecifier(t.identifier("_TamaguiTheme"), t.identifier("Theme"))], t.stringLiteral("@tamagui/web")));
1424
+ }
1425
+ traversePath.replaceWith(t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier("_TamaguiTheme"), [t.jsxAttribute(t.jsxIdentifier("name"), themeVal.value)]), t.jsxClosingElement(t.jsxIdentifier("_TamaguiTheme")), [traversePath.node]));
1426
+ }
1427
+ }
1428
+ if (shouldPrintDebug) {
1429
+ logger.info([" - attrs (flattened): \n", (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" "));
1430
+ }
796
1431
  let foundStaticProps = {};
797
1432
  for (const key in attrs) {
798
1433
  const cur = attrs[key];
799
1434
  if (cur.type === "style") {
800
1435
  const expanded = normalizeStyleWithoutVariants(cur.value);
801
- for (const key2 in expanded) mergeToEnd(foundStaticProps, key2, expanded[key2]);
1436
+ for (const key2 in expanded) {
1437
+ mergeToEnd(foundStaticProps, key2, expanded[key2]);
1438
+ }
802
1439
  continue;
803
1440
  }
804
1441
  if (cur.type === "attr") {
805
- if (t.isJSXSpreadAttribute(cur.value) || !t.isJSXIdentifier(cur.value.name)) continue;
806
- const key2 = cur.value.name.name,
807
- value = attemptEvalSafe(cur.value.value || t.booleanLiteral(!0));
808
- value !== import_constants.FAILED_EVAL && mergeToEnd(foundStaticProps, key2, value);
1442
+ if (t.isJSXSpreadAttribute(cur.value)) {
1443
+ continue;
1444
+ }
1445
+ if (!t.isJSXIdentifier(cur.value.name)) {
1446
+ continue;
1447
+ }
1448
+ const key2 = cur.value.name.name;
1449
+ const value = attemptEvalSafe(cur.value.value || t.booleanLiteral(true));
1450
+ if (value !== import_constants.FAILED_EVAL) {
1451
+ mergeToEnd(foundStaticProps, key2, value);
1452
+ }
809
1453
  }
810
1454
  }
811
1455
  const completeProps = {};
812
- for (const key in defaultProps) key in foundStaticProps || (completeProps[key] = defaultProps[key]);
813
- for (const key in foundStaticProps) completeProps[key] = foundStaticProps[key];
1456
+ for (const key in defaultProps) {
1457
+ if (!(key in foundStaticProps)) {
1458
+ completeProps[key] = defaultProps[key];
1459
+ }
1460
+ }
1461
+ for (const key in foundStaticProps) {
1462
+ completeProps[key] = foundStaticProps[key];
1463
+ }
814
1464
  attrs = attrs.reduce((acc, cur) => {
815
1465
  if (!cur) return acc;
816
- if (cur.type === "attr" && !t.isJSXSpreadAttribute(cur.value) && shouldFlatten) {
817
- const name = cur.value.name.name;
818
- if (typeof name == "string") {
819
- if (name === "render") return acc;
820
- if (variants[name] && variantValues.has(name)) {
821
- const styleState = {
822
- ...propMapperStyleState,
823
- props: completeProps
824
- };
825
- let out = {};
826
- if (propMapper(name, variantValues.get(name), styleState, !1, (key2, val) => {
827
- out[key2] = val;
828
- }), out && isTargetingHTML) {
829
- const cn = out.className;
830
- out = reactNativeWebInternals.createDOMProps(isTextView ? "span" : "div", out), out.className = cn;
1466
+ if (cur.type === "attr" && !t.isJSXSpreadAttribute(cur.value)) {
1467
+ if (shouldFlatten) {
1468
+ const name = cur.value.name.name;
1469
+ if (typeof name === "string") {
1470
+ if (name === "render") {
1471
+ return acc;
831
1472
  }
832
- shouldPrintDebug && logger.info([" - expanded variant", name, out].join(" "));
833
- for (const key2 in out) {
834
- const value2 = out[key2];
835
- isValidStyleKey(key2, staticConfig) ? acc.push({
836
- type: "style",
837
- value: {
838
- [key2]: value2
839
- },
840
- name: key2,
841
- attr: cur.value
842
- }) : acc.push({
843
- type: "attr",
844
- value: t.jsxAttribute(t.jsxIdentifier(key2), t.jsxExpressionContainer(typeof value2 == "string" ? t.stringLiteral(value2) : (0, import_literalToAst.literalToAst)(value2)))
1473
+ if (variants[name] && variantValues.has(name)) {
1474
+ const styleState = {
1475
+ ...propMapperStyleState,
1476
+ props: completeProps
1477
+ };
1478
+ let out = {};
1479
+ propMapper(name, variantValues.get(name), styleState, false, (key2, val) => {
1480
+ out[key2] = val;
845
1481
  });
1482
+ if (out && isTargetingHTML) {
1483
+ const cn = out.className;
1484
+ out = reactNativeWebInternals.createDOMProps(isTextView ? "span" : "div", out);
1485
+ out.className = cn;
1486
+ }
1487
+ if (shouldPrintDebug) {
1488
+ logger.info([" - expanded variant", name, out].join(" "));
1489
+ }
1490
+ for (const key2 in out) {
1491
+ const value2 = out[key2];
1492
+ if (isValidStyleKey(key2, staticConfig)) {
1493
+ acc.push({
1494
+ type: "style",
1495
+ value: {
1496
+ [key2]: value2
1497
+ },
1498
+ name: key2,
1499
+ attr: cur.value
1500
+ });
1501
+ } else {
1502
+ acc.push({
1503
+ type: "attr",
1504
+ value: t.jsxAttribute(t.jsxIdentifier(key2), t.jsxExpressionContainer(typeof value2 === "string" ? t.stringLiteral(value2) : (0, import_literalToAst.literalToAst)(value2)))
1505
+ });
1506
+ }
1507
+ }
846
1508
  }
847
1509
  }
848
1510
  }
849
1511
  }
850
- if (cur.type !== "style") return acc.push(cur), acc;
1512
+ if (cur.type !== "style") {
1513
+ acc.push(cur);
1514
+ return acc;
1515
+ }
851
1516
  let key = Object.keys(cur.value)[0];
852
- const value = cur.value[key],
853
- fullKey = tamaguiConfig?.shorthands[key];
854
- return fullKey && (cur.value = {
855
- [fullKey]: value
856
- }, key = fullKey), disableExtractVariables && value[0] === "$" && (usedThemeKeys.has(key) || usedThemeKeys.has(fullKey)) ? (shouldPrintDebug && logger.info([` keeping variable inline: ${key} =`, value].join(" ")), acc.push({
857
- type: "attr",
858
- value: t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(t.stringLiteral(value)))
859
- }), acc) : (acc.push(cur), acc);
860
- }, []), tm.mark("jsx-element-expanded", !!shouldPrintDebug), shouldPrintDebug && logger.info([` - attrs (expanded):
861
- `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" "));
1517
+ const value = cur.value[key];
1518
+ const fullKey = tamaguiConfig?.shorthands[key];
1519
+ if (fullKey) {
1520
+ cur.value = {
1521
+ [fullKey]: value
1522
+ };
1523
+ key = fullKey;
1524
+ }
1525
+ if (disableExtractVariables) {
1526
+ if (value[0] === "$" && (usedThemeKeys.has(key) || usedThemeKeys.has(fullKey))) {
1527
+ if (shouldPrintDebug) {
1528
+ logger.info([` keeping variable inline: ${key} =`, value].join(" "));
1529
+ }
1530
+ acc.push({
1531
+ type: "attr",
1532
+ value: t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(t.stringLiteral(value)))
1533
+ });
1534
+ return acc;
1535
+ }
1536
+ }
1537
+ acc.push(cur);
1538
+ return acc;
1539
+ }, []);
1540
+ tm.mark("jsx-element-expanded", !!shouldPrintDebug);
1541
+ if (shouldPrintDebug) {
1542
+ logger.info([" - attrs (expanded): \n", (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" "));
1543
+ }
862
1544
  let prev = null;
863
- const getProps = (props, includeProps = !1, debugName = "") => {
864
- if (!props) return shouldPrintDebug && logger.info([" getProps() no props"].join(" ")), {};
865
- if (excludeProps?.size) for (const key in props) excludeProps.has(key) && (shouldPrintDebug && logger.info([" delete excluded", key].join(" ")), delete props[key]);
1545
+ const getProps = (props, includeProps = false, debugName = "") => {
1546
+ if (!props) {
1547
+ if (shouldPrintDebug) logger.info([" getProps() no props"].join(" "));
1548
+ return {};
1549
+ }
1550
+ if (excludeProps?.size) {
1551
+ for (const key in props) {
1552
+ if (excludeProps.has(key)) {
1553
+ if (shouldPrintDebug) logger.info([" delete excluded", key].join(" "));
1554
+ delete props[key];
1555
+ }
1556
+ }
1557
+ }
866
1558
  const before = process.env.IS_STATIC;
867
1559
  process.env.IS_STATIC = "is_static";
868
1560
  try {
869
1561
  const out = getSplitStyles(props, staticConfig, defaultTheme, "", componentState, {
870
1562
  ...styleProps,
871
- noClass: !0,
1563
+ noClass: true,
872
1564
  fallbackProps: completeProps,
873
1565
  ...(platform2 === "native" && {
874
1566
  resolveValues: "except-theme"
875
1567
  })
876
- }, void 0, void 0, void 0, void 0, !1, debugPropValue || shouldPrintDebug);
1568
+ }, void 0, void 0, void 0, void 0, false, debugPropValue || shouldPrintDebug);
877
1569
  let outProps = {
878
1570
  ...(includeProps ? out.viewProps : {}),
879
1571
  ...out.style,
880
1572
  ...out.pseudos
881
1573
  };
882
- for (const key in outProps) deoptProps.has(key) && (shouldFlatten = !1);
883
- return shouldPrintDebug && (logger.info(`(${debugName})`), logger.info(`
884
- getProps (props in): ${(0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(props))}`), logger.info(`
885
- getProps (outProps): ${(0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(outProps))}`)), out.fontFamily && ((0, import_propsToFontFamilyCache.setPropsToFontFamily)(outProps, out.fontFamily), shouldPrintDebug && logger.info(`
886
- \u{1F4AC} new font fam: ${out.fontFamily}`)), outProps;
1574
+ for (const key in outProps) {
1575
+ if (deoptProps.has(key)) {
1576
+ shouldFlatten = false;
1577
+ }
1578
+ }
1579
+ if (shouldPrintDebug) {
1580
+ logger.info(`(${debugName})`);
1581
+ logger.info(`
1582
+ getProps (props in): ${(0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(props))}`);
1583
+ logger.info(`
1584
+ getProps (outProps): ${(0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(outProps))}`);
1585
+ }
1586
+ if (out.fontFamily) {
1587
+ (0, import_propsToFontFamilyCache.setPropsToFontFamily)(outProps, out.fontFamily);
1588
+ if (shouldPrintDebug) {
1589
+ logger.info(`
1590
+ \u{1F4AC} new font fam: ${out.fontFamily}`);
1591
+ }
1592
+ }
1593
+ return outProps;
887
1594
  } catch (err) {
888
- return logger.info(["error", err.message, err.stack].join(" ")), {};
1595
+ logger.info(["error", err.message, err.stack].join(" "));
1596
+ return {};
889
1597
  } finally {
890
1598
  process.env.IS_STATIC = before;
891
1599
  }
@@ -893,92 +1601,183 @@ function createExtractor({
893
1601
  attrs.unshift({
894
1602
  type: "style",
895
1603
  value: defaultProps
896
- }), attrs = attrs.reduce((acc, cur) => {
1604
+ });
1605
+ attrs = attrs.reduce((acc, cur) => {
897
1606
  if (cur.type === "style") {
898
1607
  const keys = Object.keys(cur.value || {});
899
- if (!keys.length) return acc;
900
- const key = keys[0],
901
- value = cur.value[key],
902
- isMediaLikeKey = key[0] === "$" && (key.startsWith("$theme-") || key.startsWith("$platform-") || key.startsWith("$group-") || mediaQueryConfig[key.slice(1)]);
903
- if (
1608
+ if (!keys.length) {
1609
+ return acc;
1610
+ }
1611
+ const key = keys[0];
1612
+ const value = cur.value[key];
1613
+ const isMediaLikeKey = key[0] === "$" && (key.startsWith("$theme-") || key.startsWith("$platform-") || key.startsWith("$group-") || mediaQueryConfig[key.slice(1)]);
1614
+ const shouldKeepOriginalAttr =
904
1615
  // !isStyleAndAttr[key] &&
905
1616
  !shouldFlatten &&
906
1617
  // de-opt if non-style
907
- !validStyles[key] && !pseudoDescriptors[key] && !isMediaLikeKey && !(key.startsWith("data-") || key.startsWith("aria-"))) return shouldPrintDebug && logger.info([" - keeping as non-style", key].join(" ")), prev = cur, acc.push({
908
- type: "attr",
909
- value: t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(typeof value == "string" ? t.stringLiteral(value) : (0, import_literalToAst.literalToAst)(value)))
910
- }), acc.push(cur), acc;
911
- if (prev?.type === "style") return mergeStyles(prev.value, cur.value), acc;
1618
+ !validStyles[key] && !pseudoDescriptors[key] && !isMediaLikeKey && !(key.startsWith("data-") || key.startsWith("aria-"));
1619
+ if (shouldKeepOriginalAttr) {
1620
+ if (shouldPrintDebug) {
1621
+ logger.info([" - keeping as non-style", key].join(" "));
1622
+ }
1623
+ prev = cur;
1624
+ acc.push({
1625
+ type: "attr",
1626
+ value: t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(typeof value === "string" ? t.stringLiteral(value) : (0, import_literalToAst.literalToAst)(value)))
1627
+ });
1628
+ acc.push(cur);
1629
+ return acc;
1630
+ }
1631
+ if (prev?.type === "style") {
1632
+ mergeStyles(prev.value, cur.value);
1633
+ return acc;
1634
+ }
912
1635
  }
913
- return cur.type === "style" && (prev = cur), acc.push(cur), acc;
914
- }, []), shouldPrintDebug && logger.info([` - attrs (combined \u{1F500}):
915
- `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" "));
1636
+ if (cur.type === "style") {
1637
+ prev = cur;
1638
+ }
1639
+ acc.push(cur);
1640
+ return acc;
1641
+ }, []);
1642
+ if (shouldPrintDebug) {
1643
+ logger.info([" - attrs (combined \u{1F500}): \n", (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" "));
1644
+ }
916
1645
  let getStyleError = null;
917
- for (const attr of attrs) try {
918
- switch (shouldPrintDebug && console.info(` Processing ${attr.type}:`), attr.type) {
919
- case "ternary":
920
- {
921
- const a = getProps(attr.value.alternate, !1, "ternary.alternate"),
922
- c = getProps(attr.value.consequent, !1, "ternary.consequent");
923
- a && (attr.value.alternate = a), c && (attr.value.consequent = c), shouldPrintDebug && logger.info([" => tern ", (0, import_extractHelpers.attrStr)(attr)].join(" "));
924
- continue;
925
- }
926
- case "style":
927
- {
928
- const styles = getProps(attr.value, !1, "style");
929
- styles && (attr.value = styles), shouldPrintDebug && logger.info([" * styles (in)", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(attr.value))].join(" ")), shouldPrintDebug && logger.info([" * styles (out)", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(styles))].join(" "));
930
- continue;
931
- }
932
- case "attr":
933
- if (shouldFlatten && t.isJSXAttribute(attr.value)) {
934
- const key = attr.value.name.name;
935
- if (key === "style" || key === "className" || key === "render") continue;
936
- const value = attemptEvalSafe(attr.value.value || t.booleanLiteral(!0));
937
- if (value !== import_constants.FAILED_EVAL) {
938
- const outProps = getProps({
939
- [key]: value
940
- }, !0, `attr.${key}`),
941
- outKey = Object.keys(outProps)[0];
942
- if (outKey) {
943
- const outVal = outProps[outKey];
944
- attr.value = t.jsxAttribute(t.jsxIdentifier(outKey), t.jsxExpressionContainer(typeof outVal == "string" ? t.stringLiteral(outVal) : (0, import_literalToAst.literalToAst)(outVal)));
1646
+ for (const attr of attrs) {
1647
+ try {
1648
+ if (shouldPrintDebug) {
1649
+ console.info(` Processing ${attr.type}:`);
1650
+ }
1651
+ switch (attr.type) {
1652
+ case "ternary":
1653
+ {
1654
+ const a = getProps(attr.value.alternate, false, "ternary.alternate");
1655
+ const c = getProps(attr.value.consequent, false, "ternary.consequent");
1656
+ if (a) attr.value.alternate = a;
1657
+ if (c) attr.value.consequent = c;
1658
+ if (shouldPrintDebug) logger.info([" => tern ", (0, import_extractHelpers.attrStr)(attr)].join(" "));
1659
+ continue;
1660
+ }
1661
+ case "style":
1662
+ {
1663
+ const styles = getProps(attr.value, false, "style");
1664
+ if (styles) {
1665
+ attr.value = styles;
945
1666
  }
1667
+ if (shouldPrintDebug) logger.info([" * styles (in)", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(attr.value))].join(" "));
1668
+ if (shouldPrintDebug) logger.info([" * styles (out)", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(styles))].join(" "));
1669
+ continue;
946
1670
  }
947
- }
1671
+ case "attr":
1672
+ {
1673
+ if (shouldFlatten && t.isJSXAttribute(attr.value)) {
1674
+ const key = attr.value.name.name;
1675
+ if (key === "style" || key === "className" || key === "render") {
1676
+ continue;
1677
+ }
1678
+ const value = attemptEvalSafe(attr.value.value || t.booleanLiteral(true));
1679
+ if (value !== import_constants.FAILED_EVAL) {
1680
+ const outProps = getProps({
1681
+ [key]: value
1682
+ }, true, `attr.${key}`);
1683
+ const outKey = Object.keys(outProps)[0];
1684
+ if (outKey) {
1685
+ const outVal = outProps[outKey];
1686
+ attr.value = t.jsxAttribute(t.jsxIdentifier(outKey), t.jsxExpressionContainer(typeof outVal === "string" ? t.stringLiteral(outVal) : (0, import_literalToAst.literalToAst)(outVal)));
1687
+ }
1688
+ }
1689
+ }
1690
+ }
1691
+ }
1692
+ } catch (err) {
1693
+ getStyleError = err;
948
1694
  }
949
- } catch (err) {
950
- getStyleError = err;
951
1695
  }
952
- if (shouldPrintDebug && logger.info([` - attrs (ternaries/combined):
953
- `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" ")), tm.mark("jsx-element-styles", !!shouldPrintDebug), getStyleError) return logger.info([" \u26A0\uFE0F postprocessing error, deopt", getStyleError].join(" ")), node.attributes = ogAttributes, null;
1696
+ if (shouldPrintDebug) {
1697
+ logger.info([" - attrs (ternaries/combined):\n", (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" "));
1698
+ }
1699
+ tm.mark("jsx-element-styles", !!shouldPrintDebug);
1700
+ if (getStyleError) {
1701
+ logger.info([" \u26A0\uFE0F postprocessing error, deopt", getStyleError].join(" "));
1702
+ node.attributes = ogAttributes;
1703
+ return null;
1704
+ }
954
1705
  const existingStyleKeys = /* @__PURE__ */new Set();
955
1706
  for (let i = attrs.length - 1; i >= 0; i--) {
956
1707
  const attr = attrs[i];
957
- if (shouldFlatten && attr.type === "attr" && t.isJSXAttribute(attr.value) && t.isJSXIdentifier(attr.value.name)) {
958
- const name = attr.value.name.name;
959
- INLINE_EXTRACTABLE[name] && (attr.value.name.name = INLINE_EXTRACTABLE[name]);
960
- }
961
- if (attr.type === "style") for (const key in attr.value) existingStyleKeys.has(key) ? (shouldPrintDebug && logger.info([` >> delete existing ${key}`].join(" ")), delete attr.value[key]) : existingStyleKeys.add(key);
962
- }
963
- if (attrs = attrs.filter(Boolean), !shouldFlatten && inlineWhenUnflattened.size) {
964
- for (const [index, attr] of attrs.entries()) if (attr.type === "style") for (const key in attr.value) {
965
- if (!inlineWhenUnflattened.has(key)) continue;
966
- const val = inlineWhenUnflattenedOGVals[key];
967
- val ? (delete attr.value[key], attrs.splice(index - 1, 0, val.attr)) : delete attr.value[key];
968
- }
969
- }
970
- if (attrs = attrs.filter(x => !(x.type === "style" && Object.keys(x.value).length === 0)), !shouldFlatten && platform2 === "native") return shouldPrintDebug && logger.info(`Disabled flattening except for simple cases on native for now: ${JSON.stringify({
971
- flatNode: flatNodeName,
972
- shouldDeopt,
973
- canFlattenProps,
974
- hasSpread,
975
- "staticConfig.isStyledHOC": staticConfig.isStyledHOC,
976
- "!staticConfig.isHOC": !staticConfig.isHOC,
977
- "staticConfig.isReactNative": staticConfig.isReactNative,
978
- "staticConfig.neverFlatten": staticConfig.neverFlatten
979
- }, null, 2)}`), node.attributes = ogAttributes, null;
980
- if (shouldPrintDebug && (logger.info([` - inlined props (${inlined.size}):`, shouldDeopt ? " deopted" : "", hasSpread ? " has spread" : "", staticConfig.neverFlatten ? "neverFlatten" : ""].join(" ")), logger.info(` - attrs (end):
981
- ${(0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))}`)), onExtractTag({
1708
+ if (shouldFlatten) {
1709
+ if (attr.type === "attr") {
1710
+ if (t.isJSXAttribute(attr.value)) {
1711
+ if (t.isJSXIdentifier(attr.value.name)) {
1712
+ const name = attr.value.name.name;
1713
+ if (INLINE_EXTRACTABLE[name]) {
1714
+ attr.value.name.name = INLINE_EXTRACTABLE[name];
1715
+ }
1716
+ }
1717
+ }
1718
+ }
1719
+ }
1720
+ if (attr.type === "style") {
1721
+ for (const key in attr.value) {
1722
+ if (existingStyleKeys.has(key)) {
1723
+ if (shouldPrintDebug) {
1724
+ logger.info([` >> delete existing ${key}`].join(" "));
1725
+ }
1726
+ delete attr.value[key];
1727
+ } else {
1728
+ existingStyleKeys.add(key);
1729
+ }
1730
+ }
1731
+ }
1732
+ }
1733
+ attrs = attrs.filter(Boolean);
1734
+ if (!shouldFlatten) {
1735
+ if (inlineWhenUnflattened.size) {
1736
+ for (const [index, attr] of attrs.entries()) {
1737
+ if (attr.type === "style") {
1738
+ for (const key in attr.value) {
1739
+ if (!inlineWhenUnflattened.has(key)) continue;
1740
+ const val = inlineWhenUnflattenedOGVals[key];
1741
+ if (val) {
1742
+ delete attr.value[key];
1743
+ attrs.splice(index - 1, 0, val.attr);
1744
+ } else {
1745
+ delete attr.value[key];
1746
+ }
1747
+ }
1748
+ }
1749
+ }
1750
+ }
1751
+ }
1752
+ attrs = attrs.filter(x => {
1753
+ if (x.type === "style" && Object.keys(x.value).length === 0) {
1754
+ return false;
1755
+ }
1756
+ return true;
1757
+ });
1758
+ const isNativeNotFlat = !shouldFlatten && platform2 === "native";
1759
+ if (isNativeNotFlat) {
1760
+ if (shouldPrintDebug) {
1761
+ logger.info(`Disabled flattening except for simple cases on native for now: ${JSON.stringify({
1762
+ flatNode: flatNodeName,
1763
+ shouldDeopt,
1764
+ canFlattenProps,
1765
+ hasSpread,
1766
+ "staticConfig.isStyledHOC": staticConfig.isStyledHOC,
1767
+ "!staticConfig.isHOC": !staticConfig.isHOC,
1768
+ "staticConfig.isReactNative": staticConfig.isReactNative,
1769
+ "staticConfig.neverFlatten": staticConfig.neverFlatten
1770
+ }, null, 2)}`);
1771
+ }
1772
+ node.attributes = ogAttributes;
1773
+ return null;
1774
+ }
1775
+ if (shouldPrintDebug) {
1776
+ logger.info([` - inlined props (${inlined.size}):`, shouldDeopt ? " deopted" : "", hasSpread ? " has spread" : "", staticConfig.neverFlatten ? "neverFlatten" : ""].join(" "));
1777
+ logger.info(` - attrs (end):
1778
+ ${(0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))}`);
1779
+ }
1780
+ onExtractTag({
982
1781
  parserProps: propsWithFileInfo,
983
1782
  attrs,
984
1783
  node,
@@ -992,17 +1791,37 @@ function createExtractor({
992
1791
  programPath,
993
1792
  completeProps,
994
1793
  staticConfig
995
- }), shouldFlatten) {
996
- shouldPrintDebug && logger.info([" [\u2705] flattened", originalNodeName, flatNodeName].join(" "));
1794
+ });
1795
+ if (shouldFlatten) {
1796
+ if (shouldPrintDebug) {
1797
+ logger.info([" [\u2705] flattened", originalNodeName, flatNodeName].join(" "));
1798
+ }
997
1799
  const currentName = node.name?.name;
998
- (!currentName || currentName === originalNodeName || currentName.startsWith("__ReactNative")) && (node.name.name = flatNodeName, closingElement && (closingElement.name.name = flatNodeName)), res.flattened++;
1800
+ if (!currentName || currentName === originalNodeName || currentName.startsWith("__ReactNative")) {
1801
+ node.name.name = flatNodeName;
1802
+ if (closingElement) {
1803
+ closingElement.name.name = flatNodeName;
1804
+ }
1805
+ }
1806
+ res.flattened++;
999
1807
  }
1000
1808
  } catch (err) {
1001
- node.attributes = ogAttributes, err instanceof import_errors.BailOptimizationError || (console.error(`@tamagui/static error, reverting optimization. In ${filePath} ${lineNumbers} on ${originalNodeName}: ${err.message}. For stack trace set environment TAMAGUI_DEBUG=1`), process.env.TAMAGUI_DEBUG === "1" && console.error(err.stack));
1809
+ node.attributes = ogAttributes;
1810
+ if (!(err instanceof import_errors.BailOptimizationError)) {
1811
+ console.error(`@tamagui/static error, reverting optimization. In ${filePath} ${lineNumbers} on ${originalNodeName}: ${err.message}. For stack trace set environment TAMAGUI_DEBUG=1`);
1812
+ if (process.env.TAMAGUI_DEBUG === "1") {
1813
+ console.error(err.stack);
1814
+ }
1815
+ }
1002
1816
  } finally {
1003
- debugPropValue && (shouldPrintDebug = ogDebug);
1817
+ if (debugPropValue) {
1818
+ shouldPrintDebug = ogDebug;
1819
+ }
1004
1820
  }
1005
1821
  }
1006
- }), tm.mark("jsx-done", !!shouldPrintDebug), tm.done(shouldPrintDebug === "verbose"), res;
1822
+ });
1823
+ tm.mark("jsx-done", !!shouldPrintDebug);
1824
+ tm.done(shouldPrintDebug === "verbose");
1825
+ return res;
1007
1826
  }
1008
1827
  }