ThroughIdentifierReplacer.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { inject, injectable, } from 'inversify';
  2. import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers';
  3. import * as ESTree from 'estree';
  4. import { IGlobalIdentifierNamesCacheStorage } from '../../../interfaces/storages/identifier-names-cache/IGlobalIdentifierNamesCacheStorage';
  5. import { IOptions } from '../../../interfaces/options/IOptions';
  6. import { IThroughIdentifierReplacer } from '../../../interfaces/node-transformers/rename-identifiers-transformers/replacer/IThroughIdentifierReplacer';
  7. import { NodeFactory } from '../../../node/NodeFactory';
  8. @injectable()
  9. export class ThroughIdentifierReplacer implements IThroughIdentifierReplacer {
  10. /**
  11. * @type {IGlobalIdentifierNamesCacheStorage}
  12. */
  13. private readonly identifierNamesCacheStorage: IGlobalIdentifierNamesCacheStorage;
  14. /**
  15. * @type {IOptions}
  16. */
  17. private readonly options: IOptions;
  18. /**
  19. * @param {IGlobalIdentifierNamesCacheStorage} identifierNamesCacheStorage
  20. * @param {IOptions} options
  21. */
  22. public constructor (
  23. @inject(ServiceIdentifiers.IGlobalIdentifierNamesCacheStorage)
  24. identifierNamesCacheStorage: IGlobalIdentifierNamesCacheStorage,
  25. @inject(ServiceIdentifiers.IOptions) options: IOptions
  26. ) {
  27. this.identifierNamesCacheStorage = identifierNamesCacheStorage;
  28. this.options = options;
  29. }
  30. /**
  31. * @param {Identifier} identifierNode
  32. * @returns {Identifier}
  33. */
  34. public replace (identifierNode: ESTree.Identifier): ESTree.Identifier {
  35. const identifierName: string = identifierNode.name;
  36. const newIdentifierName: string = this.options.identifierNamesCache && !this.isReservedName(identifierName)
  37. ? this.identifierNamesCacheStorage.get(identifierName) ?? identifierName
  38. : identifierName;
  39. return NodeFactory.identifierNode(newIdentifierName);
  40. }
  41. /**
  42. * @param {string} name
  43. * @returns {boolean}
  44. */
  45. private isReservedName (name: string): boolean {
  46. if (!this.options.reservedNames.length) {
  47. return false;
  48. }
  49. return this.options.reservedNames
  50. .some((reservedName: string) => {
  51. return new RegExp(reservedName, 'g').exec(name) !== null;
  52. });
  53. }
  54. }