All files / src/workers ResourceInjector.ts

91.11% Statements 82/90
69.62% Branches 55/79
100% Functions 14/14
91.35% Lines 74/81

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                                                            2x 2x 2x                                       3x 4x 4x   3x   3x 2x         1x                 1x 1x   1x       1x 1x 1x 1x     1x 1x       3x 3x                   2x 1x 1x               13x 13x   13x 13x 13x 13x                   13x   13x         3x             10x 13x   3x   2x                 3x             1x 1x   2x           2x 2x 1x   1x               3x 2x 2x 2x 2x 1x   1x                           6x 1x               5x     5x 2x               3x 3x 3x 1x             2x 2x   6x 2x 2x 2x 2x 2x 2x   1x         2x   1x                     1x                
import { createI18nKey } from "../protocol/ProtocolValidator.js";
import { ResourceMap, EngineErrorCode } from "../types.js";
import { EngineError } from "../errors/EngineError.js";
 
interface MessagePayload {
  type: string;
  resources?: ResourceMap;
  [key: string]: unknown;
}
 
interface WorkerGlobalScope {
  postMessage: (message: unknown) => void;
  onmessage: ((ev: MessageEvent) => void) | null;
}
 
interface EmscriptenFS {
  mkdir: (path: string) => void;
  writeFile: (path: string, data: Uint8Array) => void;
}
 
interface EmscriptenModule {
  FS?: EmscriptenFS;
  locateFile?: (path: string, prefix: string) => string;
  [key: string]: unknown;
}
 
/**
 * Worker 側でリソースの注入とパス解決を管理するユーティリティ。
 */
export class ResourceInjector {
  private static resources: ResourceMap = {};
  private static isReady = false;
  private static readyCallbacks: (() => void)[] = [];
 
  /**
   * WorkerGlobalScope の型ガード
   */
  private static isWorkerScope(obj: unknown): obj is WorkerGlobalScope {
    return (
      typeof obj === "object" &&
      obj !== null &&
      "postMessage" in obj &&
      typeof (obj as { postMessage?: unknown }).postMessage === "function" &&
      "onmessage" in obj &&
      !("document" in obj)
    );
  }
 
  /**
   * メッセージを監視し、リソース注入コマンドを処理します。
   */
  static listen(onMessage?: (ev: MessageEvent) => void): void {
    const handler = (ev: MessageEvent) => {
      const data = ev.data;
      if (!data || typeof data !== "object") return;
 
      const payload = data as MessagePayload;
 
      if (payload.type === "MG_INJECT_RESOURCES") {
        if (
          !payload.resources ||
          typeof payload.resources !== "object" ||
          payload.resources === null
        ) {
          throw new EngineError({
            code: EngineErrorCode.PROTOCOL_ERROR,
            message:
              "[ResourceInjector] Invalid or missing resources in MG_INJECT_RESOURCES",
            i18nKey: createI18nKey("engine.errors.protocolError"),
            i18nParams: { message: "Invalid resources payload" },
          });
        }
 
        this.resources = { ...this.resources, ...payload.resources };
        this.isReady = true;
 
        Iif (typeof self !== "undefined" && this.isWorkerScope(self)) {
          self.postMessage({ type: "MG_RESOURCES_READY" });
        }
 
        const callbacks = [...this.readyCallbacks];
        this.readyCallbacks = [];
        callbacks.forEach((cb) => cb());
        return;
      }
 
      Eif (onMessage) {
        onMessage(ev);
      }
    };
 
    if (typeof globalThis.addEventListener === "function") {
      globalThis.addEventListener("message", handler);
    } else if (Etypeof self !== "undefined" && this.isWorkerScope(self)) {
      self.onmessage = handler;
    }
  }
 
  /**
   * リソースの注入が完了するまで待機します。
   */
  static waitForReady(): Promise<void> {
    if (this.isReady) return Promise.resolve();
    return new Promise((resolve) => {
      this.readyCallbacks.push(resolve);
    });
  }
 
