opentelemetry-esbuild-plugin-node 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] Drew Corlin
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,151 @@
1
+ # OpenTelemetry Esbuild for Node
2
+
3
+ [![NPM Published Version][npm-img]][npm-url]
4
+ [![Apache License][license-image]][license-url]
5
+
6
+ ## About
7
+
8
+ This module provides a way to auto instrument any Node application to capture telemetry from a number of popular libraries and frameworks, via an [esbuild](https://esbuild.github.io/) plugin.
9
+ You can export the telemetry data in a variety of formats. Exporters, samplers, and more can be configured via [environment variables][env-var-url].
10
+ The net result is the ability to gather telemetry data from a Node application without any code changes.
11
+
12
+ This module also provides a simple way to manually initialize multiple Node instrumentations for use with the OpenTelemetry SDK.
13
+
14
+ Compatible with OpenTelemetry JS API and SDK `1.0+`.
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install --save @opentelemetry/esbuild-plugin-node
20
+ ```
21
+
22
+ ## Usage: Esbuild plugin
23
+
24
+ This module includes instrumentation for all supported instrumentations and [all available data exporters][exporter-url].
25
+ It provides a completely automatic, out-of-the-box experience.
26
+ Please see the [Supported Instrumentations](#supported-instrumentations) section for more information.
27
+
28
+ Enable auto instrumentation by configuring it in your esbuild script:
29
+
30
+ ```javascript
31
+ const { openTelemetryPlugin } = require('@opentelemetry/esbuild-plugin-node');
32
+ const { build } = require('esbuild');
33
+
34
+ build({
35
+ entryPoints: ['src/server.ts'],
36
+ bundle: true,
37
+ outfile: 'dist/server.js',
38
+ target: 'node20',
39
+ platform: 'node',
40
+ sourcemap: true,
41
+ plugins: [openTelemetryPlugin()],
42
+ });
43
+ ```
44
+
45
+ ## Usage: Instrumentation Initialization
46
+
47
+ OpenTelemetry Meta Packages for Node automatically loads instrumentations for Node builtin modules and common packages.
48
+
49
+ Enable auto instrumentation by configuring it in your esbuild script:
50
+
51
+ ```javascript
52
+ const { openTelemetryPlugin } = require('@opentelemetry/esbuild-plugin-node');
53
+ const { build } = require('esbuild');
54
+
55
+ build({
56
+ entryPoints: ['src/server.ts'],
57
+ bundle: true,
58
+ outfile: 'dist/server.js',
59
+ target: 'node20',
60
+ platform: 'node',
61
+ sourcemap: true,
62
+ plugins: [openTelemetryPlugin()],
63
+ });
64
+ ```
65
+
66
+ Custom configuration for each of the instrumentations can be passed to the plugin, by providing an object with the name of the instrumentation as a key, and its configuration as the value.
67
+
68
+ ```javascript
69
+ const { openTelemetryPlugin } = require('@opentelemetry/esbuild-plugin-node');
70
+ const { build } = require('esbuild');
71
+
72
+ build({
73
+ entryPoints: ['src/server.ts'],
74
+ bundle: true,
75
+ outfile: 'dist/server.js',
76
+ target: 'node20',
77
+ platform: 'node',
78
+ sourcemap: true,
79
+ plugins: [
80
+ openTelemetryPlugin({
81
+ instrumentationConfig: {
82
+ '@opentelemetry/instrumentation-aws-sdk': {
83
+ suppressInternalInstrumentation: true,
84
+ },
85
+ },
86
+ }),
87
+ ],
88
+ });
89
+ ```
90
+
91
+ This esbuild script will instrument non-builtin packages but will not configure the rest of the OpenTelemetry SDK to export traces
92
+ from your application. To do that you must also configure the SDK.
93
+
94
+ The esbuild script currently only patches non-builtin modules (more specifically, modules in [opentelemetry-js-contrib](https://github.com/open-telemetry/opentelemetry-js-contrib)), so this is also the place to configure the instrumentation
95
+ for builtins or add any additional instrumentations.
96
+
97
+ ### Gotchas
98
+
99
+ There are limitations to the configuration options for each package. Most notably, any functions (like `ignoreIncomingRequestHook` in the example) are not allowed to be passed in to plugins.
100
+
101
+ The reason for this is that the current mechanism of instrumenting packages involves stringifying the instrumentation configs, which does not account for any external scoped dependencies, and thus creates subtle opportunities for bugs.
102
+
103
+ ```javascript
104
+ const {
105
+ getNodeAutoInstrumentations,
106
+ } = require('@opentelemetry/auto-instrumentations-node');
107
+ const {
108
+ AsyncHooksContextManager,
109
+ } = require('@opentelemetry/context-async-hooks');
110
+ const {
111
+ OTLPTraceExporter,
112
+ } = require('@opentelemetry/exporter-trace-otlp-http');
113
+ const { NodeSDK } = require('@opentelemetry/sdk-node');
114
+
115
+ const instrumentations = getNodeAutoInstrumentations();
116
+
117
+ const sdk = new NodeSDK({
118
+ traceExporter: new OTLPTraceExporter(),
119
+ contextManager: new AsyncHooksContextManager().enable(),
120
+ instrumentations,
121
+ });
122
+
123
+ sdk.start();
124
+
125
+ process.on('SIGTERM', () => {
126
+ sdk.shutdown().finally(() => process.exit(0));
127
+ });
128
+ ```
129
+
130
+ ## Supported instrumentations
131
+
132
+ See [@opentelemetry/auto-instrumentations-node](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/metapackages/auto-instrumentations-node) for the supported packages.
133
+
134
+ Note that Node.js builtin modules will not be patched by this plugin.
135
+
136
+ ## Useful links
137
+
138
+ - For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
139
+ - For more about OpenTelemetry JavaScript: <https://github.com/open-telemetry/opentelemetry-js>
140
+ - For more about Esbuild plugins: <https://esbuild.github.io/plugins/>
141
+
142
+ ## License
143
+
144
+ APACHE 2.0 - See [LICENSE][license-url] for more information.
145
+
146
+ [license-url]: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/LICENSE
147
+ [license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
148
+ [npm-url]: https://www.npmjs.com/package/@opentelemetry/auto-instrumentations-node
149
+ [npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fauto-instrumentations-node.svg
150
+ [env-var-url]: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md#general-sdk-configuration
151
+ [exporter-url]: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md#otlp-exporter
@@ -0,0 +1,3 @@
1
+ import type { ModuleParams } from './types';
2
+ export declare function wrapModule(originalSource: string, { path, moduleVersion, oTelInstrumentationPackage, oTelInstrumentationClass, instrumentationName, oTelInstrumentationConstructorArgs, }: ModuleParams): string;
3
+ //# sourceMappingURL=common.d.ts.map
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.wrapModule = void 0;
19
+ function wrapModule(originalSource, { path, moduleVersion, oTelInstrumentationPackage, oTelInstrumentationClass, instrumentationName, oTelInstrumentationConstructorArgs = '', }) {
20
+ return `
21
+ (function() {
22
+ ${originalSource}
23
+ })(...arguments);
24
+ {
25
+ const { diag } = require('@opentelemetry/api');
26
+
27
+ try {
28
+ let mod = module.exports;
29
+
30
+ const { satisfies } = require('semver');
31
+ const { ${oTelInstrumentationClass} } = require('${oTelInstrumentationPackage}');
32
+ const instrumentations = new ${oTelInstrumentationClass}(${oTelInstrumentationConstructorArgs}).getModuleDefinitions();
33
+
34
+ for (const instrumentation of instrumentations.filter(i => i.name === '${instrumentationName}')) {
35
+ if (!instrumentation.supportedVersions.some(v => satisfies('${moduleVersion}', v))) {
36
+ diag.debug('Skipping instrumentation ${instrumentationName}, because module version ${moduleVersion} does not match supported versions ' + instrumentation.supportedVersions.join(','));
37
+ continue;
38
+ }
39
+
40
+ if (instrumentation.patch) {
41
+ diag.debug('Applying instrumentation patch ${instrumentationName} via esbuild-plugin-node');
42
+ mod = instrumentation.patch(mod)
43
+ }
44
+
45
+ if (instrumentation.files?.length) {
46
+ for (const file of instrumentation.files.filter(f => f.name === '${path}')) {
47
+ if (!file.supportedVersions.some(v => satisfies('${moduleVersion}', v))) {
48
+ diag.debug('Skipping instrumentation for ${path}@${moduleVersion} because it does not match supported versions' + file.supportedVersions.join(','));
49
+ continue;
50
+ }
51
+ diag.debug('Applying instrumentation patch to ${path}@${moduleVersion} via esbuild-plugin-node');
52
+ mod = file.patch(mod, '${moduleVersion}');
53
+ }
54
+ }
55
+ }
56
+
57
+ module.exports = mod;
58
+ } catch (e) {
59
+ diag.error('Error applying instrumentation ${instrumentationName}', e);
60
+ }
61
+ }
62
+ `;
63
+ }
64
+ exports.wrapModule = wrapModule;
65
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAIH,SAAgB,UAAU,CACxB,cAAsB,EACtB,EACE,IAAI,EACJ,aAAa,EACb,0BAA0B,EAC1B,wBAAwB,EACxB,mBAAmB,EACnB,kCAAkC,GAAG,EAAE,GAC1B;IAEf,OAAO;;IAEL,cAAc;;;;;;;;;cASJ,wBAAwB,iBAAiB,0BAA0B;mCAC9C,wBAAwB,IAAI,kCAAkC;;6EAEpB,mBAAmB;oEAC5B,aAAa;+CAClC,mBAAmB,4BAA4B,aAAa;;;;;qDAKtD,mBAAmB;;;;;2EAKG,IAAI;6DAClB,aAAa;uDACnB,IAAI,IAAI,aAAa;;;0DAGlB,IAAI,IAAI,aAAa;mCAC5C,aAAa;;;;;;;iDAOC,mBAAmB;;;CAGnE,CAAC;AACF,CAAC;AAtDD,gCAsDC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ModuleParams } from './types';\n\nexport function wrapModule(\n originalSource: string,\n {\n path,\n moduleVersion,\n oTelInstrumentationPackage,\n oTelInstrumentationClass,\n instrumentationName,\n oTelInstrumentationConstructorArgs = '',\n }: ModuleParams\n) {\n return `\n(function() {\n ${originalSource}\n})(...arguments);\n{\n const { diag } = require('@opentelemetry/api');\n\n try {\n let mod = module.exports;\n\n const { satisfies } = require('semver');\n const { ${oTelInstrumentationClass} } = require('${oTelInstrumentationPackage}');\n const instrumentations = new ${oTelInstrumentationClass}(${oTelInstrumentationConstructorArgs}).getModuleDefinitions();\n\n for (const instrumentation of instrumentations.filter(i => i.name === '${instrumentationName}')) {\n if (!instrumentation.supportedVersions.some(v => satisfies('${moduleVersion}', v))) {\n diag.debug('Skipping instrumentation ${instrumentationName}, because module version ${moduleVersion} does not match supported versions ' + instrumentation.supportedVersions.join(','));\n continue;\n }\n\n if (instrumentation.patch) {\n diag.debug('Applying instrumentation patch ${instrumentationName} via esbuild-plugin-node');\n mod = instrumentation.patch(mod)\n }\n\n if (instrumentation.files?.length) {\n for (const file of instrumentation.files.filter(f => f.name === '${path}')) {\n if (!file.supportedVersions.some(v => satisfies('${moduleVersion}', v))) {\n diag.debug('Skipping instrumentation for ${path}@${moduleVersion} because it does not match supported versions' + file.supportedVersions.join(','));\n continue;\n }\n diag.debug('Applying instrumentation patch to ${path}@${moduleVersion} via esbuild-plugin-node');\n mod = file.patch(mod, '${moduleVersion}');\n }\n }\n }\n\n module.exports = mod;\n } catch (e) {\n diag.error('Error applying instrumentation ${instrumentationName}', e);\n }\n}\n`;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export { otelPackageToInstrumentationConfig } from './main';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.otelPackageToInstrumentationConfig = void 0;
19
+ var main_1 = require("./main");
20
+ Object.defineProperty(exports, "otelPackageToInstrumentationConfig", { enumerable: true, get: function () { return main_1.otelPackageToInstrumentationConfig; } });
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/config/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,+BAA4D;AAAnD,0HAAA,kCAAkC,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { otelPackageToInstrumentationConfig } from './main';\n"]}
@@ -0,0 +1,18 @@
1
+ import { InstrumentationModuleDefinition } from '@opentelemetry/instrumentation';
2
+ import { EsbuildInstrumentationConfigMap } from '../types';
3
+ export declare const instrumentationModuleDefinitions: InstrumentationModuleDefinition[];
4
+ export declare function getOtelPackageToInstrumentationConfig(): Record<string, {
5
+ oTelInstrumentationPackage: keyof EsbuildInstrumentationConfigMap;
6
+ oTelInstrumentationClass: string;
7
+ configGenerator: <T extends {
8
+ enabled?: boolean | undefined;
9
+ }>(config?: T | undefined) => string | undefined;
10
+ }>;
11
+ export declare const otelPackageToInstrumentationConfig: Record<string, {
12
+ oTelInstrumentationPackage: keyof EsbuildInstrumentationConfigMap;
13
+ oTelInstrumentationClass: string;
14
+ configGenerator: <T extends {
15
+ enabled?: boolean | undefined;
16
+ }>(config?: T | undefined) => string | undefined;
17
+ }>;
18
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.otelPackageToInstrumentationConfig = exports.getOtelPackageToInstrumentationConfig = exports.instrumentationModuleDefinitions = void 0;
19
+ const instrumentation_1 = require("@opentelemetry/instrumentation");
20
+ const auto_instrumentations_node_1 = require("@opentelemetry/auto-instrumentations-node");
21
+ const instrumentations = (0, auto_instrumentations_node_1.getNodeAutoInstrumentations)();
22
+ const instrumentationModuleDefinitionsByInstrumentationName = Object.fromEntries(instrumentations.map(i => [i.instrumentationName, getModuleDefinitions(i)]));
23
+ exports.instrumentationModuleDefinitions = Object.values(instrumentationModuleDefinitionsByInstrumentationName).flat();
24
+ function getModuleDefinitions(instrumentation) {
25
+ var _a;
26
+ if (instrumentation instanceof instrumentation_1.InstrumentationBase) {
27
+ return (_a = instrumentation.getModuleDefinitions()) !== null && _a !== void 0 ? _a : [];
28
+ }
29
+ return [];
30
+ }
31
+ function configGenerator(config) {
32
+ if (!config)
33
+ return;
34
+ return JSON.stringify(Object.fromEntries(Object.entries(config).filter(([, v]) => typeof v !== 'function')));
35
+ }
36
+ function getOtelPackageToInstrumentationConfig() {
37
+ const otelPackageToInstrumentationConfig = {};
38
+ for (const instrumentation of instrumentations) {
39
+ const moduleDefinitions = instrumentationModuleDefinitionsByInstrumentationName[instrumentation.instrumentationName];
40
+ for (const instrumentationModuleDefinition of moduleDefinitions) {
41
+ // For some reason @opentelemetry/instrumentation-generic-pool reports its name as just Instrumentation
42
+ // TODO: See if this goes away with an upgrade
43
+ if (instrumentation.constructor.name === 'Instrumentation')
44
+ continue;
45
+ otelPackageToInstrumentationConfig[instrumentationModuleDefinition.name] =
46
+ {
47
+ oTelInstrumentationPackage: instrumentation.instrumentationName,
48
+ oTelInstrumentationClass: instrumentation.constructor.name,
49
+ configGenerator,
50
+ };
51
+ }
52
+ }
53
+ return otelPackageToInstrumentationConfig;
54
+ }
55
+ exports.getOtelPackageToInstrumentationConfig = getOtelPackageToInstrumentationConfig;
56
+ exports.otelPackageToInstrumentationConfig = getOtelPackageToInstrumentationConfig();
57
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../../../src/config/main.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,oEAIwC;AAGxC,0FAAwF;AAExF,MAAM,gBAAgB,GAAG,IAAA,wDAA2B,GAAE,CAAC;AACvD,MAAM,qDAAqD,GACzD,MAAM,CAAC,WAAW,CAChB,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,mBAAmB,EAAE,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC,CAC5E,CAAC;AAES,QAAA,gCAAgC,GAAG,MAAM,CAAC,MAAM,CAC3D,qDAAqD,CACtD,CAAC,IAAI,EAAE,CAAC;AAET,SAAS,oBAAoB,CAC3B,eAAgC;;IAEhC,IAAI,eAAe,YAAY,qCAAmB,EAAE;QAClD,OAAO,MAAA,eAAe,CAAC,oBAAoB,EAAE,mCAAI,EAAE,CAAC;KACrD;IAED,OAAO,EAAE,CAAC;AACZ,CAAC;AAED,SAAS,eAAe,CACtB,MAAU;IAEV,IAAI,CAAC,MAAM;QAAE,OAAO;IACpB,OAAO,IAAI,CAAC,SAAS,CACnB,MAAM,CAAC,WAAW,CAChB,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,UAAU,CAAC,CAClE,CACF,CAAC;AACJ,CAAC;AAED,SAAgB,qCAAqC;IACnD,MAAM,kCAAkC,GASpC,EAAE,CAAC;IACP,KAAK,MAAM,eAAe,IAAI,gBAAgB,EAAE;QAC9C,MAAM,iBAAiB,GACrB,qDAAqD,CACnD,eAAe,CAAC,mBAAmB,CACpC,CAAC;QAEJ,KAAK,MAAM,+BAA+B,IAAI,iBAAiB,EAAE;YAC/D,uGAAuG;YACvG,8CAA8C;YAC9C,IAAI,eAAe,CAAC,WAAW,CAAC,IAAI,KAAK,iBAAiB;gBAAE,SAAS;YACrE,kCAAkC,CAAC,+BAA+B,CAAC,IAAI,CAAC;gBACtE;oBACE,0BAA0B,EACxB,eAAe,CAAC,mBAA4D;oBAC9E,wBAAwB,EAAE,eAAe,CAAC,WAAW,CAAC,IAAI;oBAC1D,eAAe;iBAChB,CAAC;SACL;KACF;IACD,OAAO,kCAAkC,CAAC;AAC5C,CAAC;AA/BD,sFA+BC;AAEY,QAAA,kCAAkC,GAC7C,qCAAqC,EAAE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Instrumentation,\n InstrumentationBase,\n InstrumentationModuleDefinition,\n} from '@opentelemetry/instrumentation';\n\nimport { EsbuildInstrumentationConfigMap } from '../types';\nimport { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\n\nconst instrumentations = getNodeAutoInstrumentations();\nconst instrumentationModuleDefinitionsByInstrumentationName =\n Object.fromEntries(\n instrumentations.map(i => [i.instrumentationName, getModuleDefinitions(i)])\n );\n\nexport const instrumentationModuleDefinitions = Object.values(\n instrumentationModuleDefinitionsByInstrumentationName\n).flat();\n\nfunction getModuleDefinitions(\n instrumentation: Instrumentation\n): InstrumentationModuleDefinition[] {\n if (instrumentation instanceof InstrumentationBase) {\n return instrumentation.getModuleDefinitions() ?? [];\n }\n\n return [];\n}\n\nfunction configGenerator<T extends { enabled?: boolean }>(\n config?: T\n): string | undefined {\n if (!config) return;\n return JSON.stringify(\n Object.fromEntries(\n Object.entries(config).filter(([, v]) => typeof v !== 'function')\n )\n );\n}\n\nexport function getOtelPackageToInstrumentationConfig() {\n const otelPackageToInstrumentationConfig: Record<\n string,\n {\n oTelInstrumentationPackage: keyof EsbuildInstrumentationConfigMap;\n oTelInstrumentationClass: string;\n configGenerator: <T extends { enabled?: boolean }>(\n config?: T\n ) => string | undefined;\n }\n > = {};\n for (const instrumentation of instrumentations) {\n const moduleDefinitions =\n instrumentationModuleDefinitionsByInstrumentationName[\n instrumentation.instrumentationName\n ];\n\n for (const instrumentationModuleDefinition of moduleDefinitions) {\n // For some reason @opentelemetry/instrumentation-generic-pool reports its name as just Instrumentation\n // TODO: See if this goes away with an upgrade\n if (instrumentation.constructor.name === 'Instrumentation') continue;\n otelPackageToInstrumentationConfig[instrumentationModuleDefinition.name] =\n {\n oTelInstrumentationPackage:\n instrumentation.instrumentationName as keyof EsbuildInstrumentationConfigMap,\n oTelInstrumentationClass: instrumentation.constructor.name,\n configGenerator,\n };\n }\n }\n return otelPackageToInstrumentationConfig;\n}\n\nexport const otelPackageToInstrumentationConfig =\n getOtelPackageToInstrumentationConfig();\n"]}
@@ -0,0 +1,7 @@
1
+ import { EsbuildInstrumentationConfigMap } from '../types';
2
+ export interface InstrumentationConfig<T extends keyof EsbuildInstrumentationConfigMap> {
3
+ oTelInstrumentationPackage: T;
4
+ oTelInstrumentationClass: string;
5
+ configGenerator: (config?: EsbuildInstrumentationConfigMap[T]) => string | undefined;
6
+ }
7
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/config/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EsbuildInstrumentationConfigMap } from '../types';\n\nexport interface InstrumentationConfig<\n T extends keyof EsbuildInstrumentationConfigMap\n> {\n oTelInstrumentationPackage: T;\n oTelInstrumentationClass: string;\n configGenerator: (\n config?: EsbuildInstrumentationConfigMap[T]\n ) => string | undefined;\n}\n"]}
@@ -0,0 +1,3 @@
1
+ export { openTelemetryPlugin } from './plugin';
2
+ export { OpenTelemetryPluginParams } from './types';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.openTelemetryPlugin = void 0;
19
+ var plugin_1 = require("./plugin");
20
+ Object.defineProperty(exports, "openTelemetryPlugin", { enumerable: true, get: function () { return plugin_1.openTelemetryPlugin; } });
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,mCAA+C;AAAtC,6GAAA,mBAAmB,OAAA","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { openTelemetryPlugin } from './plugin';\nexport { OpenTelemetryPluginParams } from './types';\n"]}
@@ -0,0 +1,4 @@
1
+ import { OpenTelemetryPluginParams } from './types';
2
+ import { Plugin } from 'esbuild';
3
+ export declare function openTelemetryPlugin(pluginConfig?: OpenTelemetryPluginParams): Plugin;
4
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.openTelemetryPlugin = void 0;
19
+ const path_1 = require("path");
20
+ const main_1 = require("./config/main");
21
+ const module_1 = require("module");
22
+ const promises_1 = require("fs/promises");
23
+ const semver_1 = require("semver");
24
+ const common_1 = require("./common");
25
+ const NODE_MODULES = 'node_modules/';
26
+ const BUILT_INS = new Set(module_1.builtinModules.flatMap(b => [b, `node:${b}`]));
27
+ function openTelemetryPlugin(pluginConfig) {
28
+ return {
29
+ name: 'open-telemetry',
30
+ setup(build) {
31
+ build.onResolve({ filter: /.*/ }, async (args) => {
32
+ if (shouldIgnoreModule({
33
+ namespace: args.namespace,
34
+ path: args.path,
35
+ importer: args.importer,
36
+ externalModules: pluginConfig === null || pluginConfig === void 0 ? void 0 : pluginConfig.externalModules,
37
+ pathPrefixesToIgnore: pluginConfig === null || pluginConfig === void 0 ? void 0 : pluginConfig.pathPrefixesToIgnore,
38
+ })) {
39
+ return;
40
+ }
41
+ let path;
42
+ let extractedModule;
43
+ try {
44
+ const result = extractPackageAndModulePath(args.path, args.resolveDir);
45
+ path = result.path;
46
+ extractedModule = result.extractedModule;
47
+ }
48
+ catch (e) {
49
+ // Some libraries like `mongodb` require optional dependencies, which may not be present and their absence doesn't break the code
50
+ // Currently esbuild doesn't provide any better way to handle this in plugins: https://github.com/evanw/esbuild/issues/1127
51
+ }
52
+ // If it's a local import, don't patch it
53
+ if (!extractedModule)
54
+ return;
55
+ // We'll rely on the OTel auto-instrumentation at runtime to patch builtin modules
56
+ if (isBuiltIn(args.path, extractedModule))
57
+ return;
58
+ const moduleVersion = await getModuleVersion({
59
+ extractedModule,
60
+ resolveDir: args.resolveDir,
61
+ build,
62
+ });
63
+ if (!moduleVersion)
64
+ return;
65
+ // See if we have an instrumentation registered for this package
66
+ const matchingInstrumentation = getInstrumentation({
67
+ extractedModule,
68
+ moduleVersion,
69
+ path: args.path,
70
+ });
71
+ if (!matchingInstrumentation)
72
+ return;
73
+ const pluginData = {
74
+ extractedModule,
75
+ moduleVersion,
76
+ shouldPatchPackage: true,
77
+ instrumentationName: matchingInstrumentation.name,
78
+ };
79
+ return { path, pluginData };
80
+ });
81
+ build.onLoad({ filter: /.*/ }, async ({ path, pluginData }) => {
82
+ var _a;
83
+ // Ignore any packages that don't have an instrumentation registered for them
84
+ if (!(pluginData === null || pluginData === void 0 ? void 0 : pluginData.shouldPatchPackage))
85
+ return;
86
+ const contents = await (0, promises_1.readFile)(path);
87
+ const config = main_1.otelPackageToInstrumentationConfig[pluginData.instrumentationName];
88
+ if (!config)
89
+ return;
90
+ // console.log('config is', config);
91
+ const packageConfig = (_a = pluginConfig === null || pluginConfig === void 0 ? void 0 : pluginConfig.instrumentationConfig) === null || _a === void 0 ? void 0 : _a[config.oTelInstrumentationPackage];
92
+ const extractedModule = pluginData.extractedModule;
93
+ return {
94
+ contents: (0, common_1.wrapModule)(contents.toString(), {
95
+ path: (0, path_1.join)(extractedModule.package || '', extractedModule.path || ''),
96
+ moduleVersion: pluginData.moduleVersion,
97
+ instrumentationName: pluginData.instrumentationName,
98
+ oTelInstrumentationClass: config.oTelInstrumentationClass,
99
+ oTelInstrumentationPackage: config.oTelInstrumentationPackage,
100
+ oTelInstrumentationConstructorArgs: config.configGenerator(packageConfig),
101
+ }),
102
+ resolveDir: (0, path_1.dirname)(path),
103
+ };
104
+ });
105
+ },
106
+ };
107
+ }
108
+ exports.openTelemetryPlugin = openTelemetryPlugin;
109
+ /**
110
+ * For a given full path to a module,
111
+ * return the package name it belongs to and the local path to the module
112
+ * input: '/foo/node_modules/@co/stuff/foo/bar/baz.js'
113
+ * output: { package: '@co/stuff', path: 'foo/bar/baz.js' }
114
+ */
115
+ function extractPackageAndModulePath(originalPath, resolveDir) {
116
+ // @see https://github.com/nodejs/node/issues/47000
117
+ const path = require.resolve(originalPath === '.' ? './' : originalPath === '..' ? '../' : originalPath, { paths: [resolveDir] });
118
+ const nodeModulesIndex = path.lastIndexOf(NODE_MODULES);
119
+ if (nodeModulesIndex < 0)
120
+ return { path, extractedModule: null };
121
+ const subPath = path.substring(nodeModulesIndex + NODE_MODULES.length);
122
+ const firstSlashIndex = subPath.indexOf('/');
123
+ if (!subPath.startsWith('@')) {
124
+ return {
125
+ path,
126
+ extractedModule: {
127
+ package: subPath.substring(0, firstSlashIndex),
128
+ path: subPath.substring(firstSlashIndex + 1),
129
+ },
130
+ };
131
+ }
132
+ const secondSlash = subPath.substring(firstSlashIndex + 1).indexOf('/');
133
+ return {
134
+ path,
135
+ extractedModule: {
136
+ package: subPath.substring(0, firstSlashIndex + secondSlash + 1),
137
+ path: subPath.substring(firstSlashIndex + secondSlash + 2),
138
+ },
139
+ };
140
+ }
141
+ function shouldIgnoreModule({ namespace, path, importer, externalModules, pathPrefixesToIgnore, }) {
142
+ // If onLoad is being triggered from another plugin, ignore it
143
+ if (namespace !== 'file')
144
+ return true;
145
+ // If it's a local import from our code, ignore it
146
+ if (!importer.includes(NODE_MODULES) && path.startsWith('.'))
147
+ return true;
148
+ // If it starts with a prefix to ignore, ignore it
149
+ if (pathPrefixesToIgnore === null || pathPrefixesToIgnore === void 0 ? void 0 : pathPrefixesToIgnore.some(prefix => path.startsWith(prefix))) {
150
+ return true;
151
+ }
152
+ // If it's marked as external, ignore it
153
+ if (externalModules === null || externalModules === void 0 ? void 0 : externalModules.includes(path))
154
+ return true;
155
+ return false;
156
+ }
157
+ function isBuiltIn(path, extractedModule) {
158
+ return (BUILT_INS.has(path) ||
159
+ BUILT_INS.has(`${extractedModule.package}/${extractedModule.path}`));
160
+ }
161
+ const moduleVersionByPackageJsonPath = new Map();
162
+ async function getModuleVersion({ extractedModule, resolveDir, build, }) {
163
+ const path = `${extractedModule.package}/package.json`;
164
+ const contents = moduleVersionByPackageJsonPath.get(path);
165
+ if (contents)
166
+ return contents;
167
+ const { path: packageJsonPath } = await build.resolve(path, {
168
+ resolveDir,
169
+ kind: 'require-resolve',
170
+ });
171
+ if (!packageJsonPath)
172
+ return;
173
+ const packageJsonContents = await (0, promises_1.readFile)(packageJsonPath);
174
+ const moduleVersion = JSON.parse(packageJsonContents.toString()).version;
175
+ moduleVersionByPackageJsonPath.set(path, moduleVersion);
176
+ return moduleVersion;
177
+ }
178
+ function getInstrumentation({ extractedModule, path, moduleVersion, }) {
179
+ for (const instrumentationModuleDefinition of main_1.instrumentationModuleDefinitions) {
180
+ const fullModulePath = `${extractedModule.package}/${extractedModule.path}`;
181
+ const nameMatches = instrumentationModuleDefinition.name === path ||
182
+ instrumentationModuleDefinition.name === fullModulePath;
183
+ if (!nameMatches) {
184
+ const fileMatch = instrumentationModuleDefinition.files.find(file => {
185
+ return file.name === path || file.name === fullModulePath;
186
+ });
187
+ if (!fileMatch)
188
+ continue;
189
+ }
190
+ if (instrumentationModuleDefinition.supportedVersions.some(supportedVersion => (0, semver_1.satisfies)(moduleVersion, supportedVersion))) {
191
+ return instrumentationModuleDefinition;
192
+ }
193
+ if (instrumentationModuleDefinition.files.some(file => {
194
+ if (file.name !== path && file.name !== fullModulePath)
195
+ return false;
196
+ return file.supportedVersions.some(supportedVersion => (0, semver_1.satisfies)(moduleVersion, supportedVersion));
197
+ })) {
198
+ return instrumentationModuleDefinition;
199
+ }
200
+ }
201
+ return null;
202
+ }
203
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../src/plugin.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AASH,+BAAqC;AACrC,wCAGuB;AAGvB,mCAAwC;AACxC,0CAAuC;AACvC,mCAAmC;AACnC,qCAAsC;AAEtC,MAAM,YAAY,GAAG,eAAe,CAAC;AAErC,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,uBAAc,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AAEzE,SAAgB,mBAAmB,CACjC,YAAwC;IAExC,OAAO;QACL,IAAI,EAAE,gBAAgB;QACtB,KAAK,CAAC,KAAK;YACT,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,KAAK,EAAC,IAAI,EAAC,EAAE;gBAC7C,IACE,kBAAkB,CAAC;oBACjB,SAAS,EAAE,IAAI,CAAC,SAAS;oBACzB,IAAI,EAAE,IAAI,CAAC,IAAI;oBACf,QAAQ,EAAE,IAAI,CAAC,QAAQ;oBACvB,eAAe,EAAE,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,eAAe;oBAC9C,oBAAoB,EAAE,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,oBAAoB;iBACzD,CAAC,EACF;oBACA,OAAO;iBACR;gBAED,IAAI,IAAI,CAAC;gBACT,IAAI,eAAe,CAAC;gBAEpB,IAAI;oBACF,MAAM,MAAM,GAAG,2BAA2B,CACxC,IAAI,CAAC,IAAI,EACT,IAAI,CAAC,UAAU,CAChB,CAAC;oBACF,IAAI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,+BAA+B,IAAI,uCAAgC,EAAE;QAC9E,MAAM,cAAc,GAAG,GAAG,eAAe,CAAC,OAAO,IAAI,eAAe,CAAC,IAAI,EAAE,CAAC;QAC5E,MAAM,WAAW,GACf,+BAA+B,CAAC,IAAI,KAAK,IAAI;YAC7C,+BAA+B,CAAC,IAAI,KAAK,cAAc,CAAC;QAE1D,IAAI,CAAC,WAAW,EAAE;YAChB,MAAM,SAAS,GAAG,+BAA+B,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;gBAClE,OAAO,IAAI,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,cAAc,CAAC;YAC5D,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,SAAS;gBAAE,SAAS;SAC1B;QAED,IACE,+BAA+B,CAAC,iBAAiB,CAAC,IAAI,CAAC,gBAAgB,CAAC,EAAE,CACxE,IAAA,kBAAS,EAAC,aAAa,EAAE,gBAAgB,CAAC,CAC3C,EACD;YACA,OAAO,+BAA+B,CAAC;SACxC;QAED,IACE,+BAA+B,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;YAChD,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,cAAc;gBAAE,OAAO,KAAK,CAAC;YACrE,OAAO,IAAI,CAAC,iBAAiB,CAAC,IAAI,CAAC,gBAAgB,CAAC,EAAE,CACpD,IAAA,kBAAS,EAAC,aAAa,EAAE,gBAAgB,CAAC,CAC3C,CAAC;QACJ,CAAC,CAAC,EACF;YACA,OAAO,+BAA+B,CAAC;SACxC;KACF;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ExtractedModule,\n OnLoadArgs,\n OpenTelemetryPluginParams,\n PluginData,\n} from './types';\nimport { Plugin, PluginBuild } from 'esbuild';\nimport { dirname, join } from 'path';\nimport {\n instrumentationModuleDefinitions,\n otelPackageToInstrumentationConfig,\n} from './config/main';\n\nimport { InstrumentationModuleDefinition } from '@opentelemetry/instrumentation';\nimport { builtinModules } from 'module';\nimport { readFile } from 'fs/promises';\nimport { satisfies } from 'semver';\nimport { wrapModule } from './common';\n\nconst NODE_MODULES = 'node_modules/';\n\nconst BUILT_INS = new Set(builtinModules.flatMap(b => [b, `node:${b}`]));\n\nexport function openTelemetryPlugin(\n pluginConfig?: OpenTelemetryPluginParams\n): Plugin {\n return {\n name: 'open-telemetry',\n setup(build) {\n build.onResolve({ filter: /.*/ }, async args => {\n if (\n shouldIgnoreModule({\n namespace: args.namespace,\n path: args.path,\n importer: args.importer,\n externalModules: pluginConfig?.externalModules,\n pathPrefixesToIgnore: pluginConfig?.pathPrefixesToIgnore,\n })\n ) {\n return;\n }\n\n let path;\n let extractedModule;\n\n try {\n const result = extractPackageAndModulePath(\n args.path,\n args.resolveDir\n );\n path = result.path;\n extractedModule = result.extractedModule;\n } catch (e) {\n // Some libraries like `mongodb` require optional dependencies, which may not be present and their absence doesn't break the code\n // Currently esbuild doesn't provide any better way to handle this in plugins: https://github.com/evanw/esbuild/issues/1127\n }\n\n // If it's a local import, don't patch it\n if (!extractedModule) return;\n\n // We'll rely on the OTel auto-instrumentation at runtime to patch builtin modules\n if (isBuiltIn(args.path, extractedModule)) return;\n\n const moduleVersion = await getModuleVersion({\n extractedModule,\n resolveDir: args.resolveDir,\n build,\n });\n if (!moduleVersion) return;\n\n // See if we have an instrumentation registered for this package\n const matchingInstrumentation = getInstrumentation({\n extractedModule,\n moduleVersion,\n path: args.path,\n });\n if (!matchingInstrumentation) return;\n\n const pluginData: PluginData = {\n extractedModule,\n moduleVersion,\n shouldPatchPackage: true,\n instrumentationName: matchingInstrumentation.name,\n };\n\n return { path, pluginData };\n });\n\n build.onLoad(\n { filter: /.*/ },\n async ({ path, pluginData }: OnLoadArgs) => {\n // Ignore any packages that don't have an instrumentation registered for them\n if (!pluginData?.shouldPatchPackage) return;\n\n const contents = await readFile(path);\n\n const config =\n otelPackageToInstrumentationConfig[pluginData.instrumentationName];\n if (!config) return;\n\n // console.log('config is', config);\n const packageConfig =\n pluginConfig?.instrumentationConfig?.[\n config.oTelInstrumentationPackage\n ];\n const extractedModule = pluginData.extractedModule;\n\n return {\n contents: wrapModule(contents.toString(), {\n path: join(\n extractedModule.package || '',\n extractedModule.path || ''\n ),\n moduleVersion: pluginData.moduleVersion,\n instrumentationName: pluginData.instrumentationName,\n oTelInstrumentationClass: config.oTelInstrumentationClass,\n oTelInstrumentationPackage: config.oTelInstrumentationPackage,\n oTelInstrumentationConstructorArgs:\n config.configGenerator(packageConfig),\n }),\n resolveDir: dirname(path),\n };\n }\n );\n },\n };\n}\n\n/**\n * For a given full path to a module,\n * return the package name it belongs to and the local path to the module\n * input: '/foo/node_modules/@co/stuff/foo/bar/baz.js'\n * output: { package: '@co/stuff', path: 'foo/bar/baz.js' }\n */\nfunction extractPackageAndModulePath(\n originalPath: string,\n resolveDir: string\n): { path: string; extractedModule: ExtractedModule | null } {\n // @see https://github.com/nodejs/node/issues/47000\n const path = require.resolve(\n originalPath === '.' ? './' : originalPath === '..' ? '../' : originalPath,\n { paths: [resolveDir] }\n );\n\n const nodeModulesIndex = path.lastIndexOf(NODE_MODULES);\n if (nodeModulesIndex < 0) return { path, extractedModule: null };\n\n const subPath = path.substring(nodeModulesIndex + NODE_MODULES.length);\n const firstSlashIndex = subPath.indexOf('/');\n\n if (!subPath.startsWith('@')) {\n return {\n path,\n extractedModule: {\n package: subPath.substring(0, firstSlashIndex),\n path: subPath.substring(firstSlashIndex + 1),\n },\n };\n }\n\n const secondSlash = subPath.substring(firstSlashIndex + 1).indexOf('/');\n return {\n path,\n extractedModule: {\n package: subPath.substring(0, firstSlashIndex + secondSlash + 1),\n path: subPath.substring(firstSlashIndex + secondSlash + 2),\n },\n };\n}\n\nfunction shouldIgnoreModule({\n namespace,\n path,\n importer,\n externalModules,\n pathPrefixesToIgnore,\n}: {\n namespace: string;\n path: string;\n importer: string;\n externalModules?: string[];\n pathPrefixesToIgnore?: string[];\n}): boolean {\n // If onLoad is being triggered from another plugin, ignore it\n if (namespace !== 'file') return true;\n // If it's a local import from our code, ignore it\n if (!importer.includes(NODE_MODULES) && path.startsWith('.')) return true;\n // If it starts with a prefix to ignore, ignore it\n if (pathPrefixesToIgnore?.some(prefix => path.startsWith(prefix))) {\n return true;\n }\n // If it's marked as external, ignore it\n if (externalModules?.includes(path)) return true;\n\n return false;\n}\n\nfunction isBuiltIn(path: string, extractedModule: ExtractedModule): boolean {\n return (\n BUILT_INS.has(path) ||\n BUILT_INS.has(`${extractedModule.package}/${extractedModule.path}`)\n );\n}\n\nconst moduleVersionByPackageJsonPath = new Map<string, string>();\n\nasync function getModuleVersion({\n extractedModule,\n resolveDir,\n build,\n}: {\n extractedModule: ExtractedModule;\n resolveDir: string;\n build: PluginBuild;\n}) {\n const path = `${extractedModule.package}/package.json`;\n const contents = moduleVersionByPackageJsonPath.get(path);\n if (contents) return contents;\n\n const { path: packageJsonPath } = await build.resolve(path, {\n resolveDir,\n kind: 'require-resolve',\n });\n if (!packageJsonPath) return;\n\n const packageJsonContents = await readFile(packageJsonPath);\n const moduleVersion = JSON.parse(packageJsonContents.toString()).version;\n moduleVersionByPackageJsonPath.set(path, moduleVersion);\n return moduleVersion;\n}\n\nfunction getInstrumentation({\n extractedModule,\n path,\n moduleVersion,\n}: {\n extractedModule: ExtractedModule;\n path: string;\n moduleVersion: string;\n}): InstrumentationModuleDefinition | null {\n for (const instrumentationModuleDefinition of instrumentationModuleDefinitions) {\n const fullModulePath = `${extractedModule.package}/${extractedModule.path}`;\n const nameMatches =\n instrumentationModuleDefinition.name === path ||\n instrumentationModuleDefinition.name === fullModulePath;\n\n if (!nameMatches) {\n const fileMatch = instrumentationModuleDefinition.files.find(file => {\n return file.name === path || file.name === fullModulePath;\n });\n if (!fileMatch) continue;\n }\n\n if (\n instrumentationModuleDefinition.supportedVersions.some(supportedVersion =>\n satisfies(moduleVersion, supportedVersion)\n )\n ) {\n return instrumentationModuleDefinition;\n }\n\n if (\n instrumentationModuleDefinition.files.some(file => {\n if (file.name !== path && file.name !== fullModulePath) return false;\n return file.supportedVersions.some(supportedVersion =>\n satisfies(moduleVersion, supportedVersion)\n );\n })\n ) {\n return instrumentationModuleDefinition;\n }\n }\n return null;\n}\n"]}
@@ -0,0 +1,46 @@
1
+ import type { OnLoadArgs as EsbuildOnLoadArgs } from 'esbuild';
2
+ import type { InstrumentationConfigMap } from '@opentelemetry/auto-instrumentations-node';
3
+ export interface ExtractedModule {
4
+ package: string;
5
+ path: string;
6
+ }
7
+ export declare type PluginData = {
8
+ extractedModule: ExtractedModule;
9
+ shouldPatchPackage: boolean;
10
+ moduleVersion: string;
11
+ instrumentationName: string;
12
+ };
13
+ export declare type OnLoadArgs = Omit<EsbuildOnLoadArgs, 'pluginData'> & {
14
+ pluginData?: PluginData;
15
+ };
16
+ export interface ModuleParams {
17
+ path?: string;
18
+ oTelInstrumentationPackage: string;
19
+ oTelInstrumentationClass: string;
20
+ oTelInstrumentationConstructorArgs?: string;
21
+ instrumentationName?: string;
22
+ moduleVersion: string;
23
+ }
24
+ declare type _RemoveFunctions<T> = {
25
+ [P in keyof T as T[P] extends (...args: unknown[]) => unknown ? never : P]: T[P];
26
+ };
27
+ export declare type RemoveFunctions<T> = Partial<_RemoveFunctions<Required<T>>>;
28
+ declare type BuiltinPackages = '@opentelemetry/instrumentation-dns' | '@opentelemetry/instrumentation-fs' | '@opentelemetry/instrumentation-http';
29
+ declare type NonBuiltinInstrumentationConfigMap = Omit<InstrumentationConfigMap, BuiltinPackages>;
30
+ export declare type EsbuildInstrumentationConfigMap = {
31
+ [K in keyof NonBuiltinInstrumentationConfigMap]: RemoveFunctions<NonBuiltinInstrumentationConfigMap[K]>;
32
+ };
33
+ export interface OpenTelemetryPluginParams {
34
+ instrumentationConfig?: EsbuildInstrumentationConfigMap;
35
+ /** Modules to consider external and ignore from the plugin */
36
+ externalModules?: string[];
37
+ /**
38
+ * Path prefixes to ignore.
39
+ *
40
+ * ie if you configure compilerOptions.paths in your tsconfig.json to use something like `~/` for the
41
+ * root of your project then you could set that here to ignore modules
42
+ */
43
+ pathPrefixesToIgnore?: string[];
44
+ }
45
+ export {};
46
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ /*
3
+ * Copyright The OpenTelemetry Authors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * https://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { OnLoadArgs as EsbuildOnLoadArgs } from 'esbuild';\nimport type { InstrumentationConfigMap } from '@opentelemetry/auto-instrumentations-node';\n\nexport interface ExtractedModule {\n package: string;\n path: string;\n}\n\nexport type PluginData = {\n extractedModule: ExtractedModule;\n shouldPatchPackage: boolean;\n moduleVersion: string;\n instrumentationName: string;\n};\n\nexport type OnLoadArgs = Omit<EsbuildOnLoadArgs, 'pluginData'> & {\n pluginData?: PluginData;\n};\n\nexport interface ModuleParams {\n path?: string;\n oTelInstrumentationPackage: string;\n oTelInstrumentationClass: string;\n oTelInstrumentationConstructorArgs?: string;\n instrumentationName?: string;\n moduleVersion: string;\n}\n\ntype _RemoveFunctions<T> = {\n [P in keyof T as T[P] extends (...args: unknown[]) => unknown\n ? never\n : P]: T[P];\n};\n\n// _RemoveFunctions does not work on optional fields, so first make the type required then apply Partial to the result\nexport type RemoveFunctions<T> = Partial<_RemoveFunctions<Required<T>>>;\n\ntype BuiltinPackages =\n | '@opentelemetry/instrumentation-dns'\n | '@opentelemetry/instrumentation-fs'\n | '@opentelemetry/instrumentation-http';\n\ntype NonBuiltinInstrumentationConfigMap = Omit<\n InstrumentationConfigMap,\n BuiltinPackages\n>;\n\nexport type EsbuildInstrumentationConfigMap = {\n [K in keyof NonBuiltinInstrumentationConfigMap]: RemoveFunctions<\n NonBuiltinInstrumentationConfigMap[K]\n >;\n};\n\nexport interface OpenTelemetryPluginParams {\n instrumentationConfig?: EsbuildInstrumentationConfigMap;\n\n /** Modules to consider external and ignore from the plugin */\n externalModules?: string[];\n\n /**\n * Path prefixes to ignore.\n *\n * ie if you configure compilerOptions.paths in your tsconfig.json to use something like `~/` for the\n * root of your project then you could set that here to ignore modules\n */\n pathPrefixesToIgnore?: string[];\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,77 @@
1
+ {
2
+ "name": "opentelemetry-esbuild-plugin-node",
3
+ "version": "0.1.0",
4
+ "description": "Metapackage which bundles opentelemetry node core and contrib instrumentations via an esbuild plugin",
5
+ "author": "Drew Corlin",
6
+ "homepage": "https://github.com/DrewCorlin/opentelemetry-esbuild-plugin-node",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/DrewCorlin/opentelemetry-esbuild-plugin-node.git"
10
+ },
11
+ "license": "Apache-2.0",
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "main": "build/src/index.js",
19
+ "types": "build/src/index.d.ts",
20
+ "exports": {
21
+ ".": "./build/src/index.js"
22
+ },
23
+ "scripts": {
24
+ "clean": "rimraf build/*",
25
+ "compile": "tsc -p .",
26
+ "lint": "eslint . --ext .ts",
27
+ "lint:fix": "eslint . --ext .ts --fix",
28
+ "prepublishOnly": "npm run compile",
29
+ "tdd": "yarn test -- --watch-extensions ts --watch",
30
+ "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.ts'",
31
+ "watch": "tsc -w"
32
+ },
33
+ "bugs": {
34
+ "url": "https://github.com/DrewCorlin/opentelemetry-esbuild-plugin-node/issues"
35
+ },
36
+ "devDependencies": {
37
+ "@fastify/rate-limit": "^9.1.0",
38
+ "@opentelemetry/api": "^1.9.0",
39
+ "@opentelemetry/sdk-node": "^0.55.0",
40
+ "@types/mocha": "7.0.2",
41
+ "@types/node": "18.6.5",
42
+ "@types/semver": "^7.5.8",
43
+ "@typescript-eslint/eslint-plugin": "5.8.1",
44
+ "@typescript-eslint/parser": "5.8.1",
45
+ "eslint": "8.7.0",
46
+ "eslint-config-airbnb-base": "15.0.0",
47
+ "eslint-config-prettier": "8.8.0",
48
+ "eslint-plugin-header": "3.1.1",
49
+ "eslint-plugin-import": "2.27.5",
50
+ "eslint-plugin-node": "11.1.0",
51
+ "eslint-plugin-prettier": "4.2.1",
52
+ "fastify": "4.15.0",
53
+ "graphql": "^16.10.0",
54
+ "mocha": "7.2.0",
55
+ "mongodb": "6.8.0",
56
+ "mongodb-memory-server": "9.5.0",
57
+ "nyc": "15.1.0",
58
+ "pino": "^8.19.0",
59
+ "prettier": "2.8.8",
60
+ "redis": "^4.7.0",
61
+ "rimraf": "5.0.5",
62
+ "ts-mocha": "10.0.0",
63
+ "ts-node": "^10.9.2",
64
+ "typescript": "4.4.4"
65
+ },
66
+ "dependencies": {
67
+ "@opentelemetry/auto-instrumentations-node": "0.53.0",
68
+ "@opentelemetry/instrumentation": "^0.55.0",
69
+ "esbuild": "0.21.x",
70
+ "semver": "^7.6.3"
71
+ },
72
+ "files": [
73
+ "build/src/**/*.js",
74
+ "build/src/**/*.js.map",
75
+ "build/src/**/*.d.ts"
76
+ ]
77
+ }