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.
 
 
 
 

1113 line
36 KiB

  1. import nodePath from 'path';
  2. import { SourceMapGenerator } from 'source-map';
  3. import convert from 'convert-source-map';
  4. import findRoot from 'find-root';
  5. import memoize from '@emotion/memoize';
  6. import hashString from '@emotion/hash';
  7. import escapeRegexp from 'escape-string-regexp';
  8. import { serializeStyles } from '@emotion/serialize';
  9. import { addNamed, addDefault } from '@babel/helper-module-imports';
  10. import { createMacro } from 'babel-plugin-macros';
  11. // babel-plugin-styled-components
  12. // https://github.com/styled-components/babel-plugin-styled-components/blob/8d44acc36f067d60d4e09f9c22ff89695bc332d2/src/minify/index.js
  13. var multilineCommentRegex = /\/\*[^!](.|[\r\n])*?\*\//g;
  14. var lineCommentStart = /\/\//g;
  15. var symbolRegex = /(\s*[;:{},]\s*)/g; // Counts occurences of substr inside str
  16. var countOccurences = function countOccurences(str, substr) {
  17. return str.split(substr).length - 1;
  18. }; // Joins substrings until predicate returns true
  19. var reduceSubstr = function reduceSubstr(substrs, join, predicate) {
  20. var length = substrs.length;
  21. var res = substrs[0];
  22. if (length === 1) {
  23. return res;
  24. }
  25. for (var i = 1; i < length; i++) {
  26. if (predicate(res)) {
  27. break;
  28. }
  29. res += join + substrs[i];
  30. }
  31. return res;
  32. }; // Joins at comment starts when it's inside a string or parantheses
  33. // effectively removing line comments
  34. var stripLineComment = function stripLineComment(line) {
  35. return reduceSubstr(line.split(lineCommentStart), '//', function (str) {
  36. return !str.endsWith(':') && // NOTE: This is another guard against urls, if they're not inside strings or parantheses.
  37. countOccurences(str, "'") % 2 === 0 && countOccurences(str, '"') % 2 === 0 && countOccurences(str, '(') === countOccurences(str, ')');
  38. });
  39. };
  40. var compressSymbols = function compressSymbols(code) {
  41. return code.split(symbolRegex).reduce(function (str, fragment, index) {
  42. // Even-indices are non-symbol fragments
  43. if (index % 2 === 0) {
  44. return str + fragment;
  45. } // Only manipulate symbols outside of strings
  46. if (countOccurences(str, "'") % 2 === 0 && countOccurences(str, '"') % 2 === 0) {
  47. return str + fragment.trim();
  48. }
  49. return str + fragment;
  50. }, '');
  51. }; // Detects lines that are exclusively line comments
  52. var isLineComment = function isLineComment(line) {
  53. return line.trim().startsWith('//');
  54. };
  55. var linebreakRegex = /[\r\n]\s*/g;
  56. var spacesAndLinebreakRegex = /\s+|\n+/g;
  57. function multilineReplacer(match) {
  58. // When we encounter a standard multi-line CSS comment and it contains a '@'
  59. // character, we keep the comment but optimize it into a single line. Some
  60. // Stylis plugins, such as the stylis-rtl via the cssjanus plugin, use this
  61. // special comment syntax to control behavior (such as: /* @noflip */).
  62. // We can do this with standard CSS comments because they will work with
  63. // compression, as opposed to non-standard single-line comments that will
  64. // break compressed CSS. If the comment doesn't contain '@', then we replace
  65. // it with a line break, which effectively removes it from the output.
  66. var keepComment = match.indexOf('@') > -1;
  67. if (keepComment) {
  68. return match.replace(spacesAndLinebreakRegex, ' ').trim();
  69. }
  70. return '\n';
  71. }
  72. var minify = function minify(code) {
  73. var newCode = code.replace(multilineCommentRegex, multilineReplacer) // If allowed, remove line breaks and extra space from multi-line comments so they appear on one line
  74. .split(linebreakRegex) // Split at newlines
  75. .filter(function (line) {
  76. return line.length > 0 && !isLineComment(line);
  77. }) // Removes lines containing only line comments
  78. .map(stripLineComment) // Remove line comments inside text
  79. .join(' '); // Rejoin all lines
  80. return compressSymbols(newCode);
  81. };
  82. function getExpressionsFromTemplateLiteral(node, t) {
  83. var raw = createRawStringFromTemplateLiteral(node);
  84. var minified = minify(raw);
  85. return replacePlaceholdersWithExpressions(minified, node.expressions || [], t);
  86. }
  87. var interleave = function interleave(strings, interpolations) {
  88. return interpolations.reduce(function (array, interp, i) {
  89. return array.concat([interp], strings[i + 1]);
  90. }, [strings[0]]);
  91. };
  92. function getDynamicMatches(str) {
  93. var re = /xxx(\d+)xxx/gm;
  94. var match;
  95. var matches = [];
  96. while ((match = re.exec(str)) !== null) {
  97. // so that flow doesn't complain
  98. if (match !== null) {
  99. matches.push({
  100. value: match[0],
  101. p1: parseInt(match[1], 10),
  102. index: match.index
  103. });
  104. }
  105. }
  106. return matches;
  107. }
  108. function replacePlaceholdersWithExpressions(str, expressions, t) {
  109. var matches = getDynamicMatches(str);
  110. if (matches.length === 0) {
  111. if (str === '') {
  112. return [];
  113. }
  114. return [t.stringLiteral(str)];
  115. }
  116. var strings = [];
  117. var finalExpressions = [];
  118. var cursor = 0;
  119. matches.forEach(function (_ref, i) {
  120. var value = _ref.value,
  121. p1 = _ref.p1,
  122. index = _ref.index;
  123. var preMatch = str.substring(cursor, index);
  124. cursor = cursor + preMatch.length + value.length;
  125. if (preMatch) {
  126. strings.push(t.stringLiteral(preMatch));
  127. } else if (i === 0) {
  128. strings.push(t.stringLiteral(''));
  129. }
  130. finalExpressions.push(expressions[p1]);
  131. if (i === matches.length - 1) {
  132. strings.push(t.stringLiteral(str.substring(index + value.length)));
  133. }
  134. });
  135. return interleave(strings, finalExpressions).filter(function (node) {
  136. return node.value !== '';
  137. });
  138. }
  139. function createRawStringFromTemplateLiteral(quasi) {
  140. var strs = quasi.quasis.map(function (x) {
  141. return x.value.cooked;
  142. });
  143. var src = strs.reduce(function (arr, str, i) {
  144. arr.push(str);
  145. if (i !== strs.length - 1) {
  146. arr.push("xxx" + i + "xxx");
  147. }
  148. return arr;
  149. }, []).join('').trim();
  150. return src;
  151. }
  152. var invalidClassNameCharacters = /[!"#$%&'()*+,./:;<=>?@[\]^`|}~{]/g;
  153. var sanitizeLabelPart = function sanitizeLabelPart(labelPart) {
  154. return labelPart.trim().replace(invalidClassNameCharacters, '-');
  155. };
  156. function getLabel(identifierName, autoLabel, labelFormat, filename) {
  157. if (!identifierName || !autoLabel) return null;
  158. if (!labelFormat) return sanitizeLabelPart(identifierName);
  159. var parsedPath = nodePath.parse(filename);
  160. var localDirname = nodePath.basename(parsedPath.dir);
  161. var localFilename = parsedPath.name;
  162. if (localFilename === 'index') {
  163. localFilename = localDirname;
  164. }
  165. return labelFormat.replace(/\[local\]/gi, sanitizeLabelPart(identifierName)).replace(/\[filename\]/gi, sanitizeLabelPart(localFilename)).replace(/\[dirname\]/gi, sanitizeLabelPart(localDirname));
  166. }
  167. function getLabelFromPath(path, state, t) {
  168. return getLabel(getIdentifierName(path, t), state.opts.autoLabel === undefined ? process.env.NODE_ENV !== 'production' : state.opts.autoLabel, state.opts.labelFormat, state.file.opts.filename);
  169. }
  170. var pascalCaseRegex = /^[A-Z][A-Za-z]+/;
  171. function getDeclaratorName(path, t) {
  172. // $FlowFixMe
  173. var parent = path.findParent(function (p) {
  174. return p.isVariableDeclarator() || p.isFunctionDeclaration() || p.isFunctionExpression() || p.isArrowFunctionExpression() || p.isObjectProperty();
  175. });
  176. if (!parent) {
  177. return '';
  178. } // we probably have a css call assigned to a variable
  179. // so we'll just return the variable name
  180. if (parent.isVariableDeclarator()) {
  181. if (t.isIdentifier(parent.node.id)) {
  182. return parent.node.id.name;
  183. }
  184. return '';
  185. } // we probably have an inline css prop usage
  186. if (parent.isFunctionDeclaration()) {
  187. var _name = parent.node.id.name;
  188. if (pascalCaseRegex.test(_name)) {
  189. return _name;
  190. }
  191. return '';
  192. } // we could also have an object property
  193. if (parent.isObjectProperty() && !parent.node.computed) {
  194. return parent.node.key.name;
  195. }
  196. var variableDeclarator = path.findParent(function (p) {
  197. return p.isVariableDeclarator();
  198. });
  199. if (!variableDeclarator) {
  200. return '';
  201. }
  202. var name = variableDeclarator.node.id.name;
  203. if (pascalCaseRegex.test(name)) {
  204. return name;
  205. }
  206. return '';
  207. }
  208. function getIdentifierName(path, t) {
  209. var classOrClassPropertyParent;
  210. if (t.isObjectProperty(path.parentPath) && path.parentPath.node.computed === false && (t.isIdentifier(path.parentPath.node.key) || t.isStringLiteral(path.parentPath.node.key))) {
  211. return path.parentPath.node.key.name || path.parentPath.node.key.value;
  212. }
  213. if (path) {
  214. // $FlowFixMe
  215. classOrClassPropertyParent = path.findParent(function (p) {
  216. return t.isClassProperty(p) || t.isClass(p);
  217. });
  218. }
  219. if (classOrClassPropertyParent) {
  220. if (t.isClassProperty(classOrClassPropertyParent) && classOrClassPropertyParent.node.computed === false && t.isIdentifier(classOrClassPropertyParent.node.key)) {
  221. return classOrClassPropertyParent.node.key.name;
  222. }
  223. if (t.isClass(classOrClassPropertyParent) && classOrClassPropertyParent.node.id) {
  224. return t.isIdentifier(classOrClassPropertyParent.node.id) ? classOrClassPropertyParent.node.id.name : '';
  225. }
  226. }
  227. var declaratorName = getDeclaratorName(path, t); // if the name starts with _ it was probably generated by babel so we should ignore it
  228. if (declaratorName.charAt(0) === '_') {
  229. return '';
  230. }
  231. return declaratorName;
  232. }
  233. function getGeneratorOpts(file) {
  234. return file.opts.generatorOpts ? file.opts.generatorOpts : file.opts;
  235. }
  236. function makeSourceMapGenerator(file) {
  237. var generatorOpts = getGeneratorOpts(file);
  238. var filename = generatorOpts.sourceFileName;
  239. var generator = new SourceMapGenerator({
  240. file: filename,
  241. sourceRoot: generatorOpts.sourceRoot
  242. });
  243. generator.setSourceContent(filename, file.code);
  244. return generator;
  245. }
  246. function getSourceMap(offset, state) {
  247. var generator = makeSourceMapGenerator(state.file);
  248. var generatorOpts = getGeneratorOpts(state.file);
  249. if (generatorOpts.sourceFileName && generatorOpts.sourceFileName !== 'unknown') {
  250. generator.addMapping({
  251. generated: {
  252. line: 1,
  253. column: 0
  254. },
  255. source: generatorOpts.sourceFileName,
  256. original: offset
  257. });
  258. return convert.fromObject(generator).toComment({
  259. multiline: true
  260. });
  261. }
  262. return '';
  263. }
  264. var hashArray = function hashArray(arr) {
  265. return hashString(arr.join(''));
  266. };
  267. var unsafeRequire = require;
  268. var getPackageRootPath = memoize(function (filename) {
  269. return findRoot(filename);
  270. });
  271. var separator = new RegExp(escapeRegexp(nodePath.sep), 'g');
  272. var normalizePath = function normalizePath(path) {
  273. return nodePath.normalize(path).replace(separator, '/');
  274. };
  275. function getTargetClassName(state, t) {
  276. if (state.emotionTargetClassNameCount === undefined) {
  277. state.emotionTargetClassNameCount = 0;
  278. }
  279. var hasFilepath = state.file.opts.filename && state.file.opts.filename !== 'unknown';
  280. var filename = hasFilepath ? state.file.opts.filename : ''; // normalize the file path to ignore folder structure
  281. // outside the current node project and arch-specific delimiters
  282. var moduleName = '';
  283. var rootPath = filename;
  284. try {
  285. rootPath = getPackageRootPath(filename);
  286. moduleName = unsafeRequire(rootPath + '/package.json').name;
  287. } catch (err) {}
  288. var finalPath = filename === rootPath ? 'root' : filename.slice(rootPath.length);
  289. var positionInFile = state.emotionTargetClassNameCount++;
  290. var stuffToHash = [moduleName];
  291. if (finalPath) {
  292. stuffToHash.push(normalizePath(finalPath));
  293. } else {
  294. stuffToHash.push(state.file.code);
  295. }
  296. var stableClassName = "e" + hashArray(stuffToHash) + positionInFile;
  297. return stableClassName;
  298. }
  299. // it's meant to simplify the most common cases so i don't want to make it especially complex
  300. // also, this will be unnecessary when prepack is ready
  301. function simplifyObject(node, t) {
  302. var finalString = '';
  303. for (var i = 0; i < node.properties.length; i++) {
  304. var _ref;
  305. var property = node.properties[i];
  306. 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)) {
  307. return node;
  308. }
  309. var key = property.key.name || property.key.value;
  310. if (key === 'styles') {
  311. return node;
  312. }
  313. if (t.isObjectExpression(property.value)) {
  314. var simplifiedChild = simplifyObject(property.value, t);
  315. if (!t.isStringLiteral(simplifiedChild)) {
  316. return node;
  317. }
  318. finalString += key + "{" + simplifiedChild.value + "}";
  319. continue;
  320. }
  321. var value = property.value.value;
  322. finalString += serializeStyles([(_ref = {}, _ref[key] = value, _ref)]).styles;
  323. }
  324. return t.stringLiteral(finalString);
  325. }
  326. // this only works correctly in modules, but we don't run on scripts anyway, so it's fine
  327. // the difference is that in modules template objects are being cached per call site
  328. function getTypeScriptMakeTemplateObjectPath(path) {
  329. if (path.node.arguments.length === 0) {
  330. return null;
  331. }
  332. var firstArgPath = path.get('arguments')[0];
  333. if (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') && firstArgPath.node.right.right.arguments.length === 2) {
  334. return firstArgPath.get('right.right');
  335. }
  336. return null;
  337. } // this is only used to prevent appending strings/expressions to arguments incorectly
  338. // we could push them to found array expressions, as we do it for TS-transpile output ¯\_(ツ)_/¯
  339. // it seems overly complicated though - mainly because we'd also have to check against existing stuff of a particular type (source maps & labels)
  340. // considering Babel double-transpilation as a valid use case seems rather far-fetched
  341. function isTaggedTemplateTranspiledByBabel(path) {
  342. if (path.node.arguments.length === 0) {
  343. return false;
  344. }
  345. var firstArgPath = path.get('arguments')[0];
  346. if (!firstArgPath.isCallExpression() || !firstArgPath.get('callee').isIdentifier()) {
  347. return false;
  348. }
  349. var calleeName = firstArgPath.node.callee.name;
  350. if (!calleeName.includes('templateObject')) {
  351. return false;
  352. }
  353. var bindingPath = path.scope.getBinding(calleeName).path;
  354. if (!bindingPath.isFunction()) {
  355. return false;
  356. }
  357. var functionBody = bindingPath.get('body.body');
  358. if (!functionBody[0].isVariableDeclaration()) {
  359. return false;
  360. }
  361. var declarationInit = functionBody[0].get('declarations')[0].get('init');
  362. if (!declarationInit.isCallExpression()) {
  363. return false;
  364. }
  365. var declarationInitArguments = declarationInit.get('arguments');
  366. if (declarationInitArguments.length === 0 || declarationInitArguments.length > 2 || declarationInitArguments.some(function (argPath) {
  367. return !argPath.isArrayExpression();
  368. })) {
  369. return false;
  370. }
  371. return true;
  372. }
  373. var appendStringToArguments = function appendStringToArguments(path, string, t) {
  374. if (!string) {
  375. return;
  376. }
  377. var args = path.node.arguments;
  378. if (t.isStringLiteral(args[args.length - 1])) {
  379. args[args.length - 1].value += string;
  380. } else {
  381. var makeTemplateObjectCallPath = getTypeScriptMakeTemplateObjectPath(path);
  382. if (makeTemplateObjectCallPath) {
  383. makeTemplateObjectCallPath.get('arguments').forEach(function (argPath) {
  384. var elements = argPath.get('elements');
  385. var lastElement = elements[elements.length - 1];
  386. lastElement.replaceWith(t.stringLiteral(lastElement.node.value + string));
  387. });
  388. } else if (!isTaggedTemplateTranspiledByBabel(path)) {
  389. args.push(t.stringLiteral(string));
  390. }
  391. }
  392. };
  393. var joinStringLiterals = function joinStringLiterals(expressions, t) {
  394. return expressions.reduce(function (finalExpressions, currentExpression, i) {
  395. if (!t.isStringLiteral(currentExpression)) {
  396. finalExpressions.push(currentExpression);
  397. } else if (t.isStringLiteral(finalExpressions[finalExpressions.length - 1])) {
  398. finalExpressions[finalExpressions.length - 1].value += currentExpression.value;
  399. } else {
  400. finalExpressions.push(currentExpression);
  401. }
  402. return finalExpressions;
  403. }, []);
  404. };
  405. var 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)."; // with babel@6 fallback
  406. var cloneNode = function cloneNode(t, node) {
  407. return typeof t.cloneNode === 'function' ? t.cloneNode(node) : t.cloneDeep(node);
  408. };
  409. function createSourceMapConditional(t, production, development) {
  410. return t.conditionalExpression(t.binaryExpression('===', t.memberExpression(t.memberExpression(t.identifier('process'), t.identifier('env')), t.identifier('NODE_ENV')), t.stringLiteral('production')), production, development);
  411. }
  412. var transformExpressionWithStyles = function transformExpressionWithStyles(_ref) {
  413. var babel = _ref.babel,
  414. state = _ref.state,
  415. path = _ref.path,
  416. shouldLabel = _ref.shouldLabel,
  417. _ref$sourceMap = _ref.sourceMap,
  418. sourceMap = _ref$sourceMap === void 0 ? '' : _ref$sourceMap;
  419. var t = babel.types;
  420. if (t.isTaggedTemplateExpression(path)) {
  421. var expressions = getExpressionsFromTemplateLiteral(path.node.quasi, t);
  422. if (state.emotionSourceMap && path.node.quasi.loc !== undefined) {
  423. sourceMap = getSourceMap(path.node.quasi.loc.start, state);
  424. }
  425. path.replaceWith(t.callExpression(path.node.tag, expressions));
  426. }
  427. if (t.isCallExpression(path)) {
  428. var canAppendStrings = path.node.arguments.every(function (arg) {
  429. return arg.type !== 'SpreadElement';
  430. });
  431. if (canAppendStrings && shouldLabel) {
  432. var label = getLabelFromPath(path, state, t);
  433. if (label) {
  434. appendStringToArguments(path, ";label:" + label + ";", t);
  435. }
  436. }
  437. path.get('arguments').forEach(function (node) {
  438. if (t.isObjectExpression(node)) {
  439. node.replaceWith(simplifyObject(node.node, t));
  440. }
  441. });
  442. path.node.arguments = joinStringLiterals(path.node.arguments, t);
  443. if (canAppendStrings && state.emotionSourceMap && !sourceMap && path.node.loc !== undefined) {
  444. sourceMap = getSourceMap(path.node.loc.start, state);
  445. }
  446. if (path.node.arguments.length === 1 && t.isStringLiteral(path.node.arguments[0])) {
  447. var cssString = path.node.arguments[0].value;
  448. var res = serializeStyles([cssString]);
  449. var prodNode = t.objectExpression([t.objectProperty(t.identifier('name'), t.stringLiteral(res.name)), t.objectProperty(t.identifier('styles'), t.stringLiteral(res.styles))]);
  450. var node = prodNode;
  451. if (sourceMap) {
  452. if (!state.emotionStringifiedCssId) {
  453. var uid = state.file.scope.generateUidIdentifier('__EMOTION_STRINGIFIED_CSS_ERROR__');
  454. state.emotionStringifiedCssId = uid;
  455. var cssObjectToString = t.functionDeclaration(uid, [], t.blockStatement([t.returnStatement(t.stringLiteral(CSS_OBJECT_STRINGIFIED_ERROR))]));
  456. cssObjectToString._compact = true;
  457. state.file.path.unshiftContainer('body', [cssObjectToString]);
  458. }
  459. 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))]);
  460. node = createSourceMapConditional(t, prodNode, devNode);
  461. }
  462. return node;
  463. }
  464. if (sourceMap) {
  465. var lastIndex = path.node.arguments.length - 1;
  466. var last = path.node.arguments[lastIndex];
  467. var sourceMapConditional = createSourceMapConditional(t, t.stringLiteral(''), t.stringLiteral(sourceMap));
  468. if (t.isStringLiteral(last)) {
  469. path.node.arguments[lastIndex] = t.binaryExpression('+', last, sourceMapConditional);
  470. } else {
  471. var makeTemplateObjectCallPath = getTypeScriptMakeTemplateObjectPath(path);
  472. if (makeTemplateObjectCallPath) {
  473. var sourceMapId = state.file.scope.generateUidIdentifier('emotionSourceMap');
  474. var sourceMapDeclaration = t.variableDeclaration('var', [t.variableDeclarator(sourceMapId, sourceMapConditional)]);
  475. sourceMapDeclaration._compact = true;
  476. state.file.path.unshiftContainer('body', [sourceMapDeclaration]);
  477. makeTemplateObjectCallPath.get('arguments').forEach(function (argPath) {
  478. var elements = argPath.get('elements');
  479. var lastElement = elements[elements.length - 1];
  480. lastElement.replaceWith(t.binaryExpression('+', lastElement.node, cloneNode(t, sourceMapId)));
  481. });
  482. } else if (!isTaggedTemplateTranspiledByBabel(path)) {
  483. path.node.arguments.push(sourceMapConditional);
  484. }
  485. }
  486. }
  487. }
  488. };
  489. var getKnownProperties = function getKnownProperties(t, node) {
  490. return new Set(node.properties.filter(function (n) {
  491. return t.isObjectProperty(n) && !n.computed;
  492. }).map(function (n) {
  493. return t.isIdentifier(n.key) ? n.key.name : n.key.value;
  494. }));
  495. };
  496. var getStyledOptions = function getStyledOptions(t, path, state) {
  497. var args = path.node.arguments;
  498. var optionsArgument = args.length >= 2 ? args[1] : null;
  499. var properties = [];
  500. var knownProperties = optionsArgument && t.isObjectExpression(optionsArgument) ? getKnownProperties(t, optionsArgument) : new Set();
  501. if (!knownProperties.has('target')) {
  502. properties.push(t.objectProperty(t.identifier('target'), t.stringLiteral(getTargetClassName(state))));
  503. }
  504. var label = getLabelFromPath(path, state, t);
  505. if (label && !knownProperties.has('label')) {
  506. properties.push(t.objectProperty(t.identifier('label'), t.stringLiteral(label)));
  507. }
  508. if (optionsArgument) {
  509. if (!t.isObjectExpression(optionsArgument)) {
  510. return t.callExpression(state.file.addHelper('extends'), [t.objectExpression([]), t.objectExpression(properties), optionsArgument]);
  511. }
  512. properties.unshift.apply(properties, optionsArgument.properties);
  513. }
  514. return t.objectExpression( // $FlowFixMe
  515. properties);
  516. };
  517. var createEmotionMacro = function createEmotionMacro(instancePath) {
  518. return createMacro(function macro(_ref) {
  519. var references = _ref.references,
  520. state = _ref.state,
  521. babel = _ref.babel,
  522. isEmotionCall = _ref.isEmotionCall;
  523. if (!isEmotionCall) {
  524. state.emotionSourceMap = true;
  525. }
  526. var t = babel.types;
  527. Object.keys(references).forEach(function (referenceKey) {
  528. var isPure = true;
  529. var runtimeNode = addNamed(state.file.path, referenceKey, instancePath);
  530. switch (referenceKey) {
  531. case 'injectGlobal':
  532. {
  533. isPure = false;
  534. }
  535. // eslint-disable-next-line no-fallthrough
  536. case 'css':
  537. case 'keyframes':
  538. {
  539. references[referenceKey].reverse().forEach(function (reference) {
  540. var path = reference.parentPath;
  541. reference.replaceWith(t.cloneDeep(runtimeNode));
  542. if (isPure) {
  543. path.addComment('leading', '#__PURE__');
  544. }
  545. var node = transformExpressionWithStyles({
  546. babel: babel,
  547. state: state,
  548. path: path,
  549. shouldLabel: true
  550. });
  551. if (node) {
  552. path.node.arguments[0] = node;
  553. }
  554. });
  555. break;
  556. }
  557. default:
  558. {
  559. references[referenceKey].reverse().forEach(function (reference) {
  560. reference.replaceWith(t.cloneDeep(runtimeNode));
  561. });
  562. }
  563. }
  564. });
  565. });
  566. };
  567. var createStyledMacro = function createStyledMacro(_ref) {
  568. var importPath = _ref.importPath,
  569. _ref$originalImportPa = _ref.originalImportPath,
  570. originalImportPath = _ref$originalImportPa === void 0 ? importPath : _ref$originalImportPa,
  571. isWeb = _ref.isWeb;
  572. return createMacro(function (_ref2) {
  573. var references = _ref2.references,
  574. state = _ref2.state,
  575. babel = _ref2.babel,
  576. isEmotionCall = _ref2.isEmotionCall;
  577. if (!isEmotionCall) {
  578. state.emotionSourceMap = true;
  579. }
  580. var t = babel.types;
  581. if (references["default"] && references["default"].length) {
  582. var _styledIdentifier;
  583. var getStyledIdentifier = function getStyledIdentifier() {
  584. if (_styledIdentifier === undefined) {
  585. _styledIdentifier = addDefault(state.file.path, importPath, {
  586. nameHint: 'styled'
  587. });
  588. }
  589. return t.cloneDeep(_styledIdentifier);
  590. };
  591. var originalImportPathStyledIdentifier;
  592. var getOriginalImportPathStyledIdentifier = function getOriginalImportPathStyledIdentifier() {
  593. if (originalImportPathStyledIdentifier === undefined) {
  594. originalImportPathStyledIdentifier = addDefault(state.file.path, originalImportPath, {
  595. nameHint: 'styled'
  596. });
  597. }
  598. return t.cloneDeep(originalImportPathStyledIdentifier);
  599. };
  600. if (importPath === originalImportPath) {
  601. getOriginalImportPathStyledIdentifier = getStyledIdentifier;
  602. }
  603. references["default"].forEach(function (reference) {
  604. var isCall = false;
  605. if (t.isMemberExpression(reference.parent) && reference.parent.computed === false) {
  606. isCall = true;
  607. if ( // checks if the first character is lowercase
  608. // becasue we don't want to transform the member expression if
  609. // it's in primitives/native
  610. reference.parent.property.name.charCodeAt(0) > 96) {
  611. reference.parentPath.replaceWith(t.callExpression(getStyledIdentifier(), [t.stringLiteral(reference.parent.property.name)]));
  612. } else {
  613. reference.replaceWith(getStyledIdentifier());
  614. }
  615. } else if (reference.parentPath && reference.parentPath.parentPath && t.isCallExpression(reference.parentPath) && reference.parent.callee === reference.node) {
  616. isCall = true;
  617. reference.replaceWith(getStyledIdentifier());
  618. } else {
  619. reference.replaceWith(getOriginalImportPathStyledIdentifier());
  620. }
  621. if (reference.parentPath && reference.parentPath.parentPath) {
  622. var styledCallPath = reference.parentPath.parentPath;
  623. var node = transformExpressionWithStyles({
  624. path: styledCallPath,
  625. state: state,
  626. babel: babel,
  627. shouldLabel: false
  628. });
  629. if (node && isWeb) {
  630. // we know the argument length will be 1 since that's the only time we will have a node since it will be static
  631. styledCallPath.node.arguments[0] = node;
  632. }
  633. }
  634. if (isCall) {
  635. reference.addComment('leading', '#__PURE__');
  636. if (isWeb) {
  637. reference.parentPath.node.arguments[1] = getStyledOptions(t, reference.parentPath, state);
  638. }
  639. }
  640. });
  641. }
  642. Object.keys(references).filter(function (x) {
  643. return x !== 'default';
  644. }).forEach(function (referenceKey) {
  645. var runtimeNode = addNamed(state.file.path, referenceKey, importPath);
  646. references[referenceKey].reverse().forEach(function (reference) {
  647. reference.replaceWith(t.cloneDeep(runtimeNode));
  648. });
  649. });
  650. });
  651. };
  652. var transformCssCallExpression = function transformCssCallExpression(_ref) {
  653. var babel = _ref.babel,
  654. state = _ref.state,
  655. path = _ref.path,
  656. sourceMap = _ref.sourceMap;
  657. var node = transformExpressionWithStyles({
  658. babel: babel,
  659. state: state,
  660. path: path,
  661. shouldLabel: true,
  662. sourceMap: sourceMap
  663. });
  664. if (node) {
  665. path.replaceWith(node);
  666. path.hoist();
  667. } else if (path.isCallExpression()) {
  668. path.addComment('leading', '#__PURE__');
  669. }
  670. };
  671. var cssMacro = createMacro(function (_ref2) {
  672. var references = _ref2.references,
  673. state = _ref2.state,
  674. babel = _ref2.babel,
  675. isEmotionCall = _ref2.isEmotionCall;
  676. if (!isEmotionCall) {
  677. state.emotionSourceMap = true;
  678. }
  679. var t = babel.types;
  680. if (references["default"] && references["default"].length) {
  681. references["default"].reverse().forEach(function (reference) {
  682. if (!state.cssIdentifier) {
  683. state.cssIdentifier = addDefault(reference, '@emotion/css', {
  684. nameHint: 'css'
  685. });
  686. }
  687. reference.replaceWith(t.cloneDeep(state.cssIdentifier));
  688. transformCssCallExpression({
  689. babel: babel,
  690. state: state,
  691. path: reference.parentPath
  692. });
  693. });
  694. }
  695. Object.keys(references).filter(function (x) {
  696. return x !== 'default';
  697. }).forEach(function (referenceKey) {
  698. var runtimeNode = addNamed(state.file.path, referenceKey, '@emotion/css', {
  699. nameHint: referenceKey
  700. });
  701. references[referenceKey].reverse().forEach(function (reference) {
  702. reference.replaceWith(t.cloneDeep(runtimeNode));
  703. });
  704. });
  705. });
  706. var webStyledMacro = createStyledMacro({
  707. importPath: '@emotion/styled-base',
  708. originalImportPath: '@emotion/styled',
  709. isWeb: true
  710. });
  711. var nativeStyledMacro = createStyledMacro({
  712. importPath: '@emotion/native',
  713. originalImportPath: '@emotion/native',
  714. isWeb: false
  715. });
  716. var primitivesStyledMacro = createStyledMacro({
  717. importPath: '@emotion/primitives',
  718. originalImportPath: '@emotion/primitives',
  719. isWeb: false
  720. });
  721. var macros = {
  722. createEmotionMacro: createEmotionMacro,
  723. css: cssMacro,
  724. createStyledMacro: createStyledMacro
  725. };
  726. var emotionCoreMacroThatsNotARealMacro = function emotionCoreMacroThatsNotARealMacro(_ref) {
  727. var references = _ref.references,
  728. state = _ref.state,
  729. babel = _ref.babel;
  730. Object.keys(references).forEach(function (refKey) {
  731. if (refKey === 'css') {
  732. references[refKey].forEach(function (path) {
  733. transformCssCallExpression({
  734. babel: babel,
  735. state: state,
  736. path: path.parentPath
  737. });
  738. });
  739. }
  740. });
  741. };
  742. emotionCoreMacroThatsNotARealMacro.keepImport = true;
  743. function getAbsolutePath(instancePath, rootPath) {
  744. if (instancePath.charAt(0) === '.') {
  745. var absoluteInstancePath = nodePath.resolve(rootPath, instancePath);
  746. return absoluteInstancePath;
  747. }
  748. return false;
  749. }
  750. function getInstancePathToCompare(instancePath, rootPath) {
  751. var absolutePath = getAbsolutePath(instancePath, rootPath);
  752. if (absolutePath === false) {
  753. return instancePath;
  754. }
  755. return absolutePath;
  756. }
  757. function index (babel) {
  758. var t = babel.types;
  759. return {
  760. name: 'emotion',
  761. inherits: require('babel-plugin-syntax-jsx'),
  762. visitor: {
  763. ImportDeclaration: function ImportDeclaration(path, state) {
  764. var hasFilepath = path.hub.file.opts.filename && path.hub.file.opts.filename !== 'unknown';
  765. var dirname = hasFilepath ? nodePath.dirname(path.hub.file.opts.filename) : '';
  766. if (!state.pluginMacros[path.node.source.value] && state.emotionInstancePaths.indexOf(getInstancePathToCompare(path.node.source.value, dirname)) !== -1) {
  767. state.pluginMacros[path.node.source.value] = createEmotionMacro(path.node.source.value);
  768. }
  769. var pluginMacros = state.pluginMacros; // most of this is from https://github.com/kentcdodds/babel-plugin-macros/blob/master/src/index.js
  770. if (pluginMacros[path.node.source.value] === undefined) {
  771. return;
  772. }
  773. if (t.isImportNamespaceSpecifier(path.node.specifiers[0])) {
  774. return;
  775. }
  776. var imports = path.node.specifiers.map(function (s) {
  777. return {
  778. localName: s.local.name,
  779. importedName: s.type === 'ImportDefaultSpecifier' ? 'default' : s.imported.name
  780. };
  781. });
  782. var shouldExit = false;
  783. var hasReferences = false;
  784. var referencePathsByImportName = imports.reduce(function (byName, _ref2) {
  785. var importedName = _ref2.importedName,
  786. localName = _ref2.localName;
  787. var binding = path.scope.getBinding(localName);
  788. if (!binding) {
  789. shouldExit = true;
  790. return byName;
  791. }
  792. byName[importedName] = binding.referencePaths;
  793. hasReferences = hasReferences || Boolean(byName[importedName].length);
  794. return byName;
  795. }, {});
  796. if (!hasReferences || shouldExit) {
  797. return;
  798. }
  799. /**
  800. * Other plugins that run before babel-plugin-macros might use path.replace, where a path is
  801. * put into its own replacement. Apparently babel does not update the scope after such
  802. * an operation. As a remedy, the whole scope is traversed again with an empty "Identifier"
  803. * visitor - this makes the problem go away.
  804. *
  805. * See: https://github.com/kentcdodds/import-all.macro/issues/7
  806. */
  807. state.file.scope.path.traverse({
  808. Identifier: function Identifier() {}
  809. });
  810. pluginMacros[path.node.source.value]({
  811. references: referencePathsByImportName,
  812. state: state,
  813. babel: babel,
  814. isBabelMacrosCall: true,
  815. isEmotionCall: true
  816. });
  817. if (!pluginMacros[path.node.source.value].keepImport) {
  818. path.remove();
  819. }
  820. },
  821. Program: function Program(path, state) {
  822. state.emotionInstancePaths = (state.opts.instances || []).map(function (instancePath) {
  823. return getInstancePathToCompare(instancePath, process.cwd());
  824. });
  825. state.pluginMacros = {
  826. '@emotion/css': cssMacro,
  827. '@emotion/styled': webStyledMacro,
  828. '@emotion/core': emotionCoreMacroThatsNotARealMacro,
  829. '@emotion/primitives': primitivesStyledMacro,
  830. '@emotion/native': nativeStyledMacro,
  831. emotion: createEmotionMacro('emotion')
  832. };
  833. if (state.opts.cssPropOptimization === undefined) {
  834. for (var _iterator = path.node.body, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
  835. var _ref3;
  836. if (_isArray) {
  837. if (_i >= _iterator.length) break;
  838. _ref3 = _iterator[_i++];
  839. } else {
  840. _i = _iterator.next();
  841. if (_i.done) break;
  842. _ref3 = _i.value;
  843. }
  844. var node = _ref3;
  845. if (t.isImportDeclaration(node) && node.source.value === '@emotion/core' && node.specifiers.some(function (x) {
  846. return t.isImportSpecifier(x) && x.imported.name === 'jsx';
  847. })) {
  848. state.transformCssProp = true;
  849. break;
  850. }
  851. }
  852. } else {
  853. state.transformCssProp = state.opts.cssPropOptimization;
  854. }
  855. if (state.opts.sourceMap === false) {
  856. state.emotionSourceMap = false;
  857. } else {
  858. state.emotionSourceMap = true;
  859. }
  860. },
  861. JSXAttribute: function JSXAttribute(path, state) {
  862. if (path.node.name.name !== 'css' || !state.transformCssProp) {
  863. return;
  864. }
  865. if (t.isJSXExpressionContainer(path.node.value) && (t.isObjectExpression(path.node.value.expression) || t.isArrayExpression(path.node.value.expression))) {
  866. var expressionPath = path.get('value.expression');
  867. var sourceMap = state.emotionSourceMap && path.node.loc !== undefined ? getSourceMap(path.node.loc.start, state) : '';
  868. expressionPath.replaceWith(t.callExpression( // the name of this identifier doesn't really matter at all
  869. // it'll never appear in generated code
  870. t.identifier('___shouldNeverAppearCSS'), [path.node.value.expression]));
  871. transformCssCallExpression({
  872. babel: babel,
  873. state: state,
  874. path: expressionPath,
  875. sourceMap: sourceMap
  876. });
  877. if (t.isCallExpression(expressionPath)) {
  878. if (!state.cssIdentifier) {
  879. state.cssIdentifier = addDefault(path, '@emotion/css', {
  880. nameHint: 'css'
  881. });
  882. }
  883. expressionPath.get('callee').replaceWith(t.cloneDeep(state.cssIdentifier));
  884. }
  885. }
  886. },
  887. CallExpression: {
  888. exit: function exit(path, state) {
  889. try {
  890. if (path.node.callee && path.node.callee.property && path.node.callee.property.name === 'withComponent') {
  891. switch (path.node.arguments.length) {
  892. case 1:
  893. case 2:
  894. {
  895. path.node.arguments[1] = getStyledOptions(t, path, state);
  896. }
  897. }
  898. }
  899. } catch (e) {
  900. throw path.buildCodeFrameError(e);
  901. }
  902. }
  903. }
  904. }
  905. };
  906. }
  907. export default index;
  908. export { macros };