@copilotkit/react-native 2.0.0-rc.4 → 2.0.0-rc.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +334 -2
  2. package/USAGE.md +382 -21
  3. package/dist/CopilotKitProvider-Cbfrm_7u.d.mts +65 -0
  4. package/dist/{CopilotKitProvider-Byw3cqe2.cjs → CopilotKitProvider-CvJYytjn.cjs} +56 -42
  5. package/dist/CopilotKitProvider-CvJYytjn.cjs.map +1 -0
  6. package/dist/CopilotKitProvider-Dv3ISMKf.d.cts +65 -0
  7. package/dist/{CopilotKitProvider-CE4bc6CP.mjs → CopilotKitProvider-oTdmylSY.mjs} +55 -42
  8. package/dist/CopilotKitProvider-oTdmylSY.mjs.map +1 -0
  9. package/dist/{Markdown-C_9Re36O.cjs → Markdown-DLopAh5W.cjs} +10 -10
  10. package/dist/Markdown-DLopAh5W.cjs.map +1 -0
  11. package/dist/{Markdown-JsYh7oSA.d.mts → Markdown-Du-b_Qpr.d.mts} +3 -3
  12. package/dist/{Markdown-1ips7myr.d.cts → Markdown-UXZdDjzs.d.cts} +3 -3
  13. package/dist/{Markdown-C6AsLHmd.mjs → Markdown-VxtPJ_yh.mjs} +4 -4
  14. package/dist/Markdown-VxtPJ_yh.mjs.map +1 -0
  15. package/dist/{MarkdownRendererContext-CAnuohIS.mjs → MarkdownRendererContext-EobUsERg.mjs} +1 -1
  16. package/dist/{MarkdownRendererContext-CAnuohIS.mjs.map → MarkdownRendererContext-EobUsERg.mjs.map} +1 -1
  17. package/dist/MarkdownRendererContext-cDEHvbw9.cjs +40 -0
  18. package/dist/{MarkdownRendererContext-BRNe808d.cjs.map → MarkdownRendererContext-cDEHvbw9.cjs.map} +1 -1
  19. package/dist/chunk-C0xms8kb.cjs +34 -0
  20. package/dist/components/index.cjs +78 -175
  21. package/dist/components/index.cjs.map +1 -1
  22. package/dist/components/index.d.cts +2 -2
  23. package/dist/components/index.d.mts +2 -2
  24. package/dist/components/index.mjs +76 -174
  25. package/dist/components/index.mjs.map +1 -1
  26. package/dist/generative-ui/index.cjs +612 -0
  27. package/dist/generative-ui/index.cjs.map +1 -0
  28. package/dist/generative-ui/index.d.cts +341 -0
  29. package/dist/generative-ui/index.d.mts +341 -0
  30. package/dist/generative-ui/index.mjs +549 -0
  31. package/dist/generative-ui/index.mjs.map +1 -0
  32. package/dist/headless.cjs +2 -2
  33. package/dist/headless.d.cts +2 -2
  34. package/dist/headless.d.mts +2 -2
  35. package/dist/headless.mjs +1 -1
  36. package/dist/index.cjs +131 -162
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +36 -18
  39. package/dist/index.d.mts +36 -18
  40. package/dist/index.mjs +130 -161
  41. package/dist/index.mjs.map +1 -1
  42. package/dist/polyfills/encoding.cjs +115 -5
  43. package/dist/polyfills/encoding.cjs.map +1 -1
  44. package/dist/polyfills/encoding.d.cts +31 -1
  45. package/dist/polyfills/encoding.d.mts +31 -1
  46. package/dist/polyfills/encoding.mjs +113 -6
  47. package/dist/polyfills/encoding.mjs.map +1 -1
  48. package/dist/polyfills/streams.cjs +1 -1
  49. package/dist/polyfills.cjs +218 -2
  50. package/dist/polyfills.cjs.map +1 -1
  51. package/dist/polyfills.mjs +217 -1
  52. package/dist/polyfills.mjs.map +1 -1
  53. package/package.json +51 -21
  54. package/project.json +6 -1
  55. package/scripts/__tests__/verify-polyfill-barrel.test.mjs +150 -0
  56. package/scripts/verify-polyfill-barrel.mjs +158 -11
  57. package/src/CopilotChat.tsx +114 -93
  58. package/src/CopilotKitProvider.tsx +87 -130
  59. package/src/CopilotPopup.tsx +2 -2
  60. package/src/CopilotSidebar.tsx +7 -5
  61. package/src/__mocks__/react-native.ts +31 -0
  62. package/src/__mocks__/test-copilotkit.tsx +9 -3
  63. package/src/__tests__/attachments-integration.test.tsx +15 -2
  64. package/src/__tests__/copilot-chat-agentid.test.tsx +15 -2
  65. package/src/__tests__/copilot-chat-attachments.test.tsx +15 -2
  66. package/src/__tests__/copilot-chat-configuration.test.tsx +82 -0
  67. package/src/__tests__/copilot-chat-threads.test.tsx +232 -0
  68. package/src/__tests__/copilot-popup.test.tsx +15 -2
  69. package/src/__tests__/copilot-sidebar.test.tsx +15 -2
  70. package/src/__tests__/copilotkit-provider.test.tsx +68 -73
  71. package/src/__tests__/generative-ui-harness.tsx +243 -0
  72. package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
  73. package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
  74. package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
  75. package/src/__tests__/generative-ui.test.tsx +1000 -0
  76. package/src/__tests__/headless-entry-surface.test.ts +979 -60
  77. package/src/__tests__/headless-integration.test.tsx +11 -1
  78. package/src/__tests__/use-attachments.test.ts +27 -2
  79. package/src/components/CopilotChat.tsx +106 -233
  80. package/src/components/CopilotModal.tsx +1 -1
  81. package/src/components/Markdown.tsx +4 -4
  82. package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -1
  83. package/src/components/__tests__/CopilotChat.test.tsx +12 -4
  84. package/src/components/__tests__/CopilotChatInterrupt.test.tsx +208 -0
  85. package/src/components/__tests__/Markdown.code-alias.test.tsx +1 -1
  86. package/src/components/index.ts +6 -0
  87. package/src/components/messages/AssistantMessage.tsx +3 -3
  88. package/src/components/messages/TypingIndicator.tsx +4 -4
  89. package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
  90. package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
  91. package/src/generative-ui/GenerativeUISurface.tsx +303 -0
  92. package/src/generative-ui/host.tsx +138 -0
  93. package/src/generative-ui/index.ts +93 -0
  94. package/src/generative-ui/internal.ts +55 -0
  95. package/src/hooks/use-attachments.ts +95 -139
  96. package/src/index.ts +8 -3
  97. package/src/polyfills/__tests__/encoding-utf8.test.ts +112 -0
  98. package/src/polyfills/encoding.ts +160 -4
  99. package/src/types.d.ts +0 -13
  100. package/tsdown.config.ts +1 -0
  101. package/dist/CopilotKitProvider-BWjzCdHN.d.mts +0 -121
  102. package/dist/CopilotKitProvider-Btm10msB.d.cts +0 -121
  103. package/dist/CopilotKitProvider-Byw3cqe2.cjs.map +0 -1
  104. package/dist/CopilotKitProvider-CE4bc6CP.mjs.map +0 -1
  105. package/dist/Markdown-C6AsLHmd.mjs.map +0 -1
  106. package/dist/Markdown-C_9Re36O.cjs.map +0 -1
  107. package/dist/MarkdownRendererContext-BRNe808d.cjs +0 -72
  108. package/dist/streaming-fetch-Bm91EsRc.cjs +0 -225
  109. package/dist/streaming-fetch-Bm91EsRc.cjs.map +0 -1
  110. package/dist/streaming-fetch-Dm1oN4f2.mjs +0 -219
  111. package/dist/streaming-fetch-Dm1oN4f2.mjs.map +0 -1
