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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/dist/check-dep-versions.cjs +201 -96
  2. package/dist/checkDeps.cjs +250 -46
  3. package/dist/constants.cjs +32 -30
  4. package/dist/exports.cjs +18 -13
  5. package/dist/extractor/accessSafe.cjs +25 -23
  6. package/dist/extractor/babelParse.cjs +30 -28
  7. package/dist/extractor/buildClassName.cjs +59 -35
  8. package/dist/extractor/bundle.cjs +177 -101
  9. package/dist/extractor/bundleConfig.cjs +554 -167
  10. package/dist/extractor/concatClassName.cjs +41 -29
  11. package/dist/extractor/createEvaluator.cjs +54 -41
  12. package/dist/extractor/createExtractor.cjs +1400 -581
  13. package/dist/extractor/createLogger.cjs +30 -25
  14. package/dist/extractor/detectModuleFormat.cjs +55 -0
  15. package/dist/extractor/ensureImportingConcat.cjs +31 -25
  16. package/dist/extractor/errors.cjs +12 -10
  17. package/dist/extractor/esbuildAliasPlugin.cjs +28 -16
  18. package/dist/extractor/esbuildTsconfigPaths.cjs +60 -36
  19. package/dist/extractor/evaluateAstNode.cjs +104 -59
  20. package/dist/extractor/extractHelpers.cjs +130 -67
  21. package/dist/extractor/extractMediaStyle.cjs +110 -69
  22. package/dist/extractor/extractToClassNames.cjs +337 -229
  23. package/dist/extractor/extractToNative.cjs +248 -154
  24. package/dist/extractor/findTopmostFunction.cjs +22 -13
  25. package/dist/extractor/generatedUid.cjs +39 -28
  26. package/dist/extractor/getPrefixLogs.cjs +12 -10
  27. package/dist/extractor/getPropValueFromAttributes.cjs +52 -34
  28. package/dist/extractor/getSourceModule.cjs +73 -37
  29. package/dist/extractor/getStaticBindingsForScope.cjs +131 -68
  30. package/dist/extractor/getTamaguiConfigPathFromOptionsConfig.cjs +20 -14
  31. package/dist/extractor/hasTopLevelAwait.cjs +62 -0
  32. package/dist/extractor/hoistClassNames.cjs +46 -32
  33. package/dist/extractor/literalToAst.cjs +67 -42
  34. package/dist/extractor/loadFile.cjs +9 -3
  35. package/dist/extractor/loadTamagui.cjs +149 -104
  36. package/dist/extractor/logLines.cjs +27 -19
  37. package/dist/extractor/normalizeTernaries.cjs +66 -44
  38. package/dist/extractor/propsToFontFamilyCache.cjs +15 -11
  39. package/dist/extractor/regenerateConfig.cjs +109 -81
  40. package/dist/extractor/removeUnusedHooks.cjs +73 -41
  41. package/dist/extractor/timer.cjs +23 -14
  42. package/dist/extractor/validHTMLAttributes.cjs +61 -59
  43. package/dist/extractor/watchTamaguiConfig.cjs +35 -23
  44. package/dist/getPragmaOptions.cjs +38 -19
  45. package/dist/helpers/memoize.cjs +24 -16
  46. package/dist/helpers/requireTamaguiCore.cjs +22 -15
  47. package/dist/index.cjs +26 -24
  48. package/dist/registerRequire.cjs +167 -65
  49. package/dist/server.cjs +35 -28
  50. package/dist/types.cjs +7 -5
  51. package/dist/worker.cjs +62 -40
  52. package/package.json +26 -22
  53. package/src/checkDeps.ts +305 -68
  54. package/src/exports.ts +1 -0
  55. package/src/extractor/babelParse.ts +1 -0
  56. package/src/extractor/bundle.ts +140 -37
  57. package/src/extractor/bundleConfig.ts +435 -61
  58. package/src/extractor/createExtractor.ts +283 -48
  59. package/src/extractor/detectModuleFormat.ts +42 -0
  60. package/src/extractor/esbuildTsconfigPaths.ts +6 -1
  61. package/src/extractor/extractToClassNames.ts +15 -9
  62. package/src/extractor/extractToNative.ts +66 -33
  63. package/src/extractor/hasTopLevelAwait.ts +28 -0
  64. package/src/extractor/loadTamagui.ts +2 -2
  65. package/src/getPragmaOptions.ts +6 -1
  66. package/src/registerRequire.ts +88 -8
  67. package/types/checkDeps.d.ts.map +1 -1
  68. package/types/exports.d.ts +1 -0
  69. package/types/exports.d.ts.map +1 -1
  70. package/types/extractor/babelParse.d.ts.map +1 -1
  71. package/types/extractor/bundle.d.ts +83 -1
  72. package/types/extractor/bundle.d.ts.map +1 -1
  73. package/types/extractor/bundleConfig.d.ts +15 -2
  74. package/types/extractor/bundleConfig.d.ts.map +1 -1
  75. package/types/extractor/createExtractor.d.ts.map +1 -1
  76. package/types/extractor/detectModuleFormat.d.ts +5 -0
  77. package/types/extractor/detectModuleFormat.d.ts.map +1 -0
  78. package/types/extractor/esbuildTsconfigPaths.d.ts +8 -0
  79. package/types/extractor/esbuildTsconfigPaths.d.ts.map +1 -1
  80. package/types/extractor/extractToClassNames.d.ts.map +1 -1
  81. package/types/extractor/extractToNative.d.ts.map +1 -1
  82. package/types/extractor/hasTopLevelAwait.d.ts +2 -0
  83. package/types/extractor/hasTopLevelAwait.d.ts.map +1 -0
  84. package/types/getPragmaOptions.d.ts.map +1 -1
  85. package/types/registerRequire.d.ts.map +1 -1
  86. package/dist/check-dep-versions.js +0 -389
  87. package/dist/check-dep-versions.js.map +0 -6
  88. package/dist/checkDeps.js +0 -60
  89. package/dist/checkDeps.js.map +0 -6
  90. package/dist/constants.js +0 -34
  91. package/dist/constants.js.map +0 -6
  92. package/dist/exports.js +0 -34
  93. package/dist/exports.js.map +0 -6
  94. package/dist/extractor/accessSafe.js +0 -47
  95. package/dist/extractor/accessSafe.js.map +0 -6
  96. package/dist/extractor/babelParse.js +0 -59
  97. package/dist/extractor/babelParse.js.map +0 -6
  98. package/dist/extractor/buildClassName.js +0 -72
  99. package/dist/extractor/buildClassName.js.map +0 -6
  100. package/dist/extractor/bundle.js +0 -135
  101. package/dist/extractor/bundle.js.map +0 -6
  102. package/dist/extractor/bundleConfig.js +0 -352
  103. package/dist/extractor/bundleConfig.js.map +0 -6
  104. package/dist/extractor/concatClassName.js +0 -69
  105. package/dist/extractor/concatClassName.js.map +0 -6
  106. package/dist/extractor/createEvaluator.js +0 -66
  107. package/dist/extractor/createEvaluator.js.map +0 -6
  108. package/dist/extractor/createExtractor.js +0 -1215
  109. package/dist/extractor/createExtractor.js.map +0 -6
  110. package/dist/extractor/createLogger.js +0 -32
  111. package/dist/extractor/createLogger.js.map +0 -6
  112. package/dist/extractor/ensureImportingConcat.js +0 -50
  113. package/dist/extractor/ensureImportingConcat.js.map +0 -6
  114. package/dist/extractor/errors.js +0 -22
  115. package/dist/extractor/errors.js.map +0 -6
  116. package/dist/extractor/esbuildAliasPlugin.js +0 -36
  117. package/dist/extractor/esbuildAliasPlugin.js.map +0 -6
  118. package/dist/extractor/esbuildTsconfigPaths.js +0 -79
  119. package/dist/extractor/esbuildTsconfigPaths.js.map +0 -6
  120. package/dist/extractor/evaluateAstNode.js +0 -99
  121. package/dist/extractor/evaluateAstNode.js.map +0 -6
  122. package/dist/extractor/extractHelpers.js +0 -108
  123. package/dist/extractor/extractHelpers.js.map +0 -6
  124. package/dist/extractor/extractMediaStyle.js +0 -123
  125. package/dist/extractor/extractMediaStyle.js.map +0 -6
  126. package/dist/extractor/extractToClassNames.js +0 -351
  127. package/dist/extractor/extractToClassNames.js.map +0 -6
  128. package/dist/extractor/extractToNative.js +0 -286
  129. package/dist/extractor/extractToNative.js.map +0 -6
  130. package/dist/extractor/findTopmostFunction.js +0 -32
  131. package/dist/extractor/findTopmostFunction.js.map +0 -6
  132. package/dist/extractor/generatedUid.js +0 -42
  133. package/dist/extractor/generatedUid.js.map +0 -6
  134. package/dist/extractor/getPrefixLogs.js +0 -24
  135. package/dist/extractor/getPrefixLogs.js.map +0 -6
  136. package/dist/extractor/getPropValueFromAttributes.js +0 -65
  137. package/dist/extractor/getPropValueFromAttributes.js.map +0 -6
  138. package/dist/extractor/getSourceModule.js +0 -62
  139. package/dist/extractor/getSourceModule.js.map +0 -6
  140. package/dist/extractor/getStaticBindingsForScope.js +0 -145
  141. package/dist/extractor/getStaticBindingsForScope.js.map +0 -6
  142. package/dist/extractor/getTamaguiConfigPathFromOptionsConfig.js +0 -32
  143. package/dist/extractor/getTamaguiConfigPathFromOptionsConfig.js.map +0 -6
  144. package/dist/extractor/hoistClassNames.js +0 -63
  145. package/dist/extractor/hoistClassNames.js.map +0 -6
  146. package/dist/extractor/literalToAst.js +0 -90
  147. package/dist/extractor/literalToAst.js.map +0 -6
  148. package/dist/extractor/loadFile.js +0 -14
  149. package/dist/extractor/loadFile.js.map +0 -6
  150. package/dist/extractor/loadTamagui.js +0 -306
  151. package/dist/extractor/loadTamagui.js.map +0 -6
  152. package/dist/extractor/logLines.js +0 -30
  153. package/dist/extractor/logLines.js.map +0 -6
  154. package/dist/extractor/normalizeTernaries.js +0 -61
  155. package/dist/extractor/normalizeTernaries.js.map +0 -6
  156. package/dist/extractor/propsToFontFamilyCache.js +0 -33
  157. package/dist/extractor/propsToFontFamilyCache.js.map +0 -6
  158. package/dist/extractor/regenerateConfig.js +0 -123
  159. package/dist/extractor/regenerateConfig.js.map +0 -6
  160. package/dist/extractor/removeUnusedHooks.js +0 -72
  161. package/dist/extractor/removeUnusedHooks.js.map +0 -6
  162. package/dist/extractor/timer.js +0 -38
  163. package/dist/extractor/timer.js.map +0 -6
  164. package/dist/extractor/validHTMLAttributes.js +0 -72
  165. package/dist/extractor/validHTMLAttributes.js.map +0 -6
  166. package/dist/extractor/watchTamaguiConfig.js +0 -57
  167. package/dist/extractor/watchTamaguiConfig.js.map +0 -6
  168. package/dist/getPragmaOptions.js +0 -46
  169. package/dist/getPragmaOptions.js.map +0 -6
  170. package/dist/helpers/memoize.js +0 -33
  171. package/dist/helpers/memoize.js.map +0 -6
  172. package/dist/helpers/requireTamaguiCore.js +0 -30
  173. package/dist/helpers/requireTamaguiCore.js.map +0 -6
  174. package/dist/index.js +0 -30
  175. package/dist/index.js.map +0 -6
  176. package/dist/registerRequire.js +0 -100
  177. package/dist/registerRequire.js.map +0 -6
  178. package/dist/server.js +0 -58
  179. package/dist/server.js.map +0 -6
  180. package/dist/setup.js +0 -1
  181. package/dist/setup.js.map +0 -6
  182. package/dist/types.js +0 -14
  183. package/dist/types.js.map +0 -6
  184. package/dist/worker.js +0 -72
  185. package/dist/worker.js.map +0 -6
