@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.
- package/README.md +248 -0
- package/package.json +49 -0
- package/schema/miniapp.schema.json +269 -0
- package/src/api.ts +10 -0
- package/src/build-helpers.test.ts +104 -0
- package/src/build-helpers.ts +357 -0
- package/src/build.ts +67 -0
- package/src/dev-server.test.ts +138 -0
- package/src/dev-server.ts +454 -0
- package/src/dev.ts +348 -0
- package/src/hardware.ts +163 -0
- package/src/lan.test.ts +84 -0
- package/src/lan.ts +161 -0
- package/src/manifest-format.ts +121 -0
- package/src/manifest-mutate.test.ts +191 -0
- package/src/manifest-mutate.ts +213 -0
- package/src/manifest-wizard.ts +218 -0
- package/src/manifest.test.ts +376 -0
- package/src/manifest.ts +412 -0
- package/src/pack.ts +131 -0
- package/src/permission-hints.ts +40 -0
- package/src/permission.ts +142 -0
- package/src/qr.test.ts +81 -0
- package/src/qr.ts +119 -0
- package/src/regenerate-schema.ts +6 -0
- package/src/release.ts +265 -0
- package/src/schema.test.ts +64 -0
- package/src/schema.ts +258 -0
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import {readFile} from "fs/promises"
|
|
2
|
+
import {createRequire} from "module"
|
|
3
|
+
import {dirname, isAbsolute, join, relative, resolve} from "path"
|
|
4
|
+
import {fileURLToPath} from "url"
|
|
5
|
+
import ts from "typescript"
|
|
6
|
+
|
|
7
|
+
type ResolveArgs = {path: string}
|
|
8
|
+
type ResolveResult = {path: string}
|
|
9
|
+
type LoadArgs = {path: string}
|
|
10
|
+
type LoadResult = {contents: string; loader: "js" | "jsx" | "ts" | "tsx"}
|
|
11
|
+
type BunBuild = {
|
|
12
|
+
onResolve(args: {filter: RegExp}, callback: (args: ResolveArgs) => ResolveResult): void
|
|
13
|
+
onLoad(args: {filter: RegExp}, callback: (args: LoadArgs) => Promise<LoadResult | undefined>): void
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface BackgroundRuntimeFinding {
|
|
17
|
+
api: string
|
|
18
|
+
line: number
|
|
19
|
+
column: number
|
|
20
|
+
replacement: string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const UNSUPPORTED_BACKGROUND_GLOBALS = new Map<string, string>([
|
|
24
|
+
["window", "move browser/UI work to src/ui/"],
|
|
25
|
+
["document", "move DOM work to src/ui/"],
|
|
26
|
+
["navigator", "move browser capability checks to src/ui/"],
|
|
27
|
+
["location", "use session.location for glasses/phone location, or move browser URL work to src/ui/"],
|
|
28
|
+
["performance", "use Date.now() for elapsed time"],
|
|
29
|
+
["XMLHttpRequest", "use fetch()"],
|
|
30
|
+
["EventSource", "use fetch() or WebSocket"],
|
|
31
|
+
["FormData", "send a supported string request body"],
|
|
32
|
+
["File", "move browser file handling to src/ui/ or use session.blob"],
|
|
33
|
+
["FileReader", "move browser file handling to src/ui/ or use session.blob"],
|
|
34
|
+
["Blob", "use session.blob for binary storage"],
|
|
35
|
+
["URL", "pass URL strings directly"],
|
|
36
|
+
["URLSearchParams", "build the query string explicitly"],
|
|
37
|
+
["Request", "call fetch() with a URL string and options"],
|
|
38
|
+
["Response", "consume the object returned by fetch()"],
|
|
39
|
+
["Headers", "pass a plain header record to fetch()"],
|
|
40
|
+
["Worker", "keep durable work in the background entry itself"],
|
|
41
|
+
["MessageChannel", "use session.ui channels"],
|
|
42
|
+
["MutationObserver", "move DOM work to src/ui/"],
|
|
43
|
+
["HTMLElement", "move DOM work to src/ui/"],
|
|
44
|
+
["customElements", "move DOM work to src/ui/"],
|
|
45
|
+
["indexedDB", "use session.storage, session.blob, or localStorage"],
|
|
46
|
+
["caches", "use session.storage, session.blob, or localStorage"],
|
|
47
|
+
["process", "remove the Node API; build.ts only inlines PUBLIC_* values"],
|
|
48
|
+
["Buffer", "use Uint8Array plus TextEncoder/TextDecoder or the SDK base64 helpers"],
|
|
49
|
+
["require", "use a static import that Bun can bundle"],
|
|
50
|
+
["module", "use ES modules"],
|
|
51
|
+
["exports", "use ES module exports"],
|
|
52
|
+
["__dirname", "do not read the filesystem at runtime"],
|
|
53
|
+
["__filename", "do not read the filesystem at runtime"],
|
|
54
|
+
])
|
|
55
|
+
|
|
56
|
+
const NODE_BUILTINS = new Set([
|
|
57
|
+
"assert",
|
|
58
|
+
"async_hooks",
|
|
59
|
+
"buffer",
|
|
60
|
+
"child_process",
|
|
61
|
+
"cluster",
|
|
62
|
+
"console",
|
|
63
|
+
"crypto",
|
|
64
|
+
"dgram",
|
|
65
|
+
"diagnostics_channel",
|
|
66
|
+
"dns",
|
|
67
|
+
"domain",
|
|
68
|
+
"events",
|
|
69
|
+
"fs",
|
|
70
|
+
"http",
|
|
71
|
+
"http2",
|
|
72
|
+
"https",
|
|
73
|
+
"module",
|
|
74
|
+
"net",
|
|
75
|
+
"os",
|
|
76
|
+
"path",
|
|
77
|
+
"perf_hooks",
|
|
78
|
+
"process",
|
|
79
|
+
"punycode",
|
|
80
|
+
"querystring",
|
|
81
|
+
"readline",
|
|
82
|
+
"repl",
|
|
83
|
+
"stream",
|
|
84
|
+
"string_decoder",
|
|
85
|
+
"sys",
|
|
86
|
+
"timers",
|
|
87
|
+
"tls",
|
|
88
|
+
"trace_events",
|
|
89
|
+
"tty",
|
|
90
|
+
"url",
|
|
91
|
+
"util",
|
|
92
|
+
"v8",
|
|
93
|
+
"vm",
|
|
94
|
+
"wasi",
|
|
95
|
+
"worker_threads",
|
|
96
|
+
"zlib",
|
|
97
|
+
])
|
|
98
|
+
|
|
99
|
+
function nodeBuiltinName(specifier: string): string | null {
|
|
100
|
+
const bare = specifier.startsWith("node:") ? specifier.slice(5) : specifier
|
|
101
|
+
const root = bare.split("/")[0]!
|
|
102
|
+
return NODE_BUILTINS.has(root) ? specifier : null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function importHasRuntimeBindings(node: ts.ImportDeclaration): boolean {
|
|
106
|
+
const clause = node.importClause
|
|
107
|
+
if (!clause) return true
|
|
108
|
+
if (clause.isTypeOnly) return false
|
|
109
|
+
if (clause.name) return true
|
|
110
|
+
if (clause.namedBindings && ts.isNamespaceImport(clause.namedBindings)) return true
|
|
111
|
+
return clause.namedBindings?.elements.some((element) => !element.isTypeOnly) ?? false
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function exportHasRuntimeBindings(node: ts.ExportDeclaration): boolean {
|
|
115
|
+
if (node.isTypeOnly) return false
|
|
116
|
+
if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) return true
|
|
117
|
+
return node.exportClause.elements.some((element) => !element.isTypeOnly)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isDeclarationOrPropertyName(node: ts.Identifier): boolean {
|
|
121
|
+
const parent = node.parent
|
|
122
|
+
if (!parent) return false
|
|
123
|
+
if (ts.isPropertyAccessExpression(parent) && parent.name === node) return true
|
|
124
|
+
if (ts.isPropertyAssignment(parent) && parent.name === node) return true
|
|
125
|
+
if (ts.isMethodDeclaration(parent) && parent.name === node) return true
|
|
126
|
+
if (ts.isPropertyDeclaration(parent) && parent.name === node) return true
|
|
127
|
+
if (ts.isPropertySignature(parent) && parent.name === node) return true
|
|
128
|
+
if (ts.isBindingElement(parent) && parent.name === node) return true
|
|
129
|
+
if (ts.isVariableDeclaration(parent) && parent.name === node) return true
|
|
130
|
+
if (ts.isParameter(parent) && parent.name === node) return true
|
|
131
|
+
if (ts.isFunctionDeclaration(parent) && parent.name === node) return true
|
|
132
|
+
if (ts.isFunctionExpression(parent) && parent.name === node) return true
|
|
133
|
+
if (ts.isClassDeclaration(parent) && parent.name === node) return true
|
|
134
|
+
if (ts.isClassExpression(parent) && parent.name === node) return true
|
|
135
|
+
if (ts.isInterfaceDeclaration(parent) && parent.name === node) return true
|
|
136
|
+
if (ts.isTypeAliasDeclaration(parent) && parent.name === node) return true
|
|
137
|
+
if (ts.isEnumDeclaration(parent) && parent.name === node) return true
|
|
138
|
+
if (ts.isImportClause(parent) || ts.isImportSpecifier(parent) || ts.isNamespaceImport(parent)) return true
|
|
139
|
+
if (ts.isExportSpecifier(parent)) return true
|
|
140
|
+
if (ts.isQualifiedName(parent) || ts.isTypeReferenceNode(parent) || ts.isTypeQueryNode(parent)) return true
|
|
141
|
+
return false
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function isPublicEnvAccess(node: ts.Identifier): boolean {
|
|
145
|
+
const envAccess = node.parent
|
|
146
|
+
if (
|
|
147
|
+
node.text !== "process" ||
|
|
148
|
+
!envAccess ||
|
|
149
|
+
!ts.isPropertyAccessExpression(envAccess) ||
|
|
150
|
+
envAccess.expression !== node ||
|
|
151
|
+
envAccess.name.text !== "env"
|
|
152
|
+
) {
|
|
153
|
+
return false
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const valueAccess = envAccess.parent
|
|
157
|
+
return (
|
|
158
|
+
ts.isPropertyAccessExpression(valueAccess) &&
|
|
159
|
+
valueAccess.expression === envAccess &&
|
|
160
|
+
valueAccess.name.text.startsWith("PUBLIC_")
|
|
161
|
+
)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Analyze one background source file against the documented bare-runtime contract. */
|
|
165
|
+
export function findUnsupportedBackgroundApis(
|
|
166
|
+
sourceText: string,
|
|
167
|
+
fileName = "background.ts",
|
|
168
|
+
): BackgroundRuntimeFinding[] {
|
|
169
|
+
const kind = fileName.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS
|
|
170
|
+
const source = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.Latest, true, kind)
|
|
171
|
+
const compilerOptions: ts.CompilerOptions = {
|
|
172
|
+
allowJs: true,
|
|
173
|
+
jsx: ts.JsxEmit.Preserve,
|
|
174
|
+
noLib: true,
|
|
175
|
+
noResolve: true,
|
|
176
|
+
target: ts.ScriptTarget.Latest,
|
|
177
|
+
}
|
|
178
|
+
const host = ts.createCompilerHost(compilerOptions)
|
|
179
|
+
host.fileExists = (candidate) => candidate === fileName
|
|
180
|
+
host.getSourceFile = (candidate) => (candidate === fileName ? source : undefined)
|
|
181
|
+
host.readFile = (candidate) => (candidate === fileName ? sourceText : undefined)
|
|
182
|
+
host.writeFile = () => {}
|
|
183
|
+
const checker = ts.createProgram([fileName], compilerOptions, host).getTypeChecker()
|
|
184
|
+
const findings: BackgroundRuntimeFinding[] = []
|
|
185
|
+
const seen = new Set<string>()
|
|
186
|
+
|
|
187
|
+
const isLocallyBound = (node: ts.Identifier): boolean =>
|
|
188
|
+
checker
|
|
189
|
+
.getSymbolAtLocation(node)
|
|
190
|
+
?.declarations?.some((declaration) => declaration.getSourceFile() === source) ?? false
|
|
191
|
+
|
|
192
|
+
const globalObjectPath = (node: ts.PropertyAccessExpression): string[] | null => {
|
|
193
|
+
const properties: string[] = []
|
|
194
|
+
let expression: ts.Expression = node
|
|
195
|
+
while (ts.isPropertyAccessExpression(expression)) {
|
|
196
|
+
properties.unshift(expression.name.text)
|
|
197
|
+
expression = expression.expression
|
|
198
|
+
}
|
|
199
|
+
if (
|
|
200
|
+
!ts.isIdentifier(expression) ||
|
|
201
|
+
(expression.text !== "globalThis" && expression.text !== "self") ||
|
|
202
|
+
isLocallyBound(expression)
|
|
203
|
+
) {
|
|
204
|
+
return null
|
|
205
|
+
}
|
|
206
|
+
return [expression.text, ...properties]
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const add = (node: ts.Node, api: string, replacement: string): void => {
|
|
210
|
+
const start = node.getStart(source)
|
|
211
|
+
const {line, character} = source.getLineAndCharacterOfPosition(start)
|
|
212
|
+
const key = `${api}:${line}:${character}`
|
|
213
|
+
if (seen.has(key)) return
|
|
214
|
+
seen.add(key)
|
|
215
|
+
findings.push({api, line: line + 1, column: character + 1, replacement})
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const visit = (node: ts.Node): void => {
|
|
219
|
+
if (
|
|
220
|
+
ts.isImportDeclaration(node) &&
|
|
221
|
+
importHasRuntimeBindings(node) &&
|
|
222
|
+
ts.isStringLiteral(node.moduleSpecifier)
|
|
223
|
+
) {
|
|
224
|
+
const builtin = nodeBuiltinName(node.moduleSpecifier.text)
|
|
225
|
+
if (builtin) {
|
|
226
|
+
add(node.moduleSpecifier, builtin, "remove the Node built-in; it is unavailable in background")
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (
|
|
231
|
+
ts.isExportDeclaration(node) &&
|
|
232
|
+
exportHasRuntimeBindings(node) &&
|
|
233
|
+
node.moduleSpecifier &&
|
|
234
|
+
ts.isStringLiteral(node.moduleSpecifier)
|
|
235
|
+
) {
|
|
236
|
+
const builtin = nodeBuiltinName(node.moduleSpecifier.text)
|
|
237
|
+
if (builtin) {
|
|
238
|
+
add(node.moduleSpecifier, builtin, "remove the Node built-in; it is unavailable in background")
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
if (
|
|
243
|
+
ts.isCallExpression(node) &&
|
|
244
|
+
node.expression.kind === ts.SyntaxKind.ImportKeyword &&
|
|
245
|
+
node.arguments.length === 1
|
|
246
|
+
) {
|
|
247
|
+
const specifier = node.arguments[0]
|
|
248
|
+
if (specifier && ts.isStringLiteral(specifier)) {
|
|
249
|
+
const builtin = nodeBuiltinName(specifier.text)
|
|
250
|
+
if (builtin) add(specifier, builtin, "remove the Node built-in; it is unavailable in background")
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (
|
|
255
|
+
ts.isPropertyAccessExpression(node)
|
|
256
|
+
) {
|
|
257
|
+
const path = globalObjectPath(node)
|
|
258
|
+
if (path?.[1] === "crypto" && path[2] === "subtle") {
|
|
259
|
+
add(node, `${path[0]}.crypto.subtle`, "use crypto.getRandomValues/randomUUID or move cryptography behind your backend")
|
|
260
|
+
} else if (path?.[1]) {
|
|
261
|
+
const replacement = UNSUPPORTED_BACKGROUND_GLOBALS.get(path[1])
|
|
262
|
+
if (replacement) add(node, `${path[0]}.${path[1]}`, replacement)
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (
|
|
267
|
+
ts.isPropertyAccessExpression(node) &&
|
|
268
|
+
ts.isIdentifier(node.expression) &&
|
|
269
|
+
node.expression.text === "crypto" &&
|
|
270
|
+
!isLocallyBound(node.expression) &&
|
|
271
|
+
node.name.text === "subtle"
|
|
272
|
+
) {
|
|
273
|
+
add(node, "crypto.subtle", "use crypto.getRandomValues/randomUUID or move cryptography behind your backend")
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (
|
|
277
|
+
ts.isIdentifier(node) &&
|
|
278
|
+
!isDeclarationOrPropertyName(node) &&
|
|
279
|
+
!isLocallyBound(node) &&
|
|
280
|
+
!isPublicEnvAccess(node)
|
|
281
|
+
) {
|
|
282
|
+
const replacement = UNSUPPORTED_BACKGROUND_GLOBALS.get(node.text)
|
|
283
|
+
if (replacement) add(node, node.text, replacement)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
ts.forEachChild(node, visit)
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
visit(source)
|
|
290
|
+
return findings.sort((a, b) => a.line - b.line || a.column - b.column)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Fail the background bundle when source code relies on browser or Node APIs
|
|
295
|
+
* that do not exist in Glassly's JavaScriptCore/QuickJS runtime.
|
|
296
|
+
*/
|
|
297
|
+
export function backgroundRuntimeGuardPlugin(importMetaUrl: string) {
|
|
298
|
+
const sourceRoot = resolve(dirname(fileURLToPath(importMetaUrl)), "src")
|
|
299
|
+
return {
|
|
300
|
+
name: "glassly-background-runtime-guard",
|
|
301
|
+
setup(build: BunBuild) {
|
|
302
|
+
build.onLoad({filter: /\.[cm]?[jt]sx?$/}, async ({path}) => {
|
|
303
|
+
const rel = relative(sourceRoot, path)
|
|
304
|
+
if (rel.startsWith("..") || isAbsolute(rel)) return undefined
|
|
305
|
+
|
|
306
|
+
const contents = await readFile(path, "utf8")
|
|
307
|
+
const findings = findUnsupportedBackgroundApis(contents, path)
|
|
308
|
+
if (findings.length > 0) {
|
|
309
|
+
const details = findings
|
|
310
|
+
.map(({api, line, column, replacement}) => ` ${rel}:${line}:${column} ${api}: ${replacement}`)
|
|
311
|
+
.join("\n")
|
|
312
|
+
throw new Error(
|
|
313
|
+
`Unsupported API in Glassly miniapp background runtime:\n${details}\n` +
|
|
314
|
+
"Background is not a browser or Node. Put browser UI code in src/ui/.",
|
|
315
|
+
)
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const ext = path.split(".").pop()
|
|
319
|
+
const loader =
|
|
320
|
+
ext === "tsx" ? "tsx" : ext === "jsx" ? "jsx" : ext === "ts" || ext === "mts" || ext === "cts" ? "ts" : "js"
|
|
321
|
+
return {contents, loader}
|
|
322
|
+
})
|
|
323
|
+
},
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Force React and ReactDOM imports in a miniapp UI bundle to resolve to one
|
|
329
|
+
* package instance. This prevents invalid-hook-call crashes when a workspace
|
|
330
|
+
* has multiple React versions available and Bun resolves `react/jsx-runtime`
|
|
331
|
+
* from a dependency tree different from `react-dom/client`.
|
|
332
|
+
*/
|
|
333
|
+
export function reactSingletonPlugin(importMetaUrl: string) {
|
|
334
|
+
const require = createRequire(importMetaUrl)
|
|
335
|
+
const reactRoot = dirname(require.resolve("react/package.json"))
|
|
336
|
+
const reactDomRoot = dirname(require.resolve("react-dom/package.json"))
|
|
337
|
+
|
|
338
|
+
const aliases = new Map([
|
|
339
|
+
["react", join(reactRoot, "index.js")],
|
|
340
|
+
["react/jsx-runtime", join(reactRoot, "jsx-runtime.js")],
|
|
341
|
+
["react/jsx-dev-runtime", join(reactRoot, "jsx-dev-runtime.js")],
|
|
342
|
+
["react-dom", join(reactDomRoot, "index.js")],
|
|
343
|
+
["react-dom/client", join(reactDomRoot, "client.js")],
|
|
344
|
+
])
|
|
345
|
+
|
|
346
|
+
return {
|
|
347
|
+
name: "glassly-react-singleton",
|
|
348
|
+
setup(build: BunBuild) {
|
|
349
|
+
build.onResolve({filter: /^react(?:\/jsx-runtime|\/jsx-dev-runtime)?$/}, ({path}) => {
|
|
350
|
+
return {path: aliases.get(path)!}
|
|
351
|
+
})
|
|
352
|
+
build.onResolve({filter: /^react-dom(?:\/client)?$/}, ({path}) => {
|
|
353
|
+
return {path: aliases.get(path)!}
|
|
354
|
+
})
|
|
355
|
+
},
|
|
356
|
+
}
|
|
357
|
+
}
|
package/src/build.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared production-build step used by `release` and `pack`.
|
|
3
|
+
*
|
|
4
|
+
* Both commands produce a distributable bundle, so both must agree on what
|
|
5
|
+
* that means: `<pm> run build` with NODE_ENV=production. Build scripts read
|
|
6
|
+
* process.env.NODE_ENV and substitute it via Bun.build's `define`, which
|
|
7
|
+
* tree-shakes any `if (NODE_ENV === "development")` branches (dev panels,
|
|
8
|
+
* debug overlays) out of the bundle. Without this, `pack` would silently
|
|
9
|
+
* zip whatever mode the last build happened to be — usually a dev build
|
|
10
|
+
* left behind by `glassly dev`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import {existsSync, readFileSync} from 'fs'
|
|
14
|
+
import {join, resolve} from 'path'
|
|
15
|
+
|
|
16
|
+
export function detectPackageManager(cwd: string): 'bun' | 'pnpm' | 'yarn' | 'npm' {
|
|
17
|
+
if (existsSync(join(cwd, 'bun.lock')) || existsSync(join(cwd, 'bun.lockb'))) return 'bun'
|
|
18
|
+
if (existsSync(join(cwd, 'pnpm-lock.yaml'))) return 'pnpm'
|
|
19
|
+
if (existsSync(join(cwd, 'yarn.lock'))) return 'yarn'
|
|
20
|
+
return 'npm'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function packageJsonHasBuildScript(cwd: string): boolean {
|
|
24
|
+
const pkgPath = join(cwd, 'package.json')
|
|
25
|
+
if (!existsSync(pkgPath)) return false
|
|
26
|
+
try {
|
|
27
|
+
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
|
|
28
|
+
return typeof pkg?.scripts?.build === 'string' && pkg.scripts.build.length > 0
|
|
29
|
+
} catch {
|
|
30
|
+
return false
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Run `<pm> run build` with NODE_ENV=production and verify it produced
|
|
36
|
+
* `dist/`. Exits the process with an error message on any failure.
|
|
37
|
+
*/
|
|
38
|
+
export async function buildProduction(cwd: string): Promise<void> {
|
|
39
|
+
const pm = detectPackageManager(cwd)
|
|
40
|
+
if (!packageJsonHasBuildScript(cwd)) {
|
|
41
|
+
console.error(
|
|
42
|
+
'Error: no "build" script in package.json. Add one (e.g. "build": "vite build") and re-run.',
|
|
43
|
+
)
|
|
44
|
+
process.exit(1)
|
|
45
|
+
}
|
|
46
|
+
console.log(`Building with ${pm} run build...`)
|
|
47
|
+
const buildStart = Date.now()
|
|
48
|
+
const buildProc = Bun.spawn([pm, 'run', 'build'], {
|
|
49
|
+
cwd,
|
|
50
|
+
env: {...process.env, NODE_ENV: 'production'},
|
|
51
|
+
stdout: 'inherit',
|
|
52
|
+
stderr: 'inherit',
|
|
53
|
+
})
|
|
54
|
+
const buildCode = await buildProc.exited
|
|
55
|
+
if (buildCode !== 0) {
|
|
56
|
+
console.error('Error: build failed')
|
|
57
|
+
process.exit(1)
|
|
58
|
+
}
|
|
59
|
+
const distDir = resolve(cwd, 'dist')
|
|
60
|
+
if (!existsSync(distDir)) {
|
|
61
|
+
console.error(
|
|
62
|
+
'Error: build succeeded but dist/ does not exist. Configure your bundler to output to dist/.',
|
|
63
|
+
)
|
|
64
|
+
process.exit(1)
|
|
65
|
+
}
|
|
66
|
+
console.log(`✓ Built (${((Date.now() - buildStart) / 1000).toFixed(1)}s)`)
|
|
67
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/// <reference types="bun-types" />
|
|
2
|
+
|
|
3
|
+
import {afterEach, beforeEach, describe, expect, test} from "bun:test"
|
|
4
|
+
import {mkdirSync, mkdtempSync, rmSync, writeFileSync} from "fs"
|
|
5
|
+
import {tmpdir} from "os"
|
|
6
|
+
import {join} from "path"
|
|
7
|
+
import JSZip from "jszip"
|
|
8
|
+
|
|
9
|
+
import {buildProjectZip, listProjectFiles} from "./dev-server"
|
|
10
|
+
|
|
11
|
+
describe("listProjectFiles — dist/ inclusion", () => {
|
|
12
|
+
let root: string
|
|
13
|
+
|
|
14
|
+
beforeEach(() => {
|
|
15
|
+
root = mkdtempSync(join(tmpdir(), "glassly-dev-test-"))
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
afterEach(() => {
|
|
19
|
+
rmSync(root, {recursive: true, force: true})
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
function touch(rel: string, contents = "// stub") {
|
|
23
|
+
const abs = join(root, rel)
|
|
24
|
+
mkdirSync(join(abs, ".."), {recursive: true})
|
|
25
|
+
writeFileSync(abs, contents)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Convenience: the zip-internal entry names the function produces.
|
|
29
|
+
const entries = (root: string) => listProjectFiles(root).map((f) => f.entry)
|
|
30
|
+
|
|
31
|
+
test("ships both build bundles with the dist/ prefix stripped off the entry names", () => {
|
|
32
|
+
touch('miniapp.json', '{"packageName":"com.test","version":"1.0.0","name":"Test"}')
|
|
33
|
+
touch("dist/background/index.js")
|
|
34
|
+
touch("dist/ui/index.html")
|
|
35
|
+
touch("dist/ui/main.js")
|
|
36
|
+
touch("src/background/index.ts")
|
|
37
|
+
const listed = listProjectFiles(root)
|
|
38
|
+
// disk paths keep dist/ (that's where the files live)…
|
|
39
|
+
expect(listed.map((f) => f.disk)).toContain("dist/background/index.js")
|
|
40
|
+
// …but zip entry names drop it, matching miniapp.json's entry.* paths.
|
|
41
|
+
expect(entries(root)).toContain("background/index.js")
|
|
42
|
+
expect(entries(root)).toContain("ui/index.html")
|
|
43
|
+
expect(entries(root)).toContain("ui/main.js")
|
|
44
|
+
expect(entries(root)).toContain("miniapp.json")
|
|
45
|
+
expect(entries(root)).not.toContain("dist/background/index.js")
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
test("strict allowlist: source + build config + node_modules + public are NOT shipped", () => {
|
|
49
|
+
touch('miniapp.json', '{"packageName":"com.test","version":"1.0.0","name":"Test"}')
|
|
50
|
+
touch("dist/background/index.js")
|
|
51
|
+
touch("src/background/index.ts")
|
|
52
|
+
touch("package.json")
|
|
53
|
+
touch("tsconfig.json")
|
|
54
|
+
touch("build.ts")
|
|
55
|
+
touch("bunfig.toml")
|
|
56
|
+
touch("node_modules/x/index.js")
|
|
57
|
+
touch("public/fonts/big.ttf")
|
|
58
|
+
const listed = entries(root)
|
|
59
|
+
expect(listed.some((p) => p.startsWith("src/"))).toBe(false)
|
|
60
|
+
expect(listed.some((p) => p.startsWith("public/"))).toBe(false)
|
|
61
|
+
expect(listed.some((p) => p.startsWith("node_modules/"))).toBe(false)
|
|
62
|
+
expect(listed).not.toContain("package.json")
|
|
63
|
+
expect(listed).not.toContain("tsconfig.json")
|
|
64
|
+
expect(listed).not.toContain("build.ts")
|
|
65
|
+
expect(listed).not.toContain("bunfig.toml")
|
|
66
|
+
expect(listed).toContain("miniapp.json")
|
|
67
|
+
expect(listed).toContain("background/index.js")
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
test("ships the manifest-declared icon and skips unrelated images", () => {
|
|
71
|
+
touch('miniapp.json', '{"packageName":"com.test","version":"1.0.0","name":"Test","icon":"my-icon.png"}')
|
|
72
|
+
touch("my-icon.png")
|
|
73
|
+
touch("other-image.png")
|
|
74
|
+
touch("dist/background/index.js")
|
|
75
|
+
const listed = entries(root)
|
|
76
|
+
expect(listed).toContain("my-icon.png")
|
|
77
|
+
expect(listed).not.toContain("other-image.png")
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
test("defaults to icon.png when manifest does not declare an icon", () => {
|
|
81
|
+
touch('miniapp.json', '{"packageName":"com.test","version":"1.0.0","name":"Test"}')
|
|
82
|
+
touch("icon.png")
|
|
83
|
+
touch("dist/background/index.js")
|
|
84
|
+
const listed = entries(root)
|
|
85
|
+
expect(listed).toContain("icon.png")
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
test("skips icon if it is missing from disk (manifest may be stale)", () => {
|
|
89
|
+
touch('miniapp.json', '{"packageName":"com.test","version":"1.0.0","name":"Test","icon":"icon.png"}')
|
|
90
|
+
touch("dist/background/index.js")
|
|
91
|
+
const listed = entries(root)
|
|
92
|
+
expect(listed).not.toContain("icon.png")
|
|
93
|
+
})
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
describe("buildProjectZip — two-output bundle contract", () => {
|
|
97
|
+
let root: string
|
|
98
|
+
|
|
99
|
+
beforeEach(() => {
|
|
100
|
+
root = mkdtempSync(join(tmpdir(), "glassly-zip-test-"))
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
afterEach(() => {
|
|
104
|
+
rmSync(root, {recursive: true, force: true})
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
function touch(rel: string, contents = "// stub") {
|
|
108
|
+
const abs = join(root, rel)
|
|
109
|
+
mkdirSync(join(abs, ".."), {recursive: true})
|
|
110
|
+
writeFileSync(abs, contents)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
test("zip ships both bundles at the root (dist/ prefix stripped), manifest at root", async () => {
|
|
114
|
+
touch("miniapp.json", '{"packageName":"com.test","version":"1.0.0","name":"Test","hardwareRequirements":[]}')
|
|
115
|
+
touch("dist/background/index.js", "console.log('bg')")
|
|
116
|
+
touch("dist/ui/index.html", "<!doctype html><html></html>")
|
|
117
|
+
touch("dist/ui/main.js", "console.log('ui')")
|
|
118
|
+
const buf = await buildProjectZip(root)
|
|
119
|
+
const zip = await JSZip.loadAsync(buf)
|
|
120
|
+
expect(zip.files["miniapp.json"]).toBeDefined()
|
|
121
|
+
expect(zip.files["background/index.js"]).toBeDefined()
|
|
122
|
+
expect(zip.files["ui/index.html"]).toBeDefined()
|
|
123
|
+
expect(zip.files["ui/main.js"]).toBeDefined()
|
|
124
|
+
// The on-disk dist/ prefix must not leak into the zip layout.
|
|
125
|
+
expect(zip.files["dist/background/index.js"]).toBeUndefined()
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
test("zip preserves file contents byte-for-byte", async () => {
|
|
129
|
+
touch("miniapp.json", '{"a":1}')
|
|
130
|
+
touch("dist/background/index.js", "/* bg-stub */")
|
|
131
|
+
const buf = await buildProjectZip(root)
|
|
132
|
+
const zip = await JSZip.loadAsync(buf)
|
|
133
|
+
const manifest = await zip.files["miniapp.json"]!.async("string")
|
|
134
|
+
const bg = await zip.files["background/index.js"]!.async("string")
|
|
135
|
+
expect(manifest).toBe('{"a":1}')
|
|
136
|
+
expect(bg).toBe("/* bg-stub */")
|
|
137
|
+
})
|
|
138
|
+
})
|