@sixb/app 0.0.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/LICENSE +21 -0
- package/README.md +172 -0
- package/dist/agents.d.ts +6 -0
- package/dist/agents.d.ts.map +1 -0
- package/dist/agents.js +26 -0
- package/dist/agents.js.map +10 -0
- package/dist/build.d.ts +21 -0
- package/dist/build.d.ts.map +1 -0
- package/dist/codegen.d.ts +43 -0
- package/dist/codegen.d.ts.map +1 -0
- package/dist/createCustomApp.d.ts +43 -0
- package/dist/createCustomApp.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1464 -0
- package/dist/index.js.map +18 -0
- package/dist/manifest.d.ts +3 -0
- package/dist/manifest.d.ts.map +1 -0
- package/dist/metadata.d.ts +29 -0
- package/dist/metadata.d.ts.map +1 -0
- package/dist/runtime.d.ts +12 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/scanner.d.ts +19 -0
- package/dist/scanner.d.ts.map +1 -0
- package/dist/styles.d.ts +33 -0
- package/dist/styles.d.ts.map +1 -0
- package/dist/tailwind.d.ts +62 -0
- package/dist/tailwind.d.ts.map +1 -0
- package/dist/tsconfig.json +5 -0
- package/package.json +74 -0
- package/src/agents.ts +23 -0
- package/src/build.ts +105 -0
- package/src/codegen.ts +587 -0
- package/src/createCustomApp.ts +770 -0
- package/src/index.ts +15 -0
- package/src/manifest.ts +29 -0
- package/src/metadata.ts +206 -0
- package/src/runtime.ts +16 -0
- package/src/scanner.ts +81 -0
- package/src/styles.ts +83 -0
- package/src/tailwind.ts +195 -0
|
@@ -0,0 +1,770 @@
|
|
|
1
|
+
import { watch } from "node:fs"
|
|
2
|
+
import { access, cp, mkdir, readFile, writeFile } from "node:fs/promises"
|
|
3
|
+
import { dirname, isAbsolute, join, normalize, relative, resolve } from "node:path"
|
|
4
|
+
import { pathToFileURL } from "node:url"
|
|
5
|
+
import type { AuthSessionAudience } from "@sixb/core"
|
|
6
|
+
import {
|
|
7
|
+
type BuildAppResult,
|
|
8
|
+
buildApp,
|
|
9
|
+
prepareAppHtmlBundleEntry,
|
|
10
|
+
restoreAppStaticUrls,
|
|
11
|
+
} from "./build"
|
|
12
|
+
import { type BuiltInRouteManifestEntry, generateAppEntry, generateRouteManifest } from "./codegen"
|
|
13
|
+
import { renderCustomAppRuntimeScript } from "./runtime"
|
|
14
|
+
import { type PageRoute, scanPages } from "./scanner"
|
|
15
|
+
import { type CustomAppStylesheet, resolveCustomAppStylesheet } from "./styles"
|
|
16
|
+
import { createTailwindCssCompiler, type TailwindCssCompiler } from "./tailwind"
|
|
17
|
+
|
|
18
|
+
export interface CreateCustomAppOptions {
|
|
19
|
+
rootDir: string
|
|
20
|
+
appDir?: string
|
|
21
|
+
generatedDir?: string
|
|
22
|
+
publicDir?: string
|
|
23
|
+
apiBaseUrl?: string
|
|
24
|
+
audience?: AuthSessionAudience
|
|
25
|
+
authEnabled?: boolean
|
|
26
|
+
agentRoutes?: boolean
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface CustomAppDevOptions {
|
|
30
|
+
host?: string
|
|
31
|
+
port?: number
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface CustomAppBuildOptions {
|
|
35
|
+
outdir?: string
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface CustomAppStartOptions {
|
|
39
|
+
host?: string
|
|
40
|
+
port?: number
|
|
41
|
+
outdir?: string
|
|
42
|
+
apiBaseUrl?: string
|
|
43
|
+
audience?: AuthSessionAudience
|
|
44
|
+
authEnabled?: boolean
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface CustomAppDevServer {
|
|
48
|
+
host: string
|
|
49
|
+
port: number
|
|
50
|
+
url: string
|
|
51
|
+
stop(): Promise<void>
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface CustomAppInstance {
|
|
55
|
+
scanRoutes(): Promise<PageRoute[]>
|
|
56
|
+
hasRoutes(): Promise<boolean>
|
|
57
|
+
dev(options?: CustomAppDevOptions): Promise<CustomAppDevServer>
|
|
58
|
+
build(options?: CustomAppBuildOptions): Promise<BuildAppResult>
|
|
59
|
+
start(options?: CustomAppStartOptions): Promise<CustomAppDevServer>
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
type BunServeRoutes = NonNullable<Parameters<typeof Bun.serve>[0]["routes"]>
|
|
63
|
+
type BunServeRoute = BunServeRoutes[string]
|
|
64
|
+
const packageRoot = resolve(import.meta.dir, "..")
|
|
65
|
+
const builtInAgentRouteModule = "@sixb/app/agents"
|
|
66
|
+
const builtInAgentRoutePaths = ["/agents", "/agents/new/:agentId", "/agents/:threadId"] as const
|
|
67
|
+
const builtInAgentRouteSourcePath = join(packageRoot, "src", "agents.ts")
|
|
68
|
+
const customAppManifestRoute = "/app.webmanifest"
|
|
69
|
+
const internalAppShellRoute = "/__sixb/generated/app-shell"
|
|
70
|
+
|
|
71
|
+
export async function createCustomApp(options: CreateCustomAppOptions): Promise<CustomAppInstance> {
|
|
72
|
+
const rootDir = resolve(options.rootDir)
|
|
73
|
+
const appDir = options.appDir ? resolve(rootDir, options.appDir) : resolve(rootDir, "app")
|
|
74
|
+
const generatedDir = resolve(rootDir, options.generatedDir ?? join(".sixb", "generated"))
|
|
75
|
+
const publicDir = options.publicDir
|
|
76
|
+
? resolve(rootDir, options.publicDir)
|
|
77
|
+
: resolve(appDir, "public")
|
|
78
|
+
const apiBaseUrl = options.apiBaseUrl
|
|
79
|
+
const audience = options.audience ?? "app"
|
|
80
|
+
const authEnabled = options.authEnabled ?? true
|
|
81
|
+
const agentRoutesEnabled = options.agentRoutes ?? true
|
|
82
|
+
|
|
83
|
+
async function scanRoutes(): Promise<PageRoute[]> {
|
|
84
|
+
if (!(await pathExists(appDir))) {
|
|
85
|
+
return []
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return await scanPages(appDir)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
let tailwindCompiler: TailwindCssCompiler | null = null
|
|
92
|
+
let tailwindCompilerKey: string | null = null
|
|
93
|
+
let builtInAgentCssCompiler: TailwindCssCompiler | null = null
|
|
94
|
+
|
|
95
|
+
// `app/globals.css` is source. When it uses Tailwind, compile it to
|
|
96
|
+
// `.sixb/generated/app.css` and bundle that; plain CSS bundles as-is. This
|
|
97
|
+
// runs in both dev and build, so `sixb build` alone always produces fresh CSS.
|
|
98
|
+
async function prepareStylesheet(stylesheet?: CustomAppStylesheet): Promise<CustomAppStylesheet> {
|
|
99
|
+
stylesheet ??= await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir })
|
|
100
|
+
if (stylesheet.kind !== "tailwind") {
|
|
101
|
+
return stylesheet
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
await compileAppTailwindStylesheet(stylesheet.sourcePath, stylesheet.outputPath)
|
|
105
|
+
return stylesheet
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function compileAppTailwindStylesheet(
|
|
109
|
+
inputPath: string,
|
|
110
|
+
outputPath: string
|
|
111
|
+
): Promise<void> {
|
|
112
|
+
const key = `${inputPath}\0${outputPath}`
|
|
113
|
+
if (tailwindCompilerKey !== key) {
|
|
114
|
+
await tailwindCompiler?.stop()
|
|
115
|
+
tailwindCompiler = createTailwindCssCompiler({
|
|
116
|
+
inputPath,
|
|
117
|
+
outputPath,
|
|
118
|
+
// Scope Tailwind's automatic source detection to app/ so it never walks
|
|
119
|
+
// vendor/ or unrelated trees; resolve the CLI from the project's deps.
|
|
120
|
+
cwd: appDir,
|
|
121
|
+
resolveFrom: rootDir,
|
|
122
|
+
label: "[SixbCustomApp]",
|
|
123
|
+
})
|
|
124
|
+
tailwindCompilerKey = key
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const compiler = tailwindCompiler
|
|
128
|
+
if (!compiler) {
|
|
129
|
+
throw new Error("[SixbCustomApp] Tailwind CSS compiler was not initialized")
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
await compiler.compile()
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function prepareCombinedBuiltInAgentStylesheet(
|
|
136
|
+
stylesheet: Extract<CustomAppStylesheet, { kind: "tailwind" }>
|
|
137
|
+
): Promise<string> {
|
|
138
|
+
const inputPath = join(generatedDir, "app.input.css")
|
|
139
|
+
const uiGlobalsPath = Bun.resolveSync("@sixb/ui/globals.css", packageRoot)
|
|
140
|
+
const agentUiGlobalsPath = Bun.resolveSync("@sixb/agent-ui/globals.css", packageRoot)
|
|
141
|
+
await writeFileIfChanged(
|
|
142
|
+
inputPath,
|
|
143
|
+
[
|
|
144
|
+
`@import ${JSON.stringify(uiGlobalsPath)};`,
|
|
145
|
+
`@source ${JSON.stringify(builtInAgentRouteSourcePath)};`,
|
|
146
|
+
`@import ${JSON.stringify(stylesheet.sourcePath)};`,
|
|
147
|
+
`@import ${JSON.stringify(agentUiGlobalsPath)};`,
|
|
148
|
+
"",
|
|
149
|
+
].join("\n")
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
await compileAppTailwindStylesheet(inputPath, stylesheet.outputPath)
|
|
153
|
+
return stylesheet.outputPath
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function prepareStylesheets(builtInRoutes: readonly BuiltInRouteManifestEntry[]): Promise<{
|
|
157
|
+
stylesheetPath: string | null
|
|
158
|
+
frameworkStylesheetPaths: readonly string[]
|
|
159
|
+
}> {
|
|
160
|
+
const stylesheet = await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir })
|
|
161
|
+
|
|
162
|
+
if (stylesheet.kind === "tailwind" && builtInRoutes.length > 0) {
|
|
163
|
+
return {
|
|
164
|
+
stylesheetPath: await prepareCombinedBuiltInAgentStylesheet(stylesheet),
|
|
165
|
+
frameworkStylesheetPaths: [],
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const preparedStylesheet = await prepareStylesheet(stylesheet)
|
|
170
|
+
const builtInAgentStylesheetPath = await prepareBuiltInAgentStylesheet(builtInRoutes)
|
|
171
|
+
|
|
172
|
+
return {
|
|
173
|
+
frameworkStylesheetPaths: builtInAgentStylesheetPath ? [builtInAgentStylesheetPath] : [],
|
|
174
|
+
stylesheetPath:
|
|
175
|
+
preparedStylesheet.kind === "none"
|
|
176
|
+
? null
|
|
177
|
+
: preparedStylesheet.kind === "static"
|
|
178
|
+
? preparedStylesheet.path
|
|
179
|
+
: preparedStylesheet.outputPath,
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
async function prepareBuiltInAgentStylesheet(
|
|
184
|
+
builtInRoutes: readonly BuiltInRouteManifestEntry[]
|
|
185
|
+
): Promise<string | null> {
|
|
186
|
+
if (builtInRoutes.length === 0) {
|
|
187
|
+
return null
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const inputPath = join(generatedDir, "agent-ui.input.css")
|
|
191
|
+
const outputPath = join(generatedDir, "agent-ui.css")
|
|
192
|
+
const uiGlobalsPath = Bun.resolveSync("@sixb/ui/globals.css", packageRoot)
|
|
193
|
+
const agentUiGlobalsPath = Bun.resolveSync("@sixb/agent-ui/globals.css", packageRoot)
|
|
194
|
+
await writeFileIfChanged(
|
|
195
|
+
inputPath,
|
|
196
|
+
[
|
|
197
|
+
`@import ${JSON.stringify(uiGlobalsPath)};`,
|
|
198
|
+
`@source ${JSON.stringify(builtInAgentRouteSourcePath)};`,
|
|
199
|
+
`@import ${JSON.stringify(agentUiGlobalsPath)};`,
|
|
200
|
+
"",
|
|
201
|
+
].join("\n")
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
builtInAgentCssCompiler ??= createTailwindCssCompiler({
|
|
205
|
+
inputPath,
|
|
206
|
+
outputPath,
|
|
207
|
+
cwd: packageRoot,
|
|
208
|
+
resolveFrom: packageRoot,
|
|
209
|
+
label: "[SixbCustomApp]",
|
|
210
|
+
})
|
|
211
|
+
await builtInAgentCssCompiler.compile()
|
|
212
|
+
return outputPath
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function prepareGeneratedApp(): Promise<{
|
|
216
|
+
htmlPath: string
|
|
217
|
+
manifestPath: string
|
|
218
|
+
routes: PageRoute[]
|
|
219
|
+
}> {
|
|
220
|
+
const routes = await scanRoutes()
|
|
221
|
+
if (routes.length === 0) {
|
|
222
|
+
throw new Error(`[SixbCustomApp] No app routes found in ${appDir}`)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const builtInRoutes = agentRoutesEnabled ? builtInAgentRoutesFor(routes) : []
|
|
226
|
+
const stylesheets = await prepareStylesheets(builtInRoutes)
|
|
227
|
+
await generateRouteManifest(routes, generatedDir, { builtInRoutes })
|
|
228
|
+
const { htmlPath, manifestPath } = await generateAppEntry(rootDir, generatedDir, {
|
|
229
|
+
apiBaseUrl,
|
|
230
|
+
audience,
|
|
231
|
+
authEnabled,
|
|
232
|
+
appDir,
|
|
233
|
+
publicDir,
|
|
234
|
+
frameworkStylesheetPaths: stylesheets.frameworkStylesheetPaths,
|
|
235
|
+
stylesheetPath: stylesheets.stylesheetPath,
|
|
236
|
+
})
|
|
237
|
+
return { htmlPath, manifestPath, routes }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
async scanRoutes() {
|
|
242
|
+
return await scanRoutes()
|
|
243
|
+
},
|
|
244
|
+
|
|
245
|
+
async hasRoutes() {
|
|
246
|
+
const routes = await scanRoutes()
|
|
247
|
+
return routes.length > 0
|
|
248
|
+
},
|
|
249
|
+
|
|
250
|
+
async dev(devOptions: CustomAppDevOptions = {}) {
|
|
251
|
+
const host = devOptions.host ?? "0.0.0.0"
|
|
252
|
+
const port = devOptions.port ?? 3001
|
|
253
|
+
const { htmlPath, manifestPath } = await prepareGeneratedApp()
|
|
254
|
+
let htmlImportVersion = 0
|
|
255
|
+
let htmlBundle = await importHtmlBundle(htmlPath, htmlImportVersion)
|
|
256
|
+
const publicRoutes = (await pathExists(publicDir)) ? await createPublicRoutes(publicDir) : {}
|
|
257
|
+
let internalOrigin = ""
|
|
258
|
+
const serveOptions = (bundle: Bun.HTMLBundle) =>
|
|
259
|
+
({
|
|
260
|
+
port,
|
|
261
|
+
hostname: host,
|
|
262
|
+
development: true,
|
|
263
|
+
routes: {
|
|
264
|
+
...publicRoutes,
|
|
265
|
+
...reservedSixbRoutes(),
|
|
266
|
+
[customAppManifestRoute]: manifestRoute(manifestPath),
|
|
267
|
+
[internalAppShellRoute]: htmlBundleRoute(bundle),
|
|
268
|
+
"/": spaHtmlRoute(() => internalOrigin),
|
|
269
|
+
"/*": spaHtmlRoute(() => internalOrigin),
|
|
270
|
+
},
|
|
271
|
+
}) as Parameters<typeof Bun.serve>[0]
|
|
272
|
+
const server = Bun.serve(serveOptions(htmlBundle))
|
|
273
|
+
internalOrigin = devServerInternalOrigin(host, server.port ?? port)
|
|
274
|
+
|
|
275
|
+
// .ts/.tsx edits can change Tailwind's scanned classes and .css edits
|
|
276
|
+
// change the stylesheet source, so both regenerate the entry and
|
|
277
|
+
// recompile CSS. Debounced so a burst of saves builds once.
|
|
278
|
+
let rebuildTimer: ReturnType<typeof setTimeout> | null = null
|
|
279
|
+
let rebuildChain: Promise<void> = Promise.resolve()
|
|
280
|
+
const enqueueRebuild = () => {
|
|
281
|
+
rebuildChain = rebuildChain
|
|
282
|
+
.then(async () => {
|
|
283
|
+
const { htmlPath: nextHtmlPath } = await prepareGeneratedApp()
|
|
284
|
+
htmlImportVersion++
|
|
285
|
+
htmlBundle = await importHtmlBundle(nextHtmlPath, htmlImportVersion)
|
|
286
|
+
server.reload(serveOptions(htmlBundle))
|
|
287
|
+
})
|
|
288
|
+
.catch((error) => {
|
|
289
|
+
// Keep serving the last good build, but tell the user why styles
|
|
290
|
+
// or routes are stale instead of failing silently.
|
|
291
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
292
|
+
console.error(`[SixbCustomApp] Rebuild failed: ${message}`)
|
|
293
|
+
})
|
|
294
|
+
}
|
|
295
|
+
const watcher = watch(appDir, { recursive: true }, (_eventType, filename) => {
|
|
296
|
+
if (!filename) return
|
|
297
|
+
if (!/\.(ts|tsx|css)$/.test(String(filename))) return
|
|
298
|
+
|
|
299
|
+
if (rebuildTimer) {
|
|
300
|
+
clearTimeout(rebuildTimer)
|
|
301
|
+
}
|
|
302
|
+
rebuildTimer = setTimeout(() => {
|
|
303
|
+
rebuildTimer = null
|
|
304
|
+
enqueueRebuild()
|
|
305
|
+
}, 80)
|
|
306
|
+
})
|
|
307
|
+
|
|
308
|
+
// An FSWatcher emits `error` as an event, and an unhandled one takes the whole dev process
|
|
309
|
+
// down — the `.catch()` above only covers a failed rebuild. Losing file watching should cost
|
|
310
|
+
// hot reload, not the server: keep serving the last good build and say so.
|
|
311
|
+
watcher.on("error", (error: unknown) => {
|
|
312
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
313
|
+
console.error(
|
|
314
|
+
`[SixbCustomApp] Stopped watching ${appDir}: ${message}. ` +
|
|
315
|
+
"Serving the last build; restart to resume hot reload."
|
|
316
|
+
)
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
const displayHost = host === "0.0.0.0" ? "localhost" : host
|
|
320
|
+
|
|
321
|
+
return {
|
|
322
|
+
host,
|
|
323
|
+
port,
|
|
324
|
+
url: `http://${displayHost}:${port}`,
|
|
325
|
+
async stop() {
|
|
326
|
+
if (rebuildTimer) {
|
|
327
|
+
clearTimeout(rebuildTimer)
|
|
328
|
+
rebuildTimer = null
|
|
329
|
+
}
|
|
330
|
+
watcher.close()
|
|
331
|
+
await rebuildChain
|
|
332
|
+
await tailwindCompiler?.stop()
|
|
333
|
+
await builtInAgentCssCompiler?.stop()
|
|
334
|
+
server.stop(true)
|
|
335
|
+
},
|
|
336
|
+
}
|
|
337
|
+
},
|
|
338
|
+
|
|
339
|
+
async build(buildOptions: CustomAppBuildOptions = {}) {
|
|
340
|
+
const outdir = resolve(rootDir, buildOptions.outdir ?? join(".sixb", "dist", "app"))
|
|
341
|
+
const { htmlPath, manifestPath } = await prepareGeneratedApp()
|
|
342
|
+
const result = await buildApp({
|
|
343
|
+
entryPath: htmlPath,
|
|
344
|
+
manifestPath,
|
|
345
|
+
outdir,
|
|
346
|
+
})
|
|
347
|
+
|
|
348
|
+
if (result.success && (await pathExists(publicDir))) {
|
|
349
|
+
await cp(publicDir, outdir, {
|
|
350
|
+
recursive: true,
|
|
351
|
+
force: true,
|
|
352
|
+
filter: (source) => resolve(source) !== join(publicDir, "app.webmanifest"),
|
|
353
|
+
})
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
return result
|
|
357
|
+
},
|
|
358
|
+
|
|
359
|
+
async start(startOptions: CustomAppStartOptions = {}) {
|
|
360
|
+
const host = startOptions.host ?? "0.0.0.0"
|
|
361
|
+
const port = startOptions.port ?? 3001
|
|
362
|
+
const outdir = resolve(rootDir, startOptions.outdir ?? join(".sixb", "dist", "app"))
|
|
363
|
+
const indexPath = join(outdir, "index.html")
|
|
364
|
+
|
|
365
|
+
if (!(await pathExists(indexPath))) {
|
|
366
|
+
throw new Error(`[SixbCustomApp] No built app found in ${outdir}`)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
const indexHtml = injectRuntimeConfig(await Bun.file(indexPath).text(), {
|
|
370
|
+
apiBaseUrl: startOptions.apiBaseUrl ?? apiBaseUrl,
|
|
371
|
+
audience: startOptions.audience ?? audience,
|
|
372
|
+
authEnabled: startOptions.authEnabled ?? authEnabled,
|
|
373
|
+
})
|
|
374
|
+
const server = Bun.serve({
|
|
375
|
+
port,
|
|
376
|
+
hostname: host,
|
|
377
|
+
development: false,
|
|
378
|
+
async fetch(req) {
|
|
379
|
+
const url = new URL(req.url)
|
|
380
|
+
if (isReservedSixbRoute(url.pathname)) {
|
|
381
|
+
return notFoundResponse()
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
385
|
+
return notFoundResponse()
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (url.pathname === "/" || url.pathname === "") {
|
|
389
|
+
return htmlResponse(req, indexHtml)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const resolvedPath = resolveStaticPath(outdir, url.pathname)
|
|
393
|
+
if (!resolvedPath) {
|
|
394
|
+
return notFoundResponse()
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const directFile = Bun.file(resolvedPath)
|
|
398
|
+
if (await directFile.exists()) {
|
|
399
|
+
return fileResponse(req, directFile, staticAssetHeaders(url.pathname))
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (isAssetRequest(url.pathname)) {
|
|
403
|
+
return notFoundResponse()
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const htmlFile = Bun.file(`${resolvedPath}.html`)
|
|
407
|
+
if (await htmlFile.exists()) {
|
|
408
|
+
return fileResponse(req, htmlFile)
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
const nestedIndexFile = Bun.file(join(resolvedPath, "index.html"))
|
|
412
|
+
if (await nestedIndexFile.exists()) {
|
|
413
|
+
return fileResponse(req, nestedIndexFile)
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
return htmlResponse(req, indexHtml)
|
|
417
|
+
},
|
|
418
|
+
})
|
|
419
|
+
|
|
420
|
+
const displayHost = host === "0.0.0.0" ? "localhost" : host
|
|
421
|
+
|
|
422
|
+
return {
|
|
423
|
+
host,
|
|
424
|
+
port,
|
|
425
|
+
url: `http://${displayHost}:${port}`,
|
|
426
|
+
async stop() {
|
|
427
|
+
server.stop(true)
|
|
428
|
+
},
|
|
429
|
+
}
|
|
430
|
+
},
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
async function pathExists(path: string): Promise<boolean> {
|
|
435
|
+
try {
|
|
436
|
+
await access(path)
|
|
437
|
+
return true
|
|
438
|
+
} catch {
|
|
439
|
+
return false
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function builtInAgentRoutesFor(routes: readonly PageRoute[]): BuiltInRouteManifestEntry[] {
|
|
444
|
+
const projectRoutePaths = new Set(routes.map((route) => route.path))
|
|
445
|
+
|
|
446
|
+
return builtInAgentRoutePaths
|
|
447
|
+
.filter((path) => !projectRoutePaths.has(path))
|
|
448
|
+
.map((path) => ({
|
|
449
|
+
path,
|
|
450
|
+
moduleSpecifier: builtInAgentRouteModule,
|
|
451
|
+
}))
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
async function writeFileIfChanged(path: string, content: string): Promise<void> {
|
|
455
|
+
try {
|
|
456
|
+
if ((await readFile(path, "utf-8")) === content) {
|
|
457
|
+
return
|
|
458
|
+
}
|
|
459
|
+
} catch (error) {
|
|
460
|
+
if (!isFileNotFoundError(error)) {
|
|
461
|
+
throw error
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
await mkdir(dirname(path), { recursive: true })
|
|
466
|
+
await writeFile(path, content, "utf-8")
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function isFileNotFoundError(error: unknown): boolean {
|
|
470
|
+
return (
|
|
471
|
+
error instanceof Error &&
|
|
472
|
+
"code" in error &&
|
|
473
|
+
(error as Error & { readonly code?: unknown }).code === "ENOENT"
|
|
474
|
+
)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
async function createPublicRoutes(publicDir: string): Promise<BunServeRoutes> {
|
|
478
|
+
const files = new Bun.Glob("**/*").scan({
|
|
479
|
+
cwd: publicDir,
|
|
480
|
+
absolute: true,
|
|
481
|
+
onlyFiles: true,
|
|
482
|
+
})
|
|
483
|
+
const routes: BunServeRoutes = {}
|
|
484
|
+
|
|
485
|
+
for await (const filePath of files) {
|
|
486
|
+
const routePath = `/${filePath
|
|
487
|
+
.slice(publicDir.length + 1)
|
|
488
|
+
.split("\\")
|
|
489
|
+
.join("/")}`
|
|
490
|
+
if (isReservedSixbRoute(routePath) || routePath === customAppManifestRoute) {
|
|
491
|
+
continue
|
|
492
|
+
}
|
|
493
|
+
routes[routePath] = getHeadRoute((request) => filePathResponse(request, filePath))
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
return routes
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function reservedSixbRoutes(): BunServeRoutes {
|
|
500
|
+
const handler = () => notFoundResponse()
|
|
501
|
+
return {
|
|
502
|
+
"/api": allMethodsRoute(handler),
|
|
503
|
+
"/api/*": allMethodsRoute(handler),
|
|
504
|
+
"/auth": allMethodsRoute(handler),
|
|
505
|
+
"/auth/*": allMethodsRoute(handler),
|
|
506
|
+
"/ws": allMethodsRoute(handler),
|
|
507
|
+
"/ws/*": allMethodsRoute(handler),
|
|
508
|
+
"/docs": allMethodsRoute(handler),
|
|
509
|
+
"/docs/*": allMethodsRoute(handler),
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function isReservedSixbRoute(pathname: string): boolean {
|
|
514
|
+
return (
|
|
515
|
+
pathname === "/api" ||
|
|
516
|
+
pathname.startsWith("/api/") ||
|
|
517
|
+
pathname === "/auth" ||
|
|
518
|
+
pathname.startsWith("/auth/") ||
|
|
519
|
+
pathname === "/ws" ||
|
|
520
|
+
pathname.startsWith("/ws/") ||
|
|
521
|
+
pathname === "/docs" ||
|
|
522
|
+
pathname.startsWith("/docs/")
|
|
523
|
+
)
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// Static-asset extensions whose absence should 404 rather than fall back to the
|
|
527
|
+
// SPA shell — otherwise the browser would receive HTML for a missing
|
|
528
|
+
// script/style/image and fail with a confusing content-type error.
|
|
529
|
+
const ASSET_EXTENSIONS = new Set([
|
|
530
|
+
"js",
|
|
531
|
+
"mjs",
|
|
532
|
+
"cjs",
|
|
533
|
+
"css",
|
|
534
|
+
"map",
|
|
535
|
+
"json",
|
|
536
|
+
"wasm",
|
|
537
|
+
"ico",
|
|
538
|
+
"png",
|
|
539
|
+
"jpg",
|
|
540
|
+
"jpeg",
|
|
541
|
+
"gif",
|
|
542
|
+
"svg",
|
|
543
|
+
"webp",
|
|
544
|
+
"avif",
|
|
545
|
+
"bmp",
|
|
546
|
+
"woff",
|
|
547
|
+
"woff2",
|
|
548
|
+
"ttf",
|
|
549
|
+
"otf",
|
|
550
|
+
"eot",
|
|
551
|
+
"mp4",
|
|
552
|
+
"webm",
|
|
553
|
+
"ogg",
|
|
554
|
+
"mp3",
|
|
555
|
+
"wav",
|
|
556
|
+
"txt",
|
|
557
|
+
"xml",
|
|
558
|
+
"webmanifest",
|
|
559
|
+
"pdf",
|
|
560
|
+
])
|
|
561
|
+
|
|
562
|
+
function isAssetRequest(pathname: string): boolean {
|
|
563
|
+
// Decode first: client routes can carry percent-encoded slashes (`%2F`) inside a
|
|
564
|
+
// single path segment (e.g. an object id), so the raw pathname's "last segment"
|
|
565
|
+
// is unreliable. Falling back to the SPA shell for these is the whole point.
|
|
566
|
+
let decoded = pathname
|
|
567
|
+
try {
|
|
568
|
+
decoded = decodeURIComponent(pathname)
|
|
569
|
+
} catch {
|
|
570
|
+
// Keep the raw pathname when it isn't valid percent-encoding.
|
|
571
|
+
}
|
|
572
|
+
const lastSegment = decoded.split(/[\\/]+/).pop() ?? ""
|
|
573
|
+
const dot = lastSegment.lastIndexOf(".")
|
|
574
|
+
// No extension, a leading-dot file, or a trailing dot → not an asset request.
|
|
575
|
+
if (dot <= 0 || dot === lastSegment.length - 1) return false
|
|
576
|
+
return ASSET_EXTENSIONS.has(lastSegment.slice(dot + 1).toLowerCase())
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function resolveStaticPath(appRoot: string, pathname: string): string | null {
|
|
580
|
+
let decodedPath: string
|
|
581
|
+
try {
|
|
582
|
+
decodedPath = decodeURIComponent(pathname)
|
|
583
|
+
} catch {
|
|
584
|
+
return null
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
if (decodedPath.includes("\0")) return null
|
|
588
|
+
const segments = decodedPath.split(/[\\/]+/)
|
|
589
|
+
if (segments.includes("..")) return null
|
|
590
|
+
|
|
591
|
+
const normalizedPath = normalize(decodedPath).replace(/^[\\/]+/, "")
|
|
592
|
+
const resolvedPath = resolve(appRoot, normalizedPath)
|
|
593
|
+
const rel = relative(appRoot, resolvedPath)
|
|
594
|
+
|
|
595
|
+
if (rel.startsWith("..") || isAbsolute(rel)) return null
|
|
596
|
+
return resolvedPath
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
function injectRuntimeConfig(
|
|
600
|
+
html: string,
|
|
601
|
+
config: {
|
|
602
|
+
readonly apiBaseUrl?: string
|
|
603
|
+
readonly audience: AuthSessionAudience
|
|
604
|
+
readonly authEnabled: boolean
|
|
605
|
+
}
|
|
606
|
+
): string {
|
|
607
|
+
if (!config.apiBaseUrl) {
|
|
608
|
+
return html
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const script = renderCustomAppRuntimeScript({
|
|
612
|
+
api: { baseUrl: config.apiBaseUrl },
|
|
613
|
+
auth: { audience: config.audience, enabled: config.authEnabled },
|
|
614
|
+
})
|
|
615
|
+
const existingRuntimeScript = /<script>window\.__SIXB_RUNTIME__ = .*?;<\/script>/
|
|
616
|
+
if (existingRuntimeScript.test(html)) {
|
|
617
|
+
return html.replace(existingRuntimeScript, script)
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
if (html.includes("</head>")) {
|
|
621
|
+
return html.replace("</head>", ` ${script}\n </head>`)
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
return `${script}\n${html}`
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
function htmlResponse(request: Request, html: string): Response {
|
|
628
|
+
return new Response(request.method === "HEAD" ? null : html, {
|
|
629
|
+
headers: {
|
|
630
|
+
"content-type": "text/html; charset=utf-8",
|
|
631
|
+
"cache-control": "no-store",
|
|
632
|
+
},
|
|
633
|
+
})
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// Bun.build emits content-hashed bundles named `chunk-<hash>.<ext>` (see buildApp).
|
|
637
|
+
// Their contents can never change under the same URL, so they are safe to cache
|
|
638
|
+
// forever — matching how Atlas serves its hashed assets. Files copied
|
|
639
|
+
// from `public/` keep their names across deploys and stay uncached.
|
|
640
|
+
const IMMUTABLE_ASSET_PATTERN = /^chunk-[a-z0-9]+\.(js|css|js\.map|css\.map)$/
|
|
641
|
+
|
|
642
|
+
function staticAssetHeaders(pathname: string): Record<string, string> {
|
|
643
|
+
if (pathname === customAppManifestRoute) {
|
|
644
|
+
return {
|
|
645
|
+
"content-type": "application/manifest+json; charset=utf-8",
|
|
646
|
+
"cache-control": "no-cache",
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const lastSegment = pathname.split("/").pop() ?? ""
|
|
651
|
+
if (!IMMUTABLE_ASSET_PATTERN.test(lastSegment)) {
|
|
652
|
+
return {}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
return { "cache-control": "public, max-age=31536000, immutable" }
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function fileResponse(
|
|
659
|
+
request: Request,
|
|
660
|
+
file: Bun.BunFile,
|
|
661
|
+
headers: Record<string, string> = {}
|
|
662
|
+
): Response {
|
|
663
|
+
return new Response(request.method === "HEAD" ? null : file, { headers })
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function filePathResponse(request: Request, path: string): Response {
|
|
667
|
+
return fileResponse(request, Bun.file(path))
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
function notFoundResponse(): Response {
|
|
671
|
+
return new Response("Not Found", {
|
|
672
|
+
status: 404,
|
|
673
|
+
headers: {
|
|
674
|
+
"cache-control": "no-store",
|
|
675
|
+
},
|
|
676
|
+
})
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
function getHeadRoute(handler: (request: Request) => Response | Promise<Response>): BunServeRoute {
|
|
680
|
+
return {
|
|
681
|
+
GET: handler,
|
|
682
|
+
HEAD: handler,
|
|
683
|
+
} as unknown as BunServeRoute
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function allMethodsRoute(handler: (request: Request) => Response): BunServeRoute {
|
|
687
|
+
return {
|
|
688
|
+
GET: handler,
|
|
689
|
+
HEAD: handler,
|
|
690
|
+
POST: handler,
|
|
691
|
+
PUT: handler,
|
|
692
|
+
PATCH: handler,
|
|
693
|
+
DELETE: handler,
|
|
694
|
+
OPTIONS: handler,
|
|
695
|
+
} as unknown as BunServeRoute
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
async function importHtmlBundle(htmlPath: string, version: number): Promise<Bun.HTMLBundle> {
|
|
699
|
+
const bundleEntryPath = await prepareAppHtmlBundleEntry(htmlPath)
|
|
700
|
+
const url = pathToFileURL(bundleEntryPath)
|
|
701
|
+
url.searchParams.set("v", String(version))
|
|
702
|
+
const htmlModule = (await import(url.href)) as { default: Bun.HTMLBundle }
|
|
703
|
+
return htmlModule.default
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function htmlBundleRoute(bundle: Bun.HTMLBundle): BunServeRoute {
|
|
707
|
+
return {
|
|
708
|
+
GET: bundle,
|
|
709
|
+
HEAD: bundle,
|
|
710
|
+
} as unknown as BunServeRoute
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
function manifestRoute(manifestPath: string): BunServeRoute {
|
|
714
|
+
return getHeadRoute((request) =>
|
|
715
|
+
fileResponse(request, Bun.file(manifestPath), staticAssetHeaders(customAppManifestRoute))
|
|
716
|
+
)
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
function devServerInternalOrigin(host: string, port: number): string {
|
|
720
|
+
if (host === "0.0.0.0") {
|
|
721
|
+
return `http://127.0.0.1:${port}`
|
|
722
|
+
}
|
|
723
|
+
if (host === "::" || host === "[::]") {
|
|
724
|
+
return `http://[::1]:${port}`
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host
|
|
728
|
+
return `http://${urlHost}:${port}`
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
function spaHtmlRoute(internalOrigin: () => string): BunServeRoute {
|
|
732
|
+
return getHeadRoute(async (request) => {
|
|
733
|
+
const publicUrl = new URL(request.url)
|
|
734
|
+
if (publicUrl.pathname !== "/" && isAssetRequest(publicUrl.pathname)) {
|
|
735
|
+
return notFoundResponse()
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
const url = new URL(internalAppShellRoute, internalOrigin())
|
|
739
|
+
url.search = publicUrl.search
|
|
740
|
+
const requestHeaders = new Headers(request.headers)
|
|
741
|
+
for (const header of [
|
|
742
|
+
"forwarded",
|
|
743
|
+
"host",
|
|
744
|
+
"x-forwarded-host",
|
|
745
|
+
"x-forwarded-port",
|
|
746
|
+
"x-forwarded-proto",
|
|
747
|
+
]) {
|
|
748
|
+
requestHeaders.delete(header)
|
|
749
|
+
}
|
|
750
|
+
const bundleResponse = await fetch(
|
|
751
|
+
new Request(url, { method: request.method, headers: requestHeaders })
|
|
752
|
+
)
|
|
753
|
+
const responseHeaders = new Headers(bundleResponse.headers)
|
|
754
|
+
responseHeaders.delete("content-length")
|
|
755
|
+
responseHeaders.delete("etag")
|
|
756
|
+
if (request.method === "HEAD") {
|
|
757
|
+
return new Response(null, {
|
|
758
|
+
status: bundleResponse.status,
|
|
759
|
+
statusText: bundleResponse.statusText,
|
|
760
|
+
headers: responseHeaders,
|
|
761
|
+
})
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
return new Response(restoreAppStaticUrls(await bundleResponse.text()), {
|
|
765
|
+
status: bundleResponse.status,
|
|
766
|
+
statusText: bundleResponse.statusText,
|
|
767
|
+
headers: responseHeaders,
|
|
768
|
+
})
|
|
769
|
+
})
|
|
770
|
+
}
|