All files / src/lib/compiler enginePlugins.ts

66.45% Statements 103/155
73.21% Branches 41/56
66.67% Functions 10/15
65.28% Lines 94/144

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 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 4211x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                                             1x           9x         9x 13x 3x   10x 10x 10x 4x               10x       1x                                                                   1x                                                                                                                                                                                                                                                             1x                   13x 1x     12x 12x 7x 2x     10x 3x 1x     9x 4x   5x 7x     4x 1x     8x     12x 7x 7x 7x 6x         1x     5x               1x       25x 25x       25x 3x         22x 18x 17x 17x 9x 8x   8x           6x                   1x 25x           1x 10x           1x       9x         9x   9x   9x 15x 15x 15x 4x     11x           9x               1x             11x 13x 13x 10x 10x 2x         8x 6x 6x 6x 6x 1x               5x             2x                  
import fs, { readJSON } from "fs-extra";
import Path from "path";
import l10n from "shared/lib/lang/l10n";
import copy from "lib/helpers/fsCopy";
import { isFilePathWithinFolder } from "lib/helpers/path";
import { applyPatch } from "diff";
import { PluginMetadata } from "lib/pluginManager/types";
import { satisfies } from "semver";
import { pathToPosix } from "shared/lib/helpers/path";
import glob from "glob";
import { promisify } from "util";
import { Value } from "@sinclair/typebox/value";
import { readEngineVersion } from "lib/project/engine";
import { isKnownEngineVersion } from "lib/project/ejectEngineChangelog";
 
const globAsync = promisify(glob);
 
declare const RELEASE_VERSION: string;
 
type ApplyEnginePluginOptions = {
  outputRoot: string;
  projectRoot: string;
  expectedEngineVersion: string;
  unusedFiles: string[];
  progress: (msg: string) => void;
  warnings: (msg: string) => void;
};
 
type EnginePluginEntry = {
  enginePluginPath: string;
  pluginName: string;
  order: number;
};
 
/**
 * Scans a plugin's engine files and warns if any would overwrite files already
 * written by a previously processed plugin. Updates writtenByPlugin in-place.
 */
export const warnOnPluginFileCollisions = async (
  usedEnginePluginPath: string,
  pluginName: string,
  writtenByPlugin: Map<string, string>,
  warnings: (msg: string) => void,
): Promise<void> => {
  const pluginFiles = await globAsync("**/*", {
    cwd: usedEnginePluginPath,
    nodir: true,
  });
 
  for (const relFile of pluginFiles) {
    if (isPatchFile(relFile) || isEngineManifestFile(relFile)) {
      continue;
    }
    const posixRel = pathToPosix(relFile);
    const previousPlugin = writtenByPlugin.get(posixRel);
    if (previousPlugin !== undefined) {
      warnings(
        l10n("WARNING_PLUGIN_OVERWROTE_FILE", {
          filename: posixRel,
          pluginName,
          previousPlugin,
        }),
      );
    }
    writtenByPlugin.set(posixRel, pluginName);
  }
};
 
export const buildSortedEnginePluginList = async (
  pluginsPath: string,
): Promise<EnginePluginEntry[]> => {
  const enginePluginPaths = await globAsync(`${pluginsPath}/**/engine`);
  const enginePlugins: EnginePluginEntry[] = [];
 
  for (const enginePluginPath of enginePluginPaths) {
    const enginePluginDir = Path.dirname(enginePluginPath);
    const pluginName = Path.relative(pluginsPath, enginePluginDir);
    const pluginJsonPath = Path.join(enginePluginDir, "plugin.json");
 
    let order = 0;
 
    try {
      const pluginJson = await readJSON(pluginJsonPath);
      const pluginData = Value.Cast(PluginMetadata, pluginJson);
      order = pluginData.order ?? 0;
    } catch {
      order = 0;
    }
 
    enginePlugins.push({
      enginePluginPath,
      pluginName,
      order,
    });
  }
 
  // Sort so lower order runs first, higher order runs last
  enginePlugins.sort((a, b) => a.order - b.order);
 
  return enginePlugins;
};
 
