@glassly/miniapp-cli 0.1.10 → 0.1.11

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/src/sim/sim.ts ADDED
@@ -0,0 +1,333 @@
1
+ import {spawn} from "child_process"
2
+ import {createHash} from "crypto"
3
+ import {closeSync, openSync, existsSync, mkdirSync, readdirSync, readFileSync, unlinkSync, watch, writeFileSync, type FSWatcher} from "fs"
4
+ import {createRequire} from "module"
5
+ import os from "os"
6
+ import {dirname, join, resolve} from "path"
7
+ import {fileURLToPath} from "url"
8
+
9
+ import {runBuild} from "../dev.js"
10
+ import {validateManifest} from "../manifest.js"
11
+ import type {BackgroundHandle} from "./background.js"
12
+ import type {SimHostEvent, SimLogEntry, SimManifest} from "./host.js"
13
+
14
+ const DEFAULT_SIM_PORT = 4500
15
+ const PORT_SCAN_LIMIT = 50
16
+ const REBUILD_DEBOUNCE_MS = 150
17
+
18
+ export interface SimOptions {
19
+ cwd?: string
20
+ port?: number
21
+ device?: string
22
+ open?: boolean
23
+ openBrowser?: (url: string) => Promise<unknown> | unknown
24
+ }
25
+
26
+ export interface SimRecord {
27
+ port: number
28
+ pid: number
29
+ cwd: string
30
+ packageName: string
31
+ url: string
32
+ }
33
+
34
+ const COLOR = {reset: "\x1b[0m", dim: "\x1b[2m", red: "\x1b[31m", yellow: "\x1b[33m", magenta: "\x1b[35m", cyan: "\x1b[36m"}
35
+
36
+ export function simRecordDir(): string {
37
+ return join(os.tmpdir(), "glassly-sim")
38
+ }
39
+
40
+ export function simRecordPath(cwd: string): string {
41
+ return join(simRecordDir(), `${createHash("sha1").update(resolve(cwd)).digest("hex").slice(0, 16)}.json`)
42
+ }
43
+
44
+ export function listSimRecords(): SimRecord[] {
45
+ const dir = simRecordDir()
46
+ if (!existsSync(dir)) return []
47
+ const records: {record: SimRecord; mtime: number}[] = []
48
+ for (const name of readdirSync(dir)) {
49
+ if (!name.endsWith(".json")) continue
50
+ const path = join(dir, name)
51
+ try {
52
+ const record = JSON.parse(readFileSync(path, "utf-8")) as SimRecord
53
+ process.kill(record.pid, 0)
54
+ records.push({record, mtime: Bun.file(path).lastModified})
55
+ } catch {
56
+ try {
57
+ unlinkSync(path)
58
+ } catch {
59
+ /* someone else removed it */
60
+ }
61
+ }
62
+ }
63
+ return records.sort((a, b) => b.mtime - a.mtime).map((entry) => entry.record)
64
+ }
65
+
66
+ export interface DetachedSim extends SimRecord {
67
+ logPath: string
68
+ alreadyRunning: boolean
69
+ }
70
+
71
+ /**
72
+ * `command` is the argv that runs `glassly sim` in the foreground. A
73
+ * simulator already running for the project is reused.
74
+ */
75
+ export async function simDetached(options: {cwd?: string; command: string[]; timeoutMs?: number}): Promise<DetachedSim> {
76
+ const cwd = resolve(options.cwd ?? process.cwd())
77
+ const logPath = simRecordPath(cwd).replace(/\.json$/, ".log")
78
+ const running = listSimRecords().find((record) => record.cwd === cwd)
79
+ if (running) return {...running, logPath, alreadyRunning: true}
80
+
81
+ mkdirSync(simRecordDir(), {recursive: true})
82
+ const log = openSync(logPath, "w")
83
+ const child = spawn(options.command[0], options.command.slice(1), {cwd, detached: true, stdio: ["ignore", log, log]})
84
+ closeSync(log)
85
+ let exited: number | null = null
86
+ child.on("exit", (code) => (exited = code ?? 1))
87
+ child.unref()
88
+
89
+ const deadline = Date.now() + (options.timeoutMs ?? 120_000)
90
+ while (Date.now() < deadline) {
91
+ if (exited !== null) {
92
+ throw new Error(`The simulator exited before it was ready:\n${readFileSync(logPath, "utf-8").trim().split("\n").slice(-15).join("\n")}`)
93
+ }
94
+ const record = listSimRecords().find((candidate) => candidate.cwd === cwd)
95
+ if (record) {
96
+ const answered = await fetch(`http://127.0.0.1:${record.port}/api/status`).then(
97
+ (response) => response.ok,
98
+ () => false,
99
+ )
100
+ if (answered) return {...record, logPath, alreadyRunning: false}
101
+ }
102
+ await Bun.sleep(150)
103
+ }
104
+ child.kill()
105
+ throw new Error(`The simulator did not come up in time. Its output is in ${logPath}`)
106
+ }
107
+
108
+ function canListen(port: number): boolean {
109
+ try {
110
+ Bun.serve({hostname: "127.0.0.1", port, fetch: () => new Response()}).stop(true)
111
+ return true
112
+ } catch {
113
+ return false
114
+ }
115
+ }
116
+
117
+ function pickPort(start: number): number {
118
+ for (let port = start; port < start + PORT_SCAN_LIMIT; port++) if (canListen(port)) return port
119
+ throw new Error(`No free port between ${start} and ${start + PORT_SCAN_LIMIT - 1} for the simulator`)
120
+ }
121
+
122
+ function printLog(entry: SimLogEntry): void {
123
+ if (entry.source === "bridge") return
124
+ const d = new Date(entry.timestamp)
125
+ const time = [d.getHours(), d.getMinutes(), d.getSeconds()].map((n) => String(n).padStart(2, "0")).join(":")
126
+ const tag =
127
+ entry.source === "ui"
128
+ ? `${COLOR.cyan}[UI]${COLOR.reset}`
129
+ : entry.source === "background"
130
+ ? `${COLOR.magenta}[JSRuntime]${COLOR.reset}`
131
+ : `${COLOR.dim}[sim]${COLOR.reset}`
132
+ const color = entry.level === "error" ? COLOR.red : entry.level === "warn" ? COLOR.yellow : ""
133
+ console.log(`${COLOR.dim}${time}${COLOR.reset} ${tag} ${color}${entry.message}${color ? COLOR.reset : ""}`)
134
+ }
135
+
136
+ function readManifest(cwd: string): SimManifest & {entry: {background: string; ui?: string}} {
137
+ const path = resolve(cwd, "miniapp.json")
138
+ if (!existsSync(path)) throw new Error(`miniapp.json not found in ${cwd}`)
139
+ let manifest: Record<string, unknown>
140
+ try {
141
+ manifest = JSON.parse(readFileSync(path, "utf-8"))
142
+ } catch {
143
+ throw new Error("miniapp.json is not valid JSON")
144
+ }
145
+ const {valid, errors} = validateManifest(manifest)
146
+ if (!valid) throw new Error(`miniapp.json validation failed:\n${errors.map((e) => ` - ${e}`).join("\n")}`)
147
+ const entry = manifest.entry as {background?: string; ui?: string} | undefined
148
+ if (!entry || typeof entry.background !== "string") {
149
+ throw new Error("miniapp.json is missing `entry.background`; the simulator runs the background bundle.")
150
+ }
151
+ return manifest as unknown as SimManifest & {entry: {background: string; ui?: string}}
152
+ }
153
+
154
+ /**
155
+ * The host modules import SDK exports an older @glassly/miniapp lacks, so
156
+ * they load only after that check has produced a clear message.
157
+ */
158
+ async function loadHostModules() {
159
+ const require = createRequire(import.meta.url)
160
+ try {
161
+ require.resolve("@glassly/miniapp/host")
162
+ if (typeof (require("@glassly/miniapp/display") as {processScene?: unknown}).processScene !== "function") {
163
+ throw new Error("no scene pipeline")
164
+ }
165
+ } catch {
166
+ let found = "no @glassly/miniapp installed"
167
+ try {
168
+ found = `found ${(require("@glassly/miniapp/package.json") as {version: string}).version}`
169
+ } catch {
170
+ /* keep the default */
171
+ }
172
+ throw new Error(
173
+ `glassly sim needs a newer @glassly/miniapp than this project has (${found}). ` +
174
+ `Upgrade @glassly/miniapp in the project's dependencies and try again.`,
175
+ )
176
+ }
177
+ const [host, server, background, device, storage, screenshot] = await Promise.all([
178
+ import("./host.js"),
179
+ import("./server.js"),
180
+ import("./background.js"),
181
+ import("./device.js"),
182
+ import("./storage.js"),
183
+ import("./screenshot.js"),
184
+ ])
185
+ return {...host, ...server, ...background, ...device, ...storage, ...screenshot}
186
+ }
187
+
188
+ async function buildPage(): Promise<{html: string; js: string; css: string}> {
189
+ const dir = join(dirname(fileURLToPath(import.meta.url)), "client")
190
+ const result = await Bun.build({entrypoints: [join(dir, "main.ts")], target: "browser", minify: true})
191
+ if (!result.success) throw new Error(`Could not build the simulator page:\n${result.logs.join("\n")}`)
192
+ return {
193
+ html: readFileSync(join(dir, "index.html"), "utf-8"),
194
+ css: readFileSync(join(dir, "app.css"), "utf-8"),
195
+ js: await result.outputs[0].text(),
196
+ }
197
+ }
198
+
199
+ export async function sim(options: SimOptions = {}): Promise<void> {
200
+ const cwd = resolve(options.cwd ?? process.cwd())
201
+ const manifest = readManifest(cwd)
202
+ const modules = await loadHostModules()
203
+ const device = modules.simDevice(options.device)
204
+
205
+ console.log(`Building ${manifest.name} (${manifest.packageName})...`)
206
+ await runBuild(cwd)
207
+
208
+ const bundlePath = () => resolve(cwd, "dist", manifest.entry.background)
209
+ const ui = () => {
210
+ if (!manifest.entry.ui) return null
211
+ const entry = resolve(cwd, "dist", manifest.entry.ui)
212
+ return {dir: dirname(entry), entry: entry.slice(dirname(entry).length + 1)}
213
+ }
214
+
215
+ const screen = await modules.createScreenRenderer()
216
+ if (typeof screen === "string") console.warn(`Screenshots disabled: ${screen}`)
217
+
218
+ let background: BackgroundHandle | null = null
219
+ let server: ReturnType<typeof modules.startSimServer> | null = null
220
+ const host = new modules.SimHost({
221
+ manifest,
222
+ device,
223
+ storage: modules.createSimStorage(join(os.homedir(), ".glassly", "sim", manifest.packageName, "storage.json")),
224
+ toBackground: (raw) => background?.send(raw),
225
+ emit: (event: SimHostEvent) => {
226
+ if (event.type === "log") printLog(event.entry)
227
+ if (event.type === "exit") stopBackground(false)
228
+ server?.handle(event)
229
+ },
230
+ })
231
+
232
+ const stopBackground = (crashed: boolean) => {
233
+ background?.stop()
234
+ background = null
235
+ host.backgroundStopped(crashed)
236
+ }
237
+
238
+ const startBackground = () => {
239
+ background?.stop()
240
+ host.backgroundStarted()
241
+ background = modules.startBackground(bundlePath(), {
242
+ onBridge: (raw) => host.fromBackground(raw),
243
+ onLog: (level, args) => host.log("background", level, modules.formatLogArgs(args)),
244
+ onError: (message, stack) => host.log("background", "error", stack || message),
245
+ onCrash: () => {
246
+ host.log("host", "error", "The background script failed to start. Fix it and save to try again.")
247
+ stopBackground(true)
248
+ },
249
+ })
250
+ }
251
+
252
+ const port = pickPort(options.port ?? DEFAULT_SIM_PORT)
253
+ let watcher: FSWatcher | null = null
254
+ let shuttingDown = false
255
+ const shutdown = () => {
256
+ if (shuttingDown) return
257
+ shuttingDown = true
258
+ watcher?.close()
259
+ background?.stop()
260
+ server?.stop()
261
+ try {
262
+ unlinkSync(simRecordPath(cwd))
263
+ } catch {
264
+ /* already gone */
265
+ }
266
+ process.exit(0)
267
+ }
268
+
269
+ server = modules.startSimServer({
270
+ host,
271
+ port,
272
+ packageName: manifest.packageName,
273
+ ui: ui(),
274
+ screen,
275
+ page: await buildPage(),
276
+ restart: async () => startBackground(),
277
+ stop: shutdown,
278
+ })
279
+ startBackground()
280
+
281
+ let pending: "ui" | "all" | null = null
282
+ let manifestChanged = false
283
+ let timer: ReturnType<typeof setTimeout> | null = null
284
+ let quietUntil = 0
285
+ const under = (file: string, name: string) =>
286
+ file === name || file.startsWith(`${name}/`) || file.includes(`/${name}/`)
287
+ watcher = watch(cwd, {recursive: true}, (_event, filename) => {
288
+ if (!filename || filename === "." || Date.now() < quietUntil) return
289
+ const file = filename.split("\\").join("/")
290
+ if (["node_modules", ".git", "dist", "build"].some((name) => under(file, name))) return
291
+ const scope = file.startsWith("src/ui/") ? "ui" : "all"
292
+ if (file === "miniapp.json") manifestChanged = true
293
+ pending = pending === "all" ? "all" : scope
294
+ if (timer) clearTimeout(timer)
295
+ timer = setTimeout(async () => {
296
+ const what = pending
297
+ pending = null
298
+ timer = null
299
+ quietUntil = Date.now() + 1_500
300
+ if (manifestChanged) {
301
+ manifestChanged = false
302
+ host.log("host", "warn", "miniapp.json changed: restart glassly sim to apply its permissions and entries")
303
+ }
304
+ try {
305
+ await runBuild(cwd, {capture: true})
306
+ } catch (error) {
307
+ host.log("host", "error", `Rebuild failed: ${(error as Error).message}`)
308
+ quietUntil = Date.now() + 1_500
309
+ return
310
+ }
311
+ quietUntil = Date.now() + 1_500
312
+ host.log("host", "info", `${what === "ui" ? "reload" : "respawn-bg"} ${file}`)
313
+ if (what === "all") startBackground()
314
+ server?.reloadUi()
315
+ }, REBUILD_DEBOUNCE_MS)
316
+ })
317
+
318
+ const url = `http://localhost:${server.port}`
319
+ mkdirSync(simRecordDir(), {recursive: true})
320
+ const record: SimRecord = {port: server.port, pid: process.pid, cwd, packageName: manifest.packageName, url}
321
+ writeFileSync(simRecordPath(cwd), JSON.stringify(record))
322
+
323
+ console.log(`\nGlassly Simulator running ${manifest.name} on ${device.capabilities.modelName}`)
324
+ console.log(` Window: ${url}`)
325
+ if (manifest.entry.ui) console.log(` Phone page: ${url}/ui/`)
326
+ console.log(` Control: glassly sim screenshot | screen | tap | say "..." | logs (glassly sim --help)`)
327
+ console.log(` Saving a source file rebuilds and reloads. Ctrl+C stops.\n`)
328
+
329
+ process.on("SIGINT", shutdown)
330
+ process.on("SIGTERM", shutdown)
331
+ if (options.open !== false && options.openBrowser) await options.openBrowser(url)
332
+ await new Promise<void>(() => {})
333
+ }
@@ -0,0 +1,46 @@
1
+ import {existsSync, mkdirSync, readFileSync, writeFileSync} from "fs"
2
+ import {dirname} from "path"
3
+
4
+ export interface SimStorage {
5
+ get(key: string): string | null
6
+ set(key: string, value: string | null): void
7
+ delete(key: string): void
8
+ keys(): string[]
9
+ getAll(): Record<string, string>
10
+ clear(): void
11
+ }
12
+
13
+ export function createSimStorage(path?: string): SimStorage {
14
+ let values: Record<string, string> = {}
15
+ if (path && existsSync(path)) {
16
+ try {
17
+ const parsed = JSON.parse(readFileSync(path, "utf-8"))
18
+ if (parsed && typeof parsed === "object") values = parsed as Record<string, string>
19
+ } catch {
20
+ values = {}
21
+ }
22
+ }
23
+ const persist = () => {
24
+ if (!path) return
25
+ mkdirSync(dirname(path), {recursive: true})
26
+ writeFileSync(path, JSON.stringify(values, null, 2))
27
+ }
28
+ return {
29
+ get: (key) => (key in values ? values[key] : null),
30
+ set(key, value) {
31
+ if (value === null) delete values[key]
32
+ else values[key] = value
33
+ persist()
34
+ },
35
+ delete(key) {
36
+ delete values[key]
37
+ persist()
38
+ },
39
+ keys: () => Object.keys(values),
40
+ getAll: () => ({...values}),
41
+ clear() {
42
+ values = {}
43
+ persist()
44
+ },
45
+ }
46
+ }