@sixb/app 0.1.5 → 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/README.md +21 -4
- package/dist/build.d.ts +19 -0
- package/dist/build.d.ts.map +1 -1
- package/dist/codegen.d.ts +8 -2
- package/dist/codegen.d.ts.map +1 -1
- package/dist/createCustomApp.d.ts.map +1 -1
- package/dist/dev-reload.d.ts +3 -0
- package/dist/dev-reload.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +873 -106
- package/dist/index.js.map +8 -7
- package/package.json +4 -4
- package/src/build.ts +185 -44
- package/src/codegen.ts +530 -63
- package/src/createCustomApp.ts +292 -23
- package/src/dev-reload.ts +54 -0
- package/src/index.ts +1 -0
- package/src/scanner.ts +8 -2
package/src/createCustomApp.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto"
|
|
1
2
|
import { watch } from "node:fs"
|
|
2
3
|
import { access, cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"
|
|
3
4
|
import { dirname, isAbsolute, join, normalize, relative, resolve } from "node:path"
|
|
@@ -5,10 +6,13 @@ import { pathToFileURL } from "node:url"
|
|
|
5
6
|
import type { AuthSessionAudience } from "@sixb/core"
|
|
6
7
|
import {
|
|
7
8
|
type BuildAppResult,
|
|
9
|
+
type BuildSharedAppDevResult,
|
|
8
10
|
buildApp,
|
|
9
11
|
buildAuthExperience,
|
|
12
|
+
buildSharedAppDev,
|
|
10
13
|
prepareAppHtmlBundleEntry,
|
|
11
14
|
restoreAppStaticUrls,
|
|
15
|
+
SHARED_APP_SHELL_FILE_NAME,
|
|
12
16
|
} from "./build"
|
|
13
17
|
import {
|
|
14
18
|
type BuiltInRouteManifestEntry,
|
|
@@ -16,6 +20,7 @@ import {
|
|
|
16
20
|
generateAuthExperienceEntry,
|
|
17
21
|
generateRouteManifest,
|
|
18
22
|
} from "./codegen"
|
|
23
|
+
import { devReloadResponse } from "./dev-reload"
|
|
19
24
|
import { renderCustomAppRuntimeScript } from "./runtime"
|
|
20
25
|
import { type PageRoute, routePatternKey, scanAppRoutes } from "./scanner"
|
|
21
26
|
import { type CustomAppStylesheet, resolveCustomAppStylesheet } from "./styles"
|
|
@@ -84,6 +89,7 @@ const builtInAgentRoutePaths = ["/agents", "/agents/new/:agentId", "/agents/:thr
|
|
|
84
89
|
const builtInAgentRouteSourcePath = join(packageRoot, "src", "agents.ts")
|
|
85
90
|
const customAppManifestRoute = "/app.webmanifest"
|
|
86
91
|
const internalAppShellRoute = "/__sixb/generated/app-shell"
|
|
92
|
+
const internalSharedAppShellRoute = "/__sixb/generated/shared-app-shell"
|
|
87
93
|
|
|
88
94
|
export async function createCustomApp(options: CreateCustomAppOptions): Promise<CustomAppInstance> {
|
|
89
95
|
const rootDir = resolve(options.rootDir)
|
|
@@ -230,6 +236,9 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
230
236
|
htmlPath: string
|
|
231
237
|
mainPath: string
|
|
232
238
|
manifestPath: string
|
|
239
|
+
runtimePath: string
|
|
240
|
+
sharedHtmlPath: string
|
|
241
|
+
sharedMainPath: string
|
|
233
242
|
routes: PageRoute[]
|
|
234
243
|
}> {
|
|
235
244
|
const discovery = await scanAppRoutes(appDir)
|
|
@@ -244,7 +253,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
244
253
|
builtInRoutes,
|
|
245
254
|
layouts: discovery.layouts,
|
|
246
255
|
})
|
|
247
|
-
const
|
|
256
|
+
const entry = await generateAppEntry(rootDir, generatedDir, {
|
|
248
257
|
apiBaseUrl,
|
|
249
258
|
audience,
|
|
250
259
|
authEnabled,
|
|
@@ -253,7 +262,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
253
262
|
frameworkStylesheetPaths: stylesheets.frameworkStylesheetPaths,
|
|
254
263
|
stylesheetPath: stylesheets.stylesheetPath,
|
|
255
264
|
})
|
|
256
|
-
return {
|
|
265
|
+
return { ...entry, routes }
|
|
257
266
|
}
|
|
258
267
|
|
|
259
268
|
async function prepareAuthExperience(
|
|
@@ -325,12 +334,23 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
325
334
|
async dev(devOptions: CustomAppDevOptions = {}) {
|
|
326
335
|
const host = devOptions.host ?? "0.0.0.0"
|
|
327
336
|
const port = devOptions.port ?? 3001
|
|
328
|
-
const { htmlPath, manifestPath } = await prepareGeneratedApp()
|
|
337
|
+
const { htmlPath, manifestPath, sharedHtmlPath, sharedMainPath } = await prepareGeneratedApp()
|
|
329
338
|
await prepareAuthExperience()
|
|
330
339
|
let htmlImportVersion = 0
|
|
331
340
|
let htmlBundle = await importHtmlBundle(htmlPath, htmlImportVersion)
|
|
341
|
+
const sharedDevRoot = join(generatedDir, "shared-dev")
|
|
342
|
+
await rm(sharedDevRoot, { recursive: true, force: true })
|
|
343
|
+
let sharedBuildVersion = 0
|
|
344
|
+
let sharedSourceVersion = 0
|
|
345
|
+
let sharedBuiltSourceVersion = -1
|
|
346
|
+
let sharedBuild: BuildSharedAppDevResult | null = null
|
|
347
|
+
let sharedBuildPromise: Promise<BuildSharedAppDevResult> | null = null
|
|
348
|
+
let sharedAssetRoutes: BunServeRoutes = {}
|
|
349
|
+
let stopping = false
|
|
350
|
+
const privateAppShellRoute = `${internalAppShellRoute}-${randomBytes(18).toString("base64url")}`
|
|
332
351
|
const publicRoutes = (await pathExists(publicDir)) ? await createPublicRoutes(publicDir) : {}
|
|
333
352
|
let internalOrigin = ""
|
|
353
|
+
let server: ReturnType<typeof Bun.serve> | null = null
|
|
334
354
|
const serveOptions = (bundle: Bun.HTMLBundle) =>
|
|
335
355
|
({
|
|
336
356
|
port,
|
|
@@ -338,14 +358,63 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
338
358
|
development: true,
|
|
339
359
|
routes: {
|
|
340
360
|
...publicRoutes,
|
|
361
|
+
...sharedAssetRoutes,
|
|
341
362
|
...reservedSixbRoutes(),
|
|
363
|
+
"/__sixb/dev-reload.js": getHeadRoute(devReloadResponse),
|
|
342
364
|
[customAppManifestRoute]: manifestRoute(manifestPath),
|
|
343
|
-
[
|
|
344
|
-
|
|
345
|
-
"
|
|
365
|
+
[privateAppShellRoute]: htmlBundleRoute(bundle),
|
|
366
|
+
...sharedAppDevRoutes(async () => (await ensureSharedBuild()).html, apiBaseUrl),
|
|
367
|
+
"/": spaHtmlRoute(() => internalOrigin, { shellRoute: privateAppShellRoute }),
|
|
368
|
+
"/*": spaHtmlRoute(() => internalOrigin, { shellRoute: privateAppShellRoute }),
|
|
346
369
|
},
|
|
347
370
|
}) as Parameters<typeof Bun.serve>[0]
|
|
348
|
-
|
|
371
|
+
|
|
372
|
+
// Bun 1.3's programmatic bundler shares native state with HTMLBundle imports. Starting a
|
|
373
|
+
// second browser build for every ordinary dev server can corrupt later builds in the same
|
|
374
|
+
// process (EISDIR/Unseekable reads). A shared page is uncommon, so build it only on its first
|
|
375
|
+
// request and deduplicate concurrent GET/HEAD requests. Watch rebuilds invalidate this cache;
|
|
376
|
+
// the next shared request gets the new graph while old hashed assets remain reachable.
|
|
377
|
+
async function ensureSharedBuild(): Promise<BuildSharedAppDevResult> {
|
|
378
|
+
if (stopping) {
|
|
379
|
+
throw new Error("[SixbCustomApp] Shared development build requested while stopping.")
|
|
380
|
+
}
|
|
381
|
+
if (sharedBuild && sharedBuiltSourceVersion === sharedSourceVersion) {
|
|
382
|
+
return sharedBuild
|
|
383
|
+
}
|
|
384
|
+
if (sharedBuildPromise) {
|
|
385
|
+
await sharedBuildPromise
|
|
386
|
+
return await ensureSharedBuild()
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const sourceVersion = sharedSourceVersion
|
|
390
|
+
const outdir = join(sharedDevRoot, String(sharedBuildVersion++))
|
|
391
|
+
const build = buildSharedAppDev({
|
|
392
|
+
entryPath: sharedHtmlPath,
|
|
393
|
+
outdir,
|
|
394
|
+
scriptEntryPath: sharedMainPath,
|
|
395
|
+
})
|
|
396
|
+
.then((result) => {
|
|
397
|
+
sharedAssetRoutes = {
|
|
398
|
+
...sharedAssetRoutes,
|
|
399
|
+
...createGeneratedAssetRoutes(outdir, result.assetPaths),
|
|
400
|
+
}
|
|
401
|
+
sharedBuild = result
|
|
402
|
+
sharedBuiltSourceVersion = sourceVersion
|
|
403
|
+
server?.reload(serveOptions(htmlBundle))
|
|
404
|
+
return result
|
|
405
|
+
})
|
|
406
|
+
.finally(() => {
|
|
407
|
+
sharedBuildPromise = null
|
|
408
|
+
})
|
|
409
|
+
sharedBuildPromise = build
|
|
410
|
+
const result = await build
|
|
411
|
+
if (!stopping && sourceVersion !== sharedSourceVersion) {
|
|
412
|
+
return await ensureSharedBuild()
|
|
413
|
+
}
|
|
414
|
+
return result
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
server = Bun.serve(serveOptions(htmlBundle))
|
|
349
418
|
internalOrigin = devServerInternalOrigin(host, server.port ?? port)
|
|
350
419
|
|
|
351
420
|
// .ts/.tsx edits can change Tailwind's scanned classes and .css edits
|
|
@@ -360,7 +429,10 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
360
429
|
await prepareAuthExperience()
|
|
361
430
|
htmlImportVersion++
|
|
362
431
|
htmlBundle = await importHtmlBundle(nextHtmlPath, htmlImportVersion)
|
|
363
|
-
|
|
432
|
+
// prepareGeneratedApp refreshed the stable shared entry paths; invalidate the lazy
|
|
433
|
+
// browser graph only after the normal HTML bundle also rebuilt successfully.
|
|
434
|
+
sharedSourceVersion++
|
|
435
|
+
server?.reload(serveOptions(htmlBundle))
|
|
364
436
|
})
|
|
365
437
|
.catch((error) => {
|
|
366
438
|
// Keep serving the last good build, but tell the user why styles
|
|
@@ -400,6 +472,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
400
472
|
port,
|
|
401
473
|
url: `http://${displayHost}:${port}`,
|
|
402
474
|
async stop() {
|
|
475
|
+
stopping = true
|
|
403
476
|
if (rebuildTimer) {
|
|
404
477
|
clearTimeout(rebuildTimer)
|
|
405
478
|
rebuildTimer = null
|
|
@@ -409,17 +482,24 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
409
482
|
await tailwindCompiler?.stop()
|
|
410
483
|
await authTailwindCompiler?.stop()
|
|
411
484
|
await builtInAgentCssCompiler?.stop()
|
|
412
|
-
server
|
|
485
|
+
const activeServer = server
|
|
486
|
+
server = null
|
|
487
|
+
activeServer?.stop(true)
|
|
488
|
+
await sharedBuildPromise?.catch(() => {})
|
|
489
|
+
await rm(sharedDevRoot, { recursive: true, force: true })
|
|
413
490
|
},
|
|
414
491
|
}
|
|
415
492
|
},
|
|
416
493
|
|
|
417
494
|
async build(buildOptions: CustomAppBuildOptions = {}) {
|
|
418
495
|
const outdir = resolve(rootDir, buildOptions.outdir ?? join(".sixb", "dist", "app"))
|
|
419
|
-
const { htmlPath, mainPath, manifestPath } =
|
|
496
|
+
const { htmlPath, mainPath, manifestPath, sharedHtmlPath, sharedMainPath } =
|
|
497
|
+
await prepareGeneratedApp()
|
|
420
498
|
const result = await buildApp({
|
|
421
499
|
entryPath: htmlPath,
|
|
422
500
|
scriptEntryPath: mainPath,
|
|
501
|
+
sharedEntryPath: sharedHtmlPath,
|
|
502
|
+
sharedScriptEntryPath: sharedMainPath,
|
|
423
503
|
manifestPath,
|
|
424
504
|
outdir,
|
|
425
505
|
})
|
|
@@ -436,6 +516,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
436
516
|
const resolvedSource = resolve(source)
|
|
437
517
|
return (
|
|
438
518
|
resolvedSource !== join(publicDir, "app.webmanifest") &&
|
|
519
|
+
resolvedSource !== join(publicDir, SHARED_APP_SHELL_FILE_NAME) &&
|
|
439
520
|
resolvedSource !== join(publicDir, "auth")
|
|
440
521
|
)
|
|
441
522
|
},
|
|
@@ -450,16 +531,28 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
450
531
|
const port = startOptions.port ?? 3001
|
|
451
532
|
const outdir = resolve(rootDir, startOptions.outdir ?? join(".sixb", "dist", "app"))
|
|
452
533
|
const indexPath = join(outdir, "index.html")
|
|
534
|
+
const sharedIndexPath = join(outdir, SHARED_APP_SHELL_FILE_NAME)
|
|
453
535
|
|
|
454
536
|
if (!(await pathExists(indexPath))) {
|
|
455
537
|
throw new Error(`[SixbCustomApp] No built app found in ${outdir}`)
|
|
456
538
|
}
|
|
539
|
+
if (!(await pathExists(sharedIndexPath))) {
|
|
540
|
+
throw new Error(
|
|
541
|
+
`[SixbCustomApp] Built app in ${outdir} is missing ${SHARED_APP_SHELL_FILE_NAME}; rebuild required.`
|
|
542
|
+
)
|
|
543
|
+
}
|
|
457
544
|
|
|
458
545
|
const indexHtml = injectRuntimeConfig(await Bun.file(indexPath).text(), {
|
|
459
546
|
apiBaseUrl: startOptions.apiBaseUrl ?? apiBaseUrl,
|
|
460
547
|
audience: startOptions.audience ?? audience,
|
|
461
548
|
authEnabled: startOptions.authEnabled ?? authEnabled,
|
|
462
549
|
})
|
|
550
|
+
const sharedIndexHtml = injectRuntimeConfig(await Bun.file(sharedIndexPath).text(), {
|
|
551
|
+
apiBaseUrl: startOptions.apiBaseUrl ?? apiBaseUrl,
|
|
552
|
+
audience: "app",
|
|
553
|
+
authEnabled: false,
|
|
554
|
+
})
|
|
555
|
+
const runtimeApiBaseUrl = startOptions.apiBaseUrl ?? apiBaseUrl
|
|
463
556
|
const server = Bun.serve({
|
|
464
557
|
port,
|
|
465
558
|
hostname: host,
|
|
@@ -470,10 +563,25 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
470
563
|
return notFoundResponse()
|
|
471
564
|
}
|
|
472
565
|
|
|
566
|
+
if (isFrameworkPrivateRoute(url.pathname)) {
|
|
567
|
+
return notFoundResponse()
|
|
568
|
+
}
|
|
569
|
+
|
|
473
570
|
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
474
571
|
return notFoundResponse()
|
|
475
572
|
}
|
|
476
573
|
|
|
574
|
+
if (isSharedAppRoute(url.pathname)) {
|
|
575
|
+
if (isAssetRequest(url.pathname)) {
|
|
576
|
+
return notFoundResponse()
|
|
577
|
+
}
|
|
578
|
+
return sharedHtmlResponse(req, sharedIndexHtml, runtimeApiBaseUrl)
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
if (isSharedNamespace(url.pathname)) {
|
|
582
|
+
return notFoundResponse()
|
|
583
|
+
}
|
|
584
|
+
|
|
477
585
|
if (url.pathname === "/" || url.pathname === "") {
|
|
478
586
|
return htmlResponse(req, indexHtml)
|
|
479
587
|
}
|
|
@@ -576,7 +684,12 @@ async function createPublicRoutes(publicDir: string): Promise<BunServeRoutes> {
|
|
|
576
684
|
.slice(publicDir.length + 1)
|
|
577
685
|
.split("\\")
|
|
578
686
|
.join("/")}`
|
|
579
|
-
if (
|
|
687
|
+
if (
|
|
688
|
+
isReservedSixbRoute(routePath) ||
|
|
689
|
+
isSharedNamespace(routePath) ||
|
|
690
|
+
isFrameworkPrivateRoute(routePath) ||
|
|
691
|
+
routePath === customAppManifestRoute
|
|
692
|
+
) {
|
|
580
693
|
continue
|
|
581
694
|
}
|
|
582
695
|
routes[routePath] = getHeadRoute((request) => filePathResponse(request, filePath))
|
|
@@ -585,9 +698,32 @@ async function createPublicRoutes(publicDir: string): Promise<BunServeRoutes> {
|
|
|
585
698
|
return routes
|
|
586
699
|
}
|
|
587
700
|
|
|
701
|
+
function createGeneratedAssetRoutes(
|
|
702
|
+
outputRoot: string,
|
|
703
|
+
assetPaths: readonly string[]
|
|
704
|
+
): BunServeRoutes {
|
|
705
|
+
const routes: BunServeRoutes = {}
|
|
706
|
+
for (const assetPath of assetPaths) {
|
|
707
|
+
const relativePath = relative(outputRoot, assetPath)
|
|
708
|
+
if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
|
|
709
|
+
throw new Error(`[SixbCustomApp] Shared development asset escaped its output directory.`)
|
|
710
|
+
}
|
|
711
|
+
const routePath = `/${relativePath.split("\\").join("/")}`
|
|
712
|
+
routes[routePath] = getHeadRoute((request) =>
|
|
713
|
+
fileResponse(request, Bun.file(assetPath), { "cache-control": "no-store" })
|
|
714
|
+
)
|
|
715
|
+
}
|
|
716
|
+
return routes
|
|
717
|
+
}
|
|
718
|
+
|
|
588
719
|
function reservedSixbRoutes(): BunServeRoutes {
|
|
589
720
|
const handler = () => notFoundResponse()
|
|
590
721
|
return {
|
|
722
|
+
[internalAppShellRoute]: allMethodsRoute(handler),
|
|
723
|
+
[`${internalAppShellRoute}/*`]: allMethodsRoute(handler),
|
|
724
|
+
[internalSharedAppShellRoute]: allMethodsRoute(handler),
|
|
725
|
+
[`${internalSharedAppShellRoute}/*`]: allMethodsRoute(handler),
|
|
726
|
+
[`/${SHARED_APP_SHELL_FILE_NAME}`]: allMethodsRoute(handler),
|
|
591
727
|
"/api": allMethodsRoute(handler),
|
|
592
728
|
"/api/*": allMethodsRoute(handler),
|
|
593
729
|
"/auth": allMethodsRoute(handler),
|
|
@@ -599,16 +735,76 @@ function reservedSixbRoutes(): BunServeRoutes {
|
|
|
599
735
|
}
|
|
600
736
|
}
|
|
601
737
|
|
|
738
|
+
function sharedAppDevRoutes(
|
|
739
|
+
html: () => string | Promise<string>,
|
|
740
|
+
apiBaseUrl: string | undefined
|
|
741
|
+
): BunServeRoutes {
|
|
742
|
+
const reject = () => notFoundResponse()
|
|
743
|
+
const guardedHandler = async (request: Request) => {
|
|
744
|
+
const pathname = new URL(request.url).pathname
|
|
745
|
+
if (!isSharedAppRoute(pathname) || isAssetRequest(pathname)) {
|
|
746
|
+
return notFoundResponse()
|
|
747
|
+
}
|
|
748
|
+
return sharedHtmlResponse(request, await html(), apiBaseUrl)
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
return {
|
|
752
|
+
"/shared": allMethodsRoute(reject),
|
|
753
|
+
"/shared/*": {
|
|
754
|
+
GET: guardedHandler,
|
|
755
|
+
HEAD: guardedHandler,
|
|
756
|
+
POST: reject,
|
|
757
|
+
PUT: reject,
|
|
758
|
+
PATCH: reject,
|
|
759
|
+
DELETE: reject,
|
|
760
|
+
OPTIONS: reject,
|
|
761
|
+
} as unknown as BunServeRoute,
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
function isSharedAppRoute(pathname: string): boolean {
|
|
766
|
+
return /^\/shared\/[^/]+(?:\/.*)?$/.test(pathname)
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
function isSharedNamespace(pathname: string): boolean {
|
|
770
|
+
const decoded = decodeRoutePathname(pathname)
|
|
771
|
+
return decoded === "/shared" || decoded?.startsWith("/shared/") === true
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function isFrameworkPrivateRoute(pathname: string): boolean {
|
|
775
|
+
const decoded = decodeRoutePathname(pathname)?.toLowerCase()
|
|
776
|
+
if (!decoded) return false
|
|
777
|
+
const sharedShellRoute = `/${SHARED_APP_SHELL_FILE_NAME}`
|
|
778
|
+
return (
|
|
779
|
+
decoded === sharedShellRoute ||
|
|
780
|
+
decoded.startsWith(`${sharedShellRoute}/`) ||
|
|
781
|
+
decoded === internalAppShellRoute ||
|
|
782
|
+
decoded.startsWith(`${internalAppShellRoute}/`) ||
|
|
783
|
+
decoded === internalSharedAppShellRoute ||
|
|
784
|
+
decoded.startsWith(`${internalSharedAppShellRoute}/`)
|
|
785
|
+
)
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
function decodeRoutePathname(pathname: string): string | null {
|
|
789
|
+
try {
|
|
790
|
+
return decodeURIComponent(pathname).replaceAll("\\", "/")
|
|
791
|
+
} catch {
|
|
792
|
+
return null
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
602
796
|
function isReservedSixbRoute(pathname: string): boolean {
|
|
797
|
+
const decoded = decodeRoutePathname(pathname)
|
|
798
|
+
if (!decoded) return false
|
|
603
799
|
return (
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
800
|
+
decoded === "/api" ||
|
|
801
|
+
decoded.startsWith("/api/") ||
|
|
802
|
+
decoded === "/auth" ||
|
|
803
|
+
decoded.startsWith("/auth/") ||
|
|
804
|
+
decoded === "/ws" ||
|
|
805
|
+
decoded.startsWith("/ws/") ||
|
|
806
|
+
decoded === "/docs" ||
|
|
807
|
+
decoded.startsWith("/docs/")
|
|
612
808
|
)
|
|
613
809
|
}
|
|
614
810
|
|
|
@@ -722,11 +918,70 @@ function htmlResponse(request: Request, html: string): Response {
|
|
|
722
918
|
})
|
|
723
919
|
}
|
|
724
920
|
|
|
921
|
+
function sharedHtmlResponse(
|
|
922
|
+
request: Request,
|
|
923
|
+
html: string,
|
|
924
|
+
apiBaseUrl: string | undefined
|
|
925
|
+
): Response {
|
|
926
|
+
const secured = secureSharedHtml(html, request, { apiBaseUrl })
|
|
927
|
+
return new Response(request.method === "HEAD" ? null : secured.html, {
|
|
928
|
+
headers: {
|
|
929
|
+
"content-type": "text/html; charset=utf-8",
|
|
930
|
+
...secured.headers,
|
|
931
|
+
},
|
|
932
|
+
})
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
function secureSharedHtml(
|
|
936
|
+
html: string,
|
|
937
|
+
request: Request,
|
|
938
|
+
options: { readonly apiBaseUrl?: string }
|
|
939
|
+
): { readonly html: string; readonly headers: Record<string, string> } {
|
|
940
|
+
const nonce = randomBytes(18).toString("base64url")
|
|
941
|
+
const requestOrigin = new URL(request.url).origin
|
|
942
|
+
let apiOrigin = requestOrigin
|
|
943
|
+
try {
|
|
944
|
+
apiOrigin = new URL(options.apiBaseUrl ?? requestOrigin, requestOrigin).origin
|
|
945
|
+
} catch {
|
|
946
|
+
// The browser client reports an invalid runtime URL. Keep the document policy fail-closed.
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
const connectSources = ["'self'", ...(apiOrigin === requestOrigin ? [] : [apiOrigin])]
|
|
950
|
+
const scriptSources = [`'nonce-${nonce}'`, "'strict-dynamic'", "'self'"]
|
|
951
|
+
const contentSecurityPolicy = [
|
|
952
|
+
"default-src 'none'",
|
|
953
|
+
"base-uri 'none'",
|
|
954
|
+
"object-src 'none'",
|
|
955
|
+
"frame-ancestors 'none'",
|
|
956
|
+
"form-action 'none'",
|
|
957
|
+
`script-src ${scriptSources.join(" ")}`,
|
|
958
|
+
"style-src 'self' 'unsafe-inline'",
|
|
959
|
+
"img-src 'self' data: blob: https:",
|
|
960
|
+
"font-src 'self' data: https:",
|
|
961
|
+
`connect-src ${connectSources.join(" ")}`,
|
|
962
|
+
"manifest-src 'none'",
|
|
963
|
+
].join("; ")
|
|
964
|
+
|
|
965
|
+
return {
|
|
966
|
+
html: html.replace(/<script(?![^>]*\snonce=)/g, `<script nonce="${nonce}"`),
|
|
967
|
+
headers: {
|
|
968
|
+
"cache-control": "no-store",
|
|
969
|
+
"content-security-policy": contentSecurityPolicy,
|
|
970
|
+
"permissions-policy":
|
|
971
|
+
"camera=(), geolocation=(), microphone=(), payment=(), usb=(), browsing-topics=()",
|
|
972
|
+
"referrer-policy": "no-referrer",
|
|
973
|
+
"x-content-type-options": "nosniff",
|
|
974
|
+
"x-frame-options": "DENY",
|
|
975
|
+
"x-robots-tag": "noindex, nofollow, noarchive",
|
|
976
|
+
},
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
|
|
725
980
|
// buildApp emits content-hashed entry, chunk, and asset names. Their contents can never change
|
|
726
981
|
// under the same URL, so they are safe to cache forever. Files copied from `public/` keep their
|
|
727
982
|
// names across deploys and stay uncached.
|
|
728
983
|
const IMMUTABLE_ASSET_PATTERN =
|
|
729
|
-
/^(?:(?:app|chunk)-[a-z0-9]+|(?:chunk|asset)-.+-[a-z0-9]+)\.[a-z0-9]+(?:\.map)?$/
|
|
984
|
+
/^(?:(?:app|shared|chunk)-[a-z0-9]+|(?:chunk|asset)-.+-[a-z0-9]+)\.[a-z0-9]+(?:\.map)?$/
|
|
730
985
|
|
|
731
986
|
function staticAssetHeaders(pathname: string): Record<string, string> {
|
|
732
987
|
if (pathname === customAppManifestRoute) {
|
|
@@ -878,14 +1133,24 @@ function devServerInternalOrigin(host: string, port: number): string {
|
|
|
878
1133
|
return `http://${urlHost}:${port}`
|
|
879
1134
|
}
|
|
880
1135
|
|
|
881
|
-
function spaHtmlRoute(
|
|
1136
|
+
function spaHtmlRoute(
|
|
1137
|
+
internalOrigin: () => string,
|
|
1138
|
+
options: { readonly shellRoute?: string } = {}
|
|
1139
|
+
): BunServeRoute {
|
|
882
1140
|
return getHeadRoute(async (request) => {
|
|
883
1141
|
const publicUrl = new URL(request.url)
|
|
1142
|
+
if (
|
|
1143
|
+
isReservedSixbRoute(publicUrl.pathname) ||
|
|
1144
|
+
isSharedNamespace(publicUrl.pathname) ||
|
|
1145
|
+
isFrameworkPrivateRoute(publicUrl.pathname)
|
|
1146
|
+
) {
|
|
1147
|
+
return notFoundResponse()
|
|
1148
|
+
}
|
|
884
1149
|
if (publicUrl.pathname !== "/" && isAssetRequest(publicUrl.pathname)) {
|
|
885
1150
|
return notFoundResponse()
|
|
886
1151
|
}
|
|
887
1152
|
|
|
888
|
-
const url = new URL(internalAppShellRoute, internalOrigin())
|
|
1153
|
+
const url = new URL(options.shellRoute ?? internalAppShellRoute, internalOrigin())
|
|
889
1154
|
url.search = publicUrl.search
|
|
890
1155
|
const requestHeaders = new Headers(request.headers)
|
|
891
1156
|
for (const header of [
|
|
@@ -911,7 +1176,11 @@ function spaHtmlRoute(internalOrigin: () => string): BunServeRoute {
|
|
|
911
1176
|
})
|
|
912
1177
|
}
|
|
913
1178
|
|
|
914
|
-
|
|
1179
|
+
const html = restoreAppStaticUrls(await bundleResponse.text()).replace(
|
|
1180
|
+
"</head>",
|
|
1181
|
+
'<script src="/__sixb/dev-reload.js"></script></head>'
|
|
1182
|
+
)
|
|
1183
|
+
return new Response(html, {
|
|
915
1184
|
status: bundleResponse.status,
|
|
916
1185
|
statusText: bundleResponse.statusText,
|
|
917
1186
|
headers: responseHeaders,
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** Served only by development browser servers; the CLI marks a generation ready last. */
|
|
2
|
+
export function devReloadResponse(request: Request): Response {
|
|
3
|
+
const generation = process.env.SIXB_DEV_GENERATION
|
|
4
|
+
const headers = new Headers({
|
|
5
|
+
"content-type": "text/javascript; charset=utf-8",
|
|
6
|
+
"cache-control": "no-store",
|
|
7
|
+
})
|
|
8
|
+
if (generation && process.env.SIXB_DEV_READY === "1") {
|
|
9
|
+
headers.set("x-sixb-dev-generation", generation)
|
|
10
|
+
}
|
|
11
|
+
if (request.method === "HEAD") return new Response(null, { headers })
|
|
12
|
+
const script = generation
|
|
13
|
+
? `(() => {
|
|
14
|
+
if (window.__sixbDevReload) return;
|
|
15
|
+
window.__sixbDevReload = true;
|
|
16
|
+
const generation = ${JSON.stringify(generation).replaceAll("<", "\\u003c")};
|
|
17
|
+
let timer;
|
|
18
|
+
let checking = false;
|
|
19
|
+
let finished = false;
|
|
20
|
+
let failures = 0;
|
|
21
|
+
const hidden = () => document.visibilityState === "hidden";
|
|
22
|
+
function schedule(delay) {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
timer = setTimeout(poll, delay);
|
|
25
|
+
}
|
|
26
|
+
async function poll() {
|
|
27
|
+
if (checking || finished) return;
|
|
28
|
+
if (hidden()) { schedule(15000); return; }
|
|
29
|
+
checking = true;
|
|
30
|
+
try {
|
|
31
|
+
const response = await fetch("/__sixb/dev-reload.js", {
|
|
32
|
+
method: "HEAD", cache: "no-store", signal: AbortSignal.timeout(3000)
|
|
33
|
+
});
|
|
34
|
+
const next = response.headers.get("x-sixb-dev-generation");
|
|
35
|
+
if (response.ok && next && next !== generation) {
|
|
36
|
+
finished = true;
|
|
37
|
+
document.removeEventListener("visibilitychange", visible);
|
|
38
|
+
location.reload();
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
failures = response.ok && next ? 0 : Math.min(failures + 1, 4);
|
|
42
|
+
} catch { failures = Math.min(failures + 1, 4); }
|
|
43
|
+
finally { checking = false; }
|
|
44
|
+
schedule(Math.min(1000 * 2 ** failures, 10000));
|
|
45
|
+
}
|
|
46
|
+
function visible() {
|
|
47
|
+
if (!hidden()) { clearTimeout(timer); void poll(); }
|
|
48
|
+
}
|
|
49
|
+
document.addEventListener("visibilitychange", visible);
|
|
50
|
+
void poll();
|
|
51
|
+
})();`
|
|
52
|
+
: ""
|
|
53
|
+
return new Response(script, { headers })
|
|
54
|
+
}
|
package/src/index.ts
CHANGED
package/src/scanner.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { readdir } from "node:fs/promises"
|
|
|
2
2
|
import { join, relative } from "node:path"
|
|
3
3
|
|
|
4
4
|
const dynamicSegmentPattern = /^\[([\w-]+)\]$/
|
|
5
|
-
const reservedRoutePrefixes = ["/api", "/auth", "/ws", "/docs", "/__sixb"] as const
|
|
5
|
+
const reservedRoutePrefixes = ["/api", "/auth", "/ws", "/docs", "/__sixb", "/shared"] as const
|
|
6
6
|
const reservedRoutePaths = new Set(["/app.webmanifest"])
|
|
7
7
|
|
|
8
8
|
export interface PageRoute {
|
|
@@ -134,6 +134,12 @@ function validateChildDirectories(
|
|
|
134
134
|
|
|
135
135
|
for (const entry of entries) {
|
|
136
136
|
if (!entry.isDirectory()) continue
|
|
137
|
+
if (!relativeDir && entry.name.toLowerCase() === "shared") {
|
|
138
|
+
throw new Error(
|
|
139
|
+
"[SixbCustomApp] app/shared is reserved for framework-managed shared links. " +
|
|
140
|
+
"Move this page to another route."
|
|
141
|
+
)
|
|
142
|
+
}
|
|
137
143
|
const segment = routeSegment(entry.name, join(relativeDir, entry.name))
|
|
138
144
|
const key = segment.startsWith(":") ? ":" : segment.toLowerCase()
|
|
139
145
|
const existing = claimedSegments.get(key)
|
|
@@ -188,7 +194,7 @@ function assertRouteIsAvailable(path: string, relativePath: string): void {
|
|
|
188
194
|
if (!reserved) return
|
|
189
195
|
|
|
190
196
|
throw new Error(
|
|
191
|
-
`[SixbCustomApp] Page ${displayAppPath(relativePath)} resolves to reserved framework path '${path}'. Choose a route outside /api, /auth, /ws, /docs, /__sixb, and /app.webmanifest.`
|
|
197
|
+
`[SixbCustomApp] Page ${displayAppPath(relativePath)} resolves to reserved framework path '${path}'. Choose a route outside /api, /auth, /ws, /docs, /__sixb, /shared, and /app.webmanifest.`
|
|
192
198
|
)
|
|
193
199
|
}
|
|
194
200
|
|