@@ -1029,11 +1029,39 @@ func esmRouter(db Database, esmStorage storage.Storage, logger *log.Logger) rex.
10291029 } else {
10301030 // return wasm file as an es6 module when `?module` query is present (requires `top-level-await` support)
10311031 if pathKind == RawFile && strings .HasSuffix (esm .SubPath , ".wasm" ) && query .Has ("module" ) {
1032- buf := & bytes.Buffer {}
10331032 wasmUrl := origin + pathname
1034- fmt .Fprintf (buf , "/* esm.sh - wasm module */\n " )
1035- fmt .Fprintf (buf , "const data = await fetch(%s).then(r => r.arrayBuffer());\n export default new WebAssembly.Module(data);" , strings .TrimSpace (string (utils .MustEncodeJSON (wasmUrl ))))
1033+ buf := bytes .NewBufferString ("/* esm.sh - wasm module */\n " )
1034+ buf .WriteString ("const data = await fetch(" )
1035+ buf .WriteString (strings .TrimSpace (string (utils .MustEncodeJSON (wasmUrl ))))
1036+ buf .WriteString (").then(r => r.arrayBuffer());\n " )
1037+ buf .WriteString ("export default new WebAssembly.Module(data);" )
10361038 ctx .SetHeader ("Content-Type" , ctJavaScript )
1039+ ctx .SetHeader ("Content-Length" , fmt .Sprintf ("%d" , buf .Len ()))
1040+ ctx .SetHeader ("Cache-Control" , ccImmutable )
1041+ return buf
1042+ }
1043+
1044+ // return css file as a `CSSStyleSheet` object when `?module` query is present
1045+ if pathKind == RawFile && strings .HasSuffix (esm .SubPath , ".css" ) && query .Has ("module" ) {
1046+ filename := path .Join (npmrc .StoreDir (), esm .Name (), "node_modules" , esm .PkgName , esm .SubPath )
1047+ css , err := os .ReadFile (filename )
1048+ if err != nil {
1049+ return rex .Status (500 , err .Error ())
1050+ }
1051+ buf := bytes .NewBufferString ("/* esm.sh - css module */\n " )
1052+ buf .WriteString ("const stylesheet = new CSSStyleSheet();\n " )
1053+ if bytes .ContainsRune (css , '`' ) {
1054+ buf .WriteString ("stylesheet.replaceSync(`" )
1055+ buf .WriteString (strings .TrimSpace (string (utils .MustEncodeJSON (string (css )))))
1056+ buf .WriteString (");\n " )
1057+ } else {
1058+ buf .WriteString ("stylesheet.replaceSync(`" )
1059+ buf .Write (css )
1060+ buf .WriteString ("`);\n " )
1061+ }
1062+ buf .WriteString ("export default stylesheet;\n " )
1063+ ctx .SetHeader ("Content-Type" , ctJavaScript )
1064+ ctx .SetHeader ("Content-Length" , fmt .Sprintf ("%d" , buf .Len ()))
10371065 ctx .SetHeader ("Cache-Control" , ccImmutable )
10381066 return buf
10391067 }
0 commit comments