wasm-idle 1.1.0 → 1.2.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.
Files changed (197) hide show
  1. package/README.md +267 -112
  2. package/dist/container/bash-profile.d.ts +80 -0
  3. package/dist/container/bash-profile.js +328 -0
  4. package/dist/container/binding.d.ts +39 -0
  5. package/dist/container/binding.js +331 -0
  6. package/dist/container/clang-runtime.d.ts +42 -0
  7. package/dist/container/clang-runtime.js +561 -0
  8. package/dist/container/client.d.ts +14 -0
  9. package/dist/container/client.js +185 -0
  10. package/dist/container/explorer.d.ts +31 -0
  11. package/dist/container/explorer.js +112 -0
  12. package/dist/container/index.d.ts +11 -0
  13. package/dist/container/index.js +11 -0
  14. package/dist/container/owner-worker.d.ts +19 -0
  15. package/dist/container/owner-worker.js +464 -0
  16. package/dist/container/protocol.d.ts +84 -0
  17. package/dist/container/protocol.js +28 -0
  18. package/dist/container/runtime-adapter.d.ts +75 -0
  19. package/dist/container/runtime-adapter.js +537 -0
  20. package/dist/container/shell-control.d.ts +49 -0
  21. package/dist/container/shell-control.js +360 -0
  22. package/dist/container/workspace.d.ts +12 -0
  23. package/dist/container/workspace.js +29 -0
  24. package/dist/index.d.ts +1 -1
  25. package/dist/playground/assetBridge.js +111 -33
  26. package/dist/playground/assets.d.ts +10 -2
  27. package/dist/playground/c3.js +22 -0
  28. package/dist/playground/c3Memory.d.ts +19 -0
  29. package/dist/playground/c3Memory.js +117 -0
  30. package/dist/playground/cachedClang.js +143 -34
  31. package/dist/playground/clang.d.ts +5 -1
  32. package/dist/playground/clang.js +61 -5
  33. package/dist/playground/clangAssetIntegrity.js +6 -6
  34. package/dist/playground/clangWorkerProtocol.d.ts +12 -1
  35. package/dist/playground/cobol.d.ts +3 -0
  36. package/dist/playground/cobol.js +10 -1
  37. package/dist/playground/commonlispAssets.d.ts +2 -2
  38. package/dist/playground/compiledArtifactCache.d.ts +3 -1
  39. package/dist/playground/compiledArtifactCache.js +31 -5
  40. package/dist/playground/compiledLldb.d.ts +41 -0
  41. package/dist/playground/compiledLldb.js +167 -0
  42. package/dist/playground/d.d.ts +10 -2
  43. package/dist/playground/d.js +161 -14
  44. package/dist/playground/debugDeadline.d.ts +12 -0
  45. package/dist/playground/debugDeadline.js +34 -0
  46. package/dist/playground/debugMailbox.d.ts +12 -0
  47. package/dist/playground/debugMailbox.js +77 -0
  48. package/dist/playground/dotnet.js +6 -8
  49. package/dist/playground/fortran.d.ts +3 -0
  50. package/dist/playground/fortran.js +10 -1
  51. package/dist/playground/go.js +23 -7
  52. package/dist/playground/goDebugInstrumentation.js +207 -97
  53. package/dist/playground/java-debug-FMHDKUN6.js +124 -0
  54. package/dist/playground/java-debug-notices.txt +492 -0
  55. package/dist/playground/java.d.ts +17 -1
  56. package/dist/playground/java.js +162 -5
  57. package/dist/playground/javaDebug.d.ts +62 -0
  58. package/dist/playground/javaDebug.js +305 -0
  59. package/dist/playground/javaDebugBridge.d.ts +6 -0
  60. package/dist/playground/javaDebugBridge.js +250 -0
  61. package/dist/playground/javaDebugSource.d.ts +9 -0
  62. package/dist/playground/javaDebugSource.js +4 -0
  63. package/dist/playground/javaRuntimeErrors.d.ts +9 -0
  64. package/dist/playground/javaRuntimeErrors.js +93 -0
  65. package/dist/playground/lean4Assets.d.ts +1 -25
  66. package/dist/playground/lean4Assets.js +2 -123
  67. package/dist/playground/lfortran.js +10 -0
  68. package/dist/playground/lfortranAssets.d.ts +2 -2
  69. package/dist/playground/lldbSession.d.ts +23 -2
  70. package/dist/playground/lldbSession.js +278 -58
  71. package/dist/playground/lldbSourcePath.d.ts +2 -0
  72. package/dist/playground/lldbSourcePath.js +9 -0
  73. package/dist/playground/lua.d.ts +20 -1
  74. package/dist/playground/lua.js +190 -8
  75. package/dist/playground/luaDebug.d.ts +1 -0
  76. package/dist/playground/luaDebug.js +1 -0
  77. package/dist/playground/nim.d.ts +1 -0
  78. package/dist/playground/nim.js +30 -0
  79. package/dist/playground/objectivec.d.ts +10 -6
  80. package/dist/playground/objectivec.js +85 -10
  81. package/dist/playground/options.d.ts +12 -4
  82. package/dist/playground/python.d.ts +8 -1
  83. package/dist/playground/python.js +89 -6
  84. package/dist/playground/ruby.d.ts +10 -1
  85. package/dist/playground/ruby.js +66 -1
  86. package/dist/playground/rubyDebug.d.ts +21 -0
  87. package/dist/playground/rubyDebug.js +128 -0
  88. package/dist/playground/runtimeAssetCache.d.ts +1 -32
  89. package/dist/playground/runtimeAssetCache.js +1 -193
  90. package/dist/playground/runtimeSession.d.ts +2 -2
  91. package/dist/playground/runtimeSession.js +11 -11
  92. package/dist/playground/rust.d.ts +10 -0
  93. package/dist/playground/rust.js +230 -51
  94. package/dist/playground/sandbox.d.ts +8 -1
  95. package/dist/playground/staticStdinRing.d.ts +2 -1
  96. package/dist/playground/staticStdinRing.js +21 -10
  97. package/dist/playground/staticWorkerRuntime.d.ts +15 -1
  98. package/dist/playground/staticWorkerRuntime.js +127 -19
  99. package/dist/playground/stdinBuffer.d.ts +1 -1
  100. package/dist/playground/stdinBuffer.js +19 -2
  101. package/dist/playground/tinygo.d.ts +3 -0
  102. package/dist/playground/tinygo.js +88 -6
  103. package/dist/playground/typescript.js +8 -0
  104. package/dist/playground/v.d.ts +6 -2
  105. package/dist/playground/v.js +76 -13
  106. package/dist/playground/wasmAwkVersion.d.ts +13 -13
  107. package/dist/playground/wasmAwkVersion.js +4 -4
  108. package/dist/playground/wasmBqnVersion.d.ts +2 -2
  109. package/dist/playground/wasmBqnVersion.js +2 -2
  110. package/dist/playground/wasmC3Version.d.ts +2 -2
  111. package/dist/playground/wasmC3Version.js +2 -2
  112. package/dist/playground/wasmClojureScriptVersion.d.ts +2 -2
  113. package/dist/playground/wasmClojureScriptVersion.js +2 -2
  114. package/dist/playground/wasmCommonLispVersion.d.ts +2 -2
  115. package/dist/playground/wasmCommonLispVersion.js +2 -2
  116. package/dist/playground/wasmDIntegrity.d.ts +5 -5
  117. package/dist/playground/wasmDIntegrity.js +5 -5
  118. package/dist/playground/wasmDVersion.d.ts +16 -1
  119. package/dist/playground/wasmDVersion.js +16 -1
  120. package/dist/playground/wasmDebugVersion.d.ts +1 -1
  121. package/dist/playground/wasmDebugVersion.js +1 -1
  122. package/dist/playground/wasmForthVersion.d.ts +2 -2
  123. package/dist/playground/wasmForthVersion.js +2 -2
  124. package/dist/playground/wasmGleamVersion.d.ts +2 -2
  125. package/dist/playground/wasmGleamVersion.js +2 -2
  126. package/dist/playground/wasmGrainVersion.d.ts +2 -2
  127. package/dist/playground/wasmGrainVersion.js +2 -2
  128. package/dist/playground/wasmJVersion.d.ts +2 -2
  129. package/dist/playground/wasmJVersion.js +2 -2
  130. package/dist/playground/wasmJanetVersion.js +2 -2
  131. package/dist/playground/wasmJuliaVersion.js +2 -2
  132. package/dist/playground/wasmLean4Version.d.ts +1 -110
  133. package/dist/playground/wasmLean4Version.js +2 -111
  134. package/dist/playground/wasmLfortranVersion.d.ts +2 -2
  135. package/dist/playground/wasmLfortranVersion.js +2 -2
  136. package/dist/playground/wasmLuaVersion.d.ts +1 -1
  137. package/dist/playground/wasmLuaVersion.js +1 -1
  138. package/dist/playground/wasmNimVersion.d.ts +9 -9
  139. package/dist/playground/wasmNimVersion.js +6 -6
  140. package/dist/playground/wasmOcamlVersion.d.ts +2 -2
  141. package/dist/playground/wasmOcamlVersion.js +1 -1
  142. package/dist/playground/wasmPascalVersion.js +2 -2
  143. package/dist/playground/wasmPerlVersion.js +2 -2
  144. package/dist/playground/wasmPrologVersion.d.ts +2 -2
  145. package/dist/playground/wasmPrologVersion.js +2 -2
  146. package/dist/playground/wasmReScriptVersion.d.ts +2 -2
  147. package/dist/playground/wasmReScriptVersion.js +2 -2
  148. package/dist/playground/wasmRustVersion.d.ts +26 -38
  149. package/dist/playground/wasmRustVersion.js +25 -40
  150. package/dist/playground/wasmTclVersion.d.ts +4 -4
  151. package/dist/playground/wasmTclVersion.js +2 -2
  152. package/dist/playground/wasmTinyGoVersion.d.ts +14 -14
  153. package/dist/playground/wasmTinyGoVersion.js +14 -14
  154. package/dist/playground/wasmTypeScriptVersion.d.ts +5 -5
  155. package/dist/playground/wasmTypeScriptVersion.js +5 -5
  156. package/dist/playground/worker/cachedClangCompile.js +52 -4
  157. package/dist/playground/worker/cachedClangExecute.js +6 -5
  158. package/dist/playground/worker/clang.js +33 -11
  159. package/dist/playground/worker/cobol.js +3 -3
  160. package/dist/playground/worker/d.js +63 -7
  161. package/dist/playground/worker/fortran.js +3 -3
  162. package/dist/playground/worker/go.js +16 -5
  163. package/dist/playground/worker/haskell.js +10 -7
  164. package/dist/playground/worker/java.js +263 -45
  165. package/dist/playground/worker/javaDebugEvaluator.d.ts +16 -0
  166. package/dist/playground/worker/javaDebugEvaluator.js +44 -0
  167. package/dist/playground/worker/javaDebugRuntime.d.ts +24 -0
  168. package/dist/playground/worker/javaDebugRuntime.js +315 -0
  169. package/dist/playground/worker/javaOutput.d.ts +11 -0
  170. package/dist/playground/worker/javaOutput.js +54 -0
  171. package/dist/playground/worker/lua.js +15 -3
  172. package/dist/playground/worker/php.js +15 -9
  173. package/dist/playground/worker/python.js +102 -30
  174. package/dist/playground/worker/pythonExecution.js +17 -1
  175. package/dist/playground/worker/pythonWorkspaceFiles.d.ts +6 -0
  176. package/dist/playground/worker/pythonWorkspaceFiles.js +26 -0
  177. package/dist/playground/worker/pythonWorkspaceImports.d.ts +4 -0
  178. package/dist/playground/worker/pythonWorkspaceImports.js +129 -0
  179. package/dist/playground/worker/r.js +13 -6
  180. package/dist/playground/worker/ruby.js +13 -0
  181. package/dist/playground/worker/rubyDebugPreview.d.ts +2 -0
  182. package/dist/playground/worker/rubyDebugPreview.js +80 -0
  183. package/dist/playground/worker/rubyTracepoint.d.ts +16 -0
  184. package/dist/playground/worker/rubyTracepoint.js +162 -0
  185. package/dist/playground/worker/rust.js +38 -3
  186. package/dist/playground/worker/sqlite.js +4 -3
  187. package/dist/playground/worker/tinygo.js +11 -3
  188. package/dist/playground/worker/typescript.js +2 -3
  189. package/dist/playground/worker/v.js +32 -7
  190. package/dist/playground/worker/wat.js +2 -3
  191. package/dist/playground/worker/zig.js +20 -6
  192. package/dist/playground/workerSession.d.ts +1 -28
  193. package/dist/playground/workerSession.js +1 -164
  194. package/dist/playground/zig.js +4 -0
  195. package/package.json +66 -15
  196. package/dist/playground/worker/python.runtime.cases.d.ts +0 -1
  197. package/dist/playground/worker/python.runtime.cases.js +0 -374
