@sixb/app 0.1.1 → 0.1.2
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 +18 -0
- package/dist/agents.d.ts +6 -1
- package/dist/agents.d.ts.map +1 -1
- package/dist/agents.js +16 -5
- package/dist/agents.js.map +3 -3
- package/dist/build.d.ts +3 -2
- package/dist/build.d.ts.map +1 -1
- package/dist/createCustomApp.d.ts.map +1 -1
- package/dist/index.js +175 -54
- package/dist/index.js.map +4 -4
- package/package.json +4 -4
- package/src/agents.ts +28 -5
- package/src/build.ts +141 -40
- package/src/createCustomApp.ts +72 -9
package/src/build.ts
CHANGED
|
@@ -1,11 +1,23 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { existsSync } from "node:fs"
|
|
2
|
+
import { copyFile, mkdir, readFile, rm, writeFile } from "node:fs/promises"
|
|
3
|
+
import { basename, dirname, extname, join, resolve } from "node:path"
|
|
4
|
+
import { promisify } from "node:util"
|
|
5
|
+
import {
|
|
6
|
+
brotliCompress as brotliCompressCallback,
|
|
7
|
+
gzip as gzipCallback,
|
|
8
|
+
constants as zlibConstants,
|
|
9
|
+
} from "node:zlib"
|
|
3
10
|
|
|
4
11
|
const STATIC_ASSET_ORIGIN = "https://sixb-static.invalid"
|
|
12
|
+
const brotliCompress = promisify(brotliCompressCallback)
|
|
13
|
+
const gzip = promisify(gzipCallback)
|
|
14
|
+
const PRECOMPRESSION_CONCURRENCY = 4
|
|
5
15
|
|
|
6
16
|
export interface BuildAppOptions {
|
|
7
17
|
/** Path to the generated index.html entry point */
|
|
8
18
|
entryPath: string
|
|
19
|
+
/** Browser TypeScript entry generated alongside `entryPath`. */
|
|
20
|
+
scriptEntryPath: string
|
|
9
21
|
/** Generated manifest copied to the stable `/app.webmanifest` output path. */
|
|
10
22
|
manifestPath?: string
|
|
11
23
|
/** Output directory, defaults to `.sixb/dist/app` */
|
|
@@ -19,8 +31,7 @@ export interface BuildAppResult {
|
|
|
19
31
|
}
|
|
20
32
|
|
|
21
33
|
/**
|
|
22
|
-
* Builds the
|
|
23
|
-
* Outputs a production-ready static bundle.
|
|
34
|
+
* Builds the generated browser entry and writes a production-ready static shell and bundle.
|
|
24
35
|
*/
|
|
25
36
|
export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult> {
|
|
26
37
|
const outdir = options.outdir ?? join(process.cwd(), ".sixb", "dist", "app")
|
|
@@ -29,26 +40,31 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
|
|
|
29
40
|
await rm(outdir, { recursive: true, force: true })
|
|
30
41
|
await mkdir(outdir, { recursive: true })
|
|
31
42
|
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
43
|
+
const result = await Bun.build({
|
|
44
|
+
// Build the script entry directly rather than Bun's HTML entry. Bun cannot currently preserve
|
|
45
|
+
// a large dynamic-import graph reliably when splitting an HTML entry: one of the lazy chunks
|
|
46
|
+
// can be written into the shell's script tag. Building TypeScript directly also lets Shiki's
|
|
47
|
+
// hundreds of grammars remain off the initial custom-app path.
|
|
48
|
+
entrypoints: [options.scriptEntryPath],
|
|
49
|
+
outdir,
|
|
50
|
+
target: "browser",
|
|
51
|
+
conditions: ["bun"],
|
|
52
|
+
publicPath: "/",
|
|
53
|
+
minify: true,
|
|
54
|
+
splitting: true,
|
|
55
|
+
naming: {
|
|
56
|
+
entry: "app-[hash].[ext]",
|
|
57
|
+
chunk: "chunk-[name]-[hash].[ext]",
|
|
58
|
+
asset: "asset-[name]-[hash].[ext]",
|
|
59
|
+
},
|
|
60
|
+
plugins: [extensionlessSourceImportPlugin],
|
|
61
|
+
// React is bundled into this browser output, so without pinning NODE_ENV the production build
|
|
62
|
+
// of a user's app ships React's development build: dev-only checks on every render, and the
|
|
63
|
+
// warnings that go with them. This is also the only knob that selects the production JSX
|
|
64
|
+
// runtime — an ambient NODE_ENV does not.
|
|
65
|
+
define: { "process.env.NODE_ENV": '"production"' },
|
|
66
|
+
sourcemap: "external",
|
|
67
|
+
})
|
|
52
68
|
|
|
53
69
|
if (!result.success) {
|
|
54
70
|
return {
|
|
@@ -58,12 +74,38 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
|
|
|
58
74
|
}
|
|
59
75
|
}
|
|
60
76
|
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
77
|
+
const script = result.outputs.find(
|
|
78
|
+
(output) => output.kind === "entry-point" && output.type.startsWith("text/javascript")
|
|
79
|
+
)
|
|
80
|
+
const stylesheets = result.outputs.filter((output) => output.type.startsWith("text/css"))
|
|
81
|
+
if (!script || stylesheets.length > 1) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`[SixbCustomApp] Expected one browser entry and at most one stylesheet, found ${script ? 1 : 0} entries and ${stylesheets.length} stylesheets.`
|
|
84
|
+
)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const sourceHtml = restoreAppStaticUrls(await readFile(options.entryPath, "utf-8"))
|
|
88
|
+
const sourceEntryPattern =
|
|
89
|
+
/\s*<script\s+type=["']module["']\s+src=["']\.\/main\.tsx["']><\/script>/
|
|
90
|
+
if (!sourceEntryPattern.test(sourceHtml)) {
|
|
91
|
+
throw new Error("[SixbCustomApp] Generated app shell is missing its ./main.tsx entry.")
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const assetTags = [
|
|
95
|
+
...stylesheets.map(
|
|
96
|
+
(stylesheet) => `<link rel="stylesheet" crossorigin href="/${basename(stylesheet.path)}">`
|
|
97
|
+
),
|
|
98
|
+
`<script type="module" crossorigin src="/${basename(script.path)}"></script>`,
|
|
99
|
+
].join("")
|
|
100
|
+
const html = withLoadingShell(sourceHtml)
|
|
101
|
+
.replace(sourceEntryPattern, "")
|
|
102
|
+
.replace("</head>", ` ${assetTags}</head>`)
|
|
103
|
+
await writeFile(join(outdir, "index.html"), html, "utf-8")
|
|
104
|
+
|
|
64
105
|
if (options.manifestPath) {
|
|
65
106
|
await copyFile(options.manifestPath, join(outdir, "app.webmanifest"))
|
|
66
107
|
}
|
|
108
|
+
await precompressBuildAssets(result.outputs)
|
|
67
109
|
|
|
68
110
|
return { success: true, outdir }
|
|
69
111
|
}
|
|
@@ -86,20 +128,79 @@ export function restoreAppStaticUrls(html: string): string {
|
|
|
86
128
|
return html.replaceAll(STATIC_ASSET_ORIGIN, "")
|
|
87
129
|
}
|
|
88
130
|
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
131
|
+
function withLoadingShell(html: string): string {
|
|
132
|
+
const styles = `<style data-sixb-loading-shell>
|
|
133
|
+
.sixb-loading-shell{position:fixed;inset:0;display:grid;place-items:center;background:#fff;color:#71717a}
|
|
134
|
+
.sixb-loading-spinner{width:1.25rem;height:1.25rem;border:2px solid currentColor;border-right-color:transparent;border-radius:9999px;animation:sixb-loading-spin .7s linear infinite}
|
|
135
|
+
@media(prefers-color-scheme:dark){.sixb-loading-shell{background:#09090b;color:#a1a1aa}}
|
|
136
|
+
@media(prefers-reduced-motion:reduce){.sixb-loading-spinner{animation-duration:1.5s}}
|
|
137
|
+
@keyframes sixb-loading-spin{to{transform:rotate(360deg)}}
|
|
138
|
+
</style>`
|
|
139
|
+
const root =
|
|
140
|
+
'<div id="root"><div class="sixb-loading-shell" role="status" aria-label="Loading application"><span class="sixb-loading-spinner" aria-hidden="true"></span></div></div>'
|
|
93
141
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
const normalized = url.startsWith("./") ? url.slice(2) : url
|
|
98
|
-
return `${attr}=${quote}/${normalized}${quote}`
|
|
99
|
-
}
|
|
100
|
-
)
|
|
142
|
+
if (!html.includes('<div id="root"></div>') || !html.includes("</head>")) {
|
|
143
|
+
throw new Error("[SixbCustomApp] Generated app shell is missing its root or head element.")
|
|
144
|
+
}
|
|
101
145
|
|
|
102
|
-
|
|
103
|
-
|
|
146
|
+
return html.replace("</head>", `${styles}\n </head>`).replace('<div id="root"></div>', root)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const extensionlessSourceImportPlugin: Bun.BunPlugin = {
|
|
150
|
+
name: "sixb-extensionless-source-imports",
|
|
151
|
+
setup(build) {
|
|
152
|
+
// A direct TypeScript entry with splitting exposes a Bun 1.3 resolver edge in linked workspace
|
|
153
|
+
// packages: extensionless relative imports such as `../json` can fail even though `json.ts`
|
|
154
|
+
// exists. HTML entries masked it, but HTML splitting can point at the wrong dynamic chunk.
|
|
155
|
+
build.onResolve({ filter: /^\.\.?\// }, (args) => {
|
|
156
|
+
if (extname(args.path)) return undefined
|
|
157
|
+
|
|
158
|
+
const base = resolve(dirname(args.importer), args.path)
|
|
159
|
+
for (const candidate of [
|
|
160
|
+
`${base}.ts`,
|
|
161
|
+
`${base}.tsx`,
|
|
162
|
+
`${base}.js`,
|
|
163
|
+
`${base}.jsx`,
|
|
164
|
+
join(base, "index.ts"),
|
|
165
|
+
join(base, "index.tsx"),
|
|
166
|
+
join(base, "index.js"),
|
|
167
|
+
join(base, "index.jsx"),
|
|
168
|
+
]) {
|
|
169
|
+
if (existsSync(candidate)) return { path: candidate }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return undefined
|
|
173
|
+
})
|
|
174
|
+
},
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function precompressBuildAssets(
|
|
178
|
+
outputs: readonly { readonly path: string; readonly type: string }[]
|
|
179
|
+
): Promise<void> {
|
|
180
|
+
const paths = outputs
|
|
181
|
+
.filter(
|
|
182
|
+
(output) => output.type.startsWith("text/javascript") || output.type.startsWith("text/css")
|
|
183
|
+
)
|
|
184
|
+
.map((output) => output.path)
|
|
185
|
+
let cursor = 0
|
|
186
|
+
|
|
187
|
+
const worker = async () => {
|
|
188
|
+
while (cursor < paths.length) {
|
|
189
|
+
const path = paths[cursor++]
|
|
190
|
+
const bytes = await Bun.file(path).arrayBuffer()
|
|
191
|
+
const [brotli, gzipped] = await Promise.all([
|
|
192
|
+
brotliCompress(bytes, {
|
|
193
|
+
params: {
|
|
194
|
+
[zlibConstants.BROTLI_PARAM_QUALITY]: 5,
|
|
195
|
+
},
|
|
196
|
+
}),
|
|
197
|
+
gzip(bytes, { level: 9 }),
|
|
198
|
+
])
|
|
199
|
+
await Promise.all([writeFile(`${path}.br`, brotli), writeFile(`${path}.gz`, gzipped)])
|
|
200
|
+
}
|
|
104
201
|
}
|
|
202
|
+
|
|
203
|
+
await Promise.all(
|
|
204
|
+
Array.from({ length: Math.min(PRECOMPRESSION_CONCURRENCY, paths.length) }, worker)
|
|
205
|
+
)
|
|
105
206
|
}
|
package/src/createCustomApp.ts
CHANGED
|
@@ -214,6 +214,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
214
214
|
|
|
215
215
|
async function prepareGeneratedApp(): Promise<{
|
|
216
216
|
htmlPath: string
|
|
217
|
+
mainPath: string
|
|
217
218
|
manifestPath: string
|
|
218
219
|
routes: PageRoute[]
|
|
219
220
|
}> {
|
|
@@ -225,7 +226,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
225
226
|
const builtInRoutes = agentRoutesEnabled ? builtInAgentRoutesFor(routes) : []
|
|
226
227
|
const stylesheets = await prepareStylesheets(builtInRoutes)
|
|
227
228
|
await generateRouteManifest(routes, generatedDir, { builtInRoutes })
|
|
228
|
-
const { htmlPath, manifestPath } = await generateAppEntry(rootDir, generatedDir, {
|
|
229
|
+
const { htmlPath, mainPath, manifestPath } = await generateAppEntry(rootDir, generatedDir, {
|
|
229
230
|
apiBaseUrl,
|
|
230
231
|
audience,
|
|
231
232
|
authEnabled,
|
|
@@ -234,7 +235,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
234
235
|
frameworkStylesheetPaths: stylesheets.frameworkStylesheetPaths,
|
|
235
236
|
stylesheetPath: stylesheets.stylesheetPath,
|
|
236
237
|
})
|
|
237
|
-
return { htmlPath, manifestPath, routes }
|
|
238
|
+
return { htmlPath, mainPath, manifestPath, routes }
|
|
238
239
|
}
|
|
239
240
|
|
|
240
241
|
return {
|
|
@@ -338,9 +339,10 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
338
339
|
|
|
339
340
|
async build(buildOptions: CustomAppBuildOptions = {}) {
|
|
340
341
|
const outdir = resolve(rootDir, buildOptions.outdir ?? join(".sixb", "dist", "app"))
|
|
341
|
-
const { htmlPath, manifestPath } = await prepareGeneratedApp()
|
|
342
|
+
const { htmlPath, mainPath, manifestPath } = await prepareGeneratedApp()
|
|
342
343
|
const result = await buildApp({
|
|
343
344
|
entryPath: htmlPath,
|
|
345
|
+
scriptEntryPath: mainPath,
|
|
344
346
|
manifestPath,
|
|
345
347
|
outdir,
|
|
346
348
|
})
|
|
@@ -396,7 +398,7 @@ export async function createCustomApp(options: CreateCustomAppOptions): Promise<
|
|
|
396
398
|
|
|
397
399
|
const directFile = Bun.file(resolvedPath)
|
|
398
400
|
if (await directFile.exists()) {
|
|
399
|
-
return
|
|
401
|
+
return staticFileResponse(req, resolvedPath, staticAssetHeaders(url.pathname))
|
|
400
402
|
}
|
|
401
403
|
|
|
402
404
|
if (isAssetRequest(url.pathname)) {
|
|
@@ -633,11 +635,11 @@ function htmlResponse(request: Request, html: string): Response {
|
|
|
633
635
|
})
|
|
634
636
|
}
|
|
635
637
|
|
|
636
|
-
//
|
|
637
|
-
//
|
|
638
|
-
//
|
|
639
|
-
|
|
640
|
-
|
|
638
|
+
// buildApp emits content-hashed entry, chunk, and asset names. Their contents can never change
|
|
639
|
+
// under the same URL, so they are safe to cache forever. Files copied from `public/` keep their
|
|
640
|
+
// names across deploys and stay uncached.
|
|
641
|
+
const IMMUTABLE_ASSET_PATTERN =
|
|
642
|
+
/^(?:(?:app|chunk)-[a-z0-9]+|(?:chunk|asset)-.+-[a-z0-9]+)\.[a-z0-9]+(?:\.map)?$/
|
|
641
643
|
|
|
642
644
|
function staticAssetHeaders(pathname: string): Record<string, string> {
|
|
643
645
|
if (pathname === customAppManifestRoute) {
|
|
@@ -655,6 +657,67 @@ function staticAssetHeaders(pathname: string): Record<string, string> {
|
|
|
655
657
|
return { "cache-control": "public, max-age=31536000, immutable" }
|
|
656
658
|
}
|
|
657
659
|
|
|
660
|
+
async function staticFileResponse(
|
|
661
|
+
request: Request,
|
|
662
|
+
path: string,
|
|
663
|
+
headers: Record<string, string>
|
|
664
|
+
): Promise<Response> {
|
|
665
|
+
const responseHeaders = new Headers(headers)
|
|
666
|
+
const originalFile = Bun.file(path)
|
|
667
|
+
let responseFile = originalFile
|
|
668
|
+
|
|
669
|
+
if (isPrecompressedAsset(path)) {
|
|
670
|
+
responseHeaders.append("vary", "Accept-Encoding")
|
|
671
|
+
if (!request.headers.has("range")) {
|
|
672
|
+
for (const encoding of acceptedPrecompressedEncodings(request)) {
|
|
673
|
+
const candidate = Bun.file(`${path}.${encoding === "br" ? "br" : "gz"}`)
|
|
674
|
+
if (!(await candidate.exists())) continue
|
|
675
|
+
|
|
676
|
+
responseFile = candidate
|
|
677
|
+
responseHeaders.set("content-encoding", encoding)
|
|
678
|
+
responseHeaders.set("content-type", originalFile.type)
|
|
679
|
+
break
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
return new Response(request.method === "HEAD" ? null : responseFile, {
|
|
685
|
+
headers: responseHeaders,
|
|
686
|
+
})
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function isPrecompressedAsset(path: string): boolean {
|
|
690
|
+
return path.endsWith(".js") || path.endsWith(".css")
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
function acceptedPrecompressedEncodings(request: Request): ("br" | "gzip")[] {
|
|
694
|
+
const header = request.headers.get("accept-encoding")
|
|
695
|
+
if (!header) return []
|
|
696
|
+
|
|
697
|
+
const qualities = new Map<string, number>()
|
|
698
|
+
for (const item of header.split(",")) {
|
|
699
|
+
const [rawName, ...parameters] = item.trim().split(";")
|
|
700
|
+
const name = rawName.toLowerCase()
|
|
701
|
+
let quality = 1
|
|
702
|
+
for (const parameter of parameters) {
|
|
703
|
+
const match = parameter.trim().match(/^q=(0(?:\.\d+)?|1(?:\.0+)?)$/)
|
|
704
|
+
if (match) quality = Number(match[1])
|
|
705
|
+
}
|
|
706
|
+
qualities.set(name, quality)
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
const wildcard = qualities.get("*") ?? 0
|
|
710
|
+
return (["br", "gzip"] as const)
|
|
711
|
+
.map((encoding, preference) => ({
|
|
712
|
+
encoding,
|
|
713
|
+
preference,
|
|
714
|
+
quality: qualities.get(encoding) ?? wildcard,
|
|
715
|
+
}))
|
|
716
|
+
.filter((candidate) => candidate.quality > 0)
|
|
717
|
+
.sort((left, right) => right.quality - left.quality || left.preference - right.preference)
|
|
718
|
+
.map((candidate) => candidate.encoding)
|
|
719
|
+
}
|
|
720
|
+
|
|
658
721
|
function fileResponse(
|
|
659
722
|
request: Request,
|
|
660
723
|
file: Bun.BunFile,
|