Elffuss BraidHub

kikocis/continue public

9d8db5fc402e · 15.7 KiBRawPermalink
1const fs = require("fs");
2const path = require("path");
3
4const ncp = require("ncp").ncp;
5const { rimrafSync } = require("rimraf");
6
7const {
8 validateFilesPresent,
9 execCmdSync,
10 autodetectPlatformAndArch,
11} = require("../../../scripts/util/index");
12
13const {
14 copyConfigSchema,
15 writeBuildTimestamp,
16 generateConfigYamlSchema,
17} = require("./utils");
18
19// Clear folders that will be packaged to ensure clean slate
20rimrafSync(path.join(__dirname, "..", "bin"));
21rimrafSync(path.join(__dirname, "..", "out"));
22fs.mkdirSync(path.join(__dirname, "..", "out", "node_modules"), {
23 recursive: true,
24});
25const guiDist = path.join(__dirname, "..", "..", "..", "gui", "dist");
26if (!fs.existsSync(guiDist)) {
27 fs.mkdirSync(guiDist, { recursive: true });
28}
29
30// Get the target to package for
31let target = undefined;
32const args = process.argv;
33if (args[2] === "--target") {
34 target = args[3];
35}
36
37let os;
38let arch;
39if (!target) {
40 [os, arch] = autodetectPlatformAndArch();
41} else {
42 [os, arch] = target.split("-");
43}
44
45if (os === "alpine") {
46 os = "linux";
47}
48if (arch === "armhf") {
49 arch = "arm64";
50}
51target = `${os}-${arch}`;
52console.log("[info] Using target: ", target);
53
54const exe = os === "win32" ? ".exe" : "";
55
56const isInGitHubAction = !!process.env.GITHUB_ACTIONS;
57
58const isArmTarget =
59 target === "darwin-arm64" ||
60 target === "linux-arm64" ||
61 target === "win32-arm64";
62
63const isWinTarget = target?.startsWith("win");
64const isLinuxTarget = target?.startsWith("linux");
65const isMacTarget = target?.startsWith("darwin");
66
67void (async () => {
68 console.log("[info] Packaging extension for target ", target);
69
70 // Generate and copy over config-yaml-schema.json
71 generateConfigYamlSchema();
72
73 // Copy config schemas to intellij
74 copyConfigSchema();
75
76 if (!process.cwd().endsWith("vscode")) {
77 // This is sometimes run from root dir instead (e.g. in VS Code tasks)
78 process.chdir("extensions/vscode");
79 }
80
81 // Make sure we have an initial timestamp file
82 writeBuildTimestamp();
83
84 // Install node_modules //
85 execCmdSync("npm install");
86 console.log("[info] npm install in extensions/vscode completed");
87
88 process.chdir("../../gui");
89
90 execCmdSync("npm install");
91 console.log("[info] npm install in gui completed");
92
93 if (isInGitHubAction) {
94 execCmdSync("npm run build");
95 }
96
97 // Copy over the dist folder to the JetBrains extension //
98 const intellijExtensionWebviewPath = path.join(
99 "..",
100 "extensions",
101 "intellij",
102 "src",
103 "main",
104 "resources",
105 "webview",
106 );
107
108 const indexHtmlPath = path.join(intellijExtensionWebviewPath, "index.html");
109 fs.copyFileSync(indexHtmlPath, "tmp_index.html");
110 rimrafSync(intellijExtensionWebviewPath);
111 fs.mkdirSync(intellijExtensionWebviewPath, { recursive: true });
112
113 await new Promise((resolve, reject) => {
114 ncp("dist", intellijExtensionWebviewPath, (error) => {
115 if (error) {
116 console.warn(
117 "[error] Error copying React app build to JetBrains extension: ",
118 error,
119 );
120 reject(error);
121 }
122 resolve();
123 });
124 });
125
126 // Put back index.html
127 if (fs.existsSync(indexHtmlPath)) {
128 rimrafSync(indexHtmlPath);
129 }
130 fs.copyFileSync("tmp_index.html", indexHtmlPath);
131 fs.unlinkSync("tmp_index.html");
132
133 console.log("[info] Copied gui build to JetBrains extension");
134
135 // Then copy over the dist folder to the VSCode extension //
136 const vscodeGuiPath = path.join("../extensions/vscode/gui");
137 fs.mkdirSync(vscodeGuiPath, { recursive: true });
138 await new Promise((resolve, reject) => {
139 ncp("dist", vscodeGuiPath, (error) => {
140 if (error) {
141 console.log(
142 "Error copying React app build to VSCode extension: ",
143 error,
144 );
145 reject(error);
146 } else {
147 console.log("Copied gui build to VSCode extension");
148 resolve();
149 }
150 });
151 });
152
153 if (!fs.existsSync(path.join("dist", "assets", "index.js"))) {
154 throw new Error("gui build did not produce index.js");
155 }
156 if (!fs.existsSync(path.join("dist", "assets", "index.css"))) {
157 throw new Error("gui build did not produce index.css");
158 }
159
160 // Copy over native / wasm modules //
161 process.chdir("../extensions/vscode");
162
163 fs.mkdirSync("bin", { recursive: true });
164
165 // onnxruntime-node
166 await new Promise((resolve, reject) => {
167 ncp(
168 path.join(__dirname, "../../../core/node_modules/onnxruntime-node/bin"),
169 path.join(__dirname, "../bin"),
170 {
171 dereference: true,
172 },
173 (error) => {
174 if (error) {
175 console.warn("[info] Error copying onnxruntime-node files", error);
176 reject(error);
177 }
178 resolve();
179 },
180 );
181 });
182 if (target) {
183 // If building for production, only need the binaries for current platform
184 try {
185 if (!target.startsWith("darwin")) {
186 rimrafSync(path.join(__dirname, "../bin/napi-v3/darwin"));
187 }
188 if (!target.startsWith("linux")) {
189 rimrafSync(path.join(__dirname, "../bin/napi-v3/linux"));
190 }
191 if (!target.startsWith("win")) {
192 rimrafSync(path.join(__dirname, "../bin/napi-v3/win32"));
193 }
194
195 // Also don't want to include cuda/shared/tensorrt binaries, they are too large
196 if (target.startsWith("linux")) {
197 const filesToRemove = [
198 "libonnxruntime_providers_cuda.so",
199 "libonnxruntime_providers_shared.so",
200 "libonnxruntime_providers_tensorrt.so",
201 ];
202 filesToRemove.forEach((file) => {
203 const filepath = path.join(
204 __dirname,
205 "../bin/napi-v3/linux/x64",
206 file,
207 );
208 if (fs.existsSync(filepath)) {
209 fs.rmSync(filepath);
210 }
211 });
212 }
213 } catch (e) {
214 console.warn("[info] Error removing unused binaries", e);
215 }
216 }
217 console.log("[info] Copied onnxruntime-node");
218
219 // tree-sitter-wasm
220 fs.mkdirSync("out", { recursive: true });
221
222 await new Promise((resolve, reject) => {
223 ncp(
224 path.join(__dirname, "../../../core/node_modules/tree-sitter-wasms/out"),
225 path.join(__dirname, "../out/tree-sitter-wasms"),
226 { dereference: true },
227 (error) => {
228 if (error) {
229 console.warn("[error] Error copying tree-sitter-wasm files", error);
230 reject(error);
231 } else {
232 resolve();
233 }
234 },
235 );
236 });
237
238 const filesToCopy = [
239 "../../../core/vendor/tree-sitter.wasm",
240 "../../../core/llm/llamaTokenizerWorkerPool.mjs",
241 "../../../core/llm/llamaTokenizer.mjs",
242 "../../../core/llm/tiktokenWorkerPool.mjs",
243 "../../../core/util/start_ollama.sh",
244 ];
245
246 for (const f of filesToCopy) {
247 fs.copyFileSync(
248 path.join(__dirname, f),
249 path.join(__dirname, "..", "out", path.basename(f)),
250 );
251 console.log(`[info] Copied ${path.basename(f)}`);
252 }
253
254 // tree-sitter tag query files
255 // ncp(
256 // path.join(
257 // __dirname,
258 // "../../../core/node_modules/llm-code-highlighter/dist/tag-qry",
259 // ),
260 // path.join(__dirname, "../out/tag-qry"),
261 // (error) => {
262 // if (error)
263 // console.warn("Error copying code-highlighter tag-qry files", error);
264 // },
265 // );
266
267 // textmate-syntaxes
268 await new Promise((resolve, reject) => {
269 ncp(
270 path.join(__dirname, "../textmate-syntaxes"),
271 path.join(__dirname, "../gui/textmate-syntaxes"),
272 (error) => {
273 if (error) {
274 console.warn("[error] Error copying textmate-syntaxes", error);
275 reject(error);
276 } else {
277 resolve();
278 }
279 },
280 );
281 });
282
283 async function installNodeModuleInTempDirAndCopyToCurrent(
284 packageName,
285 toCopy,
286 ) {
287 console.log(`Copying ${packageName} to ${toCopy}`);
288 // This is a way to install only one package without npm trying to install all the dependencies
289 // Create a temporary directory for installing the package
290 const adjustedName = packageName.replace(/@/g, "").replace("/", "-");
291
292 const tempDir = `/tmp/continue-node_modules-${adjustedName}`;
293 const currentDir = process.cwd();
294
295 // Remove the dir we will be copying to
296 rimrafSync(`node_modules/${toCopy}`);
297
298 // Ensure the temporary directory exists
299 fs.mkdirSync(tempDir, { recursive: true });
300
301 try {
302 // Move to the temporary directory
303 process.chdir(tempDir);
304
305 // Initialize a new package.json and install the package
306 execCmdSync(`npm init -y && npm i -f ${packageName} --no-save`);
307
308 console.log(
309 `Contents of: ${packageName}`,
310 fs.readdirSync(path.join(tempDir, "node_modules", toCopy)),
311 );
312
313 // Without this it seems the file isn't completely written to disk
314 // Ideally we validate file integrity in the validation at the end
315 await new Promise((resolve) => setTimeout(resolve, 2000));
316
317 // Copy the installed package back to the current directory
318 await new Promise((resolve, reject) => {
319 ncp(
320 path.join(tempDir, "node_modules", toCopy),
321 path.join(currentDir, "node_modules", toCopy),
322 { dereference: true },
323 (error) => {
324 if (error) {
325 console.error(
326 `[error] Error copying ${packageName} package`,
327 error,
328 );
329 reject(error);
330 } else {
331 resolve();
332 }
333 },
334 );
335 });
336 } finally {
337 // Clean up the temporary directory
338 // rimrafSync(tempDir);
339
340 // Return to the original directory
341 process.chdir(currentDir);
342 }
343 }
344
345 // GitHub Actions doesn't support ARM, so we need to download pre-saved binaries
346 // 02/07/25 - the above comment is out of date, there is now support for ARM runners on GitHub Actions
347 if (isInGitHubAction && isArmTarget) {
348 // lancedb binary
349 const packageToInstall = {
350 "darwin-arm64": "@lancedb/vectordb-darwin-arm64",
351 "linux-arm64": "@lancedb/vectordb-linux-arm64-gnu",
352 "win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
353 }[target];
354 console.log(
355 "[info] Downloading pre-built lancedb binary: " + packageToInstall,
356 );
357
358 await installNodeModuleInTempDirAndCopyToCurrent(
359 packageToInstall,
360 "@lancedb",
361 );
362
363 // Replace the installed with pre-built
364 console.log("[info] Downloading pre-built sqlite3 binary");
365 rimrafSync("../../core/node_modules/sqlite3/build");
366 const downloadUrl = {
367 "darwin-arm64":
368 "https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-darwin-arm64.tar.gz",
369 "linux-arm64":
370 "https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v3-linux-arm64.tar.gz",
371 // node-sqlite3 doesn't have a pre-built binary for win32-arm64
372 "win32-arm64":
373 "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz",
374 }[target];
375 execCmdSync(
376 `curl -L -o ../../core/node_modules/sqlite3/build.tar.gz ${downloadUrl}`,
377 );
378 execCmdSync("cd ../../core/node_modules/sqlite3 && tar -xvzf build.tar.gz");
379 fs.unlinkSync("../../core/node_modules/sqlite3/build.tar.gz");
380
381 // Download and unzip esbuild
382 console.log("[info] Downloading pre-built esbuild binary");
383 rimrafSync("node_modules/@esbuild");
384 fs.mkdirSync("node_modules/@esbuild", { recursive: true });
385 execCmdSync(
386 `curl -o node_modules/@esbuild/esbuild.zip https://continue-server-binaries.s3.us-west-1.amazonaws.com/${target}/esbuild.zip`,
387 );
388 execCmdSync(`cd node_modules/@esbuild && unzip esbuild.zip`);
389 fs.unlinkSync("node_modules/@esbuild/esbuild.zip");
390 } else {
391 // Download esbuild from npm in tmp and copy over
392 console.log("npm installing esbuild binary");
393 await installNodeModuleInTempDirAndCopyToCurrent(
394 "esbuild@0.17.19",
395 "@esbuild",
396 );
397 }
398
399 console.log("[info] Copying sqlite node binding from core");
400 await new Promise((resolve, reject) => {
401 ncp(
402 path.join(__dirname, "../../../core/node_modules/sqlite3/build"),
403 path.join(__dirname, "../out/build"),
404 { dereference: true },
405 (error) => {
406 if (error) {
407 console.warn("[error] Error copying sqlite3 files", error);
408 reject(error);
409 } else {
410 resolve();
411 }
412 },
413 );
414 });
415
416 // Copied here as well for the VS Code test suite
417 await new Promise((resolve, reject) => {
418 ncp(
419 path.join(__dirname, "../../../core/node_modules/sqlite3/build"),
420 path.join(__dirname, "../out"),
421 { dereference: true },
422 (error) => {
423 if (error) {
424 console.warn("[error] Error copying sqlite3 files", error);
425 reject(error);
426 } else {
427 resolve();
428 }
429 },
430 );
431 });
432
433 // Copy node_modules for pre-built binaries
434 const NODE_MODULES_TO_COPY = [
435 "esbuild",
436 "@esbuild",
437 "@lancedb",
438 "@vscode/ripgrep",
439 "workerpool",
440 ];
441
442 fs.mkdirSync("out/node_modules", { recursive: true });
443
444 await Promise.all(
445 NODE_MODULES_TO_COPY.map(
446 (mod) =>
447 new Promise((resolve, reject) => {
448 fs.mkdirSync(`out/node_modules/${mod}`, { recursive: true });
449 ncp(
450 `node_modules/${mod}`,
451 `out/node_modules/${mod}`,
452 { dereference: true },
453 function (error) {
454 if (error) {
455 console.error(`[error] Error copying ${mod}`, error);
456 reject(error);
457 } else {
458 console.log(`[info] Copied ${mod}`);
459 resolve();
460 }
461 },
462 );
463 }),
464 ),
465 );
466
467 // delete esbuild/bin because platform-specific @esbuild is downloaded
468 fs.rmdirSync(`out/node_modules/esbuild/bin`, { recursive: true });
469
470 console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`);
471
472 // Copy over any worker files
473 fs.cpSync(
474 "node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js",
475 "out/xhr-sync-worker.js",
476 );
477
478 // Validate the all of the necessary files are present
479 validateFilesPresent([
480 // Queries used to create the index for @code context provider
481 "tree-sitter/code-snippet-queries/c_sharp.scm",
482
483 // Queries used for @outline and @highlights context providers
484 "tag-qry/tree-sitter-c_sharp-tags.scm",
485
486 // onnx runtime bindngs
487 `bin/napi-v3/${os}/${arch}/onnxruntime_binding.node`,
488 `bin/napi-v3/${os}/${arch}/${
489 isMacTarget
490 ? "libonnxruntime.1.14.0.dylib"
491 : isLinuxTarget
492 ? "libonnxruntime.so.1.14.0"
493 : "onnxruntime.dll"
494 }`,
495
496 // Code/styling for the sidebar
497 "gui/assets/index.js",
498 "gui/assets/index.css",
499
500 // Tutorial
501 "media/move-chat-panel-right.md",
502 "continue_tutorial.py",
503 "config_schema.json",
504
505 // Embeddings model
506 "models/all-MiniLM-L6-v2/config.json",
507 "models/all-MiniLM-L6-v2/special_tokens_map.json",
508 "models/all-MiniLM-L6-v2/tokenizer_config.json",
509 "models/all-MiniLM-L6-v2/tokenizer.json",
510 "models/all-MiniLM-L6-v2/vocab.txt",
511 "models/all-MiniLM-L6-v2/onnx/model_quantized.onnx",
512
513 // node_modules (it's a bit confusing why this is necessary)
514 `node_modules/@vscode/ripgrep/bin/rg${exe}`,
515
516 // out directory (where the extension.js lives)
517 // "out/extension.js", This is generated afterward by vsce
518 // web-tree-sitter
519 "out/tree-sitter.wasm",
520 // Worker required by jsdom
521 "out/xhr-sync-worker.js",
522 // SQLite3 Node native module
523 "out/build/Release/node_sqlite3.node",
524
525 // out/node_modules (to be accessed by extension.js)
526 `out/node_modules/@vscode/ripgrep/bin/rg${exe}`,
527 `out/node_modules/@esbuild/${
528 target === "win32-arm64"
529 ? "esbuild.exe"
530 : target === "win32-x64"
531 ? "win32-x64/esbuild.exe"
532 : `${target}/bin/esbuild`
533 }`,
534 `out/node_modules/@lancedb/vectordb-${target}${isWinTarget ? "-msvc" : ""}${isLinuxTarget ? "-gnu" : ""}/index.node`,
535 `out/node_modules/esbuild/lib/main.js`,
536 ]);
537})();