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

create-handler-bindings.ts

355 lines9.8 KB

1import { z } from 'zod'
2import { convertSchemaToJsonSchema } from '@tanstack/ai'
3import type { ToolBinding } from '@tanstack/ai-code-mode'
4import type { BindingSignalMetadata, Report, UIEffect, UIUpdate } from './types'
5​
6export interface HandlerBindingContext {
7 report: Report
8 onEffect: (effect: UIEffect) => void
9 onUIUpdate: (update: UIUpdate) => void
10 onBindingCall?: (bindingName: string) => void
12​
13// ============================================================================
14// Signal Metadata for Bindings
15// ============================================================================
16​
17/**
18 * Signal metadata for bindings.
19 * Defines which bindings ARE signals and which INVALIDATE signals.
20 */
21export const BINDING_SIGNAL_METADATA: Record<string, BindingSignalMetadata> = {
22 // Read bindings - these ARE signals (components can subscribe to them)
23 external_get_balances: {
24 signal: 'balances',
25 },
26 external_get_transactions: {
27 signal: 'transactions',
28 },
29​
30 // Write bindings - these INVALIDATE signals
31 external_transfer: {
32 invalidates: ['balances', 'transactions'],
33 },
34​
35 // UI bindings - no signal relationships
36 external_ui_toast: {},
37 external_report_update_component: {},
38 external_report_remove_component: {},
40​
41/**
42 * Get the signals that a binding invalidates when called.
43 */
44export function getInvalidatedSignals(bindingName: string): string[] {
45 return BINDING_SIGNAL_METADATA[bindingName]?.invalidates || []
47​
48/**
49 * Get the signal that a binding provides (if any).
50 */
51export function getBindingSignal(bindingName: string): string | undefined {
52 return BINDING_SIGNAL_METADATA[bindingName]?.signal
54​
55const noop = async () => ({ success: true })
56​
57function createBinding(
58 name: string,
59 description: string,
60 inputSchema: z.ZodTypeAny,
61 execute: ToolBinding['execute'],
62): ToolBinding {
63 return {
64 name,
65 description,
66 inputSchema: convertSchemaToJsonSchema(inputSchema) || {
67 type: 'object',
68 properties: {},
69 },
70 outputSchema: convertSchemaToJsonSchema(z.object({ success: z.boolean() })),
71 execute,
72 }
74​
75export function createHandlerBindings(
76 context?: HandlerBindingContext,
77 _reportId?: string,
78 _canvasId: string = 'diagram',
79): Record<string, ToolBinding> {
80 // Helper to track binding calls
81 const track = (name: string) => context?.onBindingCall?.(name)
82​
83 return {
84 external_ui_toast: createBinding(
85 'external_ui_toast',
86 'Show a toast message in the UI',
87 z.object({
88 message: z.string(),
89 variant: z.enum(['default', 'success', 'error']).optional(),
90 }),
91 context
92 ? async (params) => {
93 track('external_ui_toast')
94 const parsed = z
95 .object({
96 message: z.string(),
97 variant: z.enum(['default', 'success', 'error']).optional(),
98 })
99 .parse(params)
100 context.onEffect({
101 type: 'toast',
102 params: parsed,
103 })
104 return { success: true }
105 }
106 : noop,
107 ),
108 external_report_update_component: createBinding(
109 'external_report_update_component',
110 'Update a report component props',
111 z.object({
112 componentId: z.string(),
113 props: z.record(z.string(), z.unknown()),
114 }),
115 context
116 ? async (params) => {
117 track('external_report_update_component')
118 const parsed = z
119 .object({
120 componentId: z.string(),
121 props: z.record(z.string(), z.unknown()),
122 })
123 .parse(params)
124 context.onUIUpdate({
125 type: 'update',
126 componentId: parsed.componentId,
127 props: parsed.props,
128 })
129 return { success: true }
130 }
131 : noop,
132 ),
133 external_report_remove_component: createBinding(
134 'external_report_remove_component',
135 'Remove a report component',
136 z.object({
137 componentId: z.string(),
138 }),
139 context
140 ? async (params) => {
141 track('external_report_remove_component')
142 const parsed = z.object({ componentId: z.string() }).parse(params)
143 context.onUIUpdate({
144 type: 'remove',
145 componentId: parsed.componentId,
146 })
147 return { success: true }
148 }
149 : noop,
150 ),
151 external_get_balances: createBinding(
152 'external_get_balances',
153 'Get account balances',
154 z.object({}),
155 async () => {
156 track('external_get_balances')
157 return getMockBalances()
158 },
159 ),
160 external_transfer: createBinding(
161 'external_transfer',
162 'Transfer money between accounts',
163 z.object({
164 from: z.string(),
165 to: z.string(),
166 amount: z.number(),
167 }),
168 async (params) => {
169 track('external_transfer')
170 const parsed = z
171 .object({
172 from: z.string(),
173 to: z.string(),
174 amount: z.number(),
175 })
176 .parse(params)
177 return performMockTransfer(parsed)
178 },
179 ),
180 external_get_transactions: createBinding(
181 'external_get_transactions',
182 'Get recent transactions',
183 z.object({
184 limit: z.number().optional(),
185 }),
186 async (params) => {
187 track('external_get_transactions')
188 const parsed = z.object({ limit: z.number().optional() }).parse(params)
189 return getMockTransactions(parsed.limit ?? 10)
190 },
191 ),
192 }
194​
195// ============================================
196// Mock Banking State (in-memory for demo)
197// ============================================
198​
199export interface MockTransaction {
200 id: string
201 from: string
202 to: string
203 amount: number
204 timestamp: number
205 date: string // ISO date string for chart compatibility
206 type: 'deposit' | 'withdrawal' | 'transfer'
207 balance: number // Running balance after transaction
209​
210function createInitialTransactions(): MockTransaction[] {
211 const now = Date.now()
212 const day = 24 * 60 * 60 * 1000
213 // Create some historical transactions with running balance
214 return [
215 {
216 id: crypto.randomUUID(),
217 from: 'external',
218 to: 'checking',
219 amount: 500,
220 timestamp: now - 7 * day,
221 date: new Date(now - 7 * day).toISOString(),
222 type: 'deposit',
223 balance: 800,
224 },
225 {
226 id: crypto.randomUUID(),
227 from: 'checking',
228 to: 'savings',
229 amount: 100,
230 timestamp: now - 5 * day,
231 date: new Date(now - 5 * day).toISOString(),
232 type: 'transfer',
233 balance: 700,
234 },
235 {
236 id: crypto.randomUUID(),
237 from: 'external',
238 to: 'checking',
239 amount: 300,
240 timestamp: now - 3 * day,
241 date: new Date(now - 3 * day).toISOString(),
242 type: 'deposit',
243 balance: 1000,
244 },
245 ]
247​
248let mockState = {
249 balances: {
250 checking: 1000,
251 savings: 500,
252 },
253 transactions: createInitialTransactions(),
255​
256export function getMockBalances() {
257 console.log('[MockBank] getMockBalances:', mockState.balances)
258 return { ...mockState.balances }
260​
261function performMockTransfer(params: {
262 from: string
263 to: string
264 amount: number
265}) {
266 const { from, to, amount } = params
267 console.log('[MockBank] performMockTransfer:', { from, to, amount })
268 console.log('[MockBank] Current balances:', mockState.balances)
269​
270 const fromBalance =
271 mockState.balances[from as keyof typeof mockState.balances]
272 if (fromBalance === undefined) {
273 console.log('[MockBank] Transfer failed: Invalid source account:', from)
274 return { success: false, error: `Invalid account: ${from}` }
275 }
276​
277 if (fromBalance < amount) {
278 console.log(
279 '[MockBank] Transfer failed: Insufficient funds. Has:',
280 fromBalance,
281 'Needs:',
282 amount,
283 )
284 return {
285 success: false,
286 error: `Insufficient funds in ${from}. Balance: $${fromBalance}, Requested: $${amount}`,
287 }
288 }
289​
290 mockState.balances[from as keyof typeof mockState.balances] -= amount
291 mockState.balances[to as keyof typeof mockState.balances] += amount
292​
293 const now = Date.now()
294 const transaction: MockTransaction = {
295 id: crypto.randomUUID(),
296 from,
297 to,
298 amount,
299 timestamp: now,
300 date: new Date(now).toISOString(),
301 type:
302 from === 'external'
303 ? 'deposit'
304 : to === 'external'
305 ? 'withdrawal'
306 : 'transfer',
307 balance: mockState.balances.checking + mockState.balances.savings, // Total balance
308 }
309 mockState.transactions.unshift(transaction)
310​
311 console.log(
312 '[MockBank] Transfer successful. New balances:',
313 mockState.balances,
314 )
315 return {
316 success: true,
317 balances: { ...mockState.balances },
318 newBalance: mockState.balances[to as keyof typeof mockState.balances],
319 transaction,
320 }
322​
323function getMockTransactions(limit: number) {
324 console.log('[MockBank] getMockTransactions, limit:', limit)
325 // Return transactions sorted chronologically (oldest first) for proper chart display
326 // Take the most recent `limit` transactions, then sort by timestamp ascending
327 return mockState.transactions
328 .slice(0, limit)
329 .sort((a, b) => a.timestamp - b.timestamp)
331​
332export function resetMockState() {
333 console.log('[MockBank] Resetting mock state')
334 mockState = {
335 balances: { checking: 1000, savings: 500 },
336 transactions: createInitialTransactions(),
337 }
339​
340export function simulateDeposit(account: string, amount: number) {
341 mockState.balances[account as keyof typeof mockState.balances] += amount
342 const now = Date.now()
343 const transaction: MockTransaction = {
344 id: crypto.randomUUID(),
345 from: 'external',
346 to: account,
347 amount,
348 timestamp: now,
349 date: new Date(now).toISOString(),
350 type: 'deposit',
351 balance: mockState.balances.checking + mockState.balances.savings,
352 }
353 mockState.transactions.unshift(transaction)
354 return mockState.balances[account as keyof typeof mockState.balances]