wasm-idle 1.1.2 → 1.3.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 (136) hide show
  1. package/README.md +211 -91
  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 +2 -1
  22. package/dist/index.js +1 -0
  23. package/dist/playground/assetBridge.js +5 -2
  24. package/dist/playground/assets.d.ts +8 -0
  25. package/dist/playground/clang.d.ts +5 -1
  26. package/dist/playground/clang.js +61 -5
  27. package/dist/playground/compiledLldb.d.ts +41 -0
  28. package/dist/playground/compiledLldb.js +167 -0
  29. package/dist/playground/d.d.ts +4 -1
  30. package/dist/playground/d.js +78 -9
  31. package/dist/playground/debugDeadline.d.ts +12 -0
  32. package/dist/playground/debugDeadline.js +34 -0
  33. package/dist/playground/debugMailbox.d.ts +12 -0
  34. package/dist/playground/debugMailbox.js +77 -0
  35. package/dist/playground/go.js +9 -4
  36. package/dist/playground/goDebugInstrumentation.js +24 -44
  37. package/dist/playground/java-debug-HUZVAK4F.js +124 -0
  38. package/dist/playground/java-debug-notices.txt +492 -0
  39. package/dist/playground/java.d.ts +17 -1
  40. package/dist/playground/java.js +159 -3
  41. package/dist/playground/javaDebug.d.ts +62 -0
  42. package/dist/playground/javaDebug.js +305 -0
  43. package/dist/playground/javaDebugBridge.d.ts +6 -0
  44. package/dist/playground/javaDebugBridge.js +250 -0
  45. package/dist/playground/javaDebugSource.d.ts +9 -0
  46. package/dist/playground/javaDebugSource.js +4 -0
  47. package/dist/playground/javaRuntimeErrors.js +34 -1
  48. package/dist/playground/lean4Assets.d.ts +1 -25
  49. package/dist/playground/lean4Assets.js +2 -123
  50. package/dist/playground/lfortranAssets.d.ts +2 -2
  51. package/dist/playground/lldbSession.d.ts +24 -2
  52. package/dist/playground/lldbSession.js +322 -59
  53. package/dist/playground/lldbSourcePath.d.ts +2 -0
  54. package/dist/playground/lldbSourcePath.js +9 -0
  55. package/dist/playground/lua.d.ts +20 -1
  56. package/dist/playground/lua.js +190 -8
  57. package/dist/playground/luaDebug.d.ts +1 -0
  58. package/dist/playground/luaDebug.js +1 -0
  59. package/dist/playground/nim.d.ts +1 -0
  60. package/dist/playground/nim.js +8 -0
  61. package/dist/playground/objectivec.d.ts +7 -6
  62. package/dist/playground/objectivec.js +75 -9
  63. package/dist/playground/options.d.ts +10 -4
  64. package/dist/playground/python.d.ts +11 -1
  65. package/dist/playground/python.js +203 -8
  66. package/dist/playground/pythonCompileOptions.d.ts +49 -0
  67. package/dist/playground/pythonCompileOptions.js +40 -0
  68. package/dist/playground/ruby.d.ts +10 -1
  69. package/dist/playground/ruby.js +66 -1
  70. package/dist/playground/rubyDebug.d.ts +21 -0
  71. package/dist/playground/rubyDebug.js +128 -0
  72. package/dist/playground/rust.d.ts +5 -1
  73. package/dist/playground/rust.js +128 -46
  74. package/dist/playground/sandbox.d.ts +8 -1
  75. package/dist/playground/staticRuntimeModuleVersion.d.ts +1 -1
  76. package/dist/playground/staticRuntimeModuleVersion.js +1 -1
  77. package/dist/playground/staticWorkerRuntime.js +8 -2
  78. package/dist/playground/stdinBuffer.d.ts +1 -1
  79. package/dist/playground/stdinBuffer.js +19 -2
  80. package/dist/playground/tinygo.js +7 -0
  81. package/dist/playground/typescript.js +8 -0
  82. package/dist/playground/v.d.ts +3 -2
  83. package/dist/playground/v.js +66 -12
  84. package/dist/playground/wasmC3Version.d.ts +2 -2
  85. package/dist/playground/wasmC3Version.js +2 -2
  86. package/dist/playground/wasmDebugVersion.d.ts +1 -1
  87. package/dist/playground/wasmDebugVersion.js +1 -1
  88. package/dist/playground/wasmLean4Version.d.ts +1 -110
  89. package/dist/playground/wasmLean4Version.js +2 -111
  90. package/dist/playground/wasmLfortranVersion.d.ts +2 -2
  91. package/dist/playground/wasmLfortranVersion.js +2 -2
  92. package/dist/playground/wasmLuaVersion.d.ts +1 -1
  93. package/dist/playground/wasmLuaVersion.js +1 -1
  94. package/dist/playground/wasmPrologVersion.d.ts +17 -17
  95. package/dist/playground/wasmPrologVersion.js +16 -16
  96. package/dist/playground/wasmRustVersion.d.ts +26 -38
  97. package/dist/playground/wasmRustVersion.js +25 -40
  98. package/dist/playground/wasmTypeScriptVersion.d.ts +3 -3
  99. package/dist/playground/wasmTypeScriptVersion.js +3 -3
  100. package/dist/playground/worker/clang.js +1 -1
  101. package/dist/playground/worker/cobol.js +1 -1
  102. package/dist/playground/worker/d.js +51 -2
  103. package/dist/playground/worker/fortran.js +1 -1
  104. package/dist/playground/worker/java.js +188 -35
  105. package/dist/playground/worker/javaDebugEvaluator.d.ts +16 -0
  106. package/dist/playground/worker/javaDebugEvaluator.js +44 -0
  107. package/dist/playground/worker/javaDebugRuntime.d.ts +24 -0
  108. package/dist/playground/worker/javaDebugRuntime.js +315 -0
  109. package/dist/playground/worker/javaOutput.d.ts +11 -0
  110. package/dist/playground/worker/javaOutput.js +54 -0
  111. package/dist/playground/worker/lua.js +13 -0
  112. package/dist/playground/worker/python.js +81 -23
  113. package/dist/playground/worker/pythonCompile.d.ts +4 -0
  114. package/dist/playground/worker/pythonCompile.js +122 -0
  115. package/dist/playground/worker/ruby.js +13 -0
  116. package/dist/playground/worker/rubyDebugPreview.d.ts +2 -0
  117. package/dist/playground/worker/rubyDebugPreview.js +80 -0
  118. package/dist/playground/worker/rubyTracepoint.d.ts +16 -0
  119. package/dist/playground/worker/rubyTracepoint.js +162 -0
  120. package/dist/playground/worker/rust.js +4 -1
  121. package/dist/playground/worker/v.js +30 -5
  122. package/dist/playground/zig.js +4 -0
  123. package/dist/pythonCompiler.d.ts +8 -0
  124. package/dist/pythonCompiler.js +52 -0
  125. package/package.json +76 -28
  126. package/dist/playground/container/ContainerExplorer.svelte +0 -307
  127. package/dist/playground/container/ContainerExplorer.svelte.d.ts +0 -14
  128. package/dist/playground/container/clang-runtime.js +0 -343
  129. package/dist/playground/container/client.d.ts +0 -15
  130. package/dist/playground/container/owner.worker.d.ts +0 -1
  131. package/dist/playground/container/owner.worker.js +0 -390
  132. package/dist/playground/container/release.d.ts +0 -31
  133. package/dist/playground/container/release.js +0 -612
  134. /package/dist/{playground/container → container}/explorer.js +0 -0
  135. /package/dist/{playground/container → container}/protocol.js +0 -0
  136. /package/dist/{playground/container → container}/workspace.js +0 -0
