@lightblues/jig 0.1.0 → 0.1.1
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 +1 -0
- package/dist/canvas/bridge.d.ts +110 -0
- package/dist/canvas/bridge.js +255 -0
- package/dist/canvas/build.d.ts +25 -0
- package/dist/canvas/build.js +54 -0
- package/dist/canvas/compile.d.ts +29 -0
- package/dist/canvas/compile.js +218 -0
- package/dist/canvas/context.d.ts +43 -0
- package/dist/canvas/context.js +79 -0
- package/dist/canvas/document.d.ts +50 -0
- package/dist/canvas/document.js +128 -0
- package/dist/canvas/frame.d.ts +65 -0
- package/dist/canvas/frame.js +197 -0
- package/dist/canvas/names.d.ts +1 -0
- package/dist/canvas/names.js +6 -0
- package/dist/canvas/protocol.d.ts +93 -0
- package/dist/canvas/protocol.js +152 -0
- package/dist/canvas/runtime.d.ts +25 -0
- package/dist/canvas/runtime.js +110 -0
- package/dist/canvas/server.d.ts +5 -0
- package/dist/canvas/server.js +8 -0
- package/dist/canvas/state.d.ts +31 -0
- package/dist/canvas/state.js +72 -0
- package/dist/canvas/store.d.ts +39 -0
- package/dist/canvas/store.js +82 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +30 -1
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// `@lightblues/jig/canvas/frame`: `<CanvasFrame>` for React DOM hosts. It owns the rules of v2 §4 that live in the
|
|
2
|
+
// host page, so a host cannot forget one: the sandbox, the CSP document, the `event.source` check, the rate limit,
|
|
3
|
+
// debounced state, actions only during a click, the height, the 5 s budget, lazy loading, at most 3 live frames, and
|
|
4
|
+
// the fallbacks to the source.
|
|
5
|
+
import { createElement as h, Fragment, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
|
6
|
+
import { HostBridge } from "./bridge.js";
|
|
7
|
+
import { CANVAS_SANDBOX, canvasDocument } from "./document.js";
|
|
8
|
+
export { CANVAS_SANDBOX, canvasDocument, canvasCsp } from "./document.js";
|
|
9
|
+
export { HostBridge, createPageBridge } from "./bridge.js";
|
|
10
|
+
export * from "./protocol.js";
|
|
11
|
+
/** How long the page has from mounting to its first `size` before the host shows "not responding". */
|
|
12
|
+
export const FIRST_SIZE_BUDGET_MS = 5_000;
|
|
13
|
+
/** Live frames per page by default. */
|
|
14
|
+
export const MAX_LIVE_FRAMES = 3;
|
|
15
|
+
const live = [];
|
|
16
|
+
function goLive(entry, max) {
|
|
17
|
+
const at = live.indexOf(entry);
|
|
18
|
+
if (at >= 0)
|
|
19
|
+
live.splice(at, 1);
|
|
20
|
+
live.push(entry);
|
|
21
|
+
while (live.length > Math.max(1, max))
|
|
22
|
+
live.shift().pause();
|
|
23
|
+
}
|
|
24
|
+
function leave(entry) {
|
|
25
|
+
const at = live.indexOf(entry);
|
|
26
|
+
if (at >= 0)
|
|
27
|
+
live.splice(at, 1);
|
|
28
|
+
}
|
|
29
|
+
/** Frames live now (for tests and host dashboards). */
|
|
30
|
+
export function liveFrameCount() {
|
|
31
|
+
return live.length;
|
|
32
|
+
}
|
|
33
|
+
function userActive() {
|
|
34
|
+
const ua = globalThis.navigator?.userActivation;
|
|
35
|
+
return ua?.isActive === true;
|
|
36
|
+
}
|
|
37
|
+
const box = { boxSizing: 'border-box', border: '1px solid rgba(127,127,127,.3)', borderRadius: 8, padding: 12, fontSize: 13, lineHeight: '18px' };
|
|
38
|
+
const pre = { margin: '8px 0 0', maxHeight: 360, overflow: 'auto', whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', font: '12px/17px ui-monospace,SFMono-Regular,Menlo,monospace' };
|
|
39
|
+
const button = { font: 'inherit', padding: '4px 10px', borderRadius: 6, border: '1px solid rgba(127,127,127,.45)', background: 'transparent', color: 'inherit', cursor: 'pointer' };
|
|
40
|
+
function SourceBox({ heading, detail, source, action }) {
|
|
41
|
+
return h('div', { role: 'status', 'data-jig-canvas-fallback': heading, style: box }, h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'space-between' } }, h('strong', null, heading), action ?? null), detail ? h('pre', { style: { ...pre, color: '#b42318' } }, detail) : null, source ? h('pre', { 'data-jig-canvas-source': '', style: pre }, h('code', null, source)) : null);
|
|
42
|
+
}
|
|
43
|
+
/** A model-written canvas in a sandboxed iframe. */
|
|
44
|
+
export function CanvasFrame(props) {
|
|
45
|
+
const { src, source, compileError, surface, profile, theme = 'light', load = 'visible' } = props;
|
|
46
|
+
const minHeight = props.minHeight ?? 120;
|
|
47
|
+
const maxHeight = props.maxHeight ?? 4_000;
|
|
48
|
+
const wrap = useRef(null);
|
|
49
|
+
const frame = useRef(null);
|
|
50
|
+
const [status, setStatus] = useState(load === 'eager' ? 'loading' : 'idle');
|
|
51
|
+
const [detail, setDetail] = useState('');
|
|
52
|
+
const [height, setHeight] = useState(minHeight);
|
|
53
|
+
const [showSource, setShowSource] = useState(false);
|
|
54
|
+
const [run, setRun] = useState(0);
|
|
55
|
+
const latest = useRef(props);
|
|
56
|
+
latest.current = props;
|
|
57
|
+
const report = (s, d = '') => {
|
|
58
|
+
setStatus(s);
|
|
59
|
+
setDetail(d);
|
|
60
|
+
latest.current.onStatus?.(s, d || undefined);
|
|
61
|
+
};
|
|
62
|
+
const entry = useMemo(() => ({ pause: () => report('paused') }), []);
|
|
63
|
+
const compileFailed = compileError != null || !src;
|
|
64
|
+
const running = !compileFailed && (status === 'loading' || status === 'live' || status === 'render-error');
|
|
65
|
+
// Lazy start: when scrolled into view, once.
|
|
66
|
+
useEffect(() => {
|
|
67
|
+
if (compileFailed || load !== 'visible' || status !== 'idle')
|
|
68
|
+
return;
|
|
69
|
+
const el = wrap.current;
|
|
70
|
+
if (!el || typeof IntersectionObserver === 'undefined')
|
|
71
|
+
return void report('loading');
|
|
72
|
+
const io = new IntersectionObserver((entries) => {
|
|
73
|
+
if (entries.some((e) => e.isIntersecting)) {
|
|
74
|
+
io.disconnect();
|
|
75
|
+
report('loading');
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
io.observe(el);
|
|
79
|
+
return () => io.disconnect();
|
|
80
|
+
}, [compileFailed, load, status]);
|
|
81
|
+
useEffect(() => {
|
|
82
|
+
if (!running)
|
|
83
|
+
return;
|
|
84
|
+
goLive(entry, props.maxLive ?? MAX_LIVE_FRAMES);
|
|
85
|
+
return () => leave(entry);
|
|
86
|
+
}, [running, entry]);
|
|
87
|
+
// The document is built once per run; state and theme changes after that go to the page as messages.
|
|
88
|
+
const doc = useMemo(() => {
|
|
89
|
+
if (compileFailed || typeof window === 'undefined')
|
|
90
|
+
return '';
|
|
91
|
+
const p = latest.current;
|
|
92
|
+
return canvasDocument(src, {
|
|
93
|
+
profile, surface, theme: p.theme ?? 'light', state: p.state ?? {}, title: p.title,
|
|
94
|
+
runtimeUrl: new URL(p.runtimeUrl, window.location.href).href, mediaOrigin: p.mediaOrigin, styleUrls: p.styleUrls, background: p.background,
|
|
95
|
+
});
|
|
96
|
+
}, [src, compileFailed, profile, surface, run]);
|
|
97
|
+
const bridge = useRef(null);
|
|
98
|
+
// A layout effect: the listener is in place in the same task as the commit, before the frame can run a script.
|
|
99
|
+
useLayoutEffect(() => {
|
|
100
|
+
if (!running || !doc)
|
|
101
|
+
return;
|
|
102
|
+
const el = frame.current;
|
|
103
|
+
if (!el)
|
|
104
|
+
return;
|
|
105
|
+
let sized = false;
|
|
106
|
+
let failed = false;
|
|
107
|
+
const p = latest.current;
|
|
108
|
+
const b = new HostBridge({
|
|
109
|
+
post: (m) => el.contentWindow?.postMessage(m, '*'),
|
|
110
|
+
state: p.state ?? {},
|
|
111
|
+
theme: p.theme ?? 'light',
|
|
112
|
+
debounceMs: p.debounceMs,
|
|
113
|
+
rate: p.rate,
|
|
114
|
+
eventRate: p.eventRate,
|
|
115
|
+
events: p.events,
|
|
116
|
+
userActive,
|
|
117
|
+
onState: (set) => latest.current.onState?.(set),
|
|
118
|
+
onEvent: (name, data) => latest.current.onEvent?.(name, data),
|
|
119
|
+
onAction: (action) => latest.current.onAction?.(action),
|
|
120
|
+
onSize: (hgt) => {
|
|
121
|
+
setHeight(Math.max(minHeight, Math.min(hgt, maxHeight)));
|
|
122
|
+
if (!sized) {
|
|
123
|
+
sized = true;
|
|
124
|
+
clearTimeout(budget);
|
|
125
|
+
if (!failed)
|
|
126
|
+
report('live');
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
onError: (message) => {
|
|
130
|
+
failed = true;
|
|
131
|
+
clearTimeout(budget);
|
|
132
|
+
report('render-error', message);
|
|
133
|
+
},
|
|
134
|
+
onNavigated: () => {
|
|
135
|
+
clearTimeout(budget);
|
|
136
|
+
report('navigated');
|
|
137
|
+
},
|
|
138
|
+
onReject: (reason, data) => latest.current.onReject?.(reason, data),
|
|
139
|
+
});
|
|
140
|
+
bridge.current = b;
|
|
141
|
+
const onMessage = (event) => {
|
|
142
|
+
// Only this frame's window. Another frame, a popup or the host's own scripts are ignored.
|
|
143
|
+
if (event.source === null || event.source !== el.contentWindow)
|
|
144
|
+
return;
|
|
145
|
+
b.receive(event.data);
|
|
146
|
+
};
|
|
147
|
+
window.addEventListener('message', onMessage);
|
|
148
|
+
const budget = setTimeout(() => {
|
|
149
|
+
if (!sized) {
|
|
150
|
+
b.dispose();
|
|
151
|
+
report('not-responding');
|
|
152
|
+
}
|
|
153
|
+
}, p.budgetMs ?? FIRST_SIZE_BUDGET_MS);
|
|
154
|
+
return () => {
|
|
155
|
+
clearTimeout(budget);
|
|
156
|
+
window.removeEventListener('message', onMessage);
|
|
157
|
+
b.dispose();
|
|
158
|
+
if (bridge.current === b)
|
|
159
|
+
bridge.current = null;
|
|
160
|
+
};
|
|
161
|
+
}, [running, doc]);
|
|
162
|
+
useEffect(() => bridge.current?.setState(props.state ?? {}), [props.state]);
|
|
163
|
+
useEffect(() => bridge.current?.setTheme(theme), [theme]);
|
|
164
|
+
useEffect(() => bridge.current?.update({ events: props.events }), [props.events]);
|
|
165
|
+
const title = props.title ?? 'canvas';
|
|
166
|
+
const restart = () => {
|
|
167
|
+
setRun((n) => n + 1);
|
|
168
|
+
setHeight(minHeight);
|
|
169
|
+
report('loading');
|
|
170
|
+
};
|
|
171
|
+
const toggle = h('button', { type: 'button', style: button, onClick: () => setShowSource((v) => !v) }, showSource ? 'Hide source' : 'Source');
|
|
172
|
+
let body;
|
|
173
|
+
if (compileFailed)
|
|
174
|
+
body = h(SourceBox, { heading: 'This page did not compile', detail: compileError, source });
|
|
175
|
+
else if (status === 'idle' || status === 'paused')
|
|
176
|
+
body = h(SourceBox, {
|
|
177
|
+
heading: status === 'paused' ? `${title} (paused)` : title,
|
|
178
|
+
action: h('button', { type: 'button', style: button, 'data-jig-canvas-run': '', onClick: restart }, 'Show'),
|
|
179
|
+
});
|
|
180
|
+
else if (status === 'not-responding')
|
|
181
|
+
body = h(SourceBox, { heading: 'Page not responding', source, action: h('button', { type: 'button', style: button, onClick: restart }, 'Retry') });
|
|
182
|
+
else if (status === 'navigated')
|
|
183
|
+
body = h(SourceBox, { heading: 'The page tried to leave; it was stopped', source });
|
|
184
|
+
else
|
|
185
|
+
body = h(Fragment, null, h('iframe', {
|
|
186
|
+
ref: frame,
|
|
187
|
+
srcDoc: doc,
|
|
188
|
+
sandbox: CANVAS_SANDBOX[profile],
|
|
189
|
+
referrerPolicy: 'no-referrer',
|
|
190
|
+
title,
|
|
191
|
+
'data-jig-canvas': surface,
|
|
192
|
+
style: { display: 'block', width: '100%', height, border: 0, colorScheme: 'normal' },
|
|
193
|
+
}), status === 'render-error' && source
|
|
194
|
+
? h('div', { style: { marginTop: 6 } }, toggle, showSource ? h('pre', { 'data-jig-canvas-source': '', style: pre }, h('code', null, source)) : null)
|
|
195
|
+
: null);
|
|
196
|
+
return h('div', { ref: wrap, className: props.className, style: props.style, 'data-jig-canvas-status': compileFailed ? 'compile-error' : status }, body);
|
|
197
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const RUNTIME_NAMES: readonly ["useCanvasState", "useCanvasEvent", "useCanvasAction", "useCanvasTheme", "useCanvasSurface", "useState", "useEffect", "useMemo", "useRef", "useCallback", "Fragment"];
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Names every canvas runtime adds to the kit (the protocol hooks and the React utilities Cursor's module has). Kept apart
|
|
2
|
+
// from `runtime.ts` so the server and the build script can read them without loading React.
|
|
3
|
+
export const RUNTIME_NAMES = [
|
|
4
|
+
'useCanvasState', 'useCanvasEvent', 'useCanvasAction', 'useCanvasTheme', 'useCanvasSurface',
|
|
5
|
+
'useState', 'useEffect', 'useMemo', 'useRef', 'useCallback', 'Fragment',
|
|
6
|
+
];
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/** `type` of every bridged message. */
|
|
2
|
+
export declare const FRAME_MESSAGE_TYPE = "jig-canvas";
|
|
3
|
+
/** Protocol version; a message with another `v` is dropped. */
|
|
4
|
+
export declare const FRAME_MESSAGE_VERSION = 1;
|
|
5
|
+
/** Limits (v2 §2). A message over a limit is dropped, never truncated. */
|
|
6
|
+
export declare const LIMITS: {
|
|
7
|
+
/** Longest state key. */
|
|
8
|
+
readonly key: 200;
|
|
9
|
+
/** A surface's whole state, as JSON characters. */
|
|
10
|
+
readonly state: 20000;
|
|
11
|
+
/** One event's `data`, as JSON characters. */
|
|
12
|
+
readonly eventData: 2000;
|
|
13
|
+
/** One action, as JSON characters. */
|
|
14
|
+
readonly action: 4000;
|
|
15
|
+
/** Distinct event names a tier-B surface may use. */
|
|
16
|
+
readonly eventNames: 20;
|
|
17
|
+
/** Tallest frame, in CSS pixels; a larger `size` is clamped. */
|
|
18
|
+
readonly height: 20000;
|
|
19
|
+
/** Deepest JSON nesting accepted in a value. */
|
|
20
|
+
readonly depth: 32;
|
|
21
|
+
/** Longest render-error message kept. */
|
|
22
|
+
readonly error: 2000;
|
|
23
|
+
};
|
|
24
|
+
export type ThemeKind = 'light' | 'dark';
|
|
25
|
+
export type JsonValue = null | boolean | number | string | JsonValue[] | {
|
|
26
|
+
[key: string]: JsonValue;
|
|
27
|
+
};
|
|
28
|
+
export type CanvasState = Record<string, unknown>;
|
|
29
|
+
/** What `useCanvasAction` dispatches. The host decides what each `type` does; anything else it ignores. */
|
|
30
|
+
export type CanvasAction = {
|
|
31
|
+
type: string;
|
|
32
|
+
[key: string]: unknown;
|
|
33
|
+
};
|
|
34
|
+
/** Page → host. `seq` numbers a page's state writes so a host replace can say which it has seen (`ack`). */
|
|
35
|
+
export type PageMessage = {
|
|
36
|
+
op: 'ready';
|
|
37
|
+
} | {
|
|
38
|
+
op: 'state';
|
|
39
|
+
key: string;
|
|
40
|
+
value: unknown;
|
|
41
|
+
seq: number;
|
|
42
|
+
} | {
|
|
43
|
+
op: 'event';
|
|
44
|
+
name: string;
|
|
45
|
+
data: unknown;
|
|
46
|
+
} | {
|
|
47
|
+
op: 'action';
|
|
48
|
+
action: CanvasAction;
|
|
49
|
+
} | {
|
|
50
|
+
op: 'size';
|
|
51
|
+
height: number;
|
|
52
|
+
} | {
|
|
53
|
+
op: 'error';
|
|
54
|
+
message: string;
|
|
55
|
+
}
|
|
56
|
+
/** From the relay: the page tried to load another document and was removed. */
|
|
57
|
+
| {
|
|
58
|
+
op: 'navigated';
|
|
59
|
+
};
|
|
60
|
+
/** Host → page. `state` and `init` replace the page's values; `ack` is the last page `seq` the host had seen. */
|
|
61
|
+
export type HostMessage = {
|
|
62
|
+
op: 'init';
|
|
63
|
+
state: CanvasState;
|
|
64
|
+
theme: ThemeKind;
|
|
65
|
+
ack: number;
|
|
66
|
+
} | {
|
|
67
|
+
op: 'state';
|
|
68
|
+
values: CanvasState;
|
|
69
|
+
ack: number;
|
|
70
|
+
} | {
|
|
71
|
+
op: 'theme';
|
|
72
|
+
kind: ThemeKind;
|
|
73
|
+
};
|
|
74
|
+
export declare const EVENT_NAME: RegExp;
|
|
75
|
+
/** Wrap a message for `postMessage`. */
|
|
76
|
+
export declare function frameMessage<T extends PageMessage | HostMessage>(message: T): T & {
|
|
77
|
+
type: typeof FRAME_MESSAGE_TYPE;
|
|
78
|
+
v: typeof FRAME_MESSAGE_VERSION;
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* Plain JSON within `depth`: objects with the plain prototype, arrays, strings, finite numbers, booleans, null.
|
|
82
|
+
* `postMessage` clones Maps, Dates, typed arrays and cycles; none of those is state.
|
|
83
|
+
*/
|
|
84
|
+
export declare function isJson(value: unknown, depth?: number): value is JsonValue;
|
|
85
|
+
/** JSON length of a value already checked by `isJson`. */
|
|
86
|
+
export declare function jsonSize(value: unknown): number;
|
|
87
|
+
/**
|
|
88
|
+
* A page → host message, validated, or null. Unknown ops, wrong types, oversized values, non-JSON values, keys over
|
|
89
|
+
* 200 chars and bad event or action names are all null. Checking `event.source` is the caller's job (`CanvasFrame`).
|
|
90
|
+
*/
|
|
91
|
+
export declare function parseFrameMessage(data: unknown): PageMessage | null;
|
|
92
|
+
/** A host → page message, validated, or null. The runtime also checks `event.source === window.parent`. */
|
|
93
|
+
export declare function parseHostMessage(data: unknown): HostMessage | null;
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// The canvas state protocol (J008, `.ea/docs/canvas.md`): one set of messages for tier A (in-page, provider callbacks)
|
|
2
|
+
// and tier B (sandboxed iframe, postMessage). This module is pure: no React, no DOM, no Node built-in, so the server,
|
|
3
|
+
// the host frame and the in-frame runtime all validate with the same code.
|
|
4
|
+
/** `type` of every bridged message. */
|
|
5
|
+
export const FRAME_MESSAGE_TYPE = 'jig-canvas';
|
|
6
|
+
/** Protocol version; a message with another `v` is dropped. */
|
|
7
|
+
export const FRAME_MESSAGE_VERSION = 1;
|
|
8
|
+
/** Limits (v2 §2). A message over a limit is dropped, never truncated. */
|
|
9
|
+
export const LIMITS = {
|
|
10
|
+
/** Longest state key. */
|
|
11
|
+
key: 200,
|
|
12
|
+
/** A surface's whole state, as JSON characters. */
|
|
13
|
+
state: 20_000,
|
|
14
|
+
/** One event's `data`, as JSON characters. */
|
|
15
|
+
eventData: 2_000,
|
|
16
|
+
/** One action, as JSON characters. */
|
|
17
|
+
action: 4_000,
|
|
18
|
+
/** Distinct event names a tier-B surface may use. */
|
|
19
|
+
eventNames: 20,
|
|
20
|
+
/** Tallest frame, in CSS pixels; a larger `size` is clamped. */
|
|
21
|
+
height: 20_000,
|
|
22
|
+
/** Deepest JSON nesting accepted in a value. */
|
|
23
|
+
depth: 32,
|
|
24
|
+
/** Longest render-error message kept. */
|
|
25
|
+
error: 2_000,
|
|
26
|
+
};
|
|
27
|
+
export const EVENT_NAME = /^[A-Za-z][\w.:-]{0,63}$/;
|
|
28
|
+
const ACTION_TYPE = /^[A-Za-z][\w.:-]{0,63}$/;
|
|
29
|
+
/** Wrap a message for `postMessage`. */
|
|
30
|
+
export function frameMessage(message) {
|
|
31
|
+
return { type: FRAME_MESSAGE_TYPE, v: FRAME_MESSAGE_VERSION, ...message };
|
|
32
|
+
}
|
|
33
|
+
function isPlainObject(value) {
|
|
34
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
35
|
+
return false;
|
|
36
|
+
const proto = Object.getPrototypeOf(value);
|
|
37
|
+
return proto === Object.prototype || proto === null;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Plain JSON within `depth`: objects with the plain prototype, arrays, strings, finite numbers, booleans, null.
|
|
41
|
+
* `postMessage` clones Maps, Dates, typed arrays and cycles; none of those is state.
|
|
42
|
+
*/
|
|
43
|
+
export function isJson(value, depth = LIMITS.depth) {
|
|
44
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean')
|
|
45
|
+
return true;
|
|
46
|
+
if (typeof value === 'number')
|
|
47
|
+
return Number.isFinite(value);
|
|
48
|
+
if (depth <= 0)
|
|
49
|
+
return false;
|
|
50
|
+
if (Array.isArray(value)) {
|
|
51
|
+
if (Object.getPrototypeOf(value) !== Array.prototype)
|
|
52
|
+
return false;
|
|
53
|
+
for (let i = 0; i < value.length; i++)
|
|
54
|
+
if (!(i in value) || !isJson(value[i], depth - 1))
|
|
55
|
+
return false;
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
if (!isPlainObject(value))
|
|
59
|
+
return false;
|
|
60
|
+
for (const key of Object.keys(value))
|
|
61
|
+
if (!isJson(value[key], depth - 1))
|
|
62
|
+
return false;
|
|
63
|
+
return Object.getOwnPropertySymbols(value).length === 0;
|
|
64
|
+
}
|
|
65
|
+
/** JSON length of a value already checked by `isJson`. */
|
|
66
|
+
export function jsonSize(value) {
|
|
67
|
+
return JSON.stringify(value)?.length ?? 0;
|
|
68
|
+
}
|
|
69
|
+
function envelope(data) {
|
|
70
|
+
if (!isPlainObject(data))
|
|
71
|
+
return null;
|
|
72
|
+
if (data.type !== FRAME_MESSAGE_TYPE || data.v !== FRAME_MESSAGE_VERSION || typeof data.op !== 'string')
|
|
73
|
+
return null;
|
|
74
|
+
return data;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* A page → host message, validated, or null. Unknown ops, wrong types, oversized values, non-JSON values, keys over
|
|
78
|
+
* 200 chars and bad event or action names are all null. Checking `event.source` is the caller's job (`CanvasFrame`).
|
|
79
|
+
*/
|
|
80
|
+
export function parseFrameMessage(data) {
|
|
81
|
+
const m = envelope(data);
|
|
82
|
+
if (!m)
|
|
83
|
+
return null;
|
|
84
|
+
switch (m.op) {
|
|
85
|
+
case 'ready':
|
|
86
|
+
return { op: 'ready' };
|
|
87
|
+
case 'navigated':
|
|
88
|
+
return { op: 'navigated' };
|
|
89
|
+
case 'state': {
|
|
90
|
+
const { key, value, seq } = m;
|
|
91
|
+
if (typeof key !== 'string' || !key || key.length > LIMITS.key)
|
|
92
|
+
return null;
|
|
93
|
+
if (!('value' in m) || !isJson(value) || jsonSize(value) > LIMITS.state)
|
|
94
|
+
return null;
|
|
95
|
+
if (typeof seq !== 'number' || !Number.isSafeInteger(seq) || seq < 1)
|
|
96
|
+
return null;
|
|
97
|
+
return { op: 'state', key, value, seq };
|
|
98
|
+
}
|
|
99
|
+
case 'event': {
|
|
100
|
+
const { name, data: payload = null } = m;
|
|
101
|
+
if (typeof name !== 'string' || !EVENT_NAME.test(name))
|
|
102
|
+
return null;
|
|
103
|
+
if (!isJson(payload) || jsonSize(payload) > LIMITS.eventData)
|
|
104
|
+
return null;
|
|
105
|
+
return { op: 'event', name, data: payload };
|
|
106
|
+
}
|
|
107
|
+
case 'action': {
|
|
108
|
+
const { action } = m;
|
|
109
|
+
if (!isPlainObject(action) || typeof action.type !== 'string' || !ACTION_TYPE.test(action.type))
|
|
110
|
+
return null;
|
|
111
|
+
if (!isJson(action) || jsonSize(action) > LIMITS.action)
|
|
112
|
+
return null;
|
|
113
|
+
return { op: 'action', action: action };
|
|
114
|
+
}
|
|
115
|
+
case 'size': {
|
|
116
|
+
const { height } = m;
|
|
117
|
+
if (typeof height !== 'number' || !Number.isFinite(height) || height < 0)
|
|
118
|
+
return null;
|
|
119
|
+
return { op: 'size', height: Math.min(Math.ceil(height), LIMITS.height) };
|
|
120
|
+
}
|
|
121
|
+
case 'error': {
|
|
122
|
+
const { message } = m;
|
|
123
|
+
if (typeof message !== 'string')
|
|
124
|
+
return null;
|
|
125
|
+
return { op: 'error', message: message.slice(0, LIMITS.error) };
|
|
126
|
+
}
|
|
127
|
+
default:
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
const isTheme = (v) => v === 'light' || v === 'dark';
|
|
132
|
+
const isAck = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
|
133
|
+
/** A host → page message, validated, or null. The runtime also checks `event.source === window.parent`. */
|
|
134
|
+
export function parseHostMessage(data) {
|
|
135
|
+
const m = envelope(data);
|
|
136
|
+
if (!m)
|
|
137
|
+
return null;
|
|
138
|
+
switch (m.op) {
|
|
139
|
+
case 'init':
|
|
140
|
+
if (!isPlainObject(m.state) || !isJson(m.state) || !isTheme(m.theme) || !isAck(m.ack))
|
|
141
|
+
return null;
|
|
142
|
+
return { op: 'init', state: m.state, theme: m.theme, ack: m.ack };
|
|
143
|
+
case 'state':
|
|
144
|
+
if (!isPlainObject(m.values) || !isJson(m.values) || !isAck(m.ack))
|
|
145
|
+
return null;
|
|
146
|
+
return { op: 'state', values: m.values, ack: m.ack };
|
|
147
|
+
case 'theme':
|
|
148
|
+
return isTheme(m.kind) ? { op: 'theme', kind: m.kind } : null;
|
|
149
|
+
default:
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createElement as h, Fragment, type ComponentType, type ReactNode } from 'react';
|
|
2
|
+
import type { ThemeKind } from './protocol.ts';
|
|
3
|
+
/** The compiled canvas: a CommonJS body with JSX as `__h` / `__Fragment` (`compileCanvas`). */
|
|
4
|
+
export type CanvasFactory = (require: (name: string) => unknown, exports: Record<string, unknown>, module: {
|
|
5
|
+
exports: Record<string, unknown>;
|
|
6
|
+
}, __h: typeof h, __Fragment: typeof Fragment) => void;
|
|
7
|
+
export interface CanvasRuntimeOptions {
|
|
8
|
+
/** The kit module: every name a canvas may import. The state hooks and React's hooks are added unless the kit has its own. */
|
|
9
|
+
kit: Record<string, unknown>;
|
|
10
|
+
/** Module names that resolve to the kit. Default `jig/canvas`, `cursor/canvas`. Keep in step with `compileCanvas`. */
|
|
11
|
+
modules?: readonly string[];
|
|
12
|
+
/** Wraps the canvas: the kit's theme provider and page shell. Gets the theme kind. */
|
|
13
|
+
Root?: ComponentType<{
|
|
14
|
+
theme: ThemeKind;
|
|
15
|
+
children?: ReactNode;
|
|
16
|
+
}>;
|
|
17
|
+
/** What a render error shows inside the frame. */
|
|
18
|
+
ErrorView?: ComponentType<{
|
|
19
|
+
error: unknown;
|
|
20
|
+
}>;
|
|
21
|
+
}
|
|
22
|
+
/** Load the compiled body against the kit and return its default export. Throws what the body throws. */
|
|
23
|
+
export declare function loadCanvas(factory: CanvasFactory, kit: Record<string, unknown>, modules: readonly string[]): ComponentType;
|
|
24
|
+
/** Install `window.__jigCanvas.run`. Call once in the runtime entry. */
|
|
25
|
+
export declare function startCanvasRuntime(options: CanvasRuntimeOptions): void;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// `@lightblues/jig/canvas/runtime`: the browser runtime inside the sandboxed frame: `buildRuntime` bundles this with React, react-dom and a kit into
|
|
2
|
+
// `runtime.js`. The document (`canvasDocument`) loads it and calls `window.__jigCanvas.run(factory, boot)`.
|
|
3
|
+
import { Component, createElement as h, Fragment, useEffect } from 'react';
|
|
4
|
+
import * as React from 'react';
|
|
5
|
+
import { createRoot } from 'react-dom/client';
|
|
6
|
+
import { createPageBridge } from "./bridge.js";
|
|
7
|
+
import { CanvasStateProvider, useCanvasAction, useCanvasEvent, useCanvasState, useCanvasSurface, useCanvasTheme } from "./state.js";
|
|
8
|
+
function errorText(error) {
|
|
9
|
+
return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
10
|
+
}
|
|
11
|
+
function DefaultError({ error }) {
|
|
12
|
+
return h('pre', { role: 'alert', style: { margin: 0, padding: '12px 14px', whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', font: '12px/18px ui-monospace,monospace', color: '#b42318' } }, errorText(error));
|
|
13
|
+
}
|
|
14
|
+
/** Load the compiled body against the kit and return its default export. Throws what the body throws. */
|
|
15
|
+
export function loadCanvas(factory, kit, modules) {
|
|
16
|
+
const allowed = new Set(modules);
|
|
17
|
+
const module = { exports: {} };
|
|
18
|
+
const require = (name) => {
|
|
19
|
+
if (allowed.has(name))
|
|
20
|
+
return kit;
|
|
21
|
+
throw new Error(`canvas may import only ${[...allowed].join(' or ')}; found ${JSON.stringify(name)}`);
|
|
22
|
+
};
|
|
23
|
+
factory(require, module.exports, module, h, Fragment);
|
|
24
|
+
const value = module.exports.default;
|
|
25
|
+
if (typeof value !== 'function' && !(value && typeof value === 'object' && '$$typeof' in value))
|
|
26
|
+
throw new Error('canvas must `export default` a component');
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
/** Install `window.__jigCanvas.run`. Call once in the runtime entry. */
|
|
30
|
+
export function startCanvasRuntime(options) {
|
|
31
|
+
const kit = {
|
|
32
|
+
useState: React.useState, useEffect: React.useEffect, useMemo: React.useMemo, useRef: React.useRef, useCallback: React.useCallback, Fragment,
|
|
33
|
+
useCanvasState, useCanvasEvent, useCanvasAction, useCanvasTheme, useCanvasSurface,
|
|
34
|
+
...options.kit,
|
|
35
|
+
};
|
|
36
|
+
const modules = options.modules ?? ['jig/canvas', 'cursor/canvas'];
|
|
37
|
+
const ErrorView = options.ErrorView ?? DefaultError;
|
|
38
|
+
const Root = options.Root ?? (({ children }) => h(Fragment, null, children));
|
|
39
|
+
function run(factory, boot) {
|
|
40
|
+
const parent = window.parent;
|
|
41
|
+
const bridge = createPageBridge({ post: (m) => parent.postMessage(m, '*'), init: { state: boot.state ?? {}, theme: boot.theme }, surface: boot.surface });
|
|
42
|
+
// Only the host (the parent window) may talk to the page; a sibling frame or a popup is ignored.
|
|
43
|
+
window.addEventListener('message', (event) => {
|
|
44
|
+
if (event.source !== parent)
|
|
45
|
+
return;
|
|
46
|
+
bridge.receive(event.data);
|
|
47
|
+
});
|
|
48
|
+
window.addEventListener('pagehide', () => bridge.flush());
|
|
49
|
+
bridge.ready();
|
|
50
|
+
let reported = false;
|
|
51
|
+
const report = (error) => {
|
|
52
|
+
if (reported)
|
|
53
|
+
return;
|
|
54
|
+
reported = true;
|
|
55
|
+
bridge.error(errorText(error));
|
|
56
|
+
};
|
|
57
|
+
window.addEventListener('error', (event) => report(event.error ?? event.message));
|
|
58
|
+
window.addEventListener('unhandledrejection', (event) => report(event.reason));
|
|
59
|
+
class Boundary extends Component {
|
|
60
|
+
state = { error: null };
|
|
61
|
+
static getDerivedStateFromError(error) {
|
|
62
|
+
return { error };
|
|
63
|
+
}
|
|
64
|
+
componentDidCatch(error, _info) {
|
|
65
|
+
report(error);
|
|
66
|
+
}
|
|
67
|
+
render() {
|
|
68
|
+
return this.state.error == null ? this.props.children : h(ErrorView, { error: this.state.error });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
let body = null;
|
|
72
|
+
let loadError = null;
|
|
73
|
+
try {
|
|
74
|
+
body = loadCanvas(factory, kit, modules);
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
loadError = err;
|
|
78
|
+
report(err);
|
|
79
|
+
}
|
|
80
|
+
// Height: the document's, after each layout change, but only once the canvas has committed. A page busy in its
|
|
81
|
+
// first render never sends a size, so the host's "not responding" budget catches it.
|
|
82
|
+
let committed = false;
|
|
83
|
+
let last = -1;
|
|
84
|
+
const measure = () => {
|
|
85
|
+
if (!committed)
|
|
86
|
+
return;
|
|
87
|
+
const height = Math.ceil(document.body.scrollHeight);
|
|
88
|
+
if (height !== last) {
|
|
89
|
+
last = height;
|
|
90
|
+
bridge.size(height);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
new ResizeObserver(measure).observe(document.body);
|
|
94
|
+
const Themed = () => {
|
|
95
|
+
const theme = useCanvasTheme();
|
|
96
|
+
useEffect(() => {
|
|
97
|
+
committed = true;
|
|
98
|
+
measure();
|
|
99
|
+
}, []);
|
|
100
|
+
useEffect(() => {
|
|
101
|
+
document.documentElement.dataset.theme = theme;
|
|
102
|
+
document.documentElement.style.colorScheme = theme;
|
|
103
|
+
}, [theme]);
|
|
104
|
+
return h(Root, { theme }, h(Boundary, null, loadError != null || !body ? h(ErrorView, { error: loadError }) : h(body)));
|
|
105
|
+
};
|
|
106
|
+
const root = document.getElementById('root') ?? document.body.appendChild(document.createElement('div'));
|
|
107
|
+
createRoot(root).render(h(CanvasStateProvider, { store: bridge.store }, h(Themed)));
|
|
108
|
+
}
|
|
109
|
+
window.__jigCanvas = { run };
|
|
110
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { compileCanvas, canvasTitle, CanvasCompileError, CANVAS_MODULES, CANVAS_MAX_BYTES, type CompileCanvasOptions } from './compile.ts';
|
|
2
|
+
export { canvasDocument, canvasCsp, CANVAS_SANDBOX, scriptSafe, type CanvasDocumentOptions, type CanvasProfile } from './document.ts';
|
|
3
|
+
export { surfacesContext, surfacesContextEntry, type SurfaceView, type SurfaceEvent, type SurfacesContextOptions } from './context.ts';
|
|
4
|
+
export { RUNTIME_NAMES } from './names.ts';
|
|
5
|
+
export * from './protocol.ts';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// `@lightblues/jig/canvas/server`: compile a canvas at write time, build its sandboxed document, validate what a frame
|
|
2
|
+
// posts, and render surfaces for the agent's context. Its only import is `sucrase` (an optional peer, for
|
|
3
|
+
// `compileCanvas`); everything else is pure and runs in a browser too.
|
|
4
|
+
export { compileCanvas, canvasTitle, CanvasCompileError, CANVAS_MODULES, CANVAS_MAX_BYTES } from "./compile.js";
|
|
5
|
+
export { canvasDocument, canvasCsp, CANVAS_SANDBOX, scriptSafe } from "./document.js";
|
|
6
|
+
export { surfacesContext, surfacesContextEntry } from "./context.js";
|
|
7
|
+
export { RUNTIME_NAMES } from "./names.js";
|
|
8
|
+
export * from "./protocol.js";
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import { CanvasStore, type CanvasStoreOptions } from './store.ts';
|
|
3
|
+
import type { CanvasAction, CanvasState, ThemeKind } from './protocol.ts';
|
|
4
|
+
export { CanvasStore, type CanvasStoreOptions } from './store.ts';
|
|
5
|
+
export { LIMITS, type CanvasAction, type CanvasState, type ThemeKind } from './protocol.ts';
|
|
6
|
+
export interface CanvasStateProviderProps extends CanvasStoreOptions {
|
|
7
|
+
/** A store made elsewhere (the frame runtime); its callbacks are its own and the props' are ignored. Without it the provider makes one per `surface`. */
|
|
8
|
+
store?: CanvasStore;
|
|
9
|
+
/**
|
|
10
|
+
* The host's values for this surface. When this object changes (another device or the agent changed the state), the
|
|
11
|
+
* page's values are replaced; nothing is sent back. Leave it unset to keep `initial` only.
|
|
12
|
+
*/
|
|
13
|
+
values?: CanvasState;
|
|
14
|
+
children?: ReactNode;
|
|
15
|
+
}
|
|
16
|
+
/** One surface's state. Several providers on one page keep separate state. */
|
|
17
|
+
export declare function CanvasStateProvider(props: CanvasStateProviderProps): ReactNode;
|
|
18
|
+
export type SetCanvasState<T> = (action: T | ((prev: T) => T)) => void;
|
|
19
|
+
/**
|
|
20
|
+
* `useState` whose value the host keeps per surface (and the agent can read). Outside a provider it is a plain
|
|
21
|
+
* `useState`. Values must be JSON; a write over a limit is dropped (`LIMITS`).
|
|
22
|
+
*/
|
|
23
|
+
export declare function useCanvasState<T>(key: string, defaultValue: T): [T, SetCanvasState<T>];
|
|
24
|
+
/** `(name, data) => void`: an append-only event the host stores and the agent reads (a guess, a result). */
|
|
25
|
+
export declare function useCanvasEvent(): (name: string, data?: unknown) => void;
|
|
26
|
+
/** A stable `dispatch` for buttons. The host decides what each action does, and acts only during a click. */
|
|
27
|
+
export declare function useCanvasAction(): (action: CanvasAction) => void;
|
|
28
|
+
/** The host's theme kind (`light` / `dark`); `light` outside a provider. */
|
|
29
|
+
export declare function useCanvasTheme(): ThemeKind;
|
|
30
|
+
/** The surface id of the nearest provider, `''` outside one. */
|
|
31
|
+
export declare function useCanvasSurface(): string;
|