index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = _default;
  6. function _regexpTree() {
  7. const data = _interopRequireDefault(require("regexp-tree"));
  8. _regexpTree = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14. function _default({
  15. types: t
  16. }, options) {
  17. const {
  18. runtime = true
  19. } = options;
  20. if (typeof runtime !== "boolean") {
  21. throw new Error("The 'runtime' option must be boolean");
  22. }
  23. return {
  24. name: "transform-named-capturing-groups-regex",
  25. visitor: {
  26. RegExpLiteral(path) {
  27. const node = path.node;
  28. if (node.pattern.indexOf("(?<") === -1) {
  29. return;
  30. }
  31. const result = _regexpTree().default.compatTranspile(node.extra.raw, ["namedCapturingGroups"]);
  32. const {
  33. namedCapturingGroups
  34. } = result.getExtra();
  35. if (namedCapturingGroups && Object.keys(namedCapturingGroups).length > 0) {
  36. node.pattern = result.getSource();
  37. if (runtime && !isRegExpTest(path)) {
  38. path.replaceWith(t.callExpression(this.addHelper("wrapRegExp"), [node, t.valueToNode(namedCapturingGroups)]));
  39. }
  40. }
  41. }
  42. }
  43. };
  44. }
  45. function isRegExpTest(path) {
  46. return path.parentPath.isMemberExpression({
  47. object: path.node,
  48. computed: false
  49. }) && path.parentPath.get("property").isIdentifier({
  50. name: "test"
  51. });
  52. }