@trafficwar/node 2.2.4 → 3.0.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/AGENTS.md ADDED
@@ -0,0 +1,164 @@
1
+ # Applying @trafficwar/node correctly
2
+
3
+ Read this guide before instrumenting an application. `README.md` contains the
4
+ full API and tier-placement rules. This is a server SDK for Node 22+;
5
+ framework hooks and dependency instrumentation must be implemented by the
6
+ application. Installing the package alone does not capture requests.
7
+
8
+ ## Lifecycle and delivery
9
+
10
+ - Create one long-lived `TrafficWar` client per service/API key, not per
11
+ request. Load the key from a server-side environment variable. Never send
12
+ it to a browser or commit it.
13
+ - `strictCatalog` defaults to true. Deploy application source and set
14
+ `catalogRoot` to include instrumentation and its relative imports. Check
15
+ `captureEnabled` after construction; startup issues disable all sending.
16
+ Do not silently opt out to hide scanner issues. Use `strictCatalog: false`
17
+ only when the application intentionally accepts unrestricted identities
18
+ or cannot deploy scannable source.
19
+ - `capture(event)` and `capture([events])` validate, snapshot, and enqueue
20
+ synchronously and return `void`. They do not acknowledge durable delivery.
21
+ - A clean startup scan uploads fixed declarations to `/v1/server/catalog`
22
+ independently of events; `close()` waits for that registration too. The panel
23
+ preloads stations and event/label choices from this service-scoped catalog.
24
+ Keep station `source`, `span_kind`, and `operation_type` statically resolvable
25
+ to preload them. Unresolved metadata registers the pair with
26
+ `station_known: false` and waits for live traffic to identify its station.
27
+ No source paths, payloads, latency, clients, or lanes are registered. Catalog
28
+ writes merge idempotently; removed declarations are not automatically deleted.
29
+ Registration failures use `onError` without blocking event capture. Both
30
+ `strictCatalog: false` and `verbose: false` disable scanning/registration.
31
+ - The scan includes all recognized TrafficWar calls under `catalogRoot`, not
32
+ only one client instance's calls. Use separate per-service source roots when
33
+ an application contains clients for different service keys.
34
+ - Automatic batching starts after one second or at 10,000 pending events;
35
+ the default queue bound is 100,000 unacknowledged events. Validation and
36
+ queue overflow can throw; do not let instrumentation replace an
37
+ application's response or hide its original error.
38
+ - Supply `onError` to observe background delivery failures. Await `close()`
39
+ at graceful shutdown or the end of a short-lived job; do not close or flush
40
+ the shared client on every request. Do not exit before shutdown finishes.
41
+ - Omit `event_id` to use the generated UUIDv7. Do not reuse IDs across
42
+ distinct events. Spans share `trace_id`, not `event_id`.
43
+
44
+ ## Stable event identity
45
+
46
+ - `event` is the category: `http`, `database`, `redis`, `s3`, or `external`.
47
+ `operation_type` names the work: `route.handler`, `postgres.select`,
48
+ `redis.get`, `s3.get_object`, or `payment.authorize`.
49
+ - `label` is a stable human operation name or route template, such as
50
+ `Checkout` or `GET /users/:id`. Never interpolate a user ID, query string,
51
+ timestamp, or request-specific value. String typing does not enforce this.
52
+ - `source` is a stable emitter/dependency alias: `backend-a`, `db-primary`,
53
+ `redis-1`, `assets.ovh-s3`, or `payment-gateway`. It is not the ingest host
54
+ or a request-specific URL. Allowlist caller-controlled hostnames before
55
+ using them as sources.
56
+ - `path` carries the route path. Prefer templates for parameterized routes;
57
+ avoid secrets and query strings. HTTP spans also carry `http_method` and
58
+ `status_code`.
59
+ - Put a pseudonymous actor identifier in `distinct_id`, a device identifier
60
+ in `properties`, and request correlation in `trace_id`. Do not use a raw
61
+ email address as the actor identifier.
62
+
63
+ ```ts
64
+ import { TrafficWar } from "@trafficwar/node";
65
+
66
+ const trafficwar = new TrafficWar({
67
+ apiKey: process.env.TRAFFICWAR_API_KEY!,
68
+ onError: (error) => console.error("TrafficWar delivery failed", error),
69
+ });
70
+
71
+ // After handling the request: use its measured start time and duration.
72
+ trafficwar.capture({
73
+ event: "http",
74
+ label: "Checkout",
75
+ source: "backend-a",
76
+ operation_type: "route.handler",
77
+ span_kind: "server",
78
+ path: "/v1/checkout",
79
+ http_method: "POST",
80
+ status_code: responseStatus,
81
+ timestamp: requestStartedAt,
82
+ latency_ms: measuredDurationMs,
83
+ });
84
+ ```
85
+
86
+ ## Traces and errors
87
+
88
+ - Spans for one request share `trace_id` and `label`. Measure durations with
89
+ a monotonic clock; `timestamp` is the actual span start as a `Date`, RFC3339
90
+ string, or integer epoch milliseconds. If captured after completion,
91
+ default capture-time timestamps do not describe the span's start.
92
+ - Keep inclusive durations nested. Emit dependency spans first, then the
93
+ server span, then an edge span if one was actually measured. Do not invent
94
+ browser latency or emit a synthetic edge span solely to populate the map.
95
+ - Incoming handlers use `event: "http"`, `span_kind: "server"`, and a backend
96
+ source. Outbound HTTP dependencies use `event: "external"`,
97
+ `span_kind: "client"`, and a stable dependency source. Database, Redis, and
98
+ S3 spans use their own categories and dependency sources.
99
+ - `event`, `source`, and `span_kind` determine tier placement; `source` can
100
+ take precedence over `span_kind`. Read the README's tier rules before
101
+ choosing a source. `operation_type` does not choose a tier.
102
+ - Errors require `status_code >= 400`, non-empty `error`, or non-empty
103
+ `error_code`. Put stack traces in `properties`. Properties alone do not
104
+ mark an event as an error; redact secrets before capture.
105
+
106
+ ## Startup inventory is best-effort diagnostics
107
+
108
+ - `verbose: true` prints a source inventory at client construction;
109
+ `debug: true` separately prints batch lifecycle logs. Both default to off.
110
+ - The AST inventory resolves literals, unchanged constant bindings, shorthand
111
+ fields, shared objects/arrays, static spreads/computed keys, string enums,
112
+ TypeScript assertions, and concatenations/templates with fixed inputs.
113
+ Relative ESM imports and reexports within the scan root are resolved too.
114
+ - Calls must belong to TrafficWar: import/require `@trafficwar/node`, construct
115
+ the client, or annotate an injected client/parameter with its imported
116
+ `TrafficWar` type. A variable named `client` alone is not evidence. Prefer
117
+ direct SDK calls with explicit stable identities inside framework hooks;
118
+ do not hide identity selection behind opaque wrappers.
119
+ - Optional/bracket calls, simple `.bind(client)` aliases, `captureBatch`,
120
+ `.call`/`.apply`, and calls inside template expressions are recognized.
121
+ The scanner never runs application code to determine values.
122
+ - Runtime values, opaque function results, parameter-derived identities,
123
+ TypeScript path aliases, dynamic imports, and CommonJS local export graphs
124
+ are not generally resolved. Mutated objects or objects passed to unknown
125
+ code are treated conservatively; unknown spreads/keys can override literals.
126
+ - Set `catalogRoot` to the application source directory. The scan defaults
127
+ to `process.cwd()`, runs synchronously per client, and skips dependencies,
128
+ build output (`dist`, `build`, `.next`, etc.), declarations, `test`/`tests`/
129
+ `__tests__`, and `*.test.*`/`*.spec.*`. Symlinks are skipped and mark the
130
+ scan incomplete. Limits: 4,000 files, depth 12, 512 KiB/file, 16 MiB total
131
+ source, 128 resolution levels, and 100,000 value evaluations.
132
+ - Other libraries' `capture` APIs and branches proven unreachable are ignored.
133
+ Conditions requiring runtime information and unused function bodies remain
134
+ scanned. This is bounded binding analysis, not a full TypeScript checker or
135
+ whole-program proof; an empty catalog does not prove missing instrumentation.
136
+ - No standalone CLI, framework route enumeration, or Python equivalent is
137
+ provided. Do not claim the startup list is an exhaustive event catalog or
138
+ proof that any listed event has been sent.
139
+
140
+ ## Default protection: strictCatalog
141
+
142
+ - `strictCatalog: true` is the default and requires fixed event/label
143
+ identities with source available at `catalogRoot`. It works independently
144
+ of `verbose`; verbose and debug output remain disabled by default.
145
+ - Explicit `strictCatalog: false` disables the startup gate and runtime
146
+ allowlist. With verbose also off, no source scan runs. This opt-out preserves
147
+ the previous unrestricted capture behavior; it is not a warning-only guard.
148
+ - Any missing/unresolved fields, failed or incomplete scan, or empty catalog
149
+ sets `captureEnabled` to false. Startup prints file/line issues with
150
+ `console.error`; subsequent capture calls enqueue nothing and the client
151
+ sends nothing. Fix the issues and recreate the client to enable capture.
152
+ - Unresolved does not mean proven dynamic. Use literals or statically
153
+ resolvable constants for event/label fields. Keep all required relative
154
+ imports inside `catalogRoot`; parse failures or missing local imports also
155
+ disable capture. Tests in nonstandard locations can still be scanned.
156
+ - Put runtime-dependent object spreads before explicit `event` and `label`
157
+ fields so those identities cannot be overridden by an unresolved spread.
158
+ - A clean catalog becomes a runtime pair allowlist. An unlisted event/label
159
+ throws `TrafficWarValidationError`, rejecting the entire capture call.
160
+ Previously queued valid events are still delivered. Catch instrumentation
161
+ errors where needed to preserve application responses.
162
+ - Do not restrict dynamic timestamps, measured durations, IDs, or properties.
163
+ This guard bounds event/label values; it cannot prove source provenance for
164
+ a computed runtime value that happens to equal a permitted pair.
package/README.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  Official, dependency-free TrafficWar server SDK for Node.js 22 and newer.
4
4
 
