perf(tui): shrink standalone builds and target native bindings (#6432)
* perf(tui): shrink standalone builds without dropping features * fix(tui): resolve macOS diagram fonts through CoreText * fix(webui): preserve history pagination at the page boundary * docs(tui): streamline release preflight guidance --------- Co-authored-by: Xubin Ren <52506698+Re-bin@users.noreply.github.com>
This commit is contained in:
1 parent
0e0df327c8
commit
ae7fed88e2
21 files changed
+424
-82
No files matched your search
+28
-23
@@ -1,36 +1,24 @@
|
||||
import { chmod, mkdir } from "node:fs/promises"
|
||||
import { basename, join } from "node:path"
|
||||
import { targetBindings } from "./target-bindings"
|
||||
import { nativePackages, targetPlan } from "./targets"
|
||||
|
||||
const target = process.argv[2] || `${process.platform}-${process.arch}`
|
||||
const [platform, arch] = target.split("-")
|
||||
const supportedTargets = new Set([
|
||||
"darwin-arm64",
|
||||
"darwin-x64",
|
||||
"linux-arm64",
|
||||
"linux-x64",
|
||||
"win32-x64",
|
||||
])
|
||||
|
||||
if (!platform || !arch || !supportedTargets.has(target)) {
|
||||
throw new Error(`unsupported target: ${target}`)
|
||||
}
|
||||
|
||||
const bunPlatform = platform === "win32" ? "windows" : platform
|
||||
// Wheels cannot select a CPU feature level: avoid the default AVX2-only x64 runtime.
|
||||
const cpuVariant = arch === "x64" ? "-baseline" : ""
|
||||
const extension = platform === "win32" ? ".exe" : ""
|
||||
const outputDir = join(import.meta.dir, "..", "dist")
|
||||
const output = join(outputDir, `nanobot-tui-${platform}-${arch}${extension}`)
|
||||
const plan = targetPlan(process.argv[2] || `${process.platform}-${process.arch}`)
|
||||
const root = join(import.meta.dir, "..")
|
||||
const outputDir = join(root, "dist")
|
||||
const output = join(outputDir, plan.executable)
|
||||
|
||||
await mkdir(outputDir, { recursive: true })
|
||||
const result = await Bun.build({
|
||||
entrypoints: [join(import.meta.dir, "..", "src", "index.ts")],
|
||||
define: { NANOBOT_COMPILED: "true" },
|
||||
bytecode: true,
|
||||
// Standalone files retain JS; the optional precompiled cache costs another ~22 MiB on x64.
|
||||
bytecode: false,
|
||||
format: "esm",
|
||||
plugins: [await targetBindings(plan, root)],
|
||||
minify: { whitespace: true, syntax: true, identifiers: true, keepNames: true },
|
||||
compile: {
|
||||
target: `bun-${bunPlatform}-${arch}${cpuVariant}` as Bun.Build.CompileTarget,
|
||||
target: plan.bunTarget,
|
||||
outfile: output,
|
||||
},
|
||||
})
|
||||
@@ -39,9 +27,26 @@ if (!result.success) {
|
||||
for (const log of result.logs) console.error(log)
|
||||
process.exit(1)
|
||||
}
|
||||
if (platform !== "win32") await chmod(output, 0o755)
|
||||
if (plan.platform !== "win32") await chmod(output, 0o755)
|
||||
const bytes = Bun.file(output).size
|
||||
const digest = new Bun.CryptoHasher("sha256")
|
||||
.update(await Bun.file(output).arrayBuffer())
|
||||
.digest("hex")
|
||||
await Bun.write(`${output}.sha256`, `${digest} ${basename(output)}\n`)
|
||||
await Bun.write(`${output}.size.json`, JSON.stringify({
|
||||
phase: "compiled", // macOS signing happens later; the archive manifest owns final hashes.
|
||||
target: plan.id,
|
||||
bunTarget: plan.bunTarget,
|
||||
bunVersion: Bun.version,
|
||||
bunRevision: Bun.revision,
|
||||
bytecode: false,
|
||||
executable: basename(output),
|
||||
bytes,
|
||||
sha256: digest,
|
||||
budgetBytes: plan.executableBudgetBytes,
|
||||
expectedNativePackages: nativePackages(plan),
|
||||
}, null, 2) + "\n")
|
||||
if (bytes > plan.executableBudgetBytes) {
|
||||
throw new Error(`${plan.id} executable is ${bytes} bytes; budget is ${plan.executableBudgetBytes}`)
|
||||
}
|
||||
console.log(output)
|
||||
@@ -48,6 +48,8 @@ def _source_archive(root: Path) -> bytes:
|
||||
"tsconfig.json",
|
||||
"src",
|
||||
"scripts/build.ts",
|
||||
"scripts/targets.ts",
|
||||
"scripts/target-bindings.ts",
|
||||
"scripts/prepare-target.ts",
|
||||
"scripts/release-notices.ts",
|
||||
"scripts/package-release.py",
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
import { join } from "node:path"
|
||||
|
||||
const packagesByTarget: Record<string, string[]> = {
|
||||
"darwin-arm64": ["@opentui/core-darwin-arm64", "@resvg/resvg-js-darwin-arm64"],
|
||||
"darwin-x64": ["@opentui/core-darwin-x64", "@resvg/resvg-js-darwin-x64"],
|
||||
"linux-arm64": ["@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@resvg/resvg-js-linux-arm64-gnu", "@resvg/resvg-js-linux-arm64-musl"],
|
||||
"linux-x64": ["@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@resvg/resvg-js-linux-x64-gnu", "@resvg/resvg-js-linux-x64-musl"],
|
||||
"win32-x64": ["@opentui/core-win32-x64", "@resvg/resvg-js-win32-x64-msvc"],
|
||||
}
|
||||
import { nativePackages, targetPlan } from "./targets"
|
||||
|
||||
const target = process.argv[2]
|
||||
if (!target) throw new Error("target is required")
|
||||
const packages = packagesByTarget[target]
|
||||
if (!packages) throw new Error(`unsupported target: ${target}`)
|
||||
const packages = nativePackages(targetPlan(target))
|
||||
|
||||
const root = join(import.meta.dir, "..")
|
||||
const manifest = await Bun.file(join(root, "package.json")).json()
|
||||
|
||||
@@ -1,28 +1,14 @@
|
||||
import { readdir, readFile, writeFile } from "node:fs/promises"
|
||||
import { basename, join } from "node:path"
|
||||
import { nativePackages, targetPlan } from "./targets"
|
||||
|
||||
const target = process.argv[2]
|
||||
if (!target) throw new Error("target is required")
|
||||
const supportedTargets = new Set([
|
||||
"darwin-arm64",
|
||||
"darwin-x64",
|
||||
"linux-arm64",
|
||||
"linux-x64",
|
||||
"win32-x64",
|
||||
])
|
||||
if (!supportedTargets.has(target)) throw new Error(`unsupported target: ${target}`)
|
||||
const nativePackagesByTarget: Record<string, string[]> = {
|
||||
"darwin-arm64": ["@opentui/core-darwin-arm64", "@resvg/resvg-js-darwin-arm64"],
|
||||
"darwin-x64": ["@opentui/core-darwin-x64", "@resvg/resvg-js-darwin-x64"],
|
||||
"linux-arm64": ["@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@resvg/resvg-js-linux-arm64-gnu", "@resvg/resvg-js-linux-arm64-musl"],
|
||||
"linux-x64": ["@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@resvg/resvg-js-linux-x64-gnu", "@resvg/resvg-js-linux-x64-musl"],
|
||||
"win32-x64": ["@opentui/core-win32-x64", "@resvg/resvg-js-win32-x64-msvc"],
|
||||
}
|
||||
const plan = targetPlan(target)
|
||||
|
||||
const root = join(import.meta.dir, "..")
|
||||
const projectRoot = join(root, "..")
|
||||
const extension = target.startsWith("win32-") ? ".exe" : ""
|
||||
const asset = `nanobot-tui-${target}${extension}`
|
||||
const asset = plan.executable
|
||||
const output = join(root, "dist", `${asset}.THIRD_PARTY_NOTICES.txt`)
|
||||
|
||||
type PackageNotice = {
|
||||
@@ -112,7 +98,7 @@ const notices = await Promise.all(
|
||||
(await runtimePackageRoots(root)).map(readPackageNotice),
|
||||
)
|
||||
const packagedNames = new Set(notices.map((notice) => notice.name))
|
||||
for (const name of nativePackagesByTarget[target] ?? []) {
|
||||
for (const name of nativePackages(plan)) {
|
||||
if (!packagedNames.has(name)) throw new Error(`target runtime package is missing: ${name}`)
|
||||
}
|
||||
const sections = [
|
||||
@@ -122,7 +108,7 @@ const sections = [
|
||||
"Runtime: Bun 1.3.13",
|
||||
"The release archive also contains SOURCE_OFFER.md, RELINKING.md, and the complete TUI application source.",
|
||||
"fontkit 2.0.4, dfa 1.2.0 and brotli 1.3.3 declare MIT in their included README notices.",
|
||||
"resvg's unmodified native binding includes its upstream MPL-2.0 text; source is listed in RELINKING.md.",
|
||||
"resvg's public wrapper and native binding are unmodified; its internal loader is target-selected. MPL-2.0 source is listed in RELINKING.md.",
|
||||
"",
|
||||
"===== nanobot project license =====",
|
||||
"",
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { targetBindings } from "./target-bindings"
|
||||
import { nativePackages, targetPlan } from "./targets"
|
||||
|
||||
const roots: string[] = []
|
||||
afterEach(async () => {
|
||||
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
|
||||
})
|
||||
|
||||
async function fixture(): Promise<string> {
|
||||
const root = await mkdtemp(join(tmpdir(), "nanobot-target-bindings-"))
|
||||
roots.push(root)
|
||||
await writeFile(join(root, "package.json"), "{}")
|
||||
const wrapper = join(root, "node_modules", "@resvg", "resvg-js")
|
||||
await cp(join(import.meta.dir, "..", "node_modules", "@resvg", "resvg-js"), wrapper, { recursive: true })
|
||||
for (const name of [
|
||||
"resvg-js-win32-x64-msvc", "resvg-js-darwin-arm64", "resvg-js-darwin-x64",
|
||||
"resvg-js-linux-x64-gnu", "resvg-js-linux-x64-musl", "resvg-js-linux-arm64-gnu", "resvg-js-linux-arm64-musl",
|
||||
]) {
|
||||
const path = join(root, "node_modules", "@resvg", name)
|
||||
await mkdir(path, { recursive: true })
|
||||
await writeFile(join(path, "package.json"), JSON.stringify({ name: `@resvg/${name}`, version: "2.6.2", main: "index.js" }))
|
||||
await writeFile(join(path, "index.js"), `
|
||||
class Resvg {
|
||||
constructor(svg, options) { this.binding = ${JSON.stringify(name)}; this.svg = svg; this.options = JSON.parse(options); }
|
||||
}
|
||||
module.exports = { Resvg, renderAsync: async (svg, options) => ({ svg, options: JSON.parse(options) }) };
|
||||
`)
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
async function bundle(root: string, target?: string, libc?: "gnu" | "musl") {
|
||||
const entry = join(root, "entry.js")
|
||||
await writeFile(entry, `
|
||||
${libc ? `process.report.getReport = () => ({ header: { glibcVersionRuntime: ${libc === "gnu" ? '"2.34"' : "undefined"} } });` : ""}
|
||||
const { Resvg, renderAsync } = require("@resvg/resvg-js");
|
||||
const options = { fitTo: { mode: "width", value: 321 } };
|
||||
console.log(JSON.stringify({ image: new Resvg("<svg/>", options), asyncImage: await renderAsync("<svg/>", options) }));
|
||||
`)
|
||||
const result = await Bun.build({
|
||||
entrypoints: [entry],
|
||||
outdir: join(root, "out"),
|
||||
target: "bun",
|
||||
metafile: true,
|
||||
plugins: target ? [await targetBindings(targetPlan(target), root)] : [],
|
||||
})
|
||||
if (!result.success) throw new Error(result.logs.map(String).join("\n"))
|
||||
const run = Bun.spawn([process.execPath, join(root, "out", "entry.js")], { stdout: "pipe", stderr: "pipe" })
|
||||
const [stdout, stderr, code] = await Promise.all([new Response(run.stdout).text(), new Response(run.stderr).text(), run.exited])
|
||||
expect(code, stderr).toBe(0)
|
||||
return { value: JSON.parse(stdout), inputs: Object.keys(result.metafile?.inputs ?? {}).map((path) => path.replaceAll("\\", "/")) }
|
||||
}
|
||||
|
||||
test("cross-target binding selection excludes installed host payloads and preserves the public wrapper", async () => {
|
||||
const root = await fixture()
|
||||
const original = await bundle(root)
|
||||
const selected = await bundle(root, "win32-x64")
|
||||
// Both host libc variants are installed: the generic loader pulls them into the bundle.
|
||||
expect(original.inputs.filter((path) => /resvg-js-linux-x64-.*\/index\.js$/.test(path))).toHaveLength(2)
|
||||
expect(selected.inputs.filter((path) => /resvg-js-.*\/index\.js$/.test(path))).toHaveLength(1)
|
||||
expect(selected.value).toEqual({
|
||||
image: { binding: "resvg-js-win32-x64-msvc", svg: "<svg/>", options: { fitTo: { mode: "width", value: 321 } } },
|
||||
asyncImage: { svg: "<svg/>", options: { fitTo: { mode: "width", value: 321 } } },
|
||||
})
|
||||
})
|
||||
|
||||
for (const libc of ["gnu", "musl"] as const) {
|
||||
test(`Linux target retains both native variants and selects ${libc}`, async () => {
|
||||
const root = await fixture()
|
||||
const result = await bundle(root, "linux-x64", libc)
|
||||
expect(result.value.image.binding).toBe(`resvg-js-linux-x64-${libc}`)
|
||||
expect(result.inputs.filter((path) => /resvg-js-linux-x64-.*\/index\.js$/.test(path))).toHaveLength(2)
|
||||
expect(nativePackages(targetPlan("linux-x64"))).toEqual([
|
||||
"@opentui/core-linux-x64", "@resvg/resvg-js-linux-x64-gnu",
|
||||
"@opentui/core-linux-x64-musl", "@resvg/resvg-js-linux-x64-musl",
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
test("dependency loader changes require an explicit build-adapter review", async () => {
|
||||
const root = await fixture()
|
||||
await writeFile(join(root, "node_modules", "@resvg", "resvg-js", "js-binding.js"), "module.exports = {}")
|
||||
await expect(targetBindings(targetPlan("win32-x64"), root)).rejects.toThrow("js-binding.js changed")
|
||||
})
|
||||
@@ -0,0 +1,58 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
// Target-specific replacement for resvg-js 2.6.2's generated binding loader.
|
||||
import { createRequire } from "node:module"
|
||||
import { dirname, join, resolve } from "node:path"
|
||||
import type { BunPlugin } from "bun"
|
||||
import type { TargetPlan } from "./targets"
|
||||
|
||||
// This adapter replaces only the generated loader, not resvg's public options wrapper.
|
||||
// Review the loader contract and these identities together when updating resvg.
|
||||
const resvgVersion = "2.6.2"
|
||||
const resvgSources = {
|
||||
"index.js": "b670803d88b380b0610edf743d8b74dcc132d9e2aa6aaa04cfaa06b2fcad397d",
|
||||
"js-binding.js": "d5fbe3b7450d1e393ea9856e86e16465d25be8743cae7db03e2f3249aed61e56",
|
||||
}
|
||||
|
||||
export async function targetBindings(plan: TargetPlan, root: string): Promise<BunPlugin> {
|
||||
const require = createRequire(join(root, "package.json"))
|
||||
const entry = require.resolve("@resvg/resvg-js")
|
||||
const packageRoot = dirname(entry)
|
||||
const manifest = await Bun.file(join(packageRoot, "package.json")).json()
|
||||
if (manifest.version !== resvgVersion) throw new Error(`review resvg target bindings for version ${manifest.version}`)
|
||||
for (const [name, expected] of Object.entries(resvgSources)) {
|
||||
const digest = new Bun.CryptoHasher("sha256").update(await Bun.file(join(packageRoot, name)).arrayBuffer()).digest("hex")
|
||||
if (digest !== expected) throw new Error(`review resvg target bindings: ${name} changed`)
|
||||
}
|
||||
|
||||
// Absolute resolutions keep the virtual module independent of the build host's cwd.
|
||||
const binding = (name: string) => `require(${JSON.stringify(require.resolve(name))})`
|
||||
const load = plan.platform === "linux"
|
||||
? `
|
||||
function isMusl() {
|
||||
if (!process.report || typeof process.report.getReport !== "function") {
|
||||
try {
|
||||
const lddPath = require("node:child_process").execSync("which ldd").toString().trim();
|
||||
return require("node:fs").readFileSync(lddPath, "utf8").includes("musl");
|
||||
} catch { return true; }
|
||||
}
|
||||
return !process.report.getReport().header.glibcVersionRuntime;
|
||||
}
|
||||
const nativeBinding = isMusl() ? ${binding(plan.bindings.musl.resvg)} : ${binding(plan.bindings.gnu.resvg)};
|
||||
`
|
||||
: `const nativeBinding = ${binding(plan.bindings.native.resvg)};`
|
||||
const contents = `${load}
|
||||
const { BBox, Resvg, RenderedImage, renderAsync } = nativeBinding;
|
||||
module.exports = { BBox, Resvg, RenderedImage, renderAsync };
|
||||
`
|
||||
|
||||
return {
|
||||
name: "nanobot-resvg-target",
|
||||
setup(builder) {
|
||||
builder.onResolve({ filter: /^\.\/js-binding\.js$/ }, (args) => {
|
||||
if (resolve(args.importer) === resolve(entry)) return { path: "binding", namespace: "nanobot-resvg" }
|
||||
return undefined
|
||||
})
|
||||
builder.onLoad({ filter: /^binding$/, namespace: "nanobot-resvg" }, () => ({ contents, loader: "js" }))
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
type NativePair = Readonly<{ opentui: string; resvg: string }>
|
||||
|
||||
type TargetSpec = Readonly<{
|
||||
bunTarget: Bun.Build.CompileTarget
|
||||
executableBudgetBytes: number
|
||||
}> & (
|
||||
| { platform: "linux"; bindings: { gnu: NativePair; musl: NativePair } }
|
||||
| { platform: "darwin" | "win32"; bindings: { native: NativePair } }
|
||||
)
|
||||
|
||||
const MiB = 1024 * 1024
|
||||
// Wheels cannot select CPU features: every x64 target uses Bun's baseline runtime.
|
||||
// Unmeasured arm64/macOS targets retain the existing 150 MiB archive limit.
|
||||
const targets = {
|
||||
"darwin-arm64": {
|
||||
platform: "darwin", bunTarget: "bun-darwin-arm64", executableBudgetBytes: 150 * MiB,
|
||||
bindings: { native: { opentui: "@opentui/core-darwin-arm64", resvg: "@resvg/resvg-js-darwin-arm64" } },
|
||||
},
|
||||
"darwin-x64": {
|
||||
platform: "darwin", bunTarget: "bun-darwin-x64-baseline", executableBudgetBytes: 150 * MiB,
|
||||
bindings: { native: { opentui: "@opentui/core-darwin-x64", resvg: "@resvg/resvg-js-darwin-x64" } },
|
||||
},
|
||||
"linux-arm64": {
|
||||
platform: "linux", bunTarget: "bun-linux-arm64", executableBudgetBytes: 150 * MiB,
|
||||
bindings: {
|
||||
gnu: { opentui: "@opentui/core-linux-arm64", resvg: "@resvg/resvg-js-linux-arm64-gnu" },
|
||||
musl: { opentui: "@opentui/core-linux-arm64-musl", resvg: "@resvg/resvg-js-linux-arm64-musl" },
|
||||
},
|
||||
},
|
||||
"linux-x64": {
|
||||
platform: "linux", bunTarget: "bun-linux-x64-baseline", executableBudgetBytes: 135 * MiB,
|
||||
bindings: {
|
||||
gnu: { opentui: "@opentui/core-linux-x64", resvg: "@resvg/resvg-js-linux-x64-gnu" },
|
||||
musl: { opentui: "@opentui/core-linux-x64-musl", resvg: "@resvg/resvg-js-linux-x64-musl" },
|
||||
},
|
||||
},
|
||||
"win32-x64": {
|
||||
platform: "win32", bunTarget: "bun-windows-x64-baseline", executableBudgetBytes: 135 * MiB,
|
||||
bindings: { native: { opentui: "@opentui/core-win32-x64", resvg: "@resvg/resvg-js-win32-x64-msvc" } },
|
||||
},
|
||||
} as const satisfies Record<string, TargetSpec>
|
||||
|
||||
export type TargetPlan = TargetSpec & { id: keyof typeof targets; executable: string }
|
||||
|
||||
export function targetPlan(raw: string): TargetPlan {
|
||||
if (!Object.hasOwn(targets, raw)) throw new Error(`unsupported target: ${raw}`)
|
||||
const id = raw as keyof typeof targets
|
||||
const spec = targets[id]
|
||||
return { ...spec, id, executable: `nanobot-tui-${id}${spec.platform === "win32" ? ".exe" : ""}` }
|
||||
}
|
||||
|
||||
export function nativePackages(plan: TargetPlan): string[] {
|
||||
return Object.values(plan.bindings).flatMap((pair: NativePair) => [pair.opentui, pair.resvg])
|
||||
}
|
||||
Reference in new issue
Block a user