generated from MetaMask/metamask-module-template
-
Notifications
You must be signed in to change notification settings - Fork 7
build: Bundle vats with vite #763
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
grypez
wants to merge
15
commits into
main
Choose a base branch
from
grypez/bundle-with-vite
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
fc5ab8d
build: Support bundling with vite
grypez e90670c
build: Remove @endo/import-bundle support
grypez cbda223
respin yarn
grypez 847d93e
fix test mock
grypez d4fb9ba
Apply some suggestions from code review
grypez 492dd2e
address remaining review comments
grypez 092baeb
small fixes
grypez 6f69bb2
add isVatBundle to index test
grypez 21ebcf4
build: fix bundle import scrubber (#772)
grypez 467461c
repro(4:1): isVatBundle type guard missing property validation
grypez 5e54700
repro(2:2): loadBundle missing code property validation
grypez d876d68
repro(4:2): stripCommentsPlugin nonstrict parsing
grypez 1424d58
fix(2:2): validate code property in loadBundle
grypez db40d34
fix(4:1): validate all VatBundle properties in isVatBundle
grypez 6cd04a3
fix(4:2): use script sourceType for IIFE bundle parsing
grypez File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import type { Plugin, RenderedModule } from 'rollup'; | ||
|
|
||
| export type BundleMetadata = { | ||
| exports: string[]; | ||
| modules: Record< | ||
| string, | ||
| { renderedExports: string[]; removedExports: string[] } | ||
| >; | ||
| }; | ||
|
|
||
| /** | ||
| * Rollup plugin that captures export metadata from the bundle. | ||
| * | ||
| * Uses the `generateBundle` hook to extract the exports array and | ||
| * per-module metadata (renderedExports and removedExports) from the | ||
| * entry chunk. | ||
| * | ||
| * @returns A plugin with an additional `getMetadata()` method. | ||
| */ | ||
| export function exportMetadataPlugin(): Plugin & { | ||
| getMetadata: () => BundleMetadata; | ||
| } { | ||
| const metadata: BundleMetadata = { exports: [], modules: {} }; | ||
|
|
||
| return { | ||
| name: 'export-metadata', | ||
| generateBundle(_, bundle) { | ||
| for (const chunk of Object.values(bundle)) { | ||
| if (chunk.type === 'chunk' && chunk.isEntry) { | ||
| const outputChunk = chunk; | ||
| metadata.exports = outputChunk.exports; | ||
| metadata.modules = Object.fromEntries( | ||
| Object.entries(outputChunk.modules).map( | ||
| ([id, info]: [string, RenderedModule]) => [ | ||
| id, | ||
| { | ||
| renderedExports: info.renderedExports, | ||
| removedExports: info.removedExports, | ||
| }, | ||
| ], | ||
| ), | ||
| ); | ||
| } | ||
| } | ||
| }, | ||
| getMetadata: () => metadata, | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import { describe, it, expect } from 'vitest'; | ||
|
|
||
| import { stripCommentsPlugin } from './strip-comments-plugin.ts'; | ||
|
|
||
| describe('stripCommentsPlugin', () => { | ||
| describe('parsing non-strict-mode code', () => { | ||
| const plugin = stripCommentsPlugin(); | ||
| const renderChunk = plugin.renderChunk as (code: string) => string | null; | ||
|
|
||
| it('handles octal literals in bundled IIFE code', () => { | ||
| // Octal literals like 010 are valid in non-strict mode (scripts) | ||
| // but invalid in strict mode (modules). IIFE bundles are scripts. | ||
| const iifeWithOctal = '(function() { var x = 010; /* comment */ })();'; | ||
| expect(() => renderChunk(iifeWithOctal)).not.toThrow(); | ||
| }); | ||
|
|
||
| it('handles with statements in bundled IIFE code', () => { | ||
| // 'with' statements are valid in non-strict mode (scripts) | ||
| // but invalid in strict mode (modules). IIFE bundles are scripts. | ||
| const iifeWithWith = '(function() { with(obj) { /* comment */ x; } })();'; | ||
| expect(() => renderChunk(iifeWithWith)).not.toThrow(); | ||
| }); | ||
| }); | ||
| const plugin = stripCommentsPlugin(); | ||
| const renderChunk = plugin.renderChunk as (code: string) => string | null; | ||
|
|
||
| it.each([ | ||
| [ | ||
| 'single-line comment', | ||
| 'const x = 1; // comment\nconst y = 2;', | ||
| 'const x = 1; \nconst y = 2;', | ||
| ], | ||
| [ | ||
| 'multi-line comment', | ||
| 'const x = 1; /* comment */ const y = 2;', | ||
| 'const x = 1; const y = 2;', | ||
| ], | ||
| [ | ||
| 'multiple comments', | ||
| '/* a */ const x = 1; // b\n/* c */', | ||
| ' const x = 1; \n', | ||
| ], | ||
| [ | ||
| 'comment containing import()', | ||
| 'const x = 1; // import("module")\nconst y = 2;', | ||
| 'const x = 1; \nconst y = 2;', | ||
| ], | ||
| [ | ||
| 'comment with string content preserved', | ||
| 'const x = "// in string"; // real comment', | ||
| 'const x = "// in string"; ', | ||
| ], | ||
| ['code that is only a comment', '// just a comment', ''], | ||
| ])('removes %s', (_name, code, expected) => { | ||
| expect(renderChunk(code)).toBe(expected); | ||
| }); | ||
|
|
||
| it.each([ | ||
| ['string with // pattern', 'const x = "// not a comment";'], | ||
| ['string with /* */ pattern', 'const x = "/* not a comment */";'], | ||
| ['regex literal like //', 'const re = /\\/\\//;'], | ||
| ['template literal with // pattern', 'const x = `// not a comment`;'], | ||
| ['nested quotes in string', 'const x = "a \\"// not comment\\" b";'], | ||
| ['no comments', 'const x = 1;'], | ||
| ['empty code', ''], | ||
| ])('returns null for %s', (_name, code) => { | ||
| expect(renderChunk(code)).toBeNull(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import type { Comment } from 'acorn'; | ||
| import { parse } from 'acorn'; | ||
| import type { Plugin } from 'rollup'; | ||
|
|
||
| /** | ||
| * Rollup plugin that strips comments from bundled code using AST parsing. | ||
| * | ||
| * SES rejects code containing `import(` patterns, even when they appear | ||
| * in comments. This plugin uses Acorn to definitively identify comment nodes | ||
| * and removes them to avoid triggering that detection. | ||
| * | ||
| * Uses the `renderChunk` hook to process the final output. | ||
| * | ||
| * @returns A Rollup plugin. | ||
| */ | ||
| export function stripCommentsPlugin(): Plugin { | ||
| return { | ||
| name: 'strip-comments', | ||
| renderChunk(code) { | ||
| const comments: Comment[] = []; | ||
|
|
||
| parse(code, { | ||
| ecmaVersion: 'latest', | ||
| sourceType: 'script', | ||
| onComment: comments, | ||
| }); | ||
|
|
||
| if (comments.length === 0) { | ||
| return null; | ||
| } | ||
|
|
||
| // Build result by copying non-comment ranges. | ||
| // Comments are sorted by position since acorn parses linearly. | ||
| let result = ''; | ||
| let position = 0; | ||
|
|
||
| for (const comment of comments) { | ||
| result += code.slice(position, comment.start); | ||
| position = comment.end; | ||
| } | ||
|
|
||
| result += code.slice(position); | ||
| return result; | ||
| }, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import type { VatBundle } from '@metamask/kernel-utils'; | ||
| import { build } from 'vite'; | ||
| import type { Rollup, PluginOption } from 'vite'; | ||
|
|
||
| import { exportMetadataPlugin } from './export-metadata-plugin.ts'; | ||
| import { stripCommentsPlugin } from './strip-comments-plugin.ts'; | ||
|
|
||
| export type { VatBundle }; | ||
|
|
||
| /** | ||
| * 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 modules. | ||
| * | ||
| * @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() as unknown as PluginOption, | ||
| metadataPlugin as unknown as PluginOption, | ||
| ], | ||
| }, | ||
| 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(), | ||
| }; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.