@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/dist/index.js ADDED
@@ -0,0 +1,1464 @@
1
+ // @bun
2
+ // src/createCustomApp.ts
3
+ import { watch } from "fs";
4
+ import { access as access2, cp, mkdir as mkdir4, readFile as readFile5, writeFile as writeFile3 } from "fs/promises";
5
+ import { dirname as dirname3, isAbsolute, join as join7, normalize, relative as relative3, resolve as resolve2 } from "path";
6
+ import { pathToFileURL as pathToFileURL2 } from "url";
7
+
8
+ // src/build.ts
9
+ import { copyFile, mkdir, readFile, rename, rm, writeFile } from "fs/promises";
10
+ import { basename, dirname, join } from "path";
11
+ var STATIC_ASSET_ORIGIN = "https://sixb-static.invalid";
12
+ async function buildApp(options) {
13
+ const outdir = options.outdir ?? join(process.cwd(), ".sixb", "dist", "app");
14
+ await rm(outdir, { recursive: true, force: true });
15
+ await mkdir(outdir, { recursive: true });
16
+ const bundleEntryPath = await prepareAppHtmlBundleEntry(options.entryPath);
17
+ let result;
18
+ try {
19
+ result = await Bun.build({
20
+ entrypoints: [bundleEntryPath],
21
+ outdir,
22
+ target: "browser",
23
+ conditions: ["bun"],
24
+ publicPath: "/",
25
+ minify: true,
26
+ define: { "process.env.NODE_ENV": '"production"' },
27
+ sourcemap: "external"
28
+ });
29
+ } finally {
30
+ await rm(bundleEntryPath, { force: true });
31
+ }
32
+ if (!result.success) {
33
+ return {
34
+ success: false,
35
+ outdir,
36
+ logs: result.logs.map(String)
37
+ };
38
+ }
39
+ const bundleHtmlPath = join(outdir, basename(bundleEntryPath));
40
+ await rename(bundleHtmlPath, join(outdir, "index.html"));
41
+ await rewriteIndexAssetPaths(outdir);
42
+ if (options.manifestPath) {
43
+ await copyFile(options.manifestPath, join(outdir, "app.webmanifest"));
44
+ }
45
+ return { success: true, outdir };
46
+ }
47
+ async function prepareAppHtmlBundleEntry(entryPath) {
48
+ const html = await readFile(entryPath, "utf-8");
49
+ const bundleHtml = html.replace(/(<link\s+rel=["'](?:manifest|icon|apple-touch-icon)["']\s+href=["'])(\/[^"']*)(["'][^>]*>)/g, `$1${STATIC_ASSET_ORIGIN}$2$3`);
50
+ const bundleEntryPath = join(dirname(entryPath), "index.sixb-bundle.html");
51
+ await writeFile(bundleEntryPath, bundleHtml, "utf-8");
52
+ return bundleEntryPath;
53
+ }
54
+ function restoreAppStaticUrls(html) {
55
+ return html.replaceAll(STATIC_ASSET_ORIGIN, "");
56
+ }
57
+ async function rewriteIndexAssetPaths(outdir) {
58
+ const indexPath = join(outdir, "index.html");
59
+ const originalHtml = await readFile(indexPath, "utf-8");
60
+ const html = restoreAppStaticUrls(originalHtml);
61
+ const rewritten = html.replace(/(href|src)=(["'])((?!\/|#|[a-zA-Z][a-zA-Z\d+.-]*:)(?:\.\/)?[^"'?#]+(?:[?#][^"']*)?)\2/g, (_match, attr, quote, url) => {
62
+ const normalized = url.startsWith("./") ? url.slice(2) : url;
63
+ return `${attr}=${quote}/${normalized}${quote}`;
64
+ });
65
+ if (rewritten !== originalHtml) {
66
+ await writeFile(indexPath, rewritten, "utf-8");
67
+ }
68
+ }
69
+
70
+ // src/codegen.ts
71
+ import { access, mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2 } from "fs/promises";
72
+ import { join as join3, relative, resolve } from "path";
73
+
74
+ // src/manifest.ts
75
+ function renderAppManifest(metadata) {
76
+ const manifest = {
77
+ id: "/",
78
+ name: metadata.title,
79
+ ...metadata.description ? { description: metadata.description } : {},
80
+ start_url: "/",
81
+ scope: "/",
82
+ display: "standalone",
83
+ theme_color: metadata.themeColor,
84
+ background_color: metadata.backgroundColor,
85
+ ...metadata.icons.length > 0 ? { icons: metadata.icons } : {}
86
+ };
87
+ return `${JSON.stringify(manifest, null, 2)}
88
+ `;
89
+ }
90
+
91
+ // src/metadata.ts
92
+ import { createHash } from "crypto";
93
+ import { readFile as readFile2, stat } from "fs/promises";
94
+ import { createRequire } from "module";
95
+ import { extname, join as join2 } from "path";
96
+ import { pathToFileURL } from "url";
97
+ var metadataRequire = createRequire(import.meta.url);
98
+ var metadataFields = [
99
+ "title",
100
+ "description",
101
+ "favicon",
102
+ "themeColor",
103
+ "backgroundColor"
104
+ ];
105
+ async function resolveAppMetadata(options) {
106
+ const configured = await loadConfiguredMetadata(options.layoutPath);
107
+ validateMetadata(configured, options.layoutPath);
108
+ const conventionalFaviconPath = join2(options.publicDir, "favicon.svg");
109
+ const favicon = configured.favicon ?? (await fileExists(conventionalFaviconPath) ? "/favicon.svg" : undefined);
110
+ const themeColor = configured.themeColor ?? configured.backgroundColor ?? "#ffffff";
111
+ const backgroundColor = configured.backgroundColor ?? themeColor;
112
+ const icons = [];
113
+ if (await fileExists(join2(options.publicDir, "icon-192.png"))) {
114
+ icons.push({
115
+ src: "/icon-192.png",
116
+ sizes: "192x192",
117
+ type: "image/png",
118
+ purpose: "any"
119
+ });
120
+ }
121
+ if (await fileExists(join2(options.publicDir, "icon-512.png"))) {
122
+ icons.push({
123
+ src: "/icon-512.png",
124
+ sizes: "512x512",
125
+ type: "image/png",
126
+ purpose: "any"
127
+ });
128
+ }
129
+ if (await fileExists(join2(options.publicDir, "icon-maskable-512.png"))) {
130
+ icons.push({
131
+ src: "/icon-maskable-512.png",
132
+ sizes: "512x512",
133
+ type: "image/png",
134
+ purpose: "maskable"
135
+ });
136
+ }
137
+ const hasStandardIcon = icons.some((icon) => icon.purpose === "any");
138
+ if (!hasStandardIcon && favicon) {
139
+ const type = inferImageMimeType(favicon);
140
+ if (type) {
141
+ icons.push({
142
+ src: favicon,
143
+ ...type === "image/svg+xml" ? { sizes: "any" } : {},
144
+ type,
145
+ purpose: "any"
146
+ });
147
+ }
148
+ }
149
+ return {
150
+ title: configured.title ?? "Sixb",
151
+ ...configured.description ? { description: configured.description } : {},
152
+ ...favicon ? { favicon } : {},
153
+ themeColor,
154
+ backgroundColor,
155
+ ...await fileExists(join2(options.publicDir, "apple-touch-icon.png")) ? { appleTouchIcon: "/apple-touch-icon.png" } : {},
156
+ icons
157
+ };
158
+ }
159
+ async function loadConfiguredMetadata(layoutPath) {
160
+ if (!await fileExists(layoutPath)) {
161
+ return {};
162
+ }
163
+ try {
164
+ const sourceHash = createHash("sha256").update(await readFile2(layoutPath)).digest("hex");
165
+ const url = pathToFileURL(layoutPath);
166
+ delete metadataRequire.cache[metadataRequire.resolve(layoutPath)];
167
+ url.searchParams.set("sixb-metadata", sourceHash);
168
+ const layoutModule = await import(url.href);
169
+ if (layoutModule.metadata === undefined) {
170
+ return {};
171
+ }
172
+ if (typeof layoutModule.metadata !== "object" || layoutModule.metadata === null || Array.isArray(layoutModule.metadata)) {
173
+ throw metadataError(layoutPath, "the named metadata export must be an object");
174
+ }
175
+ return layoutModule.metadata;
176
+ } catch (error) {
177
+ if (error instanceof Error && error.message.startsWith("[SixbCustomApp]")) {
178
+ throw error;
179
+ }
180
+ const detail = error instanceof Error ? error.message : String(error);
181
+ throw new Error(`[SixbCustomApp] Could not load metadata from ${layoutPath}: ${detail}. App metadata is build-time configuration, so app/layout.tsx must be import-safe in Bun and must not access window or document at module scope.`);
182
+ }
183
+ }
184
+ function validateMetadata(metadata, layoutPath) {
185
+ for (const field of metadataFields) {
186
+ const value = metadata[field];
187
+ if (value !== undefined && (typeof value !== "string" || value.trim().length === 0)) {
188
+ throw metadataError(layoutPath, `metadata.${field} must be a non-empty string when provided`);
189
+ }
190
+ }
191
+ }
192
+ function metadataError(layoutPath, detail) {
193
+ return new Error(`[SixbCustomApp] Invalid app metadata in ${layoutPath}: ${detail}`);
194
+ }
195
+ function inferImageMimeType(url) {
196
+ if (url.startsWith("data:")) {
197
+ const match = /^data:(image\/[a-z0-9.+-]+)/i.exec(url);
198
+ return match?.[1]?.toLowerCase();
199
+ }
200
+ let pathname = url;
201
+ try {
202
+ pathname = new URL(url, "https://sixb.invalid").pathname;
203
+ } catch {}
204
+ switch (extname(pathname).toLowerCase()) {
205
+ case ".svg":
206
+ return "image/svg+xml";
207
+ case ".png":
208
+ return "image/png";
209
+ case ".ico":
210
+ return "image/x-icon";
211
+ case ".jpg":
212
+ case ".jpeg":
213
+ return "image/jpeg";
214
+ case ".webp":
215
+ return "image/webp";
216
+ case ".avif":
217
+ return "image/avif";
218
+ default:
219
+ return;
220
+ }
221
+ }
222
+ async function fileExists(path) {
223
+ try {
224
+ return (await stat(path)).isFile();
225
+ } catch {
226
+ return false;
227
+ }
228
+ }
229
+
230
+ // src/runtime.ts
231
+ function renderCustomAppRuntimeScript(config) {
232
+ const safeConfig = JSON.stringify(config).replaceAll("<", "\\u003c");
233
+ return `<script>window.__SIXB_RUNTIME__ = ${safeConfig};</script>`;
234
+ }
235
+
236
+ // src/codegen.ts
237
+ async function generateRouteManifest(routes, generatedDir, options = {}) {
238
+ await mkdir2(generatedDir, { recursive: true });
239
+ const imports = routes.map((route, index) => {
240
+ const rel = relativeTo(generatedDir, route.filePath);
241
+ return `import Page${index} from ${JSON.stringify(rel)}`;
242
+ }).join(`
243
+ `);
244
+ const builtInRoutes = options.builtInRoutes ?? [];
245
+ const builtInImports = builtInRoutes.map((route, index) => {
246
+ if (route.exportName) {
247
+ return `import { ${route.exportName} as BuiltInPage${index} } from ${JSON.stringify(route.moduleSpecifier)}`;
248
+ }
249
+ return `import BuiltInPage${index} from ${JSON.stringify(route.moduleSpecifier)}`;
250
+ }).join(`
251
+ `);
252
+ const entries = routes.map((route, index) => ` { path: ${JSON.stringify(route.path)}, component: Page${index} },`).join(`
253
+ `);
254
+ const builtInEntries = builtInRoutes.map((route, index) => ` { path: ${JSON.stringify(route.path)}, component: BuiltInPage${index} },`).join(`
255
+ `);
256
+ const routeEntries = [entries, builtInEntries].filter(Boolean).join(`
257
+ `);
258
+ const importEntries = [imports, builtInImports].filter(Boolean).join(`
259
+ `);
260
+ const content = `${importEntries}
261
+
262
+ export const routes = [
263
+ ${routeEntries}
264
+ ]
265
+ `;
266
+ const outPath = join3(generatedDir, "routes.ts");
267
+ await writeFileIfChanged(outPath, content);
268
+ return outPath;
269
+ }
270
+ async function generateAppEntry(projectRoot, generatedDir, options = {}) {
271
+ await mkdir2(generatedDir, { recursive: true });
272
+ const appDir = options.appDir ? resolve(projectRoot, options.appDir) : join3(projectRoot, "app");
273
+ const publicDir = options.publicDir ? resolve(projectRoot, options.publicDir) : join3(appDir, "public");
274
+ const globalsCssPath = join3(appDir, "globals.css");
275
+ const layoutPath = join3(appDir, "layout.tsx");
276
+ const metadata = await resolveAppMetadata({ layoutPath, publicDir });
277
+ const manifestPath = join3(generatedDir, "app.webmanifest");
278
+ await writeFileIfChanged(manifestPath, renderAppManifest(metadata));
279
+ const layoutRel = relativeTo(generatedDir, layoutPath);
280
+ const hasLayout = await fileExists2(layoutPath);
281
+ const stylesheetPath = options.stylesheetPath !== undefined ? options.stylesheetPath : await fileExists2(globalsCssPath) ? globalsCssPath : null;
282
+ const stylesheetPaths = [
283
+ ...options.frameworkStylesheetPaths ?? [],
284
+ ...stylesheetPath ? [stylesheetPath] : []
285
+ ];
286
+ const globalsCssImport = stylesheetPaths.map((path) => `import ${JSON.stringify(relativeTo(generatedDir, path))}`).join(`
287
+ `);
288
+ const layoutImport = hasLayout ? `import RootLayout from ${JSON.stringify(layoutRel)}
289
+ ` : "";
290
+ const layoutWrapperStart = hasLayout ? "<RootLayout>" : "<>";
291
+ const layoutWrapperEnd = hasLayout ? "</RootLayout>" : "</>";
292
+ const runtimeConfigScript = options.apiBaseUrl ? renderCustomAppRuntimeScript({
293
+ api: { baseUrl: options.apiBaseUrl },
294
+ auth: { audience: options.audience ?? "app", enabled: options.authEnabled ?? true }
295
+ }) : "";
296
+ const mainContent = `import React from "react"
297
+ import { createRoot, type Root } from "react-dom/client"
298
+ import { signOut } from "@sixb/client"
299
+ import { BrowserRouter, Routes, Route, matchPath, useNavigate, useLocation } from "react-router-dom"
300
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
301
+ import {
302
+ configureSixbBrowserClient,
303
+ isSixbApiError,
304
+ readSixbBrowserRuntimeConfig,
305
+ requireSixbBrowserAuthSession,
306
+ } from "@sixb/client/browser"
307
+ import { routes } from "./routes"
308
+ ${globalsCssImport}
309
+ ${layoutImport}
310
+
311
+ interface CustomAppHotData {
312
+ root?: Root
313
+ queryClient?: QueryClient
314
+ }
315
+
316
+ const runtimeConfig = readSixbBrowserRuntimeConfig({ audience: "app" })
317
+ const browserClient = configureSixbBrowserClient(runtimeConfig)
318
+
319
+ if (import.meta.hot) {
320
+ import.meta.hot.accept()
321
+ import.meta.hot.dispose(() => {
322
+ browserClient.dispose()
323
+ })
324
+ }
325
+
326
+ const authSession = runtimeConfig.auth.enabled
327
+ ? await requireSixbBrowserAuthSession(runtimeConfig, browserClient)
328
+ : null
329
+ const applicationAccessDenied =
330
+ authSession?.authenticated === true && !authSession.applicationAccess.allowed
331
+ const canRenderApp =
332
+ !runtimeConfig.auth.enabled ||
333
+ (authSession?.authenticated === true && authSession.applicationAccess.allowed)
334
+
335
+ const queryClient = getQueryClient()
336
+
337
+ function getRoot(): Root {
338
+ const element = document.getElementById("root")
339
+ if (!element) {
340
+ throw new Error("[SixbApp] Could not find the root element.")
341
+ }
342
+
343
+ if (import.meta.hot) {
344
+ const data = import.meta.hot.data as CustomAppHotData
345
+ data.root ??= createRoot(element)
346
+ return data.root
347
+ }
348
+
349
+ return createRoot(element)
350
+ }
351
+
352
+ function getQueryClient(): QueryClient {
353
+ if (import.meta.hot) {
354
+ const data = import.meta.hot.data as CustomAppHotData
355
+ data.queryClient ??= createQueryClient()
356
+ return data.queryClient
357
+ }
358
+
359
+ return createQueryClient()
360
+ }
361
+
362
+ function createQueryClient(): QueryClient {
363
+ return new QueryClient({
364
+ defaultOptions: {
365
+ queries: {
366
+ refetchOnWindowFocus: false,
367
+ retry: 1,
368
+ },
369
+ },
370
+ })
371
+ }
372
+
373
+ const RESERVED_PATH_PREFIXES = ["/api", "/auth", "/ws", "/docs"]
374
+
375
+ function isReservedPath(pathname: string) {
376
+ return RESERVED_PATH_PREFIXES.some(
377
+ (prefix) => pathname === prefix || pathname.startsWith(prefix + "/")
378
+ )
379
+ }
380
+
381
+ // Makes plain same-origin <a href="/..."> clicks navigate client-side, so app
382
+ // authors get SPA navigation without remembering react-router's <Link>.
383
+ // Deliberately conservative: anything unusual falls through to the browser.
384
+ function InternalLinkInterceptor() {
385
+ const navigate = useNavigate()
386
+
387
+ React.useEffect(() => {
388
+ function onClick(event: MouseEvent) {
389
+ if (event.defaultPrevented) return
390
+ if (event.button !== 0) return
391
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
392
+
393
+ const target = event.target
394
+ if (!(target instanceof Element)) return
395
+ const anchor = target.closest("a")
396
+ if (!(anchor instanceof HTMLAnchorElement)) return
397
+ if (anchor.target && anchor.target !== "_self") return
398
+ if (anchor.hasAttribute("download")) return
399
+ if (anchor.relList.contains("external")) return
400
+ if (!anchor.getAttribute("href")) return
401
+
402
+ const url = new URL(anchor.href, window.location.href)
403
+ if (url.origin !== window.location.origin) return
404
+ if (isReservedPath(url.pathname)) return
405
+ // Only intercept destinations the app actually routes; anything else may
406
+ // be a real server resource and keeps native navigation.
407
+ if (!routes.some((route) => matchPath(route.path, url.pathname))) return
408
+ // Same-document hash links keep native scroll behavior.
409
+ if (
410
+ url.hash &&
411
+ url.pathname === window.location.pathname &&
412
+ url.search === window.location.search
413
+ ) {
414
+ return
415
+ }
416
+
417
+ event.preventDefault()
418
+ navigate(url.pathname + url.search + url.hash)
419
+ }
420
+
421
+ document.addEventListener("click", onClick)
422
+ return () => document.removeEventListener("click", onClick)
423
+ }, [navigate])
424
+
425
+ return null
426
+ }
427
+
428
+ // Shared presentational fallback used by the not-found view and the error
429
+ // boundary. Styled with @sixb/ui design tokens (var(--token)) so it adopts the
430
+ // app's theme when those tokens are loaded, but every token has a hardcoded
431
+ // fallback so it stays self-contained and readable when they are not. The
432
+ // background/foreground pair is always set together so text stays legible
433
+ // regardless of the surrounding app's background.
434
+ function AppFallback({
435
+ title,
436
+ detail,
437
+ showReload = true,
438
+ action,
439
+ }: {
440
+ title: string
441
+ detail: string
442
+ showReload?: boolean
443
+ action?: React.ReactNode
444
+ }) {
445
+ return (
446
+ <div
447
+ role="alert"
448
+ style={{
449
+ minHeight: "100dvh",
450
+ display: "flex",
451
+ flexDirection: "column",
452
+ alignItems: "center",
453
+ justifyContent: "center",
454
+ gap: "1rem",
455
+ padding: "2rem",
456
+ textAlign: "center",
457
+ fontFamily:
458
+ "var(--font-sans, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif)",
459
+ background: "var(--background, #ffffff)",
460
+ color: "var(--foreground, #1f2933)",
461
+ }}
462
+ >
463
+ <h1 style={{ margin: 0, fontSize: "1.5rem", fontWeight: 600 }}>{title}</h1>
464
+ <p style={{ margin: 0, maxWidth: "32rem", color: "var(--muted-foreground, #52606d)" }}>
465
+ {detail}
466
+ </p>
467
+ <div style={{ display: "flex", gap: "0.75rem" }}>
468
+ {action ?? (
469
+ <>
470
+ <a
471
+ href="/"
472
+ style={{
473
+ padding: "0.5rem 1rem",
474
+ borderRadius: "var(--radius, 0.5rem)",
475
+ background: "var(--primary, #1f2933)",
476
+ color: "var(--primary-foreground, #ffffff)",
477
+ textDecoration: "none",
478
+ }}
479
+ >
480
+ Go home
481
+ </a>
482
+ {showReload ? (
483
+ <button
484
+ type="button"
485
+ onClick={() => window.location.reload()}
486
+ style={{
487
+ padding: "0.5rem 1rem",
488
+ borderRadius: "var(--radius, 0.5rem)",
489
+ border: "1px solid var(--border, #cbd2d9)",
490
+ background: "transparent",
491
+ color: "inherit",
492
+ cursor: "pointer",
493
+ }}
494
+ >
495
+ Reload
496
+ </button>
497
+ ) : null}
498
+ </>
499
+ )}
500
+ </div>
501
+ </div>
502
+ )
503
+ }
504
+
505
+ function AccessDeniedView() {
506
+ const [isSigningOut, setIsSigningOut] = React.useState(false)
507
+
508
+ async function handleSignOut() {
509
+ setIsSigningOut(true)
510
+ try {
511
+ await signOut({ throwOnError: true })
512
+ window.location.reload()
513
+ } catch {
514
+ setIsSigningOut(false)
515
+ }
516
+ }
517
+
518
+ return (
519
+ <AppFallback
520
+ title="Access required"
521
+ detail="Your account is signed in, but it does not have permission to access this app."
522
+ showReload={false}
523
+ action={
524
+ <button
525
+ type="button"
526
+ disabled={isSigningOut}
527
+ onClick={handleSignOut}
528
+ style={{
529
+ padding: "0.5rem 1rem",
530
+ borderRadius: "var(--radius, 0.5rem)",
531
+ border: "1px solid var(--border, #cbd2d9)",
532
+ background: "transparent",
533
+ color: "inherit",
534
+ cursor: isSigningOut ? "default" : "pointer",
535
+ }}
536
+ >
537
+ {isSigningOut ? "Signing out\u2026" : "Sign out"}
538
+ </button>
539
+ }
540
+ />
541
+ )
542
+ }
543
+
544
+ // The not-found view. Rendered both for unmatched client routes (the catch-all
545
+ // route below) and for an expected 404 surfaced through a query. Apps will be
546
+ // able to override this via app/not-found.tsx.
547
+ function NotFoundView() {
548
+ return (
549
+ <AppFallback
550
+ title="Not found"
551
+ detail="The page or resource you requested does not exist."
552
+ showReload={false}
553
+ />
554
+ )
555
+ }
556
+
557
+ // Last-resort safety net so an uncaught render throw (a 404 surfaced through a
558
+ // suspense/throwOnError query, a bug, a failed import) shows a fallback instead
559
+ // of a blank page and a console error. A missing object is an expected state,
560
+ // so a 404 reuses the not-found view rather than the generic crash screen.
561
+ // Apps will be able to override this via app/error.tsx.
562
+ function AppErrorFallback({ error }: { error: unknown }) {
563
+ if (isSixbApiError(error) && error.status === 404) {
564
+ return <NotFoundView />
565
+ }
566
+ return (
567
+ <AppFallback
568
+ title="Something went wrong"
569
+ detail={error instanceof Error ? error.message : String(error)}
570
+ />
571
+ )
572
+ }
573
+
574
+ class AppErrorBoundary extends React.Component<
575
+ { resetKey: string; children: React.ReactNode },
576
+ { error: unknown }
577
+ > {
578
+ state: { error: unknown } = { error: null }
579
+
580
+ static getDerivedStateFromError(error: unknown) {
581
+ return { error }
582
+ }
583
+
584
+ componentDidCatch(error: unknown) {
585
+ console.error("[SixbApp] Uncaught render error:", error)
586
+ }
587
+
588
+ // Clear the error when the route changes so navigating away (or an in-app
589
+ // link) recovers without a full reload.
590
+ componentDidUpdate(prevProps: { resetKey: string }) {
591
+ if (this.state.error !== null && prevProps.resetKey !== this.props.resetKey) {
592
+ this.setState({ error: null })
593
+ }
594
+ }
595
+
596
+ render() {
597
+ if (this.state.error !== null) {
598
+ return <AppErrorFallback error={this.state.error} />
599
+ }
600
+ return this.props.children
601
+ }
602
+ }
603
+
604
+ function RoutedErrorBoundary({ children }: { children: React.ReactNode }) {
605
+ const location = useLocation()
606
+ return (
607
+ <AppErrorBoundary resetKey={location.pathname + location.search}>{children}</AppErrorBoundary>
608
+ )
609
+ }
610
+
611
+ function App() {
612
+ return (
613
+ <QueryClientProvider client={queryClient}>
614
+ <BrowserRouter>
615
+ <InternalLinkInterceptor />
616
+ <RoutedErrorBoundary>
617
+ ${layoutWrapperStart}
618
+ <Routes>
619
+ {routes.map((route) => (
620
+ <Route key={route.path} path={route.path} element={<route.component />} />
621
+ ))}
622
+ <Route path="*" element={<NotFoundView />} />
623
+ </Routes>
624
+ ${layoutWrapperEnd}
625
+ </RoutedErrorBoundary>
626
+ </BrowserRouter>
627
+ </QueryClientProvider>
628
+ )
629
+ }
630
+
631
+ if (canRenderApp) {
632
+ getRoot().render(<App />)
633
+ } else if (applicationAccessDenied) {
634
+ getRoot().render(<AccessDeniedView />)
635
+ }
636
+ `;
637
+ const mainPath = join3(generatedDir, "main.tsx");
638
+ await writeFileIfChanged(mainPath, mainContent);
639
+ const metadataHead = renderMetadataHead(metadata);
640
+ const htmlContent = `<!DOCTYPE html>
641
+ <html lang="en">
642
+ <head>
643
+ <meta charset="UTF-8" />
644
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
645
+ ${metadataHead}
646
+ ${runtimeConfigScript}
647
+ <style>
648
+ * {
649
+ box-sizing: border-box;
650
+ }
651
+ html,
652
+ body,
653
+ #root {
654
+ margin: 0;
655
+ min-height: 100%;
656
+ }
657
+ body,
658
+ #root {
659
+ min-height: 100vh;
660
+ min-height: 100dvh;
661
+ }
662
+ @media (display-mode: standalone) {
663
+ html,
664
+ body {
665
+ overscroll-behavior: none;
666
+ }
667
+ }
668
+ </style>
669
+ </head>
670
+ <body>
671
+ <div id="root"></div>
672
+ <script type="module" src="./main.tsx"></script>
673
+ </body>
674
+ </html>
675
+ `;
676
+ const htmlPath = join3(generatedDir, "index.html");
677
+ await writeFileIfChanged(htmlPath, htmlContent);
678
+ return { htmlPath, mainPath, manifestPath };
679
+ }
680
+ function renderMetadataHead(metadata) {
681
+ const tags = [
682
+ ` <title>${escapeHtmlText(metadata.title)}</title>`,
683
+ ...metadata.description ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`] : [],
684
+ ` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`,
685
+ ' <link rel="manifest" href="/app.webmanifest" />',
686
+ ...metadata.favicon ? [` <link rel="icon" href="${escapeHtmlAttribute(metadata.favicon)}" />`] : [],
687
+ ...metadata.appleTouchIcon ? [` <link rel="apple-touch-icon" href="${metadata.appleTouchIcon}" />`] : []
688
+ ];
689
+ return tags.join(`
690
+ `);
691
+ }
692
+ function escapeHtmlText(value) {
693
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
694
+ }
695
+ function escapeHtmlAttribute(value) {
696
+ return escapeHtmlText(value).replaceAll('"', "&quot;").replaceAll("'", "&#39;");
697
+ }
698
+ async function writeFileIfChanged(path, content) {
699
+ try {
700
+ if (await readFile3(path, "utf-8") === content) {
701
+ return;
702
+ }
703
+ } catch (error) {
704
+ if (!isFileNotFoundError(error)) {
705
+ throw error;
706
+ }
707
+ }
708
+ await writeFile2(path, content, "utf-8");
709
+ }
710
+ function isFileNotFoundError(error) {
711
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
712
+ }
713
+ function relativeTo(from, to) {
714
+ let rel = relative(from, to);
715
+ if (!rel.startsWith("."))
716
+ rel = `./${rel}`;
717
+ return rel;
718
+ }
719
+ async function fileExists2(path) {
720
+ try {
721
+ await access(path);
722
+ return true;
723
+ } catch {
724
+ return false;
725
+ }
726
+ }
727
+
728
+ // src/scanner.ts
729
+ import { readdir } from "fs/promises";
730
+ import { join as join4, relative as relative2 } from "path";
731
+ async function scanPages(appDir) {
732
+ const routes = [];
733
+ await walkDir(appDir, appDir, routes);
734
+ routes.sort((a, b) => a.path.localeCompare(b.path));
735
+ return routes;
736
+ }
737
+ async function walkDir(dir, appDir, routes) {
738
+ let entries;
739
+ try {
740
+ entries = await readdir(dir, { withFileTypes: true });
741
+ } catch {
742
+ return;
743
+ }
744
+ for (const entry of entries) {
745
+ const name = String(entry.name);
746
+ if (name.startsWith("_"))
747
+ continue;
748
+ const fullPath = join4(dir, name);
749
+ if (entry.isDirectory()) {
750
+ await walkDir(fullPath, appDir, routes);
751
+ continue;
752
+ }
753
+ if (!entry.isFile())
754
+ continue;
755
+ const isPageModule = name === "page.tsx" || name === "page.ts";
756
+ if (!isPageModule)
757
+ continue;
758
+ const relativePath = relative2(appDir, fullPath);
759
+ const routePath = filePathToRoutePath(relativePath);
760
+ routes.push({
761
+ path: routePath,
762
+ filePath: fullPath,
763
+ relativePath
764
+ });
765
+ }
766
+ }
767
+ function filePathToRoutePath(filePath) {
768
+ let route = filePath.replace(/\.(tsx|ts)$/, "");
769
+ route = route.split("\\").join("/");
770
+ route = route.replace(/\[([^\]]+)\]/g, ":$1");
771
+ if (route === "page")
772
+ return "/";
773
+ route = route.replace(/\/page$/, "");
774
+ if (!route.startsWith("/"))
775
+ route = `/${route}`;
776
+ return route;
777
+ }
778
+
779
+ // src/styles.ts
780
+ import { readFile as readFile4 } from "fs/promises";
781
+ import { join as join6 } from "path";
782
+
783
+ // src/tailwind.ts
784
+ import { mkdir as mkdir3 } from "fs/promises";
785
+ import { dirname as dirname2, join as join5 } from "path";
786
+ function resolveTailwindCliEntry(resolveFrom) {
787
+ try {
788
+ const packageJsonPath = Bun.resolveSync("@tailwindcss/cli/package.json", resolveFrom);
789
+ return join5(dirname2(packageJsonPath), "dist", "index.mjs");
790
+ } catch {
791
+ return null;
792
+ }
793
+ }
794
+ function createTailwindCssCompiler(options) {
795
+ const cwd = options.cwd ?? dirname2(options.inputPath);
796
+ const resolveFrom = options.resolveFrom ?? cwd;
797
+ const label = options.label ?? "[SixbTailwind]";
798
+ const debounceMs = options.debounceMs ?? 50;
799
+ const timeoutMs = options.timeoutMs ?? 60000;
800
+ const onError = options.onError ?? ((error) => console.error(`${label} ${error.message}`));
801
+ let chain = Promise.resolve();
802
+ let timer = null;
803
+ let stopped = false;
804
+ let activeProcess = null;
805
+ async function runCompile() {
806
+ if (stopped)
807
+ return;
808
+ const cliEntry = resolveTailwindCliEntry(resolveFrom);
809
+ if (!cliEntry) {
810
+ throw new Error(`${label} Tailwind CSS build requires '@tailwindcss/cli'. Install it with: bun add tailwindcss @tailwindcss/cli`);
811
+ }
812
+ await mkdir3(dirname2(options.outputPath), { recursive: true });
813
+ if (stopped)
814
+ return;
815
+ const args = [process.execPath, cliEntry, "-i", options.inputPath, "-o", options.outputPath];
816
+ if (options.minify) {
817
+ args.push("--minify");
818
+ }
819
+ const proc = Bun.spawn(args, {
820
+ cwd,
821
+ stdout: "ignore",
822
+ stderr: "pipe"
823
+ });
824
+ activeProcess = proc;
825
+ const stderr = new Response(proc.stderr).text().catch(() => "");
826
+ let timeout;
827
+ const timedOut = new Promise((resolve2) => {
828
+ timeout = setTimeout(() => resolve2("timeout"), timeoutMs);
829
+ });
830
+ try {
831
+ const outcome = await Promise.race([proc.exited, timedOut]);
832
+ if (stopped)
833
+ return;
834
+ if (outcome === "timeout") {
835
+ proc.kill("SIGKILL");
836
+ await proc.exited;
837
+ throw new Error(`${label} Tailwind CSS build did not finish within ${timeoutMs}ms and was killed. ` + `Check ${options.inputPath} and the sources Tailwind scans from ${cwd}.`);
838
+ }
839
+ if (outcome !== 0) {
840
+ throw new Error(`${label} Tailwind CSS build failed: ${(await stderr).trim()}`);
841
+ }
842
+ } finally {
843
+ clearTimeout(timeout);
844
+ activeProcess = null;
845
+ }
846
+ }
847
+ function compile() {
848
+ stopped = false;
849
+ const build = chain.then(() => runCompile());
850
+ chain = build.then(() => {}, () => {});
851
+ return build;
852
+ }
853
+ return {
854
+ compile,
855
+ schedule() {
856
+ if (stopped)
857
+ return;
858
+ if (timer) {
859
+ clearTimeout(timer);
860
+ }
861
+ timer = setTimeout(() => {
862
+ timer = null;
863
+ compile().catch((error) => {
864
+ onError(error instanceof Error ? error : new Error(String(error)));
865
+ });
866
+ }, debounceMs);
867
+ },
868
+ async stop() {
869
+ stopped = true;
870
+ if (timer) {
871
+ clearTimeout(timer);
872
+ timer = null;
873
+ }
874
+ activeProcess?.kill("SIGKILL");
875
+ await chain;
876
+ }
877
+ };
878
+ }
879
+
880
+ // src/styles.ts
881
+ async function resolveCustomAppStylesheet(input) {
882
+ const sourcePath = join6(input.appDir, "globals.css");
883
+ let css;
884
+ try {
885
+ css = await readFile4(sourcePath, "utf-8");
886
+ } catch {
887
+ return { kind: "none" };
888
+ }
889
+ if (!usesTailwind(css)) {
890
+ return { kind: "static", path: sourcePath };
891
+ }
892
+ if (!resolveTailwindCliEntry(input.rootDir)) {
893
+ throw new Error("[SixbCustomApp] app/globals.css uses Tailwind features but '@tailwindcss/cli' is not installed. Install it with: bun add tailwindcss @tailwindcss/cli");
894
+ }
895
+ return {
896
+ kind: "tailwind",
897
+ sourcePath,
898
+ outputPath: join6(input.generatedDir, "app.css")
899
+ };
900
+ }
901
+ var TAILWIND_AT_RULES = /@(?:tailwind|source|theme|plugin|config|utility|custom-variant|variant|apply)\b/;
902
+ function usesTailwind(css) {
903
+ const stripped = css.replace(/\/\*[\s\S]*?\*\//g, "");
904
+ if (TAILWIND_AT_RULES.test(stripped)) {
905
+ return true;
906
+ }
907
+ for (const match of stripped.matchAll(/@import\s+(?:url\(\s*)?["']([^"']+)["']/g)) {
908
+ const specifier = match[1];
909
+ if (!specifier.startsWith(".") && !specifier.startsWith("/") && !specifier.startsWith("#") && !/^(?:https?:|data:)/.test(specifier)) {
910
+ return true;
911
+ }
912
+ }
913
+ return false;
914
+ }
915
+
916
+ // src/createCustomApp.ts
917
+ var packageRoot = resolve2(import.meta.dir, "..");
918
+ var builtInAgentRouteModule = "@sixb/app/agents";
919
+ var builtInAgentRoutePaths = ["/agents", "/agents/new/:agentId", "/agents/:threadId"];
920
+ var builtInAgentRouteSourcePath = join7(packageRoot, "src", "agents.ts");
921
+ var customAppManifestRoute = "/app.webmanifest";
922
+ var internalAppShellRoute = "/__sixb/generated/app-shell";
923
+ async function createCustomApp(options) {
924
+ const rootDir = resolve2(options.rootDir);
925
+ const appDir = options.appDir ? resolve2(rootDir, options.appDir) : resolve2(rootDir, "app");
926
+ const generatedDir = resolve2(rootDir, options.generatedDir ?? join7(".sixb", "generated"));
927
+ const publicDir = options.publicDir ? resolve2(rootDir, options.publicDir) : resolve2(appDir, "public");
928
+ const apiBaseUrl = options.apiBaseUrl;
929
+ const audience = options.audience ?? "app";
930
+ const authEnabled = options.authEnabled ?? true;
931
+ const agentRoutesEnabled = options.agentRoutes ?? true;
932
+ async function scanRoutes() {
933
+ if (!await pathExists(appDir)) {
934
+ return [];
935
+ }
936
+ return await scanPages(appDir);
937
+ }
938
+ let tailwindCompiler = null;
939
+ let tailwindCompilerKey = null;
940
+ let builtInAgentCssCompiler = null;
941
+ async function prepareStylesheet(stylesheet) {
942
+ stylesheet ??= await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
943
+ if (stylesheet.kind !== "tailwind") {
944
+ return stylesheet;
945
+ }
946
+ await compileAppTailwindStylesheet(stylesheet.sourcePath, stylesheet.outputPath);
947
+ return stylesheet;
948
+ }
949
+ async function compileAppTailwindStylesheet(inputPath, outputPath) {
950
+ const key = `${inputPath}\x00${outputPath}`;
951
+ if (tailwindCompilerKey !== key) {
952
+ await tailwindCompiler?.stop();
953
+ tailwindCompiler = createTailwindCssCompiler({
954
+ inputPath,
955
+ outputPath,
956
+ cwd: appDir,
957
+ resolveFrom: rootDir,
958
+ label: "[SixbCustomApp]"
959
+ });
960
+ tailwindCompilerKey = key;
961
+ }
962
+ const compiler = tailwindCompiler;
963
+ if (!compiler) {
964
+ throw new Error("[SixbCustomApp] Tailwind CSS compiler was not initialized");
965
+ }
966
+ await compiler.compile();
967
+ }
968
+ async function prepareCombinedBuiltInAgentStylesheet(stylesheet) {
969
+ const inputPath = join7(generatedDir, "app.input.css");
970
+ const uiGlobalsPath = Bun.resolveSync("@sixb/ui/globals.css", packageRoot);
971
+ const agentUiGlobalsPath = Bun.resolveSync("@sixb/agent-ui/globals.css", packageRoot);
972
+ await writeFileIfChanged2(inputPath, [
973
+ `@import ${JSON.stringify(uiGlobalsPath)};`,
974
+ `@source ${JSON.stringify(builtInAgentRouteSourcePath)};`,
975
+ `@import ${JSON.stringify(stylesheet.sourcePath)};`,
976
+ `@import ${JSON.stringify(agentUiGlobalsPath)};`,
977
+ ""
978
+ ].join(`
979
+ `));
980
+ await compileAppTailwindStylesheet(inputPath, stylesheet.outputPath);
981
+ return stylesheet.outputPath;
982
+ }
983
+ async function prepareStylesheets(builtInRoutes) {
984
+ const stylesheet = await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir });
985
+ if (stylesheet.kind === "tailwind" && builtInRoutes.length > 0) {
986
+ return {
987
+ stylesheetPath: await prepareCombinedBuiltInAgentStylesheet(stylesheet),
988
+ frameworkStylesheetPaths: []
989
+ };
990
+ }
991
+ const preparedStylesheet = await prepareStylesheet(stylesheet);
992
+ const builtInAgentStylesheetPath = await prepareBuiltInAgentStylesheet(builtInRoutes);
993
+ return {
994
+ frameworkStylesheetPaths: builtInAgentStylesheetPath ? [builtInAgentStylesheetPath] : [],
995
+ stylesheetPath: preparedStylesheet.kind === "none" ? null : preparedStylesheet.kind === "static" ? preparedStylesheet.path : preparedStylesheet.outputPath
996
+ };
997
+ }
998
+ async function prepareBuiltInAgentStylesheet(builtInRoutes) {
999
+ if (builtInRoutes.length === 0) {
1000
+ return null;
1001
+ }
1002
+ const inputPath = join7(generatedDir, "agent-ui.input.css");
1003
+ const outputPath = join7(generatedDir, "agent-ui.css");
1004
+ const uiGlobalsPath = Bun.resolveSync("@sixb/ui/globals.css", packageRoot);
1005
+ const agentUiGlobalsPath = Bun.resolveSync("@sixb/agent-ui/globals.css", packageRoot);
1006
+ await writeFileIfChanged2(inputPath, [
1007
+ `@import ${JSON.stringify(uiGlobalsPath)};`,
1008
+ `@source ${JSON.stringify(builtInAgentRouteSourcePath)};`,
1009
+ `@import ${JSON.stringify(agentUiGlobalsPath)};`,
1010
+ ""
1011
+ ].join(`
1012
+ `));
1013
+ builtInAgentCssCompiler ??= createTailwindCssCompiler({
1014
+ inputPath,
1015
+ outputPath,
1016
+ cwd: packageRoot,
1017
+ resolveFrom: packageRoot,
1018
+ label: "[SixbCustomApp]"
1019
+ });
1020
+ await builtInAgentCssCompiler.compile();
1021
+ return outputPath;
1022
+ }
1023
+ async function prepareGeneratedApp() {
1024
+ const routes = await scanRoutes();
1025
+ if (routes.length === 0) {
1026
+ throw new Error(`[SixbCustomApp] No app routes found in ${appDir}`);
1027
+ }
1028
+ const builtInRoutes = agentRoutesEnabled ? builtInAgentRoutesFor(routes) : [];
1029
+ const stylesheets = await prepareStylesheets(builtInRoutes);
1030
+ await generateRouteManifest(routes, generatedDir, { builtInRoutes });
1031
+ const { htmlPath, manifestPath } = await generateAppEntry(rootDir, generatedDir, {
1032
+ apiBaseUrl,
1033
+ audience,
1034
+ authEnabled,
1035
+ appDir,
1036
+ publicDir,
1037
+ frameworkStylesheetPaths: stylesheets.frameworkStylesheetPaths,
1038
+ stylesheetPath: stylesheets.stylesheetPath
1039
+ });
1040
+ return { htmlPath, manifestPath, routes };
1041
+ }
1042
+ return {
1043
+ async scanRoutes() {
1044
+ return await scanRoutes();
1045
+ },
1046
+ async hasRoutes() {
1047
+ const routes = await scanRoutes();
1048
+ return routes.length > 0;
1049
+ },
1050
+ async dev(devOptions = {}) {
1051
+ const host = devOptions.host ?? "0.0.0.0";
1052
+ const port = devOptions.port ?? 3001;
1053
+ const { htmlPath, manifestPath } = await prepareGeneratedApp();
1054
+ let htmlImportVersion = 0;
1055
+ let htmlBundle = await importHtmlBundle(htmlPath, htmlImportVersion);
1056
+ const publicRoutes = await pathExists(publicDir) ? await createPublicRoutes(publicDir) : {};
1057
+ let internalOrigin = "";
1058
+ const serveOptions = (bundle) => ({
1059
+ port,
1060
+ hostname: host,
1061
+ development: true,
1062
+ routes: {
1063
+ ...publicRoutes,
1064
+ ...reservedSixbRoutes(),
1065
+ [customAppManifestRoute]: manifestRoute(manifestPath),
1066
+ [internalAppShellRoute]: htmlBundleRoute(bundle),
1067
+ "/": spaHtmlRoute(() => internalOrigin),
1068
+ "/*": spaHtmlRoute(() => internalOrigin)
1069
+ }
1070
+ });
1071
+ const server = Bun.serve(serveOptions(htmlBundle));
1072
+ internalOrigin = devServerInternalOrigin(host, server.port ?? port);
1073
+ let rebuildTimer = null;
1074
+ let rebuildChain = Promise.resolve();
1075
+ const enqueueRebuild = () => {
1076
+ rebuildChain = rebuildChain.then(async () => {
1077
+ const { htmlPath: nextHtmlPath } = await prepareGeneratedApp();
1078
+ htmlImportVersion++;
1079
+ htmlBundle = await importHtmlBundle(nextHtmlPath, htmlImportVersion);
1080
+ server.reload(serveOptions(htmlBundle));
1081
+ }).catch((error) => {
1082
+ const message = error instanceof Error ? error.message : String(error);
1083
+ console.error(`[SixbCustomApp] Rebuild failed: ${message}`);
1084
+ });
1085
+ };
1086
+ const watcher = watch(appDir, { recursive: true }, (_eventType, filename) => {
1087
+ if (!filename)
1088
+ return;
1089
+ if (!/\.(ts|tsx|css)$/.test(String(filename)))
1090
+ return;
1091
+ if (rebuildTimer) {
1092
+ clearTimeout(rebuildTimer);
1093
+ }
1094
+ rebuildTimer = setTimeout(() => {
1095
+ rebuildTimer = null;
1096
+ enqueueRebuild();
1097
+ }, 80);
1098
+ });
1099
+ watcher.on("error", (error) => {
1100
+ const message = error instanceof Error ? error.message : String(error);
1101
+ console.error(`[SixbCustomApp] Stopped watching ${appDir}: ${message}. ` + "Serving the last build; restart to resume hot reload.");
1102
+ });
1103
+ const displayHost = host === "0.0.0.0" ? "localhost" : host;
1104
+ return {
1105
+ host,
1106
+ port,
1107
+ url: `http://${displayHost}:${port}`,
1108
+ async stop() {
1109
+ if (rebuildTimer) {
1110
+ clearTimeout(rebuildTimer);
1111
+ rebuildTimer = null;
1112
+ }
1113
+ watcher.close();
1114
+ await rebuildChain;
1115
+ await tailwindCompiler?.stop();
1116
+ await builtInAgentCssCompiler?.stop();
1117
+ server.stop(true);
1118
+ }
1119
+ };
1120
+ },
1121
+ async build(buildOptions = {}) {
1122
+ const outdir = resolve2(rootDir, buildOptions.outdir ?? join7(".sixb", "dist", "app"));
1123
+ const { htmlPath, manifestPath } = await prepareGeneratedApp();
1124
+ const result = await buildApp({
1125
+ entryPath: htmlPath,
1126
+ manifestPath,
1127
+ outdir
1128
+ });
1129
+ if (result.success && await pathExists(publicDir)) {
1130
+ await cp(publicDir, outdir, {
1131
+ recursive: true,
1132
+ force: true,
1133
+ filter: (source) => resolve2(source) !== join7(publicDir, "app.webmanifest")
1134
+ });
1135
+ }
1136
+ return result;
1137
+ },
1138
+ async start(startOptions = {}) {
1139
+ const host = startOptions.host ?? "0.0.0.0";
1140
+ const port = startOptions.port ?? 3001;
1141
+ const outdir = resolve2(rootDir, startOptions.outdir ?? join7(".sixb", "dist", "app"));
1142
+ const indexPath = join7(outdir, "index.html");
1143
+ if (!await pathExists(indexPath)) {
1144
+ throw new Error(`[SixbCustomApp] No built app found in ${outdir}`);
1145
+ }
1146
+ const indexHtml = injectRuntimeConfig(await Bun.file(indexPath).text(), {
1147
+ apiBaseUrl: startOptions.apiBaseUrl ?? apiBaseUrl,
1148
+ audience: startOptions.audience ?? audience,
1149
+ authEnabled: startOptions.authEnabled ?? authEnabled
1150
+ });
1151
+ const server = Bun.serve({
1152
+ port,
1153
+ hostname: host,
1154
+ development: false,
1155
+ async fetch(req) {
1156
+ const url = new URL(req.url);
1157
+ if (isReservedSixbRoute(url.pathname)) {
1158
+ return notFoundResponse();
1159
+ }
1160
+ if (req.method !== "GET" && req.method !== "HEAD") {
1161
+ return notFoundResponse();
1162
+ }
1163
+ if (url.pathname === "/" || url.pathname === "") {
1164
+ return htmlResponse(req, indexHtml);
1165
+ }
1166
+ const resolvedPath = resolveStaticPath(outdir, url.pathname);
1167
+ if (!resolvedPath) {
1168
+ return notFoundResponse();
1169
+ }
1170
+ const directFile = Bun.file(resolvedPath);
1171
+ if (await directFile.exists()) {
1172
+ return fileResponse(req, directFile, staticAssetHeaders(url.pathname));
1173
+ }
1174
+ if (isAssetRequest(url.pathname)) {
1175
+ return notFoundResponse();
1176
+ }
1177
+ const htmlFile = Bun.file(`${resolvedPath}.html`);
1178
+ if (await htmlFile.exists()) {
1179
+ return fileResponse(req, htmlFile);
1180
+ }
1181
+ const nestedIndexFile = Bun.file(join7(resolvedPath, "index.html"));
1182
+ if (await nestedIndexFile.exists()) {
1183
+ return fileResponse(req, nestedIndexFile);
1184
+ }
1185
+ return htmlResponse(req, indexHtml);
1186
+ }
1187
+ });
1188
+ const displayHost = host === "0.0.0.0" ? "localhost" : host;
1189
+ return {
1190
+ host,
1191
+ port,
1192
+ url: `http://${displayHost}:${port}`,
1193
+ async stop() {
1194
+ server.stop(true);
1195
+ }
1196
+ };
1197
+ }
1198
+ };
1199
+ }
1200
+ async function pathExists(path) {
1201
+ try {
1202
+ await access2(path);
1203
+ return true;
1204
+ } catch {
1205
+ return false;
1206
+ }
1207
+ }
1208
+ function builtInAgentRoutesFor(routes) {
1209
+ const projectRoutePaths = new Set(routes.map((route) => route.path));
1210
+ return builtInAgentRoutePaths.filter((path) => !projectRoutePaths.has(path)).map((path) => ({
1211
+ path,
1212
+ moduleSpecifier: builtInAgentRouteModule
1213
+ }));
1214
+ }
1215
+ async function writeFileIfChanged2(path, content) {
1216
+ try {
1217
+ if (await readFile5(path, "utf-8") === content) {
1218
+ return;
1219
+ }
1220
+ } catch (error) {
1221
+ if (!isFileNotFoundError2(error)) {
1222
+ throw error;
1223
+ }
1224
+ }
1225
+ await mkdir4(dirname3(path), { recursive: true });
1226
+ await writeFile3(path, content, "utf-8");
1227
+ }
1228
+ function isFileNotFoundError2(error) {
1229
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
1230
+ }
1231
+ async function createPublicRoutes(publicDir) {
1232
+ const files = new Bun.Glob("**/*").scan({
1233
+ cwd: publicDir,
1234
+ absolute: true,
1235
+ onlyFiles: true
1236
+ });
1237
+ const routes = {};
1238
+ for await (const filePath of files) {
1239
+ const routePath = `/${filePath.slice(publicDir.length + 1).split("\\").join("/")}`;
1240
+ if (isReservedSixbRoute(routePath) || routePath === customAppManifestRoute) {
1241
+ continue;
1242
+ }
1243
+ routes[routePath] = getHeadRoute((request) => filePathResponse(request, filePath));
1244
+ }
1245
+ return routes;
1246
+ }
1247
+ function reservedSixbRoutes() {
1248
+ const handler = () => notFoundResponse();
1249
+ return {
1250
+ "/api": allMethodsRoute(handler),
1251
+ "/api/*": allMethodsRoute(handler),
1252
+ "/auth": allMethodsRoute(handler),
1253
+ "/auth/*": allMethodsRoute(handler),
1254
+ "/ws": allMethodsRoute(handler),
1255
+ "/ws/*": allMethodsRoute(handler),
1256
+ "/docs": allMethodsRoute(handler),
1257
+ "/docs/*": allMethodsRoute(handler)
1258
+ };
1259
+ }
1260
+ function isReservedSixbRoute(pathname) {
1261
+ return pathname === "/api" || pathname.startsWith("/api/") || pathname === "/auth" || pathname.startsWith("/auth/") || pathname === "/ws" || pathname.startsWith("/ws/") || pathname === "/docs" || pathname.startsWith("/docs/");
1262
+ }
1263
+ var ASSET_EXTENSIONS = new Set([
1264
+ "js",
1265
+ "mjs",
1266
+ "cjs",
1267
+ "css",
1268
+ "map",
1269
+ "json",
1270
+ "wasm",
1271
+ "ico",
1272
+ "png",
1273
+ "jpg",
1274
+ "jpeg",
1275
+ "gif",
1276
+ "svg",
1277
+ "webp",
1278
+ "avif",
1279
+ "bmp",
1280
+ "woff",
1281
+ "woff2",
1282
+ "ttf",
1283
+ "otf",
1284
+ "eot",
1285
+ "mp4",
1286
+ "webm",
1287
+ "ogg",
1288
+ "mp3",
1289
+ "wav",
1290
+ "txt",
1291
+ "xml",
1292
+ "webmanifest",
1293
+ "pdf"
1294
+ ]);
1295
+ function isAssetRequest(pathname) {
1296
+ let decoded = pathname;
1297
+ try {
1298
+ decoded = decodeURIComponent(pathname);
1299
+ } catch {}
1300
+ const lastSegment = decoded.split(/[\\/]+/).pop() ?? "";
1301
+ const dot = lastSegment.lastIndexOf(".");
1302
+ if (dot <= 0 || dot === lastSegment.length - 1)
1303
+ return false;
1304
+ return ASSET_EXTENSIONS.has(lastSegment.slice(dot + 1).toLowerCase());
1305
+ }
1306
+ function resolveStaticPath(appRoot, pathname) {
1307
+ let decodedPath;
1308
+ try {
1309
+ decodedPath = decodeURIComponent(pathname);
1310
+ } catch {
1311
+ return null;
1312
+ }
1313
+ if (decodedPath.includes("\x00"))
1314
+ return null;
1315
+ const segments = decodedPath.split(/[\\/]+/);
1316
+ if (segments.includes(".."))
1317
+ return null;
1318
+ const normalizedPath = normalize(decodedPath).replace(/^[\\/]+/, "");
1319
+ const resolvedPath = resolve2(appRoot, normalizedPath);
1320
+ const rel = relative3(appRoot, resolvedPath);
1321
+ if (rel.startsWith("..") || isAbsolute(rel))
1322
+ return null;
1323
+ return resolvedPath;
1324
+ }
1325
+ function injectRuntimeConfig(html, config) {
1326
+ if (!config.apiBaseUrl) {
1327
+ return html;
1328
+ }
1329
+ const script = renderCustomAppRuntimeScript({
1330
+ api: { baseUrl: config.apiBaseUrl },
1331
+ auth: { audience: config.audience, enabled: config.authEnabled }
1332
+ });
1333
+ const existingRuntimeScript = /<script>window\.__SIXB_RUNTIME__ = .*?;<\/script>/;
1334
+ if (existingRuntimeScript.test(html)) {
1335
+ return html.replace(existingRuntimeScript, script);
1336
+ }
1337
+ if (html.includes("</head>")) {
1338
+ return html.replace("</head>", ` ${script}
1339
+ </head>`);
1340
+ }
1341
+ return `${script}
1342
+ ${html}`;
1343
+ }
1344
+ function htmlResponse(request, html) {
1345
+ return new Response(request.method === "HEAD" ? null : html, {
1346
+ headers: {
1347
+ "content-type": "text/html; charset=utf-8",
1348
+ "cache-control": "no-store"
1349
+ }
1350
+ });
1351
+ }
1352
+ var IMMUTABLE_ASSET_PATTERN = /^chunk-[a-z0-9]+\.(js|css|js\.map|css\.map)$/;
1353
+ function staticAssetHeaders(pathname) {
1354
+ if (pathname === customAppManifestRoute) {
1355
+ return {
1356
+ "content-type": "application/manifest+json; charset=utf-8",
1357
+ "cache-control": "no-cache"
1358
+ };
1359
+ }
1360
+ const lastSegment = pathname.split("/").pop() ?? "";
1361
+ if (!IMMUTABLE_ASSET_PATTERN.test(lastSegment)) {
1362
+ return {};
1363
+ }
1364
+ return { "cache-control": "public, max-age=31536000, immutable" };
1365
+ }
1366
+ function fileResponse(request, file, headers = {}) {
1367
+ return new Response(request.method === "HEAD" ? null : file, { headers });
1368
+ }
1369
+ function filePathResponse(request, path) {
1370
+ return fileResponse(request, Bun.file(path));
1371
+ }
1372
+ function notFoundResponse() {
1373
+ return new Response("Not Found", {
1374
+ status: 404,
1375
+ headers: {
1376
+ "cache-control": "no-store"
1377
+ }
1378
+ });
1379
+ }
1380
+ function getHeadRoute(handler) {
1381
+ return {
1382
+ GET: handler,
1383
+ HEAD: handler
1384
+ };
1385
+ }
1386
+ function allMethodsRoute(handler) {
1387
+ return {
1388
+ GET: handler,
1389
+ HEAD: handler,
1390
+ POST: handler,
1391
+ PUT: handler,
1392
+ PATCH: handler,
1393
+ DELETE: handler,
1394
+ OPTIONS: handler
1395
+ };
1396
+ }
1397
+ async function importHtmlBundle(htmlPath, version) {
1398
+ const bundleEntryPath = await prepareAppHtmlBundleEntry(htmlPath);
1399
+ const url = pathToFileURL2(bundleEntryPath);
1400
+ url.searchParams.set("v", String(version));
1401
+ const htmlModule = await import(url.href);
1402
+ return htmlModule.default;
1403
+ }
1404
+ function htmlBundleRoute(bundle) {
1405
+ return {
1406
+ GET: bundle,
1407
+ HEAD: bundle
1408
+ };
1409
+ }
1410
+ function manifestRoute(manifestPath) {
1411
+ return getHeadRoute((request) => fileResponse(request, Bun.file(manifestPath), staticAssetHeaders(customAppManifestRoute)));
1412
+ }
1413
+ function devServerInternalOrigin(host, port) {
1414
+ if (host === "0.0.0.0") {
1415
+ return `http://127.0.0.1:${port}`;
1416
+ }
1417
+ if (host === "::" || host === "[::]") {
1418
+ return `http://[::1]:${port}`;
1419
+ }
1420
+ const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
1421
+ return `http://${urlHost}:${port}`;
1422
+ }
1423
+ function spaHtmlRoute(internalOrigin) {
1424
+ return getHeadRoute(async (request) => {
1425
+ const publicUrl = new URL(request.url);
1426
+ if (publicUrl.pathname !== "/" && isAssetRequest(publicUrl.pathname)) {
1427
+ return notFoundResponse();
1428
+ }
1429
+ const url = new URL(internalAppShellRoute, internalOrigin());
1430
+ url.search = publicUrl.search;
1431
+ const requestHeaders = new Headers(request.headers);
1432
+ for (const header of [
1433
+ "forwarded",
1434
+ "host",
1435
+ "x-forwarded-host",
1436
+ "x-forwarded-port",
1437
+ "x-forwarded-proto"
1438
+ ]) {
1439
+ requestHeaders.delete(header);
1440
+ }
1441
+ const bundleResponse = await fetch(new Request(url, { method: request.method, headers: requestHeaders }));
1442
+ const responseHeaders = new Headers(bundleResponse.headers);
1443
+ responseHeaders.delete("content-length");
1444
+ responseHeaders.delete("etag");
1445
+ if (request.method === "HEAD") {
1446
+ return new Response(null, {
1447
+ status: bundleResponse.status,
1448
+ statusText: bundleResponse.statusText,
1449
+ headers: responseHeaders
1450
+ });
1451
+ }
1452
+ return new Response(restoreAppStaticUrls(await bundleResponse.text()), {
1453
+ status: bundleResponse.status,
1454
+ statusText: bundleResponse.statusText,
1455
+ headers: responseHeaders
1456
+ });
1457
+ });
1458
+ }
1459
+ export {
1460
+ createTailwindCssCompiler,
1461
+ createCustomApp
1462
+ };
1463
+
1464
+ //# debugId=EF77EB82048A32D864756E2164756E21