diff --git a/packages/wxt/src/utils/__tests__/define-unlisted-script.test.ts b/packages/wxt/src/utils/__tests__/define-unlisted-script.test.ts index 4d656e515..f4b327b8c 100644 --- a/packages/wxt/src/utils/__tests__/define-unlisted-script.test.ts +++ b/packages/wxt/src/utils/__tests__/define-unlisted-script.test.ts @@ -21,4 +21,22 @@ describe('defineUnlistedScript', () => { expect(actual).toEqual({ main }); }); + + it('should return the object definition when given a main function that returns a value', () => { + const main = vi.fn(() => 'test'); + + const actual = defineUnlistedScript(main); + + expect(actual).toEqual({ main }); + expect(actual.main()).eq('test'); + }); + + it('should return the object definition when given a main function that returns a promise', async () => { + const main = vi.fn(() => Promise.resolve('test')); + + const actual = defineUnlistedScript(main); + + expect(actual).toEqual({ main }); + await expect(actual.main()).resolves.toEqual('test'); + }); }); diff --git a/packages/wxt/src/virtual/unlisted-script-entrypoint.ts b/packages/wxt/src/virtual/unlisted-script-entrypoint.ts index 843d9ac46..05d4bcddf 100644 --- a/packages/wxt/src/virtual/unlisted-script-entrypoint.ts +++ b/packages/wxt/src/virtual/unlisted-script-entrypoint.ts @@ -2,10 +2,29 @@ import definition from 'virtual:user-unlisted-script-entrypoint'; import { logger } from '../utils/internal/logger'; import { initPlugins } from 'virtual:wxt-plugins'; -const result = (async () => { +const result = (() => { try { initPlugins(); - return await definition.main(); + } catch (err) { + logger.error( + `Failed to initialize plugins for "${import.meta.env.ENTRYPOINT}"`, + err, + ); + throw err; + } + let result; + try { + result = definition.main(); + + if (result && typeof result === 'object' && 'then' in result) { + result = (result as Promise).catch((err) => { + logger.error( + `The unlisted script "${import.meta.env.ENTRYPOINT}" crashed on startup!`, + err, + ); + throw err; + }); + } } catch (err) { logger.error( `The unlisted script "${import.meta.env.ENTRYPOINT}" crashed on startup!`, @@ -13,6 +32,7 @@ const result = (async () => { ); throw err; } + return result; })(); // Return the main function's result to the background when executed via the