-
Notifications
You must be signed in to change notification settings - Fork 136
Expand file tree
/
Copy pathbuild.ts
More file actions
executable file
·338 lines (308 loc) · 10.9 KB
/
Copy pathbuild.ts
File metadata and controls
executable file
·338 lines (308 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/usr/bin/env bun
import { $ } from "bun"
import fs from "fs"
import path from "path"
import { fileURLToPath } from "url"
import solidPlugin from "@opentui/solid/bun-plugin"
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const dir = path.resolve(__dirname, "..")
process.chdir(dir)
import { Script } from "@opencode-ai/script"
import pkg from "../package.json"
// Python engine has been eliminated — all methods run natively in TypeScript.
// ALTIMATE_ENGINE_VERSION is no longer needed at runtime.
// Read CHANGELOG.md for bundling
const changelogPath = path.resolve(dir, "../../CHANGELOG.md")
const changelog = fs.existsSync(changelogPath) ? await Bun.file(changelogPath).text() : ""
console.log(`Loaded CHANGELOG.md (${changelog.length} chars)`)
const modelsUrl = process.env.OPENCODE_MODELS_URL || "https://models.dev"
// Fetch and generate models.dev snapshot
const modelsData = process.env.MODELS_DEV_API_JSON
? await Bun.file(process.env.MODELS_DEV_API_JSON).text()
: await fetch(`${modelsUrl}/api.json`).then((x) => x.text())
await Bun.write(
path.join(dir, "src/provider/models-snapshot.ts"),
`// Auto-generated by build.ts - do not edit\nexport const snapshot = ${modelsData.trim()} as const\n`,
)
console.log("Generated models-snapshot.ts")
// Load migrations from migration directories
const migrationDirs = (
await fs.promises.readdir(path.join(dir, "migration"), {
withFileTypes: true,
})
)
.filter((entry) => entry.isDirectory() && /^\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}/.test(entry.name))
.map((entry) => entry.name)
.sort()
const migrations = await Promise.all(
migrationDirs.map(async (name) => {
const file = path.join(dir, "migration", name, "migration.sql")
const sql = await Bun.file(file).text()
const match = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(name)
const timestamp = match
? Date.UTC(
Number(match[1]),
Number(match[2]) - 1,
Number(match[3]),
Number(match[4]),
Number(match[5]),
Number(match[6]),
)
: 0
return { sql, timestamp, name }
}),
)
console.log(`Loaded ${migrations.length} migrations`)
// Load builtin skills from .opencode/skills/ directory for embedding in binary.
// This ensures skills are available in ALL distribution channels (npm, Homebrew, AUR, Docker)
// without relying on postinstall filesystem copies.
const skillsRoot = path.resolve(dir, "../../.opencode/skills")
const skillEntries = fs.existsSync(skillsRoot)
? (await fs.promises.readdir(skillsRoot, { withFileTypes: true })).filter((e) => e.isDirectory())
: []
const builtinSkills: { name: string; content: string }[] = []
for (const entry of skillEntries) {
const skillFile = path.join(skillsRoot, entry.name, "SKILL.md")
if (!fs.existsSync(skillFile)) continue
const content = await Bun.file(skillFile).text()
builtinSkills.push({ name: entry.name, content })
}
console.log(`Loaded ${builtinSkills.length} builtin skills`)
if (Script.release && builtinSkills.length === 0) {
console.error("No builtin skills were loaded from ../../.opencode/skills; aborting release build.")
process.exit(1)
}
const singleFlag = process.argv.includes("--single")
const baselineFlag = process.argv.includes("--baseline")
const skipInstall = process.argv.includes("--skip-install")
const allTargets: {
os: string
arch: "arm64" | "x64"
abi?: "musl"
avx2?: false
}[] = [
{
os: "linux",
arch: "arm64",
},
{
os: "linux",
arch: "x64",
},
{
os: "linux",
arch: "x64",
avx2: false,
},
{
os: "linux",
arch: "arm64",
abi: "musl",
},
{
os: "linux",
arch: "x64",
abi: "musl",
},
{
os: "linux",
arch: "x64",
abi: "musl",
avx2: false,
},
{
os: "darwin",
arch: "arm64",
},
{
os: "darwin",
arch: "x64",
},
{
os: "darwin",
arch: "x64",
avx2: false,
},
{
os: "win32",
arch: "arm64",
},
{
os: "win32",
arch: "x64",
},
{
os: "win32",
arch: "x64",
avx2: false,
},
]
// If --targets is provided, filter to only matching OS values
const validOsValues = new Set(allTargets.map(t => t.os))
const targetsFlag = process.argv.find(a => a.startsWith('--targets='))?.split('=')[1]?.split(',')
if (targetsFlag) {
const invalid = targetsFlag.filter(t => !validOsValues.has(t))
if (invalid.length > 0) {
console.error(`error: invalid --targets value(s): ${invalid.join(', ')}. Valid values: ${[...validOsValues].join(', ')}`)
process.exit(1)
}
}
// --target-index=N builds a single target by index (for parallel CI matrix)
const targetIndexFlag = process.argv.find(a => a.startsWith('--target-index='))?.split('=')[1]
const targets = targetIndexFlag !== undefined
? [allTargets[parseInt(targetIndexFlag, 10)]].filter(Boolean)
: singleFlag
? allTargets.filter((item) => {
if (item.os !== process.platform || item.arch !== process.arch) {
return false
}
// When building for the current platform, prefer a single native binary by default.
// Baseline binaries require additional Bun artifacts and can be flaky to download.
if (item.avx2 === false) {
return baselineFlag
}
// also skip abi-specific builds for the same reason
if (item.abi !== undefined) {
return false
}
return true
})
: targetsFlag
? allTargets.filter(t => targetsFlag.includes(t.os))
: allTargets
await $`rm -rf dist`
// Packages excluded from the compiled binary — must be resolvable from
// node_modules at runtime. Split into required (must ship with the wrapper
// package) and optional (user installs on demand).
const requiredExternals = [
// NAPI native module — cannot be embedded in Bun single-file executable.
"@altimateai/altimate-core",
]
const optionalExternals = [
// Database drivers — native addons, users install on demand per warehouse
"pg", "snowflake-sdk", "@google-cloud/bigquery", "@databricks/sql",
"mysql2", "mssql", "oracledb", "duckdb",
// Optional infra packages — native addons or heavy optional deps
"keytar", "ssh2", "dockerode",
]
const binaries: Record<string, string> = {}
if (!skipInstall) {
await $`bun install --os="*" --cpu="*" @opentui/core@${pkg.dependencies["@opentui/core"]}`
await $`bun install --os="*" --cpu="*" @parcel/watcher@${pkg.dependencies["@parcel/watcher"]}`
}
for (const item of targets) {
const name = [
pkg.name,
// changing to win32 flags npm for some reason
item.os === "win32" ? "windows" : item.os,
item.arch,
item.avx2 === false ? "baseline" : undefined,
item.abi === undefined ? undefined : item.abi,
]
.filter(Boolean)
.join("-")
console.log(`building ${name}`)
await $`mkdir -p dist/${name}/bin`
const opentuiCoreDir = path.dirname(fileURLToPath(import.meta.resolve("@opentui/core")))
const parserWorker = fs.realpathSync(path.join(opentuiCoreDir, "parser.worker.js"))
const workerPath = "./src/cli/cmd/tui/worker.ts"
// Use platform-specific bunfs root path based on target OS
const bunfsRoot = item.os === "win32" ? "B:/~BUN/root/" : "/$bunfs/root/"
const workerRelativePath = path.relative(dir, parserWorker).replaceAll("\\", "/")
await Bun.build({
conditions: ["browser"],
tsconfig: "./tsconfig.json",
plugins: [solidPlugin],
sourcemap: "external",
// IMPORTANT: Without code splitting, Bun inlines dynamic import() targets
// into the main chunk. Any external require() in those targets will fail
// at startup — not when the import() is called. Only mark packages as
// external when they truly cannot be bundled (e.g. NAPI native addons).
external: [...requiredExternals, ...optionalExternals],
compile: {
autoloadBunfig: false,
autoloadDotenv: false,
autoloadTsconfig: true,
autoloadPackageJson: true,
target: name.replace(pkg.name, "bun") as any,
outfile: `dist/${name}/bin/altimate`,
execArgv: [`--user-agent=altimate/${Script.version}`, "--use-system-ca", "--"],
windows: {},
},
entrypoints: ["./src/index.ts", parserWorker, workerPath],
define: {
OPENCODE_VERSION: `'${Script.version}'`,
OPENCODE_CHANNEL: `'${Script.channel}'`,
// ALTIMATE_ENGINE_VERSION removed — Python engine eliminated
OPENCODE_LIBC: item.os === "linux" ? `'${item.abi ?? "glibc"}'` : "undefined",
OPENCODE_MIGRATIONS: JSON.stringify(migrations),
OPENCODE_BUILTIN_SKILLS: JSON.stringify(builtinSkills),
OPENCODE_CHANGELOG: JSON.stringify(changelog),
OPENCODE_WORKER_PATH: workerPath,
OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + workerRelativePath,
},
})
// Create backward-compatible altimate-code alias
if (item.os === "win32") {
await $`cp dist/${name}/bin/altimate.exe dist/${name}/bin/altimate-code.exe`.nothrow()
} else {
await $`ln -sf altimate dist/${name}/bin/altimate-code`.nothrow()
}
await $`rm -rf ./dist/${name}/bin/tui`
await Bun.file(`dist/${name}/package.json`).write(
JSON.stringify(
{
name,
version: Script.version,
os: [item.os],
cpu: [item.arch],
},
null,
2,
),
)
binaries[name] = Script.version
}
// ---------------------------------------------------------------------------
// Build-time verification: ensure required externals are in package.json
// dependencies so they ship with the npm wrapper package. This catches the
// scenario where a new NAPI module is added to `external` but not to
// package.json dependencies — which would compile fine but crash at runtime.
// ---------------------------------------------------------------------------
{
// Only check dependencies (not devDependencies) — publish.ts only ships
// dependencies to end users. A required external in devDependencies would
// pass this check but be missing for npm users.
const pkgDeps: Record<string, string> = {
...pkg.dependencies,
}
const missing = requiredExternals.filter((ext) => !pkgDeps[ext])
if (missing.length > 0) {
const msg =
`Required external(s) not in package.json: ${missing.join(", ")}\n` +
`These packages are marked as external in the binary build but are not\n` +
`listed as dependencies. The binary will crash at runtime.\n` +
`Add them to "dependencies" in packages/opencode/package.json.`
if (Script.release) {
console.error(`FATAL: ${msg}`)
process.exit(1)
} else {
console.warn(`WARNING: ${msg}`)
}
} else {
console.log(`Verified ${requiredExternals.length} required external(s) are in package.json`)
}
}
if (Script.release) {
for (const key of Object.keys(binaries)) {
const archiveName = key.replace(/^@altimateai\//, "")
const archivePath = path.resolve("dist", archiveName)
if (key.includes("linux")) {
await $`tar -czf ${archivePath}.tar.gz *`.cwd(`dist/${key}/bin`)
} else {
await $`zip -r ${archivePath}.zip *`.cwd(`dist/${key}/bin`)
}
}
}
export { binaries }