All files / server/services arduino-compiler.ts

84.84% Statements 84/99
73.77% Branches 45/61
56.25% Functions 9/16
86.31% Lines 82/95

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                    56x 56x 56x 56x 56x     56x 56x 56x     21x 21x           21x             52x       52x       52x                         52x   52x 7x 7x 7x   7x               45x                                   52x           52x 52x   52x                           52x     52x           52x   52x 52x     52x 52x 52x 52x 52x 52x 52x 52x   52x   52x 52x 7x                                 45x       45x                           45x 44x     44x       44x         44x     43x         52x     43x 43x 43x 43x   43x 30x 30x         30x 30x 30x   13x         13x 13x 13x     43x                     2x                   52x                                       30x 30x 30x   30x                                         30x                                 13x 13x 13x     13x 5x 7x 7x       13x                 52x          
//arduino-compiler.ts
 
import { mkdtemp, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { randomUUID, createHash } from "node:crypto";
import { Logger } from "@shared/logger";
import { ParserMessage, IOPinRecord } from "@shared/schema";
import { CodeParser } from "@shared/code-parser";
import { detectSketchEntrypoints } from "@shared/utils/sketch-validation";
import { getFastTmpBaseDir } from "@shared/utils/temp-paths";
import { reservedNamesValidator } from "@shared/reserved-names-validator";
import { getUnifiedGatekeeper, TaskPriority } from "./unified-gatekeeper";
import { ProcessExecutor } from "./process-executor";
import { type CompilationError } from "./compiler/compiler-output-parser";
import { config } from "../config";
import { resolvePathWithinRoot } from "../security/safe-paths";
import {
  ensureTempDirs,
  cleanupSketchDirs,
} from "./compiler/temp-fs";
import {
  writeBinaryToStorage,
  writeOutputToCache,
  writeHexToCache,
  runHexCacheCleanup,
  checkCacheHits,
} from "./compiler/cache-manager";
import { processHeaderIncludes } from "./compiler/header-processor";
import { compileWithArduinoCli, type CLICompileConfig } from "./compiler/cli-runner";
 
// Re-export for backwards compatibility
export type { CompilationError } from "./compiler/compiler-output-parser";
 
export interface CompilationResult {
  success: boolean;
  output: string;
  // raw stderr text for backwards compatibility and debugging
  stderr?: string;
  // structured list of errors/warnings from the compiler
  errors: CompilationError[];
  binary?: Buffer;
  arduinoCliStatus: "idle" | "compiling" | "success" | "error";
  // gccStatus removed – it was deprecated and is no longer populated
  parserMessages?: ParserMessage[]; // Parser validation messages
  ioRegistry?: IOPinRecord[]; // I/O Registry for visualization
}
 
export interface CompileRequestOptions {
  fqbn?: string;
  libraries?: string[];
  sketchHash?: string;
  coreFingerprint?: string;
  buildPath?: string;
  buildCachePath?: string;
  hexCacheDir?: string;
}
 
export class ArduinoCompiler {
  private readonly tempDir = join(process.cwd(), "temp");
  private readonly logger = new Logger("ArduinoCompiler");
  private readonly processExecutor = new ProcessExecutor();
  private readonly defaultFqbn = config.compilation.fqbn;
  private readonly defaultBuildCacheDir = config.compilation.cacheDir;
  // Hex and binary outputs use the shared storage dir (storage/cache) so that
  // both worker-pool compiles and direct-compiler compiles share the same cache.
  private readonly defaultBinaryStorageDir = join(config.compilation.buildCacheDir, "binaries");
  private readonly defaultHexCacheDir = join(config.compilation.buildCacheDir, "hex-cache");
  private readonly defaultBuildCachePath = join(this.defaultBuildCacheDir, "build-cache");
 
  static async create(): Promise<ArduinoCompiler> {
    const instance = new ArduinoCompiler();
    ensureTempDirs({
      tempDir: instance.tempDir,
      hexCacheDir: instance.defaultHexCacheDir,
      buildCachePath: instance.defaultBuildCachePath,
      binaryStorageDir: instance.defaultBinaryStorageDir,
    });
    return instance;
  }
 
  private buildSketchHash(
    code: string,
    options?: CompileRequestOptions,
  ): string {
    Iif (options?.sketchHash) {
      return options.sketchHash;
    }
 
    const payload = JSON.stringify({
      code,
      fqbn: options?.fqbn || this.defaultFqbn,
    });
    return createHash("sha256").update(payload).digest("hex");
  }
 
  /**
   * Validates that the sketch contains required entry points (setup and loop).
   * Returns { hasSetup, hasLoop } and error message if validation fails.
   */
  private validateSketchEntrypoints(code: string): {
    valid: boolean;
    hasSetup: boolean;
    hasLoop: boolean;
    errorMessage?: string;
  } {
    const { hasSetup, hasLoop } = detectSketchEntrypoints(code);
 
    if (!hasSetup || !hasLoop) {
      const missingFunctions = [];
      if (!hasSetup) missingFunctions.push("setup()");
      if (!hasLoop) missingFunctions.push("loop()");
 
      return {
        valid: false,
        hasSetup,
        hasLoop,
        errorMessage: `Missing Arduino functions: ${missingFunctions.join(" and ")}\n\nArduino sketches require:\n- void setup() { }\n- void loop() { }`,
      };
    }
 
    return { valid: true, hasSetup, hasLoop };
  }
 
 
 
 
 
 
 
 
 
  async compile(
    code: string,
    headers?: Array<{ name: string; content: string }>,
    tempRoot?: string,
    options?: CompileRequestOptions,
  ): Promise<CompilationResult> {
    // GATEKEEPER: Acquire a compile slot to prevent race conditions
    const release = await getUnifiedGatekeeper().acquireCompileSlot(
      TaskPriority.NORMAL,
      30000,
      "arduino-compiler",
    );
 
    try {
      return await this.compileInternal(code, headers, tempRoot, options);
    } finally {
      release();
    }
  }
 
  /**
   * Internal compile implementation (wrapped by compile with gatekeeper)
   * Orchestrates compilation by delegating to helper functions for clarity.
   */
  private async compileInternal(
    code: string,
    headers?: Array<{ name: string; content: string }>,
    tempRoot?: string,
    options?: CompileRequestOptions,
  ): Promise<CompilationResult> {
    const sketchId = randomUUID();
 
    // Ensure provided tempRoot exists (important for Worker pool and deterministic tests)
    Iif (tempRoot) {
      await mkdir(tempRoot, { recursive: true }).catch(() => {});
    }
 
    // use a unique temporary directory per-call to avoid state conflicts
    const baseTempDir =
      tempRoot || (await mkdtemp(join(getFastTmpBaseDir(), "unosim-")));
 
    const sketchDir = resolvePathWithinRoot(baseTempDir, sketchId);
    const sketchFile = resolvePathWithinRoot(sketchDir, `${sketchId}.ino`);
 
    // Pre-compilation validation and parsing
    const parser = new CodeParser();
    const parserMessages = parser.parseAll(code);
    const reservedNameMessages = reservedNamesValidator.validateReservedNames(code);
    const allParserMessages = [...parserMessages, ...reservedNameMessages];
    const ioRegistry: IOPinRecord[] = [];
    const sketchHash = this.buildSketchHash(code, options);
    const hexCacheDir = options?.hexCacheDir || this.defaultHexCacheDir;
    const compileStartedAt = process.hrtime.bigint();
 
    try {
      // 1. Validate sketch has required entry points
      const validation = this.validateSketchEntrypoints(code);
      if (!validation.valid) {
        return {
          success: false,
          output: "",
          stderr: validation.errorMessage,
          errors: [],
          arduinoCliStatus: "error",
          parserMessages: allParserMessages,
          ioRegistry,
        };
      }
 
      // 2. Check both instant and hex caches.
      // Only use the cache when the output sidecar (.output.txt) also exists so
      // the full "Sketch uses X bytes … Board: Arduino UNO" message is returned.
      // If cachedOutput is null (e.g. old cache entry written before the sidecar
      // was introduced) we fall through to a fresh compile so the sidecar gets
      // written and the user always sees the complete output.
      const cacheResult = await checkCacheHits(sketchHash, {
        binaryStorageDir: this.defaultBinaryStorageDir,
        hexCacheDir,
      }, compileStartedAt);
      Iif (cacheResult.cached && cacheResult.binary && cacheResult.cachedOutput !== null) {
        return {
          success: true,
          output: cacheResult.cachedOutput,
          stderr: undefined,
          errors: [],
          binary: cacheResult.binary,
          arduinoCliStatus: "success",
          parserMessages: allParserMessages,
          ioRegistry,
        };
      }
 
      // 3. Create directories and process headers
      await mkdir(sketchDir, { recursive: true });
      Iif (options?.buildPath) {
        await mkdir(options.buildPath, { recursive: true }).catch(() => {});
      }
      Iif (options?.buildCachePath) {
        await mkdir(options.buildCachePath, { recursive: true }).catch(() => {});
      }
 
      const { processedCode, lineOffset } = await processHeaderIncludes(
        code,
        headers,
        sketchDir,
      );
      await writeFile(sketchFile, processedCode);
 
      // 4. Run Arduino CLI compilation
      const cliConfig: CLICompileConfig = {
        fqbn: options?.fqbn || this.defaultFqbn,
        buildPath: options?.buildPath,
        buildCachePath: options?.buildCachePath || this.defaultBuildCachePath,
      };
      const cliResult = await compileWithArduinoCli(sketchFile, cliConfig, this.processExecutor);
 
      // 5. Handle result (success or error)
      let cliOutput = "";
      let cliErrors = "";
      let parsedErrors: CompilationError[] = [];
      let arduinoCliStatus: "success" | "error" = "error";
 
      if (cliResult.success) {
        arduinoCliStatus = "success";
        const successResult = await this.handleCompilationSuccess(
          sketchHash,
          hexCacheDir,
          cliResult,
        );
        cliOutput = successResult.cliOutput;
        cliErrors = successResult.cliErrors;
        parsedErrors = successResult.parsedErrors;
      } else {
        const errorResult = this.handleCompilationError(
          cliResult.errors || "Compilation failed",
          lineOffset,
          cliResult,
        );
        cliOutput = errorResult.cliOutput;
        cliErrors = errorResult.cliErrors;
        parsedErrors = errorResult.parsedErrors;
      }
 
      return {
        success: cliResult.success,
        output: cliOutput,
        stderr: cliErrors || undefined,
        errors: parsedErrors,
        binary: cliResult.binary,
        arduinoCliStatus,
        parserMessages: allParserMessages,
        ioRegistry,
      };
    } catch (error) {
      return {
        success: false,
        output: "",
        stderr: `Compilation failed: ${error instanceof Error ? error.message : String(error)}`,
        errors: [],
        arduinoCliStatus: "error",
        parserMessages: allParserMessages,
        ioRegistry,
      };
    } finally {
      await this._cleanupSketchDirs(sketchDir, baseTempDir, tempRoot);
    }
  }
 
 
 
  /**
   * Handles successful compilation: writes caches and formats output.
   */
  private async handleCompilationSuccess(
    sketchHash: string,
    hexCacheDir: string,
    cliResult: {
      success: boolean;
      output: string;
      errors?: string;
      parsedErrors?: CompilationError[];
      binary?: Buffer;
    },
  ): Promise<{ cliOutput: string; cliErrors: string; parsedErrors: CompilationError[] }> {
    const cliOutput = cliResult.output || "";
    let cliErrors = cliResult.errors || "";
    const parsedErrors = cliResult.parsedErrors || [];
 
    Iif (cliResult.binary) {
      // Write to both instant cache and persistent hex cache
      await writeHexToCache(sketchHash, hexCacheDir, cliResult.binary).catch((error) => {
        this.logger.debug(
          `[CompileCache] failed to write HEX cache: ${error instanceof Error ? error.message : String(error)}`,
        );
      });
      await writeBinaryToStorage(sketchHash, cliResult.binary, this.defaultBinaryStorageDir).catch((error) => {
        this.logger.debug(
          `[CompileCache] failed to write binary storage cache: ${error instanceof Error ? error.message : String(error)}`,
        );
      });
      // Store the formatted output alongside both cache locations so cache hits
      // can reproduce the full compiler output (sketch size, RAM usage, etc.)
      if (cliOutput) {
        await writeOutputToCache(hexCacheDir, sketchHash, cliOutput).catch(() => undefined);
        await writeOutputToCache(this.defaultBinaryStorageDir, sketchHash, cliOutput).catch(() => undefined);
      }
      await runHexCacheCleanup(hexCacheDir);
    }
 
    return { cliOutput, cliErrors, parsedErrors };
  }
 
  /**
   * Handles compilation errors: cleans error messages and parses them into structured errors.
   */
  private handleCompilationError(
    cliErrors: string,
    lineOffset: number,
    cliResult: {
      success: boolean;
      output: string;
      errors?: string;
      parsedErrors?: CompilationError[];
      binary?: Buffer;
    },
  ): { cliOutput: string; cliErrors: string; parsedErrors: CompilationError[] } {
    const cliOutput = "";
    let cleanedErrors = cliErrors;
    const parsedErrors = cliResult.parsedErrors || [];
 
    // Correct stderr text for offset so UI shows original line numbers
    if (lineOffset > 0 && cleanedErrors) {
      cleanedErrors = cleanedErrors.replaceAll(/sketch\.ino:(\d+):/g, (_m, n) => {
        const corrected = Math.max(1, Number.parseInt(n, 10) - lineOffset);
        return `sketch.ino:${corrected}:`;
      });
    }
 
    return { cliOutput, cliErrors: cleanedErrors, parsedErrors };
  }
 
  /** Remove sketch-specific temporary directories created during compilation. */
  private async _cleanupSketchDirs(
    sketchDir: string,
    baseTempDir: string,
    tempRoot?: string,
  ): Promise<void> {
    await cleanupSketchDirs(sketchDir, baseTempDir, tempRoot);
  }
}
 
// singleton instance removed, not used anywhere