Open History to see the last commit
1#!/usr/bin/env node
2
3import { readFileSync, readdirSync, statSync, writeFileSync } from 'fs'
4import { join, dirname, relative } from 'path'
5import { fileURLToPath } from 'url'
6import semver from 'semver'
7
8const __filename = fileURLToPath(import.meta.url)
9const __dirname = dirname(__filename)
10
11// Parse command line arguments
12const args = process.argv.slice(2)
13const shouldUpdate = args.includes('--update')
14
15// Colors for console output
16const colors = {
17 red: '\x1b[31m',
18 green: '\x1b[32m',
19 yellow: '\x1b[33m',
20 blue: '\x1b[34m',
21 reset: '\x1b[0m',
22 bold: '\x1b[1m',
23}
24
25/**
26 * Recursively find all package.json files in a directory
27 */
28function findPackageJsonFiles(dir, files = []) {
29 const items = readdirSync(dir)
30
31 for (const item of items) {
32 const fullPath = join(dir, item)
33 const stat = statSync(fullPath)
34
35 if (stat.isDirectory() && item !== 'node_modules' && item !== 'dist') {
36 findPackageJsonFiles(fullPath, files)
37 } else if (item === 'package.json') {
38 files.push(fullPath)
39 }
40 }
41
42 return files
43}
44
45// Cache for package versions to avoid duplicate API calls
46const versionCache = new Map()
47
48/**
49 * Get the latest version of a package from npm with caching and timeout
50 */
51async function getLatestVersion(packageName) {
52 // Check cache first
53 if (versionCache.has(packageName)) {
54 return versionCache.get(packageName)
55 }
56
57 try {
58 // Add timeout to prevent hanging
59 const controller = new AbortController()
60 const timeoutId = setTimeout(() => controller.abort(), 10000) // 10 second timeout
61
62 const response = await fetch(
63 `https://registry.npmjs.org/${packageName}/latest`,
64 {
65 signal: controller.signal,
66 headers: {
67 'User-Agent': 'create-tsrouter-app-outdated-checker',
68 },
69 },
70 )
71
72 clearTimeout(timeoutId)
73
74 if (!response.ok) {
75 throw new Error(`HTTP ${response.status}`)
76 }
77
78 const data = await response.json()
79 const version = data.version
80
81 // Cache the result
82 versionCache.set(packageName, version)
83 return version
84 } catch (error) {
85 if (error.name === 'AbortError') {
86 console.warn(
87 `${colors.yellow}Warning: Timeout fetching latest version for ${packageName}${colors.reset}`,
88 )
89 } else {
90 console.warn(
91 `${colors.yellow}Warning: Could not fetch latest version for ${packageName}: ${error.message}${colors.reset}`,
92 )
93 }
94
95 // Cache null result to avoid retrying
96 versionCache.set(packageName, null)
97 return null
98 }
99}
100
101/**
102 * Check if a version range satisfies the latest version
103 */
104function isVersionRangeOutdated(versionRange, latestVersion) {
105 try {
106 // Clean the version range (remove any npm-specific prefixes)
107 const cleanRange = versionRange.replace(/^npm:/, '').split('@').pop()
108
109 // Check if the range satisfies the latest version
110 return !semver.satisfies(latestVersion, cleanRange)
111 } catch (error) {
112 console.warn(
113 `${colors.yellow}Warning: Could not parse version range "${versionRange}": ${error.message}${colors.reset}`,
114 )
115 return false
116 }
117}
118
119/**
120 * Update package.json file with new versions
121 */
122function updatePackageJson(filePath, outdatedPackages) {
123 try {
124 const content = readFileSync(filePath, 'utf8')
125 const packageJson = JSON.parse(content)
126
127 let updated = false
128
129 for (const pkg of outdatedPackages) {
130 // Check and update in dependencies
131 if (packageJson.dependencies && packageJson.dependencies[pkg.name]) {
132 const currentRange = packageJson.dependencies[pkg.name]
133 const newRange = updateVersionRange(currentRange, pkg.latest)
134 packageJson.dependencies[pkg.name] = newRange
135 updated = true
136 }
137
138 // Check and update in devDependencies
139 if (
140 packageJson.devDependencies &&
141 packageJson.devDependencies[pkg.name]
142 ) {
143 const currentRange = packageJson.devDependencies[pkg.name]
144 const newRange = updateVersionRange(currentRange, pkg.latest)
145 packageJson.devDependencies[pkg.name] = newRange
146 updated = true
147 }
148
149 // Check and update in peerDependencies
150 if (
151 packageJson.peerDependencies &&
152 packageJson.peerDependencies[pkg.name]
153 ) {
154 const currentRange = packageJson.peerDependencies[pkg.name]
155 const newRange = updateVersionRange(currentRange, pkg.latest)
156 packageJson.peerDependencies[pkg.name] = newRange
157 updated = true
158 }
159 }
160
161 if (updated) {
162 // Write back with proper formatting
163 writeFileSync(filePath, JSON.stringify(packageJson, null, 2) + '\n')
164 return true
165 }
166
167 return false
168 } catch (error) {
169 console.error(
170 `${colors.red}Error updating ${filePath}: ${error.message}${colors.reset}`,
171 )
172 return false
173 }
174}
175
176/**
177 * Update version range while preserving the range type (^, ~, etc.)
178 */
179function updateVersionRange(currentRange, latestVersion) {
180 // Preserve the prefix (^, ~, >=, etc.)
181 if (currentRange.startsWith('^')) {
182 return `^${latestVersion}`
183 } else if (currentRange.startsWith('~')) {
184 return `~${latestVersion}`
185 } else if (currentRange.startsWith('>=')) {
186 return `>=${latestVersion}`
187 } else if (currentRange.startsWith('>')) {
188 return `>${latestVersion}`
189 } else if (currentRange.startsWith('<=')) {
190 return `<=${latestVersion}`
191 } else if (currentRange.startsWith('<')) {
192 return `<${latestVersion}`
193 } else {
194 // Exact version or other format, just use the latest version
195 return latestVersion
196 }
197}
198
199/**
200 * Get relative path for display
201 */
202function getDisplayPath(filePath, frameworksDir) {
203 const relativePath = relative(frameworksDir, filePath)
204 // Remove the package.json part
205 return relativePath.replace('/package.json', '')
206}
207
208/**
209 * Check dependencies in a package.json file
210 */
211async function checkPackageJson(filePath) {
212 try {
213 const content = readFileSync(filePath, 'utf8')
214 const packageJson = JSON.parse(content)
215
216 const outdatedPackages = []
217 const allDependencies = {
218 ...packageJson.dependencies,
219 ...packageJson.devDependencies,
220 ...packageJson.peerDependencies,
221 }
222
223 if (Object.keys(allDependencies).length === 0) {
224 return { filePath, outdatedPackages: [], totalDependencies: 0 }
225 }
226
227 const packageNames = Object.keys(allDependencies).filter((name) => {
228 const versionRange = allDependencies[name]
229 // Skip workspace dependencies and local packages
230 return !(
231 versionRange.startsWith('workspace:') ||
232 versionRange.startsWith('file:') ||
233 versionRange.startsWith('link:')
234 )
235 })
236
237 // Process packages in batches to avoid overwhelming the API
238 const batchSize = 5
239 for (let i = 0; i < packageNames.length; i += batchSize) {
240 const batch = packageNames.slice(i, i + batchSize)
241
242 // Process batch in parallel
243 const promises = batch.map(async (packageName) => {
244 const versionRange = allDependencies[packageName]
245 const latestVersion = await getLatestVersion(packageName)
246
247 if (!latestVersion) {
248 return null
249 }
250
251 if (isVersionRangeOutdated(versionRange, latestVersion)) {
252 return {
253 name: packageName,
254 current: versionRange,
255 latest: latestVersion,
256 }
257 }
258
259 return null
260 })
261
262 const results = await Promise.all(promises)
263 outdatedPackages.push(...results.filter(Boolean))
264
265 // Small delay between batches
266 if (i + batchSize < packageNames.length) {
267 await new Promise((resolve) => setTimeout(resolve, 50))
268 }
269 }
270
271 return {
272 filePath,
273 outdatedPackages,
274 totalDependencies: Object.keys(allDependencies).length,
275 }
276 } catch (error) {
277 console.error(
278 `${colors.red}Error processing ${filePath}: ${error.message}${colors.reset}`,
279 )
280 return {
281 filePath,
282 outdatedPackages: [],
283 totalDependencies: 0,
284 error: error.message,
285 }
286 }
287}
288
289/**
290 * Main function
291 */
292async function main() {
293 const actionText = shouldUpdate ? 'Updating' : 'Checking for'
294 console.log(
295 `${colors.bold}${colors.blue}${actionText} outdated packages in frameworks directory...${colors.reset}\n`,
296 )
297
298 const frameworksDir = join(__dirname, '..', 'frameworks')
299 const packageJsonFiles = findPackageJsonFiles(frameworksDir)
300
301 console.log(`Found ${packageJsonFiles.length} package.json files\n`)
302
303 let totalOutdated = 0
304 let totalChecked = 0
305 let totalUpdated = 0
306 const results = []
307
308 for (let i = 0; i < packageJsonFiles.length; i++) {
309 const filePath = packageJsonFiles[i]
310 const displayPath = getDisplayPath(filePath, frameworksDir)
311
312 // Show progress
313 process.stdout.write(
314 `\r${colors.blue}Processing ${i + 1}/${packageJsonFiles.length}: ${displayPath}...${colors.reset}`,
315 )
316
317 const result = await checkPackageJson(filePath)
318 results.push(result)
319
320 if (result.error) {
321 console.log(`\n${colors.red}Error: ${result.error}${colors.reset}`)
322 continue
323 }
324
325 totalChecked += result.totalDependencies
326 totalOutdated += result.outdatedPackages.length
327
328 if (result.outdatedPackages.length > 0) {
329 console.log(
330 `\n${colors.red}${colors.bold}Found ${result.outdatedPackages.length} outdated packages in ${displayPath}:${colors.reset}`,
331 )
332 for (const pkg of result.outdatedPackages) {
333 console.log(
334 ` ${colors.red}${pkg.name}${colors.reset}: ${pkg.current} → ${colors.green}${pkg.latest}${colors.reset}`,
335 )
336 }
337
338 if (shouldUpdate) {
339 const updated = updatePackageJson(filePath, result.outdatedPackages)
340 if (updated) {
341 totalUpdated++
342 console.log(
343 ` ${colors.green}✓ Updated ${displayPath}${colors.reset}`,
344 )
345 } else {
346 console.log(
347 ` ${colors.yellow}⚠ Failed to update ${displayPath}${colors.reset}`,
348 )
349 }
350 }
351
352 console.log()
353 }
354 }
355
356 // Clear progress line and add spacing
357 console.log('\n')
358
359 // Summary
360 console.log(`${colors.bold}${colors.blue}Summary:${colors.reset}`)
361 console.log(`Total dependencies checked: ${totalChecked}`)
362 console.log(
363 `Total outdated packages: ${colors.red}${totalOutdated}${colors.reset}`,
364 )
365
366 if (shouldUpdate) {
367 console.log(
368 `Total files updated: ${colors.green}${totalUpdated}${colors.reset}`,
369 )
370 }
371
372 if (totalOutdated === 0) {
373 console.log(
374 `${colors.green}${colors.bold}🎉 All packages are up to date!${colors.reset}`,
375 )
376 } else if (shouldUpdate && totalUpdated > 0) {
377 console.log(
378 `${colors.green}${colors.bold}✅ Successfully updated ${totalUpdated} files with outdated packages!${colors.reset}`,
379 )
380 } else if (shouldUpdate && totalUpdated === 0) {
381 console.log(
382 `${colors.yellow}${colors.bold}⚠️ No files were updated. Check for errors above.${colors.reset}`,
383 )
384 } else {
385 console.log(
386 `${colors.yellow}${colors.bold}⚠️ Found outdated packages that need attention. Use --update to update them.${colors.reset}`,
387 )
388 }
389
390 // Exit with error code if outdated packages found and not updating
391 process.exit(totalOutdated > 0 && !shouldUpdate ? 1 : 0)
392}
393
394main().catch((error) => {
395 console.error(
396 `${colors.red}${colors.bold}Fatal error: ${error.message}${colors.reset}`,
397 )
398 process.exit(1)
399})