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
@@ -4,6 +4,8 @@ import { parsePythonPackageLock } from '../pythonPackageLock';
4
4
  import { WASM_APECODE_VERSION, WASM_APECODE_WHEELS } from '../wasmApecodeVersion';
5
5
  import { withCachedPyodideModule } from './runtimeModule';
6
6
  import { createPythonExecutionHelpers } from './pythonExecution';
7
+ import { createPythonWorkspaceImports } from './pythonWorkspaceImports';
8
+ import { createPythonWorkspaceFiles } from './pythonWorkspaceFiles';
7
9
  import { PYTHON_DEBUG_PREVIEW } from './pythonDebugPreview';
8
10
  import { createPythonStdio, PYTHON_FLUSH_HOOK_FACTORY } from './pythonStdio';
9
11
  import { fetchRuntimeAssetBytes } from './runtimeAssetFetch';
@@ -24,6 +26,9 @@ let installedHyVersion;
24
26
  let installedAheuiVersion;
25
27
  let installedApecodeVersion;
26
28
  let executionHelpers;
29
+ let invalidateWorkspaceImports;
30
+ let syncWorkspaceFiles;
31
+ let debugPauseSequence = 0;
27
32
  let installPythonFlushHooks;
28
33
  const PYTHON_EXTENSIONS = {
29
34
  hy: {
@@ -366,8 +371,18 @@ function normalizeWorkspacePath(path) {
366
371
  .filter((part) => part && part !== '.' && part !== '..')
367
372
  .join('/');
368
373
  }
369
- function writeWorkspaceFiles(files = []) {
374
+ function writeWorkspaceFiles(files = [], syncPythonWorkspace = false) {
370
375
  const fs = pyodide.FS;
376
+ if (syncPythonWorkspace) {
377
+ const normalized = files
378
+ .map((file) => ({ ...file, path: normalizeWorkspacePath(file.path) }))
379
+ .filter((file) => file.path);
380
+ invalidateWorkspaceImports ??= createPythonWorkspaceImports(pyodide);
381
+ invalidateWorkspaceImports(normalized.map((file) => file.path));
382
+ syncWorkspaceFiles ??= createPythonWorkspaceFiles(fs);
383
+ syncWorkspaceFiles(normalized);
384
+ return;
385
+ }
371
386
  for (const file of files) {
372
387
  const safePath = normalizeWorkspacePath(file.path);
373
388
  if (!safePath)
@@ -525,7 +540,7 @@ self.onmessage = async (event) => {
525
540
  const preparationKey = packagePreparationKey(code, activePath, workspaceFiles);
526
541
  await loadPyodide(baseUrl);
527
542
  if (!usesInterpreterFileDescriptors)
528
- writeWorkspaceFiles(workspaceFiles);
543
+ writeWorkspaceFiles(workspaceFiles, isPython);
529
544
  // The genuine language implementations own their source, never Python's import scanner.
530
545
  if (isPython) {
531
546
  postProgress(15, 'Resolving Python imports');
@@ -551,7 +566,7 @@ self.onmessage = async (event) => {
551
566
  try {
552
567
  await loadPyodide(baseUrl);
553
568
  if (!usesInterpreterFileDescriptors)
554
- writeWorkspaceFiles(workspaceFiles);
569
+ writeWorkspaceFiles(workspaceFiles, isPython);
555
570
  if (isHy && installedHyVersion === undefined) {
556
571
  throw new Error('Hy runtime is not installed');
557
572
  }
@@ -631,6 +646,7 @@ self.onmessage = async (event) => {
631
646
  const debugReadWatchName = `__wasm_idle_python_debug_watch_read_${ts}`;
632
647
  const debugWriteWatchName = `__wasm_idle_python_debug_watch_write_${ts}`;
633
648
  const debugReadBreakpointsName = `__wasm_idle_python_debug_breakpoints_${ts}`;
649
+ const debugBreakpointStateName = `__wasm_idle_python_debug_breakpoint_state_${ts}`;
634
650
  const executionReadyName = `__wasm_idle_python_execution_ready_${ts}`;
635
651
  let executionReadyReported = false;
636
652
  self[executionReadyName] = () => {
@@ -669,9 +685,19 @@ self.onmessage = async (event) => {
669
685
  line: Number(line),
670
686
  reason,
671
687
  locals,
672
- callStack
688
+ callStack,
689
+ scopes: [
690
+ {
691
+ name: 'Locals',
692
+ presentationHint: 'locals',
693
+ variablesReference: ++debugPauseSequence,
694
+ expensive: false,
695
+ variables: locals
696
+ }
697
+ ]
673
698
  }
674
699
  });
700
+ return debugPauseSequence;
675
701
  };
676
702
  self[debugWaitName] = () => {
677
703
  const sequence = Atomics.load(debugBufferPyodide, 0);
@@ -703,6 +729,13 @@ self.onmessage = async (event) => {
703
729
  }
704
730
  return JSON.stringify({ version, lines });
705
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
+ };
706
739
  const executionFilename = normalizeWorkspacePath(activePath || '') ||
707
740
  (isHy ? '__wasm_idle_user__.hy' : '__wasm_idle_user__.py');
708
741
  const debugFilename = normalizeWorkspacePath(debugPath || '') || executionFilename;
@@ -729,28 +762,39 @@ self.onmessage = async (event) => {
729
762
  import builtins
730
763
  import inspect
731
764
  import json
765
+ import os
732
766
  import sys
767
+ import types
733
768
  from js import ${executionReadyName} as __wasm_idle_execution_ready
734
769
  ${debug ? `from js import ${debugPauseName}, ${debugWaitName}` : ''}
735
770
  ${debug ? `from js import ${debugReadWatchName}, ${debugWriteWatchName}` : ''}
736
771
  ${debug ? `from js import ${debugReadBreakpointsName}` : ''}
772
+ ${debug ? `from js import ${debugBreakpointStateName} as __wasm_idle_debug_breakpoint_state` : ''}
737
773
 
738
774
  ${imageHook}
739
775
 
740
776
  ${debug
741
777
  ? `
778
+ import os as __wasm_idle_debug_os
779
+
780
+ # Direct compilation uses relative paths; imported modules use absolute paths.
781
+ # Capture both identities before user code can change the working directory.
782
+ __wasm_idle_debug_source_filenames = {
783
+ ${debugFilenameLiteral},
784
+ __wasm_idle_debug_os.path.abspath(${debugFilenameLiteral}),
785
+ }
742
786
  __wasm_idle_debug_breakpoints = set(${normalizedBreakpoints})
743
787
  __wasm_idle_debug_breakpoint_version = -1
744
788
  __wasm_idle_debug_pause_on_entry = ${pauseOnEntry ? 'True' : 'False'}
745
789
  __wasm_idle_debug_step_mode = None
746
- __wasm_idle_debug_resume_skip = None
747
790
  __wasm_idle_debug_next_depth = None
748
- __wasm_idle_debug_next_line = None
749
791
  __wasm_idle_debug_step_out_depth = None
750
792
 
751
793
  def __wasm_idle_debug_refresh_breakpoints():
752
794
  global __wasm_idle_debug_breakpoints
753
795
  global __wasm_idle_debug_breakpoint_version
796
+ if __wasm_idle_debug_breakpoint_state.version == __wasm_idle_debug_breakpoint_version:
797
+ return
754
798
  payload = ${debugReadBreakpointsName}(__wasm_idle_debug_breakpoint_version)
755
799
  # JavaScript null crosses Pyodide as JsNull rather than Python None.
756
800
  if not isinstance(payload, str):
@@ -766,27 +810,36 @@ def __wasm_idle_debug_depth(frame):
766
810
  depth = 0
767
811
  current = frame
768
812
  while current is not None:
769
- if current.f_code.co_filename == ${debugFilenameLiteral}:
813
+ if current.f_code.co_filename in __wasm_idle_debug_source_filenames:
770
814
  depth += 1
771
815
  current = current.f_back
772
816
  return depth
773
817
 
774
818
  ${PYTHON_DEBUG_PREVIEW}
775
819
 
776
- def __wasm_idle_debug_locals(frame):
820
+ def __wasm_idle_debug_locals(frame, start=0, count=50):
777
821
  locals_preview = []
822
+ index = 0
778
823
  for name, value in frame.f_locals.items():
779
824
  if name == "__builtins__" or name.startswith("__wasm_idle_") or name.startswith("."):
780
825
  continue
781
- locals_preview.append({"name": name, "value": __wasm_idle_debug_preview(value)})
782
- 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
783
836
  return locals_preview
784
837
 
785
838
  def __wasm_idle_debug_stack(frame):
786
839
  stack = []
787
840
  current = frame
788
841
  while current is not None:
789
- if current.f_code.co_filename == ${debugFilenameLiteral}:
842
+ if current.f_code.co_filename in __wasm_idle_debug_source_filenames:
790
843
  stack.append({"functionName": current.f_code.co_name, "line": current.f_lineno})
791
844
  current = current.f_back
792
845
  return stack
@@ -794,24 +847,20 @@ def __wasm_idle_debug_stack(frame):
794
847
  def __wasm_idle_debug_trace(frame, event, arg):
795
848
  global __wasm_idle_debug_pause_on_entry
796
849
  global __wasm_idle_debug_step_mode
797
- global __wasm_idle_debug_resume_skip
798
850
  global __wasm_idle_debug_next_depth
799
- global __wasm_idle_debug_next_line
800
851
  global __wasm_idle_debug_step_out_depth
801
852
 
802
- if frame.f_code.co_filename != ${debugFilenameLiteral}:
853
+ if frame.f_code.co_filename not in __wasm_idle_debug_source_filenames:
803
854
  return None
804
855
  if event != "line":
805
856
  return __wasm_idle_debug_trace
806
857
 
807
858
  __wasm_idle_debug_refresh_breakpoints()
808
- 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")
809
862
  depth = __wasm_idle_debug_depth(frame) if needs_depth else None
810
863
  line = frame.f_lineno
811
- if __wasm_idle_debug_resume_skip == (depth, line):
812
- return __wasm_idle_debug_trace
813
- if __wasm_idle_debug_resume_skip is not None:
814
- __wasm_idle_debug_resume_skip = None
815
864
 
816
865
  reason = None
817
866
  if __wasm_idle_debug_pause_on_entry:
@@ -820,7 +869,7 @@ def __wasm_idle_debug_trace(frame, event, arg):
820
869
  reason = "breakpoint"
821
870
  elif __wasm_idle_debug_step_mode == "step":
822
871
  reason = "step"
823
- 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:
824
873
  reason = "nextLine"
825
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:
826
875
  reason = "stepOut"
@@ -833,16 +882,25 @@ def __wasm_idle_debug_trace(frame, event, arg):
833
882
  __wasm_idle_debug_pause_on_entry = False
834
883
  __wasm_idle_debug_step_mode = None
835
884
  __wasm_idle_debug_next_depth = None
836
- __wasm_idle_debug_next_line = None
837
885
  __wasm_idle_debug_step_out_depth = None
838
886
 
839
887
  sys.stdout.flush()
840
888
  sys.stderr.flush()
841
- ${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)))
842
890
  while True:
843
891
  command = ${debugWaitName}()
844
892
  if command < 0:
845
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
846
904
  if command != 5:
847
905
  break
848
906
  try:
@@ -851,13 +909,11 @@ def __wasm_idle_debug_trace(frame, event, arg):
851
909
  except Exception as error:
852
910
  result = "?" if error.__class__.__name__ == "NameError" else "error"
853
911
  ${debugWriteWatchName}(result)
854
- __wasm_idle_debug_resume_skip = (depth, line)
855
912
  if command == 2:
856
913
  __wasm_idle_debug_step_mode = "step"
857
914
  elif command == 3:
858
915
  __wasm_idle_debug_step_mode = "next"
859
916
  __wasm_idle_debug_next_depth = depth
860
- __wasm_idle_debug_next_line = line
861
917
  elif command == 4:
862
918
  __wasm_idle_debug_step_mode = "out"
863
919
  __wasm_idle_debug_step_out_depth = max(0, depth - 1)
@@ -892,17 +948,27 @@ finally:
892
948
  del __wasm_idle_execution_ready
893
949
  `
894
950
  : `
951
+ __wasm_idle_missing_main = object()
952
+ __wasm_idle_previous_main = sys.modules.get("__main__", __wasm_idle_missing_main)
953
+ __wasm_idle_previous_path = sys.path
895
954
  try:
896
- __wasm_idle_globals = {
897
- "__name__": "__main__",
955
+ __wasm_idle_module = types.ModuleType("__main__")
956
+ __wasm_idle_module.__file__ = ${executionFilenameLiteral}
957
+ __wasm_idle_globals = __wasm_idle_module.__dict__
958
+ __wasm_idle_globals.update({
898
959
  ${JSON.stringify(executionReadyName)}: __wasm_idle_execution_ready,
899
- }
960
+ })
900
961
  __wasm_idle_compiled = compile(
901
962
  ${JSON.stringify(code)},
902
963
  ${executionFilenameLiteral},
903
964
  "exec",
904
965
  flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT,
905
966
  )
967
+ sys.modules["__main__"] = __wasm_idle_module
968
+ __wasm_idle_run_paths = list(dict.fromkeys((
969
+ os.path.dirname(os.path.abspath(${executionFilenameLiteral})), os.getcwd()
970
+ )))
971
+ sys.path = __wasm_idle_run_paths + [path for path in __wasm_idle_previous_path if path not in __wasm_idle_run_paths]
906
972
  __wasm_idle_globals.pop(${JSON.stringify(executionReadyName)})()
907
973
  __wasm_idle_result = eval(
908
974
  __wasm_idle_compiled,
@@ -912,15 +978,18 @@ try:
912
978
  if inspect.isawaitable(__wasm_idle_result):
913
979
  await __wasm_idle_result
914
980
  finally:
981
+ sys.path = __wasm_idle_previous_path
982
+ if __wasm_idle_previous_main is __wasm_idle_missing_main:
983
+ sys.modules.pop("__main__", None)
984
+ else:
985
+ sys.modules["__main__"] = __wasm_idle_previous_main
915
986
  __wasm_idle_globals.pop(${JSON.stringify(executionReadyName)}, None)
916
987
  del __wasm_idle_execution_ready
917
988
  sys.settrace(None)
918
989
  ${debug
919
990
  ? `
920
991
  __wasm_idle_debug_step_mode = None
921
- __wasm_idle_debug_resume_skip = None
922
992
  __wasm_idle_debug_next_depth = None
923
- __wasm_idle_debug_next_line = None
924
993
  __wasm_idle_debug_step_out_depth = None
925
994
  `
926
995
  : ''}
@@ -934,7 +1003,9 @@ finally:
934
1003
  try {
935
1004
  finishStdio();
936
1005
  }
937
- catch { /* Preserve the execution error. */ }
1006
+ catch {
1007
+ /* Preserve the execution error. */
1008
+ }
938
1009
  self.postMessage({ error: e.message || 'Unknown error' });
939
1010
  }
940
1011
  finally {
@@ -947,6 +1018,7 @@ finally:
947
1018
  delete self[debugReadWatchName];
948
1019
  delete self[debugWriteWatchName];
949
1020
  delete self[debugReadBreakpointsName];
1021
+ delete self[debugBreakpointStateName];
950
1022
  }
951
1023
  }
952
1024
  };
@@ -5,7 +5,9 @@ def __wasm_idle_make_execution_helpers(image_source, max_entries=8, max_bytes=41
5
5
  import builtins
6
6
  import inspect
7
7
  import marshal
8
+ import os
8
9
  import sys
10
+ import types
9
11
  from collections import OrderedDict
10
12
  from pyodide.code import find_imports
11
13
 
@@ -61,6 +63,9 @@ def __wasm_idle_make_execution_helpers(image_source, max_entries=8, max_bytes=41
61
63
 
62
64
  async def run(source, filename, ready, input_bridge=None, output_bridge=None):
63
65
  previous_input, previous_print = builtins.input, builtins.print
66
+ missing_main = object()
67
+ previous_main = sys.modules.get("__main__", missing_main)
68
+ previous_path = sys.path
64
69
  def input_wrapper(prompt=""):
65
70
  value = input_bridge(prompt)
66
71
  if value is None:
@@ -87,12 +92,23 @@ def __wasm_idle_make_execution_helpers(image_source, max_entries=8, max_bytes=41
87
92
  # This budget accounts source strings and serialized code, not total Wasm heap.
88
93
  weight = sys.getsizeof(source) + sys.getsizeof(filename) + len(marshal.dumps(compiled))
89
94
  code_cache.put(key, compiled, weight)
90
- scope = {"__name__": "__main__"}
95
+ main_module = types.ModuleType("__main__")
96
+ main_module.__file__ = filename
97
+ scope = main_module.__dict__
98
+ sys.modules["__main__"] = main_module
99
+ # Script siblings take precedence; shared workspace-root modules follow.
100
+ run_paths = list(dict.fromkeys((os.path.dirname(os.path.abspath(filename)), os.getcwd())))
101
+ sys.path = run_paths + [path for path in previous_path if path not in run_paths]
91
102
  ready()
92
103
  result = evaluate(compiled, scope, scope)
93
104
  if inspect.isawaitable(result):
94
105
  await result
95
106
  finally:
107
+ sys.path = previous_path
108
+ if previous_main is missing_main:
109
+ sys.modules.pop("__main__", None)
110
+ else:
111
+ sys.modules["__main__"] = previous_main
96
112
  sys.settrace(None)
97
113
  builtins.input, builtins.print = previous_input, previous_print
98
114
 
@@ -0,0 +1,6 @@
1
+ import type { PyodideInterface } from 'pyodide';
2
+ /** Own only supplied files; generated files and directories survive later runs. */
3
+ export declare function createPythonWorkspaceFiles(fs: PyodideInterface['FS']): (files: {
4
+ path: string;
5
+ content: string;
6
+ }[]) => void;
@@ -0,0 +1,26 @@
1
+ /** Own only supplied files; generated files and directories survive later runs. */
2
+ export function createPythonWorkspaceFiles(fs) {
3
+ const workspaceFs = fs;
4
+ const writtenPaths = new Set();
5
+ return (files) => {
6
+ const root = fs.cwd().replace(/\/$/, '');
7
+ const currentPaths = new Set(files.map((file) => `${root}/${file.path}`));
8
+ for (const path of writtenPaths) {
9
+ if (currentPaths.has(path))
10
+ continue;
11
+ // A former input can become a generated directory owned by user code.
12
+ if (workspaceFs.analyzePath(path).exists && !fs.isDir(fs.lstat(path).mode)) {
13
+ fs.unlink(path);
14
+ }
15
+ writtenPaths.delete(path);
16
+ }
17
+ for (const file of files) {
18
+ const directory = file.path.split('/').slice(0, -1).join('/');
19
+ if (directory)
20
+ workspaceFs.mkdirTree(directory);
21
+ fs.writeFile(file.path, file.content);
22
+ // Retain ownership even when a later write in this operation fails.
23
+ writtenPaths.add(`${root}/${file.path}`);
24
+ }
25
+ };
26
+ }
@@ -0,0 +1,4 @@
1
+ import type { PyodideInterface } from 'pyodide';
2
+ export declare const PYTHON_WORKSPACE_IMPORTS_FACTORY: string;
3
+ /** Invalidate imports at the workspace boundary, including prepared and debug runs. */
4
+ export declare function createPythonWorkspaceImports(runtime: PyodideInterface): (paths: string[]) => any;
@@ -0,0 +1,129 @@
1
+ export const PYTHON_WORKSPACE_IMPORTS_FACTORY = String.raw `
2
+ def __wasm_idle_make_workspace_imports():
3
+ import importlib
4
+ import importlib.machinery
5
+ import importlib.util
6
+ import json
7
+ import os
8
+ import sys
9
+
10
+ previous_sources = set()
11
+ previous_paths = set()
12
+ imported_modules = {}
13
+ imported_cache_paths = set()
14
+
15
+ class WorkspaceLoader:
16
+ def __init__(self, loader, cache_path):
17
+ self.loader = loader
18
+ self.cache_path = cache_path
19
+
20
+ def create_module(self, spec):
21
+ return self.loader.create_module(spec)
22
+
23
+ def exec_module(self, module):
24
+ # Remember ownership before user code can remove or retarget its
25
+ # alias, including code executing inside the imported module.
26
+ imported_modules[id(module)] = module
27
+ if self.cache_path is not None:
28
+ imported_cache_paths.add(self.cache_path)
29
+ return self.loader.exec_module(module)
30
+
31
+ def __getattr__(self, name):
32
+ return getattr(self.loader, name)
33
+
34
+ class WorkspaceFinder:
35
+ def find_spec(self, fullname, path=None, target=None):
36
+ spec = importlib.machinery.PathFinder.find_spec(fullname, path, target)
37
+ if spec is None or not isinstance(spec.loader, (
38
+ importlib.machinery.SourceFileLoader,
39
+ importlib.machinery.SourcelessFileLoader,
40
+ )):
41
+ return spec
42
+ filename = spec.origin
43
+ if not isinstance(filename, str):
44
+ return spec
45
+ if filename.endswith(".pyc"):
46
+ try:
47
+ filename = importlib.util.source_from_cache(filename)
48
+ except ValueError:
49
+ return spec
50
+ filename = os.path.abspath(filename)
51
+ if filename in previous_sources or os.path.realpath(filename) in previous_paths:
52
+ # Resolve the cache while the alias still names this source.
53
+ # Resolving it at cleanup could delete another directory's cache.
54
+ cache_path = os.path.realpath(spec.cached) if spec.cached else None
55
+ spec.loader = WorkspaceLoader(spec.loader, cache_path)
56
+ return spec
57
+
58
+ # Preserve custom finders ahead of normal filesystem imports. The wrapper
59
+ # delegates the standard file loader's resource and source APIs unchanged.
60
+ for index, finder in enumerate(sys.meta_path):
61
+ if finder is importlib.machinery.PathFinder:
62
+ sys.meta_path.insert(index, WorkspaceFinder())
63
+ break
64
+
65
+ def invalidate(paths_json):
66
+ nonlocal previous_sources, previous_paths
67
+ current_sources = {os.path.abspath(path) for path in json.loads(paths_json)}
68
+ current_paths = {os.path.realpath(path) for path in current_sources}
69
+ # Retain both identities so a removed or renamed supplied symlink still
70
+ # owns its lexical imports and the physical source it pointed to.
71
+ workspace_sources = previous_sources | current_sources
72
+ workspace_paths = previous_paths | current_paths
73
+ cache_sources = workspace_sources | workspace_paths
74
+ # Only modules backed by supplied workspace files belong to this run.
75
+ # Keep interpreter, standard-library and installed-package state intact.
76
+ for name, module in list(sys.modules.items()):
77
+ if module is None or imported_modules.get(id(module)) is not module:
78
+ filename = getattr(module, "__file__", None)
79
+ if not isinstance(filename, str):
80
+ continue
81
+ if filename.endswith(".pyc"):
82
+ try:
83
+ filename = importlib.util.source_from_cache(filename)
84
+ except ValueError:
85
+ continue
86
+ filename = os.path.abspath(filename)
87
+ if filename not in workspace_sources and os.path.realpath(filename) not in workspace_paths:
88
+ continue
89
+ # Handle modules loaded before this workspace boundary as well.
90
+ cache_sources.add(filename)
91
+ sys.modules.pop(name, None)
92
+ parent_name, _, child_name = name.rpartition(".")
93
+ parent = sys.modules.get(parent_name)
94
+ if parent is not None and getattr(parent, child_name, None) is module:
95
+ delattr(parent, child_name)
96
+ # Rewrites can have the same size and timestamp; invalidate their bytecode,
97
+ # too, so removing sys.modules cannot reload an obsolete cached source.
98
+ cache_paths = imported_cache_paths | {
99
+ importlib.util.cache_from_source(filename)
100
+ for filename in cache_sources if filename.endswith(".py")
101
+ }
102
+ for cache_path in cache_paths:
103
+ try:
104
+ os.unlink(cache_path)
105
+ except (FileNotFoundError, NotADirectoryError):
106
+ # Python imports also tolerate an unavailable cache parent.
107
+ pass
108
+ importlib.invalidate_caches()
109
+ imported_modules.clear()
110
+ imported_cache_paths.clear()
111
+ previous_sources = current_sources
112
+ previous_paths = current_paths
113
+
114
+ return invalidate
115
+
116
+ __wasm_idle_make_workspace_imports
117
+ `;
118
+ /** Invalidate imports at the workspace boundary, including prepared and debug runs. */
119
+ export function createPythonWorkspaceImports(runtime) {
120
+ const factory = runtime.runPython(PYTHON_WORKSPACE_IMPORTS_FACTORY);
121
+ let invalidate;
122
+ try {
123
+ invalidate = factory();
124
+ }
125
+ finally {
126
+ factory.destroy();
127
+ }
128
+ return (paths) => invalidate(JSON.stringify(paths));
129
+ }
@@ -93,13 +93,20 @@ function readInitialStdin(code, initialStdin, log = true) {
93
93
  return initialStdin;
94
94
  if (!codeMightReadStdin(code))
95
95
  return '';
96
- const chunk = waitForBufferedStdin(stdinBufferR, () => postMessage({ buffer: true }));
97
- if (log) {
98
- console.log(chunk == null
99
- ? '[wasm-idle:r-stdin] read(bytes=0, eof=true)'
100
- : `[wasm-idle:r-stdin] read(bytes=${encoder.encode(chunk).byteLength}, text=${JSON.stringify(chunk)})`);
96
+ // R reads stdin from a file written before the program starts, so collect
97
+ // terminal input until EOF instead of dropping chunks typed after the first.
98
+ let input = '';
99
+ while (true) {
100
+ const chunk = waitForBufferedStdin(stdinBufferR, () => postMessage({ buffer: true }));
101
+ if (log) {
102
+ console.log(chunk == null
103
+ ? '[wasm-idle:r-stdin] read(bytes=0, eof=true)'
104
+ : `[wasm-idle:r-stdin] read(bytes=${encoder.encode(chunk).byteLength}, text=${JSON.stringify(chunk)})`);
105
+ }
106
+ if (chunk == null)
107
+ return input;
108
+ input += chunk;
101
109
  }
102
- return chunk || '';
103
110
  }
104
111
  function buildRunnerSource(activePath, args) {
105
112
  const argsSource = args.map(rString).join(', ');
@@ -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;