5
+ For AI-assisted integration, read [AGENTS.md](AGENTS.md). It ships with the
6
+ npm package at `node_modules/@trafficwar/node/AGENTS.md`; link that path from
7
+ your application's own agent guidance so the agent knows to read it.
8
+
5
9
  ## Install
6
10
 
7
11
  ```sh
@@ -49,6 +53,12 @@ request.
49
53
  enqueues the input synchronously, then returns `void`; it does not return an
50
54
  `IngestResult` or wait for the network.
51
55
 
56
+ **Strict catalog protection is enabled by default.** Application source must
57
+ be available under `catalogRoot` (default: `process.cwd()`). Startup catalog
58
+ issues disable capture without preventing the application from starting.
59
+ See [Default event/label protection](#default-eventlabel-protection) before
60
+ deploying a source-free build or upgrading an existing integration.
61
+
52
62
  `Date` timestamps are serialized as RFC3339 without changing the caller's
53
63
  object. String timestamps must be RFC3339; numeric timestamps are integer epoch
54
64
  milliseconds. If `timestamp` is omitted, the SDK sets it to the current time at
@@ -89,13 +99,13 @@ const trafficwar = new TrafficWar({
89
99
  });
90
100
  ```
91
101
 
92
- Set `verbose: true` to print, once at startup, every `event` and `label` the
93
- SDK can see statically in `capture()` calls under the working directory (or
94
- `catalogRoot`). String literals are printed as written. A present value that
95
- is not a static string is printed as `<dynamic>`, and a missing one as
96
- `<missing>`. The scan skips `node_modules` and does not print payloads, API
97
- keys, or other properties. A scan failure is logged and does not stop the
98
- client.
102
+ Set `verbose: true` to print, once per client at startup, `capture()` calls whose
103
+ `event` and `label` resolve to fixed strings. The scan looks under the
104
+ working directory, or `catalogRoot` when that is set. A call is omitted when
105
+ either value is missing or unresolved. The scan skips `node_modules` and does not print
106
+ payloads, API keys, or other properties. Scanning runs by default because
107
+ strict protection is enabled; verbose only controls inventory output. A scan
108
+ failure is logged and disables capture unless `strictCatalog: false` is set.
99
109
 
