-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathwebcontainer.ts
More file actions
82 lines (65 loc) · 1.94 KB
/
webcontainer.ts
File metadata and controls
82 lines (65 loc) · 1.94 KB
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
import { WebContainer as WebContainerApi } from "@webcontainer/api";
import { FileSystem } from "./file-system";
import { ProcessWrap } from "./process";
export class WebContainer extends FileSystem {
/** @internal */
private _instancePromise?: WebContainerApi;
/** @internal */
private _isReady: Promise<void>;
/** @internal */
private _onExit: (() => Promise<unknown>)[] = [];
constructor() {
super();
this._isReady = new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error("WebContainer boot timed out in 30s"));
}, 30_000);
WebContainerApi.boot({}).then((instance) => {
clearTimeout(timeout);
this._instancePromise = instance;
resolve();
});
});
}
/** @internal */
protected get _instance(): WebContainerApi {
if (!this._instancePromise) {
throw new Error(
"Webcontainer is not yet ready, make sure to call wait() after creation",
);
}
return this._instancePromise;
}
/** @internal */
async wait() {
await this._isReady;
}
/** @internal */
onServerReady(callback: (options: { port: number; url: string }) => void) {
this._instance.on("server-ready", (port, url) => {
callback({ port, url });
});
}
/** @internal */
async teardown() {
await Promise.all(this._onExit.map((fn) => fn()));
// @ts-ignore -- internal
await this._instance._instance.teardown();
this._instance.teardown();
this._instancePromise = undefined;
}
/**
* Run command inside WebContainer.
* See [`runCommand` documentation](https://github.com/stackblitz/webcontainer-test#runcommand) for usage examples.
*/
runCommand(
command: string,
args: string[] = [],
): PromiseLike<string> & ProcessWrap {
const proc = new ProcessWrap(
this._instance.spawn(command, args, { output: true }),
);
this._onExit.push(() => proc.exit());
return proc;
}
}