@rootcat/node 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.
Files changed (55) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +213 -2
  3. package/dist/callsite.d.ts +109 -0
  4. package/dist/callsite.js +565 -0
  5. package/dist/callsite.js.map +1 -0
  6. package/dist/config.d.ts +75 -0
  7. package/dist/config.js +182 -0
  8. package/dist/config.js.map +1 -0
  9. package/dist/drizzle.d.ts +21 -0
  10. package/dist/drizzle.js +124 -0
  11. package/dist/drizzle.js.map +1 -0
  12. package/dist/esm.mjs +41 -0
  13. package/dist/esmhook.d.ts +12 -0
  14. package/dist/esmhook.js +84 -0
  15. package/dist/esmhook.js.map +1 -0
  16. package/dist/index.d.ts +12 -0
  17. package/dist/index.js +50 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/intake.d.ts +40 -0
  20. package/dist/intake.js +164 -0
  21. package/dist/intake.js.map +1 -0
  22. package/dist/keys.d.ts +9 -0
  23. package/dist/keys.js +15 -0
  24. package/dist/keys.js.map +1 -0
  25. package/dist/notices.d.ts +2 -0
  26. package/dist/notices.js +21 -0
  27. package/dist/notices.js.map +1 -0
  28. package/dist/otlp.d.ts +75 -0
  29. package/dist/otlp.js +449 -0
  30. package/dist/otlp.js.map +1 -0
  31. package/dist/pg.d.ts +16 -0
  32. package/dist/pg.js +165 -0
  33. package/dist/pg.js.map +1 -0
  34. package/dist/pgpool.d.ts +13 -0
  35. package/dist/pgpool.js +85 -0
  36. package/dist/pgpool.js.map +1 -0
  37. package/dist/postgresjs.d.ts +33 -0
  38. package/dist/postgresjs.js +272 -0
  39. package/dist/postgresjs.js.map +1 -0
  40. package/dist/privacy.d.ts +38 -0
  41. package/dist/privacy.js +147 -0
  42. package/dist/privacy.js.map +1 -0
  43. package/dist/processor.d.ts +94 -0
  44. package/dist/processor.js +252 -0
  45. package/dist/processor.js.map +1 -0
  46. package/dist/register.d.ts +1 -0
  47. package/dist/register.js +12 -0
  48. package/dist/register.js.map +1 -0
  49. package/dist/sampler.d.ts +12 -0
  50. package/dist/sampler.js +52 -0
  51. package/dist/sampler.js.map +1 -0
  52. package/dist/sdk.d.ts +88 -0
  53. package/dist/sdk.js +305 -0
  54. package/dist/sdk.js.map +1 -0
  55. package/package.json +65 -4
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 2026 Kelvin Guchu
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,214 @@
1
- # Temporary Holding Version
1
+ # @rootcat/node
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
+ Tracing for Node services that report to the Rootcat host agent, with the
4
+ line of application code behind every database and HTTP client call.
5
+ Loading the package starts an OpenTelemetry tracer with a curated set of
6
+ instrumentations and posts the spans to the agent's OTLP intake on the
7
+ same host. It talks to the host agent and to nothing else; it needs no
8
+ token.
9
+
10
+ ## Enable
11
+
12
+ **Next.js** (the recommended setup): add `instrumentation.ts` beside
13
+ `next.config.js`. Next loads it before the application, in every server
14
+ it starts, including the standalone output:
15
+
16
+ ```ts
17
+ // instrumentation.ts
18
+ export async function register() {
19
+ if (process.env.NEXT_RUNTIME === 'nodejs') await import('@rootcat/node');
20
+ }
21
+ ```
22
+
23
+ With `output: 'standalone'`, keep the package and the drivers out of the
24
+ server bundles (a bundled driver cannot be patched):
25
+
26
+ ```js
27
+ // next.config.js
28
+ module.exports = {
29
+ output: 'standalone',
30
+ serverExternalPackages: ['@rootcat/node', 'postgres', 'drizzle-orm'],
31
+ experimental: { serverSourceMaps: true },
32
+ };
33
+ ```
34
+
35
+ **CommonJS apps** (Express, Fastify, a worker): one line, first in the
36
+ entry file, before anything else is required:
37
+
38
+ ```js
39
+ require('@rootcat/node');
40
+ ```
41
+
42
+ **ES module apps** (`"type": "module"`): an entry of two files, so the
43
+ application's imports are resolved after the package is loaded:
44
+
45
+ ```js
46
+ // main.mjs
47
+ import '@rootcat/node';
48
+ await import('./app.mjs');
49
+ ```
50
+
51
+ A single file with `import '@rootcat/node'` above `import pg from 'pg'`
52
+ does not work: an ES module's static imports are all resolved and loaded
53
+ before any of them runs, so the drivers are already in memory, unpatched,
54
+ when the package starts. The dynamic `import()` runs after it.
55
+
56
+ **When the code cannot change**, set the variable instead (in Dokploy, the
57
+ application's Environment tab):
58
+
59
+ ```
60
+ NODE_OPTIONS="--require @rootcat/node" # CommonJS
61
+ NODE_OPTIONS="--import @rootcat/node/esm" # ES modules
62
+ ```
63
+
64
+ Using the line and the variable together is harmless: the tracer starts
65
+ once.
66
+
67
+ The intake address is discovered: inside a container on a Docker bridge
68
+ it is the container's default gateway (the bridge address the agent
69
+ listens on); on the host, or in a container on the host's network, it is
70
+ loopback; port 4318 either way. Discovery never picks a public address.
71
+ The host-network check looks for a Docker bridge in `/sys/class/net`: a
72
+ container on the host's network under Podman, or on a Docker host with no
73
+ bridge network, should set `ROOTCAT_OTLP_URL=http://127.0.0.1:4318`.
74
+ `ROOTCAT_OTLP_URL` overrides discovery. The service name is `ROOTCAT_SERVICE`,
75
+ else `OTEL_SERVICE_NAME`, else the `name` of the nearest `package.json`.
76
+
77
+ If another OpenTelemetry SDK is already registered in the process (Sentry
78
+ 8 and later, an app's own `NodeSDK`), the package prints one line and
79
+ does not start. If it starts first, the other SDK's registration fails
80
+ instead; load one of them.
81
+
82
+ ## What is traced
83
+
84
+ | Package | Spans | Call site | Tested here |
85
+ |---|---|---|---|
86
+ | `http`, `https` | server and client requests | client requests | through Next.js |
87
+ | `fetch`, `undici` | client requests | yes | no |
88
+ | `pg` | one span per query; cursors and streams (`pg-cursor`, `pg-query-stream`) are not traced | yes, through the pool as well | yes |
89
+ | `postgres` (postgres.js) | one span per query | tagged templates, and queries made through Drizzle | yes |
90
+ | `drizzle-orm` | the driver spans below it | yes, from where the query was built | yes, over `pg` and postgres.js |
91
+ | `mysql2` | queries | yes | no |
92
+ | `mongodb` | commands | yes | no |
93
+ | `ioredis`, `redis` | commands | yes | no |
94
+ | `@prisma/client` | when the app installs `@prisma/instrumentation` | the operation's | no |
95
+
96
+ Every client span carries `code.filepath`, `code.lineno` and
97
+ `code.function` for the first application frame: outside `node_modules`,
98
+ resolved through the file's source map when it has one, and skipped when
99
+ the map sends it into a bundled library. `code.filepath` is relative to
100
+ the working directory (or, outside it, to the parent of the file's
101
+ package), cut from the front to 120 bytes; the server's absolute layout
102
+ is not sent. A query run where no application frame is on the stack (a
103
+ pool handing it to a client on the next tick, an awaited ORM promise)
104
+ takes the site captured where the application made the call; a query
105
+ issued in the continuation of another gets its own.
106
+
107
+ ## What never leaves the process
108
+
109
+ Literals in query text: strings, numbers and dollar-quoted bodies become
110
+ `?`, comments are dropped, placeholders (`$1`) and identifiers stay
111
+ (`ROOTCAT_DB_STATEMENT=off` keeps only the first keyword). Parameter
112
+ values (never read). Query strings and fragments on URLs, and every path
113
+ segment that could hold an identifier or a token (`/users/42/orders` is
114
+ sent as `/users/{id}/orders`): a segment is kept only when it is a name of
115
+ letters, hyphens and underscores up to 32 bytes (not a mixed-case run of
116
+ twelve or more) or a version such as `v1`, so a username or slug made of
117
+ letters (`/u/kelvin`) is sent, and numbers, UUIDs, tokens, emails and file
118
+ names are not. Client addresses and user agents. Request
119
+ and response bodies and headers. Environment variables and command lines.
120
+ A database server's error message (only the error class and SQLSTATE
121
+ travel). A recorded exception's stack trace is sent as frames only.
122
+
123
+ ## Settings
124
+
125
+ | Variable | Default | Meaning |
126
+ |---|---|---|
127
+ | `ROOTCAT_SAMPLE` | `1` | share of traces recorded, `0` to `1`; a trace is kept or dropped whole, and an incoming `traceparent`'s sampled flag is ignored |
128
+ | `ROOTCAT_CALLSITE_SAMPLE` | `1` | capture a call site for one recorded client span in N; `0` for none |
129
+ | `ROOTCAT_OTLP_URL` | discovered | intake origin, or a full `/v1/traces` URL |
130
+ | `ROOTCAT_SERVICE` | `OTEL_SERVICE_NAME`, then package.json | service name |
131
+ | `ROOTCAT_ENVIRONMENT` | `NODE_ENV` | `deployment.environment.name` |
132
+ | `ROOTCAT_DB_STATEMENT` | `masked` | `off` keeps only the statement's first keyword |
133
+ | `ROOTCAT_DISABLE` | | comma list: `http,undici,pg,postgres,drizzle,mysql2,mongodb,ioredis,redis,prisma` |
134
+ | `ROOTCAT_DEBUG` | | `1` prints the OpenTelemetry diagnostics and the chosen intake to stderr |
135
+ | `ROOTCAT_DISABLED` | | `1` loads nothing |
136
+
137
+ The two sampling settings are the only tuning; batching and the stack
138
+ walk are fixed. The `OTEL_EXPORTER_OTLP_*` and `OTEL_TRACES_SAMPLER`
139
+ variables are not read: spans go to the agent, sampled as above.
140
+
141
+ ## Cost
142
+
143
+ Measured in one warmed-up process on a loop of sequential `pg` queries
144
+ over loopback, the worst case for a per-query cost (`npm run bench`;
145
+ WSL2, Node 24.21). Each loopback query costs 174 µs of CPU untraced.
146
+
147
+ | Setting | CPU added per query | Wall added per query |
148
+ |---|---|---|
149
+ | Defaults (every query traced, every call site) | +190 µs | +204 µs |
150
+ | `ROOTCAT_CALLSITE_SAMPLE=0` (no call sites) | +114 µs | +137 µs |
151
+ | `ROOTCAT_CALLSITE_SAMPLE=10` | +142 µs | +166 µs |
152
+ | `ROOTCAT_SAMPLE=0.1` (one trace in ten) | +63 µs | +82 µs |
153
+ | A query in an unsampled trace | +29 µs | +45 µs |
154
+
155
+ On a 20 ms request with five queries that is about 1 ms of CPU with the
156
+ defaults and 0.3 ms at one trace in ten. Hot, a call-site capture costs
157
+ 11 µs, a span 4 µs, encoding a span 3.1 µs; in a server waiting on its
158
+ database each query runs on cold caches and pays about four times that.
159
+ Loading the package adds 0.3 to 0.4 s to the start of a process, about
160
+ half of it the module loader hook (every module load waits on its
161
+ thread).
162
+
163
+ ## When the agent is not there
164
+
165
+ Spans are batched (every 10 s, up to 512 per export, 4096 queued; past
166
+ that the newest are dropped and stderr says so once), bounded (4 KiB per
167
+ attribute value, statements and exception stacks included) and posted as
168
+ protobuf in requests of at most 900 KiB, under the agent's 1 MiB bound,
169
+ with a 2 s timeout and at most two exports in flight. A request the
170
+ intake refuses as too large is said once on stderr. A failed export
171
+ drops its batch. The application never waits on the exporter and never
172
+ sees its errors. A process exiting with the intake unreachable waits up
173
+ to 2 s for the last flush; on SIGTERM or SIGINT with no handler of the
174
+ application's own, the flush is bounded to 2 s and the signal re-raised.
175
+ A `process.exit()` ends the process before any flush: the spans of its
176
+ last batch interval are lost.
177
+
178
+ ## Next.js details
179
+
180
+ `pg`, `mongodb` and `@prisma/client` are external in Next.js by default;
181
+ `postgres` and `drizzle-orm` are bundled unless listed. With
182
+ `serverSourceMaps` the call sites name the original source files; the
183
+ standalone output does not copy the maps, so a Dockerfile that copies
184
+ `.next/standalone` should also copy every `.map` under `.next/server`,
185
+ keeping its path (route chunks, `chunks/ssr/` for server components, and
186
+ `app/**/page.js.map`), or the call sites name positions in the chunk:
187
+
188
+ ```dockerfile
189
+ # after copying .next/standalone and .next/static
190
+ COPY --from=builder /app/.next/server /tmp/next-server
191
+ RUN cd /tmp/next-server && find . -name '*.map' -exec cp --parents {} /app/.next/server/ \; && rm -rf /tmp/next-server
192
+ ```
193
+
194
+ ## Bundlers
195
+
196
+ An application bundled into one file (esbuild, webpack, Next.js server
197
+ bundles) no longer loads its drivers through `require` or `import`, so
198
+ nothing can patch them. Keep the drivers external (`--packages=external`
199
+ in esbuild, `externals` in webpack, `serverExternalPackages` in Next.js).
200
+ Call sites inside a bundle resolve through its source map when the bundle
201
+ has one. Source maps are read once per file, at most 32 MiB each and
202
+ 64 MiB held at once, synchronously the first time a file appears on a
203
+ captured stack.
204
+
205
+ ## Development
206
+
207
+ ```
208
+ npm install
209
+ npm test # builds, then node:test; docker tests skip without docker
210
+ npm run setup:next # installs the Next.js fixture for its test (once)
211
+ npm run bench # call-site cost, startup and the pg loop
212
+ ```
213
+
214
+ The package is not published yet.
@@ -0,0 +1,109 @@
1
+ import { TraceMap } from '@jridgewell/trace-mapping';
2
+ /** CallSiteLocation is one resolved frame. */
3
+ export interface CallSiteLocation {
4
+ /** file is an absolute path, or a bundler path such as app/route.ts. */
5
+ file: string;
6
+ /** line is 1-based. */
7
+ line: number;
8
+ /** column is 1-based, 0 when unknown. */
9
+ column: number;
10
+ /** function is the enclosing function's name, "" when anonymous. */
11
+ function: string;
12
+ }
13
+ type V8CallSite = NodeJS.CallSite;
14
+ /** defaultDepth is how many frames a full capture walks. */
15
+ export declare const defaultDepth = 32;
16
+ /**
17
+ * shortDepth is the first walk from an entry wrapper: its caller is the
18
+ * application or an ORM a few frames above it. A stack frame costs about
19
+ * a microsecond to collect; the full walk is the fallback.
20
+ */
21
+ export declare const shortDepth = 3;
22
+ /** Bounds on source maps: per map, and for all maps held at once. */
23
+ export declare const maxSourceMapBytes: number;
24
+ export declare const sourceMapBudgetBytes: number;
25
+ /** maxDisplayPathBytes keeps code.filepath within the agent's 128-byte bound. */
26
+ export declare const maxDisplayPathBytes = 120;
27
+ /**
28
+ * captureFrames returns up to depth frames as V8 CallSite objects,
29
+ * starting below the topmost call of above (or of captureFrames itself).
30
+ * Error.prepareStackTrace and Error.stackTraceLimit are swapped for the
31
+ * duration of the capture only. When above is not on the stack, V8 gives
32
+ * nothing; the caller falls back to an uncut walk.
33
+ */
34
+ export declare function captureFrames(depth: number, above?: Function): V8CallSite[];
35
+ /**
36
+ * normalizeFile turns a CallSite file name into a path: file URLs become
37
+ * paths, webpack-internal URLs lose their prefix; node: internals, eval
38
+ * and other non-paths give undefined.
39
+ */
40
+ export declare function normalizeFile(file: string | null | undefined): string | undefined;
41
+ /**
42
+ * isAppFile reports whether a path belongs to the application: no
43
+ * node_modules segment (absolute or bundler-relative, as a source map
44
+ * names a bundled library) and not this package's own code.
45
+ */
46
+ export declare function isAppFile(file: string, own?: readonly string[]): boolean;
47
+ /** firstAppFrame returns the first captured frame whose generated file is application code, unresolved. */
48
+ export declare function firstAppFrame(sites: readonly V8CallSite[], isApp?: (file: string) => boolean): CallSiteLocation | undefined;
49
+ /**
50
+ * appLocation walks the frames, resolves each candidate through its
51
+ * source map, and returns the first whose original source is application
52
+ * code: a frame in a bundle that maps into a bundled library is passed
53
+ * over, as an unbundled library frame is.
54
+ */
55
+ export declare function appLocation(sites: readonly V8CallSite[], isApp?: (file: string) => boolean): CallSiteLocation | undefined;
56
+ /** resetSourceMapCache forgets loaded maps (tests). */
57
+ export declare function resetSourceMapCache(): void;
58
+ /** sourceMapBytesHeld reports what the cache holds (tests). */
59
+ export declare function sourceMapBytesHeld(): number;
60
+ /**
61
+ * sourceMapFor loads the source map a generated file points at through
62
+ * its sourceMappingURL comment (inline data URL or a file beside it),
63
+ * once per file, and remembers the result; null when none. A map over
64
+ * maxSourceMapBytes is not read; the maps held together stay within
65
+ * sourceMapBudgetBytes, the least recently loaded given up first (and
66
+ * read again if their file comes back). The read is synchronous and
67
+ * happens the first time a file is seen on a captured stack.
68
+ */
69
+ export declare function sourceMapFor(file: string): TraceMap | null;
70
+ /** sourceMappingURL finds the last sourceMappingURL comment in text. */
71
+ export declare function sourceMappingURL(text: string): string | undefined;
72
+ /**
73
+ * originalPath makes a mapped source readable: file URLs become paths and
74
+ * bundler schemes (webpack://, turbopack://) are reduced to the project
75
+ * relative path they carry.
76
+ */
77
+ export declare function originalPath(source: string): string;
78
+ /**
79
+ * resolveLocation maps a generated position to the original source when
80
+ * the file has a source map: the one Node already holds (with
81
+ * --enable-source-maps, or a loader such as tsx registering its maps),
82
+ * else the file's own. Otherwise the location is returned as is.
83
+ */
84
+ export declare function resolveLocation(location: CallSiteLocation): CallSiteLocation;
85
+ /**
86
+ * parseStack finds the first application frame in a formatted V8 stack
87
+ * (one a driver captured itself, such as postgres.js's query origin) and
88
+ * resolves it. undefined when there is none.
89
+ */
90
+ export declare function parseStack(stack: string, isApp?: (file: string) => boolean): CallSiteLocation | undefined;
91
+ /**
92
+ * captureCallSite is the whole operation: capture, pick the application
93
+ * frame, resolve it. From an entry wrapper (above), a short walk below
94
+ * the wrapper first, the full walk only when that finds no application
95
+ * frame. undefined when no application frame is on the stack.
96
+ */
97
+ export declare function captureCallSite(depth?: number, isApp?: (file: string) => boolean, above?: Function): CallSiteLocation | undefined;
98
+ /**
99
+ * displayPath is what code.filepath carries: a bundler path as it is, a
100
+ * file under the working directory relative to it, any other file
101
+ * relative to the parent of its nearest package.json directory (so it
102
+ * names its package), and at most maxDisplayPathBytes from the end, so
103
+ * the file name survives the agent's bound. The server's absolute layout
104
+ * (a home directory, a deploy path) is not sent.
105
+ */
106
+ export declare function displayPath(file: string, cwd?: string): string;
107
+ /** clipFromStart keeps the last bytes of a path, cut at a segment. */
108
+ export declare function clipFromStart(text: string, limit: number): string;
109
+ export {};