Open History to see the last commit
1import { wrapCode } from '@tanstack/ai-code-mode'
2import { normalizeError } from './error-normalizer'
3import type ivm from 'isolated-vm'
4import type { ExecutionResult, IsolateContext } from '@tanstack/ai-code-mode'
5
6/**
7 * IsolateContext implementation using isolated-vm
8 */
9export class NodeIsolateContext implements IsolateContext {
10 private readonly isolate: ivm.Isolate
11 private readonly context: ivm.Context
12 private readonly logs: Array<string>
13 private readonly timeout: number
14 private disposed = false
15
16 constructor(
17 isolate: ivm.Isolate,
18 context: ivm.Context,
19 logs: Array<string>,
20 timeout: number,
21 ) {
22 this.isolate = isolate
23 this.context = context
24 this.logs = logs
25 this.timeout = timeout
26 }
27
28 async execute<T = unknown>(code: string): Promise<ExecutionResult<T>> {
29 if (this.disposed) {
30 return {
31 success: false,
32 error: {
33 name: 'DisposedError',
34 message: 'Context has been disposed',
35 },
36 logs: [],
37 }
38 }
39
40 // Clear previous logs
41 this.logs.length = 0
42
43 try {
44 // Wrap user code in async IIFE
45 const wrappedCode = wrapCode(code)
46
47 // Compile the script
48 const script = await this.isolate.compileScript(wrappedCode)
49
50 // Run with timeout
51 const result = await script.run(this.context, {
52 timeout: this.timeout,
53 promise: true,
54 })
55
56 // Parse result if it's a JSON string (from our serialization)
57 let parsedResult: T
58 if (typeof result === 'string') {
59 try {
60 parsedResult = JSON.parse(result) as T
61 } catch {
62 parsedResult = result as T
63 }
64 } else {
65 parsedResult = result as T
66 }
67
68 return {
69 success: true,
70 value: parsedResult,
71 logs: [...this.logs],
72 }
73 } catch (error) {
74 return {
75 success: false,
76 error: normalizeError(error),
77 logs: [...this.logs],
78 }
79 }
80 }
81
82 dispose(): Promise<void> {
83 if (!this.disposed) {
84 this.disposed = true
85 this.context.release()
86 this.isolate.dispose()
87 }
88 return Promise.resolve()
89 }
90}