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,360 @@
1
+ export const SHELL_CONTROL_COMMAND = 'wasm-idle-shell-control';
2
+ export const SHELL_CONTROL_FUNCTION_ENV = 'BASH_FUNC___wasm_idle_poll%%';
3
+ export const SHELL_CONTROL_ROUTE = `/usr/local/bin/${SHELL_CONTROL_COMMAND}`;
4
+ export const SHELL_CONTROL_MOUNT = '/usr/share/wasm-idle-shell-control';
5
+ export const SHELL_CONTROL_RCFILE = `${SHELL_CONTROL_MOUNT}/rcfile`;
6
+ export const SHELL_CONTROL_REQUEST = '/tmp/.wasm-idle-shell-control-request';
7
+ const SHELL_INPUTRC = '/tmp/.wasm-idle-shell-inputrc';
8
+ const ADAPTER = 'website-shell-control-v1';
9
+ const MAX_GENERATION = 2147483647;
10
+ const encoder = new TextEncoder();
11
+ const abortError = (message) => new DOMException(message, 'AbortError');
12
+ const canonicalDirectory = (path) => path.length <= 4096 &&
13
+ path.startsWith('/') &&
14
+ !path.includes('\0') &&
15
+ (path === '/' ||
16
+ path
17
+ .slice(1)
18
+ .split('/')
19
+ .every((part) => part && part !== '.' && part !== '..'));
20
+ function rcfile(session, languages) {
21
+ return [
22
+ '# Trusted application rcfile. The mailbox is data and is never evaluated.',
23
+ '__wasm_idle_poll() {',
24
+ ' local __wic_version __wic_session __wic_generation __wic_language __wic_extra __wic_oldpwd __wic_fd',
25
+ ` local __wic_expected_session='${session}'`,
26
+ // WASIX dup2 restoration loses stdin's polling rights. Read through a fresh
27
+ // descriptor instead of temporarily replacing the live terminal's fd 0.
28
+ ` [[ -f '${SHELL_CONTROL_REQUEST}' && -r '${SHELL_CONTROL_REQUEST}' ]] || return 0`,
29
+ ` if builtin exec {__wic_fd}< '${SHELL_CONTROL_REQUEST}'; then :; else return 0; fi`,
30
+ ' if IFS=\' \' builtin read -r -n 160 -u "$__wic_fd" __wic_version __wic_session __wic_generation __wic_language __wic_extra; then',
31
+ ' builtin exec {__wic_fd}<&-',
32
+ ' else',
33
+ ' builtin exec {__wic_fd}<&-',
34
+ ' return 0',
35
+ ' fi',
36
+ ' [[ "$__wic_session" == "$__wic_expected_session" && -z "$__wic_extra" ]] || return 0',
37
+ ' [[ "$__wic_generation" =~ ^[1-9][0-9]{0,9}$ ]] || return 0',
38
+ ` (( __wic_generation <= ${MAX_GENERATION} && __wic_generation > \${__wasm_idle_control_generation:-0} )) || return 0`,
39
+ ' if [[ "$__wic_version" == 2 ]]; then',
40
+ ' case "$__wic_language" in suspend|resume) ;; *) return 0 ;; esac',
41
+ ' __wasm_idle_control_generation=$__wic_generation',
42
+ // Output belongs to the actual shell, while its editing buffer remains untouched.
43
+ ' builtin printf "\\r\\n"',
44
+ ` if '${SHELL_CONTROL_ROUTE}' 2 "$__wic_session" "$__wic_generation" "$__wic_language" ok; then :; else :; fi`,
45
+ // The pinned native hook decodes PS1 and redraws the preserved Readline buffer.
46
+ ' [[ "$__wic_language" == resume ]] && return 124',
47
+ ' return 0',
48
+ ' fi',
49
+ ' [[ "$__wic_version" == 1 ]] || return 0',
50
+ ` case "$__wic_language" in ${languages.join('|')}) ;; *) return 0 ;; esac`,
51
+ ' __wasm_idle_control_generation=$__wic_generation',
52
+ ' __wic_oldpwd=$PWD',
53
+ ' if builtin cd -P -- "/workspace/$__wic_language"; then',
54
+ ` if '${SHELL_CONTROL_ROUTE}' 1 "$__wic_session" "$__wic_generation" "$__wic_language" ok; then :; else :; fi`,
55
+ ' if [[ "$__wic_oldpwd" != "$PWD" ]]; then',
56
+ ' builtin printf "\\r\\n"',
57
+ ' return 124',
58
+ ' fi',
59
+ ' else',
60
+ ` if '${SHELL_CONTROL_ROUTE}' 1 "$__wic_session" "$__wic_generation" "$__wic_language" failed; then :; else :; fi`,
61
+ ' fi',
62
+ ' return 0',
63
+ '}',
64
+ // The native primary Readline hook preserves both $? and PIPESTATUS.
65
+ // A PROMPT_COMMAND wrapper cannot restore PIPESTATUS and must not own polling.
66
+ 'readonly -f __wasm_idle_poll',
67
+ ''
68
+ ].join('\n');
69
+ }
70
+ /** Host directory requests are read only at the producer's real primary-prompt boundary. */
71
+ export function createShellControl(options) {
72
+ const languages = [...new Set(options.languages)].sort();
73
+ if (!languages.length || languages.some((language) => !/^[A-Z][A-Z0-9_]{0,63}$/.test(language)))
74
+ throw new Error('Shell control requires a fixed language allowlist');
75
+ const allowed = new Set(languages);
76
+ const session = options.session ??
77
+ Array.from(crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, '0')).join('');
78
+ if (!/^[a-f0-9]{32}$/.test(session))
79
+ throw new Error('Invalid shell control session');
80
+ let cwd = options.initialDirectory ?? '/workspace';
81
+ if (cwd !== '/workspace' && !languages.some((language) => cwd === `/workspace/${language}`))
82
+ throw new Error('Invalid initial shell directory');
83
+ let filesystem, disposed = false, generation = 0, appliedGeneration = 0;
84
+ let pending, error = null;
85
+ let lastAcknowledgement;
86
+ const inspect = () => Object.freeze({
87
+ ready: Boolean(filesystem),
88
+ disposed,
89
+ cwd,
90
+ pendingCwd: pending?.cwd ?? null,
91
+ generation,
92
+ appliedGeneration,
93
+ error
94
+ });
95
+ const changed = () => {
96
+ try {
97
+ options.onChange?.(inspect());
98
+ }
99
+ catch {
100
+ /* Observers do not own protocol state. */
101
+ }
102
+ };
103
+ const currentFilesystem = () => {
104
+ if (disposed)
105
+ throw new Error('Shell directory control has been disposed');
106
+ if (!filesystem)
107
+ throw new Error('Shell directory control has not been set up');
108
+ return filesystem;
109
+ };
110
+ const ensureDirectory = (fs, path) => {
111
+ if (fs.lstat('/workspace').type !== 'directory' ||
112
+ fs.realpath('/workspace') !== '/workspace')
113
+ throw new Error('Workspace root is not a directory');
114
+ try {
115
+ if (fs.lstat(path).type !== 'directory' || fs.realpath(path) !== path)
116
+ throw new Error('Shell directory must be an actual project directory');
117
+ }
118
+ catch (reason) {
119
+ if (reason.code !== 'ENOENT')
120
+ throw reason;
121
+ fs.mkdir(path);
122
+ }
123
+ };
124
+ const writeRequest = (fs, value) => {
125
+ if (fs.lstat('/tmp').type !== 'directory' || fs.realpath('/tmp') !== '/tmp')
126
+ throw new Error('Shell control needs the private temporary mount');
127
+ try {
128
+ if (fs.lstat(SHELL_CONTROL_REQUEST).type !== 'file')
129
+ throw new Error('Shell control mailbox must be a regular file');
130
+ }
131
+ catch (reason) {
132
+ if (reason.code !== 'ENOENT')
133
+ throw reason;
134
+ }
135
+ fs.writeFile(SHELL_CONTROL_REQUEST, encoder.encode(value), { mode: 0o600 });
136
+ };
137
+ const acknowledge = (args, actualCwd) => {
138
+ if (disposed ||
139
+ !filesystem ||
140
+ args.length !== 5 ||
141
+ !['1', '2'].includes(args[0]) ||
142
+ args[1] !== session ||
143
+ !/^[1-9][0-9]{0,9}$/.test(args[2]) ||
144
+ !(args[0] === '1' ? allowed.has(args[3]) : ['suspend', 'resume'].includes(args[3])) ||
145
+ !['ok', 'failed'].includes(args[4]) ||
146
+ !canonicalDirectory(actualCwd))
147
+ return 126;
148
+ const version = args[0], received = Number(args[2]), target = args[3], verdict = args[4];
149
+ if (version === '1' && verdict === 'ok' && actualCwd !== `/workspace/${target}`)
150
+ return 126;
151
+ if (received > MAX_GENERATION || received > generation)
152
+ return 126;
153
+ if (received < generation)
154
+ return 0; // A superseded completion cannot publish the new request.
155
+ if (!pending)
156
+ return lastAcknowledgement?.version === version &&
157
+ lastAcknowledgement.generation === received &&
158
+ lastAcknowledgement.target === target &&
159
+ lastAcknowledgement.cwd === actualCwd &&
160
+ lastAcknowledgement.verdict === verdict
161
+ ? 0
162
+ : 126;
163
+ if (pending.version !== version ||
164
+ pending.target !== target ||
165
+ (pending.cwd && verdict === 'ok' && actualCwd !== pending.cwd))
166
+ return 126;
167
+ const completed = pending;
168
+ pending = undefined;
169
+ completed.removeAbort?.();
170
+ cwd = actualCwd;
171
+ lastAcknowledgement = { version, generation: received, target, cwd: actualCwd, verdict };
172
+ if (verdict === 'ok') {
173
+ appliedGeneration = received;
174
+ error = null;
175
+ completed.resolve();
176
+ }
177
+ else {
178
+ error = `Bash could not enter ${completed.cwd}`;
179
+ completed.reject(new Error(error));
180
+ }
181
+ changed();
182
+ return 0;
183
+ };
184
+ const request = (version, target, signal) => {
185
+ try {
186
+ const fs = currentFilesystem();
187
+ signal?.throwIfAborted();
188
+ if (version === '1' ? !allowed.has(target) : !['suspend', 'resume'].includes(target))
189
+ throw new Error('Unknown shell control target');
190
+ if (pending?.version === version && pending.target === target)
191
+ return pending.promise;
192
+ if (generation === MAX_GENERATION)
193
+ throw new Error('Shell control generation exhausted');
194
+ const targetCwd = version === '1' ? `/workspace/${target}` : undefined, nextGeneration = generation + 1;
195
+ if (targetCwd)
196
+ ensureDirectory(fs, targetCwd);
197
+ writeRequest(fs, `${version} ${session} ${nextGeneration} ${target}\n`);
198
+ pending?.removeAbort?.();
199
+ pending?.reject(abortError('Shell control request was superseded'));
200
+ let resolve, reject;
201
+ const promise = new Promise((yes, no) => {
202
+ resolve = yes;
203
+ reject = no;
204
+ });
205
+ const next = {
206
+ version,
207
+ target,
208
+ cwd: targetCwd,
209
+ promise,
210
+ resolve,
211
+ reject
212
+ };
213
+ pending = next;
214
+ generation = nextGeneration;
215
+ error = null;
216
+ if (signal) {
217
+ const abort = () => {
218
+ if (pending !== next)
219
+ return;
220
+ pending = undefined;
221
+ next.removeAbort?.();
222
+ // A foreground command must not receive control on its eventual return.
223
+ try {
224
+ writeRequest(fs, `1 ${session} 0 -\n`);
225
+ }
226
+ catch {
227
+ /* Preserve the cancellation if the guest has removed its mailbox. */
228
+ }
229
+ reject(signal.reason ?? abortError('Shell control request was cancelled'));
230
+ changed();
231
+ };
232
+ signal.addEventListener('abort', abort, { once: true });
233
+ next.removeAbort = () => signal.removeEventListener('abort', abort);
234
+ }
235
+ changed();
236
+ return promise;
237
+ }
238
+ catch (reason) {
239
+ return Promise.reject(reason);
240
+ }
241
+ };
242
+ const adapter = {
243
+ id: ADAPTER,
244
+ filesystem: 'live',
245
+ async start(request) {
246
+ if (request.fs !== currentFilesystem() ||
247
+ request.invocation.command !== SHELL_CONTROL_COMMAND)
248
+ throw new Error('Shell control command belongs to a different container');
249
+ const emptyOutput = () => new ReadableStream({
250
+ start(controller) {
251
+ controller.close();
252
+ }
253
+ });
254
+ return {
255
+ stdin: new WritableStream({
256
+ write(bytes) {
257
+ if (bytes.length)
258
+ throw new Error('Shell control does not consume program input');
259
+ }
260
+ }),
261
+ stdout: emptyOutput(),
262
+ stderr: emptyOutput(),
263
+ async run() {
264
+ return {
265
+ code: request.signal.aborted
266
+ ? 143
267
+ : acknowledge(request.invocation.args, request.invocation.cwd)
268
+ };
269
+ },
270
+ async dispose() { }
271
+ };
272
+ }
273
+ };
274
+ const commands = Object.freeze({
275
+ [SHELL_CONTROL_COMMAND]: Object.freeze({
276
+ adapter: ADAPTER,
277
+ bytes: new Uint8Array(),
278
+ argv0: SHELL_CONTROL_COMMAND
279
+ })
280
+ });
281
+ const configuration = Object.freeze({
282
+ mountPath: SHELL_CONTROL_MOUNT,
283
+ rcfilePath: SHELL_CONTROL_RCFILE,
284
+ requestPath: SHELL_CONTROL_REQUEST,
285
+ // The pinned WASIX host requests inherited write access even for O_RDONLY.
286
+ // Standard Bash function import bootstraps the trusted body without opening
287
+ // a readonly file; the opt-in producer makes this one imported function readonly.
288
+ args: Object.freeze(['--noprofile', '--norc', '-i']),
289
+ env: Object.freeze({
290
+ WASM_IDLE_SHELL_CONTROL: '1',
291
+ INPUTRC: SHELL_INPUTRC,
292
+ [SHELL_CONTROL_FUNCTION_ENV]: `() ${rcfile(session, languages).match(/__wasm_idle_poll\(\) (\{[\s\S]*?\n\})/)[1]}`
293
+ })
294
+ });
295
+ return Object.freeze({
296
+ adapter,
297
+ commands,
298
+ route: Object.freeze({ path: SHELL_CONTROL_ROUTE, command: SHELL_CONTROL_COMMAND }),
299
+ setup(fs) {
300
+ if (disposed)
301
+ throw new Error('Shell directory control has been disposed');
302
+ if (filesystem) {
303
+ if (filesystem !== fs)
304
+ throw new Error('Shell control cannot share containers');
305
+ return configuration;
306
+ }
307
+ ensureDirectory(fs, cwd);
308
+ writeRequest(fs, `1 ${session} 0 -\n`);
309
+ // The pinned C locale otherwise interprets UTF-8 input as Meta keys.
310
+ // Keep this on the writable mount: WASIX overrequests rights on open.
311
+ fs.writeFile(SHELL_INPUTRC, encoder.encode('set input-meta on\nset convert-meta off\nset output-meta on\n'), { mode: 0o600 });
312
+ fs.mountReadonly(SHELL_CONTROL_MOUNT, [
313
+ {
314
+ path: 'rcfile',
315
+ type: 'file',
316
+ mode: 0o444,
317
+ data: encoder.encode(rcfile(session, languages))
318
+ }
319
+ ]);
320
+ filesystem = fs;
321
+ changed();
322
+ return configuration;
323
+ },
324
+ requestDirectory(language) {
325
+ if (!allowed.has(language))
326
+ return Promise.reject(new Error('Unknown shell project directory'));
327
+ return request('1', language);
328
+ },
329
+ requestPrompt(action, signal) {
330
+ return request('2', action, signal);
331
+ },
332
+ onInvocation(invocation) {
333
+ return invocation.path === SHELL_CONTROL_ROUTE
334
+ ? acknowledge(invocation.argv.slice(1), invocation.cwd)
335
+ : undefined;
336
+ },
337
+ inspect,
338
+ dispose() {
339
+ if (disposed)
340
+ return;
341
+ disposed = true;
342
+ pending?.removeAbort?.();
343
+ pending?.reject(abortError('Shell directory control was disposed'));
344
+ pending = undefined;
345
+ if (filesystem) {
346
+ try {
347
+ if (filesystem.lstat(SHELL_CONTROL_REQUEST).type === 'file' &&
348
+ new TextDecoder()
349
+ .decode(filesystem.readFile(SHELL_CONTROL_REQUEST))
350
+ .startsWith(`1 ${session} `))
351
+ filesystem.unlink(SHELL_CONTROL_REQUEST);
352
+ }
353
+ catch {
354
+ /* The guest may already have removed the temporary mailbox. */
355
+ }
356
+ }
357
+ changed();
358
+ }
359
+ });
360
+ }
@@ -0,0 +1,12 @@
1
+ export interface WorkspaceFile {
2
+ path: string;
3
+ content: string;
4
+ encoding?: 'utf-8' | 'data-url';
5
+ }
6
+ /** Reconcile independent terminal edits without discarding an unpublished editor revision. */
7
+ export declare function mergeContainerWorkspace(local: readonly WorkspaceFile[], baseline: readonly WorkspaceFile[], remote: readonly WorkspaceFile[], options?: {
8
+ acceptRemoteConflicts?: boolean;
9
+ }): {
10
+ files: WorkspaceFile[];
11
+ conflicts: string[];
12
+ };
@@ -0,0 +1,29 @@
1
+ const same = (a, b) => a === b ||
2
+ (!!a && !!b && a.content === b.content && (a.encoding ?? 'utf-8') === (b.encoding ?? 'utf-8'));
3
+ /** Reconcile independent terminal edits without discarding an unpublished editor revision. */
4
+ export function mergeContainerWorkspace(local, baseline, remote, options = {}) {
5
+ const localByPath = new Map(local.map((file) => [file.path, file]));
6
+ const baseByPath = new Map(baseline.map((file) => [file.path, file]));
7
+ const remoteByPath = new Map(remote.map((file) => [file.path, file]));
8
+ const conflicts = [];
9
+ const files = [];
10
+ for (const path of new Set([
11
+ ...localByPath.keys(),
12
+ ...baseByPath.keys(),
13
+ ...remoteByPath.keys()
14
+ ])) {
15
+ const here = localByPath.get(path), before = baseByPath.get(path), there = remoteByPath.get(path);
16
+ let selected;
17
+ if (same(here, before))
18
+ selected = there;
19
+ else if (same(there, before) || same(here, there))
20
+ selected = here;
21
+ else {
22
+ conflicts.push(path);
23
+ selected = options.acceptRemoteConflicts ? there : here;
24
+ }
25
+ if (selected)
26
+ files.push({ ...selected });
27
+ }
28
+ return { files, conflicts };
29
+ }
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export { createRuntimeSession } from './playground/runtimeSession';
5
5
  export { configureRuntimeAssetCache, createRuntimeAssetCacheBackend, fetchPinnedRuntimeAsset, prefetchRuntimeAssets, resolveRuntimeAssetLockEntry, type PrefetchRuntimeAssetsOptions, type PrefetchRuntimeAssetsResult, type RuntimeAssetCacheStats, type RuntimeAssetCacheBackend, type RuntimeAssetCacheBackendIdentity, type PinnedRuntimeAssetRequest, getRuntimeAssetCacheOptions, getRuntimeAssetCacheStats, clearRuntimeAssetCache, pruneRuntimeAssetCache, requestRuntimeAssetCachePersistence, type RuntimeAssetCacheOptions } from '@wasm-idle/core';
