-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathindex.js
307 lines (246 loc) · 8.28 KB
/
index.js
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
import { WebContainer } from '@webcontainer/api';
import base64 from 'base64-js';
import AnsiToHtml from 'ansi-to-html';
import * as yootils from 'yootils';
import { escape_html, get_depth } from '../../../utils.js';
import { ready } from '../common/index.js';
const converter = new AnsiToHtml({
fg: 'var(--sk-text-3)'
});
/** @type {import('@webcontainer/api').WebContainer} Web container singleton */
let vm;
/**
* @param {import('svelte/store').Writable<string | null>} base
* @param {import('svelte/store').Writable<Error | null>} error
* @param {import('svelte/store').Writable<{ value: number, text: string }>} progress
* @param {import('svelte/store').Writable<string[]>} logs
* @returns {Promise<import('$lib/types').Adapter>}
*/
export async function create(base, error, progress, logs) {
if (/safari/i.test(navigator.userAgent) && !/chrome/i.test(navigator.userAgent)) {
throw new Error('WebContainers are not supported by Safari');
}
progress.set({ value: 0, text: 'loading files' });
const q = yootils.queue(1);
/** Paths and contents of the currently loaded file stubs */
let current_stubs = stubs_to_map([]);
progress.set({ value: 1 / 5, text: 'booting webcontainer' });
vm = await WebContainer.boot();
progress.set({ value: 2 / 5, text: 'writing virtual files' });
const common = await ready;
await vm.mount({
'common.zip': {
file: { contents: new Uint8Array(common.zipped) }
},
'unzip.cjs': {
file: { contents: common.unzip }
}
});
const log_stream = () =>
new WritableStream({
write(chunk) {
if (chunk === '\x1B[1;1H') {
// clear screen
logs.set([]);
} else {
const log = converter.toHtml(escape_html(chunk)).replace(/\n/g, '<br>');
logs.update(($logs) => [...$logs, log]);
}
}
});
progress.set({ value: 3 / 5, text: 'unzipping files' });
const unzip = await vm.spawn('node', ['unzip.cjs']);
unzip.output.pipeTo(log_stream());
const code = await unzip.exit;
if (code !== 0) {
throw new Error('Failed to initialize WebContainer');
}
await vm.spawn('chmod', ['a+x', 'node_modules/vite/bin/vite.js']);
vm.on('server-ready', (_port, url) => {
base.set(url);
});
vm.on('error', ({ message }) => {
error.set(new Error(message));
});
let launched = false;
async function launch() {
if (launched) return;
launched = true;
progress.set({ value: 4 / 5, text: 'starting dev server' });
await new Promise(async (fulfil, reject) => {
const error_unsub = vm.on('error', (error) => {
error_unsub();
reject(new Error(error.message));
});
const ready_unsub = vm.on('server-ready', (_port, base) => {
ready_unsub();
progress.set({ value: 5 / 5, text: 'ready' });
fulfil(base); // this will be the last thing that happens if everything goes well
});
await run_dev();
async function run_dev() {
const process = await vm.spawn('turbo', ['run', 'dev']);
// TODO differentiate between stdout and stderr (sets `vite_error` to `true`)
// https://github.com/stackblitz/webcontainer-core/issues/971
process.output.pipeTo(log_stream());
// keep restarting dev server (can crash in case of illegal +files for example)
await process.exit;
run_dev();
}
});
}
return {
reset: (stubs) => {
return q.add(async () => {
/** @type {import('$lib/types').Stub[]} */
const to_write = [];
const force_delete = [];
let include_server_files = false;
for (const stub of stubs) {
if (stub.name.endsWith('/__delete')) {
force_delete.push(stub.name.slice(0, -9));
} else if (stub.type === 'file') {
if (stub.contents.startsWith('__delete')) {
force_delete.push(stub.name);
continue;
}
const current = /** @type {import('$lib/types').FileStub} */ (
current_stubs.get(stub.name)
);
if (current?.contents !== stub.contents) {
to_write.push(stub);
if (!include_server_files || stub.basename.endsWith('server.js')) {
include_server_files = true;
}
}
} else {
// always add directories, otherwise convert_stubs_to_tree will fail
to_write.push(stub);
}
current_stubs.delete(stub.name);
}
// Don't delete the node_modules folder when switching from one exercise to another
// where, as this crashes the dev server.
const to_delete = [
...Array.from(current_stubs.keys()).filter(
(s) => !s.startsWith('/node_modules')
),
...force_delete
];
current_stubs = stubs_to_map(stubs);
// For some reason, server-ready is fired again when the vite dev server is restarted.
// We need to wait for it to finish before we can continue, else we might
// request files from Vite before it's ready, leading to a timeout.
const will_restart = launched && to_write.some(will_restart_vite_dev_server);
const promise = will_restart
? new Promise((fulfil, reject) => {
const error_unsub = vm.on('error', (error) => {
error_unsub();
reject(new Error(error.message));
});
const ready_unsub = vm.on('server-ready', (port, base) => {
ready_unsub();
console.log(`server ready on port ${port} at ${performance.now()}: ${base}`);
fulfil(undefined);
});
setTimeout(() => {
reject(new Error('Timed out resetting WebContainer'));
}, 10000);
})
: Promise.resolve();
for (const file of to_delete) {
await vm.fs.rm(file, { force: true, recursive: true });
}
await vm.mount(convert_stubs_to_tree(to_write));
await promise;
await new Promise((f) => setTimeout(f, 200)); // wait for chokidar
// Also trigger a reload of the iframe in case new files were added / old ones deleted,
// because that can result in a broken UI state
const should_reload = !launched || will_restart || to_delete.length > 0 || include_server_files;
await launch();
return should_reload;
});
},
update: (file) => {
return q.add(async () => {
/** @type {import('@webcontainer/api').FileSystemTree} */
const root = {};
let tree = root;
const path = file.name.split('/').slice(1);
const basename = /** @type {string} */ (path.pop());
for (const part of path) {
if (!tree[part]) {
/** @type {import('@webcontainer/api').FileSystemTree} */
const directory = {};
tree[part] = {
directory
};
}
tree = /** @type {import('@webcontainer/api').DirectoryNode} */ (tree[part]).directory;
}
tree[basename] = to_file(file);
await vm.mount(root);
current_stubs.set(file.name, file);
// we need to stagger sequential updates, just enough that the HMR
// wires don't get crossed. 50ms seems to be enough of a delay
// to avoid glitches without noticeably affecting update speed
await new Promise((f) => setTimeout(f, 50));
return will_restart_vite_dev_server(file);
});
}
};
}
/**
* @param {import('$lib/types').Stub} file
*/
function will_restart_vite_dev_server(file) {
return (
file.type === 'file' &&
(file.name === '/vite.config.js' || file.name === '/svelte.config.js' || file.name === '/.env')
);
}
/**
* @param {import('$lib/types').Stub[]} stubs
* @returns {import('@webcontainer/api').FileSystemTree}
*/
function convert_stubs_to_tree(stubs, depth = 1) {
/** @type {import('@webcontainer/api').FileSystemTree} */
const tree = {};
for (const stub of stubs) {
if (get_depth(stub.name) === depth) {
if (stub.type === 'directory') {
const children = stubs.filter((child) => child.name.startsWith(stub.name));
tree[stub.basename] = {
directory: convert_stubs_to_tree(children, depth + 1)
};
} else {
tree[stub.basename] = to_file(stub);
}
}
}
return tree;
}
/** @param {import('$lib/types').FileStub} file */
function to_file(file) {
// special case
if (file.name === '/src/app.html' || file.name === '/src/error.html') {
const contents = file.contents + '<script type="module" src="/src/__client.js"></script>';
return {
file: { contents }
};
}
const contents = file.text ? file.contents : base64.toByteArray(file.contents);
return {
file: { contents }
};
}
/**
* @param {import('$lib/types').Stub[]} files
* @returns {Map<string, import('$lib/types').Stub>}
*/
function stubs_to_map(files, map = new Map()) {
for (const file of files) {
map.set(file.name, file);
}
return map;
}