forked from google-gemini/gemini-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_binary.js
More file actions
456 lines (393 loc) · 12.1 KB
/
build_binary.js
File metadata and controls
456 lines (393 loc) · 12.1 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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { spawnSync } from 'node:child_process';
import {
cpSync,
rmSync,
mkdirSync,
existsSync,
copyFileSync,
writeFileSync,
readFileSync,
} from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import process from 'node:process';
import { globSync } from 'glob';
import { createHash } from 'node:crypto';
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = join(__dirname, '..');
const distDir = join(root, 'dist');
const bundleDir = join(root, 'bundle');
const stagingDir = join(bundleDir, 'native_modules');
const seaConfigPath = join(root, 'sea-config.json');
const manifestPath = join(bundleDir, 'manifest.json');
const entitlementsPath = join(root, 'scripts/entitlements.plist');
// --- Helper Functions ---
/**
* Safely executes a command using spawnSync.
* @param {string} command
* @param {string[]} args
* @param {object} options
*/
function runCommand(command, args, options = {}) {
let finalCommand = command;
let useShell = options.shell || false;
// On Windows, npm/npx are batch files and need a shell
if (
process.platform === 'win32' &&
(command === 'npm' || command === 'npx')
) {
finalCommand = `${command}.cmd`;
useShell = true;
}
const finalOptions = {
stdio: 'inherit',
cwd: root,
shell: useShell,
...options,
};
const result = spawnSync(finalCommand, args, finalOptions);
if (result.status !== 0) {
if (result.error) {
throw result.error;
}
throw new Error(
`Command failed with exit code ${result.status}: ${command}`,
);
}
return result;
}
/**
* Removes existing digital signatures from a binary.
* @param {string} filePath
*/
function removeSignature(filePath) {
console.log(`Removing signature from ${filePath}...`);
const platform = process.platform;
try {
if (platform === 'darwin') {
spawnSync('codesign', ['--remove-signature', filePath], {
stdio: 'ignore',
});
} else if (platform === 'win32') {
spawnSync('signtool', ['remove', '/s', filePath], {
stdio: 'ignore',
});
}
} catch {
// Best effort: Ignore failures
}
}
/**
* Signs a binary using hardcoded tools for the platform.
* @param {string} filePath
*/
function signFile(filePath) {
const platform = process.platform;
if (platform === 'darwin') {
const identity = process.env.APPLE_IDENTITY || '-';
console.log(`Signing ${filePath} (Identity: ${identity})...`);
const args = [
'--sign',
identity,
'--force',
'--timestamp',
'--options',
'runtime',
];
if (existsSync(entitlementsPath)) {
args.push('--entitlements', entitlementsPath);
}
args.push(filePath);
runCommand('codesign', args);
} else if (platform === 'win32') {
const args = ['sign'];
if (process.env.WINDOWS_PFX_FILE && process.env.WINDOWS_PFX_PASSWORD) {
args.push(
'/f',
process.env.WINDOWS_PFX_FILE,
'/p',
process.env.WINDOWS_PFX_PASSWORD,
);
} else {
args.push('/a');
}
args.push(
'/fd',
'SHA256',
'/td',
'SHA256',
'/tr',
'http://timestamp.digicert.com',
filePath,
);
console.log(`Signing ${filePath}...`);
try {
runCommand('signtool', args, { stdio: 'pipe' });
} catch (e) {
let msg = e.message;
if (process.env.WINDOWS_PFX_PASSWORD) {
msg = msg.replaceAll(process.env.WINDOWS_PFX_PASSWORD, '******');
}
throw new Error(msg);
}
} else if (platform === 'linux') {
console.log(`Skipping signing for ${filePath} on Linux.`);
}
}
console.log('Build Binary Script Started...');
// 1. Clean dist
if (existsSync(distDir)) {
console.log('Cleaning dist directory...');
rmSync(distDir, { recursive: true, force: true });
}
mkdirSync(distDir, { recursive: true });
// 2. Build Bundle
console.log('Running npm clean, install, and bundle...');
try {
runCommand('npm', ['run', 'clean']);
runCommand('npm', ['install']);
runCommand('npm', ['run', 'bundle']);
} catch (e) {
console.error('Build step failed:', e.message);
process.exit(1);
}
// 3. Stage & Sign Native Modules
const includeNativeModules = process.env.BUNDLE_NATIVE_MODULES !== 'false';
console.log(`Include Native Modules: ${includeNativeModules}`);
if (includeNativeModules) {
console.log('Staging and signing native modules...');
// Prepare staging
if (existsSync(stagingDir))
rmSync(stagingDir, { recursive: true, force: true });
mkdirSync(stagingDir, { recursive: true });
// Copy @lydell/node-pty to staging
const lydellSrc = join(root, 'node_modules/@lydell');
const lydellStaging = join(stagingDir, 'node_modules/@lydell');
if (existsSync(lydellSrc)) {
mkdirSync(dirname(lydellStaging), { recursive: true });
cpSync(lydellSrc, lydellStaging, { recursive: true });
} else {
console.warn(
'Warning: @lydell/node-pty not found in node_modules. Native terminal features may fail.',
);
}
// Sign Staged .node files
try {
const nodeFiles = globSync('**/*.node', {
cwd: stagingDir,
absolute: true,
});
for (const file of nodeFiles) {
signFile(file);
}
} catch (e) {
console.warn('Warning: Failed to sign native modules:', e.code);
}
} else {
console.log('Skipping native modules bundling (BUNDLE_NATIVE_MODULES=false)');
}
// 4. Generate SEA Configuration and Manifest
console.log('Generating SEA configuration and manifest...');
const packageJson = JSON.parse(
readFileSync(join(root, 'package.json'), 'utf8'),
);
// Helper to calc hash
const sha256 = (content) => createHash('sha256').update(content).digest('hex');
const assets = {
'manifest.json': 'bundle/manifest.json',
};
const manifest = {
main: 'gemini.mjs',
mainHash: '',
version: packageJson.version,
files: [],
};
// Add all javascript chunks from the bundle directory
const jsFiles = globSync('*.js', { cwd: bundleDir });
for (const jsFile of jsFiles) {
const fsPath = join(bundleDir, jsFile);
const content = readFileSync(fsPath);
const hash = sha256(content);
// Node SEA requires the main entry point to be explicitly mapped
if (jsFile === 'gemini.js') {
assets['gemini.mjs'] = fsPath;
manifest.mainHash = hash;
} else {
// Other chunks need to be mapped exactly as they are named so dynamic imports find them
assets[jsFile] = fsPath;
manifest.files.push({ key: jsFile, path: jsFile, hash: hash });
}
}
// Helper to recursively find files from STAGING
function addAssetsFromDir(baseDir, runtimePrefix) {
const fullDir = join(stagingDir, baseDir);
if (!existsSync(fullDir)) return;
const items = globSync('**/*', { cwd: fullDir, nodir: true });
for (const item of items) {
const relativePath = join(runtimePrefix, item);
const assetKey = `files:${relativePath}`;
const fsPath = join(fullDir, item);
// Calc hash
const content = readFileSync(fsPath);
const hash = sha256(content);
assets[assetKey] = fsPath;
manifest.files.push({ key: assetKey, path: relativePath, hash: hash });
}
}
// Add sb files
const sbFiles = globSync('sandbox-macos-*.sb', { cwd: bundleDir });
for (const sbFile of sbFiles) {
const fsPath = join(bundleDir, sbFile);
const content = readFileSync(fsPath);
const hash = sha256(content);
assets[sbFile] = fsPath;
manifest.files.push({ key: sbFile, path: sbFile, hash: hash });
}
// Add policy files
const policyDir = join(bundleDir, 'policies');
if (existsSync(policyDir)) {
const policyFiles = globSync('*.toml', { cwd: policyDir });
for (const policyFile of policyFiles) {
const fsPath = join(policyDir, policyFile);
const relativePath = join('policies', policyFile);
const content = readFileSync(fsPath);
const hash = sha256(content);
// Use a unique key to avoid collision if filenames overlap (though unlikely here)
// But sea-launch writes to 'path', so key is just for lookup.
const assetKey = `policies:${policyFile}`;
assets[assetKey] = fsPath;
manifest.files.push({ key: assetKey, path: relativePath, hash: hash });
}
}
// Add assets from Staging
if (includeNativeModules) {
addAssetsFromDir('node_modules/@lydell', 'node_modules/@lydell');
}
writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
const seaConfig = {
main: 'sea/sea-launch.cjs',
output: 'dist/sea-prep.blob',
disableExperimentalSEAWarning: true,
assets: assets,
};
writeFileSync(seaConfigPath, JSON.stringify(seaConfig, null, 2));
console.log(`Configured ${Object.keys(assets).length} embedded assets.`);
// 5. Generate SEA Blob
console.log('Generating SEA blob...');
try {
runCommand('node', ['--experimental-sea-config', 'sea-config.json']);
} catch (e) {
console.error('Failed to generate SEA blob:', e.message);
// Cleanup
if (existsSync(seaConfigPath)) rmSync(seaConfigPath);
if (existsSync(manifestPath)) rmSync(manifestPath);
if (existsSync(stagingDir))
rmSync(stagingDir, { recursive: true, force: true });
process.exit(1);
}
// Check blob existence
const blobPath = join(distDir, 'sea-prep.blob');
if (!existsSync(blobPath)) {
console.error('Error: sea-prep.blob not found in dist/');
process.exit(1);
}
// 6. Identify Target & Prepare Binary
const platform = process.platform;
const arch = process.arch;
const targetName = `${platform}-${arch}`;
console.log(`Targeting: ${targetName}`);
const targetDir = join(distDir, targetName);
mkdirSync(targetDir, { recursive: true });
const nodeBinary = process.execPath;
const binaryName = platform === 'win32' ? 'gemini.exe' : 'gemini';
const targetBinaryPath = join(targetDir, binaryName);
console.log(`Copying node binary from ${nodeBinary} to ${targetBinaryPath}...`);
copyFileSync(nodeBinary, targetBinaryPath);
if (platform === 'darwin') {
console.log(`Thinning universal binary for ${arch}...`);
try {
// Attempt to thin the binary. Will fail safely if it's not a fat binary.
runCommand('lipo', [
targetBinaryPath,
'-thin',
arch,
'-output',
targetBinaryPath,
]);
} catch (e) {
console.log(`Skipping lipo thinning: ${e.message}`);
}
}
// Remove existing signature using helper
removeSignature(targetBinaryPath);
// Copy standard bundle assets (policies, .sb files)
console.log('Copying additional resources...');
if (existsSync(bundleDir)) {
cpSync(bundleDir, targetDir, { recursive: true });
}
// Clean up source JS files from output (we only want embedded)
const filesToRemove = [
'gemini.mjs',
'gemini.mjs.map',
'gemini-sea.cjs',
'sea-launch.cjs',
'manifest.json',
'native_modules',
'policies',
];
filesToRemove.forEach((f) => {
const p = join(targetDir, f);
if (existsSync(p)) rmSync(p, { recursive: true, force: true });
});
// Remove all chunk and entry .js/.js.map files
const jsFilesToRemove = globSync('*.{js,js.map}', { cwd: targetDir });
for (const f of jsFilesToRemove) {
rmSync(join(targetDir, f));
}
// Remove .sb files from targetDir
const sbFilesToRemove = globSync('sandbox-macos-*.sb', { cwd: targetDir });
for (const f of sbFilesToRemove) {
rmSync(join(targetDir, f));
}
// 7. Inject Blob
console.log('Injecting SEA blob...');
const sentinelFuse = 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2';
try {
const args = [
'postject',
targetBinaryPath,
'NODE_SEA_BLOB',
blobPath,
'--sentinel-fuse',
sentinelFuse,
];
if (platform === 'darwin') {
args.push('--macho-segment-name', 'NODE_SEA');
}
runCommand('npx', args);
console.log('Injection successful.');
} catch (e) {
console.error('Postject failed:', e.message);
process.exit(1);
}
// 8. Final Signing
console.log('Signing final executable...');
try {
signFile(targetBinaryPath);
} catch (e) {
console.warn('Warning: Final signing failed:', e.code);
console.warn('Continuing without signing...');
}
// 9. Cleanup
console.log('Cleaning up artifacts...');
rmSync(blobPath);
if (existsSync(seaConfigPath)) rmSync(seaConfigPath);
if (existsSync(manifestPath)) rmSync(manifestPath);
if (existsSync(stagingDir))
rmSync(stagingDir, { recursive: true, force: true });
console.log(`Binary built successfully in ${targetDir}`);