@@ -1,1215 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: !0 });
9
- }, __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from == "object" || typeof from == "function")
11
- for (let key of __getOwnPropNames(from))
12
- !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- return to;
14
- };
15
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
16
- // If the importer is in node compatibility mode or this is not an ESM
17
- // file that has been converted to a CommonJS file using a Babel-
18
- // compatible transform (i.e. "__esModule" has not been set), then set
19
- // "default" to the CommonJS "module.exports" for node compatibility.
20
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
21
- mod
22
- )), __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod);
23
- var createExtractor_exports = {};
24
- __export(createExtractor_exports, {
25
- createExtractor: () => createExtractor
26
- });
27
- module.exports = __toCommonJS(createExtractor_exports);
28
- var import_traverse = __toESM(require("@babel/traverse")), t = __toESM(require("@babel/types")), import_cli_color = require("@tamagui/cli-color"), reactNativeWebInternals = __toESM(require("@tamagui/react-native-web-internals")), import_web = require("@tamagui/web"), import_node_path = require("node:path"), import_constants = require("../constants"), import_requireTamaguiCore = require("../helpers/requireTamaguiCore"), import_createEvaluator = require("./createEvaluator"), import_evaluateAstNode = require("./evaluateAstNode"), import_extractHelpers = require("./extractHelpers"), import_findTopmostFunction = require("./findTopmostFunction"), import_getStaticBindingsForScope = require("./getStaticBindingsForScope"), import_literalToAst = require("./literalToAst"), import_loadTamagui = require("./loadTamagui"), import_logLines = require("./logLines"), import_normalizeTernaries = require("./normalizeTernaries"), import_propsToFontFamilyCache = require("./propsToFontFamilyCache"), import_timer = require("./timer"), import_validHTMLAttributes = require("./validHTMLAttributes"), import_errors = require("./errors");
29
- const UNTOUCHED_PROPS = {
30
- key: !0,
31
- style: !0,
32
- className: !0
33
- }, createTernary = (x) => x;
34
- let hasLoggedBaseInfo = !1;
35
- function isFullyDisabled(props) {
36
- return props.disableExtraction && props.disableDebugAttr;
37
- }
38
- function createExtractor({ logger = console, platform = "web" } = { logger: console }) {
39
- const INLINE_EXTRACTABLE = {
40
- ref: "ref",
41
- key: "key",
42
- ...platform === "web" && {
43
- onPress: "onClick",
44
- onHoverIn: "onMouseEnter",
45
- onHoverOut: "onMouseLeave",
46
- onPressIn: "onMouseDown",
47
- onPressOut: "onMouseUp"
48
- }
49
- }, componentState = {
50
- focus: !1,
51
- focusVisible: !1,
52
- focusWithin: !1,
53
- hover: !1,
54
- unmounted: !0,
55
- press: !1,
56
- pressIn: !1,
57
- disabled: !1
58
- }, styleProps = {
59
- resolveValues: "variable",
60
- noClass: !1,
61
- isAnimated: !1
62
- }, shouldAddDebugProp = (
63
- // really basic disable this for next.js because it messes with ssr
64
- !process.env.npm_package_dependencies_next && !0 && process.env.IDENTIFY_TAGS !== "false" && (process.env.NODE_ENV === "development" || process.env.IDENTIFY_TAGS)
65
- );
66
- let projectInfo = null;
67
- function loadSync(props) {
68
- return isFullyDisabled(props) ? null : projectInfo ||= (0, import_loadTamagui.loadTamaguiSync)(props);
69
- }
70
- async function load(props) {
71
- return isFullyDisabled(props) ? null : projectInfo ||= await (0, import_loadTamagui.loadTamagui)(props);
72
- }
73
- return {
74
- options: {
75
- logger
76
- },
77
- cleanupBeforeExit: import_getStaticBindingsForScope.cleanupBeforeExit,
78
- loadTamagui: load,
79
- loadTamaguiSync: loadSync,
80
- getTamagui() {
81
- return projectInfo?.tamaguiConfig;
82
- },
83
- parseSync: (f, props) => {
84
- globalThis.expo ||= {};
85
- const projectInfo2 = loadSync(props);
86
- return parseWithConfig(projectInfo2 || {}, f, props);
87
- },
88
- parse: async (f, props) => {
89
- globalThis.expo ||= {};
90
- const projectInfo2 = await load(props);
91
- return parseWithConfig(projectInfo2 || {}, f, props);
92
- }
93
- };
94
- function parseWithConfig({ components, tamaguiConfig }, fileOrPath, options) {
95
- const {
96
- config = "tamagui.config.ts",
97
- importsWhitelist = ["constants.js"],
98
- evaluateVars = !0,
99
- sourcePath = "",
100
- onExtractTag,
101
- onStyledDefinitionRule,
102
- getFlattenedNode,
103
- disable,
104
- disableExtraction,
105
- disableExtractVariables,
106
- disableDebugAttr,
107
- enableDynamicEvaluation = !1,
108
- includeExtensions = [".ts", ".tsx", ".jsx"],
109
- extractStyledDefinitions = !1,
110
- prefixLogs,
111
- excludeProps,
112
- platform: platform2,
113
- ...restProps
114
- } = options;
115
- if (sourcePath.includes(".tamagui-dynamic-eval"))
116
- return null;
117
- const {
118
- normalizeStyle,
119
- getSplitStyles,
120
- mediaQueryConfig,
121
- propMapper,
122
- proxyThemeVariables,
123
- getDefaultProps,
124
- pseudoDescriptors
125
- } = (0, import_requireTamaguiCore.requireTamaguiCore)(platform2);
126
- let shouldPrintDebug = options.shouldPrintDebug || !1;
127
- if (disable === !0 || Array.isArray(disable) && disable.includes(sourcePath))
128
- return null;
129
- if (!isFullyDisabled(options) && !components)
130
- throw new Error("Must provide components");
131
- if (sourcePath && includeExtensions && !includeExtensions.some((ext) => sourcePath.endsWith(ext)))
132
- return shouldPrintDebug && logger.info(
133
- `Ignoring file due to includeExtensions: ${sourcePath}, includeExtensions: ${includeExtensions.join(
134
- ", "
135
- )}`
136
- ), null;
137
- function isValidStyleKey(name, staticConfig) {
138
- if (!projectInfo)
139
- throw new Error("Tamagui extractor not loaded yet");
140
- if (platform2 === "native" && name[0] === "$" && mediaQueryConfig[name.slice(1)])
141
- return !1;
142
- if (name[0] === "$") {
143
- const mediaName = name.slice(1);
144
- if (mediaName.startsWith("theme-") || mediaName.startsWith("platform-") || mediaName.startsWith("group-") || mediaQueryConfig[mediaName])
145
- return !0;
146
- }
147
- return !!(staticConfig.validStyles?.[name] || pseudoDescriptors[name] || // don't disable variants or else you lose many things flattening
148
- staticConfig.variants?.[name] || projectInfo?.tamaguiConfig?.shorthands[name]);
149
- }
150
- const isTargetingHTML = platform2 === "web", ogDebug = shouldPrintDebug, tm = (0, import_timer.timer)(), propsWithFileInfo = {
151
- ...options,
152
- sourcePath,
153
- allLoadedComponents: components ? [...components] : []
154
- };
155
- hasLoggedBaseInfo || (hasLoggedBaseInfo = !0, shouldPrintDebug && logger.info(
156
- [
157
- "loaded components:",
158
- propsWithFileInfo.allLoadedComponents.map((comp) => Object.keys(comp.nameToInfo).join(", ")).join(", ")
159
- ].join(" ")
160
- ), process.env.DEBUG?.startsWith("tamagui") && logger.info(
161
- [
162
- "loaded:",
163
- propsWithFileInfo.allLoadedComponents.map((x) => x.moduleName)
164
- ].join(`
165
- `)
166
- )), tm.mark("load-tamagui", !!shouldPrintDebug), isFullyDisabled(options) || tamaguiConfig?.themes || (console.error(
167
- `\u26D4\uFE0F Error: Missing "themes" in your tamagui.config file:
168
-
169
- You may not need the compiler! Remember you can run Tamagui with no configuration at all.
170
-
171
- You may have not "export default" your config (you can also "export const config").
172
-
173
- Or this may be due to duplicated dependency versions:
174
- - try out https://github.com/bmish/check-dependency-version-consistency to see if there are mis-matches.
175
- - or search your lockfile for mis-matches.
176
- `
177
- ), console.info(" Got config:", tamaguiConfig), process.exit(0));
178
- const firstThemeName = Object.keys(tamaguiConfig?.themes || {})[0], firstTheme = tamaguiConfig?.themes[firstThemeName] || {};
179
- if (!firstTheme || typeof firstTheme != "object") {
180
- const err = `Missing theme ${firstThemeName}, an error occurred when importing your config`;
181
- throw console.info(err, "Got config:", tamaguiConfig), console.info("Looking for theme:", firstThemeName), new Error(err);
182
- }
183
- const proxiedTheme = proxyThemeVariables(firstTheme), themeAccessListeners = /* @__PURE__ */ new Set(), defaultTheme = new Proxy(proxiedTheme, {
184
- get(target, key) {
185
- return Reflect.has(target, key) && themeAccessListeners.forEach((cb) => cb(String(key))), Reflect.get(target, key);
186
- }
187
- }), body = fileOrPath.type === "Program" ? fileOrPath.get("body") : fileOrPath.program.body;
188
- isFullyDisabled(options) || Object.keys(components || []).length === 0 && (console.warn(
189
- "Warning: Tamagui didn't find any valid components (DEBUG=tamagui for more)"
190
- ), process.env.DEBUG === "tamagui" && console.info("components", Object.keys(components || []), components)), shouldPrintDebug === "verbose" && (logger.info(
191
- `allLoadedComponent modules ${propsWithFileInfo.allLoadedComponents.map((k) => k.moduleName).join(", ")}`
192
- ), logger.info(
193
- `valid import paths: ${JSON.stringify(
194
- (0, import_extractHelpers.getValidComponentsPaths)(propsWithFileInfo)
195
- )}`
196
- ));
197
- let doesUseValidImport = !1, hasImportedTheme = !1;
198
- const importDeclarations = [];
199
- for (const bodyPath of body) {
200
- if (bodyPath.type !== "ImportDeclaration") continue;
201
- const node = "node" in bodyPath ? bodyPath.node : bodyPath, moduleName = node.source.value, valid = (0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName);
202
- if (valid && importDeclarations.push(node), shouldPrintDebug === "verbose" && logger.info(` - import via ${moduleName} ${valid}`), extractStyledDefinitions && valid && node.specifiers.some((specifier) => specifier.local.name === "styled")) {
203
- doesUseValidImport = !0;
204
- break;
205
- }
206
- if (valid) {
207
- const names = node.specifiers.map((specifier) => specifier.local.name), isValidComponent = names.some(
208
- (name) => !!(0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName, name)
209
- );
210
- if (shouldPrintDebug === "verbose" && logger.info(
211
- ` - import ${isValidComponent ? "\u2705" : "\u21E3"} - ${names.join(
212
- ", "
213
- )} via package '${moduleName}' - (valid: ${JSON.stringify(
214
- (0, import_extractHelpers.getValidComponentsPaths)(propsWithFileInfo)
215
- )})`
216
- ), isValidComponent) {
217
- doesUseValidImport = !0;
218
- break;
219
- }
220
- }
221
- }
222
- if (shouldPrintDebug && logger.info(
223
- `${JSON.stringify({ doesUseValidImport, hasImportedTheme }, null, 2)}
224
- `
225
- ), !doesUseValidImport)
226
- return null;
227
- function getValidImportedComponent(componentName) {
228
- const importDeclaration = importDeclarations.find(
229
- (dec) => dec.specifiers.some((spec) => spec.local.name === componentName)
230
- );
231
- return importDeclaration ? (0, import_extractHelpers.getValidImport)(
232
- propsWithFileInfo,
233
- importDeclaration.source.value,
234
- componentName
235
- ) : null;
236
- }
237
- tm.mark("import-check", !!shouldPrintDebug);
238
- let couldntParse = !1;
239
- const modifiedComponents = /* @__PURE__ */ new Set(), bindingCache = {}, callTraverse = (a) => fileOrPath.type === "File" ? (0, import_traverse.default)(fileOrPath, a) : fileOrPath.traverse(a), shouldDisableExtraction = disableExtraction === !0 || Array.isArray(disableExtraction) && disableExtraction.includes(sourcePath);
240
- let programPath = null;
241
- const res = {
242
- styled: 0,
243
- flattened: 0,
244
- optimized: 0,
245
- modified: 0,
246
- found: 0
247
- }, version = `${Math.random()}`;
248
- return callTraverse({
249
- // @ts-ignore
250
- Program: {
251
- enter(path) {
252
- programPath = path;
253
- }
254
- },
255
- // styled() calls
256
- CallExpression(path) {
257
- if (disable || shouldDisableExtraction || extractStyledDefinitions === !1 || !t.isIdentifier(path.node.callee) || path.node.callee.name !== "styled")
258
- return;
259
- const variableName = t.isVariableDeclarator(path.parent) && t.isIdentifier(path.parent.id) ? path.parent.id.name : "unknown", parentNode = path.node.arguments[0];
260
- if (!t.isIdentifier(parentNode))
261
- return;
262
- const parentName = parentNode.name, definition = path.node.arguments[1];
263
- if (!parentName || !definition || !t.isObjectExpression(definition))
264
- return;
265
- let Component = getValidImportedComponent(variableName);
266
- if (!Component) {
267
- if (enableDynamicEvaluation !== !0)
268
- return;
269
- try {
270
- shouldPrintDebug && logger.info(
271
- `Unknown component: ${variableName} = styled(${parentName}) attempting dynamic load: ${sourcePath}`
272
- );
273
- const out2 = (0, import_loadTamagui.loadTamaguiSync)({
274
- forceExports: !0,
275
- components: [sourcePath],
276
- cacheKey: version
277
- });
278
- if (!out2?.components) {
279
- shouldPrintDebug && logger.info(`Couldn't load, got ${out2}`);
280
- return;
281
- }
282
- if (propsWithFileInfo.allLoadedComponents = [
283
- ...propsWithFileInfo.allLoadedComponents,
284
- ...out2.components
285
- ], Component = out2.components.flatMap((x) => x.nameToInfo[variableName] ?? [])[0], !out2.cached) {
286
- const foundNames = out2.components?.map((x) => Object.keys(x.nameToInfo).join(", ")).join(", ").trim();
287
- foundNames && (0, import_cli_color.colorLog)(
288
- import_cli_color.Color.FgYellow,
289
- ` | Tamagui found dynamic components: ${foundNames}`
290
- );
291
- }
292
- } catch {
293
- shouldPrintDebug && logger.info(
294
- `skip optimize styled(${variableName}), unable to pre-process (DEBUG=tamagui for more)`
295
- );
296
- }
297
- }
298
- if (!Component) {
299
- shouldPrintDebug && logger.info(" No component found");
300
- return;
301
- }
302
- const componentSkipProps = /* @__PURE__ */ new Set([
303
- ...Component.staticConfig.inlineWhenUnflattened || [],
304
- ...Component.staticConfig.inlineProps || [],
305
- // for now skip variants, will return to them
306
- "variants",
307
- "defaultVariants",
308
- // skip fontFamily its basically a "variant", important for theme use to be value always
309
- "fontFamily",
310
- "name",
311
- "focusStyle",
312
- "focusVisibleStyle",
313
- "focusWithinStyle",
314
- "disabledStyle",
315
- "hoverStyle",
316
- "pressStyle"
317
- ]), skipped = /* @__PURE__ */ new Set(), styles = {}, staticNamespace = (0, import_getStaticBindingsForScope.getStaticBindingsForScope)(
318
- path.scope,
319
- importsWhitelist,
320
- sourcePath,
321
- bindingCache,
322
- shouldPrintDebug
323
- ), attemptEval = evaluateVars ? (0, import_createEvaluator.createEvaluator)({
324
- props: propsWithFileInfo,
325
- staticNamespace,
326
- sourcePath,
327
- shouldPrintDebug
328
- }) : import_evaluateAstNode.evaluateAstNode, attemptEvalSafe = (0, import_createEvaluator.createSafeEvaluator)(attemptEval);
329
- for (const property of definition.properties) {
330
- if (!t.isObjectProperty(property) || !t.isIdentifier(property.key) || !isValidStyleKey(property.key.name, Component.staticConfig) || // TODO make pseudos and variants work
331
- // skip pseudos
332
- pseudoDescriptors[property.key.name] || // skip variants
333
- Component.staticConfig.variants?.[property.key.name] || componentSkipProps.has(property.key.name)) {
334
- skipped.add(property);
335
- continue;
336
- }
337
- const out2 = attemptEvalSafe(property.value);
338
- out2 === import_constants.FAILED_EVAL ? skipped.add(property) : styles[property.key.name] = out2;
339
- }
340
- const out = getSplitStyles(
341
- styles,
342
- Component.staticConfig,
343
- defaultTheme,
344
- "",
345
- componentState,
346
- styleProps,
347
- void 0,
348
- void 0,
349
- void 0,
350
- void 0,
351
- !1,
352
- shouldPrintDebug
353
- ), classNames = {
354
- ...out.classNames
355
- };
356
- if (shouldPrintDebug && logger.info(
357
- [
358
- `Extracted styled(${variableName})
359
- `,
360
- JSON.stringify(styles, null, 2),
361
- `
362
- classNames:`,
363
- JSON.stringify(classNames, null, 2),
364
- `
365
- rulesToInsert:`,
366
- out.rulesToInsert
367
- ].join(" ")
368
- ), definition.properties = definition.properties.map((prop) => {
369
- if (skipped.has(prop) || !t.isObjectProperty(prop) || !t.isIdentifier(prop.key))
370
- return prop;
371
- const key = prop.key.name, value = classNames[key];
372
- return value ? t.objectProperty(t.stringLiteral(key), t.stringLiteral(value)) : prop;
373
- }), out.rulesToInsert)
374
- for (const key in out.rulesToInsert) {
375
- const styleObject = out.rulesToInsert[key];
376
- onStyledDefinitionRule?.(
377
- styleObject[import_web.StyleObjectIdentifier],
378
- styleObject[import_web.StyleObjectRules]
379
- );
380
- }
381
- res.styled++, shouldPrintDebug && logger.info(`Extracted styled(${variableName})`);
382
- },
383
- JSXElement(traversePath) {
384
- tm.mark("jsx-element", !!shouldPrintDebug);
385
- const node = traversePath.node.openingElement, ogAttributes = node.attributes.map((attr) => ({ ...attr })), componentName = (0, import_extractHelpers.findComponentName)(traversePath.scope), closingElement = traversePath.node.closingElement;
386
- if (closingElement && t.isJSXMemberExpression(closingElement?.name) || !t.isJSXIdentifier(node.name)) {
387
- shouldPrintDebug && logger.info(" skip non-identifier element");
388
- return;
389
- }
390
- const binding = traversePath.scope.getBinding(node.name.name);
391
- let moduleName = "";
392
- if (binding && t.isImportDeclaration(binding.path.parent) && (moduleName = binding.path.parent.source.value, !(0, import_extractHelpers.isValidImport)(propsWithFileInfo, moduleName, binding.identifier.name))) {
393
- shouldPrintDebug && logger.info(
394
- ` - Binding in component ${componentName} not valid import: "${binding.identifier.name}" isn't in ${moduleName}
395
- `
396
- );
397
- return;
398
- }
399
- const component = (0, import_extractHelpers.getValidComponent)(propsWithFileInfo, moduleName, node.name.name);
400
- if (!component || !component.staticConfig) {
401
- shouldPrintDebug && logger.info(`
402
- - No Tamagui conf for: ${node.name.name}
403
- `);
404
- return;
405
- }
406
- const originalNodeName = node.name.name;
407
- res.found++;
408
- const filePath = `./${(0, import_node_path.relative)(process.cwd(), sourcePath)}`, lineNumbers = node.loc ? node.loc.start.line + (node.loc.start.line !== node.loc.end.line ? `-${node.loc.end.line}` : "") : "", codePosition = `${filePath}:${lineNumbers}`, debugPropValue = node.attributes.filter(
409
- (n) => t.isJSXAttribute(n) && t.isJSXIdentifier(n.name) && n.name.name === "debug"
410
- ).map((n) => n.value === null ? !0 : t.isStringLiteral(n.value) ? n.value.value : !1)[0];
411
- if (debugPropValue && (shouldPrintDebug = debugPropValue), shouldPrintDebug && (logger.info(
412
- `\x1B[33m\x1B[0m ${componentName} | ${codePosition} -------------------`
413
- ), logger.info(
414
- [
415
- "\x1B[1m",
416
- "\x1B[32m",
417
- `<${originalNodeName} />`,
418
- disableDebugAttr ? "" : "\u{1F41B}"
419
- ].join(" ")
420
- )), platform2 !== "native" && shouldAddDebugProp && !disableDebugAttr && (res.modified++, node.attributes.unshift(
421
- t.jsxAttribute(t.jsxIdentifier("data-is"), t.stringLiteral(node.name.name))
422
- ), componentName && node.attributes.unshift(
423
- t.jsxAttribute(t.jsxIdentifier("data-in"), t.stringLiteral(componentName))
424
- ), node.attributes.unshift(
425
- t.jsxAttribute(
426
- t.jsxIdentifier("data-at"),
427
- t.stringLiteral(`${(0, import_node_path.basename)(filePath)}:${lineNumbers}`)
428
- )
429
- )), shouldDisableExtraction) {
430
- shouldPrintDebug === "verbose" && logger.info(` \u274C Extraction disabled: ${JSON.stringify(disableExtraction)}
431
- `);
432
- return;
433
- }
434
- try {
435
- let evaluateAttribute = function(path) {
436
- const attribute = path.node, attr = { type: "attr", value: attribute };
437
- if (t.isJSXSpreadAttribute(attribute)) {
438
- const arg = attribute.argument, conditional = t.isConditionalExpression(arg) ? (
439
- // <YStack {...isSmall ? { color: 'red } : { color: 'blue }}
440
- [arg.test, arg.consequent, arg.alternate]
441
- ) : t.isLogicalExpression(arg) && arg.operator === "&&" ? (
442
- // <YStack {...isSmall && { color: 'red }}
443
- [arg.left, arg.right, null]
444
- ) : null;
445
- if (conditional) {
446
- const [test, alt, cons] = conditional;
447
- if (!test) throw new Error("no test");
448
- return [alt, cons].some((side) => side && !isStaticObject(side)) ? (shouldPrintDebug && logger.info(`not extractable ${alt} ${cons}`), attr) : [
449
- ...flattenNestedTernaries(test, alt) || [],
450
- ...cons && flattenNestedTernaries(t.unaryExpression("!", test), cons) || []
451
- ].map((ternary) => ({
452
- type: "ternary",
453
- value: ternary
454
- }));
455
- }
456
- }
457
- if (t.isJSXSpreadAttribute(attribute) || !attribute.name || typeof attribute.name.name != "string")
458
- return shouldPrintDebug && logger.info(" ! inlining, spread attr"), inlined.set(`${Math.random()}`, "spread"), attr;
459
- const name = attribute.name.name;
460
- if (name === "style")
461
- return shouldDeopt = !0, null;
462
- if (excludeProps?.has(name))
463
- return shouldPrintDebug && logger.info([" excluding prop", name].join(" ")), null;
464
- if (inlineProps.has(name))
465
- return inlined.set(name, name), shouldPrintDebug && logger.info([" ! inlining, inline prop", name].join(" ")), attr;
466
- if (UNTOUCHED_PROPS[name])
467
- return attr;
468
- if (INLINE_EXTRACTABLE[name])
469
- return inlined.set(name, INLINE_EXTRACTABLE[name]), attr;
470
- if (name.startsWith("data-") || name.startsWith("aria-") || import_validHTMLAttributes.validHTMLAttributes[name])
471
- return attr;
472
- if ((name === "enterStyle" || name === "exitStyle") && t.isJSXExpressionContainer(attribute?.value))
473
- return shouldDeopt = !0, attr;
474
- if (name[0] === "$" && t.isJSXExpressionContainer(attribute?.value)) {
475
- const shortname = name.slice(1);
476
- if (mediaQueryConfig[shortname]) {
477
- const expression = attribute.value.expression;
478
- if (!t.isJSXEmptyExpression(expression)) {
479
- const ternaries2 = flattenNestedTernaries(
480
- t.stringLiteral(shortname),
481
- expression,
482
- {
483
- inlineMediaQuery: shortname
484
- }
485
- );
486
- if (ternaries2)
487
- return ternaries2.map((value2) => ({
488
- type: "ternary",
489
- value: value2
490
- }));
491
- }
492
- }
493
- }
494
- const [value, valuePath] = t.isJSXExpressionContainer(attribute?.value) ? [attribute.value.expression, path.get("value")] : [attribute.value, path.get("value")], remove = () => {
495
- Array.isArray(valuePath) ? valuePath.map((p) => p.remove()) : valuePath.remove();
496
- };
497
- if (name === "ref")
498
- return shouldPrintDebug && logger.info([" ! inlining, ref", name].join(" ")), inlined.set("ref", "ref"), attr;
499
- if (name === "render")
500
- return (!value || value.type !== "StringLiteral") && (shouldPrintDebug && logger.info(" ! deopt on render prop (not a string literal)"), shouldDeopt = !0), {
501
- type: "attr",
502
- value: path.node
503
- };
504
- if (disableExtractVariables === !0 && value && value.type === "StringLiteral" && value.value[0] === "$")
505
- return shouldPrintDebug && logger.info(
506
- [
507
- ` ! inlining, native disable extract: ${name} =`,
508
- value.value
509
- ].join(" ")
510
- ), inlined.set(name, !0), attr;
511
- if (name === "theme")
512
- return inlined.set("theme", attr.value), attr;
513
- const styleValue = attemptEvalSafe(value);
514
- if (!variants[name] && !isValidStyleKey(name, staticConfig)) {
515
- let out = null;
516
- propMapper(name, styleValue, propMapperStyleState, !1, (key, val) => {
517
- out ||= {}, out[key] = val;
518
- }), out && isTargetingHTML && (out = reactNativeWebInternals.createDOMProps(
519
- isTextView ? "span" : "div",
520
- out
521
- ), delete out.className);
522
- let didInline = !1;
523
- const attributes = Object.keys(out).map((key) => {
524
- const val = out[key];
525
- return isValidStyleKey(key, staticConfig) ? {
526
- type: "style",
527
- value: { [key]: styleValue },
528
- name: key,
529
- attr: path.node
530
- } : import_validHTMLAttributes.validHTMLAttributes[key] || key.startsWith("aria-") || key.startsWith("data-") || // this is debug stuff added by vite / new jsx transform
531
- key === "__source" || key === "__self" ? attr : (shouldPrintDebug && logger.info(" ! inlining, non-static " + key), didInline = !0, inlined.set(key, val), val);
532
- });
533
- return didInline ? (shouldPrintDebug && logger.info(
534
- ` bailing flattening due to attributes ${attributes.map(
535
- (x) => x.toString()
536
- )}`
537
- ), attr) : attributes;
538
- }
539
- if (styleValue !== import_constants.FAILED_EVAL) {
540
- if (inlineWhenUnflattened.has(name) && (inlineWhenUnflattenedOGVals[name] = { styleValue, attr }), isValidStyleKey(name, staticConfig)) {
541
- if (name[0] === "$") {
542
- if (name.startsWith("$theme-") || name.startsWith("$group-"))
543
- return shouldPrintDebug && logger.info(` ! not flattening media-like style: ${name}`), inlined.set(name, !0), attr;
544
- if (name.startsWith("$platform-")) {
545
- const platformName = name.slice(10);
546
- return (platformName === platform2 || platformName === "native" && platform2 === "native" || platformName === "web" && platform2 === "web") && typeof styleValue == "object" ? (shouldPrintDebug && logger.info(
547
- ` flattening $platform-${platformName}: ${JSON.stringify(styleValue)}`
548
- ), Object.entries(styleValue).map(([key, val]) => ({
549
- type: "style",
550
- value: { [key]: val },
551
- name: key,
552
- attr: path.node
553
- }))) : (shouldPrintDebug && logger.info(` ! skipping non-matching platform style: ${name}`), []);
554
- }
555
- }
556
- return shouldPrintDebug && logger.info(` style: ${name} = ${JSON.stringify(styleValue)}`), name in defaultProps || hasSetOptimized || (res.optimized++, hasSetOptimized = !0), {
557
- type: "style",
558
- value: { [name]: styleValue },
559
- name,
560
- attr: path.node
561
- };
562
- }
563
- return variants[name] && variantValues.set(name, styleValue), inlined.set(name, !0), attr;
564
- }
565
- if (t.isBinaryExpression(value)) {
566
- shouldPrintDebug && logger.info(` binary expression ${name} = ${value}`);
567
- const { operator, left, right } = value, lVal = attemptEvalSafe(left), rVal = attemptEvalSafe(right);
568
- if (shouldPrintDebug && logger.info(
569
- ` evalBinaryExpression lVal ${String(lVal)}, rVal ${String(rVal)}`
570
- ), lVal !== import_constants.FAILED_EVAL && t.isConditionalExpression(right)) {
571
- const ternary = addBinaryConditional(operator, left, right);
572
- if (ternary) return ternary;
573
- }
574
- if (rVal !== import_constants.FAILED_EVAL && t.isConditionalExpression(left)) {
575
- const ternary = addBinaryConditional(operator, right, left);
576
- if (ternary) return ternary;
577
- }
578
- return shouldPrintDebug && logger.info(" evalBinaryExpression cant extract"), inlined.set(name, !0), attr;
579
- }
580
- const staticConditional = getStaticConditional(value);
581
- if (staticConditional)
582
- return shouldPrintDebug === "verbose" && logger.info(` static conditional ${name} ${value}`), { type: "ternary", value: staticConditional };
583
- const staticLogical = getStaticLogical(value);
584
- if (staticLogical)
585
- return shouldPrintDebug === "verbose" && logger.info(` static ternary ${name} = ${value}`), { type: "ternary", value: staticLogical };
586
- return inlined.set(name, !0), shouldPrintDebug && logger.info(` ! inline no match ${name} ${value}`), attr;
587
- function addBinaryConditional(operator, staticExpr, cond) {
588
- if (getStaticConditional(cond)) {
589
- const alt = attemptEval(
590
- t.binaryExpression(operator, staticExpr, cond.alternate)
591
- ), cons = attemptEval(
592
- t.binaryExpression(operator, staticExpr, cond.consequent)
593
- );
594
- return shouldPrintDebug && logger.info([" binaryConditional", cond.test, cons, alt].join(" ")), {
595
- type: "ternary",
596
- value: {
597
- test: cond.test,
598
- remove,
599
- alternate: { [name]: alt },
600
- consequent: { [name]: cons }
601
- }
602
- };
603
- }
604
- return null;
605
- }
606
- function getStaticConditional(value2) {
607
- if (t.isConditionalExpression(value2))
608
- try {
609
- const aVal = attemptEval(value2.alternate), cVal = attemptEval(value2.consequent);
610
- if (shouldPrintDebug) {
611
- const type = value2.test.type;
612
- logger.info([" static ternary", type, cVal, aVal].join(" "));
613
- }
614
- return {
615
- test: value2.test,
616
- remove,
617
- consequent: { [name]: cVal },
618
- alternate: { [name]: aVal }
619
- };
620
- } catch (err) {
621
- shouldPrintDebug && logger.info([" cant eval ternary", err.message].join(" "));
622
- }
623
- return null;
624
- }
625
- function getStaticLogical(value2) {
626
- if (t.isLogicalExpression(value2) && value2.operator === "&&")
627
- try {
628
- const val = attemptEval(value2.right);
629
- return shouldPrintDebug && logger.info([" staticLogical", value2.left, name, val].join(" ")), {
630
- test: value2.left,
631
- remove,
632
- consequent: { [name]: val },
633
- alternate: null
634
- };
635
- } catch (err) {
636
- shouldPrintDebug && logger.info([" cant static eval logical", err].join(" "));
637
- }
638
- return null;
639
- }
640
- }, isStaticObject = function(obj) {
641
- return t.isObjectExpression(obj) && obj.properties.every((prop) => {
642
- if (!t.isObjectProperty(prop))
643
- return !1;
644
- const propName = prop.key.name;
645
- return !isValidStyleKey(propName, staticConfig) && propName !== "render" ? (shouldPrintDebug && logger.info([" not a valid style prop!", propName].join(" ")), !1) : !0;
646
- });
647
- }, flattenNestedTernaries = function(test, side, ternaryPartial = {}) {
648
- if (!side)
649
- return null;
650
- if (!isStaticObject(side))
651
- throw new Error("not extractable");
652
- return side.properties.flatMap((property) => {
653
- if (!t.isObjectProperty(property))
654
- throw new Error("expected object property");
655
- if (t.isConditionalExpression(property.value)) {
656
- const [truthy, falsy] = [
657
- t.objectExpression([
658
- t.objectProperty(property.key, property.value.consequent)
659
- ]),
660
- t.objectExpression([
661
- t.objectProperty(property.key, property.value.alternate)
662
- ])
663
- ].map((x) => attemptEval(x));
664
- return [
665
- createTernary({
666
- remove() {
667
- },
668
- ...ternaryPartial,
669
- test: t.logicalExpression("&&", test, property.value.test),
670
- consequent: truthy,
671
- alternate: null
672
- }),
673
- createTernary({
674
- ...ternaryPartial,
675
- test: t.logicalExpression(
676
- "&&",
677
- test,
678
- t.unaryExpression("!", property.value.test)
679
- ),
680
- consequent: falsy,
681
- alternate: null,
682
- remove() {
683
- }
684
- })
685
- ];
686
- }
687
- const obj = t.objectExpression([
688
- t.objectProperty(property.key, property.value)
689
- ]), consequent = attemptEval(obj);
690
- return createTernary({
691
- remove() {
692
- },
693
- ...ternaryPartial,
694
- test,
695
- consequent,
696
- alternate: null
697
- });
698
- });
699
- }, mergeToEnd = function(obj, key, val) {
700
- key in obj && delete obj[key], obj[key] = val;
701
- }, normalizeStyleWithoutVariants = function(style) {
702
- let res2 = {};
703
- for (const key in style)
704
- if (staticConfig.variants && key in staticConfig.variants)
705
- mergeToEnd(res2, key, style[key]);
706
- else {
707
- const expanded = normalizeStyle({ [key]: style[key] }, !0);
708
- for (const key2 in expanded)
709
- mergeToEnd(res2, key2, expanded[key2]);
710
- }
711
- return res2;
712
- }, mergeStyles = function(prev2, next) {
713
- for (const key in next)
714
- pseudoDescriptors[key] ? (prev2[key] = prev2[key] || {}, Object.assign(prev2[key], next[key])) : mergeToEnd(prev2, key, next[key]);
715
- };
716
- const { staticConfig } = component, defaultProps = {
717
- ...getDefaultProps(staticConfig)
718
- }, variants = staticConfig.variants || {}, isTextView = staticConfig.isText || !1, validStyles = staticConfig?.validStyles ?? {};
719
- if (process.env.NODE_ENV === "production" && isTextView)
720
- return;
721
- let tagName = defaultProps.render ?? (isTextView ? "span" : "div");
722
- traversePath.get("openingElement").get("attributes").forEach((path) => {
723
- const attr = path.node;
724
- if (t.isJSXSpreadAttribute(attr) || attr.name.name !== "render") return;
725
- const val = attr.value;
726
- t.isStringLiteral(val) && (tagName = val.value);
727
- }), shouldPrintDebug === "verbose" && console.info(` Start tag ${tagName}`);
728
- const flatNodeName = getFlattenedNode?.({ isTextView, tag: tagName }), inlineProps = /* @__PURE__ */ new Set([
729
- // adding some always inline props
730
- ...restProps.inlineProps || [],
731
- ...staticConfig.inlineProps || []
732
- ]), deoptProps = /* @__PURE__ */ new Set([
733
- // always de-opt animation these
734
- "animation",
735
- "animateOnly",
736
- "animatePresence",
737
- "disableOptimization",
738
- ...isTargetingHTML ? [] : [
739
- "pressStyle",
740
- "focusStyle",
741
- "focusVisibleStyle",
742
- "focusWithinStyle",
743
- "disabledStyle"
744
- ],
745
- // when using a non-CSS driver, de-opt on enterStyle/exitStyle
746
- ...tamaguiConfig?.animations.isReactNative ? ["enterStyle", "exitStyle"] : []
747
- ]), inlineWhenUnflattened = new Set(staticConfig.inlineWhenUnflattened || []), staticNamespace = (0, import_getStaticBindingsForScope.getStaticBindingsForScope)(
748
- traversePath.scope,
749
- importsWhitelist,
750
- sourcePath,
751
- bindingCache,
752
- shouldPrintDebug
753
- ), attemptEval = evaluateVars ? (0, import_createEvaluator.createEvaluator)({
754
- props: propsWithFileInfo,
755
- staticNamespace,
756
- sourcePath,
757
- traversePath,
758
- shouldPrintDebug
759
- }) : import_evaluateAstNode.evaluateAstNode, attemptEvalSafe = (0, import_createEvaluator.createSafeEvaluator)(attemptEval);
760
- if (shouldPrintDebug && logger.info(` staticNamespace ${Object.keys(staticNamespace).join(", ")}`), couldntParse)
761
- return;
762
- tm.mark("jsx-element-flattened", !!shouldPrintDebug);
763
- let attrs = [], shouldDeopt = !1;
764
- const inlined = /* @__PURE__ */ new Map(), variantValues = /* @__PURE__ */ new Map();
765
- let hasSetOptimized = !1;
766
- const inlineWhenUnflattenedOGVals = {}, propMapperStyleState = {
767
- staticConfig,
768
- usedKeys: {},
769
- classNames: {},
770
- style: {},
771
- theme: defaultTheme,
772
- viewProps: defaultProps,
773
- conf: tamaguiConfig,
774
- props: defaultProps,
775
- componentState,
776
- styleProps: {
777
- ...styleProps,
778
- resolveValues: "auto"
779
- },
780
- debug: shouldPrintDebug
781
- };
782
- if (attrs = traversePath.get("openingElement").get("attributes").flatMap((path) => {
783
- if (!shouldDeopt)
784
- try {
785
- const res2 = evaluateAttribute(path);
786
- return res2 || path.remove(), res2;
787
- } catch (err) {
788
- return shouldPrintDebug && (logger.info(
789
- [
790
- "Recoverable error extracting attribute",
791
- err.message,
792
- shouldPrintDebug === "verbose" ? err.stack : ""
793
- ].join(" ")
794
- ), shouldPrintDebug === "verbose" && logger.info(`node ${path.node?.type}`)), inlined.set(`${Math.random()}`, "spread"), {
795
- type: "attr",
796
- value: path.node
797
- };
798
- }
799
- }).flat(4).filter(import_extractHelpers.isPresent), shouldPrintDebug && logger.info(
800
- [` - attrs (before):
801
- `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(" ")
802
- ), couldntParse || shouldDeopt) {
803
- shouldPrintDebug && logger.info(
804
- [" avoid optimizing:", { couldntParse, shouldDeopt }].join(" ")
805
- ), node.attributes = ogAttributes;
806
- return;
807
- }
808
- const parentFn = (0, import_findTopmostFunction.findTopmostFunction)(traversePath);
809
- parentFn && modifiedComponents.add(parentFn);
810
- const hasSpread = attrs.some(
811
- (x) => x.type === "attr" && t.isJSXSpreadAttribute(x.value)
812
- ), hasOnlyStringChildren = !hasSpread && (node.selfClosing || traversePath.node.children && traversePath.node.children.every((x) => x.type === "JSXText"));
813
- let themeVal = inlined.get("theme");
814
- platform2 !== "native" && inlined.delete("theme");
815
- for (const [key] of inlined) {
816
- const isStaticObjectVariant = staticConfig.variants?.[key] && variantValues.has(key);
817
- (INLINE_EXTRACTABLE[key] || isStaticObjectVariant) && inlined.delete(key);
818
- }
819
- const canFlattenProps = inlined.size === 0;
820
- let shouldFlatten = !!(flatNodeName && !shouldDeopt && canFlattenProps && !hasSpread && !staticConfig.isStyledHOC && !staticConfig.isHOC && !staticConfig.isReactNative && staticConfig.neverFlatten !== !0 && (staticConfig.neverFlatten !== "jsx" || hasOnlyStringChildren));
821
- const usedThemeKeys = /* @__PURE__ */ new Set();
822
- if (themeAccessListeners.add((key) => {
823
- disableExtractVariables && (usedThemeKeys.add(key), shouldFlatten = !1, shouldPrintDebug === "verbose" && logger.info([" ! accessing theme key, avoid flatten", key].join(" ")));
824
- }), !shouldFlatten) {
825
- shouldPrintDebug && logger.info(
826
- `Deopting ${JSON.stringify({
827
- shouldFlatten,
828
- shouldDeopt,
829
- canFlattenProps,
830
- hasSpread,
831
- neverFlatten: staticConfig.neverFlatten
832
- })}`
833
- ), node.attributes = ogAttributes;
834
- return;
835
- }
836
- let skipMap = !1;
837
- const defaultStyleAttrs = Object.keys(defaultProps).flatMap((key) => {
838
- if (skipMap) return [];
839
- const value = defaultProps[key];
840
- if (key === "theme" && !themeVal)
841
- return platform2 === "native" && (shouldFlatten = !1, skipMap = !0, inlined.set("theme", { value: t.stringLiteral(value) })), themeVal = { value: t.stringLiteral(value) }, [];
842
- if (!isValidStyleKey(key, staticConfig))
843
- return [];
844
- const name = tamaguiConfig?.shorthands[key] || key;
845
- if (value === void 0) {
846
- logger.warn(
847
- `\u26A0\uFE0F Error evaluating default style for component, prop ${key} ${value}`
848
- ), shouldDeopt = !0;
849
- return;
850
- }
851
- return name[0] === "$" && mediaQueryConfig[name.slice(1)] ? (defaultProps[key] = void 0, evaluateAttribute({
852
- node: t.jsxAttribute(
853
- t.jsxIdentifier(name),
854
- t.jsxExpressionContainer(
855
- t.objectExpression(
856
- Object.keys(value).filter((k) => typeof value[k] < "u").map((k) => t.objectProperty(t.identifier(k), (0, import_literalToAst.literalToAst)(value[k])))
857
- )
858
- )
859
- )
860
- })) : {
861
- type: "style",
862
- name,
863
- value: { [name]: value }
864
- };
865
- });
866
- skipMap || defaultStyleAttrs.length && (attrs = [...defaultStyleAttrs, ...attrs]);
867
- let ternaries = [];
868
- attrs = attrs.reduce((out, cur) => {
869
- const next = attrs[attrs.indexOf(cur) + 1];
870
- if (cur.type === "ternary" && ternaries.push(cur.value), (!next || next.type !== "ternary") && ternaries.length) {
871
- const normalized = (0, import_normalizeTernaries.normalizeTernaries)(ternaries).map(
872
- ({ alternate, consequent, ...rest }) => ({
873
- type: "ternary",
874
- value: {
875
- ...rest,
876
- alternate: alternate || null,
877
- consequent: consequent || null
878
- }
879
- })
880
- );
881
- try {
882
- return [...out, ...normalized];
883
- } finally {
884
- shouldPrintDebug && logger.info(
885
- ` normalizeTernaries (${ternaries.length} => ${normalized.length})`
886
- ), ternaries = [];
887
- }
888
- }
889
- return cur.type === "ternary" || out.push(cur), out;
890
- }, []).flat(), themeVal && (programPath ? (shouldPrintDebug && logger.info([" - wrapping theme", themeVal].join(" ")), attrs = attrs.filter(
891
- (x) => !(x.type === "attr" && t.isJSXAttribute(x.value) && x.value.name.name === "theme")
892
- ), hasImportedTheme || (hasImportedTheme = !0, programPath.node.body.push(
893
- t.importDeclaration(
894
- [
895
- t.importSpecifier(
896
- t.identifier("_TamaguiTheme"),
897
- t.identifier("Theme")
898
- )
899
- ],
900
- t.stringLiteral("@tamagui/web")
901
- )
902
- )), traversePath.replaceWith(
903
- t.jsxElement(
904
- t.jsxOpeningElement(t.jsxIdentifier("_TamaguiTheme"), [
905
- t.jsxAttribute(t.jsxIdentifier("name"), themeVal.value)
906
- ]),
907
- t.jsxClosingElement(t.jsxIdentifier("_TamaguiTheme")),
908
- [traversePath.node]
909
- )
910
- )) : console.warn(
911
- `No program path found, avoiding importing flattening / importing theme in ${sourcePath}`
912
- )), shouldPrintDebug && logger.info(
913
- [` - attrs (flattened):
914
- `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(
915
- " "
916
- )
917
- );
918
- let foundStaticProps = {};
919
- for (const key in attrs) {
920
- const cur = attrs[key];
921
- if (cur.type === "style") {
922
- const expanded = normalizeStyleWithoutVariants(cur.value);
923
- for (const key2 in expanded)
924
- mergeToEnd(foundStaticProps, key2, expanded[key2]);
925
- continue;
926
- }
927
- if (cur.type === "attr") {
928
- if (t.isJSXSpreadAttribute(cur.value) || !t.isJSXIdentifier(cur.value.name))
929
- continue;
930
- const key2 = cur.value.name.name, value = attemptEvalSafe(cur.value.value || t.booleanLiteral(!0));
931
- value !== import_constants.FAILED_EVAL && mergeToEnd(foundStaticProps, key2, value);
932
- }
933
- }
934
- const completeProps = {};
935
- for (const key in defaultProps)
936
- key in foundStaticProps || (completeProps[key] = defaultProps[key]);
937
- for (const key in foundStaticProps)
938
- completeProps[key] = foundStaticProps[key];
939
- attrs = attrs.reduce((acc, cur) => {
940
- if (!cur) return acc;
941
- if (cur.type === "attr" && !t.isJSXSpreadAttribute(cur.value) && shouldFlatten) {
942
- const name = cur.value.name.name;
943
- if (typeof name == "string") {
944
- if (name === "render")
945
- return acc;
946
- if (variants[name] && variantValues.has(name)) {
947
- const styleState = {
948
- ...propMapperStyleState,
949
- props: completeProps
950
- };
951
- let out = {};
952
- if (propMapper(
953
- name,
954
- variantValues.get(name),
955
- styleState,
956
- !1,
957
- (key2, val) => {
958
- out[key2] = val;
959
- }
960
- ), out && isTargetingHTML) {
961
- const cn = out.className;
962
- out = reactNativeWebInternals.createDOMProps(
963
- isTextView ? "span" : "div",
964
- out
965
- ), out.className = cn;
966
- }
967
- shouldPrintDebug && logger.info([" - expanded variant", name, out].join(" "));
968
- for (const key2 in out) {
969
- const value2 = out[key2];
970
- isValidStyleKey(key2, staticConfig) ? acc.push({
971
- type: "style",
972
- value: { [key2]: value2 },
973
- name: key2,
974
- attr: cur.value
975
- }) : acc.push({
976
- type: "attr",
977
- value: t.jsxAttribute(
978
- t.jsxIdentifier(key2),
979
- t.jsxExpressionContainer(
980
- typeof value2 == "string" ? t.stringLiteral(value2) : (0, import_literalToAst.literalToAst)(value2)
981
- )
982
- )
983
- });
984
- }
985
- }
986
- }
987
- }
988
- if (cur.type !== "style")
989
- return acc.push(cur), acc;
990
- let key = Object.keys(cur.value)[0];
991
- const value = cur.value[key], fullKey = tamaguiConfig?.shorthands[key];
992
- return fullKey && (cur.value = { [fullKey]: value }, key = fullKey), disableExtractVariables && value[0] === "$" && (usedThemeKeys.has(key) || usedThemeKeys.has(fullKey)) ? (shouldPrintDebug && logger.info([` keeping variable inline: ${key} =`, value].join(" ")), acc.push({
993
- type: "attr",
994
- value: t.jsxAttribute(
995
- t.jsxIdentifier(key),
996
- t.jsxExpressionContainer(t.stringLiteral(value))
997
- )
998
- }), acc) : (acc.push(cur), acc);
999
- }, []), tm.mark("jsx-element-expanded", !!shouldPrintDebug), shouldPrintDebug && logger.info(
1000
- [` - attrs (expanded):
1001
- `, (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))].join(
1002
- " "
1003
- )
1004
- );
1005
- let prev = null;
1006
- const getProps = (props, includeProps = !1, debugName = "") => {
1007
- if (!props)
1008
- return shouldPrintDebug && logger.info([" getProps() no props"].join(" ")), {};
1009
- if (excludeProps?.size)
1010
- for (const key in props)
1011
- excludeProps.has(key) && (shouldPrintDebug && logger.info([" delete excluded", key].join(" ")), delete props[key]);
1012
- const before = process.env.IS_STATIC;
1013
- process.env.IS_STATIC = "is_static";
1014
- try {
1015
- const out = getSplitStyles(
1016
- props,
1017
- staticConfig,
1018
- defaultTheme,
1019
- "",
1020
- componentState,
1021
- {
1022
- ...styleProps,
1023
- noClass: !0,
1024
- fallbackProps: completeProps,
1025
- ...platform2 === "native" && {
1026
- resolveValues: "except-theme"
1027
- }
1028
- },
1029
- void 0,
1030
- void 0,
1031
- void 0,
1032
- void 0,
1033
- !1,
1034
- debugPropValue || shouldPrintDebug
1035
- );
1036
- let outProps = {
1037
- ...includeProps ? out.viewProps : {},
1038
- ...out.style,
1039
- ...out.pseudos
1040
- };
1041
- for (const key in outProps)
1042
- deoptProps.has(key) && (shouldFlatten = !1);
1043
- return shouldPrintDebug && (logger.info(`(${debugName})`), logger.info(`
1044
- getProps (props in): ${(0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(props))}`), logger.info(
1045
- `
1046
- getProps (outProps): ${(0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(outProps))}`
1047
- )), out.fontFamily && ((0, import_propsToFontFamilyCache.setPropsToFontFamily)(outProps, out.fontFamily), shouldPrintDebug && logger.info(`
1048
- \u{1F4AC} new font fam: ${out.fontFamily}`)), outProps;
1049
- } catch (err) {
1050
- return logger.info(["error", err.message, err.stack].join(" ")), {};
1051
- } finally {
1052
- process.env.IS_STATIC = before;
1053
- }
1054
- };
1055
- attrs.unshift({
1056
- type: "style",
1057
- value: defaultProps
1058
- }), attrs = attrs.reduce((acc, cur) => {
1059
- if (cur.type === "style") {
1060
- const keys = Object.keys(cur.value || {});
1061
- if (!keys.length)
1062
- return acc;
1063
- const key = keys[0], value = cur.value[key], isMediaLikeKey = key[0] === "$" && (key.startsWith("$theme-") || key.startsWith("$platform-") || key.startsWith("$group-") || mediaQueryConfig[key.slice(1)]);
1064
- if (
1065
- // !isStyleAndAttr[key] &&
1066
- !shouldFlatten && // de-opt if non-style
1067
- !validStyles[key] && !pseudoDescriptors[key] && !isMediaLikeKey && !(key.startsWith("data-") || key.startsWith("aria-"))
1068
- )
1069
- return shouldPrintDebug && logger.info([" - keeping as non-style", key].join(" ")), prev = cur, acc.push({
1070
- type: "attr",
1071
- value: t.jsxAttribute(
1072
- t.jsxIdentifier(key),
1073
- t.jsxExpressionContainer(
1074
- typeof value == "string" ? t.stringLiteral(value) : (0, import_literalToAst.literalToAst)(value)
1075
- )
1076
- )
1077
- }), acc.push(cur), acc;
1078
- if (prev?.type === "style")
1079
- return mergeStyles(prev.value, cur.value), acc;
1080
- }
1081
- return cur.type === "style" && (prev = cur), acc.push(cur), acc;
1082
- }, []), shouldPrintDebug && logger.info(
1083
- [
1084
- ` - attrs (combined \u{1F500}):
1085
- `,
1086
- (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))
1087
- ].join(" ")
1088
- );
1089
- let getStyleError = null;
1090
- for (const attr of attrs)
1091
- try {
1092
- switch (shouldPrintDebug && console.info(` Processing ${attr.type}:`), attr.type) {
1093
- case "ternary": {
1094
- const a = getProps(attr.value.alternate, !1, "ternary.alternate"), c = getProps(attr.value.consequent, !1, "ternary.consequent");
1095
- a && (attr.value.alternate = a), c && (attr.value.consequent = c), shouldPrintDebug && logger.info([" => tern ", (0, import_extractHelpers.attrStr)(attr)].join(" "));
1096
- continue;
1097
- }
1098
- case "style": {
1099
- const styles = getProps(attr.value, !1, "style");
1100
- styles && (attr.value = styles), shouldPrintDebug && logger.info(
1101
- [" * styles (in)", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(attr.value))].join(" ")
1102
- ), shouldPrintDebug && logger.info(
1103
- [" * styles (out)", (0, import_logLines.logLines)((0, import_extractHelpers.objToStr)(styles))].join(" ")
1104
- );
1105
- continue;
1106
- }
1107
- case "attr":
1108
- if (shouldFlatten && t.isJSXAttribute(attr.value)) {
1109
- const key = attr.value.name.name;
1110
- if (key === "style" || key === "className" || key === "render")
1111
- continue;
1112
- const value = attemptEvalSafe(
1113
- attr.value.value || t.booleanLiteral(!0)
1114
- );
1115
- if (value !== import_constants.FAILED_EVAL) {
1116
- const outProps = getProps({ [key]: value }, !0, `attr.${key}`), outKey = Object.keys(outProps)[0];
1117
- if (outKey) {
1118
- const outVal = outProps[outKey];
1119
- attr.value = t.jsxAttribute(
1120
- t.jsxIdentifier(outKey),
1121
- t.jsxExpressionContainer(
1122
- typeof outVal == "string" ? t.stringLiteral(outVal) : (0, import_literalToAst.literalToAst)(outVal)
1123
- )
1124
- );
1125
- }
1126
- }
1127
- }
1128
- }
1129
- } catch (err) {
1130
- getStyleError = err;
1131
- }
1132
- if (shouldPrintDebug && logger.info(
1133
- [
1134
- ` - attrs (ternaries/combined):
1135
- `,
1136
- (0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))
1137
- ].join(" ")
1138
- ), tm.mark("jsx-element-styles", !!shouldPrintDebug), getStyleError)
1139
- return logger.info([" \u26A0\uFE0F postprocessing error, deopt", getStyleError].join(" ")), node.attributes = ogAttributes, null;
1140
- const existingStyleKeys = /* @__PURE__ */ new Set();
1141
- for (let i = attrs.length - 1; i >= 0; i--) {
1142
- const attr = attrs[i];
1143
- if (shouldFlatten && attr.type === "attr" && t.isJSXAttribute(attr.value) && t.isJSXIdentifier(attr.value.name)) {
1144
- const name = attr.value.name.name;
1145
- INLINE_EXTRACTABLE[name] && (attr.value.name.name = INLINE_EXTRACTABLE[name]);
1146
- }
1147
- if (attr.type === "style")
1148
- for (const key in attr.value)
1149
- existingStyleKeys.has(key) ? (shouldPrintDebug && logger.info([` >> delete existing ${key}`].join(" ")), delete attr.value[key]) : existingStyleKeys.add(key);
1150
- }
1151
- if (attrs = attrs.filter(Boolean), !shouldFlatten && inlineWhenUnflattened.size) {
1152
- for (const [index, attr] of attrs.entries())
1153
- if (attr.type === "style")
1154
- for (const key in attr.value) {
1155
- if (!inlineWhenUnflattened.has(key)) continue;
1156
- const val = inlineWhenUnflattenedOGVals[key];
1157
- val ? (delete attr.value[key], attrs.splice(index - 1, 0, val.attr)) : delete attr.value[key];
1158
- }
1159
- }
1160
- if (attrs = attrs.filter((x) => !(x.type === "style" && Object.keys(x.value).length === 0)), !shouldFlatten && platform2 === "native")
1161
- return shouldPrintDebug && logger.info(
1162
- `Disabled flattening except for simple cases on native for now: ${JSON.stringify(
1163
- {
1164
- flatNode: flatNodeName,
1165
- shouldDeopt,
1166
- canFlattenProps,
1167
- hasSpread,
1168
- "staticConfig.isStyledHOC": staticConfig.isStyledHOC,
1169
- "!staticConfig.isHOC": !staticConfig.isHOC,
1170
- "staticConfig.isReactNative": staticConfig.isReactNative,
1171
- "staticConfig.neverFlatten": staticConfig.neverFlatten
1172
- },
1173
- null,
1174
- 2
1175
- )}`
1176
- ), node.attributes = ogAttributes, null;
1177
- if (shouldPrintDebug && (logger.info(
1178
- [
1179
- ` - inlined props (${inlined.size}):`,
1180
- shouldDeopt ? " deopted" : "",
1181
- hasSpread ? " has spread" : "",
1182
- staticConfig.neverFlatten ? "neverFlatten" : ""
1183
- ].join(" ")
1184
- ), logger.info(` - attrs (end):
1185
- ${(0, import_logLines.logLines)(attrs.map(import_extractHelpers.attrStr).join(", "))}`)), onExtractTag({
1186
- parserProps: propsWithFileInfo,
1187
- attrs,
1188
- node,
1189
- lineNumbers,
1190
- filePath,
1191
- config: tamaguiConfig,
1192
- flatNodeName,
1193
- attemptEval,
1194
- jsxPath: traversePath,
1195
- originalNodeName,
1196
- programPath,
1197
- completeProps,
1198
- staticConfig
1199
- }), shouldFlatten) {
1200
- shouldPrintDebug && logger.info([" [\u2705] flattened", originalNodeName, flatNodeName].join(" "));
1201
- const currentName = node.name?.name;
1202
- (!currentName || currentName === originalNodeName || currentName.startsWith("__ReactNative")) && (node.name.name = flatNodeName, closingElement && (closingElement.name.name = flatNodeName)), res.flattened++;
1203
- }
1204
- } catch (err) {
1205
- node.attributes = ogAttributes, err instanceof import_errors.BailOptimizationError || (console.error(
1206
- `@tamagui/static error, reverting optimization. In ${filePath} ${lineNumbers} on ${originalNodeName}: ${err.message}. For stack trace set environment TAMAGUI_DEBUG=1`
1207
- ), process.env.TAMAGUI_DEBUG === "1" && console.error(err.stack));
1208
- } finally {
1209
- debugPropValue && (shouldPrintDebug = ogDebug);
1210
- }
1211
- }
1212
- }), tm.mark("jsx-done", !!shouldPrintDebug), tm.done(shouldPrintDebug === "verbose"), res;
1213
- }
1214
- }
1215
- //# sourceMappingURL=createExtractor.js.map