IdentifierObfuscatingReplacer.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { injectable, inject } from 'inversify';
  2. import { ServiceIdentifiers } from '../../../../container/ServiceIdentifiers';
  3. import * as ESTree from 'estree';
  4. import { IIdentifierObfuscatingReplacer } from '../../../../interfaces/node-transformers/obfuscating-transformers/IIdentifierObfuscatingReplacer';
  5. import { IOptions } from '../../../../interfaces/options/IOptions';
  6. import { AbstractObfuscatingReplacer } from '../AbstractObfuscatingReplacer';
  7. import { Nodes } from '../../../../node/Nodes';
  8. import { RandomGeneratorUtils } from '../../../../utils/RandomGeneratorUtils';
  9. @injectable()
  10. export class IdentifierObfuscatingReplacer extends AbstractObfuscatingReplacer implements IIdentifierObfuscatingReplacer {
  11. /**
  12. * @type {Map<string, string>}
  13. */
  14. private readonly namesMap: Map<string, string> = new Map();
  15. /**
  16. * @param options
  17. */
  18. constructor (
  19. @inject(ServiceIdentifiers.IOptions) options: IOptions
  20. ) {
  21. super(options);
  22. }
  23. /**
  24. * @param nodeValue
  25. * @param nodeIdentifier
  26. * @returns {ESTree.Identifier}
  27. */
  28. public replace (nodeValue: string, nodeIdentifier: number): ESTree.Identifier {
  29. const mapKey: string = `${nodeValue}-${String(nodeIdentifier)}`;
  30. if (this.namesMap.has(mapKey)) {
  31. nodeValue = <string>this.namesMap.get(mapKey);
  32. }
  33. return Nodes.getIdentifierNode(nodeValue);
  34. }
  35. /**
  36. * Store all `nodeIdentifier`'s as keys in given `namesMap` with random names as value.
  37. * Reserved names will be ignored.
  38. *
  39. * @param nodeName
  40. * @param nodeIdentifier
  41. */
  42. public storeNames (nodeName: string, nodeIdentifier: number): void {
  43. if (!this.isReservedName(nodeName)) {
  44. this.namesMap.set(`${nodeName}-${String(nodeIdentifier)}`, RandomGeneratorUtils.getRandomVariableName(6));
  45. }
  46. }
  47. /**
  48. * @param name
  49. * @returns {boolean}
  50. */
  51. private isReservedName (name: string): boolean {
  52. return this.options.reservedNames
  53. .some((reservedName: string) => {
  54. return new RegExp(reservedName, 'g').exec(name) !== null;
  55. });
  56. }
  57. }