@lensmcp/nest-instrumentation 1.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/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 ADDED
@@ -0,0 +1,158 @@
1
+ # @lensmcp/nest-instrumentation
2
+
3
+ Zero-config NestJS instrumentation for [LensMCP](https://github.com/kiwiapps-ltd/lensmcp) — the observability lens for coding agents.
4
+
5
+ This package wires LensMCP into a NestJS application so an agent can _see_ how requests actually flow through it: every controller hop and provider-method call becomes a timed span, each HTTP request becomes a `server-request` event with method/route/status/duration, repeated DB / Redis / external calls inside one method surface as `loop` (N+1) warnings, and the live provider graph is materialised from `singleton-instance` events. All of it is correlated by a per-request `flowId` / `requestId` carried across async boundaries via `AsyncLocalStorage`, so the trace from an inbound request through its services, queries, and queue jobs stays connected.
6
+
7
+ There are two ways to turn it on, and **you only need one**:
8
+
9
+ 1. **Explicit drop-in.** Replace `NestFactory.create(AppModule)` with `createLensmcpNestApp(AppModule, …)` in your `main.ts`. One import, no edits to `AppModule`.
10
+ 2. **Zero-touch graft.** Do nothing. When [`@lensmcp/node-instrumentation`](https://github.com/kiwiapps-ltd/lensmcp) is loaded into the process, it patches `NestFactory.create` and grafts `LensmcpModule.forRoot` around your root module automatically — no import in your source at all. This is how LensMCP instruments apps under its zero-touch runtime.
11
+
12
+ Both paths produce the same instrumentation; the drop-in is just the graft done by hand.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ yarn add @lensmcp/nest-instrumentation
18
+ ```
19
+
20
+ `@nestjs/common`, `@nestjs/core` (`>=10 <12`), and `rxjs` (`^7`) are peer dependencies — already present in any Nest app.
21
+
22
+ ## Usage
23
+
24
+ In your `main.ts`, swap `NestFactory.create` for `createLensmcpNestApp`:
25
+
26
+ ```ts
27
+ // main.ts
28
+ import { createLensmcpNestApp } from '@lensmcp/nest-instrumentation';
29
+ import { AppModule } from './app.module';
30
+
31
+ const app = await createLensmcpNestApp(AppModule, {
32
+ projectName: 'api',
33
+ });
34
+
35
+ await app.listen(3100);
36
+ ```
37
+
38
+ That is the whole setup. `createLensmcpNestApp` builds a wrapper root module that imports both `LensmcpModule` and your `AppModule`, then calls `NestFactory.create` for you — so `AppModule` is never touched. Because the wrapper lists LensMCP first, the trace interceptor is registered **outermost**: a user interceptor that short-circuits (e.g. a cache hit) cannot bypass tracing.
39
+
40
+ The drop-in turns on zero-config defaults: `trace.autoInstrumentMethods` is `true` and `memory` defaults to `{ mode: 'light', scope: 'all' }`, so every provider's methods are traced and every provider's `Map` / `Set` / `Array` fields are watched for growth — with no `@TraceMethod` or `@TraceProvider` decorators required. You can override any of these:
41
+
42
+ ```ts
43
+ const app = await createLensmcpNestApp(AppModule, {
44
+ projectName: 'api',
45
+ trace: { autoInstrumentMethods: true, db: true },
46
+ memory: { mode: 'light', scope: 'tagged' },
47
+ nestOptions: { cors: true }, // forwarded to NestFactory.create
48
+ });
49
+ ```
50
+
51
+ `projectName` falls back to `process.env.LENSMCP_PROJECT` (then `'app'`) if omitted. The event sink is auto-selected from the environment (see [How it fits](#how-it-fits)).
52
+
53
+ ### Zero-touch alternative
54
+
55
+ If the process is already running [`@lensmcp/node-instrumentation`](https://github.com/kiwiapps-ltd/lensmcp), you do not need this import at all. It grafts `LensmcpModule.forRoot({ trace: { autoInstrumentMethods: true }, memory: { mode: 'light', scope: 'all' } })` around your root module the moment `NestFactory.create` is called. An ordinary `main.ts` —
56
+
57
+ ```ts
58
+ const app = await NestFactory.create(AppModule);
59
+ await app.listen(3100);
60
+ ```
61
+
62
+ — comes up fully instrumented with **zero lens code in your source**. Roots already wrapped by `createLensmcpNestApp` carry a marker and are left alone, so the two paths never double-wrap.
63
+
64
+ ### Manual module wiring (advanced)
65
+
66
+ If you build your own root module instead of using the drop-in, import `LensmcpModule.forRoot(...)` directly:
67
+
68
+ ```ts
69
+ import { Module } from '@nestjs/common';
70
+ import { LensmcpModule } from '@lensmcp/nest-instrumentation';
71
+
72
+ @Module({
73
+ imports: [LensmcpModule.forRoot({ projectName: 'api' })],
74
+ })
75
+ export class AppModule {}
76
+ ```
77
+
78
+ Note that `forRoot` does **not** default `autoInstrumentMethods` on — only `createLensmcpNestApp` and the zero-touch graft do. Imported bare, you opt methods in per-class with `@TraceMethod()` (or enable `trace.autoInstrumentMethods` yourself).
79
+
80
+ ## What it captures
81
+
82
+ - **Request flows** — an `APP_INTERCEPTOR` (`TraceInterceptor`) brackets every HTTP request. It reads `x-request-id`, `x-lensmcp-flow-id`, `x-lensmcp-origin-node-id`, and W3C `traceparent` headers, opens a `LensmcpRequestContext` in `AsyncLocalStorage`, and on completion emits a `server-request` event (method, route, status, duration) plus a span. Errors are resolved to their real HTTP status (via `HttpException.getStatus()` or a `status` / `statusCode` field) rather than Nest's not-yet-written default.
83
+ - **Controller hops** — the interceptor times the controller method itself and emits a `Controller.handler (12ms)` span with `role: 'controller'`, so the trace shows the controller between the request and its services instead of skipping straight to the service.
84
+ - **Provider-method traces** — when `trace.autoInstrumentMethods` is on, `LensmcpProviderTracker` walks the Nest container at bootstrap and wraps each provider's own prototype methods with a traced wrapper (in place, preserving `this`). Singleton instances are wrapped per-instance; request-scoped / transient providers are wrapped once on the shared prototype so every per-request instance is covered. Lifecycle hooks (`onModuleInit`, `onApplicationBootstrap`, etc.), getters/setters, methods already decorated with `@TraceMethod`, and anything marked `@LensmcpIgnore` are skipped.
85
+ - **N+1 / fan-out detection** — each traced method snapshots the request's DB / Redis / external counters on entry; if a method issues ≥3 operations of the same class, it emits a `loop` warning (e.g. `loop in OrdersService.list (12 DB calls)`). DB call counts come from `@TraceMethod({ db: true })` and from the zero-touch taps in `@lensmcp/node-instrumentation` (pg, ioredis, fetch/http).
86
+ - **Provider graph & lifecycle** — every controller and provider emits a `singleton-instance` event at bootstrap (with module, scope, and a `generation` counter that increments on each `forRoot` / hot reload) and a `disposed` event on module destroy, so the agent can materialise the live provider tree and tell a new generation from a stale one.
87
+ - **Memory** — when `memory.mode !== 'off'`, container fields (`Map` / `Set` / `Array`) on providers are tracked for size and growth via `@lensmcp/memory-tracker`. `scope: 'all'` watches every provider; `scope: 'tagged'` watches only those marked `@TraceProvider({ memory: true })`. Each request is bracketed as a "flow" so the suspect-leak detector can compare container sizes at request start vs. after it settles. `mode: 'deep'` additionally enables heap snapshots.
88
+
89
+ ## API
90
+
91
+ ### `createLensmcpNestApp(appModule, options?)`
92
+
93
+ ```ts
94
+ function createLensmcpNestApp(
95
+ appModule: Type<unknown> | DynamicModule,
96
+ options?: CreateLensmcpNestAppOptions,
97
+ ): Promise<INestApplication>;
98
+ ```
99
+
100
+ Drop-in for `NestFactory.create`. Returns a standard `INestApplication`. Applies the zero-config defaults described above.
101
+
102
+ `CreateLensmcpNestAppOptions` extends `Partial<LensmcpModuleOptions>` (below) and adds:
103
+
104
+ | Option | Type | Description |
105
+ | ------------- | ------------------------ | -------------------------------------------------------- |
106
+ | `nestOptions` | `NestApplicationOptions` | Forwarded to `NestFactory.create` (logger, CORS, etc.). |
107
+
108
+ ### `LensmcpModule.forRoot(options)`
109
+
110
+ ```ts
111
+ LensmcpModule.forRoot(options: LensmcpModuleOptions): DynamicModule;
112
+ ```
113
+
114
+ Returns a **global** dynamic module that registers the `TraceInterceptor` as an `APP_INTERCEPTOR` and the `LensmcpProviderTracker`, and (when memory is enabled) configures `@lensmcp/memory-tracker`. Options resolve synchronously at call time, so `@TraceMethod` decorators applied to constructor-injected providers find them at decoration time.
115
+
116
+ #### `LensmcpModuleOptions`
117
+
118
+ | Option | Type | Default | Description |
119
+ | ------------- | ----------------------------------------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------- |
120
+ | `projectName` | `string` | _(required)_ | Stamped onto every event for resource routing. |
121
+ | `sessionId` | `string` | `process.env.LENSMCP_SESSION_ID` or a fresh id | Session id stamped onto every event. |
122
+ | `emit` | `EventSink` | env-selected (see below) | Override where events go. |
123
+ | `trace` | object _(below)_ | tracing on, `db`/`redis`/`queues`/auto off | Which trace layers to enable. |
124
+ | `memory` | `{ mode?: 'off' \| 'light' \| 'deep'; scope?: 'tagged' \| 'all' }` | `{ mode: 'off', scope: 'tagged' }` | Memory container tracking. (`createLensmcpNestApp` / zero-touch default this to `light` / `all`.) |
125
+
126
+ `trace` fields (all booleans): `requests`, `guards`, `controllers`, `services` default `true`; `db`, `redis`, `queues` default `false`; `autoInstrumentMethods` defaults `false` for bare `forRoot` and `true` for `createLensmcpNestApp` / the zero-touch graft.
127
+
128
+ ### Decorators
129
+
130
+ - **`@TraceMethod(name?)`** / **`@TraceMethod({ name?, db? })`** — trace a single method; emits a span per call. `db: true` marks it a DB query (emits a `db-query` event and bumps the request DB counter).
131
+ - **`@TraceProvider({ memory? })`** — opt a provider into memory container tracking when `memory.scope === 'tagged'`.
132
+ - **`@LensmcpIgnore()`** — exclude a class (all methods) or a single method from auto-instrumentation.
133
+
134
+ ### Low-level building blocks
135
+
136
+ Re-exported for advanced use and custom integrations:
137
+
138
+ - `TraceInterceptor`, `LensmcpProviderTracker` — the interceptor and tracker registered by `forRoot`.
139
+ - `traceWrap(fn, spanName, { db? })`, `isTraced(fn)`, `isIgnored(target)` — the shared method-tracing core.
140
+ - `readTraceProvider(ctor)` — read `@TraceProvider` metadata off a class.
141
+ - `LENSMCP_CONTEXT_STORAGE`, `currentLensmcpContext()`, `runInLensmcpContext(ctx, fn)` — the per-request `AsyncLocalStorage`.
142
+ - `defaultEventSink()`, `inMemorySink()` — the env-driven sink and an in-memory sink for tests.
143
+
144
+ ### Key types
145
+
146
+ `CreateLensmcpNestAppOptions`, `LensmcpModuleOptions`, `ResolvedOptions`, `EventSink`, `LensmcpRequestContext`, `TraceMethodOptions`, `TraceProviderOptions`.
147
+
148
+ ## How it fits
149
+
150
+ `@lensmcp/nest-instrumentation` is the NestJS adapter in the LensMCP stack. It is **grafted automatically by `@lensmcp/node-instrumentation`** under the zero-touch runtime — which patches `NestFactory.create` and dynamically imports this package to call `LensmcpModule.forRoot` — so host source stays lens-free. Used by hand, the `createLensmcpNestApp` drop-in does the same wiring with one import.
151
+
152
+ Every event it emits is a `BaseEvent` from [`@lensmcp/protocol-types`](https://github.com/kiwiapps-ltd/lensmcp) (kinds: `server-request`, `span`, `db-query`, `loop`, `singleton-instance`), shared by every LensMCP source so they reduce into the same resource views. Memory tracking is delegated to `@lensmcp/memory-tracker`, and ids / fingerprints come from `@lensmcp/core`.
153
+
154
+ By default events are routed by `defaultEventSink()`, which picks a transport from the environment: `LENSMCP_EVENT_FILE` (append JSONL), `LENSMCP_UDS` (reconnecting NDJSON over a Unix domain socket), or `LENSMCP_IPC_SOCKET` (UDP datagrams); with no session configured it falls back to logging only errors to stdout under a `[lensmcp]` prefix.
155
+
156
+ ---
157
+
158
+ Part of [LensMCP](https://github.com/kiwiapps-ltd/lensmcp). Apache-2.0.
package/index.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export { LensmcpModule } from './lib/lensmcp.module.js';
2
+ export { createLensmcpNestApp, type CreateLensmcpNestAppOptions, } from './lib/lensmcp-app.js';
3
+ export { TraceMethod, type TraceMethodOptions } from './lib/trace-method.js';
4
+ export { LensmcpIgnore, traceWrap, isTraced, isIgnored } from './lib/instrument.js';
5
+ export { TraceInterceptor } from './lib/trace-interceptor.js';
6
+ export { LensmcpProviderTracker } from './lib/provider-tracker.js';
7
+ export { TraceProvider, readTraceProvider, type TraceProviderOptions, } from './lib/trace-provider.js';
8
+ export { LENSMCP_CONTEXT_STORAGE, currentLensmcpContext, runInLensmcpContext, type LensmcpRequestContext, } from './lib/context.js';
9
+ export { defaultEventSink, inMemorySink } from './lib/event-sink.js';
10
+ export type { LensmcpModuleOptions, EventSink, ResolvedOptions } from './lib/types.js';
11
+ //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EACL,oBAAoB,EACpB,KAAK,2BAA2B,GACjC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,WAAW,EAAE,KAAK,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC7E,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACpF,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnE,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,KAAK,oBAAoB,GAC1B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,uBAAuB,EACvB,qBAAqB,EACrB,mBAAmB,EACnB,KAAK,qBAAqB,GAC3B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACrE,YAAY,EAAE,oBAAoB,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC"}
package/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { LensmcpModule } from './lib/lensmcp.module.js';
2
+ export { createLensmcpNestApp, } from './lib/lensmcp-app.js';
3
+ export { TraceMethod } from './lib/trace-method.js';
4
+ export { LensmcpIgnore, traceWrap, isTraced, isIgnored } from './lib/instrument.js';
5
+ export { TraceInterceptor } from './lib/trace-interceptor.js';
6
+ export { LensmcpProviderTracker } from './lib/provider-tracker.js';
7
+ export { TraceProvider, readTraceProvider, } from './lib/trace-provider.js';
8
+ export { LENSMCP_CONTEXT_STORAGE, currentLensmcpContext, runInLensmcpContext, } from './lib/context.js';
9
+ export { defaultEventSink, inMemorySink } from './lib/event-sink.js';
@@ -0,0 +1,37 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ /**
3
+ * Per-request context propagated across async boundaries via
4
+ * `AsyncLocalStorage`. Lets `@TraceMethod`-decorated service calls,
5
+ * DB queries, and queue jobs all stamp the correct `flowId` /
6
+ * `requestId` / `traceparent` without needing to thread them through
7
+ * every function call.
8
+ *
9
+ * Filled by `TraceInterceptor` at the start of every server request.
10
+ */
11
+ export interface LensmcpRequestContext {
12
+ /** Lensmcp session id stamped onto every event in this request. */
13
+ sessionId: string;
14
+ /** Per-request id; matches the `x-request-id` header if present. */
15
+ requestId: string;
16
+ /** Causal chain id, propagated from the upstream caller. */
17
+ flowId?: string;
18
+ /** Originating node in the structural tree (frontend button, effect, etc.). */
19
+ originNodeId?: string;
20
+ /** W3C Trace Context header. */
21
+ traceparent?: string;
22
+ /**
23
+ * Monotonic operation counters for this request, mutated in place.
24
+ * Incremented by the zero-touch taps (@lensmcp/node-instrumentation: pg,
25
+ * ioredis, fetch/http egress) and by `@TraceMethod({ db: true })`. Every
26
+ * traced method snapshots them on entry and, on exit, emits a `loop`
27
+ * event when the deltas show the method issued multiple operations —
28
+ * the N+1 / fan-out signal.
29
+ */
30
+ dbCallCount?: number;
31
+ redisCallCount?: number;
32
+ externalCallCount?: number;
33
+ }
34
+ export declare const LENSMCP_CONTEXT_STORAGE: AsyncLocalStorage<LensmcpRequestContext>;
35
+ export declare function currentLensmcpContext(): LensmcpRequestContext | undefined;
36
+ export declare function runInLensmcpContext<T>(ctx: LensmcpRequestContext, fn: () => T): T;
37
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/lib/context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD;;;;;;;;GAQG;AACH,MAAM,WAAW,qBAAqB;IACpC,mEAAmE;IACnE,SAAS,EAAE,MAAM,CAAC;IAClB,oEAAoE;IACpE,SAAS,EAAE,MAAM,CAAC;IAClB,4DAA4D;IAC5D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+EAA+E;IAC/E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,gCAAgC;IAChC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,eAAO,MAAM,uBAAuB,0CAAiD,CAAC;AAEtF,wBAAgB,qBAAqB,IAAI,qBAAqB,GAAG,SAAS,CAEzE;AAED,wBAAgB,mBAAmB,CAAC,CAAC,EACnC,GAAG,EAAE,qBAAqB,EAC1B,EAAE,EAAE,MAAM,CAAC,GACV,CAAC,CAEH"}
package/lib/context.js ADDED
@@ -0,0 +1,8 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ export const LENSMCP_CONTEXT_STORAGE = new AsyncLocalStorage();
3
+ export function currentLensmcpContext() {
4
+ return LENSMCP_CONTEXT_STORAGE.getStore();
5
+ }
6
+ export function runInLensmcpContext(ctx, fn) {
7
+ return LENSMCP_CONTEXT_STORAGE.run(ctx, fn);
8
+ }
@@ -0,0 +1,23 @@
1
+ import type { BaseEvent } from '@lensmcp/protocol-types';
2
+ import type { EventSink } from './types.js';
3
+ /**
4
+ * Resolve an `EventSink` from env vars + caller overrides.
5
+ *
6
+ * Resolution order:
7
+ * 1. `LENSMCP_EVENT_FILE` — append one JSON line per event.
8
+ * The Phase 3 e2e smoke uses this (no IPC plumbing needed).
9
+ * 2. `LENSMCP_UDS` — Unix domain socket, framed NDJSON, reconnecting.
10
+ * The hardened transport (reliable, no datagram size cap).
11
+ * 3. `LENSMCP_IPC_SOCKET` — UDP datagram per event (one-shot, lossy).
12
+ * 4. fallthrough — write to stdout under a `[lensmcp]` prefix so
13
+ * humans can see something useful even without a session.
14
+ *
15
+ * The UDS client is a compact mirror of `@lensmcp/session`'s `createUdsSink`
16
+ * (inlined to keep this app-injected lib free of the session bundle).
17
+ */
18
+ export declare function defaultEventSink(): EventSink;
19
+ export declare function inMemorySink(): {
20
+ sink: EventSink;
21
+ events: BaseEvent[];
22
+ };
23
+ //# sourceMappingURL=event-sink.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-sink.d.ts","sourceRoot":"","sources":["../../src/lib/event-sink.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,IAAI,SAAS,CAoC5C;AAED,wBAAgB,YAAY,IAAI;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,MAAM,EAAE,SAAS,EAAE,CAAA;CAAE,CAGvE"}
@@ -0,0 +1,110 @@
1
+ import { createSocket } from 'node:dgram';
2
+ import { connect } from 'node:net';
3
+ import { appendFile } from 'node:fs/promises';
4
+ /**
5
+ * Resolve an `EventSink` from env vars + caller overrides.
6
+ *
7
+ * Resolution order:
8
+ * 1. `LENSMCP_EVENT_FILE` — append one JSON line per event.
9
+ * The Phase 3 e2e smoke uses this (no IPC plumbing needed).
10
+ * 2. `LENSMCP_UDS` — Unix domain socket, framed NDJSON, reconnecting.
11
+ * The hardened transport (reliable, no datagram size cap).
12
+ * 3. `LENSMCP_IPC_SOCKET` — UDP datagram per event (one-shot, lossy).
13
+ * 4. fallthrough — write to stdout under a `[lensmcp]` prefix so
14
+ * humans can see something useful even without a session.
15
+ *
16
+ * The UDS client is a compact mirror of `@lensmcp/session`'s `createUdsSink`
17
+ * (inlined to keep this app-injected lib free of the session bundle).
18
+ */
19
+ export function defaultEventSink() {
20
+ const filePath = process.env['LENSMCP_EVENT_FILE'];
21
+ if (filePath) {
22
+ return (event) => {
23
+ void appendFile(filePath, JSON.stringify(event) + '\n').catch(() => undefined);
24
+ };
25
+ }
26
+ const udsPath = process.env['LENSMCP_UDS'];
27
+ if (udsPath) {
28
+ return udsEventSink(udsPath);
29
+ }
30
+ const socketPath = process.env['LENSMCP_IPC_SOCKET'];
31
+ if (socketPath) {
32
+ const [host, portStr] = socketPath.split(':');
33
+ if (host && portStr) {
34
+ const port = Number(portStr);
35
+ const sock = createSocket('udp4');
36
+ sock.unref();
37
+ return (event) => {
38
+ try {
39
+ const buf = Buffer.from(JSON.stringify(event));
40
+ sock.send(buf, port, host, () => undefined);
41
+ }
42
+ catch {
43
+ /* swallow */
44
+ }
45
+ };
46
+ }
47
+ }
48
+ return (event) => {
49
+ if (event.severity === 'error' || event.severity === 'fatal') {
50
+ console.warn(`[lensmcp] ${event.severity}: ${event.title}`);
51
+ }
52
+ };
53
+ }
54
+ export function inMemorySink() {
55
+ const events = [];
56
+ return { sink: (e) => events.push(e), events };
57
+ }
58
+ /** Reconnecting NDJSON client over a Unix domain socket (see uds.ts). */
59
+ function udsEventSink(path) {
60
+ const queue = [];
61
+ let sock = null;
62
+ let connecting = false;
63
+ const flush = () => {
64
+ if (!sock || !sock.writable)
65
+ return;
66
+ while (queue.length > 0)
67
+ sock.write(queue.shift());
68
+ };
69
+ const open = () => {
70
+ if (connecting || sock)
71
+ return;
72
+ connecting = true;
73
+ const s = connect(path);
74
+ s.on('connect', () => {
75
+ connecting = false;
76
+ sock = s;
77
+ flush();
78
+ });
79
+ s.on('drain', flush);
80
+ s.on('error', () => {
81
+ connecting = false;
82
+ sock = null;
83
+ });
84
+ s.on('close', () => {
85
+ sock = null;
86
+ });
87
+ s.unref();
88
+ };
89
+ open();
90
+ return (event) => {
91
+ queue.push(JSON.stringify(event) + '\n');
92
+ while (queue.length > 10000)
93
+ queue.shift();
94
+ if (sock && sock.writable) {
95
+ flush();
96
+ return;
97
+ }
98
+ // Dead socket (server restart) — drop it so open() reconnects.
99
+ if (sock) {
100
+ try {
101
+ sock.destroy();
102
+ }
103
+ catch {
104
+ /* ignore */
105
+ }
106
+ sock = null;
107
+ }
108
+ open();
109
+ };
110
+ }
@@ -0,0 +1,17 @@
1
+ /** Marks a function already wrapped by traceWrap (avoids double-wrap). */
2
+ export declare const LENSMCP_TRACED: unique symbol;
3
+ /** Marks a class/method opted out of auto-instrumentation. */
4
+ export declare const LENSMCP_IGNORE: unique symbol;
5
+ export interface TraceWrapOptions {
6
+ db?: boolean;
7
+ }
8
+ /** `@LensmcpIgnore()` — skip a class (all methods) or a single method. */
9
+ export declare function LensmcpIgnore(): ClassDecorator & MethodDecorator;
10
+ export declare function isTraced(fn: unknown): boolean;
11
+ export declare function isIgnored(target: unknown): boolean;
12
+ /**
13
+ * Wrap `fn` with span + db-call tracing. Pure: no decorator/Nest
14
+ * coupling, so the auto-instrumenter can apply it to any instance method.
15
+ */
16
+ export declare function traceWrap<F extends (...args: never[]) => unknown>(fn: F, spanName: string, options?: TraceWrapOptions): F;
17
+ //# sourceMappingURL=instrument.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrument.d.ts","sourceRoot":"","sources":["../../src/lib/instrument.ts"],"names":[],"mappings":"AAaA,0EAA0E;AAC1E,eAAO,MAAM,cAAc,eAAqD,CAAC;AACjF,8DAA8D;AAC9D,eAAO,MAAM,cAAc,eAAqD,CAAC;AAEjF,MAAM,WAAW,gBAAgB;IAC/B,EAAE,CAAC,EAAE,OAAO,CAAC;CACd;AAED,0EAA0E;AAC1E,wBAAgB,aAAa,IAAI,cAAc,GAAG,eAAe,CAWhE;AAED,wBAAgB,QAAQ,CAAC,EAAE,EAAE,OAAO,GAAG,OAAO,CAE7C;AAED,wBAAgB,SAAS,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAMlD;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,CAAC,SAAS,CAAC,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,OAAO,EAC/D,EAAE,EAAE,CAAC,EACL,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE,gBAAqB,GAC7B,CAAC,CA8HH"}