ObfuscatedCode.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import { inject, injectable } from 'inversify';
  2. import { ServiceIdentifiers } from '../container/ServiceIdentifiers';
  3. import { ICryptUtils } from '../interfaces/utils/ICryptUtils';
  4. import { IObfuscatedCode } from '../interfaces/source-code/IObfuscatedCode';
  5. import { initializable } from '../decorators/Initializable';
  6. import { SourceMapMode } from '../enums/source-map/SourceMapMode';
  7. import { IOptions } from '../interfaces/options/IOptions';
  8. @injectable()
  9. export class ObfuscatedCode implements IObfuscatedCode {
  10. /**
  11. * @type {ICryptUtils}
  12. */
  13. private readonly cryptUtils: ICryptUtils;
  14. /**
  15. * @type {string}
  16. */
  17. @initializable()
  18. private obfuscatedCode!: string;
  19. /**
  20. * @type {IOptions}
  21. */
  22. private readonly options: IOptions;
  23. /**
  24. * @type {string}
  25. */
  26. @initializable()
  27. private sourceMap!: string;
  28. constructor (
  29. @inject(ServiceIdentifiers.ICryptUtils) cryptUtils: ICryptUtils,
  30. @inject(ServiceIdentifiers.IOptions) options: IOptions
  31. ) {
  32. this.cryptUtils = cryptUtils;
  33. this.options = options;
  34. }
  35. /**
  36. * @param {string} obfuscatedCode
  37. * @param {string} sourceMap
  38. */
  39. public initialize (obfuscatedCode: string, sourceMap: string): void {
  40. this.obfuscatedCode = obfuscatedCode;
  41. this.sourceMap = sourceMap;
  42. }
  43. /**
  44. * @returns {string}
  45. */
  46. public getObfuscatedCode (): string {
  47. return this.correctObfuscatedCode();
  48. }
  49. /**
  50. * @returns {string}
  51. */
  52. public getSourceMap (): string {
  53. return this.sourceMap;
  54. }
  55. /**
  56. * @returns {string}
  57. */
  58. public toString (): string {
  59. return this.obfuscatedCode;
  60. }
  61. /**
  62. * @returns {string}
  63. */
  64. private correctObfuscatedCode (): string {
  65. if (!this.sourceMap) {
  66. return this.obfuscatedCode;
  67. }
  68. const sourceMapUrl: string = this.options.sourceMapBaseUrl + this.options.sourceMapFileName;
  69. let sourceMappingUrl: string = '//# sourceMappingURL=';
  70. switch (this.options.sourceMapMode) {
  71. case SourceMapMode.Inline:
  72. sourceMappingUrl += `data:application/json;base64,${this.cryptUtils.btoa(this.sourceMap)}`;
  73. break;
  74. case SourceMapMode.Separate:
  75. default:
  76. if (!sourceMapUrl) {
  77. return this.obfuscatedCode;
  78. }
  79. sourceMappingUrl += sourceMapUrl;
  80. }
  81. return `${this.obfuscatedCode}\n${sourceMappingUrl}`;
  82. }
  83. }