@@ -5,6 +5,7 @@ import { bufferedSequence, flushBufferedEof, flushQueuedStdin, resetBufferedStdi
5
5
  import { createWasmIdleSharedBuffer, requireSharedArrayBuffer } from './sharedBuffer';
6
6
  import { WorkerSession } from './workerSession';
7
7
  import { reportWorkerProgress } from './workerProgress';
8
+ import { resolvePythonCompileRequest } from './pythonCompileOptions';
8
9
  import { BusyError, DEFAULT_WORKSPACE_LIMITS, OutputLimitError, RuntimeConfigurationError, TimeoutError, resolveExecutionLimits, validateExecutionWorkspace } from '@wasm-idle/core';
9
10
  const debugBreakpointBufferInts = 1028;
10
11
  const outputEncoder = new TextEncoder();
@@ -12,7 +13,7 @@ const abortReason = (signal, phase, label = 'Python') => signal.reason !== undef
12
13
  ? signal.reason
13
14
  : new DOMException(phase === 'startup'
14
15
  ? `${label} runtime startup aborted`
15
- : `${label} execution aborted`, 'AbortError');
16
+ : `${label} ${phase === 'compile' ? 'compilation' : 'execution'} aborted`, 'AbortError');
16
17
  class Python {
17
18
  ts = Date.now();
18
19
  output = null;
@@ -22,7 +23,13 @@ class Python {
22
23
  buffer = createWasmIdleSharedBuffer(1024);
23
24
  debugBuffer = createWasmIdleSharedBuffer(Int32Array.BYTES_PER_ELEMENT * debugBreakpointBufferInts);
24
25
  watchBuffer = createWasmIdleSharedBuffer(1024);
25
- watchResultBuffer = createWasmIdleSharedBuffer(1024);
26
+ // Fifty locals of 256 name + 200 preview code points fit even if JSON needs
27
+ // two six-character surrogate escapes per point. Watch/page requests share it.
28
+ watchResultBuffer = createWasmIdleSharedBuffer(320 * 1024);
29
+ pausedVariablesReference;
30
+ inspectionController = new AbortController();
31
+ inspectionFailure;
32
+ inspectionQueue = Promise.resolve();
26
33
  interruptBuffer = createWasmIdleSharedBuffer(1);
27
34
  pendingInput = [];
28
35
  begin = 0;
@@ -127,6 +134,7 @@ class Python {
127
134
  cancelOperation(operation, reason) {
128
135
  if (!this.isOperationActive(operation))
129
136
  return;
137
+ this.setInspectionPause();
130
138
  operation.cancelled = true;
131
139
  operation.cancellationReason = reason;
132
140
  this.activeOperation = null;
@@ -181,7 +189,7 @@ class Python {
181
189
  timeout = setTimeout(() => {
182
190
  if (!this.isOperationActive(operation))
183
191
  return;
184
- this.cancelOperation(operation, new TimeoutError(`${this.runtimeLabel} ${operation.phase === 'startup' ? 'startup' : 'execution'} timed out after ${timeoutMs} ms`, {
192
+ this.cancelOperation(operation, new TimeoutError(`${this.runtimeLabel} ${operation.phase === 'startup' ? 'startup' : operation.phase === 'compile' ? 'compilation' : 'execution'} timed out after ${timeoutMs} ms`, {
185
193
  phase: operation.phase,
186
194
  runtimeId: this.runtimeId,
187
195
  timeoutMs
@@ -340,6 +348,125 @@ class Python {
340
348
  this.pendingEof = true;
341
349
  this.flushPendingInput();
342
350
  }
351
+ /** Used by compilePython's dedicated instance; never runs source or resolves its imports. */
352
+ compile(code, options = {}) {
353
+ let operation;
354
+ try {
355
+ operation = this.beginOperation('compile');
356
+ }
357
+ catch (error) {
358
+ return Promise.reject(error);
359
+ }
360
+ let request;
361
+ const worker = this.worker;
362
+ try {
363
+ if (this.workerLanguage !== 'python') {
364
+ throw new RuntimeConfigurationError('Bytecode compilation is only available for Python');
365
+ }
366
+ request = resolvePythonCompileRequest(code, options);
367
+ options.signal?.throwIfAborted();
368
+ if (!worker)
369
+ throw new Error('Python worker not loaded');
370
+ this.assetBridge?.setExecutionPersistentCache(options.persistentCache);
371
+ }
372
+ catch (error) {
373
+ return Promise.reject(this.releaseBeforeSession(operation, error));
374
+ }
375
+ const { fileName, optimize, limits, invalidationMode, timestamp } = request;
376
+ const path = fileName.slice(0, -3) + '.pyc';
377
+ this.exit = false;
378
+ this.begin = Date.now();
379
+ let handler;
380
+ const compiling = new Promise((resolve, reject) => {
381
+ const workerOperation = this.workerSession.beginRun(worker, reject);
382
+ this.bindOperationTimeout(operation, limits.compileTimeoutMs);
383
+ this.bindAbortSignal(operation, options.signal);
384
+ if (!this.isOperationActive(operation))
385
+ return;
386
+ const finish = (result, error) => {
387
+ if (!this.isOperationActive(operation))
388
+ return;
389
+ this.workerSession.complete(workerOperation);
390
+ this.releaseOperation(operation);
391
+ this.cleanupOperation(operation);
392
+ if (result)
393
+ resolve(result);
394
+ else
395
+ reject(error);
396
+ };
397
+ handler = (event) => {
398
+ if (!this.isOperationActive(operation) || this.worker !== worker)
399
+ return;
400
+ try {
401
+ if (this.assetBridge?.handleMessage(event))
402
+ return;
403
+ reportWorkerProgress(options.progress, event.data?.progress);
404
+ if (!this.isOperationActive(operation))
405
+ return;
406
+ if (event.data?.error !== undefined) {
407
+ const outputLimit = event.data.outputLimit;
408
+ finish(undefined, outputLimit
409
+ ? new OutputLimitError(String(event.data.error), {
410
+ runtimeId: 'PYTHON3',
411
+ phase: 'compile',
412
+ actual: outputLimit.actual,
413
+ limit: outputLimit.limit
414
+ })
415
+ : event.data.error);
416
+ return;
417
+ }
418
+ if (event.data?.compiled === undefined)
419
+ return;
420
+ const result = event.data.compiled;
421
+ if (!result ||
422
+ result.path !== path ||
423
+ !(result.data instanceof Uint8Array) ||
424
+ result.data.byteLength < 16 ||
425
+ typeof result.pythonVersion !== 'string' ||
426
+ typeof result.cacheTag !== 'string' ||
427
+ typeof result.magicNumber !== 'string' ||
428
+ !/^[0-9a-f]{8}$/.test(result.magicNumber))
429
+ throw new Error('Invalid Python bytecode result');
430
+ if (result.data.byteLength > limits.maxOutputBytes) {
431
+ throw new OutputLimitError('Python bytecode exceeds the configured byte limit', {
432
+ runtimeId: 'PYTHON3',
433
+ phase: 'compile',
434
+ actual: result.data.byteLength,
435
+ limit: limits.maxOutputBytes
436
+ });
437
+ }
438
+ finish(result);
439
+ }
440
+ catch (error) {
441
+ this.cancelOperation(operation, error);
442
+ }
443
+ };
444
+ worker.onmessage = handler;
445
+ try {
446
+ worker.postMessage({
447
+ compile: true,
448
+ language: 'python',
449
+ code,
450
+ fileName,
451
+ optimize,
452
+ invalidationMode,
453
+ timestamp,
454
+ maxArtifactBytes: limits.maxOutputBytes
455
+ });
456
+ }
457
+ catch (error) {
458
+ finish(undefined, error);
459
+ }
460
+ });
461
+ return compiling.finally(() => {
462
+ this.releaseOperation(operation);
463
+ this.cleanupOperation(operation);
464
+ this.exit = true;
465
+ this.elapse = Date.now() - this.begin;
466
+ if (worker?.onmessage === handler)
467
+ worker.onmessage = null;
468
+ });
469
+ }
343
470
  flushPendingInput() {
344
471
  if (!this.waitingForInput)
345
472
  return;
@@ -426,6 +553,7 @@ class Python {
426
553
  this.waitingForInput = false;
427
554
  this.pendingEof = false;
428
555
  }
556
+ this.setInspectionPause();
429
557
  this.exit = false;
430
558
  const running = new Promise((resolve, reject) => {
431
559
  const workerOperation = this.workerSession.beginRun(worker, reject);
@@ -442,6 +570,7 @@ class Python {
442
570
  worker.onmessage === handler &&
443
571
  runUid === this.uid;
444
572
  const settleRunState = () => {
573
+ this.setInspectionPause();
445
574
  this.elapse = Date.now() - this.begin;
446
575
  this.exit = true;
447
576
  this.waitingForInput = false;
@@ -520,8 +649,12 @@ class Python {
520
649
  }
521
650
  if (!ownsRun())
522
651
  return;
523
- if (debugEvent)
652
+ if (debugEvent) {
653
+ this.setInspectionPause(debugEvent.type === 'pause'
654
+ ? debugEvent.scopes?.[0]?.variablesReference
655
+ : undefined);
524
656
  this.ondebug?.(debugEvent);
657
+ }
525
658
  if (!ownsRun())
526
659
  return;
527
660
  if (log)
@@ -581,6 +714,7 @@ class Python {
581
714
  });
582
715
  }
583
716
  debugCommand(command) {
717
+ this.setInspectionPause();
584
718
  const control = new Int32Array(this.debugBuffer);
585
719
  Atomics.store(control, 1, command === 'stepInto' ? 2 : command === 'nextLine' ? 3 : command === 'stepOut' ? 4 : 1);
586
720
  Atomics.add(control, 0, 1);
@@ -598,23 +732,84 @@ class Python {
598
732
  Atomics.store(control, 3, next.length);
599
733
  Atomics.add(control, 2, 1);
600
734
  }
601
- async debugEvaluate(expression) {
735
+ setInspectionPause(reference) {
736
+ this.inspectionController.abort();
737
+ this.inspectionController = new AbortController();
738
+ this.inspectionFailure = undefined;
739
+ this.pausedVariablesReference = reference;
740
+ }
741
+ async inspect(command, expression, signal) {
742
+ if (signal.aborted)
743
+ return '?';
602
744
  if (!this.worker)
603
745
  throw new Error('Worker not loaded');
604
746
  resetBufferedStdin(this.watchResultBuffer);
605
747
  const previousSequence = bufferedSequence(this.watchResultBuffer);
606
748
  flushQueuedStdin([expression], this.watchBuffer);
607
749
  const control = new Int32Array(this.debugBuffer);
608
- Atomics.store(control, 1, 5);
750
+ Atomics.store(control, 1, command);
609
751
  Atomics.add(control, 0, 1);
610
752
  Atomics.notify(control, 0);
611
- return ((await waitForBufferedSequenceChange(this.watchResultBuffer, previousSequence, 5000)) ??
612
- '?');
753
+ try {
754
+ return ((await waitForBufferedSequenceChange(this.watchResultBuffer, previousSequence, 5000, signal)) ?? '?');
755
+ }
756
+ catch (error) {
757
+ if (signal.aborted)
758
+ return '?';
759
+ if (signal === this.inspectionController.signal) {
760
+ // Replies have no request identifier. A timed-out target evaluation can
761
+ // still finish, so this pause cannot safely reuse its response mailbox.
762
+ const failure = new Error('Python debugger inspection timed out. Resume or step to a new pause before inspecting again.', { cause: error });
763
+ this.inspectionFailure = failure;
764
+ this.inspectionController.abort(failure);
765
+ throw failure;
766
+ }
767
+ throw error;
768
+ }
769
+ }
770
+ debugEvaluate(expression) {
771
+ const reference = this.pausedVariablesReference;
772
+ const signal = this.inspectionController.signal;
773
+ const request = this.inspectionQueue.then(async () => {
774
+ if (signal === this.inspectionController.signal && this.inspectionFailure)
775
+ throw this.inspectionFailure;
776
+ if (signal.aborted ||
777
+ reference === undefined ||
778
+ reference !== this.pausedVariablesReference)
779
+ return '?';
780
+ const value = await this.inspect(5, expression, signal);
781
+ return !signal.aborted && reference === this.pausedVariablesReference ? value : '?';
782
+ });
783
+ this.inspectionQueue = request.catch(() => { });
784
+ return request;
785
+ }
786
+ debugVariables(reference, start = 0, count = 50) {
787
+ if (!Number.isSafeInteger(reference) ||
788
+ !Number.isSafeInteger(start) ||
789
+ start < 0 ||
790
+ !Number.isSafeInteger(count) ||
791
+ count < 1)
792
+ return Promise.resolve([]);
793
+ const signal = this.inspectionController.signal;
794
+ const request = this.inspectionQueue.then(async () => {
795
+ if (signal === this.inspectionController.signal && this.inspectionFailure)
796
+ throw this.inspectionFailure;
797
+ if (signal.aborted || reference !== this.pausedVariablesReference)
798
+ return [];
799
+ const result = await this.inspect(6, JSON.stringify({ reference, start, count: Math.min(50, count) }), signal);
800
+ if (signal.aborted || reference !== this.pausedVariablesReference)
801
+ return [];
802
+ const page = JSON.parse(result);
803
+ return Array.isArray(page) ? page : [];
804
+ });
805
+ this.inspectionQueue = request.catch(() => { });
806
+ return request;
613
807
  }
614
808
  kill() {
615
809
  this.terminate();
616
810
  }
617
811
  terminate(reason = 'Process terminated') {
812
+ this.setInspectionPause();
618
813
  const activeOperation = this.activeOperation;
619
814
  if (activeOperation) {
620
815
  this.cancelOperation(activeOperation, reason);
@@ -0,0 +1,49 @@
1
+ import { type ExecutionLimits, type RuntimeAssetCacheOptions } from '@wasm-idle/core';
2
+ import type { SandboxProgress, SandboxRuntimeAssets } from './sandbox';
3
+ export interface PythonCompileOptions {
4
+ /** Relative source path used in tracebacks. Defaults to main.py. */
5
+ fileName?: string;
6
+ /** 0 preserves assertions and docstrings; 1 removes assertions; 2 also removes docstrings. */
7
+ optimize?: 0 | 1 | 2;
8
+ /** Cache invalidation format. Defaults to reproducible checked-hash bytecode without a timestamp. */
9
+ invalidationMode?: 'checked-hash' | 'unchecked-hash' | 'timestamp';
10
+ /** Source mtime in integer Unix seconds (0–4294967295). Only valid in timestamp mode; defaults to 0. */
11
+ timestamp?: number;
12
+ runtimeAssets?: SandboxRuntimeAssets;
13
+ persistentCache?: RuntimeAssetCacheOptions;
14
+ signal?: AbortSignal;
15
+ progress?: SandboxProgress;
16
+ /** maxWorkspaceBytes bounds the source; maxOutputBytes bounds the returned .pyc. */
17
+ limits?: Partial<Pick<ExecutionLimits, 'assetTimeoutMs' | 'startupTimeoutMs' | 'compileTimeoutMs' | 'maxWorkspaceBytes' | 'maxOutputBytes' | 'maxAssetBytes'>>;
18
+ }
19
+ export interface PythonCompileResult {
20
+ /** Relative output path, e.g. pkg/main.pyc. */
21
+ path: string;
22
+ data: Uint8Array;
23
+ pythonVersion: string;
24
+ cacheTag: string;
25
+ /** Four-byte CPython magic number encoded as eight hexadecimal digits. */
26
+ magicNumber: string;
27
+ }
28
+ /** Share header-option validation between the host and the actual compiler boundary. */
29
+ export declare function resolvePythonBytecodeOptions(options: Pick<PythonCompileOptions, 'invalidationMode' | 'timestamp'>): {
30
+ invalidationMode: "checked-hash" | "unchecked-hash";
31
+ timestamp: undefined;
32
+ } | {
33
+ invalidationMode: "timestamp";
34
+ timestamp: number;
35
+ };
36
+ /** Validate before starting a runtime, and again at the direct adapter boundary. */
37
+ export declare function resolvePythonCompileRequest(code: string, options: PythonCompileOptions): {
38
+ invalidationMode: "checked-hash" | "unchecked-hash";
39
+ timestamp: undefined;
40
+ fileName: string;
41
+ optimize: 0 | 1 | 2;
42
+ limits: ExecutionLimits;
43
+ } | {
44
+ invalidationMode: "timestamp";
45
+ timestamp: number;
46
+ fileName: string;
47
+ optimize: 0 | 1 | 2;
48
+ limits: ExecutionLimits;
49
+ };
@@ -0,0 +1,40 @@
1
+ import { RuntimeConfigurationError, resolveExecutionLimits, validateExecutionWorkspace } from '@wasm-idle/core';
2
+ /** Share header-option validation between the host and the actual compiler boundary. */
3
+ export function resolvePythonBytecodeOptions(options) {
4
+ const invalidationMode = options.invalidationMode === undefined ? 'checked-hash' : options.invalidationMode;
5
+ if (!['checked-hash', 'unchecked-hash', 'timestamp'].includes(invalidationMode)) {
6
+ throw new RuntimeConfigurationError('Python invalidationMode must be checked-hash, unchecked-hash, or timestamp');
7
+ }
8
+ if (invalidationMode !== 'timestamp') {
9
+ if (options.timestamp !== undefined) {
10
+ throw new RuntimeConfigurationError('Python timestamp requires timestamp invalidation mode');
11
+ }
12
+ return { invalidationMode, timestamp: undefined };
13
+ }
14
+ const timestamp = options.timestamp === undefined ? 0 : options.timestamp;
15
+ if (!Number.isInteger(timestamp) || timestamp < 0 || timestamp > 0xffffffff) {
16
+ throw new RuntimeConfigurationError('Python timestamp must be an integer Unix time from 0 to 4294967295 seconds');
17
+ }
18
+ return { invalidationMode, timestamp };
19
+ }
20
+ /** Validate before starting a runtime, and again at the direct adapter boundary. */
21
+ export function resolvePythonCompileRequest(code, options) {
22
+ if (typeof code !== 'string') {
23
+ throw new RuntimeConfigurationError('Python source must be a string');
24
+ }
25
+ const limits = resolveExecutionLimits(options.limits);
26
+ const optimize = options.optimize ?? 0;
27
+ if (![0, 1, 2].includes(optimize)) {
28
+ throw new RuntimeConfigurationError('Python optimize must be 0, 1, or 2');
29
+ }
30
+ const bytecodeOptions = resolvePythonBytecodeOptions(options);
31
+ const workspace = validateExecutionWorkspace(code, [], options.fileName ?? 'main.py', {
32
+ maxFileBytes: limits.maxWorkspaceBytes,
33
+ maxTotalBytes: limits.maxWorkspaceBytes
34
+ });
35
+ const fileName = workspace.activePath;
36
+ if (!/\.py$/i.test(fileName)) {
37
+ throw new RuntimeConfigurationError('Python compilation requires a .py file name');
38
+ }
39
+ return { fileName, optimize, limits, ...bytecodeOptions };
40
+ }
@@ -1,5 +1,5 @@
1
1
  import { type PlaygroundRuntimeAssets } from './assets';
2
- import { type CompilerDiagnostic, type SandboxExecutionOptions } from './options';
2
+ import { type DebugCommand, type DebugSessionEvent, type CompilerDiagnostic, type SandboxExecutionOptions } from './options';
3
3
  import type { Sandbox, SandboxProgress } from './sandbox';
4
4
  declare class Ruby implements Sandbox {
5
5
  private readonly workerLanguage;
@@ -15,6 +15,8 @@ declare class Ruby implements Sandbox {
15
15
  moduleUrl: string;
16
16
  private runtimeAssetKey;
17
17
  oncompilerdiagnostic?: (diagnostic: CompilerDiagnostic) => void;
18
+ ondebug?: (event: DebugSessionEvent) => void;
19
+ private debugSession?;
18
20
  waitingForInput: boolean;
19
21
  pendingEof: boolean;
20
22
  private activeOperation;
@@ -44,6 +46,13 @@ declare class Ruby implements Sandbox {
44
46
  eof(): void;
45
47
  private flushPendingInput;
46
48
  run(code: string, prepare: boolean, _log?: boolean, _prog?: SandboxProgress, args?: string[], options?: SandboxExecutionOptions): Promise<boolean | string>;
49
+ debugCommand(command: DebugCommand): void;
50
+ debugPause(): void;
51
+ setBreakpoints(lines: number[], sourcePath?: string): void;
52
+ debugEvaluate(expression: string): Promise<string>;
53
+ debugScopes(frameId: number): Promise<import("@wasm-idle/core").DebugScope[]>;
54
+ debugFrameScopes(frameId: number): Promise<import("@wasm-idle/core").DebugScope[]>;
55
+ debugVariables(reference: number, start?: number, count?: number): Promise<import("@wasm-idle/core").DebugVariable[]>;
47
56
  kill(): void;
48
57
  terminate(reason?: unknown): void;
49
58
  clear(): Promise<void>;
@@ -5,6 +5,8 @@ import { resolveSandboxExecutionArgs } from './options';
5
5
  import { flushBufferedEof, flushQueuedStdin, resetBufferedStdin } from './stdinBuffer';
6
6
  import { createWasmIdleSharedBuffer } from './sharedBuffer';
7
7
  import { WorkerSession } from './workerSession';
8
+ import { RubyDebugSession } from './rubyDebug';
9
+ import { DebugDeadline } from './debugDeadline';
8
10
  import { reportWorkerInputReady, reportWorkerProgress } from './workerProgress';
9
11
  import { BusyError, AssetTooLargeError, CancelledError, DEFAULT_WORKSPACE_LIMITS, DiagnosticLimitError, OutputLimitError, RUBY_MAX_ASSET_BYTES, RUBY_MAX_MANIFEST_BYTES, RUBY_MAX_MODULE_BYTES, RuntimeConfigurationError, TimeoutError, fetchPinnedRuntimeAsset, resolveExecutionLimits, validateExecutionWorkspace } from '@wasm-idle/core';
10
12
  const OUTPUT_ENCODER = new TextEncoder();
@@ -27,6 +29,8 @@ class Ruby {
27
29
  moduleUrl = '';
28
30
  runtimeAssetKey = '';
29
31
  oncompilerdiagnostic;
32
+ ondebug;
33
+ debugSession;
30
34
  waitingForInput = false;
31
35
  pendingEof = false;
32
36
  activeOperation = null;
@@ -595,12 +599,37 @@ class Ruby {
595
599
  const hasExplicitStdin = request.stdin !== undefined;
596
600
  this.prepareRunStdin(activeOperation, hasExplicitStdin);
597
601
  this.exit = false;
602
+ let runDebugSession;
598
603
  const running = new Promise((resolve, reject) => {
599
604
  let diagnosticCount = 0;
600
605
  let outputBytes = 0;
601
606
  const workerOperation = this.workerSession.beginRun(worker, reject);
602
607
  const timeoutMs = Math.min(2_147_483_647, limits.compileTimeoutMs + limits.runTimeoutMs);
603
- this.bindOperationTimeout(activeOperation, timeoutMs);
608
+ let debugDeadline;
609
+ if (!prepare && this.workerLanguage === 'ruby' && options.debugMode === 'tracepoint') {
610
+ debugDeadline = new DebugDeadline(timeoutMs, () => this.cancelOperation(activeOperation, new TimeoutError(`Ruby execution timed out after ${timeoutMs} ms`, {
611
+ phase: 'execute',
612
+ runtimeId: 'RUBY',
613
+ timeoutMs
614
+ })));
615
+ runDebugSession = new RubyDebugSession(options.debugPath || request.activePath, (event) => {
616
+ if (event.type === 'pause')
617
+ debugDeadline?.pause();
618
+ if (event.type === 'resume')
619
+ debugDeadline?.resume();
620
+ this.ondebug?.(event);
621
+ });
622
+ this.debugSession = runDebugSession;
623
+ const session = runDebugSession;
624
+ activeOperation.cleanups.push(() => {
625
+ debugDeadline?.dispose();
626
+ if (this.debugSession === session)
627
+ this.debugSession = undefined;
628
+ session.dispose();
629
+ });
630
+ }
631
+ else
632
+ this.bindOperationTimeout(activeOperation, timeoutMs);
604
633
  this.bindAbortSignal(activeOperation, signal);
605
634
  if (!this.isOperationActive(activeOperation))
606
635
  return;
@@ -651,6 +680,10 @@ class Ruby {
651
680
  return;
652
681
  }
653
682
  try {
683
+ if (event.data.rubyDebug && runDebugSession) {
684
+ runDebugSession.handle(event.data.rubyDebug);
685
+ return;
686
+ }
654
687
  const { output, results, error, buffer, diagnostic, progress } = event.data;
655
688
  if (buffer && !hasExplicitStdin) {
656
689
  this.waitingForInput = true;
@@ -722,6 +755,17 @@ class Ruby {
722
755
  stdin: request.stdin,
723
756
  activePath: request.activePath,
724
757
  workspaceFiles: request.workspaceFiles,
758
+ ...(runDebugSession
759
+ ? {
760
+ rubyDebug: {
761
+ buffer: runDebugSession.mailbox.buffer,
762
+ sourcePath: options.debugPath || request.activePath,
763
+ breakpoints: options.breakpoints ?? [],
764
+ sourceBreakpoints: options.sourceBreakpoints,
765
+ pauseOnEntry: options.pauseOnEntry !== false
766
+ }
767
+ }
768
+ : {}),
725
769
  log: _log
726
770
  });
727
771
  }
@@ -740,6 +784,27 @@ class Ruby {
740
784
  this.cleanupOperation(activeOperation);
741
785
  });
742
786
  }
787
+ debugCommand(command) {
788
+ this.debugSession?.command(command);
789
+ }
790
+ debugPause() {
791
+ this.debugSession?.pause();
792
+ }
793
+ setBreakpoints(lines, sourcePath) {
794
+ this.debugSession?.setBreakpoints(lines, sourcePath);
795
+ }
796
+ debugEvaluate(expression) {
797
+ return this.debugSession?.evaluate(expression) ?? Promise.resolve('?');
798
+ }
799
+ async debugScopes(frameId) {
800
+ return this.debugSession?.scopes(frameId) ?? [];
801
+ }
802
+ async debugFrameScopes(frameId) {
803
+ return this.debugSession?.scopes(frameId, false) ?? [];
804
+ }
805
+ async debugVariables(reference, start, count) {
806
+ return this.debugSession?.variables(reference, start, count) ?? [];
807
+ }
743
808
  kill() {
744
809
  this.terminate();
745
810
  }
@@ -0,0 +1,21 @@
1
+ import { DebugCommandMailbox } from './debugMailbox';
2
+ import type { DebugCommand, DebugScope, DebugSessionEvent, DebugVariable } from './options';
3
+ export declare class RubyDebugSession {
4
+ private readonly sourcePath;
5
+ private readonly emit;
6
+ readonly mailbox: DebugCommandMailbox;
7
+ private nextRequest;
8
+ private pending;
9
+ private frames;
10
+ private frameId?;
11
+ private closed;
12
+ constructor(sourcePath: string, emit: (event: DebugSessionEvent) => void);
13
+ handle(message: any): void;
14
+ command(command: DebugCommand): void;
15
+ pause(): void;
16
+ setBreakpoints(lines: number[], sourcePath?: string): void;
17
+ evaluate(expression: string): Promise<string>;
18
+ scopes(frameId: number, select?: boolean): DebugScope[];
19
+ variables(reference: number, start?: number, count?: number): DebugVariable[];
20
+ dispose(): void;
21
+ }
@@ -0,0 +1,128 @@
1
+ import { DebugCommandMailbox } from './debugMailbox';
2
+ export class RubyDebugSession {
3
+ sourcePath;
4
+ emit;
5
+ mailbox = new DebugCommandMailbox('Ruby');
6
+ nextRequest = 0;
7
+ pending = new Map();
8
+ frames = new Map();
9
+ frameId;
10
+ closed = false;
11
+ constructor(sourcePath, emit) {
12
+ this.sourcePath = sourcePath;
13
+ this.emit = emit;
14
+ }
15
+ handle(message) {
16
+ if (this.closed)
17
+ return;
18
+ if (message.consumed)
19
+ this.mailbox.flush();
20
+ if (message.response) {
21
+ const response = message.response;
22
+ const pending = this.pending.get(response.id);
23
+ if (!pending)
24
+ return;
25
+ this.pending.delete(response.id);
26
+ clearTimeout(pending.timer);
27
+ if (response.error)
28
+ pending.reject(new Error(response.error));
29
+ else
30
+ pending.resolve(response.value);
31
+ return;
32
+ }
33
+ const event = message.event;
34
+ if (!event)
35
+ return;
36
+ if (event.type === 'pause') {
37
+ this.frames.clear();
38
+ for (const frame of message.frames ?? [])
39
+ this.frames.set(frame.id, frame.locals);
40
+ this.frameId = event.frameId;
41
+ }
42
+ else if (event.type === 'resume') {
43
+ this.frames.clear();
44
+ this.frameId = undefined;
45
+ for (const pending of this.pending.values()) {
46
+ clearTimeout(pending.timer);
47
+ pending.reject(new Error('Ruby evaluation became stale'));
48
+ }
49
+ this.pending.clear();
50
+ }
51
+ this.emit(event);
52
+ }
53
+ command(command) {
54
+ this.mailbox.send(JSON.stringify({ op: 'control', command }));
55
+ }
56
+ pause() {
57
+ this.mailbox.send(JSON.stringify({ op: 'pause' }));
58
+ }
59
+ setBreakpoints(lines, sourcePath = this.sourcePath) {
60
+ if (lines.length > 1024 || lines.some((line) => !Number.isSafeInteger(line) || line < 1))
61
+ throw new RangeError('Invalid Ruby breakpoint lines');
62
+ this.mailbox.send(JSON.stringify({ op: 'breakpoints', lines, sourcePath }));
63
+ }
64
+ evaluate(expression) {
65
+ if (expression.length > 4096)
66
+ return Promise.reject(new RangeError('Expression exceeds 4096 characters'));
67
+ if (this.closed || this.frameId === undefined)
68
+ return Promise.reject(new Error('Ruby evaluation requires a paused frame'));
69
+ return new Promise((resolve, reject) => {
70
+ const id = ++this.nextRequest;
71
+ const timer = setTimeout(() => {
72
+ this.pending.delete(id);
73
+ reject(new Error('Ruby evaluation timed out'));
74
+ }, 10_000);
75
+ this.pending.set(id, { resolve, reject, timer });
76
+ try {
77
+ this.mailbox.send(JSON.stringify({ op: 'evaluate', id, expression, frameId: this.frameId }));
78
+ }
79
+ catch (error) {
80
+ clearTimeout(timer);
81
+ this.pending.delete(id);
82
+ reject(error);
83
+ }
84
+ });
85
+ }
86
+ scopes(frameId, select = true) {
87
+ if (!this.frames.has(frameId))
88
+ return [];
89
+ if (select)
90
+ this.frameId = frameId;
91
+ return [
92
+ {
93
+ name: 'Locals',
94
+ variablesReference: frameId,
95
+ namedVariables: this.frames.get(frameId).length,
96
+ expensive: false,
97
+ variables: this.frames.get(frameId)
98
+ }
99
+ ];
100
+ }
101
+ variables(reference, start = 0, count = 50) {
102
+ if (!Number.isSafeInteger(start) ||
103
+ start < 0 ||
104
+ !Number.isSafeInteger(count) ||
105
+ count < 0 ||
106
+ count > 1000)
107
+ throw new RangeError('Invalid Ruby variable page');
108
+ return (this.frames.get(reference) ?? []).slice(start, start + count);
109
+ }
110
+ dispose() {
111
+ if (this.closed)
112
+ return;
113
+ this.closed = true;
114
+ this.mailbox.close();
115
+ this.frames.clear();
116
+ for (const pending of this.pending.values()) {
117
+ clearTimeout(pending.timer);
118
+ pending.reject(new Error('Ruby debugger stopped'));
119
+ }
120
+ this.pending.clear();
121
+ try {
122
+ this.emit({ type: 'stop' });
123
+ }
124
+ catch {
125
+ /* Cleanup survives caller notification failures. */
126
+ }
127
+ }
128
+ }