You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

547 lines
29 KiB

  1. "use strict";
  2. function _interopDefault(ex) {
  3. return ex && "object" == typeof ex && "default" in ex ? ex.default : ex;
  4. }
  5. Object.defineProperty(exports, "__esModule", {
  6. value: !0
  7. });
  8. var nodePath = _interopDefault(require("path")), sourceMap = require("source-map"), convert = _interopDefault(require("convert-source-map")), findRoot = _interopDefault(require("find-root")), memoize = _interopDefault(require("@emotion/memoize")), hashString = _interopDefault(require("@emotion/hash")), escapeRegexp = _interopDefault(require("escape-string-regexp")), serialize = require("@emotion/serialize"), helperModuleImports = require("@babel/helper-module-imports"), babelPluginMacros = require("babel-plugin-macros"), multilineCommentRegex = /\/\*[^!](.|[\r\n])*?\*\//g, lineCommentStart = /\/\//g, symbolRegex = /(\s*[;:{},]\s*)/g, countOccurences = function(str, substr) {
  9. return str.split(substr).length - 1;
  10. }, reduceSubstr = function(substrs, join, predicate) {
  11. var length = substrs.length, res = substrs[0];
  12. if (1 === length) return res;
  13. for (var i = 1; i < length && !predicate(res); i++) res += join + substrs[i];
  14. return res;
  15. }, stripLineComment = function(line) {
  16. return reduceSubstr(line.split(lineCommentStart), "//", function(str) {
  17. return !str.endsWith(":") && countOccurences(str, "'") % 2 == 0 && countOccurences(str, '"') % 2 == 0 && countOccurences(str, "(") === countOccurences(str, ")");
  18. });
  19. }, compressSymbols = function(code) {
  20. return code.split(symbolRegex).reduce(function(str, fragment, index) {
  21. return index % 2 == 0 ? str + fragment : countOccurences(str, "'") % 2 == 0 && countOccurences(str, '"') % 2 == 0 ? str + fragment.trim() : str + fragment;
  22. }, "");
  23. }, isLineComment = function(line) {
  24. return line.trim().startsWith("//");
  25. }, linebreakRegex = /[\r\n]\s*/g, spacesAndLinebreakRegex = /\s+|\n+/g;
  26. function multilineReplacer(match) {
  27. return match.indexOf("@") > -1 ? match.replace(spacesAndLinebreakRegex, " ").trim() : "\n";
  28. }
  29. var minify = function(code) {
  30. var newCode = code.replace(multilineCommentRegex, multilineReplacer).split(linebreakRegex).filter(function(line) {
  31. return line.length > 0 && !isLineComment(line);
  32. }).map(stripLineComment).join(" ");
  33. return compressSymbols(newCode);
  34. };
  35. function getExpressionsFromTemplateLiteral(node, t) {
  36. var raw = createRawStringFromTemplateLiteral(node);
  37. return replacePlaceholdersWithExpressions(minify(raw), node.expressions || [], t);
  38. }
  39. var interleave = function(strings, interpolations) {
  40. return interpolations.reduce(function(array, interp, i) {
  41. return array.concat([ interp ], strings[i + 1]);
  42. }, [ strings[0] ]);
  43. };
  44. function getDynamicMatches(str) {
  45. for (var match, re = /xxx(\d+)xxx/gm, matches = []; null !== (match = re.exec(str)); ) null !== match && matches.push({
  46. value: match[0],
  47. p1: parseInt(match[1], 10),
  48. index: match.index
  49. });
  50. return matches;
  51. }
  52. function replacePlaceholdersWithExpressions(str, expressions, t) {
  53. var matches = getDynamicMatches(str);
  54. if (0 === matches.length) return "" === str ? [] : [ t.stringLiteral(str) ];
  55. var strings = [], finalExpressions = [], cursor = 0;
  56. return matches.forEach(function(_ref, i) {
  57. var value = _ref.value, p1 = _ref.p1, index = _ref.index, preMatch = str.substring(cursor, index);
  58. cursor = cursor + preMatch.length + value.length, preMatch ? strings.push(t.stringLiteral(preMatch)) : 0 === i && strings.push(t.stringLiteral("")),
  59. finalExpressions.push(expressions[p1]), i === matches.length - 1 && strings.push(t.stringLiteral(str.substring(index + value.length)));
  60. }), interleave(strings, finalExpressions).filter(function(node) {
  61. return "" !== node.value;
  62. });
  63. }
  64. function createRawStringFromTemplateLiteral(quasi) {
  65. var strs = quasi.quasis.map(function(x) {
  66. return x.value.cooked;
  67. });
  68. return strs.reduce(function(arr, str, i) {
  69. return arr.push(str), i !== strs.length - 1 && arr.push("xxx" + i + "xxx"), arr;
  70. }, []).join("").trim();
  71. }
  72. var invalidClassNameCharacters = /[!"#$%&'()*+,.\/:;<=>?@[\]^`|}~{]/g, sanitizeLabelPart = function(labelPart) {
  73. return labelPart.trim().replace(invalidClassNameCharacters, "-");
  74. };
  75. function getLabel(identifierName, autoLabel, labelFormat, filename) {
  76. if (!identifierName || !autoLabel) return null;
  77. if (!labelFormat) return sanitizeLabelPart(identifierName);
  78. var parsedPath = nodePath.parse(filename), localDirname = nodePath.basename(parsedPath.dir), localFilename = parsedPath.name;
  79. return "index" === localFilename && (localFilename = localDirname), labelFormat.replace(/\[local\]/gi, sanitizeLabelPart(identifierName)).replace(/\[filename\]/gi, sanitizeLabelPart(localFilename)).replace(/\[dirname\]/gi, sanitizeLabelPart(localDirname));
  80. }
  81. function getLabelFromPath(path, state, t) {
  82. return getLabel(getIdentifierName(path, t), void 0 !== state.opts.autoLabel && state.opts.autoLabel, state.opts.labelFormat, state.file.opts.filename);
  83. }
  84. var pascalCaseRegex = /^[A-Z][A-Za-z]+/;
  85. function getDeclaratorName(path, t) {
  86. var parent = path.findParent(function(p) {
  87. return p.isVariableDeclarator() || p.isFunctionDeclaration() || p.isFunctionExpression() || p.isArrowFunctionExpression() || p.isObjectProperty();
  88. });
  89. if (!parent) return "";
  90. if (parent.isVariableDeclarator()) return t.isIdentifier(parent.node.id) ? parent.node.id.name : "";
  91. if (parent.isFunctionDeclaration()) {
  92. var _name = parent.node.id.name;
  93. return pascalCaseRegex.test(_name) ? _name : "";
  94. }
  95. if (parent.isObjectProperty() && !parent.node.computed) return parent.node.key.name;
  96. var variableDeclarator = path.findParent(function(p) {
  97. return p.isVariableDeclarator();
  98. });
  99. if (!variableDeclarator) return "";
  100. var name = variableDeclarator.node.id.name;
  101. return pascalCaseRegex.test(name) ? name : "";
  102. }
  103. function getIdentifierName(path, t) {
  104. var classOrClassPropertyParent;
  105. if (t.isObjectProperty(path.parentPath) && !1 === path.parentPath.node.computed && (t.isIdentifier(path.parentPath.node.key) || t.isStringLiteral(path.parentPath.node.key))) return path.parentPath.node.key.name || path.parentPath.node.key.value;
  106. if (path && (classOrClassPropertyParent = path.findParent(function(p) {
  107. return t.isClassProperty(p) || t.isClass(p);
  108. })), classOrClassPropertyParent) {
  109. if (t.isClassProperty(classOrClassPropertyParent) && !1 === classOrClassPropertyParent.node.computed && t.isIdentifier(classOrClassPropertyParent.node.key)) return classOrClassPropertyParent.node.key.name;
  110. if (t.isClass(classOrClassPropertyParent) && classOrClassPropertyParent.node.id) return t.isIdentifier(classOrClassPropertyParent.node.id) ? classOrClassPropertyParent.node.id.name : "";
  111. }
  112. var declaratorName = getDeclaratorName(path, t);
  113. return "_" === declaratorName.charAt(0) ? "" : declaratorName;
  114. }
  115. function getGeneratorOpts(file) {
  116. return file.opts.generatorOpts ? file.opts.generatorOpts : file.opts;
  117. }
  118. function makeSourceMapGenerator(file) {
  119. var generatorOpts = getGeneratorOpts(file), filename = generatorOpts.sourceFileName, generator = new sourceMap.SourceMapGenerator({
  120. file: filename,
  121. sourceRoot: generatorOpts.sourceRoot
  122. });
  123. return generator.setSourceContent(filename, file.code), generator;
  124. }
  125. function getSourceMap(offset, state) {
  126. var generator = makeSourceMapGenerator(state.file), generatorOpts = getGeneratorOpts(state.file);
  127. return generatorOpts.sourceFileName && "unknown" !== generatorOpts.sourceFileName ? (generator.addMapping({
  128. generated: {
  129. line: 1,
  130. column: 0
  131. },
  132. source: generatorOpts.sourceFileName,
  133. original: offset
  134. }), convert.fromObject(generator).toComment({
  135. multiline: !0
  136. })) : "";
  137. }
  138. var hashArray = function(arr) {
  139. return hashString(arr.join(""));
  140. }, unsafeRequire = require, getPackageRootPath = memoize(function(filename) {
  141. return findRoot(filename);
  142. }), separator = new RegExp(escapeRegexp(nodePath.sep), "g"), normalizePath = function(path) {
  143. return nodePath.normalize(path).replace(separator, "/");
  144. };
  145. function getTargetClassName(state, t) {
  146. void 0 === state.emotionTargetClassNameCount && (state.emotionTargetClassNameCount = 0);
  147. var filename = state.file.opts.filename && "unknown" !== state.file.opts.filename ? state.file.opts.filename : "", moduleName = "", rootPath = filename;
  148. try {
  149. rootPath = getPackageRootPath(filename), moduleName = unsafeRequire(rootPath + "/package.json").name;
  150. } catch (err) {}
  151. var finalPath = filename === rootPath ? "root" : filename.slice(rootPath.length), positionInFile = state.emotionTargetClassNameCount++, stuffToHash = [ moduleName ];
  152. return finalPath ? stuffToHash.push(normalizePath(finalPath)) : stuffToHash.push(state.file.code),
  153. "e" + hashArray(stuffToHash) + positionInFile;
  154. }
  155. function simplifyObject(node, t) {
  156. for (var finalString = "", i = 0; i < node.properties.length; i++) {
  157. var _ref, property = node.properties[i];
  158. if (!t.isObjectProperty(property) || property.computed || !t.isIdentifier(property.key) && !t.isStringLiteral(property.key) || !t.isStringLiteral(property.value) && !t.isNumericLiteral(property.value) && !t.isObjectExpression(property.value)) return node;
  159. var key = property.key.name || property.key.value;
  160. if ("styles" === key) return node;
  161. if (t.isObjectExpression(property.value)) {
  162. var simplifiedChild = simplifyObject(property.value, t);
  163. if (!t.isStringLiteral(simplifiedChild)) return node;
  164. finalString += key + "{" + simplifiedChild.value + "}";
  165. } else {
  166. var value = property.value.value;
  167. finalString += serialize.serializeStyles([ (_ref = {}, _ref[key] = value, _ref) ]).styles;
  168. }
  169. }
  170. return t.stringLiteral(finalString);
  171. }
  172. function getTypeScriptMakeTemplateObjectPath(path) {
  173. if (0 === path.node.arguments.length) return null;
  174. var firstArgPath = path.get("arguments")[0];
  175. return firstArgPath.isLogicalExpression() && firstArgPath.get("left").isIdentifier() && firstArgPath.get("right").isAssignmentExpression() && firstArgPath.get("right.right").isCallExpression() && firstArgPath.get("right.right.callee").isIdentifier() && firstArgPath.node.right.right.callee.name.includes("makeTemplateObject") && 2 === firstArgPath.node.right.right.arguments.length ? firstArgPath.get("right.right") : null;
  176. }
  177. function isTaggedTemplateTranspiledByBabel(path) {
  178. if (0 === path.node.arguments.length) return !1;
  179. var firstArgPath = path.get("arguments")[0];
  180. if (!firstArgPath.isCallExpression() || !firstArgPath.get("callee").isIdentifier()) return !1;
  181. var calleeName = firstArgPath.node.callee.name;
  182. if (!calleeName.includes("templateObject")) return !1;
  183. var bindingPath = path.scope.getBinding(calleeName).path;
  184. if (!bindingPath.isFunction()) return !1;
  185. var functionBody = bindingPath.get("body.body");
  186. if (!functionBody[0].isVariableDeclaration()) return !1;
  187. var declarationInit = functionBody[0].get("declarations")[0].get("init");
  188. if (!declarationInit.isCallExpression()) return !1;
  189. var declarationInitArguments = declarationInit.get("arguments");
  190. return !(0 === declarationInitArguments.length || declarationInitArguments.length > 2 || declarationInitArguments.some(function(argPath) {
  191. return !argPath.isArrayExpression();
  192. }));
  193. }
  194. var appendStringToArguments = function(path, string, t) {
  195. if (string) {
  196. var args = path.node.arguments;
  197. if (t.isStringLiteral(args[args.length - 1])) args[args.length - 1].value += string; else {
  198. var makeTemplateObjectCallPath = getTypeScriptMakeTemplateObjectPath(path);
  199. makeTemplateObjectCallPath ? makeTemplateObjectCallPath.get("arguments").forEach(function(argPath) {
  200. var elements = argPath.get("elements"), lastElement = elements[elements.length - 1];
  201. lastElement.replaceWith(t.stringLiteral(lastElement.node.value + string));
  202. }) : isTaggedTemplateTranspiledByBabel(path) || args.push(t.stringLiteral(string));
  203. }
  204. }
  205. }, joinStringLiterals = function(expressions, t) {
  206. return expressions.reduce(function(finalExpressions, currentExpression, i) {
  207. return t.isStringLiteral(currentExpression) && t.isStringLiteral(finalExpressions[finalExpressions.length - 1]) ? finalExpressions[finalExpressions.length - 1].value += currentExpression.value : finalExpressions.push(currentExpression),
  208. finalExpressions;
  209. }, []);
  210. }, CSS_OBJECT_STRINGIFIED_ERROR = "You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop).", cloneNode = function(t, node) {
  211. return "function" == typeof t.cloneNode ? t.cloneNode(node) : t.cloneDeep(node);
  212. };
  213. function createSourceMapConditional(t, production, development) {
  214. return t.conditionalExpression(t.binaryExpression("===", t.memberExpression(t.memberExpression(t.identifier("process"), t.identifier("env")), t.identifier("NODE_ENV")), t.stringLiteral("production")), production, development);
  215. }
  216. var transformExpressionWithStyles = function(_ref) {
  217. var babel = _ref.babel, state = _ref.state, path = _ref.path, shouldLabel = _ref.shouldLabel, _ref$sourceMap = _ref.sourceMap, sourceMap = void 0 === _ref$sourceMap ? "" : _ref$sourceMap, t = babel.types;
  218. if (t.isTaggedTemplateExpression(path)) {
  219. var expressions = getExpressionsFromTemplateLiteral(path.node.quasi, t);
  220. state.emotionSourceMap && void 0 !== path.node.quasi.loc && (sourceMap = getSourceMap(path.node.quasi.loc.start, state)),
  221. path.replaceWith(t.callExpression(path.node.tag, expressions));
  222. }
  223. if (t.isCallExpression(path)) {
  224. var canAppendStrings = path.node.arguments.every(function(arg) {
  225. return "SpreadElement" !== arg.type;
  226. });
  227. if (canAppendStrings && shouldLabel) {
  228. var label = getLabelFromPath(path, state, t);
  229. label && appendStringToArguments(path, ";label:" + label + ";", t);
  230. }
  231. if (path.get("arguments").forEach(function(node) {
  232. t.isObjectExpression(node) && node.replaceWith(simplifyObject(node.node, t));
  233. }), path.node.arguments = joinStringLiterals(path.node.arguments, t), canAppendStrings && state.emotionSourceMap && !sourceMap && void 0 !== path.node.loc && (sourceMap = getSourceMap(path.node.loc.start, state)),
  234. 1 === path.node.arguments.length && t.isStringLiteral(path.node.arguments[0])) {
  235. var cssString = path.node.arguments[0].value, res = serialize.serializeStyles([ cssString ]), prodNode = t.objectExpression([ t.objectProperty(t.identifier("name"), t.stringLiteral(res.name)), t.objectProperty(t.identifier("styles"), t.stringLiteral(res.styles)) ]), node = prodNode;
  236. if (sourceMap) {
  237. if (!state.emotionStringifiedCssId) {
  238. var uid = state.file.scope.generateUidIdentifier("__EMOTION_STRINGIFIED_CSS_ERROR__");
  239. state.emotionStringifiedCssId = uid;
  240. var cssObjectToString = t.functionDeclaration(uid, [], t.blockStatement([ t.returnStatement(t.stringLiteral(CSS_OBJECT_STRINGIFIED_ERROR)) ]));
  241. cssObjectToString._compact = !0, state.file.path.unshiftContainer("body", [ cssObjectToString ]);
  242. }
  243. var devNode = t.objectExpression([ t.objectProperty(t.identifier("name"), t.stringLiteral(res.name)), t.objectProperty(t.identifier("styles"), t.stringLiteral(res.styles)), t.objectProperty(t.identifier("map"), t.stringLiteral(sourceMap)), t.objectProperty(t.identifier("toString"), cloneNode(t, state.emotionStringifiedCssId)) ]);
  244. node = createSourceMapConditional(t, prodNode, devNode);
  245. }
  246. return node;
  247. }
  248. if (sourceMap) {
  249. var lastIndex = path.node.arguments.length - 1, last = path.node.arguments[lastIndex], sourceMapConditional = createSourceMapConditional(t, t.stringLiteral(""), t.stringLiteral(sourceMap));
  250. if (t.isStringLiteral(last)) path.node.arguments[lastIndex] = t.binaryExpression("+", last, sourceMapConditional); else {
  251. var makeTemplateObjectCallPath = getTypeScriptMakeTemplateObjectPath(path);
  252. if (makeTemplateObjectCallPath) {
  253. var sourceMapId = state.file.scope.generateUidIdentifier("emotionSourceMap"), sourceMapDeclaration = t.variableDeclaration("var", [ t.variableDeclarator(sourceMapId, sourceMapConditional) ]);
  254. sourceMapDeclaration._compact = !0, state.file.path.unshiftContainer("body", [ sourceMapDeclaration ]),
  255. makeTemplateObjectCallPath.get("arguments").forEach(function(argPath) {
  256. var elements = argPath.get("elements"), lastElement = elements[elements.length - 1];
  257. lastElement.replaceWith(t.binaryExpression("+", lastElement.node, cloneNode(t, sourceMapId)));
  258. });
  259. } else isTaggedTemplateTranspiledByBabel(path) || path.node.arguments.push(sourceMapConditional);
  260. }
  261. }
  262. }
  263. }, getKnownProperties = function(t, node) {
  264. return new Set(node.properties.filter(function(n) {
  265. return t.isObjectProperty(n) && !n.computed;
  266. }).map(function(n) {
  267. return t.isIdentifier(n.key) ? n.key.name : n.key.value;
  268. }));
  269. }, getStyledOptions = function(t, path, state) {
  270. var args = path.node.arguments, optionsArgument = args.length >= 2 ? args[1] : null, properties = [], knownProperties = optionsArgument && t.isObjectExpression(optionsArgument) ? getKnownProperties(t, optionsArgument) : new Set();
  271. knownProperties.has("target") || properties.push(t.objectProperty(t.identifier("target"), t.stringLiteral(getTargetClassName(state))));
  272. var label = getLabelFromPath(path, state, t);
  273. if (label && !knownProperties.has("label") && properties.push(t.objectProperty(t.identifier("label"), t.stringLiteral(label))),
  274. optionsArgument) {
  275. if (!t.isObjectExpression(optionsArgument)) return t.callExpression(state.file.addHelper("extends"), [ t.objectExpression([]), t.objectExpression(properties), optionsArgument ]);
  276. properties.unshift.apply(properties, optionsArgument.properties);
  277. }
  278. return t.objectExpression(properties);
  279. }, createEmotionMacro = function(instancePath) {
  280. return babelPluginMacros.createMacro(function(_ref) {
  281. var references = _ref.references, state = _ref.state, babel = _ref.babel;
  282. _ref.isEmotionCall || (state.emotionSourceMap = !0);
  283. var t = babel.types;
  284. Object.keys(references).forEach(function(referenceKey) {
  285. var isPure = !0, runtimeNode = helperModuleImports.addNamed(state.file.path, referenceKey, instancePath);
  286. switch (referenceKey) {
  287. case "injectGlobal":
  288. isPure = !1;
  289. case "css":
  290. case "keyframes":
  291. references[referenceKey].reverse().forEach(function(reference) {
  292. var path = reference.parentPath;
  293. reference.replaceWith(t.cloneDeep(runtimeNode)), isPure && path.addComment("leading", "#__PURE__");
  294. var node = transformExpressionWithStyles({
  295. babel: babel,
  296. state: state,
  297. path: path,
  298. shouldLabel: !0
  299. });
  300. node && (path.node.arguments[0] = node);
  301. });
  302. break;
  303. default:
  304. references[referenceKey].reverse().forEach(function(reference) {
  305. reference.replaceWith(t.cloneDeep(runtimeNode));
  306. });
  307. }
  308. });
  309. });
  310. }, createStyledMacro = function(_ref) {
  311. var importPath = _ref.importPath, _ref$originalImportPa = _ref.originalImportPath, originalImportPath = void 0 === _ref$originalImportPa ? importPath : _ref$originalImportPa, isWeb = _ref.isWeb;
  312. return babelPluginMacros.createMacro(function(_ref2) {
  313. var references = _ref2.references, state = _ref2.state, babel = _ref2.babel;
  314. _ref2.isEmotionCall || (state.emotionSourceMap = !0);
  315. var t = babel.types;
  316. if (references.default && references.default.length) {
  317. var _styledIdentifier, originalImportPathStyledIdentifier, getStyledIdentifier = function() {
  318. return void 0 === _styledIdentifier && (_styledIdentifier = helperModuleImports.addDefault(state.file.path, importPath, {
  319. nameHint: "styled"
  320. })), t.cloneDeep(_styledIdentifier);
  321. }, getOriginalImportPathStyledIdentifier = function() {
  322. return void 0 === originalImportPathStyledIdentifier && (originalImportPathStyledIdentifier = helperModuleImports.addDefault(state.file.path, originalImportPath, {
  323. nameHint: "styled"
  324. })), t.cloneDeep(originalImportPathStyledIdentifier);
  325. };
  326. importPath === originalImportPath && (getOriginalImportPathStyledIdentifier = getStyledIdentifier),
  327. references.default.forEach(function(reference) {
  328. var isCall = !1;
  329. if (t.isMemberExpression(reference.parent) && !1 === reference.parent.computed ? (isCall = !0,
  330. reference.parent.property.name.charCodeAt(0) > 96 ? reference.parentPath.replaceWith(t.callExpression(getStyledIdentifier(), [ t.stringLiteral(reference.parent.property.name) ])) : reference.replaceWith(getStyledIdentifier())) : reference.parentPath && reference.parentPath.parentPath && t.isCallExpression(reference.parentPath) && reference.parent.callee === reference.node ? (isCall = !0,
  331. reference.replaceWith(getStyledIdentifier())) : reference.replaceWith(getOriginalImportPathStyledIdentifier()),
  332. reference.parentPath && reference.parentPath.parentPath) {
  333. var styledCallPath = reference.parentPath.parentPath, node = transformExpressionWithStyles({
  334. path: styledCallPath,
  335. state: state,
  336. babel: babel,
  337. shouldLabel: !1
  338. });
  339. node && isWeb && (styledCallPath.node.arguments[0] = node);
  340. }
  341. isCall && (reference.addComment("leading", "#__PURE__"), isWeb && (reference.parentPath.node.arguments[1] = getStyledOptions(t, reference.parentPath, state)));
  342. });
  343. }
  344. Object.keys(references).filter(function(x) {
  345. return "default" !== x;
  346. }).forEach(function(referenceKey) {
  347. var runtimeNode = helperModuleImports.addNamed(state.file.path, referenceKey, importPath);
  348. references[referenceKey].reverse().forEach(function(reference) {
  349. reference.replaceWith(t.cloneDeep(runtimeNode));
  350. });
  351. });
  352. });
  353. }, transformCssCallExpression = function(_ref) {
  354. var babel = _ref.babel, state = _ref.state, path = _ref.path, sourceMap = _ref.sourceMap, node = transformExpressionWithStyles({
  355. babel: babel,
  356. state: state,
  357. path: path,
  358. shouldLabel: !0,
  359. sourceMap: sourceMap
  360. });
  361. node ? (path.replaceWith(node), path.hoist()) : path.isCallExpression() && path.addComment("leading", "#__PURE__");
  362. }, cssMacro = babelPluginMacros.createMacro(function(_ref2) {
  363. var references = _ref2.references, state = _ref2.state, babel = _ref2.babel;
  364. _ref2.isEmotionCall || (state.emotionSourceMap = !0);
  365. var t = babel.types;
  366. references.default && references.default.length && references.default.reverse().forEach(function(reference) {
  367. state.cssIdentifier || (state.cssIdentifier = helperModuleImports.addDefault(reference, "@emotion/css", {
  368. nameHint: "css"
  369. })), reference.replaceWith(t.cloneDeep(state.cssIdentifier)), transformCssCallExpression({
  370. babel: babel,
  371. state: state,
  372. path: reference.parentPath
  373. });
  374. }), Object.keys(references).filter(function(x) {
  375. return "default" !== x;
  376. }).forEach(function(referenceKey) {
  377. var runtimeNode = helperModuleImports.addNamed(state.file.path, referenceKey, "@emotion/css", {
  378. nameHint: referenceKey
  379. });
  380. references[referenceKey].reverse().forEach(function(reference) {
  381. reference.replaceWith(t.cloneDeep(runtimeNode));
  382. });
  383. });
  384. }), webStyledMacro = createStyledMacro({
  385. importPath: "@emotion/styled-base",
  386. originalImportPath: "@emotion/styled",
  387. isWeb: !0
  388. }), nativeStyledMacro = createStyledMacro({
  389. importPath: "@emotion/native",
  390. originalImportPath: "@emotion/native",
  391. isWeb: !1
  392. }), primitivesStyledMacro = createStyledMacro({
  393. importPath: "@emotion/primitives",
  394. originalImportPath: "@emotion/primitives",
  395. isWeb: !1
  396. }), macros = {
  397. createEmotionMacro: createEmotionMacro,
  398. css: cssMacro,
  399. createStyledMacro: createStyledMacro
  400. }, emotionCoreMacroThatsNotARealMacro = function(_ref) {
  401. var references = _ref.references, state = _ref.state, babel = _ref.babel;
  402. Object.keys(references).forEach(function(refKey) {
  403. "css" === refKey && references[refKey].forEach(function(path) {
  404. transformCssCallExpression({
  405. babel: babel,
  406. state: state,
  407. path: path.parentPath
  408. });
  409. });
  410. });
  411. };
  412. function getAbsolutePath(instancePath, rootPath) {
  413. return "." === instancePath.charAt(0) && nodePath.resolve(rootPath, instancePath);
  414. }
  415. function getInstancePathToCompare(instancePath, rootPath) {
  416. var absolutePath = getAbsolutePath(instancePath, rootPath);
  417. return !1 === absolutePath ? instancePath : absolutePath;
  418. }
  419. function index(babel) {
  420. var t = babel.types;
  421. return {
  422. name: "emotion",
  423. inherits: require("babel-plugin-syntax-jsx"),
  424. visitor: {
  425. ImportDeclaration: function(path, state) {
  426. var dirname = path.hub.file.opts.filename && "unknown" !== path.hub.file.opts.filename ? nodePath.dirname(path.hub.file.opts.filename) : "";
  427. state.pluginMacros[path.node.source.value] || -1 === state.emotionInstancePaths.indexOf(getInstancePathToCompare(path.node.source.value, dirname)) || (state.pluginMacros[path.node.source.value] = createEmotionMacro(path.node.source.value));
  428. var pluginMacros = state.pluginMacros;
  429. if (void 0 !== pluginMacros[path.node.source.value] && !t.isImportNamespaceSpecifier(path.node.specifiers[0])) {
  430. var imports = path.node.specifiers.map(function(s) {
  431. return {
  432. localName: s.local.name,
  433. importedName: "ImportDefaultSpecifier" === s.type ? "default" : s.imported.name
  434. };
  435. }), shouldExit = !1, hasReferences = !1, referencePathsByImportName = imports.reduce(function(byName, _ref2) {
  436. var importedName = _ref2.importedName, localName = _ref2.localName, binding = path.scope.getBinding(localName);
  437. return binding ? (byName[importedName] = binding.referencePaths, hasReferences = hasReferences || Boolean(byName[importedName].length),
  438. byName) : (shouldExit = !0, byName);
  439. }, {});
  440. hasReferences && !shouldExit && (state.file.scope.path.traverse({
  441. Identifier: function() {}
  442. }), pluginMacros[path.node.source.value]({
  443. references: referencePathsByImportName,
  444. state: state,
  445. babel: babel,
  446. isBabelMacrosCall: !0,
  447. isEmotionCall: !0
  448. }), pluginMacros[path.node.source.value].keepImport || path.remove());
  449. }
  450. },
  451. Program: function(path, state) {
  452. if (state.emotionInstancePaths = (state.opts.instances || []).map(function(instancePath) {
  453. return getInstancePathToCompare(instancePath, process.cwd());
  454. }), state.pluginMacros = {
  455. "@emotion/css": cssMacro,
  456. "@emotion/styled": webStyledMacro,
  457. "@emotion/core": emotionCoreMacroThatsNotARealMacro,
  458. "@emotion/primitives": primitivesStyledMacro,
  459. "@emotion/native": nativeStyledMacro,
  460. emotion: createEmotionMacro("emotion")
  461. }, void 0 === state.opts.cssPropOptimization) {
  462. var _iterator = path.node.body, _isArray = Array.isArray(_iterator), _i = 0;
  463. for (_iterator = _isArray ? _iterator : _iterator[Symbol.iterator](); ;) {
  464. var _ref3;
  465. if (_isArray) {
  466. if (_i >= _iterator.length) break;
  467. _ref3 = _iterator[_i++];
  468. } else {
  469. if ((_i = _iterator.next()).done) break;
  470. _ref3 = _i.value;
  471. }
  472. var node = _ref3;
  473. if (t.isImportDeclaration(node) && "@emotion/core" === node.source.value && node.specifiers.some(function(x) {
  474. return t.isImportSpecifier(x) && "jsx" === x.imported.name;
  475. })) {
  476. state.transformCssProp = !0;
  477. break;
  478. }
  479. }
  480. } else state.transformCssProp = state.opts.cssPropOptimization;
  481. !1 === state.opts.sourceMap ? state.emotionSourceMap = !1 : state.emotionSourceMap = !0;
  482. },
  483. JSXAttribute: function(path, state) {
  484. if ("css" === path.node.name.name && state.transformCssProp && t.isJSXExpressionContainer(path.node.value) && (t.isObjectExpression(path.node.value.expression) || t.isArrayExpression(path.node.value.expression))) {
  485. var expressionPath = path.get("value.expression"), sourceMap = state.emotionSourceMap && void 0 !== path.node.loc ? getSourceMap(path.node.loc.start, state) : "";
  486. expressionPath.replaceWith(t.callExpression(t.identifier("___shouldNeverAppearCSS"), [ path.node.value.expression ])),
  487. transformCssCallExpression({
  488. babel: babel,
  489. state: state,
  490. path: expressionPath,
  491. sourceMap: sourceMap
  492. }), t.isCallExpression(expressionPath) && (state.cssIdentifier || (state.cssIdentifier = helperModuleImports.addDefault(path, "@emotion/css", {
  493. nameHint: "css"
  494. })), expressionPath.get("callee").replaceWith(t.cloneDeep(state.cssIdentifier)));
  495. }
  496. },
  497. CallExpression: {
  498. exit: function(path, state) {
  499. try {
  500. if (path.node.callee && path.node.callee.property && "withComponent" === path.node.callee.property.name) switch (path.node.arguments.length) {
  501. case 1:
  502. case 2:
  503. path.node.arguments[1] = getStyledOptions(t, path, state);
  504. }
  505. } catch (e) {
  506. throw path.buildCodeFrameError(e);
  507. }
  508. }
  509. }
  510. }
  511. };
  512. }
  513. emotionCoreMacroThatsNotARealMacro.keepImport = !0, exports.default = index, exports.macros = macros;