@tracecode/harness 0.4.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 (55) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/LICENSE +674 -0
  3. package/README.md +266 -0
  4. package/dist/browser.cjs +1352 -0
  5. package/dist/browser.cjs.map +1 -0
  6. package/dist/browser.d.cts +49 -0
  7. package/dist/browser.d.ts +49 -0
  8. package/dist/browser.js +1317 -0
  9. package/dist/browser.js.map +1 -0
  10. package/dist/cli.cjs +70 -0
  11. package/dist/cli.cjs.map +1 -0
  12. package/dist/cli.d.cts +1 -0
  13. package/dist/cli.d.ts +1 -0
  14. package/dist/cli.js +70 -0
  15. package/dist/cli.js.map +1 -0
  16. package/dist/core.cjs +286 -0
  17. package/dist/core.cjs.map +1 -0
  18. package/dist/core.d.cts +69 -0
  19. package/dist/core.d.ts +69 -0
  20. package/dist/core.js +254 -0
  21. package/dist/core.js.map +1 -0
  22. package/dist/index.cjs +2603 -0
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.cts +6 -0
  25. package/dist/index.d.ts +6 -0
  26. package/dist/index.js +2538 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/internal/browser.cjs +647 -0
  29. package/dist/internal/browser.cjs.map +1 -0
  30. package/dist/internal/browser.d.cts +143 -0
  31. package/dist/internal/browser.d.ts +143 -0
  32. package/dist/internal/browser.js +617 -0
  33. package/dist/internal/browser.js.map +1 -0
  34. package/dist/javascript.cjs +549 -0
  35. package/dist/javascript.cjs.map +1 -0
  36. package/dist/javascript.d.cts +11 -0
  37. package/dist/javascript.d.ts +11 -0
  38. package/dist/javascript.js +518 -0
  39. package/dist/javascript.js.map +1 -0
  40. package/dist/python.cjs +744 -0
  41. package/dist/python.cjs.map +1 -0
  42. package/dist/python.d.cts +97 -0
  43. package/dist/python.d.ts +97 -0
  44. package/dist/python.js +698 -0
  45. package/dist/python.js.map +1 -0
  46. package/dist/runtime-types-C7d1LFbx.d.ts +85 -0
  47. package/dist/runtime-types-Dvgn07z9.d.cts +85 -0
  48. package/dist/types-Bzr1Ohcf.d.cts +96 -0
  49. package/dist/types-Bzr1Ohcf.d.ts +96 -0
  50. package/package.json +89 -0
  51. package/workers/javascript/javascript-worker.js +2918 -0
  52. package/workers/python/generated-python-harness-snippets.js +20 -0
  53. package/workers/python/pyodide-worker.js +1197 -0
  54. package/workers/python/runtime-core.js +1529 -0
  55. package/workers/vendor/typescript.js +200276 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,2603 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/index.ts
