generated from MetaMask/metamask-module-template
-
Notifications
You must be signed in to change notification settings - Fork 5
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
Merged
Merged
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
a765ca7
build: Support bundling with vite
grypez ff56480
build: Remove @endo/import-bundle support
grypez d8b0178
respin yarn
grypez dd54c25
fix test mock
grypez 7d1ffcd
Apply some suggestions from code review
grypez 69039b0
address remaining review comments
grypez 46caccd
small fixes
grypez 0fa7ea3
add isVatBundle to index test
grypez 20165fa
build: fix bundle import scrubber (#772)
grypez ef51f72
repro(4:1): isVatBundle type guard missing property validation
grypez 1802892
repro(2:2): loadBundle missing code property validation
grypez 8390606
repro(4:2): stripCommentsPlugin nonstrict parsing
grypez ca925e5
fix(2:2): validate code property in loadBundle
grypez 9ca966b
fix(4:1): validate all VatBundle properties in isVatBundle
grypez 1da5def
fix(4:2): use script sourceType for IIFE bundle parsing
grypez 0d4fbdf
fix(5:4): remove redundant assert from loadBundle
grypez 4f7d795
fix(5:1): remove unused VatBundle re-export
grypez 0aba19e
fix(5:2,5:3): remove unused BundleMetadata export and modules metadata
grypez c4ba419
fix: update test.bundle fixture to use external field
grypez 685b9af
fix(6:2): remove unnecessary VatBundle type cast
grypez 2082e18
fix(7:1): use external field in test bundle mocks
grypez 831a2dc
fix(7:2): remove unnecessary export from LoadBundleOptions
grypez c0cf139
fix(8:1,8:2): use superstruct for VatBundle and fix plugin types
grypez acce346
repro(8:1): add tests for null/non-object bundle content
grypez 4d3ef97
fix(8:1): add null check validation to loadBundle
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,32 @@ | ||
| import type { Plugin } from 'vite'; | ||
|
|
||
| type BundleMetadata = { | ||
| exports: string[]; | ||
| external: string[]; | ||
| }; | ||
cursor[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * Rollup plugin that captures export metadata from the bundle. | ||
| * | ||
| * Uses the `generateBundle` hook to extract the exports array from the | ||
| * entry chunk. | ||
| * | ||
| * @returns A plugin with an additional `getMetadata()` method. | ||
| */ | ||
| export function exportMetadataPlugin(): Plugin & { | ||
| getMetadata: () => BundleMetadata; | ||
| } { | ||
| const metadata: BundleMetadata = { exports: [], external: [] }; | ||
|
|
||
| return { | ||
| name: 'export-metadata', | ||
| generateBundle(_, bundle) { | ||
| for (const chunk of Object.values(bundle)) { | ||
| if (chunk.type === 'chunk' && chunk.isEntry) { | ||
| metadata.exports = chunk.exports; | ||
| } | ||
| } | ||
| }, | ||
| 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 'vite'; | ||
|
|
||
| /** | ||
| * 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, | ||
| }); | ||
cursor[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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,55 @@ | ||
| 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(), | ||
| }; | ||
| } |
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.