wasm-idle 1.1.2 → 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 (121) hide show
  1. package/README.md +134 -82
  2. package/dist/container/bash-profile.d.ts +80 -0
  3. package/dist/container/bash-profile.js +328 -0
  4. package/dist/{playground/container → container}/binding.d.ts +21 -8
  5. package/dist/{playground/container → container}/binding.js +109 -25
  6. package/dist/{playground/container → container}/clang-runtime.d.ts +11 -7
  7. package/dist/container/clang-runtime.js +561 -0
  8. package/dist/container/client.d.ts +14 -0
  9. package/dist/{playground/container → container}/client.js +2 -6
  10. package/dist/{playground/container → container}/explorer.d.ts +1 -1
  11. package/dist/container/index.d.ts +11 -0
  12. package/dist/container/index.js +11 -0
  13. package/dist/container/owner-worker.d.ts +19 -0
  14. package/dist/container/owner-worker.js +464 -0
  15. package/dist/{playground/container → container}/protocol.d.ts +12 -1
  16. package/dist/{playground/container → container}/runtime-adapter.d.ts +13 -11
  17. package/dist/{playground/container → container}/runtime-adapter.js +104 -41
  18. package/dist/{playground/container → container}/shell-control.d.ts +2 -2
  19. package/dist/{playground/container → container}/shell-control.js +93 -36
  20. package/dist/{playground/container → container}/workspace.d.ts +5 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/playground/assetBridge.js +5 -2
  23. package/dist/playground/assets.d.ts +8 -0
  24. package/dist/playground/clang.d.ts +5 -1
  25. package/dist/playground/clang.js +61 -5
  26. package/dist/playground/compiledLldb.d.ts +41 -0
  27. package/dist/playground/compiledLldb.js +167 -0
  28. package/dist/playground/d.d.ts +4 -1
  29. package/dist/playground/d.js +78 -9
  30. package/dist/playground/debugDeadline.d.ts +12 -0
  31. package/dist/playground/debugDeadline.js +34 -0
  32. package/dist/playground/debugMailbox.d.ts +12 -0
  33. package/dist/playground/debugMailbox.js +77 -0
  34. package/dist/playground/go.js +9 -4
  35. package/dist/playground/goDebugInstrumentation.js +24 -44
  36. package/dist/playground/java-debug-FMHDKUN6.js +124 -0
  37. package/dist/playground/java-debug-notices.txt +492 -0
  38. package/dist/playground/java.d.ts +17 -1
  39. package/dist/playground/java.js +159 -3
  40. package/dist/playground/javaDebug.d.ts +62 -0
  41. package/dist/playground/javaDebug.js +305 -0
  42. package/dist/playground/javaDebugBridge.d.ts +6 -0
  43. package/dist/playground/javaDebugBridge.js +250 -0
  44. package/dist/playground/javaDebugSource.d.ts +9 -0
  45. package/dist/playground/javaDebugSource.js +4 -0
  46. package/dist/playground/javaRuntimeErrors.js +34 -1
  47. package/dist/playground/lean4Assets.d.ts +1 -25
  48. package/dist/playground/lean4Assets.js +2 -123
  49. package/dist/playground/lfortranAssets.d.ts +2 -2
  50. package/dist/playground/lldbSession.d.ts +23 -2
  51. package/dist/playground/lldbSession.js +278 -58
  52. package/dist/playground/lldbSourcePath.d.ts +2 -0
  53. package/dist/playground/lldbSourcePath.js +9 -0
  54. package/dist/playground/lua.d.ts +20 -1
  55. package/dist/playground/lua.js +190 -8
  56. package/dist/playground/luaDebug.d.ts +1 -0
  57. package/dist/playground/luaDebug.js +1 -0
  58. package/dist/playground/nim.d.ts +1 -0
  59. package/dist/playground/nim.js +8 -0
  60. package/dist/playground/objectivec.d.ts +7 -6
  61. package/dist/playground/objectivec.js +75 -9
  62. package/dist/playground/options.d.ts +10 -4
  63. package/dist/playground/python.d.ts +8 -1
  64. package/dist/playground/python.js +81 -6
  65. package/dist/playground/ruby.d.ts +10 -1
  66. package/dist/playground/ruby.js +66 -1
  67. package/dist/playground/rubyDebug.d.ts +21 -0
  68. package/dist/playground/rubyDebug.js +128 -0
  69. package/dist/playground/rust.d.ts +5 -1
  70. package/dist/playground/rust.js +128 -46
  71. package/dist/playground/sandbox.d.ts +8 -1
  72. package/dist/playground/staticWorkerRuntime.js +8 -2
  73. package/dist/playground/stdinBuffer.d.ts +1 -1
  74. package/dist/playground/stdinBuffer.js +19 -2
  75. package/dist/playground/tinygo.js +7 -0
  76. package/dist/playground/typescript.js +8 -0
  77. package/dist/playground/v.d.ts +3 -2
  78. package/dist/playground/v.js +66 -12
  79. package/dist/playground/wasmC3Version.d.ts +2 -2
  80. package/dist/playground/wasmC3Version.js +2 -2
  81. package/dist/playground/wasmLean4Version.d.ts +1 -110
  82. package/dist/playground/wasmLean4Version.js +2 -111
  83. package/dist/playground/wasmLfortranVersion.d.ts +2 -2
  84. package/dist/playground/wasmLfortranVersion.js +2 -2
  85. package/dist/playground/wasmLuaVersion.d.ts +1 -1
  86. package/dist/playground/wasmLuaVersion.js +1 -1
  87. package/dist/playground/wasmRustVersion.d.ts +26 -38
  88. package/dist/playground/wasmRustVersion.js +25 -40
  89. package/dist/playground/worker/clang.js +1 -1
  90. package/dist/playground/worker/cobol.js +1 -1
  91. package/dist/playground/worker/d.js +51 -2
  92. package/dist/playground/worker/fortran.js +1 -1
  93. package/dist/playground/worker/java.js +188 -35
  94. package/dist/playground/worker/javaDebugEvaluator.d.ts +16 -0
  95. package/dist/playground/worker/javaDebugEvaluator.js +44 -0
  96. package/dist/playground/worker/javaDebugRuntime.d.ts +24 -0
  97. package/dist/playground/worker/javaDebugRuntime.js +315 -0
  98. package/dist/playground/worker/javaOutput.d.ts +11 -0
  99. package/dist/playground/worker/javaOutput.js +54 -0
  100. package/dist/playground/worker/lua.js +13 -0
  101. package/dist/playground/worker/python.js +57 -22
  102. package/dist/playground/worker/ruby.js +13 -0
  103. package/dist/playground/worker/rubyDebugPreview.d.ts +2 -0
  104. package/dist/playground/worker/rubyDebugPreview.js +80 -0
  105. package/dist/playground/worker/rubyTracepoint.d.ts +16 -0
  106. package/dist/playground/worker/rubyTracepoint.js +162 -0
  107. package/dist/playground/worker/rust.js +4 -1
  108. package/dist/playground/worker/v.js +30 -5
  109. package/dist/playground/zig.js +4 -0
  110. package/package.json +55 -11
  111. package/dist/playground/container/ContainerExplorer.svelte +0 -307
  112. package/dist/playground/container/ContainerExplorer.svelte.d.ts +0 -14
  113. package/dist/playground/container/clang-runtime.js +0 -343
  114. package/dist/playground/container/client.d.ts +0 -15
  115. package/dist/playground/container/owner.worker.d.ts +0 -1
  116. package/dist/playground/container/owner.worker.js +0 -390
  117. package/dist/playground/container/release.d.ts +0 -31
  118. package/dist/playground/container/release.js +0 -612
  119. /package/dist/{playground/container → container}/explorer.js +0 -0
  120. /package/dist/{playground/container → container}/protocol.js +0 -0
  121. /package/dist/{playground/container → container}/workspace.js +0 -0
