@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.
@@ -0,0 +1,213 @@
1
+ // Pure manifest mutation helpers. No I/O. Returns new manifest objects.
2
+ //
3
+ // Used by the object-verb subcommands (`permission add`, `hardware add`, etc.)
4
+ // and the interactive `glassly-miniapp manifest` wizard. Both surfaces share
5
+ // these primitives so behavior is identical.
6
+
7
+ import {
8
+ ALLOWED_HARDWARE_LEVELS,
9
+ ALLOWED_HARDWARE_TYPES,
10
+ ALLOWED_PERMISSIONS,
11
+ AllowedHardwareLevel,
12
+ AllowedHardwareType,
13
+ AllowedPermission,
14
+ ManifestHardwareRequirement,
15
+ ManifestPermission,
16
+ MiniappManifestV1,
17
+ } from "./manifest.js"
18
+
19
+ export type Manifest = MiniappManifestV1 & Record<string, unknown>
20
+
21
+ export interface ManifestMutateError {
22
+ code:
23
+ | "unknown_type"
24
+ | "duplicate"
25
+ | "invalid_level"
26
+ | "not_present"
27
+ message: string
28
+ /** For `unknown_type`: the closest allowed value by Levenshtein distance, if any. */
29
+ closestMatch?: string
30
+ }
31
+
32
+ export class MutateError extends Error {
33
+ readonly info: ManifestMutateError
34
+ constructor(info: ManifestMutateError) {
35
+ super(info.message)
36
+ this.name = "MutateError"
37
+ this.info = info
38
+ }
39
+ }
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // Permissions
43
+ // ---------------------------------------------------------------------------
44
+
45
+ export function listPermissions(m: Manifest): ManifestPermission[] {
46
+ return [...(m.permissions ?? [])]
47
+ }
48
+
49
+ export function addPermission(
50
+ m: Manifest,
51
+ type: string,
52
+ opts?: {description?: string; required?: boolean},
53
+ ): Manifest {
54
+ const validated = validatePermissionType(type)
55
+ const existing = m.permissions ?? []
56
+ if (existing.some((p) => p.type === validated)) {
57
+ throw new MutateError({
58
+ code: "duplicate",
59
+ message: `${validated} is already declared. Use 'glassly-miniapp permission remove ${validated}' first if you want to update its description / required flag.`,
60
+ })
61
+ }
62
+ const entry: ManifestPermission = {type: validated}
63
+ if (opts?.description !== undefined) entry.description = opts.description
64
+ if (opts?.required !== undefined) entry.required = opts.required
65
+ return {...m, permissions: [...existing, entry]}
66
+ }
67
+
68
+ export function removePermission(m: Manifest, type: string): Manifest {
69
+ const validated = validatePermissionType(type)
70
+ const existing = m.permissions ?? []
71
+ if (!existing.some((p) => p.type === validated)) {
72
+ throw new MutateError({
73
+ code: "not_present",
74
+ message: `${validated} is not declared. Currently declared: ${existing.map((p) => p.type).join(", ") || "(none)"}.`,
75
+ })
76
+ }
77
+ return {...m, permissions: existing.filter((p) => p.type !== validated)}
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // Hardware
82
+ // ---------------------------------------------------------------------------
83
+
84
+ export function listHardware(m: Manifest): ManifestHardwareRequirement[] {
85
+ return [...(m.hardwareRequirements ?? [])]
86
+ }
87
+
88
+ export function addHardware(
89
+ m: Manifest,
90
+ type: string,
91
+ level: string,
92
+ opts?: {description?: string},
93
+ ): Manifest {
94
+ const validatedType = validateHardwareType(type)
95
+ const validatedLevel = validateHardwareLevel(level)
96
+ const existing = m.hardwareRequirements ?? []
97
+ if (existing.some((h) => h.type === validatedType)) {
98
+ throw new MutateError({
99
+ code: "duplicate",
100
+ message: `${validatedType} hardware requirement already declared. Use 'glassly-miniapp hardware remove ${validatedType}' first if you want to update its level / description.`,
101
+ })
102
+ }
103
+ const entry: ManifestHardwareRequirement = {type: validatedType, level: validatedLevel}
104
+ if (opts?.description !== undefined) entry.description = opts.description
105
+ return {...m, hardwareRequirements: [...existing, entry]}
106
+ }
107
+
108
+ export function removeHardware(m: Manifest, type: string): Manifest {
109
+ const validatedType = validateHardwareType(type)
110
+ const existing = m.hardwareRequirements ?? []
111
+ if (!existing.some((h) => h.type === validatedType)) {
112
+ throw new MutateError({
113
+ code: "not_present",
114
+ message: `${validatedType} hardware requirement is not declared. Currently declared: ${existing.map((h) => h.type).join(", ") || "(none)"}.`,
115
+ })
116
+ }
117
+ return {...m, hardwareRequirements: existing.filter((h) => h.type !== validatedType)}
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // Validators (with Levenshtein closest-match suggestions)
122
+ // ---------------------------------------------------------------------------
123
+
124
+ function validatePermissionType(input: string): AllowedPermission {
125
+ const normalized = input.toUpperCase()
126
+ if ((ALLOWED_PERMISSIONS as readonly string[]).includes(normalized)) {
127
+ return normalized as AllowedPermission
128
+ }
129
+ const closest = closestAllowedValue(normalized, ALLOWED_PERMISSIONS)
130
+ throw new MutateError({
131
+ code: "unknown_type",
132
+ message:
133
+ `Unknown permission "${input}".` +
134
+ (closest ? ` Did you mean "${closest}"?` : "") +
135
+ ` Allowed: ${ALLOWED_PERMISSIONS.join(", ")}.`,
136
+ ...(closest ? {closestMatch: closest} : {}),
137
+ })
138
+ }
139
+
140
+ function validateHardwareType(input: string): AllowedHardwareType {
141
+ const normalized = input.toUpperCase()
142
+ if ((ALLOWED_HARDWARE_TYPES as readonly string[]).includes(normalized)) {
143
+ return normalized as AllowedHardwareType
144
+ }
145
+ const closest = closestAllowedValue(normalized, ALLOWED_HARDWARE_TYPES)
146
+ throw new MutateError({
147
+ code: "unknown_type",
148
+ message:
149
+ `Unknown hardware type "${input}".` +
150
+ (closest ? ` Did you mean "${closest}"?` : "") +
151
+ ` Allowed: ${ALLOWED_HARDWARE_TYPES.join(", ")}.`,
152
+ ...(closest ? {closestMatch: closest} : {}),
153
+ })
154
+ }
155
+
156
+ function validateHardwareLevel(input: string): AllowedHardwareLevel {
157
+ const normalized = input.toUpperCase()
158
+ if ((ALLOWED_HARDWARE_LEVELS as readonly string[]).includes(normalized)) {
159
+ return normalized as AllowedHardwareLevel
160
+ }
161
+ const closest = closestAllowedValue(normalized, ALLOWED_HARDWARE_LEVELS)
162
+ throw new MutateError({
163
+ code: "invalid_level",
164
+ message:
165
+ `Invalid hardware level "${input}".` +
166
+ (closest ? ` Did you mean "${closest}"?` : "") +
167
+ ` Allowed: ${ALLOWED_HARDWARE_LEVELS.join(", ")}.`,
168
+ ...(closest ? {closestMatch: closest} : {}),
169
+ })
170
+ }
171
+
172
+ /**
173
+ * Return the closest allowed value to `input` by Levenshtein distance. Threshold
174
+ * of 2 — anything further is too distant to be helpful.
175
+ */
176
+ export function closestAllowedValue<T extends string>(
177
+ input: string,
178
+ allowed: readonly T[],
179
+ ): T | null {
180
+ const upper = input.toUpperCase()
181
+ let best: T | null = null
182
+ let bestDist = Infinity
183
+ for (const candidate of allowed) {
184
+ const d = levenshtein(upper, candidate)
185
+ if (d < bestDist) {
186
+ bestDist = d
187
+ best = candidate
188
+ }
189
+ }
190
+ return bestDist <= 2 ? best : null
191
+ }
192
+
193
+ function levenshtein(a: string, b: string): number {
194
+ if (a === b) return 0
195
+ if (!a.length) return b.length
196
+ if (!b.length) return a.length
197
+
198
+ const prev = new Array<number>(b.length + 1)
199
+ for (let j = 0; j <= b.length; j++) prev[j] = j
200
+
201
+ for (let i = 1; i <= a.length; i++) {
202
+ let curr = i
203
+ for (let j = 1; j <= b.length; j++) {
204
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1
205
+ const next = Math.min(curr + 1, prev[j] + 1, prev[j - 1] + cost)
206
+ prev[j - 1] = curr
207
+ curr = next
208
+ }
209
+ prev[b.length] = curr
210
+ }
211
+
212
+ return prev[b.length]
213
+ }
@@ -0,0 +1,218 @@
1
+ // `glassly-miniapp manifest` — interactive top-level wizard.
2
+ //
3
+ // Uses the same mutation backend as the object-verb subcommands, so behavior
4
+ // is identical. Loop-driven: read manifest, prompt for an action, mutate,
5
+ // persist, loop.
6
+
7
+ import * as p from "@clack/prompts"
8
+ import {ALLOWED_HARDWARE_LEVELS, ALLOWED_HARDWARE_TYPES, ALLOWED_PERMISSIONS} from "./manifest.js"
9
+ import {
10
+ addHardware,
11
+ addPermission,
12
+ listHardware,
13
+ listPermissions,
14
+ Manifest,
15
+ MutateError,
16
+ removeHardware,
17
+ removePermission,
18
+ } from "./manifest-mutate.js"
19
+ import {formatLoadError, formatWriteError, loadManifest, writeManifest} from "./manifest-format.js"
20
+ import {hardwareDescription, permissionDescription} from "./permission-hints.js"
21
+
22
+ export async function runManifestWizard(): Promise<void> {
23
+ p.intro("Glassly miniapp manifest editor")
24
+
25
+ const loaded = loadManifest(process.cwd())
26
+ if (!loaded.ok) {
27
+ p.cancel(formatLoadError(loaded.error))
28
+ process.exit(1)
29
+ }
30
+ let {path, manifest} = loaded.value
31
+ // Stage updates locally; persist after each mutation so Ctrl-C never loses
32
+ // a confirmed change. (Matches the spec's note: don't batch.)
33
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
34
+ let _initialPath = path
35
+
36
+ while (true) {
37
+ const action = await p.select({
38
+ message: "What would you like to do?",
39
+ options: [
40
+ {value: "permissions", label: "Edit permissions", hint: `${listPermissions(manifest).length} declared`},
41
+ {value: "hardware", label: "Edit hardware requirements", hint: `${listHardware(manifest).length} declared`},
42
+ {value: "show", label: "Show current manifest"},
43
+ {value: "done", label: "Done"},
44
+ ],
45
+ })
46
+ if (p.isCancel(action) || action === "done") break
47
+
48
+ if (action === "show") {
49
+ p.note(JSON.stringify(manifest, null, 2), "miniapp.json")
50
+ continue
51
+ }
52
+
53
+ if (action === "permissions") {
54
+ manifest = await editPermissions(manifest)
55
+ const w = writeManifest(path, manifest)
56
+ if (!w.ok) {
57
+ p.cancel(formatWriteError(w.error))
58
+ process.exit(1)
59
+ }
60
+ continue
61
+ }
62
+
63
+ if (action === "hardware") {
64
+ manifest = await editHardware(manifest)
65
+ const w = writeManifest(path, manifest)
66
+ if (!w.ok) {
67
+ p.cancel(formatWriteError(w.error))
68
+ process.exit(1)
69
+ }
70
+ continue
71
+ }
72
+ }
73
+
74
+ p.outro("Saved miniapp.json ✨")
75
+ }
76
+
77
+ async function editPermissions(manifest: Manifest): Promise<Manifest> {
78
+ const sub = await p.select({
79
+ message: "Permissions",
80
+ options: [
81
+ {value: "add", label: "Add a permission"},
82
+ {value: "remove", label: "Remove a permission"},
83
+ {value: "back", label: "Back"},
84
+ ],
85
+ })
86
+ if (p.isCancel(sub) || sub === "back") return manifest
87
+
88
+ if (sub === "add") {
89
+ const declared = new Set(listPermissions(manifest).map((perm) => perm.type))
90
+ const available = ALLOWED_PERMISSIONS.filter((perm) => !declared.has(perm))
91
+ if (available.length === 0) {
92
+ p.note("All permissions are already declared.", "Permissions")
93
+ return manifest
94
+ }
95
+ const picked = await p.multiselect({
96
+ message: "Which permission(s) to add?",
97
+ required: false,
98
+ options: available.map((perm) => ({value: perm, label: perm, hint: permissionDescription(perm)})),
99
+ })
100
+ if (p.isCancel(picked)) return manifest
101
+ let updated = manifest
102
+ for (const type of picked as readonly string[]) {
103
+ const desc = await p.text({
104
+ message: `Description for ${type} (optional):`,
105
+ placeholder: "(skip)",
106
+ })
107
+ if (p.isCancel(desc)) return updated
108
+ const opts = typeof desc === "string" && desc.trim() ? {description: desc.trim()} : undefined
109
+ try {
110
+ updated = addPermission(updated, type, opts)
111
+ } catch (e) {
112
+ if (e instanceof MutateError) {
113
+ p.note(e.message, "Skipped")
114
+ } else {
115
+ throw e
116
+ }
117
+ }
118
+ }
119
+ return updated
120
+ }
121
+
122
+ if (sub === "remove") {
123
+ const declared = listPermissions(manifest)
124
+ if (declared.length === 0) {
125
+ p.note("No permissions to remove.", "Permissions")
126
+ return manifest
127
+ }
128
+ const picked = await p.select({
129
+ message: "Which permission to remove?",
130
+ options: declared.map((perm) => ({value: perm.type, label: perm.type})),
131
+ })
132
+ if (p.isCancel(picked)) return manifest
133
+ try {
134
+ return removePermission(manifest, picked as string)
135
+ } catch (e) {
136
+ if (e instanceof MutateError) {
137
+ p.note(e.message, "Skipped")
138
+ }
139
+ return manifest
140
+ }
141
+ }
142
+
143
+ return manifest
144
+ }
145
+
146
+ async function editHardware(manifest: Manifest): Promise<Manifest> {
147
+ const sub = await p.select({
148
+ message: "Hardware requirements",
149
+ options: [
150
+ {value: "add", label: "Add a hardware requirement"},
151
+ {value: "remove", label: "Remove a hardware requirement"},
152
+ {value: "back", label: "Back"},
153
+ ],
154
+ })
155
+ if (p.isCancel(sub) || sub === "back") return manifest
156
+
157
+ if (sub === "add") {
158
+ const declared = new Set(listHardware(manifest).map((h) => h.type))
159
+ const available = ALLOWED_HARDWARE_TYPES.filter((h) => !declared.has(h))
160
+ if (available.length === 0) {
161
+ p.note("All hardware types are already declared.", "Hardware")
162
+ return manifest
163
+ }
164
+ const type = await p.select({
165
+ message: "Which hardware?",
166
+ options: available.map((h) => ({value: h, label: h, hint: hardwareDescription(h)})),
167
+ })
168
+ if (p.isCancel(type)) return manifest
169
+
170
+ const level = await p.select({
171
+ message: "Required or optional?",
172
+ options: ALLOWED_HARDWARE_LEVELS.map((l) => ({
173
+ value: l,
174
+ label: l,
175
+ hint:
176
+ l === "REQUIRED"
177
+ ? "Glasses without this hardware can't run the app"
178
+ : "Glasses without this hardware still run the app (degraded)",
179
+ })),
180
+ })
181
+ if (p.isCancel(level)) return manifest
182
+
183
+ const desc = await p.text({
184
+ message: "Description (optional):",
185
+ placeholder: "(skip)",
186
+ })
187
+ if (p.isCancel(desc)) return manifest
188
+ const opts = typeof desc === "string" && desc.trim() ? {description: desc.trim()} : undefined
189
+
190
+ try {
191
+ return addHardware(manifest, type as string, level as string, opts)
192
+ } catch (e) {
193
+ if (e instanceof MutateError) p.note(e.message, "Skipped")
194
+ return manifest
195
+ }
196
+ }
197
+
198
+ if (sub === "remove") {
199
+ const declared = listHardware(manifest)
200
+ if (declared.length === 0) {
201
+ p.note("No hardware requirements to remove.", "Hardware")
202
+ return manifest
203
+ }
204
+ const picked = await p.select({
205
+ message: "Which hardware to remove?",
206
+ options: declared.map((h) => ({value: h.type, label: `${h.type} (${h.level})`})),
207
+ })
208
+ if (p.isCancel(picked)) return manifest
209
+ try {
210
+ return removeHardware(manifest, picked as string)
211
+ } catch (e) {
212
+ if (e instanceof MutateError) p.note(e.message, "Skipped")
213
+ return manifest
214
+ }
215
+ }
216
+
217
+ return manifest
218
+ }