@lensmcp/bridge 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # @lensmcp/bridge
2
+
3
+ The build-agnostic **browser-event bridge** for LensMCP.
4
+
5
+ A tiny WebSocket server that the injected [`@lensmcp/client-runtime`](../client-runtime)
6
+ connects to, forwarding every observed browser event (errors, console, fetch,
7
+ route changes, and pre-formed React/Valtio publishes) onto the LensMCP event
8
+ bus — either in-process or, more usually, cross-process over the same
9
+ `LENSMCP_EVENT_FILE` / `LENSMCP_UDS` / `LENSMCP_IPC_SOCKET` transport the
10
+ MCP server tails.
11
+
12
+ This logic used to live **inside** `@lensmcp/vite-plugin`, which is why
13
+ LensMCP only worked for Vite apps. It was lifted out here so the exact same
14
+ bridge can run:
15
+
16
+ - **embedded** in the Vite dev server (the plugin calls `createBridgeServer`
17
+ on an ephemeral port), or
18
+ - **standalone** as a sidecar on a fixed port for **webpack**, **Next.js**,
19
+ or **no-build** hosts — where the browser runtime finds the endpoint by a
20
+ known URL (`ws://127.0.0.1:5747` by default) instead of one a bundler baked
21
+ in.
22
+
23
+ ## Standalone
24
+
25
+ ```bash
26
+ LENSMCP_EVENT_FILE=.lensmcp/events.jsonl node bridge.js
27
+ # or
28
+ lensmcp bridge
29
+ ```
30
+
31
+ | Env | Default | Meaning |
32
+ | --- | --- | --- |
33
+ | `LENSMCP_WS_HOST` | `127.0.0.1` | bind host |
34
+ | `LENSMCP_WS_PORT` | `5747` | bind port (`0` = ephemeral) |
35
+ | `LENSMCP_SESSION_ID` | — | session id stamped on each event |
36
+ | `LENSMCP_EVENT_FILE` | — | JSONL sink the MCP server ingests |
37
+
38
+ Point the browser at it with `@lensmcp/client-runtime/auto` (zero build):
39
+
40
+ ```ts
41
+ import '@lensmcp/client-runtime/auto';
42
+ ```
43
+
44
+ ## Embedding
45
+
46
+ ```ts
47
+ import { createBridgeServer } from '@lensmcp/bridge';
48
+
49
+ const bridge = await createBridgeServer({ port: 0, bus });
50
+ console.log(bridge.port);
51
+ await bridge.close();
52
+ ```
53
+
54
+ The bridge is **strictly passive**: it never mutates app state, never
55
+ changes scheduling, and never throws into the host.
package/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ export { createBridgeServer, makePublisher, handleClientEnvelope, findFreePort, type BridgeServer, type BridgeServerOptions, type BridgeDeps, } from './lib/server.js';
2
+ export { envelopeToEvent } from './lib/event-mappers.js';
3
+ export { resolveEnvSink, resetEnvSinkCache, udsEnvSink } from './lib/env-sink.js';
4
+ export { DEFAULT_WS_HOST, DEFAULT_WS_PORT, ENV_WS_HOST, ENV_WS_PORT, ENV_SESSION_ID, } from './lib/constants.js';
5
+ export type { ClientEnvelope, EnvSink } from './lib/types.js';
6
+ //# 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,EACL,kBAAkB,EAClB,aAAa,EACb,oBAAoB,EACpB,YAAY,EACZ,KAAK,YAAY,EACjB,KAAK,mBAAmB,EACxB,KAAK,UAAU,GAChB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAClF,OAAO,EACL,eAAe,EACf,eAAe,EACf,WAAW,EACX,WAAW,EACX,cAAc,GACf,MAAM,oBAAoB,CAAC;AAC5B,YAAY,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC"}
package/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createBridgeServer, makePublisher, handleClientEnvelope, findFreePort, } from './lib/server.js';
2
+ export { envelopeToEvent } from './lib/event-mappers.js';
3
+ export { resolveEnvSink, resetEnvSinkCache, udsEnvSink } from './lib/env-sink.js';
4
+ export { DEFAULT_WS_HOST, DEFAULT_WS_PORT, ENV_WS_HOST, ENV_WS_PORT, ENV_SESSION_ID, } from './lib/constants.js';
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Shared transport constants for the LensMCP browser-event bridge.
3
+ *
4
+ * The bridge is the single WebSocket endpoint that the injected
5
+ * `@lensmcp/client-runtime` posts envelopes to. For the Vite plugin this
6
+ * endpoint is born inside the dev server on an ephemeral port; for every
7
+ * other host (webpack, Next.js, no-build) it runs as a standalone sidecar
8
+ * on a FIXED, env-overridable port — so the browser runtime can find it
9
+ * without a build step baking the URL in.
10
+ *
11
+ * `DEFAULT_WS_PORT` must agree between the standalone bridge runner
12
+ * (`@lensmcp/bridge`) and the no-build client entry
13
+ * (`@lensmcp/client-runtime/auto`), which lives in a separate
14
+ * browser-targeted package and re-declares the same literal.
15
+ */
16
+ export declare const DEFAULT_WS_HOST = "127.0.0.1";
17
+ /** Default fixed port for the standalone bridge sidecar. Override via `LENSMCP_WS_PORT`. */
18
+ export declare const DEFAULT_WS_PORT = 5747;
19
+ /** Env var: bind host for the standalone bridge. */
20
+ export declare const ENV_WS_HOST = "LENSMCP_WS_HOST";
21
+ /** Env var: bind port for the standalone bridge (`0` selects an ephemeral port). */
22
+ export declare const ENV_WS_PORT = "LENSMCP_WS_PORT";
23
+ /** Env var: session id stamped onto every event the bridge publishes. */
24
+ export declare const ENV_SESSION_ID = "LENSMCP_SESSION_ID";
25
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/lib/constants.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,eAAe,cAAc,CAAC;AAE3C,4FAA4F;AAC5F,eAAO,MAAM,eAAe,OAAO,CAAC;AAEpC,oDAAoD;AACpD,eAAO,MAAM,WAAW,oBAAoB,CAAC;AAC7C,oFAAoF;AACpF,eAAO,MAAM,WAAW,oBAAoB,CAAC;AAC7C,yEAAyE;AACzE,eAAO,MAAM,cAAc,uBAAuB,CAAC"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Shared transport constants for the LensMCP browser-event bridge.
3
+ *
4
+ * The bridge is the single WebSocket endpoint that the injected
5
+ * `@lensmcp/client-runtime` posts envelopes to. For the Vite plugin this
6
+ * endpoint is born inside the dev server on an ephemeral port; for every
7
+ * other host (webpack, Next.js, no-build) it runs as a standalone sidecar
8
+ * on a FIXED, env-overridable port — so the browser runtime can find it
9
+ * without a build step baking the URL in.
10
+ *
11
+ * `DEFAULT_WS_PORT` must agree between the standalone bridge runner
12
+ * (`@lensmcp/bridge`) and the no-build client entry
13
+ * (`@lensmcp/client-runtime/auto`), which lives in a separate
14
+ * browser-targeted package and re-declares the same literal.
15
+ */
16
+ export const DEFAULT_WS_HOST = '127.0.0.1';
17
+ /** Default fixed port for the standalone bridge sidecar. Override via `LENSMCP_WS_PORT`. */
18
+ export const DEFAULT_WS_PORT = 5747;
19
+ /** Env var: bind host for the standalone bridge. */
20
+ export const ENV_WS_HOST = 'LENSMCP_WS_HOST';
21
+ /** Env var: bind port for the standalone bridge (`0` selects an ephemeral port). */
22
+ export const ENV_WS_PORT = 'LENSMCP_WS_PORT';
23
+ /** Env var: session id stamped onto every event the bridge publishes. */
24
+ export const ENV_SESSION_ID = 'LENSMCP_SESSION_ID';
@@ -0,0 +1,7 @@
1
+ import type { EnvSink } from './types.js';
2
+ export declare function resolveEnvSink(): EnvSink | null;
3
+ /** Test/embedding hook: drop the memoised sink so the next resolve re-reads env. */
4
+ export declare function resetEnvSinkCache(): void;
5
+ /** Reconnecting NDJSON client over a Unix domain socket (see session/uds.ts). */
6
+ export declare function udsEnvSink(path: string): EnvSink;
7
+ //# sourceMappingURL=env-sink.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env-sink.d.ts","sourceRoot":"","sources":["../../src/lib/env-sink.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAa1C,wBAAgB,cAAc,IAAI,OAAO,GAAG,IAAI,CAsC/C;AAED,oFAAoF;AACpF,wBAAgB,iBAAiB,IAAI,IAAI,CAExC;AAED,iFAAiF;AACjF,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAgDhD"}
@@ -0,0 +1,112 @@
1
+ import { connect } from 'node:net';
2
+ import { createSocket } from 'node:dgram';
3
+ import { appendFileSync } from 'node:fs';
4
+ /**
5
+ * Resolve a cross-process event sink from env, mirroring
6
+ * `@lensmcp/nest-instrumentation`'s `defaultEventSink` so every producer
7
+ * (Nest app, Vite plugin, standalone bridge) speaks the same transport:
8
+ * 1. `LENSMCP_EVENT_FILE` — append one JSON line per event.
9
+ * 2. `LENSMCP_UDS` — Unix domain socket, framed NDJSON, reconnecting.
10
+ * 3. `LENSMCP_IPC_SOCKET` (`host:port`) — one UDP datagram per event.
11
+ * Cached after first resolution; returns `null` when none is set.
12
+ */
13
+ let cachedEnvSink;
14
+ export function resolveEnvSink() {
15
+ if (cachedEnvSink !== undefined)
16
+ return cachedEnvSink;
17
+ const filePath = process.env['LENSMCP_EVENT_FILE'];
18
+ if (filePath) {
19
+ cachedEnvSink = (event) => {
20
+ try {
21
+ appendFileSync(filePath, JSON.stringify(event) + '\n');
22
+ }
23
+ catch {
24
+ /* swallow */
25
+ }
26
+ };
27
+ return cachedEnvSink;
28
+ }
29
+ const udsPath = process.env['LENSMCP_UDS'];
30
+ if (udsPath) {
31
+ cachedEnvSink = udsEnvSink(udsPath);
32
+ return cachedEnvSink;
33
+ }
34
+ const socketPath = process.env['LENSMCP_IPC_SOCKET'];
35
+ if (socketPath) {
36
+ const [host, portStr] = socketPath.split(':');
37
+ const port = Number(portStr);
38
+ if (host && Number.isFinite(port)) {
39
+ const sock = createSocket('udp4');
40
+ sock.unref();
41
+ cachedEnvSink = (event) => {
42
+ try {
43
+ const buf = Buffer.from(JSON.stringify(event));
44
+ sock.send(buf, port, host, () => undefined);
45
+ }
46
+ catch {
47
+ /* swallow */
48
+ }
49
+ };
50
+ return cachedEnvSink;
51
+ }
52
+ }
53
+ cachedEnvSink = null;
54
+ return null;
55
+ }
56
+ /** Test/embedding hook: drop the memoised sink so the next resolve re-reads env. */
57
+ export function resetEnvSinkCache() {
58
+ cachedEnvSink = undefined;
59
+ }
60
+ /** Reconnecting NDJSON client over a Unix domain socket (see session/uds.ts). */
61
+ export function udsEnvSink(path) {
62
+ const queue = [];
63
+ let sock = null;
64
+ let connecting = false;
65
+ const flush = () => {
66
+ if (!sock || !sock.writable)
67
+ return;
68
+ while (queue.length > 0)
69
+ sock.write(queue.shift());
70
+ };
71
+ const open = () => {
72
+ if (connecting || sock)
73
+ return;
74
+ connecting = true;
75
+ const s = connect(path);
76
+ s.on('connect', () => {
77
+ connecting = false;
78
+ sock = s;
79
+ flush();
80
+ });
81
+ s.on('drain', flush);
82
+ s.on('error', () => {
83
+ connecting = false;
84
+ sock = null;
85
+ });
86
+ s.on('close', () => {
87
+ sock = null;
88
+ });
89
+ s.unref();
90
+ };
91
+ open();
92
+ return (event) => {
93
+ queue.push(JSON.stringify(event) + '\n');
94
+ while (queue.length > 10000)
95
+ queue.shift();
96
+ if (sock && sock.writable) {
97
+ flush();
98
+ return;
99
+ }
100
+ // Dead socket (server restart) — drop it so open() reconnects.
101
+ if (sock) {
102
+ try {
103
+ sock.destroy();
104
+ }
105
+ catch {
106
+ /* ignore */
107
+ }
108
+ sock = null;
109
+ }
110
+ open();
111
+ };
112
+ }
@@ -0,0 +1,10 @@
1
+ import type { BaseEvent } from '@lensmcp/protocol-types';
2
+ import type { ClientEnvelope } from './types.js';
3
+ /**
4
+ * Translate a single client-runtime envelope into the normalised
5
+ * `BaseEvent` consumed by the LensMCP event bus. The bridge publishes
6
+ * these; reducers in `@lensmcp/<app>` materialise them into
7
+ * `runtime://browser/*` resources.
8
+ */
9
+ export declare function envelopeToEvent(env: ClientEnvelope, sessionId?: string): BaseEvent;
10
+ //# sourceMappingURL=event-mappers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-mappers.d.ts","sourceRoot":"","sources":["../../src/lib/event-mappers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAIjD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,cAAc,EAAE,SAAS,SAAyB,GAAG,SAAS,CAuIlG"}
@@ -0,0 +1,169 @@
1
+ import { fingerprint, ulid } from '@lensmcp/core';
2
+ const SESSION_ID_PLACEHOLDER = 'pending';
3
+ /**
4
+ * Translate a single client-runtime envelope into the normalised
5
+ * `BaseEvent` consumed by the LensMCP event bus. The bridge publishes
6
+ * these; reducers in `@lensmcp/<app>` materialise them into
7
+ * `runtime://browser/*` resources.
8
+ */
9
+ export function envelopeToEvent(env, sessionId = SESSION_ID_PLACEHOLDER) {
10
+ // Per-tab identity stamped by the client runtime — keys browser://tabs.
11
+ const tab = env.tabId ? { tabId: env.tabId } : {};
12
+ switch (env.kind) {
13
+ case 'error':
14
+ return {
15
+ id: ulid(),
16
+ sessionId,
17
+ timestamp: env.at,
18
+ source: 'client-runtime',
19
+ category: 'runtime',
20
+ severity: 'error',
21
+ context: { sessionId, ...tab },
22
+ fingerprint: fingerprint({
23
+ kind: 'runtime',
24
+ identity: `error:${normaliseStackTopFrame(env.stack)}`,
25
+ file: env.source,
26
+ detail: env.message,
27
+ }),
28
+ title: env.message,
29
+ message: env.stack ?? env.message,
30
+ location: env.source
31
+ ? { file: env.source, line: env.lineno, column: env.colno }
32
+ : undefined,
33
+ raw: env,
34
+ };
35
+ case 'unhandledrejection':
36
+ return {
37
+ id: ulid(),
38
+ sessionId,
39
+ timestamp: env.at,
40
+ source: 'client-runtime',
41
+ category: 'runtime',
42
+ severity: 'error',
43
+ context: { sessionId, ...tab },
44
+ fingerprint: fingerprint({
45
+ kind: 'runtime',
46
+ identity: `unhandledrejection:${env.reason.slice(0, 80)}`,
47
+ }),
48
+ title: 'Unhandled promise rejection',
49
+ message: env.reason,
50
+ raw: env,
51
+ };
52
+ case 'console': {
53
+ const severity = env.level === 'error' ? 'error' : env.level === 'warn' ? 'warning' : 'info';
54
+ const text = env.args.map(stringify).join(' ');
55
+ return {
56
+ id: ulid(),
57
+ sessionId,
58
+ timestamp: env.at,
59
+ source: 'client-runtime',
60
+ category: 'runtime',
61
+ severity,
62
+ context: { sessionId, ...tab },
63
+ fingerprint: fingerprint({
64
+ kind: 'runtime',
65
+ identity: `console:${env.level}:${text.slice(0, 80)}`,
66
+ }),
67
+ title: `console.${env.level}`,
68
+ message: text,
69
+ raw: env,
70
+ };
71
+ }
72
+ case 'fetch': {
73
+ const failed = env.error !== undefined || (env.status !== undefined && env.status >= 400);
74
+ return {
75
+ id: ulid(),
76
+ sessionId,
77
+ timestamp: env.at,
78
+ source: 'client-runtime',
79
+ category: 'network',
80
+ severity: failed ? 'error' : 'info',
81
+ context: { sessionId, ...tab },
82
+ fingerprint: fingerprint({
83
+ kind: 'network',
84
+ identity: `${env.method}:${normaliseUrl(env.url)}:${env.status ?? 'err'}`,
85
+ }),
86
+ title: `${env.method} ${env.url}${env.status !== undefined ? ` → ${env.status}` : ''}`,
87
+ message: env.error,
88
+ relatedUrls: [env.url],
89
+ raw: env,
90
+ };
91
+ }
92
+ case 'route':
93
+ return {
94
+ id: ulid(),
95
+ sessionId,
96
+ timestamp: env.at,
97
+ source: 'client-runtime',
98
+ category: 'runtime',
99
+ severity: 'info',
100
+ context: { sessionId, url: env.url, ...tab },
101
+ fingerprint: fingerprint({ kind: 'runtime', identity: `route:${env.url}` }),
102
+ title: `Route → ${env.url}`,
103
+ raw: env,
104
+ };
105
+ case 'ready':
106
+ return {
107
+ id: ulid(),
108
+ sessionId,
109
+ timestamp: env.at,
110
+ source: 'client-runtime',
111
+ category: 'runtime',
112
+ severity: 'info',
113
+ context: { sessionId, url: env.url, ...tab },
114
+ fingerprint: fingerprint({ kind: 'runtime', identity: 'client-ready' }),
115
+ title: 'Client runtime ready',
116
+ message: env.userAgent,
117
+ raw: env,
118
+ };
119
+ case 'publish':
120
+ // Pre-formed publish envelope from in-page instrumentation. Trust
121
+ // its source/category (the producer is our own injected code); the
122
+ // reducers gate on those, and the context carries the flow id so
123
+ // React renders correlate with the originating user action.
124
+ return {
125
+ id: ulid(),
126
+ sessionId,
127
+ timestamp: env.at,
128
+ source: env.source,
129
+ category: env.category,
130
+ severity: (env.severity ?? 'info'),
131
+ context: { sessionId, ...tab, ...(env.context ?? {}) },
132
+ fingerprint: env.fingerprint ?? fingerprint({ kind: 'publish', identity: env.title }),
133
+ title: env.title,
134
+ message: env.message,
135
+ raw: env.raw,
136
+ };
137
+ }
138
+ }
139
+ // --- helpers ---
140
+ function normaliseStackTopFrame(stack) {
141
+ if (!stack)
142
+ return 'unknown';
143
+ const lines = stack.split('\n').slice(0, 2);
144
+ for (const line of lines) {
145
+ const m = line.match(/at\s+(\S+)/);
146
+ if (m && m[1])
147
+ return m[1];
148
+ }
149
+ return 'unknown';
150
+ }
151
+ function normaliseUrl(url) {
152
+ try {
153
+ const u = new URL(url, 'http://x');
154
+ return `${u.pathname}`;
155
+ }
156
+ catch {
157
+ return url;
158
+ }
159
+ }
160
+ function stringify(v) {
161
+ if (typeof v === 'string')
162
+ return v;
163
+ try {
164
+ return JSON.stringify(v);
165
+ }
166
+ catch {
167
+ return String(v);
168
+ }
169
+ }
@@ -0,0 +1,56 @@
1
+ import type { BaseEvent } from '@lensmcp/protocol-types';
2
+ import type { EventBus } from '@lensmcp/core';
3
+ import type { EnvSink } from './types.js';
4
+ /**
5
+ * Where bridge events go. Both are optional:
6
+ * • `bus` — publish in-process (tests, or a host that embeds the bridge
7
+ * inside the same process as its reducers).
8
+ * • `sink` — forward cross-process over the env transport
9
+ * (`LENSMCP_EVENT_FILE` / `LENSMCP_UDS` / `LENSMCP_IPC_SOCKET`).
10
+ * When neither is given, the sink is resolved lazily from env — the
11
+ * standalone sidecar case, where the MCP server tails the same file.
12
+ */
13
+ export interface BridgeDeps {
14
+ bus?: EventBus;
15
+ sink?: EnvSink;
16
+ /** Session id stamped onto each event. */
17
+ sessionId?: string;
18
+ }
19
+ export interface BridgeServerOptions extends BridgeDeps {
20
+ /** Bind host. Default `127.0.0.1`. */
21
+ host?: string;
22
+ /** Bind port. `0` selects an ephemeral port; default {@link DEFAULT_WS_PORT}. */
23
+ port?: number;
24
+ }
25
+ export interface BridgeServer {
26
+ /** The actual bound port (resolved even when `port: 0` was requested). */
27
+ readonly port: number;
28
+ readonly host: string;
29
+ /** Stop accepting connections and release the port. */
30
+ close(): Promise<void>;
31
+ }
32
+ /**
33
+ * Build a `publish` function honouring the bus → sink → env-sink → console
34
+ * precedence. Mirrors the logic the Vite plugin used to inline, lifted here
35
+ * so the standalone sidecar and the plugin share one path.
36
+ */
37
+ export declare function makePublisher(deps: BridgeDeps): (event: BaseEvent) => void;
38
+ /**
39
+ * Parse one raw WebSocket message from the injected client runtime and
40
+ * forward the resulting event via `publish`. Exported so it can be
41
+ * exercised over a real WebSocket without booting any bundler.
42
+ */
43
+ export declare function handleClientEnvelope(raw: string, publish: (event: BaseEvent) => void, sessionId?: string): void;
44
+ /**
45
+ * Stand up the browser-event bridge: a WebSocket server the injected
46
+ * `@lensmcp/client-runtime` connects to, forwarding every envelope onto
47
+ * the event bus (in-process or cross-process). Build-agnostic — the Vite
48
+ * plugin uses it on an ephemeral port; the standalone sidecar uses it on a
49
+ * fixed port for webpack / Next.js / no-build hosts.
50
+ *
51
+ * Resolves once the server is listening, with the actual bound `port`.
52
+ */
53
+ export declare function createBridgeServer(options?: BridgeServerOptions): Promise<BridgeServer>;
54
+ /** Allocate an ephemeral free port (used when `port: 0` is requested). */
55
+ export declare function findFreePort(): Promise<number>;
56
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/lib/server.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACzD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAI9C,OAAO,KAAK,EAAkB,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1D;;;;;;;;GAQG;AACH,MAAM,WAAW,UAAU;IACzB,GAAG,CAAC,EAAE,QAAQ,CAAC;IACf,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,0CAA0C;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,mBAAoB,SAAQ,UAAU;IACrD,sCAAsC;IACtC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,iFAAiF;IACjF,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,YAAY;IAC3B,0EAA0E;IAC1E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,uDAAuD;IACvD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,UAAU,GAAG,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,CAsB1E;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,CAAC,KAAK,EAAE,SAAS,KAAK,IAAI,EACnC,SAAS,CAAC,EAAE,MAAM,GACjB,IAAI,CASN;AAED;;;;;;;;GAQG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,YAAY,CAAC,CAmCjG;AAED,0EAA0E;AAC1E,wBAAgB,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC,CAgB9C"}
package/lib/server.js ADDED
@@ -0,0 +1,109 @@
1
+ import { createServer as createNetServer } from 'node:net';
2
+ import { WebSocketServer } from 'ws';
3
+ import { DEFAULT_WS_HOST, DEFAULT_WS_PORT } from './constants.js';
4
+ import { resolveEnvSink } from './env-sink.js';
5
+ import { envelopeToEvent } from './event-mappers.js';
6
+ /**
7
+ * Build a `publish` function honouring the bus → sink → env-sink → console
8
+ * precedence. Mirrors the logic the Vite plugin used to inline, lifted here
9
+ * so the standalone sidecar and the plugin share one path.
10
+ */
11
+ export function makePublisher(deps) {
12
+ let resolvedSink;
13
+ return (event) => {
14
+ if (deps.bus) {
15
+ deps.bus.publish(event);
16
+ return;
17
+ }
18
+ if (deps.sink) {
19
+ deps.sink(event);
20
+ return;
21
+ }
22
+ // Resolve the env sink once, lazily — matches the Nest sink contract.
23
+ if (resolvedSink === undefined)
24
+ resolvedSink = resolveEnvSink();
25
+ if (resolvedSink) {
26
+ resolvedSink(event);
27
+ return;
28
+ }
29
+ // Standalone fallback so the bridge is debuggable without any transport.
30
+ if (event.severity === 'error' || event.severity === 'fatal') {
31
+ console.debug(`[lensmcp-bridge] ${event.severity}: ${event.title}`);
32
+ }
33
+ };
34
+ }
35
+ /**
36
+ * Parse one raw WebSocket message from the injected client runtime and
37
+ * forward the resulting event via `publish`. Exported so it can be
38
+ * exercised over a real WebSocket without booting any bundler.
39
+ */
40
+ export function handleClientEnvelope(raw, publish, sessionId) {
41
+ let env;
42
+ try {
43
+ env = JSON.parse(raw);
44
+ }
45
+ catch {
46
+ return; // ignore malformed
47
+ }
48
+ if (!env || typeof env !== 'object' || !('kind' in env))
49
+ return;
50
+ publish(envelopeToEvent(env, sessionId));
51
+ }
52
+ /**
53
+ * Stand up the browser-event bridge: a WebSocket server the injected
54
+ * `@lensmcp/client-runtime` connects to, forwarding every envelope onto
55
+ * the event bus (in-process or cross-process). Build-agnostic — the Vite
56
+ * plugin uses it on an ephemeral port; the standalone sidecar uses it on a
57
+ * fixed port for webpack / Next.js / no-build hosts.
58
+ *
59
+ * Resolves once the server is listening, with the actual bound `port`.
60
+ */
61
+ export async function createBridgeServer(options = {}) {
62
+ const host = options.host ?? DEFAULT_WS_HOST;
63
+ const requestedPort = options.port ?? DEFAULT_WS_PORT;
64
+ const port = requestedPort === 0 ? await findFreePort() : requestedPort;
65
+ const publish = makePublisher(options);
66
+ const wss = new WebSocketServer({ host, port });
67
+ wss.on('connection', (socket) => {
68
+ socket.on('message', (raw) => {
69
+ handleClientEnvelope(raw.toString(), publish, options.sessionId);
70
+ });
71
+ });
72
+ await new Promise((resolve, reject) => {
73
+ const onError = (err) => {
74
+ wss.off('listening', onListening);
75
+ reject(err);
76
+ };
77
+ const onListening = () => {
78
+ wss.off('error', onError);
79
+ resolve();
80
+ };
81
+ wss.once('error', onError);
82
+ wss.once('listening', onListening);
83
+ });
84
+ return {
85
+ port,
86
+ host,
87
+ close: () => new Promise((resolve) => {
88
+ wss.close(() => resolve());
89
+ }),
90
+ };
91
+ }
92
+ /** Allocate an ephemeral free port (used when `port: 0` is requested). */
93
+ export function findFreePort() {
94
+ return new Promise((resolve, reject) => {
95
+ const s = createNetServer();
96
+ s.unref();
97
+ s.on('error', reject);
98
+ s.listen(0, () => {
99
+ const addr = s.address();
100
+ if (!addr) {
101
+ s.close();
102
+ reject(new Error('Could not allocate free port'));
103
+ return;
104
+ }
105
+ const freePort = addr.port;
106
+ s.close(() => resolve(freePort));
107
+ });
108
+ });
109
+ }
package/lib/types.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The wire format spoken between the injected `@lensmcp/client-runtime`
3
+ * and the bridge's WebSocket. Kept intentionally narrow — the client
4
+ * runtime *only* emits these envelopes, never anything else.
5
+ *
6
+ * This type was originally owned by `@lensmcp/vite-plugin`; it moved here
7
+ * when the bridge was decoupled from Vite so every host (webpack, Next.js,
8
+ * no-build) shares one definition. The Vite plugin re-exports it for
9
+ * backwards compatibility.
10
+ */
11
+ export type ClientEnvelope = ({
12
+ kind: 'error';
13
+ at: number;
14
+ message: string;
15
+ stack?: string;
16
+ source?: string;
17
+ lineno?: number;
18
+ colno?: number;
19
+ } | {
20
+ kind: 'unhandledrejection';
21
+ at: number;
22
+ reason: string;
23
+ } | {
24
+ kind: 'console';
25
+ at: number;
26
+ level: 'log' | 'info' | 'warn' | 'error' | 'debug';
27
+ args: unknown[];
28
+ } | {
29
+ kind: 'fetch';
30
+ at: number;
31
+ method: string;
32
+ url: string;
33
+ status?: number;
34
+ durationMs?: number;
35
+ ok?: boolean;
36
+ error?: string;
37
+ } | {
38
+ kind: 'route';
39
+ at: number;
40
+ url: string;
41
+ from?: string;
42
+ } | {
43
+ kind: 'ready';
44
+ at: number;
45
+ userAgent: string;
46
+ url: string;
47
+ } | {
48
+ kind: 'publish';
49
+ at: number;
50
+ source: string;
51
+ category: string;
52
+ severity?: string;
53
+ title: string;
54
+ message?: string;
55
+ fingerprint?: string;
56
+ context?: Record<string, unknown>;
57
+ raw?: unknown;
58
+ }) & {
59
+ /** Per-tab identity stamped by the client runtime (sessionStorage is per-tab) — keys `browser://tabs`. */
60
+ tabId?: string;
61
+ };
62
+ /** A cross-process event sink: takes one normalised event and forwards it onward. */
63
+ export type EnvSink = (event: import('@lensmcp/protocol-types').BaseEvent) => void;
64
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/lib/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,MAAM,cAAc,GAAG,CACzB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAChH;IAAE,IAAI,EAAE,oBAAoB,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC1D;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC;IAAC,IAAI,EAAE,OAAO,EAAE,CAAA;CAAE,GACpG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,EAAE,CAAC,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAC9H;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,GACzD;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAK7D;IACE,IAAI,EAAE,SAAS,CAAC;IAChB,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,GAAG,CAAC,EAAE,OAAO,CAAC;CACf,CACJ,GAAG;IACF,0GAA0G;IAC1G,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,qFAAqF;AACrF,MAAM,MAAM,OAAO,GAAG,CAAC,KAAK,EAAE,OAAO,yBAAyB,EAAE,SAAS,KAAK,IAAI,CAAC"}
package/lib/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/main.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=main.d.ts.map
package/main.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":""}
package/main.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Standalone bridge sidecar — the build-agnostic entry.
3
+ *
4
+ * Run directly (`node bridge.js`) or via `lensmcp bridge`. Stands up the
5
+ * WebSocket the injected `@lensmcp/client-runtime` connects to, on a FIXED
6
+ * port (so a no-build / webpack / Next.js host can point at a known URL),
7
+ * and forwards every browser envelope onto the cross-process event sink
8
+ * the MCP server tails.
9
+ *
10
+ * Env:
11
+ * LENSMCP_WS_HOST bind host (default 127.0.0.1)
12
+ * LENSMCP_WS_PORT bind port (default 5747; `0` = ephemeral)
13
+ * LENSMCP_SESSION_ID session id stamped onto every event (optional)
14
+ * LENSMCP_EVENT_FILE JSONL sink the MCP server ingests (or LENSMCP_UDS /
15
+ * LENSMCP_IPC_SOCKET) — resolved by the env sink.
16
+ */
17
+ import { DEFAULT_WS_HOST, DEFAULT_WS_PORT, ENV_SESSION_ID, ENV_WS_HOST, ENV_WS_PORT } from './lib/constants.js';
18
+ import { createBridgeServer } from './lib/server.js';
19
+ async function main() {
20
+ const host = process.env[ENV_WS_HOST] ?? DEFAULT_WS_HOST;
21
+ const portRaw = process.env[ENV_WS_PORT];
22
+ const port = portRaw !== undefined && portRaw !== '' ? Number(portRaw) : DEFAULT_WS_PORT;
23
+ if (!Number.isFinite(port) || port < 0) {
24
+ console.error(`[lensmcp-bridge] invalid ${ENV_WS_PORT}=${portRaw}`);
25
+ process.exit(2);
26
+ }
27
+ const sessionId = process.env[ENV_SESSION_ID];
28
+ let server;
29
+ try {
30
+ server = await createBridgeServer({ host, port, sessionId });
31
+ }
32
+ catch (err) {
33
+ console.error(`[lensmcp-bridge] failed to listen on ws://${host}:${port} — ${err.message}`);
34
+ process.exit(1);
35
+ }
36
+ console.log(`[lensmcp-bridge] listening on ws://${server.host}:${server.port}`);
37
+ let closing = false;
38
+ const shutdown = () => {
39
+ if (closing)
40
+ return;
41
+ closing = true;
42
+ void server.close().then(() => process.exit(0));
43
+ };
44
+ process.on('SIGINT', shutdown);
45
+ process.on('SIGTERM', shutdown);
46
+ }
47
+ void main();
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@lensmcp/bridge",
3
+ "version": "1.1.0",
4
+ "type": "module",
5
+ "main": "./index.js",
6
+ "module": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "exports": {
9
+ "./package.json": "./package.json",
10
+ ".": {
11
+ "types": "./index.d.ts",
12
+ "import": "./index.js",
13
+ "default": "./index.js"
14
+ },
15
+ "./server": {
16
+ "types": "./lib/server.d.ts",
17
+ "import": "./lib/server.js",
18
+ "default": "./lib/server.js"
19
+ }
20
+ },
21
+ "dependencies": {
22
+ "@lensmcp/core": "1.1.0",
23
+ "@lensmcp/protocol-types": "1.1.0",
24
+ "tslib": "^2.3.0",
25
+ "ws": "^8.21.0"
26
+ },
27
+ "license": "Apache-2.0",
28
+ "homepage": "https://github.com/kiwiapps-ltd/lensmcp#readme",
29
+ "bugs": {
30
+ "url": "https://github.com/kiwiapps-ltd/lensmcp/issues"
31
+ },
32
+ "engines": {
33
+ "node": ">=18"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "description": "LensMCP browser-event bridge — a build-agnostic WebSocket server that forwards @lensmcp/client-runtime envelopes onto the LensMCP event bus. Used by the Vite plugin and as a standalone sidecar for webpack / Next.js / no-build hosts.",
39
+ "keywords": [
40
+ "lensmcp",
41
+ "mcp",
42
+ "observability",
43
+ "ai-agents",
44
+ "claude",
45
+ "websocket",
46
+ "bridge"
47
+ ],
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "git+https://github.com/kiwiapps-ltd/lensmcp.git",
51
+ "directory": "libs/bridge"
52
+ }
53
+ }