Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
25 changes: 12 additions & 13 deletions lib/collaborators.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,23 +43,22 @@ Collaborator.TYPES = {
};

export async function getCollaborators(cli, request, argv) {
const { readme, owner, repo } = argv;
let readmeText;
if (readme) {
cli.updateSpinner(`Reading collaborator contacts from ${readme}`);
readmeText = fs.readFileSync(readme, 'utf8');
} else {
cli.updateSpinner(
'Getting collaborator contacts from README of nodejs/node');
const url = 'https://raw.githubusercontent.com/nodejs/node/HEAD/README.md';
readmeText = await request.text(url);
}

const { readme } = argv;
let collaborators;
try {
let readmeText;
if (readme) {
cli.updateSpinner(`Reading collaborator contacts from ${readme}`);
readmeText = fs.readFileSync(readme, 'utf8');
} else {
cli.updateSpinner(
'Getting collaborator contacts from README of nodejs/node');
const url = 'https://raw.githubusercontent.com/nodejs/node/HEAD/README.md';
readmeText = await request.text(url);
}
collaborators = parseCollaborators(readmeText, cli);
} catch (err) {
const readmePath = readme || `${owner}/${repo}/README.md`;
const readmePath = readme || 'nodejs/node/README.md';
cli.stopSpinner(`Failed to get collaborator info from ${readmePath}`,
cli.SPINNER_STATUS.FAILED);
throw err;
Expand Down
27 changes: 23 additions & 4 deletions lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ function wrappedFetch(url, options, ...args) {
return fetch(url, options, ...args);
}

async function fetchResponse(request, url, options) {
const res = await request.fetch(url, options);
if (isDebugVerbosity()) {
debuglog('[Request] Got response from', url, ':\n', res.status, ' ', res.statusText);
}
return res;
}

export default class Request {
constructor(credentials) {
this.credentials = credentials;
Expand Down Expand Up @@ -51,9 +59,19 @@ export default class Request {
}

async text(url, options = {}) {
const res = await this.fetch(url, options);
if (isDebugVerbosity()) {
debuglog('[Request] Got response from', url, ':\n', res.status, ' ', res.statusText);
const res = await fetchResponse(this, url, options);
if (!res.ok) {
const status = `${res.status} ${res.statusText ?? ''}`.trim();
const message = `Unable to fetch ${url}: ${status}`;
try {
await res.body?.cancel();
} catch (err) {
if (isDebugVerbosity()) {
debuglog('[Request] Failed to cancel response body from', url, ':\n', err);
}
throw new Error(message, { cause: err });
}
throw new Error(message);
}
return res.text();
}
Expand All @@ -71,7 +89,8 @@ export default class Request {

async json(url, options = {}) {
options.headers = options.headers || {};
const text = await this.text(url, options);
const res = await fetchResponse(this, url, options);
const text = await res.text();
try {
return JSON.parse(text);
} catch (e) {
Expand Down
27 changes: 17 additions & 10 deletions lib/voting_session.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,17 +71,24 @@ export default class VotingSession extends Session {
async decryptKeyPart(prInfo) {
const subPath = `${prInfo.headRef.name}/vote.yml`;
this.cli.startSpinner('Downloading vote file from remote...');
const yamlString = await this.req.text(
`/repos/${this.owner}/${this.repo}/contents/${
encodeURIComponent(subPath)}?ref=${prInfo.commits.nodes[0].commit.oid}`,
{
agent: this.req.proxyAgent,
headers: {
Accept: 'application/vnd.github.raw+json',
'X-GitHub-Api-Version': '2026-03-10'
let yamlString;
try {
yamlString = await this.req.text(
`/repos/${this.owner}/${this.repo}/contents/${
encodeURIComponent(subPath)}?ref=${prInfo.commits.nodes[0].commit.oid}`,
{
agent: this.req.proxyAgent,
headers: {
Accept: 'application/vnd.github.raw+json',
'X-GitHub-Api-Version': '2026-03-10'
}
}
}
);
);
} catch (err) {
this.cli.stopSpinner('Failed to download vote file',
this.cli.SPINNER_STATUS.FAILED);
throw err;
}
this.cli.stopSpinner('Download complete');

const { shares } = yaml.load(yamlString);
Expand Down
93 changes: 93 additions & 0 deletions test/unit/collaborators.test.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { describe, it, beforeEach } from 'node:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import assert from 'node:assert';
import os from 'node:os';
import path from 'node:path';

import {
isCollaborator,
getCollaborators
} from '../../lib/collaborators.js';
import Request from '../../lib/request.js';

import {
readme,
Expand Down Expand Up @@ -186,6 +190,95 @@ describe('collaborators', function() {
async() => getCollaborators(cli, request, argv),
/Error: Could not find any collaborators/);
});

it('should stop spinner and rethrow when request.text rejects', async() => {
const argv = { owner: 'nodejs', repo: 'node' };
const err = new Error('Unable to fetch README: 503 Service Unavailable');
const request = {
async text() {
throw err;
}
};

await assert.rejects(
() => getCollaborators(cli, request, argv),
(caught) => caught === err);
cli.assertCalledWith({
stopSpinner: [[
'Failed to get collaborator info from nodejs/node/README.md',
cli.SPINNER_STATUS.FAILED
]]
}, { ignore: ['updateSpinner'] });
});

it('should reject non-ok HTTP responses via Request instead of parse error', async() => {
const argv = { owner: 'nodejs', repo: 'node' };
const request = Object.assign(Object.create(Request.prototype), {
credentials: {},
proxyAgent: undefined
});
let cancelled = false;
request.fetch = async() => ({
ok: false,
status: 503,
statusText: 'Service Unavailable',
body: {
cancel: async() => {
cancelled = true;
}
},
text: async() => '<html>503</html>'
});

await assert.rejects(
() => getCollaborators(cli, request, argv),
/Unable to fetch .*: 503 Service Unavailable/);
assert.strictEqual(cancelled, true);
cli.assertCalledWith({
stopSpinner: [[
'Failed to get collaborator info from nodejs/node/README.md',
cli.SPINNER_STATUS.FAILED
]]
}, { ignore: ['updateSpinner'] });
});

it('should stop spinner and rethrow when local readme file cannot be read', async(t) => {
const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'ncu-collaborators-'));
t.after(() => rmSync(tmpDir, { recursive: true, force: true }));
const missingPath = path.join(tmpDir, 'missing-README.md');
const argv = { owner: 'nodejs', repo: 'node', readme: missingPath };

await assert.rejects(
() => getCollaborators(cli, {}, argv),
{ code: 'ENOENT' });
cli.assertCalledWith({
stopSpinner: [[
`Failed to get collaborator info from ${missingPath}`,
cli.SPINNER_STATUS.FAILED
]]
}, { ignore: ['updateSpinner'] });
});

it('should report nodejs/node/README.md when remote fetch fails for another repo',
async() => {
const argv = { owner: 'nodejs', repo: 'llnode' };
const err = new Error('Unable to fetch README: 503 Service Unavailable');
const request = {
async text() {
throw err;
}
};

await assert.rejects(
() => getCollaborators(cli, request, argv),
(caught) => caught === err);
cli.assertCalledWith({
stopSpinner: [[
'Failed to get collaborator info from nodejs/node/README.md',
cli.SPINNER_STATUS.FAILED
]]
}, { ignore: ['updateSpinner'] });
});
});

describe('isCollaborator', () => {
Expand Down
143 changes: 143 additions & 0 deletions test/unit/request.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,149 @@ describe('Request', () => {
});
});
});

describe('text', () => {
it('returns response text when status is ok', async() => {
const request = createRequest({});
request.fetch = async() => ({
ok: true,
status: 200,
statusText: 'OK',
text: async() => 'hello world'
});

const body = await request.text('https://example.com/README.md');
assert.strictEqual(body, 'hello world');
});

it('rejects non-ok responses and cancels the body', async() => {
const request = createRequest({});
let cancelled = false;
let readBody = false;
request.fetch = async() => ({
ok: false,
status: 503,
statusText: 'Service Unavailable',
body: {
cancel: async() => {
cancelled = true;
}
},
text: async() => {
readBody = true;
return '<html>503</html>';
}
});

await assert.rejects(
() => request.text('https://example.com/README.md'),
/Unable to fetch https:\/\/example\.com\/README\.md: 503 Service Unavailable/);
assert.strictEqual(cancelled, true);
assert.strictEqual(readBody, false);
});

it('rejects non-ok responses when res.body is missing', async() => {
const request = createRequest({});
let readBody = false;
request.fetch = async() => ({
ok: false,
status: 502,
statusText: 'Bad Gateway',
text: async() => {
readBody = true;
return '<html>502</html>';
}
});

await assert.rejects(
() => request.text('https://example.com/README.md'),
/Unable to fetch https:\/\/example\.com\/README\.md: 502 Bad Gateway/);
assert.strictEqual(readBody, false);
});

it('rejects with HTTP status when cancelling an errored response body fails', async() => {
const request = createRequest({});
const streamErr = new TypeError('terminated');
const stream = new ReadableStream({
start(controller) {
controller.error(streamErr);
}
});
request.fetch = async() => new Response(stream, {
status: 503,
statusText: 'Service Unavailable'
});

await assert.rejects(
() => request.text('https://example.com/README.md'),
(err) => {
assert.strictEqual(
err.message,
'Unable to fetch https://example.com/README.md: 503 Service Unavailable');
assert.strictEqual(err.cause, streamErr);
return true;
});
});

it('omits trailing space when statusText is empty', async() => {
const request = createRequest({});
request.fetch = async() => ({
ok: false,
status: 503,
statusText: '',
body: { cancel: async() => {} }
});

await assert.rejects(
() => request.text('https://example.com/README.md'),
(err) => {
assert.strictEqual(err.message, 'Unable to fetch https://example.com/README.md: 503');
return true;
});
});

it('preserves falsy body cancellation rejection reasons as cause', async() => {
const request = createRequest({});
for (const reason of [false, undefined]) {
const stream = new ReadableStream({
start(controller) {
controller.error(reason);
}
});
request.fetch = async() => new Response(stream, {
status: 503,
statusText: 'Service Unavailable'
});

await assert.rejects(
() => request.text('https://example.com/README.md'),
(err) => {
assert.strictEqual(
err.message,
'Unable to fetch https://example.com/README.md: 503 Service Unavailable');
assert.strictEqual(Object.hasOwn(err, 'cause'), true);
assert.strictEqual(err.cause, reason);
return true;
});
}
});
});

describe('json', () => {
it('parses JSON payloads on non-ok responses', async() => {
const request = createRequest({});
delete request.json;
request.fetch = async() => ({
ok: false,
status: 401,
statusText: 'Unauthorized',
text: async() => '{"message":"Bad credentials"}'
});

const body = await request.json('/graphql', { method: 'POST' });
assert.deepStrictEqual(body, { message: 'Bad credentials' });
});
});
});

describe('Request: OpenJS CNA', () => {
Expand Down
Loading