compile.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const compile = (cst, options = {}) => {
  3. const keepProtected = options.safe === true || options.keepProtected === true;
  4. let firstSeen = false;
  5. const walk = (node, parent) => {
  6. let output = '';
  7. let inner;
  8. let lines;
  9. for (const child of node.nodes) {
  10. switch (child.type) {
  11. case 'block':
  12. if (options.first && firstSeen === true) {
  13. output += walk(child, node);
  14. break;
  15. }
  16. if (options.preserveNewlines === true) {
  17. inner = walk(child, node);
  18. lines = inner.split('\n');
  19. output += '\n'.repeat(lines.length - 1);
  20. break;
  21. }
  22. if (keepProtected === true && child.protected === true) {
  23. output += walk(child, node);
  24. break;
  25. }
  26. firstSeen = true;
  27. break;
  28. case 'line':
  29. if (options.first && firstSeen === true) {
  30. output += child.value;
  31. break;
  32. }
  33. if (keepProtected === true && child.protected === true) {
  34. output += child.value;
  35. }
  36. firstSeen = true;
  37. break;
  38. case 'open':
  39. case 'close':
  40. case 'text':
  41. case 'newline':
  42. default: {
  43. output += child.value || '';
  44. break;
  45. }
  46. }
  47. }
  48. return output;
  49. };
  50. return walk(cst);
  51. };
  52. module.exports = compile;