@tamagui/static 1.0.1-beta.190 → 1.0.1-beta.192
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.
- package/dist/constants.js +0 -3
- package/dist/constants.js.map +2 -2
- package/dist/extractor/buildClassName.js +20 -5
- package/dist/extractor/buildClassName.js.map +2 -2
- package/dist/extractor/createEvaluator.js +3 -3
- package/dist/extractor/createEvaluator.js.map +2 -2
- package/dist/extractor/createExtractor.js +72 -49
- package/dist/extractor/createExtractor.js.map +3 -3
- package/dist/extractor/ensureImportingConcat.js +4 -8
- package/dist/extractor/ensureImportingConcat.js.map +2 -2
- package/dist/extractor/extractHelpers.js +37 -9
- package/dist/extractor/extractHelpers.js.map +3 -3
- package/dist/extractor/extractMediaStyle.js +11 -11
- package/dist/extractor/extractMediaStyle.js.map +2 -2
- package/dist/extractor/extractToClassNames.js +5 -17
- package/dist/extractor/extractToClassNames.js.map +2 -2
- package/dist/extractor/getStaticBindingsForScope.js +3 -3
- package/dist/extractor/getStaticBindingsForScope.js.map +2 -2
- package/dist/extractor/loadTamagui.js +7 -5
- package/dist/extractor/loadTamagui.js.map +2 -2
- package/dist/types.js.map +1 -1
- package/package.json +16 -14
- package/src/constants.ts +0 -1
- package/src/extractor/buildClassName.ts +20 -4
- package/src/extractor/createEvaluator.ts +5 -5
- package/src/extractor/createExtractor.ts +53 -33
- package/src/extractor/ensureImportingConcat.ts +4 -11
- package/src/extractor/extractHelpers.ts +41 -7
- package/src/extractor/extractMediaStyle.ts +17 -10
- package/src/extractor/extractToClassNames.ts +6 -20
- package/src/extractor/getStaticBindingsForScope.ts +4 -4
- package/src/extractor/loadTamagui.ts +9 -7
- package/src/types.ts +5 -2
- package/types/constants.d.ts +0 -1
- package/types/extractor/buildClassName.d.ts +4 -1
- package/types/extractor/createEvaluator.d.ts +3 -3
- package/types/extractor/createExtractor.d.ts +1 -1
- package/types/extractor/extractHelpers.d.ts +5 -3
- package/types/extractor/extractMediaStyle.d.ts +3 -3
- package/types/types.d.ts +4 -2
|
@@ -26,16 +26,21 @@ var extractHelpers_exports = {};
|
|
|
26
26
|
__export(extractHelpers_exports, {
|
|
27
27
|
attrStr: () => attrStr,
|
|
28
28
|
findComponentName: () => findComponentName,
|
|
29
|
-
|
|
29
|
+
isComponentPackage: () => isComponentPackage,
|
|
30
|
+
isInsideComponentPackage: () => isInsideComponentPackage,
|
|
30
31
|
isPresent: () => isPresent,
|
|
31
32
|
isSimpleSpread: () => isSimpleSpread,
|
|
33
|
+
isValidImport: () => isValidImport,
|
|
32
34
|
isValidThemeHook: () => isValidThemeHook,
|
|
33
35
|
objToStr: () => objToStr,
|
|
34
36
|
ternaryStr: () => ternaryStr
|
|
35
37
|
});
|
|
36
38
|
module.exports = __toCommonJS(extractHelpers_exports);
|
|
39
|
+
var import_path = require("path");
|
|
37
40
|
var import_generator = __toESM(require("@babel/generator"));
|
|
38
41
|
var t = __toESM(require("@babel/types"));
|
|
42
|
+
var import_find_root = __toESM(require("find-root"));
|
|
43
|
+
var import_lodash = require("lodash");
|
|
39
44
|
function isPresent(input) {
|
|
40
45
|
return input != null;
|
|
41
46
|
}
|
|
@@ -92,7 +97,7 @@ function findComponentName(scope) {
|
|
|
92
97
|
}
|
|
93
98
|
return componentName;
|
|
94
99
|
}
|
|
95
|
-
function isValidThemeHook(jsxPath, n, sourcePath) {
|
|
100
|
+
function isValidThemeHook(props, jsxPath, n, sourcePath) {
|
|
96
101
|
var _a;
|
|
97
102
|
if (!t.isIdentifier(n.object) || !t.isIdentifier(n.property))
|
|
98
103
|
return false;
|
|
@@ -112,23 +117,46 @@ function isValidThemeHook(jsxPath, n, sourcePath) {
|
|
|
112
117
|
const importNode = (_a = binding.scope.getBinding("useTheme")) == null ? void 0 : _a.path.parent;
|
|
113
118
|
if (!t.isImportDeclaration(importNode))
|
|
114
119
|
return false;
|
|
115
|
-
if (
|
|
116
|
-
|
|
117
|
-
return false;
|
|
118
|
-
}
|
|
120
|
+
if (!isValidImport(props, sourcePath)) {
|
|
121
|
+
return false;
|
|
119
122
|
}
|
|
120
123
|
return true;
|
|
121
124
|
}
|
|
122
|
-
const
|
|
123
|
-
return
|
|
125
|
+
const isInsideComponentPackage = (props, srcName) => {
|
|
126
|
+
return getValidComponentsPaths(props).some((path) => {
|
|
127
|
+
return srcName.startsWith(path);
|
|
128
|
+
});
|
|
129
|
+
};
|
|
130
|
+
const isComponentPackage = (props, srcName) => {
|
|
131
|
+
return getValidComponentsPaths(props).some((path) => {
|
|
132
|
+
return srcName.startsWith(path);
|
|
133
|
+
});
|
|
134
|
+
};
|
|
135
|
+
const isValidImport = (props, srcName) => {
|
|
136
|
+
if (typeof srcName !== "string") {
|
|
137
|
+
console.trace(`Invalid file name: ${srcName}`);
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
return srcName.startsWith(".") ? isInsideComponentPackage(props, srcName) : isComponentPackage(props, srcName);
|
|
124
141
|
};
|
|
142
|
+
const getValidComponentPackages = (0, import_lodash.memoize)((props) => {
|
|
143
|
+
return [.../* @__PURE__ */ new Set(["@tamagui/core", "tamagui", ...props.components])];
|
|
144
|
+
});
|
|
145
|
+
const getValidComponentsPaths = (0, import_lodash.memoize)((props) => {
|
|
146
|
+
return getValidComponentPackages(props).map((pkg) => {
|
|
147
|
+
const root = (0, import_find_root.default)(pkg);
|
|
148
|
+
return (0, import_path.basename)(root);
|
|
149
|
+
});
|
|
150
|
+
});
|
|
125
151
|
// Annotate the CommonJS export names for ESM import in node:
|
|
126
152
|
0 && (module.exports = {
|
|
127
153
|
attrStr,
|
|
128
154
|
findComponentName,
|
|
129
|
-
|
|
155
|
+
isComponentPackage,
|
|
156
|
+
isInsideComponentPackage,
|
|
130
157
|
isPresent,
|
|
131
158
|
isSimpleSpread,
|
|
159
|
+
isValidImport,
|
|
132
160
|
isValidThemeHook,
|
|
133
161
|
objToStr,
|
|
134
162
|
ternaryStr
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/extractor/extractHelpers.ts"],
|
|
4
|
-
"sourcesContent": ["import generate from '@babel/generator'\nimport type { NodePath } from '@babel/traverse'\nimport * as t from '@babel/types'\n\nimport type { ExtractedAttr, Ternary } from '../types.js'\n\n// import { astToLiteral } from './literalToAst'\n\nexport function isPresent<T extends Object>(input: null | void | undefined | T): input is T {\n return input != null\n}\n\nexport function isSimpleSpread(node: t.JSXSpreadAttribute) {\n return t.isIdentifier(node.argument) || t.isMemberExpression(node.argument)\n}\n\nexport const attrStr = (attr?: ExtractedAttr) => {\n return !attr\n ? ''\n : attr.type === 'attr'\n ? getNameAttr(attr.value)\n : attr.type === 'ternary'\n ? `...${ternaryStr(attr.value)}`\n : `${attr.type}(${objToStr(attr.value)})`\n}\n\nexport const objToStr = (obj: any, spacer = ', ') => {\n if (!obj) {\n return `${obj}`\n }\n return `{${Object.entries(obj)\n .map(\n ([k, v]) =>\n `${k}:${\n Array.isArray(v)\n ? `[...]`\n : v && typeof v === 'object'\n ? `${objToStr(v, ',')}`\n : JSON.stringify(v)\n }`\n )\n .join(spacer)}}`\n}\n\nconst getNameAttr = (attr: t.JSXAttribute | t.JSXSpreadAttribute) => {\n if (t.isJSXSpreadAttribute(attr)) {\n return `...${attr.argument['name']}`\n }\n return 'name' in attr ? attr.name.name : `unknown-${attr['type']}`\n}\n\nexport const ternaryStr = (x: Ternary) => {\n const conditional = t.isIdentifier(x.test)\n ? x.test.name\n : t.isMemberExpression(x.test)\n ? [x.test.object['name'], x.test.property['name']]\n : generate(x.test).code\n return [\n 'ternary(',\n conditional,\n isFilledObj(x.consequent) ? ` ? ${objToStr(x.consequent)}` : ' ? \uD83D\uDEAB',\n isFilledObj(x.alternate) ? ` : ${objToStr(x.alternate)}` : ' : \uD83D\uDEAB',\n ')',\n ]\n .flat()\n .join('')\n}\n\nconst isFilledObj = (obj: any) => obj && Object.keys(obj).length\n\nexport function findComponentName(scope) {\n const componentName = ''\n let cur = scope.path\n while (cur.parentPath && !t.isProgram(cur.parentPath.parent)) {\n cur = cur.parentPath\n }\n let node = cur.parent\n if (t.isExportNamedDeclaration(node)) {\n node = node.declaration\n }\n if (t.isVariableDeclaration(node)) {\n const [dec] = node.declarations\n if (t.isVariableDeclarator(dec) && t.isIdentifier(dec.id)) {\n return dec.id.name\n }\n }\n if (t.isFunctionDeclaration(node)) {\n return node.id?.name\n }\n return componentName\n}\n\nexport function isValidThemeHook(\n jsxPath: NodePath<t.JSXElement>,\n n: t.MemberExpression,\n sourcePath: string\n) {\n if (!t.isIdentifier(n.object) || !t.isIdentifier(n.property)) return false\n const bindings = jsxPath.scope.getAllBindings()\n const binding = bindings[n.object.name]\n if (!binding?.path) return false\n if (!binding.path.isVariableDeclarator()) return false\n const init = binding.path.node.init\n if (!t.isCallExpression(init)) return false\n if (!t.isIdentifier(init.callee)) return false\n // TODO could support renaming useTheme by looking up import first\n if (init.callee.name !== 'useTheme') return false\n const importNode = binding.scope.getBinding('useTheme')?.path.parent\n if (!t.isImportDeclaration(importNode)) return false\n if (
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAqB;AAErB,QAAmB;
|
|
6
|
-
"names": ["generate"]
|
|
4
|
+
"sourcesContent": ["import { basename, relative } from 'path'\n\nimport generate from '@babel/generator'\nimport type { NodePath } from '@babel/traverse'\nimport * as t from '@babel/types'\nimport findRoot from 'find-root'\nimport { memoize } from 'lodash'\n\nimport type { ExtractedAttr, TamaguiOptionsWithFileInfo, Ternary } from '../types.js'\n\n// import { astToLiteral } from './literalToAst'\n\nexport function isPresent<T extends Object>(input: null | void | undefined | T): input is T {\n return input != null\n}\n\nexport function isSimpleSpread(node: t.JSXSpreadAttribute) {\n return t.isIdentifier(node.argument) || t.isMemberExpression(node.argument)\n}\n\nexport const attrStr = (attr?: ExtractedAttr) => {\n return !attr\n ? ''\n : attr.type === 'attr'\n ? getNameAttr(attr.value)\n : attr.type === 'ternary'\n ? `...${ternaryStr(attr.value)}`\n : `${attr.type}(${objToStr(attr.value)})`\n}\n\nexport const objToStr = (obj: any, spacer = ', ') => {\n if (!obj) {\n return `${obj}`\n }\n return `{${Object.entries(obj)\n .map(\n ([k, v]) =>\n `${k}:${\n Array.isArray(v)\n ? `[...]`\n : v && typeof v === 'object'\n ? `${objToStr(v, ',')}`\n : JSON.stringify(v)\n }`\n )\n .join(spacer)}}`\n}\n\nconst getNameAttr = (attr: t.JSXAttribute | t.JSXSpreadAttribute) => {\n if (t.isJSXSpreadAttribute(attr)) {\n return `...${attr.argument['name']}`\n }\n return 'name' in attr ? attr.name.name : `unknown-${attr['type']}`\n}\n\nexport const ternaryStr = (x: Ternary) => {\n const conditional = t.isIdentifier(x.test)\n ? x.test.name\n : t.isMemberExpression(x.test)\n ? [x.test.object['name'], x.test.property['name']]\n : generate(x.test).code\n return [\n 'ternary(',\n conditional,\n isFilledObj(x.consequent) ? ` ? ${objToStr(x.consequent)}` : ' ? \uD83D\uDEAB',\n isFilledObj(x.alternate) ? ` : ${objToStr(x.alternate)}` : ' : \uD83D\uDEAB',\n ')',\n ]\n .flat()\n .join('')\n}\n\nconst isFilledObj = (obj: any) => obj && Object.keys(obj).length\n\nexport function findComponentName(scope) {\n const componentName = ''\n let cur = scope.path\n while (cur.parentPath && !t.isProgram(cur.parentPath.parent)) {\n cur = cur.parentPath\n }\n let node = cur.parent\n if (t.isExportNamedDeclaration(node)) {\n node = node.declaration\n }\n if (t.isVariableDeclaration(node)) {\n const [dec] = node.declarations\n if (t.isVariableDeclarator(dec) && t.isIdentifier(dec.id)) {\n return dec.id.name\n }\n }\n if (t.isFunctionDeclaration(node)) {\n return node.id?.name\n }\n return componentName\n}\n\nexport function isValidThemeHook(\n props: TamaguiOptionsWithFileInfo,\n jsxPath: NodePath<t.JSXElement>,\n n: t.MemberExpression,\n sourcePath: string\n) {\n if (!t.isIdentifier(n.object) || !t.isIdentifier(n.property)) return false\n const bindings = jsxPath.scope.getAllBindings()\n const binding = bindings[n.object.name]\n if (!binding?.path) return false\n if (!binding.path.isVariableDeclarator()) return false\n const init = binding.path.node.init\n if (!t.isCallExpression(init)) return false\n if (!t.isIdentifier(init.callee)) return false\n // TODO could support renaming useTheme by looking up import first\n if (init.callee.name !== 'useTheme') return false\n const importNode = binding.scope.getBinding('useTheme')?.path.parent\n if (!t.isImportDeclaration(importNode)) return false\n if (!isValidImport(props, sourcePath)) {\n return false\n }\n return true\n}\n\nexport const isInsideComponentPackage = (props: TamaguiOptionsWithFileInfo, srcName: string) => {\n return getValidComponentsPaths(props).some((path) => {\n return srcName.startsWith(path)\n })\n}\n\nexport const isComponentPackage = (props: TamaguiOptionsWithFileInfo, srcName: string) => {\n return getValidComponentsPaths(props).some((path) => {\n return srcName.startsWith(path)\n })\n}\n\nexport const isValidImport = (props: TamaguiOptionsWithFileInfo, srcName: string) => {\n if (typeof srcName !== 'string') {\n // eslint-disable-next-line no-console\n console.trace(`Invalid file name: ${srcName}`)\n return false\n }\n return srcName.startsWith('.')\n ? isInsideComponentPackage(props, srcName)\n : isComponentPackage(props, srcName)\n}\n\nconst getValidComponentPackages = memoize((props: TamaguiOptionsWithFileInfo) => {\n // just always look for `tamagui` and `@tamagui/core`\n return [...new Set(['@tamagui/core', 'tamagui', ...props.components])]\n})\n\nconst getValidComponentsPaths = memoize((props: TamaguiOptionsWithFileInfo) => {\n return getValidComponentPackages(props).map((pkg) => {\n const root = findRoot(pkg)\n return basename(root)\n })\n})\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAmC;AAEnC,uBAAqB;AAErB,QAAmB;AACnB,uBAAqB;AACrB,oBAAwB;AAMjB,SAAS,UAA4B,OAAgD;AAC1F,SAAO,SAA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,WAAO;AAC/C,MAAI,CAAC,cAAc,OAAO,UAAU,GAAG;AACrC,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEO,MAAM,2BAA2B,CAAC,OAAmC,YAAoB;AAC9F,SAAO,wBAAwB,KAAK,EAAE,KAAK,CAAC,SAAS;AACnD,WAAO,QAAQ,WAAW,IAAI;AAAA,EAChC,CAAC;AACH;AAEO,MAAM,qBAAqB,CAAC,OAAmC,YAAoB;AACxF,SAAO,wBAAwB,KAAK,EAAE,KAAK,CAAC,SAAS;AACnD,WAAO,QAAQ,WAAW,IAAI;AAAA,EAChC,CAAC;AACH;AAEO,MAAM,gBAAgB,CAAC,OAAmC,YAAoB;AACnF,MAAI,OAAO,YAAY,UAAU;AAE/B,YAAQ,MAAM,sBAAsB,SAAS;AAC7C,WAAO;AAAA,EACT;AACA,SAAO,QAAQ,WAAW,GAAG,IACzB,yBAAyB,OAAO,OAAO,IACvC,mBAAmB,OAAO,OAAO;AACvC;AAEA,MAAM,gCAA4B,uBAAQ,CAAC,UAAsC;AAE/E,SAAO,CAAC,GAAG,oBAAI,IAAI,CAAC,iBAAiB,WAAW,GAAG,MAAM,UAAU,CAAC,CAAC;AACvE,CAAC;AAED,MAAM,8BAA0B,uBAAQ,CAAC,UAAsC;AAC7E,SAAO,0BAA0B,KAAK,EAAE,IAAI,CAAC,QAAQ;AACnD,UAAM,WAAO,iBAAAC,SAAS,GAAG;AACzB,eAAO,sBAAS,IAAI;AAAA,EACtB,CAAC;AACH,CAAC;",
|
|
6
|
+
"names": ["generate", "findRoot"]
|
|
7
7
|
}
|
|
@@ -32,8 +32,8 @@ var t = __toESM(require("@babel/types"));
|
|
|
32
32
|
var import_core_node = require("@tamagui/core-node");
|
|
33
33
|
var import_constants = require("../constants.js");
|
|
34
34
|
var import_extractHelpers = require("./extractHelpers.js");
|
|
35
|
-
function extractMediaStyle(ternary, jsxPath, tamaguiConfig, sourcePath, importance = 0, shouldPrintDebug = false) {
|
|
36
|
-
const mt = getMediaQueryTernary(ternary, jsxPath, sourcePath);
|
|
35
|
+
function extractMediaStyle(props, ternary, jsxPath, tamaguiConfig, sourcePath, importance = 0, shouldPrintDebug = false) {
|
|
36
|
+
const mt = getMediaQueryTernary(props, ternary, jsxPath, sourcePath);
|
|
37
37
|
if (!mt) {
|
|
38
38
|
return null;
|
|
39
39
|
}
|
|
@@ -96,9 +96,10 @@ function extractMediaStyle(ternary, jsxPath, tamaguiConfig, sourcePath, importan
|
|
|
96
96
|
ternary.remove();
|
|
97
97
|
return { mediaStyles, ternaryWithoutMedia: mt.ternaryWithoutMedia };
|
|
98
98
|
}
|
|
99
|
-
function getMediaQueryTernary(ternary, jsxPath, sourcePath) {
|
|
99
|
+
function getMediaQueryTernary(props, ternary, jsxPath, sourcePath) {
|
|
100
100
|
if (t.isLogicalExpression(ternary.test) && ternary.test.operator === "&&") {
|
|
101
101
|
const mediaLeft = getMediaInfoFromExpression(
|
|
102
|
+
props,
|
|
102
103
|
ternary.test.left,
|
|
103
104
|
jsxPath,
|
|
104
105
|
sourcePath,
|
|
@@ -115,6 +116,7 @@ function getMediaQueryTernary(ternary, jsxPath, sourcePath) {
|
|
|
115
116
|
}
|
|
116
117
|
}
|
|
117
118
|
const result = getMediaInfoFromExpression(
|
|
119
|
+
props,
|
|
118
120
|
ternary.test,
|
|
119
121
|
jsxPath,
|
|
120
122
|
sourcePath,
|
|
@@ -128,7 +130,7 @@ function getMediaQueryTernary(ternary, jsxPath, sourcePath) {
|
|
|
128
130
|
}
|
|
129
131
|
return null;
|
|
130
132
|
}
|
|
131
|
-
function getMediaInfoFromExpression(test, jsxPath, sourcePath, inlineMediaQuery) {
|
|
133
|
+
function getMediaInfoFromExpression(props, test, jsxPath, sourcePath, inlineMediaQuery) {
|
|
132
134
|
var _a, _b, _c;
|
|
133
135
|
if (inlineMediaQuery) {
|
|
134
136
|
return {
|
|
@@ -146,7 +148,7 @@ function getMediaInfoFromExpression(test, jsxPath, sourcePath, inlineMediaQuery)
|
|
|
146
148
|
const bindingNode = (_a = binding.path) == null ? void 0 : _a.node;
|
|
147
149
|
if (!t.isVariableDeclarator(bindingNode) || !bindingNode.init)
|
|
148
150
|
return false;
|
|
149
|
-
if (!isValidMediaCall(jsxPath, bindingNode.init, sourcePath))
|
|
151
|
+
if (!isValidMediaCall(props, jsxPath, bindingNode.init, sourcePath))
|
|
150
152
|
return false;
|
|
151
153
|
return { key, bindingName: name };
|
|
152
154
|
}
|
|
@@ -155,13 +157,13 @@ function getMediaInfoFromExpression(test, jsxPath, sourcePath, inlineMediaQuery)
|
|
|
155
157
|
const node = (_c = (_b = jsxPath.scope.getBinding(test.name)) == null ? void 0 : _b.path) == null ? void 0 : _c.node;
|
|
156
158
|
if (!t.isVariableDeclarator(node))
|
|
157
159
|
return false;
|
|
158
|
-
if (!node.init || !isValidMediaCall(jsxPath, node.init, sourcePath))
|
|
160
|
+
if (!node.init || !isValidMediaCall(props, jsxPath, node.init, sourcePath))
|
|
159
161
|
return false;
|
|
160
162
|
return { key, bindingName: key };
|
|
161
163
|
}
|
|
162
164
|
return null;
|
|
163
165
|
}
|
|
164
|
-
function isValidMediaCall(jsxPath, init, sourcePath) {
|
|
166
|
+
function isValidMediaCall(props, jsxPath, init, sourcePath) {
|
|
165
167
|
if (!t.isCallExpression(init))
|
|
166
168
|
return false;
|
|
167
169
|
if (!t.isIdentifier(init.callee))
|
|
@@ -175,10 +177,8 @@ function isValidMediaCall(jsxPath, init, sourcePath) {
|
|
|
175
177
|
const useMediaImport = mediaBinding.path.parent;
|
|
176
178
|
if (!t.isImportDeclaration(useMediaImport))
|
|
177
179
|
return false;
|
|
178
|
-
if (
|
|
179
|
-
|
|
180
|
-
return false;
|
|
181
|
-
}
|
|
180
|
+
if (!(0, import_extractHelpers.isValidImport)(props, sourcePath)) {
|
|
181
|
+
return false;
|
|
182
182
|
}
|
|
183
183
|
return true;
|
|
184
184
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/extractor/extractMediaStyle.ts"],
|
|
4
|
-
"sourcesContent": ["import { NodePath } from '@babel/traverse'\nimport * as t from '@babel/types'\nimport { TamaguiInternalConfig, getStylesAtomic, mediaObjectToString } from '@tamagui/core-node'\nimport { ViewStyle } from 'react-native'\n\nimport { MEDIA_SEP } from '../constants.js'\nimport type { StyleObject, Ternary } from '../types.js'\nimport {
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,QAAmB;AACnB,uBAA4E;AAG5E,uBAA0B;AAE1B,
|
|
4
|
+
"sourcesContent": ["import { NodePath } from '@babel/traverse'\nimport * as t from '@babel/types'\nimport { TamaguiInternalConfig, getStylesAtomic, mediaObjectToString } from '@tamagui/core-node'\nimport type { ViewStyle } from 'react-native'\n\nimport { MEDIA_SEP } from '../constants.js'\nimport type { StyleObject, TamaguiOptionsWithFileInfo, Ternary } from '../types.js'\nimport { isPresent, isValidImport } from './extractHelpers.js'\n\nexport function extractMediaStyle(\n props: TamaguiOptionsWithFileInfo,\n ternary: Ternary,\n jsxPath: NodePath<t.JSXElement>,\n tamaguiConfig: TamaguiInternalConfig,\n sourcePath: string,\n importance = 0,\n shouldPrintDebug: boolean | 'verbose' = false\n) {\n const mt = getMediaQueryTernary(props, ternary, jsxPath, sourcePath)\n if (!mt) {\n return null\n }\n const { key } = mt\n const mq = tamaguiConfig.media[key]\n if (!mq) {\n // eslint-disable-next-line no-console\n console.error(`Media query \"${key}\" not found: ${Object.keys(tamaguiConfig.media)}`)\n return null\n }\n const getStyleObj = (styleObj: ViewStyle | null, negate = false) => {\n return styleObj ? { styleObj, negate } : null\n }\n const styleOpts = [\n getStyleObj(ternary.consequent, false),\n getStyleObj(ternary.alternate, true),\n ].filter(isPresent)\n if (shouldPrintDebug && !styleOpts.length) {\n // eslint-disable-next-line no-console\n console.log(' media query, no styles?')\n return null\n }\n // for now order first strongest\n const mediaKeys = Object.keys(tamaguiConfig.media)\n const mediaKeyPrecendence = mediaKeys.reduce((acc, cur, i) => {\n acc[cur] = new Array(importance + 1).fill(':root').join('')\n return acc\n }, {})\n let mediaStyles: StyleObject[] = []\n for (const { styleObj, negate } of styleOpts) {\n const styles = getStylesAtomic(styleObj)\n const singleMediaStyles = styles.map((style) => {\n const negKey = negate ? '0' : ''\n const ogPrefix = style.identifier.slice(0, style.identifier.indexOf('-') + 1)\n // adds an extra separator before and after to detect later in concatClassName\n // so it goes from: \"_f-[hash]\"\n // to: \"_f-_sm0_[hash]\" or \"_f-_sm_[hash]\"\n const identifier = `${style.identifier.replace(\n ogPrefix,\n `${ogPrefix}${MEDIA_SEP}${key}${negKey}${MEDIA_SEP}`\n )}`\n const className = `.${identifier}`\n const mediaSelector = mediaObjectToString(tamaguiConfig.media[key])\n const screenStr = negate ? 'not all' : 'screen'\n const mediaQuery = `${screenStr} and ${mediaSelector}`\n const precendencePrefix = mediaKeyPrecendence[key]\n const styleInner = style.rules\n .map((rule) => rule.replace(style.identifier, identifier))\n .join(';')\n // combines media queries if they already exist\n let styleRule = ''\n if (styleInner.includes('@media')) {\n // combine\n styleRule = styleInner.replace('{', ` and ${mediaQuery} {`)\n } else {\n styleRule = `@media ${mediaQuery} { ${precendencePrefix} ${styleInner} }`\n }\n return {\n ...style,\n identifier,\n className,\n rules: [styleRule],\n }\n })\n if (shouldPrintDebug === 'verbose') {\n // prettier-ignore\n // eslint-disable-next-line no-console\n console.log(' media styles:', importance, styleObj, singleMediaStyles.map(x => x.identifier).join(', '))\n }\n // add to output\n mediaStyles = [...mediaStyles, ...singleMediaStyles]\n }\n // filter out\n ternary.remove()\n return { mediaStyles, ternaryWithoutMedia: mt.ternaryWithoutMedia }\n}\n\nfunction getMediaQueryTernary(\n props: TamaguiOptionsWithFileInfo,\n ternary: Ternary,\n jsxPath: NodePath<t.JSXElement>,\n sourcePath: string\n): null | {\n key: string\n bindingName: string\n ternaryWithoutMedia: Ternary | null\n} {\n // this handles unwrapping logical && media query ternarys\n // first, unwrap if it has media logicalExpression\n if (t.isLogicalExpression(ternary.test) && ternary.test.operator === '&&') {\n // *should* be normalized to always be on left side\n const mediaLeft = getMediaInfoFromExpression(\n props,\n ternary.test.left,\n jsxPath,\n sourcePath,\n ternary.inlineMediaQuery\n )\n if (mediaLeft) {\n return {\n ...mediaLeft,\n ternaryWithoutMedia: {\n ...ternary,\n test: ternary.test.right,\n },\n }\n }\n }\n // const media = useMedia()\n // ... media.sm\n const result = getMediaInfoFromExpression(\n props,\n ternary.test,\n jsxPath,\n sourcePath,\n ternary.inlineMediaQuery\n )\n if (result) {\n return {\n ...result,\n ternaryWithoutMedia: null,\n }\n }\n return null\n}\n\nfunction getMediaInfoFromExpression(\n props: TamaguiOptionsWithFileInfo,\n test: t.Expression,\n jsxPath: NodePath<t.JSXElement>,\n sourcePath: string,\n inlineMediaQuery?: string\n) {\n if (inlineMediaQuery) {\n return {\n key: inlineMediaQuery,\n bindingName: inlineMediaQuery,\n }\n }\n if (t.isMemberExpression(test) && t.isIdentifier(test.object) && t.isIdentifier(test.property)) {\n const name = test.object['name']\n const key = test.property['name']\n const bindings = jsxPath.scope.getAllBindings()\n const binding = bindings[name]\n if (!binding) return false\n const bindingNode = binding.path?.node\n if (!t.isVariableDeclarator(bindingNode) || !bindingNode.init) return false\n if (!isValidMediaCall(props, jsxPath, bindingNode.init, sourcePath)) return false\n return { key, bindingName: name }\n }\n if (t.isIdentifier(test)) {\n const key = test.name\n const node = jsxPath.scope.getBinding(test.name)?.path?.node\n if (!t.isVariableDeclarator(node)) return false\n if (!node.init || !isValidMediaCall(props, jsxPath, node.init, sourcePath)) return false\n return { key, bindingName: key }\n }\n return null\n}\n\nexport function isValidMediaCall(\n props: TamaguiOptionsWithFileInfo,\n jsxPath: NodePath<t.JSXElement>,\n init: t.Expression,\n sourcePath: string\n) {\n if (!t.isCallExpression(init)) return false\n if (!t.isIdentifier(init.callee)) return false\n // TODO could support renaming useMedia by looking up import first\n if (init.callee.name !== 'useMedia') return false\n const bindings = jsxPath.scope.getAllBindings()\n const mediaBinding = bindings['useMedia']\n if (!mediaBinding) return false\n const useMediaImport = mediaBinding.path.parent\n if (!t.isImportDeclaration(useMediaImport)) return false\n if (!isValidImport(props, sourcePath)) {\n return false\n }\n return true\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,QAAmB;AACnB,uBAA4E;AAG5E,uBAA0B;AAE1B,4BAAyC;AAElC,SAAS,kBACd,OACA,SACA,SACA,eACA,YACA,aAAa,GACb,mBAAwC,OACxC;AACA,QAAM,KAAK,qBAAqB,OAAO,SAAS,SAAS,UAAU;AACnE,MAAI,CAAC,IAAI;AACP,WAAO;AAAA,EACT;AACA,QAAM,EAAE,IAAI,IAAI;AAChB,QAAM,KAAK,cAAc,MAAM;AAC/B,MAAI,CAAC,IAAI;AAEP,YAAQ,MAAM,gBAAgB,mBAAmB,OAAO,KAAK,cAAc,KAAK,GAAG;AACnF,WAAO;AAAA,EACT;AACA,QAAM,cAAc,CAAC,UAA4B,SAAS,UAAU;AAClE,WAAO,WAAW,EAAE,UAAU,OAAO,IAAI;AAAA,EAC3C;AACA,QAAM,YAAY;AAAA,IAChB,YAAY,QAAQ,YAAY,KAAK;AAAA,IACrC,YAAY,QAAQ,WAAW,IAAI;AAAA,EACrC,EAAE,OAAO,+BAAS;AAClB,MAAI,oBAAoB,CAAC,UAAU,QAAQ;AAEzC,YAAQ,IAAI,2BAA2B;AACvC,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,OAAO,KAAK,cAAc,KAAK;AACjD,QAAM,sBAAsB,UAAU,OAAO,CAAC,KAAK,KAAK,MAAM;AAC5D,QAAI,OAAO,IAAI,MAAM,aAAa,CAAC,EAAE,KAAK,OAAO,EAAE,KAAK,EAAE;AAC1D,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AACL,MAAI,cAA6B,CAAC;AA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,mBAA2C;AACxD,QAAI,CAAC,EAAE,qBAAqB,IAAI;AAAG,aAAO;AAC1C,QAAI,CAAC,KAAK,QAAQ,CAAC,iBAAiB,OAAO,SAAS,KAAK,MAAM,UAAU;AAAG,aAAO;AACnF,WAAO,EAAE,KAAK,aAAa,IAAI;AAAA,EACjC;AACA,SAAO;AACT;AAEO,SAAS,iBACd,OACA,SACA,MACA,YACA;AACA,MAAI,CAAC,EAAE,iBAAiB,IAAI;AAAG,WAAO;AACtC,MAAI,CAAC,EAAE,aAAa,KAAK,MAAM;AAAG,WAAO;AAEzC,MAAI,KAAK,OAAO,SAAS;AAAY,WAAO;AAC5C,QAAM,WAAW,QAAQ,MAAM,eAAe;AAC9C,QAAM,eAAe,SAAS;AAC9B,MAAI,CAAC;AAAc,WAAO;AAC1B,QAAM,iBAAiB,aAAa,KAAK;AACzC,MAAI,CAAC,EAAE,oBAAoB,cAAc;AAAG,WAAO;AACnD,MAAI,KAAC,qCAAc,OAAO,UAAU,GAAG;AACrC,WAAO;AAAA,EACT;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -35,7 +35,6 @@ var t = __toESM(require("@babel/types"));
|
|
|
35
35
|
var import_core_node = require("@tamagui/core-node");
|
|
36
36
|
var import_helpers = require("@tamagui/helpers");
|
|
37
37
|
var import_invariant = __toESM(require("invariant"));
|
|
38
|
-
var import_constants = require("../constants.js");
|
|
39
38
|
var import_babelParse = require("./babelParse.js");
|
|
40
39
|
var import_buildClassName = require("./buildClassName.js");
|
|
41
40
|
var import_ensureImportingConcat = require("./ensureImportingConcat.js");
|
|
@@ -82,9 +81,9 @@ async function extractToClassNames({
|
|
|
82
81
|
const existingHoists = {};
|
|
83
82
|
let hasFlattened = false;
|
|
84
83
|
const res = await extractor.parse(ast, {
|
|
85
|
-
sourcePath,
|
|
86
84
|
shouldPrintDebug,
|
|
87
85
|
...options,
|
|
86
|
+
sourcePath,
|
|
88
87
|
target: "html",
|
|
89
88
|
extractStyledDefinitions: true,
|
|
90
89
|
onStyleRule(identifier, rules) {
|
|
@@ -206,6 +205,7 @@ async function extractToClassNames({
|
|
|
206
205
|
}
|
|
207
206
|
case "ternary": {
|
|
208
207
|
const mediaExtraction = (0, import_extractMediaStyle.extractMediaStyle)(
|
|
208
|
+
{ ...options, sourcePath },
|
|
209
209
|
attr.value,
|
|
210
210
|
jsxPath,
|
|
211
211
|
extractor.getTamagui(),
|
|
@@ -291,15 +291,7 @@ async function extractToClassNames({
|
|
|
291
291
|
}
|
|
292
292
|
return value;
|
|
293
293
|
})();
|
|
294
|
-
|
|
295
|
-
if (names) {
|
|
296
|
-
if (t.isStringLiteral(names)) {
|
|
297
|
-
names.value = (0, import_helpers.concatClassName)(names.value);
|
|
298
|
-
names.value = `${extraClassNames} ${names.value}`;
|
|
299
|
-
} else {
|
|
300
|
-
names = t.binaryExpression("+", t.stringLiteral(extraClassNames), names);
|
|
301
|
-
}
|
|
302
|
-
}
|
|
294
|
+
const names = (0, import_buildClassName.buildClassName)(finalClassNames, extraClassNames);
|
|
303
295
|
const nameExpr = names ? (0, import_hoistClassNames.hoistClassNames)(jsxPath, existingHoists, names) : null;
|
|
304
296
|
let expr = nameExpr;
|
|
305
297
|
if (nameExpr && !t.isIdentifier(nameExpr)) {
|
|
@@ -309,7 +301,7 @@ async function extractToClassNames({
|
|
|
309
301
|
const simpleSpreads = attrs.filter(
|
|
310
302
|
(x) => t.isJSXSpreadAttribute(x.value) && (0, import_extractHelpers.isSimpleSpread)(x.value)
|
|
311
303
|
);
|
|
312
|
-
expr = t.callExpression(t.identifier(
|
|
304
|
+
expr = t.callExpression(t.identifier("concatClassName"), [
|
|
313
305
|
expr,
|
|
314
306
|
...simpleSpreads.map((val) => val.value["argument"])
|
|
315
307
|
]);
|
|
@@ -329,12 +321,8 @@ async function extractToClassNames({
|
|
|
329
321
|
cssMap.set(className, val);
|
|
330
322
|
}
|
|
331
323
|
} else if (rules.length) {
|
|
332
|
-
if (rules.length > 1) {
|
|
333
|
-
console.log(" rules error", { rules });
|
|
334
|
-
throw new Error(`Shouldn't have more than one rule`);
|
|
335
|
-
}
|
|
336
324
|
cssMap.set(className, {
|
|
337
|
-
css: rules
|
|
325
|
+
css: rules.join("\n"),
|
|
338
326
|
commentTexts: [comment]
|
|
339
327
|
});
|
|
340
328
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/extractor/extractToClassNames.ts"],
|
|
4
|
-
"sourcesContent": ["import * as path from 'path'\nimport { basename } from 'path'\nimport * as util from 'util'\n\nimport generate from '@babel/generator'\nimport * as t from '@babel/types'\nimport { getStylesAtomic } from '@tamagui/core-node'\nimport { concatClassName } from '@tamagui/helpers'\nimport invariant from 'invariant'\nimport { ViewStyle } from 'react-native'\n\nimport { CONCAT_CLASSNAME_IMPORT } from '../constants.js'\nimport type { ClassNameObject, StyleObject, TamaguiOptions, Ternary } from '../types.js'\nimport { babelParse } from './babelParse.js'\nimport { buildClassName } from './buildClassName.js'\nimport { Extractor } from './createExtractor.js'\nimport { ensureImportingConcat } from './ensureImportingConcat.js'\nimport { isSimpleSpread } from './extractHelpers.js'\nimport { extractMediaStyle } from './extractMediaStyle.js'\nimport { getPrefixLogs } from './getPrefixLogs.js'\nimport { hoistClassNames } from './hoistClassNames.js'\nimport { logLines } from './logLines.js'\nimport { timer } from './timer.js'\n\nconst mergeStyleGroups = {\n shadowOpacity: true,\n shadowRadius: true,\n shadowColor: true,\n shadowOffset: true,\n}\n\nexport type ExtractedResponse = {\n js: string | Buffer\n styles: string\n stylesPath?: string\n ast: t.File\n map: any // RawSourceMap from 'source-map'\n}\n\nexport async function extractToClassNames({\n extractor,\n source,\n sourcePath,\n options,\n shouldPrintDebug,\n}: {\n extractor: Extractor\n source: string | Buffer\n sourcePath: string\n options: TamaguiOptions\n shouldPrintDebug: boolean | 'verbose'\n}): Promise<ExtractedResponse | null> {\n const tm = timer()\n\n if (typeof source !== 'string') {\n throw new Error('`source` must be a string of javascript')\n }\n invariant(\n typeof sourcePath === 'string' && path.isAbsolute(sourcePath),\n '`sourcePath` must be an absolute path to a .js file'\n )\n\n // dont include loading in timing of parsing (one time cost)\n await extractor.loadTamagui(options)\n\n const shouldLogTiming = options.logTimings ?? true\n const start = Date.now()\n const mem = shouldLogTiming ? process.memoryUsage() : null\n\n // Using a map for (officially supported) guaranteed insertion order\n let ast: t.File\n\n try {\n ast = babelParse(source)\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('babel parse error:', sourcePath)\n throw err\n }\n\n tm.mark(`babel-parse`, shouldPrintDebug === 'verbose')\n\n const cssMap = new Map<string, { css: string; commentTexts: string[] }>()\n const existingHoists: { [key: string]: t.Identifier } = {}\n\n let hasFlattened = false\n\n const res = await extractor.parse(ast, {\n sourcePath,\n shouldPrintDebug,\n ...options,\n target: 'html',\n extractStyledDefinitions: true,\n onStyleRule(identifier, rules) {\n cssMap.set(`.${identifier}`, { css: rules.join(';'), commentTexts: [] })\n },\n getFlattenedNode: ({ tag }) => {\n hasFlattened = true\n return tag\n },\n onExtractTag: ({\n attrs,\n node,\n attemptEval,\n jsxPath,\n originalNodeName,\n filePath,\n lineNumbers,\n programPath,\n isFlattened,\n completeProps,\n staticConfig,\n }) => {\n // bail out of views that don't accept className (falls back to runtime + style={})\n if (staticConfig.acceptsClassName === false) {\n if (shouldPrintDebug) {\n // eslint-disable-next-line no-console\n console.log(`bail, acceptsClassName is false`)\n }\n return\n }\n\n // reset hasFlattened\n const didFlattenThisTag = hasFlattened\n hasFlattened = false\n\n let finalClassNames: ClassNameObject[] = []\n const finalAttrs: (t.JSXAttribute | t.JSXSpreadAttribute)[] = []\n let finalStyles: StyleObject[] = []\n\n let viewStyles = {}\n for (const attr of attrs) {\n if (attr.type === 'style') {\n viewStyles = {\n ...viewStyles,\n ...attr.value,\n }\n }\n }\n\n const ensureNeededPrevStyle = (style: ViewStyle) => {\n // ensure all group keys are merged\n const keys = Object.keys(style)\n if (!keys.some((key) => mergeStyleGroups[key])) {\n return style\n }\n for (const k in mergeStyleGroups) {\n if (k in viewStyles) {\n style[k] = style[k] ?? viewStyles[k]\n }\n }\n return style\n }\n\n const addStyles = (style: ViewStyle | null): StyleObject[] => {\n if (!style) return []\n const styleWithPrev = ensureNeededPrevStyle(style)\n const res = getStylesAtomic(styleWithPrev)\n if (res.length) {\n finalStyles = [...finalStyles, ...res]\n }\n return res\n }\n\n // 1 to start above any :hover styles\n let lastMediaImportance = 1\n for (const attr of attrs) {\n switch (attr.type) {\n case 'style': {\n if (!isFlattened) {\n const styles = getStylesAtomic(attr.value)\n\n finalStyles = [...finalStyles, ...styles]\n\n for (const style of styles) {\n // leave them as attributes\n const prop = style.pseudo ? `${style.property}-${style.pseudo}` : style.property\n finalAttrs.push(\n t.jsxAttribute(t.jsxIdentifier(prop), t.stringLiteral(style.identifier))\n )\n }\n } else {\n const styles = addStyles(attr.value)\n const newClassNames = concatClassName(styles.map((x) => x.identifier).join(' '))\n const existing = finalClassNames.find(\n (x) => x.type == 'StringLiteral'\n ) as t.StringLiteral | null\n\n if (existing) {\n existing.value = `${existing.value} ${newClassNames}`\n } else {\n finalClassNames = [...finalClassNames, t.stringLiteral(newClassNames)]\n }\n }\n\n break\n }\n case 'attr': {\n const val = attr.value\n if (t.isJSXSpreadAttribute(val)) {\n if (isSimpleSpread(val)) {\n finalClassNames.push(\n t.logicalExpression(\n '&&',\n val.argument,\n t.memberExpression(val.argument, t.identifier('className'))\n )\n )\n }\n } else if (val.name.name === 'className') {\n const value = val.value\n if (value) {\n try {\n const evaluatedValue = attemptEval(value)\n finalClassNames.push(t.stringLiteral(evaluatedValue))\n } catch (e) {\n finalClassNames.push(value['expression'])\n }\n }\n continue\n }\n finalAttrs.push(val)\n break\n }\n case 'ternary': {\n const mediaExtraction = extractMediaStyle(\n attr.value,\n jsxPath,\n extractor.getTamagui()!,\n sourcePath,\n lastMediaImportance,\n shouldPrintDebug\n )\n if (shouldPrintDebug) {\n if (mediaExtraction) {\n // eslint-disable-next-line no-console\n console.log(\n 'ternary (mediaStyles)',\n mediaExtraction.ternaryWithoutMedia?.inlineMediaQuery ?? '',\n mediaExtraction.mediaStyles.map((x) => x.identifier).join('.')\n )\n }\n }\n if (!mediaExtraction) {\n addTernaryStyle(\n attr.value,\n addStyles(attr.value.consequent),\n addStyles(attr.value.alternate)\n )\n continue\n }\n lastMediaImportance++\n if (mediaExtraction.mediaStyles) {\n finalStyles = [...finalStyles, ...mediaExtraction.mediaStyles]\n }\n if (mediaExtraction.ternaryWithoutMedia) {\n addTernaryStyle(mediaExtraction.ternaryWithoutMedia, mediaExtraction.mediaStyles, [])\n } else {\n finalClassNames = [\n ...finalClassNames,\n ...mediaExtraction.mediaStyles.map((x) => t.stringLiteral(x.identifier)),\n ]\n }\n break\n }\n }\n }\n\n function addTernaryStyle(ternary: Ternary, a: any, b: any) {\n const cCN = a.map((x) => x.identifier).join(' ')\n const aCN = b.map((x) => x.identifier).join(' ')\n if (a.length && b.length) {\n finalClassNames.push(\n t.conditionalExpression(ternary.test, t.stringLiteral(cCN), t.stringLiteral(aCN))\n )\n } else {\n finalClassNames.push(\n t.conditionalExpression(\n ternary.test,\n t.stringLiteral(' ' + cCN),\n t.stringLiteral(' ' + aCN)\n )\n )\n }\n }\n\n if (shouldPrintDebug) {\n // eslint-disable-next-line no-console\n console.log(\n ' finalClassNames\\n',\n logLines(finalClassNames.map((x) => x['value']).join(' '))\n )\n }\n\n node.attributes = finalAttrs\n\n if (finalClassNames.length) {\n const extraClassNames = (() => {\n let value = ''\n if (!isFlattened) {\n return value\n }\n\n // helper to see how many get flattened\n if (process.env.TAMAGUI_DEBUG_OPTIMIZATIONS) {\n value += `is_tamagui_flattened`\n }\n\n // add is_Component className\n if (staticConfig.componentName) {\n value += ` is_${staticConfig.componentName}`\n }\n\n if (staticConfig.isText) {\n let family = completeProps.fontFamily\n if (family[0] === '$') {\n family = family.slice(1)\n }\n value += ` font_${family}`\n }\n\n return value\n })()\n\n // inserts the _cn variable and uses it for className\n let names = buildClassName(finalClassNames)\n\n if (names) {\n if (t.isStringLiteral(names)) {\n names.value = concatClassName(names.value)\n names.value = `${extraClassNames} ${names.value}`\n } else {\n names = t.binaryExpression('+', t.stringLiteral(extraClassNames), names)\n }\n }\n\n const nameExpr = names ? hoistClassNames(jsxPath, existingHoists, names) : null\n let expr = nameExpr\n\n // if has some spreads, use concat helper\n if (nameExpr && !t.isIdentifier(nameExpr)) {\n if (!didFlattenThisTag) {\n // not flat\n } else {\n ensureImportingConcat(programPath)\n const simpleSpreads = attrs.filter(\n (x) => t.isJSXSpreadAttribute(x.value) && isSimpleSpread(x.value)\n )\n expr = t.callExpression(t.identifier(CONCAT_CLASSNAME_IMPORT), [\n expr,\n ...simpleSpreads.map((val) => val.value['argument']),\n ])\n }\n }\n\n node.attributes.push(\n t.jsxAttribute(t.jsxIdentifier('className'), t.jsxExpressionContainer(expr))\n )\n }\n\n const comment = util.format('/* %s:%s (%s) */', filePath, lineNumbers, originalNodeName)\n\n for (const { identifier, rules } of finalStyles) {\n const className = `.${identifier}`\n if (cssMap.has(className)) {\n if (comment) {\n const val = cssMap.get(className)!\n val.commentTexts.push(comment)\n cssMap.set(className, val)\n }\n } else if (rules.length) {\n if (rules.length > 1) {\n // eslint-disable-next-line no-console\n console.log(' rules error', { rules })\n throw new Error(`Shouldn't have more than one rule`)\n }\n cssMap.set(className, {\n css: rules[0],\n commentTexts: [comment],\n })\n }\n }\n },\n })\n\n if (!res || (!res.modified && !res.optimized && !res.flattened && !res.styled)) {\n if (shouldPrintDebug) {\n // eslint-disable-next-line no-console\n console.log('no res or none modified', res)\n }\n return null\n }\n\n const styles = Array.from(cssMap.values())\n .map((x) => x.css)\n .join('\\n')\n .trim()\n\n const result = generate(\n ast,\n {\n concise: false,\n filename: sourcePath,\n // this makes the debug output terrible, and i think sourcemap works already\n retainLines: false,\n sourceFileName: sourcePath,\n sourceMaps: true,\n },\n source\n )\n\n if (shouldPrintDebug) {\n // eslint-disable-next-line no-console\n console.log(\n '\\n -------- output code ------- \\n\\n',\n result.code\n .split('\\n')\n .filter((x) => !x.startsWith('//'))\n .join('\\n')\n )\n // eslint-disable-next-line no-console\n console.log('\\n -------- output style -------- \\n\\n', styles)\n }\n\n if (shouldLogTiming) {\n const memUsed = mem\n ? Math.round(((process.memoryUsage().heapUsed - mem.heapUsed) / 1024 / 1204) * 10) / 10\n : 0\n const path = basename(sourcePath)\n .replace(/\\.[jt]sx?$/, '')\n .slice(0, 22)\n .trim()\n .padStart(24)\n\n const numStyled = `${res.styled}`.padStart(3)\n const numOptimized = `${res.optimized}`.padStart(3)\n const numFound = `${res.found}`.padStart(3)\n const numFlattened = `${res.flattened}`.padStart(3)\n const memory = process.env.DEBUG && memUsed > 10 ? ` ${memUsed}MB` : ''\n const timing = Date.now() - start\n const timingStr = `${timing}ms`.padStart(6)\n const pre = getPrefixLogs(options)\n const memStr = memory ? `(${memory})` : ''\n // eslint-disable-next-line no-console\n console.log(\n `${pre} ${path} ${numFound} \u00B7 ${numOptimized} \u00B7 ${numFlattened} \u00B7 ${numStyled} ${timingStr} ${memStr}`\n )\n }\n\n return {\n ast,\n styles,\n js: result.code,\n map: result.map,\n }\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAAsB;AACtB,kBAAyB;AACzB,WAAsB;AAEtB,uBAAqB;AACrB,QAAmB;AACnB,uBAAgC;AAChC,qBAAgC;AAChC,uBAAsB;
|
|
4
|
+
"sourcesContent": ["import * as path from 'path'\nimport { basename } from 'path'\nimport * as util from 'util'\n\nimport generate from '@babel/generator'\nimport * as t from '@babel/types'\nimport { getStylesAtomic } from '@tamagui/core-node'\nimport { concatClassName } from '@tamagui/helpers'\nimport invariant from 'invariant'\nimport type { ViewStyle } from 'react-native'\n\nimport type { ClassNameObject, StyleObject, TamaguiOptions, Ternary } from '../types.js'\nimport { babelParse } from './babelParse.js'\nimport { buildClassName } from './buildClassName.js'\nimport { Extractor } from './createExtractor.js'\nimport { ensureImportingConcat } from './ensureImportingConcat.js'\nimport { isSimpleSpread } from './extractHelpers.js'\nimport { extractMediaStyle } from './extractMediaStyle.js'\nimport { getPrefixLogs } from './getPrefixLogs.js'\nimport { hoistClassNames } from './hoistClassNames.js'\nimport { logLines } from './logLines.js'\nimport { timer } from './timer.js'\n\nconst mergeStyleGroups = {\n shadowOpacity: true,\n shadowRadius: true,\n shadowColor: true,\n shadowOffset: true,\n}\n\nexport type ExtractedResponse = {\n js: string | Buffer\n styles: string\n stylesPath?: string\n ast: t.File\n map: any // RawSourceMap from 'source-map'\n}\n\nexport async function extractToClassNames({\n extractor,\n source,\n sourcePath,\n options,\n shouldPrintDebug,\n}: {\n extractor: Extractor\n source: string | Buffer\n sourcePath: string\n options: TamaguiOptions\n shouldPrintDebug: boolean | 'verbose'\n}): Promise<ExtractedResponse | null> {\n const tm = timer()\n\n if (typeof source !== 'string') {\n throw new Error('`source` must be a string of javascript')\n }\n invariant(\n typeof sourcePath === 'string' && path.isAbsolute(sourcePath),\n '`sourcePath` must be an absolute path to a .js file'\n )\n\n // dont include loading in timing of parsing (one time cost)\n await extractor.loadTamagui(options)\n\n const shouldLogTiming = options.logTimings ?? true\n const start = Date.now()\n const mem = shouldLogTiming ? process.memoryUsage() : null\n\n // Using a map for (officially supported) guaranteed insertion order\n let ast: t.File\n\n try {\n ast = babelParse(source)\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('babel parse error:', sourcePath)\n throw err\n }\n\n tm.mark(`babel-parse`, shouldPrintDebug === 'verbose')\n\n const cssMap = new Map<string, { css: string; commentTexts: string[] }>()\n const existingHoists: { [key: string]: t.Identifier } = {}\n\n let hasFlattened = false\n\n const res = await extractor.parse(ast, {\n shouldPrintDebug,\n ...options,\n sourcePath,\n target: 'html',\n extractStyledDefinitions: true,\n onStyleRule(identifier, rules) {\n cssMap.set(`.${identifier}`, { css: rules.join(';'), commentTexts: [] })\n },\n getFlattenedNode: ({ tag }) => {\n hasFlattened = true\n return tag\n },\n onExtractTag: ({\n attrs,\n node,\n attemptEval,\n jsxPath,\n originalNodeName,\n filePath,\n lineNumbers,\n programPath,\n isFlattened,\n completeProps,\n staticConfig,\n }) => {\n // bail out of views that don't accept className (falls back to runtime + style={})\n if (staticConfig.acceptsClassName === false) {\n if (shouldPrintDebug) {\n // eslint-disable-next-line no-console\n console.log(`bail, acceptsClassName is false`)\n }\n return\n }\n\n // reset hasFlattened\n const didFlattenThisTag = hasFlattened\n hasFlattened = false\n\n let finalClassNames: ClassNameObject[] = []\n const finalAttrs: (t.JSXAttribute | t.JSXSpreadAttribute)[] = []\n let finalStyles: StyleObject[] = []\n\n let viewStyles = {}\n for (const attr of attrs) {\n if (attr.type === 'style') {\n viewStyles = {\n ...viewStyles,\n ...attr.value,\n }\n }\n }\n\n const ensureNeededPrevStyle = (style: ViewStyle) => {\n // ensure all group keys are merged\n const keys = Object.keys(style)\n if (!keys.some((key) => mergeStyleGroups[key])) {\n return style\n }\n for (const k in mergeStyleGroups) {\n if (k in viewStyles) {\n style[k] = style[k] ?? viewStyles[k]\n }\n }\n return style\n }\n\n const addStyles = (style: ViewStyle | null): StyleObject[] => {\n if (!style) return []\n const styleWithPrev = ensureNeededPrevStyle(style)\n const res = getStylesAtomic(styleWithPrev)\n if (res.length) {\n finalStyles = [...finalStyles, ...res]\n }\n return res\n }\n\n // 1 to start above any :hover styles\n let lastMediaImportance = 1\n for (const attr of attrs) {\n switch (attr.type) {\n case 'style': {\n if (!isFlattened) {\n const styles = getStylesAtomic(attr.value)\n\n finalStyles = [...finalStyles, ...styles]\n\n for (const style of styles) {\n // leave them as attributes\n const prop = style.pseudo ? `${style.property}-${style.pseudo}` : style.property\n finalAttrs.push(\n t.jsxAttribute(t.jsxIdentifier(prop), t.stringLiteral(style.identifier))\n )\n }\n } else {\n const styles = addStyles(attr.value)\n const newClassNames = concatClassName(styles.map((x) => x.identifier).join(' '))\n const existing = finalClassNames.find(\n (x) => x.type == 'StringLiteral'\n ) as t.StringLiteral | null\n\n if (existing) {\n existing.value = `${existing.value} ${newClassNames}`\n } else {\n finalClassNames = [...finalClassNames, t.stringLiteral(newClassNames)]\n }\n }\n\n break\n }\n case 'attr': {\n const val = attr.value\n if (t.isJSXSpreadAttribute(val)) {\n if (isSimpleSpread(val)) {\n finalClassNames.push(\n t.logicalExpression(\n '&&',\n val.argument,\n t.memberExpression(val.argument, t.identifier('className'))\n )\n )\n }\n } else if (val.name.name === 'className') {\n const value = val.value\n if (value) {\n try {\n const evaluatedValue = attemptEval(value)\n finalClassNames.push(t.stringLiteral(evaluatedValue))\n } catch (e) {\n finalClassNames.push(value['expression'])\n }\n }\n continue\n }\n finalAttrs.push(val)\n break\n }\n case 'ternary': {\n const mediaExtraction = extractMediaStyle(\n { ...options, sourcePath },\n attr.value,\n jsxPath,\n extractor.getTamagui()!,\n sourcePath,\n lastMediaImportance,\n shouldPrintDebug\n )\n if (shouldPrintDebug) {\n if (mediaExtraction) {\n // eslint-disable-next-line no-console\n console.log(\n 'ternary (mediaStyles)',\n mediaExtraction.ternaryWithoutMedia?.inlineMediaQuery ?? '',\n mediaExtraction.mediaStyles.map((x) => x.identifier).join('.')\n )\n }\n }\n if (!mediaExtraction) {\n addTernaryStyle(\n attr.value,\n addStyles(attr.value.consequent),\n addStyles(attr.value.alternate)\n )\n continue\n }\n lastMediaImportance++\n if (mediaExtraction.mediaStyles) {\n finalStyles = [...finalStyles, ...mediaExtraction.mediaStyles]\n }\n if (mediaExtraction.ternaryWithoutMedia) {\n addTernaryStyle(mediaExtraction.ternaryWithoutMedia, mediaExtraction.mediaStyles, [])\n } else {\n finalClassNames = [\n ...finalClassNames,\n ...mediaExtraction.mediaStyles.map((x) => t.stringLiteral(x.identifier)),\n ]\n }\n break\n }\n }\n }\n\n function addTernaryStyle(ternary: Ternary, a: any, b: any) {\n const cCN = a.map((x) => x.identifier).join(' ')\n const aCN = b.map((x) => x.identifier).join(' ')\n if (a.length && b.length) {\n finalClassNames.push(\n t.conditionalExpression(ternary.test, t.stringLiteral(cCN), t.stringLiteral(aCN))\n )\n } else {\n finalClassNames.push(\n t.conditionalExpression(\n ternary.test,\n t.stringLiteral(' ' + cCN),\n t.stringLiteral(' ' + aCN)\n )\n )\n }\n }\n\n if (shouldPrintDebug) {\n // eslint-disable-next-line no-console\n console.log(\n ' finalClassNames\\n',\n logLines(finalClassNames.map((x) => x['value']).join(' '))\n )\n }\n\n node.attributes = finalAttrs\n\n if (finalClassNames.length) {\n const extraClassNames = (() => {\n let value = ''\n if (!isFlattened) {\n return value\n }\n\n // helper to see how many get flattened\n if (process.env.TAMAGUI_DEBUG_OPTIMIZATIONS) {\n value += `is_tamagui_flattened`\n }\n\n // add is_Component className\n if (staticConfig.componentName) {\n value += ` is_${staticConfig.componentName}`\n }\n\n if (staticConfig.isText) {\n let family = completeProps.fontFamily\n if (family[0] === '$') {\n family = family.slice(1)\n }\n value += ` font_${family}`\n }\n\n return value\n })()\n\n // inserts the _cn variable and uses it for className\n const names = buildClassName(finalClassNames, extraClassNames)\n\n const nameExpr = names ? hoistClassNames(jsxPath, existingHoists, names) : null\n let expr = nameExpr\n\n // if has some spreads, use concat helper\n if (nameExpr && !t.isIdentifier(nameExpr)) {\n if (!didFlattenThisTag) {\n // not flat\n } else {\n ensureImportingConcat(programPath)\n const simpleSpreads = attrs.filter(\n (x) => t.isJSXSpreadAttribute(x.value) && isSimpleSpread(x.value)\n )\n expr = t.callExpression(t.identifier('concatClassName'), [\n expr,\n ...simpleSpreads.map((val) => val.value['argument']),\n ])\n }\n }\n\n node.attributes.push(\n t.jsxAttribute(t.jsxIdentifier('className'), t.jsxExpressionContainer(expr))\n )\n }\n\n const comment = util.format('/* %s:%s (%s) */', filePath, lineNumbers, originalNodeName)\n\n for (const { identifier, rules } of finalStyles) {\n const className = `.${identifier}`\n if (cssMap.has(className)) {\n if (comment) {\n const val = cssMap.get(className)!\n val.commentTexts.push(comment)\n cssMap.set(className, val)\n }\n } else if (rules.length) {\n cssMap.set(className, {\n css: rules.join('\\n'),\n commentTexts: [comment],\n })\n }\n }\n },\n })\n\n if (!res || (!res.modified && !res.optimized && !res.flattened && !res.styled)) {\n if (shouldPrintDebug) {\n // eslint-disable-next-line no-console\n console.log('no res or none modified', res)\n }\n return null\n }\n\n const styles = Array.from(cssMap.values())\n .map((x) => x.css)\n .join('\\n')\n .trim()\n\n const result = generate(\n ast,\n {\n concise: false,\n filename: sourcePath,\n // this makes the debug output terrible, and i think sourcemap works already\n retainLines: false,\n sourceFileName: sourcePath,\n sourceMaps: true,\n },\n source\n )\n\n if (shouldPrintDebug) {\n // eslint-disable-next-line no-console\n console.log(\n '\\n -------- output code ------- \\n\\n',\n result.code\n .split('\\n')\n .filter((x) => !x.startsWith('//'))\n .join('\\n')\n )\n // eslint-disable-next-line no-console\n console.log('\\n -------- output style -------- \\n\\n', styles)\n }\n\n if (shouldLogTiming) {\n const memUsed = mem\n ? Math.round(((process.memoryUsage().heapUsed - mem.heapUsed) / 1024 / 1204) * 10) / 10\n : 0\n const path = basename(sourcePath)\n .replace(/\\.[jt]sx?$/, '')\n .slice(0, 22)\n .trim()\n .padStart(24)\n\n const numStyled = `${res.styled}`.padStart(3)\n const numOptimized = `${res.optimized}`.padStart(3)\n const numFound = `${res.found}`.padStart(3)\n const numFlattened = `${res.flattened}`.padStart(3)\n const memory = process.env.DEBUG && memUsed > 10 ? ` ${memUsed}MB` : ''\n const timing = Date.now() - start\n const timingStr = `${timing}ms`.padStart(6)\n const pre = getPrefixLogs(options)\n const memStr = memory ? `(${memory})` : ''\n // eslint-disable-next-line no-console\n console.log(\n `${pre} ${path} ${numFound} \u00B7 ${numOptimized} \u00B7 ${numFlattened} \u00B7 ${numStyled} ${timingStr} ${memStr}`\n )\n }\n\n return {\n ast,\n styles,\n js: result.code,\n map: result.map,\n }\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;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,12 @@ async function getStaticBindingsForScope(scope, whitelist = [], sourcePath, bind
|
|
|
130
130
|
}
|
|
131
131
|
}
|
|
132
132
|
} catch (err) {
|
|
133
|
-
if (
|
|
134
|
-
console.log(`Error in partial evaluation`, err.message, err.stack);
|
|
135
|
-
} else {
|
|
133
|
+
if (shouldPrintDebug) {
|
|
136
134
|
console.warn(
|
|
137
135
|
` | Skipping partial evaluation of constant file: ${moduleName} (DEBUG=tamagui for more)`
|
|
138
136
|
);
|
|
137
|
+
} else if ((_a = process.env.DEBUG) == null ? void 0 : _a.startsWith("tamagui")) {
|
|
138
|
+
console.log(`Error in partial evaluation`, err.message, err.stack);
|
|
139
139
|
}
|
|
140
140
|
}
|
|
141
141
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/extractor/getStaticBindingsForScope.ts"],
|
|
4
|
-
"sourcesContent": ["import { fork } from 'child_process'\nimport { dirname, extname, join, resolve } from 'path'\n\nimport { Binding, NodePath } from '@babel/traverse'\nimport * as t from '@babel/types'\n\nimport { evaluateAstNode } from './evaluateAstNode.js'\nimport { getSourceModule } from './getSourceModule.js'\n\nconst isLocalImport = (path: string) => path.startsWith('.') || path.startsWith('/')\n\nfunction resolveImportPath(sourcePath: string, path: string) {\n const sourceDir = dirname(sourcePath)\n if (isLocalImport(path)) {\n if (extname(path) === '') {\n path += '.js'\n }\n return resolve(sourceDir, path)\n }\n return path\n}\n\nconst cache = new Map()\nconst pending = new Map<string, Promise<any>>()\nsetInterval(() => {\n if (cache.size) {\n cache.clear()\n }\n}, 10)\n\nconst loadCmd = `${join(__dirname, 'loadFile.js')}`\n\nlet exited = false\nconst child = fork(loadCmd, [], {\n execArgv: ['-r', 'esbuild-register'],\n detached: true,\n stdio: 'ignore',\n})\n\nexport function cleanupBeforeExit() {\n if (exited) return\n child.removeAllListeners()\n child.unref()\n child.disconnect()\n child.kill()\n exited = true\n}\n\nprocess.once('SIGTERM', cleanupBeforeExit)\nprocess.once('SIGINT', cleanupBeforeExit)\nprocess.once('beforeExit', cleanupBeforeExit)\n\nfunction importModule(path: string) {\n if (pending.has(path)) {\n return pending.get(path)\n }\n const promise = new Promise((res, rej) => {\n if (cache.has(path)) {\n return cache.get(path)\n }\n const listener = (msg: any) => {\n if (!msg) return\n if (typeof msg !== 'string') return\n if (msg[0] === '-') {\n rej(new Error(msg.slice(1)))\n return\n }\n child.removeListener('message', listener)\n const val = JSON.parse(msg)\n cache.set(path, val)\n res(val)\n }\n child.once('message', listener)\n child.send(`${path.replace('.js', '')}`)\n })\n pending.set(path, promise)\n return promise\n}\n\nexport async function getStaticBindingsForScope(\n scope: NodePath<t.JSXElement>['scope'],\n whitelist: string[] = [],\n sourcePath: string,\n bindingCache: Record<string, string | null>,\n shouldPrintDebug: boolean | 'verbose'\n): Promise<Record<string, any>> {\n const bindings: Record<string, Binding> = scope.getAllBindings() as any\n const ret: Record<string, any> = {}\n\n if (\n shouldPrintDebug\n ) {\n // prettier-ignore\n // console.log(' ', Object.keys(bindings).length, 'variables in scope')\n // .map(x => bindings[x].identifier?.name).join(', ')\n }\n\n // on react native at least it doesnt find some bindings? not sure why\n // lets add in whitelisted imports if they exist\n const program = scope.getProgramParent().block as t.Program\n for (const node of program.body) {\n if (t.isImportDeclaration(node)) {\n const importPath = node.source.value\n if (!node.specifiers.length) continue\n if (!isLocalImport(importPath)) {\n continue\n }\n const moduleName = resolveImportPath(sourcePath, importPath)\n const isOnWhitelist = whitelist.some((test) => moduleName.endsWith(test))\n if (!isOnWhitelist) continue\n try {\n const src = await importModule(moduleName)\n if (!src) continue\n for (const specifier of node.specifiers) {\n if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported)) {\n if (typeof src[specifier.imported.name] !== 'undefined') {\n const val = src[specifier.local.name]\n ret[specifier.local.name] = val\n }\n }\n }\n } catch (err: any) {\n if (
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;A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BAAI,UAAU,MAAM,QAAQ;AAAA,YAC9B;AAAA,UACF;AAAA,QACF;AAAA,MACF,SAAS,KAAP;AACA,
|
|
4
|
+
"sourcesContent": ["import { fork } from 'child_process'\nimport { dirname, extname, join, resolve } from 'path'\n\nimport { Binding, NodePath } from '@babel/traverse'\nimport * as t from '@babel/types'\n\nimport { evaluateAstNode } from './evaluateAstNode.js'\nimport { getSourceModule } from './getSourceModule.js'\n\nconst isLocalImport = (path: string) => path.startsWith('.') || path.startsWith('/')\n\nfunction resolveImportPath(sourcePath: string, path: string) {\n const sourceDir = dirname(sourcePath)\n if (isLocalImport(path)) {\n if (extname(path) === '') {\n path += '.js'\n }\n return resolve(sourceDir, path)\n }\n return path\n}\n\nconst cache = new Map()\nconst pending = new Map<string, Promise<any>>()\nsetInterval(() => {\n if (cache.size) {\n cache.clear()\n }\n}, 10)\n\nconst loadCmd = `${join(__dirname, 'loadFile.js')}`\n\nlet exited = false\nconst child = fork(loadCmd, [], {\n execArgv: ['-r', 'esbuild-register'],\n detached: true,\n stdio: 'ignore',\n})\n\nexport function cleanupBeforeExit() {\n if (exited) return\n child.removeAllListeners()\n child.unref()\n child.disconnect()\n child.kill()\n exited = true\n}\n\nprocess.once('SIGTERM', cleanupBeforeExit)\nprocess.once('SIGINT', cleanupBeforeExit)\nprocess.once('beforeExit', cleanupBeforeExit)\n\nfunction importModule(path: string) {\n if (pending.has(path)) {\n return pending.get(path)\n }\n const promise = new Promise((res, rej) => {\n if (cache.has(path)) {\n return cache.get(path)\n }\n const listener = (msg: any) => {\n if (!msg) return\n if (typeof msg !== 'string') return\n if (msg[0] === '-') {\n rej(new Error(msg.slice(1)))\n return\n }\n child.removeListener('message', listener)\n const val = JSON.parse(msg)\n cache.set(path, val)\n res(val)\n }\n child.once('message', listener)\n child.send(`${path.replace('.js', '')}`)\n })\n pending.set(path, promise)\n return promise\n}\n\nexport async function getStaticBindingsForScope(\n scope: NodePath<t.JSXElement>['scope'],\n whitelist: string[] = [],\n sourcePath: string,\n bindingCache: Record<string, string | null>,\n shouldPrintDebug: boolean | 'verbose'\n): Promise<Record<string, any>> {\n const bindings: Record<string, Binding> = scope.getAllBindings() as any\n const ret: Record<string, any> = {}\n\n if (\n shouldPrintDebug\n ) {\n // prettier-ignore\n // console.log(' ', Object.keys(bindings).length, 'variables in scope')\n // .map(x => bindings[x].identifier?.name).join(', ')\n }\n\n // on react native at least it doesnt find some bindings? not sure why\n // lets add in whitelisted imports if they exist\n const program = scope.getProgramParent().block as t.Program\n for (const node of program.body) {\n if (t.isImportDeclaration(node)) {\n const importPath = node.source.value\n if (!node.specifiers.length) continue\n if (!isLocalImport(importPath)) {\n continue\n }\n const moduleName = resolveImportPath(sourcePath, importPath)\n const isOnWhitelist = whitelist.some((test) => moduleName.endsWith(test))\n if (!isOnWhitelist) continue\n try {\n const src = await importModule(moduleName)\n if (!src) continue\n for (const specifier of node.specifiers) {\n if (t.isImportSpecifier(specifier) && t.isIdentifier(specifier.imported)) {\n if (typeof src[specifier.imported.name] !== 'undefined') {\n const val = src[specifier.local.name]\n ret[specifier.local.name] = val\n }\n }\n }\n } catch (err: any) {\n if (shouldPrintDebug) {\n // eslint-disable-next-line no-console\n console.warn(\n ` | Skipping partial evaluation of constant file: ${moduleName} (DEBUG=tamagui for more)`\n )\n } else if (process.env.DEBUG?.startsWith('tamagui')) {\n // eslint-disable-next-line no-console\n console.log(`Error in partial evaluation`, err.message, err.stack)\n }\n }\n }\n }\n\n if (!bindingCache) {\n throw new Error('BindingCache is a required param')\n }\n\n for (const k in bindings) {\n const binding = bindings[k]\n\n // check to see if the item is a module\n const sourceModule = getSourceModule(k, binding)\n if (sourceModule) {\n if (!sourceModule.sourceModule) {\n continue\n }\n\n const moduleName = resolveImportPath(sourcePath, sourceModule.sourceModule)\n const isOnWhitelist = whitelist.some((test) => moduleName.endsWith(test))\n\n // TODO we could cache this at the file level.. and check if its been touched since\n\n if (isOnWhitelist) {\n const src = importModule(moduleName)\n if (!src) {\n // eslint-disable-next-line no-console\n console.log(\n ` | \u26A0\uFE0F Missing file ${moduleName} via ${sourcePath} import ${sourceModule.sourceModule}?`\n )\n return {}\n }\n if (sourceModule.destructured) {\n if (sourceModule.imported) {\n ret[k] = src[sourceModule.imported]\n }\n } else {\n ret[k] = src\n }\n }\n continue\n }\n\n const { parent } = binding.path\n\n if (!t.isVariableDeclaration(parent) || parent.kind !== 'const') {\n continue\n }\n\n // pick out the right variable declarator\n const dec = parent.declarations.find((d) => t.isIdentifier(d.id) && d.id.name === k)\n\n // if init is not set, there's nothing to evaluate\n // TODO: handle spread syntax\n if (!dec || !dec.init) {\n continue\n }\n\n // missing start/end will break caching\n if (typeof dec.id.start !== 'number' || typeof dec.id.end !== 'number') {\n // eslint-disable-next-line no-console\n console.error('dec.id.start/end is not a number')\n continue\n }\n\n if (!t.isIdentifier(dec.id)) {\n // eslint-disable-next-line no-console\n console.error('dec is not an identifier')\n continue\n }\n\n const cacheKey = `${dec.id.name}_${dec.id.start}-${dec.id.end}`\n\n // retrieve value from cache\n if (bindingCache.hasOwnProperty(cacheKey)) {\n ret[k] = bindingCache[cacheKey]\n continue\n }\n // retrieve value from cache\n if (bindingCache.hasOwnProperty(cacheKey)) {\n ret[k] = bindingCache[cacheKey]\n continue\n }\n\n // evaluate\n try {\n ret[k] = evaluateAstNode(dec.init, undefined, shouldPrintDebug)\n bindingCache[cacheKey] = ret[k]\n continue\n } catch {\n // skip\n }\n }\n\n return ret\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAAqB;AACrB,kBAAgD;AAGhD,QAAmB;AAEnB,6BAAgC;AAChC,6BAAgC;AAEhC,MAAM,gBAAgB,CAAC,SAAiB,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,GAAG;AAEnF,SAAS,kBAAkB,YAAoB,MAAc;AAC3D,QAAM,gBAAY,qBAAQ,UAAU;AACpC,MAAI,cAAc,IAA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GAAG,QAAQ,IAAI,GAAG,SAAS,IAAI,GAAG;AAG1D,QAAI,aAAa,eAAe,QAAQ,GAAG;AACzC,UAAI,KAAK,aAAa;AACtB;AAAA,IACF;AAEA,QAAI,aAAa,eAAe,QAAQ,GAAG;AACzC,UAAI,KAAK,aAAa;AACtB;AAAA,IACF;AAGA,QAAI;AACF,UAAI,SAAK,wCAAgB,IAAI,MAAM,QAAW,gBAAgB;AAC9D,mBAAa,YAAY,IAAI;AAC7B;AAAA,IACF,QAAE;AAAA,IAEF;AAAA,EACF;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -63,7 +63,7 @@ async function loadTamagui(props) {
|
|
|
63
63
|
);
|
|
64
64
|
const external = ["@tamagui/core", "@tamagui/core-node", "react", "react-dom"];
|
|
65
65
|
const configEntry = props.config ? (0, import_path.join)(process.cwd(), props.config) : "";
|
|
66
|
-
if ((_a = process.env.DEBUG) == null ? void 0 : _a.startsWith("tamagui")) {
|
|
66
|
+
if (process.env.NODE_ENV === "development" && ((_a = process.env.DEBUG) == null ? void 0 : _a.startsWith("tamagui"))) {
|
|
67
67
|
console.log(`Building config entry`, configEntry);
|
|
68
68
|
}
|
|
69
69
|
try {
|
|
@@ -96,9 +96,6 @@ Tamagui built config and components:`
|
|
|
96
96
|
});
|
|
97
97
|
})
|
|
98
98
|
]);
|
|
99
|
-
if ((_b = process.env.DEBUG) == null ? void 0 : _b.startsWith("tamagui")) {
|
|
100
|
-
console.log(`Built configs`);
|
|
101
|
-
}
|
|
102
99
|
const coreNode = require("@tamagui/core-node");
|
|
103
100
|
(0, import_require.registerRequire)(props.bubbleErrors);
|
|
104
101
|
const config = require(configOutPath).default;
|
|
@@ -110,6 +107,9 @@ Tamagui built config and components:`
|
|
|
110
107
|
}),
|
|
111
108
|
...includesCore && gatherTamaguiComponentInfo([coreNode])
|
|
112
109
|
};
|
|
110
|
+
if (process.env.NODE_ENV === "development" && ((_b = process.env.DEBUG) == null ? void 0 : _b.startsWith("tamagui"))) {
|
|
111
|
+
console.log("Loaded components", components);
|
|
112
|
+
}
|
|
113
113
|
cache[key] = {
|
|
114
114
|
components,
|
|
115
115
|
nameToPaths: {},
|
|
@@ -212,7 +212,9 @@ function loadTamaguiSync(props) {
|
|
|
212
212
|
tamaguiConfig = exp["default"] || exp;
|
|
213
213
|
if (!tamaguiConfig || !tamaguiConfig.parsed) {
|
|
214
214
|
const confPath = require.resolve(configPath);
|
|
215
|
-
throw new Error(`Can't find valid config in ${confPath}
|
|
215
|
+
throw new Error(`Can't find valid config in ${confPath}:
|
|
216
|
+
|
|
217
|
+
Be sure you "export default" the config.`);
|
|
216
218
|
}
|
|
217
219
|
}
|
|
218
220
|
const components = loadComponents(props);
|