StringLiteralReplacer.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { TUnicodeArrayCallsWrapper } from 'app/types/custom-nodes/TUnicodeArrayCallsWrapper';
  2. import { TUnicodeArrayNode } from 'app/types/custom-nodes/TUnicodeArrayNode';
  3. import { AbstractReplacer } from './AbstractReplacer';
  4. import { NumberLiteralReplacer } from './NumberLiteralReplacer';
  5. import { UnicodeArray } from 'app/UnicodeArray';
  6. import { Utils } from 'app/Utils';
  7. export class StringLiteralReplacer extends AbstractReplacer {
  8. /**
  9. * @param nodeValue
  10. * @returns {string}
  11. */
  12. public replace (nodeValue: string): string {
  13. const replaceWithUnicodeArrayFlag: boolean = Math.random() <= this.options.unicodeArrayThreshold;
  14. if (this.options.encodeUnicodeLiterals && replaceWithUnicodeArrayFlag) {
  15. nodeValue = Utils.btoa(nodeValue);
  16. }
  17. nodeValue = Utils.stringToUnicode(nodeValue);
  18. if (this.options.unicodeArray && replaceWithUnicodeArrayFlag) {
  19. return this.replaceStringLiteralWithUnicodeArrayCall(nodeValue);
  20. }
  21. return nodeValue;
  22. }
  23. /**
  24. * @param value
  25. * @returns {string}
  26. */
  27. private replaceStringLiteralWithUnicodeArrayCall (value: string): string {
  28. const unicodeArrayNode: TUnicodeArrayNode = <TUnicodeArrayNode>this.nodes.get('unicodeArrayNode');
  29. if (!unicodeArrayNode) {
  30. throw new ReferenceError('`unicodeArrayNode` node is not found in Map with custom nodes.');
  31. }
  32. let unicodeArray: UnicodeArray = unicodeArrayNode.getNodeData(),
  33. indexOfExistingValue: number = unicodeArray.getIndexOf(value),
  34. indexOfValue: number,
  35. hexadecimalIndex: string;
  36. if (indexOfExistingValue >= 0) {
  37. indexOfValue = indexOfExistingValue;
  38. } else {
  39. indexOfValue = unicodeArray.getLength();
  40. unicodeArrayNode.updateNodeData(value);
  41. }
  42. hexadecimalIndex = new NumberLiteralReplacer(this.nodes, this.options)
  43. .replace(indexOfValue);
  44. if (this.options.wrapUnicodeArrayCalls) {
  45. const unicodeArrayCallsWrapper: TUnicodeArrayCallsWrapper = <TUnicodeArrayCallsWrapper>this.nodes.get('unicodeArrayCallsWrapper');
  46. if (!unicodeArrayCallsWrapper) {
  47. throw new ReferenceError('`unicodeArrayCallsWrapper` node is not found in Map with custom nodes.');
  48. }
  49. return `${unicodeArrayCallsWrapper.getNodeIdentifier()}('${hexadecimalIndex}')`;
  50. }
  51. return `${unicodeArrayNode.getNodeIdentifier()}[${hexadecimalIndex}]`;
  52. }
  53. }