fix(formatting): Fix minor formatting issues and newline consistency across project files

This commit is contained in:
Philipp Kunz 2025-05-03 18:56:00 +00:00
parent 7d087e39ef
commit def467a27b
9 changed files with 53 additions and 50 deletions

View File

@ -1,5 +1,13 @@
# Changelog # Changelog
## 2025-05-03 - 4.0.1 - fix(formatting)
Fix minor formatting issues and newline consistency across project files
- Ensure newline at end of package.json, errors.ts, logging.ts, and test files
- Refine code block formatting in readme.md
- Adjust whitespace and code style in smartnetwork classes and cloudflarespeed module
- Minor commitinfo data format update
## 2025-04-28 - 4.0.0 - BREAKING CHANGE(smartnetwork) ## 2025-04-28 - 4.0.0 - BREAKING CHANGE(smartnetwork)
Enhance documentation and add configurable speed test options with plugin architecture improvements Enhance documentation and add configurable speed test options with plugin architecture improvements

View File

@ -16,9 +16,7 @@ You can perform a hop-by-hop traceroute to measure latency per hop. Falls back t
```typescript ```typescript
const hops = await myNetwork.traceroute('google.com', { maxHops: 10, timeout: 5000 }); const hops = await myNetwork.traceroute('google.com', { maxHops: 10, timeout: 5000 });
hops.forEach(h => hops.forEach((h) => console.log(`${h.ttl}\t${h.ip}\t${h.rtt === null ? '*' : h.rtt + ' ms'}`));
console.log(`${h.ttl}\t${h.ip}\t${h.rtt === null ? '*' : h.rtt + ' ms'}`),
);
``` ```
This command will download `@push.rocks/smartnetwork` and add it to your project's `package.json` file. This command will download `@push.rocks/smartnetwork` and add it to your project's `package.json` file.
@ -44,6 +42,7 @@ const myNetwork = new SmartNetwork();
### Performing a Speed Test ### Performing a Speed Test
You can measure the network speed using the `getSpeed` method. It supports optional parameters: You can measure the network speed using the `getSpeed` method. It supports optional parameters:
- `parallelStreams`: number of concurrent streams (default: 1) - `parallelStreams`: number of concurrent streams (default: 1)
- `duration`: test duration in seconds (default: fixed segments) - `duration`: test duration in seconds (default: fixed segments)
@ -143,6 +142,7 @@ console.log(`Public IPv6: ${publicIps.v6}`);
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. 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.
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. 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.
### Plugin Architecture ### Plugin Architecture
You can extend `SmartNetwork` with custom plugins by registering them at runtime: You can extend `SmartNetwork` with custom plugins by registering them at runtime:

View File

@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartnetwork', name: '@push.rocks/smartnetwork',
version: '4.0.0', version: '4.0.1',
description: 'A toolkit for network diagnostics including speed tests, port availability checks, and more.' description: 'A toolkit for network diagnostics including speed tests, port availability checks, and more.'
} }

View File