@@ -0,0 +1,537 @@
1
+ import { assertDebugBreakpointSupport, normalizeDebugSourceBreakpoints, normalizeLanguageId, normalizeWorkspacePath, validateWorkspaceFiles } from '@wasm-idle/core';
2
+ import { ContainerError } from '@wasm-idle/container';
3
+ const COMMAND = 'website-playground-engine';
4
+ const ADAPTER = 'website-playground-host-v1';
5
+ const encoder = new TextEncoder();
6
+ const decoder = new TextDecoder();
7
+ const defaultSource = (language) => ({
8
+ C: 'main.c',
9
+ CPP: 'main.cpp',
10
+ PYTHON: 'main.py',
11
+ PYTHON3: 'main.py',
12
+ JAVA: 'Main.java',
13
+ RUST: 'main.rs',
14
+ GO: 'main.go',
15
+ JAVASCRIPT: 'main.js',
16
+ TYPESCRIPT: 'main.ts'
17
+ })[language] ?? 'main.txt';
18
+ /** Existing real engines keep their private runtime FS; their source snapshot is the common VFS. */
19
+ export class ContainerRuntimeAdapter {
20
+ settings;
21
+ adapter;
22
+ commands = {
23
+ [COMMAND]: { adapter: ADAPTER, bytes: new Uint8Array(), argv0: COMMAND }
24
+ };
25
+ filesystemProfile = 'shared-source-snapshot; runtime-private-files-not-exported';
26
+ #container;
27
+ #sessions = new Map();
28
+ #jobs = new Map();
29
+ #published = new Map();
30
+ #workspaceReads = new Map();
31
+ #nextJob = 0;
32
+ #disposed = false;
33
+ constructor(settings) {
34
+ this.settings = settings;
35
+ this.adapter = {
36
+ id: ADAPTER,
37
+ filesystem: 'live',
38
+ start: async (request) => {
39
+ const job = this.#jobs.get(request.invocation.args[0]);
40
+ if (!job ||
41
+ request.invocation.args.length !== 1 ||
42
+ request.fs !== this.fs ||
43
+ request.invocation.cwd !== this.directory(job.language))
44
+ throw new ContainerError('INVALID_ARGUMENT', 'Unknown application runtime job');
45
+ let output, errors;
46
+ let closed = false, bytes = 0;
47
+ const stdout = new ReadableStream({
48
+ start(controller) {
49
+ output = controller;
50
+ }
51
+ });
52
+ const stderr = new ReadableStream({
53
+ start(controller) {
54
+ errors = controller;
55
+ }
56
+ });
57
+ const session = this.session(job.language);
58
+ job.output = (data) => {
59
+ if (closed || request.signal.aborted)
60
+ return;
61
+ const chunk = encoder.encode(data);
62
+ bytes += chunk.byteLength;
63
+ if (bytes > request.limits.maxOutputBytes) {
64
+ job.error = new ContainerError('RESOURCE_LIMIT', 'Runtime output exceeds the container limit');
65
+ void this.stop(job.language).catch(() => { });
66
+ return;
67
+ }
68
+ if (chunk.byteLength)
69
+ output.enqueue(chunk);
70
+ };
71
+ const abort = () => {
72
+ void session.sandbox.then((sandbox) => sandbox.terminate()).catch(() => { });
73
+ };
74
+ request.signal.addEventListener('abort', abort, { once: true });
75
+ return {
76
+ stdin: new WritableStream({
77
+ write: (chunk) => this.write(job.language, decoder.decode(chunk, { stream: true })),
78
+ close: () => (job.method === 'run' ? this.eof(job.language) : undefined)
79
+ }),
80
+ stdout,
81
+ stderr,
82
+ run: async () => {
83
+ try {
84
+ const sandbox = await session.sandbox;
85
+ request.signal.throwIfAborted();
86
+ const options = { ...job.options, signal: request.signal };
87
+ if (job.method === 'load') {
88
+ await sandbox.load(job.code, job.log, job.args, options, job.progress);
89
+ job.result = true;
90
+ }
91
+ else {
92
+ const running = sandbox.run(job.code, job.method === 'prepare', job.log, job.progress, job.args, options);
93
+ if (job.method === 'run') {
94
+ job.readyForInput = true;
95
+ await this.flushInput(session, sandbox);
96
+ }
97
+ job.result = await running;
98
+ }
99
+ if (job.error)
100
+ throw job.error;
101
+ return { code: job.result === false ? 1 : 0 };
102
+ }
103
+ catch (error) {
104
+ job.error = error;
105
+ throw error;
106
+ }
107
+ },
108
+ dispose: async () => {
109
+ if (closed)
110
+ return;
111
+ closed = true;
112
+ request.signal.removeEventListener('abort', abort);
113
+ job.readyForInput = false;
114
+ if (request.signal.aborted)
115
+ await session.sandbox
116
+ .then((sandbox) => sandbox.terminate())
117
+ .catch(() => { });
118
+ output.close();
119
+ errors.close();
120
+ }
121
+ };
122
+ }
123
+ };
124
+ }
125
+ attach(container) {
126
+ if (this.#container)
127
+ throw new Error('Runtime adapter is already attached');
128
+ this.#container = container;
129
+ }
130
+ get fs() {
131
+ if (!this.#container)
132
+ throw new Error('Container not attached');
133
+ return this.#container.fs;
134
+ }
135
+ directoryPath(language) {
136
+ if (typeof language !== 'string' ||
137
+ !/^[A-Z][A-Z0-9_]{0,63}$/u.test(language) ||
138
+ !normalizeLanguageId(language))
139
+ throw new TypeError('Unsupported workspace language');
140
+ return `/workspace/${language}`;
141
+ }
142
+ directory(language) {
143
+ const path = this.directoryPath(language);
144
+ this.fs.mkdir(path, { recursive: true });
145
+ return path;
146
+ }
147
+ session(language) {
148
+ if (this.#disposed)
149
+ throw new Error('Runtime owner disposed');
150
+ let session = this.#sessions.get(language);
151
+ if (session)
152
+ return session;
153
+ const binding = this.settings.createBinding(this.settings.runtimeAssets);
154
+ session = {
155
+ binding,
156
+ sandbox: undefined,
157
+ pendingInput: [],
158
+ pendingBytes: 0,
159
+ pendingEof: false
160
+ };
161
+ const owner = session;
162
+ session.sandbox = binding.load(language).then((value) => {
163
+ const sandbox = value;
164
+ sandbox.output = (data) => owner.active?.output?.(data);
165
+ for (const [property, name] of [
166
+ ['ondebug', 'debug'],
167
+ ['oncompilerdiagnostic', 'diagnostic'],
168
+ ['image', 'image']
169
+ ])
170
+ sandbox[property] = (data) => this.settings.emit({
171
+ language,
172
+ name,
173
+ data,
174
+ requestId: owner.active?.requestId
175
+ });
176
+ return sandbox;
177
+ });
178
+ void session.sandbox.catch(() => { });
179
+ this.#sessions.set(language, session);
180
+ return session;
181
+ }
182
+ syncWorkspace(language, files, expectedBaseFiles, project) {
183
+ const path = this.directoryPath(language);
184
+ const validated = validateWorkspaceFiles(files, {
185
+ maxFiles: 2048,
186
+ maxFileBytes: 16 * 1024 * 1024,
187
+ maxTotalBytes: 64 * 1024 * 1024,
188
+ caseSensitive: true
189
+ });
190
+ const next = new Set(validated.map((file) => file.path));
191
+ let publishedNext = next;
192
+ if (project !== undefined) {
193
+ if (expectedBaseFiles === undefined || !Array.isArray(project) || project.length > 2048)
194
+ throw new TypeError('Invalid workspace delta metadata');
195
+ // Keep whole-project path/count/size admission without sending unchanged bodies.
196
+ const paths = validateWorkspaceFiles(project.map((file) => ({ path: file.path, content: '' })), { maxFiles: 2048, caseSensitive: true });
197
+ const sizes = new Map();
198
+ let total = 0;
199
+ for (let index = 0; index < paths.length; index++) {
200
+ const size = project[index].bytes;
201
+ if (!Number.isSafeInteger(size) || size < 0 || size > 16 * 1024 * 1024)
202
+ throw new TypeError('Invalid workspace file size');
203
+ total += size;
204
+ sizes.set(paths[index].path, size);
205
+ }
206
+ if (total > 64 * 1024 * 1024)
207
+ throw new TypeError('Workspace exceeds total size limit');
208
+ for (const file of validated) {
209
+ const size = typeof file.content === 'string'
210
+ ? encoder.encode(file.content).length
211
+ : file.content.length;
212
+ if (sizes.get(file.path) !== size)
213
+ throw new TypeError('Workspace delta size mismatch');
214
+ }
215
+ publishedNext = new Set(sizes.keys());
216
+ }
217
+ const asBytes = (content) => typeof content === 'string' ? encoder.encode(content) : content;
218
+ const equal = (left, right) => left === undefined || right === undefined
219
+ ? left === right
220
+ : left.length === right.length &&
221
+ left.every((byte, index) => byte === right[index]);
222
+ const current = (name) => {
223
+ try {
224
+ return this.fs.readFile(name, { root: path, cwd: path });
225
+ }
226
+ catch (error) {
227
+ if (error.code !== 'ENOENT')
228
+ throw error;
229
+ return undefined;
230
+ }
231
+ };
232
+ const base = expectedBaseFiles === undefined
233
+ ? undefined
234
+ : new Map(validateWorkspaceFiles(expectedBaseFiles, {
235
+ maxFiles: 2048,
236
+ maxFileBytes: 16 * 1024 * 1024,
237
+ maxTotalBytes: 64 * 1024 * 1024,
238
+ caseSensitive: true
239
+ }).map((file) => [file.path, asBytes(file.content)]));
240
+ const previousPaths = base?.keys() ?? this.#published.get(language) ?? [];
241
+ const deletions = [...previousPaths].filter((previous) => !next.has(previous));
242
+ if (project && deletions.some((name) => publishedNext.has(name)))
243
+ throw new TypeError('Deleted workspace file remains in project metadata');
244
+ // Compare all touched files before publishing even the first edit. Shell-created
245
+ // paths outside the editor's baseline are retained unless explicitly supplied.
246
+ if (base) {
247
+ for (const file of validated) {
248
+ const before = base.get(file.path), after = asBytes(file.content);
249
+ if (equal(before, after))
250
+ continue;
251
+ const present = current(file.path);
252
+ if (!equal(present, before) && !equal(present, after))
253
+ throw new ContainerError('FILESYSTEM_CONFLICT', `Workspace changed while editing ${file.path}`);
254
+ }
255
+ for (const file of deletions)
256
+ if (current(file) !== undefined && !equal(current(file), base.get(file)))
257
+ throw new ContainerError('FILESYSTEM_CONFLICT', `Workspace changed before deleting ${file}`);
258
+ }
259
+ this.fs.applyFileChanges({
260
+ remove: deletions,
261
+ write: validated
262
+ // Unchanged editor buffers must not overwrite newer shell revisions.
263
+ .filter((file) => !base?.has(file.path) ||
264
+ !equal(base.get(file.path), asBytes(file.content)))
265
+ .map((file) => ({ path: file.path, bytes: asBytes(file.content) }))
266
+ }, { root: path, cwd: path, createRoot: true });
267
+ this.#published.set(language, publishedNext);
268
+ }
269
+ readWorkspaceDelta(language, since) {
270
+ const root = this.directory(language);
271
+ const previous = this.#workspaceReads.get(language);
272
+ const reset = !previous || since !== previous.revision;
273
+ const versions = new Map();
274
+ const files = [];
275
+ const visit = (path) => {
276
+ for (const name of this.fs.readdir(path || '.', { root, cwd: root })) {
277
+ const relative = path ? `${path}/${name}` : name;
278
+ const options = { root, cwd: root };
279
+ const stat = this.fs.lstat(relative, options);
280
+ if (stat.type === 'directory')
281
+ visit(relative);
282
+ else if (stat.type === 'file') {
283
+ const version = this.fs.captureFileVersion(relative, options);
284
+ versions.set(relative, version);
285
+ if (reset || previous?.versions.get(relative) !== version)
286
+ files.push({
287
+ path: relative,
288
+ content: this.fs.readFile(relative, options)
289
+ });
290
+ }
291
+ }
292
+ };
293
+ visit('');
294
+ const deleted = reset
295
+ ? []
296
+ : [...previous.versions.keys()].filter((path) => !versions.has(path));
297
+ const revision = (previous?.revision ?? 0) + 1;
298
+ this.#workspaceReads.set(language, { revision, versions });
299
+ return { revision, reset, files, deleted };
300
+ }
301
+ readWorkspace(language) {
302
+ const root = this.directory(language), files = [];
303
+ const visit = (path) => {
304
+ for (const name of this.fs.readdir(path || '.', { root, cwd: root })) {
305
+ const relative = path ? `${path}/${name}` : name;
306
+ const stat = this.fs.lstat(relative, { root, cwd: root });
307
+ if (stat.type === 'directory')
308
+ visit(relative);
309
+ else if (stat.type === 'file')
310
+ files.push({
311
+ path: relative,
312
+ content: this.fs.readFile(relative, { root, cwd: root })
313
+ });
314
+ }
315
+ };
316
+ visit('');
317
+ return files;
318
+ }
319
+ /** Enumerate the common namespace without copying file bodies or following links. */
320
+ listWorkspaceFiles() {
321
+ const entries = [];
322
+ const options = { root: '/workspace', cwd: '/workspace' };
323
+ const visit = (parent) => {
324
+ for (const name of this.fs.readdir(parent || '.', options)) {
325
+ const path = parent ? `${parent}/${name}` : name;
326
+ const stat = this.fs.lstat(path, options);
327
+ if (stat.type !== 'file' && stat.type !== 'directory' && stat.type !== 'symlink')
328
+ continue;
329
+ entries.push({ path, type: stat.type, size: stat.size });
330
+ if (stat.type === 'directory')
331
+ visit(path);
332
+ }
333
+ };
334
+ visit('');
335
+ return entries;
336
+ }
337
+ inputs(language, code, options) {
338
+ const root = this.directory(language);
339
+ const activePath = normalizeWorkspacePath(options.activePath ?? defaultSource(language));
340
+ try {
341
+ this.fs.stat(activePath, { root, cwd: root });
342
+ }
343
+ catch (error) {
344
+ if (error.code !== 'ENOENT')
345
+ throw error;
346
+ this.syncWorkspace(language, [
347
+ ...new Map([...(options.workspaceFiles ?? []), { path: activePath, content: code }].map((entry) => [entry.path, entry])).values()
348
+ ]);
349
+ }
350
+ const files = this.readWorkspace(language);
351
+ return {
352
+ code: new TextDecoder('utf-8', { fatal: true }).decode(this.fs.readFile(activePath, { root, cwd: root })),
353
+ options: {
354
+ ...options,
355
+ activePath,
356
+ workspaceFiles: files
357
+ }
358
+ };
359
+ }
360
+ async execute(method, language, code = '', log = true, args = [], options = {}, signal, progress, requestId = 0) {
361
+ const session = this.session(language);
362
+ if (session.active)
363
+ throw new ContainerError('RESOURCE_LIMIT', `${language} already has an active runtime job`);
364
+ const source = this.inputs(language, code, options);
365
+ const job = {
366
+ id: String(++this.#nextJob),
367
+ language,
368
+ method,
369
+ code: source.code,
370
+ log,
371
+ args: [...args],
372
+ options: source.options,
373
+ signal,
374
+ progress,
375
+ requestId
376
+ };
377
+ session.active = job;
378
+ this.#jobs.set(job.id, job);
379
+ try {
380
+ const process = await this.#container.spawn(COMMAND, [job.id], {
381
+ cwd: this.directory(language),
382
+ env: options.env,
383
+ signal
384
+ });
385
+ job.process = process;
386
+ const drain = async (stream) => {
387
+ const reader = stream.getReader(), text = new TextDecoder();
388
+ try {
389
+ for (;;) {
390
+ const { value, done } = await reader.read();
391
+ if (done)
392
+ break;
393
+ const data = text.decode(value, { stream: true });
394
+ if (data)
395
+ this.settings.emit({ language, name: 'output', data, requestId });
396
+ }
397
+ const tail = text.decode();
398
+ if (tail)
399
+ this.settings.emit({ language, name: 'output', data: tail, requestId });
400
+ }
401
+ finally {
402
+ reader.releaseLock();
403
+ }
404
+ };
405
+ const [result] = await Promise.all([
406
+ process.exited,
407
+ drain(process.stdout),
408
+ drain(process.stderr)
409
+ ]);
410
+ if (signal.aborted)
411
+ throw signal.reason ?? new DOMException('Runtime cancelled', 'AbortError');
412
+ if (job.error)
413
+ throw job.error;
414
+ if (result.reason !== 'exited')
415
+ throw new Error(`Runtime ended with ${result.reason}`);
416
+ return method === 'load' ? undefined : (job.result ?? result.code === 0);
417
+ }
418
+ finally {
419
+ if (session.active === job)
420
+ session.active = undefined;
421
+ this.#jobs.delete(job.id);
422
+ }
423
+ }
424
+ async flushInput(session, sandbox) {
425
+ if (!session.active?.readyForInput)
426
+ return;
427
+ for (const value of session.pendingInput.splice(0))
428
+ sandbox.write?.(value);
429
+ session.pendingBytes = 0;
430
+ if (session.pendingEof) {
431
+ session.pendingEof = false;
432
+ sandbox.eof();
433
+ }
434
+ }
435
+ async write(language, value) {
436
+ if (typeof value !== 'string')
437
+ throw new TypeError('Runtime input must be text');
438
+ const session = this.session(language);
439
+ if (session.pendingEof)
440
+ throw new Error('Runtime input is closed');
441
+ const size = encoder.encode(value).byteLength;
442
+ if (session.pendingBytes + size > 8 * 1024 * 1024)
443
+ throw new Error('Pending runtime input exceeds the container limit');
444
+ session.pendingInput.push(value);
445
+ session.pendingBytes += size;
446
+ if (session.active?.readyForInput)
447
+ await this.flushInput(session, await session.sandbox);
448
+ }
449
+ async eof(language) {
450
+ const session = this.session(language);
451
+ session.pendingEof = true;
452
+ if (session.active?.readyForInput)
453
+ await this.flushInput(session, await session.sandbox);
454
+ }
455
+ async stop(language) {
456
+ const session = this.#sessions.get(language);
457
+ if (!session)
458
+ return;
459
+ session.pendingInput.length = 0;
460
+ session.pendingBytes = 0;
461
+ session.pendingEof = false;
462
+ await Promise.all([
463
+ session.active?.process?.terminate(),
464
+ session.sandbox.then((sandbox) => sandbox.terminate()).catch(() => { })
465
+ ]);
466
+ }
467
+ async clear(language) {
468
+ await (await this.session(language).sandbox).clear();
469
+ }
470
+ async restart(language) {
471
+ await this.stop(language);
472
+ const session = this.#sessions.get(language);
473
+ this.#sessions.delete(language);
474
+ await session?.binding.dispose?.();
475
+ }
476
+ async debug(language, method, args) {
477
+ const allowed = new Set([
478
+ 'debugCommand',
479
+ 'debugPause',
480
+ 'setBreakpoints',
481
+ 'setSourceBreakpoints',
482
+ 'debugEvaluate',
483
+ 'debugEvaluateValue',
484
+ 'debugSetSteppingOptions',
485
+ 'debugVariables',
486
+ 'debugScopes',
487
+ 'debugFrameScopes',
488
+ 'debugFrameName',
489
+ 'debugReadMemory',
490
+ 'debugWriteMemory',
491
+ 'debugDataBreakpointInfo',
492
+ 'debugSetDataBreakpoints'
493
+ ]);
494
+ if (!allowed.has(method))
495
+ throw new TypeError('Unknown debugger method');
496
+ const specifications = method === 'setSourceBreakpoints'
497
+ ? normalizeDebugSourceBreakpoints(args[0])
498
+ : undefined;
499
+ const sourcePath = specifications ? args[1] : undefined;
500
+ if (sourcePath !== undefined && typeof sourcePath !== 'string')
501
+ throw new TypeError('Invalid debugger source path');
502
+ const sandbox = await this.session(language).sandbox;
503
+ const handler = sandbox[method];
504
+ if (specifications &&
505
+ typeof handler !== 'function' &&
506
+ typeof sandbox.setBreakpoints === 'function') {
507
+ assertDebugBreakpointSupport(specifications, {});
508
+ return await sandbox.setBreakpoints(specifications
509
+ .filter((value) => value.enabled !== false)
510
+ .map((value) => value.line), sourcePath);
511
+ }
512
+ if (typeof handler !== 'function')
513
+ throw new Error(`The ${language} runtime does not support ${method}`);
514
+ return await handler.apply(sandbox, specifications ? [specifications, sourcePath] : args);
515
+ }
516
+ inspect() {
517
+ return [...this.#jobs.values()].map((job) => ({
518
+ language: job.language,
519
+ pid: job.process?.pid,
520
+ phase: job.method,
521
+ filesystem: this.filesystemProfile
522
+ }));
523
+ }
524
+ async dispose() {
525
+ if (this.#disposed)
526
+ return;
527
+ this.#disposed = true;
528
+ await Promise.allSettled([...this.#sessions.values()].map(async (session) => {
529
+ await session.active?.process?.terminate();
530
+ await session.binding.dispose?.();
531
+ }));
532
+ this.#sessions.clear();
533
+ this.#jobs.clear();
534
+ this.#workspaceReads.clear();
535
+ }
536
+ }
537
+ export { ContainerRuntimeAdapter as WebsiteRuntimeAdapter };
@@ -0,0 +1,49 @@
1
+ import type { CommandDefinition, HostCommandInvocation, LiveCommandAdapter, MemoryFileSystem } from '@wasm-idle/container';
2
+ export declare const SHELL_CONTROL_COMMAND = "wasm-idle-shell-control";
3
+ export declare const SHELL_CONTROL_FUNCTION_ENV = "BASH_FUNC___wasm_idle_poll%%";
4
+ export declare const SHELL_CONTROL_ROUTE = "/usr/local/bin/wasm-idle-shell-control";
5
+ export declare const SHELL_CONTROL_MOUNT = "/usr/share/wasm-idle-shell-control";
6
+ export declare const SHELL_CONTROL_RCFILE = "/usr/share/wasm-idle-shell-control/rcfile";
7
+ export declare const SHELL_CONTROL_REQUEST = "/tmp/.wasm-idle-shell-control-request";
8
+ export interface ShellControlInspection {
9
+ readonly ready: boolean;
10
+ readonly disposed: boolean;
11
+ /** Last cwd confirmed by the actual shell host invocation, or the host's initial cwd. */
12
+ readonly cwd: string;
13
+ readonly pendingCwd: string | null;
14
+ readonly generation: number;
15
+ readonly appliedGeneration: number;
16
+ readonly error: string | null;
17
+ }
18
+ export interface ShellControlOptions {
19
+ languages: readonly string[];
20
+ initialDirectory?: string;
21
+ onChange?: (inspection: ShellControlInspection) => void;
22
+ /** Trusted deterministic protocol fixture input; never read from guest messages. */
23
+ session?: string;
24
+ }
25
+ /** Host directory requests are read only at the producer's real primary-prompt boundary. */
26
+ export declare function createShellControl(options: ShellControlOptions): Readonly<{
27
+ adapter: LiveCommandAdapter;
28
+ commands: Readonly<Record<string, CommandDefinition>>;
29
+ route: Readonly<{
30
+ path: "/usr/local/bin/wasm-idle-shell-control";
31
+ command: "wasm-idle-shell-control";
32
+ }>;
33
+ setup(fs: MemoryFileSystem): Readonly<{
34
+ mountPath: "/usr/share/wasm-idle-shell-control";
35
+ rcfilePath: "/usr/share/wasm-idle-shell-control/rcfile";
36
+ requestPath: "/tmp/.wasm-idle-shell-control-request";
37
+ args: readonly string[];
38
+ env: Readonly<{
39
+ WASM_IDLE_SHELL_CONTROL: "1";
40
+ INPUTRC: "/tmp/.wasm-idle-shell-inputrc";
41
+ "BASH_FUNC___wasm_idle_poll%%": `() ${string}`;
42
+ }>;
43
+ }>;
44
+ requestDirectory(language: string): Promise<void>;
45
+ requestPrompt(action: "suspend" | "resume", signal?: AbortSignal): Promise<void>;
46
+ onInvocation(invocation: HostCommandInvocation): number | undefined;
47
+ inspect: () => ShellControlInspection;
48
+ dispose(): void;
49
+ }>;