@sixb/app 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/build.ts CHANGED
@@ -30,6 +30,15 @@ export interface BuildAppResult {
30
30
  logs?: string[]
31
31
  }
32
32
 
33
+ export interface BuildAuthExperienceOptions {
34
+ /** Generated HTML shell containing the auth bootstrap placeholder. */
35
+ entryPath: string
36
+ /** Browser TypeScript entry generated alongside `entryPath`. */
37
+ scriptEntryPath: string
38
+ /** Directory written for the API server to mount under `/auth`. */
39
+ outdir: string
40
+ }
41
+
33
42
  /**
34
43
  * Builds the generated browser entry and writes a production-ready static shell and bundle.
35
44
  */
@@ -110,6 +119,74 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
110
119
  return { success: true, outdir }
111
120
  }
112
121
 
122
+ /** Builds the optional custom auth entry as API-served static assets. */
123
+ export async function buildAuthExperience(
124
+ options: BuildAuthExperienceOptions
125
+ ): Promise<BuildAppResult> {
126
+ const outdir = resolve(options.outdir)
127
+ const assetsDir = join(outdir, "assets")
128
+ await rm(outdir, { recursive: true, force: true })
129
+ await mkdir(assetsDir, { recursive: true })
130
+
131
+ const result = await Bun.build({
132
+ entrypoints: [options.scriptEntryPath],
133
+ outdir: assetsDir,
134
+ target: "browser",
135
+ conditions: ["bun"],
136
+ publicPath: "/auth/assets/",
137
+ minify: true,
138
+ splitting: true,
139
+ naming: {
140
+ entry: "auth-[hash].[ext]",
141
+ chunk: "chunk-[name]-[hash].[ext]",
142
+ asset: "asset-[name]-[hash].[ext]",
143
+ },
144
+ plugins: [extensionlessSourceImportPlugin],
145
+ define: { "process.env.NODE_ENV": '"production"' },
146
+ sourcemap: "external",
147
+ })
148
+
149
+ if (!result.success) {
150
+ return {
151
+ success: false,
152
+ outdir,
153
+ logs: result.logs.map(String),
154
+ }
155
+ }
156
+
157
+ const script = result.outputs.find(
158
+ (output) => output.kind === "entry-point" && output.type.startsWith("text/javascript")
159
+ )
160
+ const stylesheets = result.outputs.filter((output) => output.type.startsWith("text/css"))
161
+ if (!script || stylesheets.length > 1) {
162
+ throw new Error(
163
+ `[SixbCustomApp] Expected one auth entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`
164
+ )
165
+ }
166
+
167
+ const sourceHtml = await readFile(options.entryPath, "utf-8")
168
+ const sourceEntryPattern =
169
+ /\s*<script\s+type=["']module["']\s+src=["']\.\/auth-main\.tsx["']><\/script>/
170
+ if (!sourceEntryPattern.test(sourceHtml)) {
171
+ throw new Error("[SixbCustomApp] Generated auth shell is missing its ./auth-main.tsx entry.")
172
+ }
173
+
174
+ const assetTags = [
175
+ ...stylesheets.map(
176
+ (stylesheet) =>
177
+ `<link rel="stylesheet" crossorigin href="/auth/assets/${basename(stylesheet.path)}">`
178
+ ),
179
+ `<script type="module" crossorigin src="/auth/assets/${basename(script.path)}"></script>`,
180
+ ].join("")
181
+ const html = sourceHtml
182
+ .replace(sourceEntryPattern, "")
183
+ .replace("</head>", ` ${assetTags}</head>`)
184
+ await writeFile(join(outdir, "index.html"), html, "utf-8")
185
+ await precompressBuildAssets(result.outputs)
186
+
187
+ return { success: true, outdir }
188
+ }
189
+
113
190
  // Bun's HTML bundler currently tries to resolve root-relative link assets from
114
191
  // the filesystem root. A temporary external origin keeps these stable URLs out
115
192
  // of the asset graph; dev responses and production output restore the originals.
package/src/codegen.ts CHANGED
@@ -16,6 +16,8 @@ export interface GenerateRouteManifestOptions {
16
16
  readonly builtInRoutes?: readonly BuiltInRouteManifestEntry[]
17
17
  }
18
18
 
19
+ export const AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER = "__SIXB_AUTH_BOOTSTRAP__"
20
+
19
21
  /**
20
22
  * Generates `.sixb/generated/routes.ts` with static route imports. Pages are
21
23
  * eager on purpose: project-specific apps bundle small, and a single bundle
@@ -69,6 +71,143 @@ ${routeEntries}
69
71
  return outPath
70
72
  }
71
73
 
74
+ /** Generates the optional browser entry served by the API for `/auth/*`. */
75
+ export async function generateAuthExperienceEntry(
76
+ projectRoot: string,
77
+ generatedDir: string,
78
+ options: {
79
+ readonly appDir?: string
80
+ readonly publicDir?: string
81
+ readonly stylesheetPath?: string | null
82
+ } = {}
83
+ ): Promise<{ readonly htmlPath: string; readonly mainPath: string } | null> {
84
+ await mkdir(generatedDir, { recursive: true })
85
+
86
+ const appDir = options.appDir ? resolve(projectRoot, options.appDir) : join(projectRoot, "app")
87
+ const authPath = join(appDir, "auth.tsx")
88
+ if (!(await fileExists(authPath))) {
89
+ return null
90
+ }
91
+
92
+ const publicDir = options.publicDir
93
+ ? resolve(projectRoot, options.publicDir)
94
+ : join(appDir, "public")
95
+ const layoutPath = join(appDir, "layout.tsx")
96
+ const globalsCssPath = join(appDir, "globals.css")
97
+ const metadata = await resolveAppMetadata({ layoutPath, publicDir })
98
+ const stylesheetPath =
99
+ options.stylesheetPath !== undefined
100
+ ? options.stylesheetPath
101
+ : (await fileExists(globalsCssPath))
102
+ ? globalsCssPath
103
+ : null
104
+ const stylesheetImport = stylesheetPath
105
+ ? `import ${JSON.stringify(relativeTo(generatedDir, stylesheetPath))}`
106
+ : ""
107
+ const authRel = relativeTo(generatedDir, authPath)
108
+
109
+ const mainContent = `import React from "react"
110
+ import { createRoot } from "react-dom/client"
111
+ import type {
112
+ AuthExperienceActions,
113
+ AuthExperienceState,
114
+ } from "@sixb/app/auth"
115
+ import AuthExperience from ${JSON.stringify(authRel)}
116
+ ${stylesheetImport}
117
+
118
+ interface AuthExperienceBootstrap {
119
+ readonly state: AuthExperienceState
120
+ readonly signInUrl: string
121
+ readonly submission?: {
122
+ readonly kind: "requestMagicLink" | "confirmSignIn"
123
+ readonly action: string
124
+ readonly fields: Readonly<Record<string, string>>
125
+ }
126
+ }
127
+
128
+ const root = document.getElementById("root")
129
+ if (!root) {
130
+ throw new Error("[SixbApp] Could not find the auth experience root element.")
131
+ }
132
+
133
+ const encodedBootstrap = root.dataset.sixbAuth
134
+ if (!encodedBootstrap) {
135
+ throw new Error("[SixbApp] Auth experience bootstrap is missing.")
136
+ }
137
+
138
+ const bootstrap = decodeBootstrap(encodedBootstrap)
139
+ const actions: AuthExperienceActions = {
140
+ requestMagicLink(email) {
141
+ submit("requestMagicLink", { email })
142
+ },
143
+ confirmSignIn() {
144
+ submit("confirmSignIn")
145
+ },
146
+ restartSignIn() {
147
+ window.location.assign(bootstrap.signInUrl)
148
+ },
149
+ }
150
+
151
+ function submit(
152
+ kind: NonNullable<AuthExperienceBootstrap["submission"]>["kind"],
153
+ additionalFields: Readonly<Record<string, string>> = {}
154
+ ): void {
155
+ const submission = bootstrap.submission
156
+ if (!submission || submission.kind !== kind) {
157
+ throw new Error("[SixbApp] Auth action '" + kind + "' is not available in this state.")
158
+ }
159
+
160
+ const form = document.createElement("form")
161
+ form.method = "post"
162
+ form.action = submission.action
163
+ form.hidden = true
164
+ for (const [name, value] of Object.entries({ ...submission.fields, ...additionalFields })) {
165
+ const input = document.createElement("input")
166
+ input.type = "hidden"
167
+ input.name = name
168
+ input.value = value
169
+ form.append(input)
170
+ }
171
+ document.body.append(form)
172
+ form.submit()
173
+ }
174
+
175
+ function decodeBootstrap(value: string): AuthExperienceBootstrap {
176
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/")
177
+ const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=")
178
+ const bytes = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0))
179
+ return JSON.parse(new TextDecoder().decode(bytes)) as AuthExperienceBootstrap
180
+ }
181
+
182
+ createRoot(root).render(<AuthExperience state={bootstrap.state} actions={actions} />)
183
+ `
184
+
185
+ const mainPath = join(generatedDir, "auth-main.tsx")
186
+ await writeFileIfChanged(mainPath, mainContent)
187
+
188
+ const htmlContent = `<!DOCTYPE html>
189
+ <html lang="en">
190
+ <head>
191
+ <meta charset="UTF-8" />
192
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
193
+ ${renderAuthMetadataHead(metadata)}
194
+ <style>
195
+ * { box-sizing: border-box; }
196
+ html, body, #root { margin: 0; min-height: 100%; }
197
+ body, #root { min-height: 100vh; min-height: 100dvh; }
198
+ </style>
199
+ </head>
200
+ <body>
201
+ <div id="root" data-sixb-auth="${AUTH_EXPERIENCE_BOOTSTRAP_PLACEHOLDER}"></div>
202
+ <script type="module" src="./auth-main.tsx"></script>
203
+ </body>
204
+ </html>
205
+ `
206
+ const htmlPath = join(generatedDir, "auth-index.html")
207
+ await writeFileIfChanged(htmlPath, htmlContent)
208
+ return { htmlPath, mainPath }
209
+ }
210
+
72
211
  /**
73
212
  * Generates the app entry files:
74
213
  * - `.sixb/generated/index.html` — HTML shell
@@ -540,6 +679,20 @@ function renderMetadataHead(metadata: Awaited<ReturnType<typeof resolveAppMetada
540
679
  return tags.join("\n")
541
680
  }
542
681
 
682
+ function renderAuthMetadataHead(metadata: Awaited<ReturnType<typeof resolveAppMetadata>>): string {
683
+ const tags = [
684
+ ` <title>${escapeHtmlText(metadata.title)}</title>`,
685
+ ...(metadata.description
686
+ ? [` <meta name="description" content="${escapeHtmlAttribute(metadata.description)}" />`]
687
+ : []),
688
+ ` <meta name="theme-color" content="${escapeHtmlAttribute(metadata.themeColor)}" />`,
689
+ ...(metadata.favicon && /^(?:https?:|data:)/.test(metadata.favicon)
690
+ ? [` <link rel="icon" href="${escapeHtmlAttribute(metadata.favicon)}" />`]
691
+ : []),
692
+ ]
693
+ return tags.join("\n")
694
+ }
695
+
543
696
  function escapeHtmlText(value: string): string {
544
697
  return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
545
698
  }
@@ -1,15 +1,21 @@
1
1
  import { watch } from "node:fs"
2
- import { access, cp, mkdir, readFile, writeFile } from "node:fs/promises"
2
+ import { access, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"
3
3
  import { dirname, isAbsolute, join, normalize, relative, resolve } from "node:path"
4
4
  import { pathToFileURL } from "node:url"
5
5
  import type { AuthSessionAudience } from "@sixb/core"
6
6
  import {
7
7
  type BuildAppResult,
8
8
  buildApp,
9
+ buildAuthExperience,
9
10
  prepareAppHtmlBundleEntry,
10
11
  restoreAppStaticUrls,
11
12
  } from "./build"
12
- import { type BuiltInRouteManifestEntry, generateAppEntry, generateRouteManifest } from "./codegen"
13
+ import {
14
+ type BuiltInRouteManifestEntry,
15
+ generateAppEntry,
16
+ generateAuthExperienceEntry,
17
+ generateRouteManifest,
18
+ } from "./codegen"
13
19
  import { renderCustomAppRuntimeScript } from "./runtime"
14
20
  import { type PageRoute, scanPages } from "./scanner"
15
21
  import { type CustomAppStylesheet, resolveCustomAppStylesheet } from "./styles"
@@ -35,6 +41,14 @@ export interface CustomAppBuildOptions {
35
41
  outdir?: string
36
42
  }
37
43
 
44
+ export interface CustomAuthExperienceBuildOptions {
45
+ outdir?: string
46
+ }
47
+
48
+ export interface CustomAuthExperienceBuildResult {
49
+ readonly outdir: string
50
+ }
51
+
38
52
  export interface CustomAppStartOptions {
39
53
  host?: string
40
54
  port?: number
@@ -54,6 +68,9 @@ export interface CustomAppDevServer {
54
68
  export interface CustomAppInstance {
55
69
  scanRoutes(): Promise<PageRoute[]>
56
70
  hasRoutes(): Promise<boolean>
71
+ prepareAuthExperience(
72
+ options?: CustomAuthExperienceBuildOptions
73
+ ): Promise<CustomAuthExperienceBuildResult | null>
57
74
  dev(options?: CustomAppDevOptions): Promise<CustomAppDevServer>
58
75
  build(options?: CustomAppBuildOptions): Promise<BuildAppResult>
59
76
  start(options?: CustomAppStartOptions): Promise<CustomAppDevServer>
@@ -90,6 +107,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
90
107
 
91
108
  let tailwindCompiler: TailwindCssCompiler | null = null
92
109
  let tailwindCompilerKey: string | null = null
110
+ let authTailwindCompiler: TailwindCssCompiler | null = null
93
111
  let builtInAgentCssCompiler: TailwindCssCompiler | null = null
94
112
 
95
113
  // `app/globals.css` is source. When it uses Tailwind, compile it to
@@ -238,6 +256,58 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
238
256
  return { htmlPath, mainPath, manifestPath, routes }
239
257
  }
240
258
 
259
+ async function prepareAuthExperience(
260
+ authOptions: CustomAuthExperienceBuildOptions = {}
261
+ ): Promise<CustomAuthExperienceBuildResult | null> {
262
+ const outdir = authOptions.outdir
263
+ ? resolve(rootDir, authOptions.outdir)
264
+ : join(generatedDir, "auth")
265
+ if (!(await pathExists(join(appDir, "auth.tsx")))) {
266
+ await rm(outdir, { recursive: true, force: true })
267
+ return null
268
+ }
269
+
270
+ const stylesheet = await resolveCustomAppStylesheet({ appDir, generatedDir, rootDir })
271
+ let stylesheetPath: string | null
272
+ if (stylesheet.kind === "none") {
273
+ stylesheetPath = null
274
+ } else if (stylesheet.kind === "static") {
275
+ stylesheetPath = stylesheet.path
276
+ } else {
277
+ const outputPath = join(generatedDir, "auth.css")
278
+ authTailwindCompiler ??= createTailwindCssCompiler({
279
+ inputPath: stylesheet.sourcePath,
280
+ outputPath,
281
+ cwd: appDir,
282
+ resolveFrom: rootDir,
283
+ label: "[SixbCustomApp]",
284
+ })
285
+ await authTailwindCompiler.compile()
286
+ stylesheetPath = outputPath
287
+ }
288
+
289
+ const entry = await generateAuthExperienceEntry(rootDir, generatedDir, {
290
+ appDir,
291
+ publicDir,
292
+ stylesheetPath,
293
+ })
294
+ if (!entry) {
295
+ return null
296
+ }
297
+
298
+ const result = await buildAuthExperience({
299
+ entryPath: entry.htmlPath,
300
+ scriptEntryPath: entry.mainPath,
301
+ outdir,
302
+ })
303
+ if (!result.success) {
304
+ throw new Error(
305
+ `[SixbCustomApp] Failed to build the auth experience: ${(result.logs ?? []).join("\n")}`
306
+ )
307
+ }
308
+ return { outdir: result.outdir }
309
+ }
310
+
241
311
  return {
242
312
  async scanRoutes() {
243
313
  return await scanRoutes()
@@ -248,10 +318,15 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
248
318
  return routes.length > 0
249
319
  },
250
320
 
321
+ async prepareAuthExperience(options) {
322
+ return await prepareAuthExperience(options)
323
+ },
324
+
251
325
  async dev(devOptions: CustomAppDevOptions = {}) {
252
326
  const host = devOptions.host ?? "0.0.0.0"
253
327
  const port = devOptions.port ?? 3001
254
328
  const { htmlPath, manifestPath } = await prepareGeneratedApp()
329
+ await prepareAuthExperience()
255
330
  let htmlImportVersion = 0
256
331
  let htmlBundle = await importHtmlBundle(htmlPath, htmlImportVersion)
257
332
  const publicRoutes = (await pathExists(publicDir)) ? await createPublicRoutes(publicDir) : {}
@@ -282,6 +357,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
282
357
  rebuildChain = rebuildChain
283
358
  .then(async () => {
284
359
  const { htmlPath: nextHtmlPath } = await prepareGeneratedApp()
360
+ await prepareAuthExperience()
285
361
  htmlImportVersion++
286
362
  htmlBundle = await importHtmlBundle(nextHtmlPath, htmlImportVersion)
287
363
  server.reload(serveOptions(htmlBundle))
@@ -331,6 +407,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
331
407
  watcher.close()
332
408
  await rebuildChain
333
409
  await tailwindCompiler?.stop()
410
+ await authTailwindCompiler?.stop()
334
411
  await builtInAgentCssCompiler?.stop()
335
412
  server.stop(true)
336
413
  },
@@ -347,11 +424,21 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
347
424
  outdir,
348
425
  })
349
426
 
427
+ if (result.success) {
428
+ await prepareAuthExperience({ outdir: join(outdir, "auth") })
429
+ }
430
+
350
431
  if (result.success && (await pathExists(publicDir))) {
351
432
  await cp(publicDir, outdir, {
352
433
  recursive: true,
353
434
  force: true,
354
- filter: (source) => resolve(source) !== join(publicDir, "app.webmanifest"),
435
+ filter: (source) => {
436
+ const resolvedSource = resolve(source)
437
+ return (
438
+ resolvedSource !== join(publicDir, "app.webmanifest") &&
439
+ resolvedSource !== join(publicDir, "auth")
440
+ )
441
+ },
355
442
  })
356
443
  }
357
444
 
package/src/index.ts CHANGED
@@ -5,6 +5,8 @@ export {
5
5
  type CustomAppDevServer,
6
6
  type CustomAppInstance,
7
7
  type CustomAppStartOptions,
8
+ type CustomAuthExperienceBuildOptions,
9
+ type CustomAuthExperienceBuildResult,
8
10
  createCustomApp,
9
11
  } from "./createCustomApp"
10
12
  export type { AppMetadata } from "./metadata"