@copilotkit/react-native 2.0.0-rc.37 → 2.0.0-rc.39

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 (82) hide show
  1. package/README.md +334 -2
  2. package/USAGE.md +382 -21
  3. package/dist/{CopilotKitProvider-F7Pn5kp4.d.cts → CopilotKitProvider-Cbfrm_7u.d.mts} +2 -2
  4. package/dist/{CopilotKitProvider-DDPbJkHS.cjs → CopilotKitProvider-CvJYytjn.cjs} +4 -3
  5. package/dist/{CopilotKitProvider-DDPbJkHS.cjs.map → CopilotKitProvider-CvJYytjn.cjs.map} +1 -1
  6. package/dist/{CopilotKitProvider-Khgz5dQo.d.mts → CopilotKitProvider-Dv3ISMKf.d.cts} +2 -2
  7. package/dist/{CopilotKitProvider-BXpkAl1Y.mjs → CopilotKitProvider-oTdmylSY.mjs} +2 -2
  8. package/dist/{CopilotKitProvider-BXpkAl1Y.mjs.map → CopilotKitProvider-oTdmylSY.mjs.map} +1 -1
  9. package/dist/{Markdown-CaYHlD4j.cjs → Markdown-DLopAh5W.cjs} +3 -3
  10. package/dist/{Markdown-CaYHlD4j.cjs.map → Markdown-DLopAh5W.cjs.map} +1 -1
  11. package/dist/{Markdown-a-rdG22_.d.mts → Markdown-Du-b_Qpr.d.mts} +1 -1
  12. package/dist/{Markdown-DzjnSuu5.d.cts → Markdown-UXZdDjzs.d.cts} +1 -1
  13. package/dist/{Markdown-SE9MfY2U.mjs → Markdown-VxtPJ_yh.mjs} +1 -1
  14. package/dist/{Markdown-SE9MfY2U.mjs.map → Markdown-VxtPJ_yh.mjs.map} +1 -1
  15. package/dist/{MarkdownRendererContext-B_AKdPAN.mjs → MarkdownRendererContext-EobUsERg.mjs} +1 -1
  16. package/dist/{MarkdownRendererContext-B_AKdPAN.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 +6 -4
  21. package/dist/components/index.cjs.map +1 -1
  22. package/dist/components/index.d.cts +1 -1
  23. package/dist/components/index.d.mts +1 -1
  24. package/dist/components/index.mjs +3 -2
  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 -3
  33. package/dist/headless.d.cts +2 -2
  34. package/dist/headless.d.mts +2 -2
  35. package/dist/headless.mjs +1 -2
  36. package/dist/index.cjs +8 -7
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +3 -3
  39. package/dist/index.d.mts +2 -2
  40. package/dist/index.mjs +4 -4
  41. package/dist/polyfills/encoding.cjs +113 -3
  42. package/dist/polyfills/encoding.cjs.map +1 -1
  43. package/dist/polyfills/encoding.d.cts +31 -1
  44. package/dist/polyfills/encoding.d.mts +31 -1
  45. package/dist/polyfills/encoding.mjs +109 -3
  46. package/dist/polyfills/encoding.mjs.map +1 -1
  47. package/dist/polyfills/streams.cjs +1 -1
  48. package/dist/polyfills.cjs +218 -3
  49. package/dist/polyfills.cjs.map +1 -1
  50. package/dist/polyfills.mjs +217 -2
  51. package/dist/polyfills.mjs.map +1 -1
  52. package/package.json +13 -5
  53. package/project.json +6 -1
  54. package/scripts/__tests__/verify-polyfill-barrel.test.mjs +150 -0
  55. package/scripts/verify-polyfill-barrel.mjs +154 -5
  56. package/src/__tests__/generative-ui-harness.tsx +243 -0
  57. package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
  58. package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
  59. package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
  60. package/src/__tests__/generative-ui.test.tsx +1000 -0
  61. package/src/__tests__/headless-entry-surface.test.ts +979 -60
  62. package/src/components/index.ts +6 -0
  63. package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
  64. package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
  65. package/src/generative-ui/GenerativeUISurface.tsx +303 -0
  66. package/src/generative-ui/host.tsx +138 -0
  67. package/src/generative-ui/index.ts +93 -0
  68. package/src/generative-ui/internal.ts +55 -0
  69. package/src/index.ts +8 -3
  70. package/src/polyfills/__tests__/{utf8.test.ts → encoding-utf8.test.ts} +1 -1
  71. package/src/polyfills/encoding.ts +156 -1
  72. package/tsdown.config.ts +1 -0
  73. package/dist/MarkdownRendererContext-BRNe808d.cjs +0 -72
  74. package/dist/streaming-fetch-CLHG3Z1H.mjs +0 -219
  75. package/dist/streaming-fetch-CLHG3Z1H.mjs.map +0 -1
  76. package/dist/streaming-fetch-DbDALGya.cjs +0 -225
  77. package/dist/streaming-fetch-DbDALGya.cjs.map +0 -1
  78. package/dist/utf8-BIN9t4Oy.mjs +0 -113
  79. package/dist/utf8-BIN9t4Oy.mjs.map +0 -1
  80. package/dist/utf8-Cf3Ssy33.cjs +0 -125
  81. package/dist/utf8-Cf3Ssy33.cjs.map +0 -1
  82. package/src/polyfills/utf8.ts +0 -151
@@ -1,16 +1,29 @@
1
- import { describe, it, expect, beforeAll } from "vitest";
1
+ import { describe, it, expect, beforeAll, vi } from "vitest";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
+ import { createRequire } from "node:module";
4
5
  // Type-only, so it is erased and does NOT statically pull the entry this file
5
6
  // deliberately loads at runtime (and is not part of the walked graph either —
6
- // the walk starts at src/headless.ts / src/index.ts, not at this test).
7
+ // the walks start at the package's published entries, ENTRIES and
8
+ // generativeUIEntry below, never at this test).
7
9
  import type * as HeadlessEntry from "../headless";
8
10
  // Same reason, and additionally: the identity assertion below needs the module
9
11
  // this entry re-exports FROM, to compare bindings rather than merely count them.
10
12
  import type * as CoreHeadlessEntry from "@copilotkit/react-core/headless";
11
13
 
12
14
  /**
13
- * Guards the `@copilotkit/react-native/headless` entry (src/headless.ts).
15
+ * Guards the import graphs of the published entries of
16
+ * `@copilotkit/react-native`, with `/headless` (src/headless.ts) as the strict
17
+ * case. ENTRIES is derived from package.json `exports`, so the default barrel,
18
+ * `/components` and the polyfill subpaths are walked as well.
19
+ *
20
+ * The second `describe` covers the opt-in `/generative-ui` entry
21
+ * (src/generative-ui/index.ts): it may reach react-core only through `/context`
22
+ * and the DOM-free `/generative-ui/native`, it may reach the `zod` optional
23
+ * peer, it owns no registry, and no OTHER entry may reach it or any
24
+ * generative-UI subpath of a workspace package (that deny-list is derived from
25
+ * the packages' `exports` maps). The third `describe` checks react-core's built
26
+ * dist for a second copy of a generative UI context module.
14
27
  *
15
28
  * The whole point of the headless entry is that a consumer using only the
16
29
  * provider + agent/tool hooks does NOT have to install (or Metro-stub) the
@@ -26,7 +39,7 @@ import type * as CoreHeadlessEntry from "@copilotkit/react-core/headless";
26
39
  *
27
40
  * ─── Why the walker looks the way it does ──────────────────────────────────
28
41
  * A guard that under-reports is worse than no guard, because it is trusted. The
29
- * first version of this file had four blind spots, each of which let a REAL
42
+ * first version of this file had five blind spots, each of which let a REAL
30
43
  * violation through (or flagged a non-violation), so the walker below is written
31
44
  * to close them and each is covered by a test:
32
45
  *
@@ -93,7 +106,7 @@ const CORE_HEADLESS = "@copilotkit/react-core/headless";
93
106
  // grammars + themes), plus mermaid, cytoscape and katex. Metro does not
94
107
  // tree-shake, so ONE import of that specifier from anywhere in this package puts
95
108
  // all of it in every consumer's app bundle (issue #4893). PR #5883 moved the lean
96
- // hooks into /v2/headless precisely so this package never needs the fat entry.
109
+ // hooks into /headless precisely so this package never needs the fat entry.
97
110
  const ALLOWED_REACT_CORE_ENTRIES = [
98
111
  CORE_HEADLESS,
99
112
  "@copilotkit/react-core/context",
@@ -140,21 +153,6 @@ const FORBIDDEN_REGISTRY_APIS: readonly (readonly [
140
153
  ],
141
154
  ];
142
155
 
143
- // Deliberate exemptions from FORBIDDEN_REGISTRY_APIS: one file, one identifier,
144
- // and the reason it is not a tool/renderer registry. File paths are relative to
145
- // src/ and use forward slashes.
146
- const REGISTRY_API_EXEMPTIONS: readonly (readonly [
147
- file: string,
148
- identifier: string,
149
- why: string,
150
- ])[] = [
151
- [
152
- "components/MarkdownRendererContext.tsx",
153
- "createContext",
154
- "holds the provider-level `markdownRenderer` (a component, or config for the built-in markdown renderer). It stores no tools and no tool-call renderers",
155
- ],
156
- ];
157
-
158
156
  // Heavy modules that must never appear as a direct import from this package.
159
157
  // (Transitive leakage through react-core's own entry is covered separately by
160
158
  // packages/react-core/scripts/assert-headless-purity.mjs — this walker cannot
@@ -170,6 +168,100 @@ const FORBIDDEN_HEAVY = [
170
168
  "@copilotkit/runtime-client-gql",
171
169
  ];
172
170
 
171
+ /**
172
+ * Deliberate exceptions to FORBIDDEN_REGISTRY_APIS. Each one removes exactly
173
+ * the declaration it names from that one file before the scan, so a second
174
+ * context (or any other registry API) in the same file still trips the ban.
175
+ *
176
+ * `file` is POSIX-style relative to src/, and is compared after normalising
177
+ * `path.relative`'s separators (which are `\` on Windows).
178
+ *
179
+ * Every declaration must match exactly once in the file it names. One that no
180
+ * longer matches (the declaration was reformatted, renamed or removed, or the
181
+ * file moved) is reported as a STALE exemption, naming the exemption and its
182
+ * reason, rather than doing nothing and leaving the identifier ban to blame
183
+ * `createContext` for what is really an out-of-date exemption.
184
+ */
185
+ interface RegistryApiExemption {
186
+ file: string;
187
+ /** Each is replaced by its group 1 (what to keep), once. */
188
+ declarations: RegExp[];
189
+ reason: string;
190
+ }
191
+
192
+ const REGISTRY_API_EXEMPTIONS: readonly RegistryApiExemption[] = [
193
+ {
194
+ file: "components/MarkdownRendererContext.tsx",
195
+ declarations: [
196
+ /(import React, \{ )createContext, /,
197
+ /(const Ctx = )createContext<MarkdownRendererValue \| undefined>\(undefined\);/,
198
+ ],
199
+ reason:
200
+ "holds the provider-level `markdownRenderer` (a component, or config for the built-in markdown renderer). It stores no tools and no tool-call renderers",
201
+ },
202
+ {
203
+ file: "generative-ui/GenerativeUIProvider.tsx",
204
+ declarations: [
205
+ /(import React, \{ )createContext, /,
206
+ /()export const GenerativeUIProviderPresentContext = createContext\(false\);/,
207
+ ],
208
+ reason:
209
+ "a boolean that tells the components below 'no provider' from 'a provider without ui'; it holds no tools or renderers",
210
+ },
211
+ ];
212
+
213
+ /** A path relative to src/, with `/` separators on every platform. */
214
+ const srcRelative = (file: string) =>
215
+ path.relative(srcDir, file).replace(/\\/g, "/");
216
+
217
+ /** How many times `re` matches `code`, ignoring its own `g` flag. */
218
+ const countMatches = (code: string, re: RegExp) =>
219
+ [...code.matchAll(new RegExp(re.source, re.flags.replace("g", "") + "g"))]
220
+ .length;
221
+
222
+ /**
223
+ * Every use of a FORBIDDEN_REGISTRY_APIS identifier in the given modules, as
224
+ * `file: identifier — why`, plus every stale exemption among the files given.
225
+ * Comments are stripped first: the modules name these APIs in prose to explain
226
+ * why they do NOT call them, and a raw text match would fail on the
227
+ * documentation.
228
+ */
229
+ function registryOffenders(
230
+ files: Iterable<string>,
231
+ exemptions: readonly RegistryApiExemption[] = REGISTRY_API_EXEMPTIONS,
232
+ ): string[] {
233
+ const offenders: string[] = [];
234
+ for (const file of files) {
235
+ const here = srcRelative(file);
236
+ let code = stripComments(fs.readFileSync(file, "utf8"));
237
+ const applied = exemptions.filter((e) => e.file === here);
238
+ for (const exemption of applied) {
239
+ for (const declaration of exemption.declarations) {
240
+ const matches = countMatches(code, declaration);
241
+ if (matches !== 1) {
242
+ offenders.push(
243
+ `${here}: stale exemption — ${declaration} matched ${matches} ` +
244
+ `time(s), not once. Update or remove the exemption for ` +
245
+ `"${exemption.reason}"`,
246
+ );
247
+ }
248
+ code = code.replace(declaration, "$1");
249
+ }
250
+ }
251
+ for (const [identifier, why] of FORBIDDEN_REGISTRY_APIS) {
252
+ if (new RegExp(`\\b${identifier}\\b`).test(code)) {
253
+ const exempted = applied.length
254
+ ? ` (this file's exemption, "${applied
255
+ .map((e) => e.reason)
256
+ .join("; ")}", does not cover this use)`
257
+ : "";
258
+ offenders.push(`${here}: ${identifier} — ${why}${exempted}`);
259
+ }
260
+ }
261
+ }
262
+ return offenders;
263
+ }
264
+
173
265
  const indexEntry = path.join(srcDir, "index.ts");
174
266
  const pkgJsonPath = path.resolve(srcDir, "..", "package.json");
175
267
 
@@ -202,9 +294,22 @@ interface PkgManifest {
202
294
  * allow-list, and it is READ from package.json rather than hand-copied so it
203
295
  * cannot drift from the manifest it is meant to describe. Anything else in the
204
296
  * graph is a package the consumer may not have: every optional peer
205
- * (`@gorhom/bottom-sheet`, `expo-*`, `react-native-streamdown`, `zod`), any
206
- * brand-new third-party edge, and any Node builtin (which RN has no business
207
- * reaching). This package's OWN name is deliberately absent, which is what keeps
297
+ * (`@gorhom/bottom-sheet`, `expo-document-picker`, `expo-file-system`,
298
+ * `react-native-gesture-handler`, `react-native-reanimated`,
299
+ * `react-native-streamdown`, `zod`), any brand-new third-party edge, and any
300
+ * Node builtin (which RN has no business reaching).
301
+ *
302
+ * The walk covers this package's OWN sources only, so this set bounds what
303
+ * THEY import, not what the consumer must install in total. `zod` is the case
304
+ * in point: it is an optional peer here, and no module of this package imports
305
+ * it, yet every entry needs it at runtime — react-core's `/headless`, which
306
+ * both entries import, loads `zod` on import, and react-core declares it as a
307
+ * REQUIRED peer (`>=3.25`). It stays an optional peer at `>=3.0.0` here only
308
+ * because making a peer required, or narrowing its range, is a breaking change
309
+ * under scripts/release/lib/breaking-change-gate.ts; react-core's own peer is
310
+ * what makes the consumer install it, at `>=3.25`.
311
+ *
312
+ * This package's OWN name is deliberately absent, which is what keeps
208
313
  * this test doubling as the comment-stripping regression: the eight phantom
209
314
  * `@copilotkit/react-native…` specifiers that JSDoc examples used to harvest are
210
315
  * all self-references, so if `stripComments` regresses they fail here.
@@ -240,6 +345,14 @@ function packageNameOf(spec: string): string {
240
345
  return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]!;
241
346
  }
242
347
 
348
+ /**
349
+ * `@copilotkit/react-core` or one of its subpaths — by package name, not by
350
+ * prefix, so a sibling package such as `@copilotkit/react-core-foo` is not
351
+ * mistaken for an entry of react-core.
352
+ */
353
+ const isReactCoreSpec = (spec: string) =>
354
+ packageNameOf(spec) === "@copilotkit/react-core";
355
+
243
356
  /**
244
357
  * Comment / string / template alternation, scanned left-to-right in ONE pass.
245
358
  *
@@ -412,12 +525,137 @@ function graphFor(entry: string): Graph {
412
525
  const rel = (files: Iterable<string>) =>
413
526
  [...files].map((f) => path.relative(srcDir, f)).sort();
414
527
 
415
- const ENTRIES: [label: string, entry: string][] = [
416
- ["headless", headlessEntry],
417
- ["default barrel", indexEntry],
528
+ interface ExportingManifest extends PkgManifest {
529
+ name?: string;
530
+ exports?: unknown;
531
+ }
532
+
533
+ const readManifest = (file: string) =>
534
+ JSON.parse(fs.readFileSync(file, "utf8")) as ExportingManifest;
535
+
536
+ /**
537
+ * The file an export resolves to for `import` (else `require`, else
538
+ * `default`), following nested condition objects; null for anything else.
539
+ */
540
+ function exportTarget(value: unknown): string | null {
541
+ if (typeof value === "string") return value;
542
+ if (value && typeof value === "object") {
543
+ for (const condition of ["import", "require", "default"]) {
544
+ const target = exportTarget(
545
+ (value as Record<string, unknown>)[condition],
546
+ );
547
+ if (target) return target;
548
+ }
549
+ }
550
+ return null;
551
+ }
552
+
553
+ /** `./dist/a/b.mjs` -> the `src/a/b.ts(x)` tsdown built it from, if any. */
554
+ function sourceOfDistTarget(target: string): string | null {
555
+ const m = /^\.\/dist\/(.+)\.(?:mjs|cjs|js)$/.exec(target);
556
+ if (!m) return null;
557
+ const base = path.join(srcDir, ...m[1]!.split("/"));
558
+ return [`${base}.ts`, `${base}.tsx`].find((c) => fs.existsSync(c)) ?? null;
559
+ }
560
+
561
+ /** An export subpath, or bare specifier, with a `generative-ui` segment. */
562
+ const hasGenerativeUISegment = (subpath: string) =>
563
+ subpath.split("/").includes("generative-ui");
564
+
565
+ /** Export keys of this package that carry no module to walk, and why. */
566
+ const NON_CODE_EXPORTS: Record<string, string> = {
567
+ "./package.json": "the manifest itself",
568
+ };
569
+
570
+ /**
571
+ * The entries to walk, DERIVED from this package's `exports` map rather than
572
+ * typed in: a hand-written list missed the published `/components` entry, so
573
+ * none of the per-entry bans below applied to it. Every code export lands in
574
+ * exactly one place — `entries` (all the bans below), or `generativeUI` (the
575
+ * opt-in entry, walked by its own `describe`) — and anything that cannot be
576
+ * mapped back to a source module is a `problem`, which a test fails on.
577
+ *
578
+ * Runs at collection time, so it must not throw (blind spot #4 above):
579
+ * failures are collected, not raised.
580
+ */
581
+ function deriveEntries(): {
582
+ entries: [label: string, entry: string][];
583
+ generativeUI: string[];
584
+ problems: string[];
585
+ } {
586
+ const entries: [string, string][] = [];
587
+ const generativeUI: string[] = [];
588
+ const problems: string[] = [];
589
+ try {
590
+ const exportsMap = readManifest(pkgJsonPath).exports;
591
+ if (!exportsMap || typeof exportsMap !== "object") {
592
+ return { entries, generativeUI, problems: ["no `exports` map"] };
593
+ }
594
+ for (const [key, value] of Object.entries(exportsMap)) {
595
+ if (key in NON_CODE_EXPORTS) continue;
596
+ const target = exportTarget(value);
597
+ const source = target ? sourceOfDistTarget(target) : null;
598
+ if (!source) {
599
+ problems.push(
600
+ `${key} -> ${target ?? JSON.stringify(value)}: no src/ module found ` +
601
+ `for it. Teach sourceOfDistTarget the new layout, or add the key ` +
602
+ `to NON_CODE_EXPORTS with a reason.`,
603
+ );
604
+ } else if (hasGenerativeUISegment(key)) {
605
+ generativeUI.push(source);
606
+ } else {
607
+ entries.push([`@copilotkit/react-native${key.slice(1)}`, source]);
608
+ }
609
+ }
610
+ } catch (err) {
611
+ problems.push(`could not read the exports of ${pkgJsonPath}: ${err}`);
612
+ }
613
+ return { entries, generativeUI, problems };
614
+ }
615
+
616
+ const DERIVED_ENTRIES = deriveEntries();
617
+
618
+ // Never empty at collection, so the it.each tables below always register: if
619
+ // the derivation broke, they fall back to the two entries this guard was first
620
+ // written for, and the derivation test reports why.
621
+ const ENTRIES: [label: string, entry: string][] = DERIVED_ENTRIES.entries.length
622
+ ? DERIVED_ENTRIES.entries
623
+ : [
624
+ ["@copilotkit/react-native/headless", headlessEntry],
625
+ ["@copilotkit/react-native", indexEntry],
626
+ ];
627
+
628
+ /** Entries the derivation must find. A floor, not the list. */
629
+ const REQUIRED_ENTRIES = [
630
+ headlessEntry,
631
+ indexEntry,
632
+ path.join(srcDir, "components", "index.ts"),
418
633
  ];
419
634
 
420
635
  describe("@copilotkit/react-native/headless entry", () => {
636
+ it("walks every code export of package.json", () => {
637
+ expect(
638
+ DERIVED_ENTRIES.problems,
639
+ `package.json exports that this guard cannot map to an entry module:\n ` +
640
+ DERIVED_ENTRIES.problems.join("\n "),
641
+ ).toEqual([]);
642
+ const walked = ENTRIES.map(([, entry]) => entry);
643
+ const missing = REQUIRED_ENTRIES.filter((e) => !walked.includes(e));
644
+ expect(
645
+ missing,
646
+ `the entries derived from package.json exports do not include ` +
647
+ `${rel(missing).join(", ")} — the derivation is broken. Derived: ` +
648
+ `${rel(walked).join(", ")}`,
649
+ ).toEqual([]);
650
+ // The opt-in entry is walked by its own describe below, against the path
651
+ // it hard-codes; make sure that path is the one package.json publishes.
652
+ expect(
653
+ DERIVED_ENTRIES.generativeUI,
654
+ "package.json's generative-ui export(s) do not resolve to the entry the " +
655
+ "generative UI describe walks",
656
+ ).toEqual([path.join(srcDir, "generative-ui", "index.ts")]);
657
+ });
658
+
421
659
  // Runs for real now: nothing walks the graph before collection finishes, so a
422
660
  // missing entry file reports HERE instead of erroring the whole suite out.
423
661
  it.each(ENTRIES)("has a %s entry file", (_label, entry) => {
@@ -530,26 +768,7 @@ describe("@copilotkit/react-native/headless entry", () => {
530
768
  const { seen } = graphFor(headlessEntry);
531
769
  // Non-vacuity comes from REQUIRED_HEADLESS_MODULES above (a truncated walk
532
770
  // fails there first), so this only has to be a deny-list.
533
- const offenders: string[] = [];
534
- for (const file of seen) {
535
- // Comments stripped: this file's own graph is heavily documented and the
536
- // modules in it name these APIs in prose to explain why they do NOT call
537
- // them. A raw text match would fail on the documentation.
538
- const code = stripComments(fs.readFileSync(file, "utf8"));
539
- const relFile = path.relative(srcDir, file).split(path.sep).join("/");
540
- for (const [identifier, why] of FORBIDDEN_REGISTRY_APIS) {
541
- const exempt = REGISTRY_API_EXEMPTIONS.some(
542
- ([exemptFile, exemptIdentifier]) =>
543
- exemptFile === relFile && exemptIdentifier === identifier,
544
- );
545
- if (exempt) continue;
546
- if (new RegExp(`\\b${identifier}\\b`).test(code)) {
547
- offenders.push(
548
- `${path.relative(srcDir, file)}: ${identifier} — ${why}`,
549
- );
550
- }
551
- }
552
- }
771
+ const offenders = registryOffenders(seen);
553
772
  expect(
554
773
  offenders,
555
774
  `module(s) in the headless graph touch registry internals directly:\n ` +
@@ -560,11 +779,11 @@ describe("@copilotkit/react-native/headless entry", () => {
560
779
  });
561
780
 
562
781
  /**
563
- * The four checks below need the entry EVALUATED, not just read: they assert
782
+ * The six checks below need the entry EVALUATED, not just read: they assert
564
783
  * that the named exports exist as runtime values (a re-export of a name that
565
784
  * no longer exists is a runtime hole a static read cannot see). So the import
566
785
  * stays — but it is paid exactly once, in a hook, rather than being raced by
567
- * four tests against the default per-test budget.
786
+ * six tests against the default per-test budget.
568
787
  *
569
788
  * Why the budget below is what it is. Nothing here is hung or polling — the
570
789
  * cost is a ONE-TIME module-graph load (resolve + transform + evaluate), paid
@@ -573,12 +792,13 @@ describe("@copilotkit/react-native/headless entry", () => {
573
792
  *
574
793
  * - vitest.config.mjs sets `server.deps.inline: [/@copilotkit/]`, so the
575
794
  * workspace dists this entry pulls are transformed rather than loaded
576
- * natively: ~283 KB (core ~218 KB, react-core v2/headless ~55 KB, plus
577
- * v2/context and shared), on top of the 11 RN source modules.
578
- * - Measured on one dev machine: ~0.9–1.8s inside the full 22-file suite
579
- * (n=8), ~0.7–1.1s for this file alone (n=8) — but 4568ms on the run
580
- * straight after a cold `nx build`, i.e. 91% of the 5s budget, and the
581
- * 4 independent agents who hit this hit it as an outright timeout. Bare
795
+ * natively: ~283 KB (core ~218 KB, react-core /headless ~55 KB, plus
796
+ * /context and shared), on top of the 11 RN source modules.
797
+ * - Measured on one dev machine: ~0.9–1.8s inside the full suite as it
798
+ * was then (22 test files; there are more now) (n=8), ~0.7–1.1s for
799
+ * this file alone (n=8) — but 4568ms on the run straight after a cold
800
+ * `nx build`, i.e. 91% of the 5s budget, and the 4 independent
801
+ * agents who hit this hit it as an outright timeout. Bare
582
802
  * Node `import()` of the equivalent prebuilt dist is 461ms, so the spread
583
803
  * is resolve/transform and page-cache-cold I/O, both load-sensitive.
584
804
  *
@@ -587,7 +807,7 @@ describe("@copilotkit/react-native/headless entry", () => {
587
807
  * ~0ms. A genuinely hung import still fails, just not spuriously. Lowering it
588
808
  * re-introduces the flake; lowering the COST would mean not inlining
589
809
  * `@copilotkit/core` for this suite, which is a shared-config change affecting
590
- * all 22 test files rather than something this file can do.
810
+ * every test file in this package rather than something this file can do.
591
811
  */
592
812
  const IMPORT_BUDGET_MS = 60_000;
593
813
 
@@ -600,7 +820,7 @@ describe("@copilotkit/react-native/headless entry", () => {
600
820
  let coreHeadless: typeof CoreHeadlessEntry;
601
821
 
602
822
  beforeAll(async () => {
603
- // Both loads live in the ONE budgeted hook. core's /v2/headless is already
823
+ // Both loads live in the ONE budgeted hook. core's /headless is already
604
824
  // inside this entry's own graph, so importing it here is a module-cache
605
825
  // hit rather than a second traversal.
606
826
  [mod, coreHeadless] = await Promise.all([
@@ -737,13 +957,11 @@ describe("@copilotkit/react-native/headless entry", () => {
737
957
  // Applies to BOTH entries: the fat-entry ban is package-wide, unlike the
738
958
  // native-peer-dep ban above which only constrains the headless entry.
739
959
  it.each(ENTRIES)(
740
- "%s entry imports no react-core entry other than /v2/headless and /v2/context",
960
+ "%s entry imports no react-core entry other than /headless and /context",
741
961
  (_label, entry) => {
742
962
  const { bareSpecs } = graphFor(entry);
743
963
  const offenders = [...bareSpecs].filter(
744
- (s) =>
745
- s.startsWith("@copilotkit/react-core") &&
746
- !ALLOWED_REACT_CORE_ENTRIES.includes(s),
964
+ (s) => isReactCoreSpec(s) && !ALLOWED_REACT_CORE_ENTRIES.includes(s),
747
965
  );
748
966
  expect(
749
967
  offenders,
@@ -764,3 +982,704 @@ describe("@copilotkit/react-native/headless entry", () => {
764
982
  },
765
983
  );
766
984
  });
985
+
986
+ // ─── @copilotkit/react-native/generative-ui ─────────────────────────────────
987
+ // The generative UI entry is opt-in. It may use react-core's DOM-free generative
988
+ // UI entry, and nothing else of react-core but the shared context; and no other
989
+ // entry may reach it, so a consumer that does not use generative UI never
990
+ // bundles the surface engine or the catalog schemas of @copilotkit/shared.
991
+ // (zod is in the bundle of every entry regardless, but for different reasons:
992
+ // the headless and default entries load it through react-core's /headless,
993
+ // and this entry through react-core's /generative-ui/native, whose chat
994
+ // chunk imports it.)
995
+ const generativeUIEntry = path.join(srcDir, "generative-ui", "index.ts");
996
+ const GENERATIVE_UI_REACT_CORE_ENTRIES = [
997
+ "@copilotkit/react-core/context",
998
+ "@copilotkit/react-core/generative-ui/native",
999
+ ];
1000
+ const REQUIRED_GENERATIVE_UI_MODULES = [
1001
+ path.join("generative-ui", "index.ts"),
1002
+ path.join("generative-ui", "GenerativeUIProvider.tsx"),
1003
+ path.join("generative-ui", "GenerativeUIActivity.tsx"),
1004
+ path.join("generative-ui", "GenerativeUISurface.tsx"),
1005
+ path.join("generative-ui", "host.tsx"),
1006
+ ];
1007
+
1008
+ /**
1009
+ * Bare specifiers the generative UI graph MUST harvest. The same non-vacuity
1010
+ * floor as REQUIRED_HEADLESS_BARE: the react-core allow-list and the heavy/DOM
1011
+ * deny-lists below are all filters over `bareSpecs`, and every one of them
1012
+ * passes on an empty set. These two are the edges the entry exists for — the
1013
+ * catalog engine, and the host elements it renders into — so a walk that stops
1014
+ * harvesting them is a walk that is no longer checking anything.
1015
+ */
1016
+ const REQUIRED_GENERATIVE_UI_BARE = [
1017
+ "@copilotkit/react-core/generative-ui/native",
1018
+ "react-native",
1019
+ ];
1020
+
1021
+ /**
1022
+ * Optional peers the generative UI entry is DELIBERATELY allowed to reach, on
1023
+ * top of guaranteedPackages(). None today.
1024
+ *
1025
+ * zod needs no entry: it is not a peer of this package. react-core,
1026
+ * `@copilotkit/core` and `@copilotkit/shared` list it in their own
1027
+ * `dependencies`, so the copy they load is theirs and asks the consumer for
1028
+ * nothing.
1029
+ *
1030
+ * Every optional peer stays unsanctioned: the chat/attachment natives
1031
+ * (`@gorhom/bottom-sheet`, `expo-document-picker`, `expo-file-system`) are
1032
+ * things a generative-UI-only consumer has not been told to install. Extend
1033
+ * this list only with a reason.
1034
+ */
1035
+ const GENERATIVE_UI_ALLOWED_OPTIONAL_PEERS: string[] = [];
1036
+
1037
+ /**
1038
+ * Bare specifiers that ARE generative UI, matched exactly or as a subpath
1039
+ * prefix (never by substring, so an unrelated package whose name merely
1040
+ * contains "generative-ui" neither trips nor hides behind the check).
1041
+ *
1042
+ * DERIVED from the `exports` maps of every workspace package (and of every
1043
+ * `@copilotkit/*` dependency of this package, wherever it resolves): each
1044
+ * export subpath with a `generative-ui` segment. The hand-written list it
1045
+ * replaces missed `@copilotkit/shared/generative-ui` — the catalog schemas —
1046
+ * so the headless and default entries could have imported them unnoticed.
1047
+ *
1048
+ * GENERATIVE_UI_BARE_FLOOR is not the list. It is what the derivation must at
1049
+ * least find, so a derivation that silently finds nothing fails a test instead
1050
+ * of turning the ban off; and it is unioned in, so the ban holds meanwhile.
1051
+ */
1052
+ const matchesBare = (spec: string, dep: string) =>
1053
+ spec === dep || spec.startsWith(`${dep}/`);
1054
+
1055
+ const GENERATIVE_UI_BARE_FLOOR = [
1056
+ "@copilotkit/react-native/generative-ui",
1057
+ "@copilotkit/react-core/generative-ui",
1058
+ "@copilotkit/core/generative-ui",
1059
+ "@copilotkit/shared/generative-ui",
1060
+ ];
1061
+
1062
+ const workspacePackagesDir = path.resolve(srcDir, "..", "..");
1063
+
1064
+ /**
1065
+ * name -> `exports` of every package the derivation reads. Collection-time
1066
+ * and must not throw (blind spot #4): failures are collected as problems.
1067
+ */
1068
+ function scanExportsMaps(): {
1069
+ manifests: Map<string, unknown>;
1070
+ problems: string[];
1071
+ } {
1072
+ const manifests = new Map<string, unknown>();
1073
+ const problems: string[] = [];
1074
+ const add = (file: string) => {
1075
+ try {
1076
+ const pkg = readManifest(file);
1077
+ if (pkg.name && !manifests.has(pkg.name))
1078
+ manifests.set(pkg.name, pkg.exports);
1079
+ } catch (err) {
1080
+ problems.push(`could not read ${file}: ${err}`);
1081
+ }
1082
+ };
1083
+ try {
1084
+ for (const dir of fs.readdirSync(workspacePackagesDir)) {
1085
+ const file = path.join(workspacePackagesDir, dir, "package.json");
1086
+ if (fs.existsSync(file)) add(file);
1087
+ }
1088
+ // Belt and braces for a dependency that is not (or no longer) a
1089
+ // workspace package: read the manifest the consumer would resolve.
1090
+ const own = readManifest(pkgJsonPath);
1091
+ const requireHere = createRequire(pkgJsonPath);
1092
+ for (const name of Object.keys({
1093
+ ...own.dependencies,
1094
+ ...own.peerDependencies,
1095
+ })) {
1096
+ if (!name.startsWith("@copilotkit/") || manifests.has(name)) continue;
1097
+ try {
1098
+ add(requireHere.resolve(`${name}/package.json`));
1099
+ } catch (err) {
1100
+ problems.push(`could not resolve ${name}/package.json: ${err}`);
1101
+ }
1102
+ }
1103
+ } catch (err) {
1104
+ problems.push(`could not scan ${workspacePackagesDir}: ${err}`);
1105
+ }
1106
+ return { manifests, problems };
1107
+ }
1108
+
1109
+ /** The derivation: every export subpath with a `generative-ui` segment. */
1110
+ function deriveGenerativeUIBare(manifests: Map<string, unknown>): string[] {
1111
+ const specs: string[] = [];
1112
+ for (const [name, exportsMap] of manifests) {
1113
+ if (!exportsMap || typeof exportsMap !== "object") continue;
1114
+ for (const key of Object.keys(exportsMap)) {
1115
+ if (hasGenerativeUISegment(key)) specs.push(`${name}${key.slice(1)}`);
1116
+ }
1117
+ }
1118
+ return specs.sort();
1119
+ }
1120
+
1121
+ /**
1122
+ * The cross-check, deliberately looser than the derivation: every export
1123
+ * whose subpath OR target mentions "generative-ui" at all (an export renamed
1124
+ * to `./genui` but still pointing at `dist/generative-ui/…`, or a
1125
+ * `./generative-ui-extras` subpath), that the derivation does not cover.
1126
+ */
1127
+ function uncoveredGenerativeUIExports(
1128
+ manifests: Map<string, unknown>,
1129
+ ): string[] {
1130
+ const derived = deriveGenerativeUIBare(manifests);
1131
+ const uncovered: string[] = [];
1132
+ for (const [name, exportsMap] of manifests) {
1133
+ if (!exportsMap || typeof exportsMap !== "object") continue;
1134
+ for (const [key, value] of Object.entries(exportsMap)) {
1135
+ const spec = `${name}${key.slice(1)}`;
1136
+ if (
1137
+ `${key} ${JSON.stringify(value)}`.includes("generative-ui") &&
1138
+ !derived.some((dep) => matchesBare(spec, dep))
1139
+ ) {
1140
+ uncovered.push(spec);
1141
+ }
1142
+ }
1143
+ }
1144
+ return uncovered.sort();
1145
+ }
1146
+
1147
+ const EXPORTS_SCAN = scanExportsMaps();
1148
+
1149
+ const GENERATIVE_UI_BARE = [
1150
+ ...new Set([
1151
+ ...deriveGenerativeUIBare(EXPORTS_SCAN.manifests),
1152
+ ...GENERATIVE_UI_BARE_FLOOR,
1153
+ ]),
1154
+ ].sort();
1155
+
1156
+ describe("@copilotkit/react-native/generative-ui entry", () => {
1157
+ it("has an entry file", () => {
1158
+ expect(
1159
+ fs.existsSync(generativeUIEntry),
1160
+ `missing entry file: ${generativeUIEntry}`,
1161
+ ).toBe(true);
1162
+ });
1163
+
1164
+ it("resolves every relative import and has no unanalyzable loader", () => {
1165
+ const { unresolved, opaque } = graphFor(generativeUIEntry);
1166
+ expect(
1167
+ unresolved,
1168
+ `unresolvable relative imports in the generative UI graph — the walker ` +
1169
+ `cannot see past these, so a forbidden import hidden behind one would ` +
1170
+ `read as clean: ${unresolved.join(", ")}`,
1171
+ ).toEqual([]);
1172
+ expect(
1173
+ opaque,
1174
+ `import()/require() with a non-literal specifier in the generative UI ` +
1175
+ `graph cannot be checked. Make it a literal: ${opaque.join(", ")}`,
1176
+ ).toEqual([]);
1177
+ });
1178
+
1179
+ // The non-vacuity floor for every deny-list in this block.
1180
+ it("reaches the modules and bare imports it must reach", () => {
1181
+ const { seen, bareSpecs } = graphFor(generativeUIEntry);
1182
+ const reached = rel(seen);
1183
+ const missing = REQUIRED_GENERATIVE_UI_MODULES.filter(
1184
+ (m) => !reached.includes(m),
1185
+ );
1186
+ expect(
1187
+ missing,
1188
+ `the walk did not reach ${missing.join(", ")} — the checks below are ` +
1189
+ `then reasoning about a truncated graph. Reached: ${reached.join(", ")}`,
1190
+ ).toEqual([]);
1191
+ const missingBare = REQUIRED_GENERATIVE_UI_BARE.filter(
1192
+ (s) => !bareSpecs.has(s),
1193
+ );
1194
+ expect(
1195
+ missingBare,
1196
+ `no edge to ${missingBare.join(", ")} was harvested from the generative ` +
1197
+ `UI graph — the allow- and deny-lists below would pass on an empty set. ` +
1198
+ `Harvested: ${[...bareSpecs].sort().join(", ")}`,
1199
+ ).toEqual([]);
1200
+ });
1201
+
1202
+ it("draws only on guaranteed packages, plus the optional peers it is allowed", () => {
1203
+ const { seen, bareSpecs } = graphFor(generativeUIEntry);
1204
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8")) as PkgManifest;
1205
+ // An allowance for a package that is not even a declared optional peer is a
1206
+ // typo or a stale entry, and would quietly sanction nothing (or the wrong
1207
+ // thing); refuse it rather than trust it.
1208
+ const undeclared = GENERATIVE_UI_ALLOWED_OPTIONAL_PEERS.filter(
1209
+ (name) =>
1210
+ !pkg.peerDependencies?.[name] ||
1211
+ !pkg.peerDependenciesMeta?.[name]?.optional,
1212
+ );
1213
+ expect(
1214
+ undeclared,
1215
+ `GENERATIVE_UI_ALLOWED_OPTIONAL_PEERS names package(s) that are not ` +
1216
+ `optional peers in package.json: ${undeclared.join(", ")}`,
1217
+ ).toEqual([]);
1218
+ const allowed = new Set([
1219
+ ...guaranteedPackages(),
1220
+ ...GENERATIVE_UI_ALLOWED_OPTIONAL_PEERS,
1221
+ ]);
1222
+ const unsanctioned = [...bareSpecs]
1223
+ .filter((spec) => !allowed.has(packageNameOf(spec)))
1224
+ .sort();
1225
+ expect(
1226
+ unsanctioned,
1227
+ `the generative UI graph reaches package(s) a consumer of this entry is ` +
1228
+ `not guaranteed or told to have installed: ${unsanctioned.join(", ")}. ` +
1229
+ `Make it a dependency or non-optional peer in package.json, add it to ` +
1230
+ `GENERATIVE_UI_ALLOWED_OPTIONAL_PEERS with a reason, or drop the import. ` +
1231
+ `Graph: ${rel(seen).join(", ")}`,
1232
+ ).toEqual([]);
1233
+ });
1234
+
1235
+ it("imports only react-core's /context and DOM-free /generative-ui/native", () => {
1236
+ const { bareSpecs } = graphFor(generativeUIEntry);
1237
+ const offenders = [...bareSpecs].filter(
1238
+ (s) =>
1239
+ isReactCoreSpec(s) && !GENERATIVE_UI_REACT_CORE_ENTRIES.includes(s),
1240
+ );
1241
+ expect(
1242
+ offenders,
1243
+ `must import only ${GENERATIVE_UI_REACT_CORE_ENTRIES.join(" or ")} — ` +
1244
+ `found: ${offenders.join(", ")}. /generative-ui carries the DOM ` +
1245
+ `standard catalog (react-dom portals, KaTeX, streamdown), and the root entry the ` +
1246
+ `chat render stack (#4893).`,
1247
+ ).toEqual([]);
1248
+ });
1249
+
1250
+ it("pulls in neither the heavy render stack, the DOM, nor the chat/attachment peers", () => {
1251
+ const { bareSpecs, seen } = graphFor(generativeUIEntry);
1252
+ const banned = [...FORBIDDEN_HEAVY, ...FORBIDDEN_BARE, "react-dom"];
1253
+ const leaked = banned.filter((dep) =>
1254
+ [...bareSpecs].some((s) => matchesBare(s, dep)),
1255
+ );
1256
+ expect(
1257
+ leaked,
1258
+ `generative UI graph must not import: ${leaked.join(", ")}`,
1259
+ ).toEqual([]);
1260
+ // Base-name SUBSTRING matching, as in the headless block: a directory that
1261
+ // merely contains a forbidden name does not trip this, and a chat module
1262
+ // moved to another directory does not escape it — but any file whose base
1263
+ // name contains one (a `useCopilotChatState.ts`, say) does trip it.
1264
+ const chatModules = [...seen].filter((f) =>
1265
+ FORBIDDEN_LOCAL.some((name) =>
1266
+ path
1267
+ .basename(f)
1268
+ .replace(/\.tsx?$/, "")
1269
+ .includes(name),
1270
+ ),
1271
+ );
1272
+ expect(
1273
+ chatModules,
1274
+ `generative UI graph must not reach the chat UI / useAttachments ` +
1275
+ `modules: ${rel(chatModules).join(", ")}`,
1276
+ ).toEqual([]);
1277
+ });
1278
+
1279
+ // The same ban as the headless block's. The generative UI provider registers
1280
+ // no tool (CopilotRuntime adds `render_ui` on the server), and the
1281
+ // `render_ui` renderer is written into CopilotKitCoreReact by react-core's
1282
+ // `GenerativeUIToolCallRenderer` (chat.tsx, via `setRenderToolCalls`), which
1283
+ // the provider mounts — in react-core, outside this walk. What this pins is
1284
+ // narrower: no RN module grows a registry (or a context to hold one) next to
1285
+ // CopilotKitCoreReact. Non-vacuity comes from REQUIRED_GENERATIVE_UI_MODULES.
1286
+ it("owns no tool/renderer registry of its own anywhere in the generative UI graph", () => {
1287
+ const { seen } = graphFor(generativeUIEntry);
1288
+ const offenders = registryOffenders(seen);
1289
+ expect(
1290
+ offenders,
1291
+ `module(s) in the generative UI graph touch registry internals ` +
1292
+ `directly:\n ${offenders.join("\n ")}\n` +
1293
+ `CopilotKitCoreReact is the single registry and this package must reach ` +
1294
+ `it only through react-core's hooks.`,
1295
+ ).toEqual([]);
1296
+ });
1297
+
1298
+ it("applies the registry exemption when path.relative uses Windows separators", () => {
1299
+ // `path.relative` returns `\\`-separated paths on Windows, which the
1300
+ // POSIX-style exemption path never equalled, so the exemption silently did
1301
+ // not apply there and this graph's legitimate context failed the ban.
1302
+ const { seen } = graphFor(generativeUIEntry);
1303
+ const posixRelative = path.relative;
1304
+ const spy = vi
1305
+ .spyOn(path, "relative")
1306
+ .mockImplementation((from, to) =>
1307
+ posixRelative(from, to).split("/").join("\\"),
1308
+ );
1309
+ try {
1310
+ expect(registryOffenders(seen)).toEqual([]);
1311
+ } finally {
1312
+ spy.mockRestore();
1313
+ }
1314
+ });
1315
+
1316
+ it("has no stale registry exemption", () => {
1317
+ // Inside registryOffenders, a declaration that no longer matches is
1318
+ // already reported — but only for a file the walk reaches. A file that
1319
+ // moved or left the graph would make its exemption dead without a word,
1320
+ // so check reachability here, against every graph this file walks.
1321
+ const walked = new Set([
1322
+ ...graphFor(generativeUIEntry).seen,
1323
+ ...ENTRIES.flatMap(([, entry]) => [...graphFor(entry).seen]),
1324
+ ]);
1325
+ const stale = REGISTRY_API_EXEMPTIONS.filter(
1326
+ (e) => ![...walked].some((f) => srcRelative(f) === e.file),
1327
+ ).map((e) => `${e.file} ("${e.reason}")`);
1328
+ expect(
1329
+ stale,
1330
+ `stale registry exemption(s): the file is not in any walked graph ` +
1331
+ `(moved, renamed or no longer imported). Update or remove: ` +
1332
+ stale.join(", "),
1333
+ ).toEqual([]);
1334
+ const exemptedFiles = [...walked].filter((f) =>
1335
+ REGISTRY_API_EXEMPTIONS.some((e) => e.file === srcRelative(f)),
1336
+ );
1337
+ // Every exempted file is scanned on its own, so a declaration that no
1338
+ // longer matches exactly once is named here as stale, whichever graph it
1339
+ // is in.
1340
+ expect(
1341
+ registryOffenders(exemptedFiles).filter((o) =>
1342
+ o.includes("stale exemption"),
1343
+ ),
1344
+ ).toEqual([]);
1345
+ });
1346
+
1347
+ it("reports an exemption that no longer matches as stale, naming its reason", () => {
1348
+ // Self-test of the mechanism above, against a deliberately stale copy of
1349
+ // the real exemption: the old code applied it as a silent no-op and then
1350
+ // blamed `createContext` for it.
1351
+ const file = path.join(srcDir, "generative-ui", "GenerativeUIProvider.tsx");
1352
+ const exemption = REGISTRY_API_EXEMPTIONS.find(
1353
+ (e) => e.file === "generative-ui/GenerativeUIProvider.tsx",
1354
+ )!;
1355
+ const stale: RegistryApiExemption[] = REGISTRY_API_EXEMPTIONS.map((e) =>
1356
+ e === exemption
1357
+ ? {
1358
+ ...e,
1359
+ declarations: [
1360
+ ...e.declarations,
1361
+ /()createContext<boolean>\(false\);/,
1362
+ ],
1363
+ }
1364
+ : e,
1365
+ );
1366
+ const offenders = registryOffenders([file], stale);
1367
+ expect(offenders).toHaveLength(1);
1368
+ expect(offenders[0]).toContain("stale exemption");
1369
+ expect(offenders[0]).toContain(exemption.reason);
1370
+ });
1371
+
1372
+ it("derives the generative UI deny-list from every generative UI export", () => {
1373
+ expect(
1374
+ EXPORTS_SCAN.problems,
1375
+ `could not read every exports map the deny-list is derived from:\n ` +
1376
+ EXPORTS_SCAN.problems.join("\n "),
1377
+ ).toEqual([]);
1378
+ const derived = deriveGenerativeUIBare(EXPORTS_SCAN.manifests);
1379
+ const missingFloor = GENERATIVE_UI_BARE_FLOOR.filter(
1380
+ (s) => !derived.includes(s),
1381
+ );
1382
+ expect(
1383
+ missingFloor,
1384
+ `the exports-map derivation no longer finds ${missingFloor.join(", ")} — ` +
1385
+ `either the export was renamed or removed (update ` +
1386
+ `GENERATIVE_UI_BARE_FLOOR) or the derivation is broken. Derived: ` +
1387
+ derived.join(", "),
1388
+ ).toEqual([]);
1389
+ const uncovered = uncoveredGenerativeUIExports(EXPORTS_SCAN.manifests);
1390
+ expect(
1391
+ uncovered,
1392
+ `export(s) that mention generative-ui but are not covered by the ` +
1393
+ `derived deny-list: ${uncovered.join(", ")}. Give the export a ` +
1394
+ `\`generative-ui\` path segment, or teach deriveGenerativeUIBare about ` +
1395
+ `it, so the other entries are kept from reaching it.`,
1396
+ ).toEqual([]);
1397
+ });
1398
+
1399
+ it("the cross-check catches a generative UI export the derivation misses", () => {
1400
+ const manifests = new Map<string, unknown>([
1401
+ [
1402
+ "@copilotkit/example",
1403
+ {
1404
+ "./generative-ui": "./dist/generative-ui.mjs",
1405
+ "./genui": { import: "./dist/generative-ui/extra.mjs" },
1406
+ "./generative-ui-extras": "./dist/extras.mjs",
1407
+ "./other": "./dist/other.mjs",
1408
+ },
1409
+ ],
1410
+ ]);
1411
+ expect(deriveGenerativeUIBare(manifests)).toEqual([
1412
+ "@copilotkit/example/generative-ui",
1413
+ ]);
1414
+ expect(uncoveredGenerativeUIExports(manifests)).toEqual([
1415
+ "@copilotkit/example/generative-ui-extras",
1416
+ "@copilotkit/example/genui",
1417
+ ]);
1418
+ });
1419
+
1420
+ it.each(ENTRIES)(
1421
+ "the %s entry does not reach generative UI",
1422
+ (_label, entry) => {
1423
+ const { seen, bareSpecs } = graphFor(entry);
1424
+ const modules = rel(seen).filter((f) =>
1425
+ f.startsWith(`generative-ui${path.sep}`),
1426
+ );
1427
+ expect(
1428
+ modules,
1429
+ `this entry reaches the opt-in generative UI modules: ` +
1430
+ `${modules.join(", ")}. A consumer who never imports ` +
1431
+ `@copilotkit/react-native/generative-ui must not bundle them.`,
1432
+ ).toEqual([]);
1433
+ const specs = [...bareSpecs]
1434
+ .filter((s) => GENERATIVE_UI_BARE.some((dep) => matchesBare(s, dep)))
1435
+ .sort();
1436
+ expect(
1437
+ specs,
1438
+ `this entry imports generative UI: ${specs.join(", ")}. The surface ` +
1439
+ `engine and its catalog schemas belong only behind the opt-in ` +
1440
+ `@copilotkit/react-native/generative-ui entry.`,
1441
+ ).toEqual([]);
1442
+ },
1443
+ );
1444
+ });
1445
+
1446
+ // ─── react-core dist: one copy of each generative UI context ────────────────
1447
+ // The RN generative UI entry works only if the context its provider SETS and
1448
+ // the context its surfaces READ are the same object. GenerativeUIProvider puts
1449
+ // the runtime into react-core's `GenerativeUIRuntimeContext` and the host into
1450
+ // `GenerativeUIHostContext`, both imported from `/generative-ui/native`;
1451
+ // react-core's own hooks and SurfaceView read them from whatever chunk they
1452
+ // were bundled into. react-core's tsdown config keeps `/generative-ui/native`
1453
+ // in the main build precisely so that every entry shares ONE chunk carrying
1454
+ // these modules. If a config change inlined a second copy (native moved to its
1455
+ // own build, a chunking option), every typecheck and source-level test would
1456
+ // stay green — vitest and tsc see one source module — and a surface would
1457
+ // silently never see its runtime. react-core's context-singleton-preflight only
1458
+ // covers src/context.ts, so this checks the generative UI context modules in
1459
+ // the BUILT dist, by the `//#region <src path>` banner tsdown writes for every
1460
+ // inlined module (the same marker that preflight relies on).
1461
+ const reactCoreDir = (() => {
1462
+ try {
1463
+ return path.dirname(
1464
+ createRequire(pkgJsonPath).resolve("@copilotkit/react-core/package.json"),
1465
+ );
1466
+ } catch {
1467
+ return path.join(workspacePackagesDir, "react-core");
1468
+ }
1469
+ })();
1470
+
1471
+ /** Context modules that MUST be bundled exactly once per format. A floor. */
1472
+ const REQUIRED_SINGLE_CONTEXT_MODULES = [
1473
+ "src/generative-ui/runtime-context.ts",
1474
+ "src/generative-ui/host.tsx",
1475
+ ];
1476
+
1477
+ /** Every file under `dir` (recursively) whose name matches `re`. */
1478
+ function filesUnder(dir: string, re: RegExp): string[] {
1479
+ const out: string[] = [];
1480
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1481
+ const full = path.join(dir, entry.name);
1482
+ if (entry.isDirectory()) {
1483
+ if (entry.name !== "__tests__") out.push(...filesUnder(full, re));
1484
+ } else if (re.test(entry.name)) {
1485
+ out.push(full);
1486
+ }
1487
+ }
1488
+ return out;
1489
+ }
1490
+
1491
+ describe("@copilotkit/react-core dist: one copy of each generative UI context", () => {
1492
+ it("bundles every generative UI context module at most once per format", () => {
1493
+ const distDir = path.join(reactCoreDir, "dist");
1494
+ expect(
1495
+ fs.existsSync(distDir),
1496
+ `${distDir} does not exist — build @copilotkit/react-core first`,
1497
+ ).toBe(true);
1498
+ // Derived from source: every generative UI module that calls
1499
+ // createContext, so a new context module is covered without listing it.
1500
+ const contextModules = filesUnder(
1501
+ path.join(reactCoreDir, "src", "generative-ui"),
1502
+ /\.tsx?$/,
1503
+ )
1504
+ .filter((f) =>
1505
+ /\bcreateContext\s*[<(]/.test(
1506
+ stripComments(fs.readFileSync(f, "utf8")),
1507
+ ),
1508
+ )
1509
+ .map((f) => path.relative(reactCoreDir, f).split(path.sep).join("/"))
1510
+ .sort();
1511
+ const missingFloor = REQUIRED_SINGLE_CONTEXT_MODULES.filter(
1512
+ (m) => !contextModules.includes(m),
1513
+ );
1514
+ expect(
1515
+ missingFloor,
1516
+ `no createContext found in ${missingFloor.join(", ")} — the source scan ` +
1517
+ `is broken or the module moved; update REQUIRED_SINGLE_CONTEXT_MODULES`,
1518
+ ).toEqual([]);
1519
+
1520
+ // UMD bundles are self-contained by design (as in react-core's own
1521
+ // preflight), so only the ESM and CJS module graphs are checked.
1522
+ const bundles = filesUnder(distDir, /\.(?:mjs|cjs)$/).map((f) => ({
1523
+ file: path.relative(distDir, f).split(path.sep).join("/"),
1524
+ code: fs.readFileSync(f, "utf8"),
1525
+ }));
1526
+ const problems: string[] = [];
1527
+ for (const contextModule of contextModules) {
1528
+ const marker = `//#region ${contextModule}\n`;
1529
+ for (const format of ["mjs", "cjs"]) {
1530
+ const carriers = bundles
1531
+ .filter(
1532
+ (b) => b.file.endsWith(`.${format}`) && b.code.includes(marker),
1533
+ )
1534
+ .map((b) => b.file);
1535
+ const required =
1536
+ REQUIRED_SINGLE_CONTEXT_MODULES.includes(contextModule);
1537
+ if (carriers.length > 1 || (required && carriers.length !== 1)) {
1538
+ problems.push(
1539
+ `${contextModule} is in ${carriers.length} .${format} file(s)` +
1540
+ (carriers.length ? `: ${carriers.join(", ")}` : "") +
1541
+ (required && !carriers.length
1542
+ ? " (expected exactly 1 — or tsdown's region banner changed, " +
1543
+ "and this check can no longer see duplicates)"
1544
+ : ""),
1545
+ );
1546
+ }
1547
+ }
1548
+ }
1549
+ expect(
1550
+ problems,
1551
+ `a generative UI context module is bundled more than once in ` +
1552
+ `@copilotkit/react-core's dist, so a provider and the components ` +
1553
+ `below it can hold different context objects:\n ` +
1554
+ problems.join("\n "),
1555
+ ).toEqual([]);
1556
+ });
1557
+ });
1558
+
1559
+ /**
1560
+ * The first module a source file loads at runtime, in source order: type-only
1561
+ * imports and re-exports are erased, so they are skipped. Null if it loads none.
1562
+ */
1563
+ function firstRuntimeSpecifier(code: string): string | null {
1564
+ const stripped = stripComments(code);
1565
+ const patterns = [
1566
+ /\b(import)\s+(type\s+)?[^;"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,
1567
+ /\b(import)\s*()["'`]([^"'`]+)["'`]/g,
1568
+ /\b(export)\s+(type\s+)?[^;"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,
1569
+ ];
1570
+ let first: { index: number; spec: string } | null = null;
1571
+ for (const re of patterns) {
1572
+ for (const m of stripped.matchAll(re)) {
1573
+ if (m[2]) continue;
1574
+ if (!first || m.index! < first.index) {
1575
+ first = { index: m.index!, spec: m[3]! };
1576
+ }
1577
+ }
1578
+ }
1579
+ return first?.spec ?? null;
1580
+ }
1581
+
1582
+ /** `src/polyfills.ts` and the five modules under `src/polyfills/`. */
1583
+ const polyfillsBarrel = path.join(srcDir, "polyfills.ts");
1584
+ const isPolyfillModule = (file: string) =>
1585
+ file === polyfillsBarrel ||
1586
+ path.dirname(file) === path.join(srcDir, "polyfills");
1587
+
1588
+ /**
1589
+ * Every published entry that loads CopilotKit code. The polyfill subpaths are
1590
+ * the polyfills themselves; everything else reaches @copilotkit/core or
1591
+ * @ag-ui/client, which need ReadableStream / TextEncoder / crypto at load time
1592
+ * on Hermes.
1593
+ */
1594
+ const CODE_ENTRIES: [label: string, entry: string][] = [
1595
+ ...ENTRIES.filter(([, entry]) => !isPolyfillModule(entry)),
1596
+ ...DERIVED_ENTRIES.generativeUI.map(
1597
+ (entry) =>
1598
+ ["@copilotkit/react-native/generative-ui", entry] as [string, string],
1599
+ ),
1600
+ ];
1601
+
1602
+ /**
1603
+ * A glob from package.json `sideEffects` -> a RegExp over `./`-relative paths.
1604
+ * Only the two wildcards this package uses: `**` (any depth) and `*`.
1605
+ */
1606
+ const regexLiteral = (part: string) =>
1607
+ part.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
1608
+
1609
+ function sideEffectsGlob(glob: string): RegExp {
1610
+ const body = glob
1611
+ .split("**/")
1612
+ .map((seg) =>
1613
+ seg
1614
+ .split("**")
1615
+ .map((part) => part.split("*").map(regexLiteral).join("[^/]*"))
1616
+ .join(".*"),
1617
+ )
1618
+ .join("(?:.*/)?");
1619
+ return new RegExp(`^${body}$`);
1620
+ }
1621
+
1622
+ describe("every published entry installs the polyfills before CopilotKit loads", () => {
1623
+ it("covers the root, /headless and /generative-ui entries at least", () => {
1624
+ const walked = CODE_ENTRIES.map(([, entry]) => entry);
1625
+ const floor = [
1626
+ indexEntry,
1627
+ headlessEntry,
1628
+ path.join(srcDir, "generative-ui", "index.ts"),
1629
+ ];
1630
+ expect(
1631
+ floor.filter((e) => !walked.includes(e)),
1632
+ `entries missing from the polyfill-order check; derived: ${rel(walked).join(", ")}`,
1633
+ ).toEqual([]);
1634
+ });
1635
+
1636
+ // An app that imports this entry BEFORE any other @copilotkit/react-native
1637
+ // entry must still get the polyfills first: on Hermes, @copilotkit/core and
1638
+ // @ag-ui/client fail at load time without them, with a ReferenceError that
1639
+ // says nothing about import order. Being imported first in the file is what
1640
+ // makes the bundler emit it as the built entry's first statement, which
1641
+ // scripts/verify-polyfill-barrel.mjs then checks in dist/.
1642
+ it.each(CODE_ENTRIES)(
1643
+ "%s imports ./polyfills as its first runtime import",
1644
+ (_label, entry) => {
1645
+ const first = firstRuntimeSpecifier(fs.readFileSync(entry, "utf8"));
1646
+ expect(
1647
+ first ? resolveLocal(entry, first) : null,
1648
+ `${srcRelative(entry)} must start with \`import "${path
1649
+ .relative(path.dirname(entry), polyfillsBarrel)
1650
+ .replace(/\\/g, "/")
1651
+ .replace(/\.ts$/, "")
1652
+ .replace(/^(?!\.)/, "./")}";\` — its first runtime import is ` +
1653
+ `${JSON.stringify(first)}`,
1654
+ ).toBe(polyfillsBarrel);
1655
+ },
1656
+ );
1657
+
1658
+ // A `sideEffects` list that misses an entry tells the consumer's bundler the
1659
+ // bare `import "./polyfills"` in it can be dropped.
1660
+ it.each(CODE_ENTRIES)(
1661
+ "%s is declared in package.json sideEffects, as source and as build output",
1662
+ (label, entry) => {
1663
+ const manifest = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8")) as {
1664
+ sideEffects?: unknown;
1665
+ exports?: Record<string, unknown>;
1666
+ };
1667
+ const globs = Array.isArray(manifest.sideEffects)
1668
+ ? manifest.sideEffects.map((g) => sideEffectsGlob(String(g)))
1669
+ : [];
1670
+ const key = `.${label.slice("@copilotkit/react-native".length)}`;
1671
+ const exported = manifest.exports?.[key] as
1672
+ | Record<string, string>
1673
+ | undefined;
1674
+ const files = [
1675
+ `./${path.relative(path.dirname(pkgJsonPath), entry).replace(/\\/g, "/")}`,
1676
+ ...Object.values(exported ?? {}),
1677
+ ];
1678
+ expect(files.length, `no exports entry for ${key}`).toBeGreaterThan(1);
1679
+ expect(
1680
+ files.filter((file) => !globs.some((re) => re.test(file))),
1681
+ `not matched by any package.json sideEffects glob`,
1682
+ ).toEqual([]);
1683
+ },
1684
+ );
1685
+ });