index.cjs 2.5 KB

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