Open History to see the last commit
1import { readFileSync } from 'node:fs'
2import { builtinModules } from 'node:module'
3import { dirname, extname, join, normalize, resolve } from 'node:path'
4import { fileURLToPath } from 'node:url'
5
6const scriptDir = dirname(fileURLToPath(import.meta.url))
7const repoRoot = resolve(scriptDir, '../../..')
8const fixtureRoot = resolve(scriptDir, '..')
9
10const packageEntries = new Map<string, string>([
11 ['@tanstack/ai-react', 'packages/ai-react/src/index.ts'],
12 ['@tanstack/ai-client', 'packages/ai-client/src/index.ts'],
13 ['@tanstack/ai-event-client', 'packages/ai-event-client/src/index.ts'],
14 ['@tanstack/ai-utils', 'packages/ai-utils/src/index.ts'],
15 ['@tanstack/ai/client', 'packages/ai/src/client.ts'],
16])
17
18const providerSdkPackages = new Set([
19 '@anthropic-ai/sdk',
20 '@fal-ai/client',
21 '@google/genai',
22 '@google/generative-ai',
23 '@openrouter/sdk',
24 'elevenlabs',
25 'ollama',
26 'openai',
27])
28
29const forbiddenPackages = new Set([
30 '@tanstack/ai-react/ui',
31 '@tanstack/react-ai-devtools',
32 '@tanstack/solid-ai-devtools',
33 'react-dom',
34 'solid-js',
35 'svelte',
36 'vue',
37])
38
39const providerPackagePattern =
40 /^@tanstack\/ai-(anthropic|byteplus|elevenlabs|fal|gemini|grok|groq|ollama|openai|openrouter)(?:\/|$)/
41
42const forbiddenPackagePrefixes = ['@vue/']
43const builtins = new Set(
44 builtinModules.flatMap((name) => [name, `node:${name}`]),
45)
46
47const forbiddenServerSymbols = new Set([
48 'chat',
49 'chatParamsFromRequest',
50 'chatParamsFromRequestBody',
51 'embedding',
52 'generateAudio',
53 'generateImage',
54 'generateSpeech',
55 'generateTranscription',
56 'generateVideo',
57 'getVideoJobStatus',
58 'mergeAgentTools',
59 'realtimeToken',
60 'resumeJsonResponse',
61 'streamToText',
62 'summarize',
63 'toHttpResponse',
64 'toHttpStream',
65 'toJsonResponse',
66 'toServerSentEventsResponse',
67 'toServerSentEventsStream',
68])
69
70interface SpecifierUse {
71 names?: Set<string>
72 specifier: string
73}
74
75const visited = new Set<string>()
76const failures: Array<string> = []
77
78function read(file: string) {
79 return readFileSync(file, 'utf8')
80}
81
82function normalized(file: string) {
83 return normalize(file).replaceAll('\\', '/')
84}
85
86function assertNoForbiddenText(file: string, source: string) {
87 if (
88 normalized(file).startsWith(normalized(fixtureRoot)) &&
89 source.includes('/api/chat')
90 ) {
91 failures.push(`${file} contains the browser default /api/chat`)
92 }
93}
94
95function parseNames(namedBlock: string): Set<string> {
96 const withoutComments = stripComments(namedBlock)
97 const names = withoutComments
98 .split(',')
99 .map((part) => part.trim())
100 .filter(Boolean)
101 .map((part) =>
102 part
103 .replace(/^type\s+/, '')
104 .split(/\s+as\s+/)[0]
105 ?.trim(),
106 )
107 .filter((name): name is string => Boolean(name))
108
109 return new Set(names)
110}
111
112function stripComments(source: string) {
113 return source.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gm, '')
114}
115
116function mergeUse(
117 uses: Array<SpecifierUse>,
118 specifier: string,
119 names: Set<string> | undefined,
120) {
121 const existing = uses.find((use) => use.specifier === specifier)
122 if (!existing) {
123 uses.push({ specifier, ...(names ? { names } : {}) })
124 return
125 }
126 if (!names || !existing.names) {
127 delete existing.names
128 return
129 }
130 for (const name of names) existing.names.add(name)
131}
132
133function importUses(source: string): Array<SpecifierUse> {
134 const parseSource = stripComments(source)
135 const uses: Array<SpecifierUse> = []
136 const importPattern =
137 /import\s+(?:type\s+)?([\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g
138 const sideEffectPattern = /import\s+['"]([^'"]+)['"]/g
139 const dynamicPattern = /import\(\s*['"]([^'"]+)['"]\s*\)/g
140
141 for (const match of parseSource.matchAll(importPattern)) {
142 const clause = match[1]?.trim() ?? ''
143 const specifier = match[2]
144 if (!specifier) continue
145
146 const named = clause.match(/\{([\s\S]*?)\}/)
147 mergeUse(uses, specifier, named ? parseNames(named[1] ?? '') : undefined)
148 }
149
150 for (const match of parseSource.matchAll(sideEffectPattern)) {
151 if (match[1]) mergeUse(uses, match[1], undefined)
152 }
153
154 for (const match of parseSource.matchAll(dynamicPattern)) {
155 if (match[1]) mergeUse(uses, match[1], undefined)
156 }
157
158 return uses
159}
160
161function exportUsesForNames(
162 source: string,
163 requestedNames?: Set<string>,
164): Array<SpecifierUse> {
165 const parseSource = stripComments(source)
166 const uses: Array<SpecifierUse> = []
167 const exportFromPattern =
168 /export\s+(?:type\s+)?\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"]/g
169 const exportAllPattern = /export\s+(?:type\s+)?\*\s+from\s+['"]([^'"]+)['"]/g
170
171 for (const match of parseSource.matchAll(exportFromPattern)) {
172 const exportedNames = parseNames(match[1] ?? '')
173 const specifier = match[2]
174 if (!specifier) continue
175
176 const matchingNames =
177 requestedNames === undefined
178 ? exportedNames
179 : new Set(
180 Array.from(exportedNames).filter((name) =>
181 requestedNames.has(name),
182 ),
183 )
184
185 if (matchingNames.size > 0) mergeUse(uses, specifier, matchingNames)
186 }
187
188 for (const match of parseSource.matchAll(exportAllPattern)) {
189 if (match[1]) mergeUse(uses, match[1], requestedNames)
190 }
191
192 return uses
193}
194
195function localExportSources(
196 source: string,
197 requestedNames: Set<string>,
198): Array<string> {
199 const parseSource = stripComments(source)
200 const sources: Array<string> = []
201 const localExportPattern =
202 /export\s+(?:async\s+)?(?:function|class|const|let|var|interface|type)\s+([A-Za-z_$][\w$]*)/g
203
204 for (const match of parseSource.matchAll(localExportPattern)) {
205 const name = match[1]
206 if (name && requestedNames.has(name)) {
207 sources.push(name)
208 }
209 }
210
211 return sources
212}
213
214function resolveRelative(fromFile: string, specifier: string) {
215 const base = resolve(dirname(fromFile), specifier)
216 const candidates = extname(base)
217 ? [base]
218 : [`${base}.ts`, `${base}.tsx`, `${base}.js`, join(base, 'index.ts')]
219
220 return candidates.find((candidate) => {
221 try {
222 readFileSync(candidate)
223 return true
224 } catch {
225 return false
226 }
227 })
228}
229
230function checkForbiddenNamedImport(
231 fromFile: string,
232 specifier: string,
233 names?: Set<string>,
234) {
235 if (!names) return
236
237 for (const name of names) {
238 if (forbiddenServerSymbols.has(name)) {
239 failures.push(
240 `${fromFile} imports or re-exports server-only helper ${name} from ${specifier}`,
241 )
242 }
243 }
244}
245
246function checkExternal(fromFile: string, use: SpecifierUse) {
247 const { names, specifier } = use
248
249 if (specifier === '@tanstack/ai') {
250 failures.push(
251 `${fromFile} imports root @tanstack/ai; use @tanstack/ai/client for the React Native client graph`,
252 )
253 }
254 if (providerSdkPackages.has(specifier)) {
255 failures.push(`${fromFile} imports provider SDK ${specifier}`)
256 }
257 if (providerPackagePattern.test(specifier)) {
258 failures.push(`${fromFile} imports provider package ${specifier}`)
259 }
260 if (forbiddenPackages.has(specifier)) {
261 failures.push(`${fromFile} imports non-RN package ${specifier}`)
262 }
263 if (forbiddenPackagePrefixes.some((prefix) => specifier.startsWith(prefix))) {
264 failures.push(`${fromFile} imports non-RN package ${specifier}`)
265 }
266 if (builtins.has(specifier)) {
267 failures.push(`${fromFile} imports Node builtin ${specifier}`)
268 }
269
270 checkForbiddenNamedImport(fromFile, specifier, names)
271}
272
273function walk(file: string, requestedExports?: Set<string>) {
274 const visitKey = `${normalized(file)}::${
275 requestedExports ? Array.from(requestedExports).sort().join(',') : '*'
276 }`
277 if (visited.has(visitKey)) return
278 visited.add(visitKey)
279
280 const source = read(file)
281 assertNoForbiddenText(file, source)
282
283 if (requestedExports) {
284 for (const localName of localExportSources(source, requestedExports)) {
285 if (forbiddenServerSymbols.has(localName)) {
286 failures.push(`${file} exports server-only helper ${localName}`)
287 }
288 }
289 }
290
291 const uses = [
292 ...importUses(source),
293 ...(requestedExports ? exportUsesForNames(source, requestedExports) : []),
294 ]
295
296 for (const use of uses) {
297 const packageEntry = packageEntries.get(use.specifier)
298 if (packageEntry) {
299 walk(resolve(repoRoot, packageEntry), use.names)
300 continue
301 }
302
303 if (use.specifier.startsWith('.')) {
304 const resolved = resolveRelative(file, use.specifier)
305 if (resolved) {
306 walk(resolved, use.names)
307 }
308 continue
309 }
310
311 checkExternal(file, use)
312 }
313}
314
315walk(resolve(fixtureRoot, 'src/App.tsx'))
316
317if (failures.length > 0) {
318 console.error(failures.join('\n'))
319 process.exit(1)
320}
321
322console.log(
323 `React Native import surface smoke passed (${visited.size} visits).`,
324)