All files / kernel-utils/src/vite-plugins bundle-vat.ts

41.66% Statements 10/24
50% Branches 6/12
40% Functions 2/5
41.66% Lines 10/24

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                                                                1x     16x 5x     11x         11x 4x           11x 4x     7x             1x                                                                                                                                                    
import type {
  OutputChunk,
  Plugin as RolldownPlugin,
  RolldownOutput,
} from 'rolldown';
import { build } from 'vite';
 
import type { VatBundle } from '../vat-bundle.ts';
import { exportMetadataPlugin } from './export-metadata-plugin.ts';
import { stripCommentsPlugin } from './strip-comments-plugin.ts';
 
export type { VatBundle } from '../vat-bundle.ts';
 
/**
 * A Rolldown plugin that replaces dynamic `import()` calls with `Promise.resolve({})`.
 *
 * Rolldown does not support IIFE format when any module in the bundle graph
 * contains dynamic imports, even when `output.codeSplitting` is false.
 * Some third-party packages (e.g. viem) use lazy `await import(x)` inside
 * utility functions that vats never actually call. This plugin removes those
 * dynamic imports from the code so that Rolldown accepts the IIFE format.
 *
 * Pattern transformed:
 *   `import('specifier')` / `import("specifier")` / `` import(`specifier`) ``
 *   → `Promise.resolve({})`
 *
 * Only replaces calls with literal string specifiers. Dynamic expressions
 * like `import(variable)` are left untouched.
 *
 * @returns A Rolldown plugin.
 */
export function removeDynamicImportsPlugin(): RolldownPlugin {
  return {
    name: 'ocap-kernel:remove-dynamic-imports',
    transform(code, id) {
      if (!/\bimport\s*\(/u.test(code)) {
        return null;
      }
 
      const transformed = code.replace(
        /\bimport\s*\(\s*(['"`])[^'"`]+\1\s*\)/gu,
        'Promise.resolve({})',
      );
 
      if (/\bimport\s*\(/u.test(transformed)) {
        this.warn(
          `Module "${id}" contains dynamic import() expressions that could not ` +
            `be replaced (e.g. computed specifiers). Rolldown may reject IIFE output.`,
        );
      }
 
      if (transformed === code) {
        return null;
      }
 
      return { code: transformed, map: null };
    },
  };
}
 
// Rolldown has global state that is corrupted when multiple build() calls run
// concurrently with IIFE format. Serialize all bundleVat calls to avoid this.
let buildQueue: Promise<void> = Promise.resolve();
 
/**
 * Bundle a vat source file using vite.
 *
 * Produces an IIFE bundle that assigns exports to a `__vatExports__` global,
 * along with metadata about the bundle's exports and external dependencies.
 *
 * @param sourcePath - Absolute path to the vat entry point.
 * @returns The bundle object containing code and metadata.
 */
export async function bundleVat(sourcePath: string): Promise<VatBundle> {
  const metadataPlugin = exportMetadataPlugin();
 
  // Wait for any in-flight build to finish before starting ours, then
  // register a slot so the next caller waits for us.
  const prevQueue = buildQueue;
  let releaseLock!: () => void;
  buildQueue = new Promise<void>((resolve) => {
    releaseLock = resolve;
  });
 
  let result: Awaited<ReturnType<typeof build>>;
  try {
    await prevQueue;
    result = await build({
      configFile: false,
      logLevel: 'silent',
      // TODO: Remove this define block and add a process shim to VatSupervisor
      // workerEndowments instead. This injects into ALL bundles but is only needed
      // for libraries like immer that check process.env.NODE_ENV.
      define: {
        'process.env.NODE_ENV': JSON.stringify('production'),
      },
      build: {
        write: false,
        minify: false,
        lib: {
          entry: sourcePath,
          formats: ['iife'],
          name: '__vatExports__',
        },
        rolldownOptions: {
          output: {
            exports: 'named',
            codeSplitting: false,
          },
          plugins: [
            removeDynamicImportsPlugin(),
            stripCommentsPlugin(),
            metadataPlugin,
          ],
        },
      },
    });
  } finally {
    releaseLock();
  }
 
  const output = Array.isArray(result) ? result[0] : result;
  const chunk = (output as RolldownOutput).output.find(
    (item): item is OutputChunk => item.type === 'chunk' && item.isEntry,
  );
 
  if (!chunk) {
    throw new Error(`Failed to produce bundle for ${sourcePath}`);
  }
 
  return {
    moduleFormat: 'iife',
    code: chunk.code,
    ...metadataPlugin.getMetadata(),
  };
}