@nullplatform/ui-plugin-sdk 0.2.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/README.md +38 -0
- package/dist/bridge.d.ts +40 -0
- package/dist/bridge.js +84 -0
- package/dist/catalog.d.ts +26 -0
- package/dist/catalog.js +113 -0
- package/dist/components.d.ts +149 -0
- package/dist/components.js +57 -0
- package/dist/context.d.ts +47 -0
- package/dist/context.js +47 -0
- package/dist/contract/allowlist.d.ts +16 -0
- package/dist/contract/allowlist.js +70 -0
- package/dist/contract/index.d.ts +4 -0
- package/dist/contract/index.js +4 -0
- package/dist/contract/manifest.d.ts +46 -0
- package/dist/contract/manifest.js +108 -0
- package/dist/contract/storage.d.ts +4 -0
- package/dist/contract/storage.js +19 -0
- package/dist/contract/when.d.ts +19 -0
- package/dist/contract/when.js +104 -0
- package/dist/contract-cjs/allowlist.js +76 -0
- package/dist/contract-cjs/index.js +24 -0
- package/dist/contract-cjs/manifest.js +114 -0
- package/dist/contract-cjs/package.json +1 -0
- package/dist/contract-cjs/storage.js +24 -0
- package/dist/contract-cjs/when.js +115 -0
- package/dist/defineUI.d.ts +15 -0
- package/dist/defineUI.js +18 -0
- package/dist/elements.d.ts +10 -0
- package/dist/elements.js +39 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +6 -0
- package/dist/polyfill.d.ts +6 -0
- package/dist/polyfill.js +6 -0
- package/dist/protocol.d.ts +170 -0
- package/dist/protocol.js +112 -0
- package/dist/worker.d.ts +17 -0
- package/dist/worker.js +135 -0
- package/package.json +61 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.WhenError = exports.CONTEXT_ROOTS = void 0;
|
|
7
|
+
exports.extractRoots = extractRoots;
|
|
8
|
+
exports.validateWhen = validateWhen;
|
|
9
|
+
exports.evaluateWhen = evaluateWhen;
|
|
10
|
+
exports.rolloutIncludes = rolloutIncludes;
|
|
11
|
+
/**
|
|
12
|
+
* `when` conditions: a Mongo-style query (evaluated with `sift`) over a context
|
|
13
|
+
* document whose top-level keys are the roots below. The same evaluator runs in
|
|
14
|
+
* the API (installations and manifests) and in the host (developer mode).
|
|
15
|
+
*/
|
|
16
|
+
const sift_1 = __importDefault(require("sift"));
|
|
17
|
+
/** Roots a condition may reference. The API knows how to load each one; anything else is rejected at write time. */
|
|
18
|
+
exports.CONTEXT_ROOTS = ['nrn', 'organization', 'account', 'namespace', 'application', 'scope', 'deployment', 'user'];
|
|
19
|
+
/** Operators that would execute code or are meaningless outside MongoDB. */
|
|
20
|
+
const FORBIDDEN_OPERATORS = new Set(['$where', '$function', '$expr', '$jsonSchema', '$text', '$accumulator']);
|
|
21
|
+
/** Logical operators whose operands are themselves queries against the same document. */
|
|
22
|
+
const LOGICAL_LIST_OPERATORS = new Set(['$and', '$or', '$nor']);
|
|
23
|
+
class WhenError extends Error {
|
|
24
|
+
constructor(message) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.name = 'WhenError';
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
exports.WhenError = WhenError;
|
|
30
|
+
const isPlainObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
|
|
31
|
+
const rootOf = (field) => field.split('.')[0];
|
|
32
|
+
/** Top-level roots referenced by a query (walks `$and` / `$or` / `$nor`; field operands are never roots). */
|
|
33
|
+
function extractRoots(when) {
|
|
34
|
+
const roots = new Set();
|
|
35
|
+
const walk = (query) => {
|
|
36
|
+
if (!isPlainObject(query))
|
|
37
|
+
return;
|
|
38
|
+
for (const [key, value] of Object.entries(query)) {
|
|
39
|
+
if (key.startsWith('$')) {
|
|
40
|
+
if (LOGICAL_LIST_OPERATORS.has(key) && Array.isArray(value))
|
|
41
|
+
value.forEach(walk);
|
|
42
|
+
else if (key === '$not')
|
|
43
|
+
walk(value);
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
roots.add(rootOf(key));
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
walk(when);
|
|
50
|
+
return [...roots];
|
|
51
|
+
}
|
|
52
|
+
/** Deep check for forbidden operators and non-JSON values (functions, symbols). */
|
|
53
|
+
function assertSafe(value, path) {
|
|
54
|
+
if (typeof value === 'function' || typeof value === 'symbol')
|
|
55
|
+
throw new WhenError(`${path || 'when'} must be plain JSON`);
|
|
56
|
+
if (Array.isArray(value)) {
|
|
57
|
+
value.forEach((item, index) => assertSafe(item, `${path}[${index}]`));
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (!isPlainObject(value))
|
|
61
|
+
return;
|
|
62
|
+
for (const [key, item] of Object.entries(value)) {
|
|
63
|
+
if (FORBIDDEN_OPERATORS.has(key))
|
|
64
|
+
throw new WhenError(`Operator ${key} is not allowed`);
|
|
65
|
+
assertSafe(item, path ? `${path}.${key}` : key);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** Validates an untrusted condition: plain object, JSON only, no code operators, known roots. Returns it unchanged. */
|
|
69
|
+
function validateWhen(input) {
|
|
70
|
+
if (!isPlainObject(input))
|
|
71
|
+
throw new WhenError('when must be an object');
|
|
72
|
+
assertSafe(input, '');
|
|
73
|
+
for (const root of extractRoots(input)) {
|
|
74
|
+
if (!exports.CONTEXT_ROOTS.includes(root)) {
|
|
75
|
+
throw new WhenError(`Unknown context root "${root}" (allowed: ${exports.CONTEXT_ROOTS.join(', ')})`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return input;
|
|
79
|
+
}
|
|
80
|
+
/** True when the query matches the context. An empty or missing query always matches; an invalid one never does. */
|
|
81
|
+
function evaluateWhen(when, context) {
|
|
82
|
+
if (!when || Object.keys(when).length === 0)
|
|
83
|
+
return true;
|
|
84
|
+
try {
|
|
85
|
+
return (0, sift_1.default)(when)(context ?? {});
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** FNV-1a 32-bit: stable across runtimes, good enough to bucket users. */
|
|
92
|
+
function fnv1a(input) {
|
|
93
|
+
let hash = 0x811c9dc5;
|
|
94
|
+
for (let i = 0; i < input.length; i++) {
|
|
95
|
+
hash ^= input.charCodeAt(i);
|
|
96
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
97
|
+
}
|
|
98
|
+
return hash >>> 0;
|
|
99
|
+
}
|
|
100
|
+
/** Deterministic per (user, package): the same user always lands in the same bucket for a package. */
|
|
101
|
+
function rolloutIncludes(rollout, userId, packageSlug) {
|
|
102
|
+
const raw = rollout?.percentage;
|
|
103
|
+
if (raw === undefined || raw === null)
|
|
104
|
+
return true;
|
|
105
|
+
const percentage = Math.max(0, Math.min(100, Number(raw)));
|
|
106
|
+
if (Number.isNaN(percentage))
|
|
107
|
+
return true;
|
|
108
|
+
if (percentage >= 100)
|
|
109
|
+
return true;
|
|
110
|
+
if (percentage <= 0)
|
|
111
|
+
return false;
|
|
112
|
+
if (userId === undefined || userId === null || userId === '')
|
|
113
|
+
return false;
|
|
114
|
+
return fnv1a(`${userId}:${packageSlug}`) % 100 < percentage;
|
|
115
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ComponentType } from 'react';
|
|
2
|
+
import type { WidgetProps } from './context.js';
|
|
3
|
+
export interface DefineUIOptions {
|
|
4
|
+
/** Widget id → component. Ids must match the manifest `contributes[].widget`. */
|
|
5
|
+
widgets: Record<string, ComponentType<WidgetProps>>;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Entry point of a UI plugin. Registers the widgets and starts listening for
|
|
9
|
+
* the sandbox handshake. Call it once at the top level of your bundle.
|
|
10
|
+
*
|
|
11
|
+
* Tooling (`describe`, the publish script) evaluates the bundle outside a
|
|
12
|
+
* sandbox with `globalThis.__npPluginDescribe` set, to learn which widgets the
|
|
13
|
+
* bundle defines without running any widget.
|
|
14
|
+
*/
|
|
15
|
+
export declare function defineUI(options: DefineUIOptions): void;
|
package/dist/defineUI.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { listenForSandbox, register } from './worker.js';
|
|
2
|
+
/**
|
|
3
|
+
* Entry point of a UI plugin. Registers the widgets and starts listening for
|
|
4
|
+
* the sandbox handshake. Call it once at the top level of your bundle.
|
|
5
|
+
*
|
|
6
|
+
* Tooling (`describe`, the publish script) evaluates the bundle outside a
|
|
7
|
+
* sandbox with `globalThis.__npPluginDescribe` set, to learn which widgets the
|
|
8
|
+
* bundle defines without running any widget.
|
|
9
|
+
*/
|
|
10
|
+
export function defineUI(options) {
|
|
11
|
+
register({ widgets: options.widgets });
|
|
12
|
+
const describe = globalThis.__npPluginDescribe;
|
|
13
|
+
if (typeof describe === 'function') {
|
|
14
|
+
describe({ widgets: Object.keys(options.widgets) });
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
listenForSandbox();
|
|
18
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import "./polyfill.js";
|
|
2
|
+
/**
|
|
3
|
+
* Worker-side custom elements for the catalog, built with remote-dom.
|
|
4
|
+
* Must run after the DOM polyfill is installed (see `worker.ts`).
|
|
5
|
+
*/
|
|
6
|
+
import '@remote-dom/core/polyfill';
|
|
7
|
+
import type { RemoteElementConstructor } from '@remote-dom/core/elements';
|
|
8
|
+
export declare const ROOT_TAG = "remote-root";
|
|
9
|
+
/** Defines every catalog element (idempotent). */
|
|
10
|
+
export declare function defineCatalogElements(): Map<string, RemoteElementConstructor<any, any, any, any>>;
|
package/dist/elements.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import "./polyfill.js";
|
|
2
|
+
/**
|
|
3
|
+
* Worker-side custom elements for the catalog, built with remote-dom.
|
|
4
|
+
* Must run after the DOM polyfill is installed (see `worker.ts`).
|
|
5
|
+
*/
|
|
6
|
+
import '@remote-dom/core/polyfill';
|
|
7
|
+
import { createRemoteElement, RemoteRootElement, RemoteFragmentElement } from '@remote-dom/core/elements';
|
|
8
|
+
import { CATALOG, FRAGMENT_TAG } from './catalog.js';
|
|
9
|
+
export const ROOT_TAG = 'remote-root';
|
|
10
|
+
const registry = new Map();
|
|
11
|
+
function defineElement(spec) {
|
|
12
|
+
const properties = {};
|
|
13
|
+
for (const [name, type] of Object.entries(spec.properties)) {
|
|
14
|
+
const ctor = type === 'number' ? Number : type === 'boolean' ? Boolean : type === 'string' ? String : Object;
|
|
15
|
+
properties[name] = { type: ctor, attribute: false };
|
|
16
|
+
}
|
|
17
|
+
const events = {};
|
|
18
|
+
for (const event of Object.keys(spec.events))
|
|
19
|
+
events[event] = {};
|
|
20
|
+
const slots = {};
|
|
21
|
+
for (const slot of spec.slots ?? [])
|
|
22
|
+
slots[slot] = {};
|
|
23
|
+
const Element = createRemoteElement({ properties, events, slots });
|
|
24
|
+
if (!customElements.get(spec.tag))
|
|
25
|
+
customElements.define(spec.tag, Element);
|
|
26
|
+
return Element;
|
|
27
|
+
}
|
|
28
|
+
/** Defines every catalog element (idempotent). */
|
|
29
|
+
export function defineCatalogElements() {
|
|
30
|
+
if (registry.size)
|
|
31
|
+
return registry;
|
|
32
|
+
if (!customElements.get(ROOT_TAG))
|
|
33
|
+
customElements.define(ROOT_TAG, RemoteRootElement);
|
|
34
|
+
if (!customElements.get(FRAGMENT_TAG))
|
|
35
|
+
customElements.define(FRAGMENT_TAG, RemoteFragmentElement);
|
|
36
|
+
for (const spec of CATALOG)
|
|
37
|
+
registry.set(spec.tag, defineElement(spec));
|
|
38
|
+
return registry;
|
|
39
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import "./polyfill.js";
|
|
2
|
+
export { defineUI, type DefineUIOptions } from './defineUI.js';
|
|
3
|
+
export { usePluginContext, useNullplatform, useQuery, type WidgetProps, type QueryState } from './context.js';
|
|
4
|
+
export { nullplatform, type NullplatformBridge } from './bridge.js';
|
|
5
|
+
export * from './components.js';
|
|
6
|
+
export type { PluginContext, ApiRequest, HttpRequest, HttpResponse, NavigationTarget, SnackbarOptions } from './protocol.js';
|
|
7
|
+
export { BridgeError } from './protocol.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import "./polyfill.js";
|
|
2
|
+
export { defineUI } from './defineUI.js';
|
|
3
|
+
export { usePluginContext, useNullplatform, useQuery } from './context.js';
|
|
4
|
+
export { nullplatform } from './bridge.js';
|
|
5
|
+
export * from './components.js';
|
|
6
|
+
export { BridgeError } from './protocol.js';
|
package/dist/polyfill.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire protocol between the host page and a plugin worker.
|
|
3
|
+
*
|
|
4
|
+
* Everything that crosses the MessagePort must be structured-cloneable.
|
|
5
|
+
* Functions (event handlers rendered by the plugin) are replaced by
|
|
6
|
+
* `{ $fn: id }` tokens on the worker side and turned back into proxies on the
|
|
7
|
+
* host side; the host invokes them with a `fn` message.
|
|
8
|
+
*/
|
|
9
|
+
export declare const PROTOCOL_VERSION = 1;
|
|
10
|
+
export type FunctionToken = {
|
|
11
|
+
$fn: string;
|
|
12
|
+
};
|
|
13
|
+
export interface PluginContext {
|
|
14
|
+
organization?: {
|
|
15
|
+
id: number | string;
|
|
16
|
+
slug?: string;
|
|
17
|
+
name?: string;
|
|
18
|
+
};
|
|
19
|
+
account?: {
|
|
20
|
+
id: number | string;
|
|
21
|
+
slug?: string;
|
|
22
|
+
name?: string;
|
|
23
|
+
};
|
|
24
|
+
namespace?: {
|
|
25
|
+
id: number | string;
|
|
26
|
+
slug?: string;
|
|
27
|
+
name?: string;
|
|
28
|
+
};
|
|
29
|
+
application?: {
|
|
30
|
+
id: number | string;
|
|
31
|
+
slug?: string;
|
|
32
|
+
name?: string;
|
|
33
|
+
};
|
|
34
|
+
nrn?: string;
|
|
35
|
+
user?: {
|
|
36
|
+
id: number | string;
|
|
37
|
+
email?: string;
|
|
38
|
+
};
|
|
39
|
+
locale?: string;
|
|
40
|
+
route?: {
|
|
41
|
+
path: string;
|
|
42
|
+
params: Record<string, string>;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export interface ApiRequest {
|
|
46
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
47
|
+
path: string;
|
|
48
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
49
|
+
body?: unknown;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* A request to an external https host declared in `permissions.http`. The host executes it
|
|
53
|
+
* with a platform-signed plugin call token; the plugin never holds any credential.
|
|
54
|
+
*/
|
|
55
|
+
export interface HttpRequest {
|
|
56
|
+
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
57
|
+
url: string;
|
|
58
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
59
|
+
body?: unknown;
|
|
60
|
+
/** Extra request headers; `authorization`, `cookie` and `host` are always stripped by the host. */
|
|
61
|
+
headers?: Record<string, string>;
|
|
62
|
+
}
|
|
63
|
+
export interface HttpResponse {
|
|
64
|
+
status: number;
|
|
65
|
+
headers: Record<string, string>;
|
|
66
|
+
/** Parsed JSON when the response is JSON, text otherwise. */
|
|
67
|
+
body: unknown;
|
|
68
|
+
}
|
|
69
|
+
export interface NavigationTarget {
|
|
70
|
+
/** Logical route name resolved by the host (e.g. `application`, `scope`, `deployment`). */
|
|
71
|
+
to: string;
|
|
72
|
+
params?: Record<string, string | number>;
|
|
73
|
+
}
|
|
74
|
+
export interface SnackbarOptions {
|
|
75
|
+
title: string;
|
|
76
|
+
variant?: 'default' | 'success' | 'error' | 'warning' | 'info';
|
|
77
|
+
}
|
|
78
|
+
/** Methods a plugin can call on the host. */
|
|
79
|
+
export interface BridgeMethods {
|
|
80
|
+
'assets.url': (path: string) => Promise<string>;
|
|
81
|
+
'api.request': (request: ApiRequest) => Promise<unknown>;
|
|
82
|
+
'http.request': (request: HttpRequest) => Promise<HttpResponse>;
|
|
83
|
+
'navigation.push': (target: NavigationTarget) => Promise<void>;
|
|
84
|
+
'ui.snackbar': (options: SnackbarOptions) => Promise<void>;
|
|
85
|
+
'context.get': () => Promise<PluginContext>;
|
|
86
|
+
}
|
|
87
|
+
export type BridgeMethodName = keyof BridgeMethods;
|
|
88
|
+
export type WorkerMessage = {
|
|
89
|
+
type: 'ready';
|
|
90
|
+
protocol: number;
|
|
91
|
+
pluginId: string;
|
|
92
|
+
widgets: string[];
|
|
93
|
+
} | {
|
|
94
|
+
type: 'mutate';
|
|
95
|
+
mountId: string;
|
|
96
|
+
records: unknown[];
|
|
97
|
+
} | {
|
|
98
|
+
type: 'call';
|
|
99
|
+
id: string;
|
|
100
|
+
method: BridgeMethodName;
|
|
101
|
+
args: unknown[];
|
|
102
|
+
} | {
|
|
103
|
+
type: 'fn-result';
|
|
104
|
+
id: string;
|
|
105
|
+
ok: boolean;
|
|
106
|
+
value?: unknown;
|
|
107
|
+
error?: SerializedError;
|
|
108
|
+
} | {
|
|
109
|
+
type: 'log';
|
|
110
|
+
level: 'debug' | 'info' | 'warn' | 'error';
|
|
111
|
+
args: unknown[];
|
|
112
|
+
} | {
|
|
113
|
+
type: 'error';
|
|
114
|
+
mountId?: string;
|
|
115
|
+
error: SerializedError;
|
|
116
|
+
};
|
|
117
|
+
export type HostMessage = {
|
|
118
|
+
type: 'init';
|
|
119
|
+
pluginId: string;
|
|
120
|
+
context: PluginContext;
|
|
121
|
+
} | {
|
|
122
|
+
type: 'mount';
|
|
123
|
+
mountId: string;
|
|
124
|
+
slot: string;
|
|
125
|
+
widgetId: string;
|
|
126
|
+
context: PluginContext;
|
|
127
|
+
config?: unknown;
|
|
128
|
+
} | {
|
|
129
|
+
type: 'unmount';
|
|
130
|
+
mountId: string;
|
|
131
|
+
} | {
|
|
132
|
+
type: 'context';
|
|
133
|
+
context: PluginContext;
|
|
134
|
+
} | {
|
|
135
|
+
type: 'fn';
|
|
136
|
+
id: string;
|
|
137
|
+
fnId: string;
|
|
138
|
+
args: unknown[];
|
|
139
|
+
} | {
|
|
140
|
+
type: 'result';
|
|
141
|
+
id: string;
|
|
142
|
+
ok: boolean;
|
|
143
|
+
value?: unknown;
|
|
144
|
+
error?: SerializedError;
|
|
145
|
+
};
|
|
146
|
+
export interface SerializedError {
|
|
147
|
+
message: string;
|
|
148
|
+
code?: string;
|
|
149
|
+
stack?: string;
|
|
150
|
+
}
|
|
151
|
+
export declare class BridgeError extends Error {
|
|
152
|
+
code: string;
|
|
153
|
+
constructor(message: string, code?: string);
|
|
154
|
+
}
|
|
155
|
+
export declare function serializeError(error: unknown): SerializedError;
|
|
156
|
+
export declare function deserializeError(error: SerializedError): BridgeError;
|
|
157
|
+
export declare function isFunctionToken(value: unknown): value is FunctionToken;
|
|
158
|
+
/**
|
|
159
|
+
* Deeply replaces functions with tokens. Returns the cloneable value and the
|
|
160
|
+
* functions that were extracted, keyed by their token id.
|
|
161
|
+
*/
|
|
162
|
+
export declare function serializeFunctions(value: unknown, nextId: () => string, registry: Map<string, (...args: unknown[]) => unknown>): unknown;
|
|
163
|
+
/** Deeply replaces function tokens with functions produced by `resolve`. */
|
|
164
|
+
export declare function deserializeFunctions(value: unknown, resolve: (id: string) => (...args: unknown[]) => unknown): unknown;
|
|
165
|
+
/**
|
|
166
|
+
* Makes a value safe to post: drops functions, DOM nodes, cycles and events,
|
|
167
|
+
* keeping plain data. Used for event handler arguments flowing host → worker.
|
|
168
|
+
*/
|
|
169
|
+
export declare function toCloneable(value: unknown, seen?: WeakSet<object>): unknown;
|
|
170
|
+
export declare function createIdGenerator(prefix: string): () => string;
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire protocol between the host page and a plugin worker.
|
|
3
|
+
*
|
|
4
|
+
* Everything that crosses the MessagePort must be structured-cloneable.
|
|
5
|
+
* Functions (event handlers rendered by the plugin) are replaced by
|
|
6
|
+
* `{ $fn: id }` tokens on the worker side and turned back into proxies on the
|
|
7
|
+
* host side; the host invokes them with a `fn` message.
|
|
8
|
+
*/
|
|
9
|
+
export const PROTOCOL_VERSION = 1;
|
|
10
|
+
export class BridgeError extends Error {
|
|
11
|
+
code;
|
|
12
|
+
constructor(message, code = 'BRIDGE_ERROR') {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = 'BridgeError';
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function serializeError(error) {
|
|
19
|
+
if (error instanceof BridgeError)
|
|
20
|
+
return { message: error.message, code: error.code, stack: error.stack };
|
|
21
|
+
if (error instanceof Error) {
|
|
22
|
+
const code = error.code;
|
|
23
|
+
return { message: error.message, code: typeof code === 'string' ? code : undefined, stack: error.stack };
|
|
24
|
+
}
|
|
25
|
+
return { message: String(error) };
|
|
26
|
+
}
|
|
27
|
+
export function deserializeError(error) {
|
|
28
|
+
const bridgeError = new BridgeError(error.message, error.code);
|
|
29
|
+
if (error.stack)
|
|
30
|
+
bridgeError.stack = error.stack;
|
|
31
|
+
return bridgeError;
|
|
32
|
+
}
|
|
33
|
+
// ---- function tokens -----------------------------------------------------
|
|
34
|
+
export function isFunctionToken(value) {
|
|
35
|
+
return typeof value === 'object' && value !== null && typeof value.$fn === 'string';
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Deeply replaces functions with tokens. Returns the cloneable value and the
|
|
39
|
+
* functions that were extracted, keyed by their token id.
|
|
40
|
+
*/
|
|
41
|
+
export function serializeFunctions(value, nextId, registry) {
|
|
42
|
+
if (typeof value === 'function') {
|
|
43
|
+
const id = nextId();
|
|
44
|
+
registry.set(id, value);
|
|
45
|
+
return { $fn: id };
|
|
46
|
+
}
|
|
47
|
+
if (Array.isArray(value))
|
|
48
|
+
return value.map((item) => serializeFunctions(item, nextId, registry));
|
|
49
|
+
if (value && typeof value === 'object') {
|
|
50
|
+
const out = {};
|
|
51
|
+
for (const [key, item] of Object.entries(value)) {
|
|
52
|
+
out[key] = serializeFunctions(item, nextId, registry);
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
return value;
|
|
57
|
+
}
|
|
58
|
+
/** Deeply replaces function tokens with functions produced by `resolve`. */
|
|
59
|
+
export function deserializeFunctions(value, resolve) {
|
|
60
|
+
if (isFunctionToken(value))
|
|
61
|
+
return resolve(value.$fn);
|
|
62
|
+
if (Array.isArray(value))
|
|
63
|
+
return value.map((item) => deserializeFunctions(item, resolve));
|
|
64
|
+
if (value && typeof value === 'object') {
|
|
65
|
+
const out = {};
|
|
66
|
+
for (const [key, item] of Object.entries(value)) {
|
|
67
|
+
out[key] = deserializeFunctions(item, resolve);
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Makes a value safe to post: drops functions, DOM nodes, cycles and events,
|
|
75
|
+
* keeping plain data. Used for event handler arguments flowing host → worker.
|
|
76
|
+
*/
|
|
77
|
+
export function toCloneable(value, seen = new WeakSet()) {
|
|
78
|
+
if (value === null || value === undefined)
|
|
79
|
+
return value;
|
|
80
|
+
const type = typeof value;
|
|
81
|
+
if (type === 'string' || type === 'number' || type === 'boolean')
|
|
82
|
+
return value;
|
|
83
|
+
if (type === 'function' || type === 'symbol' || type === 'bigint')
|
|
84
|
+
return undefined;
|
|
85
|
+
if (value instanceof Date)
|
|
86
|
+
return value.toISOString();
|
|
87
|
+
if (typeof Event !== 'undefined' && value instanceof Event) {
|
|
88
|
+
const detail = value.detail;
|
|
89
|
+
return { type: value.type, detail: toCloneable(detail, seen) };
|
|
90
|
+
}
|
|
91
|
+
if (typeof Node !== 'undefined' && value instanceof Node)
|
|
92
|
+
return undefined;
|
|
93
|
+
if (Array.isArray(value))
|
|
94
|
+
return value.map((item) => toCloneable(item, seen));
|
|
95
|
+
if (type === 'object') {
|
|
96
|
+
if (seen.has(value))
|
|
97
|
+
return undefined;
|
|
98
|
+
seen.add(value);
|
|
99
|
+
const out = {};
|
|
100
|
+
for (const [key, item] of Object.entries(value)) {
|
|
101
|
+
const cloned = toCloneable(item, seen);
|
|
102
|
+
if (cloned !== undefined)
|
|
103
|
+
out[key] = cloned;
|
|
104
|
+
}
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
let counter = 0;
|
|
110
|
+
export function createIdGenerator(prefix) {
|
|
111
|
+
return () => `${prefix}-${++counter}`;
|
|
112
|
+
}
|
package/dist/worker.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import "./polyfill.js";
|
|
2
|
+
/**
|
|
3
|
+
* Worker-side runtime: receives the MessagePort from the sandbox bootstrap,
|
|
4
|
+
* mounts widgets into remote-dom roots and relays mutations to the host.
|
|
5
|
+
*/
|
|
6
|
+
import { type ComponentType } from 'react';
|
|
7
|
+
import { type WidgetProps } from './context.js';
|
|
8
|
+
import { type PluginContext } from './protocol.js';
|
|
9
|
+
export interface PluginDefinition {
|
|
10
|
+
widgets: Record<string, ComponentType<WidgetProps>>;
|
|
11
|
+
}
|
|
12
|
+
/** Connects this worker to the host through the port handed over by the sandbox. */
|
|
13
|
+
export declare function connect(port: MessagePort): void;
|
|
14
|
+
export declare function register(nextDefinition: PluginDefinition): void;
|
|
15
|
+
/** Installed once: the sandbox posts `{ type: 'connect' }` with the port. */
|
|
16
|
+
export declare function listenForSandbox(): void;
|
|
17
|
+
export declare function currentContext(): Promise<PluginContext>;
|
package/dist/worker.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import "./polyfill.js";
|
|
2
|
+
/**
|
|
3
|
+
* Worker-side runtime: receives the MessagePort from the sandbox bootstrap,
|
|
4
|
+
* mounts widgets into remote-dom roots and relays mutations to the host.
|
|
5
|
+
*/
|
|
6
|
+
import { createElement } from 'react';
|
|
7
|
+
import { createRoot } from 'react-dom/client';
|
|
8
|
+
import { BatchingRemoteConnection } from '@remote-dom/core/elements';
|
|
9
|
+
import { defineCatalogElements, ROOT_TAG } from './elements.js';
|
|
10
|
+
import { bridge } from './bridge.js';
|
|
11
|
+
import { PluginContextProvider, broadcastContext } from './context.js';
|
|
12
|
+
import { PROTOCOL_VERSION, createIdGenerator, serializeError, serializeFunctions, } from './protocol.js';
|
|
13
|
+
const functions = new Map();
|
|
14
|
+
const nextFunctionId = createIdGenerator('fn');
|
|
15
|
+
const mounts = new Map();
|
|
16
|
+
let definition = null;
|
|
17
|
+
let pluginId = 'unknown';
|
|
18
|
+
function createConnection(port, mountId) {
|
|
19
|
+
const raw = {
|
|
20
|
+
mutate(records) {
|
|
21
|
+
const cloneable = serializeFunctions(records, nextFunctionId, functions);
|
|
22
|
+
port.postMessage({ type: 'mutate', mountId, records: cloneable });
|
|
23
|
+
},
|
|
24
|
+
call() {
|
|
25
|
+
return undefined;
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
return new BatchingRemoteConnection(raw);
|
|
29
|
+
}
|
|
30
|
+
function mount(port, message) {
|
|
31
|
+
if (!definition)
|
|
32
|
+
throw new Error('defineUI() was not called before mount');
|
|
33
|
+
const Widget = definition.widgets[message.widgetId];
|
|
34
|
+
if (!Widget)
|
|
35
|
+
throw new Error(`Widget "${message.widgetId}" is not defined by this plugin`);
|
|
36
|
+
defineCatalogElements();
|
|
37
|
+
const element = document.createElement(ROOT_TAG);
|
|
38
|
+
document.body.append(element);
|
|
39
|
+
element.connect(createConnection(port, message.mountId));
|
|
40
|
+
const root = createRoot(element);
|
|
41
|
+
root.render(createElement(PluginContextProvider, { initial: message.context }, createElement(Widget, { slot: message.slot, config: message.config })));
|
|
42
|
+
mounts.set(message.mountId, { root, element });
|
|
43
|
+
}
|
|
44
|
+
function unmount(mountId) {
|
|
45
|
+
const current = mounts.get(mountId);
|
|
46
|
+
if (!current)
|
|
47
|
+
return;
|
|
48
|
+
current.root.unmount();
|
|
49
|
+
current.element.remove();
|
|
50
|
+
mounts.delete(mountId);
|
|
51
|
+
}
|
|
52
|
+
async function invokeFunction(port, message) {
|
|
53
|
+
const fn = functions.get(message.fnId);
|
|
54
|
+
if (!fn) {
|
|
55
|
+
port.postMessage({ type: 'fn-result', id: message.id, ok: false, error: { message: `Unknown function ${message.fnId}` } });
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const value = await fn(...message.args);
|
|
60
|
+
port.postMessage({ type: 'fn-result', id: message.id, ok: true, value: safeValue(value) });
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
port.postMessage({ type: 'fn-result', id: message.id, ok: false, error: serializeError(error) });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function safeValue(value) {
|
|
67
|
+
try {
|
|
68
|
+
structuredClone(value);
|
|
69
|
+
return value;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function handle(port, message) {
|
|
76
|
+
try {
|
|
77
|
+
switch (message.type) {
|
|
78
|
+
case 'init':
|
|
79
|
+
pluginId = message.pluginId;
|
|
80
|
+
broadcastContext(message.context);
|
|
81
|
+
break;
|
|
82
|
+
case 'mount':
|
|
83
|
+
mount(port, message);
|
|
84
|
+
break;
|
|
85
|
+
case 'unmount':
|
|
86
|
+
unmount(message.mountId);
|
|
87
|
+
break;
|
|
88
|
+
case 'context':
|
|
89
|
+
broadcastContext(message.context);
|
|
90
|
+
break;
|
|
91
|
+
case 'fn':
|
|
92
|
+
void invokeFunction(port, message);
|
|
93
|
+
break;
|
|
94
|
+
case 'result':
|
|
95
|
+
bridge.handleResult(message);
|
|
96
|
+
break;
|
|
97
|
+
default:
|
|
98
|
+
break;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
const mountId = 'mountId' in message ? message.mountId : undefined;
|
|
103
|
+
port.postMessage({ type: 'error', mountId, error: serializeError(error) });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Connects this worker to the host through the port handed over by the sandbox. */
|
|
107
|
+
export function connect(port) {
|
|
108
|
+
bridge.attach(port);
|
|
109
|
+
port.onmessage = (event) => handle(port, event.data);
|
|
110
|
+
port.start?.();
|
|
111
|
+
port.postMessage({
|
|
112
|
+
type: 'ready',
|
|
113
|
+
protocol: PROTOCOL_VERSION,
|
|
114
|
+
pluginId,
|
|
115
|
+
widgets: definition ? Object.keys(definition.widgets) : [],
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
export function register(nextDefinition) {
|
|
119
|
+
definition = nextDefinition;
|
|
120
|
+
}
|
|
121
|
+
/** Installed once: the sandbox posts `{ type: 'connect' }` with the port. */
|
|
122
|
+
export function listenForSandbox() {
|
|
123
|
+
const scope = globalThis;
|
|
124
|
+
if (scope.__npPluginListening || typeof scope.addEventListener !== 'function')
|
|
125
|
+
return;
|
|
126
|
+
scope.__npPluginListening = true;
|
|
127
|
+
scope.addEventListener('message', (event) => {
|
|
128
|
+
const data = event.data;
|
|
129
|
+
if (data?.type === 'connect' && event.ports[0])
|
|
130
|
+
connect(event.ports[0]);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
export function currentContext() {
|
|
134
|
+
return bridge.call('context.get');
|
|
135
|
+
}
|