{"name":"@apm-js-collab/code-transformer","version":"0.14.0","license":"Apache-2.0","_id":"@apm-js-collab/code-transformer@0.14.0","maintainers":[{"name":"timfish","email":"tim@timfish.uk"},{"name":"bizob2828","email":"robert.evans25@gmail.com"}],"homepage":"https://github.com/nodejs/orchestrion-js#readme","bugs":{"url":"https://github.com/nodejs/orchestrion-js/issues"},"dist":{"shasum":"b4a43bfbc67047038eac1e276d1388285f714bbe","tarball":"http://registry-npm.ywwl.com/@apm-js-collab/code-transformer/download/@apm-js-collab/code-transformer-0.14.0.tgz","fileCount":10,"integrity":"sha512-6G+FETQ/VyRBsIkDDZ5sc9fb7O6d6W9rm8bZPHumISZw/6nwxvnS+VTyxd3sKM04aZwHG5hJIHb7VPdPCLieSQ==","signatures":[{"sig":"MEUCIQCSNvIqkC5BE5hJGwWHnKntxCqiS19xG7fvoR8xaLKkDwIgCJwPFOV3m6kIvE5Dq+Ed6fufLMYsHgzOCsg7pOIdgGk=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/@apm-js-collab%2fcode-transformer@0.14.0","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":58940,"size":16498,"noattachment":false,"key":"/@apm-js-collab/code-transformer/-/@apm-js-collab/code-transformer-0.14.0.tgz"},"main":"./index.js","types":"./index.d.ts","volta":{"node":"22.15.0"},"gitHead":"dc04dcfcae1f4b6099cf9a66900dbbae3729559b","scripts":{"lint":"eslint .","test":"node --test tests/tests.test.mjs","lint:fix":"eslint --fix .","test:watch":"node --watch --test tests/tests.test.mjs"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:a903b8be-dfd7-4572-9641-e47a8f837639"}},"repository":{"url":"git+https://github.com/nodejs/orchestrion-js.git","type":"git"},"_npmVersion":"11.15.0","description":"This is a library to aid in instrumenting Node.js libraries at build or load time.","directories":{},"_nodeVersion":"22.15.0","dependencies":{"astring":"^1.9.0","esquery":"^1.7.0","meriyah":"^6.1.4","semifies":"^1.0.0","source-map":"^0.6.0","@types/estree":"^1.0.8"},"_hasShrinkwrap":false,"devDependencies":{"eslint":"^9.39.4","typescript":"^5.8.3","@types/node":"^18.0.0","neostandard":"^0.13.0"},"_npmOperationalInternal":{"tmp":"tmp/code-transformer_0.14.0_1779901664555_0.045185961289793575","host":"s3://npm-registry-packages-npm-production"},"readme":"# Orchestrion-JS / `@apm-js-collab/code-transformer`\n\nThis is a library to aid in instrumenting Node.js libraries at build or load\ntime.\n\nIt uses an AST walker to inject code that calls Node.js\n[`TracingChannel`](https://nodejs.org/api/diagnostics_channel.html#class-tracingchannel).\n\nYou likely don't want to use this library directly; instead, consider using:\n\n- [`@apm-js-collab/tracing-hooks/`](https://github.com/apm-js-collab/tracing-hooks/)\n  - ESM and `require` hooks to instrument modules as they are loaded.\n- [`apm-js-collab/code-transformer-bundler-plugins`](https://github.com/apm-js-collab/code-transformer-bundler-plugins)\n  - Bundler plugins for webpack, Vite, Rollup and esbuild to instrument modules\n    at build time.\n\n## JavaScript\n\n`@apm-js-collab/code-transformer` exposes the library.\n\n### Usage\n\n```javascript\nimport * as codeTransformer from \"@apm-js-collab/code-transformer\";\n\n// The full instrumentation config\nconst instrumentation = {\n    // The name of the diagnostics channel\n    channelName: \"my-channel\",\n    // Define the module you'd like to inject tracing channels into\n    module: {\n        name: \"my-module\",\n        versionRange: \">=1.0.0\",\n        filePath: \"./dist/index.js\",\n    },\n    // Define the function you'd like to instrument\n    // (e.g., match a method named 'foo' that returns a Promise)\n    functionQuery: {\n        methodName: \"fetch\",\n        kind: \"Async\",\n    },\n};\n\n// Create an InstrumentationMatcher with an array of instrumentation configs\nconst matcher = codeTransformer.create([instrumentation]);\n\n// Get a transformer for a specific module\nconst transformer = matcher.getTransformer(\n    \"my-module\",\n    \"1.2.3\",\n    \"./dist/index.js\",\n);\n\nif (transformer === undefined) {\n    throw new Error(\"No transformer found for module\");\n}\n\n// Transform code\nconst inputCode = \"async function fetch() { return 42; }\";\nconst result = transformer.transform(inputCode, \"unknown\");\nconsole.log(result.code);\n```\n\n### Export Aliases\n\nWhen a module re-exports a function or class under a different name using\n`export { local as exported }`, you can target the **exported** name in your\n`FunctionQuery` by setting `isExportAlias: true`. The transformer will resolve\nthe alias to the local declaration before matching.\n\nFor example, given:\n\n```js\nfunction f(url) { return fetch(url); }\nexport { f as fetchAliased };\n```\n\nYou can target `fetchAliased` in your config:\n\n```js\nconst instrumentation = {\n    channelName: \"my-channel\",\n    module: { name: \"my-module\", versionRange: \">=1.0.0\", filePath: \"./index.mjs\" },\n    functionQuery: { functionName: \"fetchAliased\", kind: \"Async\", isExportAlias: true },\n};\n```\n\nThis also works for class exports (e.g., `export { MyClass as PublicClass }`).\n\n### Mutating the Return Value\n\nA subscriber can both observe or mutate a function's return value\nvia `message.result`. Reassigning `message.result` is useful when\na function returns another function (or object) that you need to\nwrap, like a factory that returns a per-request handler.\n\nFor **synchronous** functions, reassign `message.result` in the\n`end` handler:\n\n```js\nconst instrumentation = {\n    channelName: \"create-handler\",\n    module: { name: \"my-framework\", versionRange: \">=1.0.0\", filePath: \"lib/router.js\" },\n    functionQuery: { methodName: \"create\", kind: \"Sync\" },\n};\n```\n\n```js\nconst { tracingChannel } = require(\"node:diagnostics_channel\");\n\ntracingChannel(\"orchestrion:my-framework:create-handler\").subscribe({\n    end(message) {\n        const original = message.result;\n        // Replace the returned handler with a wrapped version.\n        message.result = function wrapped(...args) {\n            // ...start a span, etc.\n            return original.apply(this, args);\n        };\n    },\n});\n```\n\nFor **asynchronous** functions, reassign `message.result` in the\n`asyncEnd` handler to substitute the value the returned promise\nresolves to — for example, to wrap a function the promise resolves\nto:\n\n```js\nconst instrumentation = {\n    channelName: \"load-handler\",\n    module: { name: \"my-framework\", versionRange: \">=1.0.0\", filePath: \"lib/router.js\" },\n    functionQuery: { methodName: \"load\", kind: \"Async\" },\n};\n```\n\n```js\ntracingChannel(\"orchestrion:my-framework:load-handler\").subscribe({\n    asyncEnd(message) {\n        const original = message.result;\n        message.result = function wrapped(...args) {\n            // ...start a span, etc.\n            return original.apply(this, args);\n        };\n    },\n});\n```\n\n> [!INFO]\n>\n> Mutating the resolved value of an async function only works\n> when it returns a native `Promise` (`value instanceof\n> Promise`). Promise subclasses and other userland thenables are\n> side-chained and returned to the caller unchanged so that their\n> subclass-specific methods (e.g. `APIPromise.withResponse()`)\n> remain accessible; their resolved value therefore **cannot** be\n> mutated, and reassigning `message.result` for them has no\n> effect.\n\nOn the throw path the original error still propagates; the\nsubstituted return value only applies when the function returns (or\nresolves) normally. If no subscriber reassigns `message.result`, the\noriginal return value is preserved unchanged.\n\n### AST Query\n\nThe name-based `FunctionQuery` variants cover the common cases\n(named functions, class/object methods, expressions). When you\nneed to target a node they can't express, such as an **anonymous\nfunction returned by a factory** (a decorator factory, a\nper-request handler), you can set `astQuery` to a raw\n[esquery](https://github.com/estools/esquery) selector instead.\n\nWhen present, `astQuery` chooses the nodes to instrument and\ntakes precedence over `functionQuery`'s matching fields;\n`functionQuery` then only supplies behaviour (`kind`, `index`,\n`callbackIndex`) and may be omitted (it defaults to `kind:\n\"Sync\"`).\n\nFor example, to instrument the decorator returned by a factory:\n\n```js\nfunction Injectable(options) {\n    return (target) => { /* applied to the decorated class */ };\n}\n```\n\n```js\nconst instrumentation = {\n    channelName: \"injectable-apply\",\n    module: { name: \"@nestjs/common\", versionRange: \">=8.0.0\", filePath: \"decorators/core/injectable.decorator.js\" },\n    // Match the arrow returned from `Injectable`. There is no name to target!\n    astQuery: 'FunctionDeclaration[id.name=\"Injectable\"] ReturnStatement > ArrowFunctionExpression',\n    functionQuery: { kind: \"Sync\" },\n};\n```\n\nThe channel then fires each time the decorator is applied, with\nthe decorated target available as `message.arguments[0]`, which a\nsubscriber can mutate, for example to wrap prototype methods.\n\nAn `astQuery` is used verbatim, so it can match any node,\nincluding ones the name-based variants don't expose, such as\nanonymous or deeply nested functions. (Both name-based and\n`astQuery` matching work on synchronous and async functions\nalike.)\n\nIf an `astQuery` matches no nodes, the \"failed to find injection\npoints\" error includes the selector so it can be debugged.\n\n### Custom Transforms\n\nThe built-in operators (`traceSync`, `tracePromise`,\n`traceCallback`, `traceAuto`, selected by `functionQuery.kind`)\ncover diagnostics-channel tracing. When you need to rewrite a\nmatched node differently, register a custom operator with\n`matcher.addTransform(name, fn)` and reference it from a config's\n`transform` field. When `transform` is set it takes precedence\nover `functionQuery.kind`.\n\nA custom transform receives the same arguments an esquery\ntraversal yields, plus the merged instrumentation state, and\nmutates the matched node in place:\n\n```ts\ntype CustomTransform = (state, node, parent, ancestry) => void;\n```\n\n- `state` - the config merged with runtime fields\n  (`moduleVersion`, `moduleType`, `operator`, the resolved\n  `functionQuery`, …).\n- `node` - the matched AST node (the function/expression selected\n  by `functionQuery` or `astQuery`).\n- `parent`, `ancestry` - the parent node and full ancestor chain\n  (root last); `ancestry[ancestry.length - 1]` is the `Program`.\n\nA custom transform fully owns how `node` is rewritten. It is not\nrequired to inject a tracing channel at all.\n\n```js\nconst matcher = codeTransformer.create([\n    {\n        channelName: \"fetch\",\n        module: { name: \"my-module\", versionRange: \">=1.0.0\", filePath: \"index.js\" },\n        functionQuery: { functionName: \"fetch\", kind: \"Sync\" },\n        transform: \"myCustomTransform\",\n    },\n]);\n\nmatcher.addTransform(\"myCustomTransform\", (state, node) => {\n    // Mutate the matched node's AST however you need.\n    node.body.body.unshift(/* an ESTree statement */);\n});\n```\n\nRegistering a name matching a built-in transform (`traceSync`,\n`tracePromise`, `traceCallback`, `traceAuto`,\n`tracingChannelImport`, `tracingChannelDeclaration`) overrides it\neverywhere it is dispatched — including when one built-in invokes\nanother internally (e.g. the trace operators calling\n`tracingChannelDeclaration`, which in turn calls\n`tracingChannelImport`). `state.transforms` holds the merged map\n(built-ins plus registered overrides) used for this dispatch; to\ndelegate to the original built-in from an override, call it via\nthe `@apm-js-collab/code-transformer/lib/transforms` module\ndirectly.\n\n(The CLI accepts the same transforms via the `customTransforms`\nfield of a configuration module. See: [CLI Tool](#cli-tool).)\n\n### API Reference\n\n```ts\ntype ModuleType = \"esm\" | \"cjs\" | \"unknown\";\ntype FunctionKind = \"Sync\" | \"Async\" | \"Callback\" | \"Auto\";\n```\n\n#### **`FunctionQuery` Variants**\n\n```ts\ntype FunctionQuery =\n    | // Match class constructor\n    { className: string; index?: number | null; isExportAlias?: boolean }\n    | // Match class method\n    {\n        className: string;\n        methodName: string;\n        kind: FunctionKind;\n        index?: number | null;\n        callbackIndex?: number;\n        isExportAlias?: boolean;\n    }\n    | // Match method on objects\n    { methodName: string; kind: FunctionKind; index?: number | null; callbackIndex?: number }\n    | // Match standalone function\n    { functionName: string; kind: FunctionKind; index?: number | null; callbackIndex?: number; isExportAlias?: boolean }\n    | // Match arrow function or function expression\n    { expressionName: string; kind: FunctionKind; index?: number | null; callbackIndex?: number; isExportAlias?: boolean };\n    | // Match private class methods\n    { className: string; privateMethodName: string; kind: FunctionKind; index?: number | null; callbackIndex?: number };\n```\n\n#### **`ModuleMatcher`**\n\n```ts\ntype ModuleMatcher = {\n    /** Module name */\n    name: string; \n    /** Matching semver range */\n    versionRange: string;\n    /** \n     * Relative Unix-style path to the file from the module root (e.g. \"lib/index.js\") \n     * Or a regular expression to test against the Unix-style path.\n     */\n    filePath: string | RegExp;\n};\n```\n\n#### **`InstrumentationConfig`**\n\n```ts\n// Behaviour-only fields, used when `astQuery` does the matching.\ntype FunctionBehavior = {\n    kind?: FunctionKind;\n    index?: number | null;\n    callbackIndex?: number;\n};\n\ntype InstrumentationConfig =\n    | {\n        channelName: string; // Name of the diagnostics channel\n        module: ModuleMatcher;\n        functionQuery: FunctionQuery; // Name-based matching\n        astQuery?: string; // Raw esquery selector; takes precedence over functionQuery matching\n        transform?: string; // Name of a custom transform registered via addTransform\n    }\n    | {\n        channelName: string;\n        module: ModuleMatcher;\n        astQuery: string; // Raw esquery selector chooses the node(s)\n        functionQuery?: FunctionBehavior; // Behaviour only; matching fields ignored\n        transform?: string;\n    };\n```\n\n### Functions\n\n```ts\ncreate(configs: InstrumentationConfig[], dcModule?: string | null): InstrumentationMatcher;\n```\n\nCreate a matcher for one or more instrumentation configurations.\n\n- `configs` - Array of instrumentation configurations.\n- `dcModule` - Optional module to import `diagnostics_channel` API from.\n\n#### **`InstrumentationMatcher`**\n\n```ts\ngetTransformer(moduleName: string, version: string, filePath: string): Transformer | undefined;\n```\n\nGets a transformer for a specific module and file.\n\nReturns a `Transformer` for the given module, or `undefined` if there were no\nmatching instrumentation configurations.\n\n- `moduleName` - Name of the module.\n- `version` - Version of the module.\n- `filePath` - Relative Unix-style path to the file from the module root (e.g. `\"lib/index.js\"`). Windows-style backslash paths are also accepted and will be normalized automatically.\n\n```ts\naddTransform(name: string, fn: CustomTransform): void;\n```\n\nRegisters a custom transform operator under `name`, referenced\nfrom a config's `transform` field. See [Custom\nTransforms](#custom-transforms).\n\n- `name` - Operator name (also used as the config's `transform`\n  value).\n- `fn` - `(state, node, parent, ancestry) => void`; mutates the\n  matched node.\n\n#### **`Transformer`**\n\n```ts\ntransform(code: string | Buffer, moduleType: ModuleType, sourcemap?: string | undefined): TransformOutput;\n```\n\nTransforms the code, injecting tracing as configured.\n\nReturns `{ code, map }`. `map` will be undefined if no sourcemap was supplied.\n\n- `code` - The JavaScript code to transform.\n- `moduleType` - The type of module being transformed.\n- `sourcemap` - Optional existing source map for the code.\n\n## CLI Tool\n\nThe package includes a CLI tool for applying transformations to source files:\n\n```bash\nnpx @apm-js-collab/code-transformer transformer.js source-file.js\n```\n\n### CLI Usage\n\nThe CLI tool takes two arguments:\n1. `transformer.js` - A file that exports instrumentation configuration(s)\n2. `source-file.js` - The source file to transform (can be any path, including node_modules)\n\nThe transformed code is written to stdout, which you can redirect to a file or pipe to other commands.\n\n### CLI Example\n\nCreate a transformer configuration file:\n\n```javascript\n// my-transformer.js\nmodule.exports = [{\n  channelName: 'my-fetch-channel',\n  module: {\n    name: 'my-module',\n    versionRange: '>=1.0.0',\n    filePath: 'index.js'\n  },\n  functionQuery: {\n    functionName: 'fetch',\n    kind: 'Async'\n  }\n}]\n```\n\nApply the transformation:\n\n```bash\nnpx @apm-js-collab/code-transformer my-transformer.js lib/index.js > instrumented.js\n```\n\nThe transformer configuration file can also export an object with additional options:\n\n```javascript\nmodule.exports = {\n  configs: [/* array of configs */],\n  dcModule: './custom-diagnostics-channel.js', // optional custom dc module\n  customTransforms: {  // optional custom transform functions\n    myCustomTransform: (state, node) => {\n      // custom AST transformation logic\n    }\n  }\n}\n```\n\n## License\n\nSee LICENSE\n","publish_time":1779901664712,"_cnpm_publish_time":1779901664712,"dist-tags":{"latest":"0.19.0"}}