@@ -3,41 +3,47 @@ import cors from 'cors';
33import express from 'express' ;
44import fs from 'node:fs' ;
55import path from 'node:path' ;
6- import { sandboxVersion } from '../../src/livecodes/html/sandbox/index.ts' ;
76import { dirname } from './utils.ts' ;
87
9- export const sandbox = ( { hostname, port } : { hostname : string ; port : number } ) => {
8+ export const sandbox = async ( { hostname, port } : { hostname : string ; port : number } ) => {
109 const app = express ( ) ;
1110
1211 app . use ( cors ( ) ) ;
1312 app . disable ( 'x-powered-by' ) ;
1413
1514 const sandboxDir = path . resolve ( dirname , 'sandbox' ) ;
16- let sandboxVersionDir = path . resolve ( sandboxDir , sandboxVersion ) ;
17- fs . readdirSync ( sandboxDir ) . forEach ( ( v ) => {
18- if ( fs . statSync ( path . resolve ( sandboxDir , v ) ) . isDirectory ( ) ) {
19- sandboxVersionDir = path . resolve ( sandboxDir , v ) ;
20- }
21- } ) ;
15+ const dirs = await fs . promises . readdir ( sandboxDir ) ;
16+ const version =
17+ dirs
18+ . filter ( ( v ) => v . startsWith ( 'v' ) )
19+ . map ( ( v ) => Number ( v . slice ( 1 ) ) )
20+ . filter ( ( v ) => ! Number . isNaN ( v ) )
21+ . sort ( ( a , b ) => b - a )
22+ . map ( ( v ) => 'v' + v )
23+ . pop ( ) || '' ;
24+ const sandboxVersionDir = path . resolve ( sandboxDir , version ) ;
2225
2326 app . use ( '/' , ( req , res ) => {
2427 if ( req . path === '/' ) {
2528 res . set ( 'Content-Type' , 'text/html' ) ;
2629 res . status ( 200 ) . sendFile ( path . resolve ( sandboxVersionDir , 'index.html' ) ) ;
2730 return ;
2831 }
29- const reqPath = req . path . endsWith ( '/' )
32+ let reqPath = req . path . endsWith ( '/' )
3033 ? req . path + 'index.html'
3134 : ! req . path . split ( '/' ) . pop ( ) ?. includes ( '.' )
3235 ? req . path + '.html'
3336 : req . path ;
34- res . set ( 'Content-Type' , 'text/html' ) ;
35- const filePath = path . resolve ( dirname , 'sandbox' + reqPath ) ;
36- if ( fs . existsSync ( filePath ) ) {
37- res . status ( 200 ) . sendFile ( filePath ) ;
38- return ;
37+ if ( reqPath . startsWith ( '/' ) ) {
38+ reqPath = reqPath . slice ( 1 ) ;
3939 }
40- res . status ( 404 ) . sendFile ( path . resolve ( sandboxVersionDir , 'index.html' ) ) ;
40+ const filePath = path . resolve ( sandboxDir , reqPath ) ;
41+ const onError = ( _err : unknown ) => {
42+ if ( res . headersSent ) return ;
43+ res . status ( 404 ) . sendFile ( path . resolve ( sandboxVersionDir , 'index.html' ) ) ;
44+ } ;
45+ res . set ( 'Content-Type' , 'text/html' ) ;
46+ res . status ( 200 ) . sendFile ( filePath , onError ) ;
4147 } ) ;
4248
4349 app . listen ( port , ( ) => {
0 commit comments