Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// @ts-check
'use strict'
const { join } = require('path')
const { readFile } = require('fs')
const { promisify } = require('util')
const https = require('https')
const readFileAsync = promisify(readFile)
/**
*
* @param {string} url
* @param {(err: Error|null, data: string|null) => any} callback
*/
const __request = (url, callback) => https.get(
url,
{ timeout: 1000 },
res => {
let data = ''
// A chunk of data has been recieved.
res.on('data', chunk => { data += chunk })
// The whole response has been received.
res.on('end', () => callback(null, data))
}
).on('error', err => callback(err, null))
const requestAsync = promisify(__request)
/**
* @param {string} packageName
*
* @returns {Promise<{ 'dist-tags': { latest: string } }>}
*/
const request = async packageName => {
const plainResult = await requestAsync(`https://registry.npmjs.org/${packageName}`)
const result = JSON.parse(plainResult)
return result
}
/**
* @param {[string, string]} dependencyEntry
*
* @returns {Promise<{ [x: string]: string }>}
*/
const checkLatestPackageInRegistry = async dependencyEntry => {
const [dependency] = dependencyEntry
const response = await request(dependency)
return {
[dependency]: `^${response['dist-tags'].latest}`
}
}
/**
* @param {{ [x: string]: string }} dependencies
*
* @returns {Promise<{ [x: string]: string }>}
*/
const checkUpdate = async dependencies => (await Promise.all(
Object.entries(dependencies || {}).map(checkLatestPackageInRegistry)
)).reduce(
(accummulator, current) => Object.assign({}, accummulator, current), // reducer
{} // initial value
)
;(async () => {
try {
const packageJsonFilePath = join(__dirname, 'package.json')
const packageJsonContent = await readFileAsync(packageJsonFilePath, 'utf-8')
/**
* @type {{ dependencies: { [x: string]: string }, devDependencies: { [x: string]: string } }}
*/
const { dependencies, devDependencies } = JSON.parse(packageJsonContent)
const [newDependencies, newDevDependencies] = await Promise.all([
checkUpdate(dependencies),
checkUpdate(devDependencies)
])
console.log(
JSON.stringify({
dependencies: newDependencies,
devDependencies: newDevDependencies
},
undefined,
2)
)
} catch (error) {
console.error('Caught an error!')
console.error(error)
process.exit(1)
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment