All files / cli/src/vite vat-bundler.ts

0% Statements 0/8
0% Branches 0/6
0% Functions 0/2
0% Lines 0/8

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                                                                                                               
import type { VatBundle } from '@metamask/kernel-utils';
import { build } from 'vite';
import type { Rollup } from 'vite';
 
import { exportMetadataPlugin } from './export-metadata-plugin.ts';
import { stripCommentsPlugin } from './strip-comments-plugin.ts';
 
/**
 * 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();
 
  const result = await build({
    configFile: false,
    logLevel: 'silent',
    build: {
      write: false,
      lib: {
        entry: sourcePath,
        formats: ['iife'],
        name: '__vatExports__',
      },
      rollupOptions: {
        output: {
          exports: 'named',
          inlineDynamicImports: true,
        },
        plugins: [stripCommentsPlugin(), metadataPlugin],
      },
      minify: false,
    },
  });
 
  const output = Array.isArray(result) ? result[0] : result;
  const chunk = (output as Rollup.RollupOutput).output.find(
    (item): item is Rollup.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(),
  };
}