@glassly/miniapp-cli 0.1.0-beta.3

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,454 @@
1
+ // Sidecar dev server for `glassly dev`. Runs on `userPort + 1`,
2
+ // alongside the static file server `dev.ts` boots on `userPort`. Hosts
3
+ // the `__host_dev` WebSocket multiplexed channel:
4
+ //
5
+ // laptop → phone : {type: "reload"} (UI WebView reload — filesystem watcher fired in src/ui)
6
+ // laptop → phone : {type: "respawn-bg"} (background JSContext respawn — filesystem watcher fired in src/background)
7
+ // phone → laptop: {type: "log", level, args, ...} (forwarded console calls)
8
+ //
9
+ // Plus a hello handshake (`{type: "hello", protocol: "glassly-dev/1"}` →
10
+ // `{type: "hello-ack"}`) so a phone connecting to the wrong sidecar (or an
11
+ // older one) can detect mismatch.
12
+ //
13
+ // Also exposes `/__host_dev/bundle.zip` — a flat snapshot of the
14
+ // project (including `dist/`) the phone-side install pipeline downloads
15
+ // and unpacks into `lmas/<pkg>/dev-<ts>/`. `onBeforeBroadcast` is the
16
+ // hook that rebuilds `dist/` before each broadcast so the next zip
17
+ // fetch ships current code.
18
+
19
+ import {readdirSync, readFileSync, statSync, watch} from "fs"
20
+ import {join, relative} from "path"
21
+ import JSZip from "jszip"
22
+ import type {ServerWebSocket} from "bun"
23
+
24
+ export interface DevServerOptions {
25
+ port: number
26
+ /** Project root to watch for filesystem changes. Triggers reload broadcasts. */
27
+ watchDir: string
28
+ /** Suppress info console.log output. Default false. */
29
+ silent?: boolean
30
+ /**
31
+ * Hook run inside the debounced broadcast window, after the filesystem
32
+ * settles but before the phone is notified. Two-layer projects use this
33
+ * to rebuild the `dist/` snapshot so the next `bundle.zip` fetch ships
34
+ * fresh code. Rejection is caught + logged; the broadcast still fires.
35
+ */
36
+ onBeforeBroadcast?: (type: "reload" | "respawn-bg") => Promise<void>
37
+ }
38
+
39
+ interface ClientWsData {
40
+ packageName: string | null
41
+ remoteAddress: string
42
+ }
43
+
44
+ const PROTOCOL_VERSION = "glassly-dev/1"
45
+ const RELOAD_DEBOUNCE_MS = 100
46
+
47
+ /** Inbound message from the phone. */
48
+ type Inbound =
49
+ | {type: "hello"; protocol: string}
50
+ | {
51
+ type: "log"
52
+ level: string
53
+ args: unknown[]
54
+ packageName: string
55
+ timestamp: number
56
+ /**
57
+ * Which half of the miniapp emitted the log. UI = WebView, background
58
+ * = JSContext. Lets us prefix lines so devs can tell the always-on
59
+ * glasses logic apart from the WebView UI when both are noisy.
60
+ */
61
+ source: "ui" | "background"
62
+ }
63
+
64
+ const COLOR = {
65
+ reset: "\x1b[0m",
66
+ dim: "\x1b[2m",
67
+ red: "\x1b[31m",
68
+ yellow: "\x1b[33m",
69
+ magenta: "\x1b[35m",
70
+ cyan: "\x1b[36m",
71
+ }
72
+
73
+ function colorForLevel(level: string): string {
74
+ switch (level) {
75
+ case "error":
76
+ return COLOR.red
77
+ case "warn":
78
+ return COLOR.yellow
79
+ case "info":
80
+ case "debug":
81
+ return COLOR.dim
82
+ default:
83
+ return COLOR.cyan
84
+ }
85
+ }
86
+
87
+ function formatLogArgs(args: unknown[]): string {
88
+ return args
89
+ .map((a) => {
90
+ if (a !== null && typeof a === "object" && (a as Record<string, unknown>).__error === true) {
91
+ const err = a as {message?: string; stack?: string}
92
+ return err.stack || err.message || String(a)
93
+ }
94
+ if (typeof a === "string") return a
95
+ try {
96
+ return JSON.stringify(a)
97
+ } catch {
98
+ return String(a)
99
+ }
100
+ })
101
+ .join(" ")
102
+ }
103
+
104
+ function fmtTime(ts: number): string {
105
+ const d = new Date(ts)
106
+ const hh = String(d.getHours()).padStart(2, "0")
107
+ const mm = String(d.getMinutes()).padStart(2, "0")
108
+ const ss = String(d.getSeconds()).padStart(2, "0")
109
+ return `${hh}:${mm}:${ss}`
110
+ }
111
+
112
+ /**
113
+ * Start the sidecar. Returns a handle with `stop()` so dev.ts can clean up on
114
+ * SIGINT.
115
+ */
116
+ export function startDevSidecar(options: DevServerOptions): {stop: () => void; port: number} {
117
+ const sockets = new Set<ServerWebSocket<ClientWsData>>()
118
+ const log = options.silent ? () => {} : (...args: unknown[]) => console.log(...args)
119
+
120
+ const server = Bun.serve<ClientWsData>({
121
+ hostname: "0.0.0.0",
122
+ port: options.port,
123
+ fetch(req, srv) {
124
+ const url = new URL(req.url)
125
+ if (url.pathname === "/__host_dev/health") {
126
+ return new Response(JSON.stringify({ok: true, protocol: PROTOCOL_VERSION}), {
127
+ headers: {"content-type": "application/json"},
128
+ })
129
+ }
130
+ if (url.pathname === "/__host_dev/bundle.zip") {
131
+ // Snapshot of the project files for the phone-side bundle cache.
132
+ // Phone calls Composer.installMiniApp(this URL) to download + unzip
133
+ // into lmas/<pkg>/dev-<timestamp>/ — same path store-installed
134
+ // miniapps take, just with a dev-prefixed version directory.
135
+ //
136
+ // Files are placed at the zip root (no enclosing folder). The
137
+ // unpacker on the phone side requires miniapp.json to be at the
138
+ // top level. Flat structure makes that contract clean.
139
+ return buildProjectZip(options.watchDir).then((buf) => {
140
+ // `bun-types` typed Response body as ArrayBuffer / Blob / etc.
141
+ // — but NOT a raw Uint8Array view. Pass the underlying buffer
142
+ // slice instead so the response stream gets the exact bytes.
143
+ const body = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer
144
+ return new Response(body, {
145
+ headers: {
146
+ "content-type": "application/zip",
147
+ "content-length": String(buf.byteLength),
148
+ },
149
+ })
150
+ })
151
+ }
152
+ if (url.pathname === "/__host_dev") {
153
+ const upgraded = srv.upgrade(req, {
154
+ data: {packageName: null, remoteAddress: srv.requestIP(req)?.address ?? "unknown"},
155
+ })
156
+ if (upgraded) return undefined
157
+ return new Response("WebSocket upgrade required", {status: 400})
158
+ }
159
+ return new Response("Not found", {status: 404})
160
+ },
161
+ websocket: {
162
+ open(ws) {
163
+ sockets.add(ws)
164
+ // Quiet on connect — the `reload` line tells the dev their
165
+ // device is plugged into the sidecar. Otherwise normal HMR
166
+ // cycles (which respawn the JSContext + WebView) spam
167
+ // connected/disconnected pairs per filesystem change.
168
+ },
169
+ message(ws, message) {
170
+ let parsed: Inbound
171
+ try {
172
+ parsed = JSON.parse(typeof message === "string" ? message : new TextDecoder().decode(message)) as Inbound
173
+ } catch {
174
+ return
175
+ }
176
+ switch (parsed.type) {
177
+ case "hello": {
178
+ // Echo back so the phone confirms the right server.
179
+ ws.send(JSON.stringify({type: "hello-ack", protocol: PROTOCOL_VERSION}))
180
+ return
181
+ }
182
+ case "log": {
183
+ const color = colorForLevel(parsed.level)
184
+ // Source-prefix lets devs tell UI ↔ background apart at a
185
+ // glance. UI cyan, JSRuntime magenta.
186
+ const sourceTag =
187
+ parsed.source === "ui"
188
+ ? `${COLOR.cyan}[UI]${COLOR.reset}`
189
+ : `${COLOR.magenta}[JSRuntime]${COLOR.reset}`
190
+ const tag = `${color}${parsed.level}${COLOR.reset}`
191
+ const body = formatLogArgs(parsed.args ?? [])
192
+ log(
193
+ `${COLOR.dim}${fmtTime(parsed.timestamp ?? Date.now())}${COLOR.reset} ${sourceTag} ${tag} ${body}`,
194
+ )
195
+ return
196
+ }
197
+ }
198
+ },
199
+ close(ws) {
200
+ sockets.delete(ws)
201
+ // Quiet on disconnect — see open(); steady-state HMR cycles
202
+ // through this constantly and there's nothing the dev does
203
+ // with the signal.
204
+ },
205
+ },
206
+ })
207
+
208
+ // Filesystem watcher → broadcast reload or respawn-bg depending on which
209
+ // layer changed. Background code lives under `src/background/` and UI
210
+ // code under `src/ui/`; a touch under `src/background/` requires killing
211
+ // + re-spawning the JSContext, while a touch under `src/ui/` only needs
212
+ // a WebView reload. Touches anywhere else default to reload.
213
+ let reloadTimer: ReturnType<typeof setTimeout> | null = null
214
+ let pendingType: "reload" | "respawn-bg" | null = null
215
+ let suppressEventsUntil = 0
216
+ // True when a path either equals `name` or sits under `name/`. macOS
217
+ // FSEvents under `recursive: true` emits the bare directory name when
218
+ // the directory itself is rm-rf'd or renamed; matching only `name/`
219
+ // would let that event through and cause a rebuild loop.
220
+ const isUnder = (filename: string, name: string): boolean =>
221
+ filename === name || filename.startsWith(`${name}/`) || filename.includes(`/${name}/`)
222
+
223
+ const watcher = watch(options.watchDir, {recursive: true}, (_event, filename) => {
224
+ if (!filename) return
225
+ if (Date.now() < suppressEventsUntil) return
226
+ // macOS recursive FSEvents can report "." when the build removes and
227
+ // recreates dist/. Treat that as build-output churn; otherwise the dev
228
+ // server rebuilds in a tight loop.
229
+ if (filename === ".") return
230
+ // Skip noisy directories — most projects don't want to reload on
231
+ // node_modules or dist churn (the rebuild itself rewrites dist/,
232
+ // which would otherwise loop).
233
+ if (isUnder(filename, "node_modules")) return
234
+ if (isUnder(filename, ".git")) return
235
+ if (isUnder(filename, "dist")) return
236
+ if (isUnder(filename, "build")) return // pack/release zip output
237
+ if (isUnder(filename, ".next")) return
238
+
239
+ // Decide which layer the change touched. Order matters: a single batch
240
+ // may hit both layers; if so, respawn-bg wins (it implies a full reload
241
+ // anyway on the WebView side because background drives the UI state).
242
+ const touchedBackground =
243
+ filename.startsWith("src/background/") || filename.includes("/src/background/")
244
+ const nextType: "reload" | "respawn-bg" = touchedBackground ? "respawn-bg" : "reload"
245
+ if (pendingType === "respawn-bg") {
246
+ // already locked in to the heavier signal — leave it
247
+ } else {
248
+ pendingType = nextType
249
+ }
250
+
251
+ if (reloadTimer) clearTimeout(reloadTimer)
252
+ reloadTimer = setTimeout(async () => {
253
+ reloadTimer = null
254
+ const type = pendingType ?? "reload"
255
+ pendingType = null
256
+ // Two-layer projects rebuild `dist/` here so the next bundle.zip
257
+ // fetch ships current code. A build failure surfaces in the
258
+ // terminal but does not block the broadcast — phones will install
259
+ // whatever the previous successful build left behind.
260
+ if (options.onBeforeBroadcast) {
261
+ try {
262
+ suppressEventsUntil = Date.now() + 1_500
263
+ await options.onBeforeBroadcast(type)
264
+ suppressEventsUntil = Date.now() + 1_500
265
+ } catch (err) {
266
+ suppressEventsUntil = Date.now() + 1_500
267
+ log(`${COLOR.red}[__host_dev] onBeforeBroadcast failed:${COLOR.reset} ${(err as Error).message}`)
268
+ }
269
+ }
270
+ const msg = JSON.stringify({type})
271
+ let count = 0
272
+ for (const s of sockets) {
273
+ try {
274
+ s.send(msg)
275
+ count++
276
+ } catch {
277
+ /* ignore */
278
+ }
279
+ }
280
+ if (count > 0) {
281
+ // Concise reload line — match React Native Metro's style.
282
+ // `reload` covers the common case; `respawn-bg` is rarer so
283
+ // we tag it explicitly so the dev knows the JSContext is
284
+ // restarting (which clears in-memory state in the
285
+ // controller).
286
+ const verb = type === "respawn-bg" ? "respawn-bg" : "reload"
287
+ log(`${COLOR.cyan}${verb}${COLOR.reset} ${COLOR.dim}${filename}${COLOR.reset}`)
288
+ }
289
+ }, RELOAD_DEBOUNCE_MS)
290
+ })
291
+
292
+ log(`${COLOR.dim}[__host_dev]${COLOR.reset} sidecar listening on :${options.port}`)
293
+
294
+ return {
295
+ port: options.port,
296
+ stop() {
297
+ try {
298
+ watcher.close()
299
+ } catch {
300
+ /* ignore */
301
+ }
302
+ if (reloadTimer) clearTimeout(reloadTimer)
303
+ for (const s of sockets) {
304
+ try {
305
+ s.close()
306
+ } catch {
307
+ /* ignore */
308
+ }
309
+ }
310
+ sockets.clear()
311
+ server.stop(true)
312
+ },
313
+ }
314
+ }
315
+
316
+ /**
317
+ * One file to include in the bundle zip.
318
+ * - `disk` : path on disk, relative to the project root (used to read it).
319
+ * - `entry` : zip-internal name (used to store it in the zip).
320
+ *
321
+ * These diverge for build output: it lives under `dist/` on disk but ships at
322
+ * the bundle root (`dist/` stripped), so the zip layout matches `entry.*` in
323
+ * miniapp.json — which the host resolves relative to the bundle root.
324
+ */
325
+ export interface ProjectFile {
326
+ disk: string
327
+ entry: string
328
+ }
329
+
330
+ /**
331
+ * Walk the dev project's directory tree and return the files to include in
332
+ * the bundle zip, as {disk, entry} pairs.
333
+ *
334
+ * STRICT runtime-artifact allowlist:
335
+ * - miniapp.json at the root (required — unpacker fails without it)
336
+ * - icon.png (or whatever `manifest.icon` points at) — used for the
337
+ * home tile and the QR-scan icon preview
338
+ * - dist/ — the entire two-layer build output: dist/background/*.js
339
+ * and dist/ui/* (HTML, JS chunks, CSS chunks). Recursively included.
340
+ * The `dist/` prefix is stripped off the zip entry name (see ProjectFile),
341
+ * so `dist/background/index.js` ships as `background/index.js`.
342
+ *
343
+ * Source files (src/), build config (package.json, tsconfig.json,
344
+ * build.ts, bunfig.toml), node_modules/, public/, and stray pack
345
+ * artifacts (*.zip) are deliberately NOT shipped. They aren't read by
346
+ * the runtime and including them adds tens-to-hundreds of KB per
347
+ * install — slow on flaky LAN, painful for a "hot reload" loop.
348
+ *
349
+ * Entry names have no leading slash — the phone-side unpacker
350
+ * (Composer.installMiniApp) needs them exactly that way to reconstruct the
351
+ * directory tree on disk.
352
+ */
353
+ export function listProjectFiles(rootDir: string): ProjectFile[] {
354
+ const out: ProjectFile[] = []
355
+
356
+ // miniapp.json (required at zip root).
357
+ const manifestPath = join(rootDir, "miniapp.json")
358
+ let manifest: Record<string, unknown> | null = null
359
+ try {
360
+ if (statSync(manifestPath).isFile()) {
361
+ out.push({disk: "miniapp.json", entry: "miniapp.json"})
362
+ manifest = JSON.parse(readFileSync(manifestPath, "utf-8")) as Record<string, unknown>
363
+ }
364
+ } catch {
365
+ /* no manifest yet — the dev server will refuse to start; not our
366
+ problem here. */
367
+ }
368
+
369
+ // Icon (whatever path the manifest declares; default `icon.png`).
370
+ const iconRel = typeof manifest?.icon === "string" ? manifest.icon : "icon.png"
371
+ try {
372
+ if (statSync(join(rootDir, iconRel)).isFile()) {
373
+ const rel = iconRel.replace(/^\//, "")
374
+ out.push({disk: rel, entry: rel})
375
+ }
376
+ } catch {
377
+ /* no icon — non-fatal, the home tile will just render the fallback. */
378
+ }
379
+
380
+ // dist/ — full recursive walk. `onBeforeBroadcast` in `dev.ts` runs
381
+ // a fresh build before each broadcast, so what we read here is
382
+ // current at zip time. MAX_FILES guards against pathological cases
383
+ // (e.g. someone copying public/ into dist/).
384
+ const distRoot = join(rootDir, "dist")
385
+ const MAX_FILES = 500
386
+ const MAX_DEPTH = 10
387
+ type Frame = {dir: string; depth: number}
388
+ const queue: Frame[] = []
389
+ try {
390
+ if (statSync(distRoot).isDirectory()) queue.push({dir: distRoot, depth: 0})
391
+ } catch {
392
+ /* no dist yet — initial build failed or hasn't run; ship the
393
+ manifest + icon and let the host log "missing entry path". */
394
+ }
395
+ while (queue.length > 0 && out.length < MAX_FILES) {
396
+ const {dir, depth} = queue.shift()!
397
+ let entries: string[]
398
+ try {
399
+ entries = readdirSync(dir)
400
+ } catch {
401
+ continue
402
+ }
403
+ for (const entry of entries) {
404
+ if (entry.startsWith(".")) continue
405
+ const abs = join(dir, entry)
406
+ let stat
407
+ try {
408
+ stat = statSync(abs)
409
+ } catch {
410
+ continue
411
+ }
412
+ if (stat.isDirectory()) {
413
+ if (depth + 1 <= MAX_DEPTH) queue.push({dir: abs, depth: depth + 1})
414
+ } else if (stat.isFile()) {
415
+ const disk = relative(rootDir, abs).split("\\").join("/")
416
+ // Strip the leading `dist/` so build output ships at the bundle root.
417
+ const entryName = disk.replace(/^dist\//, "")
418
+ out.push({disk, entry: entryName})
419
+ if (out.length >= MAX_FILES) {
420
+ console.warn(
421
+ `[__host_dev] dist file list truncated at ${MAX_FILES} entries — bundle may be incomplete`,
422
+ )
423
+ return out
424
+ }
425
+ }
426
+ }
427
+ }
428
+
429
+ return out
430
+ }
431
+
432
+ /**
433
+ * Build a flat ZIP of the project files (files at zip root, no enclosing
434
+ * folder). Returns the encoded buffer.
435
+ *
436
+ * The phone-side unpacker (Composer.installMiniApp) requires miniapp.json
437
+ * to be at the zip's top level. Flat structure keeps the contract clean
438
+ * — the unpacker can fail loudly if the zip is malformed instead of
439
+ * tolerating multiple shapes.
440
+ */
441
+ export async function buildProjectZip(rootDir: string): Promise<Uint8Array> {
442
+ const zip = new JSZip()
443
+ for (const {disk, entry} of listProjectFiles(rootDir)) {
444
+ const abs = join(rootDir, disk)
445
+ try {
446
+ const buf = readFileSync(abs)
447
+ zip.file(entry, buf)
448
+ } catch (err) {
449
+ console.warn(`[__host_dev] failed to read ${disk}, skipping:`, err)
450
+ }
451
+ }
452
+ // STORE (no compression) — small project trees, deterministic, fast.
453
+ return zip.generateAsync({type: "uint8array", compression: "STORE"})
454
+ }