index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _helperPluginUtils = require("@babel/helper-plugin-utils");
  7. var _core = require("@babel/core");
  8. const TRACE_ID = "__source";
  9. const FILE_NAME_VAR = "_jsxFileName";
  10. var _default = (0, _helperPluginUtils.declare)(api => {
  11. api.assertVersion(7);
  12. function makeTrace(fileNameIdentifier, lineNumber, column0Based) {
  13. const fileLineLiteral = lineNumber != null ? _core.types.numericLiteral(lineNumber) : _core.types.nullLiteral();
  14. const fileColumnLiteral = column0Based != null ? _core.types.numericLiteral(column0Based + 1) : _core.types.nullLiteral();
  15. const fileNameProperty = _core.types.objectProperty(_core.types.identifier("fileName"), fileNameIdentifier);
  16. const lineNumberProperty = _core.types.objectProperty(_core.types.identifier("lineNumber"), fileLineLiteral);
  17. const columnNumberProperty = _core.types.objectProperty(_core.types.identifier("columnNumber"), fileColumnLiteral);
  18. return _core.types.objectExpression([fileNameProperty, lineNumberProperty, columnNumberProperty]);
  19. }
  20. const visitor = {
  21. JSXOpeningElement(path, state) {
  22. const id = _core.types.jsxIdentifier(TRACE_ID);
  23. const location = path.container.openingElement.loc;
  24. if (!location) {
  25. return;
  26. }
  27. const attributes = path.container.openingElement.attributes;
  28. for (let i = 0; i < attributes.length; i++) {
  29. const name = attributes[i].name;
  30. if ((name == null ? void 0 : name.name) === TRACE_ID) {
  31. return;
  32. }
  33. }
  34. if (!state.fileNameIdentifier) {
  35. const fileName = state.filename || "";
  36. const fileNameIdentifier = path.scope.generateUidIdentifier(FILE_NAME_VAR);
  37. const scope = path.hub.getScope();
  38. if (scope) {
  39. scope.push({
  40. id: fileNameIdentifier,
  41. init: _core.types.stringLiteral(fileName)
  42. });
  43. }
  44. state.fileNameIdentifier = fileNameIdentifier;
  45. }
  46. const trace = makeTrace(_core.types.cloneNode(state.fileNameIdentifier), location.start.line, location.start.column);
  47. attributes.push(_core.types.jsxAttribute(id, _core.types.jsxExpressionContainer(trace)));
  48. }
  49. };
  50. return {
  51. name: "transform-react-jsx-source",
  52. visitor
  53. };
  54. });
  55. exports.default = _default;