CommentsTransformer.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { inject, injectable, } from 'inversify';
  2. import { ServiceIdentifiers } from '../../container/ServiceIdentifiers';
  3. import * as ESTree from 'estree';
  4. import { IOptions } from '../../interfaces/options/IOptions';
  5. import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
  6. import { IVisitor } from '../../interfaces/node-transformers/IVisitor';
  7. import { AbstractNodeTransformer } from '../AbstractNodeTransformer';
  8. import { NodeGuards } from '../../node/NodeGuards';
  9. @injectable()
  10. export class CommentsTransformer extends AbstractNodeTransformer {
  11. /**
  12. * @type {string[]}
  13. */
  14. private static preservedWords: string[] = ['@license', '@preserve', 'javascript-obfuscator'];
  15. /**
  16. * @param {IRandomGenerator} randomGenerator
  17. * @param {IOptions} options
  18. */
  19. constructor (
  20. @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
  21. @inject(ServiceIdentifiers.IOptions) options: IOptions
  22. ) {
  23. super(randomGenerator, options);
  24. }
  25. /**
  26. * @return {IVisitor}
  27. */
  28. public getVisitor (): IVisitor {
  29. return {
  30. enter: (node: ESTree.Node, parentNode: ESTree.Node | null) => {
  31. if (parentNode && NodeGuards.isNodeWithComments(node)) {
  32. return this.transformNode(node, parentNode);
  33. }
  34. }
  35. };
  36. }
  37. /**
  38. * Removes all comments from node except comments that contain
  39. * `@license`, `@preserve` or `javascript-obfuscator` words
  40. *
  41. * @param {Node} node
  42. * @param {Node} parentNode
  43. * @returns {NodeGuards}
  44. */
  45. public transformNode (node: ESTree.Node, parentNode: ESTree.Node): ESTree.Node {
  46. if (node.leadingComments) {
  47. node.leadingComments = this.transformComments(node.leadingComments);
  48. }
  49. if (node.trailingComments) {
  50. node.trailingComments = this.transformComments(node.trailingComments);
  51. }
  52. return node;
  53. }
  54. /**
  55. * @param {Comment[]} comments
  56. * @returns {Comment[]}
  57. */
  58. private transformComments (comments: ESTree.Comment[]): ESTree.Comment[] {
  59. return comments.filter((comment: ESTree.Comment) =>
  60. CommentsTransformer.preservedWords
  61. .some((availableWord: string) => comment.value.includes(availableWord))
  62. );
  63. }
  64. }