openwebcontainer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,124 @@
1
+ // Type definitions for OpenWebContainer (API-compatible with the core of @webcontainer/api).
2
+
3
+ export type Unsubscribe = () => void;
4
+
5
+ export interface FileSystemTree {
6
+ [name: string]: DirectoryNode | FileNode | SymlinkNode;
7
+ }
8
+ export interface DirectoryNode {
9
+ directory: FileSystemTree;
10
+ }
11
+ export interface FileNode {
12
+ file: { contents: string | Uint8Array };
13
+ }
14
+ export interface SymlinkNode {
15
+ file: { symlink: string };
16
+ }
17
+
18
+ export interface BootOptions {
19
+ /** Name of the working directory, mounted at `/home/<workdirName>` (default `project`). */
20
+ workdirName?: string;
21
+ coep?: 'require-corp' | 'credentialless' | 'none';
22
+ /**
23
+ * Base URL of an owc-proxy deployment (e.g. `'/__owc'` or `'https://proxy.example.workers.dev/__owc'`).
24
+ * Used for outbound HTTP(S) from processes, raw TCP (relay) and the npm registry mirror.
25
+ * `undefined` = auto-detect `/__owc/health` on the page origin; `null` = no proxy.
26
+ */
27
+ proxyUrl?: string | null;
28
+ /** npm registry URL (default: `${proxyUrl}/npm` or https://registry.npmjs.org). */
29
+ npmRegistry?: string;
30
+ /** Allow raw TCP through the proxy relay (default true). */
31
+ relay?: boolean;
32
+ /** Extra environment variables for every process. */
33
+ env?: Record<string, string>;
34
+ serviceWorkerUrl?: string;
35
+ serviceWorkerScope?: string;
36
+ runtimeUrl?: string;
37
+ wasmUrl?: string;
38
+ }
39
+
40
+ export interface SpawnOptions {
41
+ cwd?: string;
42
+ env?: Record<string, string | number | boolean>;
43
+ /** Set to false to discard output. */
44
+ output?: boolean;
45
+ /** Attach a pseudo terminal of the given size (enables interactive shells, raw mode, colors). */
46
+ terminal?: { cols: number; rows: number };
47
+ }
48
+
49
+ export interface WebContainerProcess {
50
+ readonly pid: number;
51
+ /** Combined stdout/stderr (or terminal output) as decoded text. */
52
+ readonly output: ReadableStream<string>;
53
+ /** Process stdin (or keyboard input when a terminal is attached). */
54
+ readonly input: WritableStream<string | Uint8Array>;
55
+ /** Resolves with the exit code. */
56
+ readonly exit: Promise<number>;
57
+ kill(signal?: string): void;
58
+ resize(dimensions: { cols: number; rows: number }): void;
59
+ }
60
+
61
+ export interface DirEnt<T> {
62
+ name: T;
63
+ isFile(): boolean;
64
+ isDirectory(): boolean;
65
+ isSymbolicLink(): boolean;
66
+ }
67
+
68
+ export interface IFSWatcher {
69
+ close(): void;
70
+ }
71
+
72
+ export interface FileSystemAPI {
73
+ readdir(path: string, options: 'buffer' | { encoding: 'buffer'; withFileTypes?: false }): Promise<Uint8Array[]>;
74
+ readdir(path: string, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise<string[]>;
75
+ readdir(path: string, options: { encoding: 'buffer'; withFileTypes: true }): Promise<DirEnt<Uint8Array>[]>;
76
+ readdir(path: string, options: { encoding?: string | null; withFileTypes: true }): Promise<DirEnt<string>[]>;
77
+ readFile(path: string, encoding?: null): Promise<Uint8Array>;
78
+ readFile(path: string, encoding: string): Promise<string>;
79
+ writeFile(path: string, data: string | Uint8Array, options?: string | { encoding?: string | null } | null): Promise<void>;
80
+ mkdir(path: string, options?: { recursive?: false }): Promise<void>;
81
+ mkdir(path: string, options: { recursive: true }): Promise<string | undefined>;
82
+ rm(path: string, options?: { force?: boolean; recursive?: boolean }): Promise<void>;
83
+ rename(oldPath: string, newPath: string): Promise<void>;
84
+ watch(path: string, options?: { encoding?: string | null; recursive?: boolean } | null, listener?: (event: 'rename' | 'change', filename: string) => void): IFSWatcher;
85
+ watch(path: string, listener?: (event: 'rename' | 'change', filename: string) => void): IFSWatcher;
86
+ /** OpenWebContainer extension. */
87
+ stat(path: string): Promise<{ size: number; mode: number; mtimeMs: number; type: 'file' | 'dir' | 'symlink'; isFile(): boolean; isDirectory(): boolean; isSymbolicLink(): boolean }>;
88
+ /** OpenWebContainer extension. */
89
+ exists(path: string): Promise<boolean>;
90
+ }
91
+
92
+ export type PortListener = (port: number, type: 'open' | 'close', url: string) => void;
93
+ export type ServerReadyListener = (port: number, url: string) => void;
94
+ export type ErrorListener = (error: { message: string }) => void;
95
+ export type OpenListener = (text: string) => void;
96
+
97
+ export interface ExportOptions {
98
+ format?: 'json' | 'binary';
99
+ excludes?: string[];
100
+ }
101
+
102
+ export declare class WebContainer {
103
+ static boot(options?: BootOptions): Promise<WebContainer>;
104
+ readonly fs: FileSystemAPI;
105
+ readonly workdir: string;
106
+ readonly path: string;
107
+ spawn(command: string, args: string[], options?: SpawnOptions): Promise<WebContainerProcess>;
108
+ spawn(command: string, options?: SpawnOptions): Promise<WebContainerProcess>;
109
+ mount(snapshotOrTree: FileSystemTree | Uint8Array | ArrayBuffer, options?: { mountPoint?: string }): Promise<void>;
110
+ export(path: string, options?: ExportOptions & { format?: 'json' }): Promise<FileSystemTree>;
111
+ export(path: string, options: ExportOptions & { format: 'binary' }): Promise<Uint8Array>;
112
+ on(event: 'port', listener: PortListener): Unsubscribe;
113
+ on(event: 'server-ready', listener: ServerReadyListener): Unsubscribe;
114
+ on(event: 'error', listener: ErrorListener): Unsubscribe;
115
+ on(event: 'xdg-open', listener: OpenListener): Unsubscribe;
116
+ setPreviewScript(scriptSrc: string, options?: { type?: 'module' | 'importmap'; defer?: boolean; async?: boolean }): Promise<void>;
117
+ /** OpenWebContainer extension: preview URL for a port. */
118
+ previewUrl(port: number): string;
119
+ /** OpenWebContainer extension: debugging info. */
120
+ stats(): { bytes: number; inodes: number; processes: Array<{ pid: number; ppid: number; argv: string[]; cwd: string; kind: 'worker' | 'native' }>; proxy: string | null };
121
+ teardown(): void;
122
+ }
123
+
124
+ export default WebContainer;
@@ -0,0 +1,18 @@
1
+ var ie=Object.defineProperty;var c=(i,e)=>ie(i,"name",{value:e,configurable:!0});var D=class i{static{c(this,"Hasher")}static __wrap(e){let t=Object.create(i.prototype);return t.__wbg_ptr=e,P.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,P.unregister(this),e}free(){let e=this.__destroy_into_raw();s.__wbg_hasher_free(e,0)}copy(){let e=s.hasher_copy(this.__wbg_ptr);return i.__wrap(e)}digest(){let e=s.hasher_digest(this.__wbg_ptr);var t=S(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),t}constructor(e){let t=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),n=w,r=s.hasher_new(t,n);if(r[2])throw p(r[1]);return this.__wbg_ptr=r[0],P.register(this,this.__wbg_ptr,this),this}update(e){let t=v(e,s.__wbindgen_malloc),n=w;s.hasher_update(this.__wbg_ptr,t,n)}};Symbol.dispose&&(D.prototype[Symbol.dispose]=D.prototype.free);var F=class{static{c(this,"Hmac")}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,H.unregister(this),e}free(){let e=this.__destroy_into_raw();s.__wbg_hmac_free(e,0)}digest(){let e=s.hmac_digest(this.__wbg_ptr);var t=S(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),t}constructor(e,t){let n,r,o,_;try{n=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),r=w,o=v(t,s.__wbindgen_malloc),_=w}catch(l){throw o&&s.__wbindgen_free(o,_*1,1),n&&s.__wbindgen_free(n,r*1,1),l}let a=s.hmac_new(n,r,o,_);if(a[2])throw p(a[1]);return this.__wbg_ptr=a[0],H.register(this,this.__wbg_ptr,this),this}update(e){let t=v(e,s.__wbindgen_malloc),n=w;s.hmac_update(this.__wbg_ptr,t,n)}};Symbol.dispose&&(F.prototype[Symbol.dispose]=F.prototype.free);var U=class{static{c(this,"OwcKernel")}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,Y.unregister(this),e}free(){let e=this.__destroy_into_raw();s.__wbg_owckernel_free(e,0)}closeInput(e){s.owckernel_closeInput(this.__wbg_ptr,e)}exists(e){let t=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),n=w;return s.owckernel_exists(this.__wbg_ptr,t,n)!==0}exportSnapshot(e){let t=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),n=w,r=s.owckernel_exportSnapshot(this.__wbg_ptr,t,n);if(r[3])throw p(r[2]);var o=S(r[0],r[1]).slice();return s.__wbindgen_free(r[0],r[1]*1,1),o}exportTree(e,t){let n,r;try{let a,l,f,h;try{a=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),l=w,f=g(t,s.__wbindgen_malloc,s.__wbindgen_realloc),h=w}catch(b){throw f&&s.__wbindgen_free(f,h*1,1),a&&s.__wbindgen_free(a,l*1,1),b}let d=s.owckernel_exportTree(this.__wbg_ptr,a,l,f,h);var o=d[0],_=d[1];if(d[3])throw o=0,_=0,p(d[2]);return n=o,r=_,m(o,_)}finally{s.__wbindgen_free(n,r,1)}}httpAbort(e){s.owckernel_httpAbort(this.__wbg_ptr,e)}httpRequest(e,t,n,r,o,_){let a=+e,l=+t,f,h,d,b,u,y,A,J;try{f=g(n,s.__wbindgen_malloc,s.__wbindgen_realloc),h=w,d=g(r,s.__wbindgen_malloc,s.__wbindgen_realloc),b=w,u=g(o,s.__wbindgen_malloc,s.__wbindgen_realloc),y=w,A=v(_,s.__wbindgen_malloc),J=w}catch(se){throw A&&s.__wbindgen_free(A,J*1,1),u&&s.__wbindgen_free(u,y*1,1),d&&s.__wbindgen_free(d,b*1,1),f&&s.__wbindgen_free(f,h*1,1),se}s.owckernel_httpRequest(this.__wbg_ptr,a,l,f,h,d,b,u,y,A,J)}input(e,t){let n=+e,r=v(t,s.__wbindgen_malloc),o=w;s.owckernel_input(this.__wbg_ptr,n,r,o)}isAlive(e){return s.owckernel_isAlive(this.__wbg_ptr,e)!==0}isListening(e){return s.owckernel_isListening(this.__wbg_ptr,e)!==0}kill(e,t){let n=+e,r=g(t,s.__wbindgen_malloc,s.__wbindgen_realloc),o=w;return s.owckernel_kill(this.__wbg_ptr,n,r,o)!==0}message(e,t,n){let r=+e,o=+t,_=v(n,s.__wbindgen_malloc),a=w;s.owckernel_message(this.__wbg_ptr,r,o,_,a)}mkdir(e,t){let n=+t,r=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),o=w,_=s.owckernel_mkdir(this.__wbg_ptr,r,o,n);if(_[3])throw p(_[2]);let a;return _[0]!==0&&(a=m(_[0],_[1]),s.__wbindgen_free(_[0],_[1]*1,1)),a}mountSnapshot(e,t){let n,r,o,_;try{n=v(e,s.__wbindgen_malloc),r=w,o=k(t)?0:g(t,s.__wbindgen_malloc,s.__wbindgen_realloc),_=w}catch(l){throw o&&s.__wbindgen_free(o,_*1,1),n&&s.__wbindgen_free(n,r*1,1),l}let a=s.owckernel_mountSnapshot(this.__wbg_ptr,n,r,o,_);if(a[2])throw p(a[1]);return a[0]>>>0}mountTree(e,t){let n,r,o,_;try{n=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),r=w,o=k(t)?0:g(t,s.__wbindgen_malloc,s.__wbindgen_realloc),_=w}catch(l){throw o&&s.__wbindgen_free(o,_*1,1),n&&s.__wbindgen_free(n,r*1,1),l}let a=s.owckernel_mountTree(this.__wbg_ptr,n,r,o,_);if(a[2])throw p(a[1]);return a[0]>>>0}constructor(e,t){let n=g(t,s.__wbindgen_malloc,s.__wbindgen_realloc),r=w,o=s.owckernel_new(e,n,r);return this.__wbg_ptr=o,Y.register(this,this.__wbg_ptr,this),this}processes(){let e,t;try{let n=s.owckernel_processes(this.__wbg_ptr);return e=n[0],t=n[1],m(n[0],n[1])}finally{s.__wbindgen_free(e,t,1)}}rawClose(e){s.owckernel_rawClose(this.__wbg_ptr,e)}rawConnect(e){let t=s.owckernel_rawConnect(this.__wbg_ptr,e);if(t[2])throw p(t[1]);return t[0]>>>0}rawSend(e,t){let n=+e,r=v(t,s.__wbindgen_malloc),o=w;s.owckernel_rawSend(this.__wbg_ptr,n,r,o)}readFile(e){let t=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),n=w,r=s.owckernel_readFile(this.__wbg_ptr,t,n);if(r[3])throw p(r[2]);var o=S(r[0],r[1]).slice();return s.__wbindgen_free(r[0],r[1]*1,1),o}readdir(e){let t,n;try{let _=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),a=w,l=s.owckernel_readdir(this.__wbg_ptr,_,a);var r=l[0],o=l[1];if(l[3])throw r=0,o=0,p(l[2]);return t=r,n=o,m(r,o)}finally{s.__wbindgen_free(t,n,1)}}rename(e,t){let n,r,o,_;try{n=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),r=w,o=g(t,s.__wbindgen_malloc,s.__wbindgen_realloc),_=w}catch(l){throw o&&s.__wbindgen_free(o,_*1,1),n&&s.__wbindgen_free(n,r*1,1),l}let a=s.owckernel_rename(this.__wbg_ptr,n,r,o,_);if(a[1])throw p(a[0])}resize(e,t,n){s.owckernel_resize(this.__wbg_ptr,e,t,n)}rm(e,t,n){let r=+t,o=+n,_=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),a=w,l=s.owckernel_rm(this.__wbg_ptr,_,a,r,o);if(l[1])throw p(l[0])}serveModule(e,t,n,r){let o,_,a,l,f,h,d,b;try{o=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),_=w,a=g(t,s.__wbindgen_malloc,s.__wbindgen_realloc),l=w,f=g(n,s.__wbindgen_malloc,s.__wbindgen_realloc),h=w,d=g(r,s.__wbindgen_malloc,s.__wbindgen_realloc),b=w}catch(y){throw d&&s.__wbindgen_free(d,b*1,1),f&&s.__wbindgen_free(f,h*1,1),a&&s.__wbindgen_free(a,l*1,1),o&&s.__wbindgen_free(o,_*1,1),y}return s.owckernel_serveModule(this.__wbg_ptr,o,_,a,l,f,h,d,b)}setEnv(e,t){let n,r,o,_;try{n=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),r=w,o=g(t,s.__wbindgen_malloc,s.__wbindgen_realloc),_=w}catch(a){throw o&&s.__wbindgen_free(o,_*1,1),n&&s.__wbindgen_free(n,r*1,1),a}s.owckernel_setEnv(this.__wbg_ptr,n,r,o,_)}setRegistry(e,t,n){let r,o,_,a,l,f;try{r=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),o=w,_=k(t)?0:g(t,s.__wbindgen_malloc,s.__wbindgen_realloc),a=w,l=k(n)?0:g(n,s.__wbindgen_malloc,s.__wbindgen_realloc),f=w}catch(h){throw l&&s.__wbindgen_free(l,f*1,1),_&&s.__wbindgen_free(_,a*1,1),r&&s.__wbindgen_free(r,o*1,1),h}s.owckernel_setRegistry(this.__wbg_ptr,r,o,_,a,l,f)}spawn(e,t,n,r){let o=+r,_,a,l,f,h,d;try{_=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),a=w,l=g(t,s.__wbindgen_malloc,s.__wbindgen_realloc),f=w,h=g(n,s.__wbindgen_malloc,s.__wbindgen_realloc),d=w}catch(u){throw h&&s.__wbindgen_free(h,d*1,1),l&&s.__wbindgen_free(l,f*1,1),_&&s.__wbindgen_free(_,a*1,1),u}let b=s.owckernel_spawn(this.__wbg_ptr,_,a,l,f,h,d,o);if(b[2])throw p(b[1]);return b[0]>>>0}stat(e){let t,n;try{let _=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),a=w,l=s.owckernel_stat(this.__wbg_ptr,_,a);var r=l[0],o=l[1];if(l[3])throw r=0,o=0,p(l[2]);return t=r,n=o,m(r,o)}finally{s.__wbindgen_free(t,n,1)}}stats(){let e,t;try{let n=s.owckernel_stats(this.__wbg_ptr);return e=n[0],t=n[1],m(n[0],n[1])}finally{s.__wbindgen_free(e,t,1)}}syscall(e,t,n){let r=+e,o=+t,_=v(n,s.__wbindgen_malloc),a=w,l=s.owckernel_syscall(this.__wbg_ptr,r,o,_,a),f;return l[0]!==0&&(f=S(l[0],l[1]).slice(),s.__wbindgen_free(l[0],l[1]*1,1)),f}threadExited(e,t){s.owckernel_threadExited(this.__wbg_ptr,e,t)}unwatch(e){s.owckernel_unwatch(this.__wbg_ptr,e)}watch(e,t){let n=+t,r=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),o=w,_=s.owckernel_watch(this.__wbg_ptr,r,o,n);if(_[2])throw p(_[1]);return _[0]>>>0}workdir(){let e,t;try{let n=s.owckernel_workdir(this.__wbg_ptr);return e=n[0],t=n[1],m(n[0],n[1])}finally{s.__wbindgen_free(e,t,1)}}workerDied(e,t){s.owckernel_workerDied(this.__wbg_ptr,e,t)}writeFile(e,t,n){let r=+n,o,_,a,l;try{o=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),_=w,a=v(t,s.__wbindgen_malloc),l=w}catch(h){throw a&&s.__wbindgen_free(a,l*1,1),o&&s.__wbindgen_free(o,_*1,1),h}let f=s.owckernel_writeFile(this.__wbg_ptr,o,_,a,l,r);if(f[1])throw p(f[0])}};Symbol.dispose&&(U.prototype[Symbol.dispose]=U.prototype.free);var z=class{static{c(this,"ZStream")}__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,X.unregister(this),e}free(){let e=this.__destroy_into_raw();s.__wbg_zstream_free(e,0)}finish(){let e=s.zstream_finish(this.__wbg_ptr);if(e[3])throw p(e[2]);var t=S(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),t}flush(){let e=s.zstream_flush(this.__wbg_ptr);if(e[3])throw p(e[2]);var t=S(e[0],e[1]).slice();return s.__wbindgen_free(e[0],e[1]*1,1),t}constructor(e,t){let n=+t,r=g(e,s.__wbindgen_malloc,s.__wbindgen_realloc),o=w,_=s.zstream_new(r,o,n);if(_[2])throw p(_[1]);return this.__wbg_ptr=_[0],X.register(this,this.__wbg_ptr,this),this}push(e){let t=v(e,s.__wbindgen_malloc),n=w,r=s.zstream_push(this.__wbg_ptr,t,n);if(r[3])throw p(r[2]);var o=S(r[0],r[1]).slice();return s.__wbindgen_free(r[0],r[1]*1,1),o}};Symbol.dispose&&(z.prototype[Symbol.dispose]=z.prototype.free);function oe(){return{__proto__:null,"./owc_wasm_bg.js":{__proto__:null,__wbg___wbindgen_debug_string_f249a2a76caa9a55:c(function(e,t){let n=Q(t),r=g(n,s.__wbindgen_malloc,s.__wbindgen_realloc),o=w;x().setInt32((e>>>0)+4,o,!0),x().setInt32((e>>>0)+0,r,!0)},"__wbg___wbindgen_debug_string_f249a2a76caa9a55"),__wbg___wbindgen_is_function_741ff2bb612836f5:c(function(e){return typeof e=="function"},"__wbg___wbindgen_is_function_741ff2bb612836f5"),__wbg___wbindgen_is_undefined_be5b34249ff1fc15:c(function(e){return e===void 0},"__wbg___wbindgen_is_undefined_be5b34249ff1fc15"),__wbg___wbindgen_number_get_934b640d0889af78:c(function(e,t){let n=t,r=typeof n=="number"?n:void 0;x().setFloat64((e>>>0)+8,k(r)?0:r,!0),x().setInt32((e>>>0)+0,!k(r),!0)},"__wbg___wbindgen_number_get_934b640d0889af78"),__wbg___wbindgen_string_get_7ce8eee7fd327545:c(function(e,t){let n=t,r=typeof n=="string"?n:void 0;var o=k(r)?0:g(r,s.__wbindgen_malloc,s.__wbindgen_realloc),_=w;x().setInt32((e>>>0)+4,_,!0),x().setInt32((e>>>0)+0,o,!0)},"__wbg___wbindgen_string_get_7ce8eee7fd327545"),__wbg___wbindgen_throw_4c88d8bf264fd984:c(function(e,t){throw new Error(m(e,t))},"__wbg___wbindgen_throw_4c88d8bf264fd984"),__wbg__wbg_cb_unref_09736879a3f67559:c(function(e){e._wbg_cb_unref()},"__wbg__wbg_cb_unref_09736879a3f67559"),__wbg_apply_bfe2b07b146427e2:c(function(){return $(function(e,t,n){return e.apply(t,n)},arguments)},"__wbg_apply_bfe2b07b146427e2"),__wbg_call_a410eb4b59ed5965:c(function(){return $(function(e,t,n){return e.call(t,n)},arguments)},"__wbg_call_a410eb4b59ed5965"),__wbg_error_757e9472f8410341:c(function(e,t){let n,r;try{n=e,r=t,console.error(m(e,t))}finally{s.__wbindgen_free(n,r,1)}},"__wbg_error_757e9472f8410341"),__wbg_get_2080c49015e35254:c(function(){return $(function(e,t){return Reflect.get(e,t)},arguments)},"__wbg_get_2080c49015e35254"),__wbg_instanceof_Promise_59148c6049d0e3a0:c(function(e){let t;try{t=e instanceof Promise}catch{t=!1}return t},"__wbg_instanceof_Promise_59148c6049d0e3a0"),__wbg_length_186163212ffe79c3:c(function(e){return e.length},"__wbg_length_186163212ffe79c3"),__wbg_new_13de428334042d26:c(function(e){return new Uint8Array(e)},"__wbg_new_13de428334042d26"),__wbg_new_37eb45aaf5eeb820:c(function(){return new Array},"__wbg_new_37eb45aaf5eeb820"),__wbg_new_787b9fb330d55d78:c(function(e,t){return new Error(m(e,t))},"__wbg_new_787b9fb330d55d78"),__wbg_new_bb74001155cb8ca8:c(function(){return new Error},"__wbg_new_bb74001155cb8ca8"),__wbg_new_cd4348290afae586:c(function(){return new Object},"__wbg_new_cd4348290afae586"),__wbg_new_from_slice_b8daf545a41c6aa0:c(function(e,t){return new Uint8Array(S(e,t))},"__wbg_new_from_slice_b8daf545a41c6aa0"),__wbg_new_no_args_7dba612d766302e4:c(function(e,t){return new Function(m(e,t))},"__wbg_new_no_args_7dba612d766302e4"),__wbg_now_463ac581d2fc7ea3:c(function(){return Date.now()},"__wbg_now_463ac581d2fc7ea3"),__wbg_prototypesetcall_13162965d1fe7aa3:c(function(e,t,n){Uint8Array.prototype.set.call(S(e,t),n)},"__wbg_prototypesetcall_13162965d1fe7aa3"),__wbg_push_c9f4893fc209f768:c(function(e,t){return e.push(t)},"__wbg_push_c9f4893fc209f768"),__wbg_queueMicrotask_1e8503a8a690f0a3:c(function(e){return e.queueMicrotask},"__wbg_queueMicrotask_1e8503a8a690f0a3"),__wbg_queueMicrotask_4a1a4d8dd332373b:c(function(e){queueMicrotask(e)},"__wbg_queueMicrotask_4a1a4d8dd332373b"),__wbg_resolve_dbf78ab4942478b0:c(function(e){return Promise.resolve(e)},"__wbg_resolve_dbf78ab4942478b0"),__wbg_set_2793479888329cb6:c(function(){return $(function(e,t,n){return Reflect.set(e,t,n)},arguments)},"__wbg_set_2793479888329cb6"),__wbg_stack_575c4e0918581b9c:c(function(e,t){let n=t.stack,r=g(n,s.__wbindgen_malloc,s.__wbindgen_realloc),o=w;x().setInt32((e>>>0)+4,o,!0),x().setInt32((e>>>0)+0,r,!0)},"__wbg_stack_575c4e0918581b9c"),__wbg_static_accessor_GLOBAL_THIS_003ee833af9699fc:c(function(){let e=typeof globalThis>"u"?void 0:globalThis;return k(e)?0:E(e)},"__wbg_static_accessor_GLOBAL_THIS_003ee833af9699fc"),__wbg_static_accessor_GLOBAL_e4293fb22cbe77da:c(function(){let e=typeof globalThis>"u"?void 0:globalThis;return k(e)?0:E(e)},"__wbg_static_accessor_GLOBAL_e4293fb22cbe77da"),__wbg_static_accessor_SELF_53bb20457401453d:c(function(){let e=typeof self>"u"?void 0:self;return k(e)?0:E(e)},"__wbg_static_accessor_SELF_53bb20457401453d"),__wbg_static_accessor_WINDOW_b5e0810bfecb7feb:c(function(){let e=typeof window>"u"?void 0:window;return k(e)?0:E(e)},"__wbg_static_accessor_WINDOW_b5e0810bfecb7feb"),__wbg_then_656f253a5dd7d8ea:c(function(e,t,n){return e.then(t,n)},"__wbg_then_656f253a5dd7d8ea"),__wbg_then_e3f7f2d365708be8:c(function(e,t){return e.then(t)},"__wbg_then_e3f7f2d365708be8"),__wbindgen_generic_0000000000000001:c(function(e,t){return ce(e,t,_e)},"__wbindgen_generic_0000000000000001"),__wbindgen_generic_0000000000000002:c(function(e){return e},"__wbindgen_generic_0000000000000002"),__wbindgen_generic_0000000000000003:c(function(e,t){return m(e,t)},"__wbindgen_generic_0000000000000003"),__wbindgen_init_externref_table:c(function(){let e=s.__wbindgen_externrefs;e.set(0,void 0),e.set(1024,void 0),e.set(1025,null),e.set(1026,!0),e.set(1027,!1)},"__wbindgen_init_externref_table")}}}c(oe,"__wbg_get_imports");function _e(i,e,t){let n=s.wasm_bindgen_33287221aa659725___convert__closures_____invoke___wasm_bindgen_33287221aa659725___JsValue__core_6a51abefd5362b2___result__Result_____wasm_bindgen_33287221aa659725___JsError___true_(i,e,t);if(n[1])throw p(n[0])}c(_e,"wasm_bindgen_33287221aa659725___convert__closures_____invoke___wasm_bindgen_33287221aa659725___JsValue__core_6a51abefd5362b2___result__Result_____wasm_bindgen_33287221aa659725___JsError___true_");var P=typeof FinalizationRegistry>"u"?{register:c(()=>{},"register"),unregister:c(()=>{},"unregister")}:new FinalizationRegistry(i=>s.__wbg_hasher_free(i,1)),H=typeof FinalizationRegistry>"u"?{register:c(()=>{},"register"),unregister:c(()=>{},"unregister")}:new FinalizationRegistry(i=>s.__wbg_hmac_free(i,1)),Y=typeof FinalizationRegistry>"u"?{register:c(()=>{},"register"),unregister:c(()=>{},"unregister")}:new FinalizationRegistry(i=>s.__wbg_owckernel_free(i,1)),X=typeof FinalizationRegistry>"u"?{register:c(()=>{},"register"),unregister:c(()=>{},"unregister")}:new FinalizationRegistry(i=>s.__wbg_zstream_free(i,1));function E(i){let e=s.__externref_table_alloc();return s.__wbindgen_externrefs.set(e,i),e}c(E,"addToExternrefTable0");var Z=typeof FinalizationRegistry>"u"?{register:c(()=>{},"register"),unregister:c(()=>{},"unregister")}:new FinalizationRegistry(i=>s.__wbindgen_destroy_closure(i.a,i.b));function Q(i){switch(typeof i){case"number":case"boolean":case"undefined":return`${i}`;case"string":return JSON.stringify(i);case"bigint":return`${i}n`;case"symbol":return i.description!==void 0?`Symbol(${i.description})`:"Symbol";case"function":return typeof i.name=="string"&&i.name!==""?`Function(${i.name})`:"Function";case"object":{if(i===null)return"null";if(Array.isArray(i))return"["+Array.from(i,Q).join(", ")+"]";if(i instanceof Error)return`${i.name}: ${i.message}
2
+ ${i.stack}`;let e=toString.call(i),t=/\[object ([^\]]+)\]/.exec(e)?.[1];if(t===void 0)return e;if(t==="Object")try{return"Object("+JSON.stringify(i)+")"}catch{return"Object"}return t}}}c(Q,"debugString");function S(i,e){return i=i>>>0,O().subarray(i/1,i/1+e)}c(S,"getArrayU8FromWasm0");var W=null;function x(){return(W===null||W.buffer.detached===!0||W.buffer.detached===void 0&&W.buffer!==s.memory.buffer)&&(W=new DataView(s.memory.buffer)),W}c(x,"getDataViewMemory0");function m(i,e){return i=i>>>0,le(O().subarray(i,i+e))}c(m,"getStringFromWasm0");var R=null;function O(){return(R===null||R.byteLength===0)&&(R=new Uint8Array(s.memory.buffer)),R}c(O,"getUint8ArrayMemory0");function $(i,e){try{return i.apply(this,e)}catch(t){let n=E(t);s.__wbindgen_exn_store(n)}}c($,"handleError");function k(i){return i==null}c(k,"isLikeNone");function ce(i,e,t){let n={a:i,b:e,cnt:1},r=c((...o)=>{n.cnt++;let _=n.a;n.a=0;try{return t(_,n.b,...o)}finally{n.a=_,r._wbg_cb_unref()}},"real");return r._wbg_cb_unref=()=>{--n.cnt===0&&(s.__wbindgen_destroy_closure(n.a,n.b),n.a=0,Z.unregister(n))},Z.register(r,n,n),r}c(ce,"makeMutClosure");function v(i,e){let t=e(i.length*1,1)>>>0;return O().set(i,t/1),w=i.length,t}c(v,"passArray8ToWasm0");function g(i,e,t){if(t===void 0){let a=C.encode(i),l=e(a.length,1)>>>0;return O().subarray(l,l+a.length).set(a),w=a.length,l}let n=i.length,r=e(n,1)>>>0,o=O(),_=0;for(;_<n;_++){let a=i.charCodeAt(_);if(a>127)break;o[r+_]=a}if(_!==n){_!==0&&(i=i.slice(_)),r=t(r,n,n=_+i.length*3,1)>>>0;let a=O().subarray(r+_,r+n),l=C.encodeInto(i,a);_+=l.written,r=t(r,n,_,1)>>>0}return w=_,r}c(g,"passStringToWasm0");function p(i){let e=s.__wbindgen_externrefs.get(i);return s.__externref_table_dealloc(i),e}c(p,"takeFromExternrefTable0");var j=new TextDecoder("utf-8",{ignoreBOM:!0});j.decode();var ae=2146435072,q=0;function le(i){return q+=i.length,q>=ae&&(j=new TextDecoder("utf-8",{ignoreBOM:!0}),j.decode(),q=i.length),j.decode(i)}c(le,"decodeText");var C=new TextEncoder;"encodeInto"in C||(C.encodeInto=function(i,e){let t=C.encode(i);return e.set(t),{read:i.length,written:t.length}});var w=0,fe,we,s;function de(i,e){return we=i,s=i.exports,fe=e,W=null,R=null,s.__wbindgen_start(),s}c(de,"__wbg_finalize_init");async function ge(i,e){if(typeof Response=="function"&&i instanceof Response){if(!i.ok)throw new Error(`failed to fetch Wasm: ${i.status} ${i.statusText} fetching '${i.url}'`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(i,e)}catch(r){if(t(i.type)&&i.headers.get("Content-Type")!=="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",r);else throw r}let n=await i.arrayBuffer();return await WebAssembly.instantiate(n,e)}else{let n=await WebAssembly.instantiate(i,e);return n instanceof WebAssembly.Instance?{instance:n,module:i}:n}function t(n){switch(n){case"basic":case"cors":case"default":return!0}return!1}c(t,"expectedResponseType")}c(ge,"__wbg_load");var M;async function ee(i){return s!==void 0?s:(M===void 0&&(M=ue(i),M.catch(()=>{M=void 0})),M)}c(ee,"__wbg_init");async function ue(i){i!==void 0&&(Object.getPrototypeOf(i)===Object.prototype?{module_or_path:i}=i:console.warn("using deprecated parameters for the initialization function; pass a single object instead")),i===void 0&&(i=new URL("owc_wasm_bg.wasm",import.meta.url));let e=oe();(typeof i=="string"||typeof Request=="function"&&i instanceof Request||typeof URL=="function"&&i instanceof URL)&&(i=fetch(i));let{instance:t,module:n}=await ge(await i,e);return de(t,n)}c(ue,"__wbg_init_once");var N=new TextEncoder,I=new TextDecoder;function he(i,e){if(!i.length)return e;let t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}c(he,"concat");function L(i,e){let t=e.length,n=t<126?2:t<65536?4:10,r=new Uint8Array(n+4+t);r[0]=128|i,t<126?r[1]=128|t:t<65536?(r[1]=254,r[2]=t>>8,r[3]=t&255):(r[1]=255,new DataView(r.buffer).setBigUint64(2,BigInt(t)));let o=crypto.getRandomValues(new Uint8Array(4));r.set(o,n);for(let _=0;_<t;_++)r[n+4+_]=e[_]^o[_&3];return r}c(L,"frame");var B=class{static{c(this,"WsBridge")}constructor(e){this.kernel=e,this.conns=new Map}open({port:e,path:t,protocols:n,origin:r},o){let _;try{_=this.kernel.rawConnect(e)}catch{o.postMessage({t:"close",code:1006,reason:"connection refused",wasClean:!1});return}let a=btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(16)))),l={sock:_,mp:o,buf:new Uint8Array(0),open:!1,frags:[],fragOp:0,closed:!1};this.conns.set(_,l);let f=`GET ${t||"/"} HTTP/1.1\r
3
+ Host: localhost:${e}\r
4
+ Upgrade: websocket\r
5
+ Connection: Upgrade\r
6
+ Sec-WebSocket-Key: ${a}\r
7
+ Sec-WebSocket-Version: 13\r
8
+ `;r&&(f+=`Origin: ${r}\r
9
+ `),n&&n.length&&(f+=`Sec-WebSocket-Protocol: ${n.join(", ")}\r
10
+ `),this.kernel.rawSend(_,N.encode(f+`\r
11
+ `)),o.onmessage=h=>{let d=h.data;if(!l.closed){if(d.t==="send"){let b=typeof d.data=="string";globalThis.__OWC_WS_DEBUG&&console.debug("[owc-ws] -> server",t,b?d.data.slice(0,160):"<binary>"),this.kernel.rawSend(_,L(b?1:2,b?N.encode(d.data):new Uint8Array(d.data)))}else if(d.t==="close"){let b=N.encode(d.reason||""),u=new Uint8Array(2+b.length);u[0]=(d.code||1e3)>>8,u[1]=(d.code||1e3)&255,u.set(b,2),this.kernel.rawSend(_,L(8,u)),setTimeout(()=>this._finish(l,d.code||1e3,d.reason||"",!0),1e3)}}}}data(e,t){let n=this.conns.get(e);if(globalThis.__OWC_WS_DEBUG&&console.debug("[owc-ws] raw <-",e,t.length,n?n.open?"open":"handshake":"NO CONN"),!!n){if(n.buf=he(n.buf,t),!n.open){let r=I.decode(n.buf),o=r.indexOf(`\r
12
+ \r
13
+ `);if(o<0)return;let _=r.slice(0,o),a=+(/^HTTP\/1\.\d (\d{3})/.exec(_)?.[1]||0);if(a!==101){n.mp.postMessage({t:"close",code:1006,reason:`unexpected response ${a}`,wasClean:!1}),this._finish(n,1006,"",!1,!0);return}let l=/\r\nsec-websocket-protocol:\s*([^\r\n]*)/i.exec(_)?.[1]||"";n.open=!0,n.buf=n.buf.subarray(N.encode(r.slice(0,o+4)).length),n.mp.postMessage({t:"open",protocol:l})}this._parse(n)}}_parse(e){for(;;){let t=e.buf;if(t.length<2)return;let n=t[0]&128,r=t[0]&15,o=t[1]&128,_=t[1]&127,a=2;if(_===126){if(t.length<4)return;_=t[2]<<8|t[3],a=4}else if(_===127){if(t.length<10)return;_=Number(new DataView(t.buffer,t.byteOffset).getBigUint64(2)),a=10}let l=o?t.subarray(a,a+4):null;if(o&&(a+=4),t.length<a+_)return;let f=t.slice(a,a+_);if(l)for(let h=0;h<f.length;h++)f[h]^=l[h&3];if(e.buf=t.subarray(a+_),r===8){let h=f.length>=2?f[0]<<8|f[1]:1005,d=f.length>2?I.decode(f.subarray(2)):"";try{this.kernel.rawSend(e.sock,L(8,f.subarray(0,2)))}catch{}this._finish(e,h,d,!0);return}if(r===9){this.kernel.rawSend(e.sock,L(10,f));continue}if(r!==10&&(r===0?e.frags.push(f):(e.fragOp=r,e.frags=[f]),n)){let h=e.frags.reduce((u,y)=>u+y.length,0),d=new Uint8Array(h),b=0;for(let u of e.frags)d.set(u,b),b+=u.length;e.frags=[],globalThis.__OWC_WS_DEBUG&&console.debug("[owc-ws] <- server",e.fragOp===1?I.decode(d).slice(0,160):"<binary "+d.length+">"),e.fragOp===1?e.mp.postMessage({t:"message",data:I.decode(d)}):e.mp.postMessage({t:"message",data:d.buffer},[d.buffer])}}}closed(e){let t=this.conns.get(e);t&&this._finish(t,1006,"",!1,!0)}_finish(e,t,n,r,o=!1){if(!e.closed&&(e.closed=!0,this.conns.delete(e.sock),e.mp.postMessage({t:"close",code:t,reason:n,wasClean:r}),!o))try{this.kernel.rawClose(e.sock)}catch{}}};var T=new TextEncoder,be=4<<20,pe=200;function ye(){let i=new Uint8Array(6);return crypto.getRandomValues(i),[...i].map(e=>e.toString(36).padStart(2,"0")).join("").slice(0,10)}c(ye,"randomId");function me(i){let e="";for(let t=0;t<i.length;t+=32768)e+=String.fromCharCode.apply(null,i.subarray(t,t+32768));return btoa(e)}c(me,"toBase64");function ke(i){let e=atob(i),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}c(ke,"fromBase64");function ne(i){let e={};for(let[t,n]of Object.entries(i))if("directory"in n)e[t]={directory:ne(n.directory)};else if(n.file&&"symlink"in n.file)e[t]={file:{symlink:n.file.symlink}};else if(n.file){let r=n.file.contents;e[t]={file:{contents:typeof r=="string"?r:{$bytes:me(r instanceof Uint8Array?r:new Uint8Array(r))}}}}return e}c(ne,"treeToInternal");function re(i){let e={};for(let[t,n]of Object.entries(i))if(n.directory)e[t]={directory:re(n.directory)};else if(n.file&&"symlink"in n.file)e[t]={file:{symlink:n.file.symlink}};else if(n.file){let r=n.file.contents;e[t]={file:{contents:typeof r=="string"?r:ke(r.$bytes)}}}return e}c(re,"treeToExternal");function te(i,e,t){let n=T.encode(JSON.stringify({op:i,...e})),r=new Uint8Array(4+n.length+(t?t.length:0));return new DataView(r.buffer).setUint32(0,n.length,!0),r.set(n,4),t&&r.set(t,4+n.length),r}c(te,"encodeMsg");var V=class{static{c(this,"DirEnt")}constructor(e,t){this.name=e,this._type=t}isFile(){return this._type===1}isDirectory(){return this._type===2}isSymbolicLink(){return this._type===3}},G=class{static{c(this,"FileSystemAPI")}constructor(e){this._wc=e}get _k(){return this._wc._kernel}async readFile(e,t){let n=this._k.readFile(e);return t==null||t==="buffer"?n:new TextDecoder(t==="utf8"?"utf-8":t).decode(n)}async writeFile(e,t,n){let r=typeof n=="string"?n:n?.encoding,o=typeof t=="string"?T.encode(t):t instanceof Uint8Array?t:new Uint8Array(t);this._k.writeFile(e,o,!1)}async readdir(e,t){let n=JSON.parse(this._k.readdir(e)),r=typeof t=="string"?t:t?.encoding;return t?.withFileTypes?n.map(([o,_])=>new V(r==="buffer"?T.encode(o):o,_)):n.map(([o])=>r==="buffer"?T.encode(o):o)}async mkdir(e,t){let n=this._k.mkdir(e,!!t?.recursive);return t?.recursive?n:void 0}async rm(e,t){this._k.rm(e,!!t?.recursive,!!t?.force)}async rename(e,t){this._k.rename(e,t)}async stat(e){let t=JSON.parse(this._k.stat(e));return{...t,isFile:c(()=>t.type==="file","isFile"),isDirectory:c(()=>t.type==="dir","isDirectory"),isSymbolicLink:c(()=>t.type==="symlink","isSymbolicLink")}}async exists(e){return this._k.exists(e)}watch(e,t,n){typeof t=="function"&&(n=t,t={});let r=this._k.watch(e,!!t?.recursive);return this._wc._watchers.set(r,(o,_)=>n?.(o,_)),{close:c(()=>{this._k.unwatch(r),this._wc._watchers.delete(r)},"close")}}},K=class i{static{c(this,"WebContainer")}static _instance=null;static _booting=null;static async boot(e={}){for(;i._booting;)await i._booting.catch(()=>{});if(i._instance)throw new Error("Only a single WebContainer instance can be booted");let t=i._boot(e);i._booting=t;try{let n=await t;return i._instance=n,n}finally{i._booting=null}}static async _boot(e){if(typeof window>"u")throw new Error("WebContainer.boot() must be called from a browser window");if(!globalThis.crossOriginIsolated)throw new Error(`OpenWebContainer requires a cross-origin isolated page. Serve it with the headers
14
+ Cross-Origin-Opener-Policy: same-origin
15
+ Cross-Origin-Embedder-Policy: require-corp (or credentialless)`);if(!("serviceWorker"in navigator))throw new Error("OpenWebContainer requires Service Worker support");let t=import.meta.url,n=new URL(e.serviceWorkerUrl||"./owc-sw.js",t),r=new URL(e.runtimeUrl||"./owc-runtime.js",t),o=new URL(e.wasmUrl||"./owc_wasm_bg.wasm",t),[_,a,l]=await Promise.all([ve(n,e.serviceWorkerScope??"/"),WebAssembly.compileStreaming(fetch(o)),e.proxyUrl!==void 0?Promise.resolve(e.proxyUrl):Se()]);await ee({module_or_path:a});let f=new i(_,a,r,l,e);return await f._registerWithServiceWorker(),f}constructor(e,t,n,r,o){this._reg=e,this._wasm=t,this._runtimeUrl=n,this._cid=ye(),this._scopePath=new URL(e.scope).pathname.replace(/\/$/,""),this._vmBase=`${this._scopePath}/__owc/vm/${this._cid}`,this._listeners=new Map,this._workers=new Map,this._sinks=new Map,this._exitWaiters=new Map,this._watchers=new Map,this._http=new Map,this._nextSink=1,this._nextReq=1,this._previewScript=null,this._tornDown=!1,this._ports=new Set,this._readyTimers=new Map;let _=r?new URL(r,location.href).href.replace(/\/$/,""):null;this._config={cid:this._cid,vmBase:this._vmBase,origin:location.origin,proxyUrl:_,relay:o.relay!==!1},this.fs=new G(this),this._kernel=new U(this._hostImpl(),o.workdirName||"project"),this._ws=new B(this._kernel);let a=o.npmRegistry||(_?`${_}/npm`:"https://registry.npmjs.org");if(this._kernel.setRegistry(a.replace(/\/$/,""),a.startsWith("https://registry.npmjs.org")?void 0:"https://registry.npmjs.org",a.startsWith("https://registry.npmjs.org")?void 0:a.replace(/\/$/,"")),o.env)for(let[l,f]of Object.entries(o.env))this._kernel.setEnv(l,String(f));this._onSwMessage=l=>this._handleSwMessage(l),navigator.serviceWorker.addEventListener("message",this._onSwMessage),navigator.serviceWorker.startMessages?.()}_hostImpl(){return{spawnWorker:c((e,t)=>this._spawnWorker(e,JSON.parse(t)),"spawnWorker"),terminateWorker:c(e=>{let t=this._workers.get(e);if(t){for(let n of t.threads.values())n.worker.terminate();t.worker.terminate(),this._workers.delete(e)}},"terminateWorker"),post:c((e,t,n,r)=>{let o=this._workers.get(e),_=t?o?.threads.get(t):o;_&&_.worker.postMessage({t:"k",msg:JSON.parse(n),bin:r},r?[r.buffer]:[])},"post"),completeSyscall:c((e,t,n)=>{let r=this._workers.get(e),o=t?r?.threads.get(t):r;o&&this._respond(o,n)},"completeSyscall"),output:c((e,t)=>this._sinks.get(e)?.(t),"output"),event:c((e,t)=>{let n=JSON.parse(t);queueMicrotask(()=>this._onKernelEvent(e,n))},"event"),httpHead:c((e,t,n)=>this._http.get(e)?.postMessage({t:"head",status:t,headers:JSON.parse(n),inject:this._previewScript}),"httpHead"),httpChunk:c((e,t)=>this._http.get(e)?.postMessage({t:"chunk",data:t.buffer},[t.buffer]),"httpChunk"),httpEnd:c((e,t)=>{let n=this._http.get(e);this._http.delete(e),n?.postMessage({t:"end",error:t})},"httpEnd"),sockData:c((e,t)=>this._ws.data(e,t),"sockData"),sockClosed:c(e=>queueMicrotask(()=>this._ws.closed(e)),"sockClosed"),fetch:c(async(e,t,n,r)=>{let o=JSON.parse(n),_=await fetch(e,{method:t,headers:o,body:r||void 0});return{status:_.status,headers:JSON.stringify([..._.headers]),body:new Uint8Array(await _.arrayBuffer())}},"fetch"),sleep:c(e=>new Promise(t=>setTimeout(t,e)),"sleep")}}_spawnWorker(e,t){let n=(t.argv||[]).slice(0,3).join(" ").slice(0,60),r={...this._config,tids:new SharedArrayBuffer(4)},o=this._startWorker({pid:e,chan:0,init:t,config:r},`owc ${e}: ${n}`,{t:"init",init:t},[]);o.threads=new Map,this._workers.set(e,o)}_startWorker(e,t,n,r){let o=new Worker(this._runtimeUrl,{type:"module",name:t}),_=new SharedArrayBuffer(16+be);return Object.assign(e,{worker:o,ctrl:new Int32Array(_,0,4),data:new Uint8Array(_,16),pending:null}),o.onmessage=a=>this._onWorkerMessage(e,a.data),o.onerror=a=>{if(a.preventDefault?.(),e.chan)return this._threadGone(e,1,{name:"Error",message:a.message||"worker error"});let l=`owc: process ${e.pid} crashed: ${a.message||"worker error"}
16
+ `;try{this._kernel.message(e.pid,0,te("write",{fd:2},T.encode(l)))}catch{}this._kernel.workerDied(e.pid,1),this._emit("error",{message:l.trim()})},o.postMessage({...n,sab:_,wasm:this._wasm,config:e.config},r),e}_spawnThread(e,t){let n=this._workers.get(e.pid);if(!n)return;let r=t.opts.spec,o=r.file||(r.eval!==void 0?"[worker eval]":"[worker data:]"),_=`owc ${e.pid}/${t.tid}: ${t.opts.name||o.split("/").pop()}`.slice(0,80),a={pid:e.pid,chan:t.tid,init:n.init,config:n.config,owner:e,children:new Set};n.threads.set(t.tid,a),e.children?.add(a),this._startWorker(a,_,{t:"init",init:n.init,thread:{tid:t.tid,port:t.port,opts:t.opts}},t.transfer||[t.port])}_threadGone(e,t,n){let r=this._workers.get(e.pid);if(!(!r||r.threads.get(e.chan)!==e)){r.threads.delete(e.chan),e.owner.children?.delete(e),e.worker.terminate(),this._kernel.threadExited(e.pid,e.chan);for(let o of[...e.children])this._threadGone(o,1);t!==void 0&&e.owner.worker.postMessage({t:"thread",tid:e.chan,ev:"exit",code:t,error:n})}}_onWorkerMessage(e,t){let n=e.pid;switch(t.t){case"sys":{let r=this._kernel.syscall(n,e.chan,t.req);r!==void 0&&this._respond(e,r);break}case"more":e.pending&&this._writeChunk(e);break;case"msg":this._kernel.message(n,e.chan,t.req);break;case"spawnThread":this._spawnThread(e,t);break;case"terminateThread":{let r=this._workers.get(n)?.threads.get(t.tid);r&&r.owner===e&&this._threadGone(r,1);break}case"threadExit":setTimeout(()=>this._threadGone(e,t.code),20);break;case"crash":if(e.chan){this._threadGone(e,1,{name:"Error",message:t.message});break}this._kernel.message(n,0,te("write",{fd:2},T.encode(t.message+`
17
+ `))),this._kernel.workerDied(n,1);break}}_respond(e,t){e.pending={bytes:t,off:0},this._writeChunk(e)}_writeChunk(e){let t=e.pending,n=Math.min(t.bytes.length-t.off,e.data.length);e.data.set(t.bytes.subarray(t.off,t.off+n)),e.ctrl[1]=t.bytes.length,e.ctrl[2]=n,t.off+=n,t.off>=t.bytes.length&&(e.pending=null),Atomics.store(e.ctrl,0,2),Atomics.notify(e.ctrl,0)}_onKernelEvent(e,t){switch(e){case"exit":{let n=this._exitWaiters.get(t.pid);n&&(this._exitWaiters.delete(t.pid),n(t.code));break}case"port":{let n=this._previewUrl(t.port);t.type==="open"?(this._ports.add(t.port),this._emit("port",t.port,"open",n),clearTimeout(this._readyTimers.get(t.port)),this._readyTimers.set(t.port,setTimeout(()=>{this._readyTimers.delete(t.port),this._ports.has(t.port)&&this._emit("server-ready",t.port,n)},pe))):(this._ports.delete(t.port),clearTimeout(this._readyTimers.get(t.port)),this._readyTimers.delete(t.port),this._emit("port",t.port,"close",n));break}case"watch":this._watchers.get(t.id)?.(t.event,t.filename);break;case"xdg-open":this._emit("xdg-open",t.text);break;default:this._emit(e,t)}}_previewUrl(e){return`${location.origin}${this._scopePath}/__owc/p/${this._cid}-${e}/`}async _registerWithServiceWorker(){let e=navigator.serviceWorker.controller;if(!e)throw new Error("OpenWebContainer: the service worker is not controlling this page; reload it");await new Promise(t=>{let n=new MessageChannel,r=setTimeout(t,2e3);n.port1.onmessage=()=>{clearTimeout(r),t()},e.postMessage({type:"owc-register",cid:this._cid},[n.port2])})}_handleSwMessage(e){let t=e.data;if(!t||t.cid!==this._cid||this._tornDown)return;let n=e.ports[0];if(t.type==="owc-ping")n?.postMessage({ok:!0});else if(t.type==="owc-module"){let r=this._kernel.serveModule(this._vmBase,t.kind,t.rest,t.query);n.postMessage({status:r.status,contentType:r.contentType,body:r.body.buffer},[r.body.buffer])}else if(t.type==="owc-ws")this._ws.open(t,n);else if(t.type==="owc-http"){let r=this._nextReq++;this._http.set(r,n),n.onmessage=_=>{_.data?.t==="abort"&&this._kernel.httpAbort(r)};let o=t.body?new Uint8Array(t.body):new Uint8Array(0);this._kernel.httpRequest(r,t.port,t.method,t.path,JSON.stringify(t.headers),o)}}_emit(e,...t){for(let n of this._listeners.get(e)||[])try{n(...t)}catch(r){console.error(r)}}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),()=>this._listeners.get(e)?.delete(t)}async mount(e,t={}){this._assertAlive(),e instanceof Uint8Array||e instanceof ArrayBuffer?this._kernel.mountSnapshot(new Uint8Array(e),t.mountPoint):this._kernel.mountTree(JSON.stringify(ne(e)),t.mountPoint)}async spawn(e,t,n){this._assertAlive(),Array.isArray(t)||(n=t,t=[]),n=n||{};let r=this._nextSink++,o=new TextDecoder,_,a=new ReadableStream({start(u){_=u}}),l=!1;this._sinks.set(r,u=>{if(n.output===!1||l)return;let y=o.decode(u,{stream:!0});y&&_.enqueue(y)});let f;try{f=this._kernel.spawn(String(e),JSON.stringify(t.map(String)),JSON.stringify({cwd:n.cwd,env:n.env,terminal:n.terminal||null}),r)}catch(u){if(this._sinks.delete(r),u.code==="ENOENT"){let y=`jsh: command not found: ${e}\r
18
+ `;return _.enqueue(y),_.close(),{pid:-1,output:a,input:new WritableStream,exit:Promise.resolve(127),kill(){},resize(){}}}throw u}let h=new Promise(u=>{this._exitWaiters.set(f,y=>{setTimeout(()=>{let A=o.decode();A&&!l&&_.enqueue(A),l=!0;try{_.close()}catch{}this._sinks.delete(r),u(y)},0)})}),d=this._kernel,b=new WritableStream({write(u){d.input(f,typeof u=="string"?T.encode(u):new Uint8Array(u))},close(){d.closeInput(f)}});return{pid:f,output:a,input:b,exit:h,kill:c((u="SIGKILL")=>d.kill(f,u),"kill"),resize:c(({cols:u,rows:y})=>d.resize(f,u,y),"resize")}}async export(e=".",t={}){this._assertAlive();let n=t.format||"json";if(n==="binary")return this._kernel.exportSnapshot(e);if(n==="zip")throw new Error("export format 'zip' is not supported yet");return re(JSON.parse(this._kernel.exportTree(e,JSON.stringify(t.excludes||[]))))}async setPreviewScript(e,t={}){let n=[t.type?`type="${t.type}"`:"",t.defer?"defer":"",t.async?"async":""].filter(Boolean).join(" ");this._previewScript=`<script ${n}>${e}<\/script>`}previewUrl(e){return this._previewUrl(e)}get workdir(){return this._kernel.workdir()}get path(){return"/usr/local/bin:/usr/bin:/bin:/home/.npm-global/bin"}stats(){return{...JSON.parse(this._kernel.stats()),processes:JSON.parse(this._kernel.processes()),proxy:this._config.proxyUrl}}teardown(){if(this._tornDown)throw new Error("WebContainer already torn down");this._tornDown=!0;for(let[,e]of this._workers){for(let t of e.threads.values())t.worker.terminate();e.worker.terminate()}this._workers.clear(),navigator.serviceWorker.removeEventListener("message",this._onSwMessage);for(let[,e]of this._exitWaiters)e(-1);this._exitWaiters.clear(),i._instance===this&&(i._instance=null)}_assertAlive(){if(this._tornDown)throw new Error("WebContainer has been torn down")}};async function ve(i,e){let t=await navigator.serviceWorker.register(i,{scope:e,updateViaCache:"none"});return await navigator.serviceWorker.ready,navigator.serviceWorker.controller||await new Promise(n=>{let r=setTimeout(n,3e3);navigator.serviceWorker.addEventListener("controllerchange",()=>{clearTimeout(r),n()},{once:!0}),t.active?.postMessage({type:"owc-claim"})}),t}c(ve,"registerServiceWorker");async function Se(){try{let i=new AbortController,e=setTimeout(()=>i.abort(),1500),t=await fetch("/__owc/health",{signal:i.signal});if(clearTimeout(e),!t.ok)return null;let n=await t.json();return n&&n.name==="owc-proxy"?"/__owc":null}catch{return null}}c(Se,"detectProxy");var Ee=K;export{K as WebContainer,Ee as default};