index.mjs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import jsTokens from 'js-tokens';
  2. function stripLiteralJsTokens(code, options) {
  3. const FILL = options?.fillChar ?? " ";
  4. const FILL_COMMENT = " ";
  5. let result = "";
  6. const filter = options?.filter ?? (() => true);
  7. const tokens = [];
  8. for (const token of jsTokens(code, { jsx: false })) {
  9. tokens.push(token);
  10. if (token.type === "SingleLineComment") {
  11. result += FILL_COMMENT.repeat(token.value.length);
  12. continue;
  13. }
  14. if (token.type === "MultiLineComment") {
  15. result += token.value.replace(/[^\n]/g, FILL_COMMENT);
  16. continue;
  17. }
  18. if (token.type === "StringLiteral") {
  19. if (!token.closed) {
  20. result += token.value;
  21. continue;
  22. }
  23. const body = token.value.slice(1, -1);
  24. if (filter(body)) {
  25. result += token.value[0] + FILL.repeat(body.length) + token.value[token.value.length - 1];
  26. continue;
  27. }
  28. }
  29. if (token.type === "NoSubstitutionTemplate") {
  30. const body = token.value.slice(1, -1);
  31. if (filter(body)) {
  32. result += `\`${body.replace(/[^\n]/g, FILL)}\``;
  33. continue;
  34. }
  35. }
  36. if (token.type === "RegularExpressionLiteral") {
  37. const body = token.value;
  38. if (filter(body)) {
  39. result += body.replace(/\/(.*)\/(\w?)$/g, (_, $1, $2) => `/${FILL.repeat($1.length)}/${$2}`);
  40. continue;
  41. }
  42. }
  43. if (token.type === "TemplateHead") {
  44. const body = token.value.slice(1, -2);
  45. if (filter(body)) {
  46. result += `\`${body.replace(/[^\n]/g, FILL)}\${`;
  47. continue;
  48. }
  49. }
  50. if (token.type === "TemplateTail") {
  51. const body = token.value.slice(0, -2);
  52. if (filter(body)) {
  53. result += `}${body.replace(/[^\n]/g, FILL)}\``;
  54. continue;
  55. }
  56. }
  57. if (token.type === "TemplateMiddle") {
  58. const body = token.value.slice(1, -2);
  59. if (filter(body)) {
  60. result += `}${body.replace(/[^\n]/g, FILL)}\${`;
  61. continue;
  62. }
  63. }
  64. result += token.value;
  65. }
  66. return {
  67. result,
  68. tokens
  69. };
  70. }
  71. function stripLiteral(code, options) {
  72. return stripLiteralDetailed(code, options).result;
  73. }
  74. function stripLiteralDetailed(code, options) {
  75. return stripLiteralJsTokens(code, options);
  76. }
  77. export { stripLiteral, stripLiteralDetailed, stripLiteralJsTokens };