@@ -9,6 +9,7 @@ import type {
99 ListenerFunction ,
1010 Modules ,
1111 SandboxSetup ,
12+ SandpackBundlerFile ,
1213 SandpackBundlerFiles ,
1314 SandpackError ,
1415 UnsubscribeFunction ,
@@ -225,17 +226,46 @@ export class SandpackRuntime extends SandpackClient {
225226 this . iframe . addEventListener ( "load" , sendMessage ) ;
226227 }
227228
228- private handleWorkerRequest (
229+ private async handleWorkerRequest (
229230 request : IPreviewRequestMessage ,
230231 port : MessagePort
231232 ) {
233+ const notFound = ( ) => {
234+ const responseMessage : IPreviewResponseMessage = {
235+ $channel : CHANNEL_NAME ,
236+ $type : "preview/response" ,
237+ id : request . id ,
238+ headers : {
239+ "Content-Type" : "text/html; charset=utf-8" ,
240+ } ,
241+ status : 404 ,
242+ body : "File not found" ,
243+ } ;
244+
245+ port . postMessage ( responseMessage ) ;
246+ } ;
232247 try {
233248 const filepath = new URL ( request . url , this . bundlerURL ) . pathname ;
234249
235250 const headers : Record < string , string > = { } ;
236251
237252 const files = this . getFiles ( ) ;
238- const body = files [ filepath ] . code ;
253+ let file = files [ filepath ] ;
254+
255+ if ( ! file ) {
256+ const modulesFromManager = await this . getTranspiledFiles ( ) ;
257+
258+ file = modulesFromManager . find ( ( item ) =>
259+ item . path . endsWith ( filepath )
260+ ) as SandpackBundlerFile ;
261+
262+ if ( ! file ) {
263+ notFound ( ) ;
264+ return ;
265+ }
266+ }
267+
268+ const body = file . code ;
239269
240270 if ( ! headers [ "Content-Type" ] ) {
241271 const extension = getExtension ( filepath ) ;
@@ -256,18 +286,8 @@ export class SandpackRuntime extends SandpackClient {
256286
257287 port . postMessage ( responseMessage ) ;
258288 } catch ( err ) {
259- const responseMessage : IPreviewResponseMessage = {
260- $channel : CHANNEL_NAME ,
261- $type : "preview/response" ,
262- id : request . id ,
263- headers : {
264- "Content-Type" : "text/html; charset=utf-8" ,
265- } ,
266- status : 404 ,
267- body : "File not found" ,
268- } ;
269-
270- port . postMessage ( responseMessage ) ;
289+ console . error ( err ) ;
290+ notFound ( ) ;
271291 }
272292 }
273293
@@ -447,6 +467,22 @@ export class SandpackRuntime extends SandpackClient {
447467 this . dispatch ( { type : "get-transpiler-context" } ) ;
448468 } ) ;
449469
470+ public getTranspiledFiles = ( ) : Promise <
471+ Array < { path : string ; code : string } >
472+ > => {
473+ return new Promise ( ( resolve ) => {
474+ const unsubscribe = this . listen ( ( message ) => {
475+ if ( message . type === "all-modules" ) {
476+ resolve ( message . data ) ;
477+
478+ unsubscribe ( ) ;
479+ }
480+ } ) ;
481+
482+ this . dispatch ( { type : "get-modules" } ) ;
483+ } ) ;
484+ } ;
485+
450486 private getFiles ( ) : SandpackBundlerFiles {
451487 const { sandboxSetup } = this ;
452488
0 commit comments