@tamagui/static 1.0.1-beta.141 → 1.0.1-beta.142

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 (78) hide show
  1. package/dist/cjs/extractor/createEvaluator.js.map +2 -2
  2. package/dist/cjs/extractor/createExtractor.js +1138 -1106
  3. package/dist/cjs/extractor/createExtractor.js.map +2 -2
  4. package/dist/cjs/extractor/extractToClassNames.js +4 -4
  5. package/dist/cjs/extractor/extractToClassNames.js.map +2 -2
  6. package/dist/cjs/extractor/getStaticBindingsForScope.js +18 -2
  7. package/dist/cjs/extractor/getStaticBindingsForScope.js.map +2 -2
  8. package/dist/cjs/extractor/loadTamagui.js +205 -28
  9. package/dist/cjs/extractor/loadTamagui.js.map +2 -2
  10. package/dist/cjs/extractor/timer.js +8 -1
  11. package/dist/cjs/extractor/timer.js.map +2 -2
  12. package/dist/cjs/getPragmaOptions.js +68 -0
  13. package/dist/cjs/getPragmaOptions.js.map +7 -0
  14. package/dist/cjs/index.js +1 -0
  15. package/dist/cjs/index.js.map +2 -2
  16. package/dist/cjs/require.js +1 -20
  17. package/dist/cjs/require.js.map +2 -2
  18. package/dist/cjs/types.js.map +1 -1
  19. package/dist/cjs/webpackPlugin.js +35 -0
  20. package/dist/cjs/webpackPlugin.js.map +7 -0
  21. package/dist/esm/extractor/createEvaluator.js.map +2 -2
  22. package/dist/esm/extractor/createExtractor.js +1140 -1108
  23. package/dist/esm/extractor/createExtractor.js.map +2 -2
  24. package/dist/esm/extractor/extractToClassNames.js +4 -4
  25. package/dist/esm/extractor/extractToClassNames.js.map +2 -2
  26. package/dist/esm/extractor/getStaticBindingsForScope.js +17 -2
  27. package/dist/esm/extractor/getStaticBindingsForScope.js.map +2 -2
  28. package/dist/esm/extractor/loadTamagui.js +201 -28
  29. package/dist/esm/extractor/loadTamagui.js.map +2 -2
  30. package/dist/esm/extractor/timer.js +8 -1
  31. package/dist/esm/extractor/timer.js.map +2 -2
  32. package/dist/esm/getPragmaOptions.js +44 -0
  33. package/dist/esm/getPragmaOptions.js.map +7 -0
  34. package/dist/esm/index.js +1 -0
  35. package/dist/esm/index.js.map +2 -2
  36. package/dist/esm/require.js +2 -21
  37. package/dist/esm/require.js.map +2 -2
  38. package/dist/esm/webpackPlugin.js +11 -0
  39. package/dist/esm/webpackPlugin.js.map +7 -0
  40. package/dist/jsx/extractor/createEvaluator.js.map +2 -2
  41. package/dist/jsx/extractor/createExtractor.js +1133 -1101
  42. package/dist/jsx/extractor/createExtractor.js.map +2 -2
  43. package/dist/jsx/extractor/extractToClassNames.js +4 -4
  44. package/dist/jsx/extractor/extractToClassNames.js.map +2 -2
  45. package/dist/jsx/extractor/getStaticBindingsForScope.js +17 -2
  46. package/dist/jsx/extractor/getStaticBindingsForScope.js.map +2 -2
  47. package/dist/jsx/extractor/loadTamagui.js +199 -28
  48. package/dist/jsx/extractor/loadTamagui.js.map +2 -2
  49. package/dist/jsx/extractor/timer.js +8 -1
  50. package/dist/jsx/extractor/timer.js.map +2 -2
  51. package/dist/jsx/getPragmaOptions.js +43 -0
  52. package/dist/jsx/getPragmaOptions.js.map +7 -0
  53. package/dist/jsx/index.js +1 -0
  54. package/dist/jsx/index.js.map +2 -2
  55. package/dist/jsx/require.js +2 -21
  56. package/dist/jsx/require.js.map +2 -2
  57. package/dist/jsx/webpackPlugin.js +11 -0
  58. package/dist/jsx/webpackPlugin.js.map +7 -0
  59. package/package.json +20 -17
  60. package/src/extractor/createEvaluator.ts +2 -0
  61. package/src/extractor/createExtractor.ts +1592 -1532
  62. package/src/extractor/extractToClassNames.ts +25 -10
  63. package/src/extractor/getStaticBindingsForScope.ts +22 -5
  64. package/src/extractor/loadTamagui.ts +249 -32
  65. package/src/extractor/timer.ts +12 -1
  66. package/src/getPragmaOptions.ts +52 -0
  67. package/src/index.ts +2 -0
  68. package/src/require.ts +29 -24
  69. package/src/types.ts +16 -0
  70. package/src/webpackPlugin.ts +9 -0
  71. package/types/extractor/createExtractor.d.ts +21 -17
  72. package/types/extractor/extractToClassNames.d.ts +1 -1
  73. package/types/extractor/getStaticBindingsForScope.d.ts +1 -0
  74. package/types/extractor/loadTamagui.d.ts +5 -3
  75. package/types/getPragmaOptions.d.ts +9 -0
  76. package/types/index.d.ts +1 -0
  77. package/types/types.d.ts +13 -0
  78. package/types/webpackPlugin.d.ts +4 -0
@@ -15,9 +15,9 @@ import { createEvaluator, createSafeEvaluator } from "./createEvaluator";
15
15
  import { evaluateAstNode } from "./evaluateAstNode";
16
16
  import { attrStr, findComponentName, isInsideTamagui, isPresent, objToStr } from "./extractHelpers";
17
17
  import { findTopmostFunction } from "./findTopmostFunction";
18
- import { getStaticBindingsForScope } from "./getStaticBindingsForScope";
18
+ import { cleanupBeforeExit, getStaticBindingsForScope } from "./getStaticBindingsForScope";
19
19
  import { literalToAst } from "./literalToAst";
20
- import { loadTamagui } from "./loadTamagui";
20
+ import { loadTamagui, loadTamaguiSync } from "./loadTamagui";
21
21
  import { logLines } from "./logLines";
22
22
  import { normalizeTernaries } from "./normalizeTernaries";
23
23
  import { removeUnusedHooks } from "./removeUnusedHooks";
@@ -39,1295 +39,1327 @@ const INLINE_EXTRACTABLE = {
39
39
  onPressOut: "onMouseUp"
40
40
  }
41
41
  };
42
- const isAttr = (x) => x.type === "attr";
43
42
  const validHooks = {
44
43
  useMedia: true,
45
44
  useTheme: true
46
45
  };
46
+ const isAttr = (x) => x.type === "attr";
47
47
  const createTernary = (x) => x;
