traverse.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.traverse = traverse;
  6. var _nodePath = require("./node-path");
  7. var _nodes = require("./nodes");
  8. // recursively walks the AST starting at the given node. The callback is invoked for
  9. // and object that has a 'type' property.
  10. function walk(context, callback) {
  11. var stop = false;
  12. function innerWalk(context, callback) {
  13. if (stop) {
  14. return;
  15. }
  16. var node = context.node;
  17. if (node._deleted === true) {
  18. return;
  19. }
  20. var path = (0, _nodePath.createPath)(context);
  21. callback(node.type, path);
  22. if (path.shouldStop) {
  23. stop = true;
  24. return;
  25. }
  26. Object.keys(node).forEach(function (prop) {
  27. var value = node[prop];
  28. if (value === null || value === undefined) {
  29. return;
  30. }
  31. var valueAsArray = Array.isArray(value) ? value : [value];
  32. valueAsArray.forEach(function (childNode) {
  33. if (typeof childNode.type === "string") {
  34. var childContext = {
  35. node: childNode,
  36. parentKey: prop,
  37. parentPath: path,
  38. shouldStop: false,
  39. inList: Array.isArray(value)
  40. };
  41. innerWalk(childContext, callback);
  42. }
  43. });
  44. });
  45. }
  46. innerWalk(context, callback);
  47. }
  48. var noop = function noop() {};
  49. function traverse(node, visitors) {
  50. var before = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : noop;
  51. var after = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : noop;
  52. Object.keys(visitors).forEach(function (visitor) {
  53. if (!_nodes.nodeAndUnionTypes.includes(visitor)) {
  54. throw new Error("Unexpected visitor ".concat(visitor));
  55. }
  56. });
  57. var context = {
  58. node: node,
  59. inList: false,
  60. shouldStop: false,
  61. parentPath: null,
  62. parentKey: null
  63. };
  64. walk(context, function (type, path) {
  65. if (typeof visitors[type] === "function") {
  66. before(type, path);
  67. visitors[type](path);
  68. after(type, path);
  69. }
  70. var unionTypes = _nodes.unionTypesMap[type];
  71. if (!unionTypes) {
  72. throw new Error("Unexpected node type ".concat(type));
  73. }
  74. unionTypes.forEach(function (unionType) {
  75. if (typeof visitors[unionType] === "function") {
  76. before(unionType, path);
  77. visitors[unionType](path);
  78. after(unionType, path);
  79. }
  80. });
  81. });
  82. }