export const applyEnginePlugins = async ({
  progress,
  warnings,
  expectedEngineVersion,
  unusedFiles,
  outputRoot,
  projectRoot,
}: ApplyEnginePluginOptions) => {
  const pluginsPath = Path.join(projectRoot, "plugins");
 
  progress(
    l10n("COMPILER_LOOKING_FOR_ENGINE_PLUGINS", { path: "plugins/*/engine" }),
  );
 
  const pluginPaths = await globAsync(`${pluginsPath}/**/plugin.json`);
  const posixRelativePluginPaths = pluginPaths.map((p) =>
    pathToPosix(Path.relative(pluginsPath, Path.dirname(p))),
  );
 
  const releaseVersion = RELEASE_VERSION.replace(/-rc.*/, "");
 
  const enginePlugins = await buildSortedEnginePluginList(pluginsPath);
  const writtenByPlugin = new Map<string, string>();
  const allPatches: PatchInfo[] = [];
 
  for (const { enginePluginPath, pluginName } of enginePlugins) {
    progress(
      l10n("COMPILER_USING_ENGINE_PLUGIN", {
        path: pluginName,
      }),
    );
 
    const pluginJsonPath = Path.join(
      Path.dirname(enginePluginPath),
      "plugin.json",
    );
 
    let usedEnginePluginPath = enginePluginPath;
 
    try {
      const pluginJson = await readJSON(pluginJsonPath);
      const pluginData = Value.Cast(PluginMetadata, pluginJson);
 
      const altEngineResult = selectAlternateEngine(
        pluginData,
        enginePluginPath,
        releaseVersion,
        expectedEngineVersion,
        posixRelativePluginPaths,
      );
 
      usedEnginePluginPath = altEngineResult.usedPath;
 
      Iif (altEngineResult.altRuleMatched) {
        progress(
          `- ${l10n("COMPILER_USING_ENGINE_PLUGIN_VERSION", { path: altEngineResult.altRuleMatched })}`,
        );
      }
    } catch (e) {
      Iif (
        e instanceof Error &&
        e.message === "Engine alt path outside allowed directory"
      ) {
        warnings(
          l10n("WARNING_PLUGIN_MODIFIED_OUTSIDE_ENGINE_ROOT", {
            filename: Path.relative(projectRoot, enginePluginPath),
          }),
        );
      }
      // Invalid or missing plugin.json, ignore
    }
 
    try {
      const pluginEngineMetaPath = `${usedEnginePluginPath}/engine.json`;
      const pluginEngineVersion = await readEngineVersion(pluginEngineMetaPath);
      Iif (!pluginEngineVersion || !isKnownEngineVersion(pluginEngineVersion)) {
        throw new Error("Missing plugin engine version");
      }
      Iif (pluginEngineVersion !== expectedEngineVersion) {
        warnings(
          `${l10n("WARNING_ENGINE_PLUGIN_OUT_OF_DATE", {
            pluginName,
            pluginEngineVersion,
            expectedEngineVersion,
          })}`,
        );
      }
    } catch (e) {
      warnings(
        `${l10n("WARNING_ENGINE_PLUGIN_MISSING_MANIFEST", {
          pluginName,
          expectedEngineVersion,
        })}`,
      );
    }
 
    const patchPaths = await collectPatchFiles(
      usedEnginePluginPath,
      unusedFiles,
    );
 
    allPatches.push(...patchPaths.map((p) => ({ ...p, pluginName })));
 
    await warnOnPluginFileCollisions(
      usedEnginePluginPath,
      pluginName,
      writtenByPlugin,
      warnings,
    );
 
    await copy(usedEnginePluginPath, outputRoot, {
      ignore: isPatchFile,
    });
  }
 
  await applyPatches(
    allPatches,
    outputRoot,
    projectRoot,
    writtenByPlugin,
    warnings,
  );
};
 
/**
 * Determines which alternate engine path to use based on plugin rules
 */
export const selectAlternateEngine = (
  pluginData: PluginMetadata,
  enginePluginPath: string,
  releaseVersion: string,
  expectedEngineVersion: string,
  posixRelativePluginPaths: string[],
): {
  usedPath: string;
  altRuleMatched?: string;
} => {
  if (!pluginData.engineAltRules) {
    return { usedPath: enginePluginPath };
  }
 
  const altRule = pluginData.engineAltRules.find((rule) => {
    if (rule.when.gbsVersion) {
      if (!satisfies(releaseVersion, rule.when.gbsVersion)) {
        return false;
      }
    }
    if (rule.when.engineVersion) {
      if (rule.when.engineVersion !== expectedEngineVersion) {
        return false;
      }
    }
    if (rule.when.additionalPlugins) {
      const hasRequiredPlugins = rule.when.additionalPlugins.every(
        (requiredPlugin) =>
          posixRelativePluginPaths.some(
            (p) => pathToPosix(requiredPlugin) === p,
          ),
      );
      if (!hasRequiredPlugins) {
        return false;
      }
    }
    return true;
  });
 
  if (altRule && altRule.use) {
    const altEngineDir = Path.join(Path.dirname(enginePluginPath), "engineAlt");
    const altEnginePath = Path.join(altEngineDir, altRule.use);
    if (isFilePathWithinFolder(altEnginePath, altEngineDir)) {
      return {
        usedPath: altEnginePath,
        altRuleMatched: altRule.use,
      };
    }
    throw new Error("Engine alt path outside allowed directory");
  }
 
  return { usedPath: enginePluginPath };
};
 
