@@ -4,7 +4,10 @@ import type { BackgroundEventRouter } from "src/app-background"
44export type RouterHandler = ( r : BackgroundEventRouter ) => Promise < void > | undefined
55
66/** Cached router instance */
7- let router : BackgroundEventRouter | undefined
7+ let routerCache : BackgroundEventRouter | undefined
8+
9+ /** Promise for loading the router, used to avoid multiple concurrent loads */
10+ let routerPromise : Promise < BackgroundEventRouter > | undefined
811
912/**
1013 * Executes a handler function with the background event router.
@@ -13,11 +16,18 @@ let router: BackgroundEventRouter | undefined
1316 * @returns A promise that resolves when the handler completes, or undefined if an error occurs
1417 */
1518export function withRouter ( handler : RouterHandler ) : Promise < void > | undefined {
16- if ( router ) {
17- return withRouterSync ( handler , router )
18- } else {
19- return withRouterAsync ( handler )
19+ if ( routerCache ) {
20+ return runHandler ( handler , routerCache )
2021 }
22+
23+ routerPromise ??= import ( "./startup/startup_background" ) . then ( ( s ) => s . prepareBackgroundRouter ( ) )
24+
25+ return routerPromise . then ( ( router ) => {
26+ routerCache = router
27+ routerPromise = undefined
28+
29+ return runHandler ( handler , router )
30+ } )
2131}
2232
2333/**
@@ -27,24 +37,11 @@ export function withRouter(handler: RouterHandler): Promise<void> | undefined {
2737 * @param router The background event router to use
2838 * @returns A promise that resolves when the handler completes, or undefined if an error occurs
2939 */
30- function withRouterSync ( handler : RouterHandler , router : BackgroundEventRouter ) : Promise < void > | undefined {
40+ function runHandler ( handler : RouterHandler , router : BackgroundEventRouter ) : Promise < void > | undefined {
3141 try {
3242 return handler ( router )
3343 } catch ( error ) {
3444 console . error ( { error } )
3545 return
3646 }
3747}
38-
39- /**
40- * Initializes the background event router and executes a handler.
41- *
42- * @param handler The function to execute with the initialized router
43- * @returns A promise that resolves when the handler completes
44- */
45- async function withRouterAsync ( handler : RouterHandler ) : Promise < void > {
46- const { prepareBackgroundRouter } = await import ( "./startup/startup_background" )
47- router = prepareBackgroundRouter ( )
48-
49- return withRouterSync ( handler , router )
50- }
0 commit comments