@rainbow-robotics/plugin-ui 0.1.2-dev.5 → 0.1.2-dev.50
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/README.md +236 -75
- package/build-dist.mjs +55 -17
- package/dist/host-ui.d.ts +49 -0
- package/dist/host-ui.d.ts.map +1 -0
- package/dist/host-ui.js +33 -0
- package/dist/host-ui.js.map +7 -0
- package/dist/manifest.d.ts +20 -4
- package/dist/manifest.d.ts.map +1 -1
- package/dist/manifest.js +1 -1
- package/dist/manifest.js.map +2 -2
- package/dist/pluginData.d.ts +62 -0
- package/dist/pluginData.d.ts.map +1 -0
- package/dist/react.d.ts +3430 -36
- package/dist/react.js +5 -54
- package/dist/react.js.map +2 -2
- package/dist/sdk.d.ts +54 -4
- package/dist/sdk.d.ts.map +1 -1
- package/dist/sdk.js +44 -10
- package/dist/sdk.js.map +2 -2
- package/dist/viteHost.d.ts +46 -0
- package/dist/viteHost.d.ts.map +1 -0
- package/dist/viteHost.js +262 -0
- package/dist/viteHost.js.map +7 -0
- package/dist/ws.d.ts +73 -0
- package/dist/ws.d.ts.map +1 -0
- package/dist/ws.js +129 -0
- package/dist/ws.js.map +7 -0
- package/package.json +41 -22
- package/src/host-ui.ts +80 -0
- package/src/host.tsx +225 -295
- package/src/index.d.ts +1 -0
- package/src/manifest.ts +25 -4
- package/src/pluginData.tsx +232 -0
- package/src/react.tsx +9 -127
- package/src/sdk.ts +119 -18
- package/src/viteHost.ts +309 -0
- package/src/ws.ts +204 -0
- package/build-browser.mjs +0 -84
- package/dist/connect.d.ts +0 -12
- package/dist/connect.d.ts.map +0 -1
- package/dist/connect.js +0 -29
- package/dist/connect.js.map +0 -7
- package/dist/elements.d.ts +0 -195
- package/dist/elements.d.ts.map +0 -1
- package/dist/elements.js +0 -115
- package/dist/elements.js.map +0 -7
- package/dist/react.d.ts.map +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/chunks/chunk-AMCIKVG7.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/chunks/chunk-GJWPOWHG.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/chunks/chunk-JRCDA3EG.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/connect.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/elements.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/react.js +0 -1
- package/dist-browser/@rainbow-robotics/plugin-ui/sdk.js +0 -1
- package/dist-browser/vendor/react-dom-client.js +0 -1
- package/dist-browser/vendor/react-jsx-dev-runtime.js +0 -1
- package/dist-browser/vendor/react-jsx-runtime.js +0 -1
- package/dist-browser/vendor/react-runtime.js +0 -65
- package/dist-browser/vendor/react.js +0 -1
- package/src/connect.ts +0 -68
- package/src/elements.ts +0 -257
package/src/viteHost.ts
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Vite plugins for a HOST app previewing locally-developed plugins.
|
|
3
|
+
* Host-agnostic — paths are parameters.
|
|
4
|
+
*
|
|
5
|
+
* import {
|
|
6
|
+
* pluginPreviewRuntimePlugin,
|
|
7
|
+
* pluginPreviewAssetsPlugin,
|
|
8
|
+
* isPluginPreviewMode,
|
|
9
|
+
* } from "@rainbow-robotics/plugin-ui/vite-host";
|
|
10
|
+
*
|
|
11
|
+
* A built plugin's bare imports (react, rb-components, plugin-ui/*) resolve via
|
|
12
|
+
* the import map this file injects, to the host's already-loaded instances.
|
|
13
|
+
* See ./host.tsx.
|
|
14
|
+
*/
|
|
15
|
+
import type { Plugin } from "vite";
|
|
16
|
+
import { createReadStream, existsSync, readFileSync, statSync } from "node:fs";
|
|
17
|
+
import { createRequire } from "node:module";
|
|
18
|
+
import { extname, resolve } from "node:path";
|
|
19
|
+
|
|
20
|
+
const require = createRequire(import.meta.url);
|
|
21
|
+
|
|
22
|
+
export const defaultPreviewAssetPrefixes = [
|
|
23
|
+
"/imgs/",
|
|
24
|
+
"/fonts/",
|
|
25
|
+
"/models/",
|
|
26
|
+
"/sounds/",
|
|
27
|
+
"/data/",
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
export const contentTypeByExt: Record<string, string> = {
|
|
31
|
+
".avif": "image/avif",
|
|
32
|
+
".css": "text/css; charset=utf-8",
|
|
33
|
+
".gif": "image/gif",
|
|
34
|
+
".glb": "model/gltf-binary",
|
|
35
|
+
".jpeg": "image/jpeg",
|
|
36
|
+
".jpg": "image/jpeg",
|
|
37
|
+
".js": "text/javascript; charset=utf-8",
|
|
38
|
+
".json": "application/json; charset=utf-8",
|
|
39
|
+
".mp3": "audio/mpeg",
|
|
40
|
+
".png": "image/png",
|
|
41
|
+
".svg": "image/svg+xml",
|
|
42
|
+
".wasm": "application/wasm",
|
|
43
|
+
".webp": "image/webp",
|
|
44
|
+
".woff": "font/woff",
|
|
45
|
+
".woff2": "font/woff2",
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export const isPluginPreviewMode = (mode: string) => mode === "plugin-preview";
|
|
49
|
+
|
|
50
|
+
/* -------------------------------------------------------------------------- */
|
|
51
|
+
/* Shared-runtime import map (plugins reuse the host's loaded instances) */
|
|
52
|
+
/* -------------------------------------------------------------------------- */
|
|
53
|
+
|
|
54
|
+
const SHARED_BASE = "/plugin-shared";
|
|
55
|
+
|
|
56
|
+
// Each shared specifier → the named exports its shim re-exports from
|
|
57
|
+
// window.__RB_SHARED__[specifier] (set by the host, e.g. nexus/src/pluginShared).
|
|
58
|
+
//
|
|
59
|
+
// `names`: hardcoded list (small, stable modules).
|
|
60
|
+
// `parseNamesFrom`: parse the export names out of a source file's text — used
|
|
61
|
+
// for react.tsx, which re-exports the whole rb-components barrel (100+ names).
|
|
62
|
+
// We text-parse rather than import it: the barrel is .ts source, which plain
|
|
63
|
+
// Node can't execute.
|
|
64
|
+
const SHARED_MODULES: Record<
|
|
65
|
+
string,
|
|
66
|
+
{
|
|
67
|
+
file: string;
|
|
68
|
+
names?: string[];
|
|
69
|
+
parseNamesFrom?: { specifier: string; extraNames?: string[] };
|
|
70
|
+
hasDefault?: boolean;
|
|
71
|
+
}
|
|
72
|
+
> = {
|
|
73
|
+
react: {
|
|
74
|
+
file: "react",
|
|
75
|
+
hasDefault: true,
|
|
76
|
+
names: [
|
|
77
|
+
"Children", "Component", "Fragment", "Profiler", "PureComponent",
|
|
78
|
+
"StrictMode", "Suspense", "cloneElement", "createContext",
|
|
79
|
+
"createElement", "createRef", "forwardRef", "isValidElement", "lazy",
|
|
80
|
+
"memo", "startTransition", "useCallback", "useContext", "useDebugValue",
|
|
81
|
+
"useDeferredValue", "useEffect", "useId", "useImperativeHandle",
|
|
82
|
+
"useInsertionEffect", "useLayoutEffect", "useMemo", "useReducer",
|
|
83
|
+
"useRef", "useState", "useSyncExternalStore", "useTransition", "version",
|
|
84
|
+
],
|
|
85
|
+
},
|
|
86
|
+
"react/jsx-runtime": {
|
|
87
|
+
file: "react_jsx-runtime",
|
|
88
|
+
names: ["Fragment", "jsx", "jsxs"],
|
|
89
|
+
},
|
|
90
|
+
"react/jsx-dev-runtime": {
|
|
91
|
+
file: "react_jsx-dev-runtime",
|
|
92
|
+
names: ["Fragment", "jsxDEV"],
|
|
93
|
+
},
|
|
94
|
+
"react-dom": {
|
|
95
|
+
file: "react-dom",
|
|
96
|
+
hasDefault: true,
|
|
97
|
+
names: [
|
|
98
|
+
"__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED",
|
|
99
|
+
"createPortal",
|
|
100
|
+
"createRoot",
|
|
101
|
+
"findDOMNode",
|
|
102
|
+
"flushSync",
|
|
103
|
+
"hydrate",
|
|
104
|
+
"hydrateRoot",
|
|
105
|
+
"render",
|
|
106
|
+
"unmountComponentAtNode",
|
|
107
|
+
"unstable_batchedUpdates",
|
|
108
|
+
"unstable_renderSubtreeIntoContainer",
|
|
109
|
+
"version",
|
|
110
|
+
],
|
|
111
|
+
},
|
|
112
|
+
"react-dom/client": {
|
|
113
|
+
file: "react-dom_client",
|
|
114
|
+
names: ["createRoot", "hydrateRoot"],
|
|
115
|
+
},
|
|
116
|
+
"@rainbow-robotics/plugin-ui/react": {
|
|
117
|
+
file: "plugin-ui_react",
|
|
118
|
+
// react.tsx re-exports the full rb-components barrel (export *) plus the sdk
|
|
119
|
+
// hooks.
|
|
120
|
+
parseNamesFrom: {
|
|
121
|
+
specifier: "@repo/rb-components/new_components",
|
|
122
|
+
extraNames: ["useRb", "useRbFormData", "useRbSave"],
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
"@rainbow-robotics/plugin-ui/sdk": {
|
|
126
|
+
file: "plugin-ui_sdk",
|
|
127
|
+
names: ["RbContext", "useRb", "useRbFormData", "useRbSave"],
|
|
128
|
+
},
|
|
129
|
+
"@rainbow-robotics/plugin-ui/host-ui": {
|
|
130
|
+
file: "plugin-ui_host-ui",
|
|
131
|
+
names: [
|
|
132
|
+
"alert",
|
|
133
|
+
"confirm",
|
|
134
|
+
"getHostServices",
|
|
135
|
+
"prompt",
|
|
136
|
+
"setHostServices",
|
|
137
|
+
"toast",
|
|
138
|
+
],
|
|
139
|
+
},
|
|
140
|
+
"@rainbow-robotics/plugin-ui/ws": {
|
|
141
|
+
file: "plugin-ui_ws",
|
|
142
|
+
names: ["RbWs", "createLazyRbSdk"],
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// Parses `export { a, b as c, ... }` value names out of a source file's text
|
|
147
|
+
// (skips `export type { ... }` blocks and individual `type X` entries within
|
|
148
|
+
// a mixed block — types don't exist as runtime module properties). Static
|
|
149
|
+
// text parsing, not module execution, so it works for .ts source files with
|
|
150
|
+
// no loader and has no ESM-resolution footguns.
|
|
151
|
+
function parseExportedValueNames(source: string): string[] {
|
|
152
|
+
const names = new Set<string>();
|
|
153
|
+
const blockRe = /export\s+(type\s+)?\{([^}]*)\}/g;
|
|
154
|
+
let match: RegExpExecArray | null;
|
|
155
|
+
while ((match = blockRe.exec(source))) {
|
|
156
|
+
if (match[1]) continue; // whole `export type { ... }` block
|
|
157
|
+
for (const rawEntry of match[2].split(",")) {
|
|
158
|
+
const entry = rawEntry.trim();
|
|
159
|
+
if (!entry || entry.startsWith("type ")) continue;
|
|
160
|
+
const asMatch = entry.match(/^\S+\s+as\s+(\S+)$/);
|
|
161
|
+
names.add(asMatch ? asMatch[1] : entry);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return [...names];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const nameCache = new Map<string, string[]>();
|
|
168
|
+
|
|
169
|
+
function resolveNames(spec: string): string[] {
|
|
170
|
+
const mod = SHARED_MODULES[spec];
|
|
171
|
+
if (mod.names) return mod.names;
|
|
172
|
+
if (!mod.parseNamesFrom) {
|
|
173
|
+
throw new Error(`[plugin-ui] ${spec} has neither "names" nor "parseNamesFrom"`);
|
|
174
|
+
}
|
|
175
|
+
if (!nameCache.has(spec)) {
|
|
176
|
+
const { specifier, extraNames = [] } = mod.parseNamesFrom;
|
|
177
|
+
const sourcePath = require.resolve(specifier);
|
|
178
|
+
const parsed = parseExportedValueNames(readFileSync(sourcePath, "utf8"));
|
|
179
|
+
nameCache.set(spec, [...new Set([...parsed, ...extraNames])]);
|
|
180
|
+
}
|
|
181
|
+
return nameCache.get(spec)!;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function shimSource(spec: string): string {
|
|
185
|
+
const mod = SHARED_MODULES[spec];
|
|
186
|
+
const names = resolveNames(spec);
|
|
187
|
+
const g = `(globalThis.__RB_SHARED__||{})[${JSON.stringify(spec)}]`;
|
|
188
|
+
return (
|
|
189
|
+
`const m = ${g};\n` +
|
|
190
|
+
`if (!m) throw new Error("[plugin-ui] host shared module not registered: ${spec}");\n` +
|
|
191
|
+
`export const { ${names.join(", ")} } = m;\n` +
|
|
192
|
+
(mod.hasDefault ? `export default (m.default ?? m);\n` : "")
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const fileToSpec = Object.fromEntries(
|
|
197
|
+
Object.entries(SHARED_MODULES).map(([spec, { file }]) => [file, spec]),
|
|
198
|
+
);
|
|
199
|
+
|
|
200
|
+
function importMapScript(): string {
|
|
201
|
+
const imports: Record<string, string> = {};
|
|
202
|
+
for (const [spec, { file }] of Object.entries(SHARED_MODULES)) {
|
|
203
|
+
imports[spec] = `${SHARED_BASE}/${file}.js`;
|
|
204
|
+
}
|
|
205
|
+
return `<script type="importmap">${JSON.stringify({ imports })}</script>`;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Serves the shared-runtime shim modules at /plugin-shared/*.js and injects the
|
|
210
|
+
* import map so a dynamically-imported plugin's bare `import "react"` /
|
|
211
|
+
* `import "@rainbow-robotics/plugin-ui/react"` etc. resolve to the host's OWN
|
|
212
|
+
* instances (via window.__RB_SHARED__). Applied in all modes — any nexus build
|
|
213
|
+
* that can host plugins needs it.
|
|
214
|
+
*/
|
|
215
|
+
export const pluginSharedRuntimePlugin = (): Plugin => ({
|
|
216
|
+
name: "plugin-ui-shared-runtime",
|
|
217
|
+
transformIndexHtml(html) {
|
|
218
|
+
return html.replace("</head>", ` ${importMapScript()}\n </head>`);
|
|
219
|
+
},
|
|
220
|
+
configureServer(server) {
|
|
221
|
+
server.middlewares.use((req, res, next) => {
|
|
222
|
+
const url = req.url?.split("?")[0];
|
|
223
|
+
if (!url?.startsWith(`${SHARED_BASE}/`)) return next();
|
|
224
|
+
const file = url.slice(`${SHARED_BASE}/`.length).replace(/\.js$/, "");
|
|
225
|
+
const spec = fileToSpec[file];
|
|
226
|
+
if (!spec) return next();
|
|
227
|
+
res.setHeader("Content-Type", "text/javascript; charset=utf-8");
|
|
228
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
229
|
+
res.end(shimSource(spec));
|
|
230
|
+
});
|
|
231
|
+
},
|
|
232
|
+
generateBundle() {
|
|
233
|
+
for (const [spec, { file }] of Object.entries(SHARED_MODULES)) {
|
|
234
|
+
this.emitFile({
|
|
235
|
+
type: "asset",
|
|
236
|
+
fileName: `plugin-shared/${file}.js`,
|
|
237
|
+
source: shimSource(spec),
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
/** Inject the preview-host runtime flags into index.html (plugin-preview only). */
|
|
244
|
+
export const pluginPreviewRuntimePlugin = (): Plugin => ({
|
|
245
|
+
name: "plugin-ui-preview-runtime",
|
|
246
|
+
apply: (_config, { mode }) => isPluginPreviewMode(mode),
|
|
247
|
+
transformIndexHtml(html) {
|
|
248
|
+
return html.replace(
|
|
249
|
+
"</head>",
|
|
250
|
+
[
|
|
251
|
+
" <script>",
|
|
252
|
+
" window.__RB_PLUGIN_PREVIEW_HOST__ = true;",
|
|
253
|
+
" window.__RB_ASSETS_BASE_URL__ = window.location.origin;",
|
|
254
|
+
" </script>",
|
|
255
|
+
" </head>",
|
|
256
|
+
].join("\n"),
|
|
257
|
+
);
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
/** Serve the host's static assets (imgs/fonts/...) in plugin-preview dev mode. */
|
|
262
|
+
export const pluginPreviewAssetsPlugin = (opts: {
|
|
263
|
+
assetsDir: string;
|
|
264
|
+
prefixes?: string[];
|
|
265
|
+
}): Plugin => {
|
|
266
|
+
const { assetsDir, prefixes = defaultPreviewAssetPrefixes } = opts;
|
|
267
|
+
return {
|
|
268
|
+
name: "plugin-ui-preview-assets",
|
|
269
|
+
apply: (_config, { command, mode }) =>
|
|
270
|
+
command === "serve" && isPluginPreviewMode(mode),
|
|
271
|
+
configureServer(server) {
|
|
272
|
+
server.middlewares.use((req, res, next) => {
|
|
273
|
+
const url = req.url?.split("?")[0];
|
|
274
|
+
if (!url || !prefixes.some((prefix) => url.startsWith(prefix)))
|
|
275
|
+
return next();
|
|
276
|
+
|
|
277
|
+
const decodedUrl = decodeURIComponent(url);
|
|
278
|
+
const filePath = resolve(assetsDir, `.${decodedUrl}`);
|
|
279
|
+
if (!filePath.startsWith(assetsDir)) return next();
|
|
280
|
+
if (!existsSync(filePath) || !statSync(filePath).isFile()) return next();
|
|
281
|
+
|
|
282
|
+
const contentType = contentTypeByExt[extname(filePath)];
|
|
283
|
+
if (contentType) res.setHeader("Content-Type", contentType);
|
|
284
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
285
|
+
createReadStream(filePath).pipe(res);
|
|
286
|
+
});
|
|
287
|
+
},
|
|
288
|
+
};
|
|
289
|
+
};
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* All host-side plugin-ui Vite plugins in one call. Each self-gates by mode, so
|
|
293
|
+
* a host just spreads this into its `plugins` array.
|
|
294
|
+
*
|
|
295
|
+
* plugins: [muscatVitePlugin({ previewAssetsDir: resolve(here, "../assets/public") })]
|
|
296
|
+
*/
|
|
297
|
+
export const muscatVitePlugin = (opts: {
|
|
298
|
+
/** Host static assets dir served in plugin-preview dev mode. */
|
|
299
|
+
previewAssetsDir: string;
|
|
300
|
+
/** Override preview asset URL prefixes. */
|
|
301
|
+
previewAssetPrefixes?: string[];
|
|
302
|
+
}): Plugin[] => [
|
|
303
|
+
pluginSharedRuntimePlugin(),
|
|
304
|
+
pluginPreviewRuntimePlugin(),
|
|
305
|
+
pluginPreviewAssetsPlugin({
|
|
306
|
+
assetsDir: opts.previewAssetsDir,
|
|
307
|
+
prefixes: opts.previewAssetPrefixes,
|
|
308
|
+
}),
|
|
309
|
+
];
|
package/src/ws.ts
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Socket.IO communication client for plugin frontends.
|
|
3
|
+
*
|
|
4
|
+
* Topics are automatically namespaced to prevent cross-plugin collisions:
|
|
5
|
+
* "sensor/data" → "{pluginId}/sensor/data"
|
|
6
|
+
* "/broadcast/x" → "broadcast/x" (leading slash = absolute)
|
|
7
|
+
*
|
|
8
|
+
* Browser ←→ Python backend protocol:
|
|
9
|
+
* browser emits : sub, unsub, pub, action (with ack), serve_reply
|
|
10
|
+
* server emits : msg, serve_call
|
|
11
|
+
*/
|
|
12
|
+
import { io, type Socket } from "socket.io-client";
|
|
13
|
+
// Type-only — no runtime coupling to host-ui.ts.
|
|
14
|
+
import type { PluginUIServices } from "./host-ui";
|
|
15
|
+
|
|
16
|
+
export interface WsHandle {
|
|
17
|
+
undeclare(): void;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type WsSubscriber = WsHandle;
|
|
21
|
+
export type WsQueryable = WsHandle;
|
|
22
|
+
|
|
23
|
+
function resolveTopic(pluginId: string, topic: string): string {
|
|
24
|
+
return topic.startsWith("/") ? topic.slice(1) : `${pluginId}/${topic}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class RbWs {
|
|
28
|
+
private readonly _socket: Socket;
|
|
29
|
+
private readonly _pluginId: string;
|
|
30
|
+
private readonly _subHandlers = new Map<
|
|
31
|
+
string,
|
|
32
|
+
Set<(payload: unknown) => void>
|
|
33
|
+
>();
|
|
34
|
+
private readonly _serveHandlers = new Map<
|
|
35
|
+
string,
|
|
36
|
+
(payload?: unknown) => unknown | Promise<unknown>
|
|
37
|
+
>();
|
|
38
|
+
|
|
39
|
+
private constructor(socket: Socket, pluginId: string) {
|
|
40
|
+
this._socket = socket;
|
|
41
|
+
this._pluginId = pluginId;
|
|
42
|
+
|
|
43
|
+
// Deliver incoming pub/sub messages to registered handlers
|
|
44
|
+
socket.on(
|
|
45
|
+
"msg",
|
|
46
|
+
({ topic, payload }: { topic: string; payload: unknown }) => {
|
|
47
|
+
this._subHandlers.get(topic)?.forEach((h) => h(payload));
|
|
48
|
+
},
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
// Python calls a browser-side serve handler
|
|
52
|
+
socket.on(
|
|
53
|
+
"serve_call",
|
|
54
|
+
async ({
|
|
55
|
+
id,
|
|
56
|
+
topic,
|
|
57
|
+
payload,
|
|
58
|
+
}: {
|
|
59
|
+
id: string;
|
|
60
|
+
topic: string;
|
|
61
|
+
payload: unknown;
|
|
62
|
+
}) => {
|
|
63
|
+
const handler = this._serveHandlers.get(topic);
|
|
64
|
+
const result = handler ? await handler(payload) : undefined;
|
|
65
|
+
socket.emit("serve_reply", { id, payload: result });
|
|
66
|
+
},
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
static connect(url: string, pluginId: string): Promise<RbWs> {
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
const socket = io(url, { transports: ["websocket"] });
|
|
73
|
+
const onConnect = () => {
|
|
74
|
+
cleanup();
|
|
75
|
+
resolve(new RbWs(socket, pluginId));
|
|
76
|
+
};
|
|
77
|
+
const onError = (err: Error) => {
|
|
78
|
+
cleanup();
|
|
79
|
+
reject(err);
|
|
80
|
+
};
|
|
81
|
+
const cleanup = () => {
|
|
82
|
+
socket.off("connect", onConnect);
|
|
83
|
+
socket.off("connect_error", onError);
|
|
84
|
+
};
|
|
85
|
+
socket.once("connect", onConnect);
|
|
86
|
+
socket.once("connect_error", onError);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private _key(topic: string): string {
|
|
91
|
+
return resolveTopic(this._pluginId, topic);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
95
|
+
async pub<P = any>(topic: string, payload: P): Promise<void> {
|
|
96
|
+
this._socket.emit("pub", { topic: this._key(topic), payload });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
100
|
+
async sub<P = any>(
|
|
101
|
+
topic: string,
|
|
102
|
+
handler: (payload: P) => void,
|
|
103
|
+
): Promise<WsSubscriber> {
|
|
104
|
+
const key = this._key(topic);
|
|
105
|
+
if (!this._subHandlers.has(key)) {
|
|
106
|
+
this._subHandlers.set(key, new Set());
|
|
107
|
+
this._socket.emit("sub", { topic: key });
|
|
108
|
+
}
|
|
109
|
+
const h = handler as (payload: unknown) => void;
|
|
110
|
+
this._subHandlers.get(key)!.add(h);
|
|
111
|
+
return {
|
|
112
|
+
undeclare: () => {
|
|
113
|
+
const set = this._subHandlers.get(key);
|
|
114
|
+
if (!set) return;
|
|
115
|
+
set.delete(h);
|
|
116
|
+
if (set.size === 0) {
|
|
117
|
+
this._subHandlers.delete(key);
|
|
118
|
+
this._socket.emit("unsub", { topic: key });
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
125
|
+
async action<R = any, P = any>(topic: string, payload?: P): Promise<R> {
|
|
126
|
+
return new Promise((resolve, reject) => {
|
|
127
|
+
this._socket
|
|
128
|
+
.timeout(10_000)
|
|
129
|
+
.emit(
|
|
130
|
+
"action",
|
|
131
|
+
{ topic: this._key(topic), payload },
|
|
132
|
+
(err: Error | null, result: R) => {
|
|
133
|
+
if (err) reject(err);
|
|
134
|
+
else resolve(result);
|
|
135
|
+
},
|
|
136
|
+
);
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
141
|
+
async serve<P = any, R = any>(
|
|
142
|
+
topic: string,
|
|
143
|
+
handler: (payload?: P) => R | Promise<R>,
|
|
144
|
+
): Promise<WsQueryable> {
|
|
145
|
+
const key = this._key(topic);
|
|
146
|
+
this._serveHandlers.set(key, handler as (payload?: unknown) => unknown);
|
|
147
|
+
this._socket.emit("serve_register", { topic: key });
|
|
148
|
+
return {
|
|
149
|
+
undeclare: () => {
|
|
150
|
+
this._serveHandlers.delete(key);
|
|
151
|
+
this._socket.emit("serve_unregister", { topic: key });
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
close(): void {
|
|
157
|
+
this._socket.disconnect();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Builds an rb-sdk-shaped object (pub/sub/action/serve + the passed-through
|
|
163
|
+
* toast/alert/confirm/prompt) that lazily awaits a not-yet-connected `RbWs` —
|
|
164
|
+
* so callers don't block their first render on the WebSocket handshake (there
|
|
165
|
+
* may be no backend reachable yet). Shared by both host mount paths (see
|
|
166
|
+
* ./host.tsx and muscat-plugin-kit's dev bootstrap), which otherwise
|
|
167
|
+
* duplicate this wiring.
|
|
168
|
+
*/
|
|
169
|
+
export function createLazyRbSdk(
|
|
170
|
+
wsPromise: Promise<RbWs>,
|
|
171
|
+
services: PluginUIServices,
|
|
172
|
+
// Per-mount, host-provided (unlike `services`, which is a global singleton):
|
|
173
|
+
// initial `data` and the `onSave` registration the host reads back. Plain
|
|
174
|
+
// values/closures, so they cross the dev React-instance boundary safely.
|
|
175
|
+
mount?: {
|
|
176
|
+
data?: unknown;
|
|
177
|
+
onSave?: (getPayload: () => unknown) => () => void;
|
|
178
|
+
},
|
|
179
|
+
) {
|
|
180
|
+
return {
|
|
181
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
182
|
+
pub: async (topic: string, payload: any) =>
|
|
183
|
+
(await wsPromise).pub(topic, payload),
|
|
184
|
+
sub: async (
|
|
185
|
+
topic: string,
|
|
186
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
187
|
+
handler: (payload: any) => void,
|
|
188
|
+
) => (await wsPromise).sub(topic, handler),
|
|
189
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
190
|
+
action: async (topic: string, payload?: any) =>
|
|
191
|
+
(await wsPromise).action(topic, payload),
|
|
192
|
+
serve: async (
|
|
193
|
+
topic: string,
|
|
194
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
195
|
+
handler: (payload?: any) => any,
|
|
196
|
+
) => (await wsPromise).serve(topic, handler),
|
|
197
|
+
toast: services.toast,
|
|
198
|
+
alert: services.alert,
|
|
199
|
+
confirm: services.confirm,
|
|
200
|
+
prompt: services.prompt,
|
|
201
|
+
data: mount?.data,
|
|
202
|
+
onSave: mount?.onSave ?? (() => () => {}),
|
|
203
|
+
};
|
|
204
|
+
}
|
package/build-browser.mjs
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
// Builds @rainbow-robotics/plugin-ui as browser ESM for the sandbox import map.
|
|
2
|
-
// Output: dist-browser/@rainbow-robotics/plugin-ui/{connect,react,sdk,elements}.js
|
|
3
|
-
// dist-browser/vendor/react-runtime.js
|
|
4
|
-
//
|
|
5
|
-
// Consumed by:
|
|
6
|
-
// - nexus (vite plugin emits dist-browser/ → dist/plugin-runtime/)
|
|
7
|
-
// - preview-host (serves dist-browser/ at /plugin-runtime/)
|
|
8
|
-
//
|
|
9
|
-
// Run: node libraries/plugin-ui/build-browser.mjs
|
|
10
|
-
import { build } from "esbuild";
|
|
11
|
-
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
12
|
-
import { dirname, resolve } from "node:path";
|
|
13
|
-
import { fileURLToPath } from "node:url";
|
|
14
|
-
|
|
15
|
-
const here = dirname(fileURLToPath(import.meta.url));
|
|
16
|
-
const src = resolve(here, "src");
|
|
17
|
-
const out = resolve(here, "dist-browser");
|
|
18
|
-
const repoRoot = resolve(here, "../..");
|
|
19
|
-
|
|
20
|
-
const define = { "process.env.NODE_ENV": JSON.stringify("production") };
|
|
21
|
-
const shared = {
|
|
22
|
-
bundle: true,
|
|
23
|
-
format: "esm",
|
|
24
|
-
platform: "browser",
|
|
25
|
-
target: "es2020",
|
|
26
|
-
minify: true,
|
|
27
|
-
sourcemap: false,
|
|
28
|
-
define,
|
|
29
|
-
logLevel: "warning",
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
rmSync(out, { recursive: true, force: true });
|
|
33
|
-
mkdirSync(resolve(out, "@rainbow-robotics/plugin-ui"), { recursive: true });
|
|
34
|
-
mkdirSync(resolve(out, "vendor"), { recursive: true });
|
|
35
|
-
|
|
36
|
-
// Plugin-UI entry points (react / react-dom provided by vendor bundle below)
|
|
37
|
-
await build({
|
|
38
|
-
...shared,
|
|
39
|
-
entryPoints: {
|
|
40
|
-
connect: resolve(src, "connect.ts"),
|
|
41
|
-
react: resolve(src, "react.tsx"),
|
|
42
|
-
sdk: resolve(src, "sdk.ts"),
|
|
43
|
-
elements: resolve(src, "elements.ts"),
|
|
44
|
-
},
|
|
45
|
-
outdir: resolve(out, "@rainbow-robotics/plugin-ui"),
|
|
46
|
-
entryNames: "[name]",
|
|
47
|
-
chunkNames: "chunks/[name]-[hash]",
|
|
48
|
-
splitting: true,
|
|
49
|
-
external: ["react", "react-dom/client"],
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
// Single vendor bundle: React + ReactDOM (sandbox loads this once via import map)
|
|
53
|
-
const reactShim = `
|
|
54
|
-
import React from "react";
|
|
55
|
-
import * as ReactClient from "react-dom/client";
|
|
56
|
-
import * as JsxRuntime from "react/jsx-runtime";
|
|
57
|
-
import * as JsxDevRuntime from "react/jsx-dev-runtime";
|
|
58
|
-
export default React;
|
|
59
|
-
export const { Children, Fragment, Profiler, StrictMode, Suspense,
|
|
60
|
-
cloneElement, createContext, createElement, createRef, forwardRef,
|
|
61
|
-
isValidElement, lazy, memo, startTransition, useCallback, useContext,
|
|
62
|
-
useDebugValue, useDeferredValue, useEffect, useId, useImperativeHandle,
|
|
63
|
-
useInsertionEffect, useLayoutEffect, useMemo, useReducer, useRef,
|
|
64
|
-
useState, useSyncExternalStore, useTransition, version } = React;
|
|
65
|
-
export const { createRoot, hydrateRoot } = ReactClient;
|
|
66
|
-
export const { jsx, jsxs } = JsxRuntime;
|
|
67
|
-
export const { jsxDEV } = JsxDevRuntime;
|
|
68
|
-
`;
|
|
69
|
-
|
|
70
|
-
await build({
|
|
71
|
-
...shared,
|
|
72
|
-
stdin: { contents: reactShim, resolveDir: repoRoot, loader: "js" },
|
|
73
|
-
outfile: resolve(out, "vendor", "react-runtime.js"),
|
|
74
|
-
});
|
|
75
|
-
|
|
76
|
-
// Aliases so all standard React specifiers map to the single vendor file
|
|
77
|
-
for (const name of ["react", "react-jsx-runtime", "react-jsx-dev-runtime", "react-dom-client"]) {
|
|
78
|
-
writeFileSync(
|
|
79
|
-
resolve(out, "vendor", `${name}.js`),
|
|
80
|
-
'export * from "./react-runtime.js"; export { default } from "./react-runtime.js";\n',
|
|
81
|
-
);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
console.log("[plugin-ui] dist-browser ready →", out);
|
package/dist/connect.d.ts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import { type ComponentType } from "react";
|
|
2
|
-
/**
|
|
3
|
-
* Mount a plugin. Call this once from the sandbox entry (sandbox.html), passing
|
|
4
|
-
* the plugin's root component.
|
|
5
|
-
*
|
|
6
|
-
* @example
|
|
7
|
-
* import { connect } from "@rainbow-robotics/plugin-ui/connect";
|
|
8
|
-
* import App from "./content";
|
|
9
|
-
* connect(App);
|
|
10
|
-
*/
|
|
11
|
-
export declare function connect(App: ComponentType): void;
|
|
12
|
-
//# sourceMappingURL=connect.d.ts.map
|
package/dist/connect.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAiB,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAc1D;;;;;;;;GAQG;AACH,wBAAgB,OAAO,CAAC,GAAG,EAAE,aAAa,GAAG,IAAI,CAwBhD"}
|
package/dist/connect.js
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { RemoteMutationObserver } from "@remote-dom/core/elements";
|
|
2
|
-
import { ThreadWindow } from "@quilted/threads";
|
|
3
|
-
import { createElement } from "react";
|
|
4
|
-
import { createRoot } from "react-dom/client";
|
|
5
|
-
import { defineElements } from "./elements";
|
|
6
|
-
import { RbContext } from "./sdk";
|
|
7
|
-
function connect(App) {
|
|
8
|
-
defineElements();
|
|
9
|
-
const host = ThreadWindow.parent.import({
|
|
10
|
-
targetOrigin: "*"
|
|
11
|
-
});
|
|
12
|
-
void host.connect().then(({ connection, action, notify }) => {
|
|
13
|
-
const rb = {
|
|
14
|
-
action: (id, payload) => Promise.resolve(action(id, payload)),
|
|
15
|
-
notify: (message, type) => notify(message, type)
|
|
16
|
-
};
|
|
17
|
-
const root = document.createElement("remote-root");
|
|
18
|
-
document.body.append(root);
|
|
19
|
-
const observer = new RemoteMutationObserver(connection);
|
|
20
|
-
observer.observe(root);
|
|
21
|
-
createRoot(root).render(
|
|
22
|
-
createElement(RbContext.Provider, { value: rb }, createElement(App))
|
|
23
|
-
);
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
|
-
export {
|
|
27
|
-
connect
|
|
28
|
-
};
|
|
29
|
-
//# sourceMappingURL=connect.js.map
|
package/dist/connect.js.map
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/connect.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Sandbox bootstrap \u2014 runs *inside* the plugin iframe.\n *\n * The sandbox initiates the handshake (the iframe is the side that knows when it\n * is ready): it imports the host's `connect()` and calls it. The host responds\n * with a `RemoteConnection` (its `receiver.connection`, ferried by\n * @quilted/threads) plus the host SDK. We then render the plugin's React tree\n * into a detached root and let `RemoteMutationObserver` stream every DOM\n * mutation to the host, where the real rb-components live.\n *\n * The child-initiates-handshake pattern is required because @quilted/threads\n * does not buffer a call made before the other side is listening; the host has\n * been listening since it mounted the iframe, so a call *from* the sandbox is\n * always delivered.\n *\n * Verified against @remote-dom/core@1.11.x + @quilted/threads@4.x.\n */\nimport { RemoteMutationObserver } from \"@remote-dom/core/elements\";\nimport type { RemoteConnection } from \"@remote-dom/core\";\nimport { ThreadWindow } from \"@quilted/threads\";\nimport { createElement, type ComponentType } from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { defineElements } from \"./elements\";\nimport { RbContext, type RbSdk } from \"./sdk\";\n\n/** What the host exposes to the sandbox. */\ninterface HostExports {\n connect: () => Promise<{\n connection: RemoteConnection;\n action: (id: string, payload?: unknown) => Promise<unknown> | unknown;\n notify: (message: string, type?: string) => void;\n }>;\n}\n\n/**\n * Mount a plugin. Call this once from the sandbox entry (sandbox.html), passing\n * the plugin's root component.\n *\n * @example\n * import { connect } from \"@rainbow-robotics/plugin-ui/connect\";\n * import App from \"./content\";\n * connect(App);\n */\nexport function connect(App: ComponentType): void {\n defineElements();\n\n const host = ThreadWindow.parent.import<HostExports>({\n targetOrigin: \"*\",\n });\n\n void host.connect().then(({ connection, action, notify }) => {\n const rb: RbSdk = {\n action: (id, payload) => Promise.resolve(action(id, payload)),\n notify: (message, type) => notify(message, type as string | undefined),\n };\n\n const root = document.createElement(\"remote-root\");\n\n document.body.append(root);\n\n const observer = new RemoteMutationObserver(connection);\n observer.observe(root);\n\n createRoot(root).render(\n createElement(RbContext.Provider, { value: rb }, createElement(App)),\n );\n });\n}\n"],
|
|
5
|
-
"mappings": "AAiBA,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B,SAAS,qBAAyC;AAClD,SAAS,kBAAkB;AAC3B,SAAS,sBAAsB;AAC/B,SAAS,iBAA6B;AAoB/B,SAAS,QAAQ,KAA0B;AAChD,iBAAe;AAEf,QAAM,OAAO,aAAa,OAAO,OAAoB;AAAA,IACnD,cAAc;AAAA,EAChB,CAAC;AAED,OAAK,KAAK,QAAQ,EAAE,KAAK,CAAC,EAAE,YAAY,QAAQ,OAAO,MAAM;AAC3D,UAAM,KAAY;AAAA,MAChB,QAAQ,CAAC,IAAI,YAAY,QAAQ,QAAQ,OAAO,IAAI,OAAO,CAAC;AAAA,MAC5D,QAAQ,CAAC,SAAS,SAAS,OAAO,SAAS,IAA0B;AAAA,IACvE;AAEA,UAAM,OAAO,SAAS,cAAc,aAAa;AAEjD,aAAS,KAAK,OAAO,IAAI;AAEzB,UAAM,WAAW,IAAI,uBAAuB,UAAU;AACtD,aAAS,QAAQ,IAAI;AAErB,eAAW,IAAI,EAAE;AAAA,MACf,cAAc,UAAU,UAAU,EAAE,OAAO,GAAG,GAAG,cAAc,GAAG,CAAC;AAAA,IACrE;AAAA,EACF,CAAC;AACH;",
|
|
6
|
-
"names": []
|
|
7
|
-
}
|