@glassly/miniapp-cli 0.1.10 → 0.1.11-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,61 @@
1
+ import {MirrorCanvasRenderer, type MirrorCanvasEnvironment, type MirrorSnapshot} from "@glassly/miniapp/mirror"
2
+
3
+ type Canvas = typeof import("@napi-rs/canvas")
4
+ // The renderer's environment is typed against the DOM; the native canvas mirrors those shapes.
5
+ type Surface = ReturnType<MirrorCanvasEnvironment["createCanvas"]>
6
+ type Picture = Parameters<Parameters<MirrorCanvasEnvironment["loadImage"]>[1]>[0]
7
+ type Path = ReturnType<MirrorCanvasEnvironment["createPath"]>
8
+
9
+ export interface ScreenRenderer {
10
+ update(snapshot: MirrorSnapshot): void
11
+ png(scale?: number): Promise<Uint8Array>
12
+ }
13
+
14
+ async function loadCanvas(): Promise<Canvas | string> {
15
+ try {
16
+ return await import("@napi-rs/canvas")
17
+ } catch (error) {
18
+ return `no canvas binding for ${process.platform}-${process.arch} (${(error as Error).message.split("\n")[0]})`
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Resolves to a reason string where the native canvas is unavailable. Images
24
+ * must load asynchronously: the renderer asks for them while it is painting.
25
+ */
26
+ export async function createScreenRenderer(): Promise<ScreenRenderer | string> {
27
+ const canvas = await loadCanvas()
28
+ if (typeof canvas === "string") return canvas
29
+
30
+ const environment: MirrorCanvasEnvironment = {
31
+ createCanvas: (width, height) => canvas.createCanvas(width, height) as unknown as Surface,
32
+ loadImage(src, onLoad, onError) {
33
+ const image = new canvas.Image()
34
+ image.onload = () => queueMicrotask(() => onLoad(image as unknown as Picture, image.width, image.height))
35
+ image.onerror = () => queueMicrotask(onError)
36
+ image.src = src
37
+ },
38
+ createPath: (d) => new canvas.Path2D(d) as unknown as Path,
39
+ requestFrame: () => 0,
40
+ cancelFrame: () => {},
41
+ }
42
+
43
+ const surface = canvas.createCanvas(1, 1)
44
+ const renderer = new MirrorCanvasRenderer(surface as unknown as Surface, environment)
45
+
46
+ return {
47
+ update: (snapshot) => renderer.update(snapshot),
48
+ async png(scale = 1) {
49
+ const deadline = Date.now() + 2_000
50
+ while (renderer.loading && Date.now() < deadline) await Bun.sleep(10)
51
+ renderer.redraw()
52
+ const out = canvas.createCanvas(surface.width * scale, surface.height * scale)
53
+ const ctx = out.getContext("2d")
54
+ ctx.fillStyle = "#000"
55
+ ctx.fillRect(0, 0, out.width, out.height)
56
+ ctx.imageSmoothingEnabled = scale === 1
57
+ ctx.drawImage(surface, 0, 0, out.width, out.height)
58
+ return out.toBuffer("image/png")
59
+ },
60
+ }
61
+ }
@@ -0,0 +1,412 @@
1
+ import {existsSync, readFileSync, statSync} from "fs"
2
+ import {join, normalize, sep} from "path"
3
+ import type {ServerWebSocket} from "bun"
4
+ import {buildUiShim, buildWebviewGlobalsScript} from "@glassly/miniapp/host"
5
+ import type {MirrorSnapshot} from "@glassly/miniapp/mirror"
6
+
7
+ import type {SimHost, SimHostEvent} from "./host.js"
8
+ import type {ScreenRenderer} from "./screenshot.js"
9
+
10
+ export interface SimServerOptions {
11
+ host: SimHost
12
+ port: number
13
+ packageName: string
14
+ ui: {dir: string; entry: string} | null
15
+ screen: ScreenRenderer | string
16
+ page: {html: string; js: string; css: string}
17
+ restart: () => Promise<void>
18
+ stop: () => void
19
+ }
20
+
21
+ export interface SimServer {
22
+ port: number
23
+ handle(event: SimHostEvent): void
24
+ reloadUi(): void
25
+ stop(): void
26
+ }
27
+
28
+ interface SocketData {
29
+ kind: "page" | "ui"
30
+ id: string
31
+ }
32
+
33
+ const SAFE_AREA = {top: 59, bottom: 34, left: 0, right: 0}
34
+ const CAPSULE = {top: 67, right: 16, width: 80, height: 32}
35
+
36
+ const CONTENT_TYPES: Record<string, string> = {
37
+ html: "text/html; charset=utf-8",
38
+ js: "application/javascript; charset=utf-8",
39
+ mjs: "application/javascript; charset=utf-8",
40
+ css: "text/css; charset=utf-8",
41
+ json: "application/json; charset=utf-8",
42
+ map: "application/json; charset=utf-8",
43
+ png: "image/png",
44
+ jpg: "image/jpeg",
45
+ jpeg: "image/jpeg",
46
+ gif: "image/gif",
47
+ webp: "image/webp",
48
+ svg: "image/svg+xml",
49
+ ico: "image/x-icon",
50
+ woff: "font/woff",
51
+ woff2: "font/woff2",
52
+ ttf: "font/ttf",
53
+ wasm: "application/wasm",
54
+ mp3: "audio/mpeg",
55
+ wav: "audio/wav",
56
+ }
57
+
58
+ function contentType(path: string): string {
59
+ return CONTENT_TYPES[path.slice(path.lastIndexOf(".") + 1).toLowerCase()] ?? "application/octet-stream"
60
+ }
61
+
62
+ function json(body: unknown, status = 200): Response {
63
+ return new Response(JSON.stringify(body), {
64
+ status,
65
+ headers: {"content-type": "application/json; charset=utf-8", "cache-control": "no-store"},
66
+ })
67
+ }
68
+
69
+ export function describeScreen(snapshot: MirrorSnapshot): string {
70
+ const canvas = snapshot.canvas ? `${snapshot.canvas.width}x${snapshot.canvas.height}` : "no display"
71
+ const head = `${snapshot.model ?? "glasses"} ${canvas}, view ${snapshot.view ?? "none"}`
72
+ if (snapshot.content.kind !== "scene") return `${head}\n(${snapshot.content.kind})`
73
+ const lines = snapshot.content.elements.map((el) => {
74
+ const box = `${el.box.x},${el.box.y} ${el.box.w}x${el.box.h}`
75
+ const detail =
76
+ el.type === "text"
77
+ ? JSON.stringify(el.text ?? "")
78
+ : el.type === "image"
79
+ ? `${Math.round(((el.data?.length ?? 0) * 3) / 4)} bytes`
80
+ : el.type === "svg"
81
+ ? JSON.stringify((el.d ?? "").slice(0, 60))
82
+ : el.points
83
+ ? el.points.map((p) => `${p.x},${p.y}`).join(" ")
84
+ : ""
85
+ const style = el.style && Object.keys(el.style).length ? ` ${JSON.stringify(el.style)}` : ""
86
+ return `${el.type.padEnd(8)} ${el.id.padEnd(16)} @ ${box}${detail ? ` ${detail}` : ""}${style}`
87
+ })
88
+ return [head, ...lines].join("\n")
89
+ }
90
+
91
+ /**
92
+ * Must run before the page's own scripts: it installs the WebView bridge the
93
+ * Glassly App provides (carried over a WebSocket) and the phone chrome.
94
+ */
95
+ function uiBootstrap(packageName: string, colorScheme: "light" | "dark"): string {
96
+ const globals = buildWebviewGlobalsScript({
97
+ platform: "simulator",
98
+ packageName,
99
+ miniappLocal: true,
100
+ miniappDeveloperMode: true,
101
+ safeAreaInsets: SAFE_AREA,
102
+ capsuleMenu: {
103
+ ...CAPSULE,
104
+ bottom: CAPSULE.top + CAPSULE.height,
105
+ left: 393 - CAPSULE.right - CAPSULE.width,
106
+ placement: "corner",
107
+ },
108
+ colorScheme,
109
+ })
110
+ const bridge = `
111
+ (function () {
112
+ var queue = [], socket = null, open = false, dropped = false;
113
+ function connect() {
114
+ socket = new WebSocket((location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/sim/ui-socket");
115
+ socket.onopen = function () {
116
+ if (dropped) { location.reload(); return; }
117
+ open = true;
118
+ while (queue.length) socket.send(queue.shift());
119
+ };
120
+ socket.onmessage = function (event) {
121
+ var message; try { message = JSON.parse(event.data); } catch (e) { return; }
122
+ if (message.type === "frame") { if (window.__host && window.__host.recv) window.__host.recv(message.frame); }
123
+ else if (message.type === "reload") location.reload();
124
+ else if (message.type === "color-scheme") {
125
+ window.Glassly.colorScheme = message.colorScheme;
126
+ window.dispatchEvent(new Event("glassly:color-scheme-change"));
127
+ paintChrome();
128
+ }
129
+ };
130
+ socket.onclose = function () { open = false; dropped = true; setTimeout(connect, 600); };
131
+ }
132
+ window.ReactNativeWebView = {
133
+ postMessage: function (raw) { if (open) socket.send(raw); else queue.push(raw); }
134
+ };
135
+ connect();
136
+
137
+ function placeCapsule() {
138
+ var capsule = window.Glassly && window.Glassly.capsuleMenu;
139
+ if (!capsule) return;
140
+ var left = Math.max(0, window.innerWidth - capsule.right - capsule.width);
141
+ if (left === capsule.left) return;
142
+ capsule.left = left;
143
+ document.documentElement.style.setProperty("--glassly-capsule-left", left + "px");
144
+ window.dispatchEvent(new Event("glassly:safe-area-change"));
145
+ }
146
+ var chrome = null;
147
+ function paintChrome() {
148
+ if (!chrome) return;
149
+ var dark = window.Glassly.colorScheme === "dark";
150
+ chrome.style.setProperty("--ink", dark ? "#f4f4f5" : "#18181b");
151
+ chrome.style.setProperty("--pill", dark ? "rgba(63,63,70,.72)" : "rgba(255,255,255,.78)");
152
+ chrome.style.setProperty("--edge", dark ? "rgba(255,255,255,.14)" : "rgba(0,0,0,.1)");
153
+ }
154
+ function mountChrome() {
155
+ if (chrome || !document.documentElement) return;
156
+ chrome = document.createElement("div");
157
+ chrome.setAttribute("data-glassly-sim-chrome", "");
158
+ chrome.style.cssText = "position:fixed;inset:0;pointer-events:none;z-index:2147483647;font:600 15px -apple-system,system-ui,sans-serif;color:var(--ink)";
159
+ var root = chrome.attachShadow({mode: "open"});
160
+ root.innerHTML =
161
+ '<div style="position:absolute;top:18px;left:30px">9:41</div>' +
162
+ '<div style="position:absolute;top:19px;right:28px;font-size:12px;letter-spacing:.02em;opacity:.7">Simulator</div>' +
163
+ '<div style="position:absolute;top:${CAPSULE.top}px;right:${CAPSULE.right}px;width:${CAPSULE.width}px;height:${CAPSULE.height}px;box-sizing:border-box;border-radius:16px;background:var(--pill);border:1px solid var(--edge);backdrop-filter:blur(12px);display:flex;align-items:center;justify-content:space-evenly;font-size:16px;line-height:1">' +
164
+ '<span style="letter-spacing:1px">•••</span><span style="width:1px;height:14px;background:var(--edge)"></span><span style="font-size:13px">✕</span></div>' +
165
+ '<div style="position:absolute;bottom:8px;left:50%;width:134px;height:5px;margin-left:-67px;border-radius:3px;background:var(--ink);opacity:.85"></div>';
166
+ document.documentElement.appendChild(chrome);
167
+ paintChrome();
168
+ }
169
+ placeCapsule();
170
+ window.addEventListener("resize", placeCapsule);
171
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", mountChrome);
172
+ else mountChrome();
173
+ })();`
174
+ return `<script>${globals}\n${bridge}\n${buildUiShim({packageName})}</script>`
175
+ }
176
+
177
+ function injectBootstrap(html: string, bootstrap: string): string {
178
+ const head = html.match(/<head[^>]*>/i)
179
+ if (head?.index !== undefined) {
180
+ const at = head.index + head[0].length
181
+ return html.slice(0, at) + bootstrap + html.slice(at)
182
+ }
183
+ return bootstrap + html
184
+ }
185
+
186
+ export function startSimServer(options: SimServerOptions): SimServer {
187
+ const {host} = options
188
+ const pages = new Set<ServerWebSocket<SocketData>>()
189
+ const uiSockets = new Set<ServerWebSocket<SocketData>>()
190
+ let socketSeq = 0
191
+
192
+ const broadcast = (sockets: Set<ServerWebSocket<SocketData>>, message: unknown) => {
193
+ const raw = JSON.stringify(message)
194
+ for (const socket of sockets) {
195
+ try {
196
+ socket.send(raw)
197
+ } catch {
198
+ /* a closing socket */
199
+ }
200
+ }
201
+ }
202
+
203
+ const serveUi = (path: string): Response => {
204
+ if (!options.ui) return new Response("This miniapp has no UI page (no entry.ui in miniapp.json).", {status: 404})
205
+ const requested = normalize(decodeURIComponent(path)).replace(/^[/\\]+/, "")
206
+ const relative = requested === "" || requested === "." ? options.ui.entry : requested
207
+ if (relative.split(sep).includes("..")) return new Response("forbidden", {status: 403})
208
+ const file = join(options.ui.dir, relative)
209
+ if (!existsSync(file) || statSync(file).isDirectory()) return new Response("not found", {status: 404})
210
+ const headers = {"content-type": contentType(file), "cache-control": "no-store"}
211
+ if (!file.endsWith(".html")) return new Response(readFileSync(file), {headers})
212
+ const scheme = host.status().colorScheme === "light" ? "light" : "dark"
213
+ return new Response(injectBootstrap(readFileSync(file, "utf-8"), uiBootstrap(options.packageName, scheme)), {
214
+ headers,
215
+ })
216
+ }
217
+
218
+ const api = async (request: Request, url: URL): Promise<Response> => {
219
+ const route = url.pathname.slice("/api/".length)
220
+ if (request.method === "GET") {
221
+ if (route === "status") return json(host.status())
222
+ if (route === "screen") {
223
+ const snapshot = host.snapshot()
224
+ return url.searchParams.get("format") === "json"
225
+ ? json(snapshot)
226
+ : new Response(`${describeScreen(snapshot)}\n`, {headers: {"content-type": "text/plain; charset=utf-8"}})
227
+ }
228
+ if (route === "screenshot") {
229
+ if (typeof options.screen === "string") return json({error: `Screenshots are unavailable: ${options.screen}`}, 501)
230
+ if (url.searchParams.get("wait") !== "0") {
231
+ const wait = Math.min(10_000, host.displaySettlesAt() - Date.now())
232
+ if (wait > 0) await Bun.sleep(wait)
233
+ }
234
+ const scale = Math.max(1, Math.min(4, Math.round(Number(url.searchParams.get("scale")) || 1)))
235
+ const png = await options.screen.png(scale)
236
+ return new Response(png.buffer.slice(png.byteOffset, png.byteOffset + png.byteLength) as ArrayBuffer, {
237
+ headers: {"content-type": "image/png", "cache-control": "no-store"},
238
+ })
239
+ }
240
+ if (route === "logs") {
241
+ const sources = url.searchParams.get("source")?.split(",")
242
+ const entries = host
243
+ .logs(Number(url.searchParams.get("since")) || 0)
244
+ .filter((entry) => (sources ? sources.includes(entry.source) : entry.source !== "bridge"))
245
+ return json({entries, seq: host.status().logSeq})
246
+ }
247
+ if (route === "effects") return json({effects: host.recentEffects()})
248
+ return json({error: `Unknown endpoint GET /api/${route}`}, 404)
249
+ }
250
+ if (request.method !== "POST") return json({error: "Use GET or POST"}, 405)
251
+ if (!(request.headers.get("content-type") ?? "").includes("application/json")) {
252
+ return json({error: "POST bodies must be application/json"}, 415)
253
+ }
254
+ let body: Record<string, unknown>
255
+ try {
256
+ body = ((await request.json()) ?? {}) as Record<string, unknown>
257
+ } catch {
258
+ return json({error: "Body is not valid JSON"}, 400)
259
+ }
260
+ const text = (key: string) => (typeof body[key] === "string" ? (body[key] as string) : undefined)
261
+ const number = (key: string) => {
262
+ const value = Number(body[key])
263
+ if (!Number.isFinite(value)) throw new Error(`"${key}" must be a number`)
264
+ return value
265
+ }
266
+ try {
267
+ switch (route) {
268
+ case "touch":
269
+ host.touch(text("gesture") ?? "single_tap")
270
+ break
271
+ case "button":
272
+ host.button(body.pressType === "long" ? "long" : "short", text("buttonId"))
273
+ break
274
+ case "say":
275
+ host.transcription(text("text") ?? "", {
276
+ isFinal: body.isFinal !== false,
277
+ language: text("language"),
278
+ speakerId: text("speakerId"),
279
+ })
280
+ break
281
+ case "translate":
282
+ host.translation(text("text") ?? "", {
283
+ source: text("source"),
284
+ target: text("target"),
285
+ isFinal: body.isFinal !== false,
286
+ originalText: text("originalText"),
287
+ })
288
+ break
289
+ case "location":
290
+ host.setLocation(number("lat"), number("lng"), body.accuracy === undefined ? undefined : number("accuracy"))
291
+ break
292
+ case "heading":
293
+ host.setHeading(number("degrees"))
294
+ break
295
+ case "battery":
296
+ host.setBattery(body.target === "phone" ? "phone" : "glasses", number("level"), body.charging === true)
297
+ break
298
+ case "connection":
299
+ host.setGlassesConnected(body.connected !== false)
300
+ break
301
+ case "notify":
302
+ return json({ok: true, notificationId: host.notification(body as Record<string, string>)})
303
+ case "visibility":
304
+ host.setVisibility(body.visibility === "background" ? "background" : "foreground")
305
+ break
306
+ case "color-scheme": {
307
+ const colorScheme = body.colorScheme === "light" ? "light" : "dark"
308
+ host.setColorScheme(colorScheme)
309
+ broadcast(uiSockets, {type: "color-scheme", colorScheme})
310
+ break
311
+ }
312
+ case "event":
313
+ host.event(text("stream") ?? "", body.data)
314
+ break
315
+ case "ui/send":
316
+ host.uiSend(text("channel") ?? "", body.payload)
317
+ break
318
+ case "ui/request":
319
+ return json({ok: true, result: await host.uiRequest(text("channel") ?? "", body.payload, Number(body.timeoutMs) || undefined)})
320
+ case "restart":
321
+ await options.restart()
322
+ break
323
+ case "stop":
324
+ setTimeout(options.stop, 50)
325
+ break
326
+ default:
327
+ return json({error: `Unknown endpoint POST /api/${route}`}, 404)
328
+ }
329
+ } catch (error) {
330
+ return json({ok: false, error: (error as Error).message}, 400)
331
+ }
332
+ return json({ok: true})
333
+ }
334
+
335
+ const server = Bun.serve<SocketData>({
336
+ hostname: "127.0.0.1",
337
+ port: options.port,
338
+ async fetch(request, srv) {
339
+ const url = new URL(request.url)
340
+ const origin = request.headers.get("origin")
341
+ if (origin && new URL(origin).host !== url.host) return new Response("cross-origin request refused", {status: 403})
342
+
343
+ if (url.pathname === "/sim/socket" || url.pathname === "/sim/ui-socket") {
344
+ const kind = url.pathname === "/sim/socket" ? "page" : "ui"
345
+ if (srv.upgrade(request, {data: {kind, id: `${kind}-${++socketSeq}`}})) return undefined
346
+ return new Response("WebSocket upgrade required", {status: 400})
347
+ }
348
+ if (url.pathname.startsWith("/api/")) return api(request, url)
349
+ if (url.pathname === "/") {
350
+ return new Response(options.page.html, {headers: {"content-type": CONTENT_TYPES.html, "cache-control": "no-store"}})
351
+ }
352
+ if (url.pathname === "/sim/app.js") {
353
+ return new Response(options.page.js, {headers: {"content-type": CONTENT_TYPES.js, "cache-control": "no-store"}})
354
+ }
355
+ if (url.pathname === "/sim/app.css") {
356
+ return new Response(options.page.css, {headers: {"content-type": CONTENT_TYPES.css, "cache-control": "no-store"}})
357
+ }
358
+ if (url.pathname === "/ui") return Response.redirect("/ui/", 302)
359
+ if (url.pathname.startsWith("/ui/")) return serveUi(url.pathname.slice("/ui/".length))
360
+ return new Response("not found", {status: 404})
361
+ },
362
+ websocket: {
363
+ open(socket) {
364
+ if (socket.data.kind === "ui") {
365
+ uiSockets.add(socket)
366
+ return
367
+ }
368
+ pages.add(socket)
369
+ socket.send(
370
+ JSON.stringify({
371
+ type: "hello",
372
+ status: host.status(),
373
+ snapshot: host.snapshot(),
374
+ logs: host.logs().filter((entry) => entry.source !== "bridge").slice(-300),
375
+ hasUi: options.ui !== null,
376
+ }),
377
+ )
378
+ },
379
+ message(socket, message) {
380
+ if (socket.data.kind !== "ui") return
381
+ host.fromUi(socket.data.id, typeof message === "string" ? message : new TextDecoder().decode(message))
382
+ },
383
+ close(socket) {
384
+ if (socket.data.kind === "ui") {
385
+ uiSockets.delete(socket)
386
+ host.uiClosed(socket.data.id)
387
+ } else pages.delete(socket)
388
+ },
389
+ },
390
+ })
391
+
392
+ return {
393
+ port: server.port ?? options.port,
394
+ handle(event) {
395
+ if (event.type === "display") {
396
+ if (typeof options.screen !== "string") options.screen.update(event.snapshot)
397
+ broadcast(pages, {type: "display", snapshot: event.snapshot})
398
+ } else if (event.type === "log") {
399
+ if (event.entry.source !== "bridge") broadcast(pages, {type: "log", entry: event.entry})
400
+ } else if (event.type === "ui") broadcast(uiSockets, {type: "frame", frame: event.frame})
401
+ else if (event.type === "effect") broadcast(pages, {type: "effect", effect: event.effect})
402
+ else if (event.type === "status") broadcast(pages, {type: "status", status: host.status()})
403
+ },
404
+ reloadUi() {
405
+ broadcast(uiSockets, {type: "reload"})
406
+ },
407
+ stop() {
408
+ for (const socket of [...pages, ...uiSockets]) socket.close()
409
+ server.stop(true)
410
+ },
411
+ }
412
+ }