// The generator's emitter for `web/`: a contract → `.gen.ts`, everything of the web half that is // not the plugin's own work (docs/plans/plugins-plan.md in core) — the twin of emitSwift.ts and // emitKotlin.ts, over the same lowered model: // - the contract's types, as the half reads and writes them; // - `Code` + `Error`: the codes the channel rejects with, thrown; // - `Events`: one function per event; // - `Plugin`: the INTERFACE the half implements — one method per call, a value or a promise; // - `register(host, make)` + the glue that reads a call's arguments, refuses a malformed one // and hands the call over. // A HOST NODE (docs/plans/host-node-plan.md in core) has its own shape (emitNode below), the twin of // the native `NodeInstance` + `NodeGlue`: `NodeEvents` (a class, one method per // event), `NodeHalf` (the half's interface: `el`, an optional setter per prop and per listed // style, the methods, `destroy`; no measure — the DOM sizes the node's box, the half gives `el` its // natural size with CSS), `NodeGlue` (what the host calls: `setProperty(half, name, text)` // decodes a prop's WIRE TEXT as the Swift / Kotlin glue does, `setStyle(half, name, value)`, // `call(half, method, args)`) and `registerNode(host, make)` over `host.registerNode`. A method // named like a prop's setter (`setStops` of `stops`) that takes the prop's value alone IS that // setter: one member of the half. // // The wire carries VALUES, and on the web the app's own: a Uint8Array crosses as it is, a File as the // handle of a host buffer. // // The file imports NOTHING. A web half depends on its generated file, on the document it is handed // and on the browser — which is what lets another host (web-lite) and a prebuilt third-party module // take the same half. What the host is asked for is a SHAPE (`PluginHost`), declared in the file. import { EmitError } from "./emitSdk" import { channelLabel, propAsText, reachesKind, waysOf, type L, type LChannel, type LDecl, type LEvent, type LField, type LNode, type Lowered, type Ways } from "./lower" const str = (value: string): string => JSON.stringify(value) const key = (name: string): string => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? name : str(name) const at = (o: string, name: string): string => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name) ? `${o}.${name}` : `${o}[${str(name)}]` const doc = (text: string, indent = ""): string => { if (!text) return "" const lines = text.split("\n").map(l => l.trim()) if (lines.length === 1) return `${indent}/** ${lines[0]} */\n` return `${indent}/** ${lines[0]}\n${lines.slice(1).map(l => `${indent} * ${l}`.trimEnd()).join("\n")} */\n` } /** A type as the half names it. An optional that is not a member's or an argument's is a null. */ export const webType = (t: L): string => { switch (t.kind) { case "i32": case "f64": return "number" case "boolean": return "boolean" case "string": return "string" case "json": return "Json" case "file": return "PluginFile" case "entity": return "Entity" case "scene3d": return "Scene3D" case "bytes": return "Uint8Array" case "void": return "void" case "enum": case "struct": case "union": return t.name case "list": return `${t.of.kind === "optional" ? `(${webType(t.of)})` : webType(t.of)}[]` case "map": return `{ [key: string]: ${webType(t.of)} }` case "optional": return `${webType(t.of)} | null` case "tuple": return `[${t.of.map(webType).join(", ")}]` } } /** A member or an argument: left out (`name?: T`) or null (`name: T | null`). */ const member = (name: string, type: L, omit: boolean): string => type.kind === "optional" && omit ? `${key(name)}?: ${webType(type.of)}` : `${key(name)}: ${webType(type)}` /** The expression of type `T | undefined` that reads the wire's value `e`: undefined = it is not a T. */ const decode = (t: L, e: string, depth = 0): string => { const v = `v${depth}` switch (t.kind) { case "i32": return `wire.i32(${e})` case "f64": return `wire.f64(${e})` case "boolean": return `wire.bool(${e})` case "string": return `wire.string(${e})` case "json": return `wire.json(${e})` case "bytes": return `wire.bytes(${e})` case "file": return `readFile(${e})` case "entity": case "scene3d": return `readId(${e})` case "enum": case "struct": case "union": return `read${t.name}(${e})` case "list": return `wire.list(${e}, (${v}) => ${decode(t.of, v, depth + 1)})` case "map": return `wire.map(${e}, (${v}) => ${decode(t.of, v, depth + 1)})` // Absent and null are one thing on the wire: a null here. case "optional": return `(wire.present(${e}) ? ${decode(t.of, e, depth)} : null)` case "tuple": { const parts = t.of.map((m, i) => `const ${v}_${i} = ${decode(m, `${v}[${i}]`, depth + 1)}; if (${v}_${i} === undefined) return undefined`) return `((${v}): ${webType(t)} | undefined => { if (!${v}) return undefined; ${parts.join("; ")}; return [${t.of.map((_, i) => `${v}_${i}`).join(", ")}] })(wire.array(${e}, ${t.of.length}))` } case "void": throw new EmitError("void has no value to read") } } export type WebEmitOptions = { id: string } export const emitWeb = (lowered: Lowered, opts: WebEmitOptions): string => { const byName = new Map(lowered.decls.map(d => [d.name, d])) const ways: Ways = waysOf(lowered) // An enum a host node's prop crosses as TEXT is read from that text by its own reader (the // native glue's `rawValue:`): the reader is written though the wire never carries it as a value. const readAsText = new Set() for (const ch of lowered.channels) for (const p of ch.node?.props ?? []) { const inner = p.type.kind === "optional" ? p.type.of : p.type if (inner.kind === "enum") readAsText.add(inner.name) } /** Does a value of this type hold a File anywhere? Only such a value is rewritten on its way out: * everything else — a Uint8Array too — leaves as the half made it, and the app gets that value. */ const carriesFile = (t: L, seen = new Set()): boolean => { switch (t.kind) { case "file": return true case "list": case "map": case "optional": return carriesFile(t.of, seen) case "tuple": return t.of.some(m => carriesFile(m, seen)) case "struct": case "union": { if (seen.has(t.name)) return false seen.add(t.name) const d = byName.get(t.name)! if (d.kind === "struct") return d.fields.some(f => carriesFile(f.type, seen)) if (d.kind === "union") return d.members.some(m => carriesFile(m, seen)) return false } default: return false } } /** The expression that writes the value `e` to the wire; `host` = the expression of the host a * File is stored with. */ const encode = (t: L, e: string, depth = 0, host = "host"): string => { if (!carriesFile(t)) return e const v = `v${depth}` switch (t.kind) { case "file": return `writeFile(${host}, ${e})` case "struct": return `write${t.name}(${host}, ${e})` case "list": return `${e}.map((${v}) => ${encode(t.of, v, depth + 1, host)})` case "map": return `Object.fromEntries(Object.entries(${e}).map(([k, ${v}]) => [k, ${encode(t.of, v, depth + 1, host)}]))` case "tuple": return `[${t.of.map((m, i) => encode(m, `${e}[${i}]`, depth + 1, host)).join(", ")}]` case "optional": return `(${e} == null ? null : ${encode(t.of, e, depth, host)})` // A union is told apart by what its members are on the wire; a File among them is not a thing // the lowering lets through. default: throw new EmitError(`a File inside a ${t.kind} is not written by this generator`) } } /** An event's payload as the half hands it over; null for one without. */ const payloadOf = (e: LEvent): string | null => e.inline ? `{ ${e.inline.map(f => member(f.name, f.type, f.omit)).join(", ")} }` : e.payload.kind === "void" ? null : webType(e.payload) // A payload that holds a File is rewritten on its way out, like a result. const written = (e: LEvent, host = "host"): string => { if (e.inline) { const files = e.inline.filter(f => carriesFile(f.type)) if (!files.length) return "payload" return `{ ...payload, ${files.map(f => { const from = at("payload", f.name) return f.type.kind === "optional" && f.omit ? `...(${from} === undefined ? {} : { ${key(f.name)}: ${encode(f.type.of, from, 0, host)} })` : `${key(f.name)}: ${encode(f.type, from, 0, host)}` }).join(", ")} }` } return encode(e.payload, "payload", 0, host) } /** The cases of a channel's `call`: each reads its arguments off the wire, refuses a malformed one * and hands the call to `target` (the half); `host` is what a File it returns is stored with. */ const callCases = (ch: LChannel, iface: string, target: string, indent: string, host = "host"): string[] => ch.methods.map(m => { const lines: string[] = [`${indent}case ${str(m.name)}: {`] m.args.forEach((a, i) => { const bad = `throw new Error(${str(`bad arguments — ${iface}.${m.name}: ${a.name}`)})` if (a.type.kind !== "optional") { lines.push(`${indent} const a${i} = ${decode(a.type, `args[${i}]`)}`) lines.push(`${indent} if (a${i} === undefined) ${bad}`) } else { const none = a.omit ? "undefined" : "null" lines.push(`${indent} let a${i}: ${webType(a.type.of)} | ${none} = ${none}`) lines.push(`${indent} if (wire.present(args[${i}])) {\n${indent} const r = ${decode(a.type.of, `args[${i}]`)}\n${indent} if (r === undefined) ${bad}\n${indent} a${i} = r\n${indent} }`) } }) const call = `${target}.${m.name}(${m.args.map((_, i) => `a${i}`).join(", ")})` if (m.result.kind === "void") lines.push(`${indent} await ${call}\n${indent} return undefined`) else if (!carriesFile(m.result)) lines.push(`${indent} return await ${call}`) else lines.push(`${indent} const r = await ${call}\n${indent} return ${encode(m.result, "r", 0, host)}`) lines.push(`${indent}}`) return lines.join("\n") }) const emitDecl = (d: LDecl): string => { const read = ways.read.has(d.name) || readAsText.has(d.name) const write = ways.write.has(d.name) && carriesFile({ kind: d.kind, name: d.name } as L) if (d.kind === "enum") { const values = d.values.map(str) return [ doc(d.doc), `export type ${d.name} = ${values.join(" | ")}\n`, read ? `const read${d.name} = (v: unknown): ${d.name} | undefined =>\n ${values.map(x => `v === ${x}`).join(" || ")} ? v : undefined\n` : "", ].join("") } if (d.kind === "union") { return [ doc(d.doc), `export type ${d.name} = ${d.members.map(webType).join(" | ")}\n`, read ? `const read${d.name} = (v: unknown): ${d.name} | undefined =>\n ${d.members.map(m => decode(m, "v", 1)).join(" ?? ")}\n` : "", ].join("") } const members = d.fields.map(f => `${doc(f.doc, " ")} ${member(f.name, f.type, f.omit)}`) const reads = !read ? [] : d.fields.map((f, i) => { const from = at("o", f.name) if (f.type.kind !== "optional") return ` const f${i} = ${decode(f.type, from)}\n if (f${i} === undefined) return undefined` // An optional member that IS there must read: a wrong type is a malformed value, not an absent one. const inner = decode(f.type.of, from) return ` let f${i}: ${webType(f.type.of)} | ${f.omit ? "undefined" : "null"} = ${f.omit ? "undefined" : "null"}\n if (wire.present(${from})) {\n const r = ${inner}\n if (r === undefined) return undefined\n f${i} = r\n }` }) const required = d.fields.map((f, i) => ({ f, i })).filter(({ f }) => !(f.type.kind === "optional" && f.omit)) const left = d.fields.map((f, i) => ({ f, i })).filter(({ f }) => f.type.kind === "optional" && f.omit) const reader = !read ? "" : d.fields.length === 0 ? `const read${d.name} = (v: unknown): ${d.name} | undefined => !wire.present(v) || wire.object(v) ? {} : undefined\n` : [ `const read${d.name} = (v: unknown): ${d.name} | undefined => {\n const o = wire.object(v)\n if (!o) return undefined\n`, reads.join("\n") + "\n", ` const out: ${d.name} = ${required.length ? `{ ${required.map(({ f, i }) => `${key(f.name)}: f${i}`).join(", ")} }` : "{}"}\n`, left.map(({ f, i }) => ` if (f${i} !== undefined) ${at("out", f.name)} = f${i}\n`).join(""), ` return out\n}\n`, ].join("") const writer = !write ? "" : [ `const write${d.name} = (host: PluginHost, v: ${d.name}): unknown => ({\n ...v,\n`, d.fields.filter(f => carriesFile(f.type)).map(f => { const from = at("v", f.name) return f.type.kind === "optional" && f.omit ? ` ...(${from} === undefined ? {} : { ${key(f.name)}: ${encode(f.type.of, from)} }),\n` : ` ${key(f.name)}: ${encode(f.type, from)},\n` }).join(""), `})\n`, ].join("") return [ doc(d.doc), `export interface ${d.name} {${members.length ? "\n" + members.join("\n") + "\n" : ""}}\n`, reader, writer, ].join("") } const emitChannel = (ch: LChannel): string => { if (ch.node) return emitNode(ch, ch.node) const isView = ch.kind === "view" const iface = ch.iface const out: string[] = [] if (ch.codes.length) { out.push([ `/** The codes the calls of "${ch.name}" reject with. */\n`, `export type ${iface}Code = ${ch.codes.map(str).join(" | ")}\n\n`, `/** What a call throws to reject with a code of the contract — the app's promise rejects with it\n * as the message. Any other error is a message the contract has no code for. */\n`, `export class ${iface}Error extends Error {\n constructor(readonly code: ${iface}Code) { super(code) }\n}\n`, ].join("")) } // ---- events ---- const events = ch.events.map(e => { const payload = payloadOf(e) return `${doc(e.doc, " ")} ${key(e.name)}(${payload === null ? "" : `payload: ${payload}`}): void` }) out.push(`/** The events of "${ch.name}": what the half sends the app. */\nexport interface ${iface}Events {${events.length ? "\n" + events.join("\n") + "\n" : ""}}\n`) // ---- the interface ---- const signatures = ch.methods.map(m => { const args = m.args.map(a => member(a.name, a.type, a.omit)) const result = webType(m.result) const tags = [m.doc, m.rejects.length ? `Rejects with ${m.rejects.map(str).join(" / ")}.` : ""].filter(Boolean).join("\n") return `${doc(tags, " ")} ${m.name}(${args.join(", ")}): ${result} | Promise<${result}>` }) // A `@lazy` event: the half is told of its listeners, and the event it sends while there is none // goes nowhere (the glue below). const lazy = ch.events.filter(e => e.lazy) for (const e of lazy) { signatures.push(`${doc(`The app began (true) or stopped (false) listening to \`${e.name}\`, a \`@lazy\` event: start or stop what\nproduces it. Not called at the end — \`${isView ? "destroy()" : "close()"}\` stops everything.`, " ")} ${e.name}Observed(observed: boolean): void`) } out.push([ doc(ch.doc || `The ${ch.kind} "${ch.name}".`).replace(/ \*\/\n$/, `\n *\n * What the half implements. A call returns its result, or a promise of it; it rejects by throwing. */\n`), `export interface ${iface}Plugin {\n`, isView ? ` /** The element the host mounts. The half fills it and follows its size itself. */\n readonly el: HTMLElement\n` : "", signatures.length ? signatures.join("\n") + "\n" : "", isView ? ` /** The instance goes (the world swapped): release the hardware. */\n destroy?(): void\n` : ` /** The session closed (the app's close, the world's teardown): stop what it started. */\n close?(): void\n`, `}\n`, ].join("")) // ---- registration + the glue ---- const cases = callCases(ch, ch.iface, "plugin", " ") const emitters = ch.events.map(e => { const emit = `channel.emit(${str(e.name)}${payloadOf(e) === null ? "" : `, ${written(e)}`})` return ` ${key(e.name)}: (${payloadOf(e) === null ? "" : "payload"}) => ${e.lazy ? `{ if (observed.has(${str(e.name)})) ${emit} }` : emit},` }) // `$listen(event, on)`, the wrapper's own call: the app began or stopped listening to a @lazy event. if (lazy.length) { cases.push([ ` case "$listen": {`, ` const event = ${decode({ kind: "string" }, "args[0]")}`, ` const on = ${decode({ kind: "boolean" }, "args[1]")}`, ` if (event === undefined || on === undefined) throw new Error("bad arguments — $listen")`, ` if (observed.has(event) === on) return undefined`, ` switch (event) {`, ...lazy.map(e => ` case ${str(e.name)}: if (on) observed.add(event); else observed.delete(event); plugin.${e.name}Observed(on); break`), ` default: throw new Error(\`Unknown event: \${event}\`)`, ` }`, ` return undefined`, ` }`, ].join("\n")) } const params = `read${ch.params}(params) ?? {}` out.push([ `export const ${iface}Channel = {\n /** What the halves register under. */\n name: ${str(ch.name)},\n /** The contract's version: the highest \`@since\` of its members. */\n version: ${ch.version},\n} as const\n\n`, isView ? `/** Register the view: \`make\` builds one instance from its params, in the document it is handed. */\n` : `/** Register the service: \`make\` builds one session from its params. It must be cheap — no prompt,\n * no I/O: that belongs to the first call that needs it. */\n`, `export const register${iface} = (host: PluginHost, make: (params: ${ch.params}, events: ${iface}Events${isView ? ", doc: Document" : ""}) => ${iface}Plugin): void => {\n`, `__BUFFERS__`, ` host.register${isView ? "View" : "Service"}(${iface}Channel.name, (params, channel${isView ? ", doc" : ""}) => {\n`, lazy.length ? ` /** The @lazy events the app listens to. */\n const observed = new Set()\n` : "", ` const events: ${iface}Events = {${emitters.length ? "\n" + emitters.join("\n") + "\n " : ""}}\n`, ` const plugin = make(${params}, events${isView ? ", doc" : ""})\n`, // Reads a call off the wire and hands it to the half; a malformed call never reaches it. ` const call = async (method: string, args: unknown[]): Promise => {\n switch (method) {\n`, cases.length ? cases.join("\n") + "\n" : "", ` default: throw new Error(\`Unknown method: \${method}\`)\n }\n }\n`, isView ? ` return { el: plugin.el, call, destroy: () => plugin.destroy?.() }\n` : ` return { call, close: () => plugin.close?.() }\n`, ` }, ${iface}Channel.version)\n}\n`, ].join("")) return out.join("\n") } /** A host node (docs/plans/host-node-plan.md in core): the events it sends, the half's interface * (a setter per prop and per listed style, the methods; no measure — the DOM sizes the node's * box) and the glue the host calls with what the holder (web-lite's `hostnode` feature) hands * over by name: a prop's wire text, a resolved style, a call. */ const emitNode = (ch: LChannel, node: LNode): string => { const base = `${ch.iface}Node` const kind = str(ch.name) const out: string[] = [] if (ch.codes.length) { out.push([ `/** The codes the calls of the host node "${ch.name}" reject with. */\n`, `export type ${base}Code = ${ch.codes.map(str).join(" | ")}\n\n`, `/** What a call throws to reject with a code of the contract — the app's promise rejects with it\n * as the message. Any other error is a message the contract has no code for. */\n`, `export class ${base}Error extends Error {\n constructor(readonly code: ${base}Code) { super(code) }\n}\n`, ].join("")) } // ---- the setters: a prop's, a style's — and a method named like a prop's setter IS that setter ---- const methods = new Map(ch.methods.map(m => [m.name, m])) const strip = (t: L): L => t.kind === "optional" ? t.of : t const setterOf = (p: LField): string => `set${p.name.charAt(0).toUpperCase()}${p.name.slice(1)}` /** The prop a method is the setter of (`setStops(stops)` of `stops`), by the method's name. */ const merged = new Map() for (const p of node.props) { const m = methods.get(setterOf(p)) if (!m) continue if (m.args.length !== 1 || JSON.stringify(strip(m.args[0]!.type)) !== JSON.stringify(strip(p.type))) { throw new EmitError(`${ch.iface}.${p.name}: the half's setter of the prop is "${setterOf(p)}", a method of the node that takes other arguments — a method of that name takes the prop's value alone (it is the setter then), or is named otherwise`) } merged.set(m.name, p) } const styleSetter = (name: string): string => `setStyle${name.charAt(0).toUpperCase()}${name.slice(1)}` for (const s of node.styles) { const taken = methods.has(styleSetter(s.name)) || node.props.some(p => setterOf(p) === styleSetter(s.name)) if (taken) throw new EmitError(`${ch.iface}: "${styleSetter(s.name)}" is the half's setter of the style "${s.name}" — a method or a prop of the node may not take that name`) } // ---- events ---- const files = ch.events.some(e => written(e, "nodeHost!") !== "payload") const events = ch.events.map(e => { const payload = payloadOf(e) return `${doc(e.doc, " ")} ${key(e.name)}(${payload === null ? "" : `payload: ${payload}`}): void { this.#channel.emit(${str(e.name)}${payload === null ? "" : `, ${written(e, "nodeHost!")}`}) }` }) out.push([ `/** The events of the host node "${ch.name}": what the half sends the app. */\n`, `export class ${base}Events {\n readonly #channel: PluginChannel\n /** Made by \`register${base}\`, one per node. */\n constructor(channel: PluginChannel) { this.#channel = channel }\n`, events.length ? "\n" + events.join("\n") + "\n" : "", `}\n`, ].join("")) // ---- the half's interface ---- const propSetters = node.props.filter(p => !methods.has(setterOf(p))).map(p => { const optional = p.type.kind === "optional" const tags = [p.doc, optional ? "`undefined`: the app cleared it." : ""].filter(Boolean).join("\n") return `${doc(tags, " ")} ${setterOf(p)}?(value: ${webType(strip(p.type))}${optional ? " | undefined" : ""}): void` }) const styleSetters = node.styles.map(s => ` /** The style \`${s.name}\`, as the core resolved it — ${s.kind === "color" ? "a CSS color (`rgb(…)`)" : "a number (a length in px)"}; \`undefined\` when none is set. */\n` + ` ${styleSetter(s.name)}?(value: ${s.kind === "color" ? "string" : "number"} | undefined): void`) const signatures = ch.methods.map(m => { const prop = merged.get(m.name) const args = m.args.map((a, i) => { const text = member(a.name, a.type, a.omit) // the prop's setter too: a cleared prop arrives as undefined return prop && i === 0 && prop.type.kind === "optional" && !a.omit ? `${text} | undefined` : text }) const result = webType(m.result) const tags = [ m.doc, m.rejects.length ? `Rejects with ${m.rejects.map(str).join(" / ")}.` : "", prop ? `Also the setter of \`${prop.name}\`: a write of the prop calls it${prop.type.kind === "optional" ? " (\`undefined\`: cleared)" : ""}.` : "", ].filter(Boolean).join("\n") return `${doc(tags, " ")} ${m.name}(${args.join(", ")}): ${result} | Promise<${result}>` }) const sections = [propSetters, styleSetters, signatures].filter(x => x.length).map(x => x.join("\n")) out.push([ doc(ch.doc || `The host node "${ch.name}".`).replace(/ \*\/\n$/, [ `\n *\n * What the half implements: one per node of the kind, made when the SDK creates the node, in the`, ` * document it is handed. \`el\` is mounted in the node's box, which the core lays out and paints`, ` * like any node's: its size, its radius, opacity, transform and shadow${node.paintsSelf ? " (its background is the half's)" : ", its background"}.`, ` * The DOM sizes the box: one the app gives no size takes \`el\`'s natural size, which the half`, ` * gives it with CSS. A setter is optional: a half implements the props and the styles it reads.`, ` * A call returns its result, or a promise of it; it rejects by throwing. */\n`, ].join("\n")), `export interface ${base}Half {\n`, ` /** The element mounted in the node's box: it fills the box (100% × 100%) unless its own CSS sizes it. */\n readonly el: HTMLElement\n`, sections.length ? sections.join("\n") + "\n" : "", ` /** The node is released: stop what the half started. */\n destroy?(): void\n`, `}\n`, ].join("")) // ---- the glue ---- const readText = (t: L): string | null => { if (!propAsText(t)) return `propText.json(value, (w) => ${decode(t, "w")})` switch (t.kind) { case "boolean": return `propText.bool(value)` case "f64": return `propText.f64(value)` case "i32": return `propText.i32(value)` case "enum": return `read${t.name}(value)` default: return null // a string: the text itself } } const props = node.props.map(p => { const optional = p.type.kind === "optional" const call = (v: string) => `applied(${kind}, name, half.${setterOf(p)}${methods.has(setterOf(p)) ? "" : "?."}(${v}))` const read = readText(strip(p.type)) const lines = [` case ${str(p.name)}: {`] if (optional && read === null) lines.push(` return ${call("value ?? undefined")}`) else { lines.push(optional ? ` if (value === null) return ${call("undefined")}` : ` if (value === null) return dropped(${kind}, name)`) if (read === null) lines.push(` return ${call("value")}`) else lines.push(` const v = ${read}`, ` if (v === undefined) return dropped(${kind}, name)`, ` return ${call("v")}`) } lines.push(` }`) return lines.join("\n") }) const styles = node.styles.map(s => s.kind === "color" ? ` case ${str(s.name)}: return half.${styleSetter(s.name)}?.(typeof value === "string" ? value : undefined)` : ` case ${str(s.name)}: return half.${styleSetter(s.name)}?.(typeof value === "number" && Number.isFinite(value) ? value : undefined)`) const cases = callCases(ch, ch.iface, "half", " ", "nodeHost!") const usesHost = files || cases.some(c => c.includes("nodeHost!")) out.push([ `export const ${base}Channel = {\n /** What the halves register under: the node's kind. */\n name: ${kind},\n /** The contract's version: the highest \`@since\` of its members. */\n version: ${ch.version},\n} as const\n\n`, `/** What the holder hands the half, by name — read by the contract here: the half implements none of it. */\n`, `export const ${base}Glue = {\n`, ` /** A prop the SDK wrote: its wire text, null when it was cleared. A value the contract does not\n * read is dropped with a warning, as the native glue drops it: the half never sees it. */\n`, ` setProperty(half: ${base}Half, name: string, value: string | null): void {\n switch (name) {\n`, props.length ? props.join("\n") + "\n" : "", ` default: return // \`kind\` (the holder's), or a prop of a newer contract\n }\n },\n`, ` /** A style of the node, as the core resolved it (a CSS color, a number; null when none is set);\n * one the contract does not list is not the node's. */\n`, styles.length ? ` setStyle(half: ${base}Half, name: string, value: unknown): void {\n switch (name) {\n${styles.join("\n")}\n default: return\n }\n },\n` : ` setStyle(_half: ${base}Half, _name: string, _value: unknown): void {},\n`, ` /** A call of the SDK: read off the wire and handed to the half; a malformed call never reaches it. */\n`, ` async call(half: ${base}Half, method: string, args: unknown[]): Promise {\n switch (method) {\n`, cases.length ? cases.join("\n") + "\n" : "", ` default: throw new Error(\`Unknown method: \${method}\`)\n }\n },\n`, `}\n\n`, `/** Register the node: \`make\` builds one half per node of the kind, when the SDK creates the node,\n * in the document it is handed. */\n`, `export const register${base} = (host: PluginHost, make: (events: ${base}Events, doc: Document) => ${base}Half): void => {\n`, `__BUFFERS__`, usesHost ? ` nodeHost = host\n` : "", ` host.registerNode(${base}Channel.name, (channel, doc) => {\n`, ` const half = make(new ${base}Events(channel), doc)\n`, ` return {\n`, ` el: half.el,\n`, ` setProperty: (name, value) => ${base}Glue.setProperty(half, name, value),\n`, ` setStyle: (name, value) => ${base}Glue.setStyle(half, name, value),\n`, ` call: (method, args) => ${base}Glue.call(half, method, args),\n`, node.paintsSelf ? ` /** The half paints its background and backdrop (\`paints: "self"\`): the holder does not. */\n paintsSelf: true,\n` : "", ` destroy: () => half.destroy?.(),\n`, ` }\n`, ` }, ${base}Channel.version)\n}\n`, ].join("")) return out.join("\n") } const guarded = (what: string, body: () => string): string => { try { return body() } catch (e) { if (e instanceof EmitError) throw new EmitError(`${what}: ${e.message}`) throw e } } const header = lowered.channels.map(channelLabel).join("; ") const body = [ `// ---- the contract's types ----\n\n`, lowered.decls.map(d => guarded(d.name, () => emitDecl(d))).join("\n"), ...lowered.channels.map(ch => `\n// ---- ${ch.iface} ----\n\n${guarded(ch.iface, () => emitChannel(ch))}`), ].join("") const uses = (name: string): boolean => new RegExp(`\\b${name}\\b`).test(body) const views = lowered.channels.some(c => c.kind === "view") const services = lowered.channels.some(c => c.kind === "service") const nodes = lowered.channels.some(c => c.kind === "node") // A contract that hands the half the app's 3D nodes / scenes is one whose half drives them: through // the host's gl facade, which the host then must have. const drives3d = reachesKind(lowered, "entity") || reachesKind(lowered, "scene3d") return [ `// GENERATED by \`lecodes plugin gen\` from contract.d.ts — do not edit.\n`, `// ${opts.id}: ${header}.\n`, `//\n// The web half's side of the channel. This file imports nothing: a half depends on it, on the\n// document it is handed and on the browser.\n\n`, `// ---- what the host hands a half ----\n\n`, `/** Where a half's events go. */\nexport interface PluginChannel { emit(event: string, data?: unknown): void }\n\n`, `/** The host, as a half needs it: a SHAPE — the host's own type is never imported. */\nexport interface PluginHost {\n`, ` // \`version\` = the contract version the half was generated from: what the app's \`supports()\` asks.\n`, views ? ` registerView(name: string, factory: (params: unknown, channel: PluginChannel, doc: Document) => {\n el: HTMLElement, call?(method: string, args: unknown[]): unknown, destroy?(): void,\n }, version: number): void\n` : "", services ? ` registerService(name: string, factory: (params: unknown, channel: PluginChannel) => {\n call?(method: string, args: unknown[]): unknown, close?(): void,\n }, version: number): void\n` : "", nodes ? [ ` /** A host node's half, one per node of \`kind\`: made at the node's \`kind\` write, handed its props as\n`, ` * their wire text, its listed styles resolved, its calls; released with the node. */\n`, ` registerNode(kind: string, factory: (channel: PluginChannel, doc: Document) => {\n`, ` el: HTMLElement, setProperty(name: string, value: string | null): void, setStyle(name: string, value: unknown): void,\n`, ` call(method: string, args: unknown[]): unknown, paintsSelf?: boolean, destroy?(): void,\n`, ` }, version: number): void\n`, ].join("") : "", uses("writeFile") ? ` /** Store bytes in the host's buffer table: the handle a File crosses as. */\n putBuffer(bytes: ArrayBuffer): number\n` : "", uses("readFile") ? ` /** The bytes of a buffer of the host's table — what the handle of a File the app sent names. */\n getBuffer(systemId: number): ArrayBuffer | Uint8Array | null | undefined\n` : "", drives3d ? ` /** The 3D engine as the half drives it: the app's entities and scenes by their ids. */\n gl: PluginGL\n` : "", `}\n\n`, drives3d ? PLUGIN_GL : "", uses("PluginFile") ? [ `/** A \`File\` of the contract. One a half hands to the app: its bytes go into the host's buffer\n * table, the app gets the handle (a texture source, an upload, a share). One the app hands to a\n * half: the bytes of the buffer its handle names. */\n`, `export interface PluginFile { data: ArrayBuffer | Uint8Array, name: string }\n\n`, ].join("") : "", uses("writeFile") ? [ `const writeFile = (host: PluginHost, file: PluginFile): unknown => {\n`, ` const bytes = file.data instanceof Uint8Array ? file.data.slice().buffer : file.data\n`, ` return { systemId: host.putBuffer(bytes), name: file.name, size: bytes.byteLength }\n}\n\n`, ].join("") : "", uses("Json") ? `/** A value the generator passes through untyped. */\nexport type Json = null | boolean | number | string | Json[] | { [key: string]: Json }\n\n` : "", reachesKind(lowered, "entity") ? `/** A 3D node of the app (\`Entity\` of the contract): its id, what the host's gl facade (\`host.gl\`) takes. */\nexport type Entity = number\n\n` : "", reachesKind(lowered, "scene3d") ? `/** A 3D scene of the app (\`Scene3D\` of the contract): its id, what the host's gl facade (\`host.gl\`) takes. */\nexport type Scene3D = number\n\n` : "", uses("wire") || uses("readFile") ? WIRE : "", nodes ? PROP_TEXT : "", uses("nodeHost") ? NODE_HOST : "", uses("readFile") ? READ_FILE : "", uses("readId") ? READ_ID : "", body.replaceAll("__BUFFERS__", uses("readFile") ? ` buffers = (systemId) => host.getBuffer(systemId)\n` : ""), ].join("") } /** What a host node's glue reads a prop's TEXT with, and what it does with a value it cannot read. */ const PROP_TEXT = `// The readers of a host node's prop TEXT, as the SDK's generated element writes it: a string (an // enum's too) as it is, a boolean as "1" / "0", a number as its decimal text, anything else as JSON. // undefined = not a value of that type: the glue drops it, as the native glue does. const propText = { bool: (t: string): boolean | undefined => t === "1" ? true : t === "0" ? false : undefined, /** Decimal text — or what JavaScript writes for a number that is not finite, which the native * glue reads too. */ f64: (t: string): number | undefined => /^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?$/.test(t) || t === "NaN" || t === "Infinity" || t === "-Infinity" ? Number(t) : undefined, i32: (t: string): number | undefined => { if (!/^[+-]?\\d+$/.test(t)) return undefined const n = Number(t) return n >= -2147483648 && n <= 2147483647 ? n : undefined }, /** JSON text, read as the contract's type. */ json: (t: string, read: (v: unknown) => T | undefined): T | undefined => { let v: unknown try { v = JSON.parse(t) } catch { return undefined } return read(v) }, } /** A prop's value the contract does not read: dropped, with the native glue's warning. */ const dropped = (kind: string, prop: string): void => { console.warn(\`LeCodes: the node "\${kind}" dropped a value of \${prop} its contract does not read\`) } /** What a half's setter returned: a promise that fails is reported, never left unhandled. */ const applied = (kind: string, prop: string, r: unknown): void => { const then = (r as { then?: unknown } | null | undefined)?.then if (typeof then === "function") { (r as PromiseLike).then(undefined, (e: unknown) => { console.warn(\`LeCodes: the node "\${kind}" did not apply \${prop}: \${e instanceof Error ? e.message : String(e)}\`) }) } } ` /** Where a File a host node's half hands the app goes: the host it registered with. */ const NODE_HOST = `/** The host a node's half registered with: the buffer table a File it hands the app goes into. */ let nodeHost: PluginHost | undefined ` /** The reader of a File the app sent: the host's buffer table is reached through the host a half * registered with. */ const READ_FILE = `/** Where the bytes of a File the app sent are: the buffer table of the host a half registered with. */ let buffers: ((systemId: number) => ArrayBuffer | Uint8Array | null | undefined) | undefined /** A File the app handed over; undefined when it is not a handle, or the buffer is gone. */ const readFile = (v: unknown): PluginFile | undefined => { const o = wire.object(v) const id = o ? wire.i32(o.systemId) : undefined const data = id === undefined ? undefined : buffers?.(id) return o && data ? { data, name: wire.string(o.name) ?? "" } : undefined } ` /** The host's gl facade as a half sees it — a SHAPE of the web hosts' own (lecodes-web-shared's * GLFacade), the twin of `engine.gl` in Swift and Kotlin. */ const PLUGIN_GL = `/** The host's gl facade (\`host.gl\`): what a half drives the 3D engine through — the app's entities * and scenes by their ids, a scene's projection and background, a hook before each frame, a * readback. Never creates or frees an entity or a scene. Every call is a no-op on a page without * the 3D engine. */ export interface PluginGL { /** The entity's world matrix (16 numbers, column-major). */ setMatrix(entity: number, m16: ArrayLike): void setVisible(entity: number, visible: boolean): void /** The pose of the scene's camera (its world matrix). */ setCameraMatrix(scene: number, m16: ArrayLike): void /** A projection the half computes (column-major, OpenGL clip conventions), with the near / far it * was built with, in place of the scene's fov projection: drawn as it is — an off-centre one (a * camera's intrinsics) too. Made for one view: a change of \`viewport\` wants a new one. */ setProjection(scene: number, m16: ArrayLike, near: number, far: number): void /** Back to the scene's own (fov) projection. */ clearProjection(scene: number): void /** The scene's background, behind the scene: a playing video (a camera's stream), or a canvas the * half (or an engine it runs) draws the camera's picture on; null = none. \`uv\` = the affine map * from the viewport's normalized coordinates (0,0 top-left) to the picture's, row-major * [a, b, tx, c, d, ty] (identity by default). Web Lite shows the element itself: moved under the * scene's canvas (its inline style replaced: absolute, the scene's box filled, \`object-fit: cover\` * — \`uv\` is not read; a canvas sized to \`viewport\` × devicePixelRatio is shown 1:1), taken out of * the page when it is replaced or cleared. The web player (a preview) shows a video only. */ setBackground(scene: number, source: HTMLVideoElement | HTMLCanvasElement | null, uv?: ArrayLike): void /** The web has no external textures: a video or a canvas is handed to setBackground as it is. * Always null. */ createExternalTexture(): null /** \`body\` before each frame of the 3D engine, until the returned function is called — or the * world swap: in the host's own animation frame, before the tick and the render, so what a body * sets (a pose, a projection) is that frame's picture. A requestAnimationFrame callback of the * half's own is a frame late unless the browser runs it before the host's (callbacks run in the * order they were asked for). Web Lite runs the bodies while a scene is on show. */ onFrame(body: () => void): () => void /** The composite of the scene's next frame — the 3D picture, not the UI over it: RGBA8, top row * first, width, height; null (0 × 0) when the scene is not the one presented. */ readPixels(scene: number, then: (rgba: Uint8Array | null, width: number, height: number) => void): void /** The scene's view: the size of the canvas it draws on in CSS px (the space its touches arrive in; * not the window's — a player inside a device frame is smaller than its page; 0 × 0 while no scene * is on show) and the display's turn (\`screen.orientation.angle\`: 0, 90 = turned * counter-clockwise, 180, 270). Read it each frame (\`onFrame\`) and follow a change. */ viewport(scene: number): { width: number, height: number, rotation: 0 | 90 | 180 | 270 } } ` /** The reader of an Entity / a Scene3D the app sent: the id of its 3D node / scene. */ const READ_ID = `/** An Entity / a Scene3D the app sent: its id, a whole number in u32's range. */ const readId = (v: unknown): number | undefined => typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 4294967295 ? v : undefined ` /** The readers of the wire's values: undefined = absent, null, or not that type. */ const WIRE = `// The readers of the wire's values: undefined = absent, null, or not that type. On the web the wire // carries the app's OWN values (the host is JavaScript like the app). What is read of the contract is // built anew — a struct, a list, bytes — so what a half keeps is its own; a Json value alone is the // app's object, as it is. const wire = { present: (v: unknown): boolean => v !== undefined && v !== null, /** A number that is not finite is a null on the wire, as JSON has it. */ f64: (v: unknown): number | undefined => typeof v === "number" && Number.isFinite(v) ? v : undefined, i32: (v: unknown): number | undefined => typeof v === "number" && Number.isInteger(v) && v >= -2147483648 && v <= 2147483647 ? v : undefined, bool: (v: unknown): boolean | undefined => typeof v === "boolean" ? v : undefined, string: (v: unknown): string | undefined => typeof v === "string" ? v : undefined, /** Any JSON value, as it is; a null is a value here. */ json: (v: unknown): any => v, /** A copy of the bytes. Told by its class name, not \`instanceof\`: the app's realm may not be the half's. */ bytes: (v: unknown): Uint8Array | undefined => Object.prototype.toString.call(v) === "[object Uint8Array]" ? (v as Uint8Array).slice() : undefined, object: (v: unknown): Record | undefined => typeof v === "object" && v !== null && !Array.isArray(v) ? v as Record : undefined, /** An array of exactly \`count\` values (a tuple), or of any length. */ array: (v: unknown, count?: number): unknown[] | undefined => Array.isArray(v) && (count === undefined || v.length === count) ? v : undefined, /** Every element or nothing: one that does not read fails the list. */ list: (v: unknown, each: (v: unknown) => T | undefined): T[] | undefined => { if (!Array.isArray(v)) return undefined const out: T[] = [] for (const item of v) { const r = each(item) if (r === undefined) return undefined out.push(r) } return out }, map: (v: unknown, each: (v: unknown) => T | undefined): { [key: string]: T } | undefined => { if (typeof v !== "object" || v === null || Array.isArray(v)) return undefined const out: { [key: string]: T } = {} for (const [k, item] of Object.entries(v)) { const r = each(item) if (r === undefined) return undefined out[k] = r } return out }, } `