Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 67 additions & 1 deletion playwright-cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
// @ts-check

const fs = require('fs');
const os = require('os');
const path = require('path');

const { program } = require('playwright-core/lib/tools/cli-client/program');
Expand Down Expand Up @@ -60,7 +61,8 @@ async function fetchLatestVersion() {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 1500);
try {
const res = await fetch(`https://registry.npmjs.org/${packageJson.name}/latest`, { signal: controller.signal });
const url = npmRegistry().replace(/\/?$/, '/') + packageJson.name.replace('/', '%2f') + '/latest';
Comment thread
pavelfeldman marked this conversation as resolved.
Resolved
const res = await fetch(url, { signal: controller.signal });
if (!res.ok)
return undefined;
const json = await res.json();
Expand All @@ -73,6 +75,70 @@ async function fetchLatestVersion() {
}
}

// Resolves the registry npm would use for this package: the scoped registry wins
// over the default one, each looked up in env, project, user and global npmrc.
function npmRegistry() {
const env = npmEnvConfig();
const configs = [env, ...npmrcFiles(env).map(readNpmrc)];
const scope = packageJson.name.split('/')[0];
for (const key of [`${scope}:registry`, 'registry']) {
for (const config of configs) {
if (config[key])
return config[key];
}
}
return 'https://registry.npmjs.org/';
}

function npmEnvConfig() {
/** @type {Record<string, string>} */
const config = {};
for (const [name, value] of Object.entries(process.env)) {
if (value && /^npm_config_/i.test(name))
config[name.substring('npm_config_'.length).toLowerCase()] = value;
}
return config;
}

/**
* @param {Record<string, string>} env
*/
function npmrcFiles(env) {
const nodeDir = path.dirname(process.execPath);
const globalPrefix = env.prefix || process.env.PREFIX || (process.platform === 'win32' ? nodeDir : path.dirname(nodeDir));
return [
path.join(npmProjectDir(), '.npmrc'),
env.userconfig || path.join(os.homedir(), '.npmrc'),
env.globalconfig || path.join(globalPrefix, 'etc', 'npmrc'),
];
}

function npmProjectDir() {
for (let dir = process.cwd(); ; dir = path.dirname(dir)) {
if (fs.existsSync(path.join(dir, 'package.json')) || fs.existsSync(path.join(dir, 'node_modules')))
return dir;
if (path.dirname(dir) === dir)
return process.cwd();
}
}

/**
* @param {string} file
*/
function readNpmrc(file) {
/** @type {Record<string, string>} */
const config = {};
try {
for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
const match = line.match(/^\s*([^#;=\s][^=]*?)\s*=\s*(.*?)\s*$/);
if (match)
config[match[1]] = match[2].replace(/^(['"])(.*)\1$/, '$2').replace(/\$\{([^}]+)\}/g, (_, name) => process.env[name] || '');
}
} catch {
}
return config;
}

/**
*
* @param {string} current
Expand Down
83 changes: 82 additions & 1 deletion tests/integration.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,53 @@
*/

import fs from 'fs';
import http from 'http';
import path from 'path';
import { spawn } from 'child_process';
import { test, expect } from '@playwright/test';
import { test as baseTest, expect } from '@playwright/test';
import type { AddressInfo } from 'net';

type CliResult = {
output: string;
error: string;
exitCode: number | null;
};

type NpmRegistry = {
url: string;
status: number;
requests: string[];
};

const test = baseTest.extend<{ npmRegistry: NpmRegistry }>({
npmRegistry: async ({}, use) => {
const registry: NpmRegistry = { url: '', status: 200, requests: [] };
const server = http.createServer((req, res) => {
registry.requests.push(req.url!);
res.statusCode = registry.status;
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ version: '99.0.0' }));
});
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
registry.url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
await use(registry);
await new Promise(resolve => server.close(resolve));
},
});

// Enables the update check and isolates it from the npm config of the machine running the tests.
function updateCheckEnv(env: Record<string, string> = {}): Record<string, string> {
return {
'CI': '',
'NO_UPDATE_NOTIFIER': '',
'npm_config_registry': '',
'npm_config_@playwright:registry': '',
'npm_config_userconfig': test.info().outputPath('user-npmrc'),
'npm_config_globalconfig': test.info().outputPath('global-npmrc'),
...env,
};
}

async function runCli(args: string[], env: Record<string, string> = {}): Promise<CliResult> {
const cliPath = path.join(__dirname, '../playwright-cli.js');

Expand Down Expand Up @@ -136,3 +173,47 @@ test('caches the update check in the default registry directory', async ({}) =>
expect(found).toHaveLength(1);
expect(JSON.parse(fs.readFileSync(found[0], 'utf8')).lastCheck).toEqual(expect.any(Number));
});

test('update check uses the registry from npm config env', async ({ npmRegistry }) => {
expect(await runCli(['--version'], updateCheckEnv({ npm_config_registry: npmRegistry.url }))).toEqual(expect.objectContaining({
error: expect.stringContaining('Update available for @playwright/cli'),
exitCode: 0,
}));
expect(npmRegistry.requests).toEqual(['/@playwright%2fcli/latest']);
});

test('update check prefers the scoped registry from project .npmrc', async ({ npmRegistry }) => {
fs.writeFileSync(test.info().outputPath('package.json'), '{}');
fs.writeFileSync(test.info().outputPath('.npmrc'), [
`registry=${npmRegistry.url}/default/`,
`@playwright:registry=${npmRegistry.url}/scoped/`,
].join('\n'));
fs.writeFileSync(test.info().outputPath('user-npmrc'), `registry=${npmRegistry.url}/user/`);

expect(await runCli(['--version'], updateCheckEnv())).toEqual(expect.objectContaining({
error: expect.stringContaining('Update available for @playwright/cli'),
exitCode: 0,
}));
expect(npmRegistry.requests).toEqual(['/scoped/@playwright%2fcli/latest']);
});

test('update check uses the registry from user .npmrc', async ({ npmRegistry }) => {
fs.writeFileSync(test.info().outputPath('user-npmrc'), `registry=${npmRegistry.url}/user/`);

expect(await runCli(['--version'], updateCheckEnv())).toEqual(expect.objectContaining({
error: expect.stringContaining('Update available for @playwright/cli'),
exitCode: 0,
}));
expect(npmRegistry.requests).toEqual(['/user/@playwright%2fcli/latest']);
});

test('update check failure in the configured registry is silent', async ({ npmRegistry }) => {
npmRegistry.status = 401;
const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8'));
expect(await runCli(['--version'], updateCheckEnv({ npm_config_registry: npmRegistry.url }))).toEqual({
output: packageJson.version,
error: '',
exitCode: 0,
});
expect(npmRegistry.requests).toEqual(['/@playwright%2fcli/latest']);
});
Loading