@mark1russell7/netdiag-cli 0.4.0 → 0.4.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.
@@ -0,0 +1,195 @@
1
+ import { Cause, Diagnosis, Evidence, Fact, Grant, MtuSearch, Observable, Skipped, Target, VisitInput, VisitRole, VisitStep } from "@mark1russell7/netdiag/core";
2
+ import { Result } from "@mark1russell7/optional";
3
+ /** The schemes of the HTTP request of a check. */
4
+ declare const SCHEMES: readonly ["http", "https"];
5
+ /** A scheme of the HTTP request of a check. */
6
+ type Scheme = (typeof SCHEMES)[number];
7
+ /** This function tells if a value is a scheme of a check. */
8
+ declare function isScheme(value: unknown): value is Scheme;
9
+ /** The options of the command `check`. Each field is a flag of the command line. */
10
+ interface CheckOptions {
11
+ /** The host to check: a DNS name, an IP address, `host:port` or a URL. */
12
+ readonly target: string;
13
+ /** The port of the HTTP request. The default is the port in the target, then the port of the scheme. */
14
+ readonly port?: number | undefined;
15
+ /** The scheme of the HTTP request. The default is the scheme of a URL target, then `https`. */
16
+ readonly scheme?: Scheme | undefined;
17
+ /** The path of the HTTP request. The default is the path of a URL target, then `/`. */
18
+ readonly path?: string | undefined;
19
+ /** The hosts that work, for a comparison with the target. */
20
+ readonly reference?: readonly string[] | undefined;
21
+ /** The address of the DNS resolver, with an optional port. The default is the first resolver of the computer. */
22
+ readonly resolver?: string | undefined;
23
+ /** The IP address of the default gateway. Without it, the check does not ping a gateway. */
24
+ readonly gateway?: string | undefined;
25
+ /** The CIDR ranges that the user owns. The check can probe each address in them. */
26
+ readonly grant?: readonly string[] | undefined;
27
+ /** The number of echo requests to each address. The default is `DEFAULT_PING_COUNT`. */
28
+ readonly pingCount?: number | undefined;
29
+ /**
30
+ * `true` searches the MTU of the path to each address. Without it, the check searches only after a TLS handshake or
31
+ * an HTTP response that timed out. `false` does not search.
32
+ */
33
+ readonly mtu?: boolean | undefined;
34
+ }
35
+ /** The parts of the computer that a plan reads. */
36
+ interface PlanSystem {
37
+ /** The DNS resolvers of the computer, in the form of `getServers()` of `node:dns`. */
38
+ readonly resolvers: readonly string[];
39
+ }
40
+ /** The plan of a check: the target, the HTTP request, the number of echo requests, and the input of the visit. */
41
+ interface CheckPlan {
42
+ /** The target, with the port of the HTTP request when the user gives one. */
43
+ readonly target: Target;
44
+ readonly scheme: Scheme;
45
+ readonly path: string;
46
+ readonly pingCount: number;
47
+ /** When the visit searches the MTU of the path to an address. The default is `auto`. */
48
+ readonly mtu?: MtuSearch | undefined;
49
+ /** The input of `visitTarget`, with the grants of the scope. */
50
+ readonly visit: VisitInput;
51
+ }
52
+ /**
53
+ * This function gives the plan of a check from the options of the command line, or each problem of the options.
54
+ *
55
+ * The grants of the plan are the scope rule of the command. The plan grants only these hosts:
56
+ *
57
+ * - the target, and each reference host, with the basis `named`
58
+ * - the DNS resolver, with the basis `named` from `--resolver`, or `configured` from the computer
59
+ * - the gateway, when the user gives it, with the basis `named`
60
+ * - each range of `--grant`, with the basis `owned`
61
+ *
62
+ * The visit also puts in the scope the addresses that the resolver gives for a named host.
63
+ */
64
+ declare function planCheck(options: CheckOptions, system: PlanSystem): Result<CheckPlan, readonly string[]>;
65
+ /**
66
+ * A probe of a visit: the DNS query, the ICMP echo requests, the TLS handshake, the HTTP request, the HTTPS request or
67
+ * the MTU search.
68
+ */
69
+ type NextProbeKind = "dns" | "ping" | "tls" | "http" | "https" | "mtu";
70
+ /** A probe that the next step can start, for one role of the visit. */
71
+ interface NextProbe {
72
+ /** The id of the candidate: the role and the probe, for example `gateway.ping`. */
73
+ readonly id: string;
74
+ readonly role: VisitRole;
75
+ readonly probe: NextProbeKind;
76
+ /** The fact kinds that the probe gives. A TLS handshake and an HTTP request also give the TCP connect before them. */
77
+ readonly kinds: readonly string[];
78
+ /** An approximate time of the probe, in seconds. When two gains are equal, the lower cost comes first. */
79
+ readonly cost: number;
80
+ }
81
+ /** The next step of a check: the instruction in plain words, its information gain, and the features that it observes. */
82
+ interface NextStep {
83
+ /** The id of the probe of the step, for example `gateway.ping`. */
84
+ readonly id: string;
85
+ /** The instruction to the user. */
86
+ readonly step: string;
87
+ /** The expected information gain over the most probable causes, in bits. */
88
+ readonly gain: number;
89
+ /** The features that the step observes and that the evidence does not have. */
90
+ readonly observes: readonly Observable[];
91
+ }
92
+ /** The number of the most probable causes that the report shows, and that the gain of a next step tells apart. */
93
+ declare const TOP_CAUSES = 3;
94
+ /**
95
+ * The candidates of the next step: each probe of the target and of the reference hosts, and the ping of the gateway.
96
+ * The MTU search of the path to an address is a candidate of the target and of the reference hosts.
97
+ *
98
+ * - The HTTPS request is one candidate. It observes the features of the TCP connect, the TLS handshake and the HTTP
99
+ * answer together, 7 in all. Thus its gain counts what the three stages tell together.
100
+ * - The TLS handshake is a second candidate. It costs less, so it comes first when the HTTP answer adds no gain.
101
+ * - The HTTP request is the candidate of the scheme `http`, and the HTTPS request is the candidate of the scheme `https`.
102
+ */
103
+ declare const NEXT_PROBES: readonly NextProbe[];
104
+ /** The instruction to add a reference host. */
105
+ declare const ADD_REFERENCE = "Add a host that works for you with --reference <host>, for example a large web site.";
106
+ /** The instruction to add the gateway. */
107
+ declare const ADD_GATEWAY = "Give the address of your router with --gateway <address>.";
108
+ /** This function gives the instruction of a next step in plain words. */
109
+ declare function stepText(probe: NextProbe, observes: readonly Observable[], plan: CheckPlan): string;
110
+ /**
111
+ * This function gives the next steps of a check, from the largest information gain. The first step is the next step.
112
+ *
113
+ * - A candidate observes the features of its fact kinds that the evidence does not have, with the role of the probe.
114
+ * A feature after a stage that gave another value is not observable: no address follows an answer `nxdomain`.
115
+ * - A probe that cannot give its facts is not a candidate. `addressed` has the roles with an address to probe: an IP
116
+ * address, or an address of a DNS answer.
117
+ * - A step with a gain of `GAIN_RESOLUTION` or less tells nothing, so the list does not have it.
118
+ * - Two probes with the same instruction give one step, with the larger gain. For example, each probe of a reference
119
+ * host that the user did not give has the instruction `ADD_REFERENCE`.
120
+ */
121
+ declare function nextSteps(diagnosis: Diagnosis, plan: CheckPlan, addressed: ReadonlySet<VisitRole>): NextStep[];
122
+ /** The format of the JSON report of a check. A change to the shape of `CheckReport` changes the format. */
123
+ declare const CHECK_FORMAT = "netdiag-check/1";
124
+ /** A fact of a visit, with the role and the host of the step that gave it. */
125
+ interface CheckFact {
126
+ readonly role: VisitRole;
127
+ readonly host: string;
128
+ readonly fact: Fact;
129
+ }
130
+ /** A problem of a visit: a probe that did not end, with the role and the host of the step. */
131
+ interface CheckProblem {
132
+ readonly role: VisitRole;
133
+ readonly host: string;
134
+ readonly problem: string;
135
+ }
136
+ /** The report of a check. `--json` writes this object. */
137
+ interface CheckReport {
138
+ readonly format: typeof CHECK_FORMAT;
139
+ /** The target, as `host` or `host:port`. */
140
+ readonly target: string;
141
+ readonly scheme: Scheme;
142
+ readonly path: string;
143
+ /** The grants of the scope of the check. */
144
+ readonly grants: readonly Grant[];
145
+ /** Each cause, from the most probable. */
146
+ readonly causes: readonly Cause[];
147
+ /** The next step, or `null` when no probe can tell more about the most probable causes. */
148
+ readonly next: NextStep | null;
149
+ /** Each next step with a gain, from the largest gain. The first one is `next`. */
150
+ readonly choices: readonly NextStep[];
151
+ readonly problems: readonly CheckProblem[];
152
+ /** The evidence that the diagnosis used. A fact of the role `target` gives primary evidence. */
153
+ readonly evidence: readonly Evidence[];
154
+ /** The evidence that the diagnosis did not use, with the reason. */
155
+ readonly ignored: Diagnosis["ignored"];
156
+ /** The facts that gave no evidence, with the reason. */
157
+ readonly skipped: readonly Skipped[];
158
+ readonly facts: readonly CheckFact[];
159
+ }
160
+ /**
161
+ * This function gives the report of the steps of a visit.
162
+ *
163
+ * - A fact of the role `target` gives primary evidence. A fact of each other role gives reference evidence.
164
+ * - The report finds the facts of the target by their role, not by their position. Thus a first step of the role
165
+ * `local` is not a problem.
166
+ * - The causes come from `diagnose` with `STANDARD_CATALOG`. The next steps come from `nextSteps`.
167
+ */
168
+ declare function reportOf(plan: CheckPlan, steps: readonly VisitStep[]): CheckReport;
169
+ /** This function gives a probability as a percent for a person: `<1%` for a probability above 0 that rounds to 0. */
170
+ declare function percentOf(probability: number): string;
171
+ /**
172
+ * This function gives the role and the host of a step for a person. A step of the role `local` is a passive read of
173
+ * this computer, so its text is `this computer`.
174
+ */
175
+ declare function subjectText(role: string, host: string): string;
176
+ /**
177
+ * This function gives the lines of the text report of a check. The lines show the most probable causes with their
178
+ * probabilities and the next step with its gain. They also show the problems of the visit and the count of the evidence.
179
+ */
180
+ declare function formatReport(report: CheckReport): string[];
181
+ /** The largest number of problems that `readCheckReport` gives. A file of another format has many problems, and the first ones tell enough. */
182
+ declare const MAX_REPORT_PROBLEMS = 20;
183
+ /**
184
+ * This function reads a report of the format `netdiag-check/1`, for example the output of `--json`, and checks it.
185
+ *
186
+ * - Each field of `CheckReport` has its type. Each fact passes `readFact` of netdiag with the fact kinds of netdiag.
187
+ * - The causes go from the most probable, and their probabilities sum to 1. `next` is the first of `choices`.
188
+ * - Each fact id of the evidence and of `skipped` is the id of a fact of the report, and each fact id is unique.
189
+ *
190
+ * The result is the same object with the type `CheckReport`, or at most `MAX_REPORT_PROBLEMS` problems. This module
191
+ * starts no probe, so a browser can read a report with it.
192
+ */
193
+ declare function readCheckReport(value: unknown): Result<CheckReport, string[]>;
194
+ export { planCheck as C, isScheme as E, PlanSystem as S, Scheme as T, TOP_CAUSES as _, MAX_REPORT_PROBLEMS as a, CheckOptions as b, readCheckReport as c, ADD_GATEWAY as d, ADD_REFERENCE as f, NextStep as g, NextProbeKind as h, CheckReport as i, reportOf as l, NextProbe as m, CheckFact as n, formatReport as o, NEXT_PROBES as p, CheckProblem as r, percentOf as s, CHECK_FORMAT as t, subjectText as u, nextSteps as v, SCHEMES as w, CheckPlan as x, stepText as y };
195
+ //# sourceMappingURL=report-CFfbXV7w.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"report-CFfbXV7w.d.ts","names":[],"sources":["../src/scheme.ts","../src/plan.ts","../src/next.ts","../src/report.ts"],"mappings":";;;cAGa;;KAGD,iBAAiB;;iBAGb,SAAS,iBAAiB,SAAS;;UCalC;;WAEN;;WAEA;;WAEA,SAAS;;WAET;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;WAKA;;;UAIM;;WAEN;;;UAIM;;WAEN,QAAQ;WACR,QAAQ;WACR;WACA;;WAEA,MAAM;;WAEN,OAAO;;;;;;;;;;;;;;iBAgDF,UAAU,SAAS,cAAc,QAAQ,aAAa,OAAO;;;;;KClFjE;;UAGK;;WAEN;WACA,MAAM;WACN,OAAO;;WAEP;;WAEA;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA,mBAAmB;;;cAIjB;;;;;;;;;;cAmCA,sBAAsB;;cAatB;;cAGA;;iBAuDG,SAAS,OAAO,WAAW,mBAAmB,cAAc,MAAM;;;;;;;;;;;;iBAqClE,UAAU,WAAW,WAAW,MAAM,WAAW,WAAW,YAAY,aAAa;;cCxKxF;;UAGI;WACN,MAAM;WACN;WACA,MAAM;;;UAIA;WACN,MAAM;WACN;WACA;;;UAIM;WACN,eAAe;;WAEf;WACA,QAAQ;WACR;;WAEA,iBAAiB;;WAEjB,iBAAiB;;WAEjB,MAAM;;WAEN,kBAAkB;WAClB,mBAAmB;;WAEnB,mBAAmB;;WAEnB,SAAS;;WAET,kBAAkB;WAClB,gBAAgB;;;;;;;;;;iBAqBX,SAAS,MAAM,WAAW,gBAAgB,cAAc;;iBA4BxD,UAAU;;;;;iBASV,YAAY,cAAc;;;;;iBAW1B,aAAa,QAAQ;;cAoBxB;;;;;;;;;;;iBAiEG,gBAAgB,iBAAiB,OAAO"}
@@ -1,153 +1,13 @@
1
- import { DNS_ANSWER, GAIN_RESOLUTION, HTTP_RESPONSE, ICMP_ECHO, LOSS_MIN_SENT, PATH_MTU, STANDARD_CATALOG, TCP_CONNECT, TLS_HANDSHAKE, canonicalHost, diagnose, featuresOf, formatTarget, grantProblems, hostKind, isFactOf, namedGrant, parseTarget, rankProbes, readEvidence, visitTarget } from "@mark1russell7/netdiag";
2
- import { DEFAULT_PING_COUNT, MAX_PING_COUNT, commandHost } from "@mark1russell7/netdiag/tools";
1
+ import { DNS_ANSWER, GAIN_RESOLUTION, HTTP_RESPONSE, ICMP_ECHO, LOSS_MIN_SENT, NATIVE_KINDS, PATH_MTU, STANDARD_CATALOG, TCP_CONNECT, TLS_HANDSHAKE, TOOL_KINDS, VISIT_ROLES, diagnose, featuresOf, formatTarget, hostKind, isFactOf, rankProbes, readEvidence, readFact } from "@mark1russell7/netdiag/core";
3
2
  import { err, ok } from "@mark1russell7/optional";