@ -164,9 +164,10 @@ export class CloudflareSpeed {
} }
public async fetchServerLocations(): Promise<{ [key: string]: string }> { public async fetchServerLocations(): Promise<{ [key: string]: string }> {
const res = JSON.parse( const res = JSON.parse(await this.get('speed.cloudflare.com', '/locations')) as Array<{
await this.get('speed.cloudflare.com', '/locations'), iata: string;
) as Array<{ iata: string; city: string }>; city: string;
}>;
return res.reduce( return res.reduce(
(data: Record<string, string>, optionsArg) => { (data: Record<string, string>, optionsArg) => {
data[optionsArg.iata] = optionsArg.city; data[optionsArg.iata] = optionsArg.city;
@ -296,11 +297,14 @@ export class CloudflareSpeed {
const parts = i.split('='); const parts = i.split('=');
return [parts[0], parts[1]]; return [parts[0], parts[1]];
}) })
.reduce((data: Record<string, string>, [k, v]) => { .reduce(
(data: Record<string, string>, [k, v]) => {
if (v === undefined) return data; if (v === undefined) return data;
data[k] = v; data[k] = v;
return data; return data;
}, {} as Record<string, string>); },
{} as Record<string, string>,
);
return this.get('speed.cloudflare.com', '/cdn-cgi/trace').then(parseCfCdnCgiTrace); return this.get('speed.cloudflare.com', '/cdn-cgi/trace').then(parseCfCdnCgiTrace);
} }

View File

@ -44,9 +44,7 @@ export class SmartNetwork {
* get network speed * get network speed
* @param opts optional speed test parameters * @param opts optional speed test parameters
*/ */
public async getSpeed( public async getSpeed(opts?: { parallelStreams?: number; duration?: number }) {
opts?: { parallelStreams?: number; duration?: number },
) {
const cloudflareSpeedInstance = new CloudflareSpeed(opts); const cloudflareSpeedInstance = new CloudflareSpeed(opts);
return cloudflareSpeedInstance.speedTest(); return cloudflareSpeedInstance.speedTest();
} }
@ -54,10 +52,7 @@ export class SmartNetwork {
/** /**
* Send ICMP pings to a host. Optionally specify count for multiple pings. * Send ICMP pings to a host. Optionally specify count for multiple pings.
*/ */
public async ping( public async ping(host: string, opts?: { timeout?: number; count?: number }): Promise<any> {
host: string,
opts?: { timeout?: number; count?: number },
): Promise<any> {
const timeout = opts?.timeout ?? 500; const timeout = opts?.timeout ?? 500;
const count = opts?.count && opts.count > 1 ? opts.count : 1; const count = opts?.count && opts.count > 1 ? opts.count : 1;
const pinger = new plugins.smartping.Smartping(); const pinger = new plugins.smartping.Smartping();
@ -85,11 +80,7 @@ export class SmartNetwork {
const min = valid.length ? Math.min(...valid) : NaN; const min = valid.length ? Math.min(...valid) : NaN;
const max = valid.length ? Math.max(...valid) : NaN; const max = valid.length ? Math.max(...valid) : NaN;
const avg = valid.length ? stats.average(valid) : NaN; const avg = valid.length ? stats.average(valid) : NaN;
const stddev = valid.length const stddev = valid.length ? Math.sqrt(stats.average(valid.map((v) => (v - avg) ** 2))) : NaN;
? Math.sqrt(
stats.average(valid.map((v) => (v - avg) ** 2)),
)
: NaN;
const packetLoss = ((count - aliveCount) / count) * 100; const packetLoss = ((count - aliveCount) / count) * 100;
return { return {
host, host,
@ -168,7 +159,9 @@ export class SmartNetwork {
*/ */
public async isRemotePortAvailable( public async isRemotePortAvailable(
target: string, target: string,
portOrOpts?: number | { port?: number; protocol?: 'tcp' | 'udp'; timeout?: number; retries?: number }, portOrOpts?:
| number
| { port?: number; protocol?: 'tcp' | 'udp'; timeout?: number; retries?: number },
): Promise<boolean> { ): Promise<boolean> {
let hostPart: string; let hostPart: string;
let port: number | undefined; let port: number | undefined;
@ -252,7 +245,9 @@ export class SmartNetwork {
/** /**
* Resolve DNS records (A, AAAA, MX) * Resolve DNS records (A, AAAA, MX)
*/ */
public async resolveDns(host: string): Promise<{ A: string[]; AAAA: string[]; MX: { exchange: string; priority: number }[] }> { public async resolveDns(
host: string,
): Promise<{ A: string[]; AAAA: string[]; MX: { exchange: string; priority: number }[] }> {
try { try {
const dns = await import('dns'); const dns = await import('dns');
const { resolve4, resolve6, resolveMx } = dns.promises; const { resolve4, resolve6, resolveMx } = dns.promises;
@ -316,14 +311,10 @@ export class SmartNetwork {
const { exec } = await import('child_process'); const { exec } = await import('child_process');
const cmd = `traceroute -n -m ${maxHops} ${host}`; const cmd = `traceroute -n -m ${maxHops} ${host}`;
const stdout: string = await new Promise((resolve, reject) => { const stdout: string = await new Promise((resolve, reject) => {
exec( exec(cmd, { encoding: 'utf8', timeout }, (err, stdout) => {
cmd,
{ encoding: 'utf8', timeout },
(err, stdout) => {
if (err) return reject(err); if (err) return reject(err);
resolve(stdout); resolve(stdout);
}, });
);
}); });
const hops: Hop[] = []; const hops: Hop[] = [];
for (const raw of stdout.split('\n')) { for (const raw of stdout.split('\n')) {