dd-trace-bun 0.0.0-stage → 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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,124 @@
1
- # Temporary Holding Version
1
+ # dd-trace-bun
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Datadog APM for Bun servers. It makes [dd-trace](https://github.com/DataDog/dd-trace-js) trace `Bun.serve`, and so Elysia, Hono and anything else built on it, so that traces coming from your other services (Node, Go, Python, …) **continue into your Bun service instead of starting over**.
4
+
5
+ It sits on top of dd-trace rather than replacing it: outbound `fetch`, `node:http`, Express and the database clients dd-trace already instruments in Bun keep working, and spans reach the Datadog agent exactly as they do from Node.
6
+
7
+ ## Why
8
+
9
+ dd-trace's HTTP server integration hooks Node's `http.Server`. `Bun.serve` is native and never goes through it, so with plain dd-trace in Bun ([dd-trace-js#3749](https://github.com/DataDog/dd-trace-js/issues/3749)):
10
+
11
+ - requests handled by `Bun.serve`, Elysia or Hono get no server span
12
+ - incoming `x-datadog-*` / `traceparent` headers are never read
13
+ - every span created in a handler starts a new trace
14
+
15
+ ## Install
16
+
17
+ ```sh
18
+ bun add dd-trace dd-trace-bun
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ No code changes needed. Preload it and configure dd-trace with the usual `DD_*` environment variables:
24
+
25
+ ```sh
26
+ DD_SERVICE=users-api DD_ENV=prod bun --preload dd-trace-bun/init src/index.ts
27
+ ```
28
+
29
+ Or initialise it in code before your server starts. `init()` takes the same options as dd-trace's `tracer.init()` and returns the tracer:
30
+
31
+ ```ts
32
+ import { init } from 'dd-trace-bun'
33
+
34
+ const tracer = init({ service: 'users-api' })
35
+ ```
36
+
37
+ ### Elysia
38
+
39
+ `.listen()` is traced as is. Elysia serves most routes through Bun's native `routes`, so their spans are already named by route template (`GET /users/:id`). The plugin names the rest (`.all()`, optional parameters, …) and attaches handler errors to spans. Register it before your routes, because Elysia applies hooks only to routes added after them:
40
+
41
+ ```ts
42
+ import { Elysia } from 'elysia'
43
+ import { datadog } from 'dd-trace-bun/elysia'
44
+
45
+ new Elysia()
46
+ .use(datadog())
47
+ .get('/users/:id', ({ params }) => ({ id: params.id }))
48
+ .listen(3000)
49
+ ```
50
+
51
+ ### Other frameworks
52
+
53
+ Anything that ends up in `Bun.serve` is traced, including a default export Bun serves for you. Three functions let a framework integration do more:
54
+
55
+ - `setRoute(request, '/users/:id')` names the request's span after its route template.
56
+ - `recordError(request, error)` attaches an error to the span. As in dd-trace's own framework integrations, the span is only marked as an error if the response status is one (5xx by default).
57
+ - `traceHandler(fetch)` traces a fetch handler that doesn't go through `Bun.serve`.
58
+
59
+ ## Configuration
60
+
61
+ Requests go through **dd-trace's own `http` server plugin**, the code that handles `node:http` on Node, so everything is configured as it is there and behaves the same:
62
+
63
+ ```ts
64
+ tracer.use('http', {
65
+ server: {
66
+ blocklist: ['/healthz'],
67
+ validateStatus: (code) => code < 500,
68
+ hooks: { request: (span, req) => span?.setTag('tenant', req?.headers['x-tenant']) },
69
+ service: 'users-http',
70
+ },
71
+ })
72
+ ```
73
+
74
+ Environment variables such as `DD_TRACE_HEADER_TAGS`, `DD_TRACE_HTTP_SERVER_ERROR_STATUSES`, `DD_TRACE_PROPAGATION_STYLE`, `DD_TRACE_SPAN_ATTRIBUTE_SCHEMA`, `DD_TRACE_OTEL_SEMANTICS_ENABLED`, `DD_TRACE_CLIENT_IP_ENABLED` and `DD_TRACE_RESOURCE_RENAMING_ENABLED` all apply. In hooks, `req` is a Node-style view of the Bun request (`method`, `url`, `headers`, `socket.remoteAddress`) with the original `Request` on `req.request`.
75
+
76
+ **AppSec** works too (`DD_APPSEC_ENABLED=true`): attacks are reported on the span, and requests that match a blocking rule get dd-trace's blocking response without reaching your handler.
77
+
78
+ ## Parity with dd-trace on Node
79
+
80
+ `test/parity/http-server.test.ts` ports dd-trace-js's own `packages/datadog-plugin-http/test/server.spec.js`, plus propagation, AppSec and web-util behaviour other dd-trace specs cover. It runs the **same assertions** against three apps:
81
+
82
+ | App | Runtime | Tracer | Result |
83
+ |---|---|---|---|
84
+ | `node:http` (reference) | Node 22 | plain dd-trace | 28 / 28 |
85
+ | `Bun.serve` | Bun 1.4.2 | dd-trace-bun | 28 / 28 |
86
+ | Elysia `.listen()` | Bun 1.4.2 | dd-trace-bun | 28 / 28 |
87
+
88
+ The cases cover span shape (name, service, type, resource, kind, URL, method, status, component), the request scope, Datadog / W3C / B3 propagation, 5xx and thrown errors, query string obfuscation, CORS preflight trace headers, canceled requests, OTel semantics, `DD_TRACE_HTTP_SERVER_ERROR_STATUSES`, `server` config, hooks, blocklist and `service` override, a disabled server integration, resource renaming (`http.endpoint`), header tags, client IP, naming schema v1, and AppSec reporting and blocking. Elysia spans carry its matched route (`GET /*`), as dd-trace's Express integration does, so its resource and endpoint assertions expect the route.
89
+
90
+ `test/serve.test.ts` covers what only Bun has: native `routes`, `server.reload()`, WebSocket upgrades, class-based options, Elysia's client errors, and `node:http` in Bun still being traced once.
91
+
92
+ ## How it works
93
+
94
+ - `init()` patches `Bun.serve` (and `server.reload`) to wrap `fetch` and every handler in `routes`.
95
+ - Each request is published on the diagnostics channels dd-trace's `node:http` instrumentation uses, with a Node-style view of the request and response. dd-trace's http server plugin then extracts the incoming context, starts the span, applies its configuration, and finishes the span once the handler's `Response` is known. The span is active for the whole handler, across `await`s.
96
+ - Handlers of Bun's native `routes` set `http.route`, so the resource becomes `GET /users/:id`.
97
+ - What it needs from dd-trace beyond its public API (four channel names and `plugins/util/web`) is all in `src/internals.ts`. CI runs the suite against the newest dd-trace 5 and 6, so a dd-trace release that changes them shows up as a failing build. If they're missing at runtime, `init()` logs a warning and leaves `Bun.serve` alone instead of failing.
98
+
99
+ ## Limitations
100
+
101
+ - The span ends when the handler returns its `Response`, not when a streamed body finishes.
102
+ - When a bare `Bun.serve` fetch handler throws, the span records the error with status 500. Bun doesn't pass the request to your `error()` handler, so a different status it returns isn't seen. Elysia and Hono handle errors themselves and aren't affected.
103
+ - dd-trace's runtime metrics crash Bun ([oven-sh/bun#18546](https://github.com/oven-sh/bun/issues/18546)), so `init()` keeps them off even if `DD_RUNTIME_METRICS_ENABLED` is set, and logs that it did. Passing `runtimeMetrics` to `init()` overrides this.
104
+ - dd-trace's Orchestrion-based integrations (graphql, ai, bullmq, langchain, …) don't run under Bun ([dd-trace-js#3749](https://github.com/DataDog/dd-trace-js/issues/3749)). That's a gap in dd-trace itself, which this package doesn't address.
105
+ - Inside `bun test`, dd-trace turns itself into a no-op because it sees Bun's jest-compatible globals. This package's own tests therefore run the traced apps as subprocesses.
106
+
107
+ ## Compatibility
108
+
109
+ Bun ≥ 1.2.23, dd-trace ≥ 5.60 and < 7, and optionally Elysia ≥ 1.2. The whole suite passes on Bun 1.2.23, 1.3.0 and 1.4.2, dd-trace 5.131.1 and 6.20.1, and Elysia 1.2.25, 1.3.21 and 1.4.30. On dd-trace 5.60.0 and 6.0.0 Bun behaves exactly like Node, but some options the suite checks didn't exist yet. The floors are the oldest versions tested; further back, dd-trace itself breaks under Bun with or without this package (5.0.0 overflows the stack, and 6.20.1 fails to load on Bun 1.2.3).
110
+
111
+ ## Development
112
+
113
+ ```sh
114
+ bun install
115
+ bun test # 97 tests against a fake Datadog agent; node must be on PATH for the reference app
116
+ bun run typecheck
117
+ bun run build # compiles src/ to dist/, which is what the npm package exports
118
+ ```
119
+
120
+ Releases are managed with [Changesets](https://github.com/changesets/changesets). A pull request that should ship a release adds a changeset with `bunx changeset`, which asks for the bump (patch, minor or major) and a line for the changelog. Once that's merged, CI opens or updates a "Version Packages" pull request that bumps `version` and CHANGELOG.md, and merging that one publishes to npm with provenance, tags the release and creates a GitHub release. Publishing needs an `NPM_TOKEN` repository secret, or npm trusted publishing set up for this repository.
121
+
122
+ ## License
123
+
124
+ Apache-2.0, like dd-trace.
@@ -0,0 +1,9 @@
1
+ import { Elysia } from 'elysia';
2
+ /**
3
+ * Elysia plugin: names spans after the matched route (`GET /users/:id`) and attaches
4
+ * errors to them. Elysia already serves most routes through Bun's native `routes`, which
5
+ * `init()` names on its own; this covers the rest (e.g. `.all()` and optional params) and
6
+ * errors. Register it before your routes: Elysia applies hooks only to routes added after.
7
+ */
8
+ export declare const datadog: () => Elysia;
9
+ //# sourceMappingURL=elysia.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"elysia.d.ts","sourceRoot":"","sources":["../src/elysia.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAG/B;;;;;GAKG;AACH,eAAO,MAAM,OAAO,QAAO,MAOrB,CAAA"}
package/dist/elysia.js ADDED
@@ -0,0 +1,16 @@
1
+ import { Elysia } from 'elysia';
2
+ import { recordError, setRoute } from "./serve.js";
3
+ /**
4
+ * Elysia plugin: names spans after the matched route (`GET /users/:id`) and attaches
5
+ * errors to them. Elysia already serves most routes through Bun's native `routes`, which
6
+ * `init()` names on its own; this covers the rest (e.g. `.all()` and optional params) and
7
+ * errors. Register it before your routes: Elysia applies hooks only to routes added after.
8
+ */
9
+ export const datadog = () => new Elysia({ name: 'dd-trace-bun' })
10
+ .onTransform({ as: 'global' }, ({ request, route }) => {
11
+ setRoute(request, route);
12
+ })
13
+ .onError({ as: 'global' }, ({ request, error }) => {
14
+ recordError(request, error);
15
+ });
16
+ //# sourceMappingURL=elysia.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"elysia.js","sourceRoot":"","sources":["../src/elysia.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAC/B,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAElD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,GAAW,EAAE,CAClC,IAAI,MAAM,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,CAAC;KACjC,WAAW,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE;IACpD,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC,CAAC;KACD,OAAO,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE;IAChD,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;AAC7B,CAAC,CAAC,CAAA"}
@@ -0,0 +1,13 @@
1
+ import tracer from 'dd-trace';
2
+ import type { TracerOptions } from 'dd-trace';
3
+ export { recordError, setRoute, traceHandler } from './serve.ts';
4
+ /**
5
+ * Initialise dd-trace and instrument `Bun.serve`, and with it Elysia, Hono and anything
6
+ * else built on it. Call it before your server starts, or preload `dd-trace-bun/init`.
7
+ * Takes the same options as dd-trace's `tracer.init()`.
8
+ *
9
+ * Requests go through dd-trace's own http server plugin, so they're configured exactly as
10
+ * on Node: `tracer.use('http', { server: { ... } })` and the `DD_*` environment variables.
11
+ */
12
+ export declare function init(options?: TracerOptions): typeof tracer;
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,UAAU,CAAA;AAC7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAI7C,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAEhE;;;;;;;GAOG;AACH,wBAAgB,IAAI,CAAE,OAAO,GAAE,aAAkB,GAAG,OAAO,MAAM,CAiBhE"}
package/dist/index.js ADDED
@@ -0,0 +1,33 @@
1
+ import tracer from 'dd-trace';
2
+ import { web } from "./internals.js";
3
+ import { patchBunServe } from "./serve.js";
4
+ export { recordError, setRoute, traceHandler } from "./serve.js";
5
+ /**
6
+ * Initialise dd-trace and instrument `Bun.serve`, and with it Elysia, Hono and anything
7
+ * else built on it. Call it before your server starts, or preload `dd-trace-bun/init`.
8
+ * Takes the same options as dd-trace's `tracer.init()`.
9
+ *
10
+ * Requests go through dd-trace's own http server plugin, so they're configured exactly as
11
+ * on Node: `tracer.use('http', { server: { ... } })` and the `DD_*` environment variables.
12
+ */
13
+ export function init(options = {}) {
14
+ if (typeof Bun === 'undefined')
15
+ return tracer.init(options);
16
+ if (options.runtimeMetrics === undefined && isTrue(process.env.DD_RUNTIME_METRICS_ENABLED)) {
17
+ console.warn('dd-trace-bun: ignoring DD_RUNTIME_METRICS_ENABLED, dd-trace\'s runtime metrics crash Bun ' +
18
+ '(https://github.com/oven-sh/bun/issues/18546). Pass `runtimeMetrics` to init() to override.');
19
+ }
20
+ tracer.init({ ...options, runtimeMetrics: options.runtimeMetrics ?? false });
21
+ if (!web) {
22
+ console.warn('dd-trace-bun: the installed dd-trace version is not supported, Bun.serve requests will not be traced.');
23
+ return tracer;
24
+ }
25
+ // dd-trace starts its http plugin, which turns these requests into spans, once node:http is loaded
26
+ require('node:http');
27
+ patchBunServe();
28
+ return tracer;
29
+ }
30
+ function isTrue(value) {
31
+ return value === '1' || value?.toLowerCase() === 'true';
32
+ }
33
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,UAAU,CAAA;AAE7B,OAAO,EAAE,GAAG,EAAE,MAAM,gBAAgB,CAAA;AACpC,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAE1C,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAEhE;;;;;;;GAOG;AACH,MAAM,UAAU,IAAI,CAAE,UAAyB,EAAE;IAC/C,IAAI,OAAO,GAAG,KAAK,WAAW;QAAE,OAAO,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;IAE3D,IAAI,OAAO,CAAC,cAAc,KAAK,SAAS,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,EAAE,CAAC;QAC3F,OAAO,CAAC,IAAI,CAAC,2FAA2F;YACtG,6FAA6F,CAAC,CAAA;IAClG,CAAC;IACD,MAAM,CAAC,IAAI,CAAC,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,cAAc,IAAI,KAAK,EAAE,CAAC,CAAA;IAE5E,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,CAAC,IAAI,CAAC,uGAAuG,CAAC,CAAA;QACrH,OAAO,MAAM,CAAA;IACf,CAAC;IACD,mGAAmG;IACnG,OAAO,CAAC,WAAW,CAAC,CAAA;IACpB,aAAa,EAAE,CAAA;IACf,OAAO,MAAM,CAAA;AACf,CAAC;AAED,SAAS,MAAM,CAAE,KAAyB;IACxC,OAAO,KAAK,KAAK,GAAG,IAAI,KAAK,EAAE,WAAW,EAAE,KAAK,MAAM,CAAA;AACzD,CAAC"}
package/dist/init.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":""}
package/dist/init.js ADDED
@@ -0,0 +1,4 @@
1
+ // `bun --preload dd-trace-bun/init src/index.ts`, configured with the DD_* environment variables.
2
+ import { init } from "./index.js";
3
+ init();
4
+ //# sourceMappingURL=init.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init.js","sourceRoot":"","sources":["../src/init.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,OAAO,EAAE,IAAI,EAAE,MAAM,YAAY,CAAA;AAEjC,IAAI,EAAE,CAAA"}
@@ -0,0 +1,16 @@
1
+ import dc from 'node:diagnostics_channel';
2
+ import type { Span } from 'dd-trace';
3
+ export declare const requestStart: dc.Channel<any, any>;
4
+ export declare const requestExit: dc.Channel<any, any>;
5
+ export declare const requestFinish: dc.Channel<any, any>;
6
+ export declare const responseWriteHead: dc.Channel<any, any>;
7
+ /** The parts of dd-trace's `plugins/util/web`, the request context all its web integrations share. */
8
+ interface WebUtil {
9
+ root(req: object): Span | null;
10
+ setRoute(req: object, path: string): void;
11
+ addError(req: object, error: unknown): void;
12
+ }
13
+ /** Undefined when the installed dd-trace doesn't have the expected internals. */
14
+ export declare const web: WebUtil | undefined;
15
+ export {};
16
+ //# sourceMappingURL=internals.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internals.d.ts","sourceRoot":"","sources":["../src/internals.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,MAAM,0BAA0B,CAAA;AAEzC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,UAAU,CAAA;AAEpC,eAAO,MAAM,YAAY,sBAA8C,CAAA;AACvE,eAAO,MAAM,WAAW,sBAA6C,CAAA;AACrE,eAAO,MAAM,aAAa,sBAA+C,CAAA;AACzE,eAAO,MAAM,iBAAiB,sBAAyD,CAAA;AAEvF,sGAAsG;AACtG,UAAU,OAAO;IACf,IAAI,CAAE,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAAA;IAC/B,QAAQ,CAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;IAC1C,QAAQ,CAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAAA;CAC7C;AAED,iFAAiF;AACjF,eAAO,MAAM,GAAG,EAAE,OAAO,GAAG,SAAyB,CAAA"}
@@ -0,0 +1,26 @@
1
+ // Everything dd-trace-bun takes from dd-trace that isn't public API.
2
+ //
3
+ // Bun.serve requests are published on the diagnostics channels dd-trace's node:http
4
+ // server instrumentation uses (packages/datadog-instrumentations/src/http/server.js),
5
+ // so dd-trace's http server plugin and AppSec handle them exactly like node:http
6
+ // requests. CI runs the test suite against the newest dd-trace 5 and 6 releases, so a
7
+ // change to any of this shows up as a failing build.
8
+ import dc from 'node:diagnostics_channel';
9
+ import { createRequire } from 'node:module';
10
+ export const requestStart = dc.channel('apm:http:server:request:start');
11
+ export const requestExit = dc.channel('apm:http:server:request:exit');
12
+ export const requestFinish = dc.channel('apm:http:server:request:finish');
13
+ export const responseWriteHead = dc.channel('apm:http:server:response:writeHead:start');
14
+ /** Undefined when the installed dd-trace doesn't have the expected internals. */
15
+ export const web = loadWebUtil();
16
+ function loadWebUtil() {
17
+ try {
18
+ const util = createRequire(import.meta.url)('dd-trace/packages/dd-trace/src/plugins/util/web');
19
+ const complete = ['root', 'setRoute', 'addError'].every((name) => typeof util[name] === 'function');
20
+ return complete ? util : undefined;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ //# sourceMappingURL=internals.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"internals.js","sourceRoot":"","sources":["../src/internals.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,EAAE;AACF,oFAAoF;AACpF,sFAAsF;AACtF,iFAAiF;AACjF,sFAAsF;AACtF,qDAAqD;AACrD,OAAO,EAAE,MAAM,0BAA0B,CAAA;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAG3C,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAC,OAAO,CAAC,+BAA+B,CAAC,CAAA;AACvE,MAAM,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC,OAAO,CAAC,8BAA8B,CAAC,CAAA;AACrE,MAAM,CAAC,MAAM,aAAa,GAAG,EAAE,CAAC,OAAO,CAAC,gCAAgC,CAAC,CAAA;AACzE,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAC,OAAO,CAAC,0CAA0C,CAAC,CAAA;AASvF,iFAAiF;AACjF,MAAM,CAAC,MAAM,GAAG,GAAwB,WAAW,EAAE,CAAA;AAErD,SAAS,WAAW;IAClB,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,iDAAiD,CAAC,CAAA;QAC9F,MAAM,QAAQ,GAAG,CAAC,MAAM,EAAE,UAAU,EAAE,UAAU,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,CAAC,IAAI,CAAC,KAAK,UAAU,CAAC,CAAA;QACnG,OAAO,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;IACpC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAA;IAClB,CAAC;AACH,CAAC"}
@@ -0,0 +1,46 @@
1
+ import type { Server } from 'bun';
2
+ /**
3
+ * A Bun request as dd-trace sees it. This is also the `req` passed to
4
+ * `tracer.use('http', { server: { hooks: { request } } })`; `request` is the original.
5
+ */
6
+ export interface NodeRequest {
7
+ method: string;
8
+ /** Path and query string, like node:http's `req.url`. */
9
+ url: string;
10
+ /** Lower-case header names. */
11
+ headers: Record<string, string>;
12
+ socket: {
13
+ remoteAddress: string | undefined;
14
+ encrypted: boolean;
15
+ };
16
+ request: Request;
17
+ }
18
+ export declare function toNodeRequest(request: Request, server: Server<unknown> | undefined): NodeRequest;
19
+ /**
20
+ * A Bun response as dd-trace sees it. It holds the status and headers of the Response the
21
+ * handler returned. dd-trace may add headers to it (CORS allow-headers on preflights) or,
22
+ * when AppSec blocks a request, replace it with a response of its own.
23
+ */
24
+ export declare class NodeResponse {
25
+ #private;
26
+ readonly req: NodeRequest;
27
+ statusCode: number;
28
+ headersSent: boolean;
29
+ constructor(req: NodeRequest);
30
+ /** Record the status and headers the handler responded with. */
31
+ load(response: Response): void;
32
+ /** True once dd-trace wrote a complete response itself (AppSec blocking). */
33
+ get ended(): boolean;
34
+ /** The response dd-trace wrote. */
35
+ toResponse(): Response;
36
+ /** The handler's response, with any headers dd-trace added. */
37
+ withAddedHeaders(response: Response): Response;
38
+ getHeader(name: string): string | string[] | undefined;
39
+ getHeaders(): Record<string, string | string[]>;
40
+ getHeaderNames(): string[];
41
+ setHeader(name: string, value: string | number | string[]): this;
42
+ removeHeader(name: string): void;
43
+ writeHead(statusCode?: number, headers?: Record<string, string>): this;
44
+ end(body?: string): this;
45
+ }
46
+ //# sourceMappingURL=node-http.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-http.d.ts","sourceRoot":"","sources":["../src/node-http.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,KAAK,CAAA;AAGjC;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAA;IACd,yDAAyD;IACzD,GAAG,EAAE,MAAM,CAAA;IACX,+BAA+B;IAC/B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,MAAM,EAAE;QAAE,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;QAAC,SAAS,EAAE,OAAO,CAAA;KAAE,CAAA;IACjE,OAAO,EAAE,OAAO,CAAA;CACjB;AAED,wBAAgB,aAAa,CAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,SAAS,GAAG,WAAW,CAYjG;AAED;;;;GAIG;AACH,qBAAa,YAAY;;IAQV,QAAQ,CAAC,GAAG,EAAE,WAAW;IAPtC,UAAU,SAAM;IAChB,WAAW,UAAQ;gBAMG,GAAG,EAAE,WAAW;IAEtC,gEAAgE;IAChE,IAAI,CAAE,QAAQ,EAAE,QAAQ,GAAG,IAAI;IAO/B,6EAA6E;IAC7E,IAAI,KAAK,IAAK,OAAO,CAEpB;IAED,mCAAmC;IACnC,UAAU,IAAK,QAAQ;IAQvB,+DAA+D;IAC/D,gBAAgB,CAAE,QAAQ,EAAE,QAAQ,GAAG,QAAQ;IAa/C,SAAS,CAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS;IAIvD,UAAU,IAAK,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAIhD,cAAc,IAAK,MAAM,EAAE;IAI3B,SAAS,CAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,GAAG,IAAI;IAOjE,YAAY,CAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAOjC,SAAS,CAAE,UAAU,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI;IAmBvE,GAAG,CAAE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI;CAM1B"}