oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1// fixtures/build-bundles.mjs — run by a person, output committed.
2// The app performs no build step (spec §6.5); this produces the
3// artifact that makes that true: a single, minified, content-hashed
4// JS bundle committed to internal/docs/static/, embedded into the Go
5// binary by internal/docs/assets.go's //go:embed static.
6//
7// internal/docs/static/, not a top-level static/: Go's //go:embed
8// cannot reach outside (or above) the directory of the .go file doing
9// the embedding — no ".." is allowed in an embed pattern — so the
10// tree assets.go embeds has to live under internal/docs/, the same
11// way internal/docs/views/*.html already does for this app's page
12// templates.
13//
14// Paths below are resolved from this file's own location
15// (fixtures/generate.mjs's own pattern), not from the caller's
16// working directory, so `node build-bundles.mjs` works the same
17// whether it's run from fixtures/ or anywhere else.
18import { build } from 'esbuild'
19import { createHash } from 'node:crypto'
20import { readFileSync, writeFileSync, rmSync, readdirSync, mkdirSync } from 'node:fs'
21import { join, dirname } from 'node:path'
22import { fileURLToPath } from 'node:url'
23import { bundles, options } from './bundles.mjs'
24
25const here = dirname(fileURLToPath(import.meta.url))
26const staticDir = join(here, '..', 'internal', 'docs', 'static')
27
28mkdirSync(staticDir, { recursive: true })
29
30// The bundles, and the options they are built with, are bundles.mjs's
31// (shared with colophon-inputs.mjs, which names what is inside them).
32
33for (const { name, entry, format = 'esm' } of bundles) {
34 const outfile = join(staticDir, `${name}.js`)
35 await build({
36 ...options,
37 entryPoints: [join(here, entry)],
38 format,
39 outfile
40 })
41
42 // Content hash in the filename so the asset is immutable-cacheable
43 // and a stale browser cache cannot serve a bundle that disagrees
44 // with the server (internal/docs/assets.go's own doc comment).
45 const bytes = readFileSync(outfile)
46 const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 16)
47
48 // Exactly one file per bundle must ever be committed — assets.go
49 // panics at init if it finds more or less than one — so a rebuild
50 // must remove every previous hashed file for THIS name before
51 // writing the new one. The regex is anchored to the name so
52 // rebuilding one bundle never deletes the other's.
53 const stale = new RegExp(`^${name}\\.[0-9a-f]{16}\\.js$`)
54 for (const f of readdirSync(staticDir)) {
55 if (stale.test(f)) rmSync(join(staticDir, f))
56 }
57 writeFileSync(join(staticDir, `${name}.${hash}.js`), bytes)
58 rmSync(outfile)
59
60 console.log(`wrote internal/docs/static/${name}.${hash}.js (${bytes.length} bytes)`)
61}
62