  /**
   * 指定されたパスに対応する Blob URL を返します。
   */
  static resolve(path: string): string {
    let decodedPath = path;
    let prevPath = "";
 
    try {
      while (decodedPath !== prevPath) {
        prevPath = decodedPath;
        decodedPath = decodeURIComponent(decodedPath);
      }
    } catch {
      throw new EngineError({
        code: EngineErrorCode.SECURITY_ERROR,
        message: `[ResourceInjector] Invalid URL encoding in path: "${path}"`,
        i18nKey: createI18nKey("engine.errors.illegalCharacters"),
      });
    }
 
    const normalizedForCheck = decodedPath.replace(/\\/g, "/");
 
    if (
      normalizedForCheck.includes("..") ||
      normalizedForCheck.startsWith("/") ||
      normalizedForCheck.includes("./")
    ) {
      throw new EngineError({
        code: EngineErrorCode.SECURITY_ERROR,
        message: `[ResourceInjector] Path pattern detected: "${path}"`,
        i18nKey: createI18nKey("engine.errors.securityViolation"),
      });
    }
 
    const lookupPath = path.startsWith("./") ? path.slice(2) : path;
    if (this.resources[lookupPath]) return this.resources[lookupPath];
 
    for (const [mountPath, blobUrl] of Object.entries(this.resources)) {
      // 2026: Precise suffix match (ensure it matches a whole segment or the whole path)
      Iif (
        lookupPath === mountPath ||
        (lookupPath.endsWith(mountPath) &&
          lookupPath.charAt(lookupPath.length - mountPath.length - 1) === "/")
      ) {
        return blobUrl;
      }
    }
 
    return path;
  }
 
  /**
   * global fetch をオーバーライドして、注入されたリソースを自動的に解決します。
   */
  static interceptFetch(): void {
    const originalFetch = globalThis.fetch;
    globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
      const url =
        typeof input === "string"
          ? input
          : input instanceof URL
            ? input.href
            : input.url;
 
      const resolvedUrl = this.resolve(url);
      if (resolvedUrl !== url) {
        return originalFetch(resolvedUrl, init);
      }
      return originalFetch(input, init);
    };
  }
 
  /**
   * Emscripten の Module オブジェクトに対してリソース解決ロジックを注入します。
   */
  static adaptEmscriptenModule(moduleParams: EmscriptenModule): void {
    if (!moduleParams) return;
    const originalLocateFile = moduleParams.locateFile;
    moduleParams.locateFile = (path: string, prefix: string) => {
      const resolved = this.resolve(path);
      if (resolved !== path && resolved.startsWith("blob:")) {
        return resolved;
      }
      return originalLocateFile
        ? originalLocateFile(path, prefix)
        : prefix + path;
    };
  }
 
  /**
   * Emscripten の仮想ファイルシステム (FS) にリソースをマウントします。
   */
  static async mountToVFS(
    moduleInstance: EmscriptenModule,
    vfsPath: string,
    resourceKey: string,
  ): Promise<void> {
    if (!moduleInstance || !moduleInstance.FS) {
      throw new EngineError({
        code: EngineErrorCode.INTERNAL_ERROR,
        message: "ResourceInjector: Module instance or FS not found.",
        i18nKey: createI18nKey("engine.errors.internalError"),
        i18nParams: { message: "Module or FS not found" },
      });
    }
 
    const blobUrl = this.resolve(resourceKey);
    // 2026 Zenith Tier: 物理的なリソース境界の強制。
    // レジストリ解決値が blob: スキームでない場合は、外部インジェクションとみなして拒否。
    if (!blobUrl.startsWith("blob:")) {
      throw new EngineError({
        code: EngineErrorCode.INTERNAL_ERROR,
        message: "Resource not found or invalid scheme in registry",
        i18nKey: createI18nKey("engine.errors.internalError"),
        i18nParams: { resourceKey }, // 文面ではなくキーのみを渡す
      });
    }
 
    try {
      const response = await globalThis.fetch(blobUrl);
      if (!response.ok) {
        throw new EngineError({
          code: EngineErrorCode.NETWORK_ERROR,
          message: `Failed to fetch resource: ${response.statusText}`,
          i18nKey: createI18nKey("engine.errors.networkError"),
        });
      }
 
      const buffer = await response.arrayBuffer();
      const data = new Uint8Array(buffer);
 
      const parts = vfsPath.split("/").filter((p) => p);
      Eif (parts.length > 1) {
        let currentPath = "";
        for (let i = 0; i < parts.length - 1; i++) {
          currentPath += "/" + parts[i];
          try {
            moduleInstance.FS.mkdir(currentPath);
          } catch (e: unknown) {
            Iif (!this.isFsError(e) || e.code !== "EEXIST") throw e;
          }
        }
      }
 
      moduleInstance.FS.writeFile(vfsPath, data);
    } catch (error: unknown) {
      Eif (error instanceof EngineError) throw error;
      throw new EngineError({
        code: EngineErrorCode.INTERNAL_ERROR,
        message: `Failed to mount "${resourceKey}" to "${vfsPath}": ${error}`,
        i18nKey: createI18nKey("engine.errors.internalError"),
        i18nParams: { message: `Mount failed: ${resourceKey}` },
      });
    }
  }
 
  private static isFsError(e: unknown): e is { code: string } {
    return (
      typeof e === "object" &&
      e !== null &&
      "code" in e &&
      typeof (e as { code: unknown }).code === "string"
    );
  }
}