6
6
  export type { PlaygroundRuntimeSession } from './playground/runtimeSession';
7
7
  export { isSharedArrayBufferAvailable, requireSharedArrayBuffer } from './playground/sharedBuffer';
8
- export type { DebugCommand, DebugFrame, DebugSessionEvent, DebugVariable, TerminalControl } from '@wasm-idle/core';
8
+ export type { DebugCommand, DebugEvaluateOptions, DebugEvaluateResult, DebugSourceBreakpoint, DebugSourceBreakpoints, DebugSteppingOptions, DebugSessionCapabilities, DebugVariablePresentationHint, DebugFrame, DebugSessionEvent, DebugVariable, TerminalControl } from '@wasm-idle/core';
9
9
  export type { CompilerDiagnostic, SandboxExecutionOptions } from './playground/options';
10
10
  export type { PlaygroundRuntimeAssets, RuntimeAssetConfig, RuntimeAssetLoadRequest, RuntimeAssetLoader, RuntimeAssetLoaderResult } from './playground/assets';
11
11
  export type { BoundSandbox, PlaygroundBinding, PlaygroundTerminalProps, SandboxProgress, SandboxRuntimeAssets } from './playground/sandbox';
@@ -1,5 +1,5 @@
1
1
  import { RUNTIME_LOAD_ASSETS } from './assets';
