@tamagui/static 1.2.8 → 1.2.10

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