@ai-sdk/react 3.0.0-beta.99 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,699 @@
1
1
  # @ai-sdk/react
2
2
 
3
+ ## 3.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - dee8b05: ai SDK 6 beta
8
+
9
+ ### Minor Changes
10
+
11
+ - 78928cb: release: start 5.1 beta
12
+
13
+ ### Patch Changes
14
+
15
+ - 4b3b981: Fix subscribeToMessages callback dependency in useChat
16
+ - ab1087b: feat(ai): `chat.addToolResult()` is now `chat.addToolOutput()`
17
+ - c388279: force update of vulnerable react versions through peer dependency range
18
+ - 95f65c2: chore: use import \* from zod/v4
19
+ - e8109d3: feat: tool execution approval
20
+ - f6f0c5a: chore: remove zod from ui packages
21
+ - af65ab6: drop react 19-rc support. Require minimal versions for RSC to address CVE-2025-55182
22
+ - 4616b86: chore: update zod peer depenedency version
23
+ - a322efa: Added finishReason on useChat onFinish callbck
24
+ - 10c1322: fix: moved dependency `@ai-sdk/test-server` to devDependencies
25
+ - Updated dependencies [0c3b58b]
26
+ - Updated dependencies [58920e0]
27
+ - Updated dependencies [a7da2b6]
28
+ - Updated dependencies [0adc679]
29
+ - Updated dependencies [50b70d6]
30
+ - Updated dependencies [2d28066]
31
+ - Updated dependencies [fca786b]
32
+ - Updated dependencies [dee8b05]
33
+ - Updated dependencies [046aa3b]
34
+ - Updated dependencies [e1f6e8e]
35
+ - Updated dependencies [8d9e8ad]
36
+ - Updated dependencies [78928cb]
37
+ - Updated dependencies [b67d224]
38
+ - Updated dependencies [ab6f01a]
39
+ - Updated dependencies [9388ff1]
40
+ - Updated dependencies [dce03c4]
41
+ - Updated dependencies [2625a04]
42
+ - Updated dependencies [37c58a0]
43
+ - Updated dependencies [4e2b04d]
44
+ - Updated dependencies [ab1087b]
45
+ - Updated dependencies [3b1d015]
46
+ - Updated dependencies [bb10a89]
47
+ - Updated dependencies [457f1c6]
48
+ - Updated dependencies [95f65c2]
49
+ - Updated dependencies [754df61]
50
+ - Updated dependencies [016b111]
51
+ - Updated dependencies [58920e0]
52
+ - Updated dependencies [954c356]
53
+ - Updated dependencies [7fdd89d]
54
+ - Updated dependencies [eca63f3]
55
+ - Updated dependencies [90e5bdd]
56
+ - Updated dependencies [42cf7ed]
57
+ - Updated dependencies [544d4e8]
58
+ - Updated dependencies [4812235]
59
+ - Updated dependencies [7f2c9b6]
60
+ - Updated dependencies [614599a]
61
+ - Updated dependencies [0c4822d]
62
+ - Updated dependencies [e062079]
63
+ - Updated dependencies [2b49dae]
64
+ - Updated dependencies [ee651d7]
65
+ - Updated dependencies [5a4e732]
66
+ - Updated dependencies [f733285]
67
+ - Updated dependencies [9b83947]
68
+ - Updated dependencies [7eca093]
69
+ - Updated dependencies [077aea3]
70
+ - Updated dependencies [9f20c87]
71
+ - Updated dependencies [521c537]
72
+ - Updated dependencies [7169511]
73
+ - Updated dependencies [e8109d3]
74
+ - Updated dependencies [03849b0]
75
+ - Updated dependencies [ed329cb]
76
+ - Updated dependencies [22ef5c6]
77
+ - Updated dependencies [9ba4324]
78
+ - Updated dependencies [e06565c]
79
+ - Updated dependencies [32d8dbb]
80
+ - Updated dependencies [d116b4b]
81
+ - Updated dependencies [3bd2689]
82
+ - Updated dependencies [293a6b7]
83
+ - Updated dependencies [7c3c216]
84
+ - Updated dependencies [c62ecf0]
85
+ - Updated dependencies [d1bdadb]
86
+ - Updated dependencies [703459a]
87
+ - Updated dependencies [3071620]
88
+ - Updated dependencies [7e4649f]
89
+ - Updated dependencies [48454ab]
90
+ - Updated dependencies [e06b663]
91
+ - Updated dependencies [83e5744]
92
+ - Updated dependencies [8c98371]
93
+ - Updated dependencies [7e32fea]
94
+ - Updated dependencies [b1405bf]
95
+ - Updated dependencies [a5e152d]
96
+ - Updated dependencies [aa0515c]
97
+ - Updated dependencies [f6f0c5a]
98
+ - Updated dependencies [3ed5519]
99
+ - Updated dependencies [eb8d1cb]
100
+ - Updated dependencies [e7d9b00]
101
+ - Updated dependencies [d5b25ee]
102
+ - Updated dependencies [d7bae86]
103
+ - Updated dependencies [8dac895]
104
+ - Updated dependencies [a755db5]
105
+ - Updated dependencies [1c2a4c1]
106
+ - Updated dependencies [686103c]
107
+ - Updated dependencies [0d6c0d8]
108
+ - Updated dependencies [9b8d17e]
109
+ - Updated dependencies [79a8e7f]
110
+ - Updated dependencies [cbb1d35]
111
+ - Updated dependencies [d59ce25]
112
+ - Updated dependencies [475189e]
113
+ - Updated dependencies [3d83f38]
114
+ - Updated dependencies [457318b]
115
+ - Updated dependencies [b681d7d]
116
+ - Updated dependencies [c99da05]
117
+ - Updated dependencies [db913bd]
118
+ - Updated dependencies [9061dc0]
119
+ - Updated dependencies [8445d70]
120
+ - Updated dependencies [32223c8]
121
+ - Updated dependencies [8370068]
122
+ - Updated dependencies [5e313e3]
123
+ - Updated dependencies [db62f7d]
124
+ - Updated dependencies [a7f6f81]
125
+ - Updated dependencies [79ba99f]
126
+ - Updated dependencies [c98373a]
127
+ - Updated dependencies [c1efac4]
128
+ - Updated dependencies [846e80e]
129
+ - Updated dependencies [bbdcb81]
130
+ - Updated dependencies [67a407c]
131
+ - Updated dependencies [9524761]
132
+ - Updated dependencies [ca13d26]
133
+ - Updated dependencies [4616b86]
134
+ - Updated dependencies [a322efa]
135
+ - Updated dependencies [2d166e4]
136
+ - Updated dependencies [384142c]
137
+ - Updated dependencies [36b175c]
138
+ - Updated dependencies [2b1bf9d]
139
+ - Updated dependencies [81d4308]
140
+ - Updated dependencies [e0d1ea9]
141
+ - Updated dependencies [2406576]
142
+ - Updated dependencies [b1aeea7]
143
+ - Updated dependencies [dce4e7b]
144
+ - Updated dependencies [4f16c37]
145
+ - Updated dependencies [4ece5f9]
146
+ - Updated dependencies [81e29ab]
147
+ - Updated dependencies [a417a34]
148
+ - Updated dependencies [637eaa4]
149
+ - Updated dependencies [177b475]
150
+ - Updated dependencies [21e20c0]
151
+ - Updated dependencies [afe7093]
152
+ - Updated dependencies [61f7b0f]
153
+ - Updated dependencies [af9dab3]
154
+ - Updated dependencies [522f6b8]
155
+ - Updated dependencies [6306603]
156
+ - Updated dependencies [97b1d77]
157
+ - Updated dependencies [69768c2]
158
+ - Updated dependencies [27e8c3a]
159
+ - Updated dependencies [fca786b]
160
+ - Updated dependencies [81e29ab]
161
+ - Updated dependencies [7da02d2]
162
+ - Updated dependencies [763d04a]
163
+ - Updated dependencies [95b77e2]
164
+ - Updated dependencies [3794514]
165
+ - Updated dependencies [cbf52cd]
166
+ - Updated dependencies [14ca35d]
167
+ - Updated dependencies [e9e157f]
168
+ - Updated dependencies [10c1322]
169
+ - Updated dependencies [dcdac8c]
170
+ - Updated dependencies [960ec8f]
171
+ - Updated dependencies [b59d924]
172
+ - Updated dependencies [1bd7d32]
173
+ - Updated dependencies [f0b2157]
174
+ - Updated dependencies [95f65c2]
175
+ - ai@6.0.0
176
+ - @ai-sdk/provider-utils@4.0.0
177
+
178
+ ## 3.0.0-beta.172
179
+
180
+ ### Patch Changes
181
+
182
+ - Updated dependencies [ee651d7]
183
+ - ai@6.0.0-beta.169
184
+
185
+ ## 3.0.0-beta.171
186
+
187
+ ### Patch Changes
188
+
189
+ - ai@6.0.0-beta.168
190
+
191
+ ## 3.0.0-beta.170
192
+
193
+ ### Patch Changes
194
+
195
+ - Updated dependencies [475189e]
196
+ - ai@6.0.0-beta.167
197
+ - @ai-sdk/provider-utils@4.0.0-beta.59
198
+
199
+ ## 3.0.0-beta.169
200
+
201
+ ### Patch Changes
202
+
203
+ - Updated dependencies [9f20c87]
204
+ - ai@6.0.0-beta.166
205
+
206
+ ## 3.0.0-beta.168
207
+
208
+ ### Patch Changes
209
+
210
+ - Updated dependencies [2625a04]
211
+ - ai@6.0.0-beta.165
212
+ - @ai-sdk/provider-utils@4.0.0-beta.58
213
+
214
+ ## 3.0.0-beta.167
215
+
216
+ ### Patch Changes
217
+
218
+ - Updated dependencies [cbf52cd]
219
+ - ai@6.0.0-beta.164
220
+ - @ai-sdk/provider-utils@4.0.0-beta.57
221
+
222
+ ## 3.0.0-beta.166
223
+
224
+ ### Patch Changes
225
+
226
+ - ai@6.0.0-beta.163
227
+ - @ai-sdk/provider-utils@4.0.0-beta.56
228
+
229
+ ## 3.0.0-beta.165
230
+
231
+ ### Patch Changes
232
+
233
+ - Updated dependencies [50b70d6]
234
+ - @ai-sdk/provider-utils@4.0.0-beta.55
235
+ - ai@6.0.0-beta.162
236
+
237
+ ## 3.0.0-beta.164
238
+
239
+ ### Patch Changes
240
+
241
+ - ai@6.0.0-beta.161
242
+
243
+ ## 3.0.0-beta.163
244
+
245
+ ### Patch Changes
246
+
247
+ - Updated dependencies [9061dc0]
248
+ - @ai-sdk/provider-utils@4.0.0-beta.54
249
+ - ai@6.0.0-beta.160
250
+
251
+ ## 3.0.0-beta.162
252
+
253
+ ### Patch Changes
254
+
255
+ - Updated dependencies [3071620]
256
+ - ai@6.0.0-beta.159
257
+
258
+ ## 3.0.0-beta.161
259
+
260
+ ### Patch Changes
261
+
262
+ - ai@6.0.0-beta.158
263
+ - @ai-sdk/provider-utils@4.0.0-beta.53
264
+
265
+ ## 3.0.0-beta.160
266
+
267
+ ### Patch Changes
268
+
269
+ - Updated dependencies [763d04a]
270
+ - @ai-sdk/provider-utils@4.0.0-beta.52
271
+ - ai@6.0.0-beta.157
272
+
273
+ ## 3.0.0-beta.159
274
+
275
+ ### Patch Changes
276
+
277
+ - Updated dependencies [2406576]
278
+ - ai@6.0.0-beta.156
279
+
280
+ ## 3.0.0-beta.158
281
+
282
+ ### Patch Changes
283
+
284
+ - Updated dependencies [c1efac4]
285
+ - @ai-sdk/provider-utils@4.0.0-beta.51
286
+ - ai@6.0.0-beta.155
287
+
288
+ ## 3.0.0-beta.157
289
+
290
+ ### Patch Changes
291
+
292
+ - Updated dependencies [32223c8]
293
+ - @ai-sdk/provider-utils@4.0.0-beta.50
294
+ - ai@6.0.0-beta.154
295
+
296
+ ## 3.0.0-beta.156
297
+
298
+ ### Patch Changes
299
+
300
+ - Updated dependencies [83e5744]
301
+ - @ai-sdk/provider-utils@4.0.0-beta.49
302
+ - ai@6.0.0-beta.153
303
+
304
+ ## 3.0.0-beta.155
305
+
306
+ ### Patch Changes
307
+
308
+ - Updated dependencies [960ec8f]
309
+ - @ai-sdk/provider-utils@4.0.0-beta.48
310
+ - ai@6.0.0-beta.152
311
+
312
+ ## 3.0.0-beta.154
313
+
314
+ ### Patch Changes
315
+
316
+ - Updated dependencies [dcdac8c]
317
+ - ai@6.0.0-beta.151
318
+
319
+ ## 3.0.0-beta.153
320
+
321
+ ### Patch Changes
322
+
323
+ - Updated dependencies [db62f7d]
324
+ - ai@6.0.0-beta.150
325
+
326
+ ## 3.0.0-beta.152
327
+
328
+ ### Patch Changes
329
+
330
+ - Updated dependencies [4e2b04d]
331
+ - ai@6.0.0-beta.149
332
+
333
+ ## 3.0.0-beta.151
334
+
335
+ ### Patch Changes
336
+
337
+ - ai@6.0.0-beta.148
338
+
339
+ ## 3.0.0-beta.150
340
+
341
+ ### Patch Changes
342
+
343
+ - Updated dependencies [637eaa4]
344
+ - ai@6.0.0-beta.147
345
+
346
+ ## 3.0.0-beta.149
347
+
348
+ ### Patch Changes
349
+
350
+ - Updated dependencies [e9e157f]
351
+ - @ai-sdk/provider-utils@4.0.0-beta.47
352
+ - ai@6.0.0-beta.146
353
+
354
+ ## 3.0.0-beta.148
355
+
356
+ ### Patch Changes
357
+
358
+ - ai@6.0.0-beta.145
359
+
360
+ ## 3.0.0-beta.147
361
+
362
+ ### Patch Changes
363
+
364
+ - Updated dependencies [ab6f01a]
365
+ - ai@6.0.0-beta.144
366
+
367
+ ## 3.0.0-beta.146
368
+
369
+ ### Patch Changes
370
+
371
+ - c388279: force update of vulnerable react versions through peer dependency range
372
+
373
+ ## 3.0.0-beta.145
374
+
375
+ ### Patch Changes
376
+
377
+ - Updated dependencies [81e29ab]
378
+ - Updated dependencies [81e29ab]
379
+ - @ai-sdk/provider-utils@4.0.0-beta.46
380
+ - ai@6.0.0-beta.143
381
+
382
+ ## 3.0.0-beta.144
383
+
384
+ ### Patch Changes
385
+
386
+ - Updated dependencies [7169511]
387
+ - Updated dependencies [bbdcb81]
388
+ - ai@6.0.0-beta.142
389
+
390
+ ## 3.0.0-beta.143
391
+
392
+ ### Patch Changes
393
+
394
+ - Updated dependencies [b1405bf]
395
+ - ai@6.0.0-beta.141
396
+
397
+ ## 3.0.0-beta.142
398
+
399
+ ### Patch Changes
400
+
401
+ - Updated dependencies [7fdd89d]
402
+ - ai@6.0.0-beta.140
403
+
404
+ ## 3.0.0-beta.141
405
+
406
+ ### Patch Changes
407
+
408
+ - Updated dependencies [3bd2689]
409
+ - ai@6.0.0-beta.139
410
+ - @ai-sdk/provider-utils@4.0.0-beta.45
411
+
412
+ ## 3.0.0-beta.140
413
+
414
+ ### Patch Changes
415
+
416
+ - ai@6.0.0-beta.138
417
+ - @ai-sdk/provider-utils@4.0.0-beta.44
418
+
419
+ ## 3.0.0-beta.139
420
+
421
+ ### Patch Changes
422
+
423
+ - 4b3b981: Fix subscribeToMessages callback dependency in useChat
424
+
425
+ ## 3.0.0-beta.138
426
+
427
+ ### Patch Changes
428
+
429
+ - Updated dependencies [9ba4324]
430
+ - ai@6.0.0-beta.137
431
+
432
+ ## 3.0.0-beta.137
433
+
434
+ ### Patch Changes
435
+
436
+ - Updated dependencies [3d83f38]
437
+ - ai@6.0.0-beta.136
438
+
439
+ ## 3.0.0-beta.136
440
+
441
+ ### Patch Changes
442
+
443
+ - Updated dependencies [afe7093]
444
+ - ai@6.0.0-beta.135
445
+
446
+ ## 3.0.0-beta.135
447
+
448
+ ### Patch Changes
449
+
450
+ - Updated dependencies [686103c]
451
+ - ai@6.0.0-beta.134
452
+
453
+ ## 3.0.0-beta.134
454
+
455
+ ### Patch Changes
456
+
457
+ - Updated dependencies [dce03c4]
458
+ - @ai-sdk/provider-utils@4.0.0-beta.43
459
+ - ai@6.0.0-beta.133
460
+
461
+ ## 3.0.0-beta.133
462
+
463
+ ### Patch Changes
464
+
465
+ - Updated dependencies [af9dab3]
466
+ - ai@6.0.0-beta.132
467
+
468
+ ## 3.0.0-beta.132
469
+
470
+ ### Patch Changes
471
+
472
+ - Updated dependencies [3ed5519]
473
+ - @ai-sdk/provider-utils@4.0.0-beta.42
474
+ - ai@6.0.0-beta.131
475
+
476
+ ## 3.0.0-beta.131
477
+
478
+ ### Patch Changes
479
+
480
+ - af65ab6: drop react 19-rc support. Require minimal versions for RSC to address CVE-2025-55182
481
+
482
+ ## 3.0.0-beta.130
483
+
484
+ ### Patch Changes
485
+
486
+ - Updated dependencies [1bd7d32]
487
+ - @ai-sdk/provider-utils@4.0.0-beta.41
488
+ - ai@6.0.0-beta.130
489
+
490
+ ## 3.0.0-beta.129
491
+
492
+ ### Patch Changes
493
+
494
+ - Updated dependencies [67a407c]
495
+ - ai@6.0.0-beta.129
496
+
497
+ ## 3.0.0-beta.128
498
+
499
+ ### Patch Changes
500
+
501
+ - ai@6.0.0-beta.128
502
+
503
+ ## 3.0.0-beta.127
504
+
505
+ ### Patch Changes
506
+
507
+ - Updated dependencies [614599a]
508
+ - ai@6.0.0-beta.127
509
+
510
+ ## 3.0.0-beta.126
511
+
512
+ ### Patch Changes
513
+
514
+ - Updated dependencies [b67d224]
515
+ - ai@6.0.0-beta.126
516
+
517
+ ## 3.0.0-beta.125
518
+
519
+ ### Patch Changes
520
+
521
+ - Updated dependencies [0d6c0d8]
522
+ - ai@6.0.0-beta.125
523
+
524
+ ## 3.0.0-beta.124
525
+
526
+ ### Patch Changes
527
+
528
+ - Updated dependencies [544d4e8]
529
+ - @ai-sdk/provider-utils@4.0.0-beta.40
530
+ - ai@6.0.0-beta.124
531
+
532
+ ## 3.0.0-beta.123
533
+
534
+ ### Patch Changes
535
+
536
+ - Updated dependencies [954c356]
537
+ - @ai-sdk/provider-utils@4.0.0-beta.39
538
+ - ai@6.0.0-beta.123
539
+
540
+ ## 3.0.0-beta.122
541
+
542
+ ### Patch Changes
543
+
544
+ - Updated dependencies [03849b0]
545
+ - @ai-sdk/provider-utils@4.0.0-beta.38
546
+ - ai@6.0.0-beta.122
547
+
548
+ ## 3.0.0-beta.121
549
+
550
+ ### Patch Changes
551
+
552
+ - ai@6.0.0-beta.121
553
+
554
+ ## 3.0.0-beta.120
555
+
556
+ ### Patch Changes
557
+
558
+ - Updated dependencies [457318b]
559
+ - ai@6.0.0-beta.120
560
+ - @ai-sdk/provider-utils@4.0.0-beta.37
561
+
562
+ ## 3.0.0-beta.119
563
+
564
+ ### Patch Changes
565
+
566
+ - Updated dependencies [b59d924]
567
+ - ai@6.0.0-beta.119
568
+
569
+ ## 3.0.0-beta.118
570
+
571
+ ### Patch Changes
572
+
573
+ - Updated dependencies [8d9e8ad]
574
+ - ai@6.0.0-beta.118
575
+ - @ai-sdk/provider-utils@4.0.0-beta.36
576
+
577
+ ## 3.0.0-beta.117
578
+
579
+ ### Patch Changes
580
+
581
+ - ai@6.0.0-beta.117
582
+ - @ai-sdk/provider-utils@4.0.0-beta.35
583
+
584
+ ## 3.0.0-beta.116
585
+
586
+ ### Patch Changes
587
+
588
+ - Updated dependencies [4ece5f9]
589
+ - ai@6.0.0-beta.116
590
+
591
+ ## 3.0.0-beta.115
592
+
593
+ ### Patch Changes
594
+
595
+ - Updated dependencies [7da02d2]
596
+ - ai@6.0.0-beta.115
597
+
598
+ ## 3.0.0-beta.114
599
+
600
+ ### Patch Changes
601
+
602
+ - Updated dependencies [69768c2]
603
+ - ai@6.0.0-beta.114
604
+
605
+ ## 3.0.0-beta.113
606
+
607
+ ### Patch Changes
608
+
609
+ - Updated dependencies [79a8e7f]
610
+ - ai@6.0.0-beta.113
611
+
612
+ ## 3.0.0-beta.112
613
+
614
+ ### Patch Changes
615
+
616
+ - Updated dependencies [e06b663]
617
+ - ai@6.0.0-beta.112
618
+
619
+ ## 3.0.0-beta.111
620
+
621
+ ### Patch Changes
622
+
623
+ - ai@6.0.0-beta.111
624
+
625
+ ## 3.0.0-beta.110
626
+
627
+ ### Patch Changes
628
+
629
+ - Updated dependencies [db913bd]
630
+ - ai@6.0.0-beta.110
631
+ - @ai-sdk/provider-utils@4.0.0-beta.34
632
+
633
+ ## 3.0.0-beta.109
634
+
635
+ ### Patch Changes
636
+
637
+ - Updated dependencies [79ba99f]
638
+ - ai@6.0.0-beta.109
639
+
640
+ ## 3.0.0-beta.108
641
+
642
+ ### Patch Changes
643
+
644
+ - ai@6.0.0-beta.108
645
+
646
+ ## 3.0.0-beta.107
647
+
648
+ ### Patch Changes
649
+
650
+ - Updated dependencies [8445d70]
651
+ - ai@6.0.0-beta.107
652
+
653
+ ## 3.0.0-beta.106
654
+
655
+ ### Patch Changes
656
+
657
+ - ai@6.0.0-beta.106
658
+
659
+ ## 3.0.0-beta.105
660
+
661
+ ### Patch Changes
662
+
663
+ - ai@6.0.0-beta.105
664
+
665
+ ## 3.0.0-beta.104
666
+
667
+ ### Patch Changes
668
+
669
+ - Updated dependencies [2d166e4]
670
+ - ai@6.0.0-beta.104
671
+
672
+ ## 3.0.0-beta.103
673
+
674
+ ### Patch Changes
675
+
676
+ - ai@6.0.0-beta.103
677
+
678
+ ## 3.0.0-beta.102
679
+
680
+ ### Patch Changes
681
+
682
+ - ai@6.0.0-beta.102
683
+
684
+ ## 3.0.0-beta.101
685
+
686
+ ### Patch Changes
687
+
688
+ - ai@6.0.0-beta.101
689
+
690
+ ## 3.0.0-beta.100
691
+
692
+ ### Patch Changes
693
+
694
+ - Updated dependencies [8370068]
695
+ - ai@6.0.0-beta.100
696
+
3
697
  ## 3.0.0-beta.99
