@sixb/app 0.1.4 → 0.1.6

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 CHANGED
@@ -1,5 +1,6 @@
1
1
  // @bun
2
2
  // src/createCustomApp.ts
3
+ import { randomBytes } from "crypto";
3
4
  import { watch } from "fs";
4
5
  import { access as access2, cp, mkdir as mkdir4, readFile as readFile5, rm as rm2, writeFile as writeFile3 } from "fs/promises";
5
6
  import { dirname as dirname3, isAbsolute, join as join7, normalize, relative as relative3, resolve as resolve3 } from "path";
@@ -19,27 +20,15 @@ var STATIC_ASSET_ORIGIN = "https://sixb-static.invalid";
19
20
  var brotliCompress = promisify(brotliCompressCallback);
20
21
  var gzip = promisify(gzipCallback);
21
22
  var PRECOMPRESSION_CONCURRENCY = 4;
23
+ var SHARED_APP_SHELL_FILE_NAME = "shared-index.html";
22
24
  async function buildApp(options) {
23
25
  const outdir = options.outdir ?? join(process.cwd(), ".sixb", "dist", "app");
26
+ if (Boolean(options.sharedEntryPath) !== Boolean(options.sharedScriptEntryPath)) {
27
+ throw new Error("[SixbCustomApp] sharedEntryPath and sharedScriptEntryPath must be provided together.");
28
+ }
24
29
  await rm(outdir, { recursive: true, force: true });
25
30
  await mkdir(outdir, { recursive: true });
26
- const result = await Bun.build({
27
- entrypoints: [options.scriptEntryPath],
28
- outdir,
29
- target: "browser",
30
- conditions: ["bun"],
31
- publicPath: "/",
32
- minify: true,
33
- splitting: true,
34
- naming: {
35
- entry: "app-[hash].[ext]",
36
- chunk: "chunk-[name]-[hash].[ext]",
37
- asset: "asset-[name]-[hash].[ext]"
38
- },
39
- plugins: [extensionlessSourceImportPlugin],
40
- define: { "process.env.NODE_ENV": '"production"' },
41
- sourcemap: "external"
42
- });
31
+ const result = await buildBrowserEntry(options.scriptEntryPath, outdir, "app");
43
32
  if (!result.success) {
44
33
  return {
45
34
  success: false,
@@ -47,28 +36,117 @@ async function buildApp(options) {
47
36
  logs: result.logs.map(String)
48
37
  };
49
38
  }
50
- const script = result.outputs.find((output) => output.kind === "entry-point" && output.type.startsWith("text/javascript"));
51
- const stylesheets = result.outputs.filter((output) => output.type.startsWith("text/css"));
52
- if (!script || stylesheets.length > 1) {
53
- throw new Error(`[SixbCustomApp] Expected one browser entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`);
54
- }
39
+ const normalEntry = resolveBrowserEntry(result.outputs, "browser");
55
40
  const sourceHtml = restoreAppStaticUrls(await readFile(options.entryPath, "utf-8"));
56
41
  const sourceEntryPattern = /\s*<script\s+type=["']module["']\s+src=["']\.\/main\.tsx["']><\/script>/;
57
42
  if (!sourceEntryPattern.test(sourceHtml)) {
58
43
  throw new Error("[SixbCustomApp] Generated app shell is missing its ./main.tsx entry.");
59
44
  }
60
45
  const assetTags = [
61
- ...stylesheets.map((stylesheet) => `<link rel="stylesheet" crossorigin href="/${basename(stylesheet.path)}">`),
62
- `<script type="module" crossorigin src="/${basename(script.path)}"></script>`
46
+ ...normalEntry.stylesheets.map((stylesheet) => `<link rel="stylesheet" crossorigin href="/${basename(stylesheet.path)}">`),
47
+ `<script type="module" crossorigin src="/${basename(normalEntry.script.path)}"></script>`
63
48
  ].join("");
64
49
  const html = withLoadingShell(sourceHtml).replace(sourceEntryPattern, "").replace("</head>", ` ${assetTags}</head>`);
65
50
  await writeFile(join(outdir, "index.html"), html, "utf-8");
51
+ const outputs = [...result.outputs];
52
+ if (options.sharedEntryPath && options.sharedScriptEntryPath) {
53
+ const sharedResult = await buildBrowserEntry(options.sharedScriptEntryPath, outdir, "shared");
54
+ if (!sharedResult.success) {
55
+ return {
56
+ success: false,
57
+ outdir,
58
+ logs: sharedResult.logs.map(String)
59
+ };
60
+ }
61
+ const sharedEntry = resolveBrowserEntry(sharedResult.outputs, "shared browser");
62
+ const sharedHtml = await renderSharedAppHtml(options.sharedEntryPath, sharedEntry);
63
+ await writeFile(join(outdir, SHARED_APP_SHELL_FILE_NAME), sharedHtml, "utf-8");
64
+ outputs.push(...sharedResult.outputs);
65
+ }
66
66
  if (options.manifestPath) {
67
67
  await copyFile(options.manifestPath, join(outdir, "app.webmanifest"));
68
68
  }
69
- await precompressBuildAssets(result.outputs);
69
+ await precompressBuildAssets(outputs);
70
70
  return { success: true, outdir };
71
71
  }
72
+ async function buildSharedAppDev(options) {
73
+ await rm(options.outdir, { recursive: true, force: true });
74
+ await mkdir(options.outdir, { recursive: true });
75
+ let result;
76
+ try {
77
+ result = await buildBrowserEntry(options.scriptEntryPath, options.outdir, "shared-dev", true);
78
+ } catch (error) {
79
+ await rm(options.outdir, { recursive: true, force: true });
80
+ throw error;
81
+ }
82
+ if (!result.success) {
83
+ await rm(options.outdir, { recursive: true, force: true });
84
+ throw new Error(`[SixbCustomApp] Failed to build the shared development shell: ${result.logs.map(String).join(`
85
+ `)}`);
86
+ }
87
+ const entry = resolveBrowserEntry(result.outputs, "shared development browser");
88
+ return {
89
+ assetPaths: result.outputs.map((output) => output.path),
90
+ html: await renderSharedAppHtml(options.entryPath, entry)
91
+ };
92
+ }
93
+ async function buildBrowserEntry(entrypoint, outdir, entryName, development = false) {
94
+ return await Bun.build({
95
+ entrypoints: [entrypoint],
96
+ outdir,
97
+ target: "browser",
98
+ conditions: ["bun"],
99
+ publicPath: "/",
100
+ minify: !development,
101
+ splitting: true,
102
+ naming: {
103
+ entry: `${entryName}-[hash].[ext]`,
104
+ chunk: "chunk-[name]-[hash].[ext]",
105
+ asset: "asset-[name]-[hash].[ext]"
106
+ },
107
+ plugins: [extensionlessSourceImportPlugin],
108
+ define: { "process.env.NODE_ENV": development ? '"development"' : '"production"' },
109
+ sourcemap: development ? "inline" : "external"
110
+ });
111
+ }
112
+ async function renderSharedAppHtml(entryPath, entry) {
113
+ const sourceHtml = restoreAppStaticUrls(await readFile(entryPath, "utf-8"));
114
+ const sourceEntryPattern = /const \{ startSharedApp \} = await import\((["'])\.\/shared-main\.tsx\1\)\s+startSharedApp\(bootstrap\)/;
115
+ if (!sourceEntryPattern.test(sourceHtml)) {
116
+ throw new Error("[SixbCustomApp] Generated shared app shell is missing its ./shared-main.tsx import.");
117
+ }
118
+ const stylesheetUrls = entry.stylesheets.map((stylesheet) => `/${basename(stylesheet.path)}`);
119
+ const bootstrap = [
120
+ `const { startSharedApp } = await import(${JSON.stringify(`/${basename(entry.script.path)}`)})`,
121
+ ...stylesheetUrls.length > 0 ? [
122
+ " startSharedApp(bootstrap, {",
123
+ " async loadAppStyles() {",
124
+ " await Promise.all(",
125
+ ` ${JSON.stringify(stylesheetUrls)}.map((href) => new Promise((resolve) => {`,
126
+ ' const link = document.createElement("link")',
127
+ ' link.rel = "stylesheet"',
128
+ ' link.crossOrigin = "anonymous"',
129
+ ' link.addEventListener("load", resolve, { once: true })',
130
+ ' link.addEventListener("error", resolve, { once: true })',
131
+ " link.href = href",
132
+ " document.head.append(link)",
133
+ " }))",
134
+ " )",
135
+ " },",
136
+ " })"
137
+ ] : [" startSharedApp(bootstrap)"]
138
+ ].join(`
139
+ `);
140
+ return withLoadingShell(sourceHtml).replace(sourceEntryPattern, bootstrap);
141
+ }
142
+ function resolveBrowserEntry(outputs, label) {
143
+ const script = outputs.find((output) => output.kind === "entry-point" && output.type.startsWith("text/javascript"));
144
+ const stylesheets = outputs.filter((output) => output.type.startsWith("text/css"));
145
+ if (!script || stylesheets.length > 1) {
146
+ throw new Error(`[SixbCustomApp] Expected one ${label} entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`);
147
+ }
148
+ return { script, stylesheets };
149
+ }
72
150
  async function buildAuthExperience(options) {
73
151
  const outdir = resolve(options.outdir);
74
152
  const assetsDir = join(outdir, "assets");
@@ -120,7 +198,8 @@ async function buildAuthExperience(options) {
120
198
  async function prepareAppHtmlBundleEntry(entryPath) {
121
199
  const html = await readFile(entryPath, "utf-8");
122
200
  const bundleHtml = html.replace(/(<link\s+rel=["'](?:manifest|icon|apple-touch-icon)["']\s+href=["'])(\/[^"']*)(["'][^>]*>)/g, `$1${STATIC_ASSET_ORIGIN}$2$3`);
123
- const bundleEntryPath = join(dirname(entryPath), "index.sixb-bundle.html");
201
+ const entryName = basename(entryPath, ".html");
202
+ const bundleEntryPath = join(dirname(entryPath), `${entryName}.sixb-bundle.html`);
124
203
  await writeFile(bundleEntryPath, bundleHtml, "utf-8");
125
204
  return bundleEntryPath;
126
205
  }
@@ -165,7 +244,9 @@ var extensionlessSourceImportPlugin = {
165
244
  }
166
245
  };
167
246
  async function precompressBuildAssets(outputs) {
168
- const paths = outputs.filter((output) => output.type.startsWith("text/javascript") || output.type.startsWith("text/css")).map((output) => output.path);
247
+ const paths = [
248
+ ...new Set(outputs.filter((output) => output.type.startsWith("text/javascript") || output.type.startsWith("text/css")).map((output) => output.path))
249
+ ];
169
250
  let cursor = 0;
170
251
  const worker = async () => {
171
252
  while (cursor < paths.length) {
@@ -355,7 +436,7 @@ function renderCustomAppRuntimeScript(config) {
355
436
  import { readdir } from "fs/promises";
356
437
  import { join as join3, relative } from "path";
357
438
  var dynamicSegmentPattern = /^\[([\w-]+)\]$/;
358
- var reservedRoutePrefixes = ["/api", "/auth", "/ws", "/docs", "/__sixb"];
439
+ var reservedRoutePrefixes = ["/api", "/auth", "/ws", "/docs", "/__sixb", "/shared"];
359
440
  var reservedRoutePaths = new Set(["/app.webmanifest"]);
360
441
  async function scanAppRoutes(appDir) {
361
442
  const pages = [];
@@ -422,6 +503,9 @@ function validateChildDirectories(entries, relativeDir) {
422
503
  for (const entry of entries) {
423
504
  if (!entry.isDirectory())
424
505
  continue;
506
+ if (!relativeDir && entry.name.toLowerCase() === "shared") {
507
+ throw new Error("[SixbCustomApp] app/shared is reserved for framework-managed shared links. " + "Move this page to another route.");
508
+ }
425
509
  const segment = routeSegment(entry.name, join3(relativeDir, entry.name));
426
510
  const key = segment.startsWith(":") ? ":" : segment.toLowerCase();
427
511
  const existing = claimedSegments.get(key);
@@ -457,7 +541,7 @@ function assertRouteIsAvailable(path, relativePath) {
457
541
  const reserved = reservedRoutePaths.has(normalizedPath) || reservedRoutePrefixes.some((prefix) => normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`));
458
542
  if (!reserved)
459
543
  return;
460
- throw new Error(`[SixbCustomApp] Page ${displayAppPath(relativePath)} resolves to reserved framework path '${path}'. Choose a route outside /api, /auth, /ws, /docs, /__sixb, and /app.webmanifest.`);
544
+ throw new Error(`[SixbCustomApp] Page ${displayAppPath(relativePath)} resolves to reserved framework path '${path}'. Choose a route outside /api, /auth, /ws, /docs, /__sixb, /shared, and /app.webmanifest.`);
461
545
  }
462
546
  function routeSegments(path) {
463
547
  return path === "/" ? [] : path.replace(/^\/+|\/+$/g, "").split("/");
@@ -484,7 +568,14 @@ function isNotFoundError(error) {
484
568
 
485
569
  // src/codegen.ts
486
570
  var AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER = "__SIXB_AUTH_BOOTSTRAP__";
571
+ function assertNoReservedSharedRoutes(routes) {
572
+ const reservedRoute = routes.find((route) => route.path === "/shared" || route.path.startsWith("/shared/"));
573
+ if (!reservedRoute)
574
+ return;
575
+ throw new Error(`[SixbCustomApp] ${reservedRoute.relativePath} maps to the reserved ${JSON.stringify(reservedRoute.path)} route. Shared links reuse ordinary app pages; move this page outside app/shared/.`);
576
+ }
487
577
  async function generateRouteManifest(routes, generatedDir, options = {}) {
578
+ assertNoReservedSharedRoutes(routes);
488
579
  await mkdir2(generatedDir, { recursive: true });
489
580
  const pages = [...routes].sort(compareRouteModules2);
490
581
  const pageImports = pages.map((route, index) => {
@@ -791,7 +882,7 @@ async function generateAppEntry(projectRoot, generatedDir, options = {}) {
791
882
  api: { baseUrl: options.apiBaseUrl },
792
883
  auth: { audience: options.audience ?? "app", enabled: options.authEnabled ?? true }
793
884
  }) : "";
794
- const mainContent = `import React from "react"
885
+ const runtimeContent = `import React from "react"
795
886
  import { createRoot, type Root } from "react-dom/client"
796
887
  import { signOut } from "@sixb/client"
797
888
  import {
@@ -802,12 +893,7 @@ import {
802
893
  useRoutes,
803
894
  } from "react-router-dom"
804
895
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
805
- import {
806
- configureSixbBrowserClient,
807
- isSixbApiError,
808
- readSixbBrowserRuntimeConfig,
809
- requireSixbBrowserAuthSession,
810
- } from "@sixb/client/browser"
896
+ import { isSixbApiError } from "@sixb/client/browser"
811
897
  import { routePaths, routes } from "./routes"
812
898
  ${globalsCssImport}
813
899
  ${layoutImport}
@@ -817,24 +903,11 @@ interface CustomAppHotData {
817
903
  queryClient?: QueryClient
818
904
  }
819
905
 
820
- const runtimeConfig = readSixbBrowserRuntimeConfig({ audience: "app" })
821
- const browserClient = configureSixbBrowserClient(runtimeConfig)
822
-
823
- if (import.meta.hot) {
824
- import.meta.hot.accept()
825
- import.meta.hot.dispose(() => {
826
- browserClient.dispose()
827
- })
906
+ export interface StartAppOptions {
907
+ readonly basename?: string
828
908
  }
829
909
 
830
- const authSession = runtimeConfig.auth.enabled
831
- ? await requireSixbBrowserAuthSession(runtimeConfig, browserClient)
832
- : null
833
- const applicationAccessDenied =
834
- authSession?.authenticated === true && !authSession.applicationAccess.allowed
835
- const canRenderApp =
836
- !runtimeConfig.auth.enabled ||
837
- (authSession?.authenticated === true && authSession.applicationAccess.allowed)
910
+ if (import.meta.hot) import.meta.hot.accept()
838
911
 
839
912
  const queryClient = getQueryClient()
840
913
 
@@ -874,7 +947,7 @@ function createQueryClient(): QueryClient {
874
947
  })
875
948
  }
876
949
 
877
- const RESERVED_PATH_PREFIXES = ["/api", "/auth", "/ws", "/docs"]
950
+ const RESERVED_PATH_PREFIXES = ["/api", "/auth", "/ws", "/docs", "/shared"]
878
951
 
879
952
  function isReservedPath(pathname: string) {
880
953
  return RESERVED_PATH_PREFIXES.some(
@@ -882,33 +955,74 @@ function isReservedPath(pathname: string) {
882
955
  )
883
956
  }
884
957
 
958
+ function isSharedTransportPath(pathname: string): boolean {
959
+ return pathname === "/shared" || pathname.startsWith("/shared/")
960
+ }
961
+
962
+ function primaryNavigationAnchor(event: MouseEvent): HTMLAnchorElement | null {
963
+ if (event.defaultPrevented) return null
964
+ if (event.button !== 0) return null
965
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null
966
+
967
+ const target = event.target
968
+ if (!(target instanceof Element)) return null
969
+ const anchor = target.closest("a")
970
+ if (!(anchor instanceof HTMLAnchorElement)) return null
971
+ if (anchor.target && anchor.target !== "_self") return null
972
+ if (anchor.hasAttribute("download")) return null
973
+ if (anchor.relList.contains("external")) return null
974
+ if (!anchor.getAttribute("href")) return null
975
+ return anchor
976
+ }
977
+
978
+ // A React Router <Link> mutates the current document before effects can reload it. Capture shared
979
+ // transport clicks first so an OIDC document never acquires a bearer fragment.
980
+ function SharedDocumentLinkInterceptor({ basename }: { readonly basename?: string }) {
981
+ React.useLayoutEffect(() => {
982
+ function onClick(event: MouseEvent) {
983
+ const anchor = primaryNavigationAnchor(event)
984
+ if (!anchor) return
985
+
986
+ const url = new URL(anchor.href, window.location.href)
987
+ if (url.origin !== window.location.origin) return
988
+ const appPath = pathInsideApp(url.pathname, basename)
989
+ if (!isSharedTransportPath(appPath)) return
990
+
991
+ // React Router prefixes an absolute <Link to="/shared/..."> with the current basename.
992
+ // Rebuild the transport URL from the path inside the app so switching grants does not nest
993
+ // the new link beneath /shared/:currentGrantId.
994
+ const documentUrl = new URL(appPath + url.search + url.hash, url.origin)
995
+
996
+ event.preventDefault()
997
+ event.stopImmediatePropagation()
998
+ window.location.assign(documentUrl.href)
999
+ }
1000
+
1001
+ document.addEventListener("click", onClick, true)
1002
+ return () => document.removeEventListener("click", onClick, true)
1003
+ }, [basename])
1004
+
1005
+ return null
1006
+ }
1007
+
885
1008
  // Makes plain same-origin <a href="/..."> clicks navigate client-side, so app
886
1009
  // authors get SPA navigation without remembering react-router's <Link>.
887
1010
  // Deliberately conservative: anything unusual falls through to the browser.
888
- function InternalLinkInterceptor() {
1011
+ function InternalLinkInterceptor({ basename }: { readonly basename?: string }) {
889
1012
  const navigate = useNavigate()
890
1013
 
891
1014
  React.useEffect(() => {
892
1015
  function onClick(event: MouseEvent) {
893
- if (event.defaultPrevented) return
894
- if (event.button !== 0) return
895
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return
896
-
897
- const target = event.target
898
- if (!(target instanceof Element)) return
899
- const anchor = target.closest("a")
900
- if (!(anchor instanceof HTMLAnchorElement)) return
901
- if (anchor.target && anchor.target !== "_self") return
902
- if (anchor.hasAttribute("download")) return
903
- if (anchor.relList.contains("external")) return
904
- if (!anchor.getAttribute("href")) return
1016
+ const anchor = primaryNavigationAnchor(event)
1017
+ if (!anchor) return
905
1018
 
906
1019
  const url = new URL(anchor.href, window.location.href)
907
1020
  if (url.origin !== window.location.origin) return
908
- if (isReservedPath(url.pathname)) return
1021
+ const appPath = pathInsideApp(url.pathname, basename)
1022
+ if (isReservedPath(appPath)) return
909
1023
  // Only intercept destinations the app actually routes; anything else may
910
1024
  // be a real server resource and keeps native navigation.
911
- if (!routePaths.some((path) => matchPath(path, url.pathname))) return
1025
+ if (!routePaths.some((path) => matchPath(path, appPath))) return
912
1026
  // Same-document hash links keep native scroll behavior.
913
1027
  if (
914
1028
  url.hash &&
@@ -919,16 +1033,39 @@ function InternalLinkInterceptor() {
919
1033
  }
920
1034
 
921
1035
  event.preventDefault()
922
- navigate(url.pathname + url.search + url.hash)
1036
+ navigate(appPath + url.search + url.hash)
923
1037
  }
924
1038
 
925
1039
  document.addEventListener("click", onClick)
926
1040
  return () => document.removeEventListener("click", onClick)
927
- }, [navigate])
1041
+ }, [basename, navigate])
928
1042
 
929
1043
  return null
930
1044
  }
931
1045
 
1046
+ function pathInsideApp(pathname: string, basename: string | undefined): string {
1047
+ if (
1048
+ basename &&
1049
+ (pathname === basename || pathname.startsWith(basename.endsWith("/") ? basename : basename + "/"))
1050
+ ) {
1051
+ return pathname.slice(basename.length) || "/"
1052
+ }
1053
+ return pathname
1054
+ }
1055
+
1056
+ // Programmatic React Router navigation cannot be blocked by BrowserRouter. Gate the ordinary page
1057
+ // tree while forcing the new document so no route can run under the previous OIDC authority.
1058
+ function SharedDocumentBoundary({ children }: { readonly children: React.ReactNode }) {
1059
+ const location = useLocation()
1060
+ const crossingBoundary = isSharedTransportPath(location.pathname)
1061
+
1062
+ React.useLayoutEffect(() => {
1063
+ if (crossingBoundary) window.location.reload()
1064
+ }, [crossingBoundary])
1065
+
1066
+ return crossingBoundary ? null : children
1067
+ }
1068
+
932
1069
  // Shared presentational fallback used by the not-found view and the error
933
1070
  // boundary. Styled with @sixb/ui design tokens (var(--token)) so it adopts the
934
1071
  // app's theme when those tokens are loaded, but every token has a hardcoded
@@ -1063,20 +1200,32 @@ function NotFoundView() {
1063
1200
  // of a blank page and a console error. A missing object is an expected state,
1064
1201
  // so a 404 reuses the not-found view rather than the generic crash screen.
1065
1202
  // Apps will be able to override this via app/error.tsx.
1066
- function AppErrorFallback({ error }: { error: unknown }) {
1203
+ function AppErrorFallback({
1204
+ error,
1205
+ hideErrorDetails,
1206
+ }: {
1207
+ error: unknown
1208
+ hideErrorDetails: boolean
1209
+ }) {
1067
1210
  if (isSixbApiError(error) && error.status === 404) {
1068
1211
  return <NotFoundView />
1069
1212
  }
1070
1213
  return (
1071
1214
  <AppFallback
1072
1215
  title="Something went wrong"
1073
- detail={error instanceof Error ? error.message : String(error)}
1216
+ detail={
1217
+ hideErrorDetails
1218
+ ? "This shared page could not be displayed."
1219
+ : error instanceof Error
1220
+ ? error.message
1221
+ : String(error)
1222
+ }
1074
1223
  />
1075
1224
  )
1076
1225
  }
1077
1226
 
1078
1227
  class AppErrorBoundary extends React.Component<
1079
- { resetKey: string; children: React.ReactNode },
1228
+ { resetKey: string; hideErrorDetails: boolean; children: React.ReactNode },
1080
1229
  { error: unknown }
1081
1230
  > {
1082
1231
  state: { error: unknown } = { error: null }
@@ -1086,7 +1235,11 @@ class AppErrorBoundary extends React.Component<
1086
1235
  }
1087
1236
 
1088
1237
  componentDidCatch(error: unknown) {
1089
- console.error("[SixbApp] Uncaught render error:", error)
1238
+ if (this.props.hideErrorDetails) {
1239
+ console.error("[SixbApp] A shared page failed to render.")
1240
+ } else {
1241
+ console.error("[SixbApp] Uncaught render error:", error)
1242
+ }
1090
1243
  }
1091
1244
 
1092
1245
  // Clear the error when the route changes so navigating away (or an in-app
@@ -1099,16 +1252,32 @@ class AppErrorBoundary extends React.Component<
1099
1252
 
1100
1253
  render() {
1101
1254
  if (this.state.error !== null) {
1102
- return <AppErrorFallback error={this.state.error} />
1255
+ return (
1256
+ <AppErrorFallback
1257
+ error={this.state.error}
1258
+ hideErrorDetails={this.props.hideErrorDetails}
1259
+ />
1260
+ )
1103
1261
  }
1104
1262
  return this.props.children
1105
1263
  }
1106
1264
  }
1107
1265
 
1108
- function RoutedErrorBoundary({ children }: { children: React.ReactNode }) {
1266
+ function RoutedErrorBoundary({
1267
+ children,
1268
+ hideErrorDetails,
1269
+ }: {
1270
+ children: React.ReactNode
1271
+ hideErrorDetails: boolean
1272
+ }) {
1109
1273
  const location = useLocation()
1110
1274
  return (
1111
- <AppErrorBoundary resetKey={location.pathname + location.search}>{children}</AppErrorBoundary>
1275
+ <AppErrorBoundary
1276
+ resetKey={location.pathname + location.search}
1277
+ hideErrorDetails={hideErrorDetails}
1278
+ >
1279
+ {children}
1280
+ </AppErrorBoundary>
1112
1281
  )
1113
1282
  }
1114
1283
 
@@ -1118,29 +1287,270 @@ function AppRoutes() {
1118
1287
  return useRoutes(appRoutes)
1119
1288
  }
1120
1289
 
1121
- function App() {
1290
+ function RoutedApp({ hideErrorDetails }: { readonly hideErrorDetails: boolean }) {
1291
+ return (
1292
+ <RoutedErrorBoundary hideErrorDetails={hideErrorDetails}>
1293
+ ${layoutWrapperStart}
1294
+ <AppRoutes />
1295
+ ${layoutWrapperEnd}
1296
+ </RoutedErrorBoundary>
1297
+ )
1298
+ }
1299
+
1300
+ function App({ basename }: StartAppOptions) {
1122
1301
  return (
1123
1302
  <QueryClientProvider client={queryClient}>
1124
- <BrowserRouter>
1125
- <InternalLinkInterceptor />
1126
- <RoutedErrorBoundary>
1127
- ${layoutWrapperStart}
1128
- <AppRoutes />
1129
- ${layoutWrapperEnd}
1130
- </RoutedErrorBoundary>
1303
+ <BrowserRouter basename={basename}>
1304
+ <SharedDocumentLinkInterceptor basename={basename} />
1305
+ <InternalLinkInterceptor basename={basename} />
1306
+ {basename ? (
1307
+ <RoutedApp hideErrorDetails />
1308
+ ) : (
1309
+ <SharedDocumentBoundary>
1310
+ <RoutedApp hideErrorDetails={false} />
1311
+ </SharedDocumentBoundary>
1312
+ )}
1131
1313
  </BrowserRouter>
1132
1314
  </QueryClientProvider>
1133
1315
  )
1134
1316
  }
1135
1317
 
1318
+ export function startApp(options: StartAppOptions = {}) {
1319
+ getRoot().render(<App basename={options.basename} />)
1320
+ }
1321
+
1322
+ export function renderAccessDenied() {
1323
+ getRoot().render(<AccessDeniedView />)
1324
+ }
1325
+ `;
1326
+ const runtimePath = join4(generatedDir, "app-runtime.tsx");
1327
+ await writeFileIfChanged(runtimePath, runtimeContent);
1328
+ const mainContent = `import {
1329
+ configureSixbBrowserClient,
1330
+ readSixbBrowserRuntimeConfig,
1331
+ requireSixbBrowserAuthSession,
1332
+ } from "@sixb/client/browser"
1333
+ import { renderAccessDenied, startApp } from "./app-runtime"
1334
+
1335
+ const runtimeConfig = readSixbBrowserRuntimeConfig({ audience: "app" })
1336
+ const browserClient = configureSixbBrowserClient(runtimeConfig)
1337
+
1338
+ if (import.meta.hot) {
1339
+ import.meta.hot.accept()
1340
+ import.meta.hot.dispose(() => browserClient.dispose())
1341
+ }
1342
+
1343
+ const authSession = runtimeConfig.auth.enabled
1344
+ ? await requireSixbBrowserAuthSession(runtimeConfig, browserClient)
1345
+ : null
1346
+ const applicationAccessDenied =
1347
+ authSession?.authenticated === true && !authSession.applicationAccess.allowed
1348
+ const canRenderApp =
1349
+ !runtimeConfig.auth.enabled ||
1350
+ (authSession?.authenticated === true && authSession.applicationAccess.allowed)
1351
+
1136
1352
  if (canRenderApp) {
1137
- getRoot().render(<App />)
1353
+ startApp()
1138
1354
  } else if (applicationAccessDenied) {
1139
- getRoot().render(<AccessDeniedView />)
1355
+ renderAccessDenied()
1140
1356
  }
1141
1357
  `;
1142
1358
  const mainPath = join4(generatedDir, "main.tsx");
1143
1359
  await writeFileIfChanged(mainPath, mainContent);
1360
+ const sharedMainContent = `import {
1361
+ configureSixbSharedBrowserClient,
1362
+ isSixbApiError,
1363
+ readSixbBrowserRuntimeConfig,
1364
+ type SixbSharedBrowserClientController,
1365
+ } from "@sixb/client/browser"
1366
+
1367
+ export interface SharedAppBootstrap {
1368
+ readonly basename: string
1369
+ readonly grantId: string
1370
+ readonly requestedPath: string
1371
+ readonly secret: string | null
1372
+ }
1373
+
1374
+ export interface SharedAppStartOptions {
1375
+ readonly loadAppStyles?: () => Promise<void>
1376
+ }
1377
+
1378
+ let activeController: SixbSharedBrowserClientController | null = null
1379
+
1380
+ if (import.meta.hot) {
1381
+ import.meta.hot.accept()
1382
+ import.meta.hot.dispose(() => {
1383
+ activeController?.dispose()
1384
+ activeController = null
1385
+ })
1386
+ }
1387
+
1388
+ export function startSharedApp(
1389
+ bootstrap: SharedAppBootstrap,
1390
+ options: SharedAppStartOptions = {}
1391
+ ): void {
1392
+ if (!isValidBootstrap(bootstrap)) {
1393
+ renderSharedFallback("unavailable")
1394
+ return
1395
+ }
1396
+ const { basename, grantId } = bootstrap
1397
+ let loadAppStyles = options.loadAppStyles
1398
+
1399
+ activeController?.dispose()
1400
+ let controller: SixbSharedBrowserClientController
1401
+ try {
1402
+ const runtimeConfig = readSixbBrowserRuntimeConfig({
1403
+ audience: "app",
1404
+ authEnabled: false,
1405
+ })
1406
+ controller = configureSixbSharedBrowserClient(runtimeConfig, {
1407
+ grantId,
1408
+ })
1409
+ activeController = controller
1410
+ } catch {
1411
+ renderSharedFallback("unavailable")
1412
+ return
1413
+ }
1414
+
1415
+ let secret = bootstrap.secret
1416
+ let canonicalDestinationPath: string | null = null
1417
+ let appStylesLoaded = false
1418
+ let pending = false
1419
+
1420
+ const open = async () => {
1421
+ if (pending) return
1422
+ pending = true
1423
+ renderSharedFallback("loading")
1424
+
1425
+ try {
1426
+ const exchangedSecret = secret !== null
1427
+ const session = await controller.establish(secret)
1428
+ // Once a server session exists the one-time link credential must not survive a retry.
1429
+ secret = null
1430
+ if (exchangedSecret) canonicalDestinationPath = session.destinationPath
1431
+ // Keep the trusted destination pending until this document is canonical or a hard
1432
+ // navigation to it has started. Application code never imports under the caller's path.
1433
+ if (canonicalDestinationPath !== null) {
1434
+ try {
1435
+ if (!canonicalizeInitialDestination(basename, canonicalDestinationPath)) return
1436
+ } catch (error) {
1437
+ // Both same-document canonicalization and the hard-navigation fallback failed. Retire
1438
+ // the newly established session before showing a terminal error so a reload cannot
1439
+ // restore it under the caller-controlled path.
1440
+ await controller.signOut().catch(() => undefined)
1441
+ controller.dispose()
1442
+ if (activeController === controller) activeController = null
1443
+ throw error
1444
+ }
1445
+ canonicalDestinationPath = null
1446
+ }
1447
+ if (!appStylesLoaded) {
1448
+ await loadAppStyles?.()
1449
+ loadAppStyles = undefined
1450
+ appStylesLoaded = true
1451
+ }
1452
+
1453
+ const { startApp } = await import("./app-runtime")
1454
+ startApp({ basename })
1455
+ } catch (error) {
1456
+ if (isRetryableSharedFailure(error)) {
1457
+ console.error("[SixbSharedApp] Shared access could not be opened; retry is available.")
1458
+ renderSharedFallback("retryable", () => void open())
1459
+ } else {
1460
+ renderSharedFallback("unavailable")
1461
+ }
1462
+ } finally {
1463
+ pending = false
1464
+ }
1465
+ }
1466
+
1467
+ void open()
1468
+ }
1469
+
1470
+ function isValidBootstrap(value: SharedAppBootstrap): boolean {
1471
+ return (
1472
+ typeof value.grantId === "string" &&
1473
+ value.basename === "/shared/" + encodeURIComponent(value.grantId) &&
1474
+ value.requestedPath.startsWith("/") &&
1475
+ (value.secret === null || typeof value.secret === "string")
1476
+ )
1477
+ }
1478
+
1479
+ function canonicalizeInitialDestination(basename: string, destinationPath: string): boolean {
1480
+ const canonicalPath = basename + destinationPath
1481
+ if (
1482
+ window.location.pathname !== canonicalPath ||
1483
+ window.location.search !== "" ||
1484
+ window.location.hash !== ""
1485
+ ) {
1486
+ try {
1487
+ window.history.replaceState(window.history.state, "", canonicalPath)
1488
+ } catch {
1489
+ // Preserve the authority boundary even when a browser or embedding policy denies History
1490
+ // mutation: a fresh document at the trusted server destination is still safe.
1491
+ window.location.replace(canonicalPath)
1492
+ return false
1493
+ }
1494
+ }
1495
+ return true
1496
+ }
1497
+
1498
+ function isRetryableSharedFailure(error: unknown): boolean {
1499
+ if (error instanceof TypeError) return true
1500
+ return (
1501
+ isSixbApiError(error) &&
1502
+ (error.status === 408 || error.status === 429 || error.status >= 500)
1503
+ )
1504
+ }
1505
+
1506
+ function renderSharedFallback(
1507
+ state: "loading" | "retryable" | "unavailable",
1508
+ retry?: () => void
1509
+ ): void {
1510
+ const root = document.getElementById("root")
1511
+ if (!root) return
1512
+
1513
+ const main = document.createElement("main")
1514
+ main.setAttribute("role", state === "loading" ? "status" : "alert")
1515
+ main.style.cssText =
1516
+ "min-height:100dvh;display:flex;flex-direction:column;align-items:center;" +
1517
+ "justify-content:center;gap:.75rem;padding:2rem;text-align:center;" +
1518
+ "font-family:system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"
1519
+
1520
+ const title = document.createElement("h1")
1521
+ title.style.cssText = "margin:0;font-size:1.5rem"
1522
+ title.textContent =
1523
+ state === "loading"
1524
+ ? "Opening shared access\u2026"
1525
+ : state === "retryable"
1526
+ ? "Unable to open this link"
1527
+ : "Link unavailable"
1528
+ const detail = document.createElement("p")
1529
+ detail.style.cssText = "margin:0;max-width:32rem"
1530
+ detail.textContent =
1531
+ state === "loading"
1532
+ ? "Please wait while this link is verified."
1533
+ : state === "retryable"
1534
+ ? "A temporary problem occurred. Please try again."
1535
+ : "This shared link is invalid, expired, or no longer available."
1536
+ main.append(title, detail)
1537
+
1538
+ if (retry) {
1539
+ const button = document.createElement("button")
1540
+ button.type = "button"
1541
+ button.textContent = "Try again"
1542
+ button.style.cssText =
1543
+ "margin-top:.25rem;padding:.625rem 1rem;border:1px solid currentColor;" +
1544
+ "border-radius:.375rem;background:transparent;color:inherit;cursor:pointer;font:inherit"
1545
+ button.addEventListener("click", retry, { once: true })
1546
+ main.append(button)
1547
+ }
1548
+
1549
+ root.replaceChildren(main)
1550
+ }
1551
+ `;
1552
+ const sharedMainPath = join4(generatedDir, "shared-main.tsx");
1553
+ await writeFileIfChanged(sharedMainPath, sharedMainContent);
1144
1554
  const metadataHead = renderMetadataHead(metadata);
1145
1555
  const htmlContent = `<!DOCTYPE html>
1146
1556
  <html lang="en">
@@ -1180,7 +1590,117 @@ ${metadataHead}
1180
1590
  `;
1181
1591
  const htmlPath = join4(generatedDir, "index.html");
1182
1592
  await writeFileIfChanged(htmlPath, htmlContent);
1183
- return { htmlPath, mainPath, manifestPath };
1593
+ const sharedRuntimeConfigScript = options.apiBaseUrl ? renderCustomAppRuntimeScript({
1594
+ api: { baseUrl: options.apiBaseUrl },
1595
+ auth: { audience: "app", enabled: false }
1596
+ }) : "";
1597
+ const sharedHtmlContent = `<!DOCTYPE html>
1598
+ <html lang="en">
1599
+ <head>
1600
+ <meta charset="UTF-8" />
1601
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
1602
+ <meta name="robots" content="noindex, nofollow, noarchive" />
1603
+ <meta name="referrer" content="no-referrer" />
1604
+ ${renderSharedMetadataHead(metadata)}
1605
+ ${sharedRuntimeConfigScript}
1606
+ <style>
1607
+ * { box-sizing: border-box; }
1608
+ html, body, #root { margin: 0; min-height: 100%; }
1609
+ body, #root { min-height: 100vh; min-height: 100dvh; }
1610
+ </style>
1611
+ </head>
1612
+ <body>
1613
+ <div id="root"></div>
1614
+ <script>
1615
+ function renderUnavailable() {
1616
+ const root = document.getElementById("root")
1617
+ if (!root) return
1618
+ const main = document.createElement("main")
1619
+ main.setAttribute("role", "alert")
1620
+ main.style.cssText =
1621
+ "min-height:100dvh;display:grid;place-items:center;padding:2rem;text-align:center;" +
1622
+ "font-family:system-ui,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"
1623
+ const message = document.createElement("p")
1624
+ message.textContent = "This shared link is invalid, expired, or no longer available."
1625
+ main.append(message)
1626
+ root.replaceChildren(main)
1627
+ }
1628
+
1629
+ function consumeBootstrap() {
1630
+ const rawFragment = window.location.hash.startsWith("#")
1631
+ ? window.location.hash.slice(1)
1632
+ : window.location.hash
1633
+ // Only the canonical 32-byte bearer belongs to the transport. Ordinary page anchors must
1634
+ // remain intact when an established shared session is reloaded.
1635
+ const secret = /^[A-Za-z0-9_-]{43}$/.test(rawFragment) ? rawFragment : null
1636
+ if (secret !== null) {
1637
+ try {
1638
+ window.history.replaceState(
1639
+ window.history.state,
1640
+ "",
1641
+ window.location.pathname + window.location.search
1642
+ )
1643
+ } catch {
1644
+ return null
1645
+ }
1646
+ }
1647
+
1648
+ const match = /^\\/shared\\/([^/]+)(\\/.*)?$/.exec(window.location.pathname)
1649
+ if (!match) return null
1650
+ let grantId
1651
+ try {
1652
+ grantId = decodeURIComponent(match[1])
1653
+ } catch {
1654
+ return null
1655
+ }
1656
+ if (encodeURIComponent(grantId) !== match[1]) return null
1657
+ return {
1658
+ basename: "/shared/" + match[1],
1659
+ grantId,
1660
+ requestedPath: match[2] ?? "/",
1661
+ secret,
1662
+ }
1663
+ }
1664
+
1665
+ async function bootstrapSharedApp() {
1666
+ const bootstrap = consumeBootstrap()
1667
+ if (!bootstrap) {
1668
+ renderUnavailable()
1669
+ return
1670
+ }
1671
+
1672
+ try {
1673
+ const { startSharedApp } = await import("./shared-main.tsx")
1674
+ startSharedApp(bootstrap)
1675
+ } catch {
1676
+ console.error("[SixbSharedApp] Shared application bootstrap failed.")
1677
+ renderUnavailable()
1678
+ }
1679
+ }
1680
+
1681
+ void bootstrapSharedApp()
1682
+ </script>
1683
+ </body>
1684
+ </html>
1685
+ `;
1686
+ const sharedHtmlPath = join4(generatedDir, "shared-index.html");
1687
+ await writeFileIfChanged(sharedHtmlPath, sharedHtmlContent);
1688
+ return {
1689
+ htmlPath,
1690
+ mainPath,
1691
+ manifestPath,
1692
+ runtimePath,
1693
+ sharedHtmlPath,
1694
+ sharedMainPath
1695
+ };
1696
+ }
1697
+ function renderSharedMetadataHead(metadata) {
1698
+ return [
1699
+ ` <title>${escapeHtmlText(metadata.title)}</title>`,
1700
+ ...metadata.description ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`] : [],
1701
+ ` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`
1702
+ ].join(`
1703
+ `);
1184
1704
  }
1185
1705
  function renderMetadataHead(metadata) {
1186
1706
  const tags = [
@@ -1240,6 +1760,60 @@ async function fileExists2(path) {
1240
1760
  }
1241
1761
  }
1242
1762
 
1763
+ // src/dev-reload.ts
1764
+ function devReloadResponse(request) {
1765
+ const generation = process.env.SIXB_DEV_GENERATION;
1766
+ const headers = new Headers({
1767
+ "content-type": "text/javascript; charset=utf-8",
1768
+ "cache-control": "no-store"
1769
+ });
1770
+ if (generation && process.env.SIXB_DEV_READY === "1") {
1771
+ headers.set("x-sixb-dev-generation", generation);
1772
+ }
1773
+ if (request.method === "HEAD")
1774
+ return new Response(null, { headers });
1775
+ const script = generation ? `(() => {
1776
+ if (window.__sixbDevReload) return;
1777
+ window.__sixbDevReload = true;
1778
+ const generation = ${JSON.stringify(generation).replaceAll("<", "\\u003c")};
1779
+ let timer;
1780
+ let checking = false;
1781
+ let finished = false;
1782
+ let failures = 0;
1783
+ const hidden = () => document.visibilityState === "hidden";
1784
+ function schedule(delay) {
1785
+ clearTimeout(timer);
1786
+ timer = setTimeout(poll, delay);
1787
+ }
1788
+ async function poll() {
1789
+ if (checking || finished) return;
1790
+ if (hidden()) { schedule(15000); return; }
1791
+ checking = true;
1792
+ try {
1793
+ const response = await fetch("/__sixb/dev-reload.js", {
1794
+ method: "HEAD", cache: "no-store", signal: AbortSignal.timeout(3000)
1795
+ });
1796
+ const next = response.headers.get("x-sixb-dev-generation");
1797
+ if (response.ok && next && next !== generation) {
1798
+ finished = true;
1799
+ document.removeEventListener("visibilitychange", visible);
1800
+ location.reload();
1801
+ return;
1802
+ }
1803
+ failures = response.ok && next ? 0 : Math.min(failures + 1, 4);
1804
+ } catch { failures = Math.min(failures + 1, 4); }
1805
+ finally { checking = false; }
1806
+ schedule(Math.min(1000 * 2 ** failures, 10000));
1807
+ }
1808
+ function visible() {
1809
+ if (!hidden()) { clearTimeout(timer); void poll(); }
1810
+ }
1811
+ document.addEventListener("visibilitychange", visible);
1812
+ void poll();
1813
+ })();` : "";
1814
+ return new Response(script, { headers });
1815
+ }
1816
+
1243
1817
  // src/styles.ts
1244
1818
  import { readFile as readFile4 } from "fs/promises";
1245
1819
  import { join as join6 } from "path";
@@ -1384,6 +1958,7 @@ var builtInAgentRoutePaths = ["/agents", "/agents/new/:agentId", "/agents/:threa
1384
1958
  var builtInAgentRouteSourcePath = join7(packageRoot, "src", "agents.ts");
1385
1959
  var customAppManifestRoute = "/app.webmanifest";
1386
1960
  var internalAppShellRoute = "/__sixb/generated/app-shell";
1961
+ var internalSharedAppShellRoute = "/__sixb/generated/shared-app-shell";
1387
1962
  async function createCustomApp(options) {
1388
1963
  const rootDir = resolve3(options.rootDir);
1389
1964
  const appDir = options.appDir ? resolve3(rootDir, options.appDir) : resolve3(rootDir, "app");
@@ -1494,7 +2069,7 @@ async function createCustomApp(options) {
1494
2069
  builtInRoutes,
1495
2070
  layouts: discovery.layouts
1496
2071
  });
1497
- const { htmlPath, mainPath, manifestPath } = await generateAppEntry(rootDir, generatedDir, {
2072
+ const entry = await generateAppEntry(rootDir, generatedDir, {
1498
2073
  apiBaseUrl,
1499
2074
  audience,
1500
2075
  authEnabled,
@@ -1503,7 +2078,7 @@ async function createCustomApp(options) {
1503
2078
  frameworkStylesheetPaths: stylesheets.frameworkStylesheetPaths,
1504
2079
  stylesheetPath: stylesheets.stylesheetPath
1505
2080
  });
1506
- return { htmlPath, mainPath, manifestPath, routes };
2081
+ return { ...entry, routes };
1507
2082
  }
1508
2083
  async function prepareAuthExperience(authOptions = {}) {
1509
2084
  const outdir = authOptions.outdir ? resolve3(rootDir, authOptions.outdir) : join7(generatedDir, "auth");
@@ -1562,26 +2137,76 @@ async function createCustomApp(options) {
1562
2137
  async dev(devOptions = {}) {
1563
2138
  const host = devOptions.host ?? "0.0.0.0";
1564
2139
  const port = devOptions.port ?? 3001;
1565
- const { htmlPath, manifestPath } = await prepareGeneratedApp();
2140
+ const { htmlPath, manifestPath, sharedHtmlPath, sharedMainPath } = await prepareGeneratedApp();
1566
2141
  await prepareAuthExperience();
1567
2142
  let htmlImportVersion = 0;
1568
2143
  let htmlBundle = await importHtmlBundle(htmlPath, htmlImportVersion);
2144
+ const sharedDevRoot = join7(generatedDir, "shared-dev");
2145
+ await rm2(sharedDevRoot, { recursive: true, force: true });
2146
+ let sharedBuildVersion = 0;
2147
+ let sharedSourceVersion = 0;
2148
+ let sharedBuiltSourceVersion = -1;
2149
+ let sharedBuild = null;
2150
+ let sharedBuildPromise = null;
2151
+ let sharedAssetRoutes = {};
2152
+ let stopping = false;
2153
+ const privateAppShellRoute = `${internalAppShellRoute}-${randomBytes(18).toString("base64url")}`;
1569
2154
  const publicRoutes = await pathExists(publicDir) ? await createPublicRoutes(publicDir) : {};
1570
2155
  let internalOrigin = "";
2156
+ let server = null;
1571
2157
  const serveOptions = (bundle) => ({
1572
2158
  port,
1573
2159
  hostname: host,
1574
2160
  development: true,
1575
2161
  routes: {
1576
2162
  ...publicRoutes,
2163
+ ...sharedAssetRoutes,
1577
2164
  ...reservedSixbRoutes(),
2165
+ "/__sixb/dev-reload.js": getHeadRoute(devReloadResponse),
1578
2166
  [customAppManifestRoute]: manifestRoute(manifestPath),
1579
- [internalAppShellRoute]: htmlBundleRoute(bundle),
1580
- "/": spaHtmlRoute(() => internalOrigin),
1581
- "/*": spaHtmlRoute(() => internalOrigin)
2167
+ [privateAppShellRoute]: htmlBundleRoute(bundle),
2168
+ ...sharedAppDevRoutes(async () => (await ensureSharedBuild()).html, apiBaseUrl),
2169
+ "/": spaHtmlRoute(() => internalOrigin, { shellRoute: privateAppShellRoute }),
2170
+ "/*": spaHtmlRoute(() => internalOrigin, { shellRoute: privateAppShellRoute })
1582
2171
  }
1583
2172
  });
1584
- const server = Bun.serve(serveOptions(htmlBundle));
2173
+ async function ensureSharedBuild() {
2174
+ if (stopping) {
2175
+ throw new Error("[SixbCustomApp] Shared development build requested while stopping.");
2176
+ }
2177
+ if (sharedBuild && sharedBuiltSourceVersion === sharedSourceVersion) {
2178
+ return sharedBuild;
2179
+ }
2180
+ if (sharedBuildPromise) {
2181
+ await sharedBuildPromise;
2182
+ return await ensureSharedBuild();
2183
+ }
2184
+ const sourceVersion = sharedSourceVersion;
2185
+ const outdir = join7(sharedDevRoot, String(sharedBuildVersion++));
2186
+ const build = buildSharedAppDev({
2187
+ entryPath: sharedHtmlPath,
2188
+ outdir,
2189
+ scriptEntryPath: sharedMainPath
2190
+ }).then((result2) => {
2191
+ sharedAssetRoutes = {
2192
+ ...sharedAssetRoutes,
2193
+ ...createGeneratedAssetRoutes(outdir, result2.assetPaths)
2194
+ };
2195
+ sharedBuild = result2;
2196
+ sharedBuiltSourceVersion = sourceVersion;
2197
+ server?.reload(serveOptions(htmlBundle));
2198
+ return result2;
2199
+ }).finally(() => {
2200
+ sharedBuildPromise = null;
2201
+ });
2202
+ sharedBuildPromise = build;
2203
+ const result = await build;
2204
+ if (!stopping && sourceVersion !== sharedSourceVersion) {
2205
+ return await ensureSharedBuild();
2206
+ }
2207
+ return result;
2208
+ }
2209
+ server = Bun.serve(serveOptions(htmlBundle));
1585
2210
  internalOrigin = devServerInternalOrigin(host, server.port ?? port);
1586
2211
  let rebuildTimer = null;
1587
2212
  let rebuildChain = Promise.resolve();
@@ -1591,7 +2216,8 @@ async function createCustomApp(options) {
1591
2216
  await prepareAuthExperience();
1592
2217
  htmlImportVersion++;
1593
2218
  htmlBundle = await importHtmlBundle(nextHtmlPath, htmlImportVersion);
1594
- server.reload(serveOptions(htmlBundle));
2219
+ sharedSourceVersion++;
2220
+ server?.reload(serveOptions(htmlBundle));
1595
2221
  }).catch((error) => {
1596
2222
  const message = error instanceof Error ? error.message : String(error);
1597
2223
  console.error(`[SixbCustomApp] Rebuild failed: ${message}`);
@@ -1620,6 +2246,7 @@ async function createCustomApp(options) {
1620
2246
  port,
1621
2247
  url: `http://${displayHost}:${port}`,
1622
2248
  async stop() {
2249
+ stopping = true;
1623
2250
  if (rebuildTimer) {
1624
2251
  clearTimeout(rebuildTimer);
1625
2252
  rebuildTimer = null;
@@ -1629,16 +2256,22 @@ async function createCustomApp(options) {
1629
2256
  await tailwindCompiler?.stop();
1630
2257
  await authTailwindCompiler?.stop();
1631
2258
  await builtInAgentCssCompiler?.stop();
1632
- server.stop(true);
2259
+ const activeServer = server;
2260
+ server = null;
2261
+ activeServer?.stop(true);
2262
+ await sharedBuildPromise?.catch(() => {});
2263
+ await rm2(sharedDevRoot, { recursive: true, force: true });
1633
2264
  }
1634
2265
  };
1635
2266
  },
1636
2267
  async build(buildOptions = {}) {
1637
2268
  const outdir = resolve3(rootDir, buildOptions.outdir ?? join7(".sixb", "dist", "app"));
1638
- const { htmlPath, mainPath, manifestPath } = await prepareGeneratedApp();
2269
+ const { htmlPath, mainPath, manifestPath, sharedHtmlPath, sharedMainPath } = await prepareGeneratedApp();
1639
2270
  const result = await buildApp({
1640
2271
  entryPath: htmlPath,
1641
2272
  scriptEntryPath: mainPath,
2273
+ sharedEntryPath: sharedHtmlPath,
2274
+ sharedScriptEntryPath: sharedMainPath,
1642
2275
  manifestPath,
1643
2276
  outdir
1644
2277
  });
@@ -1651,7 +2284,7 @@ async function createCustomApp(options) {
1651
2284
  force: true,
1652
2285
  filter: (source) => {
1653
2286
  const resolvedSource = resolve3(source);
1654
- return resolvedSource !== join7(publicDir, "app.webmanifest") && resolvedSource !== join7(publicDir, "auth");
2287
+ return resolvedSource !== join7(publicDir, "app.webmanifest") && resolvedSource !== join7(publicDir, SHARED_APP_SHELL_FILE_NAME) && resolvedSource !== join7(publicDir, "auth");
1655
2288
  }
1656
2289
  });
1657
2290
  }
@@ -1662,14 +2295,24 @@ async function createCustomApp(options) {
1662
2295
  const port = startOptions.port ?? 3001;
1663
2296
  const outdir = resolve3(rootDir, startOptions.outdir ?? join7(".sixb", "dist", "app"));
1664
2297
  const indexPath = join7(outdir, "index.html");
2298
+ const sharedIndexPath = join7(outdir, SHARED_APP_SHELL_FILE_NAME);
1665
2299
  if (!await pathExists(indexPath)) {
1666
2300
  throw new Error(`[SixbCustomApp] No built app found in ${outdir}`);
1667
2301
  }
2302
+ if (!await pathExists(sharedIndexPath)) {
2303
+ throw new Error(`[SixbCustomApp] Built app in ${outdir} is missing ${SHARED_APP_SHELL_FILE_NAME}; rebuild required.`);
2304
+ }
1668
2305
  const indexHtml = injectRuntimeConfig(await Bun.file(indexPath).text(), {
1669
2306
  apiBaseUrl: startOptions.apiBaseUrl ?? apiBaseUrl,
1670
2307
  audience: startOptions.audience ?? audience,
1671
2308
  authEnabled: startOptions.authEnabled ?? authEnabled
1672
2309
  });
2310
+ const sharedIndexHtml = injectRuntimeConfig(await Bun.file(sharedIndexPath).text(), {
2311
+ apiBaseUrl: startOptions.apiBaseUrl ?? apiBaseUrl,
2312
+ audience: "app",
2313
+ authEnabled: false
2314
+ });
2315
+ const runtimeApiBaseUrl = startOptions.apiBaseUrl ?? apiBaseUrl;
1673
2316
  const server = Bun.serve({
1674
2317
  port,
1675
2318
  hostname: host,
@@ -1679,9 +2322,21 @@ async function createCustomApp(options) {
1679
2322
  if (isReservedSixbRoute(url.pathname)) {
1680
2323
  return notFoundResponse();
1681
2324
  }
2325
+ if (isFrameworkPrivateRoute(url.pathname)) {
2326
+ return notFoundResponse();
2327
+ }
1682
2328
  if (req.method !== "GET" && req.method !== "HEAD") {
1683
2329
  return notFoundResponse();
1684
2330
  }
2331
+ if (isSharedAppRoute(url.pathname)) {
2332
+ if (isAssetRequest(url.pathname)) {
2333
+ return notFoundResponse();
2334
+ }
2335
+ return sharedHtmlResponse(req, sharedIndexHtml, runtimeApiBaseUrl);
2336
+ }
2337
+ if (isSharedNamespace(url.pathname)) {
2338
+ return notFoundResponse();
2339
+ }
1685
2340
  if (url.pathname === "/" || url.pathname === "") {
1686
2341
  return htmlResponse(req, indexHtml);
1687
2342
  }
@@ -1759,16 +2414,33 @@ async function createPublicRoutes(publicDir) {
1759
2414
  const routes = {};
1760
2415
  for await (const filePath of files) {
1761
2416
  const routePath = `/${filePath.slice(publicDir.length + 1).split("\\").join("/")}`;
1762
- if (isReservedSixbRoute(routePath) || routePath === customAppManifestRoute) {
2417
+ if (isReservedSixbRoute(routePath) || isSharedNamespace(routePath) || isFrameworkPrivateRoute(routePath) || routePath === customAppManifestRoute) {
1763
2418
  continue;
1764
2419
  }
1765
2420
  routes[routePath] = getHeadRoute((request) => filePathResponse(request, filePath));
1766
2421
  }
1767
2422
  return routes;
1768
2423
  }
2424
+ function createGeneratedAssetRoutes(outputRoot, assetPaths) {
2425
+ const routes = {};
2426
+ for (const assetPath of assetPaths) {
2427
+ const relativePath = relative3(outputRoot, assetPath);
2428
+ if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
2429
+ throw new Error(`[SixbCustomApp] Shared development asset escaped its output directory.`);
2430
+ }
2431
+ const routePath = `/${relativePath.split("\\").join("/")}`;
2432
+ routes[routePath] = getHeadRoute((request) => fileResponse(request, Bun.file(assetPath), { "cache-control": "no-store" }));
2433
+ }
2434
+ return routes;
2435
+ }
1769
2436
  function reservedSixbRoutes() {
1770
2437
  const handler = () => notFoundResponse();
1771
2438
  return {
2439
+ [internalAppShellRoute]: allMethodsRoute(handler),
2440
+ [`${internalAppShellRoute}/*`]: allMethodsRoute(handler),
2441
+ [internalSharedAppShellRoute]: allMethodsRoute(handler),
2442
+ [`${internalSharedAppShellRoute}/*`]: allMethodsRoute(handler),
2443
+ [`/${SHARED_APP_SHELL_FILE_NAME}`]: allMethodsRoute(handler),
1772
2444
  "/api": allMethodsRoute(handler),
1773
2445
  "/api/*": allMethodsRoute(handler),
1774
2446
  "/auth": allMethodsRoute(handler),
@@ -1779,8 +2451,54 @@ function reservedSixbRoutes() {
1779
2451
  "/docs/*": allMethodsRoute(handler)
1780
2452
  };
1781
2453
  }
2454
+ function sharedAppDevRoutes(html, apiBaseUrl) {
2455
+ const reject = () => notFoundResponse();
2456
+ const guardedHandler = async (request) => {
2457
+ const pathname = new URL(request.url).pathname;
2458
+ if (!isSharedAppRoute(pathname) || isAssetRequest(pathname)) {
2459
+ return notFoundResponse();
2460
+ }
2461
+ return sharedHtmlResponse(request, await html(), apiBaseUrl);
2462
+ };
2463
+ return {
2464
+ "/shared": allMethodsRoute(reject),
2465
+ "/shared/*": {
2466
+ GET: guardedHandler,
2467
+ HEAD: guardedHandler,
2468
+ POST: reject,
2469
+ PUT: reject,
2470
+ PATCH: reject,
2471
+ DELETE: reject,
2472
+ OPTIONS: reject
2473
+ }
2474
+ };
2475
+ }
2476
+ function isSharedAppRoute(pathname) {
2477
+ return /^\/shared\/[^/]+(?:\/.*)?$/.test(pathname);
2478
+ }
2479
+ function isSharedNamespace(pathname) {
2480
+ const decoded = decodeRoutePathname(pathname);
2481
+ return decoded === "/shared" || decoded?.startsWith("/shared/") === true;
2482
+ }
2483
+ function isFrameworkPrivateRoute(pathname) {
2484
+ const decoded = decodeRoutePathname(pathname)?.toLowerCase();
2485
+ if (!decoded)
2486
+ return false;
2487
+ const sharedShellRoute = `/${SHARED_APP_SHELL_FILE_NAME}`;
2488
+ return decoded === sharedShellRoute || decoded.startsWith(`${sharedShellRoute}/`) || decoded === internalAppShellRoute || decoded.startsWith(`${internalAppShellRoute}/`) || decoded === internalSharedAppShellRoute || decoded.startsWith(`${internalSharedAppShellRoute}/`);
2489
+ }
2490
+ function decodeRoutePathname(pathname) {
2491
+ try {
2492
+ return decodeURIComponent(pathname).replaceAll("\\", "/");
2493
+ } catch {
2494
+ return null;
2495
+ }
2496
+ }
1782
2497
  function isReservedSixbRoute(pathname) {
1783
- return pathname === "/api" || pathname.startsWith("/api/") || pathname === "/auth" || pathname.startsWith("/auth/") || pathname === "/ws" || pathname.startsWith("/ws/") || pathname === "/docs" || pathname.startsWith("/docs/");
2498
+ const decoded = decodeRoutePathname(pathname);
2499
+ if (!decoded)
2500
+ return false;
2501
+ return decoded === "/api" || decoded.startsWith("/api/") || decoded === "/auth" || decoded.startsWith("/auth/") || decoded === "/ws" || decoded.startsWith("/ws/") || decoded === "/docs" || decoded.startsWith("/docs/");
1784
2502
  }
1785
2503
  var ASSET_EXTENSIONS = new Set([
1786
2504
  "js",
@@ -1871,7 +2589,51 @@ function htmlResponse(request, html) {
1871
2589
  }
1872
2590
  });
1873
2591
  }
1874
- var IMMUTABLE_ASSET_PATTERN = /^(?:(?:app|chunk)-[a-z0-9]+|(?:chunk|asset)-.+-[a-z0-9]+)\.[a-z0-9]+(?:\.map)?$/;
2592
+ function sharedHtmlResponse(request, html, apiBaseUrl) {
2593
+ const secured = secureSharedHtml(html, request, { apiBaseUrl });
2594
+ return new Response(request.method === "HEAD" ? null : secured.html, {
2595
+ headers: {
2596
+ "content-type": "text/html; charset=utf-8",
2597
+ ...secured.headers
2598
+ }
2599
+ });
2600
+ }
2601
+ function secureSharedHtml(html, request, options) {
2602
+ const nonce = randomBytes(18).toString("base64url");
2603
+ const requestOrigin = new URL(request.url).origin;
2604
+ let apiOrigin = requestOrigin;
2605
+ try {
2606
+ apiOrigin = new URL(options.apiBaseUrl ?? requestOrigin, requestOrigin).origin;
2607
+ } catch {}
2608
+ const connectSources = ["'self'", ...apiOrigin === requestOrigin ? [] : [apiOrigin]];
2609
+ const scriptSources = [`'nonce-${nonce}'`, "'strict-dynamic'", "'self'"];
2610
+ const contentSecurityPolicy = [
2611
+ "default-src 'none'",
2612
+ "base-uri 'none'",
2613
+ "object-src 'none'",
2614
+ "frame-ancestors 'none'",
2615
+ "form-action 'none'",
2616
+ `script-src ${scriptSources.join(" ")}`,
2617
+ "style-src 'self' 'unsafe-inline'",
2618
+ "img-src 'self' data: blob: https:",
2619
+ "font-src 'self' data: https:",
2620
+ `connect-src ${connectSources.join(" ")}`,
2621
+ "manifest-src 'none'"
2622
+ ].join("; ");
2623
+ return {
2624
+ html: html.replace(/<script(?![^>]*\snonce=)/g, `<script nonce="${nonce}"`),
2625
+ headers: {
2626
+ "cache-control": "no-store",
2627
+ "content-security-policy": contentSecurityPolicy,
2628
+ "permissions-policy": "camera=(), geolocation=(), microphone=(), payment=(), usb=(), browsing-topics=()",
2629
+ "referrer-policy": "no-referrer",
2630
+ "x-content-type-options": "nosniff",
2631
+ "x-frame-options": "DENY",
2632
+ "x-robots-tag": "noindex, nofollow, noarchive"
2633
+ }
2634
+ };
2635
+ }
2636
+ var IMMUTABLE_ASSET_PATTERN = /^(?:(?:app|shared|chunk)-[a-z0-9]+|(?:chunk|asset)-.+-[a-z0-9]+)\.[a-z0-9]+(?:\.map)?$/;
1875
2637
  function staticAssetHeaders(pathname) {
1876
2638
  if (pathname === customAppManifestRoute) {
1877
2639
  return {
@@ -1990,13 +2752,16 @@ function devServerInternalOrigin(host, port) {
1990
2752
  const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
1991
2753
  return `http://${urlHost}:${port}`;
1992
2754
  }
1993
- function spaHtmlRoute(internalOrigin) {
2755
+ function spaHtmlRoute(internalOrigin, options = {}) {
1994
2756
  return getHeadRoute(async (request) => {
1995
2757
  const publicUrl = new URL(request.url);
2758
+ if (isReservedSixbRoute(publicUrl.pathname) || isSharedNamespace(publicUrl.pathname) || isFrameworkPrivateRoute(publicUrl.pathname)) {
2759
+ return notFoundResponse();
2760
+ }
1996
2761
  if (publicUrl.pathname !== "/" && isAssetRequest(publicUrl.pathname)) {
1997
2762
  return notFoundResponse();
1998
2763
  }
1999
- const url = new URL(internalAppShellRoute, internalOrigin());
2764
+ const url = new URL(options.shellRoute ?? internalAppShellRoute, internalOrigin());
2000
2765
  url.search = publicUrl.search;
2001
2766
  const requestHeaders = new Headers(request.headers);
2002
2767
  for (const header of [
@@ -2019,7 +2784,8 @@ function spaHtmlRoute(internalOrigin) {
2019
2784
  headers: responseHeaders
2020
2785
  });
2021
2786
  }
2022
- return new Response(restoreAppStaticUrls(await bundleResponse.text()), {
2787
+ const html = restoreAppStaticUrls(await bundleResponse.text()).replace("</head>", '<script src="/__sixb/dev-reload.js"></script></head>');
2788
+ return new Response(html, {
2023
2789
  status: bundleResponse.status,
2024
2790
  statusText: bundleResponse.statusText,
2025
2791
  headers: responseHeaders
@@ -2027,8 +2793,9 @@ function spaHtmlRoute(internalOrigin) {
2027
2793
  });
2028
2794
  }
2029
2795
  export {
2796
+ devReloadResponse,
2030
2797
  createTailwindCssCompiler,
2031
2798
  createCustomApp
2032
2799
  };
2033
2800
 
2034
- //# debugId=66AA128AADD55E1164756E2164756E21
2801
+ //# debugId=C0D77337A7C1A9D464756E2164756E21