@@ -1,12 +1,9 @@
1
1
  // packages/react-native/src/hooks/use-attachments.ts
2
- import { useCallback, useRef, useState } from "react";
3
- import {
4
- randomUUID,
5
- getModalityFromMimeType,
6
- formatFileSize,
7
- } from "@copilotkit/shared";
2
+ import { useCallback, useRef, useState, useSyncExternalStore } from "react";
3
+ import { ɵAttachmentQueue } from "@copilotkit/core";
8
4
  import type {
9
5
  Attachment,
6
+ AttachmentsConfig,
10
7
  AttachmentUploadResult,
11
8
  AttachmentUploadErrorReason,
12
9
  } from "@copilotkit/shared";
@@ -76,10 +73,77 @@ export interface UseNativeAttachmentsReturn {
76
73
  }
77
74
 
78
75
  // ---------------------------------------------------------------------------
79
- // Constants
76
+ // Queue adapter
80
77
  // ---------------------------------------------------------------------------
81
78
 
82
- const DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB
79
+ /**
80
+ * The queue's view of a picked file: the `name`, `size` and `type` it reads to
81
+ * validate the file and to draw its placeholder.
82
+ */
83
+ interface QueuedNativeFile {
84
+ name: string;
85
+ size: number;
86
+ type: string;
87
+ }
88
+
89
+ // The native descriptor behind each file the queue holds, so the app's
90
+ // callbacks get the `NativeFileInput` they were typed for.
91
+ const nativeFiles = new WeakMap<object, NativeFileInput>();
92
+
93
+ /**
94
+ * Wraps a native file for core's `ɵAttachmentQueue`, which is typed for the
95
+ * web `File`. The queue reads only `name`, `size` and `type`, because the
96
+ * config from {@link toQueueConfig} always uploads through `onUpload` and the
97
+ * queue never reads the bytes itself.
98
+ */
99
+ function toQueueFile(file: NativeFileInput) {
100
+ const queued: QueuedNativeFile = {
101
+ name: file.name,
102
+ size: file.size,
103
+ type: file.mimeType,
104
+ };
105
+ nativeFiles.set(queued, file);
106
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the queue is typed for the web File; it only reads name, size and type, and uploads go through onUpload with the native file
107
+ return queued as unknown as File;
108
+ }
109
+
110
+ function toNativeFile(file: File) {
111
+ const native = nativeFiles.get(file);
112
+ if (!native) {
113
+ throw new Error(`[CopilotKit] "${file.name}" was not picked natively`);
114
+ }
115
+ return native;
116
+ }
117
+
118
+ /** Reads a picked file as base64 with expo-file-system. */
119
+ async function readNativeFile(file: NativeFileInput) {
120
+ const value = await FileSystem.readAsStringAsync(file.uri, {
121
+ encoding: FileSystem.EncodingType.Base64,
122
+ });
123
+ return { type: "data" as const, value, mimeType: file.mimeType };
124
+ }
125
+
126
+ /**
127
+ * The RN config as core's queue takes it. Uploads go through the app's
128
+ * `onUpload`, or through expo-file-system when there is none.
129
+ */
130
+ function toQueueConfig(
131
+ config: NativeAttachmentsConfig | undefined,
132
+ ): AttachmentsConfig | undefined {
133
+ if (!config) return undefined;
134
+ const { onUpload, onUploadFailed, ...rest } = config;
135
+ return {
136
+ ...rest,
137
+ onUpload: (file) => {
138
+ const native = toNativeFile(file);
139
+ return onUpload ? onUpload(native) : readNativeFile(native);
140
+ },
141
+ onUploadFailed: onUploadFailed
142
+ ? ({ file, ...error }) =>
143
+ onUploadFailed({ ...error, file: toNativeFile(file) })
144
+ : undefined,
145
+ };
146
+ }
83
147
 