100
110
  ```ts
101
111
  const trafficwar = new TrafficWar({
@@ -104,6 +114,128 @@ const trafficwar = new TrafficWar({
104
114
  });
105
115
  ```
106
116
 
117
+ This is a best-effort source inventory, not a complete list of instrumented
118
+ routes or proof of delivery. AST binding analysis recognizes literals, unchanged
119
+ constant bindings, shorthand, shared objects/arrays, static spreads and keys,
120
+ string enums, TypeScript assertions, and concatenations/templates with fixed
121
+ inputs. Relative ESM imports/reexports inside the root are resolved. The
122
+ scanner never executes application code.
123
+
124
+ Calls are attributed to imports/require of `@trafficwar/node`, constructed
125
+ clients, aliases, and injected clients with an imported `TrafficWar` type.
126
+ Optional/bracket calls, simple `.bind(client)` aliases, `captureBatch`,
127
+ `.call`/`.apply`, and calls inside template expressions are recognized.
128
+ Other libraries' `capture` methods, comments/regex text, conventional tests,
129
+ and branches proven unreachable are ignored. Runtime-dependent branches and
130
+ unused function bodies remain scanned; this is not whole-program reachability.
131
+
132
+ Opaque function results, wrapper parameters, TypeScript path aliases, dynamic
133
+ imports, and CommonJS local export graphs are not generally resolved. Unknown
134
+ spreads/keys can override preceding literals. Mutated objects and objects
135
+ passed to opaque code are treated conservatively, even if their declarations
136
+ use `const`. Type annotations alone do not prove that identities are static.
137
+
138
+ Scanning is synchronous and bounded to 4,000 source files, depth 12, and
139
+ 512 KiB per file, with a 16 MiB total source budget, 128 resolution levels,
140
+ and 100,000 value evaluations. Declarations, `test`/`tests`/`__tests__`, and
141
+ `*.test.*`/`*.spec.*` are skipped, along with symlinks and build directories
142
+ such as `dist`, `build`, and `.next`. The parser is bundled at build time;
143
+ the package still has no npm runtime dependencies. Point `catalogRoot` at available application
144
+ source; a production image containing only build output can print an empty
145
+ catalog. No standalone inventory CLI or framework route discovery is included.
146
+
147
+ ### Register the startup catalog
148
+
149
+ A complete, non-empty source scan registers its deduplicated declarations with
150
+ `POST /v1/server/catalog` in the background at construction, before any request
151
+ is captured. Authentication uses the same service API key. The wire contains
152
+ only `event`, `label`, statically resolved `source`, `span_kind`,
153
+ `operation_type`, and `station_known`; source files, line numbers, paths to the
154
+ scan root, properties, and request identifiers are never uploaded.
155
+
156
+ The panel reads `GET /panel/api/catalog?service=<service_id>` to preload idle
157
+ SpaceWar stations and event/label choices. API-key callers can also read
158
+ `GET /v1/server/catalog`, pinned to their key's service. Declarations are not
159
+ events and do not create traffic, clients, latency samples, or map lanes.
160
+ Registration merges idempotently per service, so replicas and separate apps
161
+ cannot erase one another's declarations. Removed declarations are not deleted
162
+ automatically. The API accepts at most 4,000 distinct declarations per service.
163
+
164
+ The scan includes all recognized TrafficWar calls under `catalogRoot`; it does
165
+ not attribute calls to individual client instances. Applications with multiple
166
+ service keys should use separate per-service source roots to avoid registering
167
+ another service's declarations.
168
+
169
+ Dynamic station metadata is omitted and marked `station_known: false`: the
170
+ event/label pair still populates selectors, but the station waits for real
171
+ traffic. Missing optional fields use the same defaults as ingest. The map
172
+ keeps its existing station/instance limits and folds overflow into `other`.
173
+
174
+ Registration uses the client's bounded retries and timeout. Failures go to
175
+ `onError` and never disable event delivery. `close()` also waits for registration;
176
+ its accepted count remains event-only. Empty, failed, incomplete, or blocked
177
+ scans do not upload. Setting both `strictCatalog: false` and `verbose: false`
178
+ opts out of scanning and registration; verbose-only mode registers only clean,
179
+ complete scans. Python does not yet register a catalog.
180
+
181
+ ### Default event/label protection
182
+
183
+ `strictCatalog` defaults to `true` and disables capture if the startup scan finds any
184
+ missing or unresolved `event`/`label`. The SDK prints the affected file and
185
+ object/argument line with `console.error`, even when `verbose` is off. A
186
+ failed, incomplete, or empty scan also disables capture. The application can
187
+ still start: `client.captureEnabled` is `false`, capture calls enqueue
188
+ nothing, and `flush()`/`close()` return zero accepted events without sending.
189
+ Fix the source and recreate the client; there is no automatic rescan.
190
+
191
+ ```ts
192
+ const trafficwar = new TrafficWar({
193
+ apiKey: process.env.TRAFFICWAR_API_KEY!,
194
+ strictCatalog: true,
195
+ catalogRoot: "./src",
196
+ verbose: true, // Optional: also print the catalog when the check passes.
197
+ });
198
+ ```
199
+
200
+ An example startup error is:
201
+
202
+ ```text
203
+ [TrafficWar] capture disabled by strictCatalog; fix these issues and restart the client:
204
+ checkout.ts:42: label missing or not a statically resolved string
205
+ ```
206
+
207
+ If the scan passes, capture accepts only exact event/label pairs in that
208
+ startup catalog. An unlisted pair throws `TrafficWarValidationError` before
209
+ any events from that call are queued; already queued valid events remain
210
+ deliverable. Catch instrumentation validation errors at the application's
211
+ boundary if they must not affect request handling. Dynamic timestamps,
212
+ durations, actor IDs, paths, and properties are not restricted by this guard.
213
+
214
+ This is deliberately conservative, not proof that a value changes at runtime:
215
+ unsupported expressions and opaque wrapper arguments remain unresolved.
216
+ Point `catalogRoot` at the instrumented application source, including required
217
+ relative imports. Source must be present; skipped symlinks, missing local
218
+ imports, parse errors, and unreadable/oversized files make the scan incomplete.
219
+ The scanner cannot establish the provenance of runtime values; a computed value
220
+ equal to an allowed pair can pass the runtime check. `strictCatalog` defaults
221
+ to `true`, while `verbose` and `debug` remain `false`. Python has no equivalent.
222
+
223
+ This default changes existing integrations: source-free builds, missing labels,
224
+ or unsupported/unresolved instrumentation will stop sending until the source
225
+ is fixed or the application deliberately opts out. To retain the previous
226
+ unrestricted capture behavior, explicitly set:
227
+
228
+ ```ts
229
+ const trafficwar = new TrafficWar({
230
+ apiKey: process.env.TRAFFICWAR_API_KEY!,
231
+ strictCatalog: false,
232
+ });
233
+ ```
234
+
235
+ Opting out disables both startup blocking and the runtime pair allowlist.
236
+ With verbose also off, no source scan runs; with verbose on, the inventory
237
+ remains diagnostics only and never blocks capture.
238
+
107
239
  The SDK generates a process-monotonic RFC 9562 UUIDv7 `event_id` for each event
