@hanzogui/static 3.0.6 → 4.3.1

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