@sixb/app 0.1.2 → 0.1.4

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/src/codegen.ts CHANGED
@@ -4,7 +4,7 @@ import type { AuthSessionAudience } from "@sixb/core"
4
4
  import { renderAppManifest } from "./manifest"
5
5
  import { resolveAppMetadata } from "./metadata"
6
6
  import { renderCustomAppRuntimeScript } from "./runtime"
7
- import type { PageRoute } from "./scanner"
7
+ import { type AppRouteLayout, type PageRoute, routePatternKey } from "./scanner"
8
8
 
9
9
  export interface BuiltInRouteManifestEntry {
10
10
  readonly path: string
@@ -14,28 +14,35 @@ export interface BuiltInRouteManifestEntry {
14
14
 
15
15
  export interface GenerateRouteManifestOptions {
16
16
  readonly builtInRoutes?: readonly BuiltInRouteManifestEntry[]
17
+ readonly layouts?: readonly AppRouteLayout[]
17
18
  }
18
19
 
20
+ export const AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER = "__SIXB_AUTH_BOOTSTRAP__"
21
+
19
22
  /**
20
- * Generates `.sixb/generated/routes.ts` with static route imports. Pages are
23
+ * Generates `.sixb/generated/routes.ts` with static page/layout imports. Modules are
21
24
  * eager on purpose: project-specific apps bundle small, and a single bundle
22
25
  * (one JS file, one render-blocking CSS file) means no Suspense gap or
23
26
  * late-arriving styles when navigating — matching how Atlas routes.
24
27
  */
25
28
  export async function generateRouteManifest(
26
- routes: PageRoute[],
29
+ routes: readonly PageRoute[],
27
30
  generatedDir: string,
28
31
  options: GenerateRouteManifestOptions = {}
29
32
  ): Promise<string> {
30
33
  await mkdir(generatedDir, { recursive: true })
31
34
 
32
- const imports = routes
35
+ const pages = [...routes].sort(compareRouteModules)
36
+ const pageImports = pages
33
37
  .map((route, index) => {
34
38
  const rel = relativeTo(generatedDir, route.filePath)
35
39
  return `import Page${index} from ${JSON.stringify(rel)}`
36
40
  })
37
41
  .join("\n")
38
- const builtInRoutes = options.builtInRoutes ?? []
42
+ const projectRoutePatterns = new Set(pages.map((route) => routePatternKey(route.path)))
43
+ const builtInRoutes = (options.builtInRoutes ?? []).filter(
44
+ (route) => !projectRoutePatterns.has(routePatternKey(route.path))
45
+ )
39
46
  const builtInImports = builtInRoutes
40
47
  .map((route, index) => {
41
48
  if (route.exportName) {
@@ -45,23 +52,61 @@ export async function generateRouteManifest(
45
52
  return `import BuiltInPage${index} from ${JSON.stringify(route.moduleSpecifier)}`
46
53
  })
47
54
  .join("\n")
48
-
49
- const entries = routes
50
- .map((route, index) => ` { path: ${JSON.stringify(route.path)}, component: Page${index} },`)
55
+ const routePatterns = [...pages, ...builtInRoutes].map((route) => routePatternKey(route.path))
56
+ const layouts = [...(options.layouts ?? [])]
57
+ .filter((layout) => {
58
+ const layoutPattern = routePatternKey(layout.path)
59
+ return routePatterns.some(
60
+ (routePattern) =>
61
+ routePattern === layoutPattern || routePattern.startsWith(`${layoutPattern}/`)
62
+ )
63
+ })
64
+ .sort(compareRouteModules)
65
+ const layoutImports = layouts
66
+ .map((layout, index) => {
67
+ const rel = relativeTo(generatedDir, layout.filePath)
68
+ return `import Layout${index} from ${JSON.stringify(rel)}`
69
+ })
51
70
  .join("\n")
52
- const builtInEntries = builtInRoutes
53
- .map(
54
- (route, index) => ` { path: ${JSON.stringify(route.path)}, component: BuiltInPage${index} },`
71
+
72
+ const tree = createRouteTree()
73
+ for (const [index, layout] of layouts.entries()) {
74
+ insertRouteLayout(tree, layout, `Layout${index}`)
75
+ }
76
+ for (const [index, route] of pages.entries()) {
77
+ insertRoutePage(tree, route.path, `Page${index}`, route.relativePath)
78
+ }
79
+ for (const [index, route] of builtInRoutes.entries()) {
80
+ insertRoutePage(
81
+ tree,
82
+ route.path,
83
+ `BuiltInPage${index}`,
84
+ `${route.moduleSpecifier} (${route.path})`
55
85
  )
56
- .join("\n")
57
- const routeEntries = [entries, builtInEntries].filter(Boolean).join("\n")
58
- const importEntries = [imports, builtInImports].filter(Boolean).join("\n")
86
+ }
59
87
 
88
+ const importEntries = [
89
+ 'import { createElement } from "react"',
90
+ layouts.length > 0
91
+ ? 'import { Outlet, type RouteObject } from "react-router-dom"'
92
+ : 'import type { RouteObject } from "react-router-dom"',
93
+ pageImports,
94
+ builtInImports,
95
+ layoutImports,
96
+ ]
97
+ .filter(Boolean)
98
+ .join("\n")
99
+ const routePaths = [
100
+ ...pages.map((route) => route.path),
101
+ ...builtInRoutes.map((route) => route.path),
102
+ ]
60
103
  const content = `${importEntries}
61
104
 
105
+ export const routePaths = ${JSON.stringify(routePaths, null, 2)} as const
106
+
62
107
  export const routes = [
63
- ${routeEntries}
64
- ]
108
+ ${renderRootRouteObjects(tree)}
109
+ ] satisfies RouteObject[]
65
110
  `
66
111
 
67
112
  const outPath = join(generatedDir, "routes.ts")
@@ -69,6 +114,301 @@ ${routeEntries}
69
114
  return outPath
70
115
  }
71
116
 
117
+ interface RouteTreePage {
118
+ readonly componentName: string
119
+ readonly source: string
120
+ }
121
+
122
+ interface RouteTreeLayout {
123
+ readonly componentName: string
124
+ readonly source: string
125
+ }
126
+
127
+ interface RouteTreeNode {
128
+ readonly segment: string
129
+ readonly children: Map<string, RouteTreeNode>
130
+ page?: RouteTreePage
131
+ layout?: RouteTreeLayout
132
+ }
133
+
134
+ function createRouteTree(segment = ""): RouteTreeNode {
135
+ return { segment, children: new Map() }
136
+ }
137
+
138
+ function insertRouteLayout(
139
+ root: RouteTreeNode,
140
+ layout: AppRouteLayout,
141
+ componentName: string
142
+ ): void {
143
+ if (layout.path === "/") {
144
+ throw new Error(
145
+ `[SixbCustomApp] Root layout ${layout.relativePath} must remain the global app wrapper.`
146
+ )
147
+ }
148
+ const node = resolveRouteNode(root, layout.path, layout.relativePath)
149
+ if (node.layout) {
150
+ throw new Error(
151
+ `[SixbCustomApp] Conflicting layouts '${node.layout.source}' and '${layout.relativePath}' own route '${layout.path}'.`
152
+ )
153
+ }
154
+ node.layout = { componentName, source: layout.relativePath }
155
+ }
156
+
157
+ function insertRoutePage(
158
+ root: RouteTreeNode,
159
+ path: string,
160
+ componentName: string,
161
+ source: string
162
+ ): void {
163
+ const node = resolveRouteNode(root, path, source)
164
+ if (node.page) {
165
+ throw new Error(
166
+ `[SixbCustomApp] Conflicting pages '${node.page.source}' and '${source}' match route '${path}'.`
167
+ )
168
+ }
169
+ node.page = { componentName, source }
170
+ }
171
+
172
+ function resolveRouteNode(root: RouteTreeNode, path: string, source: string): RouteTreeNode {
173
+ let node = root
174
+ for (const segment of splitRoutePath(path)) {
175
+ const key = segment.startsWith(":") ? ":" : segment.toLowerCase()
176
+ const existing = node.children.get(key)
177
+ if (existing) {
178
+ if (
179
+ existing.segment.startsWith(":") &&
180
+ segment.startsWith(":") &&
181
+ existing.segment !== segment
182
+ ) {
183
+ throw new Error(
184
+ `[SixbCustomApp] Route '${source}' uses dynamic segment '${segment}', but '${existing.segment}' already owns the same route position. Use one parameter name consistently.`
185
+ )
186
+ }
187
+ node = existing
188
+ continue
189
+ }
190
+
191
+ const child = createRouteTree(segment)
192
+ node.children.set(key, child)
193
+ node = child
194
+ }
195
+ return node
196
+ }
197
+
198
+ function renderRootRouteObjects(root: RouteTreeNode): string {
199
+ const lines: string[] = []
200
+ if (root.page) {
201
+ lines.push(` { path: "/", element: createElement(${root.page.componentName}) },`)
202
+ }
203
+ for (const child of sortedRenderableChildren(root)) {
204
+ lines.push(...renderRouteNode(child, 1))
205
+ }
206
+ return lines.join("\n")
207
+ }
208
+
209
+ function renderRouteNode(node: RouteTreeNode, depth: number): string[] {
210
+ const indent = " ".repeat(depth)
211
+ const children = sortedRenderableChildren(node)
212
+ if (!node.layout && node.page && children.length === 0) {
213
+ return [
214
+ `${indent}{ path: ${JSON.stringify(node.segment)}, element: createElement(${node.page.componentName}) },`,
215
+ ]
216
+ }
217
+
218
+ const lines = [`${indent}{`, `${indent} path: ${JSON.stringify(node.segment)},`]
219
+ if (node.layout) {
220
+ lines.push(
221
+ `${indent} element: createElement(${node.layout.componentName}, { children: createElement(Outlet) }),`
222
+ )
223
+ }
224
+ lines.push(`${indent} children: [`)
225
+ if (node.page) {
226
+ lines.push(`${indent} { index: true, element: createElement(${node.page.componentName}) },`)
227
+ }
228
+ for (const child of children) {
229
+ lines.push(...renderRouteNode(child, depth + 2))
230
+ }
231
+ lines.push(`${indent} ],`, `${indent}},`)
232
+ return lines
233
+ }
234
+
235
+ function sortedRenderableChildren(node: RouteTreeNode): RouteTreeNode[] {
236
+ return [...node.children.values()].filter(hasPageDescendant).sort((a, b) => {
237
+ const aDynamic = a.segment.startsWith(":")
238
+ const bDynamic = b.segment.startsWith(":")
239
+ if (aDynamic !== bDynamic) return aDynamic ? 1 : -1
240
+ return compareText(a.segment, b.segment)
241
+ })
242
+ }
243
+
244
+ function hasPageDescendant(node: RouteTreeNode): boolean {
245
+ if (node.page) return true
246
+ for (const child of node.children.values()) {
247
+ if (hasPageDescendant(child)) return true
248
+ }
249
+ return false
250
+ }
251
+
252
+ function splitRoutePath(path: string): string[] {
253
+ if (path === "/") return []
254
+ if (!path.startsWith("/")) {
255
+ throw new Error(`[SixbCustomApp] Route path '${path}' must start with '/'.`)
256
+ }
257
+ const segments = path.slice(1).split("/")
258
+ if (segments.some((segment) => !segment)) {
259
+ throw new Error(`[SixbCustomApp] Route path '${path}' contains an empty segment.`)
260
+ }
261
+ return segments
262
+ }
263
+
264
+ function compareRouteModules(
265
+ a: Pick<AppRouteLayout, "path" | "relativePath">,
266
+ b: Pick<AppRouteLayout, "path" | "relativePath">
267
+ ): number {
268
+ return compareText(a.path, b.path) || compareText(a.relativePath, b.relativePath)
269
+ }
270
+
271
+ function compareText(a: string, b: string): number {
272
+ return a < b ? -1 : a > b ? 1 : 0
273
+ }
274
+
275
+ /** Generates the optional browser entry served by the API for `/auth/*`. */
276
+ export async function generateAuthExperienceEntry(
277
+ projectRoot: string,
278
+ generatedDir: string,
279
+ options: {
280
+ readonly appDir?: string
281
+ readonly publicDir?: string
282
+ readonly stylesheetPath?: string | null
283
+ } = {}
284
+ ): Promise<{ readonly htmlPath: string; readonly mainPath: string } | null> {
285
+ await mkdir(generatedDir, { recursive: true })
286
+
287
+ const appDir = options.appDir ? resolve(projectRoot, options.appDir) : join(projectRoot, "app")
288
+ const authPath = join(appDir, "auth.tsx")
289
+ if (!(await fileExists(authPath))) {
290
+ return null
291
+ }
292
+
293
+ const publicDir = options.publicDir
294
+ ? resolve(projectRoot, options.publicDir)
295
+ : join(appDir, "public")
296
+ const layoutPath = join(appDir, "layout.tsx")
297
+ const globalsCssPath = join(appDir, "globals.css")
298
+ const metadata = await resolveAppMetadata({ layoutPath, publicDir })
299
+ const stylesheetPath =
300
+ options.stylesheetPath !== undefined
301
+ ? options.stylesheetPath
302
+ : (await fileExists(globalsCssPath))
303
+ ? globalsCssPath
304
+ : null
305
+ const stylesheetImport = stylesheetPath
306
+ ? `import ${JSON.stringify(relativeTo(generatedDir, stylesheetPath))}`
307
+ : ""
308
+ const authRel = relativeTo(generatedDir, authPath)
309
+
310
+ const mainContent = `import React from "react"
311
+ import { createRoot } from "react-dom/client"
312
+ import type {
313
+ AuthExperienceActions,
314
+ AuthExperienceState,
315
+ } from "@sixb/app/auth"
316
+ import AuthExperience from ${JSON.stringify(authRel)}
317
+ ${stylesheetImport}
318
+
319
+ interface AuthExperienceBootstrap {
320
+ readonly state: AuthExperienceState
321
+ readonly signInUrl: string
322
+ readonly submission?: {
323
+ readonly kind: "requestMagicLink" | "confirmSignIn"
324
+ readonly action: string
325
+ readonly fields: Readonly<Record<string, string>>
326
+ }
327
+ }
328
+
329
+ const root = document.getElementById("root")
330
+ if (!root) {
331
+ throw new Error("[SixbApp] Could not find the auth experience root element.")
332
+ }
333
+
334
+ const encodedBootstrap = root.dataset.sixbAuth
335
+ if (!encodedBootstrap) {
336
+ throw new Error("[SixbApp] Auth experience bootstrap is missing.")
337
+ }
338
+
339
+ const bootstrap = decodeBootstrap(encodedBootstrap)
340
+ const actions: AuthExperienceActions = {
341
+ requestMagicLink(email) {
342
+ submit("requestMagicLink", { email })
343
+ },
344
+ confirmSignIn() {
345
+ submit("confirmSignIn")
346
+ },
347
+ restartSignIn() {
348
+ window.location.assign(bootstrap.signInUrl)
349
+ },
350
+ }
351
+
352
+ function submit(
353
+ kind: NonNullable<AuthExperienceBootstrap["submission"]>["kind"],
354
+ additionalFields: Readonly<Record<string, string>> = {}
355
+ ): void {
356
+ const submission = bootstrap.submission
357
+ if (!submission || submission.kind !== kind) {
358
+ throw new Error("[SixbApp] Auth action '" + kind + "' is not available in this state.")
359
+ }
360
+
361
+ const form = document.createElement("form")
362
+ form.method = "post"
363
+ form.action = submission.action
364
+ form.hidden = true
365
+ for (const [name, value] of Object.entries({ ...submission.fields, ...additionalFields })) {
366
+ const input = document.createElement("input")
367
+ input.type = "hidden"
368
+ input.name = name
369
+ input.value = value
370
+ form.append(input)
371
+ }
372
+ document.body.append(form)
373
+ form.submit()
374
+ }
375
+
376
+ function decodeBootstrap(value: string): AuthExperienceBootstrap {
377
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/")
378
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")
379
+ const bytes = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0))
380
+ return JSON.parse(new TextDecoder().decode(bytes)) as AuthExperienceBootstrap
381
+ }
382
+
383
+ createRoot(root).render(<AuthExperience state={bootstrap.state} actions={actions} />)
384
+ `
385
+
386
+ const mainPath = join(generatedDir, "auth-main.tsx")
387
+ await writeFileIfChanged(mainPath, mainContent)
388
+
389
+ const htmlContent = `<!DOCTYPE html>
390
+ <html lang="en">
391
+ <head>
392
+ <meta charset="UTF-8" />
393
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
394
+ ${renderAuthMetadataHead(metadata)}
395
+ <style>
396
+ * { box-sizing: border-box; }
397
+ html, body, #root { margin: 0; min-height: 100%; }
398
+ body, #root { min-height: 100vh; min-height: 100dvh; }
399
+ </style>
400
+ </head>
401
+ <body>
402
+ <div id="root" data-sixb-auth="${AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER}"></div>
403
+ <script type="module" src="./auth-main.tsx"></script>
404
+ </body>
405
+ </html>
406
+ `
407
+ const htmlPath = join(generatedDir, "auth-index.html")
408
+ await writeFileIfChanged(htmlPath, htmlContent)
409
+ return { htmlPath, mainPath }
410
+ }
411
+
72
412
  /**
73
413
  * Generates the app entry files:
74
414
  * - `.sixb/generated/index.html` — HTML shell
@@ -134,7 +474,13 @@ export async function generateAppEntry(
134
474
  const mainContent = `import React from "react"
135
475
  import { createRoot, type Root } from "react-dom/client"
136
476
  import { signOut } from "@sixb/client"
137
- import { BrowserRouter, Routes, Route, matchPath, useNavigate, useLocation } from "react-router-dom"
477
+ import {
478
+ BrowserRouter,
479
+ matchPath,
480
+ useLocation,
481
+ useNavigate,
482
+ useRoutes,
483
+ } from "react-router-dom"
138
484
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
139
485
  import {
140
486
  configureSixbBrowserClient,
@@ -142,7 +488,7 @@ import {
142
488
  readSixbBrowserRuntimeConfig,
143
489
  requireSixbBrowserAuthSession,
144
490
  } from "@sixb/client/browser"
145
- import { routes } from "./routes"
491
+ import { routePaths, routes } from "./routes"
146
492
  ${globalsCssImport}
147
493
  ${layoutImport}
148
494
 
@@ -242,7 +588,7 @@ function InternalLinkInterceptor() {
242
588
  if (isReservedPath(url.pathname)) return
243
589
  // Only intercept destinations the app actually routes; anything else may
244
590
  // be a real server resource and keeps native navigation.
245
- if (!routes.some((route) => matchPath(route.path, url.pathname))) return
591
+ if (!routePaths.some((path) => matchPath(path, url.pathname))) return
246
592
  // Same-document hash links keep native scroll behavior.
247
593
  if (
248
594
  url.hash &&
@@ -446,6 +792,12 @@ function RoutedErrorBoundary({ children }: { children: React.ReactNode }) {
446
792
  )
447
793
  }
448
794
 
795
+ const appRoutes = [...routes, { path: "*", element: <NotFoundView /> }]
796
+
797
+ function AppRoutes() {
798
+ return useRoutes(appRoutes)
799
+ }
800
+
449
801
  function App() {
450
802
  return (
451
803
  <QueryClientProvider client={queryClient}>
@@ -453,12 +805,7 @@ function App() {
453
805
  <InternalLinkInterceptor />
454
806
  <RoutedErrorBoundary>
455
807
  ${layoutWrapperStart}
456
- <Routes>
457
- {routes.map((route) => (
458
- <Route key={route.path} path={route.path} element={<route.component />} />
459
- ))}
460
- <Route path="*" element={<NotFoundView />} />
461
- </Routes>
808
+ <AppRoutes />
462
809
  ${layoutWrapperEnd}
463
810
  </RoutedErrorBoundary>
464
811
  </BrowserRouter>
@@ -540,6 +887,20 @@ function renderMetadataHead(metadata: Awaited<ReturnType<typeof resolveAppMetada
540
887
  return tags.join("\n")
541
888
  }
542
889
 
890
+ function renderAuthMetadataHead(metadata: Awaited<ReturnType<typeof resolveAppMetadata>>): string {
891
+ const tags = [
892
+ ` <title>${escapeHtmlText(metadata.title)}</title>`,
893
+ ...(metadata.description
894
+ ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`]
895
+ : []),
896
+ ` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`,
897
+ ...(metadata.favicon && /^(?:https?:|data:)/.test(metadata.favicon)
898
+ ? [` <link rel="icon" href="${escapeHtmlAttribute(metadata.favicon)}" />`]
899
+ : []),
900
+ ]
901
+ return tags.join("\n")
902
+ }
903
+
543
904
  function escapeHtmlText(value: string): string {
544
905
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
545
906
  }