MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1import { get } from 'node:https';
2
3function assert(condition, message) {
4 if (!condition) throw new Error(message);
5}
6
7const originalFetch = globalThis.fetch;
8let seenUrl = null;
9
10try {
11 globalThis.fetch = async (url, init) => {
12 seenUrl = String(url);
13 assert(seenUrl === 'https://registry.npmjs.org/serve', `unexpected request URL: ${seenUrl}`);
14 assert(init.method === 'GET', `expected GET method, got ${init.method}`);
15 assert(init.headers.accept.includes('application/json'),
16 `unexpected accept header: ${init.headers.accept}`);
17
18 return new Response('{"ok":true}', {
19 status: 200,
20 headers: {
21 'content-type': 'application/json'
22 }
23 });
24 };
25
26 const body = await new Promise((resolve, reject) => {
27 const req = get({
28 host: 'registry.npmjs.org',
29 path: '/serve',
30 timeout: 500,
31 headers: {
32 accept: 'application/json'
33 }
34 }, response => {
35 assert(response.statusCode === 200, `expected 200 status, got ${response.statusCode}`);
36 assert(response.headers['content-type'] === 'application/json',
37 `unexpected content-type: ${response.headers['content-type']}`);
38
39 response.setEncoding('utf8');
40
41 let rawData = '';
42 response.on('data', chunk => {
43 rawData += chunk;
44 });
45 response.on('end', () => {
46 resolve(rawData);
47 });
48 });
49
50 req.on('error', reject);
51 req.on('timeout', () => reject(new Error('request timed out unexpectedly')));
52 });
53
54 assert(body === '{"ok":true}', `unexpected body: ${body}`);
55
56 for (const invalidInput of [
57 'http://registry.npmjs.org/serve',
58 { protocol: 'http:', host: 'registry.npmjs.org', path: '/serve' }
59 ]) {
60 let invalidError = null;
61 try {
62 get(invalidInput);
63 } catch (error) {
64 invalidError = error;
65 }
66
67 assert(invalidError, `expected invalid protocol error for ${String(invalidInput)}`);
68 assert(invalidError.name === 'TypeError',
69 `expected TypeError for invalid protocol, got ${invalidError && invalidError.name}`);
70 assert(invalidError.code === 'ERR_INVALID_PROTOCOL',
71 `expected ERR_INVALID_PROTOCOL, got ${invalidError && invalidError.code}`);
72 }
73
74 console.log('https.get fetch shim test passed');
75} finally {
76 globalThis.fetch = originalFetch;
77}