84
148
  // ---------------------------------------------------------------------------
85
149
  // Hook
@@ -87,142 +151,38 @@ const DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB
87
151
 
88
152
  /**
89
153
  * React Native hook that manages file attachment state -- picking, uploading,
90
- * and lifecycle. All returned callbacks are referentially stable via useCallback.
154
+ * and lifecycle. All returned callbacks are referentially stable.
91
155
  *
92
- * This is the RN counterpart of the web `useAttachments` hook from
93
- * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,
94
- * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).
156
+ * The queue itself (accept filter, size check, uploads, ready state) is
157
+ * `@copilotkit/core`'s `ɵAttachmentQueue`, shared with the web chats. This
158
+ * hook adds the native glue: expo-document-picker to pick files and
159
+ * expo-file-system to read them.
95
160
  */
96
161
  export function useAttachments({
97
162
  config,
98
163
  }: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {
99
164
  const enabled = config?.enabled ?? false;
100
165
 
101
- const [attachments, setAttachments] = useState<Attachment[]>([]);
102
-
103
- // Refs for stable callbacks to read latest values
166
+ // The queue reads the latest config on every action.
104
167
  const configRef = useRef(config);
105
168
  configRef.current = config;
106
- const attachmentsRef = useRef<Attachment[]>([]);
107
- attachmentsRef.current = attachments;
108
169
 
109
- /**
110
- * Simple MIME accept filter for NativeFileInput.
111
- * Handles wildcards like "image/*" and exact types like "application/pdf".
112
- * Comma-separated lists are supported.
113
- */
114
- const matchesAccept = useCallback(
115
- (file: NativeFileInput, accept: string): boolean => {
116
- if (!accept || accept === "*/*") return true;
117
- const filters = accept.split(",").map((f) => f.trim());
118
- return filters.some((filter) => {
119
- if (filter.startsWith(".")) {
120
- return file.name.toLowerCase().endsWith(filter.toLowerCase());
121
- }
122
- if (filter.endsWith("/*")) {
123
- const prefix = filter.slice(0, -2);
124
- return file.mimeType.startsWith(prefix + "/");
125
- }
126
- return file.mimeType === filter;
127
- });
128
- },
129
- [],
170
+ const [queue] = useState(
171
+ () => new ɵAttachmentQueue(() => toQueueConfig(configRef.current)),
172
+ );
173
+ const attachments = useSyncExternalStore(
174
+ useCallback((onChange) => queue.subscribe(onChange), [queue]),
175
+ () => queue.getSnapshot(),
176
+ () => queue.getSnapshot(),
130
177
  );
131
178
 
132
179
  const processFiles = useCallback(
133
- async (files: NativeFileInput[]) => {
134
- const cfg = configRef.current;
135
- const accept = cfg?.accept ?? "*/*";
136
- const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;
137
-
138
- // Filter by accept type
139
- const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));
140
- for (const file of rejectedFiles) {
141
- cfg?.onUploadFailed?.({
142
- reason: "invalid-type",
143
- file,
144
- message: `File "${file.name}" is not accepted. Supported types: ${accept}`,
145
- });
146
- }
147
-
148
- const validFiles = files.filter((f) => matchesAccept(f, accept));
149
-
150
- for (const file of validFiles) {
151
- // Size check
152
- if (file.size > maxSize) {
153
- cfg?.onUploadFailed?.({
154
- reason: "file-too-large",
155
- file,
156
- message: `File "${file.name}" exceeds the maximum size of ${formatFileSize(maxSize)}`,
157
- });
158
- continue;
159
- }
160
-
161
- const modality = getModalityFromMimeType(file.mimeType);
162
- const placeholderId = randomUUID();
163
- const placeholder: Attachment = {
164
- id: placeholderId,
165
- type: modality,
166
- source: { type: "data", value: "", mimeType: file.mimeType },
167
- filename: file.name,
168
- size: file.size,
169
- status: "uploading",
170
- };
171
-
172
- setAttachments((prev) => [...prev, placeholder]);
173
-
174
- try {
175
- let source: Attachment["source"];
176
- let uploadMetadata: Record<string, unknown> | undefined;
177
-
178
- if (cfg?.onUpload) {
179
- const { metadata: meta, ...uploadSource } =
180
- await cfg.onUpload(file);
181
- source = uploadSource;
182
- uploadMetadata = meta;
183
- } else {
184
- // Default: read file as base64 via expo-file-system
185
- const base64 = await FileSystem.readAsStringAsync(file.uri, {
186
- encoding: FileSystem.EncodingType.Base64,
187
- });
188
- source = { type: "data", value: base64, mimeType: file.mimeType };
189
- }
190
-
191
- setAttachments((prev) =>
192
- prev.map((att) =>
193
- att.id === placeholderId
194
- ? {
195
- ...att,
196
- source,
197
- status: "ready" as const,
198
- metadata: uploadMetadata,
199
- }
200
- : att,
201
- ),
202
- );
203
- } catch (error) {
204
- // Remove placeholder on failure
205
- setAttachments((prev) =>
206
- prev.filter((att) => att.id !== placeholderId),
207
- );
208
- console.error(`[CopilotKit] Failed to upload "${file.name}":`, error);
209
- cfg?.onUploadFailed?.({
210
- reason: "upload-failed",
211
- file,
212
- message:
213
- error instanceof Error
214
- ? error.message
215
- : `Failed to upload "${file.name}"`,
216
- });
217
- }
218
- }
219
- },
220
- [matchesAccept],
180
+ (files: NativeFileInput[]) => queue.processFiles(files.map(toQueueFile)),
181
+ [queue],
221
182
  );
222
183
 
223
184
  const openPicker = useCallback(async () => {
224
- const cfg = configRef.current;
225
- const accept = cfg?.accept ?? "*/*";
185
+ const accept = configRef.current?.accept ?? "*/*";
226
186
 
227
187
  // Convert accept string to array for DocumentPicker
228
188
  const typeArray = accept
@@ -239,29 +199,25 @@ export function useAttachments({
239
199
 
240
200
  if (result.canceled || !result.assets?.length) return;
241
201
 
242
- const nativeFiles: NativeFileInput[] = result.assets.map((asset) => ({
202
+ const pickedFiles: NativeFileInput[] = result.assets.map((asset) => ({
243
203
  uri: asset.uri,
244
204
  name: asset.name ?? "unknown",
245
205
  size: asset.size ?? 0,
246
206
  mimeType: asset.mimeType ?? "application/octet-stream",
247
207
  }));
248
208
 
249
- await processFiles(nativeFiles);
209
+ await processFiles(pickedFiles);
250
210
  } catch (error) {
251
211
  console.error("[CopilotKit] Document picker error:", error);
252
212
  }
253
213
  }, [processFiles]);
254
214
 
255
- const removeAttachment = useCallback((id: string) => {
256
- setAttachments((prev) => prev.filter((a) => a.id !== id));
257
- }, []);
215
+ const removeAttachment = useCallback(
216
+ (id: string) => queue.remove(id),
217
+ [queue],
218
+ );
258
219
 
259
- const consumeAttachments = useCallback(() => {
260
- const ready = attachmentsRef.current.filter((a) => a.status === "ready");
261
- if (ready.length === 0) return ready;
262
- setAttachments((prev) => prev.filter((a) => a.status !== "ready"));
263
- return ready;
264
- }, []);
220
+ const consumeAttachments = useCallback(() => queue.consumeReady(), [queue]);
265
221
 
266
222
  return {
267
223
  attachments,
package/src/index.ts CHANGED
@@ -14,9 +14,14 @@
14
14
  * ```
15
15
  */
16
16
 
17
- // Headless surface: provider + platform-agnostic hooks + core/AG-UI types.
18
- // This also side-effect-imports "./polyfills" (as its first statement), so the
19
- // polyfills install before any chat-UI module below is evaluated. The prebuilt
17
+ // Auto-install polyfills before anything else loads. "./headless" imports them
18
+ // too, but the bundler hoists the provider chunk it shares with "./headless"
19
+ // above that re-export, so the built entry would load @copilotkit/react-core
20
+ // first. Importing them here, first, is what keeps them first in dist/
21
+ // (scripts/verify-polyfill-barrel.mjs checks it).
22
+ import "./polyfills";
23
+
24
+ // Headless surface: provider + platform-agnostic hooks + core/AG-UI types. The prebuilt
20
25
  // chat components + useAttachments are layered on top here; consumers who don't
21
26
  // need them (and want to skip the @gorhom/bottom-sheet + expo-* native deps)
22
27
  // can import from "@copilotkit/react-native/headless" instead.
@@ -0,0 +1,112 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { Utf8TextDecoder, Utf8TextEncoder } from "../encoding";
3
+
4
+ // Node's built-in classes are the reference: the polyfill must give the same
5
+ // output on the runtimes that lack them.
6
+ const NativeEncoder = globalThis.TextEncoder;
7
+ const NativeDecoder = globalThis.TextDecoder;
8
+
9
+ const strings = [
10
+ "",
11
+ "hello",
12
+ "Grüße, 東京, emoji 🚀🧪",
13
+ "\u0000\u007f\u0080߿ࠀ￿",
14
+ "🚀 pair, \ud800 lone high, \udc00 lone low",
15
+ "starts with a BOM",
16
+ ];
17
+
18
+ const byteSequences: number[][] = [
19
+ [0xe2, 0x82, 0xac],
20
+ [0xc3],
21
+ [0xc0, 0x80],
22
+ [0xed, 0xa0, 0x80],
23
+ [0xf4, 0x90, 0x80, 0x80],
24
+ [0xf0, 0x9f, 0x9a],
25
+ [0xe0, 0x80, 0x41],
26
+ [0x80, 0xbf, 0x41],
27
+ [0xff, 0xfe, 0x41],
28
+ [0xef, 0xbb, 0xbf, 0x41],
29
+ [0xf0, 0x9f, 0x98, 0x80, 0xe2, 0x82],
30
+ ];
31
+
32
+ function splits(bytes: Uint8Array): Uint8Array[][] {
33
+ const out: Uint8Array[][] = [[bytes]];
34
+ for (let at = 0; at <= bytes.length; at++) {
35
+ out.push([bytes.subarray(0, at), bytes.subarray(at)]);
36
+ }
37
+ out.push([...bytes].map((byte) => new Uint8Array([byte])));
38
+ return out;
39
+ }
40
+
41
+ function streamDecode(
42
+ decoder: {
43
+ decode: (input?: Uint8Array, options?: { stream?: boolean }) => string;
44
+ },
45
+ chunks: Uint8Array[],
46
+ ): string {
47
+ return (
48
+ chunks.map((chunk) => decoder.decode(chunk, { stream: true })).join("") +
49
+ decoder.decode()
50
+ );
51
+ }
52
+
53
+ describe("Utf8TextEncoder", () => {
54
+ it.each(strings)("encodes %j like the built-in encoder", (input) => {
55
+ expect([...new Utf8TextEncoder().encode(input)]).toEqual([
56
+ ...new NativeEncoder().encode(input),
57
+ ]);
58
+ });
59
+ });
60
+
61
+ describe("Utf8TextDecoder", () => {
62
+ const inputs = [
63
+ ...strings.map((input) => new NativeEncoder().encode(input)),
64
+ ...byteSequences.map((bytes) => new Uint8Array(bytes)),
65
+ ];
66
+
67
+ it.each(inputs.map((bytes) => [[...bytes].join(","), bytes] as const))(
68
+ "decodes [%s] like the built-in decoder, in every chunk split",
69
+ (_, bytes) => {
70
+ for (const chunks of splits(bytes)) {
71
+ for (const ignoreBOM of [false, true]) {
72
+ expect(
73
+ streamDecode(new Utf8TextDecoder("utf-8", { ignoreBOM }), chunks),
74
+ ).toBe(
75
+ streamDecode(new NativeDecoder("utf-8", { ignoreBOM }), chunks),
76
+ );
77
+ }
78
+ }
79
+ },
80
+ );
81
+
82
+ it("throws on invalid bytes when fatal is set", () => {
83
+ for (const bytes of byteSequences.map((b) => new Uint8Array(b))) {
84
+ const native = () =>
85
+ new NativeDecoder("utf-8", { fatal: true }).decode(bytes);
86
+ const polyfill = () =>
87
+ new Utf8TextDecoder("utf-8", { fatal: true }).decode(bytes);
88
+ let nativeThrew = false;
89
+ try {
90
+ native();
91
+ } catch {
92
+ nativeThrew = true;
93
+ }
94
+ if (nativeThrew) expect(polyfill).toThrow(TypeError);
95
+ else expect(polyfill()).toBe(native());
96
+ }
97
+ });
98
+
99
+ it("decodes an ArrayBuffer and a view into a larger buffer", () => {
100
+ const buffer = new NativeEncoder().encode("xx東京xx").buffer;
101
+ expect(new Utf8TextDecoder().decode(buffer)).toBe("xx東京xx");
102
+ expect(new Utf8TextDecoder().decode(new Uint8Array(buffer, 2, 6))).toBe(
103
+ "東京",
104
+ );
105
+ expect(new Utf8TextDecoder().decode()).toBe("");
106
+ });
107
+
108
+ it("supports only UTF-8", () => {
109
+ expect(new Utf8TextDecoder("UTF8").encoding).toBe("utf-8");
110
+ expect(() => new Utf8TextDecoder("latin1")).toThrow(RangeError);
111
+ });
112
+ });
@@ -1,20 +1,176 @@
1
1
  /**
2
2
  * Polyfill: TextEncoder, TextDecoder
3
3
  *
4
- * Required for stream chunk processing in CopilotKit.
4
+ * Required for stream chunk processing in CopilotKit. The polyfill supports
5
+ * UTF-8, the only encoding that CopilotKit uses.
5
6
  * Skipped if the globals are already defined.
6
7
  *
7
8
  * Usage:
8
9
  * import "@copilotkit/react-native/polyfills/encoding";
9
10
  */
10
11
 
11
- import { TextEncoder, TextDecoder } from "text-encoding";
12
+ // The UTF-8 classes live in this file, not in a module of their own: a
13
+ // module shared with the polyfill barrel becomes a chunk that the bundler
14
+ // hoists above `import "./polyfills"` in every entry, and
15
+ // scripts/verify-polyfill-barrel.mjs requires the barrel to load first.
16
+
17
+ /**
18
+ * UTF-8 `TextEncoder` and `TextDecoder`, for runtimes that have neither.
19
+ *
20
+ * CopilotKit only reads and writes UTF-8, so these classes support only that
21
+ * encoding. The decoder follows the WHATWG UTF-8 decode algorithm, so its
22
+ * output, including U+FFFD for invalid bytes and `{ stream: true }` chunks,
23
+ * matches the built-in `TextDecoder`.
24
+ */
25
+
26
+ const REPLACEMENT = 0xfffd;
27
+
28
+ export class Utf8TextEncoder {
29
+ readonly encoding = "utf-8";
30
+
31
+ encode(input = ""): Uint8Array {
32
+ const bytes: number[] = [];
33
+ for (const char of input) {
34
+ let codePoint = char.codePointAt(0)!;
35
+ // A lone surrogate is not a Unicode scalar value.
36
+ if (codePoint >= 0xd800 && codePoint <= 0xdfff) codePoint = REPLACEMENT;
37
+ if (codePoint < 0x80) bytes.push(codePoint);
38
+ else if (codePoint < 0x800)
39
+ bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f));
40
+ else if (codePoint < 0x10000)
41
+ bytes.push(
42
+ 0xe0 | (codePoint >> 12),
43
+ 0x80 | ((codePoint >> 6) & 0x3f),
44
+ 0x80 | (codePoint & 0x3f),
45
+ );
46
+ else
47
+ bytes.push(
48
+ 0xf0 | (codePoint >> 18),
49
+ 0x80 | ((codePoint >> 12) & 0x3f),
50
+ 0x80 | ((codePoint >> 6) & 0x3f),
51
+ 0x80 | (codePoint & 0x3f),
52
+ );
53
+ }
54
+ return new Uint8Array(bytes);
55
+ }
56
+ }
57
+
58
+ export class Utf8TextDecoder {
59
+ readonly encoding = "utf-8";
60
+ readonly fatal: boolean;
61
+ readonly ignoreBOM: boolean;
62
+
63
+ #codePoint = 0;
64
+ #bytesNeeded = 0;
65
+ #bytesSeen = 0;
66
+ #lowerBoundary = 0x80;
67
+ #upperBoundary = 0xbf;
68
+ #atStart = true;
69
+
70
+ constructor(
71
+ label = "utf-8",
72
+ options: { fatal?: boolean; ignoreBOM?: boolean } = {},
73
+ ) {
74
+ const normalized = String(label).trim().toLowerCase();
75
+ if (normalized !== "utf-8" && normalized !== "utf8") {
76
+ throw new RangeError(`The "${label}" encoding is not supported.`);
77
+ }
78
+ this.fatal = options.fatal ?? false;
79
+ this.ignoreBOM = options.ignoreBOM ?? false;
80
+ }
81
+
82
+ decode(
83
+ input?: ArrayBuffer | ArrayBufferView,
84
+ options: { stream?: boolean } = {},
85
+ ): string {
86
+ const bytes =
87
+ input === undefined
88
+ ? new Uint8Array(0)
89
+ : ArrayBuffer.isView(input)
90
+ ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength)
91
+ : new Uint8Array(input);
92
+ const codePoints: number[] = [];
93
+
94
+ for (let i = 0; i < bytes.length; i++) {
95
+ const byte = bytes[i];
96
+ if (this.#bytesNeeded === 0) {
97
+ if (byte <= 0x7f) codePoints.push(byte);
98
+ else if (byte >= 0xc2 && byte <= 0xdf) this.#start(1, byte & 0x1f);
99
+ else if (byte >= 0xe0 && byte <= 0xef) {
100
+ if (byte === 0xe0) this.#lowerBoundary = 0xa0;
101
+ if (byte === 0xed) this.#upperBoundary = 0x9f;
102
+ this.#start(2, byte & 0x0f);
103
+ } else if (byte >= 0xf0 && byte <= 0xf4) {
104
+ if (byte === 0xf0) this.#lowerBoundary = 0x90;
105
+ if (byte === 0xf4) this.#upperBoundary = 0x8f;
106
+ this.#start(3, byte & 0x07);
107
+ } else codePoints.push(this.#error());
108
+ continue;
109
+ }
110
+ if (byte < this.#lowerBoundary || byte > this.#upperBoundary) {
111
+ // The sequence ends early. Read this byte again as a new sequence.
112
+ this.#reset();
113
+ codePoints.push(this.#error());
114
+ i--;
115
+ continue;
116
+ }
117
+ this.#lowerBoundary = 0x80;
118
+ this.#upperBoundary = 0xbf;
119
+ this.#codePoint = (this.#codePoint << 6) | (byte & 0x3f);
120
+ if (++this.#bytesSeen === this.#bytesNeeded) {
121
+ codePoints.push(this.#codePoint);
122
+ this.#reset();
123
+ }
124
+ }
125
+
126
+ if (!options.stream && this.#bytesNeeded > 0) {
127
+ this.#reset();
128
+ codePoints.push(this.#error());
129
+ }
130
+ if (this.#atStart && codePoints.length > 0) {
131
+ this.#atStart = false;
132
+ if (!this.ignoreBOM && codePoints[0] === 0xfeff) codePoints.shift();
133
+ }
134
+ if (!options.stream) this.#atStart = true;
135
+ return codePointsToString(codePoints);
136
+ }
137
+
138
+ #start(bytesNeeded: number, codePoint: number): void {
139
+ this.#bytesNeeded = bytesNeeded;
140
+ this.#codePoint = codePoint;
141
+ }
142
+
143
+ #reset(): void {
144
+ this.#codePoint = 0;
145
+ this.#bytesNeeded = 0;
146
+ this.#bytesSeen = 0;
147
+ this.#lowerBoundary = 0x80;
148
+ this.#upperBoundary = 0xbf;
149
+ }
150
+
151
+ #error(): number {
152
+ if (this.fatal) {
153
+ this.#atStart = true;
154
+ throw new TypeError("The encoded data was not valid utf-8.");
155
+ }
156
+ return REPLACEMENT;
157
+ }
158
+ }
159
+
160
+ function codePointsToString(codePoints: number[]): string {
161
+ let out = "";
162
+ // Stay under the engine's limit on function arguments.
163
+ for (let i = 0; i < codePoints.length; i += 0x8000) {
164
+ out += String.fromCodePoint(...codePoints.slice(i, i + 0x8000));
165
+ }
166
+ return out;
167
+ }
12
168
 
13
169
  const g = globalThis as Record<string, unknown>;
14
170
 
15
171
  if (typeof g.TextEncoder === "undefined") {
16
- g.TextEncoder = TextEncoder;
172
+ g.TextEncoder = Utf8TextEncoder;
17
173
  }
18
174
  if (typeof g.TextDecoder === "undefined") {
19
- g.TextDecoder = TextDecoder;
175
+ g.TextDecoder = Utf8TextDecoder;
20
176
  }
package/src/types.d.ts CHANGED
@@ -8,16 +8,3 @@ declare const __DEV__: boolean;
8
8
  // (`g`) instead of repeating `(globalThis as any)` on every line — same pattern as
9
9
  // packages/angular/src/test-setup.ts. Files without imports add `export {}` so
10
10
  // TypeScript treats them as modules with isolated scope.
11
-
12
- declare module "text-encoding" {
13
- export class TextEncoder {
14
- encode(input?: string): Uint8Array;
15
- }
16
- export class TextDecoder {
17
- constructor(label?: string, options?: { fatal?: boolean });
18
- decode(
19
- input?: ArrayBufferView | ArrayBuffer,
20
- options?: { stream?: boolean },
21
- ): string;
22
- }
23
- }
package/tsdown.config.ts CHANGED
@@ -5,6 +5,7 @@ export default defineConfig({
5
5
  "src/index.ts",
6
6
  "src/headless.ts",
7
7
  "src/components/index.ts",
8
+ "src/generative-ui/index.ts",
8
9
  "src/polyfills.ts",
9
10
  "src/polyfills/streams.ts",
10
11
  "src/polyfills/encoding.ts",