index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * The MIT License (MIT)
  3. * Copyright (c) 2017-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com>
  4. */
  5. 'use strict';
  6. var compatTransforms = require('./transforms');
  7. var _transform = require('../transform');
  8. module.exports = {
  9. /**
  10. * Translates a regexp in new syntax to equivalent regexp in old syntax.
  11. *
  12. * @param string|RegExp|AST - regexp
  13. * @param Array transformsWhitelist - names of the transforms to apply
  14. */
  15. transform: function transform(regexp) {
  16. var transformsWhitelist = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  17. var transformToApply = transformsWhitelist.length > 0 ? transformsWhitelist : Object.keys(compatTransforms);
  18. var result = void 0;
  19. // Collect extra data per transform.
  20. var extra = {};
  21. transformToApply.forEach(function (transformName) {
  22. if (!compatTransforms.hasOwnProperty(transformName)) {
  23. throw new Error('Unknown compat-transform: ' + transformName + '. ' + 'Available transforms are: ' + Object.keys(compatTransforms).join(', '));
  24. }
  25. var handler = compatTransforms[transformName];
  26. result = _transform.transform(regexp, handler);
  27. regexp = result.getAST();
  28. // Collect `extra` transform result.
  29. if (typeof handler.getExtra === 'function') {
  30. extra[transformName] = handler.getExtra();
  31. }
  32. });
  33. // Set the final extras for all transforms.
  34. result.setExtra(extra);
  35. return result;
  36. }
  37. };