@@ -0,0 +1,315 @@
1
+ export function createJavaDebugRuntime(files, options, emit, read, respond = () => { }) {
2
+ const sources = new Map(files.map((file) => [file.path, file]));
3
+ const sourcePrefix = options.debugPath?.endsWith(`/${options.activePath}`)
4
+ ? options.debugPath.slice(0, -options.activePath.length)
5
+ : '';
6
+ const displayPath = (path) => path === options.activePath ? options.debugPath || path : `${sourcePrefix}${path}`;
7
+ const breakpoints = new Map();
8
+ let mode = options.pauseOnEntry ? 'entry' : 'continue';
9
+ let targetDepth = 0;
10
+ let targetSource = '';
11
+ let targetLine = 0;
12
+ let targetColumn = 0;
13
+ let pauseRequested = false;
14
+ let stop = 0;
15
+ let pausedFrameId;
16
+ let pausedScope;
17
+ let pendingInspection;
18
+ const references = new Set();
19
+ const referenceBase = () => stop * 100_000 + 1;
20
+ const variablePage = (value) => {
21
+ if (!Array.isArray(value) || value.length > 1000)
22
+ throw new Error('Invalid Java variable response');
23
+ return value.map((item) => {
24
+ if (!item ||
25
+ typeof item.name !== 'string' ||
26
+ typeof item.value !== 'string' ||
27
+ typeof item.type !== 'string' ||
28
+ !Number.isSafeInteger(item.variablesReference) ||
29
+ item.variablesReference < 0 ||
30
+ item.variablesReference > 4096 ||
31
+ (item.indexedVariables !== undefined &&
32
+ (!Number.isSafeInteger(item.indexedVariables) || item.indexedVariables < 0)))
33
+ throw new Error('Invalid Java variable descriptor');
34
+ const reference = item.variablesReference
35
+ ? referenceBase() + item.variablesReference
36
+ : 0;
37
+ if (reference)
38
+ references.add(reference);
39
+ return {
40
+ name: item.name,
41
+ value: item.value,
42
+ type: item.type,
43
+ variablesReference: reference,
44
+ ...(item.indexedVariables !== undefined
45
+ ? { indexedVariables: item.indexedVariables }
46
+ : {})
47
+ };
48
+ });
49
+ };
50
+ const setBreakpoints = (sourcePath, lines) => {
51
+ if (!Array.isArray(lines) ||
52
+ lines.length > 1024 ||
53
+ lines.some((line) => !Number.isSafeInteger(line) || line < 1))
54
+ throw new Error('Invalid Java breakpoint lines');
55
+ const file = files.find((file) => displayPath(file.path) === sourcePath);
56
+ const executable = [
57
+ ...new Set(file?.locations.map((location) => location.line) ?? [])
58
+ ].sort((a, b) => a - b);
59
+ const resolved = [...new Set(lines)].map((requestedLine) => {
60
+ const line = executable.find((line) => line >= requestedLine);
61
+ return {
62
+ requestedLine,
63
+ line: line ?? requestedLine,
64
+ verified: line !== undefined,
65
+ ...(line === undefined
66
+ ? { message: 'No instrumented Java statement at or after this line' }
67
+ : {})
68
+ };
69
+ });
70
+ breakpoints.set(sourcePath, new Set(resolved.filter((item) => item.verified).map((item) => item.line)));
71
+ emit({
72
+ type: 'breakpoints',
73
+ sourcePath,
74
+ sourceContentSha256: file?.sourceContentSha256,
75
+ breakpoints: resolved
76
+ });
77
+ };
78
+ const command = (blocking) => {
79
+ const raw = read(blocking);
80
+ if (raw === null)
81
+ throw new Error('Java debugger stopped');
82
+ if (!raw)
83
+ return null;
84
+ return JSON.parse(raw);
85
+ };
86
+ const update = (item) => {
87
+ if (item.op === 'breakpoints')
88
+ setBreakpoints(item.sourcePath, item.lines);
89
+ else if (item.op === 'pause')
90
+ pauseRequested = true;
91
+ };
92
+ const requestError = (item, message) => {
93
+ if (Number.isSafeInteger(item.id) && item.id > 0 && Number.isSafeInteger(item.stopId))
94
+ respond({ id: item.id, stopId: item.stopId, error: message });
95
+ };
96
+ const readPaused = () => {
97
+ for (;;) {
98
+ const item = command(true);
99
+ if (!item)
100
+ continue;
101
+ if (item.op === 'control') {
102
+ if (!['continue', 'stepInto', 'nextLine', 'stepOut'].includes(item.command))
103
+ throw new Error('Invalid Java debugger control');
104
+ mode = item.command;
105
+ pausedFrameId = undefined;
106
+ pausedScope = undefined;
107
+ references.clear();
108
+ pendingInspection = undefined;
109
+ emit({ type: 'resume', command: mode });
110
+ return null;
111
+ }
112
+ if (item.op === 'breakpoints' || item.op === 'pause') {
113
+ update(item);
114
+ continue;
115
+ }
116
+ if (!Number.isSafeInteger(item.id) ||
117
+ item.id < 1 ||
118
+ item.id > 2_147_483_647 ||
119
+ item.stopId !== stop) {
120
+ requestError(item, 'Java inspection request belongs to an earlier stop');
121
+ continue;
122
+ }
123
+ if (item.op === 'scopes') {
124
+ respond({
125
+ id: item.id,
126
+ stopId: stop,
127
+ value: item.frameId === pausedFrameId && pausedScope ? [pausedScope] : []
128
+ });
129
+ continue;
130
+ }
131
+ if (item.op === 'context') {
132
+ if (item.frameId !== pausedFrameId) {
133
+ requestError(item, 'Java values are available only for the currently stopped frame');
134
+ continue;
135
+ }
136
+ pendingInspection = { id: item.id, stopId: stop, op: item.op };
137
+ return { op: item.op, id: item.id, stopId: stop };
138
+ }
139
+ if (item.op === 'variables') {
140
+ const { reference, start = 0, count = 50 } = item;
141
+ if (!references.has(reference) ||
142
+ !Number.isSafeInteger(start) ||
143
+ start < 0 ||
144
+ !Number.isSafeInteger(count) ||
145
+ count < 0 ||
146
+ count > 1000) {
147
+ requestError(item, 'Invalid or stale Java variable page');
148
+ continue;
149
+ }
150
+ pendingInspection = { id: item.id, stopId: stop, op: item.op };
151
+ return {
152
+ op: item.op,
153
+ id: item.id,
154
+ stopId: stop,
155
+ reference: reference - referenceBase(),
156
+ start,
157
+ count
158
+ };
159
+ }
160
+ requestError(item, 'Unsupported Java inspection request');
161
+ }
162
+ };
163
+ setBreakpoints(displayPath(options.activePath), options.breakpoints);
164
+ for (const source of options.sourceBreakpoints ?? [])
165
+ setBreakpoints(source.sourcePath, source.lines);
166
+ return {
167
+ poll(source, line, _column) {
168
+ if (!sources.has(source))
169
+ throw new Error('Unknown Java debugger source');
170
+ for (let item; (item = command(false));) {
171
+ if (item.op === 'breakpoints' || item.op === 'pause')
172
+ update(item);
173
+ else
174
+ requestError(item, 'Java inspection requires a paused frame');
175
+ }
176
+ return pauseRequested ||
177
+ mode !== 'continue' ||
178
+ breakpoints.get(displayPath(source))?.has(line)
179
+ ? {}
180
+ : null;
181
+ },
182
+ pause(source, line, column, serialized, rawDepth, serializedVariables = '[]', totalVariables = 0) {
183
+ if (serialized.length > 1_000_000 || !Number.isSafeInteger(rawDepth) || rawDepth < 1)
184
+ throw new Error('Invalid Java debugger stack');
185
+ const raw = JSON.parse(serialized);
186
+ if (!Array.isArray(raw) || raw.length > 64)
187
+ throw new Error('Invalid Java debugger stack');
188
+ const frames = [];
189
+ for (const frame of raw) {
190
+ if (!Array.isArray(frame) ||
191
+ frame.length !== 4 ||
192
+ typeof frame[0] !== 'string' ||
193
+ typeof frame[1] !== 'string' ||
194
+ typeof frame[2] !== 'string' ||
195
+ !Number.isSafeInteger(frame[3]))
196
+ continue;
197
+ const packagePath = frame[0]
198
+ .slice(0, Math.max(0, frame[0].lastIndexOf('.')))
199
+ .replaceAll('.', '/');
200
+ const relativePath = packagePath ? `${packagePath}/${frame[2]}` : frame[2];
201
+ const candidates = files.filter((file) => file.path.split('/').pop() === frame[2]);
202
+ const exact = candidates.filter((file) => file.path === relativePath || file.path.endsWith(`/${relativePath}`));
203
+ const file = exact.length === 1
204
+ ? exact[0]
205
+ : candidates.length === 1
206
+ ? candidates[0]
207
+ : undefined;
208
+ if (!file || frame[3] < 1 || frame[3] > file.lineCount)
209
+ continue;
210
+ frames.push({
211
+ functionName: `${frame[0]}.${frame[1]}`,
212
+ line: frame[3],
213
+ sourcePath: displayPath(file.path),
214
+ sourceContentSha256: file.sourceContentSha256
215
+ });
216
+ }
217
+ const top = frames[0];
218
+ if (!top || top.sourcePath !== displayPath(source))
219
+ throw new Error('The Java runtime could not provide the current source stack');
220
+ const breakpoint = breakpoints.get(displayPath(source))?.has(line) === true;
221
+ const progressed = source !== targetSource ||
222
+ line !== targetLine ||
223
+ rawDepth !== targetDepth ||
224
+ column === targetColumn;
225
+ const stepping = mode === 'entry' ||
226
+ (mode === 'stepInto' && progressed) ||
227
+ (mode === 'nextLine' && rawDepth <= targetDepth && progressed) ||
228
+ (mode === 'stepOut' && rawDepth < targetDepth);
229
+ if (!pauseRequested && !breakpoint && !stepping)
230
+ return null;
231
+ const reason = pauseRequested
232
+ ? 'pause'
233
+ : breakpoint
234
+ ? 'breakpoint'
235
+ : mode === 'entry'
236
+ ? 'entry'
237
+ : mode === 'stepInto'
238
+ ? 'step'
239
+ : mode === 'stepOut'
240
+ ? 'stepOut'
241
+ : 'nextLine';
242
+ pauseRequested = false;
243
+ stop++;
244
+ if (stop > 2_147_483_647 ||
245
+ serializedVariables.length > 1_000_000 ||
246
+ !Number.isSafeInteger(totalVariables) ||
247
+ totalVariables < 0 ||
248
+ totalVariables > 1024)
249
+ throw new Error('Invalid Java local snapshot');
250
+ references.clear();
251
+ pendingInspection = undefined;
252
+ const locals = variablePage(JSON.parse(serializedVariables));
253
+ frames.forEach((frame, index) => {
254
+ frame.id = stop * 100 + index + 1;
255
+ });
256
+ top.line = line;
257
+ top.column = column;
258
+ pausedFrameId = top.id;
259
+ pausedScope = {
260
+ name: 'Locals',
261
+ variablesReference: referenceBase(),
262
+ namedVariables: totalVariables,
263
+ expensive: false,
264
+ variables: locals
265
+ };
266
+ references.add(referenceBase());
267
+ targetDepth = rawDepth;
268
+ targetSource = source;
269
+ targetLine = line;
270
+ targetColumn = column;
271
+ emit({
272
+ type: 'pause',
273
+ reason,
274
+ line,
275
+ sourcePath: top.sourcePath,
276
+ sourceContentSha256: top.sourceContentSha256,
277
+ frameId: top.id,
278
+ threadId: 1,
279
+ locals,
280
+ scopes: [pausedScope],
281
+ callStack: frames,
282
+ capabilities: { readMemory: false, writeMemory: false, dataBreakpoints: false }
283
+ }, stop);
284
+ return readPaused();
285
+ },
286
+ reply(id, stopId, serialized, error) {
287
+ const inspection = pendingInspection;
288
+ if (!inspection || inspection.id !== id || inspection.stopId !== stopId || !pausedScope)
289
+ throw new Error('Java inspection reply belongs to an earlier request');
290
+ pendingInspection = undefined;
291
+ try {
292
+ if (error)
293
+ respond({ id, stopId, error });
294
+ else {
295
+ if (typeof serialized !== 'string' || serialized.length > 1_000_000)
296
+ throw new Error('Invalid Java inspection response');
297
+ const value = JSON.parse(serialized);
298
+ respond({
299
+ id,
300
+ stopId,
301
+ value: inspection.op === 'variables' ? variablePage(value) : value
302
+ });
303
+ }
304
+ }
305
+ catch (failure) {
306
+ respond({
307
+ id,
308
+ stopId,
309
+ error: failure instanceof Error ? failure.message : 'Unable to inspect Java values'
310
+ });
311
+ }
312
+ return readPaused();
313
+ }
314
+ };
315
+ }
@@ -0,0 +1,11 @@
1
+ /** Bound output while synchronous Wasm owns the worker, including newline-free output. */
2
+ export declare function createJavaOutput(emit: (text: string) => void, options?: {
3
+ maxChars?: number;
4
+ maxDelayMs?: number;
5
+ now?: () => number;
6
+ }): {
7
+ write(charCode: number): void;
8
+ flush: () => void;
9
+ flushIfDue(): void;
10
+ close(): void;
11
+ };
@@ -0,0 +1,54 @@
1
+ /** Bound output while synchronous Wasm owns the worker, including newline-free output. */
2
+ export function createJavaOutput(emit, options = {}) {
3
+ const maxChars = options.maxChars ?? 16384;
4
+ const maxDelayMs = options.maxDelayMs ?? 16;
5
+ const now = options.now ?? (() => performance.now());
6
+ if (!Number.isSafeInteger(maxChars) ||
7
+ maxChars < 2 ||
8
+ !Number.isFinite(maxDelayMs) ||
9
+ maxDelayMs < 0)
10
+ throw new RangeError('Invalid Java output batch limits');
11
+ let text = '';
12
+ let hasEmitted = false;
13
+ let lastFlush = now();
14
+ let timer;
15
+ let closed = false;
16
+ function flush() {
17
+ if (timer !== undefined)
18
+ clearTimeout(timer);
19
+ timer = undefined;
20
+ if (!text)
21
+ return;
22
+ const output = text;
23
+ text = '';
24
+ hasEmitted = true;
25
+ lastFlush = now();
26
+ emit(output);
27
+ }
28
+ return {
29
+ write(charCode) {
30
+ if (closed)
31
+ return;
32
+ // A high surrogate is held until the next code unit, so output accounting
33
+ // does not encode a valid pair as two replacement characters.
34
+ if (text.length >= maxChars - 1 && !(charCode >= 0xdc00 && charCode <= 0xdfff))
35
+ flush();
36
+ text += String.fromCharCode(charCode);
37
+ if (charCode >= 0xd800 && charCode <= 0xdbff)
38
+ return;
39
+ if (text.length >= maxChars || !hasEmitted || now() - lastFlush >= maxDelayMs)
40
+ flush();
41
+ else if (timer === undefined)
42
+ timer = setTimeout(flush, maxDelayMs);
43
+ },
44
+ flush,
45
+ flushIfDue() {
46
+ if (text && now() - lastFlush >= maxDelayMs)
47
+ flush();
48
+ },
49
+ close() {
50
+ flush();
51
+ closed = true;
52
+ }
53
+ };
54
+ }
@@ -1,4 +1,5 @@
1
1
  import { waitForBufferedStdin } from '../stdinBuffer';
