@lensmcp/react-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 +202 -0
- package/README.md +100 -0
- package/index.d.ts +11 -0
- package/index.d.ts.map +1 -0
- package/index.js +9 -0
- package/lib/babel-plugin.d.ts +59 -0
- package/lib/babel-plugin.d.ts.map +1 -0
- package/lib/babel-plugin.js +259 -0
- package/lib/context.d.ts +15 -0
- package/lib/context.d.ts.map +1 -0
- package/lib/context.js +6 -0
- package/lib/flow-fetch.d.ts +8 -0
- package/lib/flow-fetch.d.ts.map +1 -0
- package/lib/flow-fetch.js +121 -0
- package/lib/hoc.d.ts +13 -0
- package/lib/hoc.d.ts.map +1 -0
- package/lib/hoc.js +45 -0
- package/lib/identity.d.ts +23 -0
- package/lib/identity.d.ts.map +1 -0
- package/lib/identity.js +74 -0
- package/lib/lensmcp-root.d.ts +22 -0
- package/lib/lensmcp-root.d.ts.map +1 -0
- package/lib/lensmcp-root.js +53 -0
- package/lib/publish.d.ts +89 -0
- package/lib/publish.d.ts.map +1 -0
- package/lib/publish.js +174 -0
- package/lib/trace-slot.d.ts +12 -0
- package/lib/trace-slot.d.ts.map +1 -0
- package/lib/trace-slot.js +67 -0
- package/lib/traced-hooks.d.ts +12 -0
- package/lib/traced-hooks.d.ts.map +1 -0
- package/lib/traced-hooks.js +143 -0
- package/lib/types.d.ts +83 -0
- package/lib/types.d.ts.map +1 -0
- package/lib/types.js +1 -0
- package/package.json +64 -0
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,100 @@
|
|
|
1
|
+
# @lensmcp/react-instrumentation
|
|
2
|
+
|
|
3
|
+
Zero-config React instrumentation for LensMCP — a Babel transform plus a render/flow runtime that lets the LensMCP lens *see* a running React app: which components rendered, which hooks re-ran, and how a click in the browser stitches together with the server request and DB query it triggered.
|
|
4
|
+
|
|
5
|
+
This package is the React-side half of LensMCP's observability lens. A small **Babel plugin** rewrites your JSX at build time (stamping component identity, wrapping `useEffect`/`useMemo`/`useCallback`, wrapping interaction handlers, and wrapping the root render). A matching **runtime** — traced hooks, a `<LensmcpRoot>` wrapper, and a `fetch` wrapper (*flow-fetch*) — emits structured events and propagates a `flowId` across the network boundary so a single user action can be read end to end (click → fetch → server span → DB query).
|
|
6
|
+
|
|
7
|
+
You normally don't import any of this by hand. [`@lensmcp/vite-plugin`](https://github.com/kiwiapps-ltd/lensmcp) wires the Babel plugin into your React build, injects the publish channel into the served HTML, and bridges the emitted events to the lens. The exports below are available for projects that can't run the global transform (e.g. opt-in tracing) or want to start a flow manually.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
yarn add @lensmcp/react-instrumentation
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
In practice you don't add it directly — it's pulled in and configured by **`@lensmcp/vite-plugin`**, which applies the Babel plugin and sets up the transport. Install it explicitly only for the opt-in, hand-wired path described under [Usage](#usage).
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
**The realistic path (automatic).** Add `@lensmcp/vite-plugin` to your Vite config. It loads this package's Babel plugin, so every component, hook, conditional, and interaction handler in your source is instrumented with no app-code changes — and it installs the publish channel that the runtime emits into.
|
|
20
|
+
|
|
21
|
+
If you can't run the global transform, the runtime is usable directly:
|
|
22
|
+
|
|
23
|
+
```tsx
|
|
24
|
+
import { createRoot } from 'react-dom/client';
|
|
25
|
+
import { LensmcpRoot, installFlowFetch } from '@lensmcp/react-instrumentation';
|
|
26
|
+
|
|
27
|
+
// Wrap browser fetches so they carry the active flow's headers.
|
|
28
|
+
installFlowFetch();
|
|
29
|
+
|
|
30
|
+
createRoot(document.getElementById('root')!).render(
|
|
31
|
+
<LensmcpRoot page="home" route="/">
|
|
32
|
+
<App />
|
|
33
|
+
</LensmcpRoot>,
|
|
34
|
+
);
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
(This is exactly what the Babel plugin generates automatically when `autoWrapRoot` is on.) From there you can opt individual pieces in:
|
|
38
|
+
|
|
39
|
+
```tsx
|
|
40
|
+
import { withTraceComponent, withFlow, tracedUseEffect } from '@lensmcp/react-instrumentation';
|
|
41
|
+
|
|
42
|
+
// Trace a single component's renders without the global transform.
|
|
43
|
+
const TracedPanel = withTraceComponent(Panel, { source: 'src/Panel.tsx' });
|
|
44
|
+
|
|
45
|
+
// Start a correlated flow from a handler the transform didn't reach.
|
|
46
|
+
<button onClick={withFlow(save, { originType: 'user-click', originNodeId: 'ui:save' })}>
|
|
47
|
+
Save
|
|
48
|
+
</button>;
|
|
49
|
+
|
|
50
|
+
// Drop-in useEffect that emits effect-run / effect-cleanup events.
|
|
51
|
+
tracedUseEffect('Panel:42:0', () => subscribe(), [topic]);
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
If you build your own bundler integration, point the runtime at your transport with `setPublisher(fn)`; until a publisher is set, every event is buffered (capped) so the library is safe to import in tests and SSR.
|
|
55
|
+
|
|
56
|
+
## What it captures
|
|
57
|
+
|
|
58
|
+
- **Component renders** — the Babel transform stamps each JSX element with `data-agent-component` (the component name) and `data-agent-source` (`file:line`), and wraps the root in `<LensmcpRoot>`, whose React `<Profiler>` emits a `render` event (mount/update, durations, commit times) on every commit. `withTraceComponent` does the same for a single opt-in component.
|
|
59
|
+
- **Hooks** — `useEffect`/`useMemo`/`useCallback` are rewritten to traced variants that emit `effect-run` (plus `effect-cleanup`) and `hook-run` events, including a cheap `depsHash` so the lens can tell whether a hook re-ran because its dependencies changed.
|
|
60
|
+
- **Conditional slots** — `<TraceSlot>` emits `slot-content-changed` when the type of the rendered child changes (e.g. a branch swap in a JSX conditional).
|
|
61
|
+
- **Browser→server flow correlation (flow-fetch)** — interaction handlers are wrapped with `withFlow`, which opens a flow with a generated `flowId`. The patched `fetch` injects `x-lensmcp-flow-id` + `x-lensmcp-origin-node-id` headers so the server-side `@lensmcp/nest-instrumentation` stamps its spans and DB queries with the *same* flowId, and it publishes `fetch-start` / `fetch-done` / `fetch-error` legs. A short causality window (and an auto-started `page-load` flow) attributes async post-response re-renders to the action that caused them.
|
|
62
|
+
- **Identity** — stable `logicalId`s for components, hooks, and slots plus per-mount `instanceId`s, so the lens can attribute every event to a specific component instance across re-renders.
|
|
63
|
+
|
|
64
|
+
## API
|
|
65
|
+
|
|
66
|
+
Exports from the package entry (`@lensmcp/react-instrumentation`):
|
|
67
|
+
|
|
68
|
+
| Export | Description |
|
|
69
|
+
| --- | --- |
|
|
70
|
+
| `LensmcpRoot` / `LensmcpRootProps` | Root wrapper: a `<Profiler>` + context provider that emits `render` events and tags hooks with renderer/page/route. |
|
|
71
|
+
| `LensmcpContext` / `useLensmcpContext` / `LensmcpIdentityContext` | React context (and hook) carrying the active renderer/page/route and component instance identity. |
|
|
72
|
+
| `tracedUseEffect` / `tracedUseMemo` / `tracedUseCallback` | Drop-in hook replacements that emit `effect-run`/`hook-run` events; the transform rewrites bare hooks to these. |
|
|
73
|
+
| `TraceSlot` / `TraceSlotProps` | Wrapper that emits `slot-content-changed` when its primary child's type changes. |
|
|
74
|
+
| `withTraceComponent` / `WithTraceOptions` | HOC for opt-in render tracing when the global transform isn't available. |
|
|
75
|
+
| `installFlowFetch` / `FlowFetchOptions` | Monkeypatches `globalThis.fetch` to inject flow headers and publish network legs; returns an uninstall function. |
|
|
76
|
+
| `withFlow` | Wraps an event handler so each call runs inside a fresh correlated flow (idempotent; passes non-functions through). |
|
|
77
|
+
| `runInFlow` / `beginBackgroundFlow` / `currentFlow` / `activeFlow` / `extendFlowWindow` | Flow-stack and causality-window primitives for starting/inspecting/extending flows manually. |
|
|
78
|
+
| `publish` / `setPublisher` / `drainQueue` | The publish channel: emit an event, install the transport, or drain the buffered queue (tests). |
|
|
79
|
+
| `PublishEnvelope` / `PublishCategory` / `FlowSpec` | Types for the publish envelope, event category, and a flow descriptor. |
|
|
80
|
+
| `componentLogicalId` / `hookLogicalId` / `slotLogicalId` / `makeInstanceId` / `depsHash` / `resetIdentityState` | Identity helpers — build stable logical ids, per-mount instance ids, and dependency hashes. |
|
|
81
|
+
| `RenderRecord` / `EffectRecord` / `HookRecord` / `SlotChangeRecord` / `ComponentMountRecord` / `ReactPublishPayload` | Wire-shape types for the events the library publishes. |
|
|
82
|
+
|
|
83
|
+
Subpath export `@lensmcp/react-instrumentation/babel-plugin` (also re-exported from the entry as `lensmcpBabelPlugin`, with `LensmcpBabelOptions`): the JSX identity transform. Options: `production`, `includeSource`, `rootDir`, `autoWrapHooks`, `autoWrapRoot`, `autoFlowHandlers`, `flowEvents`. It's dev-only — a no-op when `production` is true or `NODE_ENV === 'production'` — and honors `// @lensmcp-ignore` (file) and `data-lensmcp-ignore` (element) opt-outs.
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
// vite.config.ts — applied for you by @lensmcp/vite-plugin
|
|
87
|
+
import lensmcpBabel from '@lensmcp/react-instrumentation/babel-plugin';
|
|
88
|
+
react({ babel: { plugins: [lensmcpBabel] } });
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## How it fits
|
|
92
|
+
|
|
93
|
+
- **Configured by [`@lensmcp/vite-plugin`](https://github.com/kiwiapps-ltd/lensmcp).** The Vite plugin runs `lensmcpBabelPlugin` over your React source and injects a client runtime that sets `window.__LENSMCP_PUBLISH__` — the transport this package's `publish()` looks for. In dev, events flow over a WebSocket to the lens; in production, over the FrontMCP server transport.
|
|
94
|
+
- **Pairs with [`@lensmcp/valtio-instrumentation`](https://github.com/kiwiapps-ltd/lensmcp).** The Vite plugin aliases `valtio` → `@lensmcp/valtio-instrumentation` so state mutations publish into the same channel, and `flowId` correlation lets a render here be tied to the state change (and the fetch) that caused it.
|
|
95
|
+
- **Server side: [`@lensmcp/nest-instrumentation`](https://github.com/kiwiapps-ltd/lensmcp).** Its `TraceInterceptor` reads the `x-lensmcp-flow-id` header set by flow-fetch and stamps server-request, span, and DB-query events with the matching flowId — completing the browser→server story.
|
|
96
|
+
- **Events use [`@lensmcp/protocol-types`](https://github.com/kiwiapps-ltd/lensmcp).** The published record shapes (`RenderPhase`, `RenderWhy`, etc.) mirror the shared protocol so the lens and reducers can consume them.
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
Part of [LensMCP](https://github.com/kiwiapps-ltd/lensmcp). Apache-2.0.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { LensmcpRoot, type LensmcpRootProps } from './lib/lensmcp-root.js';
|
|
2
|
+
export { LensmcpContext, useLensmcpContext, type LensmcpIdentityContext } from './lib/context.js';
|
|
3
|
+
export { tracedUseEffect, tracedUseMemo, tracedUseCallback, } from './lib/traced-hooks.js';
|
|
4
|
+
export { TraceSlot, type TraceSlotProps } from './lib/trace-slot.js';
|
|
5
|
+
export { withTraceComponent, type WithTraceOptions } from './lib/hoc.js';
|
|
6
|
+
export { installFlowFetch, type FlowFetchOptions } from './lib/flow-fetch.js';
|
|
7
|
+
export { publish, setPublisher, drainQueue, runInFlow, currentFlow, activeFlow, extendFlowWindow, beginBackgroundFlow, withFlow, type PublishEnvelope, type PublishCategory, type FlowSpec, } from './lib/publish.js';
|
|
8
|
+
export { componentLogicalId, hookLogicalId, slotLogicalId, makeInstanceId, depsHash, resetIdentityState, } from './lib/identity.js';
|
|
9
|
+
export type { RenderRecord, EffectRecord, HookRecord, SlotChangeRecord, ComponentMountRecord, ReactPublishPayload, } from './lib/types.js';
|
|
10
|
+
export { default as lensmcpBabelPlugin, type LensmcpBabelOptions } from './lib/babel-plugin.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,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,KAAK,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAClG,OAAO,EACL,eAAe,EACf,aAAa,EACb,iBAAiB,GAClB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,SAAS,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC9E,OAAO,EACL,OAAO,EACP,YAAY,EACZ,UAAU,EACV,SAAS,EACT,WAAW,EACX,UAAU,EACV,gBAAgB,EAChB,mBAAmB,EACnB,QAAQ,EACR,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,QAAQ,GACd,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,kBAAkB,EAClB,aAAa,EACb,aAAa,EACb,cAAc,EACd,QAAQ,EACR,kBAAkB,GACnB,MAAM,mBAAmB,CAAC;AAC3B,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,gBAAgB,EAChB,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,IAAI,kBAAkB,EAAE,KAAK,mBAAmB,EAAE,MAAM,uBAAuB,CAAC"}
|
package/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { LensmcpRoot } from './lib/lensmcp-root.js';
|
|
2
|
+
export { LensmcpContext, useLensmcpContext } from './lib/context.js';
|
|
3
|
+
export { tracedUseEffect, tracedUseMemo, tracedUseCallback, } from './lib/traced-hooks.js';
|
|
4
|
+
export { TraceSlot } from './lib/trace-slot.js';
|
|
5
|
+
export { withTraceComponent } from './lib/hoc.js';
|
|
6
|
+
export { installFlowFetch } from './lib/flow-fetch.js';
|
|
7
|
+
export { publish, setPublisher, drainQueue, runInFlow, currentFlow, activeFlow, extendFlowWindow, beginBackgroundFlow, withFlow, } from './lib/publish.js';
|
|
8
|
+
export { componentLogicalId, hookLogicalId, slotLogicalId, makeInstanceId, depsHash, resetIdentityState, } from './lib/identity.js';
|
|
9
|
+
export { default as lensmcpBabelPlugin } from './lib/babel-plugin.js';
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@lensmcp/react-instrumentation/babel-plugin`
|
|
3
|
+
*
|
|
4
|
+
* JSX identity transform. For every `<Component>` / `<div>` in dev:
|
|
5
|
+
*
|
|
6
|
+
* <CardGrid />
|
|
7
|
+
* →
|
|
8
|
+
* <CardGrid data-agent-component="CardGrid" data-agent-source="src/App.tsx:42" />
|
|
9
|
+
*
|
|
10
|
+
* Plus opt-outs:
|
|
11
|
+
* - File-level comment `// @lensmcp-ignore` skips the whole file.
|
|
12
|
+
* - Element-level `data-lensmcp-ignore` skips that one element.
|
|
13
|
+
* - Element-level leading `// @lensmcp-ignore` comment skips it.
|
|
14
|
+
*
|
|
15
|
+
* The transform is dev-only: pass `production: true` (or omit it and
|
|
16
|
+
* rely on the `NODE_ENV` check) to make the plugin a no-op.
|
|
17
|
+
*
|
|
18
|
+
* Usage in `vite.config.ts`:
|
|
19
|
+
* import lensmcpBabel from '@lensmcp/react-instrumentation/babel-plugin';
|
|
20
|
+
* react({ babel: { plugins: [lensmcpBabel] } })
|
|
21
|
+
*/
|
|
22
|
+
import type { PluginObj, PluginPass, types as t } from '@babel/core';
|
|
23
|
+
export interface LensmcpBabelOptions {
|
|
24
|
+
/** Skip the transform entirely. Default: `process.env.NODE_ENV === 'production'`. */
|
|
25
|
+
production?: boolean;
|
|
26
|
+
/** When true, also inject `data-agent-source`. Default: true. */
|
|
27
|
+
includeSource?: boolean;
|
|
28
|
+
/** Root path used to make `data-agent-source` relative. Default: cwd. */
|
|
29
|
+
rootDir?: string;
|
|
30
|
+
/** Rewrite useEffect/useMemo/useCallback → traced*. Default: true. */
|
|
31
|
+
autoWrapHooks?: boolean;
|
|
32
|
+
/** Wrap `createRoot(x).render(<App/>)` with `<LensmcpRoot>` + installFlowFetch. Default: true. */
|
|
33
|
+
autoWrapRoot?: boolean;
|
|
34
|
+
/** Wrap JSX interaction handlers (onClick/onSubmit/…) with `withFlow` so a
|
|
35
|
+
* user interaction starts a correlated flow. Default: true. */
|
|
36
|
+
autoFlowHandlers?: boolean;
|
|
37
|
+
/** Which JSX `on*` attributes start a flow. Default: the intent set below. */
|
|
38
|
+
flowEvents?: string[];
|
|
39
|
+
}
|
|
40
|
+
interface State extends PluginPass {
|
|
41
|
+
opts: LensmcpBabelOptions;
|
|
42
|
+
fileIgnored?: boolean;
|
|
43
|
+
relativePath?: string;
|
|
44
|
+
/** traced* helper names this module needs imported. */
|
|
45
|
+
needHelpers?: Set<string>;
|
|
46
|
+
/** A root render was wrapped → also import LensmcpRoot + installFlowFetch. */
|
|
47
|
+
needRoot?: boolean;
|
|
48
|
+
hookIndex?: number;
|
|
49
|
+
/** Which `on*` handlers to auto-wrap with `withFlow`. */
|
|
50
|
+
flowEvents?: Set<string>;
|
|
51
|
+
/** Local variables holding a `createRoot(...)` result (for `root.render(...)`). */
|
|
52
|
+
rootVars?: Set<string>;
|
|
53
|
+
}
|
|
54
|
+
interface BabelApi {
|
|
55
|
+
types: typeof t;
|
|
56
|
+
}
|
|
57
|
+
export default function lensmcpBabelPlugin(api: BabelApi): PluginObj<State>;
|
|
58
|
+
export {};
|
|
59
|
+
//# sourceMappingURL=babel-plugin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"babel-plugin.d.ts","sourceRoot":"","sources":["../../src/lib/babel-plugin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,KAAK,EACV,SAAS,EACT,UAAU,EAEV,KAAK,IAAI,CAAC,EACX,MAAM,aAAa,CAAC;AAErB,MAAM,WAAW,mBAAmB;IAClC,qFAAqF;IACrF,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,iEAAiE;IACjE,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,sEAAsE;IACtE,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,kGAAkG;IAClG,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;oEACgE;IAChE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,8EAA8E;IAC9E,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;CACvB;AAuBD,UAAU,KAAM,SAAQ,UAAU;IAChC,IAAI,EAAE,mBAAmB,CAAC;IAC1B,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,uDAAuD;IACvD,WAAW,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1B,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yDAAyD;IACzD,UAAU,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IACzB,mFAAmF;IACnF,QAAQ,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACxB;AAED,UAAU,QAAQ;IAChB,KAAK,EAAE,OAAO,CAAC,CAAC;CACjB;AAED,MAAM,CAAC,OAAO,UAAU,kBAAkB,CAAC,GAAG,EAAE,QAAQ,GAAG,SAAS,CAAC,KAAK,CAAC,CA4M1E"}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
const HELPER_IMPORT = '@lensmcp/react-instrumentation';
|
|
2
|
+
const HOOK_MAP = {
|
|
3
|
+
useEffect: 'tracedUseEffect',
|
|
4
|
+
useMemo: 'tracedUseMemo',
|
|
5
|
+
useCallback: 'tracedUseCallback',
|
|
6
|
+
};
|
|
7
|
+
// User interactions that constitute a flow origin. Deliberately excludes
|
|
8
|
+
// high-frequency events (mousemove/scroll/pointermove) to avoid flow spam.
|
|
9
|
+
const DEFAULT_FLOW_EVENTS = [
|
|
10
|
+
'onClick',
|
|
11
|
+
'onDoubleClick',
|
|
12
|
+
'onContextMenu',
|
|
13
|
+
'onSubmit',
|
|
14
|
+
'onChange',
|
|
15
|
+
];
|
|
16
|
+
const ORIGIN_TYPE = {
|
|
17
|
+
onSubmit: 'form-submit',
|
|
18
|
+
onChange: 'input-change',
|
|
19
|
+
};
|
|
20
|
+
export default function lensmcpBabelPlugin(api) {
|
|
21
|
+
const types = api.types;
|
|
22
|
+
return {
|
|
23
|
+
name: '@lensmcp/react-instrumentation/babel-plugin',
|
|
24
|
+
visitor: {
|
|
25
|
+
Program: {
|
|
26
|
+
enter(path, state) {
|
|
27
|
+
state.needHelpers = new Set();
|
|
28
|
+
state.needRoot = false;
|
|
29
|
+
state.hookIndex = 0;
|
|
30
|
+
state.flowEvents = new Set(state.opts.flowEvents ?? DEFAULT_FLOW_EVENTS);
|
|
31
|
+
state.rootVars = new Set();
|
|
32
|
+
if (state.opts.production ?? process.env['NODE_ENV'] === 'production') {
|
|
33
|
+
state.fileIgnored = true;
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const leading = path.node.body[0]?.leadingComments ?? path.node.directives.flatMap((d) => d.leadingComments ?? []);
|
|
37
|
+
if ((leading ?? []).some((c) => c.value.includes('@lensmcp-ignore'))) {
|
|
38
|
+
state.fileIgnored = true;
|
|
39
|
+
}
|
|
40
|
+
const file = state.file?.opts?.filename;
|
|
41
|
+
const rootDir = state.opts.rootDir ?? process.cwd();
|
|
42
|
+
if (file && file.startsWith(rootDir)) {
|
|
43
|
+
state.relativePath = file.slice(rootDir.length).replace(/^\/+/, '');
|
|
44
|
+
}
|
|
45
|
+
else if (file) {
|
|
46
|
+
state.relativePath = file;
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
exit(path, state) {
|
|
50
|
+
if (state.fileIgnored)
|
|
51
|
+
return;
|
|
52
|
+
const helpers = [...(state.needHelpers ?? [])];
|
|
53
|
+
if (state.needRoot)
|
|
54
|
+
helpers.push('LensmcpRoot', 'installFlowFetch');
|
|
55
|
+
if (helpers.length === 0)
|
|
56
|
+
return;
|
|
57
|
+
// Only import helpers not already imported from our package.
|
|
58
|
+
const already = collectImported(path.node.body, HELPER_IMPORT, types);
|
|
59
|
+
const missing = helpers.filter((h) => !already.has(h));
|
|
60
|
+
if (missing.length > 0) {
|
|
61
|
+
path.node.body.unshift(types.importDeclaration(missing.map((h) => types.importSpecifier(types.identifier(h), types.identifier(h))), types.stringLiteral(HELPER_IMPORT)));
|
|
62
|
+
}
|
|
63
|
+
// Install the flow-aware fetch once, after the imports.
|
|
64
|
+
if (state.needRoot) {
|
|
65
|
+
const firstNonImport = path.node.body.findIndex((n) => !types.isImportDeclaration(n));
|
|
66
|
+
const callStmt = types.expressionStatement(types.callExpression(types.identifier('installFlowFetch'), []));
|
|
67
|
+
path.node.body.splice(firstNonImport < 0 ? path.node.body.length : firstNonImport, 0, callStmt);
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
VariableDeclarator(path, state) {
|
|
72
|
+
if (state.fileIgnored)
|
|
73
|
+
return;
|
|
74
|
+
// Track `const root = createRoot(...)` so the common two-statement
|
|
75
|
+
// bootstrap (`root.render(<App/>)`, often inside a .then callback)
|
|
76
|
+
// also gets the LensmcpRoot wrap — not just the fluent one-liner.
|
|
77
|
+
if (state.opts.autoWrapRoot !== false &&
|
|
78
|
+
types.isIdentifier(path.node.id) &&
|
|
79
|
+
path.node.init &&
|
|
80
|
+
isRootFactoryCall(path.node.init, types)) {
|
|
81
|
+
state.rootVars.add(path.node.id.name);
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
CallExpression(path, state) {
|
|
85
|
+
if (state.fileIgnored)
|
|
86
|
+
return;
|
|
87
|
+
const callee = path.node.callee;
|
|
88
|
+
// 1. Hook auto-wrap: useEffect/useMemo/useCallback(...) → traced*.
|
|
89
|
+
if (state.opts.autoWrapHooks !== false && types.isIdentifier(callee) && HOOK_MAP[callee.name]) {
|
|
90
|
+
const traced = HOOK_MAP[callee.name];
|
|
91
|
+
// Skip if already a traced call or first arg is already an id string.
|
|
92
|
+
const id = `${state.relativePath ?? '(anon)'}:${path.node.loc?.start.line ?? 0}:${state.hookIndex++}`;
|
|
93
|
+
path.node.callee = types.identifier(traced);
|
|
94
|
+
path.node.arguments.unshift(types.stringLiteral(id));
|
|
95
|
+
state.needHelpers.add(traced);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
// 2. Root auto-wrap: createRoot(x).render(EXPR) → .render(<LensmcpRoot>{EXPR}</LensmcpRoot>).
|
|
99
|
+
if (state.opts.autoWrapRoot !== false &&
|
|
100
|
+
types.isMemberExpression(callee) &&
|
|
101
|
+
types.isIdentifier(callee.property, { name: 'render' }) &&
|
|
102
|
+
(isRootFactoryCall(callee.object, types) ||
|
|
103
|
+
(types.isIdentifier(callee.object) && state.rootVars?.has(callee.object.name))) &&
|
|
104
|
+
path.node.arguments.length >= 1) {
|
|
105
|
+
const arg = path.node.arguments[0];
|
|
106
|
+
if (arg && !isAlreadyLensmcpRoot(arg, types)) {
|
|
107
|
+
path.node.arguments[0] = types.jsxElement(types.jsxOpeningElement(types.jsxIdentifier('LensmcpRoot'), [], false), types.jsxClosingElement(types.jsxIdentifier('LensmcpRoot')), [types.jsxExpressionContainer(arg)], false);
|
|
108
|
+
state.needRoot = true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
JSXOpeningElement(path, state) {
|
|
113
|
+
if (state.fileIgnored)
|
|
114
|
+
return;
|
|
115
|
+
// Already tagged? Skip.
|
|
116
|
+
const attrs = path.node.attributes;
|
|
117
|
+
if (hasAttr(attrs, 'data-agent-component'))
|
|
118
|
+
return;
|
|
119
|
+
if (hasAttr(attrs, 'data-lensmcp-ignore'))
|
|
120
|
+
return;
|
|
121
|
+
const leading = path.parent.leadingComments ?? path.node.leadingComments;
|
|
122
|
+
if ((leading ?? []).some((c) => c.value.includes('@lensmcp-ignore'))) {
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
// Auto-wrap user-interaction handlers with `withFlow` so a click/
|
|
126
|
+
// submit/change starts a correlated flow (origin → backend) with no
|
|
127
|
+
// app code. Done before tagging so we only walk authored attributes.
|
|
128
|
+
if (state.opts.autoFlowHandlers !== false) {
|
|
129
|
+
const loc = path.node.loc;
|
|
130
|
+
const line = loc?.start.line ?? 0;
|
|
131
|
+
const file = state.relativePath ?? '(anon)';
|
|
132
|
+
for (const attr of path.node.attributes) {
|
|
133
|
+
if (attr.type !== 'JSXAttribute' ||
|
|
134
|
+
attr.name.type !== 'JSXIdentifier' ||
|
|
135
|
+
!state.flowEvents.has(attr.name.name) ||
|
|
136
|
+
!attr.value ||
|
|
137
|
+
attr.value.type !== 'JSXExpressionContainer') {
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
const expr = attr.value.expression;
|
|
141
|
+
if (expr.type === 'JSXEmptyExpression' ||
|
|
142
|
+
isAlreadyWithFlow(expr, types)) {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const event = attr.name.name;
|
|
146
|
+
attr.value.expression = types.callExpression(types.identifier('withFlow'), [
|
|
147
|
+
expr,
|
|
148
|
+
types.objectExpression([
|
|
149
|
+
types.objectProperty(types.identifier('originType'), types.stringLiteral(ORIGIN_TYPE[event] ?? 'user-click')),
|
|
150
|
+
types.objectProperty(types.identifier('originNodeId'), types.stringLiteral(`ui:${file}:${line}:${event}`)),
|
|
151
|
+
]),
|
|
152
|
+
]);
|
|
153
|
+
state.needHelpers.add('withFlow');
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const name = describeElementName(path.node.name);
|
|
157
|
+
if (!name)
|
|
158
|
+
return;
|
|
159
|
+
// Never stamp React special element types — they validate their props
|
|
160
|
+
// (React 19 errors with "Invalid prop supplied to React.Fragment") and
|
|
161
|
+
// render no DOM to identify anyway. Includes aliased context providers
|
|
162
|
+
// (`const XProvider = Ctx.Provider`), which a `Fragment`-only check misses.
|
|
163
|
+
if (isUnstampableElement(name))
|
|
164
|
+
return;
|
|
165
|
+
const newAttrs = [
|
|
166
|
+
types.jsxAttribute(types.jsxIdentifier('data-agent-component'), types.stringLiteral(name)),
|
|
167
|
+
];
|
|
168
|
+
if (state.opts.includeSource !== false) {
|
|
169
|
+
const loc = path.node.loc;
|
|
170
|
+
const line = loc?.start.line ?? 0;
|
|
171
|
+
const file = state.relativePath ?? '(anon)';
|
|
172
|
+
newAttrs.push(types.jsxAttribute(types.jsxIdentifier('data-agent-source'), types.stringLiteral(`${file}:${line}`)));
|
|
173
|
+
}
|
|
174
|
+
path.node.attributes.push(...newAttrs);
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
function hasAttr(attrs, name) {
|
|
180
|
+
return attrs.some((a) => a.type === 'JSXAttribute' &&
|
|
181
|
+
a.name.type === 'JSXIdentifier' &&
|
|
182
|
+
a.name.name === name);
|
|
183
|
+
}
|
|
184
|
+
/** Names already imported from `source` in this program body. */
|
|
185
|
+
function collectImported(body, source, types) {
|
|
186
|
+
const out = new Set();
|
|
187
|
+
for (const node of body) {
|
|
188
|
+
if (types.isImportDeclaration(node) && node.source.value === source) {
|
|
189
|
+
for (const spec of node.specifiers) {
|
|
190
|
+
if (types.isImportSpecifier(spec) && types.isIdentifier(spec.imported)) {
|
|
191
|
+
out.add(spec.imported.name);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
/** Is `node` a `createRoot(...)` / `hydrateRoot(...)` call (bare or member)? */
|
|
199
|
+
function isRootFactoryCall(node, types) {
|
|
200
|
+
if (!types.isCallExpression(node))
|
|
201
|
+
return false;
|
|
202
|
+
const callee = node.callee;
|
|
203
|
+
const names = new Set(['createRoot', 'hydrateRoot']);
|
|
204
|
+
if (types.isIdentifier(callee))
|
|
205
|
+
return names.has(callee.name);
|
|
206
|
+
if (types.isMemberExpression(callee) && types.isIdentifier(callee.property)) {
|
|
207
|
+
return names.has(callee.property.name);
|
|
208
|
+
}
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
/** Already wrapped with `withFlow(...)`? Keeps the transform idempotent. */
|
|
212
|
+
function isAlreadyWithFlow(node, types) {
|
|
213
|
+
return (types.isCallExpression(node) &&
|
|
214
|
+
types.isIdentifier(node.callee, { name: 'withFlow' }));
|
|
215
|
+
}
|
|
216
|
+
/** Already wrapped in <LensmcpRoot>? */
|
|
217
|
+
function isAlreadyLensmcpRoot(arg, types) {
|
|
218
|
+
return (types.isJSXElement(arg) &&
|
|
219
|
+
types.isJSXIdentifier(arg.openingElement.name, { name: 'LensmcpRoot' }));
|
|
220
|
+
}
|
|
221
|
+
// React special element types reject unknown props (validated like fragments
|
|
222
|
+
// in React 19). `<>…</>` is a JSXFragment and never reaches the visitor; this
|
|
223
|
+
// covers the named forms — including aliases that END in Provider/Consumer
|
|
224
|
+
// (`const NavigationSlotsProvider = Ctx.Provider`), which render no DOM and
|
|
225
|
+
// would otherwise crash the host app's console with prop-validation errors.
|
|
226
|
+
const SPECIAL_UNSTAMPABLE = new Set([
|
|
227
|
+
'Fragment',
|
|
228
|
+
'StrictMode',
|
|
229
|
+
'Suspense',
|
|
230
|
+
'SuspenseList',
|
|
231
|
+
'Profiler',
|
|
232
|
+
]);
|
|
233
|
+
function isUnstampableElement(name) {
|
|
234
|
+
const last = name.split('.').pop() ?? name;
|
|
235
|
+
if (SPECIAL_UNSTAMPABLE.has(last))
|
|
236
|
+
return true;
|
|
237
|
+
return last.endsWith('Provider') || last.endsWith('Consumer');
|
|
238
|
+
}
|
|
239
|
+
function describeElementName(node) {
|
|
240
|
+
switch (node.type) {
|
|
241
|
+
case 'JSXIdentifier':
|
|
242
|
+
return node.name;
|
|
243
|
+
case 'JSXMemberExpression': {
|
|
244
|
+
const parts = [];
|
|
245
|
+
let cur = node;
|
|
246
|
+
while (cur.type === 'JSXMemberExpression') {
|
|
247
|
+
parts.unshift(cur.property.name);
|
|
248
|
+
cur = cur.object;
|
|
249
|
+
}
|
|
250
|
+
if (cur.type === 'JSXIdentifier')
|
|
251
|
+
parts.unshift(cur.name);
|
|
252
|
+
return parts.join('.');
|
|
253
|
+
}
|
|
254
|
+
case 'JSXNamespacedName':
|
|
255
|
+
return `${node.namespace.name}:${node.name.name}`;
|
|
256
|
+
default:
|
|
257
|
+
return undefined;
|
|
258
|
+
}
|
|
259
|
+
}
|