48
- function createExtractor() {
48
+ function createExtractor({ logger = console } = { logger: console }) {
49
49
  if (!process.env.TAMAGUI_TARGET) {
50
50
  console.log('\u26A0\uFE0F Please set process.env.TAMAGUI_TARGET to either "web" or "native"');
51
51
  process.exit(1);
52
52
  }
53
53
  const shouldAddDebugProp = !process.env.npm_package_dependencies_next && process.env.TAMAGUI_TARGET !== "native" && process.env.IDENTIFY_TAGS !== "false" && (process.env.NODE_ENV === "development" || process.env.DEBUG || process.env.IDENTIFY_TAGS);
54
- let loadedTamaguiConfig;
55
- let hasLogged = false;
56
- function isValidStyleKey(name, staticConfig) {
57
- return !!(!!staticConfig.validStyles?.[name] || !!pseudoDescriptors[name] || staticConfig.variants?.[name] || loadedTamaguiConfig.shorthands[name] || (name[0] === "$" ? !!mediaQueryConfig[name.slice(1)] : false));
54
+ let projectInfo = null;
55
+ function loadSync(props) {
56
+ return projectInfo || (projectInfo = loadTamaguiSync({
57
+ config: props.config || "tamagui.config.ts",
58
+ components: props.components || ["tamagui"]
59
+ }));
60
+ }
61
+ async function load(props) {
62
+ return projectInfo || (projectInfo = await loadTamagui({
63
+ config: props.config || "tamagui.config.ts",
64
+ components: props.components || ["tamagui"]
65
+ }));
58
66
  }
59
67
  return {
68
+ options: {
69
+ logger
70
+ },
71
+ cleanupBeforeExit,
72
+ loadTamagui: load,
73
+ loadTamaguiSync: loadSync,
60
74
  getTamagui() {
61
- return loadedTamaguiConfig;
75
+ return projectInfo?.tamaguiConfig;
62
76
  },
63
- parse: (fileOrPath, {
64
- config = "tamagui.config.ts",
65
- importsWhitelist = ["constants.js"],
66
- evaluateVars = true,
67
- shouldPrintDebug = false,
68
- sourcePath = "",
69
- onExtractTag,
70
- onStyleRule,
71
- getFlattenedNode,
72
- disable,
73
- disableExtraction,
74
- disableExtractInlineMedia,
75
- disableExtractVariables,
76
- disableDebugAttr,
77
- extractStyledDefinitions = false,
78
- prefixLogs,
79
- excludeProps,
80
- target,
81
- ...props
82
- }) => {
83
- if (disable) {
84
- return null;
85
- }
86
- if (sourcePath === "") {
87
- throw new Error(`Must provide a source file name`);
88
- }
89
- if (!Array.isArray(props.components)) {
90
- throw new Error(`Must provide components array with list of Tamagui component modules`);
91
- }
92
- const isTargetingHTML = target === "html";
93
- const ogDebug = shouldPrintDebug;
94
- const tm = timer();
95
- const { components, tamaguiConfig } = loadTamagui({
96
- config,
97
- components: props.components || ["tamagui"]
98
- });
99
- if (shouldPrintDebug === "verbose") {
100
- console.log("tamagui.config.ts:", { components, config });
101
- }
102
- tm.mark("load-tamagui", shouldPrintDebug === "verbose");
103
- loadedTamaguiConfig = tamaguiConfig;
104
- const proxiedTheme = proxyThemeVariables(tamaguiConfig.themes[Object.keys(tamaguiConfig.themes)[0]]);
105
- const themeAccessListeners = /* @__PURE__ */ new Set();
106
- const defaultTheme = new Proxy(proxiedTheme, {
107
- get(target2, key) {
108
- if (key[0] === "$") {
109
- themeAccessListeners.forEach((cb) => cb(String(key)));
110
- }
111
- return Reflect.get(target2, key);
77
+ parseSync: (f, props) => {
78
+ const projectInfo2 = loadSync(props);
79
+ return parseWithConfig(projectInfo2, f, props);
80
+ },
81
+ parse: async (f, props) => {
82
+ const projectInfo2 = await load(props);
83
+ return parseWithConfig(projectInfo2, f, props);
84
+ }
85
+ };
86
+ function isValidStyleKey(name, staticConfig) {
87
+ if (!projectInfo) {
88
+ throw new Error(`Tamagui extractor not loaded yet`);
89
+ }
90
+ return !!(!!staticConfig.validStyles?.[name] || !!pseudoDescriptors[name] || staticConfig.variants?.[name] || projectInfo?.tamaguiConfig.shorthands[name] || (name[0] === "$" ? !!mediaQueryConfig[name.slice(1)] : false));
91
+ }
92
+ function parseWithConfig({ components, tamaguiConfig }, fileOrPath, {
93
+ config = "tamagui.config.ts",
94
+ importsWhitelist = ["constants.js"],
95
+ evaluateVars = true,
96
+ shouldPrintDebug = false,
97
+ sourcePath = "",
98
+ onExtractTag,
99
+ onStyleRule,
100
+ getFlattenedNode,
101
+ disable,
102
+ disableExtraction,
103
+ disableExtractInlineMedia,
104
+ disableExtractVariables,
105
+ disableDebugAttr,
106
+ extractStyledDefinitions = false,
107
+ prefixLogs,
108
+ excludeProps,
109
+ target,
110
+ ...props
111
+ }) {
112
+ if (disable) {
113
+ return null;
114
+ }
115
+ if (sourcePath === "") {
116
+ throw new Error(`Must provide a source file name`);
117
+ }
118
+ if (!components) {
119
+ throw new Error(`Must provide components`);
120
+ }
121
+ const isTargetingHTML = target === "html";
122
+ const ogDebug = shouldPrintDebug;
123
+ const tm = timer();
124
+ if (shouldPrintDebug === "verbose") {
125
+ console.log("tamagui.config.ts:", { components, config });
126
+ }
127
+ tm.mark("load-tamagui", !!shouldPrintDebug);
128
+ const proxiedTheme = proxyThemeVariables(tamaguiConfig.themes[Object.keys(tamaguiConfig.themes)[0]]);
129
+ const themeAccessListeners = /* @__PURE__ */ new Set();
130
+ const defaultTheme = new Proxy(proxiedTheme, {
131
+ get(target2, key) {
132
+ if (key[0] === "$") {
133
+ themeAccessListeners.forEach((cb) => cb(String(key)));
112
134
  }
113
- });
114
- const body = fileOrPath.type === "Program" ? fileOrPath.get("body") : fileOrPath.program.body;
115
- const isInternalImport = (importStr) => {
116
- return isInsideTamagui(sourcePath) && importStr[0] === ".";
117
- };
118
- const validComponents = Object.keys(components).filter((key) => key[0].toUpperCase() === key[0] && !!components[key]?.staticConfig).reduce((obj, name) => {
119
- obj[name] = components[name];
120
- return obj;
121
- }, {});
122
- if (shouldPrintDebug === "verbose") {
123
- console.log("validComponents", Object.keys(validComponents));
135
+ return Reflect.get(target2, key);
124
136
  }
125
- let doesUseValidImport = false;
126
- let hasImportedTheme = false;
127
- for (const bodyPath of body) {
128
- if (bodyPath.type !== "ImportDeclaration")
129
- continue;
130
- const node = "node" in bodyPath ? bodyPath.node : bodyPath;
131
- const from = node.source.value;
132
- if (extractStyledDefinitions) {
133
- if (from === "@tamagui/core" || from === "tamagui") {
134
- if (node.specifiers.some((specifier) => {
135
- return specifier.local.name === "styled";
136
- })) {
137
- doesUseValidImport = true;
138
- break;
139
- }
140
- }
141
- }
142
- const isValidImport = props.components.includes(from) || isInternalImport(from);
137
+ });
138
+ const body = fileOrPath.type === "Program" ? fileOrPath.get("body") : fileOrPath.program.body;
139
+ const isInternalImport = (importStr) => {
140
+ return isInsideTamagui(sourcePath) && importStr[0] === ".";
141
+ };
142
+ const validComponents = Object.keys(components).filter((key) => key[0].toUpperCase() === key[0] && !!components[key]?.staticConfig).reduce((obj, name) => {
143
+ obj[name] = components[name];
144
+ return obj;
145
+ }, {});
146
+ if (shouldPrintDebug === "verbose") {
147
+ logger.info(`validComponents ${Object.keys(validComponents).join(", ")}`);
148
+ }
149
+ let doesUseValidImport = false;
150
+ let hasImportedTheme = false;
151
+ for (const bodyPath of body) {
152
+ if (bodyPath.type !== "ImportDeclaration")
153
+ continue;
154
+ const node = "node" in bodyPath ? bodyPath.node : bodyPath;
155
+ const from = node.source.value;
156
+ const isValidImport = props.components.includes(from) || isInternalImport(from) || from === "@tamagui/core" || from === "tamagui";
157
+ if (extractStyledDefinitions) {
143
158
  if (isValidImport) {
144
- const isValidComponent = node.specifiers.some((specifier) => {
145
- const name = specifier.local.name;
146
- return !!(validComponents[name] || validHooks[name]);
147
- });
148
- if (shouldPrintDebug === "verbose") {
149
- console.log("import from", from, { isValidComponent });
150
- }
151
- if (isValidComponent) {
159
+ if (node.specifiers.some((specifier) => {
160
+ return specifier.local.name === "styled";
161
+ })) {
152
162
  doesUseValidImport = true;
153
163
  break;
154
164
  }
155
165
  }
156
166
  }
157
- if (shouldPrintDebug) {
158
- console.log(sourcePath, { doesUseValidImport });
159
- }
160
- if (!doesUseValidImport) {
161
- return null;
167
+ if (isValidImport) {
168
+ const isValidComponent = node.specifiers.some((specifier) => {
169
+ const name = specifier.local.name;
170
+ return !!(validComponents[name] || validHooks[name]);
171
+ });
172
+ if (shouldPrintDebug === "verbose") {
173
+ logger.info(`import from ${from} isValidComponent ${isValidComponent}`);
174
+ }
175
+ if (isValidComponent) {
176
+ doesUseValidImport = true;
177
+ break;
178
+ }
162
179
  }
163
- tm.mark("import-check", shouldPrintDebug === "verbose");
164
- let couldntParse = false;
165
- const modifiedComponents = /* @__PURE__ */ new Set();
166
- const bindingCache = {};
167
- const callTraverse = (a) => {
168
- return fileOrPath.type === "File" ? traverse(fileOrPath, a) : fileOrPath.traverse(a);
169
- };
170
- let programPath;
171
- const res = {
172
- styled: 0,
173
- flattened: 0,
174
- optimized: 0,
175
- modified: 0,
176
- found: 0
177
- };
178
- callTraverse({
179
- Program: {
180
- enter(path) {
181
- programPath = path;
182
- }
183
- },
184
- CallExpression(path) {
185
- if (disable || disableExtraction || extractStyledDefinitions === false) {
186
- return;
187
- }
188
- if (!t.isIdentifier(path.node.callee) || path.node.callee.name !== "styled") {
189
- return;
190
- }
191
- const name = t.isVariableDeclarator(path.parent) && t.isIdentifier(path.parent.id) ? path.parent.id.name : "unknown";
192
- const definition = path.node.arguments[1];
193
- if (!name || !definition || !t.isObjectExpression(definition)) {
194
- return;
195
- }
196
- const Component = validComponents[name];
197
- if (!Component) {
198
- if (shouldPrintDebug) {
199
- console.log(`Didn't recognize styled(${name}), ${name} isn't in design system provided to tamagui.config.ts`);
200
- }
201
- return;
180
+ }
181
+ if (shouldPrintDebug) {
182
+ logger.info(`source: ${sourcePath} doesUseValidImport ${doesUseValidImport}`);
183
+ }
184
+ if (!doesUseValidImport) {
185
+ return null;
186
+ }
187
+ tm.mark("import-check", !!shouldPrintDebug);
188
+ let couldntParse = false;
189
+ const modifiedComponents = /* @__PURE__ */ new Set();
190
+ const bindingCache = {};
191
+ const callTraverse = (a) => {
192
+ return fileOrPath.type === "File" ? traverse(fileOrPath, a) : fileOrPath.traverse(a);
193
+ };
194
+ let programPath;
195
+ const res = {
196
+ styled: 0,
197
+ flattened: 0,
198
+ optimized: 0,
199
+ modified: 0,
200
+ found: 0
201
+ };
202
+ callTraverse({
203
+ Program: {
204
+ enter(path) {
205
+ programPath = path;
206
+ }
207
+ },
208
+ CallExpression(path) {
209
+ if (disable || disableExtraction || extractStyledDefinitions === false) {
210
+ return;
211
+ }
212
+ if (!t.isIdentifier(path.node.callee) || path.node.callee.name !== "styled") {
213
+ return;
214
+ }
215
+ const name = t.isVariableDeclarator(path.parent) && t.isIdentifier(path.parent.id) ? path.parent.id.name : "unknown";
216
+ const definition = path.node.arguments[1];
217
+ if (!name || !definition || !t.isObjectExpression(definition)) {
218
+ return;
219
+ }
220
+ let Component = validComponents[name];
221
+ if (!Component) {
222
+ if (shouldPrintDebug) {
223
+ logger.info(`Didn't recognize styled(${name}), ${name} isn't in design system provided to tamagui.config.ts. Will attempt to build isolated and analyze.. ${programPath}`);
202
224
  }
203
- const componentSkipProps = /* @__PURE__ */ new Set([
204
- ...Component.staticConfig.inlineWhenUnflattened || [],
205
- ...Component.staticConfig.inlineProps || [],
206
- ...Component.staticConfig.deoptProps || [],
207
- "variants",
208
- "defaultVariants",
209
- "fontFamily",
210
- "name"
211
- ]);
212
- const skipped = [];
213
- const styles = {};
214
- const staticNamespace = getStaticBindingsForScope(path.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug);
215
- const attemptEval = !evaluateVars ? evaluateAstNode : createEvaluator({
216
- tamaguiConfig,
217
- staticNamespace,
218
- sourcePath,
219
- shouldPrintDebug
225
+ const out2 = loadTamaguiSync({
226
+ components: [sourcePath]
220
227
  });
221
- const attemptEvalSafe = createSafeEvaluator(attemptEval);
222
- for (const property of definition.properties) {
223
- if (!t.isObjectProperty(property) || !t.isIdentifier(property.key) || !isValidStyleKey(property.key.name, Component.staticConfig) || Component.staticConfig.variants?.[property.key.name] || componentSkipProps.has(property.key.name)) {
224
- skipped.push(property);
225
- continue;
226
- }
227
- const out2 = attemptEvalSafe(property.value);
228
- if (out2 === FAILED_EVAL) {
229
- skipped.push(property);
230
- } else {
231
- styles[property.key.name] = out2;
232
- }
228
+ if (out2.components?.[name]) {
229
+ Object.assign(validComponents, out2.components);
233
230
  }
234
- const out = getSplitStyles(styles, Component.staticConfig, defaultTheme, {
235
- focus: false,
236
- hover: false,
237
- mounted: false,
238
- press: false,
239
- pressIn: false,
240
- resolveVariablesAs: "variable"
241
- });
242
- const classNames = {
243
- ...out.classNames
244
- };
245
- const atomics = getStylesAtomic(out.style);
231
+ Component = validComponents[name];
246
232
  if (shouldPrintDebug) {
247
- console.log("Exctacting styled()", styles, out, "to", atomics);
233
+ logger.info([`Loaded`, Object.keys(out2.components).join(", "), !!Component].join(" "));
248
234
  }
249
- for (const atomic of atomics) {
250
- out.rulesToInsert = out.rulesToInsert || [];
251
- out.rulesToInsert.push(atomic);
252
- classNames[atomic.property] = atomic.identifier;
235
+ }
236
+ if (!Component) {
237
+ return;
238
+ }
239
+ const componentSkipProps = /* @__PURE__ */ new Set([
240
+ ...Component.staticConfig.inlineWhenUnflattened || [],
241
+ ...Component.staticConfig.inlineProps || [],
242
+ ...Component.staticConfig.deoptProps || [],
243
+ "variants",
244
+ "defaultVariants",
245
+ "fontFamily",
246
+ "name"
247
+ ]);
248
+ const skipped = [];
249
+ const styles = {};
250
+ const staticNamespace = getStaticBindingsForScope(path.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug);
251
+ const attemptEval = !evaluateVars ? evaluateAstNode : createEvaluator({
252
+ tamaguiConfig,
253
+ staticNamespace,
254
+ sourcePath,
255
+ shouldPrintDebug
256
+ });
257
+ const attemptEvalSafe = createSafeEvaluator(attemptEval);
258
+ for (const property of definition.properties) {
259
+ if (!t.isObjectProperty(property) || !t.isIdentifier(property.key) || !isValidStyleKey(property.key.name, Component.staticConfig) || Component.staticConfig.variants?.[property.key.name] || componentSkipProps.has(property.key.name)) {
260
+ skipped.push(property);
261
+ continue;
253
262
  }
254
- definition.properties = skipped;
255
- for (const cn in classNames) {
256
- if (componentSkipProps.has(cn)) {
257
- continue;
258
- }
259
- const val = classNames[cn];
260
- definition.properties.push(t.objectProperty(t.stringLiteral(cn), t.stringLiteral(val)));
263
+ const out2 = attemptEvalSafe(property.value);
264
+ if (out2 === FAILED_EVAL) {
265
+ skipped.push(property);
266
+ } else {
267
+ styles[property.key.name] = out2;
261
268
  }
262
- if (out.rulesToInsert) {
263
- for (const { identifier, rules } of out.rulesToInsert) {
264
- onStyleRule?.(identifier, rules);
265
- }
269
+ }
270
+ const out = getSplitStyles(styles, Component.staticConfig, defaultTheme, {
271
+ focus: false,
272
+ hover: false,
273
+ mounted: false,
274
+ press: false,
275
+ pressIn: false,
276
+ resolveVariablesAs: "variable"
277
+ });
278
+ const classNames = {
279
+ ...out.classNames
280
+ };
281
+ const atomics = getStylesAtomic(out.style);
282
+ for (const atomic of atomics) {
283
+ out.rulesToInsert = out.rulesToInsert || [];
284
+ out.rulesToInsert.push(atomic);
285
+ classNames[atomic.property] = atomic.identifier;
286
+ }
287
+ if (shouldPrintDebug) {
288
+ logger.info([`Extracted styled(${name})
289
+ `, JSON.stringify(styles, null, 2), "\n=>\n", out.rulesToInsert.flatMap((rule) => rule.rules).join("\n")].join(" "));
290
+ }
291
+ definition.properties = skipped;
292
+ for (const cn in classNames) {
293
+ if (componentSkipProps.has(cn)) {
294
+ continue;
266
295
  }
267
- res.styled++;
268
- if (shouldPrintDebug) {
269
- console.log(`Extracted styled(${name}) props:`, styles);
296
+ const val = classNames[cn];
297
+ definition.properties.push(t.objectProperty(t.stringLiteral(cn), t.stringLiteral(val)));
298
+ }
299
+ if (out.rulesToInsert) {
300
+ for (const { identifier, rules } of out.rulesToInsert) {
301
+ onStyleRule?.(identifier, rules);
270
302
  }
271
- },
272
- JSXElement(traversePath) {
273
- tm.mark("jsx-element", shouldPrintDebug === "verbose");
274
- const node = traversePath.node.openingElement;
275
- const ogAttributes = node.attributes;
276
- const componentName = findComponentName(traversePath.scope);
277
- const closingElement = traversePath.node.closingElement;
278
- if (t.isJSXMemberExpression(closingElement?.name) || !t.isJSXIdentifier(node.name)) {
303
+ }
304
+ res.styled++;
305
+ if (shouldPrintDebug) {
306
+ logger.info(`Extracted styled(${name})`);
307
+ }
308
+ },
309
+ JSXElement(traversePath) {
310
+ tm.mark("jsx-element", !!shouldPrintDebug);
311
+ const node = traversePath.node.openingElement;
312
+ const ogAttributes = node.attributes;
313
+ const componentName = findComponentName(traversePath.scope);
314
+ const closingElement = traversePath.node.closingElement;
315
+ if (t.isJSXMemberExpression(closingElement?.name) || !t.isJSXIdentifier(node.name)) {
316
+ return;
317
+ }
318
+ const binding = traversePath.scope.getBinding(node.name.name);
319
+ if (binding) {
320
+ if (!t.isImportDeclaration(binding.path.parent)) {
279
321
  return;
280
322
  }
281
- const binding = traversePath.scope.getBinding(node.name.name);
282
- if (binding) {
283
- if (!t.isImportDeclaration(binding.path.parent)) {
284
- return;
285
- }
286
- const source = binding.path.parent.source;
287
- if (!props.components.includes(source.value) && !isInternalImport(source.value)) {
288
- return;
289
- }
290
- if (!validComponents[binding.identifier.name]) {
291
- return;
292
- }
293
- }
294
- const component = validComponents[node.name.name];
295
- if (!component || !component.staticConfig) {
323
+ const source = binding.path.parent.source;
324
+ if (!props.components.includes(source.value) && !isInternalImport(source.value)) {
296
325
  return;
297
326
  }
298
- const originalNodeName = node.name.name;
299
- res.found++;
300
- const filePath = `./${relative(process.cwd(), sourcePath)}`;
301
- const lineNumbers = node.loc ? node.loc.start.line + (node.loc.start.line !== node.loc.end.line ? `-${node.loc.end.line}` : "") : "";
302
- const codePosition = `${filePath}:${lineNumbers}`;
303
- const debugPropValue = node.attributes.filter((n) => t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && n.name.name === "debug").map((n) => {
304
- if (n.value === null)
305
- return true;
306
- if (t.isStringLiteral(n.value))
307
- return n.value.value;
308
- return false;
309
- })[0];
310
- if (debugPropValue) {
311
- shouldPrintDebug = debugPropValue;
312
- }
313
- if (shouldPrintDebug) {
314
- console.log("\n");
315
- console.log("\x1B[33m%s\x1B[0m", `${componentName} | ${codePosition} -------------------`);
316
- console.log("\x1B[1m", "\x1B[32m", `<${originalNodeName} />`, disableDebugAttr ? "" : "\u{1F41B}");
317
- }
318
- if (shouldAddDebugProp && !disableDebugAttr) {
319
- res.modified++;
320
- node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-is"), t.stringLiteral(node.name.name)));
321
- if (componentName) {
322
- node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-in"), t.stringLiteral(componentName)));
323
- }
324
- node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-at"), t.stringLiteral(`${basename(filePath)}:${lineNumbers}`)));
325
- }
326
- const shouldLog = !hasLogged;
327
- if (shouldLog) {
328
- console.log(` 1\uFE0F\u20E3 Inline optimized 2\uFE0F\u20E3 Inline flattened 3\uFE0F\u20E3 styled() extracted`);
329
- const prefix = " |";
330
- console.log(prefixLogs || prefix, " total \xB7 1\uFE0F\u20E3 \xB7 2\uFE0F\u20E3 \xB7 3\uFE0F\u20E3");
331
- hasLogged = true;
332
- }
333
- if (disableExtraction) {
327
+ if (!validComponents[binding.identifier.name]) {
334
328
  return;
335
329
  }
336
- try {
337
- let evaluateAttribute2 = function(path) {
338
- const attribute = path.node;
339
- const attr = { type: "attr", value: attribute };
340
- if (t.isJSXSpreadAttribute(attribute)) {
341
- const arg = attribute.argument;
342
- const conditional = t.isConditionalExpression(arg) ? [arg.test, arg.consequent, arg.alternate] : t.isLogicalExpression(arg) && arg.operator === "&&" ? [arg.left, arg.right, null] : null;
343
- if (conditional) {
344
- const [test, alt, cons] = conditional;
345
- if (!test)
346
- throw new Error(`no test`);
347
- if ([alt, cons].some((side) => side && !isExtractable2(side))) {
348
- if (shouldPrintDebug) {
349
- console.log("not extractable", alt, cons);
350
- }
351
- return attr;
330
+ }
331
+ const component = validComponents[node.name.name];
332
+ if (!component || !component.staticConfig) {
333
+ return;
334
+ }
335
+ const originalNodeName = node.name.name;
336
+ res.found++;
337
+ const filePath = `./${relative(process.cwd(), sourcePath)}`;
338
+ const lineNumbers = node.loc ? node.loc.start.line + (node.loc.start.line !== node.loc.end.line ? `-${node.loc.end.line}` : "") : "";
339
+ const codePosition = `${filePath}:${lineNumbers}`;
340
+ const debugPropValue = node.attributes.filter((n) => t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && n.name.name === "debug").map((n) => {
341
+ if (n.value === null)
342
+ return true;
343
+ if (t.isStringLiteral(n.value))
344
+ return n.value.value;
345
+ return false;
346
+ })[0];
347
+ if (debugPropValue) {
348
+ shouldPrintDebug = debugPropValue;
349
+ }
350
+ if (shouldPrintDebug) {
351
+ logger.info("\n");
352
+ logger.info(`\x1B[33m%s\x1B[0m ${componentName} | ${codePosition} -------------------`);
353
+ logger.info(["\x1B[1m", "\x1B[32m", `<${originalNodeName} />`, disableDebugAttr ? "" : "\u{1F41B}"].join(" "));
354
+ }
355
+ if (shouldAddDebugProp && !disableDebugAttr) {
356
+ res.modified++;
357
+ node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-is"), t.stringLiteral(node.name.name)));
358
+ if (componentName) {
359
+ node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-in"), t.stringLiteral(componentName)));
360
+ }
361
+ node.attributes.unshift(t.jsxAttribute(t.jsxIdentifier("data-at"), t.stringLiteral(`${basename(filePath)}:${lineNumbers}`)));
362
+ }
363
+ if (disableExtraction) {
364
+ return;
365
+ }
366
+ try {
367
+ let evaluateAttribute2 = function(path) {
368
+ const attribute = path.node;
369
+ const attr = { type: "attr", value: attribute };
370
+ if (t.isJSXSpreadAttribute(attribute)) {
371
+ const arg = attribute.argument;
372
+ const conditional = t.isConditionalExpression(arg) ? [arg.test, arg.consequent, arg.alternate] : t.isLogicalExpression(arg) && arg.operator === "&&" ? [arg.left, arg.right, null] : null;
373
+ if (conditional) {
374
+ const [test, alt, cons] = conditional;
375
+ if (!test)
376
+ throw new Error(`no test`);
377
+ if ([alt, cons].some((side) => side && !isExtractable2(side))) {
378
+ if (shouldPrintDebug) {
379
+ logger.info(`not extractable ${alt} ${cons}`);
352
380
  }
353
- return [
354
- ...createTernariesFromObjectProperties2(test, alt) || [],
355
- ...cons && createTernariesFromObjectProperties2(t.unaryExpression("!", test), cons) || []
356
- ].map((ternary) => ({
357
- type: "ternary",
358
- value: ternary
359
- }));
360
- }
361
- }
362
- if (t.isJSXSpreadAttribute(attribute) || !attribute.name || typeof attribute.name.name !== "string") {
363
- if (shouldPrintDebug) {
364
- console.log(" ! inlining, spread attr");
365
- }
366
- inlined.set(`${Math.random()}`, "spread");
367
- return attr;
368
- }
369
- const name = attribute.name.name;
370
- if (excludeProps?.has(name)) {
371
- if (shouldPrintDebug) {
372
- console.log(" excluding prop", name);
381
+ return attr;
373
382
  }
374
- return null;
383
+ return [
384
+ ...createTernariesFromObjectProperties2(test, alt) || [],
385
+ ...cons && createTernariesFromObjectProperties2(t.unaryExpression("!", test), cons) || []
386
+ ].map((ternary) => ({
387
+ type: "ternary",
388
+ value: ternary
389
+ }));
375
390
  }
376
- if (inlineProps.has(name)) {
377
- inlined.set(name, name);
378
- if (shouldPrintDebug) {
379
- console.log(" ! inlining, inline prop", name);
380
- }
381
- return attr;
391
+ }
392
+ if (t.isJSXSpreadAttribute(attribute) || !attribute.name || typeof attribute.name.name !== "string") {
393
+ if (shouldPrintDebug) {
394
+ logger.info(" ! inlining, spread attr");
382
395
  }
383
- if (deoptProps.has(name)) {
384
- shouldDeopt = true;
385
- inlined.set(name, name);
386
- if (shouldPrintDebug) {
387
- console.log(" ! inlining, deopted prop", name);
388
- }
389
- return attr;
396
+ inlined.set(`${Math.random()}`, "spread");
397
+ return attr;
398
+ }
399
+ const name = attribute.name.name;
400
+ if (excludeProps?.has(name)) {
401
+ if (shouldPrintDebug) {
402
+ logger.info([" excluding prop", name].join(" "));
390
403
  }
391
- if (UNTOUCHED_PROPS[name]) {
392
- return attr;
404
+ return null;
405
+ }
406
+ if (inlineProps.has(name)) {
407
+ inlined.set(name, name);
408
+ if (shouldPrintDebug) {
409
+ logger.info([" ! inlining, inline prop", name].join(" "));
393
410
  }
394
- if (INLINE_EXTRACTABLE[name]) {
395
- inlined.set(name, INLINE_EXTRACTABLE[name]);
396
- return attr;
411
+ return attr;
412
+ }
413
+ if (deoptProps.has(name)) {
414
+ shouldDeopt = true;
415
+ inlined.set(name, name);
416
+ if (shouldPrintDebug) {
417
+ logger.info([" ! inlining, deopted prop", name].join(" "));
397
418
  }
398
- if (name.startsWith("data-")) {
419
+ return attr;
420
+ }
421
+ if (UNTOUCHED_PROPS[name]) {
422
+ return attr;
423
+ }
424
+ if (INLINE_EXTRACTABLE[name]) {
425
+ inlined.set(name, INLINE_EXTRACTABLE[name]);
426
+ return attr;
427
+ }
428
+ if (name.startsWith("data-")) {
429
+ return attr;
430
+ }
431
+ if (name[0] === "$" && t.isJSXExpressionContainer(attribute?.value)) {
432
+ if (disableExtractInlineMedia) {
399
433
  return attr;
400
434
  }
401
- if (name[0] === "$" && t.isJSXExpressionContainer(attribute?.value)) {
402
- if (disableExtractInlineMedia) {
403
- return attr;
404
- }
405
- const shortname = name.slice(1);
406
- if (mediaQueryConfig[shortname]) {
407
- const expression = attribute.value.expression;
408
- if (!t.isJSXEmptyExpression(expression)) {
409
- const ternaries2 = createTernariesFromObjectProperties2(t.stringLiteral(shortname), expression, {
410
- inlineMediaQuery: shortname
411
- });
412
- if (ternaries2) {
413
- return ternaries2.map((value2) => ({
414
- type: "ternary",
415
- value: value2
416
- }));
417
- }
435
+ const shortname = name.slice(1);
436
+ if (mediaQueryConfig[shortname]) {
437
+ const expression = attribute.value.expression;
438
+ if (!t.isJSXEmptyExpression(expression)) {
439
+ const ternaries2 = createTernariesFromObjectProperties2(t.stringLiteral(shortname), expression, {
440
+ inlineMediaQuery: shortname
441
+ });
442
+ if (ternaries2) {
443
+ return ternaries2.map((value2) => ({
444
+ type: "ternary",
445
+ value: value2
446
+ }));
418
447
  }
419
448
  }
420
449
  }
421
- const [value, valuePath] = (() => {
422
- if (t.isJSXExpressionContainer(attribute?.value)) {
423
- return [attribute.value.expression, path.get("value")];
424
- } else {
425
- return [attribute.value, path.get("value")];
426
- }
427
- })();
428
- const remove = () => {
429
- Array.isArray(valuePath) ? valuePath.map((p) => p.remove()) : valuePath.remove();
430
- };
431
- if (name === "ref") {
432
- if (shouldPrintDebug) {
433
- console.log(" ! inlining, ref", name);
434
- }
435
- inlined.set("ref", "ref");
436
- return attr;
450
+ }
451
+ const [value, valuePath] = (() => {
452
+ if (t.isJSXExpressionContainer(attribute?.value)) {
453
+ return [attribute.value.expression, path.get("value")];
454
+ } else {
455
+ return [attribute.value, path.get("value")];
437
456
  }
438
- if (name === "tag") {
439
- return {
440
- type: "attr",
441
- value: path.node
442
- };
457
+ })();
458
+ const remove = () => {
459
+ Array.isArray(valuePath) ? valuePath.map((p) => p.remove()) : valuePath.remove();
460
+ };
461
+ if (name === "ref") {
462
+ if (shouldPrintDebug) {
463
+ logger.info([" ! inlining, ref", name].join(" "));
443
464
  }
444
- if (disableExtractVariables) {
445
- if (value) {
446
- if (value.type === "StringLiteral" && value.value[0] === "$") {
447
- if (shouldPrintDebug) {
448
- console.log(` ! inlining, native disable extract: ${name} =`, value.value);
449
- }
450
- inlined.set(name, true);
451
- return attr;
465
+ inlined.set("ref", "ref");
466
+ return attr;
467
+ }
468
+ if (name === "tag") {
469
+ return {
470
+ type: "attr",
471
+ value: path.node
472
+ };
473
+ }
474
+ if (disableExtractVariables) {
475
+ if (value) {
476
+ if (value.type === "StringLiteral" && value.value[0] === "$") {
477
+ if (shouldPrintDebug) {
478
+ logger.info([` ! inlining, native disable extract: ${name} =`, value.value].join(" "));
452
479
  }
480
+ inlined.set(name, true);
481
+ return attr;
453
482
  }
454
483
  }
455
- if (name === "theme") {
456
- inlined.set("theme", attr.value);
457
- return attr;
458
- }
459
- const styleValue = attemptEvalSafe(value);
460
- if (!variants[name] && !isValidStyleKey(name, staticConfig)) {
461
- let keys = [name];
462
- let out = null;
463
- out = staticConfig.propMapper(name, styleValue, defaultTheme, staticConfig.defaultProps, { resolveVariablesAs: "auto" }, void 0, void 0, shouldPrintDebug);
464
- if (out) {
465
- if (!Array.isArray(out)) {
466
- console.warn(`Error expected array but got`, out);
467
- couldntParse = true;
468
- shouldDeopt = true;
469
- } else {
470
- out = Object.fromEntries(out);
471
- keys = Object.keys(out);
472
- }
473
- }
474
- if (out) {
475
- if (isTargetingHTML) {
476
- out = createDOMProps(isTextView ? "span" : "div", out);
477
- delete out.className;
478
- }
484
+ }
485
+ if (name === "theme") {
486
+ inlined.set("theme", attr.value);
487
+ return attr;
488
+ }
489
+ const styleValue = attemptEvalSafe(value);
490
+ if (!variants[name] && !isValidStyleKey(name, staticConfig)) {
491
+ let keys = [name];
492
+ let out = null;
493
+ out = staticConfig.propMapper(name, styleValue, defaultTheme, staticConfig.defaultProps, { resolveVariablesAs: "auto" }, void 0, void 0, shouldPrintDebug);
494
+ if (out) {
495
+ if (!Array.isArray(out)) {
496
+ logger.warn(`Error expected array but got`, out);
497
+ couldntParse = true;
498
+ shouldDeopt = true;
499
+ } else {
500
+ out = Object.fromEntries(out);
479
501
  keys = Object.keys(out);
480
502
  }
481
- let didInline = false;
482
- const attributes = keys.map((key) => {
483
- const val = out[key];
484
- if (isValidStyleKey(key, staticConfig)) {
485
- return {
486
- type: "style",
487
- value: { [key]: styleValue },
488
- name: key,
489
- attr: path.node
490
- };
491
- }
492
- if (validHTMLAttributes[key] || key.startsWith("aria-") || key.startsWith("data-")) {
493
- return attr;
494
- }
495
- if (shouldPrintDebug) {
496
- console.log(" ! inlining, non-static", key);
497
- }
498
- didInline = true;
499
- inlined.set(key, val);
500
- return val;
501
- });
502
- if (didInline) {
503
- if (shouldPrintDebug) {
504
- console.log(" bailing flattening due to attributes", attributes);
505
- }
506
- return attr;
507
- }
508
- return attributes;
509
503
  }
510
- if (styleValue !== FAILED_EVAL) {
511
- if (inlineWhenUnflattened.has(name)) {
512
- inlineWhenUnflattenedOGVals[name] = { styleValue, attr };
504
+ if (out) {
505
+ if (isTargetingHTML) {
506
+ out = createDOMProps(isTextView ? "span" : "div", out);
507
+ delete out.className;
513
508
  }
514
- if (isValidStyleKey(name, staticConfig)) {
515
- if (shouldPrintDebug) {
516
- console.log(` style: ${name} =`, styleValue);
517
- }
518
- if (!(name in staticConfig.defaultProps)) {
519
- if (!hasSetOptimized) {
520
- res.optimized++;
521
- hasSetOptimized = true;
522
- }
523
- }
509
+ keys = Object.keys(out);
510
+ }
511
+ let didInline = false;
512
+ const attributes = keys.map((key) => {
513
+ const val = out[key];
514
+ if (isValidStyleKey(key, staticConfig)) {
524
515
  return {
525
516
  type: "style",
526
- value: { [name]: styleValue },
527
- name,
517
+ value: { [key]: styleValue },
518
+ name: key,
528
519
  attr: path.node
529
520
  };
530
- } else {
531
- if (variants[name]) {
532
- variantValues.set(name, styleValue);
533
- }
534
- inlined.set(name, true);
521
+ }
522
+ if (validHTMLAttributes[key] || key.startsWith("aria-") || key.startsWith("data-")) {
535
523
  return attr;
536
524
  }
537
- }
538
- if (t.isBinaryExpression(value)) {
539
525
  if (shouldPrintDebug) {
540
- console.log(` binary expression ${name} = `, value);
526
+ logger.info(" ! inlining, non-static " + key);
541
527
  }
542
- const { operator, left, right } = value;
543
- const lVal = attemptEvalSafe(left);
544
- const rVal = attemptEvalSafe(right);
528
+ didInline = true;
529
+ inlined.set(key, val);
530
+ return val;
531
+ });
532
+ if (didInline) {
545
533
  if (shouldPrintDebug) {
546
- console.log(` evalBinaryExpression lVal ${String(lVal)}, rVal ${String(rVal)}`);
534
+ logger.info(` bailing flattening due to attributes ${attributes}`);
547
535
  }
548
- if (lVal !== FAILED_EVAL && t.isConditionalExpression(right)) {
549
- const ternary = addBinaryConditional(operator, left, right);
550
- if (ternary)
551
- return ternary;
536
+ return attr;
537
+ }
538
+ return attributes;
539
+ }
540
+ if (styleValue !== FAILED_EVAL) {
541
+ if (inlineWhenUnflattened.has(name)) {
542
+ inlineWhenUnflattenedOGVals[name] = { styleValue, attr };
543
+ }
544
+ if (isValidStyleKey(name, staticConfig)) {
545
+ if (shouldPrintDebug) {
546
+ logger.info(` style: ${name} = ${styleValue}`);
552
547
  }
553
- if (rVal !== FAILED_EVAL && t.isConditionalExpression(left)) {
554
- const ternary = addBinaryConditional(operator, right, left);
555
- if (ternary)
556
- return ternary;
548
+ if (!(name in staticConfig.defaultProps)) {
549
+ if (!hasSetOptimized) {
550
+ res.optimized++;
551
+ hasSetOptimized = true;
552
+ }
557
553
  }
558
- if (shouldPrintDebug) {
559
- console.log(` evalBinaryExpression cant extract`);
554
+ return {
555
+ type: "style",
556
+ value: { [name]: styleValue },
557
+ name,
558
+ attr: path.node
559
+ };
560
+ } else {
561
+ if (variants[name]) {
562
+ variantValues.set(name, styleValue);
560
563
  }
561
564
  inlined.set(name, true);
562
565
  return attr;
563
566
  }
564
- const staticConditional = getStaticConditional(value);
565
- if (staticConditional) {
566
- if (shouldPrintDebug === "verbose") {
567
- console.log(` static conditional ${name}`, value);
568
- }
569
- return { type: "ternary", value: staticConditional };
567
+ }
568
+ if (t.isBinaryExpression(value)) {
569
+ if (shouldPrintDebug) {
570
+ logger.info(` binary expression ${name} = ${value}`);
570
571
  }
571
- const staticLogical = getStaticLogical(value);
572
- if (staticLogical) {
573
- if (shouldPrintDebug === "verbose") {
574
- console.log(` static ternary ${name} = `, value);
575
- }
576
- return { type: "ternary", value: staticLogical };
572
+ const { operator, left, right } = value;
573
+ const lVal = attemptEvalSafe(left);
574
+ const rVal = attemptEvalSafe(right);
575
+ if (shouldPrintDebug) {
576
+ logger.info(` evalBinaryExpression lVal ${String(lVal)}, rVal ${String(rVal)}`);
577
+ }
578
+ if (lVal !== FAILED_EVAL && t.isConditionalExpression(right)) {
579
+ const ternary = addBinaryConditional(operator, left, right);
580
+ if (ternary)
581
+ return ternary;
582
+ }
583
+ if (rVal !== FAILED_EVAL && t.isConditionalExpression(left)) {
584
+ const ternary = addBinaryConditional(operator, right, left);
585
+ if (ternary)
586
+ return ternary;
577
587
  }
578
- inlined.set(name, true);
579
588
  if (shouldPrintDebug) {
580
- console.log(` ! inline no match ${name}`, value);
589
+ logger.info(` evalBinaryExpression cant extract`);
581
590
  }
591
+ inlined.set(name, true);
582
592
  return attr;
583
- function addBinaryConditional(operator, staticExpr, cond) {
584
- if (getStaticConditional(cond)) {
585
- const alt = attemptEval(t.binaryExpression(operator, staticExpr, cond.alternate));
586
- const cons = attemptEval(t.binaryExpression(operator, staticExpr, cond.consequent));
593
+ }
594
+ const staticConditional = getStaticConditional(value);
595
+ if (staticConditional) {
596
+ if (shouldPrintDebug === "verbose") {
597
+ logger.info(` static conditional ${name} ${value}`);
598
+ }
599
+ return { type: "ternary", value: staticConditional };
600
+ }
601
+ const staticLogical = getStaticLogical(value);
602
+ if (staticLogical) {
603
+ if (shouldPrintDebug === "verbose") {
604
+ logger.info(` static ternary ${name} = ${value}`);
605
+ }
606
+ return { type: "ternary", value: staticLogical };
607
+ }
608
+ inlined.set(name, true);
609
+ if (shouldPrintDebug) {
610
+ logger.info(` ! inline no match ${name} ${value}`);
611
+ }
612
+ return attr;
613
+ function addBinaryConditional(operator, staticExpr, cond) {
614
+ if (getStaticConditional(cond)) {
615
+ const alt = attemptEval(t.binaryExpression(operator, staticExpr, cond.alternate));
616
+ const cons = attemptEval(t.binaryExpression(operator, staticExpr, cond.consequent));
617
+ if (shouldPrintDebug) {
618
+ logger.info([" binaryConditional", cond.test, cons, alt].join(" "));
619
+ }
620
+ return {
621
+ type: "ternary",
622
+ value: {
623
+ test: cond.test,
624
+ remove,
625
+ alternate: { [name]: alt },
626
+ consequent: { [name]: cons }
627
+ }
628
+ };
629
+ }
630
+ return null;
631
+ }
632
+ function getStaticConditional(value2) {
633
+ if (t.isConditionalExpression(value2)) {
634
+ try {
635
+ const aVal = attemptEval(value2.alternate);
636
+ const cVal = attemptEval(value2.consequent);
587
637
  if (shouldPrintDebug) {
588
- console.log(" binaryConditional", cond.test, cons, alt);
638
+ const type = value2.test.type;
639
+ logger.info([" static ternary", type, cVal, aVal].join(" "));
589
640
  }
590
641
  return {
591
- type: "ternary",
592
- value: {
593
- test: cond.test,
594
- remove,
595
- alternate: { [name]: alt },
596
- consequent: { [name]: cons }
597
- }
642
+ test: value2.test,
643
+ remove,
644
+ consequent: { [name]: cVal },
645
+ alternate: { [name]: aVal }
598
646
  };
647
+ } catch (err) {
648
+ if (shouldPrintDebug) {
649
+ logger.info([" cant eval ternary", err.message].join(" "));
650
+ }
599
651
  }
600
- return null;
601
652
  }
602
- function getStaticConditional(value2) {
603
- if (t.isConditionalExpression(value2)) {
653
+ return null;
654
+ }
655
+ function getStaticLogical(value2) {
656
+ if (t.isLogicalExpression(value2)) {
657
+ if (value2.operator === "&&") {
604
658
  try {
605
- const aVal = attemptEval(value2.alternate);
606
- const cVal = attemptEval(value2.consequent);
659
+ const val = attemptEval(value2.right);
607
660
  if (shouldPrintDebug) {
608
- const type = value2.test.type;
609
- console.log(" static ternary", type, cVal, aVal);
661
+ logger.info([" staticLogical", value2.left, name, val].join(" "));
610
662
  }
611
663
  return {
612
- test: value2.test,
664
+ test: value2.left,
613
665
  remove,
614
- consequent: { [name]: cVal },
615
- alternate: { [name]: aVal }
666
+ consequent: { [name]: val },
667
+ alternate: null
616
668
  };
617
669
  } catch (err) {
618
670
  if (shouldPrintDebug) {
619
- console.log(" cant eval ternary", err.message);
671
+ logger.info([" cant static eval logical", err].join(" "));
620
672
  }
621
673
  }
622
674
  }
623
- return null;
624
675
  }
625
- function getStaticLogical(value2) {
626
- if (t.isLogicalExpression(value2)) {
627
- if (value2.operator === "&&") {
628
- try {
629
- const val = attemptEval(value2.right);
630
- if (shouldPrintDebug) {
631
- console.log(" staticLogical", value2.left, name, val);
632
- }
633
- return {
634
- test: value2.left,
635
- remove,
636
- consequent: { [name]: val },
637
- alternate: null
638
- };
639
- } catch (err) {
640
- if (shouldPrintDebug) {
641
- console.log(" cant static eval logical", err);
642
- }
643
- }
644
- }
645
- }
646
- return null;
676
+ return null;
677
+ }
678
+ }, isExtractable2 = function(obj) {
679
+ return t.isObjectExpression(obj) && obj.properties.every((prop) => {
680
+ if (!t.isObjectProperty(prop)) {
681
+ logger.info(["not object prop", prop].join(" "));
682
+ return false;
647
683
  }
648
- }, isExtractable2 = function(obj) {
649
- return t.isObjectExpression(obj) && obj.properties.every((prop) => {
650
- if (!t.isObjectProperty(prop)) {
651
- console.log("not object prop", prop);
652
- return false;
653
- }
654
- const propName = prop.key["name"];
655
- if (!isValidStyleKey(propName, staticConfig) && propName !== "tag") {
656
- if (shouldPrintDebug) {
657
- console.log(" not a valid style prop!", propName);
658
- }
659
- return false;
684
+ const propName = prop.key["name"];
685
+ if (!isValidStyleKey(propName, staticConfig) && propName !== "tag") {
686
+ if (shouldPrintDebug) {
687
+ logger.info([" not a valid style prop!", propName].join(" "));
660
688
  }
661
- return true;
662
- });
663
- }, createTernariesFromObjectProperties2 = function(test, side, ternaryPartial = {}) {
664
- if (!side) {
665
- return null;
689
+ return false;
666
690
  }
667
- if (!isExtractable2(side)) {
668
- throw new Error("not extractable");
691
+ return true;
692
+ });
693
+ }, createTernariesFromObjectProperties2 = function(test, side, ternaryPartial = {}) {
694
+ if (!side) {
695
+ return null;
696
+ }
697
+ if (!isExtractable2(side)) {
698
+ throw new Error("not extractable");
699
+ }
700
+ return side.properties.flatMap((property) => {
701
+ if (!t.isObjectProperty(property)) {
702
+ throw new Error("expected object property");
669
703
  }
670
- return side.properties.flatMap((property) => {
671
- if (!t.isObjectProperty(property)) {
672
- throw new Error("expected object property");
673
- }
674
- if (t.isIdentifier(property.key)) {
675
- const key = property.key.name;
676
- const mediaQueryKey = key.slice(1);
677
- const isMediaQuery = key[0] === "$" && mediaQueryConfig[mediaQueryKey];
678
- if (isMediaQuery) {
679
- if (t.isExpression(property.value)) {
680
- const ternaries2 = createTernariesFromObjectProperties2(t.stringLiteral(mediaQueryKey), property.value, {
681
- inlineMediaQuery: mediaQueryKey
682
- });
683
- if (ternaries2) {
684
- return ternaries2.map((value) => ({
685
- ...ternaryPartial,
686
- ...value,
687
- test: t.logicalExpression("&&", value.test, test)
688
- }));
689
- } else {
690
- console.log("\u26A0\uFE0F no ternaries?", property);
691
- }
704
+ if (t.isIdentifier(property.key)) {
705
+ const key = property.key.name;
706
+ const mediaQueryKey = key.slice(1);
707
+ const isMediaQuery = key[0] === "$" && mediaQueryConfig[mediaQueryKey];
708
+ if (isMediaQuery) {
709
+ if (t.isExpression(property.value)) {
710
+ const ternaries2 = createTernariesFromObjectProperties2(t.stringLiteral(mediaQueryKey), property.value, {
711
+ inlineMediaQuery: mediaQueryKey
712
+ });
713
+ if (ternaries2) {
714
+ return ternaries2.map((value) => ({
715
+ ...ternaryPartial,
716
+ ...value,
717
+ test: t.logicalExpression("&&", value.test, test)
718
+ }));
692
719
  } else {
693
- console.log("\u26A0\uFE0F not expression", property);
720
+ logger.info(["\u26A0\uFE0F no ternaries?", property].join(" "));
694
721
  }
722
+ } else {
723
+ logger.info(["\u26A0\uFE0F not expression", property].join(" "));
695
724
  }
696
725
  }
697
- if (t.isConditionalExpression(property.value)) {
698
- const [truthy, falsy] = [
699
- t.objectExpression([t.objectProperty(property.key, property.value.consequent)]),
700
- t.objectExpression([t.objectProperty(property.key, property.value.alternate)])
701
- ].map((x) => attemptEval(x));
702
- return [
703
- createTernary({
704
- remove() {
705
- },
706
- ...ternaryPartial,
707
- test: t.logicalExpression("&&", test, property.value.test),
708
- consequent: truthy,
709
- alternate: null
710
- }),
711
- createTernary({
712
- ...ternaryPartial,
713
- test: t.logicalExpression("&&", test, t.unaryExpression("!", property.value.test)),
714
- consequent: falsy,
715
- alternate: null,
716
- remove() {
717
- }
718
- })
719
- ];
720
- }
721
- const obj = t.objectExpression([t.objectProperty(property.key, property.value)]);
722
- const consequent = attemptEval(obj);
723
- return createTernary({
724
- remove() {
725
- },
726
- ...ternaryPartial,
727
- test,
728
- consequent,
729
- alternate: null
730
- });
731
- });
732
- }, splitVariants2 = function(style) {
733
- const variants2 = {};
734
- const styles = {};
735
- for (const key in style) {
736
- if (staticConfig.variants?.[key]) {
737
- variants2[key] = style[key];
738
- } else {
739
- styles[key] = style[key];
740
- }
741
726
  }
742
- return {
743
- variants: variants2,
744
- styles
745
- };
746
- }, expandStylesWithoutVariants2 = function(style) {
747
- const { variants: variants2, styles } = splitVariants2(style);
748
- return {
749
- ...expandStyles(styles),
750
- ...variants2
751
- };
752
- }, mergeStyles2 = function(prev2, nextIn) {
753
- const next = expandStylesWithoutVariants2(nextIn);
754
- for (const key in next) {
755
- if (pseudoDescriptors[key]) {
756
- prev2[key] = prev2[key] || {};
757
- if (shouldPrintDebug) {
758
- if (!next[key] || !prev2[key]) {
759
- console.log("warn: missing", key, prev2, next);
727
+ if (t.isConditionalExpression(property.value)) {
728
+ const [truthy, falsy] = [
729
+ t.objectExpression([t.objectProperty(property.key, property.value.consequent)]),
730
+ t.objectExpression([t.objectProperty(property.key, property.value.alternate)])
731
+ ].map((x) => attemptEval(x));
732
+ return [
733
+ createTernary({
734
+ remove() {
735
+ },
736
+ ...ternaryPartial,
737
+ test: t.logicalExpression("&&", test, property.value.test),
738
+ consequent: truthy,
739
+ alternate: null
740
+ }),
741
+ createTernary({
742
+ ...ternaryPartial,
743
+ test: t.logicalExpression("&&", test, t.unaryExpression("!", property.value.test)),
744
+ consequent: falsy,
745
+ alternate: null,
746
+ remove() {
760
747
  }
761
- }
762
- Object.assign(prev2[key], next[key]);
763
- } else {
764
- prev2[key] = next[key];
765
- }
748
+ })
749
+ ];
766
750
  }
767
- };
768
- var evaluateAttribute = evaluateAttribute2, isExtractable = isExtractable2, createTernariesFromObjectProperties = createTernariesFromObjectProperties2, splitVariants = splitVariants2, expandStylesWithoutVariants = expandStylesWithoutVariants2, mergeStyles = mergeStyles2;
769
- const { staticConfig } = component;
770
- const variants = staticConfig.variants || {};
771
- const isTextView = staticConfig.isText || false;
772
- const validStyles = staticConfig?.validStyles ?? {};
773
- let tagName = staticConfig.defaultProps.tag ?? (isTextView ? "span" : "div");
774
- traversePath.get("openingElement").get("attributes").forEach((path) => {
775
- const attr = path.node;
776
- if (t.isJSXSpreadAttribute(attr))
777
- return;
778
- if (attr.name.name !== "tag")
779
- return;
780
- const val = attr.value;
781
- if (!t.isStringLiteral(val))
782
- return;
783
- tagName = val.value;
784
- });
785
- const flatNode = getFlattenedNode({ isTextView, tag: tagName });
786
- const inlineProps = /* @__PURE__ */ new Set([
787
- ...props.inlineProps || [],
788
- ...staticConfig.inlineProps || []
789
- ]);
790
- const deoptProps = /* @__PURE__ */ new Set([
791
- "animation",
792
- ...props.deoptProps || [],
793
- ...staticConfig.deoptProps || []
794
- ]);
795
- const inlineWhenUnflattened = /* @__PURE__ */ new Set([...staticConfig.inlineWhenUnflattened || []]);
796
- const staticNamespace = getStaticBindingsForScope(traversePath.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug);
797
- const attemptEval = !evaluateVars ? evaluateAstNode : createEvaluator({
798
- tamaguiConfig,
799
- staticNamespace,
800
- sourcePath,
801
- traversePath,
802
- shouldPrintDebug
751
+ const obj = t.objectExpression([t.objectProperty(property.key, property.value)]);
752
+ const consequent = attemptEval(obj);
753
+ return createTernary({
754
+ remove() {
755
+ },
756
+ ...ternaryPartial,
757
+ test,
758
+ consequent,
759
+ alternate: null
760
+ });
803
761
  });
804
- const attemptEvalSafe = createSafeEvaluator(attemptEval);
805
- if (shouldPrintDebug) {
806
- console.log(" staticNamespace", Object.keys(staticNamespace).join(", "));
807
- }
808
- const flattenedAttrs = [];
809
- traversePath.get("openingElement").get("attributes").forEach((path) => {
810
- const attr = path.node;
811
- if (!t.isJSXSpreadAttribute(attr)) {
812
- flattenedAttrs.push(attr);
813
- return;
762
+ }, splitVariants2 = function(style) {
763
+ const variants2 = {};
764
+ const styles = {};
765
+ for (const key in style) {
766
+ if (staticConfig.variants?.[key]) {
767
+ variants2[key] = style[key];
768
+ } else {
769
+ styles[key] = style[key];
814
770
  }
815
- let arg;
816
- try {
817
- arg = attemptEval(attr.argument);
818
- } catch (e) {
771
+ }
772
+ return {
773
+ variants: variants2,
774
+ styles
775
+ };
776
+ }, expandStylesWithoutVariants2 = function(style) {
777
+ const { variants: variants2, styles } = splitVariants2(style);
778
+ return {
779
+ ...expandStyles(styles),
780
+ ...variants2
781
+ };
782
+ }, mergeStyles2 = function(prev2, nextIn) {
783
+ const next = expandStylesWithoutVariants2(nextIn);
784
+ for (const key in next) {
785
+ if (pseudoDescriptors[key]) {
786
+ prev2[key] = prev2[key] || {};
819
787
  if (shouldPrintDebug) {
820
- console.log(" couldnt parse spread", e.message);
821
- }
822
- flattenedAttrs.push(attr);
823
- return;
824
- }
825
- if (arg !== void 0) {
826
- try {
827
- if (typeof arg !== "object" || arg == null) {
828
- if (shouldPrintDebug) {
829
- console.log(" non object or null arg", arg);
830
- }
831
- flattenedAttrs.push(attr);
832
- } else {
833
- for (const k in arg) {
834
- const value = arg[k];
835
- if (!value && typeof value === "object") {
836
- console.log("shouldnt we handle this?", k, value, arg);
837
- continue;
838
- }
839
- flattenedAttrs.push(t.jsxAttribute(t.jsxIdentifier(k), t.jsxExpressionContainer(literalToAst(value))));
840
- }
788
+ if (!next[key] || !prev2[key]) {
789
+ logger.info(["warn: missing", key, prev2, next].join(" "));
841
790
  }
842
- } catch (err) {
843
- console.warn("cant parse spread, caught err", err);
844
- couldntParse = true;
845
791
  }
792
+ Object.assign(prev2[key], next[key]);
793
+ } else {
794
+ prev2[key] = next[key];
846
795
  }
847
- });
848
- if (couldntParse) {
849
- return;
850
796
  }
851
- tm.mark("jsx-element-flattened", shouldPrintDebug === "verbose");
852
- node.attributes = flattenedAttrs;
853
- let attrs = [];
854
- let shouldDeopt = false;
855
- const inlined = /* @__PURE__ */ new Map();
856
- const variantValues = /* @__PURE__ */ new Map();
857
- let hasSetOptimized = false;
858
- const inlineWhenUnflattenedOGVals = {};
859
- attrs = traversePath.get("openingElement").get("attributes").flatMap((path) => {
860
- try {
861
- const res2 = evaluateAttribute2(path);
862
- tm.mark("jsx-element-evaluate-attr", shouldPrintDebug === "verbose");
863
- if (!res2) {
864
- path.remove();
865
- }
866
- return res2;
867
- } catch (err) {
868
- if (shouldPrintDebug) {
869
- console.log("Error extracting attribute", err.message, err.stack);
870
- console.log("node", path.node);
871
- }
872
- inlined.set(`${Math.random()}`, "spread");
873
- return {
874
- type: "attr",
875
- value: path.node
876
- };
877
- }
878
- }).flat(4).filter(isPresent);
879
- if (shouldPrintDebug) {
880
- console.log(" - attrs (before):\n", logLines(attrs.map(attrStr).join(", ")));
797
+ };
798
+ var evaluateAttribute = evaluateAttribute2, isExtractable = isExtractable2, createTernariesFromObjectProperties = createTernariesFromObjectProperties2, splitVariants = splitVariants2, expandStylesWithoutVariants = expandStylesWithoutVariants2, mergeStyles = mergeStyles2;
799
+ const { staticConfig } = component;
800
+ const variants = staticConfig.variants || {};
801
+ const isTextView = staticConfig.isText || false;
802
+ const validStyles = staticConfig?.validStyles ?? {};
803
+ let tagName = staticConfig.defaultProps.tag ?? (isTextView ? "span" : "div");
804
+ traversePath.get("openingElement").get("attributes").forEach((path) => {
805
+ const attr = path.node;
806
+ if (t.isJSXSpreadAttribute(attr))
807
+ return;
808
+ if (attr.name.name !== "tag")
809
+ return;
810
+ const val = attr.value;
811
+ if (!t.isStringLiteral(val))
812
+ return;
813
+ tagName = val.value;
814
+ });
815
+ const flatNode = getFlattenedNode({ isTextView, tag: tagName });
816
+ const inlineProps = /* @__PURE__ */ new Set([
817
+ ...props.inlineProps || [],
818
+ ...staticConfig.inlineProps || []
819
+ ]);
820
+ const deoptProps = /* @__PURE__ */ new Set([
821
+ "animation",
822
+ ...props.deoptProps || [],
823
+ ...staticConfig.deoptProps || []
824
+ ]);
825
+ const inlineWhenUnflattened = /* @__PURE__ */ new Set([...staticConfig.inlineWhenUnflattened || []]);
826
+ const staticNamespace = getStaticBindingsForScope(traversePath.scope, importsWhitelist, sourcePath, bindingCache, shouldPrintDebug);
827
+ const attemptEval = !evaluateVars ? evaluateAstNode : createEvaluator({
828
+ tamaguiConfig,
829
+ staticNamespace,
830
+ sourcePath,
831
+ traversePath,
832
+ shouldPrintDebug
833
+ });
834
+ const attemptEvalSafe = createSafeEvaluator(attemptEval);
835
+ if (shouldPrintDebug) {
836
+ logger.info(` staticNamespace ${Object.keys(staticNamespace).join(", ")}`);
837
+ }
838
+ const flattenedAttrs = [];
839
+ traversePath.get("openingElement").get("attributes").forEach((path) => {
840
+ const attr = path.node;
841
+ if (!t.isJSXSpreadAttribute(attr)) {
842
+ flattenedAttrs.push(attr);
843
+ return;
881
844
  }
882
- node.attributes = attrs.filter(isAttr).map((x) => x.value);
883
- if (couldntParse || shouldDeopt) {
845
+ let arg;
846
+ try {
847
+ arg = attemptEval(attr.argument);
848
+ } catch (e) {
884
849
  if (shouldPrintDebug) {
885
- console.log(` avoid optimizing:`, { couldntParse, shouldDeopt });
850
+ logger.info([" couldnt parse spread", e.message].join(" "));
886
851
  }
887
- node.attributes = ogAttributes;
852
+ flattenedAttrs.push(attr);
888
853
  return;
889
854
  }
890
- const parentFn = findTopmostFunction(traversePath);
891
- if (parentFn) {
892
- modifiedComponents.add(parentFn);
893
- }
894
- let ternaries = [];
895
- attrs = attrs.reduce((out, cur) => {
896
- const next = attrs[attrs.indexOf(cur) + 1];
897
- if (cur.type === "ternary") {
898
- ternaries.push(cur.value);
899
- }
900
- if ((!next || next.type !== "ternary") && ternaries.length) {
901
- const normalized = normalizeTernaries(ternaries).map(({ alternate, consequent, ...rest }) => {
902
- return {
903
- type: "ternary",
904
- value: {
905
- ...rest,
906
- alternate: alternate || null,
907
- consequent: consequent || null
908
- }
909
- };
910
- });
911
- try {
912
- return [...out, ...normalized];
913
- } finally {
855
+ if (arg !== void 0) {
856
+ try {
857
+ if (typeof arg !== "object" || arg == null) {
914
858
  if (shouldPrintDebug) {
915
- console.log(` normalizeTernaries (${ternaries.length} => ${normalized.length})`);
859
+ logger.info([" non object or null arg", arg].join(" "));
860
+ }
861
+ flattenedAttrs.push(attr);
862
+ } else {
863
+ for (const k in arg) {
864
+ const value = arg[k];
865
+ if (!value && typeof value === "object") {
866
+ logger.error(["Unhandled null prop", k, value, arg].join(" "));
867
+ continue;
868
+ }
869
+ flattenedAttrs.push(t.jsxAttribute(t.jsxIdentifier(k), t.jsxExpressionContainer(literalToAst(value))));
916
870
  }
917
- ternaries = [];
918
871
  }
872
+ } catch (err) {
873
+ logger.warn(`cant parse spread, caught err ${err}`);
874
+ couldntParse = true;
919
875
  }
920
- if (cur.type === "ternary") {
921
- return out;
876
+ }
877
+ });
878
+ if (couldntParse) {
879
+ return;
880
+ }
881
+ tm.mark("jsx-element-flattened", !!shouldPrintDebug);
882
+ node.attributes = flattenedAttrs;
883
+ let attrs = [];
884
+ let shouldDeopt = false;
885
+ const inlined = /* @__PURE__ */ new Map();
886
+ const variantValues = /* @__PURE__ */ new Map();
887
+ let hasSetOptimized = false;
888
+ const inlineWhenUnflattenedOGVals = {};
889
+ attrs = traversePath.get("openingElement").get("attributes").flatMap((path) => {
890
+ try {
891
+ const res2 = evaluateAttribute2(path);
892
+ tm.mark("jsx-element-evaluate-attr", !!shouldPrintDebug);
893
+ if (!res2) {
894
+ path.remove();
922
895
  }
923
- out.push(cur);
924
- return out;
925
- }, []).flat();
926
- const hasSpread = node.attributes.some((x) => t.isJSXSpreadAttribute(x));
927
- const hasOnlyStringChildren = !hasSpread && (node.selfClosing || traversePath.node.children && traversePath.node.children.every((x) => x.type === "JSXText"));
928
- const themeVal = inlined.get("theme");
929
- inlined.delete("theme");
930
- for (const [key] of [...inlined]) {
931
- const isExtractableVariant = staticConfig.variants?.[key] && variantValues.has(key);
932
- if (INLINE_EXTRACTABLE[key] || isExtractableVariant) {
933
- inlined.delete(key);
896
+ return res2;
897
+ } catch (err) {
898
+ if (shouldPrintDebug) {
899
+ logger.info(["Error extracting attribute", err.message, err.stack].join(" "));
900
+ logger.info(`node ${path.node}`);
934
901
  }
902
+ inlined.set(`${Math.random()}`, "spread");
903
+ return {
904
+ type: "attr",
905
+ value: path.node
906
+ };
935
907
  }
936
- const canFlattenProps = inlined.size === 0;
937
- let shouldFlatten = !shouldDeopt && canFlattenProps && !hasSpread && staticConfig.neverFlatten !== true && (staticConfig.neverFlatten === "jsx" ? hasOnlyStringChildren : true);
938
- const shouldWrapTheme = shouldFlatten && themeVal;
939
- if (disableExtractVariables) {
940
- themeAccessListeners.add((key) => {
941
- shouldFlatten = false;
908
+ }).flat(4).filter(isPresent);
909
+ if (shouldPrintDebug) {
910
+ logger.info([" - attrs (before):\n", logLines(attrs.map(attrStr).join(", "))].join(" "));
911
+ }
912
+ node.attributes = attrs.filter(isAttr).map((x) => x.value);
913
+ if (couldntParse || shouldDeopt) {
914
+ if (shouldPrintDebug) {
915
+ logger.info([` avoid optimizing:`, { couldntParse, shouldDeopt }].join(" "));
916
+ }
917
+ node.attributes = ogAttributes;
918
+ return;
919
+ }
920
+ const parentFn = findTopmostFunction(traversePath);
921
+ if (parentFn) {
922
+ modifiedComponents.add(parentFn);
923
+ }
924
+ let ternaries = [];
925
+ attrs = attrs.reduce((out, cur) => {
926
+ const next = attrs[attrs.indexOf(cur) + 1];
927
+ if (cur.type === "ternary") {
928
+ ternaries.push(cur.value);
929
+ }
930
+ if ((!next || next.type !== "ternary") && ternaries.length) {
931
+ const normalized = normalizeTernaries(ternaries).map(({ alternate, consequent, ...rest }) => {
932
+ return {
933
+ type: "ternary",
934
+ value: {
935
+ ...rest,
936
+ alternate: alternate || null,
937
+ consequent: consequent || null
938
+ }
939
+ };
940
+ });
941
+ try {
942
+ return [...out, ...normalized];
943
+ } finally {
942
944
  if (shouldPrintDebug) {
943
- console.log(" ! accessing theme key, avoid flatten", key);
945
+ logger.info(` normalizeTernaries (${ternaries.length} => ${normalized.length})`);
944
946
  }
945
- });
947
+ ternaries = [];
948
+ }
946
949
  }
947
- if (shouldPrintDebug) {
948
- console.log(" - flatten?", objToStr({ hasSpread, shouldDeopt, shouldFlatten, canFlattenProps, shouldWrapTheme, hasOnlyStringChildren }), "inlined", [...inlined]);
950
+ if (cur.type === "ternary") {
951
+ return out;
949
952
  }
950
- if (shouldFlatten && shouldWrapTheme) {
953
+ out.push(cur);
954
+ return out;
955
+ }, []).flat();
956
+ const hasSpread = node.attributes.some((x) => t.isJSXSpreadAttribute(x));
957
+ const hasOnlyStringChildren = !hasSpread && (node.selfClosing || traversePath.node.children && traversePath.node.children.every((x) => x.type === "JSXText"));
958
+ const themeVal = inlined.get("theme");
959
+ inlined.delete("theme");
960
+ for (const [key] of [...inlined]) {
961
+ const isExtractableVariant = staticConfig.variants?.[key] && variantValues.has(key);
962
+ if (INLINE_EXTRACTABLE[key] || isExtractableVariant) {
963
+ inlined.delete(key);
964
+ }
965
+ }
966
+ const canFlattenProps = inlined.size === 0;
967
+ let shouldFlatten = !shouldDeopt && canFlattenProps && !hasSpread && staticConfig.neverFlatten !== true && (staticConfig.neverFlatten === "jsx" ? hasOnlyStringChildren : true);
968
+ const shouldWrapTheme = shouldFlatten && themeVal;
969
+ if (disableExtractVariables) {
970
+ themeAccessListeners.add((key) => {
971
+ shouldFlatten = false;
951
972
  if (shouldPrintDebug) {
952
- console.log(" - wrapping theme", themeVal);
953
- }
954
- attrs = attrs.filter((x) => x.type === "attr" && t.isJSXAttribute(x.value) && x.value.name.name === "theme" ? false : true);
955
- if (!hasImportedTheme) {
956
- hasImportedTheme = true;
957
- programPath.node.body.push(t.importDeclaration([t.importSpecifier(t.identifier("_TamaguiTheme"), t.identifier("Theme"))], t.stringLiteral("@tamagui/core")));
973
+ logger.info([" ! accessing theme key, avoid flatten", key].join(" "));
958
974
  }
959
- traversePath.replaceWith(t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier("_TamaguiTheme"), [
960
- t.jsxAttribute(t.jsxIdentifier("name"), themeVal.value)
961
- ]), t.jsxClosingElement(t.jsxIdentifier("_TamaguiTheme")), [traversePath.node]));
975
+ });
976
+ }
977
+ if (shouldPrintDebug) {
978
+ logger.info([" - flatten?", objToStr({ hasSpread, shouldDeopt, shouldFlatten, canFlattenProps, shouldWrapTheme, hasOnlyStringChildren }), "inlined", [...inlined]].join(" "));
979
+ }
980
+ if (shouldFlatten && shouldWrapTheme) {
981
+ if (shouldPrintDebug) {
982
+ logger.info([" - wrapping theme", themeVal].join(" "));
962
983
  }
963
- if (shouldFlatten) {
964
- const defaultStyleAttrs = Object.keys(staticConfig.defaultProps).flatMap((key) => {
965
- if (!isValidStyleKey(key, staticConfig)) {
966
- return [];
967
- }
968
- const value = staticConfig.defaultProps[key];
969
- const name = tamaguiConfig.shorthands[key] || key;
970
- if (value === void 0) {
971
- console.warn(`\u26A0\uFE0F Error evaluating default style for component, prop ${key} ${value}`);
972
- shouldDeopt = true;
973
- return;
974
- }
975
- const attr = {
976
- type: "style",
977
- name,
978
- value: { [name]: value }
979
- };
980
- return attr;
981
- });
982
- if (defaultStyleAttrs.length) {
983
- attrs = [...defaultStyleAttrs, ...attrs];
984
- }
984
+ attrs = attrs.filter((x) => x.type === "attr" && t.isJSXAttribute(x.value) && x.value.name.name === "theme" ? false : true);
985
+ if (!hasImportedTheme) {
986
+ hasImportedTheme = true;
987
+ programPath.node.body.push(t.importDeclaration([t.importSpecifier(t.identifier("_TamaguiTheme"), t.identifier("Theme"))], t.stringLiteral("@tamagui/core")));
985
988
  }
986
- if (shouldDeopt) {
987
- node.attributes = ogAttributes;
988
- return;
989
+ traversePath.replaceWith(t.jsxElement(t.jsxOpeningElement(t.jsxIdentifier("_TamaguiTheme"), [
990
+ t.jsxAttribute(t.jsxIdentifier("name"), themeVal.value)
991
+ ]), t.jsxClosingElement(t.jsxIdentifier("_TamaguiTheme")), [traversePath.node]));
992
+ }
993
+ if (shouldFlatten) {
994
+ const defaultStyleAttrs = Object.keys(staticConfig.defaultProps).flatMap((key) => {
995
+ if (!isValidStyleKey(key, staticConfig)) {
996
+ return [];
997
+ }
998
+ const value = staticConfig.defaultProps[key];
999
+ const name = tamaguiConfig.shorthands[key] || key;
1000
+ if (value === void 0) {
1001
+ logger.warn(`\u26A0\uFE0F Error evaluating default style for component, prop ${key} ${value}`);
1002
+ shouldDeopt = true;
1003
+ return;
1004
+ }
1005
+ const attr = {
1006
+ type: "style",
1007
+ name,
1008
+ value: { [name]: value }
1009
+ };
1010
+ return attr;
1011
+ });
1012
+ if (defaultStyleAttrs.length) {
1013
+ attrs = [...defaultStyleAttrs, ...attrs];
989
1014
  }
990
- const ensureOverridden = {};
991
- if (!shouldFlatten) {
992
- for (const cur of attrs) {
993
- if (cur.type === "style") {
994
- for (const key in cur.value) {
995
- const shouldEnsureOverridden = !!staticConfig.ensureOverriddenProp?.[key];
996
- const isSetInAttrsAlready = attrs.some((x) => x.type === "attr" && x.value.type === "JSXAttribute" && x.value.name.name === key);
997
- if (!isSetInAttrsAlready) {
998
- const isVariant = !!staticConfig.variants?.[cur.name || ""];
999
- if (isVariant || shouldEnsureOverridden) {
1000
- ensureOverridden[key] = true;
1001
- }
1015
+ }
1016
+ if (shouldDeopt) {
1017
+ node.attributes = ogAttributes;
1018
+ return;
1019
+ }
1020
+ const ensureOverridden = {};
1021
+ if (!shouldFlatten) {
1022
+ for (const cur of attrs) {
1023
+ if (cur.type === "style") {
1024
+ for (const key in cur.value) {
1025
+ const shouldEnsureOverridden = !!staticConfig.ensureOverriddenProp?.[key];
1026
+ const isSetInAttrsAlready = attrs.some((x) => x.type === "attr" && x.value.type === "JSXAttribute" && x.value.name.name === key);
1027
+ if (!isSetInAttrsAlready) {
1028
+ const isVariant = !!staticConfig.variants?.[cur.name || ""];
1029
+ if (isVariant || shouldEnsureOverridden) {
1030
+ ensureOverridden[key] = true;
1002
1031
  }
1003
1032
  }
1004
1033
  }
1005
1034
  }
1006
1035
  }
1007
- if (shouldPrintDebug) {
1008
- console.log(" - attrs (flattened): \n", logLines(attrs.map(attrStr).join(", ")));
1009
- console.log(" - ensureOverriden:", Object.keys(ensureOverridden).join(", "));
1036
+ }
1037
+ if (shouldPrintDebug) {
1038
+ logger.info([" - attrs (flattened): \n", logLines(attrs.map(attrStr).join(", "))].join(" "));
1039
+ logger.info([" - ensureOverriden:", Object.keys(ensureOverridden).join(", ")].join(" "));
1040
+ }
1041
+ const state = {
1042
+ noClassNames: false,
1043
+ focus: false,
1044
+ hover: false,
1045
+ mounted: true,
1046
+ press: false,
1047
+ pressIn: false
1048
+ };
1049
+ let foundStaticProps = {};
1050
+ for (const key in attrs) {
1051
+ const cur = attrs[key];
1052
+ if (cur.type === "style") {
1053
+ foundStaticProps = {
1054
+ ...foundStaticProps,
1055
+ ...expandStylesWithoutVariants2(cur.value)
1056
+ };
1057
+ continue;
1010
1058
  }
1011
- const state = {
1012
- noClassNames: false,
1013
- focus: false,
1014
- hover: false,
1015
- mounted: true,
1016
- press: false,
1017
- pressIn: false
1018
- };
1019
- let foundStaticProps = {};
1020
- for (const key in attrs) {
1021
- const cur = attrs[key];
1022
- if (cur.type === "style") {
1023
- foundStaticProps = {
1024
- ...foundStaticProps,
1025
- ...expandStylesWithoutVariants2(cur.value)
1026
- };
1059
+ if (cur.type === "attr") {
1060
+ if (t.isJSXSpreadAttribute(cur.value)) {
1027
1061
  continue;
1028
1062
  }
1029
- if (cur.type === "attr") {
1030
- if (t.isJSXSpreadAttribute(cur.value)) {
1031
- continue;
1032
- }
1033
- if (!t.isJSXIdentifier(cur.value.name)) {
1034
- continue;
1035
- }
1036
- const key2 = cur.value.name.name;
1037
- const value = attemptEvalSafe(cur.value.value || t.booleanLiteral(true));
1038
- if (value !== FAILED_EVAL) {
1039
- foundStaticProps = {
1040
- ...foundStaticProps,
1041
- [key2]: value
1042
- };
1043
- }
1063
+ if (!t.isJSXIdentifier(cur.value.name)) {
1064
+ continue;
1044
1065
  }
1045
- }
1046
- const completeProps = {};
1047
- for (const key in staticConfig.defaultProps) {
1048
- if (!(key in foundStaticProps)) {
1049
- completeProps[key] = staticConfig.defaultProps[key];
1066
+ const key2 = cur.value.name.name;
1067
+ const value = attemptEvalSafe(cur.value.value || t.booleanLiteral(true));
1068
+ if (value !== FAILED_EVAL) {
1069
+ foundStaticProps = {
1070
+ ...foundStaticProps,
1071
+ [key2]: value
1072
+ };
1050
1073
  }
1051
1074
  }
1052
- for (const key in foundStaticProps) {
1053
- completeProps[key] = foundStaticProps[key];
1075
+ }
1076
+ const completeProps = {};
1077
+ for (const key in staticConfig.defaultProps) {
1078
+ if (!(key in foundStaticProps)) {
1079
+ completeProps[key] = staticConfig.defaultProps[key];
1054
1080
  }
1055
- attrs = attrs.reduce((acc, cur) => {
1056
- if (!cur)
1057
- return acc;
1058
- if (cur.type === "attr" && !t.isJSXSpreadAttribute(cur.value)) {
1059
- if (shouldFlatten) {
1060
- const name = cur.value.name.name;
1061
- if (typeof name === "string") {
1062
- if (name === "tag") {
1063
- return acc;
1081
+ }
1082
+ for (const key in foundStaticProps) {
1083
+ completeProps[key] = foundStaticProps[key];
1084
+ }
1085
+ attrs = attrs.reduce((acc, cur) => {
1086
+ if (!cur)
1087
+ return acc;
1088
+ if (cur.type === "attr" && !t.isJSXSpreadAttribute(cur.value)) {
1089
+ if (shouldFlatten) {
1090
+ const name = cur.value.name.name;
1091
+ if (typeof name === "string") {
1092
+ if (name === "tag") {
1093
+ return acc;
1094
+ }
1095
+ if (variants[name] && variantValues.has(name)) {
1096
+ let out = Object.fromEntries(staticConfig.propMapper(name, variantValues.get(name), defaultTheme, completeProps, { ...state, resolveVariablesAs: "auto" }, void 0, void 0, shouldPrintDebug) || []);
1097
+ if (out && isTargetingHTML) {
1098
+ const cn = out.className;
1099
+ out = createDOMProps(isTextView ? "span" : "div", out);
1100
+ out.className = cn;
1064
1101
  }
1065
- if (variants[name] && variantValues.has(name)) {
1066
- let out = Object.fromEntries(staticConfig.propMapper(name, variantValues.get(name), defaultTheme, completeProps, { ...state, resolveVariablesAs: "auto" }, void 0, void 0, shouldPrintDebug) || []);
1067
- if (out && isTargetingHTML) {
1068
- const cn = out.className;
1069
- out = createDOMProps(isTextView ? "span" : "div", out);
1070
- out.className = cn;
1071
- }
1072
- if (shouldPrintDebug) {
1073
- console.log(" - expanded variant", name, out);
1074
- }
1075
- for (const key2 in out) {
1076
- const value2 = out[key2];
1077
- if (isValidStyleKey(key2, staticConfig)) {
1078
- acc.push({
1079
- type: "style",
1080
- value: { [key2]: value2 },
1081
- name: key2,
1082
- attr: cur.value
1083
- });
1084
- } else {
1085
- acc.push({
1086
- type: "attr",
1087
- value: t.jsxAttribute(t.jsxIdentifier(key2), t.jsxExpressionContainer(typeof value2 === "string" ? t.stringLiteral(value2) : literalToAst(value2)))
1088
- });
1089
- }
1102
+ if (shouldPrintDebug) {
1103
+ logger.info([" - expanded variant", name, out].join(" "));
1104
+ }
1105
+ for (const key2 in out) {
1106
+ const value2 = out[key2];
1107
+ if (isValidStyleKey(key2, staticConfig)) {
1108
+ acc.push({
1109
+ type: "style",
1110
+ value: { [key2]: value2 },
1111
+ name: key2,
1112
+ attr: cur.value
1113
+ });
1114
+ } else {
1115
+ acc.push({
1116
+ type: "attr",
1117
+ value: t.jsxAttribute(t.jsxIdentifier(key2), t.jsxExpressionContainer(typeof value2 === "string" ? t.stringLiteral(value2) : literalToAst(value2)))
1118
+ });
1090
1119
  }
1091
1120
  }
1092
1121
  }
1093
1122
  }
1094
1123
  }
1095
- if (cur.type !== "style") {
1096
- acc.push(cur);
1097
- return acc;
1098
- }
1099
- let key = Object.keys(cur.value)[0];
1100
- const value = cur.value[key];
1101
- const fullKey = tamaguiConfig.shorthands[key];
1102
- if (fullKey) {
1103
- cur.value = { [fullKey]: value };
1104
- key = fullKey;
1105
- }
1106
- if (disableExtractVariables) {
1107
- if (value[0] === "$") {
1108
- if (shouldPrintDebug) {
1109
- console.log(` keeping variable inline: ${key} =`, value);
1110
- }
1111
- acc.push({
1112
- type: "attr",
1113
- value: t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(t.stringLiteral(value)))
1114
- });
1115
- return acc;
1116
- }
1117
- }
1124
+ }
1125
+ if (cur.type !== "style") {
1118
1126
  acc.push(cur);
1119
1127
  return acc;
1120
- }, []);
1121
- tm.mark("jsx-element-expanded", shouldPrintDebug === "verbose");
1122
- if (shouldPrintDebug) {
1123
- console.log(" - attrs (expanded): \n", logLines(attrs.map(attrStr).join(", ")));
1124
1128
  }
1125
- let prev = null;
1126
- attrs = attrs.reduce((acc, cur) => {
1127
- if (cur.type === "style") {
1128
- const key = Object.keys(cur.value)[0];
1129
- const value = cur.value[key];
1130
- const shouldKeepOriginalAttr = !shouldFlatten && !validStyles[key] && !pseudoDescriptors[key] && !key.startsWith("data-");
1131
- if (shouldKeepOriginalAttr) {
1132
- if (shouldPrintDebug) {
1133
- console.log(" - keeping as non-style", key);
1134
- }
1135
- prev = cur;
1136
- acc.push({
1137
- type: "attr",
1138
- value: t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(typeof value === "string" ? t.stringLiteral(value) : literalToAst(value)))
1139
- });
1140
- acc.push(cur);
1141
- return acc;
1142
- }
1143
- if (ensureOverridden[key]) {
1144
- acc.push({
1145
- type: "attr",
1146
- value: cur.attr || t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(t.nullLiteral()))
1147
- });
1148
- }
1149
- if (prev?.type === "style") {
1150
- mergeStyles2(prev.value, cur.value);
1151
- return acc;
1129
+ let key = Object.keys(cur.value)[0];
1130
+ const value = cur.value[key];
1131
+ const fullKey = tamaguiConfig.shorthands[key];
1132
+ if (fullKey) {
1133
+ cur.value = { [fullKey]: value };
1134
+ key = fullKey;
1135
+ }
1136
+ if (disableExtractVariables) {
1137
+ if (value[0] === "$") {
1138
+ if (shouldPrintDebug) {
1139
+ logger.info([` keeping variable inline: ${key} =`, value].join(" "));
1152
1140
  }
1141
+ acc.push({
1142
+ type: "attr",
1143
+ value: t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(t.stringLiteral(value)))
1144
+ });
1145
+ return acc;
1153
1146
  }
1154
- prev = cur;
1155
- acc.push(cur);
1156
- return acc;
1157
- }, []);
1158
- if (shouldPrintDebug) {
1159
- console.log(" - attrs (combined \u{1F500}): \n", logLines(attrs.map(attrStr).join(", ")));
1160
- console.log(" - defaultProps: \n", logLines(objToStr(staticConfig.defaultProps)));
1161
- console.log(" - foundStaticProps: \n", logLines(objToStr(foundStaticProps)));
1162
- console.log(" - completeProps: \n", logLines(objToStr(completeProps)));
1163
1147
  }
1164
- const getStyles = (props2, debugName = "") => {
1165
- if (!props2 || !Object.keys(props2).length) {
1166
- if (shouldPrintDebug)
1167
- console.log(" getStyles() no props");
1168
- return {};
1169
- }
1170
- if (excludeProps && !!excludeProps.size) {
1171
- for (const key in props2) {
1172
- if (excludeProps.has(key)) {
1173
- if (shouldPrintDebug)
1174
- console.log(" delete excluded", key);
1175
- delete props2[key];
1176
- }
1148
+ acc.push(cur);
1149
+ return acc;
1150
+ }, []);
1151
+ tm.mark("jsx-element-expanded", !!shouldPrintDebug);
1152
+ if (shouldPrintDebug) {
1153
+ logger.info([" - attrs (expanded): \n", logLines(attrs.map(attrStr).join(", "))].join(" "));
1154
+ }
1155
+ let prev = null;
1156
+ attrs = attrs.reduce((acc, cur) => {
1157
+ if (cur.type === "style") {
1158
+ const key = Object.keys(cur.value)[0];
1159
+ const value = cur.value[key];
1160
+ const shouldKeepOriginalAttr = !shouldFlatten && !validStyles[key] && !pseudoDescriptors[key] && !key.startsWith("data-");
1161
+ if (shouldKeepOriginalAttr) {
1162
+ if (shouldPrintDebug) {
1163
+ logger.info([" - keeping as non-style", key].join(" "));
1177
1164
  }
1165
+ prev = cur;
1166
+ acc.push({
1167
+ type: "attr",
1168
+ value: t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(typeof value === "string" ? t.stringLiteral(value) : literalToAst(value)))
1169
+ });
1170
+ acc.push(cur);
1171
+ return acc;
1178
1172
  }
1179
- try {
1180
- const out = getSplitStyles(props2, staticConfig, defaultTheme, {
1181
- ...state,
1182
- fallbackProps: completeProps
1183
- }, void 0, props2["debug"]);
1184
- const outStyle = {
1185
- ...out.style,
1186
- ...out.pseudos
1187
- };
1188
- return outStyle;
1189
- } catch (err) {
1190
- console.log("error", err.message, err.stack);
1191
- return {};
1173
+ if (ensureOverridden[key]) {
1174
+ acc.push({
1175
+ type: "attr",
1176
+ value: cur.attr || t.jsxAttribute(t.jsxIdentifier(key), t.jsxExpressionContainer(t.nullLiteral()))
1177
+ });
1178
+ }
1179
+ if (prev?.type === "style") {
1180
+ mergeStyles2(prev.value, cur.value);
1181
+ return acc;
1192
1182
  }
1193
- };
1194
- const completeStyles = getStyles(completeProps, "completeStyles");
1195
- if (!completeStyles) {
1196
- throw new Error(`Impossible, no styles`);
1197
1183
  }
1198
- let getStyleError = null;
1199
- for (const attr of attrs) {
1200
- try {
1201
- switch (attr.type) {
1202
- case "ternary":
1203
- const a = getStyles(attr.value.alternate, "ternary.alternate");
1204
- const c = getStyles(attr.value.consequent, "ternary.consequent");
1205
- if (a)
1206
- attr.value.alternate = a;
1207
- if (c)
1208
- attr.value.consequent = c;
1209
- if (shouldPrintDebug)
1210
- console.log(" => tern ", attrStr(attr));
1211
- continue;
1212
- case "style":
1213
- const styles = getStyles(attr.value, "style");
1214
- if (styles) {
1215
- attr.value = styles;
1216
- }
1217
- if (shouldPrintDebug)
1218
- console.log(" * styles (in)", logLines(objToStr(attr.value)));
1219
- if (shouldPrintDebug)
1220
- console.log(" * styles (out)", logLines(objToStr(styles)));
1221
- continue;
1184
+ prev = cur;
1185
+ acc.push(cur);
1186
+ return acc;
1187
+ }, []);
1188
+ if (shouldPrintDebug) {
1189
+ logger.info([" - attrs (combined \u{1F500}): \n", logLines(attrs.map(attrStr).join(", "))].join(" "));
1190
+ logger.info([" - defaultProps: \n", logLines(objToStr(staticConfig.defaultProps))].join(" "));
1191
+ logger.info([" - foundStaticProps: \n", logLines(objToStr(foundStaticProps))].join(" "));
1192
+ logger.info([" - completeProps: \n", logLines(objToStr(completeProps))].join(" "));
1193
+ }
1194
+ const getStyles = (props2, debugName = "") => {
1195
+ if (!props2 || !Object.keys(props2).length) {
1196
+ if (shouldPrintDebug)
1197
+ logger.info([" getStyles() no props"].join(" "));
1198
+ return {};
1199
+ }
1200
+ if (excludeProps && !!excludeProps.size) {
1201
+ for (const key in props2) {
1202
+ if (excludeProps.has(key)) {
1203
+ if (shouldPrintDebug)
1204
+ logger.info([" delete excluded", key].join(" "));
1205
+ delete props2[key];
1222
1206
  }
1223
- } catch (err) {
1224
- getStyleError = err;
1225
1207
  }
1226
1208
  }
1227
- if (shouldPrintDebug) {
1228
- console.log(" - attrs (ternaries/combined):\n", logLines(attrs.map(attrStr).join(", ")));
1229
- }
1230
- tm.mark("jsx-element-styles", shouldPrintDebug === "verbose");
1231
- if (getStyleError) {
1232
- console.log(" \u26A0\uFE0F postprocessing error, deopt", getStyleError);
1233
- node.attributes = ogAttributes;
1234
- return node;
1209
+ try {
1210
+ const out = getSplitStyles(props2, staticConfig, defaultTheme, {
1211
+ ...state,
1212
+ fallbackProps: completeProps
1213
+ }, void 0, props2["debug"]);
1214
+ const outStyle = {
1215
+ ...out.style,
1216
+ ...out.pseudos
1217
+ };
1218
+ return outStyle;
1219
+ } catch (err) {
1220
+ logger.info(["error", err.message, err.stack].join(" "));
1221
+ return {};
1235
1222
  }
1236
- const existingStyleKeys = /* @__PURE__ */ new Set();
1237
- for (let i = attrs.length - 1; i >= 0; i--) {
1238
- const attr = attrs[i];
1239
- if (shouldFlatten) {
1240
- if (attr.type === "attr") {
1241
- if (t.isJSXAttribute(attr.value)) {
1242
- if (t.isJSXIdentifier(attr.value.name)) {
1243
- const name = attr.value.name.name;
1244
- if (INLINE_EXTRACTABLE[name]) {
1245
- attr.value.name.name = INLINE_EXTRACTABLE[name];
1246
- }
1247
- }
1223
+ };
1224
+ const completeStyles = getStyles(completeProps, "completeStyles");
1225
+ if (!completeStyles) {
1226
+ throw new Error(`Impossible, no styles`);
1227
+ }
1228
+ let getStyleError = null;
1229
+ for (const attr of attrs) {
1230
+ try {
1231
+ switch (attr.type) {
1232
+ case "ternary": {
1233
+ const a = getStyles(attr.value.alternate, "ternary.alternate");
1234
+ const c = getStyles(attr.value.consequent, "ternary.consequent");
1235
+ if (a)
1236
+ attr.value.alternate = a;
1237
+ if (c)
1238
+ attr.value.consequent = c;
1239
+ if (shouldPrintDebug)
1240
+ logger.info([" => tern ", attrStr(attr)].join(" "));
1241
+ continue;
1242
+ }
1243
+ case "style": {
1244
+ const styles = getStyles(attr.value, "style");
1245
+ if (styles) {
1246
+ attr.value = styles;
1248
1247
  }
1248
+ if (shouldPrintDebug)
1249
+ logger.info([" * styles (in)", logLines(objToStr(attr.value))].join(" "));
1250
+ if (shouldPrintDebug)
1251
+ logger.info([" * styles (out)", logLines(objToStr(styles))].join(" "));
1252
+ continue;
1249
1253
  }
1250
1254
  }
1251
- if (attr.type === "style") {
1252
- for (const key in attr.value) {
1253
- if (existingStyleKeys.has(key)) {
1254
- if (shouldPrintDebug) {
1255
- console.log(" >> delete existing", key);
1255
+ } catch (err) {
1256
+ getStyleError = err;
1257
+ }
1258
+ }
1259
+ if (shouldPrintDebug) {
1260
+ logger.info([" - attrs (ternaries/combined):\n", logLines(attrs.map(attrStr).join(", "))].join(" "));
1261
+ }
1262
+ tm.mark("jsx-element-styles", !!shouldPrintDebug);
1263
+ if (getStyleError) {
1264
+ logger.info([" \u26A0\uFE0F postprocessing error, deopt", getStyleError].join(" "));
1265
+ node.attributes = ogAttributes;
1266
+ return node;
1267
+ }
1268
+ const existingStyleKeys = /* @__PURE__ */ new Set();
1269
+ for (let i = attrs.length - 1; i >= 0; i--) {
1270
+ const attr = attrs[i];
1271
+ if (shouldFlatten) {
1272
+ if (attr.type === "attr") {
1273
+ if (t.isJSXAttribute(attr.value)) {
1274
+ if (t.isJSXIdentifier(attr.value.name)) {
1275
+ const name = attr.value.name.name;
1276
+ if (INLINE_EXTRACTABLE[name]) {
1277
+ attr.value.name.name = INLINE_EXTRACTABLE[name];
1256
1278
  }
1257
- delete attr.value[key];
1258
- } else {
1259
- existingStyleKeys.add(key);
1260
1279
  }
1261
1280
  }
1262
1281
  }
1263
1282
  }
1264
- if (!shouldFlatten) {
1265
- if (inlineWhenUnflattened.size) {
1266
- for (const [index, attr] of attrs.entries()) {
1267
- if (attr.type === "style") {
1268
- for (const key in attr.value) {
1269
- if (!inlineWhenUnflattened.has(key))
1270
- continue;
1271
- const val = inlineWhenUnflattenedOGVals[key];
1272
- if (val) {
1273
- delete attr.value[key];
1274
- attrs.splice(index - 1, 0, val.attr);
1275
- } else {
1276
- delete attr.value[key];
1277
- }
1278
- }
1283
+ if (attr.type === "style") {
1284
+ for (const key in attr.value) {
1285
+ if (existingStyleKeys.has(key)) {
1286
+ if (shouldPrintDebug) {
1287
+ logger.info([` >> delete existing ${key}`].join(" "));
1279
1288
  }
1289
+ delete attr.value[key];
1290
+ } else {
1291
+ existingStyleKeys.add(key);
1280
1292
  }
1281
1293
  }
1282
1294
  }
1283
- if (shouldFlatten) {
1284
- if (shouldPrintDebug) {
1285
- console.log(" [\u2705] flattening", originalNodeName, flatNode);
1286
- }
1287
- node.name.name = flatNode;
1288
- res.flattened++;
1289
- if (closingElement) {
1290
- closingElement.name.name = flatNode;
1295
+ }
1296
+ if (!shouldFlatten) {
1297
+ if (inlineWhenUnflattened.size) {
1298
+ for (const [index, attr] of attrs.entries()) {
1299
+ if (attr.type === "style") {
1300
+ for (const key in attr.value) {
1301
+ if (!inlineWhenUnflattened.has(key))
1302
+ continue;
1303
+ const val = inlineWhenUnflattenedOGVals[key];
1304
+ if (val) {
1305
+ delete attr.value[key];
1306
+ attrs.splice(index - 1, 0, val.attr);
1307
+ } else {
1308
+ delete attr.value[key];
1309
+ }
1310
+ }
1311
+ }
1291
1312
  }
1292
1313
  }
1314
+ }
1315
+ if (shouldFlatten) {
1293
1316
  if (shouldPrintDebug) {
1294
- console.log(` \u274A\u274A inline props (${inlined.size}):`, shouldDeopt ? " deopted" : "", hasSpread ? " has spread" : "", staticConfig.neverFlatten ? "neverFlatten" : "");
1295
- console.log(" - attrs (end):\n", logLines(attrs.map(attrStr).join(", ")));
1317
+ logger.info([" [\u2705] flattening", originalNodeName, flatNode].join(" "));
1296
1318
  }
1297
- onExtractTag({
1298
- attrs,
1299
- node,
1300
- lineNumbers,
1301
- filePath,
1302
- attemptEval,
1303
- jsxPath: traversePath,
1304
- originalNodeName,
1305
- isFlattened: shouldFlatten,
1306
- programPath,
1307
- completeProps,
1308
- staticConfig
1309
- });
1310
- } finally {
1311
- if (debugPropValue) {
1312
- shouldPrintDebug = ogDebug;
1319
+ node.name.name = flatNode;
1320
+ res.flattened++;
1321
+ if (closingElement) {
1322
+ closingElement.name.name = flatNode;
1313
1323
  }
1314
1324
  }
1325
+ if (shouldPrintDebug) {
1326
+ logger.info([` \u274A\u274A inline props (${inlined.size}):`, shouldDeopt ? " deopted" : "", hasSpread ? " has spread" : "", staticConfig.neverFlatten ? "neverFlatten" : ""].join(" "));
1327
+ logger.info(` - attrs (end):
1328
+ ${logLines(attrs.map(attrStr).join(", "))}`);
1329
+ }
1330
+ onExtractTag({
1331
+ attrs,
1332
+ node,
1333
+ lineNumbers,
1334
+ filePath,
1335
+ attemptEval,
1336
+ jsxPath: traversePath,
1337
+ originalNodeName,
1338
+ isFlattened: shouldFlatten,
1339
+ programPath,
1340
+ completeProps,
1341
+ staticConfig
1342
+ });
1343
+ } finally {
1344
+ if (debugPropValue) {
1345
+ shouldPrintDebug = ogDebug;
1346
+ }
1315
1347
  }
1316
- });
1317
- tm.mark("jsx-done", shouldPrintDebug === "verbose");
1318
- if (modifiedComponents.size) {
1319
- const all = Array.from(modifiedComponents);
1320
- if (shouldPrintDebug) {
1321
- console.log(" [\u{1FA9D}] hook check", all.length);
1322
- }
1323
- for (const comp of all) {
1324
- removeUnusedHooks(comp, shouldPrintDebug);
1325
- }
1326
1348
  }
1327
- tm.done(shouldPrintDebug === "verbose");
1328
- return res;
1349
+ });
1350
+ tm.mark("jsx-done", !!shouldPrintDebug);
1351
+ if (modifiedComponents.size) {
1352
+ const all = Array.from(modifiedComponents);
1353
+ if (shouldPrintDebug) {
1354
+ logger.info(` [\u{1FA9D}] hook check ${all.length}`);
1355
+ }
1356
+ for (const comp of all) {
1357
+ removeUnusedHooks(comp, shouldPrintDebug);
1358
+ }
1329
1359
  }
1330
- };
1360
+ tm.done(shouldPrintDebug === "verbose");
1361
+ return res;
1362
+ }
1331
1363
  }
1332
1364
  export {
1333
1365
  createExtractor