2
+ import { readLuaDebugCommand } from '../luaDebug';
2
3
  import { buildFennelCompileChunk, buildFennelRunChunk, loadFennelCompilerSource, parseFennelDiagnostic, stripHostLuaTraceback } from '../fennelBootstrap';
3
4
  let stdinBufferLua = null;
4
5
  let moduleUrl = '';
@@ -138,8 +139,20 @@ self.onmessage = async (event) => {
138
139
  }
139
140
  const hasInitialStdin = typeof stdin === 'string';
140
141
  let initialStdin = hasInitialStdin ? stdin : null;
142
+ if (event.data.debug && fennelSource)
143
+ throw new Error('Fennel source debugging is not supported.');
141
144
  const execution = await runtime.executeBrowserLuaArtifact(compiledArtifact, {
142
145
  args,
146
+ ...(event.data.debug
147
+ ? {
148
+ debug: {
149
+ breakpoints: event.data.breakpoints ?? [],
150
+ pauseOnEntry: event.data.pauseOnEntry !== false,
151
+ readCommand: (blocking) => readLuaDebugCommand(event.data.debugBuffer, blocking, () => postMessage({ debugCommandConsumed: true })),
152
+ onEvent: (debugEvent) => postMessage({ luaDebug: debugEvent })
153
+ }
154
+ }
155
+ : {}),
143
156
  onReady: () => postMessage({
144
157
  progress: {
145
158
  kind: 'ready',
@@ -28,6 +28,7 @@ let installedApecodeVersion;
28
28
  let executionHelpers;
29
29
  let invalidateWorkspaceImports;
30
30
  let syncWorkspaceFiles;
31
+ let debugPauseSequence = 0;
31
32
  let installPythonFlushHooks;
32
33
  const PYTHON_EXTENSIONS = {
33
34
  hy: {
@@ -373,7 +374,9 @@ function normalizeWorkspacePath(path) {
373
374
  function writeWorkspaceFiles(files = [], syncPythonWorkspace = false) {
374
375
  const fs = pyodide.FS;
375
376
  if (syncPythonWorkspace) {
376
- const normalized = files.map((file) => ({ ...file, path: normalizeWorkspacePath(file.path) })).filter((file) => file.path);
377
+ const normalized = files
378
+ .map((file) => ({ ...file, path: normalizeWorkspacePath(file.path) }))
379
+ .filter((file) => file.path);
377
380
  invalidateWorkspaceImports ??= createPythonWorkspaceImports(pyodide);
378
381
  invalidateWorkspaceImports(normalized.map((file) => file.path));
379
382
  syncWorkspaceFiles ??= createPythonWorkspaceFiles(fs);
@@ -643,6 +646,7 @@ self.onmessage = async (event) => {
643
646
  const debugReadWatchName = `__wasm_idle_python_debug_watch_read_${ts}`;
644
647
  const debugWriteWatchName = `__wasm_idle_python_debug_watch_write_${ts}`;
645
648
  const debugReadBreakpointsName = `__wasm_idle_python_debug_breakpoints_${ts}`;
649
+ const debugBreakpointStateName = `__wasm_idle_python_debug_breakpoint_state_${ts}`;
646
650
  const executionReadyName = `__wasm_idle_python_execution_ready_${ts}`;
647
651
  let executionReadyReported = false;
648
652
  self[executionReadyName] = () => {
@@ -681,9 +685,19 @@ self.onmessage = async (event) => {
681
685
  line: Number(line),
682
686
  reason,
683
687
  locals,
684
- callStack
688
+ callStack,
689
+ scopes: [
690
+ {
691
+ name: 'Locals',
692
+ presentationHint: 'locals',
693
+ variablesReference: ++debugPauseSequence,
694
+ expensive: false,
695
+ variables: locals
696
+ }
697
+ ]
685
698
  }
686
699
  });
700
+ return debugPauseSequence;
687
701
  };
688
702
  self[debugWaitName] = () => {
689
703
  const sequence = Atomics.load(debugBufferPyodide, 0);
@@ -715,6 +729,13 @@ self.onmessage = async (event) => {
715
729
  }
716
730
  return JSON.stringify({ version, lines });
717
731
  };
732
+ // Preserve an atomic check on every traced line, but avoid a Python-to-JS
733
+ // function call/null conversion unless a new breakpoint snapshot exists.
734
+ self[debugBreakpointStateName] = {
735
+ get version() {
736
+ return Atomics.load(debugBufferPyodide, 2);
737
+ }
738
+ };
718
739
  const executionFilename = normalizeWorkspacePath(activePath || '') ||
719
740
  (isHy ? '__wasm_idle_user__.hy' : '__wasm_idle_user__.py');
720
741
  const debugFilename = normalizeWorkspacePath(debugPath || '') || executionFilename;
@@ -748,6 +769,7 @@ from js import ${executionReadyName} as __wasm_idle_execution_ready
748
769
  ${debug ? `from js import ${debugPauseName}, ${debugWaitName}` : ''}
749
770
  ${debug ? `from js import ${debugReadWatchName}, ${debugWriteWatchName}` : ''}
750
771
  ${debug ? `from js import ${debugReadBreakpointsName}` : ''}
772
+ ${debug ? `from js import ${debugBreakpointStateName} as __wasm_idle_debug_breakpoint_state` : ''}
751
773
 
752
774
  ${imageHook}
753
775
 
@@ -765,14 +787,14 @@ __wasm_idle_debug_breakpoints = set(${normalizedBreakpoints})
765
787
  __wasm_idle_debug_breakpoint_version = -1
766
788
  __wasm_idle_debug_pause_on_entry = ${pauseOnEntry ? 'True' : 'False'}
767
789
  __wasm_idle_debug_step_mode = None
768
- __wasm_idle_debug_resume_skip = None
769
790
  __wasm_idle_debug_next_depth = None
770
- __wasm_idle_debug_next_line = None
771
791
  __wasm_idle_debug_step_out_depth = None
772
792
 
773
793
  def __wasm_idle_debug_refresh_breakpoints():
774
794
  global __wasm_idle_debug_breakpoints
775
795
  global __wasm_idle_debug_breakpoint_version
796
+ if __wasm_idle_debug_breakpoint_state.version == __wasm_idle_debug_breakpoint_version:
797
+ return
776
798
  payload = ${debugReadBreakpointsName}(__wasm_idle_debug_breakpoint_version)
777
799
  # JavaScript null crosses Pyodide as JsNull rather than Python None.
778
800
  if not isinstance(payload, str):
@@ -795,13 +817,22 @@ def __wasm_idle_debug_depth(frame):
795
817
 
796
818
  ${PYTHON_DEBUG_PREVIEW}
797
819
 
798
- def __wasm_idle_debug_locals(frame):
820
+ def __wasm_idle_debug_locals(frame, start=0, count=50):
799
821
  locals_preview = []
822
+ index = 0
800
823
  for name, value in frame.f_locals.items():
801
824
  if name == "__builtins__" or name.startswith("__wasm_idle_") or name.startswith("."):
802
825
  continue
803
- locals_preview.append({"name": name, "value": __wasm_idle_debug_preview(value)})
804
- locals_preview.sort(key = lambda item: item["name"])
826
+ if index >= start:
827
+ preview = __wasm_idle_debug_preview(value)
828
+ if len(preview) > 200:
829
+ preview = preview[:197] + "..."
830
+ suffix = "… [" + str(index) + "]"
831
+ display_name = name if len(name) <= 256 else name[:256-len(suffix)] + suffix
832
+ locals_preview.append({"name": display_name, "value": preview})
833
+ if len(locals_preview) >= count:
834
+ break
835
+ index += 1
805
836
  return locals_preview
806
837
 
807
838
  def __wasm_idle_debug_stack(frame):
@@ -816,9 +847,7 @@ def __wasm_idle_debug_stack(frame):
816
847
  def __wasm_idle_debug_trace(frame, event, arg):
817
848
  global __wasm_idle_debug_pause_on_entry
818
849
  global __wasm_idle_debug_step_mode
819
- global __wasm_idle_debug_resume_skip
820
850
  global __wasm_idle_debug_next_depth
821
- global __wasm_idle_debug_next_line
822
851
  global __wasm_idle_debug_step_out_depth
823
852
 
824
853
  if frame.f_code.co_filename not in __wasm_idle_debug_source_filenames:
@@ -827,13 +856,11 @@ def __wasm_idle_debug_trace(frame, event, arg):
827
856
  return __wasm_idle_debug_trace
828
857
 
829
858
  __wasm_idle_debug_refresh_breakpoints()
830
- needs_depth = (__wasm_idle_debug_resume_skip is not None or __wasm_idle_debug_step_mode in ("next", "out"))
859
+ # Returning from a trace callback executes this event; a later event on the same
860
+ # line is another loop iteration, not a replay of the previous stop.
861
+ needs_depth = __wasm_idle_debug_step_mode in ("next", "out")
831
862
  depth = __wasm_idle_debug_depth(frame) if needs_depth else None
832
863
  line = frame.f_lineno
833
- if __wasm_idle_debug_resume_skip == (depth, line):
834
- return __wasm_idle_debug_trace
835
- if __wasm_idle_debug_resume_skip is not None:
836
- __wasm_idle_debug_resume_skip = None
837
864
 
838
865
  reason = None
839
866
  if __wasm_idle_debug_pause_on_entry:
@@ -842,7 +869,7 @@ def __wasm_idle_debug_trace(frame, event, arg):
842
869
  reason = "breakpoint"
843
870
  elif __wasm_idle_debug_step_mode == "step":
844
871
  reason = "step"
845
- elif __wasm_idle_debug_step_mode == "next" and __wasm_idle_debug_next_depth is not None and depth <= __wasm_idle_debug_next_depth and line != __wasm_idle_debug_next_line:
872
+ elif __wasm_idle_debug_step_mode == "next" and __wasm_idle_debug_next_depth is not None and depth <= __wasm_idle_debug_next_depth:
846
873
  reason = "nextLine"
847
874
  elif __wasm_idle_debug_step_mode == "out" and __wasm_idle_debug_step_out_depth is not None and depth <= __wasm_idle_debug_step_out_depth:
848
875
  reason = "stepOut"
@@ -855,16 +882,25 @@ def __wasm_idle_debug_trace(frame, event, arg):
855
882
  __wasm_idle_debug_pause_on_entry = False
856
883
  __wasm_idle_debug_step_mode = None
857
884
  __wasm_idle_debug_next_depth = None
858
- __wasm_idle_debug_next_line = None
859
885
  __wasm_idle_debug_step_out_depth = None
860
886
 
861
887
  sys.stdout.flush()
862
888
  sys.stderr.flush()
863
- ${debugPauseName}(line, reason, json.dumps(__wasm_idle_debug_locals(frame)), json.dumps(__wasm_idle_debug_stack(frame)))
889
+ pause_reference = ${debugPauseName}(line, reason, json.dumps(__wasm_idle_debug_locals(frame)), json.dumps(__wasm_idle_debug_stack(frame)))
864
890
  while True:
865
891
  command = ${debugWaitName}()
866
892
  if command < 0:
867
893
  raise KeyboardInterrupt()
894
+ if command == 6:
895
+ try:
896
+ request = json.loads(${debugReadWatchName}())
897
+ start = max(0, int(request.get("start", 0)))
898
+ count = max(1, min(50, int(request.get("count", 50))))
899
+ page = __wasm_idle_debug_locals(frame, start, count) if request.get("reference") == pause_reference else []
900
+ ${debugWriteWatchName}(json.dumps(page))
901
+ except Exception:
902
+ ${debugWriteWatchName}("[]")
903
+ continue
868
904
  if command != 5:
869
905
  break
870
906
  try:
@@ -873,13 +909,11 @@ def __wasm_idle_debug_trace(frame, event, arg):
873
909
  except Exception as error:
874
910
  result = "?" if error.__class__.__name__ == "NameError" else "error"
875
911
  ${debugWriteWatchName}(result)
876
- __wasm_idle_debug_resume_skip = (depth, line)
877
912
  if command == 2:
878
913
  __wasm_idle_debug_step_mode = "step"
879
914
  elif command == 3:
880
915
  __wasm_idle_debug_step_mode = "next"
881
916
  __wasm_idle_debug_next_depth = depth
882
- __wasm_idle_debug_next_line = line
883
917
  elif command == 4:
884
918
  __wasm_idle_debug_step_mode = "out"
885
919
  __wasm_idle_debug_step_out_depth = max(0, depth - 1)
@@ -955,9 +989,7 @@ finally:
955
989
  ${debug
956
990
  ? `
957
991
  __wasm_idle_debug_step_mode = None
958
- __wasm_idle_debug_resume_skip = None
959
992
  __wasm_idle_debug_next_depth = None
960
- __wasm_idle_debug_next_line = None
961
993
  __wasm_idle_debug_step_out_depth = None
962
994
  `
963
995
  : ''}
@@ -971,7 +1003,9 @@ finally:
971
1003
  try {
972
1004
  finishStdio();
973
1005
  }
974
- catch { /* Preserve the execution error. */ }
1006
+ catch {
1007
+ /* Preserve the execution error. */
1008
+ }
975
1009
  self.postMessage({ error: e.message || 'Unknown error' });
976
1010
  }
977
1011
  finally {
@@ -984,6 +1018,7 @@ finally:
984
1018
  delete self[debugReadWatchName];
985
1019
  delete self[debugWriteWatchName];
986
1020
  delete self[debugReadBreakpointsName];
1021
+ delete self[debugBreakpointStateName];
987
1022
  }
988
1023
  }
989
1024
  };
@@ -1,5 +1,7 @@
1
1
  import { waitForBufferedStdin } from '../stdinBuffer';
2
2
  import { importRuntimeModule } from '../runtimeModule';
3
+ import { readDebugCommand } from '../debugMailbox';
4
+ import { executeRubyTracepoint } from './rubyTracepoint';
3
5
  import { createReadonlyGolfscriptMount } from './golfscriptMount';
4
6
  import { GOLFSCRIPT_RUNTIME_DIRECTORY, WASM_GOLFSCRIPT_INTERPRETER_RECEIPT } from '../wasmGolfscriptVersion';
5
7
  import { RUBY_RUNTIME_VERIFIED_WASM_URL, normalizeWorkspacePath, RUBY_SPLIT_PROTOCOL, verifyRubySplitPayload, rewriteRubySplitRuntimeModule, parseRubyStdlibPack, createRubyStdlibPreopens, rewriteVerifiedRubyRuntimeModule, verifyRubyRuntimePreflightPayload, verifyRuntimeAssetIntegrity, AssetTooLargeError } from '@wasm-idle/core';
@@ -514,6 +516,17 @@ end`);
514
516
  execution.flushOutput();
515
517
  }
516
518
  }
519
+ else if (message.rubyDebug) {
520
+ const debug = message.rubyDebug;
521
+ await executeRubyTracepoint(vm, code, {
522
+ path: activePath,
523
+ debugPath: debug.sourcePath,
524
+ breakpoints: debug.breakpoints,
525
+ sourceBreakpoints: debug.sourceBreakpoints,
526
+ pauseOnEntry: debug.pauseOnEntry,
527
+ files: workspaceFiles
528
+ }, (message) => postMessage({ rubyDebug: message }), (blocking) => readDebugCommand(debug.buffer, blocking, () => postMessage({ rubyDebug: { consumed: true } }), 'Ruby'));
529
+ }
517
530
  else {
518
531
  vm.eval(code);
519
532
  }
@@ -0,0 +1,2 @@
1
+ /** Automatic locals must not dispatch user inspection or container overrides. */
2
+ export declare const RUBY_DEBUG_PREVIEW: string;