Skip to content

Commit 0d8f36f

Browse files
authored
feat(hub): serve static builds from a deploy base (#494)
buildHub bakes root-absolute URLs for frame bases, dock entries, page scripts, and per-SPA asset references. A deploy base prefixes them so the same output serves under a subpath, while the on-disk deploy-root layout stays unchanged.
1 parent 9cb2bd0 commit 0d8f36f

6 files changed

Lines changed: 282 additions & 14 deletions

File tree

‎docs/content/6.errors/DF8007.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
---
2+
title: 'DF8007: Hub Base Is Outside the Deploy Base'
3+
description: 'buildHub''s base ("{base}") is not under its deployBase ("{deployBase}"), so the hub itself would be served outside the deploy root.'
4+
---
5+
6+
## Message
7+
8+
> buildHub's base ("`{base}`") is not under its deployBase ("`{deployBase}`"), so the hub itself would be served outside the deploy root.
9+
10+
## Cause
11+
12+
`deployBase` is the URL prefix the whole output tree is served under, and the hub sits inside that tree. A hub `base` outside it describes a second deployment, so the baked URLs and the file layout would disagree.
13+
14+
## Example
15+
16+
```ts
17+
// ✓ Good: the hub base includes the deploy prefix
18+
await buildHub({
19+
outDir: 'dist/__devtools',
20+
base: '/ci-build-123456/__devtools/',
21+
deployBase: '/ci-build-123456/',
22+
})
23+
24+
// ✗ Bad: the hub would be served at the domain root
25+
await buildHub({
26+
outDir: 'dist/__devtools',
27+
base: '/__devtools/',
28+
deployBase: '/ci-build-123456/',
29+
})
30+
```
31+
32+
## Fix
33+
34+
Include the deploy prefix in `base`, or omit `deployBase` when the output is served at the domain root.
35+
36+
## Source
37+
38+
- [`packages/hub/src/node/build.ts`](https://github.com/devframes/devframe/blob/main/packages/hub/src/node/build.ts): `buildHub()` rejects a `base` that does not start with `deployBase`.

‎docs/content/8.references/6.hub-api.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ The options of `buildHub()` from `@devframes/hub/build`: [Static builds](/guide/
124124
|---|---|
125125
| `outDir` | Output directory for the hub subtree; corresponds to `base` at serve time (build `base: '/__devframes/'` into `dist/__devframes`). A mount served outside the hub base (a devframe SPA or asset dir kept as a sibling of it) is written to this directory's parent (the deploy root) by its absolute path. |
126126
| `base` | Mount base baked into every absolute URL the build emits. Default `/__devframes/`. |
127+
| `deployBase` | URL prefix the deploy root is served under. Root-absolute URLs the build emits are rebased under it. Must be a prefix of `base`. Default `/`. |
127128
| `context` | An already-mounted `DevframeHubContext` to bake instead of `devframes` (the build counterpart of `initHub({ context })`); reads `ctx.frames` and `ctx.views.buildStaticDirs`. Mutually exclusive with `devframes`. |
128129
| `clean` | Remove `outDir` before writing. Default `true`; set `false` to bake beside an app's own build output. |
129130
| `pretty` | Pretty-print RPC dump JSON shards. Default `false` (minified). |

‎packages/hub/src/node/__tests__/build.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,4 +228,73 @@ describe('buildHub', () => {
228228
const index = JSON.parse(readFileSync(join(outDir, '__index.json'), 'utf-8'))
229229
expect(index.frames.map((frame: { id: string }) => frame.id)).toEqual(['gamma'])
230230
})
231+
232+
it('rejects a hub base outside `deployBase`', async () => {
233+
await expect(buildHub({
234+
outDir: join(mkdtempSync(join(tmpdir(), 'hub-build-out-')), 'hub'),
235+
base: '/__hub/',
236+
deployBase: '/sub/',
237+
cwd: mkdtempSync(join(tmpdir(), 'hub-build-cwd-')),
238+
})).rejects.toThrow(/not under its deployBase/)
239+
})
240+
241+
it('rebases the deploy-root layout under `deployBase`', async () => {
242+
const deployRoot = mkdtempSync(join(tmpdir(), 'hub-build-out-'))
243+
const outDir = join(deployRoot, '__devtools')
244+
const panel = makeDist('<script type="module" src="/__panel/app.js"></script>')
245+
writeFileSync(join(panel, 'app.js'), 'export const base = "/__panel/"\n', 'utf-8')
246+
247+
await buildHub({
248+
outDir,
249+
base: '/ci-build-123456/__devtools/',
250+
deployBase: '/ci-build-123456/',
251+
cwd: mkdtempSync(join(tmpdir(), 'hub-build-cwd-')),
252+
async configure(ctx) {
253+
await ctx.install(makeFrame('alpha', {
254+
distDir: makeDist('<script type="module" src="/__alpha/app.js"></script>'),
255+
}), { base: '/__alpha/' })
256+
ctx.views.hostStatic('/__panel/', panel)
257+
ctx.docks.register({
258+
id: 'panel',
259+
title: 'Panel',
260+
icon: '/__panel/icon.svg',
261+
type: 'iframe',
262+
url: '/__panel/',
263+
})
264+
},
265+
})
266+
267+
// The deploy root layout is unchanged on disk: siblings sit beside the hub.
268+
expect(existsSync(join(outDir, '__connection.json'))).toBe(true)
269+
expect(existsSync(join(deployRoot, '__alpha/index.html'))).toBe(true)
270+
expect(existsSync(join(deployRoot, '__panel/app.js'))).toBe(true)
271+
272+
// Discovery and per-frame meta spell the served URLs.
273+
const index = JSON.parse(readFileSync(join(outDir, '__index.json'), 'utf-8'))
274+
expect(index.base).toBe('/ci-build-123456/__devtools/')
275+
expect(index.frames).toEqual([
276+
{ id: 'alpha', base: '/ci-build-123456/__alpha/', title: 'Frame alpha' },
277+
])
278+
const frameMeta = JSON.parse(readFileSync(join(deployRoot, '__alpha/__connection.json'), 'utf-8'))
279+
expect(frameMeta.baseUrl).toBe('/ci-build-123456/__devtools/__connection.json')
280+
281+
// The baked RPC dump carries the served dock URL, not the root-absolute one.
282+
const manifest = JSON.parse(readFileSync(join(outDir, '__rpc-dump/index.json'), 'utf-8'))
283+
const stateEntry = manifest['devframe:rpc:server-state:get']
284+
const records = (Object.values(stateEntry.records) as string[])
285+
.map(path => readFileSync(join(outDir, path), 'utf-8'))
286+
const docksRecord = records.find(text => text.includes(HUB_EVENTS.sharedState.docks))!
287+
expect(docksRecord).toContain('/ci-build-123456/__alpha/')
288+
expect(docksRecord).toContain('/ci-build-123456/__panel/')
289+
expect(docksRecord).not.toContain('"/__alpha/"')
290+
expect(docksRecord).not.toContain('"/__panel/"')
291+
292+
// Root-absolute asset references inside copied SPAs follow the new location.
293+
expect(readFileSync(join(deployRoot, '__alpha/index.html'), 'utf-8'))
294+
.toContain('/ci-build-123456/__alpha/app.js')
295+
expect(readFileSync(join(deployRoot, '__panel/index.html'), 'utf-8'))
296+
.toContain('/ci-build-123456/__panel/app.js')
297+
expect(readFileSync(join(deployRoot, '__panel/app.js'), 'utf-8'))
298+
.toContain('/ci-build-123456/__panel/')
299+
})
231300
})

‎packages/hub/src/node/build.ts‎

Lines changed: 169 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { collectStaticRpcDump, writeStaticRpcDump } from 'devframe/rpc/dump'
1212
import { colors as c } from 'devframe/utils/colors'
1313
import { resolveStaticAssetsSource } from 'devframe/utils/remote-assets'
1414
import { joinURL } from 'devframe/utils/url'
15-
import { dirname, resolve } from 'pathe'
15+
import { dirname, extname, resolve } from 'pathe'
1616
import { DEVFRAMES_HUB_BASE, DOCK_RENDERERS_STATE_KEY, normalizeHubBase } from '../constants'
1717
import { mountDevframes, renderClientImportsModule, resolveDevframesInput, resolveRendererRegistrations } from './assemble'
1818
import { createHubContext } from './context'
@@ -35,6 +35,13 @@ export interface BuildHubOptions {
3535
* pointers). Default: `/__devframes/`.
3636
*/
3737
base?: string
38+
/**
39+
* URL prefix the deploy root is served under (e.g. `/ci-build-123456/`).
40+
* Root-absolute URLs the build emits are rebased under it, so the output
41+
* works below the domain root. Must be a prefix of
42+
* {@link BuildHubOptions.base}. Default: `/`.
43+
*/
44+
deployBase?: string
3845
/** Devframes to bake as docks, same input as `initHub({ devframes })`. */
3946
devframes?: DevframesInput
4047
/**
@@ -113,6 +120,9 @@ export async function buildHub(options: BuildHubOptions): Promise<void> {
113120
throw diagnostics.DF8002()
114121

115122
const base = normalizeHubBase(options.base ?? DEVFRAMES_HUB_BASE)
123+
const deployBase = normalizeHubBase(options.deployBase ?? '/')
124+
if (deployBase !== '/' && !base.startsWith(deployBase))
125+
throw diagnostics.DF8007({ base, deployBase })
116126
const cwd = options.cwd ?? process.cwd()
117127
const outDir = resolve(cwd, options.outDir)
118128
const rendererRegistrations = resolveRendererRegistrations(options.renderers ?? [])
@@ -132,26 +142,55 @@ export async function buildHub(options: BuildHubOptions): Promise<void> {
132142
* corresponds to the hub base). A base outside it is a deploy-root sibling:
133143
* `outDir`'s parent is the deploy root, and the base resolves under it by its
134144
* absolute path. This is the layout Vite DevTools serves, where devframe SPAs
135-
* and assets sit beside `/__devtools/` rather than under it.
145+
* and assets sit beside `/__devtools/` rather than under it. The deploy
146+
* prefix, when set, is stripped first: it moves the URLs, not the files.
136147
*/
137148
const deployRoot = dirname(outDir)
149+
const hubBase = stripDeployBase(base, deployBase)
138150
const resolveOutPath = (urlBase: string): string => {
139-
if (urlBase.startsWith(base))
140-
return resolve(outDir, urlBase.slice(base.length))
141-
if (!urlBase.startsWith('/'))
151+
const localBase = stripDeployBase(urlBase, deployBase)
152+
if (localBase.startsWith(hubBase))
153+
return resolve(outDir, localBase.slice(hubBase.length))
154+
if (!localBase.startsWith('/'))
142155
throw diagnostics.DF8006({ urlBase, base })
143-
return resolve(deployRoot, urlBase.slice(1))
156+
return resolve(deployRoot, localBase.slice(1))
144157
}
145158

146-
await copyBuildStatics(ctx, resolveOutPath)
159+
// Everything served outside the deploy prefix needs it added to the baked
160+
// URLs. Longest first, so a nested mount is rewritten before its parent.
161+
const servedBases = new Set([
162+
...ctx.frames.map(frame => frame.base),
163+
...ctx.views.buildStaticDirs.map(dir => dir.baseUrl),
164+
])
165+
const rewrites = deployBase === '/'
166+
? []
167+
: [...servedBases]
168+
.filter(url => url.startsWith('/') && !isUnderDeployBase(url, deployBase))
169+
.sort((a, b) => b.length - a.length)
170+
.map(url => [
171+
url,
172+
serveUrl(url, deployBase),
173+
] as const)
174+
const rebaseText = createTextRebaser(rewrites, deployBase)
175+
const rebaseValue = rewrites.length
176+
? createUrlValueRebaser(rewrites)
177+
: <T>(value: T): T => value
178+
179+
await copyBuildStatics(ctx, resolveOutPath, rewrites.length ? rebaseText : undefined)
147180
await publishRendererManifest(ctx, rendererRegistrations, base, outDir)
148181
await writeUiArtifacts(options.ui, outDir)
149-
await fs.writeFile(resolve(outDir, DEVFRAME_DOCK_IMPORTS_FILENAME), renderClientImportsModule(ctx), 'utf-8')
150-
await writeHubIndex(ctx, base, outDir, options)
151-
await writeConnectionMetas(ctx, base, outDir, resolveOutPath)
182+
await fs.writeFile(
183+
resolve(outDir, DEVFRAME_DOCK_IMPORTS_FILENAME),
184+
rebaseText(renderClientImportsModule(ctx)),
185+
'utf-8',
186+
)
187+
await writeHubIndex(ctx, base, outDir, options, deployBase)
188+
await writeConnectionMetas(ctx, base, outDir, resolveOutPath, rebaseValue)
152189

153190
console.log(c.cyan`[devframes-hub] writing RPC dump to ${resolve(outDir, '__rpc-dump')}`)
154191
const dump = await collectStaticRpcDump(ctx.rpc.definitions.values(), ctx)
192+
for (const file of Object.values(dump.files))
193+
file.data = rebaseValue(file.data)
155194
await writeStaticRpcDump(dump, outDir, { pretty: options.pretty })
156195

157196
const count = ctx.frames.length
@@ -160,6 +199,110 @@ export async function buildHub(options: BuildHubOptions): Promise<void> {
160199
: 's'} -> ${outDir}`)
161200
}
162201

202+
/** File types that can carry absolute URLs. */
203+
const TEXT_ASSET_EXTENSIONS = new Set([
204+
'.css',
205+
'.html',
206+
'.js',
207+
'.json',
208+
'.mjs',
209+
'.svg',
210+
])
211+
212+
/** Whether a root-absolute URL already sits under the deploy prefix. */
213+
function isUnderDeployBase(url: string, deployBase: string): boolean {
214+
return deployBase === '/' || url === deployBase || url.startsWith(deployBase)
215+
}
216+
217+
/**
218+
* `url` without the deploy prefix, so a served URL maps onto its on-disk
219+
* layout. The prefix moves URLs, not files.
220+
*/
221+
function stripDeployBase(url: string, deployBase: string): string {
222+
return deployBase !== '/' && url.startsWith(deployBase)
223+
? `/${url.slice(deployBase.length)}`
224+
: url
225+
}
226+
227+
/** Prefix a root-absolute URL with the deploy base. Idempotent. */
228+
function serveUrl(url: string, deployBase: string): string {
229+
if (!url.startsWith('/') || isUnderDeployBase(url, deployBase))
230+
return url
231+
return joinURL(deployBase, url)
232+
}
233+
234+
/**
235+
* Rewrite each URL prefix in a text asset, skipping occurrences that already
236+
* carry the deploy prefix.
237+
*/
238+
function createTextRebaser(
239+
rewrites: readonly (readonly [string, string])[],
240+
deployBase: string,
241+
): (text: string) => string {
242+
if (!rewrites.length || deployBase === '/')
243+
return text => text
244+
const prefixedBefore = deployBase.slice(0, -1)
245+
return (text) => {
246+
let result = text
247+
for (const [from, to] of rewrites) {
248+
result = result.replaceAll(from, (match: string, offset: number, whole: string) => {
249+
const alreadyPrefixed = offset >= prefixedBefore.length
250+
&& whole.startsWith(prefixedBefore, offset - prefixedBefore.length)
251+
return alreadyPrefixed ? match : to
252+
})
253+
}
254+
return result
255+
}
256+
}
257+
258+
/** Rebase strings in an RPC payload that start with a registered URL prefix. */
259+
function createUrlValueRebaser(
260+
rewrites: readonly (readonly [string, string])[],
261+
): <T>(value: T) => T {
262+
const rebaseString = (value: string): string => {
263+
for (const [from, to] of rewrites) {
264+
if (value === from.slice(0, -1))
265+
return to.slice(0, -1)
266+
if (value.startsWith(from))
267+
return `${to}${value.slice(from.length)}`
268+
}
269+
return value
270+
}
271+
const visit = <T>(value: T): T => {
272+
if (typeof value === 'string')
273+
return rebaseString(value) as T
274+
if (Array.isArray(value))
275+
return value.map(item => visit(item)) as T
276+
if (value && typeof value === 'object') {
277+
const prototype = Object.getPrototypeOf(value)
278+
if (prototype !== Object.prototype && prototype !== null)
279+
return value
280+
return Object.fromEntries(
281+
Object.entries(value).map(([key, item]) => [
282+
key,
283+
visit(item),
284+
]),
285+
) as T
286+
}
287+
return value
288+
}
289+
return visit
290+
}
291+
292+
/** Rewrite the text assets under a copied static dir in place. */
293+
async function rebaseTextAssets(dir: string, rebase: (text: string) => string): Promise<void> {
294+
const entries = await fs.readdir(dir, { recursive: true, withFileTypes: true })
295+
for (const entry of entries) {
296+
if (!entry.isFile() || !TEXT_ASSET_EXTENSIONS.has(extname(entry.name)))
297+
continue
298+
const filepath = resolve(entry.parentPath, entry.name)
299+
const text = await fs.readFile(filepath, 'utf-8')
300+
const next = rebase(text)
301+
if (next !== text)
302+
await fs.writeFile(filepath, next, 'utf-8')
303+
}
304+
}
305+
163306
/**
164307
* Build a `mode: 'build'` hub context and mount the `devframes` input. The host
165308
* copies nothing live (`mountStatic`/`mountConnectionMeta` are no-ops): every
@@ -213,7 +356,11 @@ async function createAndMountContext(options: BuildHubOptions, base: string, cwd
213356
* remote source (e.g. a plugin's `--assets` package) resolves to the same
214357
* locally-installed copy it would serve live.
215358
*/
216-
async function copyBuildStatics(ctx: DevframeHubContext, resolveOutPath: (urlBase: string) => string): Promise<void> {
359+
async function copyBuildStatics(
360+
ctx: DevframeHubContext,
361+
resolveOutPath: (urlBase: string) => string,
362+
rebaseText?: (text: string) => string,
363+
): Promise<void> {
217364
const storageDir = ctx.host.getStorageDir('project')
218365
for (const { baseUrl, source, resolveFrom } of ctx.views.buildStaticDirs) {
219366
const target = resolveOutPath(baseUrl)
@@ -223,6 +370,8 @@ async function copyBuildStatics(ctx: DevframeHubContext, resolveOutPath: (urlBas
223370
await fs.cp(resolved, target, { recursive: true })
224371
else
225372
await resolved.materialize(target)
373+
if (rebaseText)
374+
await rebaseTextAssets(target, rebaseText)
226375
}
227376
}
228377

@@ -278,12 +427,17 @@ async function writeHubIndex(
278427
base: string,
279428
outDir: string,
280429
options: BuildHubOptions,
430+
deployBase: string,
281431
): Promise<void> {
282432
await fs.writeFile(resolve(outDir, '__index.json'), `${JSON.stringify({
283433
name: options.name,
284434
version: options.version,
285435
base,
286-
frames: ctx.frames.map(({ id, base, title }) => ({ id, base, title })),
436+
frames: ctx.frames.map(({ id, base, title }) => ({
437+
id,
438+
base: serveUrl(base, deployBase),
439+
title,
440+
})),
287441
endpoints: {
288442
connection: DEVFRAME_CONNECTION_META_FILENAME,
289443
clientImports: DEVFRAME_DOCK_IMPORTS_FILENAME,
@@ -307,19 +461,20 @@ async function writeConnectionMetas(
307461
base: string,
308462
outDir: string,
309463
resolveOutPath: (urlBase: string) => string,
464+
rebaseValue: <T>(value: T) => T,
310465
): Promise<void> {
311466
const jsonSerializableMethods: string[] = []
312467
for (const def of ctx.rpc.definitions.values()) {
313468
if (def.jsonSerializable === true)
314469
jsonSerializableMethods.push(def.name)
315470
}
316-
const meta: ConnectionMeta = {
471+
const meta: ConnectionMeta = rebaseValue({
317472
backend: 'static',
318473
jsonSerializableMethods,
319474
...(Object.keys(ctx.staticConfig).length > 0
320475
? { configs: ctx.staticConfig }
321476
: {}),
322-
}
477+
} satisfies ConnectionMeta)
323478
await fs.writeFile(resolve(outDir, DEVFRAME_CONNECTION_META_FILENAME), JSON.stringify(meta, null, 2), 'utf-8')
324479
const frameMeta: ConnectionMeta = {
325480
...meta,

0 commit comments

Comments
 (0)