@glassly/miniapp-cli 0.1.0-dev.1

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/pack.ts ADDED
@@ -0,0 +1,137 @@
1
+ import { existsSync, mkdirSync, readFileSync, copyFileSync, writeFileSync } from 'fs';
2
+ import { resolve, join } from 'path';
3
+ import { buildProduction } from './build.js';
4
+ import { validateManifest } from './manifest.js';
5
+
6
+ export interface PackOptions {
7
+ /** Miniapp project root. Defaults to the current working directory. */
8
+ cwd?: string;
9
+ /** Run the production build before zipping. Defaults to false. */
10
+ build?: boolean;
11
+ /** Where to write the resulting zip. Defaults to build/. */
12
+ outDir?: string;
13
+ /** Quiet stdout. The `release` command swallows pack output and prints
14
+ * its own progress; standalone `pack` calls leave it on. */
15
+ silent?: boolean;
16
+ }
17
+
18
+ /**
19
+ * Validate manifest, copy manifest+icon into dist/, zip dist/ into
20
+ * `build/<packageName>-<version>.zip`. Returns the absolute path of the zip.
21
+ *
22
+ * `build/` is self-ignoring: a `.gitignore` containing `*` is written into
23
+ * it on creation (the Cargo `target/` trick), so packed zips stay out of
24
+ * version control no matter which repo the miniapp lives in — no root
25
+ * .gitignore coordination needed.
26
+ */
27
+ export async function pack(opts: PackOptions = {}): Promise<string> {
28
+ const cwd = resolve(opts.cwd ?? process.cwd());
29
+ if (opts.build) {
30
+ await buildProduction(cwd);
31
+ }
32
+
33
+ const distDir = resolve(cwd, 'dist');
34
+ const manifestSrc = resolve(cwd, 'miniapp.json');
35
+ const iconSrc = resolve(cwd, 'icon.png');
36
+
37
+ // Verify dist/ exists
38
+ if (!existsSync(distDir)) {
39
+ console.error('Error: dist/ directory not found. Build your miniapp first.');
40
+ process.exit(1);
41
+ }
42
+
43
+ // Verify miniapp.json exists
44
+ if (!existsSync(manifestSrc)) {
45
+ console.error('Error: miniapp.json not found in current directory');
46
+ process.exit(1);
47
+ }
48
+
49
+ // Read and validate manifest
50
+ const manifestRaw = readFileSync(manifestSrc, 'utf-8');
51
+ let manifest: Record<string, unknown>;
52
+ try {
53
+ manifest = JSON.parse(manifestRaw);
54
+ } catch {
55
+ console.error('Error: miniapp.json is not valid JSON');
56
+ process.exit(1);
57
+ }
58
+
59
+ const { valid, errors } = validateManifest(manifest);
60
+ if (!valid) {
61
+ console.error('Manifest validation failed:');
62
+ for (const err of errors) {
63
+ console.error(` - ${err}`);
64
+ }
65
+ process.exit(1);
66
+ }
67
+
68
+ // Enforce two-layer bundle contract when manifest.entry is set.
69
+ // `entry.background` (required for two-layer) must resolve to a file in the
70
+ // bundle. `entry.ui` (optional, for UI-bearing miniapps) likewise. Legacy
71
+ // single-bundle manifests without an `entry` object skip this check —
72
+ // pack still zips dist/ verbatim.
73
+ //
74
+ // Entry paths are relative to the *bundle root*, which is dist/'s contents
75
+ // (we zip from inside dist/ below), so `background/index.js` in the manifest
76
+ // is `dist/background/index.js` on disk — resolve against distDir.
77
+ const entry = manifest.entry as {background?: string; ui?: string} | undefined;
78
+ if (entry) {
79
+ const checkRelative = (label: string, rel: string | undefined, required: boolean) => {
80
+ if (!rel) {
81
+ if (required) {
82
+ console.error(`Error: manifest.entry.${label} is required for two-layer bundles`);
83
+ process.exit(1);
84
+ }
85
+ return;
86
+ }
87
+ const abs = resolve(distDir, rel);
88
+ if (!existsSync(abs)) {
89
+ console.error(`Error: manifest.entry.${label} points at "${rel}" but dist/${rel} does not exist`);
90
+ process.exit(1);
91
+ }
92
+ };
93
+ checkRelative('background', entry.background, true);
94
+ checkRelative('ui', entry.ui, false);
95
+ }
96
+
97
+ // Copy miniapp.json into dist/
98
+ copyFileSync(manifestSrc, join(distDir, 'miniapp.json'));
99
+
100
+ // Copy icon.png into dist/ if it exists
101
+ if (existsSync(iconSrc)) {
102
+ copyFileSync(iconSrc, join(distDir, 'icon.png'));
103
+ } else if (!opts.silent) {
104
+ console.warn('Warning: icon.png not found in project root, skipping');
105
+ }
106
+
107
+ const packageName = manifest.packageName as string;
108
+ const version = manifest.version as string;
109
+ const outputName = `${packageName}-${version}.zip`;
110
+ const outDir = resolve(cwd, opts.outDir ?? 'build');
111
+ if (!existsSync(outDir)) {
112
+ mkdirSync(outDir, { recursive: true });
113
+ }
114
+ const selfIgnore = join(outDir, '.gitignore');
115
+ if (!existsSync(selfIgnore)) {
116
+ writeFileSync(selfIgnore, '*\n');
117
+ }
118
+ const outputPath = resolve(outDir, outputName);
119
+
120
+ // Create ZIP using system zip command
121
+ const zipProc = Bun.spawn(['zip', '-r', outputPath, '.'], {
122
+ cwd: distDir,
123
+ stdout: opts.silent ? 'pipe' : 'inherit',
124
+ stderr: opts.silent ? 'pipe' : 'inherit',
125
+ });
126
+
127
+ const exitCode = await zipProc.exited;
128
+ if (exitCode !== 0) {
129
+ console.error('Error: zip command failed');
130
+ process.exit(1);
131
+ }
132
+
133
+ if (!opts.silent) {
134
+ console.log(`\nPacked: ${outputPath}`);
135
+ }
136
+ return outputPath;
137
+ }
@@ -0,0 +1,36 @@
1
+ // User-facing one-liners for the wizard / interactive prompts. Kept separate
2
+ // so manifest.ts can stay UX-string-free.
3
+
4
+ import {AllowedHardwareType, AllowedPermission} from "./manifest.js"
5
+
6
+ const PERMISSION_HINTS: Record<AllowedPermission, string> = {
7
+ MICROPHONE: "Required for transcription, audio chunks, voice activity detection",
8
+ CAMERA: "Required for taking photos via session.camera.takePhoto()",
9
+ CALENDAR: "Required to receive calendar event subscriptions",
10
+ LOCATION: "Required for foreground location updates",
11
+ BACKGROUND_LOCATION: "Required for location updates while app is backgrounded",
12
+ READ_NOTIFICATIONS: "Required to receive phone notifications",
13
+ POST_NOTIFICATIONS: "Required to post system notifications from the miniapp",
14
+ API_KEYS: "Required to read user-supplied provider API keys via session.keys.get()",
15
+ MEMORY: "Required to read/write the user's shared memory timeline via session.memory",
16
+ AI: "Required to run LLM completions via session.ai.complete()",
17
+ }
18
+
19
+ const HARDWARE_HINTS: Record<AllowedHardwareType, string> = {
20
+ CAMERA: "Glasses-side camera; required for photo capture",
21
+ DISPLAY: "Glasses display; required to show layouts",
22
+ MICROPHONE: "Glasses-side mic; required for capture",
23
+ SPEAKER: "Audio output through the glasses",
24
+ IMU: "Head position / motion sensor",
25
+ BUTTON: "Physical button on the glasses",
26
+ LIGHT: "RGB LED indicator",
27
+ WIFI: "Glasses Wi-Fi capability (e.g. for streaming)",
28
+ }
29
+
30
+ export function permissionDescription(p: AllowedPermission): string {
31
+ return PERMISSION_HINTS[p] ?? ""
32
+ }
33
+
34
+ export function hardwareDescription(h: AllowedHardwareType): string {
35
+ return HARDWARE_HINTS[h] ?? ""
36
+ }
@@ -0,0 +1,142 @@
1
+ // `glassly-miniapp permission <action>` subcommand handlers.
2
+ //
3
+ // Object-verb surface for the most common manifest edit. Both interactive
4
+ // (no type arg → clack prompts) and non-interactive (type arg given) flows.
5
+ // Shares mutation backend with the wizard via manifest-mutate.ts.
6
+
7
+ import * as p from "@clack/prompts"
8
+ import {ALLOWED_PERMISSIONS} from "./manifest.js"
9
+ import {
10
+ addPermission,
11
+ listPermissions,
12
+ MutateError,
13
+ removePermission,
14
+ type Manifest,
15
+ } from "./manifest-mutate.js"
16
+ import {formatLoadError, formatWriteError, loadManifest, writeManifest} from "./manifest-format.js"
17
+ import {permissionDescription} from "./permission-hints.js"
18
+
19
+ function loadOrExit(): {path: string; manifest: Manifest} {
20
+ const r = loadManifest(process.cwd())
21
+ if (!r.ok) {
22
+ console.error(formatLoadError(r.error))
23
+ process.exit(1)
24
+ }
25
+ return {path: r.value.path, manifest: r.value.manifest}
26
+ }
27
+
28
+ function persistOrExit(path: string, manifest: Manifest): void {
29
+ const w = writeManifest(path, manifest)
30
+ if (!w.ok) {
31
+ console.error(formatWriteError(w.error))
32
+ process.exit(1)
33
+ }
34
+ }
35
+
36
+ function printPermissions(manifest: Manifest): void {
37
+ const perms = listPermissions(manifest)
38
+ if (perms.length === 0) {
39
+ console.log("Permissions: none declared.")
40
+ return
41
+ }
42
+ console.log(`Permissions (${perms.length}):`)
43
+ for (const perm of perms) {
44
+ const desc = perm.description ? ` — ${perm.description}` : ""
45
+ const req = perm.required === false ? " [optional]" : ""
46
+ console.log(` • ${perm.type}${req}${desc}`)
47
+ }
48
+ }
49
+
50
+ export async function listPermissionsCmd(): Promise<void> {
51
+ const {manifest} = loadOrExit()
52
+ printPermissions(manifest)
53
+ }
54
+
55
+ export async function addPermissionCmd(typeArg?: string): Promise<void> {
56
+ const {path, manifest} = loadOrExit()
57
+ let type = typeArg
58
+ let description: string | undefined
59
+
60
+ if (!type) {
61
+ p.intro("Add a permission")
62
+ const declared = new Set(listPermissions(manifest).map((perm) => perm.type))
63
+ const available = ALLOWED_PERMISSIONS.filter((perm) => !declared.has(perm))
64
+ if (available.length === 0) {
65
+ p.note("All permissions are already declared. Nothing to add.", "Permissions")
66
+ p.outro("Done")
67
+ return
68
+ }
69
+ const picked = await p.select({
70
+ message: "Which permission?",
71
+ options: available.map((perm) => ({value: perm, label: perm, hint: permissionDescription(perm)})),
72
+ })
73
+ if (p.isCancel(picked)) {
74
+ p.cancel("Cancelled.")
75
+ return
76
+ }
77
+ type = picked as string
78
+ const desc = await p.text({
79
+ message: "Optional description (shown to the user when the OS prompts for permission):",
80
+ placeholder: "(skip)",
81
+ })
82
+ if (p.isCancel(desc)) {
83
+ p.cancel("Cancelled.")
84
+ return
85
+ }
86
+ if (typeof desc === "string" && desc.trim()) description = desc.trim()
87
+ }
88
+
89
+ let updated: Manifest
90
+ try {
91
+ updated = addPermission(manifest, type!, description !== undefined ? {description} : undefined)
92
+ } catch (e) {
93
+ if (e instanceof MutateError) {
94
+ console.error(e.message)
95
+ process.exit(1)
96
+ }
97
+ throw e
98
+ }
99
+
100
+ persistOrExit(path, updated)
101
+ printPermissions(updated)
102
+ if (typeArg === undefined) {
103
+ p.outro("Saved miniapp.json ✨")
104
+ }
105
+ }
106
+
107
+ export async function removePermissionCmd(typeArg?: string): Promise<void> {
108
+ const {path, manifest} = loadOrExit()
109
+ let type = typeArg
110
+
111
+ if (!type) {
112
+ const declared = listPermissions(manifest)
113
+ if (declared.length === 0) {
114
+ console.log("No permissions declared. Nothing to remove.")
115
+ return
116
+ }
117
+ p.intro("Remove a permission")
118
+ const picked = await p.select({
119
+ message: "Which permission to remove?",
120
+ options: declared.map((perm) => ({value: perm.type, label: perm.type})),
121
+ })
122
+ if (p.isCancel(picked)) {
123
+ p.cancel("Cancelled.")
124
+ return
125
+ }
126
+ type = picked as string
127
+ }
128
+
129
+ let updated: Manifest
130
+ try {
131
+ updated = removePermission(manifest, type!)
132
+ } catch (e) {
133
+ if (e instanceof MutateError) {
134
+ console.error(e.message)
135
+ process.exit(1)
136
+ }
137
+ throw e
138
+ }
139
+
140
+ persistOrExit(path, updated)
141
+ printPermissions(updated)
142
+ }
package/src/qr.test.ts ADDED
@@ -0,0 +1,81 @@
1
+ import {afterEach, describe, expect, test} from 'bun:test';
2
+ import {chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync} from 'fs';
3
+ import {tmpdir} from 'os';
4
+ import {join} from 'path';
5
+ import {writeQRPng} from './qr.js';
6
+
7
+ const tempDirs: string[] = [];
8
+
9
+ function makeTempDir(): string {
10
+ const dir = mkdtempSync(join(tmpdir(), 'glassly-qr-test-'));
11
+ tempDirs.push(dir);
12
+ return dir;
13
+ }
14
+
15
+ afterEach(() => {
16
+ for (const dir of tempDirs.splice(0)) {
17
+ try {
18
+ chmodSync(dir, 0o700);
19
+ rmSync(dir, {recursive: true, force: true});
20
+ } catch {
21
+ // best-effort cleanup
22
+ }
23
+ }
24
+ });
25
+
26
+ describe('writeQRPng', () => {
27
+ test('creates a file with mode 0o600 and non-empty PNG content', async () => {
28
+ const dir = makeTempDir();
29
+ const outPath = join(dir, 'qr.png');
30
+ await writeQRPng('miniapp://dev?url=http%3A%2F%2F192.168.1.1%3A3000', outPath);
31
+
32
+ const st = statSync(outPath);
33
+ expect(st.size).toBeGreaterThan(0);
34
+ // Mask off higher mode bits so comparison is portable across platforms.
35
+ expect(st.mode & 0o777).toBe(0o600);
36
+
37
+ const header = readFileSync(outPath).subarray(0, 8);
38
+ // PNG magic number
39
+ expect([...header]).toEqual([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
40
+ });
41
+
42
+ test('overwrites the same path in place on a second call', async () => {
43
+ const dir = makeTempDir();
44
+ const outPath = join(dir, 'qr.png');
45
+ await writeQRPng('miniapp://dev?url=http%3A%2F%2F192.168.1.1%3A3000', outPath);
46
+ const first = readFileSync(outPath);
47
+
48
+ await writeQRPng('miniapp://dev?url=http%3A%2F%2F10.0.0.1%3A3000', outPath);
49
+ const second = readFileSync(outPath);
50
+
51
+ expect(Buffer.compare(first, second)).not.toBe(0);
52
+ expect(statSync(outPath).isFile()).toBe(true);
53
+ });
54
+
55
+ test('forces mode 0o600 even when overwriting a looser-mode file', async () => {
56
+ const dir = makeTempDir();
57
+ const outPath = join(dir, 'qr.png');
58
+ writeFileSync(outPath, 'placeholder', {mode: 0o644});
59
+ chmodSync(outPath, 0o644);
60
+ expect(statSync(outPath).mode & 0o777).toBe(0o644);
61
+
62
+ await writeQRPng('miniapp://dev?url=http%3A%2F%2F192.168.1.1%3A3000', outPath);
63
+ expect(statSync(outPath).mode & 0o777).toBe(0o600);
64
+ });
65
+
66
+ test('returns false when the output directory is unwritable', async () => {
67
+ const dir = makeTempDir();
68
+ const readonlyDir = join(dir, 'readonly');
69
+ // Create a directory entry that exists as a file, so writing qr.png under it fails.
70
+ writeFileSync(readonlyDir, 'not-a-directory');
71
+ const outPath = join(readonlyDir, 'qr.png');
72
+
73
+ await expect(writeQRPng('miniapp://dev?test=1', outPath)).resolves.toBe(false);
74
+ });
75
+
76
+ test('returns true on success', async () => {
77
+ const dir = makeTempDir();
78
+ const outPath = join(dir, 'ok.png');
79
+ await expect(writeQRPng('miniapp://dev?test=1', outPath)).resolves.toBe(true);
80
+ });
81
+ });
package/src/qr.ts ADDED
@@ -0,0 +1,119 @@
1
+ import {chmodSync, writeFileSync} from 'fs';
2
+ import QRCode from 'qrcode';
3
+
4
+ export type QRSize = 'small' | 'medium' | 'large';
5
+
6
+ const BG_WHITE = '\x1b[47m';
7
+ const FG_BLACK = '\x1b[30m';
8
+ const RESET = '\x1b[0m';
9
+
10
+ // Sextant block characters indexed by a 6-bit pattern: bit 0 = upper-left,
11
+ // 1 = upper-right, 2 = middle-left, 3 = middle-right, 4 = lower-left,
12
+ // 5 = lower-right. A set bit is a dark module drawn as black foreground on
13
+ // white background. Unicode's Symbols for Legacy Computing sextant range
14
+ // (U+1FB00–U+1FB3B) omits empty, the two half blocks, and full — those come
15
+ // from Block Elements.
16
+ const SEXTANTS: string[] = Array.from({length: 64}, (_, v) => {
17
+ if (v === 0) return ' ';
18
+ if (v === 0b010101) return '▌';
19
+ if (v === 0b101010) return '▐';
20
+ if (v === 0b111111) return '█';
21
+ return String.fromCodePoint(0x1fb00 + v - 1 - (v > 0b010101 ? 1 : 0) - (v > 0b101010 ? 1 : 0));
22
+ });
23
+
24
+ /**
25
+ * Render 2x3 modules per character using sextant blocks — half the width and
26
+ * two-thirds the height of the half-block renderer. In a typical 1:2 terminal
27
+ * cell the modules come out only ~1.33x taller than wide (quadrants would be
28
+ * 2x). Perfectly square at this width needs Unicode 16 octants (2x4), which
29
+ * few terminal fonts render yet. Sextants are the most sensitive mode to
30
+ * missing font support — if the QR shows boxes or gaps, use medium/large.
31
+ */
32
+ function renderSextant(url: string): string {
33
+ const qr = QRCode.create(url, {errorCorrectionLevel: 'L'});
34
+ const size = qr.modules.size;
35
+ const data = qr.modules.data;
36
+ const margin = 1;
37
+ const padded = size + margin * 2;
38
+
39
+ const dark = (x: number, y: number): number => {
40
+ const mx = x - margin;
41
+ const my = y - margin;
42
+ if (mx < 0 || my < 0 || mx >= size || my >= size) return 0;
43
+ return data[my * size + mx] ? 1 : 0;
44
+ };
45
+
46
+ let output = '';
47
+ for (let y = 0; y < padded; y += 3) {
48
+ output += BG_WHITE + FG_BLACK;
49
+ for (let x = 0; x < padded; x += 2) {
50
+ let bits = 0;
51
+ for (let dy = 0; dy < 3; dy++) {
52
+ bits |= dark(x, y + dy) << (dy * 2);
53
+ bits |= dark(x + 1, y + dy) << (dy * 2 + 1);
54
+ }
55
+ output += SEXTANTS[bits];
56
+ }
57
+ output += RESET + '\n';
58
+ }
59
+ return output;
60
+ }
61
+
62
+ /**
63
+ * Print a scannable QR to the terminal at one of three sizes (`--qr`/`-q`):
64
+ *
65
+ * - `small` — sextant blocks, 2x3 modules per character (~20 columns for a
66
+ * dev URL). Densest, and the most dependent on the terminal font drawing
67
+ * Legacy Computing sextant glyphs flush.
68
+ * - `medium` (default) — half-block renderer, 1x2 modules per character
69
+ * (~40 columns). A line-height far from 1.0 inserts gaps between rows and
70
+ * can make small/medium unscannable.
71
+ * - `large` — each module is two spaces with forced ANSI black/white
72
+ * backgrounds (~80 columns). Survives any font or line-height.
73
+ *
74
+ * The plain URL is always printed alongside the QR as a last resort.
75
+ */
76
+ export async function printQR(url: string, opts: {size?: QRSize} = {}): Promise<void> {
77
+ const size = opts.size ?? 'medium';
78
+ try {
79
+ const str = size === 'small'
80
+ ? renderSextant(url)
81
+ : await QRCode.toString(url, {
82
+ type: 'terminal',
83
+ small: size === 'medium',
84
+ errorCorrectionLevel: 'L',
85
+ margin: 1,
86
+ });
87
+ process.stdout.write('\n' + str);
88
+ } catch (error) {
89
+ console.error(`Could not render terminal QR code: ${(error as Error).message}`);
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Write a PNG QR to disk with mode 0o600.
95
+ *
96
+ * Dev/release URLs can carry a signed attestation query param; writing with
97
+ * restrictive permissions avoids a world-readable window on multi-user machines.
98
+ * Failures only warn — a broken PNG write must not take down the server.
99
+ *
100
+ * @returns true if the file was written successfully
101
+ */
102
+ export async function writeQRPng(url: string, outPath: string): Promise<boolean> {
103
+ try {
104
+ const buffer = await QRCode.toBuffer(url, {
105
+ type: 'png',
106
+ errorCorrectionLevel: 'M',
107
+ margin: 2,
108
+ scale: 8,
109
+ });
110
+ // mode on writeFileSync only applies to newly created files — always chmod
111
+ // after write so overwrites of a looser-mode temp path stay private.
112
+ writeFileSync(outPath, buffer, {mode: 0o600});
113
+ chmodSync(outPath, 0o600);
114
+ return true;
115
+ } catch (error) {
116
+ console.warn(`Could not write QR PNG to ${outPath}: ${(error as Error).message}`);
117
+ return false;
118
+ }
119
+ }