@copilotkit/react-native 1.57.0-canary.1778116520

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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +54 -0
  3. package/dist/index.cjs +203 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +51 -0
  6. package/dist/index.d.mts +51 -0
  7. package/dist/index.mjs +101 -0
  8. package/dist/index.mjs.map +1 -0
  9. package/dist/polyfills/crypto.cjs +15 -0
  10. package/dist/polyfills/crypto.cjs.map +1 -0
  11. package/dist/polyfills/crypto.d.cts +1 -0
  12. package/dist/polyfills/crypto.d.mts +1 -0
  13. package/dist/polyfills/crypto.mjs +15 -0
  14. package/dist/polyfills/crypto.mjs.map +1 -0
  15. package/dist/polyfills/dom.cjs +59 -0
  16. package/dist/polyfills/dom.cjs.map +1 -0
  17. package/dist/polyfills/dom.d.cts +1 -0
  18. package/dist/polyfills/dom.d.mts +1 -0
  19. package/dist/polyfills/dom.mjs +59 -0
  20. package/dist/polyfills/dom.mjs.map +1 -0
  21. package/dist/polyfills/encoding.cjs +19 -0
  22. package/dist/polyfills/encoding.cjs.map +1 -0
  23. package/dist/polyfills/encoding.d.cts +1 -0
  24. package/dist/polyfills/encoding.d.mts +1 -0
  25. package/dist/polyfills/encoding.mjs +19 -0
  26. package/dist/polyfills/encoding.mjs.map +1 -0
  27. package/dist/polyfills/location.cjs +18 -0
  28. package/dist/polyfills/location.cjs.map +1 -0
  29. package/dist/polyfills/location.d.cts +1 -0
  30. package/dist/polyfills/location.d.mts +1 -0
  31. package/dist/polyfills/location.mjs +18 -0
  32. package/dist/polyfills/location.mjs.map +1 -0
  33. package/dist/polyfills/streams.cjs +20 -0
  34. package/dist/polyfills/streams.cjs.map +1 -0
  35. package/dist/polyfills/streams.d.cts +1 -0
  36. package/dist/polyfills/streams.d.mts +1 -0
  37. package/dist/polyfills/streams.mjs +20 -0
  38. package/dist/polyfills/streams.mjs.map +1 -0
  39. package/dist/polyfills.cjs +196 -0
  40. package/dist/polyfills.cjs.map +1 -0
  41. package/dist/polyfills.d.cts +1 -0
  42. package/dist/polyfills.d.mts +1 -0
  43. package/dist/polyfills.mjs +196 -0
  44. package/dist/polyfills.mjs.map +1 -0
  45. package/package.json +92 -0
  46. package/project.json +18 -0
  47. package/src/CopilotKitProvider.tsx +188 -0
  48. package/src/__tests__/copilotkit-provider.test.tsx +424 -0
  49. package/src/__tests__/headless-integration.test.tsx +378 -0
  50. package/src/__tests__/polyfills.test.ts +242 -0
  51. package/src/__tests__/setup.ts +9 -0
  52. package/src/__tests__/streaming-fetch.test.ts +486 -0
  53. package/src/index.ts +44 -0
  54. package/src/polyfills/crypto.ts +34 -0
  55. package/src/polyfills/dom.ts +85 -0
  56. package/src/polyfills/encoding.ts +20 -0
  57. package/src/polyfills/location.ts +30 -0
  58. package/src/polyfills/streams.ts +27 -0
  59. package/src/polyfills.ts +22 -0
  60. package/src/streaming-fetch.ts +336 -0
  61. package/src/types.d.ts +23 -0
  62. package/tsconfig.json +16 -0
  63. package/tsdown.config.ts +25 -0
  64. package/vitest.config.mjs +17 -0