20
+ var src_exports = {};
21
+ __export(src_exports, {
22
+ DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS: () => DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS,
23
+ LANGUAGE_RUNTIME_PROFILES: () => LANGUAGE_RUNTIME_PROFILES,
24
+ PYTHON_CLASS_DEFINITIONS: () => PYTHON_CLASS_DEFINITIONS,
25
+ PYTHON_CONVERSION_HELPERS: () => PYTHON_CONVERSION_HELPERS,
26
+ PYTHON_EXECUTE_SERIALIZE_FUNCTION: () => PYTHON_EXECUTE_SERIALIZE_FUNCTION,
27
+ PYTHON_INTERVIEW_MATERIALIZE_SERIALIZE_FUNCTION: () => PYTHON_INTERVIEW_MATERIALIZE_SERIALIZE_FUNCTION,
28
+ PYTHON_PRACTICE_MATERIALIZE_SERIALIZE_FUNCTION: () => PYTHON_PRACTICE_MATERIALIZE_SERIALIZE_FUNCTION,
29
+ PYTHON_SERIALIZE_FUNCTION: () => PYTHON_SERIALIZE_FUNCTION,
30
+ PYTHON_TRACE_SERIALIZE_FUNCTION: () => PYTHON_TRACE_SERIALIZE_FUNCTION,
31
+ RUNTIME_TRACE_CONTRACT_SCHEMA_VERSION: () => RUNTIME_TRACE_CONTRACT_SCHEMA_VERSION,
32
+ SUPPORTED_LANGUAGES: () => SUPPORTED_LANGUAGES,
33
+ TEMPLATE_PYTHON_CLASS_DEFINITIONS: () => TEMPLATE_PYTHON_CLASS_DEFINITIONS,
34
+ TEMPLATE_PYTHON_CONVERSION_HELPERS: () => TEMPLATE_PYTHON_CONVERSION_HELPERS,
35
+ TEMPLATE_PYTHON_EXECUTE_SERIALIZE_FUNCTION: () => TEMPLATE_PYTHON_EXECUTE_SERIALIZE_FUNCTION,
36
+ TEMPLATE_PYTHON_INTERVIEW_MATERIALIZE_SERIALIZE_FUNCTION: () => TEMPLATE_PYTHON_INTERVIEW_MATERIALIZE_SERIALIZE_FUNCTION,
37
+ TEMPLATE_PYTHON_PRACTICE_MATERIALIZE_SERIALIZE_FUNCTION: () => TEMPLATE_PYTHON_PRACTICE_MATERIALIZE_SERIALIZE_FUNCTION,
38
+ TEMPLATE_PYTHON_SERIALIZE_FUNCTION: () => TEMPLATE_PYTHON_SERIALIZE_FUNCTION,
39
+ TEMPLATE_PYTHON_TRACE_SERIALIZE_FUNCTION: () => TEMPLATE_PYTHON_TRACE_SERIALIZE_FUNCTION,
40
+ TYPESCRIPT_RUNTIME_DECLARATIONS: () => TYPESCRIPT_RUNTIME_DECLARATIONS,
41
+ adaptJavaScriptTraceExecutionResult: () => adaptJavaScriptTraceExecutionResult,
42
+ adaptPythonTraceExecutionResult: () => adaptPythonTraceExecutionResult,
43
+ adaptTraceExecutionResult: () => adaptTraceExecutionResult,
44
+ assertRuntimeRequestSupported: () => assertRuntimeRequestSupported,
45
+ createBrowserHarness: () => createBrowserHarness,
46
+ executeJavaScriptCode: () => executeJavaScriptCode,
47
+ executeJavaScriptWithTracing: () => executeJavaScriptWithTracing,
48
+ executeTypeScriptCode: () => executeTypeScriptCode,
49
+ generateConversionCode: () => generateConversionCode,
50
+ generateInputSetup: () => generateInputSetup,
51
+ generateSolutionScript: () => generateSolutionScript,
52
+ getLanguageRuntimeProfile: () => getLanguageRuntimeProfile,
53
+ getSupportedLanguageProfiles: () => getSupportedLanguageProfiles,
54
+ identifyConversions: () => identifyConversions,
55
+ isLanguageSupported: () => isLanguageSupported,
56
+ normalizeRuntimeTraceContract: () => normalizeRuntimeTraceContract,
57
+ resolveBrowserHarnessAssets: () => resolveBrowserHarnessAssets,
58
+ stableStringifyRuntimeTraceContract: () => stableStringifyRuntimeTraceContract,
59
+ templateToPythonLiteral: () => templateToPythonLiteral,
60
+ toPythonLiteral: () => toPythonLiteral,
61
+ withTypeScriptRuntimeDeclarations: () => withTypeScriptRuntimeDeclarations
62
+ });
63
+ module.exports = __toCommonJS(src_exports);
64
+
65
+ // packages/harness-core/src/trace-contract.ts
66
+ var RUNTIME_TRACE_CONTRACT_SCHEMA_VERSION = "2026-03-07";
67
+ var TRACE_EVENTS = /* @__PURE__ */ new Set([
68
+ "line",
69
+ "call",
70
+ "return",
71
+ "exception",
72
+ "timeout",
73
+ "stdout"
74
+ ]);
75
+ var TRACE_ACCESS_KINDS = /* @__PURE__ */ new Set([
76
+ "indexed-read",
77
+ "indexed-write",
78
+ "cell-read",
79
+ "cell-write",
80
+ "mutating-call"
81
+ ]);
82
+ function normalizeLineNumber(value, fallback = 1) {
83
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
84
+ const normalized = Math.floor(value);
85
+ return normalized > 0 ? normalized : fallback;
86
+ }
87
+ function normalizeOutputLineCount(value) {
88
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
89
+ const normalized = Math.floor(value);
90
+ return normalized >= 0 ? normalized : void 0;
91
+ }
92
+ function normalizeEvent(value) {
93
+ if (typeof value === "string" && TRACE_EVENTS.has(value)) {
94
+ return value;
95
+ }
96
+ return "line";
97
+ }
98
+ function normalizeAccessKind(value) {
99
+ if (typeof value === "string" && TRACE_ACCESS_KINDS.has(value)) {
100
+ return value;
101
+ }
102
+ return null;
103
+ }
104
+ function normalizeFunctionName(value) {
105
+ if (typeof value === "string" && value.length > 0) return value;
106
+ return "<module>";
107
+ }
108
+ function normalizeKind(value) {
109
+ if (value === "map" || value === "set" || value === "hashmap") {
110
+ return value;
111
+ }
112
+ return "hashmap";
113
+ }
114
+ function normalizeObjectKind(value) {
115
+ if (value === "hashmap" || value === "map" || value === "set" || value === "tree" || value === "linked-list" || value === "graph-adjacency") {
116
+ return value;
117
+ }
118
+ return null;
119
+ }
120
+ function normalizeScalar(value) {
121
+ if (value === null || value === void 0) return value;
122
+ if (typeof value === "string" || typeof value === "boolean") return value;
123
+ if (typeof value === "number") return Number.isFinite(value) ? value : String(value);
124
+ if (typeof value === "bigint") {
125
+ const asNumber = Number(value);
126
+ return Number.isSafeInteger(asNumber) ? asNumber : String(value);
127
+ }
128
+ if (typeof value === "function") return "<function>";
129
+ return null;
130
+ }
131
+ function normalizeUnknown(value, depth = 0, seen = /* @__PURE__ */ new WeakSet()) {
132
+ if (depth > 48) return "<max depth>";
133
+ const scalar = normalizeScalar(value);
134
+ if (scalar !== null || value === null || value === void 0) {
135
+ return scalar;
136
+ }
137
+ if (Array.isArray(value)) {
138
+ return value.map((item) => {
139
+ if (item === void 0) return null;
140
+ return normalizeUnknown(item, depth + 1, seen);
141
+ });
142
+ }
143
+ if (typeof value === "object" && value) {
144
+ if (seen.has(value)) return "<cycle>";
145
+ seen.add(value);
146
+ const normalized = {};
147
+ for (const key of Object.keys(value).sort()) {
148
+ const child = value[key];
149
+ if (child === void 0) continue;
150
+ normalized[key] = normalizeUnknown(child, depth + 1, seen);
151
+ }
152
+ seen.delete(value);
153
+ return normalized;
154
+ }
155
+ return String(value);
156
+ }
157
+ function normalizeAccesses(accesses) {
158
+ if (!Array.isArray(accesses) || accesses.length === 0) {
159
+ return void 0;
160
+ }
161
+ const normalized = accesses.map((access) => {
162
+ const variable = typeof access?.variable === "string" && access.variable.length > 0 ? access.variable : "";
163
+ const kind = normalizeAccessKind(access?.kind);
164
+ if (!variable || !kind) {
165
+ return null;
166
+ }
167
+ const indices = Array.isArray(access?.indices) ? access.indices.map(
168
+ (index) => typeof index === "number" && Number.isFinite(index) ? Math.floor(index) : null
169
+ ).filter((index) => index !== null) : void 0;
170
+ const pathDepth = access?.pathDepth === 1 || access?.pathDepth === 2 ? access.pathDepth : void 0;
171
+ const method = typeof access?.method === "string" && access.method.length > 0 ? access.method : void 0;
172
+ const payload = {
173
+ variable,
174
+ kind
175
+ };
176
+ if (indices && indices.length > 0) {
177
+ payload.indices = indices;
178
+ }
179
+ if (pathDepth !== void 0) {
180
+ payload.pathDepth = pathDepth;
181
+ }
182
+ if (method) {
183
+ payload.method = method;
184
+ }
185
+ return payload;
186
+ }).filter((access) => access !== null);
187
+ return normalized.length > 0 ? normalized : void 0;
188
+ }
189
+ function normalizeRecord(value) {
190
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
191
+ return normalizeUnknown(value);
192
+ }
193
+ function normalizeCallStackFrame(frame) {
194
+ return {
195
+ function: normalizeFunctionName(frame?.function),
196
+ line: normalizeLineNumber(frame?.line, 1),
197
+ args: normalizeRecord(frame?.args)
198
+ };
199
+ }
200
+ function normalizeVisualizationPayload(payload) {
201
+ const hashMaps = Array.isArray(payload?.hashMaps) ? payload.hashMaps.map((entry) => ({
202
+ name: typeof entry?.name === "string" ? entry.name : "",
203
+ kind: normalizeKind(entry?.kind),
204
+ entries: Array.isArray(entry?.entries) ? entry.entries.map((item) => ({
205
+ key: normalizeUnknown(item?.key),
206
+ value: normalizeUnknown(item?.value),
207
+ ...item?.highlight ? { highlight: true } : {}
208
+ })) : [],
209
+ ...entry?.highlightedKey !== void 0 ? { highlightedKey: normalizeUnknown(entry.highlightedKey) } : {},
210
+ ...entry?.deletedKey !== void 0 ? { deletedKey: normalizeUnknown(entry.deletedKey) } : {}
211
+ })).sort((a, b) => `${a.name}:${a.kind}`.localeCompare(`${b.name}:${b.kind}`)) : [];
212
+ const objectKinds = payload?.objectKinds && typeof payload.objectKinds === "object" ? Object.fromEntries(
213
+ Object.entries(payload.objectKinds).filter(([name]) => typeof name === "string" && name.length > 0).map(([name, kind]) => [name, normalizeObjectKind(kind)]).filter((entry) => entry[1] !== null).sort((a, b) => a[0].localeCompare(b[0]))
214
+ ) : void 0;
215
+ if (hashMaps.length === 0 && (!objectKinds || Object.keys(objectKinds).length === 0)) {
216
+ return void 0;
217
+ }
218
+ return {
219
+ ...hashMaps.length > 0 ? { hashMaps } : {},
220
+ ...objectKinds && Object.keys(objectKinds).length > 0 ? { objectKinds } : {}
221
+ };
222
+ }
223
+ function normalizeTraceStep(step) {
224
+ const normalizedStdoutCount = normalizeOutputLineCount(step?.stdoutLineCount);
225
+ const normalizedVisualization = normalizeVisualizationPayload(step?.visualization);
226
+ const normalizedAccesses = normalizeAccesses(step?.accesses);
227
+ return {
228
+ event: normalizeEvent(step?.event),
229
+ line: normalizeLineNumber(step?.line, 1),
230
+ function: normalizeFunctionName(step?.function),
231
+ variables: normalizeRecord(step?.variables),
232
+ ...Array.isArray(step?.callStack) && step.callStack.length > 0 ? { callStack: step.callStack.map(normalizeCallStackFrame) } : {},
233
+ ...normalizedAccesses ? { accesses: normalizedAccesses } : {},
234
+ ...step?.returnValue !== void 0 ? { returnValue: normalizeUnknown(step.returnValue) } : {},
235
+ ...normalizedStdoutCount !== void 0 ? { stdoutLineCount: normalizedStdoutCount } : {},
236
+ ...normalizedVisualization ? { visualization: normalizedVisualization } : {}
237
+ };
238
+ }
239
+ function normalizeRuntimeTraceContract(language, result) {
240
+ const normalizedTrace = Array.isArray(result.trace) ? result.trace.map(normalizeTraceStep) : [];
241
+ const lineEventCount = typeof result.lineEventCount === "number" && Number.isFinite(result.lineEventCount) ? Math.floor(result.lineEventCount) : normalizedTrace.filter((step) => step.event === "line").length;
242
+ const normalizedConsole = Array.isArray(result.consoleOutput) ? result.consoleOutput.map((line) => String(line)) : [];
243
+ return {
244
+ schemaVersion: RUNTIME_TRACE_CONTRACT_SCHEMA_VERSION,
245
+ language,
246
+ success: Boolean(result.success),
247
+ ...Object.prototype.hasOwnProperty.call(result, "output") ? { output: normalizeUnknown(result.output) } : {},
248
+ ...typeof result.error === "string" && result.error.length > 0 ? { error: result.error } : {},
249
+ ...typeof result.errorLine === "number" && Number.isFinite(result.errorLine) ? { errorLine: Math.floor(result.errorLine) } : {},
250
+ consoleOutput: normalizedConsole,
251
+ trace: normalizedTrace,
252
+ ...result.traceLimitExceeded !== void 0 ? { traceLimitExceeded: Boolean(result.traceLimitExceeded) } : {},
253
+ ...typeof result.timeoutReason === "string" && result.timeoutReason.length > 0 ? { timeoutReason: result.timeoutReason } : {},
254
+ lineEventCount: Math.max(0, lineEventCount),
255
+ traceStepCount: normalizedTrace.length
256
+ };
257
+ }
258
+ function stableStringifyRuntimeTraceContract(value) {
259
+ return JSON.stringify(normalizeUnknown(value), null, 2);
260
+ }
261
+
262
+ // packages/harness-core/src/trace-adapters/shared.ts
263
+ function denormalizeCallStackFrame(frame) {
264
+ return {
265
+ function: frame.function,
266
+ line: frame.line,
267
+ args: frame.args
268
+ };
269
+ }
270
+ function denormalizeTraceStep(step) {
271
+ return {
272
+ line: step.line,
273
+ event: step.event,
274
+ variables: step.variables,
275
+ function: step.function,
276
+ ...step.callStack ? { callStack: step.callStack.map(denormalizeCallStackFrame) } : {},
277
+ ...step.accesses ? { accesses: step.accesses } : {},
278
+ ...step.returnValue !== void 0 ? { returnValue: step.returnValue } : {},
279
+ ...step.stdoutLineCount !== void 0 ? { stdoutLineCount: step.stdoutLineCount } : {},
280
+ ...step.visualization ? { visualization: step.visualization } : {}
281
+ };
282
+ }
283
+ function adaptTraceExecutionResult(language, result) {
284
+ const normalized = normalizeRuntimeTraceContract(language, result);
285
+ const adaptedTrace = normalized.trace.map(denormalizeTraceStep);
286
+ return {
287
+ success: normalized.success,
288
+ ...Object.prototype.hasOwnProperty.call(normalized, "output") ? { output: normalized.output } : {},
289
+ ...normalized.error ? { error: normalized.error } : {},
290
+ ...normalized.errorLine !== void 0 ? { errorLine: normalized.errorLine } : {},
291
+ trace: adaptedTrace,
292
+ executionTimeMs: typeof result.executionTimeMs === "number" && Number.isFinite(result.executionTimeMs) ? result.executionTimeMs : 0,
293
+ consoleOutput: normalized.consoleOutput,
294
+ ...normalized.traceLimitExceeded !== void 0 ? { traceLimitExceeded: normalized.traceLimitExceeded } : {},
295
+ ...normalized.timeoutReason ? { timeoutReason: normalized.timeoutReason } : {},
296
+ lineEventCount: normalized.lineEventCount,
297
+ traceStepCount: adaptedTrace.length
298
+ };
299
+ }
300
+
301
+ // packages/harness-core/src/trace-adapters/python.ts
302
+ function adaptPythonTraceExecutionResult(result) {
303
+ return adaptTraceExecutionResult("python", result);
304
+ }
305
+
306
+ // packages/harness-core/src/trace-adapters/javascript.ts
307
+ function adaptJavaScriptTraceExecutionResult(language, result) {
308
+ return adaptTraceExecutionResult(language, result);
309
+ }
310
+
311
+ // packages/harness-browser/src/javascript-worker-client.ts
312
+ var EXECUTION_TIMEOUT_MS = 7e3;
313
+ var INTERVIEW_MODE_TIMEOUT_MS = 5e3;
314
+ var TRACING_TIMEOUT_MS = 7e3;
315
+ var INIT_TIMEOUT_MS = 1e4;
316
+ var MESSAGE_TIMEOUT_MS = 12e3;
317
+ var WORKER_READY_TIMEOUT_MS = 1e4;
318
+ var JavaScriptWorkerClient = class {
319
+ constructor(options) {
320
+ this.options = options;
321
+ this.debug = options.debug ?? process.env.NODE_ENV === "development";
322
+ }
323
+ worker = null;
324
+ pendingMessages = /* @__PURE__ */ new Map();
325
+ messageId = 0;
326
+ isInitializing = false;
327
+ initPromise = null;
328
+ workerReadyPromise = null;
329
+ workerReadyResolve = null;
330
+ workerReadyReject = null;
331
+ debug;
332
+ isSupported() {
333
+ return typeof Worker !== "undefined";
334
+ }
335
+ getWorker() {
336
+ if (this.worker) return this.worker;
337
+ if (!this.isSupported()) {
338
+ throw new Error("Web Workers are not supported in this environment");
339
+ }
340
+ this.workerReadyPromise = new Promise((resolve, reject) => {
341
+ this.workerReadyResolve = resolve;
342
+ this.workerReadyReject = (error) => reject(error);
343
+ });
344
+ const workerUrl = this.debug && !this.options.workerUrl.includes("?") ? `${this.options.workerUrl}?dev=${Date.now()}` : this.options.workerUrl;
345
+ this.worker = new Worker(workerUrl);
346
+ this.worker.onmessage = (event) => {
347
+ const { id, type, payload } = event.data;
348
+ if (type === "worker-ready") {
349
+ this.workerReadyResolve?.();
350
+ this.workerReadyResolve = null;
351
+ this.workerReadyReject = null;
352
+ if (this.debug) console.log("[JavaScriptWorkerClient] worker-ready");
353
+ return;
354
+ }
355
+ if (id) {
356
+ const pending = this.pendingMessages.get(id);
357
+ if (!pending) return;
358
+ this.pendingMessages.delete(id);
359
+ if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);
360
+ if (type === "error") {
361
+ pending.reject(new Error(payload.error));
362
+ return;
363
+ }
364
+ pending.resolve(payload);
365
+ }
366
+ };
367
+ this.worker.onerror = (error) => {
368
+ console.error("[JavaScriptWorkerClient] Worker error:", error);
369
+ const workerError = new Error("Worker error");
370
+ this.workerReadyReject?.(workerError);
371
+ this.workerReadyResolve = null;
372
+ this.workerReadyReject = null;
373
+ for (const [id, pending] of this.pendingMessages) {
374
+ if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);
375
+ pending.reject(workerError);
376
+ this.pendingMessages.delete(id);
377
+ }
378
+ };
379
+ return this.worker;
380
+ }
381
+ async waitForWorkerReady() {
382
+ const readyPromise = this.workerReadyPromise;
383
+ if (!readyPromise) return;
384
+ await new Promise((resolve, reject) => {
385
+ let settled = false;
386
+ const timeoutId = globalThis.setTimeout(() => {
387
+ if (settled) return;
388
+ settled = true;
389
+ const timeoutError = new Error(
390
+ `JavaScript worker failed to initialize in time (${Math.round(WORKER_READY_TIMEOUT_MS / 1e3)}s)`
391
+ );
392
+ this.terminateAndReset(timeoutError);
393
+ reject(timeoutError);
394
+ }, WORKER_READY_TIMEOUT_MS);
395
+ readyPromise.then(() => {
396
+ if (settled) return;
397
+ settled = true;
398
+ globalThis.clearTimeout(timeoutId);
399
+ resolve();
400
+ }).catch((error) => {
401
+ if (settled) return;
402
+ settled = true;
403
+ globalThis.clearTimeout(timeoutId);
404
+ reject(error instanceof Error ? error : new Error(String(error)));
405
+ });
406
+ });
407
+ }
408
+ async sendMessage(type, payload, timeoutMs = MESSAGE_TIMEOUT_MS) {
409
+ const worker = this.getWorker();
410
+ await this.waitForWorkerReady();
411
+ const id = String(++this.messageId);
412
+ return new Promise((resolve, reject) => {
413
+ this.pendingMessages.set(id, {
414
+ resolve,
415
+ reject
416
+ });
417
+ const timeoutId = globalThis.setTimeout(() => {
418
+ const pending2 = this.pendingMessages.get(id);
419
+ if (!pending2) return;
420
+ this.pendingMessages.delete(id);
421
+ pending2.reject(new Error(`Worker request timed out: ${type}`));
422
+ }, timeoutMs);
423
+ const pending = this.pendingMessages.get(id);
424
+ if (pending) pending.timeoutId = timeoutId;
425
+ worker.postMessage({ id, type, payload });
426
+ });
427
+ }
428
+ async executeWithTimeout(executor, timeoutMs) {
429
+ return new Promise((resolve, reject) => {
430
+ let settled = false;
431
+ const timeoutId = globalThis.setTimeout(() => {
432
+ if (settled) return;
433
+ settled = true;
434
+ this.terminateAndReset();
435
+ reject(
436
+ new Error(
437
+ `Execution timed out (possible infinite loop). Code execution was stopped after ${Math.round(timeoutMs / 1e3)} seconds.`
438
+ )
439
+ );
440
+ }, timeoutMs);
441
+ executor().then((result) => {
442
+ if (settled) return;
443
+ settled = true;
444
+ globalThis.clearTimeout(timeoutId);
445
+ resolve(result);
446
+ }).catch((error) => {
447
+ if (settled) return;
448
+ settled = true;
449
+ globalThis.clearTimeout(timeoutId);
450
+ reject(error);
451
+ });
452
+ });
453
+ }
454
+ terminateAndReset(reason = new Error("Worker was terminated")) {
455
+ this.workerReadyReject?.(reason);
456
+ if (this.worker) {
457
+ this.worker.terminate();
458
+ this.worker = null;
459
+ }
460
+ this.initPromise = null;
461
+ this.isInitializing = false;
462
+ this.workerReadyPromise = null;
463
+ this.workerReadyResolve = null;
464
+ this.workerReadyReject = null;
465
+ for (const [, pending] of this.pendingMessages) {
466
+ if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);
467
+ pending.reject(reason);
468
+ }
469
+ this.pendingMessages.clear();
470
+ }
471
+ async init() {
472
+ if (this.initPromise) return this.initPromise;
473
+ if (this.isInitializing) {
474
+ await new Promise((resolve) => globalThis.setTimeout(resolve, 100));
475
+ return this.init();
476
+ }
477
+ this.isInitializing = true;
478
+ this.initPromise = this.sendMessage("init", void 0, INIT_TIMEOUT_MS);
479
+ try {
480
+ return await this.initPromise;
481
+ } catch (error) {
482
+ this.initPromise = null;
483
+ throw error;
484
+ } finally {
485
+ this.isInitializing = false;
486
+ }
487
+ }
488
+ async executeWithTracing(code, functionName, inputs, options, executionStyle = "function", language = "javascript") {
489
+ await this.init();
490
+ return this.executeWithTimeout(
491
+ () => this.sendMessage(
492
+ "execute-with-tracing",
493
+ {
494
+ code,
495
+ functionName,
496
+ inputs,
497
+ options,
498
+ executionStyle,
499
+ language
500
+ },
501
+ TRACING_TIMEOUT_MS + 2e3
502
+ ),
503
+ TRACING_TIMEOUT_MS
504
+ );
505
+ }
506
+ async executeCode(code, functionName, inputs, executionStyle = "function", language = "javascript") {
507
+ await this.init();
508
+ return this.executeWithTimeout(
509
+ () => this.sendMessage(
510
+ "execute-code",
511
+ {
512
+ code,
513
+ functionName,
514
+ inputs,
515
+ executionStyle,
516
+ language
517
+ },
518
+ EXECUTION_TIMEOUT_MS + 2e3
519
+ ),
520
+ EXECUTION_TIMEOUT_MS
521
+ );
522
+ }
523
+ async executeCodeInterviewMode(code, functionName, inputs, executionStyle = "function", language = "javascript") {
524
+ await this.init();
525
+ try {
526
+ const result = await this.executeWithTimeout(
527
+ () => this.sendMessage(
528
+ "execute-code-interview",
529
+ {
530
+ code,
531
+ functionName,
532
+ inputs,
533
+ executionStyle,
534
+ language
535
+ },
536
+ INTERVIEW_MODE_TIMEOUT_MS + 2e3
537
+ ),
538
+ INTERVIEW_MODE_TIMEOUT_MS
539
+ );
540
+ if (!result.success && result.error) {
541
+ const normalized = result.error.toLowerCase();
542
+ const isTimeoutOrResourceLimit = normalized.includes("timed out") || normalized.includes("infinite loop") || normalized.includes("line-limit") || normalized.includes("single-line-limit") || normalized.includes("recursion-limit") || normalized.includes("trace-limit") || normalized.includes("line events") || normalized.includes("trace steps") || normalized.includes("call depth");
543
+ if (isTimeoutOrResourceLimit) {
544
+ return {
545
+ success: false,
546
+ output: null,
547
+ error: "Time Limit Exceeded",
548
+ consoleOutput: result.consoleOutput ?? []
549
+ };
550
+ }
551
+ }
552
+ return result;
553
+ } catch {
554
+ return {
555
+ success: false,
556
+ output: null,
557
+ error: "Time Limit Exceeded",
558
+ consoleOutput: []
559
+ };
560
+ }
561
+ }
562
+ terminate() {
563
+ this.terminateAndReset();
564
+ }
565
+ };
566
+
567
+ // packages/harness-browser/src/runtime-capability-guards.ts
568
+ function isScriptRequest(functionName) {
569
+ if (functionName == null) return true;
570
+ return functionName.trim().length === 0;
571
+ }
572
+ function executionStyleLabel(executionStyle) {
573
+ if (executionStyle === "solution-method") return "solution-method";
574
+ if (executionStyle === "ops-class") return "ops-class";
575
+ return "function";
576
+ }
577
+ function isExecutionStyleSupported(profile, executionStyle) {
578
+ const styles = profile.capabilities.execution.styles;
579
+ if (executionStyle === "solution-method") return styles.solutionMethod;
580
+ if (executionStyle === "ops-class") return styles.opsClass;
581
+ return styles.function;
582
+ }
583
+ function describeRequest(request) {
584
+ if (request === "trace") return "tracing";
585
+ if (request === "interview") return "interview execution";
586
+ return "execution";
587
+ }
588
+ function assertRuntimeRequestSupported(profile, options) {
589
+ if (options.request === "trace" && !profile.capabilities.tracing.supported) {
590
+ throw new Error(`Runtime "${profile.language}" does not support tracing.`);
591
+ }
592
+ if (options.request === "interview" && !profile.capabilities.execution.styles.interviewMode) {
593
+ throw new Error(`Runtime "${profile.language}" does not support interview execution.`);
594
+ }
595
+ if (!isExecutionStyleSupported(profile, options.executionStyle)) {
596
+ throw new Error(
597
+ `Runtime "${profile.language}" does not support execution style "${executionStyleLabel(options.executionStyle)}".`
598
+ );
599
+ }
600
+ if (isScriptRequest(options.functionName) && !profile.capabilities.execution.styles.script) {
601
+ throw new Error(`Runtime "${profile.language}" does not support script mode ${describeRequest(options.request)}.`);
602
+ }
603
+ }
604
+
605
+ // packages/harness-browser/src/runtime-profiles.ts
606
+ var PYTHON_RUNTIME_PROFILE = {
607
+ language: "python",
608
+ maturity: "stable",
609
+ capabilities: {
610
+ execution: {
611
+ styles: {
612
+ function: true,
613
+ solutionMethod: true,
614
+ opsClass: true,
615
+ script: true,
616
+ interviewMode: true
617
+ },
618
+ timeouts: {
619
+ clientTimeouts: true,
620
+ runtimeTimeouts: true
621
+ }
622
+ },
623
+ tracing: {
624
+ supported: true,
625
+ events: {
626
+ line: true,
627
+ call: true,
628
+ return: true,
629
+ exception: true,
630
+ stdout: true,
631
+ timeout: true
632
+ },
633
+ controls: {
634
+ maxTraceSteps: true,
635
+ maxLineEvents: true,
636
+ maxSingleLineHits: true,
637
+ minimalTrace: true
638
+ },
639
+ fidelity: {
640
+ preciseLineMapping: true,
641
+ stableFunctionNames: true,
642
+ callStack: true
643
+ }
644
+ },
645
+ diagnostics: {
646
+ compileErrors: false,
647
+ runtimeErrors: true,
648
+ mappedErrorLines: true,
649
+ stackTraces: false
650
+ },
651
+ structures: {
652
+ treeNodeRefs: true,
653
+ listNodeRefs: true,
654
+ mapSerialization: true,
655
+ setSerialization: true,
656
+ graphSerialization: true,
657
+ cycleReferences: true
658
+ },
659
+ visualization: {
660
+ runtimePayloads: true,
661
+ objectKinds: true,
662
+ hashMaps: true,
663
+ stepVisualization: true
664
+ }
665
+ }
666
+ };
667
+ var JAVASCRIPT_RUNTIME_PROFILE = {
668
+ language: "javascript",
669
+ maturity: "stable",
670
+ capabilities: {
671
+ execution: {
672
+ styles: {
673
+ function: true,
674
+ solutionMethod: true,
675
+ opsClass: true,
676
+ script: true,
677
+ interviewMode: true
678
+ },
679
+ timeouts: {
680
+ clientTimeouts: true,
681
+ runtimeTimeouts: false
682
+ }
683
+ },
684
+ tracing: {
685
+ supported: true,
686
+ events: {
687
+ line: true,
688
+ call: true,
689
+ return: true,
690
+ exception: true,
691
+ stdout: false,
692
+ timeout: true
693
+ },
694
+ controls: {
695
+ maxTraceSteps: true,
696
+ maxLineEvents: true,
697
+ maxSingleLineHits: true,
698
+ minimalTrace: true
699
+ },
700
+ fidelity: {
701
+ preciseLineMapping: true,
702
+ stableFunctionNames: true,
703
+ callStack: true
704
+ }
705
+ },
706
+ diagnostics: {
707
+ compileErrors: false,
708
+ runtimeErrors: true,
709
+ mappedErrorLines: false,
710
+ stackTraces: false
711
+ },
712
+ structures: {
713
+ treeNodeRefs: true,
714
+ listNodeRefs: true,
715
+ mapSerialization: true,
716
+ setSerialization: true,
717
+ graphSerialization: true,
718
+ cycleReferences: true
719
+ },
720
+ visualization: {
721
+ runtimePayloads: true,
722
+ objectKinds: true,
723
+ hashMaps: true,
724
+ stepVisualization: true
725
+ }
726
+ }
727
+ };
728
+ var TYPESCRIPT_RUNTIME_PROFILE = {
729
+ language: "typescript",
730
+ maturity: "stable",
731
+ capabilities: {
732
+ execution: {
733
+ styles: {
734
+ function: true,
735
+ solutionMethod: true,
736
+ opsClass: true,
737
+ script: true,
738
+ interviewMode: true
739
+ },
740
+ timeouts: {
741
+ clientTimeouts: true,
742
+ runtimeTimeouts: false
743
+ }
744
+ },
745
+ tracing: {
746
+ supported: true,
747
+ events: {
748
+ line: true,
749
+ call: true,
750
+ return: true,
751
+ exception: true,
752
+ stdout: false,
753
+ timeout: true
754
+ },
755
+ controls: {
756
+ maxTraceSteps: true,
757
+ maxLineEvents: true,
758
+ maxSingleLineHits: true,
759
+ minimalTrace: true
760
+ },
761
+ fidelity: {
762
+ preciseLineMapping: true,
763
+ stableFunctionNames: true,
764
+ callStack: true
765
+ }
766
+ },
767
+ diagnostics: {
768
+ compileErrors: true,
769
+ runtimeErrors: true,
770
+ mappedErrorLines: true,
771
+ stackTraces: false
772
+ },
773
+ structures: {
774
+ treeNodeRefs: true,
775
+ listNodeRefs: true,
776
+ mapSerialization: true,
777
+ setSerialization: true,
778
+ graphSerialization: true,
779
+ cycleReferences: true
780
+ },
781
+ visualization: {
782
+ runtimePayloads: true,
783
+ objectKinds: true,
784
+ hashMaps: true,
785
+ stepVisualization: true
786
+ }
787
+ }
788
+ };
789
+ var LANGUAGE_RUNTIME_PROFILES = {
790
+ python: PYTHON_RUNTIME_PROFILE,
791
+ javascript: JAVASCRIPT_RUNTIME_PROFILE,
792
+ typescript: TYPESCRIPT_RUNTIME_PROFILE
793
+ };
794
+ var SUPPORTED_LANGUAGES = Object.freeze(
795
+ Object.keys(LANGUAGE_RUNTIME_PROFILES)
796
+ );
797
+ function getLanguageRuntimeProfile(language) {
798
+ const profile = LANGUAGE_RUNTIME_PROFILES[language];
799
+ if (!profile) {
800
+ throw new Error(`Runtime profile for language "${language}" is not implemented yet.`);
801
+ }
802
+ return profile;
803
+ }
804
+ function getSupportedLanguageProfiles() {
805
+ return SUPPORTED_LANGUAGES.map((language) => LANGUAGE_RUNTIME_PROFILES[language]);
806
+ }
807
+ function isLanguageSupported(language) {
808
+ return SUPPORTED_LANGUAGES.includes(language);
809
+ }
810
+
811
+ // packages/harness-browser/src/javascript-runtime-client.ts
812
+ var JavaScriptRuntimeClient = class {
813
+ constructor(runtimeLanguage, workerClient) {
814
+ this.runtimeLanguage = runtimeLanguage;
815
+ this.workerClient = workerClient;
816
+ }
817
+ async init() {
818
+ return this.workerClient.init();
819
+ }
820
+ async executeWithTracing(code, functionName, inputs, options, executionStyle = "function") {
821
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile(this.runtimeLanguage), {
822
+ request: "trace",
823
+ executionStyle,
824
+ functionName
825
+ });
826
+ const rawResult = await this.workerClient.executeWithTracing(
827
+ code,
828
+ functionName,
829
+ inputs,
830
+ options,
831
+ executionStyle,
832
+ this.runtimeLanguage
833
+ );
834
+ return adaptJavaScriptTraceExecutionResult(this.runtimeLanguage, rawResult);
835
+ }
836
+ async executeCode(code, functionName, inputs, executionStyle = "function") {
837
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile(this.runtimeLanguage), {
838
+ request: "execute",
839
+ executionStyle,
840
+ functionName
841
+ });
842
+ return this.workerClient.executeCode(
843
+ code,
844
+ functionName,
845
+ inputs,
846
+ executionStyle,
847
+ this.runtimeLanguage
848
+ );
849
+ }
850
+ async executeCodeInterviewMode(code, functionName, inputs, executionStyle = "function") {
851
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile(this.runtimeLanguage), {
852
+ request: "interview",
853
+ executionStyle,
854
+ functionName
855
+ });
856
+ return this.workerClient.executeCodeInterviewMode(
857
+ code,
858
+ functionName,
859
+ inputs,
860
+ executionStyle,
861
+ this.runtimeLanguage
862
+ );
863
+ }
864
+ };
865
+ function createJavaScriptRuntimeClient(runtimeLanguage, workerClient) {
866
+ return new JavaScriptRuntimeClient(runtimeLanguage, workerClient);
867
+ }
868
+
869
+ // packages/harness-browser/src/pyodide-worker-client.ts
870
+ var EXECUTION_TIMEOUT_MS2 = 1e4;
871
+ var INTERVIEW_MODE_TIMEOUT_MS2 = 5e3;
872
+ var TRACING_TIMEOUT_MS2 = 3e4;
873
+ var INIT_TIMEOUT_MS2 = 12e4;
874
+ var MESSAGE_TIMEOUT_MS2 = 2e4;
875
+ var WORKER_READY_TIMEOUT_MS2 = 1e4;
876
+ var PyodideWorkerClient = class {
877
+ constructor(options) {
878
+ this.options = options;
879
+ this.debug = options.debug ?? process.env.NODE_ENV === "development";
880
+ }
881
+ worker = null;
882
+ pendingMessages = /* @__PURE__ */ new Map();
883
+ messageId = 0;
884
+ isInitializing = false;
885
+ initPromise = null;
886
+ workerReadyPromise = null;
887
+ workerReadyResolve = null;
888
+ workerReadyReject = null;
889
+ debug;
890
+ /**
891
+ * Check if Web Workers are supported
892
+ */
893
+ isSupported() {
894
+ return typeof Worker !== "undefined";
895
+ }
896
+ /**
897
+ * Get or create the worker instance
898
+ */
899
+ getWorker() {
900
+ if (this.worker) return this.worker;
901
+ if (!this.isSupported()) {
902
+ throw new Error("Web Workers are not supported in this environment");
903
+ }
904
+ this.workerReadyPromise = new Promise((resolve, reject) => {
905
+ this.workerReadyResolve = resolve;
906
+ this.workerReadyReject = (error) => reject(error);
907
+ });
908
+ const workerUrl = this.debug && !this.options.workerUrl.includes("?") ? `${this.options.workerUrl}?dev=${Date.now()}` : this.options.workerUrl;
909
+ this.worker = new Worker(workerUrl);
910
+ this.worker.onmessage = (event) => {
911
+ const { id, type, payload } = event.data;
912
+ if (type === "worker-ready") {
913
+ this.workerReadyResolve?.();
914
+ this.workerReadyResolve = null;
915
+ this.workerReadyReject = null;
916
+ if (this.debug) console.log("[PyodideWorkerClient] worker-ready");
917
+ return;
918
+ }
919
+ if (this.debug && !id) {
920
+ console.log("[PyodideWorkerClient] event", { type, payload });
921
+ }
922
+ if (id) {
923
+ const pending = this.pendingMessages.get(id);
924
+ if (pending) {
925
+ this.pendingMessages.delete(id);
926
+ if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);
927
+ if (type === "error") {
928
+ pending.reject(new Error(payload.error));
929
+ } else {
930
+ if (this.debug) console.log("[PyodideWorkerClient] recv", { id, type });
931
+ pending.resolve(payload);
932
+ }
933
+ }
934
+ }
935
+ };
936
+ this.worker.onerror = (error) => {
937
+ console.error("[PyodideWorkerClient] Worker error:", error);
938
+ const workerError = new Error("Worker error");
939
+ this.workerReadyReject?.(workerError);
940
+ this.workerReadyResolve = null;
941
+ this.workerReadyReject = null;
942
+ for (const [id, pending] of this.pendingMessages) {
943
+ if (pending.timeoutId) {
944
+ globalThis.clearTimeout(pending.timeoutId);
945
+ }
946
+ pending.reject(workerError);
947
+ this.pendingMessages.delete(id);
948
+ }
949
+ };
950
+ return this.worker;
951
+ }
952
+ /**
953
+ * Wait for worker bootstrap signal with timeout.
954
+ * Guards against deadlocks when the worker script fails before posting "worker-ready".
955
+ */
956
+ async waitForWorkerReady() {
957
+ const readyPromise = this.workerReadyPromise;
958
+ if (!readyPromise) return;
959
+ await new Promise((resolve, reject) => {
960
+ let settled = false;
961
+ const timeoutId = globalThis.setTimeout(() => {
962
+ if (settled) return;
963
+ settled = true;
964
+ const timeoutError = new Error(
965
+ `Python worker failed to initialize in time (${Math.round(WORKER_READY_TIMEOUT_MS2 / 1e3)}s)`
966
+ );
967
+ if (this.debug) {
968
+ console.warn("[PyodideWorkerClient] worker-ready timeout", { timeoutMs: WORKER_READY_TIMEOUT_MS2 });
969
+ }
970
+ this.terminateAndReset(timeoutError);
971
+ reject(timeoutError);
972
+ }, WORKER_READY_TIMEOUT_MS2);
973
+ readyPromise.then(() => {
974
+ if (settled) return;
975
+ settled = true;
976
+ globalThis.clearTimeout(timeoutId);
977
+ resolve();
978
+ }).catch((error) => {
979
+ if (settled) return;
980
+ settled = true;
981
+ globalThis.clearTimeout(timeoutId);
982
+ reject(error instanceof Error ? error : new Error(String(error)));
983
+ });
984
+ });
985
+ }
986
+ /**
987
+ * Send a message to the worker and wait for a response
988
+ */
989
+ async sendMessage(type, payload, timeoutMs = MESSAGE_TIMEOUT_MS2) {
990
+ const worker = this.getWorker();
991
+ await this.waitForWorkerReady();
992
+ const id = String(++this.messageId);
993
+ return new Promise((resolve, reject) => {
994
+ this.pendingMessages.set(id, {
995
+ resolve,
996
+ reject
997
+ });
998
+ if (this.debug) console.log("[PyodideWorkerClient] send", { id, type });
999
+ const timeoutId = globalThis.setTimeout(() => {
1000
+ const pending2 = this.pendingMessages.get(id);
1001
+ if (!pending2) return;
1002
+ this.pendingMessages.delete(id);
1003
+ if (this.debug) console.warn("[PyodideWorkerClient] timeout", { id, type });
1004
+ pending2.reject(new Error(`Worker request timed out: ${type}`));
1005
+ }, timeoutMs);
1006
+ const pending = this.pendingMessages.get(id);
1007
+ if (pending) pending.timeoutId = timeoutId;
1008
+ worker.postMessage({ id, type, payload });
1009
+ });
1010
+ }
1011
+ /**
1012
+ * Execute code with a timeout - terminates worker if execution takes too long
1013
+ */
1014
+ async executeWithTimeout(executor, timeoutMs = EXECUTION_TIMEOUT_MS2) {
1015
+ return new Promise((resolve, reject) => {
1016
+ let settled = false;
1017
+ const timeoutId = globalThis.setTimeout(() => {
1018
+ if (settled) return;
1019
+ settled = true;
1020
+ if (this.debug) {
1021
+ console.warn("[PyodideWorkerClient] Execution timeout - terminating worker");
1022
+ }
1023
+ this.terminateAndReset();
1024
+ const seconds = Math.round(timeoutMs / 1e3);
1025
+ reject(new Error(`Execution timed out (possible infinite loop). Code execution was stopped after ${seconds} seconds.`));
1026
+ }, timeoutMs);
1027
+ executor().then((result) => {
1028
+ if (settled) return;
1029
+ settled = true;
1030
+ globalThis.clearTimeout(timeoutId);
1031
+ resolve(result);
1032
+ }).catch((error) => {
1033
+ if (settled) return;
1034
+ settled = true;
1035
+ globalThis.clearTimeout(timeoutId);
1036
+ reject(error);
1037
+ });
1038
+ });
1039
+ }
1040
+ /**
1041
+ * Terminate the worker and reset state for recreation
1042
+ */
1043
+ terminateAndReset(reason = new Error("Worker was terminated")) {
1044
+ this.workerReadyReject?.(reason);
1045
+ if (this.worker) {
1046
+ this.worker.terminate();
1047
+ this.worker = null;
1048
+ }
1049
+ this.initPromise = null;
1050
+ this.isInitializing = false;
1051
+ this.workerReadyPromise = null;
1052
+ this.workerReadyResolve = null;
1053
+ for (const [, pending] of this.pendingMessages) {
1054
+ if (pending.timeoutId) globalThis.clearTimeout(pending.timeoutId);
1055
+ pending.reject(reason);
1056
+ }
1057
+ this.pendingMessages.clear();
1058
+ }
1059
+ /**
1060
+ * Initialize Pyodide in the worker
1061
+ */
1062
+ async init() {
1063
+ if (this.initPromise) {
1064
+ return this.initPromise;
1065
+ }
1066
+ if (this.isInitializing) {
1067
+ await new Promise((resolve) => setTimeout(resolve, 100));
1068
+ return this.init();
1069
+ }
1070
+ this.isInitializing = true;
1071
+ this.initPromise = (async () => {
1072
+ try {
1073
+ return await this.sendMessage("init", void 0, INIT_TIMEOUT_MS2);
1074
+ } catch (error) {
1075
+ const message = error instanceof Error ? error.message : String(error);
1076
+ const shouldRetry = message.includes("Worker request timed out: init") || message.includes("Worker was terminated") || message.includes("Worker error") || message.includes("failed to initialize in time");
1077
+ if (!shouldRetry) {
1078
+ throw error;
1079
+ }
1080
+ if (this.debug) {
1081
+ console.warn("[PyodideWorkerClient] init failed, resetting worker and retrying once", { message });
1082
+ }
1083
+ this.terminateAndReset();
1084
+ return this.sendMessage("init", void 0, INIT_TIMEOUT_MS2);
1085
+ }
1086
+ })();
1087
+ try {
1088
+ const result = await this.initPromise;
1089
+ return result;
1090
+ } catch (error) {
1091
+ this.initPromise = null;
1092
+ throw error;
1093
+ } finally {
1094
+ this.isInitializing = false;
1095
+ }
1096
+ }
1097
+ /**
1098
+ * Execute Python code with tracing for step-by-step visualization
1099
+ * @param options.maxLineEvents - Max line events before abort (for complexity analysis, use higher values)
1100
+ */
1101
+ async executeWithTracing(code, functionName, inputs, options, executionStyle = "function") {
1102
+ await this.init();
1103
+ try {
1104
+ return await this.executeWithTimeout(
1105
+ () => this.sendMessage("execute-with-tracing", {
1106
+ code,
1107
+ functionName,
1108
+ inputs,
1109
+ executionStyle,
1110
+ options
1111
+ }, TRACING_TIMEOUT_MS2 + 5e3),
1112
+ // Message timeout slightly longer than execution timeout
1113
+ TRACING_TIMEOUT_MS2
1114
+ );
1115
+ } catch (error) {
1116
+ const errorMessage = error instanceof Error ? error.message : String(error);
1117
+ const isClientTimeout = errorMessage.includes("Execution timed out") || errorMessage.includes("possible infinite loop");
1118
+ if (isClientTimeout) {
1119
+ return {
1120
+ success: false,
1121
+ error: errorMessage,
1122
+ trace: [],
1123
+ executionTimeMs: TRACING_TIMEOUT_MS2,
1124
+ consoleOutput: [],
1125
+ traceLimitExceeded: true,
1126
+ timeoutReason: "client-timeout",
1127
+ lineEventCount: 0,
1128
+ traceStepCount: 0
1129
+ };
1130
+ }
1131
+ throw error;
1132
+ }
1133
+ }
1134
+ /**
1135
+ * Execute Python code without tracing (for running tests)
1136
+ */
1137
+ async executeCode(code, functionName, inputs, executionStyle = "function") {
1138
+ await this.init();
1139
+ return this.executeWithTimeout(
1140
+ () => this.sendMessage("execute-code", {
1141
+ code,
1142
+ functionName,
1143
+ inputs,
1144
+ executionStyle
1145
+ }, EXECUTION_TIMEOUT_MS2 + 5e3),
1146
+ EXECUTION_TIMEOUT_MS2
1147
+ );
1148
+ }
1149
+ /**
1150
+ * Execute Python code in interview mode - 5 second timeout, generic error messages
1151
+ * Does not reveal which line caused the timeout
1152
+ */
1153
+ async executeCodeInterviewMode(code, functionName, inputs, executionStyle = "function") {
1154
+ await this.init();
1155
+ try {
1156
+ const result = await this.executeWithTimeout(
1157
+ () => this.sendMessage("execute-code-interview", {
1158
+ code,
1159
+ functionName,
1160
+ inputs,
1161
+ executionStyle
1162
+ }, INTERVIEW_MODE_TIMEOUT_MS2 + 2e3),
1163
+ INTERVIEW_MODE_TIMEOUT_MS2
1164
+ );
1165
+ if (!result.success && result.error) {
1166
+ const normalizedError = result.error.toLowerCase();
1167
+ const isTimeoutOrResourceLimit = normalizedError.includes("timed out") || normalizedError.includes("execution timeout") || normalizedError.includes("infinite loop") || normalizedError.includes("interview_guard_triggered") || normalizedError.includes("memory-limit") || normalizedError.includes("line-limit") || normalizedError.includes("single-line-limit") || normalizedError.includes("recursion-limit");
1168
+ if (isTimeoutOrResourceLimit) {
1169
+ return {
1170
+ success: false,
1171
+ output: null,
1172
+ error: "Time Limit Exceeded",
1173
+ consoleOutput: result.consoleOutput ?? []
1174
+ };
1175
+ }
1176
+ }
1177
+ return result;
1178
+ } catch (error) {
1179
+ const errorMsg = error instanceof Error ? error.message : String(error);
1180
+ if (errorMsg.includes("timed out") || errorMsg.includes("Execution timeout")) {
1181
+ return {
1182
+ success: false,
1183
+ output: null,
1184
+ error: "Time Limit Exceeded",
1185
+ consoleOutput: []
1186
+ };
1187
+ }
1188
+ return {
1189
+ success: false,
1190
+ output: null,
1191
+ error: errorMsg,
1192
+ consoleOutput: []
1193
+ };
1194
+ }
1195
+ }
1196
+ /**
1197
+ * Check the status of the worker
1198
+ */
1199
+ async getStatus() {
1200
+ return this.sendMessage("status");
1201
+ }
1202
+ /**
1203
+ * Analyze Python code using AST (off main thread)
1204
+ * Returns CodeFacts with semantic information about the code
1205
+ */
1206
+ async analyzeCode(code) {
1207
+ await this.init();
1208
+ return this.sendMessage("analyze-code", { code }, 5e3);
1209
+ }
1210
+ /**
1211
+ * Terminate the worker and clean up resources
1212
+ */
1213
+ terminate() {
1214
+ this.terminateAndReset();
1215
+ }
1216
+ };
1217
+
1218
+ // packages/harness-browser/src/python-runtime-client.ts
1219
+ var PythonRuntimeClient = class {
1220
+ constructor(workerClient) {
1221
+ this.workerClient = workerClient;
1222
+ }
1223
+ async init() {
1224
+ return this.workerClient.init();
1225
+ }
1226
+ async executeWithTracing(code, functionName, inputs, options, executionStyle = "function") {
1227
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile("python"), {
1228
+ request: "trace",
1229
+ executionStyle,
1230
+ functionName
1231
+ });
1232
+ const rawResult = await this.workerClient.executeWithTracing(
1233
+ code,
1234
+ functionName,
1235
+ inputs,
1236
+ options,
1237
+ executionStyle
1238
+ );
1239
+ return adaptPythonTraceExecutionResult(rawResult);
1240
+ }
1241
+ async executeCode(code, functionName, inputs, executionStyle = "function") {
1242
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile("python"), {
1243
+ request: "execute",
1244
+ executionStyle,
1245
+ functionName
1246
+ });
1247
+ return this.workerClient.executeCode(
1248
+ code,
1249
+ functionName,
1250
+ inputs,
1251
+ executionStyle
1252
+ );
1253
+ }
1254
+ async executeCodeInterviewMode(code, functionName, inputs, executionStyle = "function") {
1255
+ assertRuntimeRequestSupported(getLanguageRuntimeProfile("python"), {
1256
+ request: "interview",
1257
+ executionStyle,
1258
+ functionName
1259
+ });
1260
+ return this.workerClient.executeCodeInterviewMode(
1261
+ code,
1262
+ functionName,
1263
+ inputs,
1264
+ executionStyle
1265
+ );
1266
+ }
1267
+ };
1268
+ function createPythonRuntimeClient(workerClient) {
1269
+ return new PythonRuntimeClient(workerClient);
1270
+ }
1271
+
1272
+ // packages/harness-browser/src/runtime-assets.ts
1273
+ var DEFAULT_ASSET_BASE_URL = "/workers";
1274
+ var DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS = Object.freeze({
1275
+ pythonWorker: "pyodide-worker.js",
1276
+ pythonRuntimeCore: "pyodide/runtime-core.js",
1277
+ pythonSnippets: "generated-python-harness-snippets.js",
1278
+ javascriptWorker: "javascript-worker.js",
1279
+ typescriptCompiler: "vendor/typescript.js"
1280
+ });
1281
+ function isExplicitAssetPath(pathname) {
1282
+ return pathname.startsWith("/") || pathname.startsWith("./") || pathname.startsWith("../") || pathname.startsWith("http://") || pathname.startsWith("https://") || pathname.startsWith("data:") || pathname.startsWith("blob:");
1283
+ }
1284
+ function stripTrailingSlash(value) {
1285
+ return value.replace(/\/+$/, "");
1286
+ }
1287
+ function trimLeadingSlash(value) {
1288
+ return value.replace(/^\/+/, "");
1289
+ }
1290
+ function resolveAssetPath(baseUrl, pathname) {
1291
+ if (isExplicitAssetPath(pathname)) {
1292
+ return pathname;
1293
+ }
1294
+ const normalizedBase = stripTrailingSlash(baseUrl || DEFAULT_ASSET_BASE_URL);
1295
+ const normalizedPath = trimLeadingSlash(pathname);
1296
+ return `${normalizedBase}/${normalizedPath}`;
1297
+ }
1298
+ function resolveBrowserHarnessAssets(options = {}) {
1299
+ const assetBaseUrl = options.assetBaseUrl ?? DEFAULT_ASSET_BASE_URL;
1300
+ const assets = options.assets ?? {};
1301
+ return {
1302
+ pythonWorker: resolveAssetPath(assetBaseUrl, assets.pythonWorker ?? DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS.pythonWorker),
1303
+ pythonRuntimeCore: resolveAssetPath(
1304
+ assetBaseUrl,
1305
+ assets.pythonRuntimeCore ?? DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS.pythonRuntimeCore
1306
+ ),
1307
+ pythonSnippets: resolveAssetPath(assetBaseUrl, assets.pythonSnippets ?? DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS.pythonSnippets),
1308
+ javascriptWorker: resolveAssetPath(
1309
+ assetBaseUrl,
1310
+ assets.javascriptWorker ?? DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS.javascriptWorker
1311
+ ),
1312
+ typescriptCompiler: resolveAssetPath(
1313
+ assetBaseUrl,
1314
+ assets.typescriptCompiler ?? DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS.typescriptCompiler
1315
+ )
1316
+ };
1317
+ }
1318
+
1319
+ // packages/harness-browser/src/browser-harness.ts
1320
+ var BrowserHarnessRuntime = class {
1321
+ assets;
1322
+ supportedLanguages = SUPPORTED_LANGUAGES;
1323
+ pythonWorkerClient;
1324
+ javaScriptWorkerClient;
1325
+ clients;
1326
+ constructor(options = {}) {
1327
+ this.assets = resolveBrowserHarnessAssets(options);
1328
+ this.pythonWorkerClient = new PyodideWorkerClient({
1329
+ workerUrl: this.assets.pythonWorker,
1330
+ debug: options.debug
1331
+ });
1332
+ this.javaScriptWorkerClient = new JavaScriptWorkerClient({
1333
+ workerUrl: this.assets.javascriptWorker,
1334
+ debug: options.debug
1335
+ });
1336
+ this.clients = {
1337
+ python: createPythonRuntimeClient(this.pythonWorkerClient),
1338
+ javascript: createJavaScriptRuntimeClient("javascript", this.javaScriptWorkerClient),
1339
+ typescript: createJavaScriptRuntimeClient("typescript", this.javaScriptWorkerClient)
1340
+ };
1341
+ }
1342
+ getClient(language) {
1343
+ const client = this.clients[language];
1344
+ if (!client) {
1345
+ throw new Error(`Runtime for language "${language}" is not implemented yet.`);
1346
+ }
1347
+ return client;
1348
+ }
1349
+ getProfile(language) {
1350
+ return getLanguageRuntimeProfile(language);
1351
+ }
1352
+ getSupportedLanguageProfiles() {
1353
+ return getSupportedLanguageProfiles();
1354
+ }
1355
+ isLanguageSupported(language) {
1356
+ return isLanguageSupported(language);
1357
+ }
1358
+ disposeLanguage(language) {
1359
+ if (language === "python") {
1360
+ this.pythonWorkerClient.terminate();
1361
+ return;
1362
+ }
1363
+ this.javaScriptWorkerClient.terminate();
1364
+ }
1365
+ dispose() {
1366
+ this.pythonWorkerClient.terminate();
1367
+ this.javaScriptWorkerClient.terminate();
1368
+ }
1369
+ };
1370
+ function createBrowserHarness(options = {}) {
1371
+ return new BrowserHarnessRuntime(options);
1372
+ }
1373
+
1374
+ // packages/harness-python/src/generated/python-harness-snippets.ts
1375
+ function toPythonLiteral(value) {
1376
+ if (value === null || value === void 0) {
1377
+ return "None";
1378
+ }
1379
+ if (typeof value === "boolean") {
1380
+ return value ? "True" : "False";
1381
+ }
1382
+ if (typeof value === "number") {
1383
+ return String(value);
1384
+ }
1385
+ if (typeof value === "string") {
1386
+ return JSON.stringify(value);
1387
+ }
1388
+ if (Array.isArray(value)) {
1389
+ return "[" + value.map(toPythonLiteral).join(", ") + "]";
1390
+ }
1391
+ if (typeof value === "object") {
1392
+ const entries = Object.entries(value).map(([k, v]) => `${JSON.stringify(k)}: ${toPythonLiteral(v)}`).join(", ");
1393
+ return "{" + entries + "}";
1394
+ }
1395
+ return JSON.stringify(value);
1396
+ }
1397
+ var PYTHON_CLASS_DEFINITIONS = `
1398
+ class TreeNode:
1399
+ def __init__(self, val=0, left=None, right=None):
1400
+ self.val = val
1401
+ self.value = val
1402
+ self.left = left
1403
+ self.right = right
1404
+ def __getitem__(self, key):
1405
+ if key == 'val': return getattr(self, 'val', getattr(self, 'value', None))
1406
+ if key == 'value': return getattr(self, 'value', getattr(self, 'val', None))
1407
+ if key == 'left': return self.left
1408
+ if key == 'right': return self.right
1409
+ raise KeyError(key)
1410
+ def get(self, key, default=None):
1411
+ if key == 'val': return getattr(self, 'val', getattr(self, 'value', default))
1412
+ if key == 'value': return getattr(self, 'value', getattr(self, 'val', default))
1413
+ if key == 'left': return self.left
1414
+ if key == 'right': return self.right
1415
+ return default
1416
+ def __repr__(self):
1417
+ return f"TreeNode({getattr(self, 'val', getattr(self, 'value', None))})"
1418
+
1419
+ class ListNode:
1420
+ def __init__(self, val=0, next=None):
1421
+ self.val = val
1422
+ self.value = val
1423
+ self.next = next
1424
+ def __getitem__(self, key):
1425
+ if key == 'val': return getattr(self, 'val', getattr(self, 'value', None))
1426
+ if key == 'value': return getattr(self, 'value', getattr(self, 'val', None))
1427
+ if key == 'next': return self.next
1428
+ raise KeyError(key)
1429
+ def get(self, key, default=None):
1430
+ if key == 'val': return getattr(self, 'val', getattr(self, 'value', default))
1431
+ if key == 'value': return getattr(self, 'value', getattr(self, 'val', default))
1432
+ if key == 'next': return self.next
1433
+ return default
1434
+ def __repr__(self):
1435
+ return f"ListNode({getattr(self, 'val', getattr(self, 'value', None))})"
1436
+ `;
1437
+ var PYTHON_CONVERSION_HELPERS = "\ndef _ensure_node_value_aliases(node):\n if node is None:\n return node\n try:\n has_val = hasattr(node, 'val')\n has_value = hasattr(node, 'value')\n if has_value and not has_val:\n try:\n setattr(node, 'val', getattr(node, 'value'))\n except Exception:\n pass\n elif has_val and not has_value:\n try:\n setattr(node, 'value', getattr(node, 'val'))\n except Exception:\n pass\n except Exception:\n pass\n return node\n\ndef _dict_to_tree(d):\n if d is None:\n return None\n if not isinstance(d, dict):\n return d\n if 'val' not in d and 'value' not in d:\n return d\n node = TreeNode(d.get('val', d.get('value', 0)))\n _ensure_node_value_aliases(node)\n node.left = _dict_to_tree(d.get('left'))\n node.right = _dict_to_tree(d.get('right'))\n return node\n\ndef _dict_to_list(d, _refs=None):\n if _refs is None:\n _refs = {}\n if d is None:\n return None\n if not isinstance(d, dict):\n return d\n if '__ref__' in d:\n return _refs.get(d.get('__ref__'))\n if 'val' not in d and 'value' not in d:\n return d\n node = ListNode(d.get('val', d.get('value', 0)))\n _ensure_node_value_aliases(node)\n node_id = d.get('__id__')\n if isinstance(node_id, str) and node_id:\n _refs[node_id] = node\n node.next = _dict_to_list(d.get('next'), _refs)\n return node\n";
1438
+ var PYTHON_TRACE_SERIALIZE_FUNCTION = `
1439
+ # Sentinel to mark skipped values (functions, etc.) - distinct from None
1440
+ _SKIP_SENTINEL = "__TRACECODE_SKIP__"
1441
+ _MAX_SERIALIZE_DEPTH = 48
1442
+
1443
+ def _serialize(obj, depth=0, node_refs=None):
1444
+ if node_refs is None:
1445
+ node_refs = {}
1446
+ if isinstance(obj, (bool, int, str, type(None))):
1447
+ return obj
1448
+ elif isinstance(obj, float):
1449
+ if not math.isfinite(obj):
1450
+ if math.isnan(obj):
1451
+ return "NaN"
1452
+ return "Infinity" if obj > 0 else "-Infinity"
1453
+ return obj
1454
+ if depth > _MAX_SERIALIZE_DEPTH:
1455
+ return "<max depth>"
1456
+ elif isinstance(obj, (list, tuple)):
1457
+ return [_serialize(x, depth + 1, node_refs) for x in obj]
1458
+ elif getattr(obj, '__class__', None) and getattr(obj.__class__, '__name__', '') == 'deque':
1459
+ return [_serialize(x, depth + 1, node_refs) for x in obj]
1460
+ elif isinstance(obj, dict):
1461
+ return {str(k): _serialize(v, depth + 1, node_refs) for k, v in obj.items()}
1462
+ elif isinstance(obj, set):
1463
+ # Use try/except for sorting to handle heterogeneous sets
1464
+ try:
1465
+ sorted_vals = sorted([_serialize(x, depth + 1, node_refs) for x in obj])
1466
+ except TypeError:
1467
+ sorted_vals = [_serialize(x, depth + 1, node_refs) for x in obj]
1468
+ return {"__type__": "set", "values": sorted_vals}
1469
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and (hasattr(obj, 'left') or hasattr(obj, 'right')):
1470
+ obj_ref = id(obj)
1471
+ if obj_ref in node_refs:
1472
+ return {"__ref__": node_refs[obj_ref]}
1473
+ node_id = f"tree-{obj_ref}"
1474
+ node_refs[obj_ref] = node_id
1475
+ result = {
1476
+ "__type__": "TreeNode",
1477
+ "__id__": node_id,
1478
+ "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1, node_refs),
1479
+ }
1480
+ if hasattr(obj, 'left'):
1481
+ result["left"] = _serialize(obj.left, depth + 1, node_refs)
1482
+ if hasattr(obj, 'right'):
1483
+ result["right"] = _serialize(obj.right, depth + 1, node_refs)
1484
+ return result
1485
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and hasattr(obj, 'next'):
1486
+ obj_ref = id(obj)
1487
+ if obj_ref in node_refs:
1488
+ return {"__ref__": node_refs[obj_ref]}
1489
+ node_id = f"list-{obj_ref}"
1490
+ node_refs[obj_ref] = node_id
1491
+ result = {
1492
+ "__type__": "ListNode",
1493
+ "__id__": node_id,
1494
+ "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1, node_refs),
1495
+ }
1496
+ result["next"] = _serialize(obj.next, depth + 1, node_refs)
1497
+ return result
1498
+ elif callable(obj):
1499
+ # Skip functions entirely - return sentinel
1500
+ return _SKIP_SENTINEL
1501
+ else:
1502
+ repr_str = repr(obj)
1503
+ # Filter out function-like representations (e.g., <function foo at 0x...>)
1504
+ if repr_str.startswith('<') and repr_str.endswith('>'):
1505
+ return _SKIP_SENTINEL
1506
+ return repr_str
1507
+ `;
1508
+ var PYTHON_EXECUTE_SERIALIZE_FUNCTION = `
1509
+ _MAX_SERIALIZE_DEPTH = 48
1510
+
1511
+ def _serialize(obj, depth=0):
1512
+ if isinstance(obj, (bool, int, str, type(None))):
1513
+ return obj
1514
+ elif isinstance(obj, float):
1515
+ if not math.isfinite(obj):
1516
+ if math.isnan(obj):
1517
+ return "NaN"
1518
+ return "Infinity" if obj > 0 else "-Infinity"
1519
+ return obj
1520
+ if depth > _MAX_SERIALIZE_DEPTH:
1521
+ return "<max depth>"
1522
+ elif isinstance(obj, (list, tuple)):
1523
+ return [_serialize(x, depth + 1) for x in obj]
1524
+ elif getattr(obj, '__class__', None) and getattr(obj.__class__, '__name__', '') == 'deque':
1525
+ return [_serialize(x, depth + 1) for x in obj]
1526
+ elif isinstance(obj, dict):
1527
+ return {str(k): _serialize(v, depth + 1) for k, v in obj.items()}
1528
+ elif isinstance(obj, set):
1529
+ try:
1530
+ return {"__type__": "set", "values": sorted([_serialize(x, depth + 1) for x in obj])}
1531
+ except TypeError:
1532
+ return {"__type__": "set", "values": [_serialize(x, depth + 1) for x in obj]}
1533
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and (hasattr(obj, 'left') or hasattr(obj, 'right')):
1534
+ result = {"__type__": "TreeNode", "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1)}
1535
+ if hasattr(obj, 'left'):
1536
+ result["left"] = _serialize(obj.left, depth + 1)
1537
+ if hasattr(obj, 'right'):
1538
+ result["right"] = _serialize(obj.right, depth + 1)
1539
+ return result
1540
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and hasattr(obj, 'next'):
1541
+ result = {"__type__": "ListNode", "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1)}
1542
+ result["next"] = _serialize(obj.next, depth + 1)
1543
+ return result
1544
+ elif callable(obj):
1545
+ return None
1546
+ else:
1547
+ repr_str = repr(obj)
1548
+ if repr_str.startswith('<') and repr_str.endswith('>'):
1549
+ return None
1550
+ return repr_str
1551
+ `;
1552
+ var PYTHON_PRACTICE_MATERIALIZE_SERIALIZE_FUNCTION = `
1553
+ def _serialize(obj, depth=0, state=None):
1554
+ if state is None:
1555
+ state = {"nodes": 0, "seen": set()}
1556
+ if depth > 64:
1557
+ return "__MAX_DEPTH__"
1558
+ if isinstance(obj, (int, float, str, bool, type(None))):
1559
+ return obj
1560
+
1561
+ state["nodes"] += 1
1562
+ if state["nodes"] > 600:
1563
+ return "__MAX_NODES__"
1564
+
1565
+ if isinstance(obj, (list, tuple)):
1566
+ return [_serialize(x, depth + 1, state) for x in obj]
1567
+ elif isinstance(obj, dict):
1568
+ return {str(k): _serialize(v, depth + 1, state) for k, v in obj.items()}
1569
+ elif isinstance(obj, set):
1570
+ serialized = [_serialize(x, depth + 1, state) for x in obj]
1571
+ try:
1572
+ serialized = sorted(serialized)
1573
+ except TypeError:
1574
+ pass
1575
+ return {"__type__": "set", "values": serialized}
1576
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and (hasattr(obj, 'left') or hasattr(obj, 'right')):
1577
+ obj_id = id(obj)
1578
+ if obj_id in state["seen"]:
1579
+ return "__CYCLE__"
1580
+ state["seen"].add(obj_id)
1581
+ result = {"__type__": "TreeNode", "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1, state)}
1582
+ if hasattr(obj, 'left'):
1583
+ result["left"] = _serialize(obj.left, depth + 1, state)
1584
+ if hasattr(obj, 'right'):
1585
+ result["right"] = _serialize(obj.right, depth + 1, state)
1586
+ state["seen"].remove(obj_id)
1587
+ return result
1588
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and hasattr(obj, 'next'):
1589
+ obj_id = id(obj)
1590
+ if obj_id in state["seen"]:
1591
+ return "__CYCLE__"
1592
+ state["seen"].add(obj_id)
1593
+ result = {"__type__": "ListNode", "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1, state)}
1594
+ result["next"] = _serialize(obj.next, depth + 1, state)
1595
+ state["seen"].remove(obj_id)
1596
+ return result
1597
+ else:
1598
+ return repr(obj)
1599
+ `;
1600
+ var PYTHON_INTERVIEW_MATERIALIZE_SERIALIZE_FUNCTION = `
1601
+ def _serialize(obj, depth=0):
1602
+ if depth > 10:
1603
+ return "<max depth>"
1604
+ if isinstance(obj, (int, float, str, bool, type(None))):
1605
+ return obj
1606
+ elif isinstance(obj, (list, tuple)):
1607
+ return [_serialize(x, depth + 1) for x in obj]
1608
+ elif isinstance(obj, dict):
1609
+ return {str(k): _serialize(v, depth + 1) for k, v in obj.items()}
1610
+ elif isinstance(obj, set):
1611
+ try:
1612
+ return {"__type__": "set", "values": sorted([_serialize(x, depth + 1) for x in obj])}
1613
+ except TypeError:
1614
+ return {"__type__": "set", "values": [_serialize(x, depth + 1) for x in obj]}
1615
+ elif hasattr(obj, 'val') and (hasattr(obj, 'left') or hasattr(obj, 'right')):
1616
+ result = {"__type__": "TreeNode", "val": _serialize(getattr(obj, 'val', None), depth + 1)}
1617
+ if hasattr(obj, 'left'):
1618
+ result["left"] = _serialize(obj.left, depth + 1)
1619
+ if hasattr(obj, 'right'):
1620
+ result["right"] = _serialize(obj.right, depth + 1)
1621
+ return result
1622
+ elif hasattr(obj, 'val') and hasattr(obj, 'next'):
1623
+ result = {"__type__": "ListNode", "val": _serialize(getattr(obj, 'val', None), depth + 1)}
1624
+ result["next"] = _serialize(obj.next, depth + 1)
1625
+ return result
1626
+ else:
1627
+ return repr(obj)
1628
+ `;
1629
+ var PYTHON_SERIALIZE_FUNCTION = `
1630
+ _MAX_SERIALIZE_DEPTH = 48
1631
+
1632
+ def _serialize(obj, depth=0):
1633
+ if isinstance(obj, (bool, int, str, type(None))):
1634
+ return obj
1635
+ elif isinstance(obj, float):
1636
+ if not math.isfinite(obj):
1637
+ if math.isnan(obj):
1638
+ return "NaN"
1639
+ return "Infinity" if obj > 0 else "-Infinity"
1640
+ return obj
1641
+ if depth > _MAX_SERIALIZE_DEPTH:
1642
+ return "<max depth>"
1643
+ elif isinstance(obj, (list, tuple)):
1644
+ return [_serialize(x, depth + 1) for x in obj]
1645
+ elif getattr(obj, '__class__', None) and getattr(obj.__class__, '__name__', '') == 'deque':
1646
+ return [_serialize(x, depth + 1) for x in obj]
1647
+ elif isinstance(obj, dict):
1648
+ return {str(k): _serialize(v, depth + 1) for k, v in obj.items()}
1649
+ elif isinstance(obj, set):
1650
+ try:
1651
+ return {"__type__": "set", "values": sorted([_serialize(x, depth + 1) for x in obj])}
1652
+ except TypeError:
1653
+ return {"__type__": "set", "values": [_serialize(x, depth + 1) for x in obj]}
1654
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and (hasattr(obj, 'left') or hasattr(obj, 'right')):
1655
+ result = {"__type__": "TreeNode", "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1)}
1656
+ if hasattr(obj, 'left'):
1657
+ result["left"] = _serialize(obj.left, depth + 1)
1658
+ if hasattr(obj, 'right'):
1659
+ result["right"] = _serialize(obj.right, depth + 1)
1660
+ return result
1661
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and hasattr(obj, 'next'):
1662
+ result = {"__type__": "ListNode", "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1)}
1663
+ result["next"] = _serialize(obj.next, depth + 1)
1664
+ return result
1665
+ elif callable(obj):
1666
+ return None
1667
+ else:
1668
+ repr_str = repr(obj)
1669
+ if repr_str.startswith('<') and repr_str.endswith('>'):
1670
+ return None
1671
+ return repr_str
1672
+ `;
1673
+
1674
+ // packages/harness-python/src/python-harness.ts
1675
+ function identifyConversions(inputs) {
1676
+ const treeKeys = [];
1677
+ const listKeys = [];
1678
+ for (const [key, value] of Object.entries(inputs)) {
1679
+ if (value && typeof value === "object" && !Array.isArray(value) && ("val" in value || "value" in value)) {
1680
+ const obj = value;
1681
+ const hasLeft = "left" in obj;
1682
+ const hasRight = "right" in obj;
1683
+ const hasNext = "next" in obj;
1684
+ if (hasLeft || hasRight) {
1685
+ treeKeys.push(key);
1686
+ } else if (hasNext) {
1687
+ listKeys.push(key);
1688
+ } else {
1689
+ treeKeys.push(key);
1690
+ }
1691
+ }
1692
+ }
1693
+ return { treeKeys, listKeys };
1694
+ }
1695
+ function generateConversionCode(inputs) {
1696
+ const { treeKeys, listKeys } = identifyConversions(inputs);
1697
+ const lines = [];
1698
+ for (const key of treeKeys) {
1699
+ lines.push(`${key} = _dict_to_tree(${key})`);
1700
+ }
1701
+ for (const key of listKeys) {
1702
+ lines.push(`${key} = _dict_to_list(${key})`);
1703
+ }
1704
+ return lines.join("\n");
1705
+ }
1706
+ function generateInputSetup(inputs) {
1707
+ return Object.entries(inputs).map(([key, value]) => `${key} = ${toPythonLiteral(value)}`).join("\n");
1708
+ }
1709
+ function generateSolutionScript(solutionCode, functionName, inputs) {
1710
+ const inputSetup = generateInputSetup(inputs);
1711
+ const conversionCode = generateConversionCode(inputs);
1712
+ const paramList = Object.keys(inputs).map((key) => `${key}=${key}`).join(", ");
1713
+ return `
1714
+ import json
1715
+ import sys
1716
+
1717
+ ${PYTHON_CLASS_DEFINITIONS}
1718
+
1719
+ ${PYTHON_CONVERSION_HELPERS}
1720
+
1721
+ ${PYTHON_SERIALIZE_FUNCTION}
1722
+
1723
+ # Solution code
1724
+ ${solutionCode}
1725
+
1726
+ # Set up inputs
1727
+ ${inputSetup}
1728
+
1729
+ # Convert tree/list inputs
1730
+ ${conversionCode}
1731
+
1732
+ # Run the function
1733
+ try:
1734
+ _result = ${functionName}(${paramList})
1735
+ print(json.dumps({"success": True, "output": _serialize(_result)}))
1736
+ except Exception as e:
1737
+ print(json.dumps({"success": False, "error": f"{type(e).__name__}: {str(e)}"}))
1738
+ `;
1739
+ }
1740
+
1741
+ // packages/harness-python/src/python-harness-template.ts
1742
+ function templateToPythonLiteral(value) {
1743
+ if (value === null || value === void 0) {
1744
+ return "None";
1745
+ }
1746
+ if (typeof value === "boolean") {
1747
+ return value ? "True" : "False";
1748
+ }
1749
+ if (typeof value === "number") {
1750
+ return String(value);
1751
+ }
1752
+ if (typeof value === "string") {
1753
+ return JSON.stringify(value);
1754
+ }
1755
+ if (Array.isArray(value)) {
1756
+ return "[" + value.map(templateToPythonLiteral).join(", ") + "]";
1757
+ }
1758
+ if (typeof value === "object") {
1759
+ const entries = Object.entries(value).map(([k, v]) => `${JSON.stringify(k)}: ${templateToPythonLiteral(v)}`).join(", ");
1760
+ return "{" + entries + "}";
1761
+ }
1762
+ return JSON.stringify(value);
1763
+ }
1764
+ var TEMPLATE_PYTHON_CLASS_DEFINITIONS = `
1765
+ class TreeNode:
1766
+ def __init__(self, val=0, left=None, right=None):
1767
+ self.val = val
1768
+ self.value = val
1769
+ self.left = left
1770
+ self.right = right
1771
+ def __getitem__(self, key):
1772
+ if key == 'val': return getattr(self, 'val', getattr(self, 'value', None))
1773
+ if key == 'value': return getattr(self, 'value', getattr(self, 'val', None))
1774
+ if key == 'left': return self.left
1775
+ if key == 'right': return self.right
1776
+ raise KeyError(key)
1777
+ def get(self, key, default=None):
1778
+ if key == 'val': return getattr(self, 'val', getattr(self, 'value', default))
1779
+ if key == 'value': return getattr(self, 'value', getattr(self, 'val', default))
1780
+ if key == 'left': return self.left
1781
+ if key == 'right': return self.right
1782
+ return default
1783
+ def __repr__(self):
1784
+ return f"TreeNode({getattr(self, 'val', getattr(self, 'value', None))})"
1785
+
1786
+ class ListNode:
1787
+ def __init__(self, val=0, next=None):
1788
+ self.val = val
1789
+ self.value = val
1790
+ self.next = next
1791
+ def __getitem__(self, key):
1792
+ if key == 'val': return getattr(self, 'val', getattr(self, 'value', None))
1793
+ if key == 'value': return getattr(self, 'value', getattr(self, 'val', None))
1794
+ if key == 'next': return self.next
1795
+ raise KeyError(key)
1796
+ def get(self, key, default=None):
1797
+ if key == 'val': return getattr(self, 'val', getattr(self, 'value', default))
1798
+ if key == 'value': return getattr(self, 'value', getattr(self, 'val', default))
1799
+ if key == 'next': return self.next
1800
+ return default
1801
+ def __repr__(self):
1802
+ return f"ListNode({getattr(self, 'val', getattr(self, 'value', None))})"
1803
+ `;
1804
+ var TEMPLATE_PYTHON_CONVERSION_HELPERS = `
1805
+ def _ensure_node_value_aliases(node):
1806
+ if node is None:
1807
+ return node
1808
+ try:
1809
+ has_val = hasattr(node, 'val')
1810
+ has_value = hasattr(node, 'value')
1811
+ if has_value and not has_val:
1812
+ try:
1813
+ setattr(node, 'val', getattr(node, 'value'))
1814
+ except Exception:
1815
+ pass
1816
+ elif has_val and not has_value:
1817
+ try:
1818
+ setattr(node, 'value', getattr(node, 'val'))
1819
+ except Exception:
1820
+ pass
1821
+ except Exception:
1822
+ pass
1823
+ return node
1824
+
1825
+ def _dict_to_tree(d):
1826
+ if d is None:
1827
+ return None
1828
+ if not isinstance(d, dict):
1829
+ return d
1830
+ if 'val' not in d and 'value' not in d:
1831
+ return d
1832
+ node = TreeNode(d.get('val', d.get('value', 0)))
1833
+ _ensure_node_value_aliases(node)
1834
+ node.left = _dict_to_tree(d.get('left'))
1835
+ node.right = _dict_to_tree(d.get('right'))
1836
+ return node
1837
+
1838
+ def _dict_to_list(d, _refs=None):
1839
+ if _refs is None:
1840
+ _refs = {}
1841
+ if d is None:
1842
+ return None
1843
+ if not isinstance(d, dict):
1844
+ return d
1845
+ if '__ref__' in d:
1846
+ return _refs.get(d.get('__ref__'))
1847
+ if 'val' not in d and 'value' not in d:
1848
+ return d
1849
+ node = ListNode(d.get('val', d.get('value', 0)))
1850
+ _ensure_node_value_aliases(node)
1851
+ node_id = d.get('__id__')
1852
+ if isinstance(node_id, str) and node_id:
1853
+ _refs[node_id] = node
1854
+ node.next = _dict_to_list(d.get('next'), _refs)
1855
+ return node
1856
+ `;
1857
+ var TEMPLATE_PYTHON_TRACE_SERIALIZE_FUNCTION = `
1858
+ # Sentinel to mark skipped values (functions, etc.) - distinct from None
1859
+ _SKIP_SENTINEL = "__TRACECODE_SKIP__"
1860
+ _MAX_SERIALIZE_DEPTH = 48
1861
+
1862
+ def _serialize(obj, depth=0, node_refs=None):
1863
+ if node_refs is None:
1864
+ node_refs = {}
1865
+ if isinstance(obj, (bool, int, str, type(None))):
1866
+ return obj
1867
+ elif isinstance(obj, float):
1868
+ if not math.isfinite(obj):
1869
+ if math.isnan(obj):
1870
+ return "NaN"
1871
+ return "Infinity" if obj > 0 else "-Infinity"
1872
+ return obj
1873
+ if depth > _MAX_SERIALIZE_DEPTH:
1874
+ return "<max depth>"
1875
+ elif isinstance(obj, (list, tuple)):
1876
+ return [_serialize(x, depth + 1, node_refs) for x in obj]
1877
+ elif getattr(obj, '__class__', None) and getattr(obj.__class__, '__name__', '') == 'deque':
1878
+ return [_serialize(x, depth + 1, node_refs) for x in obj]
1879
+ elif isinstance(obj, dict):
1880
+ return {str(k): _serialize(v, depth + 1, node_refs) for k, v in obj.items()}
1881
+ elif isinstance(obj, set):
1882
+ # Use try/except for sorting to handle heterogeneous sets
1883
+ try:
1884
+ sorted_vals = sorted([_serialize(x, depth + 1, node_refs) for x in obj])
1885
+ except TypeError:
1886
+ sorted_vals = [_serialize(x, depth + 1, node_refs) for x in obj]
1887
+ return {"__type__": "set", "values": sorted_vals}
1888
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and (hasattr(obj, 'left') or hasattr(obj, 'right')):
1889
+ obj_ref = id(obj)
1890
+ if obj_ref in node_refs:
1891
+ return {"__ref__": node_refs[obj_ref]}
1892
+ node_id = f"tree-{obj_ref}"
1893
+ node_refs[obj_ref] = node_id
1894
+ result = {
1895
+ "__type__": "TreeNode",
1896
+ "__id__": node_id,
1897
+ "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1, node_refs),
1898
+ }
1899
+ if hasattr(obj, 'left'):
1900
+ result["left"] = _serialize(obj.left, depth + 1, node_refs)
1901
+ if hasattr(obj, 'right'):
1902
+ result["right"] = _serialize(obj.right, depth + 1, node_refs)
1903
+ return result
1904
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and hasattr(obj, 'next'):
1905
+ obj_ref = id(obj)
1906
+ if obj_ref in node_refs:
1907
+ return {"__ref__": node_refs[obj_ref]}
1908
+ node_id = f"list-{obj_ref}"
1909
+ node_refs[obj_ref] = node_id
1910
+ result = {
1911
+ "__type__": "ListNode",
1912
+ "__id__": node_id,
1913
+ "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1, node_refs),
1914
+ }
1915
+ result["next"] = _serialize(obj.next, depth + 1, node_refs)
1916
+ return result
1917
+ elif callable(obj):
1918
+ # Skip functions entirely - return sentinel
1919
+ return _SKIP_SENTINEL
1920
+ else:
1921
+ repr_str = repr(obj)
1922
+ # Filter out function-like representations (e.g., <function foo at 0x...>)
1923
+ if repr_str.startswith('<') and repr_str.endswith('>'):
1924
+ return _SKIP_SENTINEL
1925
+ return repr_str
1926
+ `;
1927
+ var TEMPLATE_PYTHON_EXECUTE_SERIALIZE_FUNCTION = `
1928
+ _MAX_SERIALIZE_DEPTH = 48
1929
+
1930
+ def _serialize(obj, depth=0):
1931
+ if isinstance(obj, (bool, int, str, type(None))):
1932
+ return obj
1933
+ elif isinstance(obj, float):
1934
+ if not math.isfinite(obj):
1935
+ if math.isnan(obj):
1936
+ return "NaN"
1937
+ return "Infinity" if obj > 0 else "-Infinity"
1938
+ return obj
1939
+ if depth > _MAX_SERIALIZE_DEPTH:
1940
+ return "<max depth>"
1941
+ elif isinstance(obj, (list, tuple)):
1942
+ return [_serialize(x, depth + 1) for x in obj]
1943
+ elif getattr(obj, '__class__', None) and getattr(obj.__class__, '__name__', '') == 'deque':
1944
+ return [_serialize(x, depth + 1) for x in obj]
1945
+ elif isinstance(obj, dict):
1946
+ return {str(k): _serialize(v, depth + 1) for k, v in obj.items()}
1947
+ elif isinstance(obj, set):
1948
+ try:
1949
+ return {"__type__": "set", "values": sorted([_serialize(x, depth + 1) for x in obj])}
1950
+ except TypeError:
1951
+ return {"__type__": "set", "values": [_serialize(x, depth + 1) for x in obj]}
1952
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and (hasattr(obj, 'left') or hasattr(obj, 'right')):
1953
+ result = {"__type__": "TreeNode", "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1)}
1954
+ if hasattr(obj, 'left'):
1955
+ result["left"] = _serialize(obj.left, depth + 1)
1956
+ if hasattr(obj, 'right'):
1957
+ result["right"] = _serialize(obj.right, depth + 1)
1958
+ return result
1959
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and hasattr(obj, 'next'):
1960
+ result = {"__type__": "ListNode", "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1)}
1961
+ result["next"] = _serialize(obj.next, depth + 1)
1962
+ return result
1963
+ elif callable(obj):
1964
+ return None
1965
+ else:
1966
+ repr_str = repr(obj)
1967
+ if repr_str.startswith('<') and repr_str.endswith('>'):
1968
+ return None
1969
+ return repr_str
1970
+ `;
1971
+ var TEMPLATE_PYTHON_PRACTICE_MATERIALIZE_SERIALIZE_FUNCTION = `
1972
+ def _serialize(obj, depth=0, state=None):
1973
+ if state is None:
1974
+ state = {"nodes": 0, "seen": set()}
1975
+ if depth > 64:
1976
+ return "__MAX_DEPTH__"
1977
+ if isinstance(obj, (int, float, str, bool, type(None))):
1978
+ return obj
1979
+
1980
+ state["nodes"] += 1
1981
+ if state["nodes"] > 600:
1982
+ return "__MAX_NODES__"
1983
+
1984
+ if isinstance(obj, (list, tuple)):
1985
+ return [_serialize(x, depth + 1, state) for x in obj]
1986
+ elif isinstance(obj, dict):
1987
+ return {str(k): _serialize(v, depth + 1, state) for k, v in obj.items()}
1988
+ elif isinstance(obj, set):
1989
+ serialized = [_serialize(x, depth + 1, state) for x in obj]
1990
+ try:
1991
+ serialized = sorted(serialized)
1992
+ except TypeError:
1993
+ pass
1994
+ return {"__type__": "set", "values": serialized}
1995
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and (hasattr(obj, 'left') or hasattr(obj, 'right')):
1996
+ obj_id = id(obj)
1997
+ if obj_id in state["seen"]:
1998
+ return "__CYCLE__"
1999
+ state["seen"].add(obj_id)
2000
+ result = {"__type__": "TreeNode", "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1, state)}
2001
+ if hasattr(obj, 'left'):
2002
+ result["left"] = _serialize(obj.left, depth + 1, state)
2003
+ if hasattr(obj, 'right'):
2004
+ result["right"] = _serialize(obj.right, depth + 1, state)
2005
+ state["seen"].remove(obj_id)
2006
+ return result
2007
+ elif (hasattr(obj, 'val') or hasattr(obj, 'value')) and hasattr(obj, 'next'):
2008
+ obj_id = id(obj)
2009
+ if obj_id in state["seen"]:
2010
+ return "__CYCLE__"
2011
+ state["seen"].add(obj_id)
2012
+ result = {"__type__": "ListNode", "val": _serialize(getattr(obj, 'val', getattr(obj, 'value', None)), depth + 1, state)}
2013
+ result["next"] = _serialize(obj.next, depth + 1, state)
2014
+ state["seen"].remove(obj_id)
2015
+ return result
2016
+ else:
2017
+ return repr(obj)
2018
+ `;
2019
+ var TEMPLATE_PYTHON_INTERVIEW_MATERIALIZE_SERIALIZE_FUNCTION = `
2020
+ def _serialize(obj, depth=0):
2021
+ if depth > 10:
2022
+ return "<max depth>"
2023
+ if isinstance(obj, (int, float, str, bool, type(None))):
2024
+ return obj
2025
+ elif isinstance(obj, (list, tuple)):
2026
+ return [_serialize(x, depth + 1) for x in obj]
2027
+ elif isinstance(obj, dict):
2028
+ return {str(k): _serialize(v, depth + 1) for k, v in obj.items()}
2029
+ elif isinstance(obj, set):
2030
+ try:
2031
+ return {"__type__": "set", "values": sorted([_serialize(x, depth + 1) for x in obj])}
2032
+ except TypeError:
2033
+ return {"__type__": "set", "values": [_serialize(x, depth + 1) for x in obj]}
2034
+ elif hasattr(obj, 'val') and (hasattr(obj, 'left') or hasattr(obj, 'right')):
2035
+ result = {"__type__": "TreeNode", "val": _serialize(getattr(obj, 'val', None), depth + 1)}
2036
+ if hasattr(obj, 'left'):
2037
+ result["left"] = _serialize(obj.left, depth + 1)
2038
+ if hasattr(obj, 'right'):
2039
+ result["right"] = _serialize(obj.right, depth + 1)
2040
+ return result
2041
+ elif hasattr(obj, 'val') and hasattr(obj, 'next'):
2042
+ result = {"__type__": "ListNode", "val": _serialize(getattr(obj, 'val', None), depth + 1)}
2043
+ result["next"] = _serialize(obj.next, depth + 1)
2044
+ return result
2045
+ else:
2046
+ return repr(obj)
2047
+ `;
2048
+ var TEMPLATE_PYTHON_SERIALIZE_FUNCTION = TEMPLATE_PYTHON_EXECUTE_SERIALIZE_FUNCTION;
2049
+
2050
+ // packages/harness-javascript/src/typescript-runtime-declarations.ts
2051
+ var TYPESCRIPT_RUNTIME_DECLARATIONS = `
2052
+ declare class ListNode {
2053
+ val: any;
2054
+ next: ListNode | SerializedListNode | SerializedRef | null;
2055
+ prev?: ListNode | SerializedListNode | SerializedRef | null;
2056
+ constructor(val?: any, next?: ListNode | null);
2057
+ }
2058
+
2059
+ declare class TreeNode {
2060
+ val: any;
2061
+ left: TreeNode | SerializedTreeNode | SerializedRef | null;
2062
+ right: TreeNode | SerializedTreeNode | SerializedRef | null;
2063
+ constructor(val?: any, left?: TreeNode | null, right?: TreeNode | null);
2064
+ }
2065
+
2066
+ type SerializedRef = { __ref__: string };
2067
+
2068
+ type SerializedListNode = {
2069
+ __id__?: string;
2070
+ __type__?: 'ListNode';
2071
+ val?: any;
2072
+ next?: SerializedListNode | SerializedRef | ListNode | null;
2073
+ prev?: SerializedListNode | SerializedRef | ListNode | null;
2074
+ };
2075
+
2076
+ type SerializedTreeNode = {
2077
+ __id__?: string;
2078
+ __type__?: 'TreeNode';
2079
+ val?: any;
2080
+ left?: SerializedTreeNode | SerializedRef | TreeNode | null;
2081
+ right?: SerializedTreeNode | SerializedRef | TreeNode | null;
2082
+ };
2083
+ `;
2084
+ function withTypeScriptRuntimeDeclarations(sourceCode) {
2085
+ return `${sourceCode}
2086
+
2087
+ ${TYPESCRIPT_RUNTIME_DECLARATIONS}
2088
+ `;
2089
+ }
2090
+
2091
+ // packages/harness-javascript/src/javascript-executor.ts
2092
+ var typeScriptModulePromise = null;
2093
+ async function getTypeScriptModule() {
2094
+ if (!typeScriptModulePromise) {
2095
+ const specifier = "typescript";
2096
+ typeScriptModulePromise = import(
2097
+ /* webpackIgnore: true */
2098
+ specifier
2099
+ );
2100
+ }
2101
+ return typeScriptModulePromise;
2102
+ }
2103
+ function performanceNow() {
2104
+ if (typeof performance !== "undefined" && typeof performance.now === "function") {
2105
+ return performance.now();
2106
+ }
2107
+ return Date.now();
2108
+ }
2109
+ function formatConsoleArg(value) {
2110
+ if (typeof value === "string") return value;
2111
+ if (typeof value === "number" || typeof value === "boolean" || value === null || value === void 0) {
2112
+ return String(value);
2113
+ }
2114
+ try {
2115
+ return JSON.stringify(value);
2116
+ } catch {
2117
+ return String(value);
2118
+ }
2119
+ }
2120
+ function createConsoleProxy(output) {
2121
+ const capture = (...args) => {
2122
+ output.push(args.map(formatConsoleArg).join(" "));
2123
+ };
2124
+ return {
2125
+ ...console,
2126
+ log: capture,
2127
+ info: capture,
2128
+ warn: capture,
2129
+ error: capture,
2130
+ debug: capture
2131
+ };
2132
+ }
2133
+ function isLikelyTreeNodeValue(value) {
2134
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2135
+ const hasValue = "val" in value || "value" in value;
2136
+ const hasTreeLinks = "left" in value || "right" in value;
2137
+ return hasValue && hasTreeLinks;
2138
+ }
2139
+ function isLikelyListNodeValue(value) {
2140
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2141
+ const hasValue = "val" in value || "value" in value;
2142
+ const hasTreeLinks = "left" in value || "right" in value;
2143
+ const hasListLinks = "next" in value || "prev" in value;
2144
+ return hasValue && hasListLinks && !hasTreeLinks;
2145
+ }
2146
+ function serializeValue(value, depth = 0, seen = /* @__PURE__ */ new WeakSet(), nodeRefState = { ids: /* @__PURE__ */ new Map(), nextId: 1 }) {
2147
+ if (depth > 48) return "<max depth>";
2148
+ if (value === null || value === void 0) return value;
2149
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
2150
+ return value;
2151
+ }
2152
+ if (typeof value === "bigint") {
2153
+ return Number.isSafeInteger(Number(value)) ? Number(value) : String(value);
2154
+ }
2155
+ if (typeof value === "function") {
2156
+ return "<function>";
2157
+ }
2158
+ if (Array.isArray(value)) {
2159
+ return value.map((item) => serializeValue(item, depth + 1, seen));
2160
+ }
2161
+ if (value instanceof Set) {
2162
+ return {
2163
+ __type__: "set",
2164
+ values: [...value].map((item) => serializeValue(item, depth + 1, seen, nodeRefState))
2165
+ };
2166
+ }
2167
+ if (value instanceof Map) {
2168
+ return {
2169
+ __type__: "map",
2170
+ entries: [...value.entries()].map(([k, v]) => [
2171
+ serializeValue(k, depth + 1, seen, nodeRefState),
2172
+ serializeValue(v, depth + 1, seen, nodeRefState)
2173
+ ])
2174
+ };
2175
+ }
2176
+ if (typeof value === "object") {
2177
+ if (isLikelyTreeNodeValue(value) || isLikelyListNodeValue(value)) {
2178
+ const objectValue = value;
2179
+ const nodeValue = value;
2180
+ const existingId = nodeRefState.ids.get(objectValue);
2181
+ if (existingId) {
2182
+ return { __ref__: existingId };
2183
+ }
2184
+ const isTree = isLikelyTreeNodeValue(value);
2185
+ const nodePrefix = isTree ? "tree" : "list";
2186
+ const nodeId = `${nodePrefix}-${nodeRefState.nextId++}`;
2187
+ nodeRefState.ids.set(objectValue, nodeId);
2188
+ if (isTree) {
2189
+ return {
2190
+ __type__: "TreeNode",
2191
+ __id__: nodeId,
2192
+ val: serializeValue(nodeValue.val ?? nodeValue.value ?? null, depth + 1, seen, nodeRefState),
2193
+ left: serializeValue(nodeValue.left ?? null, depth + 1, seen, nodeRefState),
2194
+ right: serializeValue(nodeValue.right ?? null, depth + 1, seen, nodeRefState)
2195
+ };
2196
+ }
2197
+ return {
2198
+ __type__: "ListNode",
2199
+ __id__: nodeId,
2200
+ val: serializeValue(nodeValue.val ?? nodeValue.value ?? null, depth + 1, seen, nodeRefState),
2201
+ next: serializeValue(nodeValue.next ?? null, depth + 1, seen, nodeRefState),
2202
+ ..."prev" in nodeValue ? { prev: serializeValue(nodeValue.prev ?? null, depth + 1, seen, nodeRefState) } : {}
2203
+ };
2204
+ }
2205
+ if (seen.has(value)) return "<cycle>";
2206
+ seen.add(value);
2207
+ const out = {};
2208
+ for (const [k, v] of Object.entries(value)) {
2209
+ out[k] = serializeValue(v, depth + 1, seen, nodeRefState);
2210
+ }
2211
+ seen.delete(value);
2212
+ return out;
2213
+ }
2214
+ return String(value);
2215
+ }
2216
+ function extractUserErrorLine(error) {
2217
+ if (typeof error === "object" && error && "__tracecodeLine" in error) {
2218
+ const line2 = Number(error.__tracecodeLine);
2219
+ if (Number.isFinite(line2)) return line2;
2220
+ }
2221
+ const stack = typeof error === "object" && error && "stack" in error ? String(error.stack ?? "") : "";
2222
+ if (!stack) return void 0;
2223
+ const match = stack.match(/<anonymous>:(\d+):\d+/);
2224
+ if (!match) return void 0;
2225
+ const line = Number.parseInt(match[1], 10);
2226
+ return Number.isFinite(line) ? line : void 0;
2227
+ }
2228
+ function isPlainObjectRecord(value) {
2229
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2230
+ return Object.prototype.toString.call(value) === "[object Object]";
2231
+ }
2232
+ function collectReferenceTargets(value, byId, seen) {
2233
+ if (value === null || value === void 0) return;
2234
+ if (typeof value !== "object") return;
2235
+ if (seen.has(value)) return;
2236
+ seen.add(value);
2237
+ if (Array.isArray(value)) {
2238
+ for (const item of value) {
2239
+ collectReferenceTargets(item, byId, seen);
2240
+ }
2241
+ return;
2242
+ }
2243
+ if (!isPlainObjectRecord(value)) return;
2244
+ if (typeof value.__id__ === "string" && value.__id__.length > 0 && !byId.has(value.__id__)) {
2245
+ byId.set(value.__id__, value);
2246
+ }
2247
+ for (const nested of Object.values(value)) {
2248
+ collectReferenceTargets(nested, byId, seen);
2249
+ }
2250
+ }
2251
+ function resolveReferenceGraph(value, byId, resolved) {
2252
+ if (value === null || value === void 0) return value;
2253
+ if (typeof value !== "object") return value;
2254
+ if (resolved.has(value)) {
2255
+ return resolved.get(value);
2256
+ }
2257
+ if (Array.isArray(value)) {
2258
+ const out2 = [];
2259
+ resolved.set(value, out2);
2260
+ for (const item of value) {
2261
+ out2.push(resolveReferenceGraph(item, byId, resolved));
2262
+ }
2263
+ return out2;
2264
+ }
2265
+ if (!isPlainObjectRecord(value)) {
2266
+ return value;
2267
+ }
2268
+ const keys = Object.keys(value);
2269
+ if (keys.length === 1 && typeof value.__ref__ === "string") {
2270
+ const target = byId.get(value.__ref__);
2271
+ if (!target) return null;
2272
+ return resolveReferenceGraph(target, byId, resolved);
2273
+ }
2274
+ const out = {};
2275
+ resolved.set(value, out);
2276
+ for (const [key, nested] of Object.entries(value)) {
2277
+ out[key] = resolveReferenceGraph(nested, byId, resolved);
2278
+ }
2279
+ return out;
2280
+ }
2281
+ function normalizeInputs(inputs) {
2282
+ if (!inputs || typeof inputs !== "object" || Array.isArray(inputs)) return {};
2283
+ const byId = /* @__PURE__ */ new Map();
2284
+ collectReferenceTargets(inputs, byId, /* @__PURE__ */ new WeakSet());
2285
+ if (byId.size === 0) {
2286
+ return inputs;
2287
+ }
2288
+ const hydrated = resolveReferenceGraph(inputs, byId, /* @__PURE__ */ new WeakMap());
2289
+ if (!hydrated || typeof hydrated !== "object" || Array.isArray(hydrated)) {
2290
+ return inputs;
2291
+ }
2292
+ return hydrated;
2293
+ }
2294
+ function collectSimpleParameterNames(ts, functionLikeNode) {
2295
+ const names = [];
2296
+ for (const parameter of functionLikeNode.parameters ?? []) {
2297
+ if (!ts.isIdentifier(parameter.name)) {
2298
+ return null;
2299
+ }
2300
+ if (parameter.name.text === "this") {
2301
+ continue;
2302
+ }
2303
+ names.push(parameter.name.text);
2304
+ }
2305
+ return names;
2306
+ }
2307
+ function getPropertyNameText(ts, name) {
2308
+ if (!name) return null;
2309
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
2310
+ return name.text;
2311
+ }
2312
+ return null;
2313
+ }
2314
+ function findFunctionLikeNode(ts, sourceFile, functionName, executionStyle) {
2315
+ let found = null;
2316
+ const visit = (node) => {
2317
+ if (found) return;
2318
+ if (executionStyle === "solution-method" && ts.isClassDeclaration(node) && node.name?.text === "Solution") {
2319
+ for (const member of node.members) {
2320
+ if (found) break;
2321
+ if (ts.isMethodDeclaration(member) && getPropertyNameText(ts, member.name) === functionName) {
2322
+ found = member;
2323
+ break;
2324
+ }
2325
+ if (ts.isPropertyDeclaration(member) && getPropertyNameText(ts, member.name) === functionName && member.initializer && (ts.isArrowFunction(member.initializer) || ts.isFunctionExpression(member.initializer))) {
2326
+ found = member.initializer;
2327
+ break;
2328
+ }
2329
+ }
2330
+ return;
2331
+ }
2332
+ if (executionStyle === "function") {
2333
+ if (ts.isFunctionDeclaration(node) && node.name?.text === functionName) {
2334
+ found = node;
2335
+ return;
2336
+ }
2337
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === functionName && node.initializer && (ts.isArrowFunction(node.initializer) || ts.isFunctionExpression(node.initializer))) {
2338
+ found = node.initializer;
2339
+ return;
2340
+ }
2341
+ }
2342
+ ts.forEachChild(node, visit);
2343
+ };
2344
+ visit(sourceFile);
2345
+ return found;
2346
+ }
2347
+ async function resolveOrderedInputKeys(code, functionName, inputs, executionStyle) {
2348
+ const fallbackKeys = Object.keys(inputs);
2349
+ if (!functionName || executionStyle === "ops-class" || fallbackKeys.length <= 1) {
2350
+ return fallbackKeys;
2351
+ }
2352
+ try {
2353
+ const ts = await getTypeScriptModule();
2354
+ const sourceFile = ts.createSourceFile("runtime-input.js", code, ts.ScriptTarget.ES2020, true, ts.ScriptKind.JS);
2355
+ const target = findFunctionLikeNode(ts, sourceFile, functionName, executionStyle);
2356
+ if (!target) {
2357
+ return fallbackKeys;
2358
+ }
2359
+ const parameterNames = collectSimpleParameterNames(ts, target);
2360
+ if (!parameterNames || parameterNames.length === 0) {
2361
+ return fallbackKeys;
2362
+ }
2363
+ const matchedKeys = parameterNames.filter((name) => Object.prototype.hasOwnProperty.call(inputs, name));
2364
+ if (matchedKeys.length === 0) {
2365
+ return fallbackKeys;
2366
+ }
2367
+ const extras = fallbackKeys.filter((key) => !matchedKeys.includes(key));
2368
+ return [...matchedKeys, ...extras];
2369
+ } catch {
2370
+ return fallbackKeys;
2371
+ }
2372
+ }
2373
+ function buildRunner(code, executionStyle, argNames) {
2374
+ if (executionStyle === "function") {
2375
+ return new Function(
2376
+ "console",
2377
+ "__functionName",
2378
+ ...argNames,
2379
+ `"use strict";
2380
+ ${code}
2381
+ let __target;
2382
+ try {
2383
+ __target = eval(__functionName);
2384
+ } catch (_err) {
2385
+ __target = undefined;
2386
+ }
2387
+ if (typeof __target !== 'function') {
2388
+ throw new Error('Function "' + __functionName + '" not found');
2389
+ }
2390
+ return __target(${argNames.join(", ")});`
2391
+ );
2392
+ }
2393
+ if (executionStyle === "solution-method") {
2394
+ return new Function(
2395
+ "console",
2396
+ "__functionName",
2397
+ ...argNames,
2398
+ `"use strict";
2399
+ ${code}
2400
+ if (typeof Solution !== 'function') {
2401
+ throw new Error('Class "Solution" not found');
2402
+ }
2403
+ const __solver = new Solution();
2404
+ const __method = __solver[__functionName];
2405
+ if (typeof __method !== 'function') {
2406
+ throw new Error('Method "Solution.' + __functionName + '" not found');
2407
+ }
2408
+ return __method.call(__solver, ${argNames.join(", ")});`
2409
+ );
2410
+ }
2411
+ if (executionStyle === "ops-class") {
2412
+ return new Function(
2413
+ "console",
2414
+ "__className",
2415
+ "__operations",
2416
+ "__arguments",
2417
+ `"use strict";
2418
+ ${code}
2419
+ if (!Array.isArray(__operations) || !Array.isArray(__arguments)) {
2420
+ throw new Error('ops-class execution requires inputs.operations and inputs.arguments (or ops/args)');
2421
+ }
2422
+ if (__operations.length !== __arguments.length) {
2423
+ throw new Error('operations and arguments must have the same length');
2424
+ }
2425
+ let __targetClass;
2426
+ try {
2427
+ __targetClass = eval(__className);
2428
+ } catch (_err) {
2429
+ __targetClass = undefined;
2430
+ }
2431
+ if (typeof __targetClass !== 'function') {
2432
+ throw new Error('Class "' + __className + '" not found');
2433
+ }
2434
+ let __instance = null;
2435
+ const __out = [];
2436
+ for (let __i = 0; __i < __operations.length; __i++) {
2437
+ const __op = __operations[__i];
2438
+ let __callArgs = __arguments[__i];
2439
+ if (__callArgs === null || __callArgs === undefined) {
2440
+ __callArgs = [];
2441
+ }
2442
+ if (!Array.isArray(__callArgs)) {
2443
+ __callArgs = [__callArgs];
2444
+ }
2445
+ if (__i === 0) {
2446
+ __instance = new __targetClass(...__callArgs);
2447
+ __out.push(null);
2448
+ continue;
2449
+ }
2450
+ if (!__instance || typeof __instance[__op] !== 'function') {
2451
+ throw new Error('Required method "' + __op + '" is not implemented on ' + (__className || 'target class'));
2452
+ }
2453
+ __out.push(__instance[__op](...__callArgs));
2454
+ }
2455
+ return __out;`
2456
+ );
2457
+ }
2458
+ throw new Error(`Execution style "${executionStyle}" is not supported for JavaScript runtime yet.`);
2459
+ }
2460
+ function getOpsClassInputs(inputs) {
2461
+ const operations = Array.isArray(inputs.operations) ? inputs.operations : Array.isArray(inputs.ops) ? inputs.ops : null;
2462
+ const argumentsList = Array.isArray(inputs.arguments) ? inputs.arguments : Array.isArray(inputs.args) ? inputs.args : null;
2463
+ return { operations, argumentsList };
2464
+ }
2465
+ async function transpileTypeScript(code) {
2466
+ const ts = await getTypeScriptModule();
2467
+ const transpileInput = withTypeScriptRuntimeDeclarations(code);
2468
+ const transpiled = ts.transpileModule(transpileInput, {
2469
+ compilerOptions: {
2470
+ target: ts.ScriptTarget.ES2020,
2471
+ module: ts.ModuleKind.None,
2472
+ strict: false,
2473
+ esModuleInterop: true
2474
+ },
2475
+ reportDiagnostics: true,
2476
+ fileName: "solution.ts"
2477
+ });
2478
+ const diagnostics = Array.isArray(transpiled.diagnostics) ? transpiled.diagnostics : [];
2479
+ const errors = diagnostics.filter((diag) => diag.category === ts.DiagnosticCategory.Error);
2480
+ if (errors.length > 0) {
2481
+ const first = errors[0];
2482
+ const messageText = ts.flattenDiagnosticMessageText(first.messageText, "\n");
2483
+ let lineNumber;
2484
+ if (first.file && typeof first.start === "number") {
2485
+ const position = first.file.getLineAndCharacterOfPosition(first.start);
2486
+ lineNumber = position.line + 1;
2487
+ }
2488
+ const error = new Error(
2489
+ lineNumber ? `TypeScript transpilation failed (line ${lineNumber}): ${messageText}` : `TypeScript transpilation failed: ${messageText}`
2490
+ );
2491
+ if (lineNumber) {
2492
+ error.__tracecodeLine = lineNumber;
2493
+ }
2494
+ throw error;
2495
+ }
2496
+ return transpiled.outputText;
2497
+ }
2498
+ async function executeJavaScriptCode(code, functionName, inputs, executionStyle = "function") {
2499
+ const consoleOutput = [];
2500
+ const consoleProxy = createConsoleProxy(consoleOutput);
2501
+ const normalizedInputs = normalizeInputs(inputs);
2502
+ try {
2503
+ let output;
2504
+ if (executionStyle === "ops-class") {
2505
+ const { operations, argumentsList } = getOpsClassInputs(normalizedInputs);
2506
+ const runner = buildRunner(code, executionStyle, []);
2507
+ output = await Promise.resolve(runner(consoleProxy, functionName, operations, argumentsList));
2508
+ } else {
2509
+ const inputKeys = await resolveOrderedInputKeys(code, functionName, normalizedInputs, executionStyle);
2510
+ const argNames = inputKeys.map((_, index) => `__arg${index}`);
2511
+ const argValues = inputKeys.map((key) => normalizedInputs[key]);
2512
+ const runner = buildRunner(code, executionStyle, argNames);
2513
+ output = await Promise.resolve(runner(consoleProxy, functionName, ...argValues));
2514
+ }
2515
+ return {
2516
+ success: true,
2517
+ output: serializeValue(output),
2518
+ consoleOutput
2519
+ };
2520
+ } catch (error) {
2521
+ return {
2522
+ success: false,
2523
+ output: null,
2524
+ error: error instanceof Error ? error.message : String(error),
2525
+ errorLine: extractUserErrorLine(error),
2526
+ consoleOutput
2527
+ };
2528
+ }
2529
+ }
2530
+ async function executeJavaScriptWithTracing(code, functionName, inputs, executionStyle = "function") {
2531
+ const startedAt = performanceNow();
2532
+ const codeResult = await executeJavaScriptCode(code, functionName ?? "", inputs, executionStyle);
2533
+ const executionTimeMs = performanceNow() - startedAt;
2534
+ if (!codeResult.success) {
2535
+ return {
2536
+ success: false,
2537
+ error: codeResult.error,
2538
+ errorLine: codeResult.errorLine,
2539
+ trace: [],
2540
+ executionTimeMs,
2541
+ consoleOutput: codeResult.consoleOutput ?? [],
2542
+ lineEventCount: 0,
2543
+ traceStepCount: 0
2544
+ };
2545
+ }
2546
+ return {
2547
+ success: true,
2548
+ output: codeResult.output,
2549
+ trace: [],
2550
+ executionTimeMs,
2551
+ consoleOutput: codeResult.consoleOutput ?? [],
2552
+ lineEventCount: 0,
2553
+ traceStepCount: 0
2554
+ };
2555
+ }
2556
+ async function executeTypeScriptCode(code, functionName, inputs, executionStyle = "function") {
2557
+ const transpiledCode = await transpileTypeScript(code);
2558
+ return executeJavaScriptCode(transpiledCode, functionName, inputs, executionStyle);
2559
+ }
2560
+ // Annotate the CommonJS export names for ESM import in node:
2561
+ 0 && (module.exports = {
2562
+ DEFAULT_BROWSER_HARNESS_ASSET_RELATIVE_PATHS,
2563
+ LANGUAGE_RUNTIME_PROFILES,
2564
+ PYTHON_CLASS_DEFINITIONS,
2565
+ PYTHON_CONVERSION_HELPERS,
2566
+ PYTHON_EXECUTE_SERIALIZE_FUNCTION,
2567
+ PYTHON_INTERVIEW_MATERIALIZE_SERIALIZE_FUNCTION,
2568
+ PYTHON_PRACTICE_MATERIALIZE_SERIALIZE_FUNCTION,
2569
+ PYTHON_SERIALIZE_FUNCTION,
2570
+ PYTHON_TRACE_SERIALIZE_FUNCTION,
2571
+ RUNTIME_TRACE_CONTRACT_SCHEMA_VERSION,
2572
+ SUPPORTED_LANGUAGES,
2573
+ TEMPLATE_PYTHON_CLASS_DEFINITIONS,
2574
+ TEMPLATE_PYTHON_CONVERSION_HELPERS,
2575
+ TEMPLATE_PYTHON_EXECUTE_SERIALIZE_FUNCTION,
2576
+ TEMPLATE_PYTHON_INTERVIEW_MATERIALIZE_SERIALIZE_FUNCTION,
2577
+ TEMPLATE_PYTHON_PRACTICE_MATERIALIZE_SERIALIZE_FUNCTION,
2578
+ TEMPLATE_PYTHON_SERIALIZE_FUNCTION,
2579
+ TEMPLATE_PYTHON_TRACE_SERIALIZE_FUNCTION,
2580
+ TYPESCRIPT_RUNTIME_DECLARATIONS,
2581
+ adaptJavaScriptTraceExecutionResult,
2582
+ adaptPythonTraceExecutionResult,
2583
+ adaptTraceExecutionResult,
2584
+ assertRuntimeRequestSupported,
2585
+ createBrowserHarness,
2586
+ executeJavaScriptCode,
2587
+ executeJavaScriptWithTracing,
2588
+ executeTypeScriptCode,
2589
+ generateConversionCode,
2590
+ generateInputSetup,
2591
+ generateSolutionScript,
2592
+ getLanguageRuntimeProfile,
2593
+ getSupportedLanguageProfiles,
2594
+ identifyConversions,
2595
+ isLanguageSupported,
2596
+ normalizeRuntimeTraceContract,
2597
+ resolveBrowserHarnessAssets,
2598
+ stableStringifyRuntimeTraceContract,
2599
+ templateToPythonLiteral,
2600
+ toPythonLiteral,
2601
+ withTypeScriptRuntimeDeclarations
2602
+ });
2603
+ //# sourceMappingURL=index.cjs.map