@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/README.md CHANGED
@@ -22,6 +22,7 @@ stays a dev dependency next to `@glassly/cli`.
22
22
  | Command | What it does |
23
23
  | ------------------------------------------------- | ------------------------------------------------------------------------- |
24
24
  | [`dev`](#dev) | Starts the dev server with hot reload, prints a QR to load it on a phone |
25
+ | [`sim`](#sim) | Runs the miniapp in the desktop simulator; subcommands drive it |
25
26
  | [`release`](#release) | Builds, packs, and serves a QR to install the release on a phone over LAN |
26
27
  | [`pack`](#pack) | Validates the manifest and zips `dist/` into `<pkg>-<version>.zip` |
27
28
  | [`manifest`](#manifest) | Interactive top-level wizard for editing `miniapp.json` |
@@ -66,6 +67,45 @@ that works without the computer.
66
67
 
67
68
  `Ctrl+C` stops the server, the sidecar, and the IP watcher.
68
69
 
70
+ ## `sim`
71
+
72
+ ```bash
73
+ glassly sim # build, run, open the simulator window
74
+ glassly sim --no-open # same, without a browser
75
+ glassly sim --detach # start in the background, return once it answers
76
+ ```
77
+
78
+ Runs a miniapp with no phone and no glasses:
79
+
80
+ 1. Validates `miniapp.json` and runs the project's `build.ts`.
81
+ 2. Evaluates `dist/background/index.js` in a Bun worker that provides the
82
+ `__dispatch` bridge the SDK's `DispatchTransport` expects. Node and Bun
83
+ globals the phone's JS context lacks (`process`, `Buffer`, `require`,
84
+ `performance`, ...) are hidden from the bundle.
85
+ 3. Answers the bundle's requests from `SimHost` (`src/sim/host.ts`), which
86
+ mirrors the Glassly App's runtime for the calls it covers and replies
87
+ `NOT_IMPLEMENTED` for the rest. Scenes go through the SDK's own
88
+ `processScene` / `diffScene` (`@glassly/miniapp/display`), the code the app
89
+ runs, against the app's Simulated Glasses profile.
90
+ 4. Serves the simulator window, the miniapp's UI page at `/ui/` (with the
91
+ `window.Glassly` globals and `window.glassly` shim from
92
+ `@glassly/miniapp/host`, carried over a WebSocket), and a JSON control API
93
+ under `/api/`, all on `127.0.0.1` (default port `4500`).
94
+ 5. Watches the project: a change under `src/ui/` reloads the page, anything else
95
+ restarts the background too.
96
+
97
+ Every `glassly sim <subcommand>` (`screen`, `screenshot`, `tap`, `say`, `logs`,
98
+ `ui request`, ...) is a call to that control API on the simulator running for
99
+ the current project, found through a record in the OS temp directory.
100
+ `screenshot` draws the display off screen with `MirrorCanvasRenderer` on
101
+ `@napi-rs/canvas`, the same renderer the window uses.
102
+
103
+ The simulator needs an `@glassly/miniapp` that exports `@glassly/miniapp/host`;
104
+ on an older SDK it says so and exits.
105
+
106
+ What it covers, and what it does not, is listed in the public docs:
107
+ <https://docs.glassly.ai/app-devs/getting-started/simulator>.
108
+
69
109
  ## `release`
70
110
 
71
111
  ```bash
@@ -246,5 +286,6 @@ The allowed-value lists are read from the project's installed `@glassly/miniapp`
246
286
  - Manifest read/write helpers: `src/manifest-format.ts`
247
287
  - Permission/hardware human-readable hints: `src/permission-hints.ts`
248
288
  - Dev sidecar WebSocket server: `src/dev-server.ts`
289
+ - Simulator: `src/sim/` (`sim.ts` command, `host.ts` protocol, `server.ts` window + control API, `background.ts` worker, `screenshot.ts`, `client/` window page)
249
290
  - QR rendering: `src/qr.ts`
250
291
  - Generated JSON Schema: `schema/miniapp.schema.json` (regenerated via `schema regenerate`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glassly/miniapp-cli",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "description": "Build tooling for Glassly miniapps: dev server, packer, manifest validation, and JSON Schema. The `glassly` command that drives it ships in @glassly/cli.",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -18,6 +18,7 @@
18
18
  },
19
19
  "dependencies": {
20
20
  "@clack/prompts": "^1.9.0",
21
+ "@napi-rs/canvas": "^1.1.0",
21
22
  "@number0/iroh": "^1.2.0",
22
23
  "jszip": "^3.10.2",
23
24
  "qrcode": "^1.5.4",
package/src/api.ts CHANGED
@@ -1,5 +1,16 @@
1
1
  export { buildProduction } from './build.js';
2
2
  export { dev, type DevAttestationInput, type DevOptions } from './dev.js';
3
+ export { sim, simDetached, listSimRecords, type DetachedSim, type SimOptions, type SimRecord } from './sim/sim.js';
4
+ export {
5
+ findSim,
6
+ simGet,
7
+ simLogs,
8
+ simPost,
9
+ simScreenshot,
10
+ simText,
11
+ type SimLogLine,
12
+ type SimTarget,
13
+ } from './sim/control.js';
3
14
  export { pack, PACK_EXTENSION, type PackOptions } from './pack.js';
4
15
  export { release, type ReleaseOptions } from './release.js';
5
16
  export { runManifestWizard } from './manifest-wizard.js';
package/src/dev.ts CHANGED
@@ -76,7 +76,7 @@ function pickDevPort(start: number): number {
76
76
  * The sidecar's `bundle.zip` endpoint reads from disk, so the build must
77
77
  * finish before the phone fetches.
78
78
  */
79
- async function runBuild(cwd: string): Promise<void> {
79
+ export async function runBuild(cwd: string, options: {capture?: boolean} = {}): Promise<void> {
80
80
  const buildScript = resolve(cwd, 'build.ts');
81
81
  if (!existsSync(buildScript)) {
82
82
  throw new Error(
@@ -87,12 +87,15 @@ async function runBuild(cwd: string): Promise<void> {
87
87
  }
88
88
  const proc = Bun.spawn(['bun', 'run', 'build.ts'], {
89
89
  cwd,
90
- stdout: 'inherit',
91
- stderr: 'inherit',
90
+ stdout: options.capture ? 'pipe' : 'inherit',
91
+ stderr: options.capture ? 'pipe' : 'inherit',
92
92
  });
93
+ const output = options.capture
94
+ ? (await Promise.all([new Response(proc.stdout as ReadableStream).text(), new Response(proc.stderr as ReadableStream).text()])).join('')
95
+ : '';
93
96
  const code = await proc.exited;
94
97
  if (code !== 0) {
95
- throw new Error(`build.ts exited with code ${code}`);
98
+ throw new Error(`build.ts exited with code ${code}${output.trim() ? `\n${output.trim()}` : ''}`);
96
99
  }
97
100
  }
98
101
 
@@ -0,0 +1,112 @@
1
+ // Worker entry: stands in for the phone's per-miniapp JS context, with the
2
+ // `__dispatch` bridge and init callback the phone's polyfill provides.
3
+
4
+ interface WorkerScope {
5
+ postMessage(message: unknown): void
6
+ onmessage: ((event: {data: Inbound}) => void) | null
7
+ addEventListener(type: string, listener: (event: any) => void): void
8
+ }
9
+
10
+ type Inbound = {type: "run"; code: string; sourceUrl: string} | {type: "bridge"; raw: string}
11
+
12
+ const scope = globalThis as unknown as WorkerScope
13
+ const g = globalThis as Record<string, any>
14
+
15
+ function serialize(arg: unknown): unknown {
16
+ if (arg instanceof Error) return {__error: true, message: arg.message, stack: arg.stack}
17
+ if (arg === null || typeof arg !== "object") return typeof arg === "function" ? String(arg) : arg
18
+ const seen = new WeakSet<object>()
19
+ try {
20
+ return JSON.parse(
21
+ JSON.stringify(arg, (_key, value) => {
22
+ if (value !== null && typeof value === "object") {
23
+ if (seen.has(value)) return "[Circular]"
24
+ seen.add(value)
25
+ }
26
+ return typeof value === "bigint" ? String(value) : value
27
+ }),
28
+ )
29
+ } catch {
30
+ return String(arg)
31
+ }
32
+ }
33
+
34
+ for (const level of ["log", "info", "warn", "error", "debug"] as const) {
35
+ console[level] = (...args: unknown[]) => scope.postMessage({type: "log", level, args: args.map(serialize)})
36
+ }
37
+
38
+ function fail(reason: unknown): void {
39
+ const error = reason instanceof Error ? reason : new Error(String(reason))
40
+ scope.postMessage({type: "error", message: error.message, stack: error.stack ?? ""})
41
+ }
42
+
43
+ g.__dispatch = (iface: string, method: string, argsJson: string): string | null => {
44
+ if (iface === "__bridge" && method === "send") {
45
+ const [raw] = JSON.parse(argsJson) as [string]
46
+ scope.postMessage({type: "bridge", raw})
47
+ }
48
+ return null
49
+ }
50
+
51
+ g.__hostError = (payloadJson: string) => {
52
+ try {
53
+ const {message, stack} = JSON.parse(payloadJson) as {message?: string; stack?: string}
54
+ scope.postMessage({type: "error", message: message ?? "unknown error", stack: stack ?? ""})
55
+ } catch {
56
+ scope.postMessage({type: "error", message: payloadJson, stack: ""})
57
+ }
58
+ }
59
+
60
+ if (typeof g.localStorage === "undefined") {
61
+ const values = new Map<string, string>()
62
+ g.localStorage = {
63
+ getItem: (key: string) => values.get(String(key)) ?? null,
64
+ setItem: (key: string, value: string) => void values.set(String(key), String(value)),
65
+ removeItem: (key: string) => void values.delete(String(key)),
66
+ clear: () => values.clear(),
67
+ key: (index: number) => [...values.keys()][index] ?? null,
68
+ get length() {
69
+ return values.size
70
+ },
71
+ }
72
+ }
73
+
74
+ scope.addEventListener("error", (event) => fail(event?.error ?? event?.message))
75
+ scope.addEventListener("unhandledrejection", (event) => {
76
+ event?.preventDefault?.()
77
+ fail(event?.reason)
78
+ })
79
+
80
+ // The phone's context has none of these; hiding them makes a bundle that
81
+ // leans on Node or Bun fail here the way it would on a phone.
82
+ const HIDDEN = [
83
+ "process",
84
+ "Bun",
85
+ "require",
86
+ "module",
87
+ "exports",
88
+ "Buffer",
89
+ "__dirname",
90
+ "__filename",
91
+ "setImmediate",
92
+ "performance",
93
+ ]
94
+
95
+ scope.onmessage = (event) => {
96
+ const message = event.data
97
+ if (message.type === "bridge") {
98
+ g.__deliverBridgeRaw?.(message.raw)
99
+ return
100
+ }
101
+ try {
102
+ new Function(...HIDDEN, `${message.code}\n//# sourceURL=${message.sourceUrl}`)()
103
+ if (typeof g.__initCallback !== "function") {
104
+ throw new Error("The background bundle never called registerMiniapp() from @glassly/miniapp/background")
105
+ }
106
+ g.__initCallback("sim")
107
+ scope.postMessage({type: "started"})
108
+ } catch (error) {
109
+ fail(error)
110
+ scope.postMessage({type: "failed"})
111
+ }
112
+ }
@@ -0,0 +1,52 @@
1
+ import {readFileSync} from "fs"
2
+
3
+ export interface BackgroundCallbacks {
4
+ onBridge: (raw: string) => void
5
+ onLog: (level: string, args: unknown[]) => void
6
+ onError: (message: string, stack: string) => void
7
+ onCrash: () => void
8
+ }
9
+
10
+ export interface BackgroundHandle {
11
+ send(raw: string): void
12
+ stop(): void
13
+ }
14
+
15
+ type Outbound =
16
+ | {type: "bridge"; raw: string}
17
+ | {type: "log"; level: string; args: unknown[]}
18
+ | {type: "error"; message: string; stack: string}
19
+ | {type: "started"}
20
+ | {type: "failed"}
21
+
22
+ export function startBackground(bundlePath: string, callbacks: BackgroundCallbacks): BackgroundHandle {
23
+ const worker = new Worker(new URL("./background-worker.ts", import.meta.url).href)
24
+ let stopped = false
25
+
26
+ worker.onmessage = (event: MessageEvent<Outbound>) => {
27
+ if (stopped) return
28
+ const message = event.data
29
+ if (message.type === "bridge") callbacks.onBridge(message.raw)
30
+ else if (message.type === "log") callbacks.onLog(message.level, message.args)
31
+ else if (message.type === "error") callbacks.onError(message.message, message.stack)
32
+ else if (message.type === "failed") callbacks.onCrash()
33
+ }
34
+ worker.onerror = (event: ErrorEvent) => {
35
+ if (stopped) return
36
+ callbacks.onError(event.message ?? "background worker error", "")
37
+ callbacks.onCrash()
38
+ }
39
+
40
+ worker.postMessage({type: "run", code: readFileSync(bundlePath, "utf-8"), sourceUrl: bundlePath})
41
+
42
+ return {
43
+ send(raw) {
44
+ if (!stopped) worker.postMessage({type: "bridge", raw})
45
+ },
46
+ stop() {
47
+ if (stopped) return
48
+ stopped = true
49
+ worker.terminate()
50
+ },
51
+ }
52
+ }