@@ -0,0 +1,486 @@
1
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
2
+
3
+ // ─── MockXHR ──────────────────────────────────────────────────────────────────
4
+
5
+ class MockXHR {
6
+ open = vi.fn();
7
+ send = vi.fn();
8
+ abort = vi.fn();
9
+ setRequestHeader = vi.fn();
10
+ getAllResponseHeaders = vi.fn(() => "");
11
+
12
+ readyState = 0;
13
+ status = 0;
14
+ statusText = "";
15
+ responseText = "";
16
+ responseType = "";
17
+ timeout = 0;
18
+
19
+ onreadystatechange: (() => void) | null = null;
20
+ onprogress: (() => void) | null = null;
21
+ onload: (() => void) | null = null;
22
+ onerror: (() => void) | null = null;
23
+ ontimeout: (() => void) | null = null;
24
+ onabort: (() => void) | null = null;
25
+ }
26
+
27
+ let mockXhr: MockXHR;
28
+
29
+ function simulateHeaders(
30
+ xhr: MockXHR,
31
+ status: number,
32
+ headers = "content-type: text/plain\r\n",
33
+ statusText = "OK",
34
+ ) {
35
+ xhr.readyState = 2;
36
+ xhr.status = status;
37
+ xhr.statusText = statusText;
38
+ xhr.getAllResponseHeaders.mockReturnValue(headers);
39
+ xhr.onreadystatechange?.();
40
+ }
41
+
42
+ function simulateProgress(xhr: MockXHR, text: string) {
43
+ xhr.responseText = text;
44
+ xhr.onprogress?.();
45
+ }
46
+
47
+ function simulateLoad(xhr: MockXHR) {
48
+ xhr.readyState = 4;
49
+ xhr.onload?.();
50
+ }
51
+
52
+ function simulateError(xhr: MockXHR) {
53
+ xhr.onerror?.();
54
+ }
55
+
56
+ function simulateTimeout(xhr: MockXHR) {
57
+ xhr.ontimeout?.();
58
+ }
59
+
60
+ // ─── Globals save/restore ─────────────────────────────────────────────────────
61
+
62
+ let savedFetch: typeof globalThis.fetch;
63
+ let savedXHR: typeof globalThis.XMLHttpRequest;
64
+ let savedResponse: typeof globalThis.Response;
65
+
66
+ beforeEach(() => {
67
+ savedFetch = globalThis.fetch;
68
+ savedXHR = globalThis.XMLHttpRequest;
69
+ savedResponse = globalThis.Response;
70
+
71
+ mockXhr = new MockXHR();
72
+ (globalThis as any).XMLHttpRequest = vi.fn(() => mockXhr);
73
+
74
+ // Make feature detection fail so the polyfill installs
75
+ (globalThis as any).Response = class {
76
+ body = null;
77
+ };
78
+ });
79
+
80
+ afterEach(() => {
81
+ globalThis.fetch = savedFetch;
82
+ (globalThis as any).XMLHttpRequest = savedXHR;
83
+ (globalThis as any).Response = savedResponse;
84
+ });
85
+
86
+ // ─── Helper: import fresh module ──────────────────────────────────────────────
87
+
88
+ async function install() {
89
+ // Reset module cache so installStreamingFetch runs fresh
90
+ vi.resetModules();
91
+ const mod = await import("../streaming-fetch");
92
+ mod.installStreamingFetch();
93
+ }
94
+
95
+ // Helper: make a fetch call and capture the mockXhr for lifecycle simulation
96
+ async function fetchAndCapture(
97
+ input: string | URL = "https://api.test/stream",
98
+ init?: RequestInit,
99
+ ) {
100
+ await install();
101
+ const fetchPromise = globalThis.fetch(input, init);
102
+ return { fetchPromise, xhr: mockXhr };
103
+ }
104
+
105
+ // ─── Tests ────────────────────────────────────────────────────────────────────
106
+
107
+ describe("installStreamingFetch", () => {
108
+ // ── Feature detection ─────────────────────────────────────────────────────
109
+
110
+ describe("feature detection", () => {
111
+ it("skips installation when native fetch already supports ReadableStream body", async () => {
112
+ const originalFetch = globalThis.fetch;
113
+ (globalThis as any).Response = class {
114
+ body = {
115
+ getReader: () => ({}),
116
+ };
117
+ };
118
+ await install();
119
+ expect(globalThis.fetch).toBe(originalFetch);
120
+ });
121
+
122
+ it("installs replacement when Response constructor is unavailable", async () => {
123
+ const originalFetch = globalThis.fetch;
124
+ delete (globalThis as any).Response;
125
+ await install();
126
+ expect(globalThis.fetch).not.toBe(originalFetch);
127
+ });
128
+
129
+ it("installs replacement when Response.body is null", async () => {
130
+ const originalFetch = globalThis.fetch;
131
+ await install();
132
+ expect(globalThis.fetch).not.toBe(originalFetch);
133
+ });
134
+
135
+ it("installs replacement when Response.body.getReader is not a function", async () => {
136
+ const originalFetch = globalThis.fetch;
137
+ (globalThis as any).Response = class {
138
+ body = {};
139
+ };
140
+ await install();
141
+ expect(globalThis.fetch).not.toBe(originalFetch);
142
+ });
143
+ });
144
+
145
+ // ── Basic request lifecycle ───────────────────────────────────────────────
146
+
147
+ describe("basic request lifecycle", () => {
148
+ it("opens XHR with correct method and URL for string input", async () => {
149
+ const { xhr } = await fetchAndCapture("https://api.test/data", {
150
+ method: "POST",
151
+ });
152
+ expect(xhr.open).toHaveBeenCalledWith("POST", "https://api.test/data");
153
+ });
154
+
155
+ it("opens XHR with correct URL for URL input", async () => {
156
+ const { xhr } = await fetchAndCapture(new URL("https://api.test/path"));
157
+ expect(xhr.open).toHaveBeenCalledWith("GET", "https://api.test/path");
158
+ });
159
+
160
+ it("defaults to GET when no method specified", async () => {
161
+ const { xhr } = await fetchAndCapture("https://api.test");
162
+ expect(xhr.open).toHaveBeenCalledWith("GET", "https://api.test");
163
+ });
164
+
165
+ it("sets request headers from plain object", async () => {
166
+ const { xhr } = await fetchAndCapture("https://api.test", {
167
+ headers: { "Content-Type": "application/json", "X-Custom": "val" },
168
+ });
169
+ expect(xhr.setRequestHeader).toHaveBeenCalledWith(
170
+ "Content-Type",
171
+ "application/json",
172
+ );
173
+ expect(xhr.setRequestHeader).toHaveBeenCalledWith("X-Custom", "val");
174
+ });
175
+
176
+ it("sets request headers from Headers instance", async () => {
177
+ const headers = new Headers({ Authorization: "Bearer tok" });
178
+ const { xhr } = await fetchAndCapture("https://api.test", { headers });
179
+ expect(xhr.setRequestHeader).toHaveBeenCalledWith(
180
+ "authorization",
181
+ "Bearer tok",
182
+ );
183
+ });
184
+
185
+ it("sets request headers from array of tuples", async () => {
186
+ const { xhr } = await fetchAndCapture("https://api.test", {
187
+ headers: [["X-Key", "val"]],
188
+ });
189
+ expect(xhr.setRequestHeader).toHaveBeenCalledWith("X-Key", "val");
190
+ });
191
+
192
+ it("sends the request body", async () => {
193
+ const { xhr } = await fetchAndCapture("https://api.test", {
194
+ method: "POST",
195
+ body: '{"key":"value"}',
196
+ });
197
+ expect(xhr.send).toHaveBeenCalledWith('{"key":"value"}');
198
+ });
199
+
200
+ it("sets XHR timeout to 60 seconds", async () => {
201
+ const { xhr } = await fetchAndCapture();
202
+ expect(xhr.timeout).toBe(60_000);
203
+ });
204
+ });
205
+
206
+ // ── Response resolution ───────────────────────────────────────────────────
207
+
208
+ describe("response resolution", () => {
209
+ it("resolves when headers arrive with non-zero status", async () => {
210
+ const { fetchPromise, xhr } = await fetchAndCapture();
211
+ simulateHeaders(xhr, 200);
212
+ const resp = await fetchPromise;
213
+ expect(resp.status).toBe(200);
214
+ });
215
+
216
+ it("exposes correct status, statusText, url, and ok", async () => {
217
+ const { fetchPromise, xhr } = await fetchAndCapture(
218
+ "https://api.test/not-found",
219
+ );
220
+ simulateHeaders(xhr, 404, "", "Not Found");
221
+ const resp = await fetchPromise;
222
+ expect(resp.ok).toBe(false);
223
+ expect(resp.status).toBe(404);
224
+ expect(resp.statusText).toBe("Not Found");
225
+ expect(resp.url).toBe("https://api.test/not-found");
226
+ });
227
+
228
+ it("parses response headers into a Headers object", async () => {
229
+ const { fetchPromise, xhr } = await fetchAndCapture();
230
+ simulateHeaders(
231
+ xhr,
232
+ 200,
233
+ "content-type: application/json\r\nx-request-id: abc123\r\n",
234
+ );
235
+ const resp = await fetchPromise;
236
+ expect(resp.headers.get("content-type")).toBe("application/json");
237
+ expect(resp.headers.get("x-request-id")).toBe("abc123");
238
+ });
239
+
240
+ it("provides a ReadableStream body on the response", async () => {
241
+ const { fetchPromise, xhr } = await fetchAndCapture();
242
+ simulateHeaders(xhr, 200);
243
+ const resp = await fetchPromise;
244
+ expect(resp.body).toBeInstanceOf(ReadableStream);
245
+ });
246
+ });
247
+
248
+ // ── Streaming chunks ──────────────────────────────────────────────────────
249
+
250
+ describe("streaming chunks", () => {
251
+ it("delivers chunks incrementally as XHR fires onprogress", async () => {
252
+ const { fetchPromise, xhr } = await fetchAndCapture();
253
+ simulateHeaders(xhr, 200);
254
+ const resp = await fetchPromise;
255
+ const reader = resp.body!.getReader();
256
+
257
+ simulateProgress(xhr, "chunk1");
258
+ const { value: c1 } = await reader.read();
259
+ expect(new TextDecoder().decode(c1)).toBe("chunk1");
260
+
261
+ simulateProgress(xhr, "chunk1chunk2");
262
+ const { value: c2 } = await reader.read();
263
+ expect(new TextDecoder().decode(c2)).toBe("chunk2");
264
+ });
265
+
266
+ it("closes stream on onload after delivering final chunks", async () => {
267
+ const { fetchPromise, xhr } = await fetchAndCapture();
268
+ simulateHeaders(xhr, 200);
269
+ const resp = await fetchPromise;
270
+ const reader = resp.body!.getReader();
271
+
272
+ xhr.responseText = "all data";
273
+ simulateLoad(xhr);
274
+
275
+ const { value, done } = await reader.read();
276
+ expect(new TextDecoder().decode(value)).toBe("all data");
277
+ const final = await reader.read();
278
+ expect(final.done).toBe(true);
279
+ });
280
+
281
+ it("encodes chunks as Uint8Array", async () => {
282
+ const { fetchPromise, xhr } = await fetchAndCapture();
283
+ simulateHeaders(xhr, 200);
284
+ const resp = await fetchPromise;
285
+ const reader = resp.body!.getReader();
286
+
287
+ simulateProgress(xhr, "hello");
288
+ const { value } = await reader.read();
289
+ // Cross-realm safe check (jsdom TextEncoder may produce a different Uint8Array)
290
+ expect(ArrayBuffer.isView(value)).toBe(true);
291
+ expect(value!.constructor.name).toBe("Uint8Array");
292
+ });
293
+ });
294
+
295
+ // ── Convenience methods ───────────────────────────────────────────────────
296
+
297
+ describe("convenience methods", () => {
298
+ it("text() returns full response text after XHR completes", async () => {
299
+ const { fetchPromise, xhr } = await fetchAndCapture();
300
+ simulateHeaders(xhr, 200);
301
+ const resp = await fetchPromise;
302
+
303
+ xhr.responseText = "hello world";
304
+ simulateLoad(xhr);
305
+
306
+ expect(await resp.text()).toBe("hello world");
307
+ });
308
+
309
+ it("json() parses full response text as JSON", async () => {
310
+ const { fetchPromise, xhr } = await fetchAndCapture();
311
+ simulateHeaders(xhr, 200);
312
+ const resp = await fetchPromise;
313
+
314
+ xhr.responseText = '{"key":"value"}';
315
+ simulateLoad(xhr);
316
+
317
+ expect(await resp.json()).toEqual({ key: "value" });
318
+ });
319
+
320
+ it("json() throws TypeError with descriptive message on invalid JSON", async () => {
321
+ const { fetchPromise, xhr } = await fetchAndCapture(
322
+ "https://api.test/bad",
323
+ { method: "POST" },
324
+ );
325
+ simulateHeaders(xhr, 200);
326
+ const resp = await fetchPromise;
327
+
328
+ xhr.responseText = "not json";
329
+ simulateLoad(xhr);
330
+
331
+ await expect(resp.json()).rejects.toThrow(TypeError);
332
+ await expect(resp.json()).rejects.toThrow(/api\.test\/bad/);
333
+ });
334
+
335
+ it("clone() always throws", async () => {
336
+ const { fetchPromise, xhr } = await fetchAndCapture();
337
+ simulateHeaders(xhr, 200);
338
+ const resp = await fetchPromise;
339
+ expect(() => resp.clone()).toThrow(/not supported/);
340
+ });
341
+
342
+ it("formData() always throws", async () => {
343
+ const { fetchPromise, xhr } = await fetchAndCapture();
344
+ simulateHeaders(xhr, 200);
345
+ const resp = await fetchPromise;
346
+ await expect(resp.formData()).rejects.toThrow(/not supported/);
347
+ });
348
+
349
+ it("marks bodyUsed after calling text()", async () => {
350
+ const { fetchPromise, xhr } = await fetchAndCapture();
351
+ simulateHeaders(xhr, 200);
352
+ const resp = await fetchPromise;
353
+ expect(resp.bodyUsed).toBe(false);
354
+
355
+ xhr.responseText = "data";
356
+ simulateLoad(xhr);
357
+ await resp.text();
358
+
359
+ expect(resp.bodyUsed).toBe(true);
360
+ });
361
+ });
362
+
363
+ // ── Abort handling ────────────────────────────────────────────────────────
364
+
365
+ describe("abort handling", () => {
366
+ it("rejects immediately when signal is already aborted", async () => {
367
+ await install();
368
+ const controller = new AbortController();
369
+ controller.abort();
370
+
371
+ await expect(
372
+ globalThis.fetch("https://api.test", { signal: controller.signal }),
373
+ ).rejects.toThrow(/aborted/i);
374
+ });
375
+
376
+ it("aborts XHR and rejects when signal fires before headers", async () => {
377
+ const controller = new AbortController();
378
+ const { fetchPromise, xhr } = await fetchAndCapture("https://api.test", {
379
+ signal: controller.signal,
380
+ });
381
+
382
+ controller.abort();
383
+
384
+ await expect(fetchPromise).rejects.toThrow(/aborted/i);
385
+ expect(xhr.abort).toHaveBeenCalled();
386
+ });
387
+
388
+ it("aborts XHR mid-stream when signal fires after headers arrive", async () => {
389
+ const controller = new AbortController();
390
+ const { fetchPromise, xhr } = await fetchAndCapture("https://api.test", {
391
+ signal: controller.signal,
392
+ });
393
+
394
+ simulateHeaders(xhr, 200);
395
+ const resp = await fetchPromise;
396
+ const reader = resp.body!.getReader();
397
+
398
+ controller.abort();
399
+
400
+ await expect(reader.read()).rejects.toThrow(/aborted/i);
401
+ expect(xhr.abort).toHaveBeenCalled();
402
+ });
403
+
404
+ it("cancelling the ReadableStream aborts the XHR", async () => {
405
+ const { fetchPromise, xhr } = await fetchAndCapture();
406
+ simulateHeaders(xhr, 200);
407
+ const resp = await fetchPromise;
408
+ const reader = resp.body!.getReader();
409
+
410
+ await reader.cancel();
411
+
412
+ expect(xhr.abort).toHaveBeenCalled();
413
+ });
414
+
415
+ it("removes abort listener after terminal XHR event (onload)", async () => {
416
+ const controller = new AbortController();
417
+ const removeSpy = vi.spyOn(controller.signal, "removeEventListener");
418
+
419
+ const { fetchPromise, xhr } = await fetchAndCapture("https://api.test", {
420
+ signal: controller.signal,
421
+ });
422
+ simulateHeaders(xhr, 200);
423
+ await fetchPromise;
424
+
425
+ xhr.responseText = "done";
426
+ simulateLoad(xhr);
427
+
428
+ expect(removeSpy).toHaveBeenCalledWith("abort", expect.any(Function));
429
+ });
430
+ });
431
+
432
+ // ── Error handling ────────────────────────────────────────────────────────
433
+
434
+ describe("error handling", () => {
435
+ it("rejects with TypeError on XHR onerror", async () => {
436
+ const { fetchPromise, xhr } = await fetchAndCapture();
437
+ simulateError(xhr);
438
+ await expect(fetchPromise).rejects.toThrow("Network request failed");
439
+ });
440
+
441
+ it("rejects with TypeError on XHR ontimeout", async () => {
442
+ const { fetchPromise, xhr } = await fetchAndCapture();
443
+ simulateTimeout(xhr);
444
+ await expect(fetchPromise).rejects.toThrow("Network request timed out");
445
+ });
446
+
447
+ it("rejects with descriptive error on readyState=4 with status=0 (CORS/DNS)", async () => {
448
+ const { fetchPromise, xhr } = await fetchAndCapture();
449
+ xhr.readyState = 4;
450
+ xhr.status = 0;
451
+ xhr.onreadystatechange?.();
452
+ await expect(fetchPromise).rejects.toThrow(/CORS failure/);
453
+ });
454
+
455
+ it("errors stream and rejects text() when onerror fires after headers", async () => {
456
+ const { fetchPromise, xhr } = await fetchAndCapture();
457
+ simulateHeaders(xhr, 200);
458
+ const resp = await fetchPromise;
459
+
460
+ simulateError(xhr);
461
+
462
+ await expect(resp.text()).rejects.toThrow("Network request failed");
463
+ });
464
+
465
+ it("does not double-reject (settled guard)", async () => {
466
+ const { fetchPromise, xhr } = await fetchAndCapture();
467
+
468
+ // First error settles the promise
469
+ simulateError(xhr);
470
+ await expect(fetchPromise).rejects.toThrow("Network request failed");
471
+
472
+ // Second error should not throw unhandled rejection
473
+ expect(() => simulateTimeout(xhr)).not.toThrow();
474
+ });
475
+ });
476
+
477
+ // ── __originalFetch ───────────────────────────────────────────────────────
478
+
479
+ describe("__originalFetch", () => {
480
+ it("exposes original fetch on the replacement", async () => {
481
+ const originalFetch = globalThis.fetch;
482
+ await install();
483
+ expect((globalThis.fetch as any).__originalFetch).toBe(originalFetch);
484
+ });
485
+ });
486
+ });
package/src/index.ts ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @copilotkit/react-native
3
+ *
4
+ * React Native bindings for CopilotKit. Provides a lightweight provider
5
+ * and re-exports platform-agnostic hooks from @copilotkit/react-core.
6
+ *
7
+ * Quick start:
8
+ * ```tsx
9
+ * import { CopilotKitProvider, useAgent, useCopilotKit } from "@copilotkit/react-native";
10
+ * ```
11
+ */
12
+
13
+ // React Native provider (no web dependencies)
14
+ export { CopilotKitProvider } from "./CopilotKitProvider";
15
+ export type { CopilotKitNativeProviderProps } from "./CopilotKitProvider";
16
+
17
+ // Re-export context and hooks from react-core (platform-agnostic)
18
+ export {
19
+ useCopilotKit,
20
+ useLicenseContext,
21
+ CopilotKitContext,
22
+ type CopilotKitContextValue,
23
+ } from "@copilotkit/react-core/v2/context";
24
+
25
+ // Re-export hooks that work without web deps
26
+ // These consume the CopilotKitContext which our provider sets
27
+ export {
28
+ useAgent,
29
+ useFrontendTool,
30
+ useComponent,
31
+ useHumanInTheLoop,
32
+ useInterrupt,
33
+ useSuggestions,
34
+ useConfigureSuggestions,
35
+ useAgentContext,
36
+ useThreads,
37
+ type UseAgentUpdate,
38
+ } from "@copilotkit/react-core/v2/headless";
39
+
40
+ // Re-export core types commonly needed
41
+ export {
42
+ type CopilotKitCoreRuntimeConnectionStatus,
43
+ type CopilotKitCoreErrorCode,
44
+ } from "@copilotkit/core";
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Polyfill: crypto.getRandomValues
3
+ *
4
+ * Required by uuid generation in CopilotKit. Uses Math.random — NOT
5
+ * cryptographically secure. For secure randomness, install
6
+ * react-native-get-random-values before this polyfill.
7
+ *
8
+ * Skipped if crypto.getRandomValues is already defined.
9
+ *
10
+ * Usage:
11
+ * import "@copilotkit/react-native/polyfills/crypto";
12
+ */
13
+
14
+ export {};
15
+
16
+ const g = globalThis as Record<string, unknown>;
17
+
18
+ if (typeof g.crypto === "undefined") {
19
+ g.crypto = {};
20
+ }
21
+ const cryptoObj = g.crypto as Record<string, unknown>;
22
+ if (!cryptoObj.getRandomValues) {
23
+ console.warn(
24
+ "[CopilotKit] Installing non-cryptographic crypto.getRandomValues polyfill (Math.random). " +
25
+ "This is NOT secure for cryptographic operations. Install 'react-native-get-random-values' " +
26
+ "for a secure implementation.",
27
+ );
28
+ cryptoObj.getRandomValues = function (array: Uint8Array): Uint8Array {
29
+ for (let i = 0; i < array.length; i++) {
30
+ array[i] = Math.floor(Math.random() * 256);
31
+ }
32
+ return array;
33
+ };
34
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Polyfill: DOMException, Headers
3
+ *
4
+ * DOMException is used by CopilotKit's isAbortError check.
5
+ * Headers is used by CopilotKit's request construction.
6
+ * Skipped if the globals are already defined.
7
+ *
8
+ * Usage:
9
+ * import "@copilotkit/react-native/polyfills/dom";
10
+ */
11
+
12
+ export {};
13
+
14
+ const g = globalThis as Record<string, unknown>;
15
+
16
+ // DOMException
17
+ if (typeof g.DOMException === "undefined") {
18
+ class DOMExceptionPolyfill extends Error {
19
+ code: number;
20
+ constructor(message?: string, name?: string) {
21
+ super(message);
22
+ this.name = name || "DOMException";
23
+ this.code = 0;
24
+ }
25
+ }
26
+ g.DOMException = DOMExceptionPolyfill;
27
+ }
28
+
29
+ // Headers
30
+ if (typeof g.Headers === "undefined") {
31
+ class HeadersPolyfill {
32
+ private _map: Record<string, string> = {};
33
+ constructor(init?: Record<string, string> | HeadersPolyfill) {
34
+ if (init) {
35
+ if (init instanceof HeadersPolyfill) {
36
+ this._map = { ...init._map };
37
+ } else {
38
+ for (const [key, value] of Object.entries(init)) {
39
+ this._map[key.toLowerCase()] = value;
40
+ }
41
+ }
42
+ }
43
+ }
44
+ get(name: string): string | null {
45
+ return this._map[name.toLowerCase()] ?? null;
46
+ }
47
+ set(name: string, value: string): void {
48
+ this._map[name.toLowerCase()] = value;
49
+ }
50
+ has(name: string): boolean {
51
+ return name.toLowerCase() in this._map;
52
+ }
53
+ delete(name: string): void {
54
+ delete this._map[name.toLowerCase()];
55
+ }
56
+ append(name: string, value: string): void {
57
+ const key = name.toLowerCase();
58
+ if (key in this._map) {
59
+ this._map[key] += ", " + value;
60
+ } else {
61
+ this._map[key] = value;
62
+ }
63
+ }
64
+ entries(): IterableIterator<[string, string]> {
65
+ return Object.entries(this._map)[Symbol.iterator]();
66
+ }
67
+ keys(): IterableIterator<string> {
68
+ return Object.keys(this._map)[Symbol.iterator]();
69
+ }
70
+ values(): IterableIterator<string> {
71
+ return Object.values(this._map)[Symbol.iterator]();
72
+ }
73
+ forEach(
74
+ callback: (value: string, key: string, parent: HeadersPolyfill) => void,
75
+ ): void {
76
+ for (const [key, value] of Object.entries(this._map)) {
77
+ callback(value, key, this);
78
+ }
79
+ }
80
+ [Symbol.iterator](): IterableIterator<[string, string]> {
81
+ return this.entries();
82
+ }
83
+ }
84
+ g.Headers = HeadersPolyfill;
85
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Polyfill: TextEncoder, TextDecoder
3
+ *
4
+ * Required for stream chunk processing in CopilotKit.
5
+ * Skipped if the globals are already defined.
6
+ *
7
+ * Usage:
8
+ * import "@copilotkit/react-native/polyfills/encoding";
9
+ */
10
+
11
+ import { TextEncoder, TextDecoder } from "text-encoding";
12
+
13
+ const g = globalThis as Record<string, unknown>;
14
+
15
+ if (typeof g.TextEncoder === "undefined") {
16
+ g.TextEncoder = TextEncoder;
17
+ }
18
+ if (typeof g.TextDecoder === "undefined") {
19
+ g.TextDecoder = TextDecoder;
20
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Polyfill: window.location
3
+ *
4
+ * Required by shouldShowDevConsole (hostname check) and agent runtime
5
+ * URL resolution (window.location.origin). Uses an obviously invalid
6
+ * hostname to avoid tricking localhost-detection code.
7
+ *
8
+ * Skipped if window.location is already defined.
9
+ *
10
+ * Usage:
11
+ * import "@copilotkit/react-native/polyfills/location";
12
+ */
13
+
14
+ export {};
15
+
16
+ if (typeof window !== "undefined") {
17
+ const w = window as unknown as Record<string, unknown>;
18
+ if (!w.location) {
19
+ w.location = {
20
+ hostname: "react-native.invalid",
21
+ href: "http://react-native.invalid",
22
+ origin: "http://react-native.invalid",
23
+ protocol: "http:",
24
+ host: "react-native.invalid",
25
+ pathname: "/",
26
+ search: "",
27
+ hash: "",
28
+ };
29
+ }
30
+ }