Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

error-normalizer.ts

102 lines2.7 KB

1import type { NormalizedError } from '@tanstack/ai-code-mode'
2​
3const MEMORY_LIMIT_ERROR = 'MemoryLimitError'
4const STACK_OVERFLOW_ERROR = 'StackOverflowError'
5const TIMEOUT_ERROR = 'TimeoutError'
6​
7/**
8 * Whether this normalized error indicates the QuickJS VM should not be reused
9 * (memory or stack limit exceeded).
10 */
11export function isFatalQuickJSLimitError(error: NormalizedError): boolean {
12 return (
13 error.name === MEMORY_LIMIT_ERROR || error.name === STACK_OVERFLOW_ERROR
14 )
16​
17/**
18 * Normalized error for code that exhausted the QuickJS heap so thoroughly
19 * that QuickJS could not even allocate an Error object — it throws a bare
20 * `null` exception value in that situation.
21 */
22export function memoryLimitError(stack?: string): NormalizedError {
23 return {
24 name: MEMORY_LIMIT_ERROR,
25 message: 'Code execution exceeded memory limit',
26 ...(stack !== undefined && { stack }),
27 }
29​
30/**
31 * Normalize various error types into a consistent format
32 */
33export function normalizeError(error: unknown): NormalizedError {
34 if (error instanceof Error) {
35 const msg = error.message
36 const lower = msg.toLowerCase()
37​
38 if (
39 lower.includes('out of memory') ||
40 lower.includes('memory alloc') ||
41 (error.name === 'InternalError' && lower.includes('memory'))
42 ) {
43 return {
44 name: MEMORY_LIMIT_ERROR,
45 message: 'Code execution exceeded memory limit',
46 stack: error.stack,
47 }
48 }
49​
50 if (lower.includes('stack overflow')) {
51 return {
52 name: STACK_OVERFLOW_ERROR,
53 message: 'Code execution exceeded stack size limit',
54 stack: error.stack,
55 }
56 }
57​
58 // quickjs-bun reports deadline expiry as a TimeoutError ("QuickJS
59 // execution timed out"); a raw QuickJS interrupt surfaces as
60 // `InternalError: interrupted`.
61 if (
62 error.name === TIMEOUT_ERROR ||
63 (error.name === 'InternalError' && msg === 'interrupted')
64 ) {
65 return {
66 name: TIMEOUT_ERROR,
67 message:
68 error.name === TIMEOUT_ERROR ? msg : 'Code execution timed out',
69 stack: error.stack,
70 }
71 }
72​
73 return {
74 name: error.name,
75 message: error.message,
76 stack: error.stack,
77 }
78 }
79​
80 if (typeof error === 'string') {
81 return {
82 name: 'Error',
83 message: error,
84 }
85 }
86​
87 if (typeof error === 'object' && error !== null) {
88 const errObj = error as Record<string, unknown>
89 return {
90 name: String(errObj.name || 'Error'),
91 message: String(errObj.message || 'Unknown error'),
92 ...(errObj['stack'] !== undefined && {
93 stack: String(errObj['stack']),
94 }),
95 }
96 }
97​
98 return {
99 name: 'UnknownError',
100 message: String(error),
101 }