type PatchInfo = { abs: string; rel: string; pluginName?: string };
 
/**
 * Applies a single patch file to a target file
 */
export const applyPatchToFile = async (
  patchInfo: PatchInfo,
  outputRoot: string,
): Promise<{ success: boolean; error?: Error }> => {
  try {
    const filePath = Path.join(
      outputRoot,
      patchInfo.rel.replace(/\.patch$/, ""),
    );
    if (!isFilePathWithinFolder(filePath, outputRoot)) {
      return {
        success: false,
        error: new Error("Path outside engine root"),
      };
    }
    const inFile = await fs.readFile(filePath, "utf8");
    const patchFile = await fs.readFile(patchInfo.abs, "utf8");
    const out = applyPatch(inFile, patchFile);
    if (out !== false) {
      await fs.writeFile(filePath, out, "utf8");
      return { success: true };
    } else {
      return {
        success: false,
        error: new Error("Patch conflict"),
      };
    }
  } catch (e) {
    return {
      success: false,
      error: e instanceof Error ? e : new Error(String(e)),
    };
  }
};
 
/**
 * Utility to check if a file is a patch file
 */
export const isPatchFile = (src: string): boolean => {
  return src.endsWith(".patch");
};
 
/**
 * Utility to check if a file is an engine.json file
 */
export const isEngineManifestFile = (src: string): boolean => {
  return src.endsWith("engine.json");
};
 
/**
 * Collects patch files for an engine plugin, excluding those that target unused files
 */
export const collectPatchFiles = async (
  usedEnginePluginPath: string,
  unusedFiles: string[],
): Promise<PatchInfo[]> => {
  const patchFiles = await globAsync("**/*.patch", {
    cwd: usedEnginePluginPath,
    absolute: true,
  });
 
  const unusedSet = new Set(unusedFiles);
 
  const patches: PatchInfo[] = [];
 
  for (const absPath of patchFiles) {
    const relPath = Path.relative(usedEnginePluginPath, absPath);
    const targetFile = pathToPosix(relPath.replace(/\.patch$/, ""));
    if (unusedSet.has(targetFile)) {
      continue;
    }
 
    patches.push({
      abs: absPath,
      rel: relPath,
    });
  }
 
  return patches;
};
 
/**
 * Applies multiple patches and returns results for each.
 * When pluginName and writtenByPlugin are provided, patch conflicts caused by
 * another plugin having overwritten the target file produce a richer warning.
 */
export const applyPatches = async (
  patchPaths: PatchInfo[],
  outputRoot: string,
  projectRoot: string,
  writtenByPlugin: Map<string, string>,
  warnings: (msg: string) => void,
): Promise<void> => {
  for (const patchPath of patchPaths) {
    const result = await applyPatchToFile(patchPath, outputRoot);
    if (!result.success) {
      const relPath = Path.relative(projectRoot, patchPath.abs);
      if (result.error?.message === "Path outside engine root") {
        warnings(
          l10n("WARNING_PLUGIN_MODIFIED_OUTSIDE_ENGINE_ROOT", {
            filename: relPath,
          }),
        );
      } else if (result.error?.message === "Patch conflict") {
        const posixRel = pathToPosix(patchPath.rel.replace(/\.patch$/, ""));
        const { pluginName } = patchPath;
        const previousPlugin = writtenByPlugin.get(posixRel);
        if (previousPlugin !== undefined && previousPlugin !== pluginName) {
          warnings(
            l10n("WARNING_PLUGIN_PATCH_CONFLICT_OVERWRITTEN", {
              filename: posixRel,
              pluginName: pluginName,
              previousPlugin,
            }),
          );
        } else {
          warnings(
            l10n("WARNING_FAILED_TO_APPLY_PATCH", {
              filename: relPath,
            }),
          );
        }
      } else {
        warnings(
          l10n("WARNING_FAILED_TO_APPLY_PATCH", {
            filename: relPath,
          }) + ` (${result.error?.message || "Unknown error"})`,
        );
      }
    }
  }
};