4
698
 
5
699
  ### Patch Changes
package/dist/index.js CHANGED
@@ -183,12 +183,11 @@ function useChat({
183
183
  if (shouldRecreateChat) {
184
184
  chatRef.current = "chat" in options ? options.chat : new Chat(options);
185
185
  }
186
- const optionsId = "id" in options ? options.id : null;
187
186
  const subscribeToMessages = (0, import_react.useCallback)(
188
187
  (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
189
- // optionsId is required to trigger re-subscription when the chat ID changes
188
+ // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
190
189
  // eslint-disable-next-line react-hooks/exhaustive-deps
191
- [throttleWaitMs, optionsId]
190
+ [throttleWaitMs, chatRef.current.id]
192
191
  );
193
192
  const messages = (0, import_react.useSyncExternalStore)(
194
193
  subscribeToMessages,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport { Chat } from './chat.react';\nexport * from './use-completion';\nexport * from './use-object';\n","import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(options),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current = 'chat' in options ? options.chat : new Chat(options);\n }\n\n const optionsId = 'id' in options ? options.id : null;\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // optionsId is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, optionsId],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<UI_MESSAGE extends UIMessage>\n implements ChatState<UI_MESSAGE>\n{\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n FlexibleSchema,\n InferSchema,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,mBAAqE;;;ACNrE,gBAAyE;;;ACAzE,wBAA6B;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,WAAO,kBAAAA,SAAiB,IAAI,MAAM,IAAI;AACzD;;;ADPA;AAGA,IAAM,iBAAN,MAEA;AAAA,EASE,YAAY,kBAAgC,CAAC,GAAG;AARhD;AACA,gCAAsB;AACtB,+BAA4B;AAE5B,2CAAqB,oBAAI,IAAgB;AACzC,yCAAmB,oBAAI,IAAgB;AACvC,wCAAkB,oBAAI,IAAgB;AAiCtC,uBAAc,CAAC,YAAwB;AACrC,yBAAK,WAAY,mBAAK,WAAU,OAAO,OAAO;AAC9C,yBAAK,wBAAL;AAAA,IACF;AAEA,sBAAa,MAAM;AACjB,yBAAK,WAAY,mBAAK,WAAU,MAAM,GAAG,EAAE;AAC3C,yBAAK,wBAAL;AAAA,IACF;AAEA,0BAAiB,CAAC,OAAe,YAAwB;AACvD,yBAAK,WAAY;AAAA,QACf,GAAG,mBAAK,WAAU,MAAM,GAAG,KAAK;AAAA;AAAA,QAEhC,KAAK,SAAS,OAAO;AAAA,QACrB,GAAG,mBAAK,WAAU,MAAM,QAAQ,CAAC;AAAA,MACnC;AACA,yBAAK,wBAAL;AAAA,IACF;AAEA,oBAAW,CAAI,UAAgB,gBAAgB,KAAK;AAEpD,wCAA8B,CAC5B,UACA,mBACiB;AACjB,YAAM,WAAW,iBACb,SAAS,UAAU,cAAc,IACjC;AACJ,yBAAK,oBAAmB,IAAI,QAAQ;AACpC,aAAO,MAAM;AACX,2BAAK,oBAAmB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BAC/C,OAAO;AAAA,gBACP,YAAQ,qBAAS,MAAM;AAAA,cACzB,CAAC;AAED;AAAA,gBACE,iBAAiB,UACb,EAAE,QAAQ,iBAAiB,OAAO,OAAO,OAAU,IACnD,EAAE,QAAQ,QAAW,OAAO,iBAAiB,MAAM;AAAA,cACzD;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASE,QAAO;AACd,cAAI,oCAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,QAAM,QAAQ,MAAM;AAClB,SAAK;AACL,gBAAY;AAAA,EACd;AAEA,QAAM,cAAc,MAAM;AACxB,aAAS,MAAS;AAClB,iBAAa,KAAK;AAClB,WAAO,MAAS;AAAA,EAClB;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["throttleFunction","import_ai","import_react","fetch","useSWR","completion","import_ai","import_react","import_swr","fetch","useSWR","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["export * from './use-chat';\nexport { Chat } from './chat.react';\nexport * from './use-completion';\nexport * from './use-object';\n","import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(options),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current = 'chat' in options ? options.chat : new Chat(options);\n }\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, chatRef.current.id],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<UI_MESSAGE extends UIMessage>\n implements ChatState<UI_MESSAGE>\n{\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n FlexibleSchema,\n InferSchema,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMA,mBAAqE;;;ACNrE,gBAAyE;;;ACAzE,wBAA6B;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,WAAO,kBAAAA,SAAiB,IAAI,MAAM,IAAI;AACzD;;;ADPA;AAGA,IAAM,iBAAN,MAEA;AAAA,EASE,YAAY,kBAAgC,CAAC,GAAG;AARhD;AACA,gCAAsB;AACtB,+BAA4B;AAE5B,2CAAqB,oBAAI,IAAgB;AACzC,yCAAmB,oBAAI,IAAgB;AACvC,wCAAkB,oBAAI,IAAgB;AAiCtC,uBAAc,CAAC,YAAwB;AACrC,yBAAK,WAAY,mBAAK,WAAU,OAAO,OAAO;AAC9C,yBAAK,wBAA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IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["throttleFunction","import_ai","import_react","fetch","useSWR","completion","import_ai","import_react","import_swr","fetch","useSWR","error"]}
package/dist/index.mjs CHANGED
@@ -145,12 +145,11 @@ function useChat({
145
145
  if (shouldRecreateChat) {
146
146
  chatRef.current = "chat" in options ? options.chat : new Chat(options);
147
147
  }
148
- const optionsId = "id" in options ? options.id : null;
149
148
  const subscribeToMessages = useCallback(
150
149
  (update) => chatRef.current["~registerMessagesCallback"](update, throttleWaitMs),
151
- // optionsId is required to trigger re-subscription when the chat ID changes
150
+ // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
152
151
  // eslint-disable-next-line react-hooks/exhaustive-deps
153
- [throttleWaitMs, optionsId]
152
+ [throttleWaitMs, chatRef.current.id]
154
153
  );
155
154
  const messages = useSyncExternalStore(
156
155
  subscribeToMessages,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(options),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current = 'chat' in options ? options.chat : new Chat(options);\n }\n\n const optionsId = 'id' in options ? options.id : null;\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // optionsId is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, optionsId],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<UI_MESSAGE extends UIMessage>\n implements ChatState<UI_MESSAGE>\n{\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n FlexibleSchema,\n InferSchema,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,SAAS,aAAa,WAAW,QAAQ,4BAA4B;;;ACNrE,SAAS,oBAAgE;;;ACAzE,OAAO,sBAAsB;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACzD;;;ADPA;AAGA,IAAM,iBAAN,MAEA;AAAA,EASE,YAAY,kBAAgC,CAAC,GAAG;AARhD;AACA,gCAAsB;AACtB,+BAA4B;AAE5B,2CAAqB,oBAAI,IAAgB;AACzC,yCAAmB,oBAAI,IAAgB;AACvC,wCAAkB,oBAAI,IAAgB;AAiCtC,uBAAc,CAAC,YAAwB;AACrC,yBAAK,WAAY,mBAAK,WAAU,OAAO,OAAO;AAC9C,yBAAK,wBAAL;AAAA,IACF;AAEA,sBAAa,MAAM;AACjB,yBAAK,WAAY,mBAAK,WAAU,MAAM,GAAG,EAAE;AAC3C,yBAAK,wBAAL;AAAA,IACF;AAEA,0BAAiB,CAAC,OAAe,YAAwB;AACvD,yBAAK,WAAY;AAAA,QACf,GAAG,mBAAK,WAAU,MAAM,GAAG,KAAK;AAAA;AAAA,QAEhC,KAAK,SAAS,OAAO;AAAA,QACrB,GAAG,mBAAK,WAAU,MAAM,QAAQ,CAAC;AAAA,MACnC;AACA,yBAAK,wBAAL;AAAA,IACF;AAEA,oBAAW,CAAI,UAAgB,gBAAgB,KA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,IAAI,MAAM,iBAAiB,eAAe;AACxD,kBAAM,gBAAgB;AAEtB,gBAAI,CAAC,gBAAgB,cAAc,aAAa,GAAG;AACjD,6BAAe;AAEf,qBAAO,aAAa;AAAA,YACtB;AAAA,UACF;AAAA,UAEA,MAAM,QAAQ;AACZ,yBAAa,KAAK;AAClB,+BAAmB,UAAU;AAE7B,gBAAI,YAAY,MAAM;AACpB,oBAAM,mBAAmB,MAAM,kBAAkB;AAAA,gBAC/C,OAAO;AAAA,gBACP,QAAQ,SAAS,MAAM;AAAA,cACzB,CAAC;AAED;AAAA,gBACE,iBAAiB,UACb,EAAE,QAAQ,iBAAiB,OAAO,OAAO,OAAU,IACnD,EAAE,QAAQ,QAAW,OAAO,iBAAiB,MAAM;AAAA,cACzD;AAAA,YACF;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,SAASC,QAAO;AACd,UAAI,aAAaA,MAAK,GAAG;AACvB;AAAA,MACF;AAEA,UAAI,WAAWA,kBAAiB,OAAO;AACrC,gBAAQA,MAAK;AAAA,MACf;AAEA,mBAAa,KAAK;AAClB,eAASA,kBAAiB,QAAQA,SAAQ,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,QAAM,QAAQ,MAAM;AAClB,SAAK;AACL,gBAAY;AAAA,EACd;AAEA,QAAM,cAAc,MAAM;AACxB,aAAS,MAAS;AAClB,iBAAa,KAAK;AAClB,WAAO,MAAS;AAAA,EAClB;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useCallback","useEffect","useRef","fetch","useRef","useEffect","useCallback","completion","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
1
+ {"version":3,"sources":["../src/use-chat.ts","../src/chat.react.ts","../src/throttle.ts","../src/use-completion.ts","../src/use-object.ts"],"sourcesContent":["import {\n AbstractChat,\n ChatInit,\n type CreateUIMessage,\n type UIMessage,\n} from 'ai';\nimport { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';\nimport { Chat } from './chat.react';\n\nexport type { CreateUIMessage, UIMessage };\n\nexport type UseChatHelpers<UI_MESSAGE extends UIMessage> = {\n /**\n * The id of the chat.\n */\n readonly id: string;\n\n /**\n * Update the `messages` state locally. This is useful when you want to\n * edit the messages on the client, and then trigger the `reload` method\n * manually to regenerate the AI response.\n */\n setMessages: (\n messages: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => void;\n\n error: Error | undefined;\n} & Pick<\n AbstractChat<UI_MESSAGE>,\n | 'sendMessage'\n | 'regenerate'\n | 'stop'\n | 'resumeStream'\n | 'addToolResult'\n | 'addToolOutput'\n | 'addToolApprovalResponse'\n | 'status'\n | 'messages'\n | 'clearError'\n>;\n\nexport type UseChatOptions<UI_MESSAGE extends UIMessage> = (\n | { chat: Chat<UI_MESSAGE> }\n | ChatInit<UI_MESSAGE>\n) & {\n /**\nCustom throttle wait in ms for the chat messages and data updates.\nDefault is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n\n /**\n * Whether to resume an ongoing chat generation stream.\n */\n resume?: boolean;\n};\n\nexport function useChat<UI_MESSAGE extends UIMessage = UIMessage>({\n experimental_throttle: throttleWaitMs,\n resume = false,\n ...options\n}: UseChatOptions<UI_MESSAGE> = {}): UseChatHelpers<UI_MESSAGE> {\n const chatRef = useRef<Chat<UI_MESSAGE>>(\n 'chat' in options ? options.chat : new Chat(options),\n );\n\n const shouldRecreateChat =\n ('chat' in options && options.chat !== chatRef.current) ||\n ('id' in options && chatRef.current.id !== options.id);\n\n if (shouldRecreateChat) {\n chatRef.current = 'chat' in options ? options.chat : new Chat(options);\n }\n\n const subscribeToMessages = useCallback(\n (update: () => void) =>\n chatRef.current['~registerMessagesCallback'](update, throttleWaitMs),\n // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [throttleWaitMs, chatRef.current.id],\n );\n\n const messages = useSyncExternalStore(\n subscribeToMessages,\n () => chatRef.current.messages,\n () => chatRef.current.messages,\n );\n\n const status = useSyncExternalStore(\n chatRef.current['~registerStatusCallback'],\n () => chatRef.current.status,\n () => chatRef.current.status,\n );\n\n const error = useSyncExternalStore(\n chatRef.current['~registerErrorCallback'],\n () => chatRef.current.error,\n () => chatRef.current.error,\n );\n\n const setMessages = useCallback(\n (\n messagesParam: UI_MESSAGE[] | ((messages: UI_MESSAGE[]) => UI_MESSAGE[]),\n ) => {\n if (typeof messagesParam === 'function') {\n messagesParam = messagesParam(chatRef.current.messages);\n }\n chatRef.current.messages = messagesParam;\n },\n [chatRef],\n );\n\n useEffect(() => {\n if (resume) {\n chatRef.current.resumeStream();\n }\n }, [resume, chatRef]);\n\n return {\n id: chatRef.current.id,\n messages,\n setMessages,\n sendMessage: chatRef.current.sendMessage,\n regenerate: chatRef.current.regenerate,\n clearError: chatRef.current.clearError,\n stop: chatRef.current.stop,\n error,\n resumeStream: chatRef.current.resumeStream,\n status,\n /**\n * @deprecated Use `addToolOutput` instead.\n */\n addToolResult: chatRef.current.addToolOutput,\n addToolOutput: chatRef.current.addToolOutput,\n addToolApprovalResponse: chatRef.current.addToolApprovalResponse,\n };\n}\n","import { AbstractChat, ChatInit, ChatState, ChatStatus, UIMessage } from 'ai';\nimport { throttle } from './throttle';\n\nclass ReactChatState<UI_MESSAGE extends UIMessage>\n implements ChatState<UI_MESSAGE>\n{\n #messages: UI_MESSAGE[];\n #status: ChatStatus = 'ready';\n #error: Error | undefined = undefined;\n\n #messagesCallbacks = new Set<() => void>();\n #statusCallbacks = new Set<() => void>();\n #errorCallbacks = new Set<() => void>();\n\n constructor(initialMessages: UI_MESSAGE[] = []) {\n this.#messages = initialMessages;\n }\n\n get status(): ChatStatus {\n return this.#status;\n }\n\n set status(newStatus: ChatStatus) {\n this.#status = newStatus;\n this.#callStatusCallbacks();\n }\n\n get error(): Error | undefined {\n return this.#error;\n }\n\n set error(newError: Error | undefined) {\n this.#error = newError;\n this.#callErrorCallbacks();\n }\n\n get messages(): UI_MESSAGE[] {\n return this.#messages;\n }\n\n set messages(newMessages: UI_MESSAGE[]) {\n this.#messages = [...newMessages];\n this.#callMessagesCallbacks();\n }\n\n pushMessage = (message: UI_MESSAGE) => {\n this.#messages = this.#messages.concat(message);\n this.#callMessagesCallbacks();\n };\n\n popMessage = () => {\n this.#messages = this.#messages.slice(0, -1);\n this.#callMessagesCallbacks();\n };\n\n replaceMessage = (index: number, message: UI_MESSAGE) => {\n this.#messages = [\n ...this.#messages.slice(0, index),\n // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:\n this.snapshot(message),\n ...this.#messages.slice(index + 1),\n ];\n this.#callMessagesCallbacks();\n };\n\n snapshot = <T>(value: T): T => structuredClone(value);\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) => {\n const callback = throttleWaitMs\n ? throttle(onChange, throttleWaitMs)\n : onChange;\n this.#messagesCallbacks.add(callback);\n return () => {\n this.#messagesCallbacks.delete(callback);\n };\n };\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) => {\n this.#statusCallbacks.add(onChange);\n return () => {\n this.#statusCallbacks.delete(onChange);\n };\n };\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) => {\n this.#errorCallbacks.add(onChange);\n return () => {\n this.#errorCallbacks.delete(onChange);\n };\n };\n\n #callMessagesCallbacks = () => {\n this.#messagesCallbacks.forEach(callback => callback());\n };\n\n #callStatusCallbacks = () => {\n this.#statusCallbacks.forEach(callback => callback());\n };\n\n #callErrorCallbacks = () => {\n this.#errorCallbacks.forEach(callback => callback());\n };\n}\n\nexport class Chat<\n UI_MESSAGE extends UIMessage,\n> extends AbstractChat<UI_MESSAGE> {\n #state: ReactChatState<UI_MESSAGE>;\n\n constructor({ messages, ...init }: ChatInit<UI_MESSAGE>) {\n const state = new ReactChatState(messages);\n super({ ...init, state });\n this.#state = state;\n }\n\n '~registerMessagesCallback' = (\n onChange: () => void,\n throttleWaitMs?: number,\n ): (() => void) =>\n this.#state['~registerMessagesCallback'](onChange, throttleWaitMs);\n\n '~registerStatusCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerStatusCallback'](onChange);\n\n '~registerErrorCallback' = (onChange: () => void): (() => void) =>\n this.#state['~registerErrorCallback'](onChange);\n}\n","import throttleFunction from 'throttleit';\n\nexport function throttle<T extends (...args: any[]) => any>(\n fn: T,\n waitMs: number | undefined,\n): T {\n return waitMs != null ? throttleFunction(fn, waitMs) : fn;\n}\n","import {\n CompletionRequestOptions,\n UseCompletionOptions,\n callCompletionApi,\n} from 'ai';\nimport { useCallback, useEffect, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\nimport { throttle } from './throttle';\n\nexport type { UseCompletionOptions };\n\nexport type UseCompletionHelpers = {\n /** The current completion result */\n completion: string;\n /**\n * Send a new prompt to the API endpoint and update the completion state.\n */\n complete: (\n prompt: string,\n options?: CompletionRequestOptions,\n ) => Promise<string | null | undefined>;\n /** The error object of the API request */\n error: undefined | Error;\n /**\n * Abort the current API request but keep the generated tokens.\n */\n stop: () => void;\n /**\n * Update the `completion` state locally.\n */\n setCompletion: (completion: string) => void;\n /** The current value of the input */\n input: string;\n /** setState-powered method to update the input value */\n setInput: React.Dispatch<React.SetStateAction<string>>;\n /**\n * An input/textarea-ready onChange handler to control the value of the input\n * @example\n * ```jsx\n * <input onChange={handleInputChange} value={input} />\n * ```\n */\n handleInputChange: (\n event:\n | React.ChangeEvent<HTMLInputElement>\n | React.ChangeEvent<HTMLTextAreaElement>,\n ) => void;\n\n /**\n * Form submission handler to automatically reset input and append a user message\n * @example\n * ```jsx\n * <form onSubmit={handleSubmit}>\n * <input onChange={handleInputChange} value={input} />\n * </form>\n * ```\n */\n handleSubmit: (event?: { preventDefault?: () => void }) => void;\n\n /** Whether the API request is in progress */\n isLoading: boolean;\n};\n\nexport function useCompletion({\n api = '/api/completion',\n id,\n initialCompletion = '',\n initialInput = '',\n credentials,\n headers,\n body,\n streamProtocol = 'data',\n fetch,\n onFinish,\n onError,\n experimental_throttle: throttleWaitMs,\n}: UseCompletionOptions & {\n /**\n * Custom throttle wait in ms for the completion and data updates.\n * Default is undefined, which disables throttling.\n */\n experimental_throttle?: number;\n} = {}): UseCompletionHelpers {\n // Generate an unique id for the completion if not provided.\n const hookId = useId();\n const completionId = id || hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<string>([api, completionId], null, {\n fallbackData: initialCompletion,\n });\n\n const { data: isLoading = false, mutate: mutateLoading } = useSWR<boolean>(\n [completionId, 'loading'],\n null,\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const completion = data!;\n\n // Abort controller to cancel the current API call.\n const [abortController, setAbortController] =\n useState<AbortController | null>(null);\n\n const extraMetadataRef = useRef({\n credentials,\n headers,\n body,\n });\n\n useEffect(() => {\n extraMetadataRef.current = {\n credentials,\n headers,\n body,\n };\n }, [credentials, headers, body]);\n\n const triggerRequest = useCallback(\n async (prompt: string, options?: CompletionRequestOptions) =>\n callCompletionApi({\n api,\n prompt,\n credentials: extraMetadataRef.current.credentials,\n headers: { ...extraMetadataRef.current.headers, ...options?.headers },\n body: {\n ...extraMetadataRef.current.body,\n ...options?.body,\n },\n streamProtocol,\n fetch,\n // throttle streamed ui updates:\n setCompletion: throttle(\n (completion: string) => mutate(completion, false),\n throttleWaitMs,\n ),\n setLoading: mutateLoading,\n setError,\n setAbortController,\n onFinish,\n onError,\n }),\n [\n mutate,\n mutateLoading,\n api,\n extraMetadataRef,\n setAbortController,\n onFinish,\n onError,\n setError,\n streamProtocol,\n fetch,\n throttleWaitMs,\n ],\n );\n\n const stop = useCallback(() => {\n if (abortController) {\n abortController.abort();\n setAbortController(null);\n }\n }, [abortController]);\n\n const setCompletion = useCallback(\n (completion: string) => {\n mutate(completion, false);\n },\n [mutate],\n );\n\n const complete = useCallback<UseCompletionHelpers['complete']>(\n async (prompt, options) => {\n return triggerRequest(prompt, options);\n },\n [triggerRequest],\n );\n\n const [input, setInput] = useState(initialInput);\n\n const handleSubmit = useCallback(\n (event?: { preventDefault?: () => void }) => {\n event?.preventDefault?.();\n return input ? complete(input) : undefined;\n },\n [input, complete],\n );\n\n const handleInputChange = useCallback(\n (e: any) => {\n setInput(e.target.value);\n },\n [setInput],\n );\n\n return {\n completion,\n complete,\n error,\n setCompletion,\n stop,\n input,\n setInput,\n handleInputChange,\n handleSubmit,\n isLoading,\n };\n}\n","import {\n FetchFunction,\n FlexibleSchema,\n InferSchema,\n isAbortError,\n safeValidateTypes,\n} from '@ai-sdk/provider-utils';\nimport { asSchema, DeepPartial, isDeepEqualData, parsePartialJson } from 'ai';\nimport { useCallback, useId, useRef, useState } from 'react';\nimport useSWR from 'swr';\n\n// use function to allow for mocking in tests:\nconst getOriginalFetch = () => fetch;\n\nexport type Experimental_UseObjectOptions<\n SCHEMA extends FlexibleSchema,\n RESULT,\n> = {\n /**\n * The API endpoint. It should stream JSON that matches the schema as chunked text.\n */\n api: string;\n\n /**\n * A schema that defines the shape of the complete object.\n */\n schema: SCHEMA;\n\n /**\n * An unique identifier. If not provided, a random one will be\n * generated. When provided, the `useObject` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * An optional value for the initial object.\n */\n initialValue?: DeepPartial<RESULT>;\n\n /**\nCustom fetch implementation. You can use it as a middleware to intercept requests,\nor to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\nCallback that is called when the stream has finished.\n */\n onFinish?: (event: {\n /**\nThe generated object (typed according to the schema).\nCan be undefined if the final object does not match the schema.\n */\n object: RESULT | undefined;\n\n /**\nOptional error object. This is e.g. a TypeValidationError when the final object does not match the schema.\n */\n error: Error | undefined;\n }) => Promise<void> | void;\n\n /**\n * Callback function to be called when an error is encountered.\n */\n onError?: (error: Error) => void;\n\n /**\n * Additional HTTP headers to be included in the request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * The credentials mode to be used for the fetch request.\n * Possible values are: 'omit', 'same-origin', 'include'.\n * Defaults to 'same-origin'.\n */\n credentials?: RequestCredentials;\n};\n\nexport type Experimental_UseObjectHelpers<RESULT, INPUT> = {\n /**\n * Calls the API with the provided input as JSON body.\n */\n submit: (input: INPUT) => void;\n\n /**\n * The current value for the generated object. Updated as the API streams JSON chunks.\n */\n object: DeepPartial<RESULT> | undefined;\n\n /**\n * The error object of the API request if any.\n */\n error: Error | undefined;\n\n /**\n * Flag that indicates whether an API request is in progress.\n */\n isLoading: boolean;\n\n /**\n * Abort the current request immediately, keep the current partial object if any.\n */\n stop: () => void;\n\n /**\n * Clear the object state.\n */\n clear: () => void;\n};\n\nfunction useObject<\n SCHEMA extends FlexibleSchema,\n RESULT = InferSchema<SCHEMA>,\n INPUT = any,\n>({\n api,\n id,\n schema, // required, in the future we will use it for validation\n initialValue,\n fetch,\n onError,\n onFinish,\n headers,\n credentials,\n}: Experimental_UseObjectOptions<\n SCHEMA,\n RESULT\n>): Experimental_UseObjectHelpers<RESULT, INPUT> {\n // Generate an unique id if not provided.\n const hookId = useId();\n const completionId = id ?? hookId;\n\n // Store the completion state in SWR, using the completionId as the key to share states.\n const { data, mutate } = useSWR<DeepPartial<RESULT>>(\n [api, completionId],\n null,\n { fallbackData: initialValue },\n );\n\n const [error, setError] = useState<undefined | Error>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n\n // Abort controller to cancel the current API call.\n const abortControllerRef = useRef<AbortController | null>(null);\n\n const stop = useCallback(() => {\n try {\n abortControllerRef.current?.abort();\n } catch (ignored) {\n } finally {\n setIsLoading(false);\n abortControllerRef.current = null;\n }\n }, []);\n\n const submit = async (input: INPUT) => {\n try {\n clearObject();\n\n setIsLoading(true);\n\n const abortController = new AbortController();\n abortControllerRef.current = abortController;\n\n const actualFetch = fetch ?? getOriginalFetch();\n const response = await actualFetch(api, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n credentials,\n signal: abortController.signal,\n body: JSON.stringify(input),\n });\n\n if (!response.ok) {\n throw new Error(\n (await response.text()) ?? 'Failed to fetch the response.',\n );\n }\n\n if (response.body == null) {\n throw new Error('The response body is empty.');\n }\n\n let accumulatedText = '';\n let latestObject: DeepPartial<RESULT> | undefined = undefined;\n\n await response.body.pipeThrough(new TextDecoderStream()).pipeTo(\n new WritableStream<string>({\n async write(chunk) {\n accumulatedText += chunk;\n\n const { value } = await parsePartialJson(accumulatedText);\n const currentObject = value as DeepPartial<RESULT>;\n\n if (!isDeepEqualData(latestObject, currentObject)) {\n latestObject = currentObject;\n\n mutate(currentObject);\n }\n },\n\n async close() {\n setIsLoading(false);\n abortControllerRef.current = null;\n\n if (onFinish != null) {\n const validationResult = await safeValidateTypes({\n value: latestObject,\n schema: asSchema(schema),\n });\n\n onFinish(\n validationResult.success\n ? { object: validationResult.value, error: undefined }\n : { object: undefined, error: validationResult.error },\n );\n }\n },\n }),\n );\n } catch (error) {\n if (isAbortError(error)) {\n return;\n }\n\n if (onError && error instanceof Error) {\n onError(error);\n }\n\n setIsLoading(false);\n setError(error instanceof Error ? error : new Error(String(error)));\n }\n };\n\n const clear = () => {\n stop();\n clearObject();\n };\n\n const clearObject = () => {\n setError(undefined);\n setIsLoading(false);\n mutate(undefined);\n };\n\n return {\n submit,\n object: data,\n error,\n isLoading,\n stop,\n clear,\n };\n}\n\nexport const experimental_useObject = useObject;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAMA,SAAS,aAAa,WAAW,QAAQ,4BAA4B;;;ACNrE,SAAS,oBAAgE;;;ACAzE,OAAO,sBAAsB;AAEtB,SAAS,SACd,IACA,QACG;AACH,SAAO,UAAU,OAAO,iBAAiB,IAAI,MAAM,IAAI;AACzD;;;ADPA;AAGA,IAAM,iBAAN,MAEA;AAAA,EASE,YAAY,kBAAgC,CAAC,GAAG;AARhD;AACA,gCAAsB;AACtB,+BAA4B;AAE5B,2CAA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,IAAI,MAAM,OAAOA,MAAK,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,QAAM,QAAQ,MAAM;AAClB,SAAK;AACL,gBAAY;AAAA,EACd;AAEA,QAAM,cAAc,MAAM;AACxB,aAAS,MAAS;AAClB,iBAAa,KAAK;AAClB,WAAO,MAAS;AAAA,EAClB;AAEA,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,yBAAyB;","names":["useCallback","useEffect","useRef","fetch","useRef","useEffect","useCallback","completion","useCallback","useId","useRef","useState","useSWR","fetch","error"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/react",
3
- "version": "3.0.0-beta.99",
3
+ "version": "3.0.0",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/index.js",
@@ -22,8 +22,8 @@
22
22
  "dependencies": {
23
23
  "swr": "^2.2.5",
24
24
  "throttleit": "2.1.0",
25
- "@ai-sdk/provider-utils": "4.0.0-beta.33",
26
- "ai": "6.0.0-beta.99"
25
+ "@ai-sdk/provider-utils": "4.0.0",
26
+ "ai": "6.0.0"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@testing-library/jest-dom": "^6.6.3",
@@ -35,16 +35,16 @@
35
35
  "eslint": "8.57.1",
36
36
  "jsdom": "^24.0.0",
37
37
  "msw": "2.6.4",
38
- "react-dom": "^18 || ^19 || ^19.0.0-rc",
38
+ "react-dom": "^18 || ^19",
39
39
  "tsup": "^7.2.0",
40
40
  "typescript": "5.8.3",
41
41
  "zod": "3.25.76",
42
- "@ai-sdk/test-server": "1.0.0-beta.1",
42
+ "@ai-sdk/test-server": "1.0.0",
43
43
  "@vercel/ai-tsconfig": "0.0.0",
44
44
  "eslint-config-vercel-ai": "0.0.0"
45
45
  },
46
46
  "peerDependencies": {
47
- "react": "^18 || ^19 || ^19.0.0-rc"
47
+ "react": "^18 || ~19.0.1 || ~19.1.2 || ^19.2.1"
48
48
  },
49
49
  "engines": {
50
50
  "node": ">=18"