@push.rocks/smartnetwork 3.0.2 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/readme.md CHANGED
@@ -1,61 +1,183 @@
1
- # @pushrocks/smartnetwork
1
+ # @push.rocks/smartnetwork
2
+
2
3
  network diagnostics
3
4
 
4
- ## Availabililty and Links
5
- * [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartnetwork)
6
- * [gitlab.com (source)](https://gitlab.com/pushrocks/smartnetwork)
7
- * [github.com (source mirror)](https://github.com/pushrocks/smartnetwork)
8
- * [docs (typedoc)](https://pushrocks.gitlab.io/smartnetwork/)
9
-
10
- ## Status for master
11
-
12
- Status Category | Status Badge
13
- -- | --
14
- GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smartnetwork/badges/master/pipeline.svg)](https://lossless.cloud)
15
- GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smartnetwork/badges/master/coverage.svg)](https://lossless.cloud)
16
- npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smartnetwork)](https://lossless.cloud)
17
- Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/smartnetwork)](https://lossless.cloud)
18
- TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
19
- node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
20
- Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
21
- PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/smartnetwork)](https://lossless.cloud)
22
- PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/smartnetwork)](https://lossless.cloud)
23
- BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/smartnetwork)](https://lossless.cloud)
24
- Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
5
+ ## Install
6
+
7
+ To install `@push.rocks/smartnetwork`, run the following command in your terminal:
8
+
9
+ ```bash
10
+ npm install @push.rocks/smartnetwork --save
11
+ ```
12
+
13
+ ### Performing a Traceroute
14
+
15
+ You can perform a hop-by-hop traceroute to measure latency per hop. Falls back to a single-hop stub if the `traceroute` binary is unavailable.
16
+
17
+ ```typescript
18
+ const hops = await myNetwork.traceroute('google.com', { maxHops: 10, timeout: 5000 });
19
+ hops.forEach((h) => console.log(`${h.ttl}\t${h.ip}\t${h.rtt === null ? '*' : h.rtt + ' ms'}`));
20
+ ```
21
+
22
+ This command will download `@push.rocks/smartnetwork` and add it to your project's `package.json` file.
25
23
 
26
24
  ## Usage
27
25
 
26
+ In this section, we will dive deep into the capabilities of the `@push.rocks/smartnetwork` package, exploring its various features through TypeScript examples. The package is designed to simplify network diagnostics tasks, including speed tests, port availability checks, ping operations, and more.
27
+
28
+ ### Basic Setup
29
+
30
+ First, import the package into your project:
31
+
32
+ ```typescript
33
+ import { SmartNetwork } from '@push.rocks/smartnetwork';
34
+ ```
35
+
36
+ Then, create an instance of `SmartNetwork`:
37
+
28
38
  ```typescript
29
- import * as smartnetwork from 'smartnetwork';
30
- const testSmartNetwork = new smartnetwork.SmartNetwork();
31
- const run = async () => {
32
- // measure average speed over a period of 5 seconds
33
- // the structure of speedResult is self explanatory using TypeScript (or the linked TypeDoc above)
34
- const speedResult: smartnetwork.SpeedResult = testSmartNetwork.getSpeed(5000);
39
+ const myNetwork = new SmartNetwork();
40
+ ```
41
+
42
+ ### Performing a Speed Test
35
43
 
36
- // you can check for local ports before trying to bind to it from your nodejs program
37
- const isLocalPortUnused: boolean = await testSmartNetwork.isLocalPortUnused(1234);
44
+ You can measure the network speed using the `getSpeed` method. It supports optional parameters:
38
45
 
39
- // you can run basic port checks on remote domains.
40
- const isRemotePortAvailable: boolean = await testSmartNetwork.isRemotePortAvailable(
41
- 'google.com:80'
42
- );
46
+ - `parallelStreams`: number of concurrent streams (default: 1)
47
+ - `duration`: test duration in seconds (default: fixed segments)
43
48
 
44
- // just another way to call for the same thing as above
45
- const isRemotePortAvailable: boolean = await testSmartNetwork.isRemotePortAvailable(
46
- 'google.com',
47
- 80
48
- );
49
+ ```typescript
50
+ const speedTest = async () => {
51
+ // Default fixed-segment test
52
+ let r = await myNetwork.getSpeed();
53
+ console.log(`Download: ${r.downloadSpeed} Mbps, Upload: ${r.uploadSpeed} Mbps`);
54
+
55
+ // Parallel + duration-based test
56
+ r = await myNetwork.getSpeed({ parallelStreams: 3, duration: 5 });
57
+ console.log(`Download: ${r.downloadSpeed} Mbps, Upload: ${r.uploadSpeed} Mbps`);
49
58
  };
59
+
60
+ speedTest();
61
+ ```
62
+
63
+ ### Checking Port Availability Locally
64
+
65
+ The `isLocalPortUnused` method allows you to check if a specific port on your local machine is available for use.
66
+
67
+ ```typescript
68
+ const checkLocalPort = async (port: number) => {
69
+ const isUnused = await myNetwork.isLocalPortUnused(port);
70
+ if (isUnused) {
71
+ console.log(`Port ${port} is available.`);
72
+ } else {
73
+ console.log(`Port ${port} is in use.`);
74
+ }
75
+ };
76
+
77
+ checkLocalPort(8080); // Example port number
78
+ ```
79
+
80
+ ### Checking Remote Port Availability
81
+
82
+ To verify if a port is available on a remote server, use `isRemotePortAvailable`. You can specify target as `"host:port"` or host plus a numeric port.
83
+
84
+ ```typescript
85
+ // Using "host:port"
86
+ await myNetwork.isRemotePortAvailable('example.com:443');
87
+
88
+ // Using host + port
89
+ await myNetwork.isRemotePortAvailable('example.com', 443);
90
+
91
+ // UDP is not supported:
92
+ try {
93
+ await myNetwork.isRemotePortAvailable('example.com', { port: 53, protocol: 'udp' });
94
+ } catch (e) {
95
+ console.error((e as any).code); // ENOTSUP
96
+ }
97
+ ```
98
+
99
+ ### Using Ping
100
+
101
+ The `ping` method sends ICMP echo requests and optionally repeats them to collect statistics.
102
+
103
+ ```typescript
104
+ // Single ping
105
+ const p1 = await myNetwork.ping('google.com');
106
+ console.log(`Alive: ${p1.alive}, RTT: ${p1.time} ms`);
107
+
108
+ // Multiple pings with statistics
109
+ const stats = await myNetwork.ping('google.com', { count: 5 });
110
+ console.log(
111
+ `min=${stats.min} ms, max=${stats.max} ms, avg=${stats.avg.toFixed(2)} ms, loss=${stats.packetLoss}%`,
112
+ );
113
+ ```
114
+
115
+ ### Getting Network Gateways
116
+
117
+ You can also retrieve network interfaces (gateways) and determine the default gateway. Caching with TTL is supported via constructor options.
118
+
119
+ ```typescript
120
+ // Create with cache TTL of 60 seconds
121
+ const netCached = new SmartNetwork({ cacheTtl: 60000 });
122
+
123
+ // List all interfaces
124
+ const gateways = await netCached.getGateways();
125
+ console.log(gateways);
126
+
127
+ // Get default gateway
128
+ const defaultGw = await netCached.getDefaultGateway();
129
+ console.log(defaultGw);
130
+ ```
131
+
132
+ ### Discovering Public IP Addresses
133
+
134
+ To find out your public IPv4 and IPv6 addresses (with caching):
135
+
136
+ ```typescript
137
+ const publicIps = await netCached.getPublicIps();
138
+ console.log(`Public IPv4: ${publicIps.v4}`);
139
+ console.log(`Public IPv6: ${publicIps.v6}`);
50
140
  ```
51
141
 
52
- ## Contribution
142
+ The `@push.rocks/smartnetwork` package provides an easy-to-use, comprehensive suite of tools for network diagnostics and monitoring, encapsulating complex network operations into simple asynchronous methods. By leveraging TypeScript, developers can benefit from type checking, ensuring that they can work with clear structures and expectations.
143
+
144
+ These examples offer a glimpse into the module's utility in real-world scenarios, demonstrating its versatility in handling common network tasks. Whether you're developing a network-sensitive application, diagnosing connectivity issues, or simply curious about your network performance, `@push.rocks/smartnetwork` equips you with the tools you need.
145
+
146
+ ### Plugin Architecture
147
+
148
+ You can extend `SmartNetwork` with custom plugins by registering them at runtime:
149
+
150
+ ```typescript
151
+ import { SmartNetwork } from '@push.rocks/smartnetwork';
152
+
153
+ // Define your plugin class or constructor
154
+ class MyCustomPlugin {
155
+ // plugin implementation goes here
156
+ }
157
+
158
+ // Register and unregister your plugin by name
159
+ SmartNetwork.registerPlugin('myPlugin', MyCustomPlugin);
160
+ // Later, remove it if no longer needed
161
+ SmartNetwork.unregisterPlugin('myPlugin');
162
+ ```
163
+
164
+ Plugins enable you to dynamically augment the core functionality without altering the library's source.
165
+
166
+ ## License and Legal Information
167
+
168
+ This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
169
+
170
+ **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
171
+
172
+ ### Trademarks
173
+
174
+ This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
53
175
 
54
- We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
176
+ ### Company Information
55
177
 
56
- For further information read the linked docs at the top of this readme.
178
+ Task Venture Capital GmbH
179
+ Registered at District court Bremen HRB 35230 HB, Germany
57
180
 
58
- > MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
59
- | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
181
+ For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
60
182
 
61
- [![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
183
+ By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
@@ -1,8 +1,8 @@
1
1
  /**
2
- * autocreated commitinfo by @pushrocks/commitinfo
2
+ * autocreated commitinfo by @push.rocks/commitinfo
3
3
  */
4
4
  export const commitinfo = {
5
- name: '@pushrocks/smartnetwork',
6
- version: '3.0.2',
7
- description: 'network diagnostics'
5
+ name: '@push.rocks/smartnetwork',
6
+ version: '4.0.1',
7
+ description: 'A toolkit for network diagnostics including speed tests, port availability checks, and more.'
8
8
  }
package/ts/errors.ts ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Custom error classes for network operations
3
+ */
4
+ export class NetworkError extends Error {
5
+ public code?: string;
6
+ constructor(message?: string, code?: string) {
7
+ super(message);
8
+ this.name = 'NetworkError';
9
+ this.code = code;
10
+ Object.setPrototypeOf(this, new.target.prototype);
11
+ }
12
+ }
13
+
14
+ export class TimeoutError extends NetworkError {
15
+ constructor(message?: string) {
16
+ super(message, 'ETIMEOUT');
17
+ this.name = 'TimeoutError';
18
+ Object.setPrototypeOf(this, new.target.prototype);
19
+ }
20
+ }
package/ts/index.ts CHANGED
@@ -1 +1,4 @@
1
1
  export * from './smartnetwork.classes.smartnetwork.js';
2
+ export type { SmartNetworkOptions, Hop } from './smartnetwork.classes.smartnetwork.js';
3
+ export { setLogger, getLogger } from './logging.js';
4
+ export { NetworkError, TimeoutError } from './errors.js';
package/ts/logging.ts ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Injectable logging interface and global logger
3
+ */
4
+ export interface Logger {
5
+ /** Debug-level messages */
6
+ debug?(...args: unknown[]): void;
7
+ /** Informational messages */
8
+ info(...args: unknown[]): void;
9
+ /** Warning messages */
10
+ warn?(...args: unknown[]): void;
11
+ /** Error messages */
12
+ error(...args: unknown[]): void;
13
+ }
14
+
15
+ let globalLogger: Logger = console;
16
+
17
+ /**
18
+ * Replace the global logger implementation
19
+ * @param logger Custom logger adhering to Logger interface
20
+ */
21
+ export function setLogger(logger: Logger): void {
22
+ globalLogger = logger;
23
+ }
24
+
25
+ /**
26
+ * Retrieve the current global logger
27
+ */
28
+ export function getLogger(): Logger {
29
+ return globalLogger;
30
+ }
@@ -1,8 +1,17 @@
1
1
  import * as plugins from './smartnetwork.plugins.js';
2
+ import { getLogger } from './logging.js';
3
+ import { NetworkError, TimeoutError } from './errors.js';
2
4
  import * as stats from './helpers/stats.js';
3
5
 
6
+ export interface SpeedOptions {
7
+ parallelStreams?: number;
8
+ duration?: number;
9
+ }
4
10
  export class CloudflareSpeed {
5
- constructor() {}
11
+ private opts: SpeedOptions;
12
+ constructor(opts?: SpeedOptions) {
13
+ this.opts = opts || {};
14
+ }
6
15
 
7
16
  public async speedTest() {
8
17
  const latency = await this.measureLatency();
@@ -10,20 +19,71 @@ export class CloudflareSpeed {
10
19
  const serverLocations = await this.fetchServerLocations();
11
20
  const cgiData = await this.fetchCfCdnCgiTrace();
12
21
 
13
- // lets test the download speed
14
- const testDown1 = await this.measureDownload(101000, 10);
15
- const testDown2 = await this.measureDownload(1001000, 8);
16
- const testDown3 = await this.measureDownload(10001000, 6);
17
- const testDown4 = await this.measureDownload(25001000, 4);
18
- const testDown5 = await this.measureDownload(100001000, 1);
19
- const downloadTests = [...testDown1, ...testDown2, ...testDown3, ...testDown4, ...testDown5];
22
+ // speed tests: either fixed segments or duration-based mode
23
+ const parallel = this.opts.parallelStreams ?? 1;
24
+ const measureDownloadParallel = (bytes: number, iterations: number) => {
25
+ if (parallel <= 1) {
26
+ return this.measureDownload(bytes, iterations);
27
+ }
28
+ return Promise.all(
29
+ Array(parallel)
30
+ .fill(null)
31
+ .map(() => this.measureDownload(bytes, iterations)),
32
+ ).then((arrays) => arrays.flat());
33
+ };
34
+ let downloadTests: number[];
35
+ if (this.opts.duration && this.opts.duration > 0) {
36
+ // duration-based download: run for specified seconds
37
+ downloadTests = [];
38
+ const durMs = this.opts.duration * 1000;
39
+ const startMs = Date.now();
40
+ // use medium chunk size for download
41
+ const chunkBytes = 25001000;
42
+ while (Date.now() - startMs < durMs) {
43
+ const speeds = await measureDownloadParallel(chunkBytes, 1);
44
+ downloadTests.push(...speeds);
45
+ }
46
+ if (downloadTests.length === 0) downloadTests = [0];
47
+ } else {
48
+ // fixed download segments
49
+ const t1 = await measureDownloadParallel(101000, 10);
50
+ const t2 = await measureDownloadParallel(1001000, 8);
51
+ const t3 = await measureDownloadParallel(10001000, 6);
52
+ const t4 = await measureDownloadParallel(25001000, 4);
53
+ const t5 = await measureDownloadParallel(100001000, 1);
54
+ downloadTests = [...t1, ...t2, ...t3, ...t4, ...t5];
55
+ }
20
56
  const speedDownload = stats.quartile(downloadTests, 0.9).toFixed(2);
21
57
 
22
- // lets test the upload speed
23
- const testUp1 = await this.measureUpload(11000, 10);
24
- const testUp2 = await this.measureUpload(101000, 10);
25
- const testUp3 = await this.measureUpload(1001000, 8);
26
- const uploadTests = [...testUp1, ...testUp2, ...testUp3];
58
+ // lets test the upload speed with configurable parallel streams
59
+ const measureUploadParallel = (bytes: number, iterations: number) => {
60
+ if (parallel <= 1) {
61
+ return this.measureUpload(bytes, iterations);
62
+ }
63
+ return Promise.all(
64
+ Array(parallel)
65
+ .fill(null)
66
+ .map(() => this.measureUpload(bytes, iterations)),
67
+ ).then((arrays) => arrays.flat());
68
+ };
69
+ let uploadTests: number[];
70
+ if (this.opts.duration && this.opts.duration > 0) {
71
+ // duration-based upload: run for specified seconds
72
+ uploadTests = [];
73
+ const durMsUp = this.opts.duration * 1000;
74
+ const startMsUp = Date.now();
75
+ const chunkBytesUp = 1001000;
76
+ while (Date.now() - startMsUp < durMsUp) {
77
+ const speeds = await measureUploadParallel(chunkBytesUp, 1);
78
+ uploadTests.push(...speeds);
79
+ }
80
+ if (uploadTests.length === 0) uploadTests = [0];
81
+ } else {
82
+ const u1 = await measureUploadParallel(11000, 10);
83
+ const u2 = await measureUploadParallel(101000, 10);
84
+ const u3 = await measureUploadParallel(1001000, 8);
85
+ uploadTests = [...u1, ...u2, ...u3];
86
+ }
27
87
  const speedUpload = stats.quartile(uploadTests, 0.9).toFixed(2);
28
88
 
29
89
  return {
@@ -49,8 +109,8 @@ export class CloudflareSpeed {
49
109
  measurements.push(response[4] - response[0] - response[6]);
50
110
  },
51
111
  (error) => {
52
- console.log(`Error: ${error}`);
53
- }
112
+ getLogger().error('Error measuring latency:', error);
113
+ },
54
114
  );
55
115
  }
56
116
 
@@ -73,8 +133,8 @@ export class CloudflareSpeed {
73
133
  measurements.push(await this.measureSpeed(bytes, transferTime));
74
134
  },
75
135
  (error) => {
76
- console.log(`Error: ${error}`);
77
- }
136
+ getLogger().error('Error measuring download chunk:', error);
137
+ },
78
138
  );
79
139
  }
80
140
 
@@ -91,8 +151,8 @@ export class CloudflareSpeed {
91
151
  measurements.push(await this.measureSpeed(bytes, transferTime));
92
152
  },
93
153
  (error) => {
94
- console.log(`Error: ${error}`);
95
- }
154
+ getLogger().error('Error measuring upload chunk:', error);
155
+ },
96
156
  );