108
240
  that omits one. A caller may override it with any valid UUID. Caller-owned
109
241
  objects are never modified.
@@ -338,9 +470,13 @@ delivery still fails.
338
470
  - `debug`: print safe batch lifecycle diagnostics with `console.debug`.
339
471
  Defaults to `false`.
340
472
  - `verbose`: at startup, statically scan source for `capture()` calls and
341
- print each `event` and `label`. Defaults to `false`.
342
- - `catalogRoot`: directory scanned when `verbose` is true. Defaults to the
343
- process working directory.
473
+ print pairs whose `event` and `label` resolve to fixed strings.
474
+ Unresolved or missing values are omitted. Defaults to `false`.
475
+ - `strictCatalog`: disable capture on unresolved/empty/incomplete source scans
476
+ and reject runtime pairs outside the startup catalog. Defaults to `true`;
477
+ explicitly set `false` to opt out.
478
+ - `catalogRoot`: directory scanned when `verbose` or `strictCatalog` is true.
479
+ Defaults to the process working directory.
344
480
  - `timeoutMs`: timeout for each attempt. Defaults to 30,000 ms, safely above
345
481
  TrafficWar's 10-second durable acknowledgement window.
346
482
  - `maxRetries`: retries after the first attempt. Defaults to 3.
@@ -0,0 +1,58 @@
1
+ # Bundled third-party software
2
+
3
+ The Node distribution includes the following parser dependencies and their
4
+ transitive dependencies. They do not require separate npm installations.
5
+
6
+ ## MIT-licensed components
7
+
8
+ - `@babel/parser`: Copyright (C) 2012-2014 by various contributors (see AUTHORS).
9
+ - `@babel/traverse`, `@babel/types`, `@babel/template`, `@babel/generator`,
10
+ `@babel/code-frame`, `@babel/helper-globals`, `@babel/helper-string-parser`,
11
+ `@babel/helper-validator-identifier`: Copyright (c) 2014-present Sebastian
12
+ McKenzie and other contributors.
13
+ - `@jridgewell/gen-mapping`, `@jridgewell/sourcemap-codec`,
14
+ `@jridgewell/trace-mapping`: Copyright 2024 Justin Ridgewell
15
+ <justin@ridgewell.name>.
16
+ - `@jridgewell/resolve-uri`: Copyright 2019 Justin Ridgewell
17
+ <jridgewell@google.com>.
18
+ - `debug`: Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>;
19
+ Copyright (c) 2018-2021 Josh Junon.
20
+ - `js-tokens`: Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell.
21
+ - `jsesc`: Copyright Mathias Bynens <https://mathiasbynens.be/>.
22
+ - `ms`: Copyright (c) 2020 Vercel, Inc.
23
+
24
+ The following MIT permission notice applies to each component above:
25
+
26
+ Permission is hereby granted, free of charge, to any person obtaining a copy
27
+ of this software and associated documentation files (the "Software"), to deal
28
+ in the Software without restriction, including without limitation the rights
29
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
30
+ copies of the Software, and to permit persons to whom the Software is
31
+ furnished to do so, subject to the following conditions:
32
+
33
+ The above copyright notice and this permission notice shall be included in
34
+ all copies or substantial portions of the Software.
35
+
36
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
37
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
38
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
39
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
40
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
41
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
42
+ THE SOFTWARE.
43
+
44
+ ## picocolors — ISC License
45
+
46
+ Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov
47
+
48
+ Permission to use, copy, modify, and/or distribute this software for any
49
+ purpose with or without fee is hereby granted, provided that the above
50
+ copyright notice and this permission notice appear in all copies.
51
+
52
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
53
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
54
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
55
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
56
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
57
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
58
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.