-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathbuild.ts
More file actions
executable file
·284 lines (257 loc) · 8.48 KB
/
build.ts
File metadata and controls
executable file
·284 lines (257 loc) · 8.48 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
#!/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 validate skill assets for embedding
const validateSkillMd = await Bun.file(path.join(dir, "src/skill/validate/SKILL.md")).text()
const validateBatchPy = await Bun.file(path.join(dir, "src/skill/validate/batch_validate.py")).text()
console.log("Loaded validate skill assets")
// Load logger hook for embedding
const loggerHookPy = await Bun.file(path.join(dir, "src/skill/validate/logger_hook.py")).text()
console.log("Loaded logger hook")
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)
}
}
const targets = 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`
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",
// Packages excluded from the compiled binary — loaded lazily at runtime.
// NOTE: @altimateai/altimate-core is intentionally NOT external — it's a
// napi binary that must be bundled for the CLI to work out of the box.
external: [
// dbt integration — heavy transitive deps, loaded on first dbt operation
"@altimateai/dbt-integration",
// Database drivers — users install on demand per warehouse
"pg", "snowflake-sdk", "@google-cloud/bigquery", "@databricks/sql",
"mysql2", "mssql", "oracledb", "duckdb", "better-sqlite3",
// Optional infra packages
"keytar", "ssh2", "dockerode", "yaml",
],
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_CHANGELOG: JSON.stringify(changelog),
ALTIMATE_VALIDATE_SKILL_MD: JSON.stringify(validateSkillMd),
ALTIMATE_VALIDATE_BATCH_PY: JSON.stringify(validateBatchPy),
ALTIMATE_LOGGER_HOOK_PY: JSON.stringify(loggerHookPy),
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
}
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 }