diff --git a/bin-src/lib/checkForUpdates.ts b/bin-src/lib/checkForUpdates.ts index 4fb9765fb..7c801d0a1 100644 --- a/bin-src/lib/checkForUpdates.ts +++ b/bin-src/lib/checkForUpdates.ts @@ -1,11 +1,11 @@ import semver from 'semver'; -import yon from 'yarn-or-npm'; +import { hasYarn } from 'yarn-or-npm'; + +import spawn from './spawn'; import { Context } from '../types'; import outdatedPackage from '../ui/messages/warnings/outdatedPackage'; -const { hasYarn } = yon; - const rejectIn = (ms: number) => new Promise((_, reject) => setTimeout(reject, ms)); const withTimeout = (promise: Promise, ms: number): Promise => Promise.race([promise, rejectIn(ms)]); @@ -18,9 +18,15 @@ export default async function checkForUpdates(ctx: Context) { let latestVersion: string; try { - const pkgUrl = `https://registry.npmjs.org/${ctx.pkg.name}`; - // If not fetched within 5 seconds, nevermind. - const res = await withTimeout(ctx.http.fetch(pkgUrl), 5000); + const registryUrl = await spawn(['config', 'get', 'registry']).catch( + () => 'https://registry.npmjs.org/' + ); + if (!['https://registry.npmjs.org/', 'https://registry.yarnpkg.com'].includes(registryUrl)) { + ctx.log.info(`Using custom npm registry: ${registryUrl}`); + } + + const pkgUrl = new URL(ctx.pkg.name, registryUrl).href; + const res = await withTimeout(ctx.http.fetch(pkgUrl), 5000); // If not fetched within 5 seconds, nevermind. const { 'dist-tags': distTags = {} } = (await res.json()) as any; if (!semver.valid(distTags.latest)) { ctx.log.warn(`Invalid dist-tag 'latest' returned from registry; skipping update check`); diff --git a/bin-src/lib/spawn.ts b/bin-src/lib/spawn.ts new file mode 100644 index 000000000..a164b40aa --- /dev/null +++ b/bin-src/lib/spawn.ts @@ -0,0 +1,19 @@ +import { spawn } from 'yarn-or-npm'; + +export default (args: Parameters[0], options: Parameters[1] = {}) => + new Promise((resolve, reject) => { + let stdout = ''; + let stderr = ''; + const child = spawn(args, options); + child.stdout.on('data', (chunk) => { + stdout += chunk; + }); + child.stderr.on('data', (chunk) => { + stderr += chunk; + }); + child.on('error', reject); + child.on('close', (code) => { + if (code === 0) resolve(stdout.trim()); + else reject(new Error(stderr)); + }); + }); diff --git a/bin-src/main.test.ts b/bin-src/main.test.ts index 13718bc86..822ed48d0 100644 --- a/bin-src/main.test.ts +++ b/bin-src/main.test.ts @@ -190,6 +190,8 @@ const openTunnel = >tunnel; jest.mock('./lib/uploadFiles'); +jest.mock('./lib/spawn', () => () => Promise.resolve('https://npm.example.com')); + let processEnv; beforeEach(() => { processEnv = process.env; @@ -614,7 +616,7 @@ describe('runAll', () => { } as any); await runAll(ctx); expect(ctx.exitCode).toBe(1); - expect(ctx.http.fetch).toHaveBeenCalledWith('https://registry.npmjs.org/chromatic'); + expect(ctx.http.fetch).toHaveBeenCalledWith('https://npm.example.com/chromatic'); expect(ctx.testLogger.warnings[0]).toMatch('Using outdated package'); });