2
- import { ProtocolError, verifyRuntimeAssetIntegrity, verifyRuntimeAssetPair, readPersistentRuntimeAsset, writePersistentRuntimeAsset, resolveRuntimeAssetLockEntry, resolveRuntimeAssetCacheOptions } from '@wasm-idle/core';
2
+ import { ProtocolError, compilePythonRuntimeModule, verifyRuntimeAssetIntegrity, verifyRuntimeAssetPair, readPersistentRuntimeAsset, writePersistentRuntimeAsset, resolveRuntimeAssetLockEntry, resolveRuntimeAssetCacheOptions } from '@wasm-idle/core';
3
3
  import { decompressGzip } from '@wasm-idle/llvm-core';
4
4
  import { readPythonPackageAssets } from './pythonPackageLock';
5
5
  import { BUNDLED_CLANG_LANGUAGE_SYSROOT_PROFILES } from './clangAssetIntegrity';
@@ -201,20 +201,22 @@ const expectedAssetsForRuntime = (runtime, languageSysroots = false) => {
201
201
  }
202
202
  return assets;
203
203
  };
204
- const integrityKey = (config) => JSON.stringify(Object.entries(config.integrity || {})
205
- .sort(([left], [right]) => left.localeCompare(right))
206
- .map(([asset, entry]) => [
207
- asset,
208
- typeof entry === 'string'
209
- ? entry
210
- : {
211
- sha256: entry.sha256,
212
- bytes: entry.bytes,
213
- mediaType: entry.mediaType,
214
- uncompressedSha256: entry.uncompressedSha256,
215
- uncompressedBytes: entry.uncompressedBytes
216
- }
217
- ]));
204
+ // Read the contract fields directly: valid receipts can use inherited or hidden getters.
205
+ const snapshotIntegrityEntry = (receipt) => typeof receipt === 'string'
206
+ ? receipt
207
+ : Object.freeze({
208
+ sha256: receipt.sha256,
209
+ bytes: receipt.bytes,
210
+ mediaType: receipt.mediaType,
211
+ uncompressedSha256: receipt.uncompressedSha256,
212
+ uncompressedBytes: receipt.uncompressedBytes
213
+ });
214
+ const integrityKey = (config) => {
215
+ const integrity = config.integrity || {};
216
+ return JSON.stringify(Object.getOwnPropertyNames(integrity)
217
+ .sort((left, right) => left.localeCompare(right))
218
+ .map((asset) => [asset, snapshotIntegrityEntry(integrity[asset])]));
219
+ };
218
220
  const allowedBaseUrlsKey = (config) => JSON.stringify([...(config.allowedBaseUrls || [])].sort());
