wasm-idle 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/README.md +267 -112
  2. package/dist/container/bash-profile.d.ts +80 -0
  3. package/dist/container/bash-profile.js +328 -0
  4. package/dist/container/binding.d.ts +39 -0
  5. package/dist/container/binding.js +331 -0
  6. package/dist/container/clang-runtime.d.ts +42 -0
  7. package/dist/container/clang-runtime.js +561 -0
  8. package/dist/container/client.d.ts +14 -0
  9. package/dist/container/client.js +185 -0
  10. package/dist/container/explorer.d.ts +31 -0
  11. package/dist/container/explorer.js +112 -0
  12. package/dist/container/index.d.ts +11 -0
  13. package/dist/container/index.js +11 -0
  14. package/dist/container/owner-worker.d.ts +19 -0
  15. package/dist/container/owner-worker.js +464 -0
  16. package/dist/container/protocol.d.ts +84 -0
  17. package/dist/container/protocol.js +28 -0
  18. package/dist/container/runtime-adapter.d.ts +75 -0
  19. package/dist/container/runtime-adapter.js +537 -0
  20. package/dist/container/shell-control.d.ts +49 -0
  21. package/dist/container/shell-control.js +360 -0
  22. package/dist/container/workspace.d.ts +12 -0
  23. package/dist/container/workspace.js +29 -0
  24. package/dist/index.d.ts +1 -1
  25. package/dist/playground/assetBridge.js +111 -33
  26. package/dist/playground/assets.d.ts +10 -2
  27. package/dist/playground/c3.js +22 -0
  28. package/dist/playground/c3Memory.d.ts +19 -0
  29. package/dist/playground/c3Memory.js +117 -0
  30. package/dist/playground/cachedClang.js +143 -34
  31. package/dist/playground/clang.d.ts +5 -1
  32. package/dist/playground/clang.js +61 -5
  33. package/dist/playground/clangAssetIntegrity.js +6 -6
  34. package/dist/playground/clangWorkerProtocol.d.ts +12 -1
  35. package/dist/playground/cobol.d.ts +3 -0
  36. package/dist/playground/cobol.js +10 -1
  37. package/dist/playground/commonlispAssets.d.ts +2 -2
  38. package/dist/playground/compiledArtifactCache.d.ts +3 -1
  39. package/dist/playground/compiledArtifactCache.js +31 -5
  40. package/dist/playground/compiledLldb.d.ts +41 -0
  41. package/dist/playground/compiledLldb.js +167 -0
  42. package/dist/playground/d.d.ts +10 -2
  43. package/dist/playground/d.js +161 -14
  44. package/dist/playground/debugDeadline.d.ts +12 -0
  45. package/dist/playground/debugDeadline.js +34 -0
  46. package/dist/playground/debugMailbox.d.ts +12 -0
  47. package/dist/playground/debugMailbox.js +77 -0
  48. package/dist/playground/dotnet.js +6 -8
  49. package/dist/playground/fortran.d.ts +3 -0
  50. package/dist/playground/fortran.js +10 -1
  51. package/dist/playground/go.js +23 -7
  52. package/dist/playground/goDebugInstrumentation.js +207 -97
  53. package/dist/playground/java-debug-FMHDKUN6.js +124 -0
  54. package/dist/playground/java-debug-notices.txt +492 -0
  55. package/dist/playground/java.d.ts +17 -1
  56. package/dist/playground/java.js +162 -5
  57. package/dist/playground/javaDebug.d.ts +62 -0
  58. package/dist/playground/javaDebug.js +305 -0
  59. package/dist/playground/javaDebugBridge.d.ts +6 -0
  60. package/dist/playground/javaDebugBridge.js +250 -0
  61. package/dist/playground/javaDebugSource.d.ts +9 -0
  62. package/dist/playground/javaDebugSource.js +4 -0
  63. package/dist/playground/javaRuntimeErrors.d.ts +9 -0
  64. package/dist/playground/javaRuntimeErrors.js +93 -0
  65. package/dist/playground/lean4Assets.d.ts +1 -25
  66. package/dist/playground/lean4Assets.js +2 -123
  67. package/dist/playground/lfortran.js +10 -0
  68. package/dist/playground/lfortranAssets.d.ts +2 -2
  69. package/dist/playground/lldbSession.d.ts +23 -2
  70. package/dist/playground/lldbSession.js +278 -58
  71. package/dist/playground/lldbSourcePath.d.ts +2 -0
  72. package/dist/playground/lldbSourcePath.js +9 -0
  73. package/dist/playground/lua.d.ts +20 -1
  74. package/dist/playground/lua.js +190 -8
  75. package/dist/playground/luaDebug.d.ts +1 -0
  76. package/dist/playground/luaDebug.js +1 -0
  77. package/dist/playground/nim.d.ts +1 -0
  78. package/dist/playground/nim.js +30 -0
  79. package/dist/playground/objectivec.d.ts +10 -6
  80. package/dist/playground/objectivec.js +85 -10
  81. package/dist/playground/options.d.ts +12 -4
  82. package/dist/playground/python.d.ts +8 -1
  83. package/dist/playground/python.js +89 -6
  84. package/dist/playground/ruby.d.ts +10 -1
  85. package/dist/playground/ruby.js +66 -1
  86. package/dist/playground/rubyDebug.d.ts +21 -0
  87. package/dist/playground/rubyDebug.js +128 -0
  88. package/dist/playground/runtimeAssetCache.d.ts +1 -32
  89. package/dist/playground/runtimeAssetCache.js +1 -193
  90. package/dist/playground/runtimeSession.d.ts +2 -2
  91. package/dist/playground/runtimeSession.js +11 -11
  92. package/dist/playground/rust.d.ts +10 -0
  93. package/dist/playground/rust.js +230 -51
  94. package/dist/playground/sandbox.d.ts +8 -1
  95. package/dist/playground/staticStdinRing.d.ts +2 -1
  96. package/dist/playground/staticStdinRing.js +21 -10
  97. package/dist/playground/staticWorkerRuntime.d.ts +15 -1
  98. package/dist/playground/staticWorkerRuntime.js +127 -19
  99. package/dist/playground/stdinBuffer.d.ts +1 -1
  100. package/dist/playground/stdinBuffer.js +19 -2
  101. package/dist/playground/tinygo.d.ts +3 -0
  102. package/dist/playground/tinygo.js +88 -6
  103. package/dist/playground/typescript.js +8 -0
  104. package/dist/playground/v.d.ts +6 -2
  105. package/dist/playground/v.js +76 -13
  106. package/dist/playground/wasmAwkVersion.d.ts +13 -13
  107. package/dist/playground/wasmAwkVersion.js +4 -4
  108. package/dist/playground/wasmBqnVersion.d.ts +2 -2
  109. package/dist/playground/wasmBqnVersion.js +2 -2
  110. package/dist/playground/wasmC3Version.d.ts +2 -2
  111. package/dist/playground/wasmC3Version.js +2 -2
  112. package/dist/playground/wasmClojureScriptVersion.d.ts +2 -2
  113. package/dist/playground/wasmClojureScriptVersion.js +2 -2
  114. package/dist/playground/wasmCommonLispVersion.d.ts +2 -2
  115. package/dist/playground/wasmCommonLispVersion.js +2 -2
  116. package/dist/playground/wasmDIntegrity.d.ts +5 -5
  117. package/dist/playground/wasmDIntegrity.js +5 -5
  118. package/dist/playground/wasmDVersion.d.ts +16 -1
  119. package/dist/playground/wasmDVersion.js +16 -1
  120. package/dist/playground/wasmDebugVersion.d.ts +1 -1
  121. package/dist/playground/wasmDebugVersion.js +1 -1
  122. package/dist/playground/wasmForthVersion.d.ts +2 -2
  123. package/dist/playground/wasmForthVersion.js +2 -2
  124. package/dist/playground/wasmGleamVersion.d.ts +2 -2
  125. package/dist/playground/wasmGleamVersion.js +2 -2
  126. package/dist/playground/wasmGrainVersion.d.ts +2 -2
  127. package/dist/playground/wasmGrainVersion.js +2 -2
  128. package/dist/playground/wasmJVersion.d.ts +2 -2
  129. package/dist/playground/wasmJVersion.js +2 -2
  130. package/dist/playground/wasmJanetVersion.js +2 -2
  131. package/dist/playground/wasmJuliaVersion.js +2 -2
  132. package/dist/playground/wasmLean4Version.d.ts +1 -110
  133. package/dist/playground/wasmLean4Version.js +2 -111
  134. package/dist/playground/wasmLfortranVersion.d.ts +2 -2
  135. package/dist/playground/wasmLfortranVersion.js +2 -2
  136. package/dist/playground/wasmLuaVersion.d.ts +1 -1
  137. package/dist/playground/wasmLuaVersion.js +1 -1
  138. package/dist/playground/wasmNimVersion.d.ts +9 -9
  139. package/dist/playground/wasmNimVersion.js +6 -6
  140. package/dist/playground/wasmOcamlVersion.d.ts +2 -2
  141. package/dist/playground/wasmOcamlVersion.js +1 -1
  142. package/dist/playground/wasmPascalVersion.js +2 -2
  143. package/dist/playground/wasmPerlVersion.js +2 -2
  144. package/dist/playground/wasmPrologVersion.d.ts +2 -2
  145. package/dist/playground/wasmPrologVersion.js +2 -2
  146. package/dist/playground/wasmReScriptVersion.d.ts +2 -2
  147. package/dist/playground/wasmReScriptVersion.js +2 -2
  148. package/dist/playground/wasmRustVersion.d.ts +26 -38
  149. package/dist/playground/wasmRustVersion.js +25 -40
  150. package/dist/playground/wasmTclVersion.d.ts +4 -4
  151. package/dist/playground/wasmTclVersion.js +2 -2
  152. package/dist/playground/wasmTinyGoVersion.d.ts +14 -14
  153. package/dist/playground/wasmTinyGoVersion.js +14 -14
  154. package/dist/playground/wasmTypeScriptVersion.d.ts +5 -5
  155. package/dist/playground/wasmTypeScriptVersion.js +5 -5
  156. package/dist/playground/worker/cachedClangCompile.js +52 -4
  157. package/dist/playground/worker/cachedClangExecute.js +6 -5
  158. package/dist/playground/worker/clang.js +33 -11
  159. package/dist/playground/worker/cobol.js +3 -3
  160. package/dist/playground/worker/d.js +63 -7
  161. package/dist/playground/worker/fortran.js +3 -3
  162. package/dist/playground/worker/go.js +16 -5
  163. package/dist/playground/worker/haskell.js +10 -7
  164. package/dist/playground/worker/java.js +263 -45
  165. package/dist/playground/worker/javaDebugEvaluator.d.ts +16 -0
  166. package/dist/playground/worker/javaDebugEvaluator.js +44 -0
  167. package/dist/playground/worker/javaDebugRuntime.d.ts +24 -0
  168. package/dist/playground/worker/javaDebugRuntime.js +315 -0
  169. package/dist/playground/worker/javaOutput.d.ts +11 -0
  170. package/dist/playground/worker/javaOutput.js +54 -0
  171. package/dist/playground/worker/lua.js +15 -3
  172. package/dist/playground/worker/php.js +15 -9
  173. package/dist/playground/worker/python.js +102 -30
  174. package/dist/playground/worker/pythonExecution.js +17 -1
  175. package/dist/playground/worker/pythonWorkspaceFiles.d.ts +6 -0
  176. package/dist/playground/worker/pythonWorkspaceFiles.js +26 -0
  177. package/dist/playground/worker/pythonWorkspaceImports.d.ts +4 -0
  178. package/dist/playground/worker/pythonWorkspaceImports.js +129 -0
  179. package/dist/playground/worker/r.js +13 -6
  180. package/dist/playground/worker/ruby.js +13 -0
  181. package/dist/playground/worker/rubyDebugPreview.d.ts +2 -0
  182. package/dist/playground/worker/rubyDebugPreview.js +80 -0
  183. package/dist/playground/worker/rubyTracepoint.d.ts +16 -0
  184. package/dist/playground/worker/rubyTracepoint.js +162 -0
  185. package/dist/playground/worker/rust.js +38 -3
  186. package/dist/playground/worker/sqlite.js +4 -3
  187. package/dist/playground/worker/tinygo.js +11 -3
  188. package/dist/playground/worker/typescript.js +2 -3
  189. package/dist/playground/worker/v.js +32 -7
  190. package/dist/playground/worker/wat.js +2 -3
  191. package/dist/playground/worker/zig.js +20 -6
  192. package/dist/playground/workerSession.d.ts +1 -28
  193. package/dist/playground/workerSession.js +1 -164
  194. package/dist/playground/zig.js +4 -0
  195. package/package.json +66 -15
  196. package/dist/playground/worker/python.runtime.cases.d.ts +0 -1
  197. package/dist/playground/worker/python.runtime.cases.js +0 -374
