-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathastro-wasm.go
343 lines (293 loc) · 9.36 KB
/
astro-wasm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//go:build js && wasm
// +build js,wasm
package main
import (
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"sync"
"syscall/js"
"github.com/norunners/vert"
astro "github.com/withastro/compiler/internal"
"github.com/withastro/compiler/internal/printer"
t "github.com/withastro/compiler/internal/t"
"github.com/withastro/compiler/internal/transform"
wasm_utils "github.com/withastro/compiler/internal_wasm/utils"
)
var done chan bool
func main() {
js.Global().Set("@astrojs/compiler", js.ValueOf(make(map[string]interface{})))
module := js.Global().Get("@astrojs/compiler")
module.Set("transform", Transform())
module.Set("parse", Parse())
module.Set("convertToTSX", ConvertToTSX())
<-make(chan struct{})
}
func jsString(j js.Value) string {
if j.Equal(js.Undefined()) || j.Equal(js.Null()) {
return ""
}
return j.String()
}
func jsBool(j js.Value) bool {
if j.Equal(js.Undefined()) || j.Equal(js.Null()) {
return false
}
return j.Bool()
}
func makeParseOptions(options js.Value) t.ParseOptions {
position := true
pos := options.Get("position")
if !pos.IsNull() && !pos.IsUndefined() {
position = pos.Bool()
}
return t.ParseOptions{
Position: position,
}
}
func makeTransformOptions(options js.Value, hash string) transform.TransformOptions {
filename := jsString(options.Get("sourcefile"))
if filename == "" {
filename = "<stdin>"
}
pathname := jsString(options.Get("pathname"))
if pathname == "" {
pathname = "<stdin>"
}
internalURL := jsString(options.Get("internalURL"))
if internalURL == "" {
internalURL = "astro/internal"
}
sourcemap := jsString(options.Get("sourcemap"))
if sourcemap == "<boolean: true>" {
sourcemap = "both"
}
site := jsString(options.Get("site"))
if site == "" {
site = "https://astro.build"
}
projectRoot := jsString(options.Get("projectRoot"))
if projectRoot == "" {
projectRoot = "."
}
staticExtraction := false
if jsBool(options.Get("experimentalStaticExtraction")) {
staticExtraction = true
}
preprocessStyle := options.Get("preprocessStyle")
return transform.TransformOptions{
Scope: hash,
Filename: filename,
Pathname: pathname,
InternalURL: internalURL,
SourceMap: sourcemap,
Site: site,
ProjectRoot: projectRoot,
PreprocessStyle: preprocessStyle,
StaticExtraction: staticExtraction,
}
}
type RawSourceMap struct {
File string `js:"file"`
Mappings string `js:"mappings"`
Names []string `js:"names"`
Sources []string `js:"sources"`
SourcesContent []string `js:"sourcesContent"`
Version int `js:"version"`
}
type HoistedScript struct {
Code string `js:"code"`
Src string `js:"src"`
Type string `js:"type"`
}
type ParseResult struct {
AST string `js:"ast"`
}
type TSXResult struct {
Code string `js:"code"`
Map string `js:"map"`
}
type TransformResult struct {
Code string `js:"code"`
Map string `js:"map"`
CSS []string `js:"css"`
Scripts []HoistedScript `js:"scripts"`
}
// This is spawned as a goroutine to preprocess style nodes using an async function passed from JS
func preprocessStyle(i int, style *astro.Node, transformOptions transform.TransformOptions, cb func()) {
defer cb()
if style.FirstChild == nil {
return
}
attrs := wasm_utils.GetAttrs(style)
data, _ := wasm_utils.Await(transformOptions.PreprocessStyle.(js.Value).Invoke(style.FirstChild.Data, attrs))
// note: Rollup (and by extension our Astro Vite plugin) allows for "undefined" and "null" responses if a transform wishes to skip this occurrence
if data[0].Equal(js.Undefined()) || data[0].Equal(js.Null()) {
return
}
str := jsString(data[0].Get("code"))
if str == "" {
return
}
style.FirstChild.Data = str
}
func Parse() interface{} {
return js.FuncOf(func(this js.Value, args []js.Value) interface{} {
source := jsString(args[0])
parseOptions := makeParseOptions(js.Value(args[1]))
var doc *astro.Node
doc, err := astro.Parse(strings.NewReader(source))
if err != nil {
fmt.Println(err)
}
result := printer.PrintToJSON(source, doc, parseOptions)
return vert.ValueOf(ParseResult{
AST: string(result.Output),
})
})
}
func ConvertToTSX() interface{} {
return js.FuncOf(func(this js.Value, args []js.Value) interface{} {
source := jsString(args[0])
transformOptions := makeTransformOptions(js.Value(args[1]), "XXXXXX")
var doc *astro.Node
doc, err := astro.Parse(strings.NewReader(source))
if err != nil {
fmt.Println(err)
}
result := printer.PrintToTSX(source, doc, transformOptions)
return vert.ValueOf(TSXResult{
Code: string(result.Output),
Map: createSourceMapString(source, result, transformOptions),
})
})
}
func Transform() interface{} {
return js.FuncOf(func(this js.Value, args []js.Value) interface{} {
source := jsString(args[0])
hash := astro.HashFromSource(source)
transformOptions := makeTransformOptions(js.Value(args[1]), hash)
handler := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
resolve := args[0]
go func() {
var doc *astro.Node
doc, err := astro.Parse(strings.NewReader(source))
if err != nil {
fmt.Println(err)
}
// Hoist styles and scripts to the top-level
transform.ExtractStyles(doc)
// Pre-process styles
// Important! These goroutines need to be spawned from this file or they don't work
var wg sync.WaitGroup
if len(doc.Styles) > 0 {
if transformOptions.PreprocessStyle.(js.Value).Type() == js.TypeFunction {
for i, style := range doc.Styles {
wg.Add(1)
i := i
go preprocessStyle(i, style, transformOptions, wg.Done)
}
}
}
// Wait for all the style goroutines to finish
wg.Wait()
// Perform CSS and element scoping as needed
transform.Transform(doc, transformOptions)
css := []string{}
scripts := []HoistedScript{}
// Only perform static CSS extraction if the flag is passed in.
if transformOptions.StaticExtraction {
css_result := printer.PrintCSS(source, doc, transformOptions)
for _, bytes := range css_result.Output {
css = append(css, string(bytes))
}
// Append hoisted scripts
for _, node := range doc.Scripts {
src := astro.GetAttribute(node, "src")
script := HoistedScript{
Src: "",
Code: "",
Type: "",
}
if src != nil {
script.Type = "external"
script.Src = src.Val
} else if node.FirstChild != nil {
script.Type = "inline"
script.Code = node.FirstChild.Data
}
scripts = append(scripts, script)
}
}
result := printer.PrintToJS(source, doc, len(css), transformOptions)
var value interface{}
switch transformOptions.SourceMap {
case "external":
value = createExternalSourceMap(source, result, css, &scripts, transformOptions)
case "both":
value = createBothSourceMap(source, result, css, &scripts, transformOptions)
case "inline":
value = createInlineSourceMap(source, result, css, &scripts, transformOptions)
default:
value = vert.ValueOf(TransformResult{
CSS: css,
Code: string(result.Output),
Map: "",
Scripts: scripts,
})
}
resolve.Invoke(value)
}()
return nil
})
defer handler.Release()
// Create and return the Promise object
promiseConstructor := js.Global().Get("Promise")
return promiseConstructor.New(handler)
})
}
func createSourceMapString(source string, result printer.PrintResult, transformOptions transform.TransformOptions) string {
sourcesContent, _ := json.Marshal(source)
sourcemap := RawSourceMap{
Version: 3,
Sources: []string{transformOptions.Filename},
SourcesContent: []string{string(sourcesContent)},
Mappings: string(result.SourceMapChunk.Buffer),
}
return fmt.Sprintf(`{
"version": 3,
"sources": ["%s"],
"sourcesContent": [%s],
"mappings": "%s",
"names": []
}`, sourcemap.Sources[0], sourcemap.SourcesContent[0], sourcemap.Mappings)
}
func createExternalSourceMap(source string, result printer.PrintResult, css []string, scripts *[]HoistedScript, transformOptions transform.TransformOptions) interface{} {
return vert.ValueOf(TransformResult{
CSS: css,
Code: string(result.Output),
Map: createSourceMapString(source, result, transformOptions),
Scripts: *scripts,
})
}
func createInlineSourceMap(source string, result printer.PrintResult, css []string, scripts *[]HoistedScript, transformOptions transform.TransformOptions) interface{} {
sourcemapString := createSourceMapString(source, result, transformOptions)
inlineSourcemap := `//# sourceMappingURL=data:application/json;charset=utf-8;base64,` + base64.StdEncoding.EncodeToString([]byte(sourcemapString))
return vert.ValueOf(TransformResult{
CSS: css,
Code: string(result.Output) + "\n" + inlineSourcemap,
Map: "",
Scripts: *scripts,
})
}
func createBothSourceMap(source string, result printer.PrintResult, css []string, scripts *[]HoistedScript, transformOptions transform.TransformOptions) interface{} {
sourcemapString := createSourceMapString(source, result, transformOptions)
inlineSourcemap := `//# sourceMappingURL=data:application/json;charset=utf-8;base64,` + base64.StdEncoding.EncodeToString([]byte(sourcemapString))
return vert.ValueOf(TransformResult{
CSS: css,
Code: string(result.Output) + "\n" + inlineSourcemap,
Map: sourcemapString,
Scripts: *scripts,
})
}