@lightblues/jig 0.0.11 → 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 +3 -1
- 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/dist/markdown/blocks.d.ts +123 -0
- package/dist/markdown/blocks.js +166 -0
- package/dist/markdown/index.d.ts +24 -0
- package/dist/markdown/index.js +182 -1
- package/dist/markdown/mermaid.d.ts +34 -0
- package/dist/markdown/mermaid.js +84 -0
- package/dist/markdown/react.d.ts +30 -0
- package/dist/markdown/react.js +57 -0
- package/package.json +55 -3
package/README.md
CHANGED
|
@@ -9,6 +9,8 @@ Planned parts (design: baton `.ea/log/2026-11-24-shared-agent-ui.md`, item #274)
|
|
|
9
9
|
| `@lightblues/jig/agent-paseo` | server adapter: a Paseo agent's timeline as AG-UI events, with replay and recovery |
|
|
10
10
|
| `@lightblues/jig/agent-pi` | server runtime for in-app pi agents: router models with tiers, sessions and runs in the host's own Postgres tables, one run as AG-UI events (run registry and SSE route: next) |
|
|
11
11
|
| `@lightblues/jig/agent-chat` | a thin headless client: follow a thread over SSE, reconnect, fold events into messages |
|
|
12
|
-
| `@lightblues/jig/markdown` | one markdown-it config for server and client: CJK, KaTeX, highlighting, safe for innerHTML, streaming-aware |
|
|
12
|
+
| `@lightblues/jig/markdown` | one markdown-it config for server and client: CJK, KaTeX, highlighting, safe for innerHTML, streaming-aware; fenced blocks with validated params, mermaid |
|
|
13
|
+
| `@lightblues/jig/markdown/react` | `FillSlots`: host components portalled into a document's block slots, mounted across streaming re-renders |
|
|
14
|
+
| `@lightblues/jig/canvas/server`, `/state`, `/frame`, `/runtime`, `/build` | model-written pages in a sandboxed frame (compile, CSP document, `<CanvasFrame>`, runtime build) and one state/event/action protocol for in-page blocks and frames; `.ea/docs/canvas.md` |
|
|
13
15
|
|
|
14
16
|
The protocol is AG-UI (`@ag-ui/core`), used as is.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { CanvasStore } from './store.ts';
|
|
2
|
+
import { type CanvasAction, type CanvasState, type HostMessage, type PageMessage, type ThemeKind } from './protocol.ts';
|
|
3
|
+
type Post<T> = (message: T & {
|
|
4
|
+
type: string;
|
|
5
|
+
v: number;
|
|
6
|
+
}) => void;
|
|
7
|
+
export interface PageBridge {
|
|
8
|
+
/** The store the hooks read; its writes, events and actions go to the host. */
|
|
9
|
+
store: CanvasStore;
|
|
10
|
+
/** A message from `window.parent` (the runtime checks the source). Invalid messages are ignored. */
|
|
11
|
+
receive(data: unknown): void;
|
|
12
|
+
/** Tell the host the page listens; it answers with `init` (the state it holds now). */
|
|
13
|
+
ready(): void;
|
|
14
|
+
size(height: number): void;
|
|
15
|
+
error(message: string): void;
|
|
16
|
+
/** Post waiting state writes now (before unload). */
|
|
17
|
+
flush(): void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The page side. State writes are coalesced: within `flushMs` only the latest value per key is posted, so a slider
|
|
21
|
+
* dragged at 60 fps sends at most one message per key per window and stays under the host's rate limit. An event or
|
|
22
|
+
* action posts the waiting writes first, so the host sees them in the page's order. Nothing is posted but `ready`
|
|
23
|
+
* until the host's `init` arrives: writes and (up to 20) events made before it are kept and posted then, in order;
|
|
24
|
+
* actions made before it are dropped.
|
|
25
|
+
*
|
|
26
|
+
* Each posted write carries a `seq`; a host `state`/`init` carries `ack`, the last `seq` the host had when it sent it.
|
|
27
|
+
* Writes newer than `ack` (posted, or still waiting) stay on top of the host's values instead of flickering back.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createPageBridge(options: {
|
|
30
|
+
post: Post<PageMessage>;
|
|
31
|
+
init: {
|
|
32
|
+
state: CanvasState;
|
|
33
|
+
theme: ThemeKind;
|
|
34
|
+
};
|
|
35
|
+
surface?: string;
|
|
36
|
+
/** Coalescing window for state writes. Default 50 ms. */
|
|
37
|
+
flushMs?: number;
|
|
38
|
+
setTimer?: (fn: () => void, ms: number) => unknown;
|
|
39
|
+
}): PageBridge;
|
|
40
|
+
export interface RateLimit {
|
|
41
|
+
/** Messages accepted at once. */
|
|
42
|
+
burst: number;
|
|
43
|
+
/** Refill per second. */
|
|
44
|
+
perSecond: number;
|
|
45
|
+
}
|
|
46
|
+
export interface HostBridgeOptions {
|
|
47
|
+
post: Post<HostMessage>;
|
|
48
|
+
/** The state the host holds for this surface now. */
|
|
49
|
+
state: CanvasState;
|
|
50
|
+
theme: ThemeKind;
|
|
51
|
+
/** Debounced state writes: every key the page changed since the last call, latest value each. */
|
|
52
|
+
onState?: (set: CanvasState) => void;
|
|
53
|
+
onEvent?: (name: string, data: unknown) => void;
|
|
54
|
+
/** Called only while `userActive()` is true. */
|
|
55
|
+
onAction?: (action: CanvasAction) => void;
|
|
56
|
+
onSize?: (height: number) => void;
|
|
57
|
+
/** The page's render error (its error box is showing). */
|
|
58
|
+
onError?: (message: string) => void;
|
|
59
|
+
onReady?: () => void;
|
|
60
|
+
/** The page tried to leave (the relay removed it). The bridge stops. */
|
|
61
|
+
onNavigated?: () => void;
|
|
62
|
+
/** Every message dropped, with the reason. */
|
|
63
|
+
onReject?: (reason: string, data: unknown) => void;
|
|
64
|
+
/** Event names allowed (a block's manifest). Without it, the first 20 distinct names are allowed. */
|
|
65
|
+
events?: readonly string[];
|
|
66
|
+
/** State writes are passed on after this long without another write. Default 800 ms. */
|
|
67
|
+
debounceMs?: number;
|
|
68
|
+
/** All page messages. Default 100 at once, 50 a second. */
|
|
69
|
+
rate?: RateLimit;
|
|
70
|
+
/** Events, within `rate`. Default 20 at once, 1 a second (60 a minute). */
|
|
71
|
+
eventRate?: RateLimit;
|
|
72
|
+
/** Whether the host page has transient user activation (`navigator.userActivation.isActive`); no API: false. */
|
|
73
|
+
userActive?: () => boolean;
|
|
74
|
+
now?: () => number;
|
|
75
|
+
setTimer?: (fn: () => void, ms: number) => unknown;
|
|
76
|
+
clearTimer?: (timer: unknown) => void;
|
|
77
|
+
}
|
|
78
|
+
/** The host side: validates, rate-limits, debounces and answers. One per live frame. */
|
|
79
|
+
export declare class HostBridge {
|
|
80
|
+
private o;
|
|
81
|
+
private state;
|
|
82
|
+
private theme;
|
|
83
|
+
private pending;
|
|
84
|
+
private lastSeq;
|
|
85
|
+
private timer;
|
|
86
|
+
private isReady;
|
|
87
|
+
private disposed;
|
|
88
|
+
private readonly names;
|
|
89
|
+
private readonly rate;
|
|
90
|
+
private readonly eventRate;
|
|
91
|
+
private readonly setTimer;
|
|
92
|
+
private readonly clearTimer;
|
|
93
|
+
constructor(options: HostBridgeOptions);
|
|
94
|
+
/** Swap callbacks for the latest props (state and theme go through `setState` / `setTheme`). */
|
|
95
|
+
update(options: Partial<Pick<HostBridgeOptions, 'onState' | 'onEvent' | 'onAction' | 'onSize' | 'onError' | 'onReady' | 'onNavigated' | 'onReject' | 'events' | 'userActive'>>): void;
|
|
96
|
+
get ready(): boolean;
|
|
97
|
+
/** What the page should show now: the host's state with the page's not-yet-passed-on writes on top. */
|
|
98
|
+
private current;
|
|
99
|
+
receive(data: unknown): void;
|
|
100
|
+
private handle;
|
|
101
|
+
/** The host's state changed (the agent, another device, or its own save): replace the page's values. */
|
|
102
|
+
setState(values: CanvasState): void;
|
|
103
|
+
setTheme(kind: ThemeKind): void;
|
|
104
|
+
/** Pass on waiting state writes now. */
|
|
105
|
+
flush(): void;
|
|
106
|
+
/** Flush and stop: later messages are ignored and nothing more is posted. */
|
|
107
|
+
dispose(): void;
|
|
108
|
+
private reject;
|
|
109
|
+
}
|
|
110
|
+
export {};
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
// Both ends of the tier-B message bridge, without DOM or React: `CanvasFrame` and the frame runtime wire these to
|
|
2
|
+
// `postMessage`, and the tests drive them through forced interleavings.
|
|
3
|
+
import { CanvasStore } from "./store.js";
|
|
4
|
+
import { frameMessage, jsonSize, LIMITS, parseFrameMessage, parseHostMessage, } from "./protocol.js";
|
|
5
|
+
/** Events a page may make before the host's `init`; later ones are dropped. */
|
|
6
|
+
const HELD_EVENTS = 20;
|
|
7
|
+
/**
|
|
8
|
+
* The page side. State writes are coalesced: within `flushMs` only the latest value per key is posted, so a slider
|
|
9
|
+
* dragged at 60 fps sends at most one message per key per window and stays under the host's rate limit. An event or
|
|
10
|
+
* action posts the waiting writes first, so the host sees them in the page's order. Nothing is posted but `ready`
|
|
11
|
+
* until the host's `init` arrives: writes and (up to 20) events made before it are kept and posted then, in order;
|
|
12
|
+
* actions made before it are dropped.
|
|
13
|
+
*
|
|
14
|
+
* Each posted write carries a `seq`; a host `state`/`init` carries `ack`, the last `seq` the host had when it sent it.
|
|
15
|
+
* Writes newer than `ack` (posted, or still waiting) stay on top of the host's values instead of flickering back.
|
|
16
|
+
*/
|
|
17
|
+
export function createPageBridge(options) {
|
|
18
|
+
const { post } = options;
|
|
19
|
+
const setTimer = options.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
|
|
20
|
+
let seq = 0;
|
|
21
|
+
let timer = null;
|
|
22
|
+
// Writes wait for `init`: before it the host would drop them, and the page would show a value nobody stored.
|
|
23
|
+
let initialized = false;
|
|
24
|
+
const outbox = new Map();
|
|
25
|
+
const held = [];
|
|
26
|
+
const unacked = new Map();
|
|
27
|
+
const flush = () => {
|
|
28
|
+
timer = null;
|
|
29
|
+
if (!initialized)
|
|
30
|
+
return;
|
|
31
|
+
for (const [key, value] of outbox) {
|
|
32
|
+
seq += 1;
|
|
33
|
+
unacked.set(key, { value, seq });
|
|
34
|
+
post(frameMessage({ op: 'state', key, value, seq }));
|
|
35
|
+
}
|
|
36
|
+
outbox.clear();
|
|
37
|
+
};
|
|
38
|
+
const store = new CanvasStore({
|
|
39
|
+
surface: options.surface,
|
|
40
|
+
initial: options.init.state,
|
|
41
|
+
theme: options.init.theme,
|
|
42
|
+
onState: (key, value) => {
|
|
43
|
+
outbox.delete(key);
|
|
44
|
+
outbox.set(key, value);
|
|
45
|
+
if (timer === null)
|
|
46
|
+
timer = setTimer(flush, options.flushMs ?? 50);
|
|
47
|
+
},
|
|
48
|
+
onEvent: (name, data) => {
|
|
49
|
+
if (!initialized)
|
|
50
|
+
return void (held.length < HELD_EVENTS && held.push({ name, data }));
|
|
51
|
+
flush();
|
|
52
|
+
post(frameMessage({ op: 'event', name, data }));
|
|
53
|
+
},
|
|
54
|
+
onAction: (action) => {
|
|
55
|
+
// An action before init is dropped, not held: posted later it could arrive during an unrelated click.
|
|
56
|
+
if (!initialized)
|
|
57
|
+
return;
|
|
58
|
+
flush();
|
|
59
|
+
post(frameMessage({ op: 'action', action }));
|
|
60
|
+
},
|
|
61
|
+
});
|
|
62
|
+
const replace = (values, ack) => {
|
|
63
|
+
for (const [key, w] of unacked)
|
|
64
|
+
if (w.seq <= ack)
|
|
65
|
+
unacked.delete(key);
|
|
66
|
+
const next = { ...values };
|
|
67
|
+
for (const [key, w] of unacked)
|
|
68
|
+
next[key] = w.value;
|
|
69
|
+
for (const [key, value] of outbox)
|
|
70
|
+
next[key] = value;
|
|
71
|
+
store.replace(next);
|
|
72
|
+
};
|
|
73
|
+
return {
|
|
74
|
+
store,
|
|
75
|
+
receive(data) {
|
|
76
|
+
const m = parseHostMessage(data);
|
|
77
|
+
if (!m)
|
|
78
|
+
return;
|
|
79
|
+
if (m.op === 'theme')
|
|
80
|
+
store.setTheme(m.kind);
|
|
81
|
+
else if (m.op === 'init') {
|
|
82
|
+
store.setTheme(m.theme);
|
|
83
|
+
replace(m.state, m.ack);
|
|
84
|
+
if (!initialized) {
|
|
85
|
+
initialized = true;
|
|
86
|
+
flush();
|
|
87
|
+
for (const e of held.splice(0))
|
|
88
|
+
post(frameMessage({ op: 'event', name: e.name, data: e.data }));
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
else
|
|
92
|
+
replace(m.values, m.ack);
|
|
93
|
+
},
|
|
94
|
+
ready: () => post(frameMessage({ op: 'ready' })),
|
|
95
|
+
size: (height) => post(frameMessage({ op: 'size', height })),
|
|
96
|
+
error: (message) => post(frameMessage({ op: 'error', message: String(message).slice(0, LIMITS.error) })),
|
|
97
|
+
flush,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
class Bucket {
|
|
101
|
+
tokens;
|
|
102
|
+
at;
|
|
103
|
+
limit;
|
|
104
|
+
now;
|
|
105
|
+
constructor(limit, now) {
|
|
106
|
+
this.limit = limit;
|
|
107
|
+
this.now = now;
|
|
108
|
+
this.tokens = limit.burst;
|
|
109
|
+
this.at = now();
|
|
110
|
+
}
|
|
111
|
+
take() {
|
|
112
|
+
const t = this.now();
|
|
113
|
+
this.tokens = Math.min(this.limit.burst, this.tokens + ((t - this.at) / 1000) * this.limit.perSecond);
|
|
114
|
+
this.at = t;
|
|
115
|
+
if (this.tokens < 1)
|
|
116
|
+
return false;
|
|
117
|
+
this.tokens -= 1;
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** The host side: validates, rate-limits, debounces and answers. One per live frame. */
|
|
122
|
+
export class HostBridge {
|
|
123
|
+
o;
|
|
124
|
+
state;
|
|
125
|
+
theme;
|
|
126
|
+
pending = {};
|
|
127
|
+
lastSeq = 0;
|
|
128
|
+
timer = null;
|
|
129
|
+
isReady = false;
|
|
130
|
+
disposed = false;
|
|
131
|
+
names = new Set();
|
|
132
|
+
rate;
|
|
133
|
+
eventRate;
|
|
134
|
+
setTimer;
|
|
135
|
+
clearTimer;
|
|
136
|
+
constructor(options) {
|
|
137
|
+
this.o = options;
|
|
138
|
+
this.state = options.state;
|
|
139
|
+
this.theme = options.theme;
|
|
140
|
+
const now = options.now ?? (() => Date.now());
|
|
141
|
+
this.rate = new Bucket(options.rate ?? { burst: 100, perSecond: 50 }, now);
|
|
142
|
+
this.eventRate = new Bucket(options.eventRate ?? { burst: 20, perSecond: 1 }, now);
|
|
143
|
+
this.setTimer = options.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
|
|
144
|
+
this.clearTimer = options.clearTimer ?? ((t) => clearTimeout(t));
|
|
145
|
+
}
|
|
146
|
+
/** Swap callbacks for the latest props (state and theme go through `setState` / `setTheme`). */
|
|
147
|
+
update(options) {
|
|
148
|
+
this.o = { ...this.o, ...options };
|
|
149
|
+
}
|
|
150
|
+
get ready() {
|
|
151
|
+
return this.isReady;
|
|
152
|
+
}
|
|
153
|
+
/** What the page should show now: the host's state with the page's not-yet-passed-on writes on top. */
|
|
154
|
+
current() {
|
|
155
|
+
return { ...this.state, ...this.pending };
|
|
156
|
+
}
|
|
157
|
+
receive(data) {
|
|
158
|
+
if (this.disposed)
|
|
159
|
+
return;
|
|
160
|
+
if (!this.rate.take())
|
|
161
|
+
return this.reject('rate limit', data);
|
|
162
|
+
const m = parseFrameMessage(data);
|
|
163
|
+
if (!m)
|
|
164
|
+
return this.reject('invalid message', data);
|
|
165
|
+
if (m.op === 'navigated') {
|
|
166
|
+
this.dispose();
|
|
167
|
+
this.o.onNavigated?.();
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
if (m.op === 'ready') {
|
|
171
|
+
if (this.isReady)
|
|
172
|
+
return this.reject('ready twice', data);
|
|
173
|
+
this.isReady = true;
|
|
174
|
+
this.o.post(frameMessage({ op: 'init', state: this.current(), theme: this.theme, ack: this.lastSeq }));
|
|
175
|
+
this.o.onReady?.();
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (!this.isReady)
|
|
179
|
+
return this.reject('before ready', data);
|
|
180
|
+
this.handle(m, data);
|
|
181
|
+
}
|
|
182
|
+
handle(m, data) {
|
|
183
|
+
switch (m.op) {
|
|
184
|
+
case 'state': {
|
|
185
|
+
this.lastSeq = Math.max(this.lastSeq, m.seq);
|
|
186
|
+
if (jsonSize({ ...this.current(), [m.key]: m.value }) > LIMITS.state)
|
|
187
|
+
return this.reject(`state over ${LIMITS.state} chars`, data);
|
|
188
|
+
this.pending[m.key] = m.value;
|
|
189
|
+
if (this.timer !== null)
|
|
190
|
+
this.clearTimer(this.timer);
|
|
191
|
+
this.timer = this.setTimer(() => this.flush(), this.o.debounceMs ?? 800);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
case 'event': {
|
|
195
|
+
const allowed = this.o.events;
|
|
196
|
+
if (allowed ? !allowed.includes(m.name) : !this.names.has(m.name) && this.names.size >= LIMITS.eventNames)
|
|
197
|
+
return this.reject(`event name ${m.name} not allowed`, data);
|
|
198
|
+
if (!this.eventRate.take())
|
|
199
|
+
return this.reject('event rate limit', data);
|
|
200
|
+
this.names.add(m.name);
|
|
201
|
+
this.o.onEvent?.(m.name, m.data);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
case 'action':
|
|
205
|
+
if (!(this.o.userActive?.() ?? false))
|
|
206
|
+
return this.reject('action without user activation', data);
|
|
207
|
+
this.o.onAction?.(m.action);
|
|
208
|
+
return;
|
|
209
|
+
case 'size':
|
|
210
|
+
this.o.onSize?.(m.height);
|
|
211
|
+
return;
|
|
212
|
+
case 'error':
|
|
213
|
+
this.o.onError?.(m.message);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
/** The host's state changed (the agent, another device, or its own save): replace the page's values. */
|
|
218
|
+
setState(values) {
|
|
219
|
+
// A host that passes a new but equal object on each render does not make the page re-render.
|
|
220
|
+
if (values === this.state || JSON.stringify(values) === JSON.stringify(this.state))
|
|
221
|
+
return;
|
|
222
|
+
this.state = values;
|
|
223
|
+
if (this.isReady && !this.disposed)
|
|
224
|
+
this.o.post(frameMessage({ op: 'state', values: this.current(), ack: this.lastSeq }));
|
|
225
|
+
}
|
|
226
|
+
setTheme(kind) {
|
|
227
|
+
if (kind === this.theme)
|
|
228
|
+
return;
|
|
229
|
+
this.theme = kind;
|
|
230
|
+
if (this.isReady && !this.disposed)
|
|
231
|
+
this.o.post(frameMessage({ op: 'theme', kind }));
|
|
232
|
+
}
|
|
233
|
+
/** Pass on waiting state writes now. */
|
|
234
|
+
flush() {
|
|
235
|
+
if (this.timer !== null)
|
|
236
|
+
this.clearTimer(this.timer);
|
|
237
|
+
this.timer = null;
|
|
238
|
+
const set = this.pending;
|
|
239
|
+
if (!Object.keys(set).length)
|
|
240
|
+
return;
|
|
241
|
+
this.pending = {};
|
|
242
|
+
this.state = { ...this.state, ...set };
|
|
243
|
+
this.o.onState?.(set);
|
|
244
|
+
}
|
|
245
|
+
/** Flush and stop: later messages are ignored and nothing more is posted. */
|
|
246
|
+
dispose() {
|
|
247
|
+
if (this.disposed)
|
|
248
|
+
return;
|
|
249
|
+
this.flush();
|
|
250
|
+
this.disposed = true;
|
|
251
|
+
}
|
|
252
|
+
reject(reason, data) {
|
|
253
|
+
this.o.onReject?.(reason, data);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface BuildRuntimeOptions {
|
|
2
|
+
/** Absolute path of the kit module: every name it exports is importable from a canvas. */
|
|
3
|
+
kit: string;
|
|
4
|
+
/** A component the kit exports that wraps every canvas (theme provider, page shell); gets `{ theme }`. */
|
|
5
|
+
root?: string;
|
|
6
|
+
/** A component the kit exports that shows a render error; gets `{ error }`. */
|
|
7
|
+
errorView?: string;
|
|
8
|
+
/** Module names that resolve to the kit. Default `jig/canvas`, `cursor/canvas`. */
|
|
9
|
+
modules?: readonly string[];
|
|
10
|
+
/** Write here as well as returning the code. */
|
|
11
|
+
outFile?: string;
|
|
12
|
+
/** Default true. */
|
|
13
|
+
minify?: boolean;
|
|
14
|
+
/** Default `['es2020']`. */
|
|
15
|
+
target?: string[];
|
|
16
|
+
}
|
|
17
|
+
export interface BuiltRuntime {
|
|
18
|
+
code: string;
|
|
19
|
+
/** sha256 of the code, 12 hex chars, for the `?v=` of the runtime URL. */
|
|
20
|
+
hash: string;
|
|
21
|
+
bytes: number;
|
|
22
|
+
/** What a canvas may import: the kit's exports and the runtime's hooks. Pass to `compileCanvas({ exports })`. */
|
|
23
|
+
exports: string[];
|
|
24
|
+
}
|
|
25
|
+
export declare function buildRuntime(options: BuildRuntimeOptions): Promise<BuiltRuntime>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// `@lightblues/jig/canvas/build`: bundle a kit with React and the frame runtime into the `runtime.js` a canvas document
|
|
2
|
+
// loads. Node only, run from a host's build script; esbuild is an optional peer.
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { RUNTIME_NAMES } from "./names.js";
|
|
8
|
+
/** The runtime module next to this file, `.ts` in the source tree and `.js` in `dist/`. */
|
|
9
|
+
function sibling(name) {
|
|
10
|
+
const self = fileURLToPath(import.meta.url);
|
|
11
|
+
return path.join(path.dirname(self), `${name}${path.extname(self)}`);
|
|
12
|
+
}
|
|
13
|
+
/** The kit's export names, from an esbuild metafile of the kit alone. */
|
|
14
|
+
async function kitExports(esbuild, kit) {
|
|
15
|
+
const r = await esbuild.build({ entryPoints: [kit], bundle: true, write: false, format: 'esm', platform: 'browser', metafile: true, logLevel: 'silent', packages: 'external', outdir: '/tmp/jig-kit-exports' });
|
|
16
|
+
const out = Object.values(r.metafile.outputs).find((o) => o.entryPoint);
|
|
17
|
+
return out ? [...out.exports].filter((n) => n !== 'default') : [];
|
|
18
|
+
}
|
|
19
|
+
export async function buildRuntime(options) {
|
|
20
|
+
const esbuild = (await import('esbuild'));
|
|
21
|
+
const kit = path.resolve(options.kit);
|
|
22
|
+
const names = await kitExports(esbuild, kit);
|
|
23
|
+
for (const n of [options.root, options.errorView])
|
|
24
|
+
if (n && !names.includes(n))
|
|
25
|
+
throw new Error(`the kit ${kit} does not export ${n}`);
|
|
26
|
+
const entry = [
|
|
27
|
+
`import * as kit from ${JSON.stringify(kit)};`,
|
|
28
|
+
`import { startCanvasRuntime } from ${JSON.stringify(sibling('runtime'))};`,
|
|
29
|
+
`startCanvasRuntime({ kit, modules: ${JSON.stringify(options.modules ?? null)} ?? undefined, Root: ${options.root ? `kit[${JSON.stringify(options.root)}]` : 'undefined'}, ErrorView: ${options.errorView ? `kit[${JSON.stringify(options.errorView)}]` : 'undefined'} });`,
|
|
30
|
+
].join('\n');
|
|
31
|
+
const r = await esbuild.build({
|
|
32
|
+
stdin: { contents: entry, resolveDir: path.dirname(kit), sourcefile: 'jig-canvas-runtime-entry.js', loader: 'js' },
|
|
33
|
+
bundle: true,
|
|
34
|
+
write: false,
|
|
35
|
+
minify: options.minify ?? true,
|
|
36
|
+
format: 'iife',
|
|
37
|
+
platform: 'browser',
|
|
38
|
+
target: options.target ?? ['es2020'],
|
|
39
|
+
define: { 'process.env.NODE_ENV': '"production"' },
|
|
40
|
+
legalComments: 'none',
|
|
41
|
+
logLevel: 'silent',
|
|
42
|
+
});
|
|
43
|
+
const code = r.outputFiles[0].text;
|
|
44
|
+
if (options.outFile) {
|
|
45
|
+
await mkdir(path.dirname(options.outFile), { recursive: true });
|
|
46
|
+
await writeFile(options.outFile, code);
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
code,
|
|
50
|
+
hash: createHash('sha256').update(code).digest('hex').slice(0, 12),
|
|
51
|
+
bytes: Buffer.byteLength(code),
|
|
52
|
+
exports: [...new Set([...RUNTIME_NAMES, ...names])].sort(),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Module names a canvas may import from by default: Cursor's, so a Cursor canvas ports, and jig's. */
|
|
2
|
+
export declare const CANVAS_MODULES: readonly ["jig/canvas", "cursor/canvas"];
|
|
3
|
+
/** Default source cap: 100 KB of UTF-8 (v2 §4). */
|
|
4
|
+
export declare const CANVAS_MAX_BYTES = 100000;
|
|
5
|
+
export interface CompileCanvasOptions {
|
|
6
|
+
/** Module names allowed in `import { … } from "<name>"`. Default `CANVAS_MODULES`; a host adds its alias (`intake/canvas`). */
|
|
7
|
+
modules?: readonly string[];
|
|
8
|
+
/** Names the kit exports. Without it, any name is accepted (a missing one is `undefined` at render). */
|
|
9
|
+
exports?: readonly string[];
|
|
10
|
+
/** Source cap in UTF-8 bytes. Default 100 KB. */
|
|
11
|
+
maxBytes?: number;
|
|
12
|
+
}
|
|
13
|
+
/** A compile failure: `message` names the line and shows it, ready to return to the model as a tool error. */
|
|
14
|
+
export declare class CanvasCompileError extends Error {
|
|
15
|
+
name: string;
|
|
16
|
+
/** The source line, when the problem has one. */
|
|
17
|
+
readonly line?: number;
|
|
18
|
+
constructor(message: string, line?: number);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Compile canvas TSX to the body the runtime runs as `(require, exports, module, __h, __Fragment)`. Throws a
|
|
22
|
+
* `CanvasCompileError` when the source is over the cap, does not parse, imports anything but named imports from an
|
|
23
|
+
* allowed module, uses `require`, dynamic `import()` or `import.meta`, re-exports, or has no `export default`.
|
|
24
|
+
*/
|
|
25
|
+
export declare function compileCanvas(source: string, options?: CompileCanvasOptions): string;
|
|
26
|
+
/** The line and one either side, numbered, each cut to 200 chars. */
|
|
27
|
+
export declare function excerpt(source: string, line: number): string;
|
|
28
|
+
/** The text of the first `<H1>` in the source, as a title fallback. */
|
|
29
|
+
export declare function canvasTitle(source: string): string;
|