219
221
  class RuntimeLoadProgress {
220
222
  samples = new Map();
@@ -550,7 +552,6 @@ export class WorkerAssetBridge {
550
552
  const generation = this.generation;
551
553
  const controller = new AbortController();
552
554
  const progress = this.progress;
553
- const context = this.captureLoadContext();
554
555
  const receiveProgress = (event) => {
555
556
  if (controller.signal.aborted || generation !== this.generation)
556
557
  return;
@@ -561,15 +562,33 @@ export class WorkerAssetBridge {
561
562
  progress.activity(event.phase, event.asset);
562
563
  }
563
564
  };
564
- const loadContext = (report) => ({
565
- ...context,
566
- progress: {
567
- update: (asset, loaded, total) => report({ kind: 'download', asset, loaded, total }, `download:${asset}`),
568
- activity: (phase, asset) => report({ kind: 'activity', asset, phase }, `activity:${asset}`)
565
+ // A rebind to the same worker aborts this load, but that worker still awaits a reply.
566
+ const replySuperseded = () => {
567
+ if (this.state !== 'active' || this.worker !== worker)
568
+ return;
569
+ try {
570
+ worker.postMessage({
571
+ assetResponse: {
572
+ id: request.id,
573
+ ok: false,
574
+ error: `Runtime asset ${request.asset} request was superseded by a rebind`
575
+ }
576
+ });
569
577
  }
570
- });
578
+ catch {
579
+ // The worker may already be terminated.
580
+ }
581
+ };
571
582
  this.activeLoads.add(controller);
572
583
  try {
584
+ const context = this.captureLoadContext();
585
+ const loadContext = (report) => ({
586
+ ...context,
587
+ progress: {
588
+ update: (asset, loaded, total) => report({ kind: 'download', asset, loaded, total }, `download:${asset}`),
589
+ activity: (phase, asset) => report({ kind: 'activity', asset, phase }, `activity:${asset}`)
590
+ }
591
+ });
573
592
  this.validateAssetRequest(loadContext(receiveProgress), request.asset);
574
593
  const identity = [
575
594
  this.runtime,
@@ -641,7 +660,10 @@ export class WorkerAssetBridge {
641
660
  else {
642
661
  const loaded = await loadBytes(signal, (event) => report(event, `${event.kind}:${event.asset}`));
643
662
  bytes = loaded.bytes.byteLength;
644
- module = await WebAssembly.compile(Uint8Array.from(loaded.bytes));
663
+ module =
664
+ this.runtime === 'python' && request.asset === 'pyodide.asm.wasm'
665
+ ? await compilePythonRuntimeModule(loaded.bytes)
666
+ : await WebAssembly.compile(Uint8Array.from(loaded.bytes));
645
667
  }
646
668
  if (signal.aborted)
647
669
  throw runtimeAssetAbortReason(signal);
@@ -650,7 +672,7 @@ export class WorkerAssetBridge {
650
672
  });
651
673
  }
652
674
  if (controller.signal.aborted || generation !== this.generation)
653
- return;
675
+ return replySuperseded();
654
676
  worker.postMessage({ assetResponse: { id: request.id, ok: true, module } });
655
677
  return;
656
678
  }
@@ -659,7 +681,7 @@ export class WorkerAssetBridge {
659
681
  this.pythonPackageAssets = readPythonPackageAssets(loaded.bytes);
660
682
  }
661
683
  if (controller.signal.aborted || generation !== this.generation)
662
- return;
684
+ return replySuperseded();
663
685
  const buffer = transferBuffer(loaded.bytes, this.cache ? false : loaded.transferOwnership);
664
686
  worker.postMessage({
665
687
  assetResponse: {
@@ -672,7 +694,7 @@ export class WorkerAssetBridge {
672
694
  }
673
695
  catch (error) {
674
696
  if (controller.signal.aborted || generation !== this.generation)
675
- return;
697
+ return replySuperseded();
676
698
  try {
677
699
  worker.postMessage({
678
700
  assetResponse: {
@@ -691,8 +713,24 @@ export class WorkerAssetBridge {
691
713
  }
692
714
  }
693
715
  captureLoadContext() {
716
+ const config = { ...this.config };
717
+ const integrity = config.integrity;
718
+ // Cache identity and verification must observe the same receipt, even if a caller
719
+ // updates its configuration while an asynchronous asset load is in progress.
720
+ // The built-in Clang map and its receipts are frozen; its identity also selects
721
+ // verified streaming, so only caller-owned maps need a new snapshot.
722
+ if (integrity && integrity !== BUNDLED_CLANG_ASSET_INTEGRITY) {
723
+ config.integrity = Object.freeze(Object.fromEntries(
724
+ // Authorization accepts own map entries regardless of enumerability.
725
+ Object.getOwnPropertyNames(integrity).map((asset) => [
726
+ asset,
727
+ snapshotIntegrityEntry(integrity[asset])
728
+ ])));
729
+ }
730
+ if (config.allowedBaseUrls)
731
+ config.allowedBaseUrls = [...config.allowedBaseUrls];
694
732
  return {
695
- config: { ...this.config },
733
+ config,
696
734
  maxAssetBytes: this.maxAssetBytes,
697
735
  expectedAssets: new Set(this.expectedAssets),
698
736
  pythonPackageAssets: new Set(this.pythonPackageAssets),
@@ -743,6 +781,7 @@ export class WorkerAssetBridge {
743
781
  throw runtimeAssetAbortReason(signal);
744
782
  if (this.runtime === 'python' && asset === 'pyodide-lock.json')
745
783
  readPythonPackageAssets(runtimeBytes);
784
+ await loaded.persist?.();
746
785
  return {
747
786
  bytes: runtimeBytes,
748
787
  mimeType: loaded.mimeType,
@@ -768,8 +807,10 @@ export class WorkerAssetBridge {
768
807
  if (!signal.aborted)
769
808
  context.progress.update(asset, loaded, total);
770
809
  };
771
- if (context.config.loader) {
772
- const pendingResult = Promise.resolve(context.config.loader({
810
+ // Do not expose the private verification context as a custom loader's receiver.
811
+ const loader = context.config.loader;
812
+ if (loader) {
813
+ const pendingResult = Promise.resolve(loader({
773
814
  runtime: this.runtime,
774
815
  asset,
775
816
  reportProgress,
@@ -930,7 +971,8 @@ export class WorkerAssetBridge {
930
971
  'bridge-v1',
931
972
  context.config.baseUrl,
932
973
  allowedBaseUrlsKey(context.config),
933
- maxAssetBytes
974
+ maxAssetBytes,
975
+ expected?.mediaType
934
976
  ])
935
977
  }
936
978
  : undefined;
@@ -943,13 +985,44 @@ export class WorkerAssetBridge {
943
985
  if (bytes) {
944
986
  requireRuntimeAssetSize(asset, bytes.byteLength, maxAssetBytes);
945
987
  context.progress.update(asset, bytes.byteLength, bytes.byteLength);
946
- return { bytes, mimeType: receipt?.mediaType, transferOwnership: true };
988
+ // A hit was validated against this same expected MIME type before it was stored.
989
+ return {
990
+ bytes,
991
+ mimeType: expected?.mediaType ?? receipt?.mediaType,
992
+ transferOwnership: true
993
+ };
947
994
  }
948
995
  }
949
996
  const loaded = await this.fetchAssetFromNetwork(context, url, asset, signal, maxAssetBytes);
997
+ if (receipt) {
998
+ // Verify even when storage is disabled, unavailable or skipped. A body that the browser
999
+ // HTTP-decoded and that lost its gzip header is checked against the logical receipt.
1000
+ const decoded = !!loaded.contentEncoding && !(loaded.bytes[0] === 0x1f && loaded.bytes[1] === 0x8b);
1001
+ if (decoded && receipt.uncompressedSha256 !== undefined) {
1002
+ await verifyRuntimeAssetIntegrity({
1003
+ asset,
1004
+ bytes: loaded.bytes,
1005
+ expected: {
1006
+ sha256: receipt.sha256,
1007
+ uncompressedSha256: receipt.uncompressedSha256,
1008
+ uncompressedBytes: receipt.uncompressedBytes
1009
+ },
1010
+ stage: 'uncompressed'
1011
+ });
1012
+ }
1013
+ else if (!decoded || !asset.endsWith('.gz')) {
1014
+ // Unpaired receipts for other assets already describe their logical bytes.
1015
+ await verifyRuntimeAssetIntegrity({
1016
+ asset,
1017
+ bytes: loaded.bytes,
1018
+ expected: { sha256: receipt.sha256, bytes: receipt.bytes }
1019
+ });
1020
+ }
1021
+ // A decoded .gz body with an unpaired receipt is left to runtime validation.
1022
+ }
950
1023
  if (identity && !loaded.contentEncoding) {
951
- // Only checksum-matching bytes are published. Existing runtime validation still runs.
952
- await writePersistentRuntimeAsset({
1024
+ // A hit skips the response MIME check, so publish only bytes that passed it.
1025
+ loaded.persist = () => writePersistentRuntimeAsset({
953
1026
  identity,
954
1027
  cache: persistentCache,
955
1028
  signal,
@@ -1177,6 +1250,11 @@ export class WorkerAssetBridge {
1177
1250
  if (url.hash) {
1178
1251
  throw new Error(`Runtime asset ${asset} URL must not include a fragment`);
1179
1252
  }
1253
+ // The prefix check below sees `/base/..%2fother` as inside `/base/`, but a server that
1254
+ // decodes the separator before resolving dot segments serves `/other`.
1255
+ if (/%2f|%5c/iu.test(url.pathname)) {
1256
+ throw new Error(`Runtime asset ${asset} URL must not include encoded path separators`);
1257
+ }
1180
1258
  const allowed = [context.config.baseUrl, ...(context.config.allowedBaseUrls || [])].some((baseUrl) => {
1181
1259
  let base;
1182
1260
  try {