File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import { extname , resolve } from 'node:path' ;
2+
3+ const port = Number ( process . env . PORT || 3000 ) ;
4+ const rootDir = resolve ( import . meta. dir , 'src' ) ;
5+
6+ function resolvePath ( pathname ) {
7+ const relativePath = pathname === '/' ? 'index.html' : pathname . slice ( 1 ) ;
8+ const targetPath = resolve ( rootDir , relativePath ) ;
9+
10+ if ( targetPath !== rootDir && ! targetPath . startsWith ( `${ rootDir } /` ) ) {
11+ return null ;
12+ }
13+
14+ return targetPath ;
15+ }
16+
17+ const server = Bun . serve ( {
18+ port,
19+ development : true ,
20+ async fetch ( req ) {
21+ const url = new URL ( req . url ) ;
22+ const pathname = decodeURIComponent ( url . pathname ) ;
23+ const targetPath = resolvePath ( pathname ) ;
24+
25+ if ( ! targetPath ) {
26+ return new Response ( 'Not found' , { status : 404 } ) ;
27+ }
28+
29+ const file = Bun . file ( targetPath ) ;
30+
31+ if ( await file . exists ( ) ) {
32+ return new Response ( file ) ;
33+ }
34+
35+ if ( ! extname ( pathname ) ) {
36+ const fallback = Bun . file ( resolve ( rootDir , 'index.html' ) ) ;
37+ return new Response ( fallback ) ;
38+ }
39+
40+ return new Response ( 'Not found' , { status : 404 } ) ;
41+ }
42+ } ) ;
43+
44+ console . log ( `Dev server running at http://localhost:${ server . port } ` ) ;
Original file line number Diff line number Diff line change @@ -6,6 +6,10 @@ export default [
66 ecmaVersion : 2022 ,
77 sourceType : 'module' ,
88 globals : {
9+ Bun : 'readonly' ,
10+ URL : 'readonly' ,
11+ Response : 'readonly' ,
12+ process : 'readonly' ,
913 window : 'readonly' ,
1014 document : 'readonly' ,
1115 console : 'readonly' ,
Original file line number Diff line number Diff line change 55 "type" : " module" ,
66 "packageManager" : " bun@1.2.22" ,
77 "scripts" : {
8+ "dev" : " bun run dev-server.js" ,
89 "lint" : " bun run lint:js && bun run lint:css && bun run lint:html" ,
9- "lint:js" : " eslint \" src/js/**/*.js\" \" src/microblogs/**/*.js\" " ,
10+ "lint:js" : " eslint dev-server.js \" src/js/**/*.js\" \" src/microblogs/**/*.js\" " ,
1011 "lint:css" : " stylelint \" src/styles/**/*.css\" " ,
1112 "lint:html" : " htmlhint src/index.html" ,
12- "lint:fix" : " eslint \" src/js/**/*.js\" \" src/microblogs/**/*.js\" --fix && stylelint \" src/styles/**/*.css\" --fix" ,
13+ "lint:fix" : " eslint dev-server.js \" src/js/**/*.js\" \" src/microblogs/**/*.js\" --fix && stylelint \" src/styles/**/*.css\" --fix" ,
1314 "prepare" : " husky"
1415 },
1516 "lint-staged" : {
You can’t perform that action at this time.
0 commit comments