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.
- package/README.md +267 -112
- package/dist/container/bash-profile.d.ts +80 -0
- package/dist/container/bash-profile.js +328 -0
- package/dist/container/binding.d.ts +39 -0
- package/dist/container/binding.js +331 -0
- package/dist/container/clang-runtime.d.ts +42 -0
- package/dist/container/clang-runtime.js +561 -0
- package/dist/container/client.d.ts +14 -0
- package/dist/container/client.js +185 -0
- package/dist/container/explorer.d.ts +31 -0
- package/dist/container/explorer.js +112 -0
- package/dist/container/index.d.ts +11 -0
- package/dist/container/index.js +11 -0
- package/dist/container/owner-worker.d.ts +19 -0
- package/dist/container/owner-worker.js +464 -0
- package/dist/container/protocol.d.ts +84 -0
- package/dist/container/protocol.js +28 -0
- package/dist/container/runtime-adapter.d.ts +75 -0
- package/dist/container/runtime-adapter.js +537 -0
- package/dist/container/shell-control.d.ts +49 -0
- package/dist/container/shell-control.js +360 -0
- package/dist/container/workspace.d.ts +12 -0
- package/dist/container/workspace.js +29 -0
- package/dist/index.d.ts +1 -1
- package/dist/playground/assetBridge.js +111 -33
- package/dist/playground/assets.d.ts +10 -2
- package/dist/playground/c3.js +22 -0
- package/dist/playground/c3Memory.d.ts +19 -0
- package/dist/playground/c3Memory.js +117 -0
- package/dist/playground/cachedClang.js +143 -34
- package/dist/playground/clang.d.ts +5 -1
- package/dist/playground/clang.js +61 -5
- package/dist/playground/clangAssetIntegrity.js +6 -6
- package/dist/playground/clangWorkerProtocol.d.ts +12 -1
- package/dist/playground/cobol.d.ts +3 -0
- package/dist/playground/cobol.js +10 -1
- package/dist/playground/commonlispAssets.d.ts +2 -2
- package/dist/playground/compiledArtifactCache.d.ts +3 -1
- package/dist/playground/compiledArtifactCache.js +31 -5
- package/dist/playground/compiledLldb.d.ts +41 -0
- package/dist/playground/compiledLldb.js +167 -0
- package/dist/playground/d.d.ts +10 -2
- package/dist/playground/d.js +161 -14
- package/dist/playground/debugDeadline.d.ts +12 -0
- package/dist/playground/debugDeadline.js +34 -0
- package/dist/playground/debugMailbox.d.ts +12 -0
- package/dist/playground/debugMailbox.js +77 -0
- package/dist/playground/dotnet.js +6 -8
- package/dist/playground/fortran.d.ts +3 -0
- package/dist/playground/fortran.js +10 -1
- package/dist/playground/go.js +23 -7
- package/dist/playground/goDebugInstrumentation.js +207 -97
- package/dist/playground/java-debug-FMHDKUN6.js +124 -0
- package/dist/playground/java-debug-notices.txt +492 -0
- package/dist/playground/java.d.ts +17 -1
- package/dist/playground/java.js +162 -5
- package/dist/playground/javaDebug.d.ts +62 -0
- package/dist/playground/javaDebug.js +305 -0
- package/dist/playground/javaDebugBridge.d.ts +6 -0
- package/dist/playground/javaDebugBridge.js +250 -0
- package/dist/playground/javaDebugSource.d.ts +9 -0
- package/dist/playground/javaDebugSource.js +4 -0
- package/dist/playground/javaRuntimeErrors.d.ts +9 -0
- package/dist/playground/javaRuntimeErrors.js +93 -0
- package/dist/playground/lean4Assets.d.ts +1 -25
- package/dist/playground/lean4Assets.js +2 -123
- package/dist/playground/lfortran.js +10 -0
- package/dist/playground/lfortranAssets.d.ts +2 -2
- package/dist/playground/lldbSession.d.ts +23 -2
- package/dist/playground/lldbSession.js +278 -58
- package/dist/playground/lldbSourcePath.d.ts +2 -0
- package/dist/playground/lldbSourcePath.js +9 -0
- package/dist/playground/lua.d.ts +20 -1
- package/dist/playground/lua.js +190 -8
- package/dist/playground/luaDebug.d.ts +1 -0
- package/dist/playground/luaDebug.js +1 -0
- package/dist/playground/nim.d.ts +1 -0
- package/dist/playground/nim.js +30 -0
- package/dist/playground/objectivec.d.ts +10 -6
- package/dist/playground/objectivec.js +85 -10
- package/dist/playground/options.d.ts +12 -4
- package/dist/playground/python.d.ts +8 -1
- package/dist/playground/python.js +89 -6
- package/dist/playground/ruby.d.ts +10 -1
- package/dist/playground/ruby.js +66 -1
- package/dist/playground/rubyDebug.d.ts +21 -0
- package/dist/playground/rubyDebug.js +128 -0
- package/dist/playground/runtimeAssetCache.d.ts +1 -32
- package/dist/playground/runtimeAssetCache.js +1 -193
- package/dist/playground/runtimeSession.d.ts +2 -2
- package/dist/playground/runtimeSession.js +11 -11
- package/dist/playground/rust.d.ts +10 -0
- package/dist/playground/rust.js +230 -51
- package/dist/playground/sandbox.d.ts +8 -1
- package/dist/playground/staticStdinRing.d.ts +2 -1
- package/dist/playground/staticStdinRing.js +21 -10
- package/dist/playground/staticWorkerRuntime.d.ts +15 -1
- package/dist/playground/staticWorkerRuntime.js +127 -19
- package/dist/playground/stdinBuffer.d.ts +1 -1
- package/dist/playground/stdinBuffer.js +19 -2
- package/dist/playground/tinygo.d.ts +3 -0
- package/dist/playground/tinygo.js +88 -6
- package/dist/playground/typescript.js +8 -0
- package/dist/playground/v.d.ts +6 -2
- package/dist/playground/v.js +76 -13
- package/dist/playground/wasmAwkVersion.d.ts +13 -13
- package/dist/playground/wasmAwkVersion.js +4 -4
- package/dist/playground/wasmBqnVersion.d.ts +2 -2
- package/dist/playground/wasmBqnVersion.js +2 -2
- package/dist/playground/wasmC3Version.d.ts +2 -2
- package/dist/playground/wasmC3Version.js +2 -2
- package/dist/playground/wasmClojureScriptVersion.d.ts +2 -2
- package/dist/playground/wasmClojureScriptVersion.js +2 -2
- package/dist/playground/wasmCommonLispVersion.d.ts +2 -2
- package/dist/playground/wasmCommonLispVersion.js +2 -2
- package/dist/playground/wasmDIntegrity.d.ts +5 -5
- package/dist/playground/wasmDIntegrity.js +5 -5
- package/dist/playground/wasmDVersion.d.ts +16 -1
- package/dist/playground/wasmDVersion.js +16 -1
- package/dist/playground/wasmDebugVersion.d.ts +1 -1
- package/dist/playground/wasmDebugVersion.js +1 -1
- package/dist/playground/wasmForthVersion.d.ts +2 -2
- package/dist/playground/wasmForthVersion.js +2 -2
- package/dist/playground/wasmGleamVersion.d.ts +2 -2
- package/dist/playground/wasmGleamVersion.js +2 -2
- package/dist/playground/wasmGrainVersion.d.ts +2 -2
- package/dist/playground/wasmGrainVersion.js +2 -2
- package/dist/playground/wasmJVersion.d.ts +2 -2
- package/dist/playground/wasmJVersion.js +2 -2
- package/dist/playground/wasmJanetVersion.js +2 -2
- package/dist/playground/wasmJuliaVersion.js +2 -2
- package/dist/playground/wasmLean4Version.d.ts +1 -110
- package/dist/playground/wasmLean4Version.js +2 -111
- package/dist/playground/wasmLfortranVersion.d.ts +2 -2
- package/dist/playground/wasmLfortranVersion.js +2 -2
- package/dist/playground/wasmLuaVersion.d.ts +1 -1
- package/dist/playground/wasmLuaVersion.js +1 -1
- package/dist/playground/wasmNimVersion.d.ts +9 -9
- package/dist/playground/wasmNimVersion.js +6 -6
- package/dist/playground/wasmOcamlVersion.d.ts +2 -2
- package/dist/playground/wasmOcamlVersion.js +1 -1
- package/dist/playground/wasmPascalVersion.js +2 -2
- package/dist/playground/wasmPerlVersion.js +2 -2
- package/dist/playground/wasmPrologVersion.d.ts +2 -2
- package/dist/playground/wasmPrologVersion.js +2 -2
- package/dist/playground/wasmReScriptVersion.d.ts +2 -2
- package/dist/playground/wasmReScriptVersion.js +2 -2
- package/dist/playground/wasmRustVersion.d.ts +26 -38
- package/dist/playground/wasmRustVersion.js +25 -40
- package/dist/playground/wasmTclVersion.d.ts +4 -4
- package/dist/playground/wasmTclVersion.js +2 -2
- package/dist/playground/wasmTinyGoVersion.d.ts +14 -14
- package/dist/playground/wasmTinyGoVersion.js +14 -14
- package/dist/playground/wasmTypeScriptVersion.d.ts +5 -5
- package/dist/playground/wasmTypeScriptVersion.js +5 -5
- package/dist/playground/worker/cachedClangCompile.js +52 -4
- package/dist/playground/worker/cachedClangExecute.js +6 -5
- package/dist/playground/worker/clang.js +33 -11
- package/dist/playground/worker/cobol.js +3 -3
- package/dist/playground/worker/d.js +63 -7
- package/dist/playground/worker/fortran.js +3 -3
- package/dist/playground/worker/go.js +16 -5
- package/dist/playground/worker/haskell.js +10 -7
- package/dist/playground/worker/java.js +263 -45
- package/dist/playground/worker/javaDebugEvaluator.d.ts +16 -0
- package/dist/playground/worker/javaDebugEvaluator.js +44 -0
- package/dist/playground/worker/javaDebugRuntime.d.ts +24 -0
- package/dist/playground/worker/javaDebugRuntime.js +315 -0
- package/dist/playground/worker/javaOutput.d.ts +11 -0
- package/dist/playground/worker/javaOutput.js +54 -0
- package/dist/playground/worker/lua.js +15 -3
- package/dist/playground/worker/php.js +15 -9
- package/dist/playground/worker/python.js +102 -30
- package/dist/playground/worker/pythonExecution.js +17 -1
- package/dist/playground/worker/pythonWorkspaceFiles.d.ts +6 -0
- package/dist/playground/worker/pythonWorkspaceFiles.js +26 -0
- package/dist/playground/worker/pythonWorkspaceImports.d.ts +4 -0
- package/dist/playground/worker/pythonWorkspaceImports.js +129 -0
- package/dist/playground/worker/r.js +13 -6
- package/dist/playground/worker/ruby.js +13 -0
- package/dist/playground/worker/rubyDebugPreview.d.ts +2 -0
- package/dist/playground/worker/rubyDebugPreview.js +80 -0
- package/dist/playground/worker/rubyTracepoint.d.ts +16 -0
- package/dist/playground/worker/rubyTracepoint.js +162 -0
- package/dist/playground/worker/rust.js +38 -3
- package/dist/playground/worker/sqlite.js +4 -3
- package/dist/playground/worker/tinygo.js +11 -3
- package/dist/playground/worker/typescript.js +2 -3
- package/dist/playground/worker/v.js +32 -7
- package/dist/playground/worker/wat.js +2 -3
- package/dist/playground/worker/zig.js +20 -6
- package/dist/playground/workerSession.d.ts +1 -28
- package/dist/playground/workerSession.js +1 -164
- package/dist/playground/zig.js +4 -0
- package/package.json +66 -15
- package/dist/playground/worker/python.runtime.cases.d.ts +0 -1
- package/dist/playground/worker/python.runtime.cases.js +0 -374
|
@@ -1,50 +1,48 @@
|
|
|
1
1
|
import { acceptCompiledTeaVmModule, loadStreamingJavaCompiler } from './javaStreaming';
|
|
2
|
+
import { createJavaOutput } from './javaOutput';
|
|
2
3
|
import { createJavaStdinBridge, prepareJavaRuntimeStdinInjection } from '../javaRuntimeStdin';
|
|
3
4
|
import { resolveJavaSourceIdentity } from '../javaSource';
|
|
5
|
+
import { prepareJavaExceptionBridge } from '../javaRuntimeErrors';
|
|
4
6
|
import { waitForBufferedStdin } from '../stdinBuffer';
|
|
7
|
+
import { createJavaDebugBridge } from '../javaDebugBridge';
|
|
8
|
+
import { readDebugCommand } from '../debugMailbox';
|
|
9
|
+
import { createJavaDebugRuntime } from './javaDebugRuntime';
|
|
5
10
|
import { configureWorkerRuntimeAssets, handleWorkerAssetMessage, loadWorkerRuntimeAsset } from './assets';
|
|
6
11
|
let compilerLib = null;
|
|
7
12
|
let compiler = null;
|
|
8
13
|
let runtimeLoad = null;
|
|
14
|
+
let exceptionDeobfuscator = null;
|
|
9
15
|
let loadedBaseUrl = '';
|
|
10
|
-
let
|
|
11
|
-
let stderrBuffer = '';
|
|
16
|
+
let output = null;
|
|
12
17
|
let compiledCode = '';
|
|
13
18
|
let compiledStdin = '';
|
|
14
19
|
let compiledMainClass = '';
|
|
20
|
+
let compiledExceptionFormatter = '';
|
|
15
21
|
let compiledWasm = null;
|
|
22
|
+
let compiledModule = null;
|
|
23
|
+
let acceptsCompiledModule = false;
|
|
16
24
|
let compiledDiagnostics = [];
|
|
17
25
|
let compiledActivePath = '';
|
|
18
26
|
let compiledWorkspaceFiles = [];
|
|
27
|
+
let compiledDebugEnabled = false;
|
|
28
|
+
let compiledDebugFiles = [];
|
|
29
|
+
// Only the isolated debugger evaluator opts in. Entries contain immutable compiled
|
|
30
|
+
// code, never instances/imports/heap state; every evaluation still loads a fresh instance.
|
|
31
|
+
const evaluationArtifacts = new Map();
|
|
32
|
+
const MAX_EVALUATION_ARTIFACTS = 8;
|
|
33
|
+
const MAX_EVALUATION_ARTIFACT_BYTES = 16 * 1024 * 1024;
|
|
34
|
+
let evaluationArtifactBytes = 0;
|
|
19
35
|
let currentSourcePaths = new Set();
|
|
20
36
|
const decoder = new TextDecoder();
|
|
21
37
|
const toInt8Array = (bytes) => new Int8Array(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
|
|
22
|
-
const flushStdout = () =>
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
stdoutBuffer = '';
|
|
27
|
-
};
|
|
28
|
-
const flushStderr = () => {
|
|
29
|
-
if (!stderrBuffer)
|
|
30
|
-
return;
|
|
31
|
-
self.postMessage({ output: stderrBuffer });
|
|
32
|
-
stderrBuffer = '';
|
|
33
|
-
};
|
|
34
|
-
const pushStdout = (charCode) => {
|
|
35
|
-
stdoutBuffer += String.fromCharCode(charCode);
|
|
36
|
-
if (charCode === 10)
|
|
37
|
-
flushStdout();
|
|
38
|
-
};
|
|
39
|
-
const pushStderr = (charCode) => {
|
|
40
|
-
stderrBuffer += String.fromCharCode(charCode);
|
|
41
|
-
if (charCode === 10)
|
|
42
|
-
flushStderr();
|
|
43
|
-
};
|
|
38
|
+
const flushStdout = () => output?.flush();
|
|
39
|
+
const flushStderr = flushStdout;
|
|
40
|
+
const pushStdout = (charCode) => output?.write(charCode);
|
|
41
|
+
const pushStderr = pushStdout;
|
|
44
42
|
self.addEventListener('message', async (event) => {
|
|
45
43
|
if (handleWorkerAssetMessage(event.data))
|
|
46
44
|
return;
|
|
47
|
-
const { load, assets, buffer, code, prepare, args = [], stdin = '', hasExplicitStdin = false, activePath, workspaceFiles = [] } = event.data;
|
|
45
|
+
const { load, assets, buffer, code, prepare, debugMode, cacheEvaluationArtifacts, javaDebug, args = [], stdin = '', hasExplicitStdin = false, activePath, workspaceFiles = [] } = event.data;
|
|
48
46
|
try {
|
|
49
47
|
if (load) {
|
|
50
48
|
const runtimeAssets = assets;
|
|
@@ -54,14 +52,18 @@ self.addEventListener('message', async (event) => {
|
|
|
54
52
|
if (!compiler || loadedBaseUrl !== baseUrl) {
|
|
55
53
|
// Observe every branch immediately: failed assets must not leave an
|
|
56
54
|
// unhandled rejection while another branch is still initializing Wasm.
|
|
57
|
-
const [nextRuntime, sdk, runtimeClasslib] = await Promise.all([
|
|
55
|
+
const [nextRuntime, sdk, runtimeClasslib, deobfuscator] = await Promise.all([
|
|
58
56
|
(async () => {
|
|
59
57
|
const [runtimeModule, compilerAsset] = await Promise.all([
|
|
60
58
|
(async () => {
|
|
61
59
|
let runtimeSource = decoder.decode((await loadWorkerRuntimeAsset('compiler.wasm-runtime.js')).bytes);
|
|
62
|
-
|
|
60
|
+
// Custom runtime loaders retain their original byte-input contract.
|
|
61
|
+
acceptsCompiledModule = streamCompiler;
|
|
62
|
+
if (acceptsCompiledModule)
|
|
63
63
|
runtimeSource = acceptCompiledTeaVmModule(runtimeSource);
|
|
64
|
-
const runtimeUrl = URL.createObjectURL(new Blob([runtimeSource], {
|
|
64
|
+
const runtimeUrl = URL.createObjectURL(new Blob([runtimeSource], {
|
|
65
|
+
type: 'text/javascript;charset=utf-8'
|
|
66
|
+
}));
|
|
65
67
|
try {
|
|
66
68
|
return await import(/* @vite-ignore */ runtimeUrl);
|
|
67
69
|
}
|
|
@@ -70,18 +72,27 @@ self.addEventListener('message', async (event) => {
|
|
|
70
72
|
}
|
|
71
73
|
})(),
|
|
72
74
|
(async () => {
|
|
73
|
-
const module = streamCompiler
|
|
74
|
-
|
|
75
|
+
const module = streamCompiler
|
|
76
|
+
? await loadStreamingJavaCompiler(baseUrl, runtimeAssets?.maxAssetBytes ?? 128 * 1024 * 1024)
|
|
77
|
+
: undefined;
|
|
78
|
+
return module
|
|
79
|
+
? { bytes: module }
|
|
80
|
+
: loadWorkerRuntimeAsset('compiler.wasm');
|
|
75
81
|
})()
|
|
76
82
|
]);
|
|
77
83
|
const load = runtimeModule.load;
|
|
78
84
|
const module = await load(compilerAsset.bytes, {
|
|
79
85
|
stackDeobfuscator: { enabled: false }
|
|
80
86
|
});
|
|
81
|
-
return {
|
|
87
|
+
return {
|
|
88
|
+
load,
|
|
89
|
+
lib: module.exports,
|
|
90
|
+
compiler: module.exports.createCompiler()
|
|
91
|
+
};
|
|
82
92
|
})(),
|
|
83
93
|
loadWorkerRuntimeAsset('compile-classlib-teavm.bin').then(({ bytes }) => toInt8Array(bytes)),
|
|
84
|
-
loadWorkerRuntimeAsset('runtime-classlib-teavm.bin').then(({ bytes }) => toInt8Array(bytes))
|
|
94
|
+
loadWorkerRuntimeAsset('runtime-classlib-teavm.bin').then(({ bytes }) => toInt8Array(bytes)),
|
|
95
|
+
loadWorkerRuntimeAsset('compiler.wasm-deobfuscator.wasm').then(({ bytes }) => WebAssembly.compile(bytes, { builtins: ['js-string'] }))
|
|
85
96
|
]);
|
|
86
97
|
// Publish only a fully initialized compiler; a failed first attempt
|
|
87
98
|
// must retry instead of acknowledging a partially initialized runtime.
|
|
@@ -90,33 +101,52 @@ self.addEventListener('message', async (event) => {
|
|
|
90
101
|
compilerLib = nextRuntime.lib;
|
|
91
102
|
compiler = nextRuntime.compiler;
|
|
92
103
|
runtimeLoad = nextRuntime.load;
|
|
104
|
+
exceptionDeobfuscator = deobfuscator;
|
|
93
105
|
loadedBaseUrl = baseUrl;
|
|
94
106
|
compiledCode = '';
|
|
95
107
|
compiledStdin = '';
|
|
96
108
|
compiledMainClass = '';
|
|
109
|
+
compiledExceptionFormatter = '';
|
|
97
110
|
compiledWasm = null;
|
|
111
|
+
compiledModule = null;
|
|
98
112
|
compiledDiagnostics = [];
|
|
99
113
|
compiledActivePath = '';
|
|
100
114
|
compiledWorkspaceFiles = [];
|
|
115
|
+
compiledDebugEnabled = false;
|
|
116
|
+
compiledDebugFiles = [];
|
|
117
|
+
evaluationArtifacts.clear();
|
|
118
|
+
evaluationArtifactBytes = 0;
|
|
101
119
|
currentSourcePaths = new Set();
|
|
102
120
|
}
|
|
103
121
|
self.postMessage({ load: true });
|
|
104
122
|
return;
|
|
105
123
|
}
|
|
106
|
-
if (!compiler || !runtimeLoad)
|
|
124
|
+
if (!compiler || !runtimeLoad || !exceptionDeobfuscator)
|
|
107
125
|
throw new Error('TeaVM compiler not loaded');
|
|
108
|
-
|
|
109
|
-
|
|
126
|
+
output?.close();
|
|
127
|
+
output = createJavaOutput((text) => self.postMessage({ output: text }));
|
|
110
128
|
const explicitStdin = hasExplicitStdin === true;
|
|
111
129
|
const stdinInjection = prepareJavaRuntimeStdinInjection(code);
|
|
112
130
|
const sourceIdentity = resolveJavaSourceIdentity(code);
|
|
113
131
|
const sourcePath = typeof activePath === 'string' && activePath ? activePath : sourceIdentity.sourcePath;
|
|
114
132
|
const sourceFileName = sourcePath.split('/').pop() || sourcePath;
|
|
115
133
|
if (!Array.isArray(workspaceFiles) ||
|
|
116
|
-
!workspaceFiles.every((file) => file &&
|
|
134
|
+
!workspaceFiles.every((file) => file &&
|
|
135
|
+
typeof file.path === 'string' &&
|
|
136
|
+
(typeof file.content === 'string' || file.content instanceof Uint8Array))) {
|
|
117
137
|
throw new Error('Invalid Java workspace files');
|
|
118
138
|
}
|
|
119
|
-
|
|
139
|
+
// Container files arrive as bytes; Java compiler inputs are strict UTF-8 source text.
|
|
140
|
+
const sourceDecoder = new TextDecoder('utf-8', { fatal: true });
|
|
141
|
+
const sourceFiles = workspaceFiles.map((file) => ({
|
|
142
|
+
path: file.path,
|
|
143
|
+
content: typeof file.content === 'string'
|
|
144
|
+
? file.content
|
|
145
|
+
: sourceDecoder.decode(file.content)
|
|
146
|
+
}));
|
|
147
|
+
const debugEnabled = debugMode === 'trace';
|
|
148
|
+
if (debugMode && debugMode !== 'none' && !debugEnabled)
|
|
149
|
+
throw new Error('Java supports the trace debugger backend');
|
|
120
150
|
const workspaceChanged = compiledActivePath !== sourcePath ||
|
|
121
151
|
compiledWorkspaceFiles.length !== sourceFiles.length ||
|
|
122
152
|
compiledWorkspaceFiles.some((file, index) => file.path !== sourceFiles[index]?.path ||
|
|
@@ -127,20 +157,79 @@ self.addEventListener('message', async (event) => {
|
|
|
127
157
|
sourceFiles.some((file) => file.path === stdinInjection.helperSourcePath))) {
|
|
128
158
|
throw new Error(`Java workspace conflicts with generated stdin helper: ${stdinInjection.helperSourcePath}`);
|
|
129
159
|
}
|
|
160
|
+
const evaluationKey = cacheEvaluationArtifacts === true &&
|
|
161
|
+
acceptsCompiledModule &&
|
|
162
|
+
!debugEnabled &&
|
|
163
|
+
sourceFiles.length === 0
|
|
164
|
+
? JSON.stringify([code, sourcePath, stdinInjection.stdinCacheKey])
|
|
165
|
+
: undefined;
|
|
166
|
+
const cachedEvaluation = evaluationKey ? evaluationArtifacts.get(evaluationKey) : undefined;
|
|
167
|
+
if (evaluationKey && cachedEvaluation) {
|
|
168
|
+
evaluationArtifacts.delete(evaluationKey);
|
|
169
|
+
evaluationArtifacts.set(evaluationKey, cachedEvaluation);
|
|
170
|
+
compiledCode = code;
|
|
171
|
+
compiledStdin = stdinInjection.stdinCacheKey;
|
|
172
|
+
compiledMainClass = cachedEvaluation.mainClass;
|
|
173
|
+
compiledExceptionFormatter = cachedEvaluation.formatter;
|
|
174
|
+
compiledWasm = cachedEvaluation.wasm;
|
|
175
|
+
compiledModule = cachedEvaluation.module;
|
|
176
|
+
compiledDiagnostics = cachedEvaluation.diagnostics;
|
|
177
|
+
compiledActivePath = sourcePath;
|
|
178
|
+
compiledWorkspaceFiles = [];
|
|
179
|
+
compiledDebugEnabled = false;
|
|
180
|
+
compiledDebugFiles = [];
|
|
181
|
+
}
|
|
130
182
|
if (compiledCode !== code ||
|
|
183
|
+
compiledDebugEnabled !== debugEnabled ||
|
|
131
184
|
compiledStdin !== stdinInjection.stdinCacheKey ||
|
|
132
|
-
workspaceChanged ||
|
|
185
|
+
(!cachedEvaluation && workspaceChanged) ||
|
|
133
186
|
!compiledWasm) {
|
|
134
187
|
// A failed rebuild must never leave a previous artifact eligible for reuse.
|
|
135
188
|
compiledWasm = null;
|
|
189
|
+
compiledModule = null;
|
|
136
190
|
compiledDiagnostics = [];
|
|
191
|
+
compiledDebugFiles = [];
|
|
137
192
|
const mainClass = sourceIdentity.mainClass;
|
|
138
193
|
currentSourcePaths = new Set([sourcePath, ...sourceFiles.map((file) => file.path)].flatMap((path) => [
|
|
139
194
|
path,
|
|
140
195
|
path.split('/').pop() || path
|
|
141
196
|
]));
|
|
197
|
+
let mainSource = stdinInjection.transformedCode;
|
|
198
|
+
let otherSources = sourceFiles;
|
|
199
|
+
let debugBridge;
|
|
200
|
+
const debugFiles = [];
|
|
201
|
+
if (debugEnabled) {
|
|
202
|
+
const { instrumentJavaDebugSource } = await import('../javaDebugSource');
|
|
203
|
+
const originals = [{ path: sourcePath, content: code }, ...sourceFiles];
|
|
204
|
+
let nonce;
|
|
205
|
+
do {
|
|
206
|
+
nonce = crypto.randomUUID().replaceAll('-', '');
|
|
207
|
+
} while (originals.some((file) => file.content.includes(nonce) || file.path.includes(nonce)));
|
|
208
|
+
debugBridge = createJavaDebugBridge(`WasmIdleJavaDebug_${nonce}`, `wasm_idle_debug_${nonce}`);
|
|
209
|
+
const instrumented = [];
|
|
210
|
+
for (const file of originals) {
|
|
211
|
+
if (file.path !== sourcePath && !file.path.endsWith('.java')) {
|
|
212
|
+
instrumented.push(file);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const result = instrumentJavaDebugSource(file.content, file.path, debugBridge.qualifiedName);
|
|
216
|
+
const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(file.content)));
|
|
217
|
+
debugFiles.push({
|
|
218
|
+
path: file.path,
|
|
219
|
+
sourceContentSha256: [...hash]
|
|
220
|
+
.map((byte) => byte.toString(16).padStart(2, '0'))
|
|
221
|
+
.join(''),
|
|
222
|
+
lineCount: file.content.trimEnd().split(/\r\n|\r|\n/).length,
|
|
223
|
+
locations: result.locations
|
|
224
|
+
});
|
|
225
|
+
instrumented.push({ path: file.path, content: result.code });
|
|
226
|
+
}
|
|
227
|
+
mainSource = prepareJavaRuntimeStdinInjection(instrumented[0].content).transformedCode;
|
|
228
|
+
otherSources = instrumented.slice(1);
|
|
229
|
+
}
|
|
142
230
|
const diagnosticLines = [];
|
|
143
231
|
const diagnosticMessages = [];
|
|
232
|
+
let compilingExceptionBridge = false;
|
|
144
233
|
const diagnosticRegistration = compiler.onDiagnostic((diagnostic) => {
|
|
145
234
|
const severity = diagnostic.severity
|
|
146
235
|
? String(diagnostic.severity).toLowerCase()
|
|
@@ -149,6 +238,8 @@ self.addEventListener('message', async (event) => {
|
|
|
149
238
|
? `${diagnostic.fileName}:${diagnostic.lineNumber || 0}${diagnostic.columnNumber ? `:${diagnostic.columnNumber}` : ''}`
|
|
150
239
|
: 'TeaVM';
|
|
151
240
|
diagnosticLines.push(`${location}: ${severity}: ${diagnostic.message}`);
|
|
241
|
+
if (compilingExceptionBridge)
|
|
242
|
+
return;
|
|
152
243
|
const fileName = diagnostic.fileName ? String(diagnostic.fileName) : null;
|
|
153
244
|
if (fileName && !currentSourcePaths.has(fileName)) {
|
|
154
245
|
return;
|
|
@@ -180,10 +271,12 @@ self.addEventListener('message', async (event) => {
|
|
|
180
271
|
compiler.clearInputClassFiles?.();
|
|
181
272
|
compiler.clearOutputFiles?.();
|
|
182
273
|
// TeaVM derives packages from source text but validates public types against the basename.
|
|
183
|
-
compiler.addSourceFile(sourceFileName,
|
|
184
|
-
for (const file of
|
|
274
|
+
compiler.addSourceFile(sourceFileName, mainSource);
|
|
275
|
+
for (const file of otherSources) {
|
|
185
276
|
compiler.addSourceFile(file.path.split('/').pop() || file.path, file.content);
|
|
186
277
|
}
|
|
278
|
+
if (debugBridge)
|
|
279
|
+
compiler.addSourceFile(debugBridge.sourceFileName, debugBridge.source);
|
|
187
280
|
if (stdinInjection.usesStdin &&
|
|
188
281
|
stdinInjection.helperSourcePath &&
|
|
189
282
|
stdinInjection.helperSource) {
|
|
@@ -205,21 +298,79 @@ self.addEventListener('message', async (event) => {
|
|
|
205
298
|
? 'Main method not found'
|
|
206
299
|
: 'Multiple main methods found');
|
|
207
300
|
}
|
|
301
|
+
// Compile the launcher against the original class files so user diagnostics and
|
|
302
|
+
// main-method validation stay independent, and original source lines are unchanged.
|
|
303
|
+
const classFiles = Array.from(compiler.listOutputFiles());
|
|
304
|
+
const exceptionBridge = prepareJavaExceptionBridge(mainClass, [
|
|
305
|
+
code,
|
|
306
|
+
...sourceFiles.map((file) => file.content),
|
|
307
|
+
stdinInjection.helperSource || ''
|
|
308
|
+
], classFiles);
|
|
309
|
+
for (const path of classFiles) {
|
|
310
|
+
if (path.endsWith('.class'))
|
|
311
|
+
compiler.addClassFile(path, compiler.getOutputFile(path));
|
|
312
|
+
}
|
|
313
|
+
compiler.clearSourceFiles();
|
|
314
|
+
compiler.addSourceFile(exceptionBridge.sourceFileName, exceptionBridge.source);
|
|
315
|
+
compiler.addSourceFile(exceptionBridge.formatterSourceFileName, exceptionBridge.formatterSource);
|
|
316
|
+
let bridgeOk;
|
|
317
|
+
try {
|
|
318
|
+
compilingExceptionBridge = true;
|
|
319
|
+
bridgeOk = compiler.compile();
|
|
320
|
+
}
|
|
321
|
+
finally {
|
|
322
|
+
compilingExceptionBridge = false;
|
|
323
|
+
}
|
|
324
|
+
if (!bridgeOk) {
|
|
325
|
+
disposeDiagnosticRegistration();
|
|
326
|
+
throw new Error(diagnosticLines.join('\n') || 'Java exception bridge compilation failed');
|
|
327
|
+
}
|
|
208
328
|
const generateOk = compiler.generateWebAssembly({
|
|
209
329
|
outputName: 'app',
|
|
210
|
-
mainClass
|
|
330
|
+
mainClass: exceptionBridge.mainClass
|
|
211
331
|
});
|
|
212
332
|
disposeDiagnosticRegistration();
|
|
213
333
|
if (!generateOk) {
|
|
214
334
|
throw new Error(diagnosticLines.join('\n') || 'TeaVM WebAssembly generation failed');
|
|
215
335
|
}
|
|
336
|
+
const nextWasm = new Uint8Array(compiler.getWebAssemblyOutputFile('app.wasm'));
|
|
337
|
+
const nextModule = acceptsCompiledModule
|
|
338
|
+
? await WebAssembly.compile(nextWasm, { builtins: ['js-string'] })
|
|
339
|
+
: null;
|
|
216
340
|
compiledCode = code;
|
|
217
341
|
compiledStdin = stdinInjection.stdinCacheKey;
|
|
218
342
|
compiledMainClass = mainClass;
|
|
219
|
-
|
|
343
|
+
compiledExceptionFormatter = exceptionBridge.formatExport;
|
|
344
|
+
compiledWasm = nextWasm;
|
|
345
|
+
compiledModule = nextModule;
|
|
220
346
|
compiledActivePath = sourcePath;
|
|
221
347
|
compiledWorkspaceFiles = sourceFiles.map((file) => ({ ...file }));
|
|
348
|
+
compiledDebugEnabled = debugEnabled;
|
|
349
|
+
compiledDebugFiles = debugFiles;
|
|
222
350
|
compiledDiagnostics = diagnosticMessages;
|
|
351
|
+
if (evaluationKey && nextModule) {
|
|
352
|
+
// Bound source, diagnostic and Wasm input bytes, not engine compiled-code RSS.
|
|
353
|
+
const bytes = nextWasm.byteLength +
|
|
354
|
+
evaluationKey.length * 2 +
|
|
355
|
+
JSON.stringify(diagnosticMessages).length * 2;
|
|
356
|
+
if (bytes <= MAX_EVALUATION_ARTIFACT_BYTES) {
|
|
357
|
+
while (evaluationArtifacts.size >= MAX_EVALUATION_ARTIFACTS ||
|
|
358
|
+
evaluationArtifactBytes + bytes > MAX_EVALUATION_ARTIFACT_BYTES) {
|
|
359
|
+
const oldest = evaluationArtifacts.keys().next().value;
|
|
360
|
+
evaluationArtifactBytes -= evaluationArtifacts.get(oldest).bytes;
|
|
361
|
+
evaluationArtifacts.delete(oldest);
|
|
362
|
+
}
|
|
363
|
+
evaluationArtifacts.set(evaluationKey, {
|
|
364
|
+
wasm: nextWasm,
|
|
365
|
+
module: nextModule,
|
|
366
|
+
mainClass,
|
|
367
|
+
formatter: exceptionBridge.formatExport,
|
|
368
|
+
diagnostics: diagnosticMessages,
|
|
369
|
+
bytes
|
|
370
|
+
});
|
|
371
|
+
evaluationArtifactBytes += bytes;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
223
374
|
}
|
|
224
375
|
else {
|
|
225
376
|
// Every operation has its own diagnostic sink, even when compilation is reused.
|
|
@@ -241,16 +392,51 @@ self.addEventListener('message', async (event) => {
|
|
|
241
392
|
const previousWindow = workerGlobal.window;
|
|
242
393
|
const hadStdinBridge = Object.prototype.hasOwnProperty.call(workerGlobal, 'wasmIdleJavaStdin');
|
|
243
394
|
const previousStdinBridge = workerGlobal.wasmIdleJavaStdin;
|
|
395
|
+
const hadOutputBridge = Object.prototype.hasOwnProperty.call(workerGlobal, 'wasmIdleJavaOutput');
|
|
396
|
+
const previousOutputBridge = workerGlobal.wasmIdleJavaOutput;
|
|
397
|
+
const hadDebugBridge = Object.prototype.hasOwnProperty.call(workerGlobal, 'wasmIdleJavaDebug');
|
|
398
|
+
const previousDebugBridge = workerGlobal.wasmIdleJavaDebug;
|
|
399
|
+
const errorConstructor = Error;
|
|
400
|
+
const stackTraceLimit = Object.getOwnPropertyDescriptor(errorConstructor, 'stackTraceLimit');
|
|
244
401
|
workerGlobal.window = workerGlobal;
|
|
245
402
|
workerGlobal.wasmIdleJavaStdin = stdinBridge;
|
|
403
|
+
workerGlobal.wasmIdleJavaOutput = { flush: () => output?.flush() };
|
|
246
404
|
try {
|
|
247
|
-
|
|
405
|
+
if (debugEnabled) {
|
|
406
|
+
if (!javaDebug)
|
|
407
|
+
throw new Error('Java debugger command transport is missing');
|
|
408
|
+
// V8 defaults to ten physical frames; retain full depth for recursive next/out.
|
|
409
|
+
if (typeof errorConstructor.stackTraceLimit === 'number')
|
|
410
|
+
errorConstructor.stackTraceLimit = Infinity;
|
|
411
|
+
workerGlobal.wasmIdleJavaDebug = createJavaDebugRuntime(compiledDebugFiles, {
|
|
412
|
+
activePath: sourcePath,
|
|
413
|
+
debugPath: javaDebug.sourcePath,
|
|
414
|
+
breakpoints: javaDebug.breakpoints ?? [],
|
|
415
|
+
sourceBreakpoints: javaDebug.sourceBreakpoints,
|
|
416
|
+
pauseOnEntry: javaDebug.pauseOnEntry !== false
|
|
417
|
+
}, (event, stopId) => {
|
|
418
|
+
if (event.type === 'pause') {
|
|
419
|
+
flushStdout();
|
|
420
|
+
flushStderr();
|
|
421
|
+
}
|
|
422
|
+
self.postMessage({ javaDebug: { event, stopId } });
|
|
423
|
+
}, (blocking) => {
|
|
424
|
+
// Synchronous Java loops prevent output timers from running. Keep
|
|
425
|
+
// elapsed batches visible while hooks poll, without flushing every hook.
|
|
426
|
+
if (!blocking)
|
|
427
|
+
output?.flushIfDue();
|
|
428
|
+
return readDebugCommand(javaDebug.buffer, blocking, () => self.postMessage({ javaDebug: { consumed: true } }), 'Java');
|
|
429
|
+
}, (response) => self.postMessage({ javaDebug: { response } }));
|
|
430
|
+
}
|
|
431
|
+
const module = await runtimeLoad(compiledModule ?? compiledWasm, {
|
|
248
432
|
installImports(imports) {
|
|
249
433
|
imports.teavmConsole.putcharStdout = pushStdout;
|
|
250
434
|
imports.teavmConsole.putcharStderr = pushStderr;
|
|
251
435
|
},
|
|
252
436
|
stackDeobfuscator: {
|
|
253
|
-
enabled:
|
|
437
|
+
enabled: true,
|
|
438
|
+
path: exceptionDeobfuscator,
|
|
439
|
+
infoLocation: 'embedded'
|
|
254
440
|
}
|
|
255
441
|
});
|
|
256
442
|
self.postMessage({
|
|
@@ -261,13 +447,41 @@ self.addEventListener('message', async (event) => {
|
|
|
261
447
|
label: 'Java program started'
|
|
262
448
|
}
|
|
263
449
|
});
|
|
264
|
-
|
|
450
|
+
try {
|
|
451
|
+
module.exports.main(args);
|
|
452
|
+
}
|
|
453
|
+
catch (error) {
|
|
454
|
+
// JSExceptions retrieves the real Java Throwable; its class, causes, and
|
|
455
|
+
// source stack survive even when getMessage() is null or empty.
|
|
456
|
+
let javaError;
|
|
457
|
+
try {
|
|
458
|
+
javaError = module.exports[compiledExceptionFormatter](error);
|
|
459
|
+
}
|
|
460
|
+
catch {
|
|
461
|
+
// A formatting failure must not replace the original runtime failure.
|
|
462
|
+
}
|
|
463
|
+
if (typeof javaError === 'string' && javaError)
|
|
464
|
+
throw new Error(javaError);
|
|
465
|
+
throw error;
|
|
466
|
+
}
|
|
265
467
|
flushStdout();
|
|
266
468
|
flushStderr();
|
|
267
469
|
self.postMessage({ results: true, mainClass: compiledMainClass });
|
|
268
470
|
}
|
|
269
471
|
finally {
|
|
270
472
|
stdinBridge.dispose();
|
|
473
|
+
if (hadOutputBridge)
|
|
474
|
+
workerGlobal.wasmIdleJavaOutput = previousOutputBridge;
|
|
475
|
+
else
|
|
476
|
+
delete workerGlobal.wasmIdleJavaOutput;
|
|
477
|
+
if (hadDebugBridge)
|
|
478
|
+
workerGlobal.wasmIdleJavaDebug = previousDebugBridge;
|
|
479
|
+
else
|
|
480
|
+
delete workerGlobal.wasmIdleJavaDebug;
|
|
481
|
+
if (stackTraceLimit)
|
|
482
|
+
Object.defineProperty(errorConstructor, 'stackTraceLimit', stackTraceLimit);
|
|
483
|
+
else
|
|
484
|
+
Reflect.deleteProperty(errorConstructor, 'stackTraceLimit');
|
|
271
485
|
if (hadStdinBridge)
|
|
272
486
|
workerGlobal.wasmIdleJavaStdin = previousStdinBridge;
|
|
273
487
|
else
|
|
@@ -287,4 +501,8 @@ self.addEventListener('message', async (event) => {
|
|
|
287
501
|
error: error instanceof Error ? error.message : String(error)
|
|
288
502
|
});
|
|
289
503
|
}
|
|
504
|
+
finally {
|
|
505
|
+
output?.close();
|
|
506
|
+
output = null;
|
|
507
|
+
}
|
|
290
508
|
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export interface JavaDebugEvaluationBinding {
|
|
2
|
+
name: string;
|
|
3
|
+
type: string;
|
|
4
|
+
/** Raw Java value text; char is a decimal UTF-16 code unit, String is unquoted. */
|
|
5
|
+
value: string | null;
|
|
6
|
+
unavailable?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface JavaDebugEvaluationRequest {
|
|
9
|
+
expression: string;
|
|
10
|
+
bindings: readonly JavaDebugEvaluationBinding[];
|
|
11
|
+
}
|
|
12
|
+
/** A standalone program; no user classes, initializers or main method are copied into it. */
|
|
13
|
+
export declare function buildJavaDebugEvaluationProgram(request: JavaDebugEvaluationRequest): {
|
|
14
|
+
code: string;
|
|
15
|
+
args: string[];
|
|
16
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Third-party license texts: java-debug-notices.txt beside the shared parser.
|
|
2
|
+
import{a as m,b as y}from"../java-debug-FMHDKUN6.js";var N=new Set(["boolean","byte","short","char","int","long","float","double"]),j=new Set(["length","isEmpty","isBlank","charAt","codePointAt","codePointBefore","codePointCount","compareTo","compareToIgnoreCase","equals","equalsIgnoreCase","contains","startsWith","endsWith","indexOf","lastIndexOf","substring","subSequence","trim","strip","stripLeading","stripTrailing","concat","hashCode","toString","regionMatches"]),x=new Set(["substring","subSequence","trim","strip","stripLeading","stripTrailing","concat","toString","valueOf","toHexString","toOctalString","toBinaryString","toUnsignedString"]),T={Math:new Set(["abs","min","max","round","ceil","floor","sqrt","cbrt","pow","sin","cos","tan","asin","acos","atan","atan2","exp","expm1","log","log10","log1p","hypot","signum","copySign","scalb","ulp","nextUp","nextDown","nextAfter","toRadians","toDegrees","addExact","subtractExact","multiplyExact","toIntExact","floorDiv","floorMod","IEEEremainder"]),String:new Set(["valueOf"]),Integer:new Set(["parseInt","parseUnsignedInt","toString","toHexString","toOctalString","toBinaryString","toUnsignedString","compare","compareUnsigned","sum","min","max","bitCount","signum","numberOfLeadingZeros","numberOfTrailingZeros","reverse","reverseBytes","rotateLeft","rotateRight","highestOneBit","lowestOneBit","toUnsignedLong"]),Long:new Set(["parseLong","parseUnsignedLong","toString","toHexString","toOctalString","toBinaryString","toUnsignedString","compare","compareUnsigned","sum","min","max","bitCount","signum","numberOfLeadingZeros","numberOfTrailingZeros","reverse","reverseBytes","rotateLeft","rotateRight","highestOneBit","lowestOneBit"]),Double:new Set(["parseDouble","toString","isNaN","isInfinite","isFinite","compare","sum","min","max"]),Float:new Set(["parseFloat","toString","isNaN","isInfinite","isFinite","compare","sum","min","max"]),Boolean:new Set(["parseBoolean","toString","logicalAnd","logicalOr","logicalXor"]),Character:new Set(["isDigit","isLetter","isLetterOrDigit","isWhitespace","isUpperCase","isLowerCase","toUpperCase","toLowerCase","toTitleCase","getNumericValue","digit","toString"])},A={Math:new Set(["PI","E"]),Integer:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Long:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Short:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Byte:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Character:new Set(["MIN_VALUE","MAX_VALUE","SIZE","BYTES"]),Double:new Set(["MIN_VALUE","MIN_NORMAL","MAX_VALUE","NaN","POSITIVE_INFINITY","NEGATIVE_INFINITY"]),Float:new Set(["MIN_VALUE","MIN_NORMAL","MAX_VALUE","NaN","POSITIVE_INFINITY","NEGATIVE_INFINITY"])},b=m((t,i)=>(t.children[i]??[]).flatMap(s=>"children"in s?[s]:[]),"nodes"),L=m((t,i)=>(t.children[i]??[]).filter(s=>!("children"in s)),"tokens");function E(t){return Object.entries(t.children).flatMap(([i,s])=>s.flatMap(f=>"children"in f?E(f):i==="Identifier"?[f]:[])).sort((i,s)=>i.startOffset-s.startOffset)}m(E,"identifiers");function M(t,i){let s=new Set;if(/\\u+[0-9a-fA-F]{4}/.test(t))throw new Error("Java evaluation does not support Unicode preprocessing escapes.");let{cst:f,tokens:o}=y(t,"expression"),S=new Set(["PlusPlus","MinusMinus","New","This","Super","Arrow","DoubleColon","LSquare","LCurly","Class","Instanceof","At"]);if(o.some(a=>S.has(a.tokenType.name)))throw new Error("Java evaluation supports read-only scalar/String expressions; mutation, objects, arrays and closures are unsupported.");let d=new Map,h=m(a=>{if(d.has(a))return d.get(a);if(a.children.AssignmentOperator)throw new Error("Java evaluation does not allow assignment or mutation.");if(a.name==="conditionalExpression"&&a.children.QuestionMark)throw new Error("Java snapshot evaluation does not support conditional expressions because compile-time constant narrowing is unavailable.");if(a.name==="typeArguments")throw new Error("Java evaluation does not support generic or user-type expressions.");let e=Object.values(a.children).flat().flatMap(p=>"children"in p?[p]:[]).map(h),n=e.includes("string")?"string":e.includes("null")?"null":"scalar";if(a.name==="literal")n=a.children.StringLiteral||a.children.TextBlock?"string":a.children.Null?"null":"scalar";else if(a.name==="referenceTypeCastExpression"){if(E(b(a,"referenceType")[0]).map(v=>v.image).join(".")!=="java.lang.String")throw new Error("Java evaluation supports only primitive and fully qualified java.lang.String casts.");n="string"}else if(a.name==="primitiveCastExpression")n="scalar";else if(a.name==="primary"){let p=b(a,"primaryPrefix")[0],v=b(p,"fqnOrRefType")[0],g=b(a,"primarySuffix"),I=0;if(v){let r=E(v).map(c=>c.image),l=!!g[0]?.children.methodInvocationSuffix,u=i.get(r[0]);if(u){if(u.unavailable!==void 0)throw new Error(`Java evaluation cannot use ${u.name}: ${u.unavailable}`);if(!N.has(u.type)&&u.type!=="String"&&u.type!=="java.lang.String")throw new Error(`Java evaluation cannot use ${u.name} (${u.type}); inspect this target reference in Variables.`);if(s.add(u.name),n=N.has(u.type)?"scalar":"string",r.length!==1||l){if(r.length!==2||!l||n!=="string"||!j.has(r[1]))throw new Error("Java evaluation cannot call target methods or access target fields.");n=x.has(r[1])?"string":"scalar",I=1}}else{let c=r.slice(2);if(r[0]!=="java"||r[1]!=="lang"||c.length!==2||(l?!Object.hasOwn(T,c[0])||!T[c[0]].has(c[1]):!Object.hasOwn(A,c[0])||!A[c[0]].has(c[1])))throw new Error(`Java evaluation cannot resolve ${r.join(".")}; use scalar/String locals or fully qualified java.lang library calls/constants.`);n=l&&x.has(c[1])?"string":"scalar",I=l?1:0}}for(let r=I;r<g.length;r+=2){let l=L(g[r],"Identifier")[0]?.image;if(n!=="string"||!l||!j.has(l)||!g[r+1]?.children.methodInvocationSuffix)throw new Error("Java evaluation supports only approved String methods on expression results.");n=x.has(l)?"string":"scalar"}}else if(a.name==="binaryExpression"){let p=b(a,"unaryExpression").map(h),v=L(a,"BinaryOperator");for(let[g,I]of v.entries()){let r=[g,g+1].some(l=>p[l]==="null"&&v[l-1]?.image!=="+"&&v[l]?.image!=="+");if(["==","!="].includes(I.image)&&(p[g]==="string"||p[g+1]==="string")&&!r)throw new Error("Java snapshot evaluation cannot compare String reference identity; use equals() for String contents.")}v.some(g=>["==","!=","<",">","<=",">=","&&","||"].includes(g.image))&&(n="scalar")}return d.set(a,n),n},"visit");return h(f),s}m(M,"validateExpression");function $(t){if(typeof t.expression!="string"||!t.expression.trim()||new TextEncoder().encode(t.expression).length>4096)throw new Error("Java expressions must contain 1\u20134096 UTF-8 bytes.");if(!Array.isArray(t.bindings)||t.bindings.length>1024)throw new Error("Java evaluation supports at most 1024 local bindings.");let i=new Map;for(let e of t.bindings){if(!e||typeof e.name!="string"||typeof e.type!="string"||e.value!==null&&typeof e.value!="string"||e.unavailable!==void 0&&typeof e.unavailable!="string")throw new Error("Invalid Java evaluation binding.");let n=y(e.name,"expression");if(n.tokens.length!==1||E(n.cst)[0]?.image!==e.name||i.has(e.name)||/\\/.test(e.name))throw new Error(`Invalid or duplicate Java local name: ${e.name}`);i.set(e.name,{...e})}let s=M(t.expression,i),f=0,o="WasmIdleEval";for(;t.expression.includes(o)||[...i.keys()].some(e=>e.includes(o));)o=`WasmIdleEval_${++f}`;let S=`${o}_args`,d=[],h=[],a={byte:"java.lang.Byte.parseByte(value)",short:"java.lang.Short.parseShort(value)",int:"java.lang.Integer.parseInt(value)",long:"java.lang.Long.parseLong(value)",float:'value.equals("NaN") ? java.lang.Float.NaN : value.equals("Infinity") ? java.lang.Float.POSITIVE_INFINITY : value.equals("-Infinity") ? java.lang.Float.NEGATIVE_INFINITY : value.equals("-0.0") ? java.lang.Float.intBitsToFloat(java.lang.Integer.MIN_VALUE) : java.lang.Float.parseFloat(value)',double:'value.equals("NaN") ? java.lang.Double.NaN : value.equals("Infinity") ? java.lang.Double.POSITIVE_INFINITY : value.equals("-Infinity") ? java.lang.Double.NEGATIVE_INFINITY : value.equals("-0.0") ? java.lang.Double.longBitsToDouble(java.lang.Long.MIN_VALUE) : java.lang.Double.parseDouble(value)',boolean:"java.lang.Boolean.parseBoolean(value)",char:"(char) java.lang.Integer.parseInt(value)"},w=0;for(let e of i.values()){if(!s.has(e.name))continue;if(w+=new TextEncoder().encode(e.value??"").length,w>65536)throw new Error("Java evaluation binding values exceed 65536 UTF-8 bytes.");let n=d.length;if(N.has(e.type)){if(e.value===null||e.type==="char"&&(!/^\d{1,5}$/.test(e.value)||Number(e.value)>65535)||e.type==="boolean"&&!["true","false"].includes(e.value))throw new Error(`Invalid ${e.type} value for Java local ${e.name}.`);d.push(e.value),h.push(`final ${e.type} ${e.name} = ${o}_${e.type}(${S}[${n}]);`)}else(e.type==="String"||e.type==="java.lang.String")&&(d.push(e.value===null?"1":"0",e.value??""),h.push(`final java.lang.String ${e.name} = ${S}[${n}].equals("1") ? null : ${S}[${n+1}];`))}return{args:d,code:`public final class ${o} {
|
|
3
|
+
${Object.entries(a).map(([e,n])=>` private static ${e} ${o}_${e}(java.lang.String value) { return ${n}; }`).join(`
|
|
4
|
+
`)}
|
|
5
|
+
${String.raw` private static java.lang.String ${o}_quote(java.lang.String value) {
|
|
6
|
+
java.lang.StringBuilder result = new java.lang.StringBuilder("\"");
|
|
7
|
+
for (int i = 0; i < value.length(); i++) {
|
|
8
|
+
char ch = value.charAt(i);
|
|
9
|
+
switch (ch) {
|
|
10
|
+
case '"': result.append("\\\""); break;
|
|
11
|
+
case '\\': result.append("\\\\"); break;
|
|
12
|
+
case '\b': result.append("\\b"); break;
|
|
13
|
+
case '\f': result.append("\\f"); break;
|
|
14
|
+
case '\n': result.append("\\n"); break;
|
|
15
|
+
case '\r': result.append("\\r"); break;
|
|
16
|
+
case '\t': result.append("\\t"); break;
|
|
17
|
+
default:
|
|
18
|
+
if (ch < 32 || java.lang.Character.isSurrogate(ch)) {
|
|
19
|
+
java.lang.String hex = java.lang.Integer.toHexString(ch);
|
|
20
|
+
result.append("\\u");
|
|
21
|
+
for (int pad = hex.length(); pad < 4; pad++) result.append('0');
|
|
22
|
+
result.append(hex);
|
|
23
|
+
} else result.append(ch);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return result.append('"').toString();
|
|
27
|
+
}`}
|
|
28
|
+
private static void ${o}_print(java.lang.Object value) {
|
|
29
|
+
if (value != null && !(value instanceof java.lang.String) && !(value instanceof java.lang.Number)
|
|
30
|
+
&& !(value instanceof java.lang.Boolean) && !(value instanceof java.lang.Character))
|
|
31
|
+
throw new java.lang.IllegalArgumentException("Java evaluation result is not a scalar or String.");
|
|
32
|
+
java.lang.String text = java.lang.String.valueOf(value);
|
|
33
|
+
if (value instanceof java.lang.String || value instanceof java.lang.Character) text = ${o}_quote(text);
|
|
34
|
+
if (text.length() > 16384) throw new java.lang.IllegalArgumentException("Java evaluation output exceeds 16384 characters.");
|
|
35
|
+
java.lang.System.out.print(text);
|
|
36
|
+
}
|
|
37
|
+
public static void main(java.lang.String[] ${S}) {
|
|
38
|
+
${h.map(e=>` ${e}`).join(`
|
|
39
|
+
`)}
|
|
40
|
+
${o}_print((${t.expression}
|
|
41
|
+
));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
`}}m($,"buildJavaDebugEvaluationProgram");export{$ as buildJavaDebugEvaluationProgram};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { DebugSessionEvent, DebugSourceBreakpoints } from '../options';
|
|
2
|
+
import type { JavaDebugLocation } from '../javaDebugSource';
|
|
3
|
+
export interface JavaDebugFile {
|
|
4
|
+
path: string;
|
|
5
|
+
sourceContentSha256: string;
|
|
6
|
+
lineCount: number;
|
|
7
|
+
locations: JavaDebugLocation[];
|
|
8
|
+
}
|
|
9
|
+
export declare function createJavaDebugRuntime(files: JavaDebugFile[], options: {
|
|
10
|
+
activePath: string;
|
|
11
|
+
debugPath?: string;
|
|
12
|
+
breakpoints: number[];
|
|
13
|
+
sourceBreakpoints?: DebugSourceBreakpoints[];
|
|
14
|
+
pauseOnEntry: boolean;
|
|
15
|
+
}, emit: (event: DebugSessionEvent, stopId?: number) => void, read: (blocking: boolean) => string | null, respond?: (response: {
|
|
16
|
+
id: number;
|
|
17
|
+
stopId: number;
|
|
18
|
+
value?: unknown;
|
|
19
|
+
error?: string;
|
|
20
|
+
}) => void): {
|
|
21
|
+
poll(source: string, line: number, _column: number): {} | null;
|
|
22
|
+
pause(source: string, line: number, column: number, serialized: string, rawDepth: number, serializedVariables?: string, totalVariables?: number): Record<string, unknown> | null;
|
|
23
|
+
reply(id: number, stopId: number, serialized: string | null, error: string | null): Record<string, unknown> | null;
|
|
24
|
+
};
|