@@ -0,0 +1,80 @@
1
+ /** Automatic locals must not dispatch user inspection or container overrides. */
2
+ export const RUBY_DEBUG_PREVIEW = String.raw `
3
+ debug_class = Kernel.instance_method(:class)
4
+ debug_equal = BasicObject.instance_method(:equal?)
5
+ debug_type_name = Module.instance_method(:name)
6
+ debug_string_slice = String.instance_method(:byteslice)
7
+ debug_string_size = String.instance_method(:bytesize)
8
+ debug_string_length = String.instance_method(:length)
9
+ debug_string_characters = String.instance_method(:[])
10
+ debug_string_encode = String.instance_method(:encode)
11
+ debug_string_inspect = String.instance_method(:inspect)
12
+ debug_integer_bits = Integer.instance_method(:bit_length)
13
+ debug_integer_text = Integer.instance_method(:to_s)
14
+ debug_integer_greater = Integer.instance_method(:>)
15
+ debug_integer_at_least = Integer.instance_method(:>=)
16
+ debug_integer_at_most = Integer.instance_method(:<=)
17
+ debug_integer_add = Integer.instance_method(:+)
18
+ debug_float_text = Float.instance_method(:to_s)
19
+ debug_symbol_name = Symbol.instance_method(:name)
20
+ debug_array_size = Array.instance_method(:length)
21
+ debug_array_get = Array.instance_method(:[])
22
+ debug_array_append = Array.instance_method(:<<)
23
+ debug_array_join = Array.instance_method(:join)
24
+ debug_hash_size = Hash.instance_method(:length)
25
+ debug_hash_each = Hash.instance_method(:each_pair)
26
+ preview_join = ->(*parts) { debug_array_join.bind_call(parts, '') }
27
+ preview_type = ->(value) do
28
+ kind = debug_class.bind_call(value)
29
+ name = debug_type_name.bind_call(kind)
30
+ name ? debug_string_encode.bind_call(debug_string_slice.bind_call(name, 0, 64), 'UTF-8', invalid: :replace, undef: :replace) : 'Object'
31
+ rescue StandardError
32
+ 'Object'
33
+ end
34
+ preview_value = nil
35
+ preview_value = ->(value, depth = 0) do
36
+ next '...' if debug_integer_at_least.bind_call(depth, 2)
37
+ next 'nil' if debug_equal.bind_call(value, nil)
38
+ next 'true' if debug_equal.bind_call(value, true)
39
+ next 'false' if debug_equal.bind_call(value, false)
40
+ kind = debug_class.bind_call(value)
41
+ text = if debug_equal.bind_call(kind, Integer)
42
+ bits = debug_integer_bits.bind_call(value)
43
+ debug_integer_at_most.bind_call(bits, 256) ? debug_integer_text.bind_call(value) : preview_join.call('<Integer: ', debug_integer_text.bind_call(bits), ' bits>')
44
+ elsif debug_equal.bind_call(kind, Float)
45
+ debug_float_text.bind_call(value)
46
+ elsif debug_equal.bind_call(kind, String) || debug_equal.bind_call(kind, Symbol)
47
+ string = debug_equal.bind_call(kind, Symbol) ? debug_symbol_name.bind_call(value) : value
48
+ prefix = debug_string_slice.bind_call(string, 0, 128)
49
+ prefix = debug_string_encode.bind_call(prefix, 'UTF-8', invalid: :replace, undef: :replace)
50
+ quoted = debug_string_inspect.bind_call(prefix)
51
+ preview_join.call(debug_equal.bind_call(kind, Symbol) ? ':' : '', quoted, debug_integer_greater.bind_call(debug_string_size.bind_call(string), 128) ? '...' : '')
52
+ elsif debug_equal.bind_call(kind, Array)
53
+ size = debug_array_size.bind_call(value)
54
+ items = []
55
+ limit = debug_integer_greater.bind_call(size, 8) ? 8 : size
56
+ # Integer#times can dispatch an overridden #succ in the pinned Ruby runtime.
57
+ index = 0
58
+ while debug_integer_greater.bind_call(limit, index)
59
+ debug_array_append.bind_call(items, preview_value.call(debug_array_get.bind_call(value, index), debug_integer_add.bind_call(depth, 1)))
60
+ index = debug_integer_add.bind_call(index, 1)
61
+ end
62
+ debug_array_append.bind_call(items, '...') if debug_integer_greater.bind_call(size, 8)
63
+ preview_join.call('[', debug_array_join.bind_call(items, ', '), ']')
64
+ elsif debug_equal.bind_call(kind, Hash)
65
+ items = []
66
+ debug_hash_each.bind_call(value) do |key, item|
67
+ next_depth = debug_integer_add.bind_call(depth, 1)
68
+ debug_array_append.bind_call(items, preview_join.call(preview_value.call(key, next_depth), '=>', preview_value.call(item, next_depth)))
69
+ break if debug_integer_at_least.bind_call(debug_array_size.bind_call(items), 6)
70
+ end
71
+ debug_array_append.bind_call(items, '...') if debug_integer_greater.bind_call(debug_hash_size.bind_call(value), 6)
72
+ preview_join.call('{', debug_array_join.bind_call(items, ', '), '}')
73
+ else
74
+ preview_join.call('<', preview_type.call(value), ' object>')
75
+ end
76
+ debug_integer_greater.bind_call(debug_string_length.bind_call(text), 512) ? preview_join.call(debug_string_characters.bind_call(text, 0, 509), '...') : text
77
+ rescue StandardError
78
+ preview_join.call('<', preview_type.call(value), ' object>')
79
+ end
80
+ `;
@@ -0,0 +1,16 @@
1
+ import type { DebugSourceBreakpoints } from '../options';
2
+ export interface RubyTracepointOptions {
3
+ path: string;
4
+ debugPath?: string;
5
+ breakpoints: number[];
6
+ sourceBreakpoints?: DebugSourceBreakpoints[];
7
+ pauseOnEntry: boolean;
8
+ files: Array<{
9
+ path: string;
10
+ content: string;
11
+ }>;
12
+ }
13
+ /** Real CRuby TracePoint and Binding APIs; user source is passed unchanged as eval data. */
14
+ export declare function executeRubyTracepoint(vm: {
15
+ eval(source: string): unknown;
16
+ }, source: string, options: RubyTracepointOptions, notify: (message: any) => void, read: (blocking: boolean) => string | null): Promise<void>;
@@ -0,0 +1,162 @@
1
+ import { RUBY_DEBUG_PREVIEW } from './rubyDebugPreview';
2
+ /** Real CRuby TracePoint and Binding APIs; user source is passed unchanged as eval data. */
3
+ export async function executeRubyTracepoint(vm, source, options, notify, read) {
4
+ const files = [...options.files, { path: options.path, content: source }];
5
+ const hashes = {};
6
+ for (const file of files) {
7
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(file.content));
8
+ hashes[file.path] = [...new Uint8Array(digest)]
9
+ .map((byte) => byte.toString(16).padStart(2, '0'))
10
+ .join('');
11
+ }
12
+ const key = `__wasmIdleRubyDebug_${crypto.randomUUID().replaceAll('-', '')}`;
13
+ const globals = globalThis;
14
+ globals[key] = {
15
+ notify: (json) => {
16
+ if (json.length > 2_000_000)
17
+ throw new Error('Ruby debugger snapshot exceeds its limit');
18
+ notify(JSON.parse(json));
19
+ },
20
+ read: (blocking) => read(blocking) ?? '{"op":"stop"}'
21
+ };
22
+ const data = JSON.stringify({ ...options, source, files, hashes, key });
23
+ const literal = `'${data.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
24
+ try {
25
+ vm.eval(String.raw `
26
+ require 'json'
27
+ require 'js'
28
+ Class.new do
29
+ def self.run(settings)
30
+ bridge = JS.global[settings['key']]
31
+ send_event = ->(value) { bridge.call(:notify, JSON.generate(value)) }
32
+ read_command = ->(blocking) do
33
+ text = bridge.call(:read, blocking).to_s
34
+ text.empty? ? nil : JSON.parse(text)
35
+ end
36
+ display_path = ->(path) do
37
+ path = path == settings['path'] ? (settings['debugPath'] || path) : path
38
+ '/workspace/' + path.sub(%r{\A(?:/workspace/|/+)}, '')
39
+ end
40
+ known = settings['files'].to_h { |file| [file['path'], file['content']] }
41
+ breakpoints = {}
42
+ executable = {}
43
+ known.each do |path, content|
44
+ next unless path == settings['path'] || path.end_with?('.rb')
45
+ begin
46
+ lines = []
47
+ collect = ->(iseq) do
48
+ lines.concat(iseq.trace_points.select { |_, event| event == :line }.map(&:first))
49
+ iseq.each_child { |child| collect.call(child) }
50
+ end
51
+ collect.call(RubyVM::InstructionSequence.compile(content, path, path, 1))
52
+ executable[display_path.call(path)] = lines.uniq.sort
53
+ rescue NameError, NoMethodError, SyntaxError
54
+ executable[display_path.call(path)] = []
55
+ end
56
+ end
57
+ set_breakpoints = ->(path, lines) do
58
+ path = display_path.call(path)
59
+ available = executable[path] || []
60
+ resolved = lines.uniq.map do |line|
61
+ actual = available.find { |candidate| candidate >= line }
62
+ {requestedLine:line, line:actual || line, verified:!actual.nil?, message:actual ? nil : 'No executable Ruby line'}
63
+ end
64
+ breakpoints[path] = resolved.select { |item| item[:verified] }.map { |item| item[:line] }
65
+ send_event.call({event:{type:'breakpoints',sourcePath:path,breakpoints:resolved}})
66
+ end
67
+ set_breakpoints.call(display_path.call(settings['path']), settings['breakpoints'])
68
+ (settings['sourceBreakpoints'] || []).each { |item| set_breakpoints.call(item['sourcePath'], item['lines']) }
69
+ format_value = ->(value) do
70
+ begin
71
+ value.inspect.encode('UTF-8', invalid: :replace, undef: :replace)[0,512]
72
+ rescue Exception => error
73
+ '<' + error.class.to_s + ' while inspecting>'
74
+ end
75
+ end
76
+ ${RUBY_DEBUG_PREVIEW}
77
+ local_values = ->(binding) do
78
+ binding.local_variables.first(50).map do |name|
79
+ value = binding.local_variable_get(name)
80
+ {name:name.to_s,value:preview_value.call(value),type:preview_type.call(value),variablesReference:0}
81
+ end
82
+ end
83
+ frames = []
84
+ mode = settings['pauseOnEntry'] ? 'entry' : 'continue'
85
+ target_depth = 0
86
+ pause_requested = false
87
+ stop_number = 0
88
+ trace = TracePoint.new(:line, :call, :return, :b_call, :b_return, :class, :end) do |point|
89
+ path = point.path.sub(%r{\A/+}, '')
90
+ next unless known.key?(path)
91
+ case point.event
92
+ when :return, :b_return, :end
93
+ frames.pop unless frames.empty?
94
+ next
95
+ when :call, :b_call, :class
96
+ frames << {binding:point.binding,path:path,line:point.lineno,name:point.method_id.to_s.empty? ? '<block>' : point.method_id.to_s}
97
+ next
98
+ end
99
+ frames << {binding:point.binding,path:path,line:point.lineno,name:'<main>'} if frames.empty?
100
+ frame = frames.last
101
+ frame[:binding] = point.binding
102
+ frame[:path] = path
103
+ frame[:line] = point.lineno
104
+ while (command = read_command.call(false))
105
+ case command['op']
106
+ when 'stop' then raise Interrupt, 'Ruby debugger stopped'
107
+ when 'pause' then pause_requested = true
108
+ when 'breakpoints' then set_breakpoints.call(command['sourcePath'], command['lines'])
109
+ end
110
+ end
111
+ breakpoint = (breakpoints[display_path.call(path)] || []).include?(point.lineno)
112
+ stepping = mode == 'entry' || mode == 'stepInto' || (mode == 'nextLine' && frames.length <= target_depth) || (mode == 'stepOut' && frames.length < target_depth)
113
+ next unless pause_requested || breakpoint || stepping
114
+ reason = pause_requested ? 'pause' : breakpoint ? 'breakpoint' : mode == 'entry' ? 'entry' : mode == 'stepInto' ? 'step' : mode
115
+ pause_requested = false
116
+ stop_number += 1
117
+ bindings = {}
118
+ snapshots = frames.reverse.first(32).each_with_index.map do |item, index|
119
+ id = stop_number * 1000 + index + 1
120
+ bindings[id] = item[:binding]
121
+ {id:id,functionName:item[:name],line:item[:line],sourcePath:display_path.call(item[:path]),sourceContentSha256:settings['hashes'][item[:path]],locals:local_values.call(item[:binding])}
122
+ end
123
+ top = snapshots.first
124
+ send_event.call({frames:snapshots,event:{type:'pause',reason:reason,line:top[:line],sourcePath:top[:sourcePath],sourceContentSha256:top[:sourceContentSha256],frameId:top[:id],threadId:1,locals:top[:locals],callStack:snapshots.map { |item| item.reject { |key,_| key == :locals } },scopes:[{name:'Locals',variablesReference:top[:id],namedVariables:top[:locals].length,expensive:false,variables:top[:locals]}],capabilities:{readMemory:false,writeMemory:false,dataBreakpoints:false}}})
125
+ loop do
126
+ command = read_command.call(true)
127
+ next unless command
128
+ case command['op']
129
+ when 'stop' then raise Interrupt, 'Ruby debugger stopped'
130
+ when 'breakpoints' then set_breakpoints.call(command['sourcePath'], command['lines'])
131
+ when 'evaluate'
132
+ begin
133
+ binding = bindings.fetch(command['frameId'])
134
+ value = format_value.call(binding.eval(command['expression']))
135
+ send_event.call({response:{id:command['id'],value:value}})
136
+ rescue Exception => error
137
+ send_event.call({response:{id:command['id'],error:error.class.to_s + ': ' + error.message}})
138
+ end
139
+ when 'control'
140
+ mode = command['command']
141
+ target_depth = frames.length
142
+ send_event.call({event:{type:'resume',command:mode}})
143
+ break
144
+ end
145
+ end
146
+ end
147
+ begin
148
+ trace.enable
149
+ eval(settings['source'], TOPLEVEL_BINDING, settings['path'], 1)
150
+ ensure
151
+ trace.disable
152
+ STDOUT.flush
153
+ STDERR.flush
154
+ end
155
+ end
156
+ end.run(JSON.parse(${literal}))
157
+ `);
158
+ }
159
+ finally {
160
+ delete globals[key];
161
+ }
162
+ }
@@ -213,6 +213,9 @@ async function loadCompiler(url, profile = runtimeProfile, moduleUrls = verified
213
213
  compiler: await factory({
214
214
  dependencies: { runtimeProfile: bootstrap.profile }
215
215
  }),
216
+ createCompiler: (createRustcModuleService) => factory({
217
+ dependencies: { runtimeProfile: bootstrap.profile, createRustcModuleService }
218
+ }),
216
219
  executeBrowserRustArtifact: module.executeBrowserRustArtifact
217
220
  };
218
221
  })();
@@ -403,9 +406,18 @@ function createRustDebugHost(options) {
403
406
  };
404
407
  }
405
408
  self.onmessage = async (event) => {
406
- const { load, persistentCache, compilerUrl: nextCompilerUrl, runtimeProfile: nextRuntimeProfile, verifiedModuleUrls: nextVerifiedModuleUrls, executableGraphFingerprint: nextExecutableGraphFingerprint, debugModuleUrl: nextDebugModuleUrl, buffer, debugBuffer, code, prepare, args = [], stdin, targetTriple = 'wasm32-wasip1', log, debug = false, debugMode: requestedDebugMode, breakpoints = [], pauseOnEntry = false, limits: executionLimits } = event.data;
409
+ const { load, persistentCache, compilerUrl: nextCompilerUrl, runtimeProfile: nextRuntimeProfile, verifiedModuleUrls: nextVerifiedModuleUrls, executableGraphFingerprint: nextExecutableGraphFingerprint, debugModuleUrl: nextDebugModuleUrl, buffer, debugBuffer, code, prepare, args = [], stdin, targetTriple = 'wasm32-wasip1', optimizationProfile: requestedOptimizationProfile = 'interactive', log, debug = false, debugMode: requestedDebugMode, breakpoints = [], pauseOnEntry = false, limits: executionLimits } = event.data;
410
+ const nextRustcModuleBroker = event.data.rustcModuleBroker;
411
+ let rustcModuleBroker;
407
412
  let ownsExecution = false;
408
413
  try {
414
+ if (nextRustcModuleBroker !== undefined) {
415
+ if (typeof MessagePort === 'undefined' ||
416
+ !(nextRustcModuleBroker instanceof MessagePort)) {
417
+ throw new Error('Rust module broker must be a private MessagePort');
418
+ }
419
+ rustcModuleBroker = nextRustcModuleBroker;
420
+ }
409
421
  if (load) {
410
422
  if (acceptedCompilerBootstrap) {
411
423
  throw new Error('wasm-rust application worker accepts exactly one bootstrap');
@@ -440,6 +452,7 @@ self.onmessage = async (event) => {
440
452
  if (debugMode !== 'none' && debugMode !== 'trace' && debugMode !== 'lldb') {
441
453
  throw new Error(`Unsupported Rust debug mode: ${String(debugMode)}`);
442
454
  }
455
+ const optimizationProfile = debugMode === 'none' ? requestedOptimizationProfile : 'interactive';
443
456
  const nonDebugResourceLimits = debugMode === 'none' ? snapshotRustNonDebugResourceLimits(executionLimits) : undefined;
444
457
  stdinBufferRust = new Int32Array(buffer);
445
458
  debugBufferRust = debugBuffer ? new Int32Array(debugBuffer) : null;
@@ -473,6 +486,7 @@ self.onmessage = async (event) => {
473
486
  const compileCacheKey = [
474
487
  executableGraphFingerprint,
475
488
  debugMode,
489
+ optimizationProfile,
476
490
  targetTriple,
477
491
  ...(nonDebugResourceLimits
478
492
  ? [String(nonDebugResourceLimits.maxAssetDeliveryBytes)]
@@ -486,10 +500,28 @@ self.onmessage = async (event) => {
486
500
  if (log) {
487
501
  console.log(`[wasm-idle:rust-worker] compile start prepare=${String(prepare)} target=${targetTriple} bytes=${compileCode.length}`);
488
502
  }
489
- const result = await runtime.compiler.compile({
503
+ const moduleBroker = rustcModuleBroker;
504
+ const compiler = moduleBroker
505
+ ? await runtime.createCompiler(() => {
506
+ if (!ownsExecution)
507
+ throw new Error('Rust module service run expired');
508
+ const channel = new MessageChannel();
509
+ try {
510
+ moduleBroker.postMessage({ type: 'rustc-module-service', port: channel.port1 }, [channel.port1]);
511
+ }
512
+ catch (error) {
513
+ channel.port1.close();
514
+ channel.port2.close();
515
+ throw error;
516
+ }
517
+ return { port: channel.port2, close: () => channel.port2.close() };
518
+ })
519
+ : runtime.compiler;
520
+ const result = await compiler.compile({
490
521
  ...(assetCache ? { assetCache } : {}),
491
522
  code: compileCode,
492
523
  debugMode,
524
+ optimizationProfile,
493
525
  ...(nonDebugResourceLimits
494
526
  ? {
495
527
  workerLimits: nonDebugResourceLimits.compilerLimits,
@@ -686,7 +718,10 @@ self.onmessage = async (event) => {
686
718
  });
687
719
  }
688
720
  finally {
689
- if (ownsExecution)
721
+ if (ownsExecution) {
690
722
  activeExecution = false;
723
+ ownsExecution = false;
724
+ }
725
+ rustcModuleBroker?.close();
691
726
  }
692
727
  };
@@ -49,12 +49,13 @@ function normalizeWorkspacePath(path) {
49
49
  .filter((part) => part && part !== '.' && part !== '..' && !part.includes('\0'))
50
50
  .join('/');
51
51
  }
52
- function loadWorkspaceFiles(db, workspaceFiles) {
52
+ function loadWorkspaceFiles(db, workspaceFiles, activePath) {
53
+ const normalizedActivePath = normalizeWorkspacePath(activePath);
53
54
  for (const file of workspaceFiles) {
54
55
  const normalizedPath = normalizeWorkspacePath(file.path);
55
56
  if (!normalizedPath || !normalizedPath.endsWith('.sql'))
56
57
  continue;
57
- if (normalizedPath === 'main.sql')
58
+ if (normalizedPath === normalizedActivePath)
58
59
  continue;
59
60
  db.exec(file.content);
60
61
  }
@@ -79,7 +80,7 @@ self.onmessage = async (event) => {
79
80
  }
80
81
  const db = new SQL.Database();
81
82
  try {
82
- loadWorkspaceFiles(db, workspaceFiles);
83
+ loadWorkspaceFiles(db, workspaceFiles, activePath);
83
84
  postMessage({
84
85
  progress: {
85
86
  kind: 'ready',
@@ -6,7 +6,6 @@ self.document = {
6
6
  }
7
7
  };
8
8
  const encoder = new TextEncoder();
9
- const decoder = new TextDecoder();
10
9
  const postExecutionReady = () => postMessage({
11
10
  progress: {
12
11
  kind: 'ready',
@@ -83,13 +82,15 @@ self.onmessage = async (event) => {
83
82
  stdinBufferTinyGo = stdin === undefined ? new Int32Array(buffer) : null;
84
83
  stdinChunkTinyGo = stdin === undefined ? new Uint8Array(0) : encoder.encode(stdin);
85
84
  stdinChunkOffsetTinyGo = 0;
85
+ const stdoutDecoder = new TextDecoder();
86
+ const stderrDecoder = new TextDecoder();
86
87
  const stdout = new ConsoleStdout((chunk) => {
87
- const text = decoder.decode(chunk);
88
+ const text = stdoutDecoder.decode(chunk, { stream: true });
88
89
  if (text)
89
90
  postMessage({ output: text });
90
91
  });
91
92
  const stderr = new ConsoleStdout((chunk) => {
92
- const text = decoder.decode(chunk);
93
+ const text = stderrDecoder.decode(chunk, { stream: true });
93
94
  if (text)
94
95
  postMessage({ output: text });
95
96
  });
@@ -136,6 +137,13 @@ self.onmessage = async (event) => {
136
137
  throw error;
137
138
  }
138
139
  }
140
+ finally {
141
+ for (const decoder of [stdoutDecoder, stderrDecoder]) {
142
+ const text = decoder.decode();
143
+ if (text)
144
+ postMessage({ output: text });
145
+ }
146
+ }
139
147
  if (log) {
140
148
  console.log(`[wasm-idle:tinygo-worker] wasi run complete exitCode=${String(exitCode)}`);
141
149
  }
@@ -239,9 +239,8 @@ self.onmessage = async (event) => {
239
239
  }
240
240
  });
241
241
  if (execution.exitCode !== 0) {
242
- throw new Error(execution.stderr
243
- ? `${language === 'typescript' ? 'TypeScript' : 'JavaScript'} program exited with code ${execution.exitCode}\n${execution.stderr}`
244
- : `${language === 'typescript' ? 'TypeScript' : 'JavaScript'} program exited with code ${execution.exitCode}`);
242
+ // stderr was already streamed to the terminal above.
243
+ throw new Error(`${language === 'typescript' ? 'TypeScript' : 'JavaScript'} program exited with code ${execution.exitCode}`);
245
244
  }
246
245
  postMessage({ results: true });
247
246
  }
@@ -1,3 +1,4 @@
1
+ import { normalizeLldbWorkspacePath } from '../lldbSourcePath';
1
2
  import { waitForBufferedStdin } from '../stdinBuffer';
2
3
  import { configureWorkerRuntimeAssets, handleWorkerAssetMessage } from './assets';
3
4
  import { createVCompiler, executeBrowserVArtifact } from '@wasm-idle/llvm-core/v';
@@ -44,17 +45,17 @@ async function loadVRuntime(clangAssets, vBaseUrl, maxAssetBytes, log) {
44
45
  self.onmessage = async (event) => {
45
46
  if (handleWorkerAssetMessage(event.data))
46
47
  return;
47
- const { code, buffer, load, log, prepare, compileArgs, programArgs, activePath, workspaceFiles, stdin, clangAssets, vBaseUrl, maxAssetBytes } = event.data;
48
+ const { code, buffer, load, log, prepare, compileArgs, programArgs, activePath, workspaceFiles, stdin, clangAssets, vBaseUrl, maxAssetBytes, debugMode } = event.data;
48
49
  if (load) {
49
50
  try {
50
51
  await loadVRuntime(clangAssets, vBaseUrl, maxAssetBytes, log);
51
52
  postMessage({ load: true });
52
53
  }
53
54
  catch (error) {
54
- postMessage({ error: error.message });
55
+ postMessage({ error: error?.message || String(error) });
55
56
  }
56
57
  }
57
- else if (typeof log === 'boolean' && !code) {
58
+ else if (code === '' || (typeof log === 'boolean' && code === undefined)) {
58
59
  // The compiler receives the current logging preference for every compilation.
59
60
  if (typeof code === 'string')
60
61
  postMessage({ results: true });
@@ -69,10 +70,16 @@ self.onmessage = async (event) => {
69
70
  initialStdinV = hasInitialStdinV ? stdin : null;
70
71
  initialStdinConsumedV = false;
71
72
  try {
72
- const files = (workspaceFiles || []);
73
+ const lldb = debugMode === 'lldb';
74
+ const files = (workspaceFiles || []).map((file) => ({
75
+ ...file,
76
+ path: lldb ? normalizeLldbWorkspacePath(file.path) : file.path
77
+ }));
78
+ const fileName = resolveInputPath(lldb ? normalizeLldbWorkspacePath(activePath || '') : activePath);
73
79
  const result = await compiler.compile({
74
- code: ensureTrailingNewline(code),
75
- fileName: resolveInputPath(activePath),
80
+ code: lldb ? code : ensureTrailingNewline(code),
81
+ fileName,
82
+ debugMode: lldb ? 'lldb' : 'none',
76
83
  compileArgs: compileArgs || [],
77
84
  workspaceFiles: files,
78
85
  log,
@@ -85,6 +92,24 @@ self.onmessage = async (event) => {
85
92
  if (!result.success || !result.artifact) {
86
93
  throw new Error(result.stderr || 'V did not produce a WebAssembly program.');
87
94
  }
95
+ if (lldb && !prepare) {
96
+ const descriptor = result.artifact.debug;
97
+ if (!descriptor)
98
+ throw new Error('V compiler did not produce a DWARF descriptor.');
99
+ const sources = new Map(files.map((file) => [`/workspace/${file.path}`, file.content]));
100
+ sources.set(`/workspace/${fileName}`, code);
101
+ postMessage({
102
+ lldbArtifact: {
103
+ bytes: result.artifact.bytes,
104
+ descriptor,
105
+ sources: descriptor.files.map((file) => ({
106
+ ...file,
107
+ content: sources.get(file.path)
108
+ }))
109
+ }
110
+ });
111
+ return;
112
+ }
88
113
  if (!prepare) {
89
114
  const execution = await executeBrowserVArtifact(result.artifact, {
90
115
  args: programArgs || [],
@@ -100,7 +125,7 @@ self.onmessage = async (event) => {
100
125
  postMessage({ results: true });
101
126
  }
102
127
  catch (error) {
103
- postMessage({ error: error.message });
128
+ postMessage({ error: error?.message || String(error) });
104
129
  }
105
130
  }
106
131
  };
@@ -173,9 +173,8 @@ self.onmessage = async (event) => {
173
173
  }
174
174
  });
175
175
  if (execution.exitCode !== 0) {
176
- throw new Error(execution.stderr
177
- ? `WAT module exited with code ${execution.exitCode}\n${execution.stderr}`
178
- : `WAT module exited with code ${execution.exitCode}`);
176
+ // stderr was already streamed to the terminal above.
177
+ throw new Error(`WAT module exited with code ${execution.exitCode}`);
179
178
  }
180
179
  postMessage({ results: true });
181
180
  }
@@ -5,7 +5,6 @@ import { waitForBufferedStdin } from '../stdinBuffer';
5
5
  import { snapshotZigExecutionAssetReceipts } from '../zigAssets';
6
6
  import { fetchRuntimeAssetBytes, resolveRuntimeAssetUrl } from './runtimeAssetFetch';
7
7
  const encoder = new TextEncoder();
8
- const decoder = new TextDecoder();
9
8
  const DEFAULT_ZIG_STDLIB_MAX_EXPANDED_BYTES = 128 * 1024 * 1024;
10
9
  const DEFAULT_ZIG_STDLIB_MAX_FILES = 4096;
11
10
  const DEFAULT_ZIP_FILE_BUFFER_BYTES = 64 * 1024;
@@ -443,11 +442,13 @@ async function compileZig({ code, activePath, workspaceFiles, targetTriple, comp
443
442
  const { compilerModule, stdDirectory } = await loadAssets(compilerUrl, stdlibUrl, assetIntegrity, runtimeMaxAssetBytes);
444
443
  const { root, entryPath } = buildWorkspaceRoot(code, activePath, workspaceFiles);
445
444
  let compilerOutput = '';
445
+ const outputDecoder = new TextDecoder();
446
+ const errorDecoder = new TextDecoder();
446
447
  const outputFd = new ConsoleStdout((chunk) => {
447
- compilerOutput += decoder.decode(chunk, { stream: true });
448
+ compilerOutput += outputDecoder.decode(chunk, { stream: true });
448
449
  });
449
450
  const errorFd = new ConsoleStdout((chunk) => {
450
- compilerOutput += decoder.decode(chunk, { stream: true });
451
+ compilerOutput += errorDecoder.decode(chunk, { stream: true });
451
452
  });
452
453
  const args = [
453
454
  'zigc.wasm',
@@ -476,6 +477,7 @@ async function compileZig({ code, activePath, workspaceFiles, targetTriple, comp
476
477
  wasi_snapshot_preview1: zigWasi.wasiImport
477
478
  }));
478
479
  const exitCode = zigWasi.start(instance);
480
+ compilerOutput += outputDecoder.decode() + errorDecoder.decode();
479
481
  if (compilerOutput)
480
482
  postMessage({ output: compilerOutput });
481
483
  if (exitCode !== 0) {
@@ -493,13 +495,15 @@ async function compileZig({ code, activePath, workspaceFiles, targetTriple, comp
493
495
  async function runZigArtifact({ artifact, args, stdin, log }) {
494
496
  stdinChunkZig = new Uint8Array(0);
495
497
  stdinChunkOffsetZig = 0;
498
+ const stdoutDecoder = new TextDecoder();
499
+ const stderrDecoder = new TextDecoder();
496
500
  const stdout = new ConsoleStdout((chunk) => {
497
- const text = decoder.decode(chunk, { stream: true });
501
+ const text = stdoutDecoder.decode(chunk, { stream: true });
498
502
  if (text)
499
503
  postMessage({ output: text });
500
504
  });
501
505
  const stderr = new ConsoleStdout((chunk) => {
502
- const text = decoder.decode(chunk, { stream: true });
506
+ const text = stderrDecoder.decode(chunk, { stream: true });
503
507
  if (text)
504
508
  postMessage({ output: text });
505
509
  });
@@ -516,7 +520,17 @@ async function runZigArtifact({ artifact, args, stdin, log }) {
516
520
  label: 'Zig program started'
517
521
  }
518
522
  });
519
- const exitCode = zigWasi.start(instance);
523
+ let exitCode;
524
+ try {
525
+ exitCode = zigWasi.start(instance);
526
+ }
527
+ finally {
528
+ for (const decoder of [stdoutDecoder, stderrDecoder]) {
529
+ const text = decoder.decode();
530
+ if (text)
531
+ postMessage({ output: text });
532
+ }
533
+ }
520
534
  if (log) {
521
535
  console.log(`[wasm-idle:zig-worker] wasi run complete exitCode=${String(exitCode)}`);
522
536
  }
@@ -1,28 +1 @@
1
- export type WorkerOperation = symbol;
2
- type WorkerSessionOptions = {
3
- label: string | (() => string);
4
- onDispose?: (worker: Worker) => void;
5
- };
6
- export declare class WorkerSession {
7
- private readonly options;
8
- private worker;
9
- private activeOperation;
10
- constructor(options: WorkerSessionOptions);
11
- attach(worker: Worker): Worker;
12
- attach(worker: Worker, operation: WorkerOperation): Worker | null;
13
- load(initialize: (resolve: () => void, reject: (reason?: unknown) => void, operation: WorkerOperation) => void | Promise<void>): Promise<void>;
14
- waitForLoad(worker: Worker, initialize: (resolve: () => void, reject: (reason?: unknown) => void) => void): Promise<void>;
15
- beginRun(worker: Worker | null | undefined, reject: (reason?: unknown) => void): symbol;
16
- complete(operation: WorkerOperation): boolean;
17
- release(worker: Worker): boolean;
18
- reset(): void;
19
- terminate(reason?: unknown): void;
20
- private get label();
21
- private startOperation;
22
- isActive(operation: WorkerOperation): boolean;
23
- private fail;
24
- private notifyDisposed;
25
- private disposeWorker;
26
- private retireWorker;
27
- }
28
- export {};
1
+ export { WorkerSession, type WorkerOperation } from '@wasm-idle/core';