97
157
  }
98
158
 
@@ -104,15 +164,17 @@ export class CloudflareSpeed {
104
164
  }
105
165
 
106
166
  public async fetchServerLocations(): Promise<{ [key: string]: string }> {
107
- const res = JSON.parse(await this.get('speed.cloudflare.com', '/locations'));
108
-
109
- return res.reduce((data: any, optionsArg: { iata: string; city: string }) => {
110
- // Bypass prettier "no-assign-param" rules
111
- const data1 = data;
112
-
113
- data1[optionsArg.iata] = optionsArg.city;
114
- return data1;
115
- }, {});
167
+ const res = JSON.parse(await this.get('speed.cloudflare.com', '/locations')) as Array<{
168
+ iata: string;
169
+ city: string;
170
+ }>;
171
+ return res.reduce(
172
+ (data: Record<string, string>, optionsArg) => {
173
+ data[optionsArg.iata] = optionsArg.city;
174
+ return data;
175
+ },
176
+ {} as Record<string, string>,
177
+ );
116
178
  }
117
179
 
118
180
  public async get(hostname: string, path: string): Promise<string> {
@@ -122,6 +184,8 @@ export class CloudflareSpeed {
122
184
  hostname,
123
185
  path,
124
186
  method: 'GET',
187
+ // disable connection pooling to avoid listener accumulation
188
+ agent: false,
125
189
  },
126
190
  (res) => {
127
191
  const body: Array<Buffer> = [];
@@ -135,10 +199,10 @@ export class CloudflareSpeed {
135
199
  reject(e);
136
200
  }
137
201
  });
