esbuild.mjs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import fs from "node:fs"
  2. import path from "node:path"
  3. import { fileURLToPath } from "node:url"
  4. import * as esbuild from "esbuild"
  5. const __filename = fileURLToPath(import.meta.url)
  6. const __dirname = path.dirname(__filename)
  7. const production = process.argv.includes("--production") || process.env["IS_DEBUG_BUILD"] === "false"
  8. const watch = process.argv.includes("--watch")
  9. const standalone = process.argv.includes("--standalone")
  10. const e2eBuild = process.argv.includes("--e2e-build")
  11. const destDir = standalone ? "dist-standalone" : "dist"
  12. /**
  13. * @type {import('esbuild').Plugin}
  14. */
  15. const aliasResolverPlugin = {
  16. name: "alias-resolver",
  17. setup(build) {
  18. const aliases = {
  19. "@": path.resolve(__dirname, "src"),
  20. "@core": path.resolve(__dirname, "src/core"),
  21. "@integrations": path.resolve(__dirname, "src/integrations"),
  22. "@services": path.resolve(__dirname, "src/services"),
  23. "@shared": path.resolve(__dirname, "src/shared"),
  24. "@utils": path.resolve(__dirname, "src/utils"),
  25. "@packages": path.resolve(__dirname, "src/packages"),
  26. }
  27. // For each alias entry, create a resolver
  28. Object.entries(aliases).forEach(([alias, aliasPath]) => {
  29. const aliasRegex = new RegExp(`^${alias}($|/.*)`)
  30. build.onResolve({ filter: aliasRegex }, (args) => {
  31. const importPath = args.path.replace(alias, aliasPath)
  32. // First, check if the path exists as is
  33. if (fs.existsSync(importPath)) {
  34. const stats = fs.statSync(importPath)
  35. if (stats.isDirectory()) {
  36. // If it's a directory, try to find index files
  37. const extensions = [".ts", ".tsx", ".js", ".jsx"]
  38. for (const ext of extensions) {
  39. const indexFile = path.join(importPath, `index${ext}`)
  40. if (fs.existsSync(indexFile)) {
  41. return { path: indexFile }
  42. }
  43. }
  44. } else {
  45. // It's a file that exists, so return it
  46. return { path: importPath }
  47. }
  48. }
  49. // If the path doesn't exist, try appending extensions
  50. const extensions = [".ts", ".tsx", ".js", ".jsx"]
  51. for (const ext of extensions) {
  52. const pathWithExtension = `${importPath}${ext}`
  53. if (fs.existsSync(pathWithExtension)) {
  54. return { path: pathWithExtension }
  55. }
  56. }
  57. // If nothing worked, return the original path and let esbuild handle the error
  58. return { path: importPath }
  59. })
  60. })
  61. },
  62. }
  63. const esbuildProblemMatcherPlugin = {
  64. name: "esbuild-problem-matcher",
  65. setup(build) {
  66. build.onStart(() => {
  67. console.log("[watch] build started")
  68. })
  69. build.onEnd((result) => {
  70. result.errors.forEach(({ text, location }) => {
  71. console.error(`✘ [ERROR] ${text}`)
  72. console.error(` ${location.file}:${location.line}:${location.column}:`)
  73. })
  74. console.log("[watch] build finished")
  75. })
  76. },
  77. }
  78. const copyWasmFiles = {
  79. name: "copy-wasm-files",
  80. setup(build) {
  81. build.onEnd(() => {
  82. // tree sitter
  83. const sourceDir = path.join(__dirname, "node_modules", "web-tree-sitter")
  84. const targetDir = path.join(__dirname, destDir)
  85. // Copy tree-sitter.wasm
  86. fs.copyFileSync(path.join(sourceDir, "tree-sitter.wasm"), path.join(targetDir, "tree-sitter.wasm"))
  87. // Copy language-specific WASM files
  88. const languageWasmDir = path.join(__dirname, "node_modules", "tree-sitter-wasms", "out")
  89. const languages = [
  90. "typescript",
  91. "tsx",
  92. "python",
  93. "rust",
  94. "javascript",
  95. "go",
  96. "cpp",
  97. "c",
  98. "c_sharp",
  99. "ruby",
  100. "java",
  101. "php",
  102. "swift",
  103. "kotlin",
  104. ]
  105. languages.forEach((lang) => {
  106. const filename = `tree-sitter-${lang}.wasm`
  107. fs.copyFileSync(path.join(languageWasmDir, filename), path.join(targetDir, filename))
  108. })
  109. })
  110. },
  111. }
  112. const buildEnvVars = {
  113. "import.meta.url": "_importMetaUrl",
  114. "process.env.IS_STANDALONE": JSON.stringify(standalone ? "true" : "false"),
  115. }
  116. if (production) {
  117. // IS_DEV is always disable in production builds.
  118. buildEnvVars["process.env.IS_DEV"] = "false"
  119. }
  120. // Set the environment and telemetry env vars. The API key env vars need to be populated in the GitHub
  121. // workflows from the secrets.
  122. if (process.env.CLINE_ENVIRONMENT) {
  123. buildEnvVars["process.env.CLINE_ENVIRONMENT"] = JSON.stringify(process.env.CLINE_ENVIRONMENT)
  124. }
  125. if (process.env.TELEMETRY_SERVICE_API_KEY) {
  126. buildEnvVars["process.env.TELEMETRY_SERVICE_API_KEY"] = JSON.stringify(process.env.TELEMETRY_SERVICE_API_KEY)
  127. }
  128. if (process.env.ERROR_SERVICE_API_KEY) {
  129. buildEnvVars["process.env.ERROR_SERVICE_API_KEY"] = JSON.stringify(process.env.ERROR_SERVICE_API_KEY)
  130. }
  131. if (process.env.POSTHOG_TELEMETRY_ENABLED) {
  132. buildEnvVars["process.env.POSTHOG_TELEMETRY_ENABLED"] = JSON.stringify(process.env.POSTHOG_TELEMETRY_ENABLED)
  133. }
  134. // OpenTelemetry configuration (injected at build time from GitHub secrets)
  135. // These provide production defaults that can be overridden at runtime via environment variables
  136. if (process.env.OTEL_TELEMETRY_ENABLED) {
  137. buildEnvVars["process.env.OTEL_TELEMETRY_ENABLED"] = JSON.stringify(process.env.OTEL_TELEMETRY_ENABLED)
  138. }
  139. if (process.env.OTEL_LOGS_EXPORTER) {
  140. buildEnvVars["process.env.OTEL_LOGS_EXPORTER"] = JSON.stringify(process.env.OTEL_LOGS_EXPORTER)
  141. }
  142. if (process.env.OTEL_METRICS_EXPORTER) {
  143. buildEnvVars["process.env.OTEL_METRICS_EXPORTER"] = JSON.stringify(process.env.OTEL_METRICS_EXPORTER)
  144. }
  145. if (process.env.OTEL_EXPORTER_OTLP_PROTOCOL) {
  146. buildEnvVars["process.env.OTEL_EXPORTER_OTLP_PROTOCOL"] = JSON.stringify(process.env.OTEL_EXPORTER_OTLP_PROTOCOL)
  147. }
  148. if (process.env.OTEL_EXPORTER_OTLP_ENDPOINT) {
  149. buildEnvVars["process.env.OTEL_EXPORTER_OTLP_ENDPOINT"] = JSON.stringify(process.env.OTEL_EXPORTER_OTLP_ENDPOINT)
  150. }
  151. if (process.env.OTEL_EXPORTER_OTLP_HEADERS) {
  152. buildEnvVars["process.env.OTEL_EXPORTER_OTLP_HEADERS"] = JSON.stringify(process.env.OTEL_EXPORTER_OTLP_HEADERS)
  153. }
  154. if (process.env.OTEL_METRIC_EXPORT_INTERVAL) {
  155. buildEnvVars["process.env.OTEL_METRIC_EXPORT_INTERVAL"] = JSON.stringify(process.env.OTEL_METRIC_EXPORT_INTERVAL)
  156. }
  157. // Base configuration shared between extension and standalone builds
  158. const baseConfig = {
  159. bundle: true,
  160. minify: production,
  161. sourcemap: !production,
  162. logLevel: "silent",
  163. define: buildEnvVars,
  164. tsconfig: path.resolve(__dirname, "tsconfig.json"),
  165. plugins: [
  166. copyWasmFiles,
  167. aliasResolverPlugin,
  168. /* add to the end of plugins array */
  169. esbuildProblemMatcherPlugin,
  170. ],
  171. format: "cjs",
  172. sourcesContent: false,
  173. platform: "node",
  174. banner: {
  175. js: "const _importMetaUrl=require('url').pathToFileURL(__filename)",
  176. },
  177. }
  178. // Extension-specific configuration
  179. const extensionConfig = {
  180. ...baseConfig,
  181. entryPoints: ["src/extension.ts"],
  182. outfile: `${destDir}/extension.js`,
  183. external: ["vscode"],
  184. }
  185. // Standalone-specific configuration
  186. const standaloneConfig = {
  187. ...baseConfig,
  188. entryPoints: ["src/standalone/cline-core.ts"],
  189. outfile: `${destDir}/cline-core.js`,
  190. // These modules need to load files from the module directory at runtime,
  191. // so they cannot be bundled.
  192. external: ["vscode", "@grpc/reflection", "grpc-health-check", "better-sqlite3"],
  193. }
  194. // E2E build script configuration
  195. const e2eBuildConfig = {
  196. ...baseConfig,
  197. entryPoints: ["src/test/e2e/utils/build.ts"],
  198. outfile: `${destDir}/e2e-build.mjs`,
  199. external: ["@vscode/test-electron", "execa"],
  200. sourcemap: false,
  201. plugins: [aliasResolverPlugin, esbuildProblemMatcherPlugin],
  202. }
  203. async function main() {
  204. const config = standalone ? standaloneConfig : e2eBuild ? e2eBuildConfig : extensionConfig
  205. const extensionCtx = await esbuild.context(config)
  206. if (watch) {
  207. await extensionCtx.watch()
  208. } else {
  209. await extensionCtx.rebuild()
  210. await extensionCtx.dispose()
  211. }
  212. }
  213. main().catch((e) => {
  214. console.error(e)
  215. process.exit(1)
  216. })