|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const rewriterPackage = process.env.NPM_REWRITER === 'true' ? '@datadog/wasm-js-rewriter' : '../' |
| 4 | +const { addEditedFile } = require('./edited-files-cache') |
| 5 | +const { Rewriter, getPrepareStackTrace } = require(rewriterPackage) |
| 6 | +const path = require('path') |
| 7 | +const Module = require('module') |
| 8 | + |
| 9 | +let rewriter |
| 10 | +let originalPrepareStackTrace = Error.prepareStackTrace |
| 11 | + |
| 12 | +const CSI_METHODS = [ |
| 13 | + { src: 'plusOperator', operator: true }, |
| 14 | + { src: 'substring' }, |
| 15 | + { src: 'trim' }, |
| 16 | + { src: 'trimStart' }, |
| 17 | + { src: 'trimEnd' }, |
| 18 | + { src: 'trimLeft' }, |
| 19 | + { src: 'trimRight' }, |
| 20 | + { src: 'toLowerCase' }, |
| 21 | + { src: 'toLocaleLowerCase' }, |
| 22 | + { src: 'toUpperCase' }, |
| 23 | + { src: 'toLocaleUpperCase' }, |
| 24 | + { src: 'replace' }, |
| 25 | + { src: 'replaceAll' }, |
| 26 | + { src: 'slice' }, |
| 27 | + { src: 'concat' } |
| 28 | +] |
| 29 | + |
| 30 | +function isFlagPresent (flag) { |
| 31 | + return process.env.NODE_OPTIONS?.includes(flag) || |
| 32 | + process.execArgv?.some(arg => arg.includes(flag)) |
| 33 | +} |
| 34 | + |
| 35 | +function initRewriter () { |
| 36 | + rewriter = new Rewriter({ |
| 37 | + csiMethods: CSI_METHODS, |
| 38 | + telemetryVerbosity: 'Debug', |
| 39 | + chainSourceMap: isFlagPresent('--enable-source-maps') |
| 40 | + }) |
| 41 | + |
| 42 | + if (rewriter) { |
| 43 | + Object.defineProperty(global.Error, 'prepareStackTrace', getPrepareStackTraceAccessor()) |
| 44 | + Module.prototype._compile = getCompileMethodFn(Module.prototype._compile) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +function getPrepareStackTraceAccessor () { |
| 49 | + let actual = getPrepareStackTrace(originalPrepareStackTrace) |
| 50 | + return { |
| 51 | + get () { |
| 52 | + return actual |
| 53 | + }, |
| 54 | + set (value) { |
| 55 | + actual = getPrepareStackTrace(value) |
| 56 | + originalPrepareStackTrace = value |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +function getCompileMethodFn (compileMethod) { |
| 62 | + return function (content, filename) { |
| 63 | + try { |
| 64 | + if (filename.indexOf(path.join('integration-test', 'requires')) > -1) { |
| 65 | + const response = rewriter.rewrite(content, filename, ['iast']) |
| 66 | + content = response.content |
| 67 | + addEditedFile(filename) |
| 68 | + } |
| 69 | + } catch (e) { |
| 70 | + // eslint-disable-next-line no-console |
| 71 | + console.error(e) |
| 72 | + } |
| 73 | + return compileMethod.apply(this, [content, filename]) |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +initRewriter() |
0 commit comments