138
- req.on('error', (err) => {
139
- reject(err);
202
+ req.on('error', (err: Error & { code?: string }) => {
203
+ reject(new NetworkError(err.message, err.code));
140
204
  });
141
- }
205
+ },
142
206
  );
143
207
 
144
208
  req.end();
@@ -179,7 +243,9 @@ export class CloudflareSpeed {
179
243
 
180
244
  return new Promise((resolve, reject) => {
181
245
  started = plugins.perfHooks.performance.now();
182
- const req = plugins.https.request(options, (res) => {
246
+ // disable connection pooling to avoid listener accumulation across requests
247
+ const reqOptions = { ...options, agent: false };
248
+ const req = plugins.https.request(reqOptions, (res) => {
183
249
  res.once('readable', () => {
184
250
  ttfb = plugins.perfHooks.performance.now();
185
251
  });
@@ -193,25 +259,26 @@ export class CloudflareSpeed {
193
259
  sslHandshake,
194
260
  ttfb,
195
261
  ended,
196
- parseFloat(res.headers['server-timing'].slice(22) as any),
262
+ parseFloat((res.headers['server-timing'] as string).slice(22)),
197
263
  ]);
198
264
  });
199
265
  });
200
266
 
201
- req.on('socket', (socket) => {
202
- socket.on('lookup', () => {
267
+ // Listen for timing events once per new socket
268
+ req.once('socket', (socket) => {
269
+ socket.once('lookup', () => {
203
270
  dnsLookup = plugins.perfHooks.performance.now();
204
271
  });
205
- socket.on('connect', () => {
272
+ socket.once('connect', () => {
206
273
  tcpHandshake = plugins.perfHooks.performance.now();
207
274
  });
208
- socket.on('secureConnect', () => {
275
+ socket.once('secureConnect', () => {
209
276
  sslHandshake = plugins.perfHooks.performance.now();
210
277
  });
211
278
  });
212
279
 
213
- req.on('error', (error) => {
214
- reject(error);
280
+ req.on('error', (error: Error & { code?: string }) => {
281
+ reject(new NetworkError(error.message, error.code));
215
282
  });
216
283
 
217
284
  req.write(data);
@@ -219,39 +286,25 @@ export class CloudflareSpeed {
219
286
  });
220
287
  }
221
288
 
222
- public async fetchCfCdnCgiTrace(): Promise<{
223
- fl: string;
224
- h: string;
225
- ip: string;
226
- ts: string;
227
- visit_scheme: string;
228
- uag: string;
229
- colo: string;
230
- http: string;
231
- loc: string;
232
- tls: string;
233
- sni: string;
234
- warp: string;
235
- gateway: string;
236
- }> {
289
+ /**
290
+ * Fetch Cloudflare's trace endpoint and parse key=value lines to a record.
291
+ */
292
+ public async fetchCfCdnCgiTrace(): Promise<Record<string, string>> {
237
293
  const parseCfCdnCgiTrace = (text: string) =>
238
294
  text
239
295
  .split('\n')
240
296
  .map((i) => {
241
- const j = i.split('=');
242
-
243
- return [j[0], j[1]];
297
+ const parts = i.split('=');
298
+ return [parts[0], parts[1]];
244
299
  })
245
- .reduce((data: any, [k, v]) => {
246
- if (v === undefined) return data;
247
-
248
- // Bypass prettier "no-assign-param" rules
249
- const data1 = data;
250
- // Object.fromEntries is only supported by Node.js 12 or newer
251
- data1[k] = v;
252
-
253
- return data1;
254
- }, {});
300
+ .reduce(
301
+ (data: Record<string, string>, [k, v]) => {
302
+ if (v === undefined) return data;
303
+ data[k] = v;
304
+ return data;
305
+ },
306
+ {} as Record<string, string>,
307
+ );
255
308
 
256
309
  return this.get('speed.cloudflare.com', '/cdn-cgi/trace').then(parseCfCdnCgiTrace);
257
310
  }