@ewe-studios/foundation-wasm-ui 0.0.0-stage → 0.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +11 -2
- package/bundle.js +15565 -0
- package/bundle.min.js +2 -0
- package/foundation_wasm/runtime/foundation-wasm.js +2449 -0
- package/index.js +3 -0
- package/package.json +12 -4
- package/ui/runtimes/foundation-ui-actions.js +698 -0
- package/ui/runtimes/foundation-ui-behaviours.js +792 -0
- package/ui/runtimes/foundation-ui-bootstrap.js +13 -0
- package/ui/runtimes/foundation-ui-connections.js +99 -0
- package/ui/runtimes/foundation-ui-frames.js +1023 -0
- package/ui/runtimes/foundation-ui-live.js +186 -0
- package/ui/runtimes/foundation-ui-recovery.js +66 -0
- package/ui/runtimes/foundation-ui-vocab.js +262 -0
- package/ui/runtimes/foundation-ui-wire.js +1 -0
- package/ui/runtimes/foundation-wasm-ui.js +2164 -0
- package/ui/runtimes/platform-scheme-interceptor.js +124 -0
- package/ui/runtimes/runtime-entry.js +4 -0
|
@@ -0,0 +1,698 @@
|
|
|
1
|
+
// Route browser actions through the negotiated frame protocol.
|
|
2
|
+
import * as wire from "./foundation-ui-wire.js";
|
|
3
|
+
import { VOCABULARY_VERSION, STRUCTURED_INPUT_VERSION } from "./foundation-ui-vocab.js";
|
|
4
|
+
import { base64urlDecode, base64urlEncode, readFrames, sheetSubmitField, installFrameRuntime, readViewResponse } from "./foundation-ui-frames.js";
|
|
5
|
+
import * as ui from "./foundation-wasm-ui.js";
|
|
6
|
+
import * as behaviours from "./foundation-ui-behaviours.js";
|
|
7
|
+
|
|
8
|
+
const validName = name => typeof name === "string" && name.length > 0 && !/[:\s\p{Cc}]/u.test(name);
|
|
9
|
+
const error = code => ({ error: code });
|
|
10
|
+
|
|
11
|
+
export function parseReference(text) {
|
|
12
|
+
if (typeof text !== "string") return error("InvalidReference");
|
|
13
|
+
const [origin, name, extra] = text.split(":");
|
|
14
|
+
if (extra !== undefined || !["host", "server"].includes(origin) || !validName(name)) {
|
|
15
|
+
return error("InvalidReference");
|
|
16
|
+
}
|
|
17
|
+
return { origin, name };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class JsActionRegistry {
|
|
21
|
+
#entries = new Map();
|
|
22
|
+
|
|
23
|
+
declare(origin, name, scope = "all", local = origin === "host") {
|
|
24
|
+
if (![null, "host", "server"].includes(origin) || !validName(name) || !["all", "web", "mobile"].includes(scope)) {
|
|
25
|
+
throw new TypeError("Invalid action declaration");
|
|
26
|
+
}
|
|
27
|
+
const entries = this.#entries.get(name) ?? [];
|
|
28
|
+
if (entries.some(e => (e.origin === null || origin === null || e.origin === origin)
|
|
29
|
+
&& (scope === "all" || e.scope === "all" || e.scope === scope))) {
|
|
30
|
+
throw new Error("Duplicate action declaration");
|
|
31
|
+
}
|
|
32
|
+
entries.push({ origin, scope, local, page: false });
|
|
33
|
+
this.#entries.set(name, entries);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
declarePage(name) {
|
|
37
|
+
this.declare("host", name, "web", true);
|
|
38
|
+
this.lookup("host", name, "web").page = true;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
registerHost(name, fn, owner) {
|
|
42
|
+
if (typeof fn !== "function") throw new TypeError("Expected a page function");
|
|
43
|
+
let entry = this.lookup("host", name, "web");
|
|
44
|
+
if (entry.error) {
|
|
45
|
+
this.declarePage(name);
|
|
46
|
+
entry = this.lookup("host", name, "web");
|
|
47
|
+
}
|
|
48
|
+
const ownerId = owner?.getAttribute?.("primal-id");
|
|
49
|
+
const sameOwner = owner && (entry.owner === owner || (ownerId != null && ownerId === entry.ownerId));
|
|
50
|
+
if ((entry.fn && !sameOwner) || entry.origin !== "host" || entry.scope !== "web") {
|
|
51
|
+
throw new Error("Duplicate action declaration");
|
|
52
|
+
}
|
|
53
|
+
Object.assign(entry, { fn, page: true, local: true, owner, ownerId });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
lookup(origin, name, surface) {
|
|
57
|
+
const entries = this.#entries.get(name);
|
|
58
|
+
if (!entries) return error("UnknownAction");
|
|
59
|
+
const matching = entries.filter(e => e.origin === null || e.origin === origin);
|
|
60
|
+
if (!matching.length) return error("UnavailableOrigin");
|
|
61
|
+
return matching.find(e => e.scope === "all" || e.scope === surface) ?? error("UnsupportedAction");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
hostFunction(name) { return this.lookup("host", name, "web").fn; }
|
|
65
|
+
|
|
66
|
+
refs(surface) {
|
|
67
|
+
const refs = [];
|
|
68
|
+
for (const [name, entries] of this.#entries) {
|
|
69
|
+
for (const entry of entries) {
|
|
70
|
+
if (entry.scope !== "all" && entry.scope !== surface) continue;
|
|
71
|
+
for (const origin of entry.origin ? [entry.origin] : ["host", "server"]) refs.push(origin + ":" + name);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return refs.sort();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function route(reference, surface, lookup, has, serverHas) {
|
|
79
|
+
const ref = typeof reference === "string" ? parseReference(reference) : reference;
|
|
80
|
+
if (ref.error) return ref;
|
|
81
|
+
const entry = lookup(ref.origin, ref.name, surface);
|
|
82
|
+
const available = serverHas(ref.name);
|
|
83
|
+
if (entry.error && !(entry.error === "UnknownAction" && ref.origin === "server" && available)) return entry;
|
|
84
|
+
let destination = ref.origin;
|
|
85
|
+
if (destination === "host" && !entry.local) {
|
|
86
|
+
if (entry.origin !== null || !available) return error("UnavailableOrigin");
|
|
87
|
+
destination = "server";
|
|
88
|
+
}
|
|
89
|
+
if (!has[destination] || (destination === "server" && available === false)) return error("UnavailableOrigin");
|
|
90
|
+
return { route: destination };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function stateBytes(text, limit) {
|
|
94
|
+
if (!text) return null;
|
|
95
|
+
if (text.length > Math.ceil(limit * 4 / 3) || !/^[A-Za-z0-9_-]+$/.test(text)) throw new Error("Invalid state attachment");
|
|
96
|
+
return base64urlDecode(text);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function finishRequest(builder, request, stream, sequence) {
|
|
100
|
+
const frame = wire.Frame.createFrame(builder, 1, stream, sequence, wire.FrameKind.FrameRequest, request);
|
|
101
|
+
wire.Frame.finishFrameBuffer(builder, frame);
|
|
102
|
+
return builder.asUint8Array();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function encodeAction(name, el, event, type, state, stream, sequence, json) {
|
|
106
|
+
const id = element => Number(element?.getAttribute("primal-id") ?? 0);
|
|
107
|
+
const b = new wire.Builder();
|
|
108
|
+
const mods = Number(!!event.altKey) | Number(!!event.ctrlKey) << 1 | Number(!!event.shiftKey) << 2 | Number(!!event.metaKey) << 3;
|
|
109
|
+
const value = event.type === "click" ? sheetSubmitField(el)?.value ?? el.value : el?.value;
|
|
110
|
+
const input = new wire.ActionInputT(type, json === null ? String(value ?? "") : null, !!el?.checked, event.keyCode ?? 0, mods, id(el?.parentElement), json).pack(b);
|
|
111
|
+
const ref = b.createString(name);
|
|
112
|
+
const attachment = state && wire.ActionRequest.createStateVector(b, state);
|
|
113
|
+
wire.ActionRequest.startActionRequest(b);
|
|
114
|
+
wire.ActionRequest.addAction(b, ref);
|
|
115
|
+
wire.ActionRequest.addNodeId(b, id(el));
|
|
116
|
+
wire.ActionRequest.addInput(b, input);
|
|
117
|
+
if (attachment) wire.ActionRequest.addState(b, attachment);
|
|
118
|
+
const action = wire.ActionRequest.endActionRequest(b);
|
|
119
|
+
wire.FrameRequest.startFrameRequest(b);
|
|
120
|
+
wire.FrameRequest.addAction(b, action);
|
|
121
|
+
return finishRequest(b, wire.FrameRequest.endFrameRequest(b), stream, sequence);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export class WebActionManager {
|
|
125
|
+
#busy = new Set();
|
|
126
|
+
#advertised;
|
|
127
|
+
#structured = false;
|
|
128
|
+
#next = 1n;
|
|
129
|
+
#reloaded = false;
|
|
130
|
+
|
|
131
|
+
constructor(deps) {
|
|
132
|
+
this.deps = deps;
|
|
133
|
+
if (deps.server?.handle && deps.server instanceof WebSocketActionTransport) {
|
|
134
|
+
let reconnect = false;
|
|
135
|
+
deps.server.onReply = bytes => this.receive(bytes).catch(error => this.onError({code: "Transport", detail: String(error)}));
|
|
136
|
+
deps.server.onDisconnect = detail => {
|
|
137
|
+
reconnect = true;
|
|
138
|
+
this.#advertised = new Set();
|
|
139
|
+
this.#structured = false;
|
|
140
|
+
this.onError({code: "Transport", detail: String(detail)});
|
|
141
|
+
};
|
|
142
|
+
deps.server.onOpen = async () => {
|
|
143
|
+
if (!reconnect) return;
|
|
144
|
+
reconnect = false;
|
|
145
|
+
try { for (const reply of await deps.server.send(this.hello())) await this.receive(reply); }
|
|
146
|
+
catch (error) { this.onError({code: "Transport", detail: String(error)}); }
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
this.streamId = deps.streamId ?? 0n;
|
|
150
|
+
this.onError = deps.onError ?? console.error;
|
|
151
|
+
this.limit = deps.maxRequestBytes ?? 1024 * 1024;
|
|
152
|
+
const hooks = deps.frames?.deps;
|
|
153
|
+
if (hooks) {
|
|
154
|
+
const previousCaps = hooks.onCaps;
|
|
155
|
+
const previousError = hooks.onError;
|
|
156
|
+
const caps = value => { previousCaps?.(value); this.applyCaps(value); };
|
|
157
|
+
const failure = detail => {
|
|
158
|
+
if (previousError !== this.onError) previousError?.(detail);
|
|
159
|
+
this.reportControl(detail);
|
|
160
|
+
};
|
|
161
|
+
hooks.onCaps = caps;
|
|
162
|
+
hooks.onError = failure;
|
|
163
|
+
this.detachControls = () => {
|
|
164
|
+
if (hooks.onCaps === caps) hooks.onCaps = previousCaps;
|
|
165
|
+
if (hooks.onError === failure) hooks.onError = previousError;
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
setStreamId(id) { this.streamId = BigInt(id); }
|
|
171
|
+
|
|
172
|
+
hello() {
|
|
173
|
+
const b = new wire.Builder();
|
|
174
|
+
const hello = new wire.ClientHelloT(VOCABULARY_VERSION, wire.Platform.Web, wire.MountSurface.Web, 0n, true,
|
|
175
|
+
this.deps.server?.requestTag ?? 0n);
|
|
176
|
+
return finishRequest(b, new wire.FrameRequestT(null, hello).pack(b), 0n, 0n);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
applyCaps(caps) {
|
|
180
|
+
caps = caps.unpack?.() ?? caps;
|
|
181
|
+
this.#structured = caps.status === wire.CapsStatus.Ok && caps.vocabularyVersion >= STRUCTURED_INPUT_VERSION;
|
|
182
|
+
this.#advertised = new Set((caps.actions ?? []).map(a => a.name));
|
|
183
|
+
this.setStreamId(caps.streamId);
|
|
184
|
+
if (this.deps.frames?.deps) this.deps.frames.deps.deliverySession =
|
|
185
|
+
caps.subscriptionResume && caps.status === wire.CapsStatus.Ok ? this.streamId : undefined;
|
|
186
|
+
const doc = this.deps.document ?? globalThis.document;
|
|
187
|
+
for (const el of doc?.querySelectorAll("[primal-id]") ?? []) {
|
|
188
|
+
const missing = Array.from(el.attributes).some(attr =>
|
|
189
|
+
attr.name.startsWith("primal:on") && attr.value.startsWith("server:") && !this.#advertised.has(attr.value.slice(7)));
|
|
190
|
+
el.toggleAttribute("data-ewe-unavailable", missing);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async receive(bytes, viewMount) {
|
|
195
|
+
if (await this.deps.frames.receive(bytes, viewMount ? { viewMount } : undefined) === false) throw new Error("Invalid action reply");
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
reportControl(detail) {
|
|
199
|
+
this.onError(detail);
|
|
200
|
+
if (!this.#reloaded && ["StateExpired", "UpdateRequired"].includes(detail.code)) {
|
|
201
|
+
this.#reloaded = true;
|
|
202
|
+
(this.deps.reload ?? (() => globalThis.location.reload()))();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async trigger(reference, el, event = {}, type = event.type) {
|
|
207
|
+
return this.#submit(reference, el, event, type, undefined);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async triggerStructured(reference, el, payload, event = {}, type = event.type) {
|
|
211
|
+
if (payload === undefined) return this.onError({ code: "InvalidInput" });
|
|
212
|
+
return this.#submit(reference, el, event, type, payload);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Deliver a data instruction to the host action configured by the receiving view. */
|
|
216
|
+
async deliverViewData(reference, el, bytes) {
|
|
217
|
+
return this.deliverHostPayload(reference, el, Array.from(bytes));
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Invoke the registered local handler for a configured host callback. */
|
|
221
|
+
async deliverHostPayload(reference, el, payload) {
|
|
222
|
+
if (parseReference(reference).origin !== "host") return this.onError({code:"UnavailableOrigin"});
|
|
223
|
+
return this.#submit(reference, el, {type:"data"}, "data", payload, true);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async #submit(reference, el, event, type, payload, delivery = false, parent) {
|
|
227
|
+
let claimed;
|
|
228
|
+
let fault = "BadRequest";
|
|
229
|
+
const fail = detail => {
|
|
230
|
+
if (parent) throw Object.assign(new Error(detail.detail ?? detail.code), detail);
|
|
231
|
+
return this.onError(detail);
|
|
232
|
+
};
|
|
233
|
+
try {
|
|
234
|
+
const ref = parseReference(reference);
|
|
235
|
+
if (ref.error) return fail({ code: ref.error });
|
|
236
|
+
if (!parent && el.closest("[data-ewe-unavailable]")) return fail({ code: "UnavailableAction" });
|
|
237
|
+
const registry = this.deps.registry;
|
|
238
|
+
const entry = registry.lookup(ref.origin, ref.name, "web");
|
|
239
|
+
const scope = this.deps.scope ?? globalThis;
|
|
240
|
+
const webHost = entry.origin === "host" && entry.scope === "web";
|
|
241
|
+
const globalFn = webHost && Object.hasOwn(scope, ref.name) && scope[ref.name];
|
|
242
|
+
const page = entry.fn ?? (typeof globalFn === "function" ? globalFn : undefined);
|
|
243
|
+
const choice = route(ref, "web", registry.lookup.bind(registry), {
|
|
244
|
+
host: page ? true : !entry.page && !!this.deps.local, server: !!this.deps.server,
|
|
245
|
+
}, name => this.#advertised?.has(name));
|
|
246
|
+
if (choice.error) return fail({ code: choice.error });
|
|
247
|
+
if (payload !== undefined && choice.route === "server" && !this.#structured) {
|
|
248
|
+
return fail({ code: "UnsupportedAction", detail: "The peer did not negotiate structured input." });
|
|
249
|
+
}
|
|
250
|
+
const viewMount = parent ? parent.viewMount : this.deps.frames?.receivingView?.(el);
|
|
251
|
+
const callAction = async (name, value, preview) => {
|
|
252
|
+
if (value === undefined) throw Object.assign(new Error("Missing child input"), {code:"InvalidInput"});
|
|
253
|
+
if (preview?.length) await this.receive(preview, viewMount);
|
|
254
|
+
return this.#submit(name, viewMount ?? el, {}, "", value, true, {viewMount});
|
|
255
|
+
};
|
|
256
|
+
const root = el?.closest("[data-ewe-root]") ?? el;
|
|
257
|
+
if (!delivery) {
|
|
258
|
+
if (this.#busy.has(root)) return fail({ code: "Busy" });
|
|
259
|
+
claimed = root;
|
|
260
|
+
this.#busy.add(root);
|
|
261
|
+
}
|
|
262
|
+
if (choice.route === "host" && page) {
|
|
263
|
+
fault = "HostThrew";
|
|
264
|
+
const result = await page.call(el, { node: el, parent: el?.parentElement, event, callAction, data: payload === undefined ? ui.buildEventData(type, event, el) : payload });
|
|
265
|
+
for (const bytes of (Array.isArray(result) ? result : [result])) if (bytes instanceof Uint8Array) await this.receive(bytes, viewMount);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const state = parent ? null : stateBytes(el.getAttribute("primal::state"), this.limit);
|
|
269
|
+
if (this.#next > 0xffffffffffffffffn) throw new Error("Request sequence exhausted");
|
|
270
|
+
let json = null;
|
|
271
|
+
if (payload !== undefined) {
|
|
272
|
+
fault = "InvalidInput";
|
|
273
|
+
const encoded = JSON.stringify(payload);
|
|
274
|
+
if (encoded === undefined) throw new Error("The payload cannot be encoded as JSON.");
|
|
275
|
+
json = new TextEncoder().encode(encoded);
|
|
276
|
+
}
|
|
277
|
+
const bytes = encodeAction(choice.route + ":" + ref.name, parent ? null : el, event, type, state, this.streamId, this.#next, json);
|
|
278
|
+
if (bytes.length > this.limit) throw new Error("Request too large");
|
|
279
|
+
++this.#next;
|
|
280
|
+
fault = "Transport";
|
|
281
|
+
const transport = choice.route === "host" ? this.deps.local : this.deps.server;
|
|
282
|
+
let replies;
|
|
283
|
+
if (choice.route === "host") replies = await transport.send(bytes, callAction);
|
|
284
|
+
else if (parent && transport.sendChild) replies = await transport.sendChild(bytes);
|
|
285
|
+
else replies = await transport.send(bytes);
|
|
286
|
+
for (const reply of replies) {
|
|
287
|
+
await this.receive(reply, viewMount);
|
|
288
|
+
if (parent) checkChildReply(reply);
|
|
289
|
+
}
|
|
290
|
+
} catch (cause) {
|
|
291
|
+
if (parent) throw Object.assign(new Error(cause.message ?? String(cause)), {code: cause.code ?? fault});
|
|
292
|
+
this.onError({ code: fault, detail: String(cause) });
|
|
293
|
+
} finally {
|
|
294
|
+
if (claimed) this.#busy.delete(claimed);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function checkChildReply(bytes) {
|
|
300
|
+
const frame = wire.Frame.getRootAsFrame(new wire.ByteBuffer(bytes));
|
|
301
|
+
const body = frame.kind(new wire.FrameMessage());
|
|
302
|
+
for (let i = 0; i < body.messagesLength(); i++) {
|
|
303
|
+
const control = body.messages(i)?.control();
|
|
304
|
+
const error = control?.error();
|
|
305
|
+
const code = error ? wire.ErrorCode[error.code()] : control?.stateExpired() ? "StateExpired" :
|
|
306
|
+
control?.updateRequired() ? "UpdateRequired" : null;
|
|
307
|
+
if (code) throw Object.assign(new Error(error?.message() || code), {code});
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
export class FetchActionTransport {
|
|
312
|
+
constructor(options) { this.options = options; }
|
|
313
|
+
|
|
314
|
+
async send(bytes) {
|
|
315
|
+
const o = this.options;
|
|
316
|
+
const headers = { "content-type": "application/primal-frame", accept: "application/primal-frame", "x-ewe-action": "1" };
|
|
317
|
+
if (o.hello) headers["x-ewe-hello"] = base64urlEncode(await o.hello());
|
|
318
|
+
if (o.csrfToken) headers["x-csrf-token"] = o.csrfToken;
|
|
319
|
+
for (let attempt = 1; ; attempt++) {
|
|
320
|
+
try {
|
|
321
|
+
const response = await (o.fetch ?? globalThis.fetch)(o.url, {
|
|
322
|
+
method: "POST", credentials: "same-origin", headers, body: bytes, signal: o.requestSignal?.(),
|
|
323
|
+
});
|
|
324
|
+
if (response.status !== 200) {
|
|
325
|
+
await response.body?.cancel();
|
|
326
|
+
throw new Error("http " + response.status);
|
|
327
|
+
}
|
|
328
|
+
const limit = o.maxResponseBytes ?? 4 * 1024 * 1024;
|
|
329
|
+
const frames = [];
|
|
330
|
+
let total = 0;
|
|
331
|
+
for await (const frame of readFrames(response.body, limit)) {
|
|
332
|
+
total += frame.byteLength + 4;
|
|
333
|
+
if (total > limit) throw new Error("Action response too large");
|
|
334
|
+
frames.push(frame);
|
|
335
|
+
}
|
|
336
|
+
if (!frames.length) throw new Error("Empty action response");
|
|
337
|
+
return frames;
|
|
338
|
+
} catch (cause) {
|
|
339
|
+
if (!o.retry || !await o.retry(cause, attempt)) throw cause;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export class WebSocketActionTransport {
|
|
346
|
+
#children = new Map();
|
|
347
|
+
constructor(socket) { this.socket = socket; }
|
|
348
|
+
|
|
349
|
+
static connect(connections, endpoint, options = {}) {
|
|
350
|
+
const sender = new WebSocketActionTransport(null);
|
|
351
|
+
sender.requestTag = connections.nextTag();
|
|
352
|
+
sender.timeout = options.handshakeTimeoutMs ?? 60000;
|
|
353
|
+
sender.replyTimeout = options.replyTimeoutMs ?? sender.timeout;
|
|
354
|
+
sender.handle = connections.acquire({ ...options, endpoint, transport: "websocket" }, {
|
|
355
|
+
accept: bytes => {
|
|
356
|
+
const frame = wire.Frame.getRootAsFrame(new wire.ByteBuffer(bytes));
|
|
357
|
+
const body = frame.kindType() === wire.FrameKind.FrameMessage && frame.kind(new wire.FrameMessage());
|
|
358
|
+
if (!body) return false;
|
|
359
|
+
const caps = body.messagesLength() && body.messages(0)?.control()?.caps();
|
|
360
|
+
return caps ? caps.requestTag() === sender.requestTag : body.ack() !== 0n && frame.streamId() === sender.session;
|
|
361
|
+
},
|
|
362
|
+
receive: bytes => {
|
|
363
|
+
const frame = wire.Frame.getRootAsFrame(new wire.ByteBuffer(bytes));
|
|
364
|
+
const body = frame.kind(new wire.FrameMessage());
|
|
365
|
+
const caps = body.messagesLength() && body.messages(0)?.control()?.caps();
|
|
366
|
+
if (caps) {
|
|
367
|
+
sender.session = caps.status() === wire.CapsStatus.Ok ? caps.streamId() : null;
|
|
368
|
+
sender.pending?.resolve([bytes]);
|
|
369
|
+
} else {
|
|
370
|
+
const child = sender.#children.get(body.ack());
|
|
371
|
+
if (child) child.resolve([bytes]);
|
|
372
|
+
else sender.onReply?.(bytes);
|
|
373
|
+
}
|
|
374
|
+
},
|
|
375
|
+
onError: cause => {
|
|
376
|
+
sender.session = null;
|
|
377
|
+
sender.pending?.reject(cause);
|
|
378
|
+
sender.#failChildren(cause);
|
|
379
|
+
sender.onDisconnect?.(cause);
|
|
380
|
+
},
|
|
381
|
+
onOpen: () => sender.onOpen?.(),
|
|
382
|
+
});
|
|
383
|
+
return sender;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
async send(bytes) {
|
|
387
|
+
if (!this.handle) {
|
|
388
|
+
if (this.socket.readyState !== 1) throw new Error("Action socket is closed");
|
|
389
|
+
this.socket.send(bytes);
|
|
390
|
+
return [];
|
|
391
|
+
}
|
|
392
|
+
const frame = wire.Frame.getRootAsFrame(new wire.ByteBuffer(bytes));
|
|
393
|
+
const request = frame.kind(new wire.FrameRequest());
|
|
394
|
+
if (!request?.hello()) {
|
|
395
|
+
if (!this.session || frame.streamId() !== this.session) throw new Error("Action connection needs a handshake");
|
|
396
|
+
await this.handle.send(bytes);
|
|
397
|
+
return [];
|
|
398
|
+
}
|
|
399
|
+
if (this.pending) throw new Error("A capability request is already pending");
|
|
400
|
+
let timer;
|
|
401
|
+
try {
|
|
402
|
+
return await new Promise((resolve, reject) => {
|
|
403
|
+
this.pending = {resolve, reject};
|
|
404
|
+
timer = setTimeout(() => reject(new Error("Capability request timed out")), this.timeout);
|
|
405
|
+
this.handle.send(bytes).catch(reject);
|
|
406
|
+
});
|
|
407
|
+
} finally { clearTimeout(timer); this.pending = null; }
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Keep the reply with the view that submitted the child request. */
|
|
411
|
+
async sendChild(bytes) {
|
|
412
|
+
if (!this.handle) return this.send(bytes);
|
|
413
|
+
const frame = wire.Frame.getRootAsFrame(new wire.ByteBuffer(bytes));
|
|
414
|
+
const id = frame.sequenceId();
|
|
415
|
+
let timer;
|
|
416
|
+
try {
|
|
417
|
+
return await new Promise((resolve, reject) => {
|
|
418
|
+
this.#children.set(id, {resolve, reject});
|
|
419
|
+
timer = setTimeout(() => reject(new Error("Action reply timed out")), this.replyTimeout);
|
|
420
|
+
this.send(bytes).catch(reject);
|
|
421
|
+
});
|
|
422
|
+
} finally { clearTimeout(timer); this.#children.delete(id); }
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
#failChildren(cause) {
|
|
426
|
+
for (const child of this.#children.values()) child.reject(cause);
|
|
427
|
+
this.#children.clear();
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
close() {
|
|
431
|
+
this.#failChildren(new Error("Action socket closed"));
|
|
432
|
+
this.pending?.reject(new Error("Action socket closed"));
|
|
433
|
+
this.handle?.close();
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export class WasmActionTransport {
|
|
438
|
+
#pending = new Map();
|
|
439
|
+
#next = 1n;
|
|
440
|
+
#closed = false;
|
|
441
|
+
|
|
442
|
+
constructor(bridge) { this.bridge = bridge; }
|
|
443
|
+
|
|
444
|
+
/** Load a browser action module and run its exported host initializer. */
|
|
445
|
+
static async boot(loader, url, {registry, start, imports = {}, bindings, storage, window = globalThis.window}) {
|
|
446
|
+
const dom = new ui.DomHeap({window, document: window.document});
|
|
447
|
+
const decoder = new TextDecoder("utf-8", {fatal: true});
|
|
448
|
+
let local;
|
|
449
|
+
const previous = loader.environment;
|
|
450
|
+
// A factory scopes memory views and finalizers to this instance.
|
|
451
|
+
const glue = bindings?.createBindings();
|
|
452
|
+
loader.environment = {
|
|
453
|
+
...previous,
|
|
454
|
+
...(glue && {[bindings.importName]: glue}),
|
|
455
|
+
get abi() {
|
|
456
|
+
const runtime = loader.runtime;
|
|
457
|
+
return {...runtime.web_abi, ...ui.domAbi(runtime, dom), ...previous.abi};
|
|
458
|
+
},
|
|
459
|
+
env: {
|
|
460
|
+
...previous.env, ...imports, ...WasmActionTransport.imports(() => local),
|
|
461
|
+
ewe_ui_declare(origin, pointer, length, scope) {
|
|
462
|
+
const name = decoder.decode(new Uint8Array(loader.runtime.bridge.memory.buffer, pointer, length));
|
|
463
|
+
registry.declare([null, "host", "server"][origin], name, ["all", "web", "mobile"][scope]);
|
|
464
|
+
},
|
|
465
|
+
},
|
|
466
|
+
};
|
|
467
|
+
try {
|
|
468
|
+
await loader.loadURL(url);
|
|
469
|
+
const runtime = loader.runtime;
|
|
470
|
+
const api = loader.module.instance.exports;
|
|
471
|
+
if (glue) {
|
|
472
|
+
glue.__wbg_set_wasm(api);
|
|
473
|
+
api.__wbindgen_start?.();
|
|
474
|
+
}
|
|
475
|
+
if (storage && !glue?.configureHostStorage) throw new Error("Missing browser storage bindings");
|
|
476
|
+
glue?.configureHostStorage?.(storage?.provider ?? "memory", storage?.namespace ?? "");
|
|
477
|
+
if (typeof api[start] !== "function") throw new Error("Missing host initializer: " + start);
|
|
478
|
+
local = new WasmActionTransport({exports: api, memory: () => runtime.bridge.memory});
|
|
479
|
+
const status = api[start]();
|
|
480
|
+
if (status !== 0) throw new Error("Host initializer " + start + " returned " + status);
|
|
481
|
+
await glue?.prepareBrowserHost?.();
|
|
482
|
+
return local;
|
|
483
|
+
} catch (error) {
|
|
484
|
+
try { local?.close(); } finally { loader.runtime.dispose(); }
|
|
485
|
+
throw error;
|
|
486
|
+
} finally {
|
|
487
|
+
loader.environment = previous;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/** Install these imports before the module starts. */
|
|
492
|
+
static imports(transport) {
|
|
493
|
+
return {
|
|
494
|
+
ewe_ui_action_done: (call, slot) => transport().complete(call, slot),
|
|
495
|
+
ewe_ui_child: (...args) => transport().#startChild(...args),
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
#startChild(parent, child, namePtr, nameLen, jsonPtr, jsonLen, previewPtr, previewLen) {
|
|
500
|
+
const api = this.bridge.exports;
|
|
501
|
+
const memory = this.bridge.memory().buffer;
|
|
502
|
+
const read = (ptr, len) => new Uint8Array(memory, ptr, len);
|
|
503
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
504
|
+
const run = async () => {
|
|
505
|
+
const callAction = this.#pending.get(parent)?.callAction;
|
|
506
|
+
if (!callAction) throw Object.assign(new Error("The parent action closed"), {code:"UnavailableOrigin"});
|
|
507
|
+
const name = decoder.decode(read(namePtr, nameLen));
|
|
508
|
+
const value = JSON.parse(decoder.decode(read(jsonPtr, jsonLen)));
|
|
509
|
+
await callAction(name, value, read(previewPtr, previewLen).slice());
|
|
510
|
+
};
|
|
511
|
+
run().then(() => {
|
|
512
|
+
if (!this.#closed) api.ewe_ui_child_done(child, -1, 0n);
|
|
513
|
+
}, cause => {
|
|
514
|
+
if (this.#closed) return;
|
|
515
|
+
let slot = -1n;
|
|
516
|
+
try {
|
|
517
|
+
const bytes = new TextEncoder().encode(cause?.message ?? String(cause));
|
|
518
|
+
slot = api.create_allocation(BigInt(bytes.length));
|
|
519
|
+
const pointer = Number(api.allocation_start_pointer(slot));
|
|
520
|
+
new Uint8Array(this.bridge.memory().buffer, pointer, bytes.length).set(bytes);
|
|
521
|
+
} catch {
|
|
522
|
+
if (slot !== -1n) api.dispose_allocation(slot);
|
|
523
|
+
slot = -1n;
|
|
524
|
+
}
|
|
525
|
+
api.ewe_ui_child_done(child, wire.ErrorCode[cause?.code] ?? wire.ErrorCode.ActionFailed, slot);
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
send(bytes, callAction) {
|
|
530
|
+
return new Promise((resolve, reject) => {
|
|
531
|
+
if (this.#closed) throw new Error("Action bridge is closed");
|
|
532
|
+
const call = this.#next++;
|
|
533
|
+
const api = this.bridge.exports;
|
|
534
|
+
const slot = api.create_allocation(BigInt(bytes.length));
|
|
535
|
+
this.#pending.set(call, { resolve, reject, callAction });
|
|
536
|
+
let handedOff = false;
|
|
537
|
+
try {
|
|
538
|
+
const ptr = Number(api.allocation_start_pointer(slot));
|
|
539
|
+
new Uint8Array(this.bridge.memory().buffer, ptr, bytes.length).set(bytes);
|
|
540
|
+
const status = api.ewe_ui_action(call, slot);
|
|
541
|
+
handedOff = true;
|
|
542
|
+
if (status !== 0) throw new Error("Action start failed: " + status);
|
|
543
|
+
} catch (cause) {
|
|
544
|
+
this.#pending.delete(call);
|
|
545
|
+
if (!handedOff) api.dispose_allocation(slot);
|
|
546
|
+
reject(cause);
|
|
547
|
+
}
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
complete(call, slot) {
|
|
552
|
+
const pending = this.#pending.get(call);
|
|
553
|
+
this.#pending.delete(call);
|
|
554
|
+
if (BigInt.asUintN(64, slot) === 0xffffffffffffffffn) { pending?.reject(new Error("Action task failed")); return; }
|
|
555
|
+
const api = this.bridge.exports;
|
|
556
|
+
try {
|
|
557
|
+
if (pending) {
|
|
558
|
+
const bytes = new Uint8Array(this.bridge.memory().buffer, Number(api.allocation_start_pointer(slot)), Number(api.allocation_length(slot))).slice();
|
|
559
|
+
pending.resolve([bytes]);
|
|
560
|
+
}
|
|
561
|
+
} catch (cause) { pending?.reject(cause); }
|
|
562
|
+
finally { api.dispose_allocation(slot); }
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
close() {
|
|
566
|
+
this.#closed = true;
|
|
567
|
+
for (const pending of this.#pending.values()) pending.reject(new Error("Action bridge closed"));
|
|
568
|
+
this.#pending.clear();
|
|
569
|
+
this.bridge.exports.ewe_ui_actions_close?.();
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const installations = new WeakMap();
|
|
574
|
+
|
|
575
|
+
export function installActionRuntime(wasmUi, deps) {
|
|
576
|
+
const runtime = wasmUi.Patcher.runtime;
|
|
577
|
+
installations.get(runtime)?.();
|
|
578
|
+
const manager = new WebActionManager(deps);
|
|
579
|
+
const trigger = manager.trigger.bind(manager);
|
|
580
|
+
wasmUi.EventDispatcher.actionHook = trigger;
|
|
581
|
+
const extensions = wasmUi.Hydrator.scopeExtensions;
|
|
582
|
+
const extend = (scope, owner) => {
|
|
583
|
+
scope.action = (name, fn) => deps.registry.registerHost(name, fn, owner);
|
|
584
|
+
scope.behaviour = (name, fn) => deps.behaviours.registerWebBehaviour(name, fn);
|
|
585
|
+
};
|
|
586
|
+
extensions.push(extend);
|
|
587
|
+
manager.dispose = () => {
|
|
588
|
+
if (installations.get(runtime) !== manager.dispose) return;
|
|
589
|
+
installations.delete(runtime);
|
|
590
|
+
manager.detachControls?.();
|
|
591
|
+
if (wasmUi.EventDispatcher.actionHook === trigger) wasmUi.EventDispatcher.actionHook = null;
|
|
592
|
+
const i = extensions.indexOf(extend);
|
|
593
|
+
if (i >= 0) extensions.splice(i, 1);
|
|
594
|
+
};
|
|
595
|
+
installations.set(runtime, manager.dispose);
|
|
596
|
+
const doc = deps.document ?? globalThis.document;
|
|
597
|
+
if (doc && !runtime.dispatcher) {
|
|
598
|
+
runtime.dispatcher = new wasmUi.EventDispatcher(id => manager.onError({code: "UnavailableOrigin", detail: "No local callback " + id}),
|
|
599
|
+
{scope: deps.scope});
|
|
600
|
+
wasmUi.initEventRuntime(runtime.dispatcher, doc);
|
|
601
|
+
} else if (doc?.body) {
|
|
602
|
+
runtime.dispatcher.scanAndWire(doc.body);
|
|
603
|
+
}
|
|
604
|
+
return manager;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
const activeApps = new WeakSet();
|
|
609
|
+
|
|
610
|
+
/** Start the configured view once. A failed start releases its resources and permits retry. */
|
|
611
|
+
export function createApp(options) {
|
|
612
|
+
let flight;
|
|
613
|
+
const cleanup = [];
|
|
614
|
+
function dispose() {
|
|
615
|
+
const errors = [];
|
|
616
|
+
while (cleanup.length) {
|
|
617
|
+
try { cleanup.pop()(); } catch (error) { errors.push(error); }
|
|
618
|
+
}
|
|
619
|
+
flight = undefined;
|
|
620
|
+
if (errors.length) throw new AggregateError(errors, "Browser app cleanup failed");
|
|
621
|
+
}
|
|
622
|
+
async function start() {
|
|
623
|
+
const {mount, moduleLoader, onError = console.error} = options;
|
|
624
|
+
const doc = mount.ownerDocument;
|
|
625
|
+
const registry = new JsActionRegistry();
|
|
626
|
+
const local = await WasmActionTransport.boot(moduleLoader, options.moduleUrl, {
|
|
627
|
+
registry, start: options.start, imports: options.imports, window: doc.defaultView,
|
|
628
|
+
bindings: options.bindings, storage: options.storage,
|
|
629
|
+
});
|
|
630
|
+
cleanup.push(() => moduleLoader.runtime.dispose(), () => local.close());
|
|
631
|
+
const runtime = ui.Patcher.runtime;
|
|
632
|
+
const connections = ui.frameConnections();
|
|
633
|
+
cleanup.push(() => connections.close());
|
|
634
|
+
const previous = {
|
|
635
|
+
dispatcher: runtime.dispatcher, frames: runtime.frames, connections: runtime.connections,
|
|
636
|
+
onMountConnect: runtime.onMountConnect,
|
|
637
|
+
};
|
|
638
|
+
const previousHook = ui.ProtocolHandler.frameHook;
|
|
639
|
+
cleanup.push(() => {
|
|
640
|
+
Object.assign(runtime, previous);
|
|
641
|
+
ui.ProtocolHandler.frameHook = previousHook;
|
|
642
|
+
});
|
|
643
|
+
runtime.frames = null;
|
|
644
|
+
runtime.dispatcher = new ui.EventDispatcher(() => {});
|
|
645
|
+
const frames = installFrameRuntime(ui, {document: doc, connections, onReport: onError, viewMount: mount});
|
|
646
|
+
ui.registerWebComponents();
|
|
647
|
+
cleanup.push(frames.registerView(options.view, mount));
|
|
648
|
+
let manager;
|
|
649
|
+
const server = typeof options.transport === "function" ? await options.transport()
|
|
650
|
+
: options.transport?.socket ? WebSocketActionTransport.connect(connections, options.transport.socket)
|
|
651
|
+
: new FetchActionTransport({url: options.transport?.http ?? "/action", hello: () => manager.hello()});
|
|
652
|
+
cleanup.push(() => server.close?.());
|
|
653
|
+
manager = installActionRuntime(ui, {registry, frames, server, local, behaviours, document: doc, onError});
|
|
654
|
+
cleanup.push(manager.dispose);
|
|
655
|
+
let initialDeliveries = [];
|
|
656
|
+
if (options.viewDataAction) {
|
|
657
|
+
const receive = event => {
|
|
658
|
+
const delivery = manager.deliverViewData(options.viewDataAction, event.target, event.detail.bytes);
|
|
659
|
+
if (initialDeliveries) initialDeliveries.push(delivery);
|
|
660
|
+
else delivery.catch(onError);
|
|
661
|
+
};
|
|
662
|
+
mount.addEventListener("ewe:data", receive);
|
|
663
|
+
cleanup.push(() => mount.removeEventListener("ewe:data", receive));
|
|
664
|
+
}
|
|
665
|
+
for (const bytes of await server.send(manager.hello())) await manager.receive(bytes);
|
|
666
|
+
const view = frames.registerLoader(mount, async signal => {
|
|
667
|
+
const response = await fetch(options.initialRoute, {
|
|
668
|
+
signal, headers: {"X-Ewe-Hello": base64urlEncode(manager.hello())},
|
|
669
|
+
});
|
|
670
|
+
return readViewResponse(response, frames.maxFrameBytes);
|
|
671
|
+
}, {onError: error => onError({code: "ViewRecovery", detail: error.message})});
|
|
672
|
+
await view.open();
|
|
673
|
+
const deliveries = initialDeliveries;
|
|
674
|
+
initialDeliveries = null;
|
|
675
|
+
await Promise.all(deliveries);
|
|
676
|
+
frames.flush();
|
|
677
|
+
return manager;
|
|
678
|
+
}
|
|
679
|
+
return {
|
|
680
|
+
boot() {
|
|
681
|
+
if (!flight && activeApps.has(ui.Patcher.runtime)) {
|
|
682
|
+
return Promise.reject(new Error("This browser action runtime already has an application"));
|
|
683
|
+
}
|
|
684
|
+
if (!flight) {
|
|
685
|
+
activeApps.add(ui.Patcher.runtime);
|
|
686
|
+
cleanup.push(() => activeApps.delete(ui.Patcher.runtime));
|
|
687
|
+
flight = start().catch(error => { dispose(); throw error; });
|
|
688
|
+
}
|
|
689
|
+
return flight;
|
|
690
|
+
},
|
|
691
|
+
async close() {
|
|
692
|
+
const pending = flight;
|
|
693
|
+
if (pending) {
|
|
694
|
+
try { await pending; } finally { if (flight === pending) dispose(); }
|
|
695
|
+
}
|
|
696
|
+
},
|
|
697
|
+
};
|
|
698
|
+
}
|