From d844832ffb16242200c3d80d7d914de1fa304f91 Mon Sep 17 00:00:00 2001 From: James Sumners Date: Wed, 17 Sep 2025 15:57:19 -0400 Subject: [PATCH] Add ability to dump patched code --- README.md | 15 +++++++++++++++ index.js | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/README.md b/README.md index 9b4c56d..9ec0cae 100644 --- a/README.md +++ b/README.md @@ -77,3 +77,18 @@ To use the CJS patch you can run your Node.js application with the `--require` f node --require cjs-patch.js your-app.js ``` +## Debugging + +The [debug module](https://www.npmjs.com/package/debug) is used to provide +insight into the patching process. Set `DEBUG='@apm-js-collab*'` to view these +logs. + +Additionally, any patched files can be written out by enabling dump mode. This +is done by setting the environment variable `TRACING_DUMP` to any value. By +default, it will write out file to the system's temporary directory as the +parent directory. The target parent directory can be configured by setting +the `TRACING_DUMP_DIR` environment variable to an absolute path. In either +case, the resolved filename of the module being patched is appended. For +example, if we are patching `lib/index.js` in the `foo` package, and we set +a base directory of `/tmp/dump/`, then the patched code will be written to +`/tmp/dump/foo/lib/index.js`. diff --git a/index.js b/index.js index e3b4cd7..f351f16 100644 --- a/index.js +++ b/index.js @@ -41,6 +41,9 @@ class ModulePatch { try { const transformedCode = transformer.transform(content, 'unknown') args[0] = transformedCode?.code + if (process.env.TRACING_DUMP) { + dump(args[0], filename) + } } catch (error) { debug('Error transforming module %s: %o', filename, error) } finally { @@ -63,5 +66,21 @@ class ModulePatch { } } +function dump(code, filename) { + const os = require('node:os') + const path = require('node:path') + const fs = require('node:fs') + + const base = process.env.TRACING_DUMP_DIR ?? os.tmpdir() + const dirname = path.dirname(filename) + const basename = path.basename(filename) + const targetDir = path.join(base, dirname) + const targetFile = path.join(targetDir, basename) + + debug('Dumping patched code to: %s', targetFile) + fs.mkdirSync(targetDir, { recursive: true }) + fs.writeFileSync(targetFile, code) +} + module.exports = ModulePatch