4
3
  import { countOf } from "@mark1russell7/text";
5
4
  import { pad } from "@mark1russell7/text/length";
6
- import { getServers } from "node:dns";
7
- import { realClock } from "@mark1russell7/algebra/clock";
8
- import { runCommand } from "@procedures/shell/command";
9
- import { readFileSync } from "node:fs";
10
- import { createProcedureCli } from "@procedures/cli-kit";
11
- import { defineProcedure } from "@procedures/client";
12
- import { z } from "zod";
13
- // src/plan.ts
5
+ // src/scheme.ts
14
6
  /** The schemes of the HTTP request of a check. */
15
7
  const SCHEMES = ["http", "https"];
16
- function isScheme(text) {
17
- return SCHEMES.includes(text);
18
- }
19
- /** This function reads a host of the user. A URL also gives a scheme and a path. Only a port in the text stays in the target. */
20
- function locate(text, what) {
21
- const parsed = parseTarget(text);
22
- if (parsed.tag === "err") return err(`The ${what} is not valid. ${parsed.error}`);
23
- if (!text.includes("://")) return ok({ target: parsed.value });
24
- const url = new URL(text.trim());
25
- const scheme = url.protocol.slice(0, -1);
26
- if (!isScheme(scheme)) return err(`The ${what} "${text}" has the scheme ${scheme}. A check sends HTTP and HTTPS requests only.`);
27
- const host = {
28
- host: parsed.value.host,
29
- kind: parsed.value.kind
30
- };
31
- const target = url.port === "" ? host : {
32
- ...host,
33
- port: Number(url.port)
34
- };
35
- return ok({
36
- target,
37
- scheme,
38
- path: `${url.pathname}${url.search}`
39
- });
40
- }
41
- /** This function gives a grant of one IP address. */
42
- function addressGrant(address, basis, note) {
43
- return {
44
- ...namedGrant(address, note),
45
- basis
46
- };
47
- }
48
- function visitHost(target) {
49
- return target.port === void 0 ? { host: target.host } : {
50
- host: target.host,
51
- port: target.port
52
- };
53
- }
54
- function whole(value, low, high) {
55
- return Number.isInteger(value) && value >= low && value <= high;
56
- }
57
- /**
58
- * This function gives the plan of a check from the options of the command line, or each problem of the options.
59
- *
60
- * The grants of the plan are the scope rule of the command. The plan grants only these hosts:
61
- *
62
- * - the target, and each reference host, with the basis `named`
63
- * - the DNS resolver, with the basis `named` from `--resolver`, or `configured` from the computer
64
- * - the gateway, when the user gives it, with the basis `named`
65
- * - each range of `--grant`, with the basis `owned`
66
- *
67
- * The visit also puts in the scope the addresses that the resolver gives for a named host.
68
- */
69
- function planCheck(options, system) {
70
- const problems = [];
71
- const grants = [];
72
- const located = locate(options.target, "target");
73
- if (located.tag === "err") return err([located.error]);
74
- const scheme = options.scheme ?? located.value.scheme ?? "https";
75
- const path = options.path ?? located.value.path ?? "/";
76
- if (!isScheme(scheme)) problems.push(`The scheme ${String(scheme)} is not http or https.`);
77
- if (!path.startsWith("/")) problems.push(`The path "${path}" does not start with "/".`);
78
- const port = options.port ?? located.value.target.port;
79
- if (port !== void 0 && !whole(port, 1, 65535)) problems.push(`The port ${port} is not an integer from 1 to 65535.`);
80
- const pingCount = options.pingCount ?? DEFAULT_PING_COUNT;
81
- if (!whole(pingCount, 0, MAX_PING_COUNT)) problems.push(`The ping count ${pingCount} is not an integer from 0 to ${MAX_PING_COUNT}.`);
82
- const target = port === void 0 ? {
83
- host: located.value.target.host,
84
- kind: located.value.target.kind
85
- } : {
86
- ...located.value.target,
87
- port
88
- };
89
- grants.push(namedGrant(target, "the target"));
90
- const references = [];
91
- for (const text of options.reference ?? []) {
92
- const reference = locate(text, "reference");
93
- if (reference.tag === "err") problems.push(reference.error);
94
- else {
95
- references.push(visitHost(reference.value.target));
96
- grants.push(namedGrant(reference.value.target, "a reference host"));
97
- }
98
- }
99
- let resolver;
100
- const resolverText = options.resolver ?? system.resolvers[0];
101
- if (resolverText !== void 0) {
102
- const from = options.resolver === void 0 ? "The DNS resolver of the computer" : "The DNS resolver";
103
- const parsed = parseTarget(resolverText);
104
- if (parsed.tag === "err") problems.push(`${from} is not valid. ${parsed.error}`);
105
- else if (parsed.value.kind === "name") problems.push(`${from} "${resolverText}" is not an IP address.`);
106
- else {
107
- resolver = parsed.value.port === void 0 ? { address: parsed.value.host } : {
108
- address: parsed.value.host,
109
- port: parsed.value.port
110
- };
111
- grants.push(addressGrant(parsed.value, options.resolver === void 0 ? "configured" : "named", "the DNS resolver"));
112
- }
113
- }
114
- let gateway;
115
- if (options.gateway !== void 0) {
116
- const host = canonicalHost(options.gateway);
117
- const kind = hostKind(host);
118
- if (kind === "name") problems.push(`The gateway "${options.gateway}" is not an IP address.`);
119
- else {
120
- gateway = host;
121
- grants.push(addressGrant({
122
- host,
123
- kind
124
- }, "named", "the default gateway"));
125
- }
126
- }
127
- for (const cidr of options.grant ?? []) grants.push({
128
- kind: "range",
129
- cidr: cidr.trim(),
130
- basis: "owned",
131
- note: "a range of --grant"
132
- });
133
- for (const grant of grants) for (const problem of grantProblems(grant)) problems.push(grant.basis === "configured" ? `${problem} Give a resolver with --resolver <address>.` : problem);
134
- if (problems.length > 0) return err(problems);
135
- const visit = {
136
- target: visitHost(target),
137
- references,
138
- ...gateway === void 0 ? {} : { gateway },
139
- ...resolver === void 0 ? {} : { resolver },
140
- grants
141
- };
142
- const mtu = options.mtu === void 0 ? "auto" : options.mtu ? "always" : "never";
143
- return ok({
144
- target,
145
- scheme,
146
- path,
147
- pingCount,
148
- mtu,
149
- visit
150
- });
8
+ /** This function tells if a value is a scheme of a check. */
9
+ function isScheme(value) {
10
+ return SCHEMES.includes(value);
151
11
  }
152
12
  // src/next.ts
153
13
  /** The number of the most probable causes that the report shows, and that the gain of a next step tells apart. */
@@ -405,96 +265,113 @@ function formatReport(report) {
405
265
  lines.push("", `${countOf(report.evidence.length, "observation")} from ${countOf(report.facts.length, "fact")}. The option --json gives each fact.`);
406
266
  return lines;
407
267
  }
408
- // src/check.ts
409
- /** This function gives the parts of this computer: the monotonic clock, `runCommand` of `@procedures/shell` and the DNS resolvers. */
410
- function systemDeps() {
411
- return {
412
- clock: realClock,
413
- tools: commandHost(runCommand, process.platform),
414
- resolvers: getServers()
415
- };
268
+ /** The largest number of problems that `readCheckReport` gives. A file of another format has many problems, and the first ones tell enough. */
269
+ const MAX_REPORT_PROBLEMS = 20;
270
+ /** The largest difference of the sum of the probabilities of the causes from 1. */
271
+ const SUM_TOLERANCE = 1e-6;
272
+ const CAUSE_KINDS = /* @__PURE__ */ new Set([
273
+ "none",
274
+ "fault",
275
+ "unknown"
276
+ ]);
277
+ const ROLES = new Set(VISIT_ROLES);
278
+ const FACT_KINDS = [...NATIVE_KINDS, ...TOOL_KINDS];
279
+ function isFields(value) {
280
+ return typeof value === "object" && value !== null && !Array.isArray(value);
281
+ }
282
+ function isName(value) {
283
+ return typeof value === "string" && value !== "";
284
+ }
285
+ function isPart(value) {
286
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
287
+ }
288
+ function isGrant(value) {
289
+ if (!isFields(value) || !isName(value["basis"])) return false;
290
+ return value["kind"] === "host" && isName(value["host"]) || value["kind"] === "range" && isName(value["cidr"]);
291
+ }
292
+ function isCause(value) {
293
+ return isFields(value) && isName(value["id"]) && CAUSE_KINDS.has(value["kind"]) && typeof value["summary"] === "string" && typeof value["step"] === "string" && isPart(value["probability"]);
294
+ }
295
+ function isNextStep(value) {
296
+ if (!isFields(value) || !isName(value["id"]) || typeof value["step"] !== "string") return false;
297
+ const gain = value["gain"];
298
+ const observes = value["observes"];
299
+ return typeof gain === "number" && Number.isFinite(gain) && gain >= 0 && Array.isArray(observes) && observes.every((each) => isFields(each) && isName(each["feature"]) && typeof each["primary"] === "boolean");
300
+ }
301
+ function isEvidence(value) {
302
+ if (!isFields(value) || !isName(value["feature"]) || !isName(value["value"]) || typeof value["primary"] !== "boolean") return false;
303
+ const facts = value["facts"];
304
+ return facts === void 0 || Array.isArray(facts) && facts.every(isName);
305
+ }
306
+ function isProblem(value) {
307
+ return isFields(value) && ROLES.has(value["role"]) && typeof value["host"] === "string" && isName(value["problem"]);
416
308
  }
417
309
  /**
418
- * This function plans a check, starts its visit, and gives the report.
310
+ * This function reads a report of the format `netdiag-check/1`, for example the output of `--json`, and checks it.
419
311
  *
420
- * It throws a `RangeError` with each problem of the options before the first probe.
312
+ * - Each field of `CheckReport` has its type. Each fact passes `readFact` of netdiag with the fact kinds of netdiag.
313
+ * - The causes go from the most probable, and their probabilities sum to 1. `next` is the first of `choices`.
314
+ * - Each fact id of the evidence and of `skipped` is the id of a fact of the report, and each fact id is unique.
315
+ *
316
+ * The result is the same object with the type `CheckReport`, or at most `MAX_REPORT_PROBLEMS` problems. This module
317
+ * starts no probe, so a browser can read a report with it.
421
318
  */
422
- async function check(options, deps) {
423
- const planned = planCheck(options, { resolvers: deps.resolvers });
424
- if (planned.tag === "err") throw new RangeError(planned.error.join("\n"));
425
- const plan = planned.value;
426
- const steps = [];
427
- const visit = visitTarget(plan.visit, {
428
- clock: deps.clock,
429
- tools: deps.tools,
430
- pingCount: plan.pingCount,
431
- mtu: plan.mtu,
432
- scheme: plan.scheme,
433
- path: plan.path,
434
- tls: deps.tls,
435
- signal: deps.signal
436
- });
437
- for await (const step of visit) steps.push(step);
438
- return reportOf(plan, steps);
439
- }
440
- // src/cli.ts
441
- /** The name of the program. */
442
- const PROGRAM = "netdiag";
443
- const CHECK_INPUT = z.object({
444
- target: z.string().min(1).describe("The host to check: a DNS name, an IP address, host:port or a URL"),
445
- port: z.number().int().min(1).max(65535).optional().describe("The port of the HTTP request. The default is the port of the scheme"),
446
- scheme: z.enum(SCHEMES).optional().describe("The scheme of the HTTP request: http or https. The default is https"),
447
- path: z.string().optional().describe("The path of the HTTP request. The default is /"),
448
- reference: z.array(z.string()).optional().describe("A host that works, for a comparison. Give the flag again for more hosts"),
449
- resolver: z.string().optional().describe("The address of the DNS resolver. The default is the first resolver of this computer"),
450
- gateway: z.string().optional().describe("The IP address of the default gateway. The check pings it"),
451
- grant: z.array(z.string()).optional().describe("A CIDR range that you own. The check can probe each address in it"),
452
- pingCount: z.number().int().min(0).max(MAX_PING_COUNT).optional().describe(`The number of echo requests to each address. The default is ${DEFAULT_PING_COUNT}`),
453
- mtu: z.boolean().optional().describe("Search the MTU of the path to each address. The default searches only after a time-out of TLS or HTTP. --no-mtu starts no search")
454
- });
455
- /** This function makes the command line of netdiag with the command `check`. */
456
- function createNetdiagCli(options) {
457
- const procedure = defineProcedure({
458
- path: ["check"],
459
- input: CHECK_INPUT,
460
- output: z.custom(),
461
- metadata: {
462
- description: "Check a target, and show the probable causes of a fault and the next step",
463
- args: ["target"],
464
- effects: {
465
- reads: ["network"],
466
- writes: ["process"],
467
- destructive: false
468
- }
469
- },
470
- handler: (input, context) => options.check(input, context.signal)
471
- });
472
- return createProcedureCli({
473
- name: PROGRAM,
474
- version: options.version,
475
- description: "the probable causes of a network fault, and the next step",
476
- procedures: [procedure],
477
- format: { check: (result) => formatReport(result) },
478
- print: options.print,
479
- terminal: options.terminal
319
+ function readCheckReport(value) {
320
+ if (!isFields(value)) return err(["The report is not a JSON object."]);
321
+ if (value["format"] !== "netdiag-check/1") return err([`The format of the report is ${JSON.stringify(value["format"] ?? null)}, not "${CHECK_FORMAT}".`]);
322
+ const problems = [];
323
+ const need = (pass, problem) => {
324
+ if (!pass) problems.push(problem);
325
+ };
326
+ const list = (field, check, what) => {
327
+ const items = value[field];
328
+ if (!Array.isArray(items)) {
329
+ problems.push(`The field ${field} of the report is not a list.`);
330
+ return [];
331
+ }
332
+ items.forEach((item, at) => need(check(item), `The item ${at + 1} of ${field} is not ${what}.`));
333
+ return items;
334
+ };
335
+ need(isName(value["target"]), "The report has no target.");
336
+ need(isScheme(value["scheme"]), "The scheme of the report is not http or https.");
337
+ need(typeof value["path"] === "string" && value["path"].startsWith("/"), "The path of the report does not start with /.");
338
+ list("grants", isGrant, "a grant");
339
+ const causes = list("causes", isCause, "a cause").filter(isCause);
340
+ if (causes.length > 0) {
341
+ const sum = causes.reduce((total, cause) => total + cause.probability, 0);
342
+ need(Math.abs(sum - 1) <= SUM_TOLERANCE, `The probabilities of the causes sum to ${sum}, not 1.`);
343
+ need(causes.every((cause, at) => at === 0 || (causes[at - 1]?.probability ?? 0) >= cause.probability), "The causes do not go from the most probable.");
344
+ }
345
+ const choices = list("choices", isNextStep, "a next step").filter(isNextStep);
346
+ const next = value["next"];
347
+ need(next === null || isNextStep(next), "The field next of the report is not a next step or null.");
348
+ need(next === null && choices.length === 0 || isNextStep(next) && next.id === choices[0]?.id, "The next step is not the first of the choices.");
349
+ list("problems", isProblem, "a problem of a probe");
350
+ const evidence = list("evidence", isEvidence, "evidence").filter(isEvidence);
351
+ const ignored = list("ignored", (item) => isFields(item) && isEvidence(item["evidence"]) && isName(item["reason"]), "evidence with a reason");
352
+ const skipped = list("skipped", (item) => isFields(item) && isName(item["fact"]) && isName(item["reason"]), "a fact with a reason");
353
+ const ids = /* @__PURE__ */ new Set();
354
+ list("facts", (item) => isFields(item) && ROLES.has(item["role"]) && typeof item["host"] === "string" && isFields(item["fact"]), "a fact with a role and a host").forEach((item, at) => {
355
+ if (!isFields(item)) return;
356
+ const read = readFact(item["fact"], FACT_KINDS);
357
+ if (read.tag === "err") {
358
+ problems.push(...read.error.map((problem) => `The item ${at + 1} of facts: ${problem}`));
359
+ const fact = item["fact"];
360
+ if (isFields(fact) && typeof fact["id"] === "string") ids.add(fact["id"]);
361
+ return;
362
+ }
363
+ need(!ids.has(read.value.id), `The fact id ${read.value.id} is not unique.`);
364
+ ids.add(read.value.id);
480
365
  });
366
+ const cited = [
367
+ ...evidence.flatMap((item) => item.facts ?? []),
368
+ ...ignored.flatMap((item) => isFields(item) && isEvidence(item["evidence"]) ? item["evidence"].facts ?? [] : []),
369
+ ...skipped.flatMap((item) => isFields(item) && isName(item["fact"]) ? [item["fact"]] : [])
370
+ ];
371
+ for (const id of new Set(cited)) need(ids.has(id), `The report names the fact ${id}, and has no fact with this id.`);
372
+ if (problems.length > 0) return err(problems.slice(0, 20));
373
+ return ok(value);
481
374
  }
482
- /** This function gives the version in `package.json` of this package. */
483
- function packageVersion() {
484
- const manifest = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
485
- const version = typeof manifest === "object" && manifest !== null && "version" in manifest ? manifest.version : void 0;
486
- return typeof version === "string" ? version : "0.0.0";
487
- }
488
- /** This function operates the command line on this computer, and gives the exit code. */
489
- async function main(argv) {
490
- return createNetdiagCli({
491
- version: packageVersion(),
492
- check: (options, signal) => check(options, {
493
- ...systemDeps(),
494
- signal
495
- })
496
- }).run(argv);
497
- }
498
- export { stepText as _, check as a, formatReport as c, subjectText as d, ADD_GATEWAY as f, nextSteps as g, TOP_CAUSES as h, packageVersion as i, percentOf as l, NEXT_PROBES as m, createNetdiagCli as n, systemDeps as o, ADD_REFERENCE as p, main as r, CHECK_FORMAT as s, PROGRAM as t, reportOf as u, SCHEMES as v, planCheck as y };
375
+ export { readCheckReport as a, ADD_GATEWAY as c, TOP_CAUSES as d, nextSteps as f, isScheme as h, percentOf as i, ADD_REFERENCE as l, SCHEMES as m, MAX_REPORT_PROBLEMS as n, reportOf as o, stepText as p, formatReport as r, subjectText as s, CHECK_FORMAT as t, NEXT_PROBES as u };
499
376
 
500
- //# sourceMappingURL=cli-BzbcmVhn.js.map
377
+ //# sourceMappingURL=report-CbppPHXp.js.map