@kaynooo/cli-probe 0.5.0 → 0.6.0

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.
Files changed (3) hide show
  1. package/README.md +27 -14
  2. package/dist/probe.js +9 -7
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @kaynooo/cli-probe
2
2
 
3
- `probe` reports what a site answers in one call: the negotiated HTTP version, the redirect chain, timings, addresses, TLS and certificate, the headers worth knowing, and a warning mark for what needs attention.
3
+ `probe` reports what a site or service answers in one call: HTTP version, redirect chain, timings, addresses, TLS and certificate, notable headers, security headers, `Set-Cookie` audit, DNS comparison, CORS preflight, direct TLS/TCP checks, public IP, and warnings for what needs attention.
4
4
 
5
5
  ```sh
6
6
  bun add -g @kaynooo/cli-probe
@@ -8,36 +8,49 @@ bun add -g @kaynooo/cli-probe
8
8
 
9
9
  | Command | What it does |
10
10
  | --- | --- |
11
- | `probe example.com` | a bare domain tries https first, then http; one line: HTTP version, status, final URL, total time, redirects, certificate expiry, first address and the warnings |
12
- | `probe example.com --verbose` | the whole table: the status chain, timings (dns, connect, tls, first byte, total), A and AAAA addresses, TLS version and cipher, certificate issuer, expiry and names, server, content type and encoding, cache control, hsts, a CDN hint, and whether h2 and h3 are offered |
13
- | `probe a.test b.test` | several targets, probed together, one line (or table) each in the order given |
11
+ | `probe example.com` | a bare domain tries https first, then http; prints the full summary for a single target (`--compact` forces one line) |
12
+ | `probe a.test b.test` | several targets, probed together, one line each in the order given (`--verbose` forces full summaries) |
14
13
  | `probe https://example.com/path --json` | the same as one JSON object |
14
+ | `probe https://example.com --all-headers` | include every response header, not just the notable ones |
15
+ | `probe example.com --fail-on-warn` | exit 1 when any target reports a warning (useful for CI checks) |
15
16
  | `probe -k https://localhost:8443` | go on with a certificate curl does not trust (it is reported as a warning) |
16
17
  | `probe -H "X-Debug: 1" https://example.com` | a header sent with every request, repeatable |
17
18
  | `probe --resolve example.com:203.0.113.7 https://example.com` | reaches the host at that address instead of the DNS answer (an IPv4 or IPv6 literal), repeatable; the certificate is read from that address, the Host header and the SNI stay the host's, and the addresses reported are that one |
18
- | `probe -t 5s example.com` | longest one request may take (20s by default, 3s for a DNS query), a bare number counting seconds |
19
- | `probe --dns example.com` | no HTTP request: the A, AAAA and CNAME records with their TTL as the system resolver, Cloudflare (1.1.1.1), Google (8.8.8.8), Quad9 (9.9.9.9) and each nameserver of the host's zone answer them, and a warning for each resolver answering otherwise than the zone's nameservers |
20
- | `probe --cors https://app.example.com https://api.example.com/items` | sends the preflight a browser on that origin sends before a JSON POST, and says whether it would go on: allowed or refused, each reason, the `access-control-*` and `vary` headers |
21
- | `probe --cors https://app.example.com --method PUT --cors-headers content-type,authorization <url>` | the preflight of another request: its method (POST by default) and the headers it carries (`content-type` by default, empty for none) |
19
+ | `probe -t 5s example.com` | longest one request may take (20s for HTTP/CORS, 10s for TLS, 5s for TCP, 3s for DNS), a bare number counting seconds |
20
+ | `probe dns example.com` | compares A, AAAA and CNAME records with their TTL across the system resolver, Cloudflare (1.1.1.1), Google (8.8.8.8), Quad9 (9.9.9.9) and each nameserver of the host's zone (`--fail-on-warn` exits 1 on warnings) |
21
+ | `probe dns -t MX,TXT,CAA example.com` | queries specific DNS record types (`A`, `AAAA`, `CNAME`, `MX`, `TXT`, `CAA`, `NS`, `SOA`) |
22
+ | `probe cors https://app.example.com https://api.example.com/items` | sends the preflight a browser on that origin sends before a JSON POST, and says whether it would go on: allowed or refused, each reason, the `access-control-*` and `vary` headers |
23
+ | `probe cors https://app.example.com --method PUT --cors-headers content-type,authorization <url>` | the preflight of another request: its method (POST by default) and the headers it carries (`content-type` by default, empty for none) |
24
+ | `probe tls example.com` | inspects TLS protocol, cipher, ALPN and certificate directly without sending an HTTP request (`--resolve`, `-t`, `--fail-on-warn`, `--json`) |
25
+ | `probe tcp example.com:443` | opens a direct non-TLS TCP connection and reports remote IP, port and DNS/connect latency (`--resolve`, `-t`, `--json`) |
26
+ | `probe ip [-4\|-6]` | prints this machine's public IPv4/IPv6 address |
22
27
 
23
28
  ## JSON output
24
29
 
25
- One target prints one object, `{target, url, version, status, chain, timings, addresses, tls, certificate, headers, cdn, offers, httpRedirect, failedHop, warnings}`, unchanged by the other options (`--json` is always the full report). Several targets print an array of those in the order given, an unreachable one being `{target, error}`.
30
+ One HTTP target prints one object, `{target, url, version, status, chain, timings, addresses, tls, certificate, headers, securityHeaders, cookies, cdn, offers, httpRedirect, failedHop, warnings}`, unchanged by the display options (`--json` is always the full report). Several targets print an array of those in the order given, an unreachable one being `{target, error}`.
26
31
 
27
32
  Redirects are followed hop by hop, at most 10; a redirect to a target that does not answer is kept as `failedHop`, `{url, error}`, with a warning. The HTTP version and timings come from `curl --write-out '%{json}'`, the certificate from `node:tls`, which Bun's fetch exposes neither of. HTTP/3 is spoken only when `curl --version` lists it, otherwise h3 is reported from `alt-svc` alone.
28
33
 
29
- Warnings: a certificate with fewer than 14 days left, expired or not trusted, an `http://` twin that does not redirect to https (checked for a bare domain or an https URL on the default port), more than 10 redirects, a site not served over https.
34
+ ### Set-Cookie audit
35
+
36
+ When the final HTTP response sends one or more `Set-Cookie` headers, each cookie is audited (without exposing its value) for missing `HttpOnly`, missing `Secure` (when served over HTTPS), and missing `SameSite` (or `SameSite=None` without `Secure`). Findings are reported in `cookies` (`{name, httpOnly, secure, sameSite, issues}`), shown on a `cookies` row in detailed text output, and appended to `warnings`. When a response sets no cookies, the `cookies` row is omitted and `cookies` is `[]`.
37
+
38
+ Warnings: a certificate with fewer than 14 days left, expired or not trusted, an `http://` twin that does not redirect to https (checked for a bare domain or an https URL on the default port), more than 10 redirects, a site not served over https, and `Set-Cookie` security issues. Pass `--fail-on-warn` on `probe http`, `probe tls`, or `probe dns` to exit 1 when any target reports a warning.
30
39
 
31
40
  ## DNS comparison
32
41
 
33
- `--dns` takes names or URLs, an IP address being refused. The zone is the nearest name up from the host that has NS records, a top-level domain or an alias never counting as one, and a lookup that fails stops the climb rather than take a parent's nameservers; the zone's nameservers are the reference, reached at the address Cloudflare gives for them. Two answers agree when their A records share an address and their AAAA records do too, so a round robin rotating its records is no disagreement while a family one side lacks is one; an alias compares by its target alone, since a zone's nameservers do not follow it out of the zone. A CDN answering by where the question comes from can still show as a disagreement.
42
+ `probe dns` takes names or URLs, an IP address being refused. The zone is the nearest name up from the host that has NS records, a top-level domain or an alias never counting as one, and a lookup that fails stops the climb rather than take a parent's nameservers; the zone's nameservers are the reference, reached at the address Cloudflare gives for them. Two answers agree when their A records share an address and their AAAA records do too, so a round robin rotating its records is no disagreement while a family one side lacks is one; an alias compares by its target alone, since a zone's nameservers do not follow it out of the zone. A CDN answering by where the question comes from can still show as a disagreement.
34
43
 
35
- The system resolver is the one `/etc/resolv.conf` names, asked directly: `/etc/hosts` is not read. The flush advice holds when that is systemd-resolved's stub, `127.0.0.53`. Under Bun a DNS query's `-t` is rounded up to whole seconds, one at least.
44
+ The system resolver is the one `/etc/resolv.conf` names, asked directly: `/etc/hosts` is not read. The flush advice holds when that is systemd-resolved's stub, `127.0.0.53`. Under Bun a DNS query's `--timeout` is rounded up to whole seconds, one at least.
36
45
 
37
46
  Warnings: the system resolver behind the zone (`sudo resolvectl flush-caches` drops its copy, the TTL saying how long it may keep it otherwise, left out for an alias whose own TTL is not known), a public resolver giving what none of the zone's nameservers gives, the nameservers disagreeing among themselves, resolvers disagreeing with no nameserver to tell which is right, a resolver not answering, no zone found or the zone lookup failing. `--json` is `{target, zone, answers, agree, warnings}`, each answer `{resolver, server, authoritative, a, aaaa, cname, ttl, error?}`.
38
47
 
39
48
  ## CORS preflight
40
49
 
41
- `--cors <origin>` sends `OPTIONS` with `Origin`, `Access-Control-Request-Method` and `Access-Control-Request-Headers`, the way a browser does, then applies the Fetch standard's checks: a 2xx status, `access-control-allow-origin` being `*` or the origin, `access-control-allow-methods` listing a method other than GET, HEAD or POST (or `*`), `access-control-allow-headers` covering every header (`*` covers all but `authorization`). The method is uppercased when it is one of the six fetch normalizes (DELETE, GET, HEAD, OPTIONS, POST, PUT) and otherwise sent and matched as typed, `patch` needing `patch` listed. `accept`, `accept-language` and `content-language` are left out of the preflight, a browser letting them through unlisted. Warnings: credentials allowed alongside a `*`, which a credentialed request does not get, and the request's origin allowed without `vary: origin`. `--json` is `{target, url, status, request, allowed, reasons, warnings, headers}`. `-H`, `--resolve`, `-k` and `-t` apply to the preflight too.
50
+ `probe cors <origin> <url>...` sends `OPTIONS` with `Origin`, `Access-Control-Request-Method` and `Access-Control-Request-Headers`, the way a browser does, then applies the Fetch standard's checks: a 2xx status, `access-control-allow-origin` being `*` or the origin, `access-control-allow-methods` listing a method other than GET, HEAD or POST (or `*`), `access-control-allow-headers` covering every header (`*` covers all but `authorization`). The method is uppercased when it is one of the six fetch normalizes (DELETE, GET, HEAD, OPTIONS, POST, PUT) and otherwise sent and matched as typed, `patch` needing `patch` listed. `accept`, `accept-language` and `content-language` are left out of the preflight, a browser letting them through unlisted. Warnings: credentials allowed alongside a `*`, which a credentialed request does not get, and the request's origin allowed without `vary: origin`. `--json` is `{target, url, status, request, allowed, reasons, warnings, headers}`. `-H`, `--resolve`, `-k` and `-t` apply to the preflight too.
51
+
52
+ ## TCP connect
53
+
54
+ `probe tcp <host:port>...` opens a direct non-TLS TCP connection using `node:net` (IPv6 literals take brackets, e.g. `[::1]:5432`) and reports the connected remote IP, port, and DNS/connect/total timings in milliseconds. `--resolve <host:ip>` overrides DNS resolution (repeatable) and `-t`/`--timeout <duration>` sets the connect timeout (`5s` by default). `--json` prints `{target, host, port, connected, remoteIp, remotePort, timings}` (or `{target, host, port, connected, error, timings}` on failure), or an array for several targets.
42
55
 
43
- Exits 0 when every site answered, 1 when one could not be reached or one of its redirects led nowhere, a CORS preflight was refused or no resolver knows a name, 2 on a usage error (a bad URL, header, origin or `--resolve` is refused before any request is made).
56
+ Exits 0 when every target succeeded (and had no warnings when `--fail-on-warn` is passed), 1 when a target could not be reached, timed out, redirected nowhere, failed CORS preflight, had no DNS records, or reported warnings with `--fail-on-warn`, and 2 on a usage error (a bad URL, `host:port`, header, origin or `--resolve` is refused before any request is made).
package/dist/probe.js CHANGED
@@ -1,13 +1,15 @@
1
1
  #!/bin/sh
2
2
  // @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
3
- var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var Nt,Y,be;var init_chunk_rkhsft4a=__esm(()=>{Nt=/\s+\S*$/,Y=/\s/;be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t))});var init_text=__esm(()=>{init_chunk_rkhsft4a()});import process from"process";function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process.stdout,env=process.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}var MODES,AGENT_VARIABLES;var init_mode=__esm(()=>{MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"]});function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var G2,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G2=/^[a-f0-9]+$/i;B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);o=Fe()});var init_colors=__esm(()=>{init_chunk_x450vn3m()});import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process2 from"process";function findUp(names,from=process2.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}var init_config=__esm(()=>{init_args()});import{existsSync as existsSync2,mkdirSync,readFileSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname as dirname2,isAbsolute,join as join2}from"path";import process3 from"process";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process3.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function mainConfigPath(where={}){let jsonc=join2(configBase(where),"kaynooo-cli","config.jsonc");return existsSync2(jsonc)?jsonc:userConfigPath("config",where)}function readCachedObject(path){let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0||!stat.isFile())return FILE_CACHE.delete(path),{};let cached=FILE_CACHE.get(path);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs&&cached.size===stat.size)return cached.data;try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8")),data=isRecord(parsed)?parsed:{};return FILE_CACHE.set(path,{mtimeMs:stat.mtimeMs,size:stat.size,data}),data}catch{return{}}}function readMainConfig(where={}){return readCachedObject(mainConfigPath(where))}var FILE_CACHE;var init_user_config=__esm(()=>{FILE_CACHE=new Map});import{existsSync as existsSync3,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process4 from"process";function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process4.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync2(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=Bun.JSONC.parse(readFileSync2(path,"utf8"));if(isRecord2(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord2(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord2(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord2(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}function warnOnce(message){if(warned.has(message))return;warned.add(message),console.error(`warning: theme ${message}`)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process4.env,from=process4.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];if(chosen===""){let mainTheme=readMainConfig({home,xdg:env.XDG_CONFIG_HOME}).theme;if(isRecord2(mainTheme))files.push({path:`${mainConfigPath({home,xdg:env.XDG_CONFIG_HOME})}#theme`,file:mainTheme})}for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}function activeTheme(){let key=`${process4.cwd()}\x00${process4.env.KIT_THEME??""}\x00${process4.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var DEFAULT,BRIGHT,LIGHT,MONO,ASCII,PRESETS,STYLES,HEX,CONTROL,MAX_FILE_BYTES=65536,SPACES,CUBE,warned,current,currentKey="";var init_theme=__esm(()=>{init_config();init_user_config();DEFAULT={colors:{accent:"cyan",id:"yellow",path:"blue",label:"dim",value:"bold",ok:"green",warn:"yellow",problem:"red",note:"dim",plan:"magenta",passed:"green",failed:"red",running:"cyan",queued:"yellow",skipped:"dim"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",rule:"\u2500",corner:"\u256D",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",ok:"greenBright",warn:"yellowBright",problem:"redBright",note:"white",plan:"magentaBright",passed:"greenBright",failed:"redBright",running:"cyanBright",queued:"yellowBright",skipped:"white"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},MONO={accent:"bold",id:"bold",path:"underline",label:"dim",value:"bold",ok:"bold",warn:"bold",problem:"bold",note:"dim",plan:"dim",passed:"bold",failed:"bold",running:"bold",queued:"dim",skipped:"dim"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},STYLES=new Set(["bold","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,SPACES=/\s+/;CUBE=[0,95,135,175,215,255];warned=new Set});import process5 from"process";function takesControlCodes(stream,env=process5.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process5.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function marked(mark,text,stream,detail,env=process5.env){let colors=paint(stream,env),head=MARK_WORDS[mark];if(takesControlCodes(stream,env)){let{theme}=activeTheme();head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark])}return`${head} ${text}${detail===void 0?"":` ${colors.dim(detail)}`}`}function role(name,stream,env=process5.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}var MARK_WORDS,STATUS_WORDS,STATUS_OF;var init_style=__esm(()=>{init_colors();init_mode();init_theme();MARK_WORDS={ok:"ok:",warn:"warning:",problem:"error:",note:"note:",plan:"would:"};STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status])))});function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}function cutToWidth(line,width,suffix=""){if(Bun.stringWidth(line)<=width)return line;let suffixWidth=suffix===""?0:Bun.stringWidth(suffix),room=Math.max(0,width-suffixWidth),kept="",index=0,styled=!1,linked=!1;while(index<line.length){ESCAPE_CODE.lastIndex=index;let escape=ESCAPE_CODE.exec(line);if(escape!==null){if(kept+=escape[0],escape[0].startsWith(`${ESC}]`))linked=!0;else styled=!0;index=ESCAPE_CODE.lastIndex;continue}let char=String.fromCodePoint(line.codePointAt(index)),columns=Bun.stringWidth(char);if(columns>room)break;kept+=char,room-=columns,index+=char.length}return`${kept}${styled?RESET_STYLE:""}${linked?CLOSE_LINK:""}${suffix}`}var ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text2=__esm(()=>{ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`});import process6 from"process";function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function truncate(text,width){return Ao(text,width,{suffix:"\u2026",includeSuffix:!0})}function textWidth(text){return Bun.stringWidth(text)}function table(rows,{cellWidth,header=!1,align=[],fit,stream=process6.stdout,env=process6.env}={}){let cells=cellWidth===void 0?rows:rows.map((row)=>row.map((cell)=>truncate(cell.replaceAll(LINE_BREAKS," "),cellWidth)));if(outputMode(stream,env)==="agent")return cells.map((row)=>row.map((cell)=>Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g," ")).join("\t")).join(`
3
+ var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};function Ao(t,e,r="..."){let{suffix:n="...",includeSuffix:s=!1,wordBoundary:o=!1}=typeof r==="string"?{suffix:r}:r;if(t.length<=e)return t;let l=Math.max(0,e),c=t.substring(0,Math.max(0,s?l-n.length:l));if(o&&!Y.test(t[c.length]??" "))c=c.replace(Nt,"")||c;if(o)c=c.trimEnd();return s?(c+n).slice(0,l):c+n}var Nt,Y,be;var init_chunk_rkhsft4a=__esm(()=>{Nt=/\s+\S*$/,Y=/\s/;be=new Map(["\u20AC","","\u201A","\u0192","\u201E","\u2026","\u2020","\u2021","\u02C6","\u2030","\u0160","\u2039","\u0152","","\u017D","","","\u2018","\u2019","\u201C","\u201D","\u2022","\u2013","\u2014","\u02DC","\u2122","\u0161","\u203A","\u0153","","\u017E","\u0178"].map((t,e)=>[t,128+e]).filter(([t])=>t))});var init_text=__esm(()=>{init_chunk_rkhsft4a()});import process from"process";function isSet(value){return value!==void 0&&value!==""&&value!=="0"&&value.toLowerCase()!=="false"}function outputMode(stream=process.stdout,env=process.env){let chosen=env.KIT_MODE;if(chosen!==void 0&&MODES.has(chosen))return chosen;if(AGENT_VARIABLES.some((name)=>isSet(env[name])))return"agent";if(stream.isTTY===!0)return"terminal";return isSet(env.CI)?"ci":"pipe"}var MODES,AGENT_VARIABLES;var init_mode=__esm(()=>{MODES=new Set(["terminal","ci","agent","pipe"]),AGENT_VARIABLES=["CLAUDECODE","AI_AGENT","CODEX_SANDBOX","CODEX_CI","CURSOR_AGENT","OPENCODE","GEMINI_CLI","ANTIGRAVITY_AGENT"]});function b(r){let e=r.startsWith("#")?r.slice(1):r;if(!G2.test(e))return[0,0,0];if(e.length===3||e.length===4)return[Number.parseInt(e[0]+e[0],16),Number.parseInt(e[1]+e[1],16),Number.parseInt(e[2]+e[2],16)];if(e.length!==6&&e.length!==8)throw Error(`Invalid hex color length: ${e.length}`);return[Number.parseInt(e.slice(0,2),16),Number.parseInt(e.slice(2,4),16),Number.parseInt(e.slice(4,6),16)]}function C(r,e=globalThis.process?.env??{}){if(e.FORCE_COLOR!==void 0)return h.has(e.FORCE_COLOR);if(e.NO_COLOR!==void 0||e.NODE_DISABLE_COLORS!==void 0||e.TERM==="dumb")return!1;return r?.isTTY===!0}function f(r,e=[]){let l="",n="";for(let t=0,i=e.length;t<i;t++)l+=`\x1B[${e[t][0]}m`,n=`\x1B[${e[t][1]}m${n}`;let c=(t)=>C(r.stream??globalThis.process?.stdout,r.env)?l+t+n:t,g=new Map;return new Proxy(c,{get(t,i){let a=B[i];if(Array.isArray(a)){let s=g.get(i);if(s===void 0)s=f(r,[...e,a]),g.set(i,s);return s}if(typeof a==="function")return(...s)=>{let y=`${i}:${s.join(",")}`,u=g.get(y);if(u===void 0){if(g.size>=64)g.clear();u=f(r,[...e,a(...s)]),g.set(y,u)}return u};throw Error(`Unknown style: ${String(i)}`)}})}function Fe(r={}){return f(r)}var G2,B,h,o;var init_chunk_x450vn3m=__esm(()=>{G2=/^[a-f0-9]+$/i;B={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49],rgb:(r,e,l,n="fg")=>[`${n==="fg"?38:48};2;${r};${e};${l}`,n==="fg"?39:49],hex:(r,e="fg")=>{let[l,n,c]=b(r);return[`${e==="fg"?38:48};2;${l};${n};${c}`,e==="fg"?39:49]},ansi256:(r,e="fg")=>[`${e==="fg"?38:48};5;${r}`,e==="fg"?39:49]},h=new Set(["","1","2","3","true"]);o=Fe()});var init_colors=__esm(()=>{init_chunk_x450vn3m()});import{existsSync}from"fs";import{dirname,join,resolve}from"path";import process2 from"process";function findUp(names,from=process2.cwd(),stop=()=>!1){let wanted=typeof names==="string"?[names]:names;for(let dir=resolve(from);;dir=dirname(dir)){let found=wanted.map((name)=>join(dir,name)).find((path)=>existsSync(path));if(found!==void 0)return found;if(stop(dir)||dirname(dir)===dir)return}}var init_config=__esm(()=>{init_args()});import{existsSync as existsSync2,mkdirSync,readFileSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname as dirname2,isAbsolute,join as join2}from"path";import process3 from"process";function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function xdgFolder(value,fallback){return value!==void 0&&isAbsolute(value)?value:fallback}function configBase(where={}){let xdg=where.xdg??(where.home===void 0?process3.env.XDG_CONFIG_HOME:void 0);return xdgFolder(xdg,join2(where.home??homedir(),".config"))}function userConfigPath(bin,where={}){return join2(configBase(where),"kaynooo-cli",`${bin}.json`)}function mainConfigPath(where={}){let jsonc=join2(configBase(where),"kaynooo-cli","config.jsonc");return existsSync2(jsonc)?jsonc:userConfigPath("config",where)}function readCachedObject(path){let stat=statSync(path,{throwIfNoEntry:!1});if(stat===void 0||!stat.isFile())return FILE_CACHE.delete(path),{};let cached=FILE_CACHE.get(path);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs&&cached.size===stat.size)return cached.data;try{let parsed=Bun.JSONC.parse(readFileSync(path,"utf8")),data=isRecord(parsed)?parsed:{};return FILE_CACHE.set(path,{mtimeMs:stat.mtimeMs,size:stat.size,data}),data}catch{return{}}}function readMainConfig(where={}){return readCachedObject(mainConfigPath(where))}var FILE_CACHE;var init_user_config=__esm(()=>{FILE_CACHE=new Map});import{existsSync as existsSync3,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{homedir as homedir2}from"os";import{join as join3,resolve as resolve2}from"path";import process4 from"process";function isColorSpec(spec){if(typeof spec==="number")return Number.isInteger(spec)&&spec>=0&&spec<=255;return typeof spec==="string"&&spec.trim()!==""&&spec.trim().split(SPACES).every((token)=>STYLES.has(token)||HEX.test(token))}function cubeLevel(channel){return CUBE.reduce((best,value,level)=>Math.abs(value-channel)<Math.abs(CUBE[best]-channel)?level:best,0)}function nearest256(hex){let rgb=[1,3,5].map((at)=>Number.parseInt(hex.slice(at,at+2),16)),levels=rgb.map(cubeLevel),cube=levels.map((level)=>CUBE[level]),grey=Math.min(23,Math.max(0,Math.round((rgb.reduce((sum,channel)=>sum+channel,0)/3-8)/10))),greyValue=8+grey*10,distance=(colour)=>colour.reduce((sum,channel,at)=>sum+(channel-rgb[at])**2,0);return distance([greyValue,greyValue,greyValue])<distance(cube)?232+grey:16+36*levels[0]+6*levels[1]+levels[2]}function hasTrueColor(env){return env.COLORTERM==="truecolor"||env.COLORTERM==="24bit"}function tinted(colors,spec,env=process4.env){if(typeof spec==="number")return colors.ansi256(spec);return spec.trim().split(SPACES).reduce((chain,token)=>{if(HEX.test(token))return hasTrueColor(env)?chain.hex(token):chain.ansi256(nearest256(token));return chain[token]??chain},colors)}function isRecord2(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function readThemeFile(path,warn){try{let stat=statSync2(path,{throwIfNoEntry:!1});if(stat===void 0)return;if(!stat.isFile()||stat.size>MAX_FILE_BYTES){warn(`${path} is not a regular file under ${MAX_FILE_BYTES/1024} KiB, theme ignored`);return}let parsed=Bun.JSONC.parse(readFileSync2(path,"utf8"));if(isRecord2(parsed))return parsed;warn(`${path} is not a JSON object, theme ignored`)}catch(error){warn(`${path} does not parse (${error instanceof Error?error.message:String(error)}), theme ignored`)}return}function applyPreset(theme,name,warn,where){if(name===void 0)return;if(typeof name!=="string"||!Object.hasOwn(PRESETS,name)){warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);return}let preset=PRESETS[name];if(Object.assign(theme.colors,preset.colors),Object.assign(theme.glyphs,preset.glyphs),preset.accents!==void 0)theme.accents=[...preset.accents];if(Object.hasOwn(preset,"gradient"))theme.gradient=preset.gradient;return name}function applyFile(theme,file,where,warn){if(isRecord2(file.colors))for(let[key,value]of Object.entries(file.colors))if(!Object.hasOwn(DEFAULT.colors,key))warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);else if(!isColorSpec(value))warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);else theme.colors[key]=value;if(isRecord2(file.glyphs))for(let[key,value]of Object.entries(file.glyphs))if(!Object.hasOwn(DEFAULT.glyphs,key))warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);else if(typeof value!=="string"||CONTROL.test(value)||Bun.stringWidth(value)!==1)warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);else theme.glyphs[key]=value;if(Array.isArray(file.accents)&&file.accents.length>0&&file.accents.every(isColorSpec))theme.accents=[...file.accents];else if(file.accents!==void 0)warn(`${where}: accents must be a non-empty list of colours`);if(file.gradient===null)theme.gradient=void 0;else if(Array.isArray(file.gradient)&&file.gradient.length===2&&file.gradient.every((end)=>typeof end==="string"&&HEX.test(end)))theme.gradient=[file.gradient[0],file.gradient[1]];else if(file.gradient!==void 0)warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);if(isRecord2(file.bins))for(let[bin,value]of Object.entries(file.bins))if(isColorSpec(value))theme.bins[bin]=value;else warn(`${where}: bin ${bin} has no valid colour`)}function endsWalk(home){return(dir)=>dir===resolve2(home)||existsSync3(join3(dir,".git"))}function warnOnce(message){if(warned.has(message))return;warned.add(message),process4.stderr.write(`warning: theme ${message}
4
+ `)}function isPath(chosen){return chosen.includes("/")||chosen.endsWith(".json")}function loadTheme({env=process4.env,from=process4.cwd(),home=homedir2(),warn=warnOnce}={}){let theme={colors:{...DEFAULT.colors},glyphs:{...DEFAULT.glyphs},accents:[...DEFAULT.accents],bins:Object.create(null),gradient:DEFAULT.gradient},sources=[],chosen=env.KIT_THEME??"",wanted=chosen===""?[userConfigPath("theme",{home,xdg:env.XDG_CONFIG_HOME}),findUp(join3(".kaynooo","theme.json"),from,endsWalk(home))]:[];if(isPath(chosen))wanted.push(resolve2(from,chosen));let files=[];if(chosen===""){let mainTheme=readMainConfig({home,xdg:env.XDG_CONFIG_HOME}).theme;if(isRecord2(mainTheme))files.push({path:`${mainConfigPath({home,xdg:env.XDG_CONFIG_HOME})}#theme`,file:mainTheme})}for(let path of wanted){let file=path===void 0?void 0:readThemeFile(path,warn);if(path!==void 0&&file!==void 0)files.push({path,file})}let preset="default";if(chosen!==""&&!isPath(chosen))preset=applyPreset(theme,chosen,warn,"KIT_THEME")??preset;else{let named=files.findLast(({file})=>file.preset!==void 0);if(named!==void 0)preset=applyPreset(theme,named.file.preset,warn,named.path)??preset}for(let{path,file}of files)applyFile(theme,file,path,warn),sources.push(path);return{theme,sources,preset}}function activeTheme(){let key=`${process4.cwd()}\x00${process4.env.KIT_THEME??""}\x00${process4.env.XDG_CONFIG_HOME??""}`;if(current===void 0||key!==currentKey)current=loadTheme(),currentKey=key;return current}var DEFAULT,BRIGHT,LIGHT,MONO,ASCII,PRESETS,STYLES,HEX,CONTROL,MAX_FILE_BYTES=65536,SPACES,CUBE,warned,current,currentKey="";var init_theme=__esm(()=>{init_config();init_user_config();DEFAULT={colors:{accent:"cyan",id:"yellow",path:"blue",label:"dim",value:"bold",ok:"green",warn:"yellow",problem:"red",note:"dim",plan:"magenta",passed:"green",failed:"red",running:"cyan",queued:"yellow",skipped:"dim"},glyphs:{ok:"\u2713",warn:"\u25B2",problem:"\u2717",note:"\u203A",plan:"\u25C7",passed:"\u2713",failed:"\u2717",running:"\u25CF",queued:"\u25CB",skipped:"-",bar:"\u2501",rule:"\u2500",corner:"\u256D",open:"\u2022",leaf:"\xB7",guide:"\u2502"},accents:["cyan","magenta","green","blue","yellow","redBright"],bins:{},gradient:["#c084fc","#67e8f9"]},BRIGHT={accent:"cyanBright",id:"yellowBright",path:"blueBright",label:"white",value:"bold whiteBright",ok:"greenBright",warn:"yellowBright",problem:"redBright",note:"white",plan:"magentaBright",passed:"greenBright",failed:"redBright",running:"cyanBright",queued:"yellowBright",skipped:"white"},LIGHT={accent:"#0369a1",id:"#b45309",path:"#1d4ed8",label:"#52525b",value:"bold",ok:"#15803d",warn:"#b45309",problem:"#b91c1c",note:"#52525b",plan:"#7e22ce",passed:"#15803d",failed:"#b91c1c",running:"#0369a1",queued:"#b45309",skipped:"#52525b"},MONO={accent:"bold",id:"bold",path:"underline",label:"dim",value:"bold",ok:"bold",warn:"bold",problem:"bold",note:"dim",plan:"dim",passed:"bold",failed:"bold",running:"bold",queued:"dim",skipped:"dim"},ASCII={ok:"+",warn:"!",problem:"x",note:">",plan:"?",passed:"+",failed:"x",running:"*",queued:"o",skipped:"-",bar:"#",rule:"-",corner:"+",open:"*",leaf:"-",guide:"|"},PRESETS={default:{},"high-contrast":{colors:BRIGHT,accents:["cyanBright","magentaBright","greenBright","blueBright","yellowBright","redBright"],gradient:["#d8b4fe","#a5f3fc"]},light:{colors:LIGHT,accents:["#0369a1","#7e22ce","#15803d","#1d4ed8","#b45309","#b91c1c"],gradient:["#7c3aed","#0284c7"]},mono:{colors:MONO,accents:["bold"],gradient:void 0},ascii:{glyphs:ASCII}},STYLES=new Set(["bold","dim","italic","underline","inverse","strikethrough","black","red","green","yellow","blue","magenta","cyan","white","gray","grey","blackBright","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"]),HEX=/^#[0-9a-f]{6}$/i,CONTROL=/\p{Cc}/u,SPACES=/\s+/;CUBE=[0,95,135,175,215,255];warned=new Set});import process5 from"process";function takesControlCodes(stream,env=process5.env){return stream.isTTY===!0&&(env.NO_COLOR===void 0||env.NO_COLOR==="")&&env.NODE_DISABLE_COLORS===void 0&&env.TERM!=="dumb"&&outputMode(stream,env)==="terminal"}function paint(stream,env=process5.env){let effective=env.NO_COLOR===""?{...env,NO_COLOR:void 0}:env;return Fe({stream:{isTTY:takesControlCodes(stream,env)},env:effective})}function marked(mark,text,stream,detail,env=process5.env){let colors=paint(stream,env),head=MARK_WORDS[mark];if(takesControlCodes(stream,env)){let{theme}=activeTheme();head=tinted(colors.bold,theme.colors[mark],env)(theme.glyphs[mark])}return`${head} ${text}${detail===void 0?"":` ${colors.dim(detail)}`}`}function writeErr(text=""){process5.stderr.write(`${text}
5
+ `)}function role(name,stream,env=process5.env){let colors=paint(stream,env);return takesControlCodes(stream,env)?tinted(colors,activeTheme().theme.colors[name],env):colors}var MARK_WORDS,STATUS_WORDS,STATUS_OF,GRAPHEMES;var init_style=__esm(()=>{init_colors();init_mode();init_theme();MARK_WORDS={ok:"ok:",warn:"warning:",problem:"error:",note:"note:",plan:"would:"};STATUS_WORDS={passed:["passed","success","succeeded","ok"],failed:["failed","failure","error","errored"],running:["running","in_progress","started","holding"],queued:["queued","waiting","pending","created","blocked","scheduled"],skipped:["skipped","cancelled","canceled","manual"]},STATUS_OF=new Map(Object.entries(STATUS_WORDS).flatMap(([status,words])=>words.map((word)=>[word,status]))),GRAPHEMES=new Intl.Segmenter});function distance(a,b){let left=[...a],right=[...b],before=[],previous=Array.from({length:right.length+1},(_,index)=>index);for(let[i,x]of left.entries()){let current=[i+1];for(let[j,y]of right.entries()){let cost=Math.min((previous[j+1]??0)+1,(current[j]??0)+1,(previous[j]??0)+(x===y?0:1));if(i>0&&j>0&&x===right[j-1]&&left[i-1]===y)cost=Math.min(cost,(before[j-1]??0)+1);current.push(cost)}before=previous,previous=current}return previous[right.length]??0}function closest(name,names){let started=names.find((known)=>known.startsWith(name));if(started!==void 0)return started;let[best]=names.map((known)=>({known,far:distance(name,known)})).sort((a,b)=>a.far-b.far);return best!==void 0&&best.far<=(name.length<4?1:2)?best.known:void 0}function wrapToWidth(text,width){let lines=[],current="";for(let word of text.split(" "))if(current!==""&&Bun.stringWidth(current)+1+Bun.stringWidth(word)>width)lines.push(current),current=word;else current=current===""?word:`${current} ${word}`;return current===""?lines:[...lines,current]}function cutToWidth(line,width,suffix=""){if(Bun.stringWidth(line)<=width)return line;let suffixWidth=suffix===""?0:Bun.stringWidth(suffix),room=Math.max(0,width-suffixWidth),kept="",index=0,styled=!1,linked=!1;while(index<line.length){ESCAPE_CODE.lastIndex=index;let escape=ESCAPE_CODE.exec(line);if(escape!==null){if(kept+=escape[0],escape[0].startsWith(`${ESC}]`))linked=!0;else styled=!0;index=ESCAPE_CODE.lastIndex;continue}let char=String.fromCodePoint(line.codePointAt(index)),columns=Bun.stringWidth(char);if(columns>room)break;kept+=char,room-=columns,index+=char.length}return`${kept}${styled?RESET_STYLE:""}${linked?CLOSE_LINK:""}${suffix}`}var ESC,ESCAPE_CODE,RESET_STYLE,CLOSE_LINK;var init_text2=__esm(()=>{ESC=String.fromCharCode(27),ESCAPE_CODE=new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`,"y"),RESET_STYLE=`${ESC}[0m`,CLOSE_LINK=`${ESC}]8;;${ESC}\\`});import process6 from"process";function formatSeconds(total){let rest=Math.max(0,Math.round(total)),amounts=UNITS.map(([unit,size])=>{let amount=Math.floor(rest/size);return rest-=amount*size,`${amount}${unit}`}),first=amounts.findIndex((amount)=>!amount.startsWith("0"));if(first===-1)return"0s";let next=amounts[first+1];return next===void 0||next.startsWith("0")?amounts[first]??"0s":`${amounts[first]} ${next}`}function formatDuration(ms){return ms<60000?`${(Math.max(0,ms)/1000).toFixed(1)}s`:formatSeconds(ms/1000)}function upTo(text,separator){let end=text.indexOf(separator);return end===-1?text:text.slice(0,end)}function truncate(text,width){return Ao(text,width,{suffix:"\u2026",includeSuffix:!0})}function textWidth(text){return Bun.stringWidth(text)}function table(rows,{cellWidth,header=!1,align=[],fit,stream=process6.stdout,env=process6.env}={}){let cells=cellWidth===void 0?rows:rows.map((row)=>row.map((cell)=>truncate(cell.replaceAll(LINE_BREAKS," "),cellWidth)));if(outputMode(stream,env)==="agent")return cells.map((row)=>row.map((cell)=>Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g," ")).join("\t")).join(`
4
6
  `);let widths=[];for(let row of cells)for(let[index,cell]of row.entries())widths[index]=Math.max(widths[index]??0,textWidth(cell));let shown=fit===void 0?cells:narrow(cells,widths,fit),colors=paint(stream,env),lines=shown.map((row)=>row.map((cell,index)=>{let width=widths[index]??0,gap=" ".repeat(Math.max(0,width-textWidth(cell)));if(align[index]==="right")return`${gap}${cell}`;return index===row.length-1?cell:`${cell}${gap}`}).join(" ").trimEnd()),rule=header&&takesControlCodes(stream,env)&&lines.length>1?[colors.dim(activeTheme().theme.glyphs.rule.repeat(Math.max(...lines.map(textWidth))))]:[];return lines.flatMap((line,index)=>header&&index===0?[colors.bold(line),...rule]:[line]).join(`
5
7
  `)}function narrow(rows,widths,limit){let used=()=>widths.reduce((sum,width)=>sum+width,0)+2*Math.max(0,widths.length-1),floor=8;while(used()>limit){let widest=-1;for(let[index,width]of widths.entries())if(width>8&&width>(widths[widest]??0))widest=index;if(widest===-1)break;widths[widest]=Math.max(8,(widths[widest]??0)-(used()-limit))}return rows.map((row)=>row.map((cell,index)=>textWidth(cell)>(widths[index]??0)?cutToWidth(cell,widths[index]??0,"\u2026"):cell))}function jsonText(value,replacer,{stream=process6.stdout,env=process6.env}={}){return JSON.stringify(value,replacer,outputMode(stream,env)==="agent"?void 0:2)}function printJson(value){console.log(jsonText(value))}var UNITS,LINE_BREAKS;var init_format=__esm(()=>{init_text();init_mode();init_style();init_text2();init_theme();UNITS=[["d",86400],["h",3600],["m",60],["s",1]];LINE_BREAKS=/\s*\n\s*/g});import process7 from"process";function usageLine(usage,colors=paint(process7.stdout),{summary:withSummary=!0}={}){let lines=usage.replace(USAGE_PREFIX,"").split(`
6
8
  `),blank=lines.indexOf(""),synopses=blank===-1?lines:lines.slice(0,blank),details=blank===-1?[]:lines.slice(blank+1),colon=synopses[0].indexOf(": "),inline=synopses[0].slice(colon+2),summary=colon===-1?details.shift():`${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;if(colon!==-1)synopses[0]=synopses[0].slice(0,colon);let head=`${colors.bold("Usage:")} ${synopses.map((line)=>line.replaceAll(OPTIONAL,(part)=>colors.dim(part))).join(`
7
9
  `)}`,lead=summary===void 0||!withSummary?[]:["",colors.bold(prose(summary,colors))],rest=details.length===0?[]:["",...details.map((line)=>prose(line,colors))];return[head,...lead,...rest].join(`
8
10
  `)}function prose(line,colors){if(colors.cyan("x")==="x")return line;return line.replaceAll(PROSE_MARKS,(match,code,flag)=>code===void 0?colors.cyan(flag??match):colors.bold(code))}function helpText(usage,options,colors=paint(process7.stdout),{examples=[],exits=[],bin,columns}={}){let{summary}=description(usage);return[...bin===void 0?[usageLine(usage,colors)]:[`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary===""?"":` ${summary}`}`,"",usageLine(usage,colors,{summary:!1})],"",colors.bold("Options:"),...optionRows(options,colors,columns),...exitRows(exits,colors),...exampleRows(examples,colors)].join(`
9
11
  `)}function exitRows(exits,colors=paint(process7.stdout)){if(exits.length===0)return[];return["",`${colors.bold("Exit codes:")} ${exits.map(([code,meaning])=>`${colors.cyan(String(code))} ${meaning}`).join(", ")}`]}function wantsHelpJson(env=process7.env,argv){if(env.KIT_HELP==="json")return!0;if(argv===void 0)return!1;let end=argv.indexOf("--"),own=end===-1?argv:argv.slice(0,end);if(own.includes("--help=json"))return!0;return(own.includes("--help")||own.includes("-h")||own[0]==="help")&&own.includes("--json")}function description(usage,{examples=[],replaces,exits}={},options){let lines=usage.replace(USAGE_PREFIX,"").split(`
10
- `),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}function exampleRows(examples,colors=paint(process7.stdout)){if(examples.length===0)return[];let shown=outputMode()==="agent"?examples.slice(0,MAX_AGENT_EXAMPLES):examples;return["",colors.bold("Examples:"),...shown.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}function wrapText(text,limit){if(text.length<=limit)return[text];let lines=[],current="";for(let word of text.split(" "))if(current==="")current=word;else if(current.length+1+word.length<=limit)current=`${current} ${word}`;else lines.push(current),current=word;if(current!=="")lines.push(current);return lines}function optionRows(options,colors=paint(process7.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapText(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}var OPTIONAL,USAGE_PREFIX,FULL_STOP,PROSE_MARKS,MAX_AGENT_EXAMPLES=2,MAX_INLINE_CHOICES=24;var init_help=__esm(()=>{init_mode();init_style();OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi});function durationMs(text,unit){if(BARE_DURATION.test(text))return Number(text)*UNIT_MS[unit];if(!DURATION.test(text))return 0;let ms=0;for(let[,amount,part]of text.matchAll(DURATION_PART))ms+=Number(amount)*UNIT_MS[part];return ms}function duration(value,name,fallback,unit="s"){if(value===void 0)return fallback;let ms=durationMs(value.trim(),unit);if(ms<1)badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);return ms}var BARE_DURATION,DURATION,DURATION_PART,UNIT_MS;var init_input=__esm(()=>{init_args();BARE_DURATION=/^\d+(?:\.\d+)?$/,DURATION=/^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/,DURATION_PART=/(\d+(?:\.\d+)?)(ms|min|[smhd])/g,UNIT_MS={ms:1,s:1000,m:60000,min:60000,h:3600000,d:86400000}});import process8 from"process";import{parseArgs}from"util";function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}function badUsage(message){throw new UsageError(message)}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}function applyOutput(color,plain,env=process8.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),helpJson=wantsHelpJson(process8.env,own),stripHelpJson=(arg)=>{if(arg==="--help=json")return["--help"];return arg==="--json"&&!("json"in options)?[]:[arg]},normalized=helpJson?own.flatMap(stripHelpJson):own,parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(normalized,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process8.stdout)?process8.stdout.columns:void 0;throw console.log(helpJson?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}var DASHES,EXIT,Exit,UsageError,HelpShown,completion,heading,OUTPUT_OPTIONS,UNKNOWN_OPTION;var init_args=__esm(()=>{init_format();init_help();init_style();init_text2();init_help();init_input();DASHES=/^-+/;EXIT=Symbol.for("@kaynooo/cli-kit/Exit");Exit=class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}};UsageError=class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}};HelpShown=class HelpShown extends Exit{constructor(){super("help shown",0)}};completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};UNKNOWN_OPTION=/^unknown option '(-[^']+)'/});var init_folders=__esm(()=>{init_user_config()});import{isIP as isIP2}from"net";import process15 from"process";init_args();import{readFileSync as readFileSync3,realpathSync}from"fs";import{resolve as resolve3}from"path";import process9 from"process";function commandLine(){try{return readFileSync3("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process9.argv.slice(2),cmdline=commandLine(),script=process9.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve3(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}init_format();init_mode();init_style();init_theme();init_args();init_format();init_format();init_style();init_text2();init_theme();init_style();init_format();init_args();import{readFileSync as readFileSync5,realpathSync as realpathSync2}from"fs";import{dirname as dirname4,join as join5}from"path";import process13 from"process";import process10 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process10.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process10.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
12
+ `),first=lines[0],colon=first.indexOf(": "),prose=lines[lines.indexOf("")+1]??"",fallback=lines.includes("")?`${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP,""):"";return{synopsis:colon===-1?first:first.slice(0,colon),summary:colon===-1?fallback:first.slice(colon+2),...replaces===void 0?{}:{replaces},examples:examples.map((example)=>typeof example==="string"?{line:example}:{line:example[0],note:example[1]}),...exits===void 0?{}:{exits:exits.map(([code,meaning])=>({code,meaning}))},...options===void 0?{}:{options:Object.entries(options).map(([name,{short,description}])=>({name,...short===void 0?{}:{short},...description===void 0?{}:{description}}))}}}function exampleRows(examples,colors=paint(process7.stdout)){if(examples.length===0)return[];let shown=outputMode()==="agent"?examples.slice(0,MAX_AGENT_EXAMPLES):examples;return["",colors.bold("Examples:"),...shown.map((example)=>typeof example==="string"?` ${example}`:` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)]}function optionRows(options,colors=paint(process7.stdout),columns){let rows=Object.entries(options).map(([name,option])=>{let short=option.short===void 0?" ":`${colors.cyan(`-${option.short}`)}, `,choices=option.choices?.join("|"),inline=choices!==void 0&&choices.length<=MAX_INLINE_CHOICES,named=inline?`<${choices}>`:"<value>",placeholder=option.optional===void 0?named:`[${named}]`,value=option.type==="string"?` ${colors.dim(placeholder)}`:"",described=choices===void 0||inline?option.description??"":[option.description,`one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");return{flag:`${short}${colors.cyan(`--${name}`)}${value}`,width:`-x, --${name}`.length+(option.type==="string"?placeholder.length+1:0),description:described}}),width=Math.max(0,...rows.map((row)=>row.width)),indent=2+width+2,room=columns!==void 0&&columns-indent>=20?columns-indent:void 0;return rows.flatMap((row)=>{if(row.description==="")return[` ${row.flag}`];let wrapped=room===void 0?[row.description]:wrapToWidth(row.description,room),[first="",...rest]=wrapped;return[` ${row.flag}${" ".repeat(width-row.width)} ${colors.dim(first)}`,...rest.map((line)=>`${" ".repeat(indent)}${colors.dim(line)}`)]})}var OPTIONAL,USAGE_PREFIX,FULL_STOP,PROSE_MARKS,MAX_AGENT_EXAMPLES=2,MAX_INLINE_CHOICES=24;var init_help=__esm(()=>{init_mode();init_style();init_text2();OPTIONAL=/(?<!\x1B)\[[^\]]+\]/g,USAGE_PREFIX=/^usage:\s*/i,FULL_STOP=/\.$/,PROSE_MARKS=/`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi});function durationMs(text,unit){if(BARE_DURATION.test(text))return Number(text)*UNIT_MS[unit];if(!DURATION.test(text))return 0;let ms=0;for(let[,amount,part]of text.matchAll(DURATION_PART))ms+=Number(amount)*UNIT_MS[part];return ms}function duration(value,name,fallback,unit="s"){if(value===void 0)return fallback;let ms=durationMs(value.trim(),unit);if(ms<1)badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);return ms}var BARE_DURATION,DURATION,DURATION_PART,UNIT_MS;var init_input=__esm(()=>{init_args();BARE_DURATION=/^\d+(?:\.\d+)?$/,DURATION=/^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/,DURATION_PART=/(\d+(?:\.\d+)?)(ms|min|[smhd])/g,UNIT_MS={ms:1,s:1000,m:60000,min:60000,h:3600000,d:86400000}});import process8 from"process";import{parseArgs}from"util";function jsonOption(holds){return{type:"boolean",description:holds===void 0?"print JSON":`print JSON: ${holds}`}}function fail(message,code=2,hint){throw new Exit(message,code,hint)}function badUsage(message){throw new UsageError(message)}class Completing{options;positionals;candidates;constructor(options,positionals=[],candidates={}){this.options=options;this.positionals=positionals;this.candidates=candidates}}function applyOutput(color,plain,env=process8.env){let when=plain===!0?"never":color??"auto";if(when==="auto")return;if(when!=="always"&&when!=="never")badUsage(`--color takes auto, always or never, not ${when}`);if(when==="always")env.FORCE_COLOR="1",delete env.NO_COLOR;else env.NO_COLOR="1",delete env.FORCE_COLOR}function parse(args,usage,options,settings={}){let output=Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name])=>!(name in options))),all={...options,...output,help:{type:"boolean",short:"h",description:"show this help"}},listing=listed(all,settings.allowNegative===!0);if(completion.active)throw new Completing(listing,settings.positionals,settings.candidates);let{own,rest}=settings.trailing===!0?splitTrailing(args,all,settings.positionals?.length??0):splitRest(args,settings.rest===!0),helpJson=wantsHelpJson(process8.env,own),stripHelpJson=(arg)=>{if(arg==="--help=json")return["--help"];return arg==="--json"&&!("json"in options)?[]:[arg]},normalized=helpJson?own.flatMap(stripHelpJson):own,parsed;try{parsed=parseArgs({args:joinDashValues(withBare(withAliases(normalized,all),all),all),options:all,allowPositionals:!0,allowNegative:settings.allowNegative===!0,strict:!0})}catch(error){let message=parseError(error);throw new UsageError(message,nearestOption(message,all,settings.allowNegative===!0))}let values=parsed.values;if(applyOutput("color"in output?values.color:void 0,"plain"in output?values.plain:void 0),values.help===!0){let columns=takesControlCodes(process8.stdout)?process8.stdout.columns:void 0;throw console.log(helpJson?JSON.stringify(description(usage,settings,listing)):helpText(usage,listing,void 0,{...settings,bin:heading.bin,columns})),new HelpShown}if(checkChoices(parsed.values,all),checkConflicts(parsed.values,all),settings.positionals!==void 0)checkPositionals(parsed.positionals,settings.positionals);return{...parsed,values:parsed.values,positionals:parsed.positionals,rest}}function splitRest(args,passes){let separator=passes?args.indexOf("--"):-1;return{own:separator===-1?args:args.slice(0,separator),rest:separator===-1?void 0:args.slice(separator+1)}}function splitTrailing(args,options,count){let takesValue=(word)=>!word.includes("=")&&Object.entries(options).some(([name,{short,type}])=>type==="string"&&(word===`--${name}`||word===`-${short}`)),seen=0;if(count===0)return{own:args,rest:void 0};for(let at=0;at<args.length;at++){let word=args[at];if(word==="--")break;if(word.startsWith("-")){if(takesValue(word))at++;continue}if(seen++,seen===count)return{own:args.slice(0,at+1),rest:args.slice(at+1)}}return{own:args,rest:void 0}}function listed(options,allowNegative){if(!allowNegative)return options;return Object.fromEntries(Object.entries(options).flatMap(([name,option])=>{if(option.type!=="boolean"||option.negative===void 0)return[[name,option]];return[...option.description===void 0?[]:[[name,option]],[`no-${name}`,{type:"boolean",description:option.negative}]]}))}function withAliases(args,options){let named=new Map(Object.entries(options).flatMap(([name,{aliases=[]}])=>aliases.map((alias)=>[`--${alias}`,`--${name}`])));if(named.size===0)return args;let separator=args.indexOf("--");return[...(separator===-1?args:args.slice(0,separator)).map((arg)=>{let at=arg.indexOf("="),current=named.get(at===-1?arg:arg.slice(0,at));return current===void 0?arg:`${current}${at===-1?"":arg.slice(at)}`}),...separator===-1?[]:args.slice(separator)]}function withBare(args,options){let bare=new Map(Object.entries(options).flatMap(([name,{short,optional}])=>optional===void 0?[]:[[`--${name}`,optional],...short===void 0?[]:[[`-${short}`,optional]]]));if(bare.size===0)return args;let separator=args.indexOf("--"),own=separator===-1?args:args.slice(0,separator);return[...own.flatMap((arg,index)=>{let optional=bare.get(arg),next=own[index+1],value=next!==void 0&&(optional?.accepts===void 0?!next.startsWith("-"):optional.accepts.test(next));return optional===void 0||value?[arg]:[arg,optional.bare]}),...separator===-1?[]:args.slice(separator)]}function checkConflicts(values,options){let given=(name)=>values[name]!==void 0&&values[name]!==!1;for(let[name,{conflicts=[]}]of Object.entries(options)){let other=given(name)?conflicts.find(given):void 0;if(other!==void 0)badUsage(`--${name} cannot be used with --${other}`)}}function checkChoices(values,options){for(let[name,option]of Object.entries(options)){if(option.choices===void 0)continue;let given=values[name];for(let value of Array.isArray(given)?given:[given])if(typeof value==="string")oneOf(value,name,option.choices)}}function oneOf(value,name,choices){if(!choices.includes(value))badUsage(`${name.startsWith("<")?name:`--${name}`} takes one of ${choices.join(", ")}, not ${value}`);return value}function checkPositionals(given,names){let variadic=names.at(-1)?.replace("]","").endsWith("...")===!0,required=names.filter((name)=>!name.startsWith("[")).length;if(given.length<required)badUsage(`missing ${names[given.length]}`);if(!variadic&&given.length>names.length)badUsage(`unexpected argument ${given[names.length]}`)}function joinDashValues(args,options){let longOf=new Map(Object.entries(options).flatMap(([name,option])=>option.short===void 0?[[`--${name}`,name]]:[[`--${name}`,name],[`-${option.short}`,name]])),isOption=(arg)=>arg==="--"||longOf.has(arg.includes("=")?arg.slice(0,arg.indexOf("=")):arg),joined=[];for(let i=0;i<args.length;i++){let arg=args[i]??"";if(arg==="--")return[...joined,...args.slice(i)];let name=longOf.get(arg),next=args[i+1];if(name!==void 0&&options[name]?.type==="string"&&next!==void 0&&next.startsWith("-")&&next!=="-"&&!isOption(next))joined.push(`--${name}=${next}`),i++;else joined.push(arg)}return joined}function parseError(error){let message=upTo(error instanceof Error?error.message:String(error),". ");return`${message.charAt(0).toLowerCase()}${message.slice(1)}`}function nearestOption(message,options,allowNegative){let typed=UNKNOWN_OPTION.exec(message)?.[1];if(typed===void 0)return;let word=typed.replace(DASHES,"");if(word.length<2&&!typed.startsWith("--"))return;let known=Object.entries(options).flatMap(([name,option])=>[...option.short===void 0?[]:[`-${option.short}`],`--${name}`,...allowNegative&&option.type==="boolean"?[`--no-${name}`]:[]]),meant=closest(word,known.map((flag)=>flag.replace(DASHES,"")));return meant===void 0?void 0:`did you mean ${known.find((flag)=>flag.replace(DASHES,"")===meant)}?`}var DASHES,EXIT,Exit,UsageError,HelpShown,completion,heading,OUTPUT_OPTIONS,UNKNOWN_OPTION;var init_args=__esm(()=>{init_format();init_help();init_style();init_text2();init_help();init_input();DASHES=/^-+/;EXIT=Symbol.for("@kaynooo/cli-kit/Exit");Exit=class Exit extends Error{code;hint;[EXIT]=!0;constructor(message,code,hint){super(message);this.code=code;this.hint=hint}static[Symbol.hasInstance](value){if(this!==Exit)return Function.prototype[Symbol.hasInstance].call(this,value);return typeof value==="object"&&value!==null&&value[EXIT]===!0}};UsageError=class UsageError extends Exit{constructor(message,hint){super(message,2,hint)}};HelpShown=class HelpShown extends Exit{constructor(){super("help shown",0)}};completion={active:!1},heading={bin:void 0},OUTPUT_OPTIONS={color:{type:"string",choices:["auto","always","never"],description:"auto (the default) colours on a terminal alone"},plain:{type:"boolean",description:"plain text, no colour or spinner: --color never"}};UNKNOWN_OPTION=/^unknown option '(-[^']+)'/});var init_folders=__esm(()=>{init_user_config()});import{isIP as isIP3}from"net";import process15 from"process";init_args();import{readFileSync as readFileSync3,realpathSync}from"fs";import{resolve as resolve3}from"path";import process9 from"process";function commandLine(){try{return readFileSync3("/proc/self/cmdline","utf8").split("\x00").slice(0,-1)}catch{return}}function realPath(word){try{return realpathSync(resolve3(word))}catch{return}}function scriptArgs(argv=process9.argv.slice(2),cmdline=commandLine(),script=process9.argv[1]){let target=script===void 0?void 0:realPath(script)??script,at=cmdline===void 0||target===void 0?-1:cmdline.findIndex((word,index)=>index>0&&(resolve3(word)===script||realPath(word)===target)),after=at===-1?[]:cmdline.slice(at+1);return after[0]==="--"&&after.length===argv.length+1&&argv.every((word,index)=>word===after[index+1])?after:argv}init_format();init_mode();init_style();init_theme();init_args();init_format();init_format();init_style();init_text2();init_theme();init_style();init_format();init_args();import{readFileSync as readFileSync5,realpathSync as realpathSync2}from"fs";import{dirname as dirname4,join as join5}from"path";import process13 from"process";import process10 from"process";var SOCKET_VARIABLE="KAYNOOO_ASKPASS_SOCKET";async function askpassClient(argv){let socketPath=process10.env[SOCKET_VARIABLE];if(socketPath===void 0)return;let request={prompt:argv[0]??"",...process10.env.SSH_ASKPASS_PROMPT==="none"?{notice:!0}:{}},{promise,resolve}=Promise.withResolvers(),received="";try{await Bun.connect({unix:socketPath,socket:{open:(socket)=>void socket.write(`${JSON.stringify(request)}
11
13
  `),data:(_,chunk)=>{received+=chunk.toString()},close:()=>resolve(received),error:()=>resolve("")}})}catch{return 1}let reply=await promise;if(reply==="")return 1;let{answer}=JSON.parse(reply);if(request.notice===!0)return 0;if(answer===void 0)return 1;return process10.stdout.write(`${answer}
12
14
  `),0}init_args();var COMPLETION_SHELLS=["fish","bash","zsh"];function completionScript(shell,bins,header=`# Generated by \`${bins[0]} --completions ${shell}\``){if(shell==="fish")return`${header}
13
15
  functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
@@ -70,12 +72,12 @@ __kaynooo_cli_bins+=(${bins.join(" ")})
70
72
  `,temp=`${path}.${process12.pid}.tmp`;writeFileSync2(temp,kept,{mode:384}),renameSync(temp,path)}function recordUsage(entry,env=process12.env,maxBytes=MAX_USAGE_BYTES){if(!usageRecorded(env))return;try{let path=usagePath(env);mkdirSync2(dirname3(path),{recursive:!0,mode:448}),appendFileSync(path,`${JSON.stringify(entry)}
71
73
  `,{mode:384}),trimUsage(path,maxBytes)}catch{}}var LEVEL_OPTIONS={...OUTPUT_OPTIONS,help:{type:"boolean",short:"h",description:"show this help"}},TOP_OPTIONS={...LEVEL_OPTIONS,version:{type:"boolean",short:"v",description:"print the version"},completions:{type:"string",choices:COMPLETION_SHELLS,description:"print the shell completion script"}};async function commandRows(all,colors){let commands=shown(all),width=Math.max(0,...Object.keys(commands).map((name)=>name.length)),groups=new Map([["Commands:",[]]]),summaries=await Promise.all(Object.values(commands).map(async({summary})=>resolveSummary(summary)));for(let[index,[name,{group}]]of Object.entries(commands).entries()){let label=group===void 0?"Commands:":`${group}:`,rows=groups.get(label)??[];rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`),groups.set(label,rows)}return[...groups].filter(([,rows])=>rows.length>0).flatMap(([label,rows],index)=>[...index===0?[]:[""],colors.bold(label),...rows])}function takeOutputFlags(argv){let index=0;for(;index<argv.length;index++){let word=argv[index];if(word==="--plain")applyOutput(void 0,!0);else if(word.startsWith("--color="))applyOutput(word.slice(8),void 0);else if(word==="--color"&&argv[index+1]!==void 0)applyOutput(argv[++index],void 0);else break}return argv.slice(index)}async function help2({path,header,summary:lazySummary,commands,defaultCommand,examples,replaces},stream,json=!1){let colors=paint(stream),prefix=path.join(" "),summary=await resolveSummary(lazySummary);if(json||wantsHelpJson())return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`,{examples,replaces}));let columns=takesControlCodes(stream)?stream.columns:void 0,fallback=defaultCommand===void 0?void 0:commands[defaultCommand],options=fallback!==void 0&&"run"in fallback?await optionsOf(fallback.run):void 0,own=Object.entries(options??{}).filter(([name])=>!(name in TOP_OPTIONS));return[header(colors,summary),"",usageLine(`${prefix} ${defaultCommand===void 0?colors.cyan("<command>"):`[${colors.cyan("<command>")}]`} [options]`,colors),"",...await commandRows(commands,colors),...own.length===0?[]:["",`${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`,...optionRows(Object.fromEntries(own),colors,columns)],"",colors.bold("Options:"),...optionRows(path.length===1?TOP_OPTIONS:LEVEL_OPTIONS,colors,columns),...exampleRows(examples??[],colors),"",`${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`].join(`
72
74
  `)}function printError(prefix,message,hint,cause){let colors=paint(process13.stderr),styled=takesControlCodes(process13.stderr),head=styled?`${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}`:`error: ${prefix}:`,under=(label,text,tint)=>text===void 0?"":`
73
- ${styled?tint(label):`${label}:`} ${text}`;console.error(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause,extra){console.error(JSON.stringify({error:message,...extra?.code===void 0?{}:{code:extra.code},...extra?.command===void 0?{}:{command:extra.command},...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let code=error instanceof Exit?error.code:1,helpHint=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?(message,hint,causeText)=>printJsonError(message,hint,causeText,{code,command:prefix}):(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??helpHint:void 0,cause),code}async function dispatch(level,typed,{version,redact}){let prefix=level.path.join(" "),argv;try{argv=takeOutputFlags(typed)}catch(error){return{code:reportThrown(prefix,error,redact,wantsJson(typed)),meta:!1}}let[name,...args]=argv,fallback=level.defaultCommand===void 0?void 0:level.commands[level.defaultCommand];if(name===void 0&&level.runBare&&fallback!==void 0&&"run"in fallback)try{return{code:await fallback.run([]),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${level.defaultCommand}`,error,redact,!1),meta:error instanceof HelpShown}}if(name===void 0&&level.path.length>1)return console.error(await help2(await expand(level,[...level.path.slice(1),...argv]),process13.stderr)),{code:2,meta:!0};if(name==="help"&&args.length>0&&args[0]!=="--json")return dispatch(level,[...args,"--help"],{version,redact});if(name===void 0||name==="help"||name==="--help"||name==="-h"||name==="--help=json")return console.log(await help2(await expand(level,[...level.path.slice(1),...argv]),process13.stdout,wantsHelpJson(process13.env,argv))),{code:0,meta:!0};if(level.path.length===1&&(name==="--version"||name==="-v"))return console.log(version()),{code:0,meta:!0};let command=lookup(level,name),rest=args,ran=name;if(command===void 0&&level.lazy.length>0)level=await expand(level,[...level.path.slice(1),...argv]),command=lookup(level,name);if(command===void 0&&level.defaultCommand!==void 0)command=level.commands[level.defaultCommand],rest=argv,ran=level.defaultCommand;if(command===void 0){let meant=closest(name,Object.keys(shown(level.commands))),hint=meant===void 0?`run ${prefix} --help for its commands`:`did you mean ${meant}?`;if(wantsJson(argv))printJsonError(`no command ${name}`,hint,void 0,{code:2,command:prefix});else printError(prefix,`no command ${name}`,hint);return{code:2,meta:!1}}if("commands"in command){let{summary}=command;return dispatch({path:[...level.path,name],header:(colors,text)=>`${colors.bold(`${prefix} ${name}`)} ${text}`,summary,...scopeOf(command.commands,command.extraCommands,command.aliases),defaultCommand:command.defaultCommand,runBare:command.runBare===!0,examples:command.examples,replaces:void 0},rest,{version,redact})}try{return{code:await command.run(rest),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${ran}`,error,redact,wantsJson(rest)),meta:error instanceof HelpShown}}}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname4(resolved);;dir=dirname4(dir)){try{let{version}=JSON.parse(readFileSync5(join5(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname4(dir)===dir)return"0.0.0"}}async function runCli(cli,argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(candidates(scopeOf(cli.commands,cli.extraCommands,cli.aliases),cli.defaultCommand,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(cli.name,flagValue(argv),printError);let version=()=>cli.version??packageVersion(),started=performance.now(),{code,meta}=await dispatch({path:[cli.name],header:(colors,about)=>`${colors.bold(cli.name)} ${colors.dim(version())} ${about}`,summary:cli.about,...scopeOf(cli.commands,cli.extraCommands,cli.aliases),defaultCommand:cli.defaultCommand,runBare:cli.runBare===!0,examples:cli.examples,replaces:cli.replaces},argv,{version,redact:cli.redact}),command=commandPath(scopeOf(cli.commands,cli.extraCommands,cli.aliases),argv);if(notifyEnd(command===void 0?cli.name:`${cli.name} ${command}`,code,performance.now()-started),cli.usage!==!1&&!meta)try{recordUsage(usageEntry(cli.name,command,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}function commandPath(scope,argv){let path=[],level=scope;for(let word of argv.filter((each)=>!each.startsWith("-"))){let command=lookup(level,word);if(command===void 0)break;if(path.push(word),!("commands"in command))break;level=scopeOf(command.commands,command.extraCommands,command.aliases)}return path.length===0?void 0:path.join(" ")}init_args();var SHELLS=new Set(["sh","bash","zsh","dash","ash","ksh","fish","csh","tcsh","nu","xonsh","elvish","pwsh","powershell"]),SCANNED_PROGRAMS=new Set(["su","runuser","flock"]),COMMAND_STRING_PROGRAMS=new Set([...SHELLS,...SCANNED_PROGRAMS]);function wrapper(short="",long=[],operands=0,runsString=!1){return{short,long,operands,runsString}}var RUNNER={...wrapper(),afterDashes:!0},WRAPPERS=new Map([["command",wrapper()],["builtin",wrapper()],["nohup",wrapper()],["setsid",wrapper()],["busybox",wrapper()],["exec",wrapper("a")],["time",wrapper("fo",["--format","--output"])],["env",wrapper("uCS",["--unset","--chdir","--split-string","--argv0"])],["sudo",wrapper("ughpCTrtUDR",["--user","--group","--host","--prompt","--close-from","--command-timeout","--role","--type","--other-user","--chdir","--chroot"])],["doas",wrapper("uC")],["timeout",wrapper("sk",["--signal","--kill-after"],1)],["nice",wrapper("n",["--adjustment"])],["ionice",wrapper("cnpPu",["--class","--classdata","--pid","--pgid","--uid"])],["stdbuf",wrapper("ioe",["--input","--output","--error"])],["chroot",wrapper("",["--userspec","--groups"],1)],["watch",wrapper("n",["--interval"],0,!0)],["flock",wrapper("wE",["--timeout","--conflict-exit-code"],1)],["parallel",wrapper("jnNSaIPlLdTsC",["--jobs","--max-args","--max-replace-args","--sshlogin","--arg-file","--delimiter","--colsep"],0,!0)],["unbuffer",wrapper()],["systemd-run",wrapper("puEMH",["--property","--unit","--description","--slice","--setenv","--machine","--host","--uid","--gid","--working-directory","--nice","--service-type"])],["xargs",wrapper("IndsEaPL",["--max-args","--max-procs","--max-chars","--delimiter","--arg-file","--eof","--max-lines","--process-slot-var"])],["strace",wrapper("abeEIoOpPsSuUX",["--trace","--output","--attach","--string-limit","--user","--env","--columns","--trace-path","--signal","--status","--summary-sort-by","--summary-columns","--const-print-style","--interruptible","--detach-on"])],["ltrace",wrapper("aeFlnopsuxX",["--output","--user","--library","--config","--align","--indent"])],["taskset",wrapper("",[],1)],["fakeroot",wrapper("lsib",["--lib","--faked"])],["sshpass",wrapper("pfdP")],["coproc",wrapper()],["proxychains",wrapper("f")],["proxychains4",wrapper("f")],["torsocks",wrapper("upaP",["--user","--pass","--address","--port"])],["chrt",wrapper("TPD",["--sched-runtime","--sched-period","--sched-deadline"],1)],["unshare",wrapper("SGRw",["--setuid","--setgid","--root","--wd","--map-user","--map-group","--map-users","--map-groups","--propagation","--setgroups"])],["nsenter",wrapper("tSG",["--target","--setuid","--setgid"])],["out",RUNNER],["slot",RUNNER],["waitfor",RUNNER],["base",RUNNER]]);init_style();init_config();init_text2();init_folders();init_format();init_args();init_args();init_mode();init_style();init_text2();var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");init_style();init_text2();init_theme();init_user_config();init_args();init_input();init_style();init_user_config();import{basename,dirname as dirname5,join as join6,relative,sep}from"path";var PARENT=`..${sep}`;var MAX_HOPS=10,SCHEME=/^[a-z][a-z0-9+.-]*:\/\//i;var CERT_PREFIX=/^(?:DNS|IP Address|IP|email|URI):/,CACHE_NODE=/^cache-/i,ALT_VALUE=/=.*$/;function parseTarget(input){let bare=!SCHEME.test(input);try{let url=new URL(bare?`https://${input}`:input);return url.protocol!=="http:"&&url.protocol!=="https:"||url.hostname===""?void 0:{url,bare}}catch{return}}var WRITE_OUT=`%{json}
75
+ ${styled?tint(label):`${label}:`} ${text}`;writeErr(`${head} ${message}${under("cause",cause,colors.dim)}${under("hint",hint,colors.yellow)}`)}function printJsonError(message,hint,cause,extra){writeErr(JSON.stringify({error:message,...extra?.code===void 0?{}:{code:extra.code},...extra?.command===void 0?{}:{command:extra.command},...hint===void 0?{}:{hint},...cause===void 0?{}:{cause}}))}function wantsJson(argv){let end=argv.indexOf("--");return(end===-1?argv:argv.slice(0,end)).includes("--json")}function reportThrown(prefix,error,redact=(text)=>text,json=!1){if(error instanceof HelpShown)return 0;let code=error instanceof Exit?error.code:1,helpHint=error instanceof UsageError?`run ${prefix} --help for its options`:void 0,named=error instanceof Error&&!(error instanceof Exit)&&error.name!=="Error"?`${error.name}: ${error.message}`:void 0,cause=error instanceof Error&&error.cause instanceof Error?redact(error.cause.message):void 0;if(error instanceof Exit&&error.code===2)noteUsageError(error.message);return(json?(message,hint,causeText)=>printJsonError(message,hint,causeText,{code,command:prefix}):(message,hint,causeText)=>printError(prefix,message,hint,causeText))(redact(named??(error instanceof Error?error.message:String(error))),error instanceof Exit?error.hint??helpHint:void 0,cause),code}async function dispatch(level,typed,{version,redact}){let prefix=level.path.join(" "),argv;try{argv=takeOutputFlags(typed)}catch(error){return{code:reportThrown(prefix,error,redact,wantsJson(typed)),meta:!1}}let[name,...args]=argv,fallback=level.defaultCommand===void 0?void 0:level.commands[level.defaultCommand];if(name===void 0&&level.runBare&&fallback!==void 0&&"run"in fallback)try{return{code:await fallback.run([]),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${level.defaultCommand}`,error,redact,!1),meta:error instanceof HelpShown}}if(name===void 0&&level.path.length>1)return writeErr(await help2(await expand(level,[...level.path.slice(1),...argv]),process13.stderr)),{code:2,meta:!0};if(name==="help"&&args.length>0&&args[0]!=="--json")return dispatch(level,[...args,"--help"],{version,redact});if(name===void 0||name==="help"||name==="--help"||name==="-h"||name==="--help=json")return console.log(await help2(await expand(level,[...level.path.slice(1),...argv]),process13.stdout,wantsHelpJson(process13.env,argv))),{code:0,meta:!0};if(level.path.length===1&&(name==="--version"||name==="-v"))return console.log(version()),{code:0,meta:!0};let command=lookup(level,name),rest=args,ran=name;if(command===void 0&&level.lazy.length>0)level=await expand(level,[...level.path.slice(1),...argv]),command=lookup(level,name);if(command===void 0&&level.defaultCommand!==void 0)command=level.commands[level.defaultCommand],rest=argv,ran=level.defaultCommand;if(command===void 0){let meant=closest(name,Object.keys(shown(level.commands))),hint=meant===void 0?`run ${prefix} --help for its commands`:`did you mean ${meant}?`;if(wantsJson(argv))printJsonError(`no command ${name}`,hint,void 0,{code:2,command:prefix});else printError(prefix,`no command ${name}`,hint);return{code:2,meta:!1}}if("commands"in command){let{summary}=command;return dispatch({path:[...level.path,name],header:(colors,text)=>`${colors.bold(`${prefix} ${name}`)} ${text}`,summary,...scopeOf(command.commands,command.extraCommands,command.aliases),defaultCommand:command.defaultCommand,runBare:command.runBare===!0,examples:command.examples,replaces:void 0},rest,{version,redact})}try{return{code:await command.run(rest),meta:!1}}catch(error){return{code:reportThrown(`${prefix} ${ran}`,error,redact,wantsJson(rest)),meta:error instanceof HelpShown}}}function packageVersion(entry=Bun.main){let resolved=entry;try{resolved=realpathSync2(entry)}catch{}for(let dir=dirname4(resolved);;dir=dirname4(dir)){try{let{version}=JSON.parse(readFileSync5(join5(dir,"package.json"),"utf8"));if(typeof version==="string")return version}catch{}if(dirname4(dir)===dir)return"0.0.0"}}async function runCli(cli,argv=scriptArgs()){let answered=await askpassClient(argv);if(answered!==void 0)return answered;if(argv[0]===COMPLETE)return printCandidates(candidates(scopeOf(cli.commands,cli.extraCommands,cli.aliases),cli.defaultCommand,argv.slice(1)));if(argv[0]===COMPLETIONS||argv[0]?.startsWith(`${COMPLETIONS}=`)===!0)return printCompletionScript(cli.name,flagValue(argv),printError);let version=()=>cli.version??packageVersion(),started=performance.now(),{code,meta}=await dispatch({path:[cli.name],header:(colors,about)=>`${colors.bold(cli.name)} ${colors.dim(version())} ${about}`,summary:cli.about,...scopeOf(cli.commands,cli.extraCommands,cli.aliases),defaultCommand:cli.defaultCommand,runBare:cli.runBare===!0,examples:cli.examples,replaces:cli.replaces},argv,{version,redact:cli.redact}),command=commandPath(scopeOf(cli.commands,cli.extraCommands,cli.aliases),argv);if(notifyEnd(command===void 0?cli.name:`${cli.name} ${command}`,code,performance.now()-started),cli.usage!==!1&&!meta)try{recordUsage(usageEntry(cli.name,command,argv,code,{ms:performance.now()-started,mode:outputMode()}))}catch{}return code}function commandPath(scope,argv){let path=[],level=scope;for(let word of argv.filter((each)=>!each.startsWith("-"))){let command=lookup(level,word);if(command===void 0)break;if(path.push(word),!("commands"in command))break;level=scopeOf(command.commands,command.extraCommands,command.aliases)}return path.length===0?void 0:path.join(" ")}init_args();var SHELLS=new Set(["sh","bash","zsh","dash","ash","ksh","fish","csh","tcsh","nu","xonsh","elvish","pwsh","powershell"]),SCANNED_PROGRAMS=new Set(["su","runuser","flock"]),COMMAND_STRING_PROGRAMS=new Set([...SHELLS,...SCANNED_PROGRAMS]);function wrapper(short="",long=[],operands=0,runsString=!1){return{short,long,operands,runsString}}var RUNNER={...wrapper(),afterDashes:!0},WRAPPERS=new Map([["command",wrapper()],["builtin",wrapper()],["nohup",wrapper()],["setsid",wrapper()],["busybox",wrapper()],["exec",wrapper("a")],["time",wrapper("fo",["--format","--output"])],["env",wrapper("uCS",["--unset","--chdir","--split-string","--argv0"])],["sudo",wrapper("ughpCTrtUDR",["--user","--group","--host","--prompt","--close-from","--command-timeout","--role","--type","--other-user","--chdir","--chroot"])],["doas",wrapper("uC")],["timeout",wrapper("sk",["--signal","--kill-after"],1)],["nice",wrapper("n",["--adjustment"])],["ionice",wrapper("cnpPu",["--class","--classdata","--pid","--pgid","--uid"])],["stdbuf",wrapper("ioe",["--input","--output","--error"])],["chroot",wrapper("",["--userspec","--groups"],1)],["watch",wrapper("n",["--interval"],0,!0)],["flock",wrapper("wE",["--timeout","--conflict-exit-code"],1)],["parallel",wrapper("jnNSaIPlLdTsC",["--jobs","--max-args","--max-replace-args","--sshlogin","--arg-file","--delimiter","--colsep"],0,!0)],["unbuffer",wrapper()],["systemd-run",wrapper("puEMH",["--property","--unit","--description","--slice","--setenv","--machine","--host","--uid","--gid","--working-directory","--nice","--service-type"])],["xargs",wrapper("IndsEaPL",["--max-args","--max-procs","--max-chars","--delimiter","--arg-file","--eof","--max-lines","--process-slot-var"])],["strace",wrapper("abeEIoOpPsSuUX",["--trace","--output","--attach","--string-limit","--user","--env","--columns","--trace-path","--signal","--status","--summary-sort-by","--summary-columns","--const-print-style","--interruptible","--detach-on"])],["ltrace",wrapper("aeFlnopsuxX",["--output","--user","--library","--config","--align","--indent"])],["taskset",wrapper("",[],1)],["fakeroot",wrapper("lsib",["--lib","--faked"])],["sshpass",wrapper("pfdP")],["coproc",wrapper()],["proxychains",wrapper("f")],["proxychains4",wrapper("f")],["torsocks",wrapper("upaP",["--user","--pass","--address","--port"])],["chrt",wrapper("TPD",["--sched-runtime","--sched-period","--sched-deadline"],1)],["unshare",wrapper("SGRw",["--setuid","--setgid","--root","--wd","--map-user","--map-group","--map-users","--map-groups","--propagation","--setgroups"])],["nsenter",wrapper("tSG",["--target","--setuid","--setgid"])],["out",RUNNER],["slot",RUNNER],["waitfor",RUNNER],["base",RUNNER]]);init_style();init_config();init_text2();init_folders();init_format();init_args();init_args();init_mode();init_style();init_text2();var{Glob}=globalThis.Bun;var SESSION_FILES=new Glob("*.json"),ACCOUNT_DIRS=new Glob("*/sessions");init_style();init_text2();init_theme();init_user_config();init_args();init_input();init_style();init_user_config();import{basename,dirname as dirname5,join as join6,relative,sep}from"path";var PARENT=`..${sep}`;var MAX_HOPS=10,SCHEME=/^[a-z][a-z0-9+.-]*:\/\//i;var CERT_PREFIX=/^(?:DNS|IP Address|IP|email|URI):/,CACHE_NODE=/^cache-/i,ALT_VALUE=/=.*$/;function parseTarget(input){let bare=!SCHEME.test(input);try{let url=new URL(bare?`https://${input}`:input);return url.protocol!=="http:"&&url.protocol!=="https:"||url.hostname===""?void 0:{url,bare}}catch{return}}var WRITE_OUT=`%{json}
74
76
  ---HEADERS---
75
- %{header_json}`;function seconds(value){return typeof value==="number"?value:0}function ms(value){return Math.round(value*1000)}function timingsOf(info){let lookup=seconds(info.time_namelookup),connect=seconds(info.time_connect),secure=seconds(info.time_appconnect),ready=secure>0?secure:connect,first=seconds(info.time_starttransfer);return{dns:ms(lookup),connect:ms(Math.max(0,connect-lookup)),tls:secure>0?ms(Math.max(0,secure-connect)):0,firstByte:ms(Math.max(0,first-ready)),total:ms(seconds(info.time_total))}}function headersOf(json){let headers={};try{let parsed=JSON.parse(json);if(typeof parsed!=="object"||parsed===null)return headers;for(let[name,value]of Object.entries(parsed)){let values=Array.isArray(value)?value.map(String):[String(value)];headers[name.toLowerCase()]=values.join(", ")}}catch{}return headers}function parseCurl(stdout){let at=stdout.indexOf(`
77
+ %{header_json}`;function seconds(value){return typeof value==="number"?value:0}function ms(value){return Math.round(value*1000)}function timingsOf(info){let lookup=seconds(info.time_namelookup),connect=seconds(info.time_connect),secure=seconds(info.time_appconnect),ready=secure>0?secure:connect,first=seconds(info.time_starttransfer);return{dns:ms(lookup),connect:ms(Math.max(0,connect-lookup)),tls:secure>0?ms(Math.max(0,secure-connect)):0,firstByte:ms(Math.max(0,first-ready)),total:ms(seconds(info.time_total))}}function parseHeaderJson(json){let headers={},setCookies=[];try{let parsed=JSON.parse(json);if(typeof parsed!=="object"||parsed===null)return{headers,setCookies};for(let[name,value]of Object.entries(parsed)){let values=Array.isArray(value)?value.map(String):[String(value)],lower=name.toLowerCase();if(headers[lower]=values.join(", "),lower==="set-cookie")setCookies.push(...values)}}catch{}return{headers,setCookies}}function parseCurl(stdout){let at=stdout.indexOf(`
76
78
  ---HEADERS---
77
- `),infoText=at===-1?stdout:stdout.slice(0,at),info;try{info=JSON.parse(infoText)}catch{return{exitcode:1,errormsg:"curl printed no result"}}let exitcode=typeof info.exitcode==="number"?info.exitcode:1,errormsg=typeof info.errormsg==="string"?info.errormsg:null,status=typeof info.response_code==="number"?info.response_code:0;if(exitcode!==0||status===0)return{exitcode:exitcode===0?1:exitcode,errormsg:errormsg??"no response"};let headers=headersOf(at===-1?"":stdout.slice(at+15)),hop={url:String(info.url_effective??info.url??""),status,version:String(info.http_version??""),timings:timingsOf(info),headers};if(typeof info.redirect_url==="string"&&info.redirect_url!=="")hop.location=info.redirect_url;else if(headers.location!==void 0)hop.location=headers.location;if(typeof info.remote_ip==="string"&&info.remote_ip!=="")hop.remoteIp=info.remote_ip;return{exitcode,errormsg,hop}}function isRedirect(status){return status===301||status===302||status===303||status===307||status===308}function nextUrl(current,location){try{let next=new URL(location,current);return next.protocol==="http:"||next.protocol==="https:"?next.href:void 0}catch{return}}function versionLabel(version){return version===""?"unknown":`HTTP/${version}`}function altSvcProtocols(altSvc){if(altSvc===void 0||altSvc.trim()==="clear")return[];let ids=altSvc.split(",").map((entry)=>entry.trim().replace(ALT_VALUE,"")).filter((id)=>id!=="");return[...new Set(ids)]}function offersOf(options){let altSvc=altSvcProtocols(options.altSvc);return{h2:options.alpn==="h2"||options.version==="2"||options.version==="3",h3:options.version==="3"||altSvc.some((id)=>id==="h3"||id.startsWith("h3-")),altSvc}}var KNOWN_SERVERS=[[/cloudflare/i,"Cloudflare"],[/cloudfront/i,"CloudFront"],[/akamai/i,"Akamai"],[/fastly/i,"Fastly"],[/vercel/i,"Vercel"],[/netlify/i,"Netlify"],[/bunnycdn/i,"BunnyCDN"],[/^(?:gws|esf|gse)$|google frontend/i,"Google"]];function cdnHint(headers){let served=headers["x-served-by"];if(headers["cf-ray"]!==void 0)return"Cloudflare (cf-ray)";if(served!==void 0)return`${CACHE_NODE.test(served)?"Fastly":served} (x-served-by)`;if(headers["x-amz-cf-id"]!==void 0)return"CloudFront (x-amz-cf-id)";if(headers["x-vercel-id"]!==void 0)return"Vercel (x-vercel-id)";if(headers.via!==void 0)return`${headers.via} (via)`;if(headers["x-cache"]!==void 0)return`${headers["x-cache"]} (x-cache)`;let server=headers.server;if(server!==void 0){let known=KNOWN_SERVERS.find(([pattern])=>pattern.test(server));if(known!==void 0)return`${known[1]} (server)`}return}var WORTH_KNOWING=["server","content-type","content-encoding","cache-control","strict-transport-security"],SECURITY_HEADERS=["strict-transport-security","content-security-policy","x-content-type-options","x-frame-options","referrer-policy","permissions-policy"];function securityAudit(headers,secure){let present={},missing=[],hasFrameAncestors=(headers["content-security-policy"]??"").toLowerCase().includes("frame-ancestors");for(let name of SECURITY_HEADERS){if(name==="strict-transport-security"&&!secure)continue;let value=headers[name];if(value!==void 0&&value!=="")present[name]=value;else if(name==="x-frame-options"&&hasFrameAncestors)continue;else missing.push(name)}return{present,missing}}function worthKnowing(headers){let kept={};for(let name of WORTH_KNOWING){let value=headers[name];if(value!==void 0)kept[name]=value}return kept}function field(value){if(typeof value==="string")return value;return Array.isArray(value)?value.join(", "):""}function nameOf(entry){if(entry===void 0)return"";let common=field(entry.CN),organization=field(entry.O);if(common!==""&&organization!==""&&common!==organization)return`${common} (${organization})`;return common===""?organization:common}function namesOf(subjectaltname){if(subjectaltname===void 0)return[];return subjectaltname.split(",").map((entry)=>entry.trim().replace(CERT_PREFIX,"")).filter((name)=>name!=="")}function daysLeftLabel(days){return`${days} ${days===1?"day":"days"} left`}function certInfo(raw,now=Date.now()){if(raw.valid_to===void 0||raw.valid_from===void 0)return;let end=Date.parse(raw.valid_to),start=Date.parse(raw.valid_from);if(Number.isNaN(end)||Number.isNaN(start))return;return{subject:nameOf(raw.subject),issuer:nameOf(raw.issuer),names:namesOf(raw.subjectaltname),validFrom:new Date(start).toISOString(),validTo:new Date(end).toISOString(),daysLeft:Math.floor((end-now)/86400000)}}function httpRedirectOf(hop){if(hop===void 0)return;let next=hop.location===void 0?void 0:nextUrl(hop.url,hop.location),redirect={status:hop.status,toHttps:isRedirect(hop.status)&&next!==void 0&&new URL(next).protocol==="https:"};if(hop.location!==void 0)redirect.location=hop.location;return redirect}function wantsHttpCheck(target){return target.url.protocol==="https:"&&target.url.port===""}function warningsOf(input){let warnings=[],{cert,httpRedirect}=input;if(cert!==void 0){if(cert.daysLeft===-1)warnings.push("certificate expired within the last day");else if(cert.daysLeft<0)warnings.push(`certificate expired ${-cert.daysLeft} days ago`);else if(cert.daysLeft<14)warnings.push(`certificate expires in ${cert.daysLeft} ${cert.daysLeft===1?"day":"days"}`)}if(input.authorizationError!==void 0)warnings.push(`certificate not trusted: ${input.authorizationError}`);if(httpRedirect!==void 0&&!httpRedirect.toHttps)warnings.push(`http:// answers ${httpRedirect.status} and does not redirect to https`);if(input.tooManyRedirects)warnings.push("more than 10 redirects");return warnings}var SIMPLE_METHODS=new Set(["GET","HEAD","POST"]),NORMALIZED_METHODS=new Set(["DELETE","GET","HEAD","OPTIONS","POST","PUT"]),SAFELISTED_HEADERS=new Set(["accept","accept-language","content-language"]),LIST=/\s*,\s*/,HOSTED_SCHEME=/^[a-z][a-z0-9+.-]*:\/\/[^/]/i;function listOf(value){return value===void 0?[]:value.trim().split(LIST).filter((item)=>item!=="")}function methodOf(input){return NORMALIZED_METHODS.has(input.toUpperCase())?input.toUpperCase():input}function requestedHeaders(value){return listOf(value).map((name)=>name.toLowerCase()).filter((name)=>!SAFELISTED_HEADERS.has(name))}function originOf(input){if(input==="null")return input;if(!HOSTED_SCHEME.test(input)||!URL.canParse(input))return;let url=new URL(input);return url.origin==="null"?`${url.protocol}//${url.host}`:url.origin}function corsVerdict(status,headers,request){let reasons=[],warnings=[],origin=headers["access-control-allow-origin"],credentials=headers["access-control-allow-credentials"]==="true",methods=listOf(headers["access-control-allow-methods"]),allowedHeaders=new Set(listOf(headers["access-control-allow-headers"]).map((name)=>name.toLowerCase()));if(status<200||status>299)reasons.push(`the preflight answered ${status}, a browser wants a 2xx`);if(origin===void 0)reasons.push("no access-control-allow-origin");else if(origin!=="*"&&origin!==request.origin)reasons.push(`access-control-allow-origin is ${origin}, not ${request.origin}`);let{method}=request;if(!SIMPLE_METHODS.has(method)&&!methods.includes("*")&&!methods.includes(method))reasons.push(methods.length===0?`no access-control-allow-methods, which ${method} needs`:`access-control-allow-methods (${methods.join(", ")}) does not list ${method}`);let missing=request.headers.map((name)=>name.toLowerCase()).filter((name)=>!allowedHeaders.has(name)&&(name==="authorization"||!allowedHeaders.has("*")));if(missing.length>0)reasons.push(`access-control-allow-headers does not cover ${missing.join(", ")}`);if(credentials&&(origin==="*"||methods.includes("*")||allowedHeaders.has("*")))warnings.push("access-control-allow-credentials comes with a * wildcard, which a request with cookies or auth does not get");if(origin===request.origin&&!listOf(headers.vary).some((name)=>name.toLowerCase()==="origin"||name==="*"))warnings.push("if the origin is echoed back from the request, vary lacks origin: a cache may hand this answer to another origin");let shown=Object.fromEntries(Object.entries(headers).filter(([name])=>name.startsWith("access-control-")||name==="vary"));return{allowed:reasons.length===0,reasons,warnings,headers:shown}}import{Resolver}from"dns/promises";var TIMEOUT_MS=3000,PUBLIC_RESOLVERS=[{name:"cloudflare",address:"1.1.1.1"},{name:"google",address:"8.8.8.8"},{name:"quad9",address:"9.9.9.9"}];function resolverFor(server,timeoutMs){let resolver=new Resolver({timeout:timeoutMs,tries:1});if(server.address!==void 0)resolver.setServers([server.address]);return resolver}function failureOf(error){let code=error.code;return code==="ETIMEOUT"||code==="ECONNREFUSED"?"no answer":String(error.message??error)}async function settled(query){try{return await query}catch(error){let code=error.code;if(code==="ENOTFOUND"||code==="ENODATA")return[];throw error}}function network(timeoutMs=TIMEOUT_MS,upstream=PUBLIC_RESOLVERS[0]){return{servers:(server)=>server.address??resolverFor(server,timeoutMs).getServers().join(", "),async records(server,host){let resolver=resolverFor(server,timeoutMs);try{let[a,aaaa,cname]=await Promise.all([settled(resolver.resolve4(host,{ttl:!0})),settled(resolver.resolve6(host,{ttl:!0})),settled(resolver.resolveCname(host))]),ttls=[...a,...aaaa].map((record)=>record.ttl);return{a:a.map((record)=>record.address).sort(),aaaa:aaaa.map((record)=>record.address).sort(),cname:cname.map((target)=>target.toLowerCase()),ttl:ttls.length===0?null:Math.min(...ttls)}}catch(error){return{a:[],aaaa:[],cname:[],ttl:null,error:failureOf(error)}}},async nameservers(zone){let resolver=resolverFor(upstream,timeoutMs),[nameservers,alias]=await Promise.all([settled(resolver.resolveNs(zone)),settled(resolver.resolveCname(zone))]);return alias.length>0?[]:nameservers},async addressOf(host){return(await settled(resolverFor(upstream,timeoutMs).resolve4(host)))[0]}}}var NO_ZONE="no zone with nameservers was found for this name",ZONE_LOOKUP_FAILED="the zone of this name could not be looked up, so no nameserver was asked";async function zoneOf(host,client){let labels=host.split(".");for(let at=0;at<labels.length-1;at++){let zone=labels.slice(at).join("."),nameservers=await failingToNothing(client.nameservers(zone));if(nameservers===void 0)return{problem:ZONE_LOOKUP_FAILED};if(nameservers.length>0)return{zone,nameservers:nameservers.sort()}}return{problem:NO_ZONE}}async function failingToNothing(query){try{return await query}catch{return}}function sameFamily(mine,theirs){if(mine.length===0||theirs.length===0)return mine.length===theirs.length;let other=new Set(theirs);return mine.some((address)=>other.has(address))}function sameAnswer(one,other){if(one.error!==void 0||other.error!==void 0)return one.error===other.error;if(one.cname.length>0||other.cname.length>0)return one.cname.join().toLowerCase()===other.cname.join().toLowerCase();return sameFamily(one.a,other.a)&&sameFamily(one.aaaa,other.aaaa)}var TRAILING_DOT=/\.$/;async function dnsReport(target,host,client=network()){let name=host.replace(TRAILING_DOT,"").toLowerCase(),found=await zoneOf(name,client),authoritative=await Promise.all(("nameservers"in found?found.nameservers:[]).map(async(nameserver)=>{let address=await failingToNothing(client.addressOf(nameserver));return address===void 0?void 0:{name:nameserver,address}})),asked=[...[{name:"system"},...PUBLIC_RESOLVERS].map((server)=>({server,authoritative:!1})),...authoritative.filter((server)=>server!==void 0).map((server)=>({server,authoritative:!0}))],answers=await Promise.all(asked.map(async({server,authoritative})=>({resolver:server.name,server:client.servers(server),authoritative,...await client.records(server,name)})));return{target,zone:"zone"in found?found.zone:null,answers,...verdictOf(answers,"problem"in found?found.problem:void 0)}}function verdictOf(answers,zoneProblem){let warnings=zoneProblem===void 0?[]:[zoneProblem],answered=answers.filter((answer)=>answer.error!=="no answer"),reference=answered.filter((answer)=>answer.authoritative),truth=reference[0]??answered[0],agree=truth===void 0||answered.every((answer)=>sameAnswer(answer,truth));if(reference.some((answer)=>!sameAnswer(answer,reference[0])))warnings.push("the zone's own nameservers disagree: one of them has not taken the last change yet");for(let answer of answers)if(answer.error==="no answer")warnings.push(`${answer.resolver} did not answer`);if(agree)return{agree,warnings};if(reference.length===0)return warnings.push(`the resolvers disagree, with no nameserver of the zone to tell which is right: ${answered.filter((answer)=>!sameAnswer(answer,truth)).map((answer)=>answer.resolver).join(", ")} differ from ${truth.resolver}`),{agree,warnings};let stale=answered.filter((answer)=>!answer.authoritative&&!reference.some((ns)=>sameAnswer(answer,ns)));for(let answer of stale){let until=answer.ttl===null||answer.cname.length>0?"":`, cached for up to ${answer.ttl}s more`;warnings.push(answer.resolver==="system"?`the system resolver answers differently from the zone's nameservers${until}: \`sudo resolvectl flush-caches\` drops its copy`:`${answer.resolver} answers differently from the zone's nameservers${until}: the change has not reached it yet`)}return{agree,warnings}}function known(report){return report.answers.some((answer)=>answer.error===void 0&&answer.a.length+answer.aaaa.length+answer.cname.length>0)}var RECORD_TYPES=["A","AAAA","CNAME","MX","TXT","CAA","NS","SOA"];async function queryRecordTypes(host,types,timeoutMs=TIMEOUT_MS){let name=host.replace(TRAILING_DOT,"").toLowerCase(),resolver=new Resolver({timeout:timeoutMs,tries:1});return Promise.all(types.map(async(type)=>{try{switch(type){case"A":return{type,values:(await settled(resolver.resolve4(name))).sort()};case"AAAA":return{type,values:(await settled(resolver.resolve6(name))).sort()};case"CNAME":return{type,values:(await settled(resolver.resolveCname(name))).map((v)=>v.toLowerCase())};case"MX":return{type,values:(await settled(resolver.resolveMx(name))).sort((a,b)=>a.priority-b.priority||a.exchange.localeCompare(b.exchange)).map((r)=>`${r.priority} ${r.exchange}`)};case"TXT":return{type,values:(await settled(resolver.resolveTxt(name))).map((parts)=>parts.join(""))};case"CAA":return{type,values:(await settled(resolver.resolveCaa(name))).map((r)=>{if(r.issue!==void 0)return`${r.critical} issue "${r.issue}"`;if(r.issuewild!==void 0)return`${r.critical} issuewild "${r.issuewild}"`;return`${r.critical} iodef "${r.iodef??""}"`})};case"NS":return{type,values:(await settled(resolver.resolveNs(name))).sort()};case"SOA":try{let soa=await resolver.resolveSoa(name);return{type,values:[`${soa.nsname} ${soa.hostmaster} serial=${soa.serial} refresh=${soa.refresh} retry=${soa.retry} expire=${soa.expire} minttl=${soa.minttl}`]}}catch(error){let code=error.code;if(code==="ENOTFOUND"||code==="ENODATA")return{type,values:[]};throw error}}}catch(error){return{type,values:[],error:failureOf(error)}}}))}async function publicIp(family,service="https://ipecho.net/plain"){let child=Bun.spawn(["curl","--silent","--show-error","--fail","--max-time","10",...family===void 0?[]:[`-${family}`],service],{stdout:"pipe",stderr:"pipe"}),[out,err,code]=await Promise.all([child.stdout.text(),child.stderr.text(),child.exited]);if(code!==0)throw Error(err.trim()===""?`curl exited ${code}`:err.trim());return out.trim()}import{lookup as lookup2}from"dns/promises";import{isIP}from"net";import{connect}from"tls";var CONNECT_TIMEOUT=10,MAX_TIME=20,HTTP3_FEATURE=/^Features:.*\bHTTP3\b/m,BRACKETS=/^\[|\]$/g,http3;async function curlHasHttp3(){if(http3!==void 0)return http3;try{let result=Bun.spawn(["curl","--version"],{stdout:"pipe",stderr:"ignore"}),text=await new Response(result.stdout).text();http3=HTTP3_FEATURE.test(text)}catch{http3=!1}return http3}function portOf(url){if(url.port!=="")return Number(url.port);return url.protocol==="https:"?443:80}function curlResolve(url,resolve){let parsed=URL.canParse(url)?new URL(url):void 0,address=parsed===void 0?void 0:resolve?.get(parsed.hostname);if(parsed===void 0||address===void 0)return[];return["--resolve",`${parsed.hostname}:${portOf(parsed)}:${isIP(address)===6?`[${address}]`:address}`]}async function runCurl(url,{http3:wantsH3,insecure,get,method,headers=[],resolve,timeoutS=MAX_TIME}){let args=["-sS","-o","/dev/null","--connect-timeout",String(Math.min(CONNECT_TIMEOUT,timeoutS)),"--max-time",String(timeoutS),"--write-out",WRITE_OUT,...curlResolve(url,resolve)];for(let header of headers)args.push("-H",header);if(method!==void 0)args.push("-X",method);else if(!get)args.push("-I");if(wantsH3)args.push("--http3");if(insecure)args.push("--insecure");try{let result=Bun.spawn(["curl",...args,url],{stdout:"pipe",stderr:"pipe"}),[stdout]=await Promise.all([new Response(result.stdout).text(),new Response(result.stderr).text(),result.exited]);return parseCurl(stdout)}catch{return{exitcode:127,errormsg:"curl is not installed"}}}async function curlHop(url,options){let result=await runCurl(url,options);if(result.hop===void 0&&options.http3)result=await runCurl(url,{...options,http3:!1});if(result.hop!==void 0&&!options.get&&options.method===void 0&&result.hop.status>=400)result=await runCurl(url,{...options,get:!0});return result}async function curlPreflight(url,request,options){let asked=[`Origin: ${request.origin}`,`Access-Control-Request-Method: ${request.method}`,...request.headers.length>0?[`Access-Control-Request-Headers: ${request.headers.join(", ")}`]:[]];return runCurl(url,{...options,headers:[...options.headers??[],...asked],http3:!1,get:!0,method:"OPTIONS"})}async function addressesOf(host,resolve){let bare=resolve?.get(host)??host.replace(BRACKETS,""),family=isIP(bare);if(family!==0)return family===4?{a:[bare],aaaa:[]}:{a:[],aaaa:[bare]};try{let found=await lookup2(bare,{all:!0});return{a:found.filter((entry)=>entry.family===4).map((entry)=>entry.address),aaaa:found.filter((entry)=>entry.family===6).map((entry)=>entry.address)}}catch{return{a:[],aaaa:[]}}}async function tlsInfo(host,port,{address,timeoutS=CONNECT_TIMEOUT}={}){let bare=host.replace(BRACKETS,"");return new Promise((resolve)=>{let socket=connect({host:address??bare,port,servername:isIP(bare)===0?bare:"",ALPNProtocols:["h2","http/1.1"],rejectUnauthorized:!1,timeout:Math.min(CONNECT_TIMEOUT,timeoutS)*1000});socket.on("secureConnect",()=>{let error=socket.authorizationError;resolve({protocol:socket.getProtocol()??"",cipher:socket.getCipher().name,alpn:typeof socket.alpnProtocol==="string"?socket.alpnProtocol:void 0,authorizationError:error===null||error===void 0||error===!1?void 0:String(error),cert:certInfo(socket.getPeerCertificate())}),socket.end()}),socket.on("error",()=>resolve(void 0)),socket.on("timeout",()=>{socket.destroy(),resolve(void 0)})})}var LABEL_WIDTH=13,HTTP_USAGE=`probe [http] [options] <url|domain>...: reports each site's HTTP version, redirect chain, timings, addresses, TLS, certificate, headers, security headers and warnings
79
+ `),infoText=at===-1?stdout:stdout.slice(0,at),info;try{info=JSON.parse(infoText)}catch{return{exitcode:1,errormsg:"curl printed no result"}}let exitcode=typeof info.exitcode==="number"?info.exitcode:1,errormsg=typeof info.errormsg==="string"?info.errormsg:null,status=typeof info.response_code==="number"?info.response_code:0;if(exitcode!==0||status===0)return{exitcode:exitcode===0?1:exitcode,errormsg:errormsg??"no response"};let{headers,setCookies}=parseHeaderJson(at===-1?"":stdout.slice(at+15)),hop={url:String(info.url_effective??info.url??""),status,version:String(info.http_version??""),timings:timingsOf(info),headers};if(setCookies.length>0)hop.setCookies=setCookies;if(typeof info.redirect_url==="string"&&info.redirect_url!=="")hop.location=info.redirect_url;else if(headers.location!==void 0)hop.location=headers.location;if(typeof info.remote_ip==="string"&&info.remote_ip!=="")hop.remoteIp=info.remote_ip;return{exitcode,errormsg,hop}}function isRedirect(status){return status===301||status===302||status===303||status===307||status===308}function nextUrl(current,location){try{let next=new URL(location,current);return next.protocol==="http:"||next.protocol==="https:"?next.href:void 0}catch{return}}function versionLabel(version){return version===""?"unknown":`HTTP/${version}`}function altSvcProtocols(altSvc){if(altSvc===void 0||altSvc.trim()==="clear")return[];let ids=altSvc.split(",").map((entry)=>entry.trim().replace(ALT_VALUE,"")).filter((id)=>id!=="");return[...new Set(ids)]}function offersOf(options){let altSvc=altSvcProtocols(options.altSvc);return{h2:options.alpn==="h2"||options.version==="2"||options.version==="3",h3:options.version==="3"||altSvc.some((id)=>id==="h3"||id.startsWith("h3-")),altSvc}}var KNOWN_SERVERS=[[/cloudflare/i,"Cloudflare"],[/cloudfront/i,"CloudFront"],[/akamai/i,"Akamai"],[/fastly/i,"Fastly"],[/vercel/i,"Vercel"],[/netlify/i,"Netlify"],[/bunnycdn/i,"BunnyCDN"],[/^(?:gws|esf|gse)$|google frontend/i,"Google"]];function cdnHint(headers){let served=headers["x-served-by"];if(headers["cf-ray"]!==void 0)return"Cloudflare (cf-ray)";if(served!==void 0)return`${CACHE_NODE.test(served)?"Fastly":served} (x-served-by)`;if(headers["x-amz-cf-id"]!==void 0)return"CloudFront (x-amz-cf-id)";if(headers["x-vercel-id"]!==void 0)return"Vercel (x-vercel-id)";if(headers.via!==void 0)return`${headers.via} (via)`;if(headers["x-cache"]!==void 0)return`${headers["x-cache"]} (x-cache)`;let server=headers.server;if(server!==void 0){let known=KNOWN_SERVERS.find(([pattern])=>pattern.test(server));if(known!==void 0)return`${known[1]} (server)`}return}var WORTH_KNOWING=["server","content-type","content-encoding","cache-control","strict-transport-security"],SECURITY_HEADERS=["strict-transport-security","content-security-policy","x-content-type-options","x-frame-options","referrer-policy","permissions-policy"];function securityAudit(headers,secure){let present={},missing=[],hasFrameAncestors=(headers["content-security-policy"]??"").toLowerCase().includes("frame-ancestors");for(let name of SECURITY_HEADERS){if(name==="strict-transport-security"&&!secure)continue;let value=headers[name];if(value!==void 0&&value!=="")present[name]=value;else if(name==="x-frame-options"&&hasFrameAncestors)continue;else missing.push(name)}return{present,missing}}function worthKnowing(headers){let kept={};for(let name of WORTH_KNOWING){let value=headers[name];if(value!==void 0)kept[name]=value}return kept}function field(value){if(typeof value==="string")return value;return Array.isArray(value)?value.join(", "):""}function nameOf(entry){if(entry===void 0)return"";let common=field(entry.CN),organization=field(entry.O);if(common!==""&&organization!==""&&common!==organization)return`${common} (${organization})`;return common===""?organization:common}function namesOf(subjectaltname){if(subjectaltname===void 0)return[];return subjectaltname.split(",").map((entry)=>entry.trim().replace(CERT_PREFIX,"")).filter((name)=>name!=="")}function daysLeftLabel(days){return`${days} ${days===1?"day":"days"} left`}function certInfo(raw,now=Date.now()){if(raw.valid_to===void 0||raw.valid_from===void 0)return;let end=Date.parse(raw.valid_to),start=Date.parse(raw.valid_from);if(Number.isNaN(end)||Number.isNaN(start))return;return{subject:nameOf(raw.subject),issuer:nameOf(raw.issuer),names:namesOf(raw.subjectaltname),validFrom:new Date(start).toISOString(),validTo:new Date(end).toISOString(),daysLeft:Math.floor((end-now)/86400000)}}function httpRedirectOf(hop){if(hop===void 0)return;let next=hop.location===void 0?void 0:nextUrl(hop.url,hop.location),redirect={status:hop.status,toHttps:isRedirect(hop.status)&&next!==void 0&&new URL(next).protocol==="https:"};if(hop.location!==void 0)redirect.location=hop.location;return redirect}function wantsHttpCheck(target){return target.url.protocol==="https:"&&target.url.port===""}function normalizeSameSite(value){let trimmed=value.trim();if(trimmed==="")return null;let lower=trimmed.toLowerCase();if(lower==="strict")return"Strict";if(lower==="lax")return"Lax";return lower==="none"?"None":trimmed}function auditCookie(header,isHttps){let parts=header.split(";"),first=(parts[0]??"").trim(),eq=first.indexOf("="),rawName=(eq===-1?first:first.slice(0,eq)).trim(),name=rawName===""?"(unnamed)":rawName,httpOnly=!1,secure=!1,sameSite=null;for(let part of parts.slice(1)){let trimmed=part.trim();if(trimmed==="")continue;let attrEq=trimmed.indexOf("="),key=(attrEq===-1?trimmed:trimmed.slice(0,attrEq)).trim().toLowerCase(),val=attrEq===-1?"":trimmed.slice(attrEq+1);if(key==="httponly")httpOnly=!0;else if(key==="secure")secure=!0;else if(key==="samesite")sameSite=normalizeSameSite(val)}let issues=[];if(!httpOnly)issues.push("missing HttpOnly");if(isHttps&&!secure)issues.push("missing Secure");if(sameSite===null)issues.push("missing SameSite");else if(sameSite.toLowerCase()==="none"&&!secure)issues.push("SameSite=None without Secure");return{name,httpOnly,secure,sameSite,issues}}function auditCookies(setCookies,isHttps){return setCookies.filter((header)=>header.trim()!=="").map((header)=>auditCookie(header,isHttps))}function warningsOf(input){let warnings=[],{cert,httpRedirect}=input;if(cert!==void 0){if(cert.daysLeft===-1)warnings.push("certificate expired within the last day");else if(cert.daysLeft<0)warnings.push(`certificate expired ${-cert.daysLeft} days ago`);else if(cert.daysLeft<14)warnings.push(`certificate expires in ${cert.daysLeft} ${cert.daysLeft===1?"day":"days"}`)}if(input.authorizationError!==void 0)warnings.push(`certificate not trusted: ${input.authorizationError}`);if(httpRedirect!==void 0&&!httpRedirect.toHttps)warnings.push(`http:// answers ${httpRedirect.status} and does not redirect to https`);if(input.tooManyRedirects)warnings.push("more than 10 redirects");for(let cookie of input.cookies??[])if(cookie.issues.length>0)warnings.push(`cookie "${cookie.name}": ${cookie.issues.join(", ")}`);return warnings}var SIMPLE_METHODS=new Set(["GET","HEAD","POST"]),NORMALIZED_METHODS=new Set(["DELETE","GET","HEAD","OPTIONS","POST","PUT"]),SAFELISTED_HEADERS=new Set(["accept","accept-language","content-language"]),LIST=/\s*,\s*/,HOSTED_SCHEME=/^[a-z][a-z0-9+.-]*:\/\/[^/]/i;function listOf(value){return value===void 0?[]:value.trim().split(LIST).filter((item)=>item!=="")}function methodOf(input){return NORMALIZED_METHODS.has(input.toUpperCase())?input.toUpperCase():input}function requestedHeaders(value){return listOf(value).map((name)=>name.toLowerCase()).filter((name)=>!SAFELISTED_HEADERS.has(name))}function originOf(input){if(input==="null")return input;if(!HOSTED_SCHEME.test(input)||!URL.canParse(input))return;let url=new URL(input);return url.origin==="null"?`${url.protocol}//${url.host}`:url.origin}function corsVerdict(status,headers,request){let reasons=[],warnings=[],origin=headers["access-control-allow-origin"],credentials=headers["access-control-allow-credentials"]==="true",methods=listOf(headers["access-control-allow-methods"]),allowedHeaders=new Set(listOf(headers["access-control-allow-headers"]).map((name)=>name.toLowerCase()));if(status<200||status>299)reasons.push(`the preflight answered ${status}, a browser wants a 2xx`);if(origin===void 0)reasons.push("no access-control-allow-origin");else if(origin!=="*"&&origin!==request.origin)reasons.push(`access-control-allow-origin is ${origin}, not ${request.origin}`);let{method}=request;if(!SIMPLE_METHODS.has(method)&&!methods.includes("*")&&!methods.includes(method))reasons.push(methods.length===0?`no access-control-allow-methods, which ${method} needs`:`access-control-allow-methods (${methods.join(", ")}) does not list ${method}`);let missing=request.headers.map((name)=>name.toLowerCase()).filter((name)=>!allowedHeaders.has(name)&&(name==="authorization"||!allowedHeaders.has("*")));if(missing.length>0)reasons.push(`access-control-allow-headers does not cover ${missing.join(", ")}`);if(credentials&&(origin==="*"||methods.includes("*")||allowedHeaders.has("*")))warnings.push("access-control-allow-credentials comes with a * wildcard, which a request with cookies or auth does not get");if(origin===request.origin&&!listOf(headers.vary).some((name)=>name.toLowerCase()==="origin"||name==="*"))warnings.push("if the origin is echoed back from the request, vary lacks origin: a cache may hand this answer to another origin");let shown=Object.fromEntries(Object.entries(headers).filter(([name])=>name.startsWith("access-control-")||name==="vary"));return{allowed:reasons.length===0,reasons,warnings,headers:shown}}import{Resolver}from"dns/promises";var TIMEOUT_MS=3000,PUBLIC_RESOLVERS=[{name:"cloudflare",address:"1.1.1.1"},{name:"google",address:"8.8.8.8"},{name:"quad9",address:"9.9.9.9"}];function resolverFor(server,timeoutMs){let resolver=new Resolver({timeout:timeoutMs,tries:1});if(server.address!==void 0)resolver.setServers([server.address]);return resolver}function failureOf(error){let code=error.code;return code==="ETIMEOUT"||code==="ECONNREFUSED"?"no answer":String(error.message??error)}async function settled(query){try{return await query}catch(error){let code=error.code;if(code==="ENOTFOUND"||code==="ENODATA")return[];throw error}}function network(timeoutMs=TIMEOUT_MS,upstream=PUBLIC_RESOLVERS[0]){return{servers:(server)=>server.address??resolverFor(server,timeoutMs).getServers().join(", "),async records(server,host){let resolver=resolverFor(server,timeoutMs);try{let[a,aaaa,cname]=await Promise.all([settled(resolver.resolve4(host,{ttl:!0})),settled(resolver.resolve6(host,{ttl:!0})),settled(resolver.resolveCname(host))]),ttls=[...a,...aaaa].map((record)=>record.ttl);return{a:a.map((record)=>record.address).sort(),aaaa:aaaa.map((record)=>record.address).sort(),cname:cname.map((target)=>target.toLowerCase()),ttl:ttls.length===0?null:Math.min(...ttls)}}catch(error){return{a:[],aaaa:[],cname:[],ttl:null,error:failureOf(error)}}},async nameservers(zone){let resolver=resolverFor(upstream,timeoutMs),[nameservers,alias]=await Promise.all([settled(resolver.resolveNs(zone)),settled(resolver.resolveCname(zone))]);return alias.length>0?[]:nameservers},async addressOf(host){return(await settled(resolverFor(upstream,timeoutMs).resolve4(host)))[0]}}}var NO_ZONE="no zone with nameservers was found for this name",ZONE_LOOKUP_FAILED="the zone of this name could not be looked up, so no nameserver was asked";async function zoneOf(host,client){let labels=host.split(".");for(let at=0;at<labels.length-1;at++){let zone=labels.slice(at).join("."),nameservers=await failingToNothing(client.nameservers(zone));if(nameservers===void 0)return{problem:ZONE_LOOKUP_FAILED};if(nameservers.length>0)return{zone,nameservers:nameservers.sort()}}return{problem:NO_ZONE}}async function failingToNothing(query){try{return await query}catch{return}}function sameFamily(mine,theirs){if(mine.length===0||theirs.length===0)return mine.length===theirs.length;let other=new Set(theirs);return mine.some((address)=>other.has(address))}function sameAnswer(one,other){if(one.error!==void 0||other.error!==void 0)return one.error===other.error;if(one.cname.length>0||other.cname.length>0)return one.cname.join().toLowerCase()===other.cname.join().toLowerCase();return sameFamily(one.a,other.a)&&sameFamily(one.aaaa,other.aaaa)}var TRAILING_DOT=/\.$/;async function dnsReport(target,host,client=network()){let name=host.replace(TRAILING_DOT,"").toLowerCase(),found=await zoneOf(name,client),authoritative=await Promise.all(("nameservers"in found?found.nameservers:[]).map(async(nameserver)=>{let address=await failingToNothing(client.addressOf(nameserver));return address===void 0?void 0:{name:nameserver,address}})),asked=[...[{name:"system"},...PUBLIC_RESOLVERS].map((server)=>({server,authoritative:!1})),...authoritative.filter((server)=>server!==void 0).map((server)=>({server,authoritative:!0}))],answers=await Promise.all(asked.map(async({server,authoritative})=>({resolver:server.name,server:client.servers(server),authoritative,...await client.records(server,name)})));return{target,zone:"zone"in found?found.zone:null,answers,...verdictOf(answers,"problem"in found?found.problem:void 0)}}function verdictOf(answers,zoneProblem){let warnings=zoneProblem===void 0?[]:[zoneProblem],answered=answers.filter((answer)=>answer.error!=="no answer"),reference=answered.filter((answer)=>answer.authoritative),truth=reference[0]??answered[0],agree=truth===void 0||answered.every((answer)=>sameAnswer(answer,truth));if(reference.some((answer)=>!sameAnswer(answer,reference[0])))warnings.push("the zone's own nameservers disagree: one of them has not taken the last change yet");for(let answer of answers)if(answer.error==="no answer")warnings.push(`${answer.resolver} did not answer`);if(agree)return{agree,warnings};if(reference.length===0)return warnings.push(`the resolvers disagree, with no nameserver of the zone to tell which is right: ${answered.filter((answer)=>!sameAnswer(answer,truth)).map((answer)=>answer.resolver).join(", ")} differ from ${truth.resolver}`),{agree,warnings};let stale=answered.filter((answer)=>!answer.authoritative&&!reference.some((ns)=>sameAnswer(answer,ns)));for(let answer of stale){let until=answer.ttl===null||answer.cname.length>0?"":`, cached for up to ${answer.ttl}s more`;warnings.push(answer.resolver==="system"?`the system resolver answers differently from the zone's nameservers${until}: \`sudo resolvectl flush-caches\` drops its copy`:`${answer.resolver} answers differently from the zone's nameservers${until}: the change has not reached it yet`)}return{agree,warnings}}function known(report){return report.answers.some((answer)=>answer.error===void 0&&answer.a.length+answer.aaaa.length+answer.cname.length>0)}var RECORD_TYPES=["A","AAAA","CNAME","MX","TXT","CAA","NS","SOA"];async function queryRecordTypes(host,types,timeoutMs=TIMEOUT_MS){let name=host.replace(TRAILING_DOT,"").toLowerCase(),resolver=new Resolver({timeout:timeoutMs,tries:1});return Promise.all(types.map(async(type)=>{try{switch(type){case"A":return{type,values:(await settled(resolver.resolve4(name))).sort()};case"AAAA":return{type,values:(await settled(resolver.resolve6(name))).sort()};case"CNAME":return{type,values:(await settled(resolver.resolveCname(name))).map((v)=>v.toLowerCase())};case"MX":return{type,values:(await settled(resolver.resolveMx(name))).sort((a,b)=>a.priority-b.priority||a.exchange.localeCompare(b.exchange)).map((r)=>`${r.priority} ${r.exchange}`)};case"TXT":return{type,values:(await settled(resolver.resolveTxt(name))).map((parts)=>parts.join(""))};case"CAA":return{type,values:(await settled(resolver.resolveCaa(name))).map((r)=>{if(r.issue!==void 0)return`${r.critical} issue "${r.issue}"`;if(r.issuewild!==void 0)return`${r.critical} issuewild "${r.issuewild}"`;return`${r.critical} iodef "${r.iodef??""}"`})};case"NS":return{type,values:(await settled(resolver.resolveNs(name))).sort()};case"SOA":try{let soa=await resolver.resolveSoa(name);return{type,values:[`${soa.nsname} ${soa.hostmaster} serial=${soa.serial} refresh=${soa.refresh} retry=${soa.retry} expire=${soa.expire} minttl=${soa.minttl}`]}}catch(error){let code=error.code;if(code==="ENOTFOUND"||code==="ENODATA")return{type,values:[]};throw error}}}catch(error){return{type,values:[],error:failureOf(error)}}}))}async function publicIp(family,service="https://ipecho.net/plain"){let child=Bun.spawn(["curl","--silent","--show-error","--fail","--max-time","10",...family===void 0?[]:[`-${family}`],service],{stdout:"pipe",stderr:"pipe"}),[out,err,code]=await Promise.all([child.stdout.text(),child.stderr.text(),child.exited]);if(code!==0)throw Error(err.trim()===""?`curl exited ${code}`:err.trim());return out.trim()}import{lookup as lookup2}from"dns/promises";import{isIP}from"net";import{connect}from"tls";var CONNECT_TIMEOUT=10,MAX_TIME=20,HTTP3_FEATURE=/^Features:.*\bHTTP3\b/m,BRACKETS=/^\[|\]$/g,http3;async function curlHasHttp3(){if(http3!==void 0)return http3;try{let result=Bun.spawn(["curl","--version"],{stdout:"pipe",stderr:"ignore"}),text=await new Response(result.stdout).text();http3=HTTP3_FEATURE.test(text)}catch{http3=!1}return http3}function portOf(url){if(url.port!=="")return Number(url.port);return url.protocol==="https:"?443:80}function curlResolve(url,resolve){let parsed=URL.canParse(url)?new URL(url):void 0,address=parsed===void 0?void 0:resolve?.get(parsed.hostname);if(parsed===void 0||address===void 0)return[];return["--resolve",`${parsed.hostname}:${portOf(parsed)}:${isIP(address)===6?`[${address}]`:address}`]}async function runCurl(url,{http3:wantsH3,insecure,get,method,headers=[],resolve,timeoutS=MAX_TIME}){let args=["-sS","-o","/dev/null","--connect-timeout",String(Math.min(CONNECT_TIMEOUT,timeoutS)),"--max-time",String(timeoutS),"--write-out",WRITE_OUT,...curlResolve(url,resolve)];for(let header of headers)args.push("-H",header);if(method!==void 0)args.push("-X",method);else if(!get)args.push("-I");if(wantsH3)args.push("--http3");if(insecure)args.push("--insecure");try{let result=Bun.spawn(["curl",...args,url],{stdout:"pipe",stderr:"pipe"}),[stdout]=await Promise.all([new Response(result.stdout).text(),new Response(result.stderr).text(),result.exited]);return parseCurl(stdout)}catch{return{exitcode:127,errormsg:"curl is not installed"}}}async function curlHop(url,options){let result=await runCurl(url,options);if(result.hop===void 0&&options.http3)result=await runCurl(url,{...options,http3:!1});if(result.hop!==void 0&&!options.get&&options.method===void 0&&result.hop.status>=400)result=await runCurl(url,{...options,get:!0});return result}async function curlPreflight(url,request,options){let asked=[`Origin: ${request.origin}`,`Access-Control-Request-Method: ${request.method}`,...request.headers.length>0?[`Access-Control-Request-Headers: ${request.headers.join(", ")}`]:[]];return runCurl(url,{...options,headers:[...options.headers??[],...asked],http3:!1,get:!0,method:"OPTIONS"})}async function addressesOf(host,resolve){let bare=resolve?.get(host)??host.replace(BRACKETS,""),family=isIP(bare);if(family!==0)return family===4?{a:[bare],aaaa:[]}:{a:[],aaaa:[bare]};try{let found=await lookup2(bare,{all:!0});return{a:found.filter((entry)=>entry.family===4).map((entry)=>entry.address),aaaa:found.filter((entry)=>entry.family===6).map((entry)=>entry.address)}}catch{return{a:[],aaaa:[]}}}async function tlsInfo(host,port,{address,timeoutS=CONNECT_TIMEOUT}={}){let bare=host.replace(BRACKETS,"");return new Promise((resolve)=>{let socket=connect({host:address??bare,port,servername:isIP(bare)===0?bare:"",ALPNProtocols:["h2","http/1.1"],rejectUnauthorized:!1,timeout:Math.min(CONNECT_TIMEOUT,timeoutS)*1000});socket.on("secureConnect",()=>{let error=socket.authorizationError;resolve({protocol:socket.getProtocol()??"",cipher:socket.getCipher().name,alpn:typeof socket.alpnProtocol==="string"?socket.alpnProtocol:void 0,authorizationError:error===null||error===void 0||error===!1?void 0:String(error),cert:certInfo(socket.getPeerCertificate())}),socket.end()}),socket.on("error",()=>resolve(void 0)),socket.on("timeout",()=>{socket.destroy(),resolve(void 0)})})}import{createConnection,isIP as isIP2}from"net";var DEFAULT_TCP_TIMEOUT_MS=5000,BRACKETED_TARGET=/^\[([^\]]+)\]:(\d+)$/,DIGITS=/^\d+$/,BAD_HOST=/[\s/:]/;function parseTcpTarget(input){let host,rawPort;if(input.startsWith("[")){let match=BRACKETED_TARGET.exec(input);if(match===null)return;if(host=match[1],rawPort=match[2],isIP2(host)!==6)return}else{let at=input.indexOf(":");if(at<1||input.includes(":",at+1))return;if(host=input.slice(0,at),rawPort=input.slice(at+1),BAD_HOST.test(host))return}if(!DIGITS.test(rawPort))return;let port=Number(rawPort);return!Number.isInteger(port)||port<1||port>65535?void 0:{host,port}}async function tcpProbe(target,host,port,options={}){let timeoutMs=options.timeoutMs??DEFAULT_TCP_TIMEOUT_MS,connectHost=options.address??host,start=performance.now(),lookupAt;return new Promise((resolve)=>{let settled=!1,timer,socket=createConnection({host:connectHost,port}),finish=(result)=>{if(settled)return;settled=!0,clearTimeout(timer),socket.destroy(),resolve(result)};timer=setTimeout(()=>{let total=Math.round(performance.now()-start),dns=lookupAt===void 0?0:Math.round(lookupAt-start);finish({target,host,port,connected:!1,error:`timed out after ${timeoutMs}ms`,timings:{dns,connect:Math.max(0,total-dns),total}})},timeoutMs),socket.on("lookup",()=>{if(lookupAt===void 0)lookupAt=performance.now()}),socket.on("connect",()=>{let end=performance.now(),total=Math.round(end-start),dns=lookupAt===void 0?0:Math.round(lookupAt-start);finish({target,host,port,connected:!0,remoteIp:socket.remoteAddress??connectHost,remotePort:socket.remotePort??port,timings:{dns,connect:Math.max(0,total-dns),total}})}),socket.on("error",(error)=>{let end=performance.now(),total=Math.round(end-start),dns=lookupAt===void 0?0:Math.round(lookupAt-start),message=error.code!==void 0&&!error.message.includes(error.code)?`${error.code}: ${error.message}`:error.message;finish({target,host,port,connected:!1,error:message,timings:{dns,connect:Math.max(0,total-dns),total}})})})}var LABEL_WIDTH=13,HTTP_USAGE=`probe [http] [options] <url|domain>...: reports each site's HTTP version, redirect chain, timings, addresses, TLS, certificate, headers, security headers, cookies and warnings
78
80
 
79
81
  A single target prints the full summary by default (--compact forces one line); multiple targets print one line each (--verbose forces full summaries).
80
- A bare domain is tried over https first, then http, following up to ${MAX_HOPS} redirects.`,HTTP_EXITS=[[0,"every site answered, warnings or not"],[1,"a site could not be reached or redirects where nothing answers"],[2,"a usage error"]],HTTP_OPTIONS={insecure:{type:"boolean",short:"k",description:"let curl go on with a certificate it does not trust"},header:{type:"string",short:"H",multiple:!0,description:"a `Name: value` header sent with every request, repeatable"},resolve:{type:"string",multiple:!0,description:"host:ip, reach the host at that address instead of the DNS answer, repeatable"},timeout:{type:"string",short:"t",description:"longest one request may take (20s): 5s, 1m, a bare number in seconds"},verbose:{type:"boolean",description:"print the full table for every target (default for a single target)"},compact:{type:"boolean",description:"print one line per target (default for multiple targets)"},"all-headers":{type:"boolean",description:"include all response headers, not just the notable ones"},json:jsonOption("one object per target {target, url, version, status, chain, timings, addresses, tls, certificate, headers, securityHeaders, cdn, offers, httpRedirect, failedHop, warnings}, or an array for several")},DNS_USAGE="probe dns [options] <domain>...: compares DNS answers across system, public and authoritative resolvers, or queries specific record types (-t MX,TXT,CAA,NS,SOA)",DNS_EXITS=[[0,"every domain resolved"],[1,"no resolver found records for a domain"],[2,"a usage error"]],DNS_OPTIONS={type:{type:"string",short:"t",description:`record types to query, comma separated: ${RECORD_TYPES.join(", ")}`},timeout:{type:"string",description:"per-query timeout (3s): 5s, 500ms, a bare number in seconds"},json:jsonOption("resolver comparison report (with records when -t is passed)")},CORS_USAGE="probe cors [options] <origin> <url>...: sends a browser CORS preflight and reports whether the request would be allowed, and why not",CORS_EXITS=[[0,"preflight allowed for every target"],[1,"preflight refused or target unreachable"],[2,"a usage error"]],CORS_OPTIONS={method:{type:"string",short:"m",description:"Access-Control-Request-Method (POST)"},"cors-headers":{type:"string",description:"Access-Control-Request-Headers, comma separated, empty for none (content-type)"},header:{type:"string",short:"H",multiple:!0,description:"extra `Name: value` request header, repeatable"},resolve:{type:"string",multiple:!0,description:"host:ip override, repeatable"},insecure:{type:"boolean",short:"k",description:"ignore untrusted TLS certificates"},timeout:{type:"string",short:"t",description:"request timeout (20s)"},json:jsonOption("{target, url, status, request, allowed, reasons, warnings, headers}")},TLS_USAGE="probe tls [options] <host[:port]|url>...: inspects TLS protocol, cipher, ALPN and certificate directly without sending an HTTP request",TLS_EXITS=[[0,"TLS handshake succeeded"],[1,"could not complete TLS handshake"],[2,"a usage error"]],TLS_OPTIONS={resolve:{type:"string",multiple:!0,description:"host:ip override, repeatable"},timeout:{type:"string",short:"t",description:"handshake timeout (10s)"},json:jsonOption("{target, host, port, protocol, cipher, alpn, certificate, authorizationError, warnings}")},IP_USAGE="probe ip [-4|-6] [--json]: prints this machine's public IP address",IP_EXITS=[[0,"printed public IP"],[1,"could not reach IP service"],[2,"a usage error"]],IP_OPTIONS={4:{type:"boolean",description:"IPv4 address only"},6:{type:"boolean",description:"IPv6 address only"},json:jsonOption("{ip}")},BRACKETS2=/^\[|\]$/g,HEADER_LINE=/^[\w!#$%&'*+.^`|~-]+:/;async function follow(start,{insecure,wire},http3){let chain=[],url=start;while(chain.length<=MAX_HOPS){let{hop,errormsg}=await curlHop(url,{...wire,http3:http3&&url.startsWith("https:"),insecure,get:!1});if(hop===void 0)return{chain,failed:{url,error:errormsg??"no response"},tooMany:!1};chain.push(hop);let next=hop.location===void 0?void 0:nextUrl(hop.url,hop.location);if(!isRedirect(hop.status)||next===void 0)return{chain,tooMany:!1};url=next}return{chain,tooMany:!0}}async function probeOne(target,input,settings){let{wire}=settings,http3=await curlHasHttp3(),followed=await follow(target.url.href,settings,http3),httpsError;if(followed.chain.length===0&&target.bare){let plain=new URL(target.url.href);plain.protocol="http:";let second=await follow(plain.href,settings,http3);if(second.chain.length>0)httpsError=followed.failed?.error,followed=second}let final=followed.chain.at(-1);if(final===void 0)return{target:input,error:`could not reach ${target.url.host}: ${followed.failed?.error??"no response"}`};let finalUrl=new URL(final.url),secure=finalUrl.protocol==="https:",[addresses,tls,twin]=await Promise.all([addressesOf(target.url.hostname,wire.resolve),secure?tlsInfo(finalUrl.hostname,portOf(finalUrl),{address:wire.resolve?.get(finalUrl.hostname),...wire.timeoutS===void 0?{}:{timeoutS:wire.timeoutS}}):Promise.resolve(void 0),wantsHttpCheck(target)&&secure?twinOf(target.url,settings):Promise.resolve(void 0)]),httpRedirect=httpRedirectOf(twin),offers=offersOf({alpn:tls?.alpn,version:final.version,altSvc:final.headers["alt-svc"]}),warnings=warningsOf({cert:tls?.cert,authorizationError:tls?.authorizationError,httpRedirect,tooManyRedirects:followed.tooMany});if(followed.failed!==void 0)warnings.unshift(`the redirect to ${followed.failed.url} got no answer: ${followed.failed.error}`);if(!secure)warnings.push(httpsError===void 0?"the site is not served over https":`the site is not served over https: ${httpsError}`);return{target:input,url:final.url,version:final.version,status:final.status,chain:followed.chain.map((hop)=>({url:hop.url,status:hop.status,version:hop.version,...hop.location===void 0?{}:{location:hop.location},ms:hop.timings.total})),timings:final.timings,addresses,tls:tls===void 0?null:{protocol:tls.protocol,cipher:tls.cipher,...tls.alpn===void 0?{}:{alpn:tls.alpn}},certificate:tls?.cert??null,headers:settings.allHeaders?final.headers:worthKnowing(final.headers),securityHeaders:securityAudit(final.headers,secure),cdn:cdnHint(final.headers)??null,offers,httpRedirect:httpRedirect??null,failedHop:followed.failed??null,warnings}}var unreached=(report)=>("error"in report)||report.failedHop!==null;async function twinOf(url,{insecure,wire}){let plain=new URL(url.href);return plain.protocol="http:",(await curlHop(plain.href,{...wire,http3:!1,insecure,get:!1})).hop}function resolvesOf(entries){let resolve=new Map;for(let entry of entries){let at=entry.indexOf(":"),address=entry.slice(at+1).replace(BRACKETS2,"");if(at<1||isIP2(address)===0)badUsage(`--resolve takes host:ip, not ${entry}`);resolve.set(entry.slice(0,at).toLowerCase(),address)}return resolve}function validateHeaders(headers){for(let header of headers)if(!HEADER_LINE.test(header))badUsage(`-H takes "Name: value", not ${header}`)}function ms2(value){return`${value}ms`}function compact(report){let{dim}=paint(process15.stdout),redirects=report.chain.length-1,parts=[`${role("accent",process15.stdout)(versionLabel(report.version))} ${role("value",process15.stdout)(String(report.status))} ${role("path",process15.stdout)(report.url)}`,ms2(report.timings.total)],address=report.addresses.a[0]??report.addresses.aaaa[0];if(redirects>0)parts.push(`${redirects} ${redirects===1?"redirect":"redirects"}`);if(report.certificate!==null)parts.push(`cert ${daysLeftLabel(report.certificate.daysLeft)}`);if(address!==void 0)parts.push(address);let line=parts.join(dim(" "));return report.warnings.length===0?line:`${line} ${marked("warn",report.warnings.join("; "),process15.stdout)}`}function print(report){let label=role("label",process15.stdout),value=role("value",process15.stdout),accent=role("accent",process15.stdout),row=(name,text)=>console.log(`${label(name.padEnd(LABEL_WIDTH))} ${text}`);if(console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path",process15.stdout)(report.url)}`),console.log(""),report.chain.length>1)console.log(table(report.chain.map((hop)=>[String(hop.status),versionLabel(hop.version),ms2(hop.ms),hop.url]),{align:["right","left","right","left"]})),console.log("");let{timings}=report;if(row("timings",`dns ${ms2(timings.dns)}, connect ${ms2(timings.connect)}, tls ${ms2(timings.tls)}, first byte ${ms2(timings.firstByte)}, total ${ms2(timings.total)}`),row("addresses",[...report.addresses.a,...report.addresses.aaaa].join(", ")||"none found"),report.tls!==null)row("tls",`${report.tls.protocol} ${report.tls.cipher}`);let cert=report.certificate;if(cert!==null)row("issuer",cert.issuer),row("expires",`${cert.validTo.slice(0,10)} (${daysLeftLabel(cert.daysLeft)})`),row("names",cert.names.join(", "));row("offers",`h2 ${report.offers.h2?"yes":"no"}, h3 ${report.offers.h3?"yes":"no"}${report.offers.altSvc.length===0?"":` (alt-svc ${report.offers.altSvc.join(" ")})`}`);for(let[name,text]of Object.entries(report.headers))row(name==="strict-transport-security"?"hsts":name,text);if(report.securityHeaders.missing.length>0)row("security",`missing ${report.securityHeaders.missing.join(", ")}`);else row("security","all key headers present");if(report.cdn!==null)row("cdn",report.cdn);if(report.httpRedirect!==null)row("http://",report.httpRedirect.toHttps?`redirects to https (${report.httpRedirect.status})`:`answers ${report.httpRedirect.status}`);for(let warning of report.warnings)console.log(marked("warn",warning,process15.stdout))}async function httpCmd(args){let{values,positionals}=parse(args,HTTP_USAGE,HTTP_OPTIONS,{positionals:["<url|domain>..."],exits:HTTP_EXITS,examples:["probe example.com",["probe a.test b.test","one line each"],["probe https://example.com --all-headers","include every response header"]]});if(values.verbose===!0&&values.compact===!0)badUsage("pass either --verbose or --compact, not both");let headers=values.header??[];validateHeaders(headers);let timeoutMs=values.timeout===void 0?void 0:duration(values.timeout,"timeout",0,"s"),wire={headers,resolve:resolvesOf(values.resolve??[]),...timeoutMs===void 0?{}:{timeoutS:timeoutMs/1000}},targets=positionals.map((input)=>{let target=parseTarget(input);if(target===void 0)badUsage(`not a URL or domain: ${input}`);return{input,target}}),reports=await Promise.all(targets.map(async({input,target})=>probeOne(target,input,{insecure:values.insecure===!0,wire,allHeaders:values["all-headers"]===!0}))),[only]=reports;if(reports.length===1&&only!==void 0&&"error"in only)fail(only.error,1);if(values.json===!0)return printJson(reports.length===1?only:reports),reports.some(unreached)?1:0;let detailed=values.verbose===!0||values.compact!==!0&&reports.length===1,first=!0;for(let report of reports){if("error"in report)console.error(marked("problem",report.error,process15.stderr));else if(detailed){if(!first)console.log("");if(reports.length>1)console.log(role("label",process15.stdout)(report.target));print(report)}else console.log(compact(report));first=!1}return reports.some(unreached)?1:0}function printDns(report,records){let label=role("label",process15.stdout),listed=(values)=>values.length===0?"-":values.join(" ");if(console.log(`${role("path",process15.stdout)(report.target)} ${label(report.zone===null?"no zone found":`zone ${report.zone}`)}`),console.log(table([["RESOLVER","SERVER","A","AAAA","CNAME","TTL"],...report.answers.map((answer)=>[answer.authoritative?`${answer.resolver} (ns)`:answer.resolver,answer.server,...answer.error===void 0?[listed(answer.a),listed(answer.aaaa),listed(answer.cname)]:[answer.error,"",""],answer.ttl===null?"-":`${answer.ttl}s`])],{header:!0})),records!==void 0&&records.length>0)console.log(""),console.log(table([["TYPE","VALUES"],...records.map((entry)=>[entry.type,entry.error??(entry.values.length===0?"-":entry.values.join("; "))])],{header:!0}));if(report.agree)console.log(marked("ok","every resolver gives the same answer",process15.stdout));for(let warning of report.warnings)console.log(marked("warn",warning,process15.stdout))}async function dnsCmd(args){let{values,positionals}=parse(args,DNS_USAGE,DNS_OPTIONS,{positionals:["<domain>..."],exits:DNS_EXITS,examples:["probe dns example.com",["probe dns -t MX,TXT,CAA example.com","query mail, TXT and CAA records"]]}),timeoutMs=values.timeout===void 0?void 0:duration(values.timeout,"timeout",0,"s"),types;if(values.type!==void 0){let raw=values.type.split(",").map((item)=>item.trim().toUpperCase()).filter(Boolean);if(raw.find((item)=>!RECORD_TYPES.includes(item))!==void 0||raw.length===0)badUsage(`--type takes ${RECORD_TYPES.join(", ")}, not ${values.type}`);types=raw}let hosts=positionals.map((input)=>{let host=parseTarget(input)?.url.hostname;if(host===void 0)badUsage(`not a URL or domain: ${input}`);if(isIP2(host.replace(BRACKETS2,""))!==0)badUsage(`probe dns takes a name, not the address ${input}`);return{input,host}});if(types!==void 0){let results=await Promise.all(hosts.map(async({input,host})=>({target:input,records:await queryRecordTypes(host,types,timeoutMs)})));if(values.json===!0)printJson(results.length===1?results[0]:results);else for(let[at,result]of results.entries()){if(at>0)console.log("");console.log(role("path",process15.stdout)(result.target)),console.log(table([["TYPE","VALUES"],...result.records.map((r)=>[r.type,r.error??(r.values.length===0?"-":r.values.join(`
81
- `))])],{header:!0}))}return results.every((r)=>r.records.some((rec)=>rec.values.length>0))?0:1}let client=network(timeoutMs),reports=await Promise.all(hosts.map(async({input,host})=>dnsReport(input,host,client)));if(values.json===!0)printJson(reports.length===1?reports[0]:reports);else for(let[at,report]of reports.entries()){if(at>0)console.log("");printDns(report)}return reports.every(known)?0:1}function printCors(report){let label=role("label",process15.stdout),{request}=report,asked=`from ${request.origin}, ${request.method}${request.headers.length===0?"":` with ${request.headers.join(", ")}`}`;console.log(`${marked(report.allowed?"ok":"problem",report.allowed?"allowed":"refused",process15.stdout)} ${role("value",process15.stdout)(String(report.status))} ${role("path",process15.stdout)(report.url)} ${label(asked)}`);for(let[name,value]of Object.entries(report.headers))console.log(` ${label(name)} ${value}`);for(let reason of report.reasons)console.log(marked("problem",reason,process15.stdout));for(let warning of report.warnings)console.log(marked("warn",warning,process15.stdout))}async function corsCmd(args){let{values,positionals}=parse(args,CORS_USAGE,CORS_OPTIONS,{positionals:["<origin>","<url>..."],exits:CORS_EXITS,examples:[["probe cors https://app.example.com https://api.example.com/items --method PUT","check whether a browser preflight succeeds"]]}),[rawOrigin,...inputs]=positionals,origin=originOf(rawOrigin);if(origin===void 0)badUsage(`origin takes an origin such as https://app.example.com, not ${rawOrigin}`);let headers=values.header??[];validateHeaders(headers);let timeoutMs=values.timeout===void 0?void 0:duration(values.timeout,"timeout",0,"s"),wire={headers,resolve:resolvesOf(values.resolve??[]),...timeoutMs===void 0?{}:{timeoutS:timeoutMs/1000}},targets=inputs.map((input)=>{let target=parseTarget(input);if(target===void 0)badUsage(`not a URL or domain: ${input}`);return{input,target}}),request={origin,method:methodOf(values.method??"POST"),headers:requestedHeaders(values["cors-headers"]??"content-type")},reports=await Promise.all(targets.map(async({input,target})=>{let{hop,errormsg}=await curlPreflight(target.url.href,request,{...wire,insecure:values.insecure===!0});if(hop===void 0)return{target:input,error:`could not reach ${target.url.host}: ${errormsg??"no response"}`};return{target:input,url:hop.url,status:hop.status,request,...corsVerdict(hop.status,hop.headers,request)}})),[only]=reports;if(reports.length===1&&only!==void 0&&"error"in only)fail(only.error,1);if(values.json===!0)printJson(reports.length===1?only:reports);else for(let report of reports)if("error"in report)console.error(marked("problem",report.error,process15.stderr));else printCors(report);return reports.every((report)=>("allowed"in report)&&report.allowed)?0:1}async function tlsCmd(args){let{values,positionals}=parse(args,TLS_USAGE,TLS_OPTIONS,{positionals:["<host[:port]|url>..."],exits:TLS_EXITS,examples:["probe tls example.com","probe tls localhost:8443 --json"]}),timeoutMs=values.timeout===void 0?void 0:duration(values.timeout,"timeout",0,"s"),resolveMap=resolvesOf(values.resolve??[]),targets=positionals.map((input)=>{let target=parseTarget(input);if(target===void 0)badUsage(`not a URL or host: ${input}`);return{input,host:target.url.hostname,port:portOf(target.url)}}),results=await Promise.all(targets.map(async({input,host,port})=>{let info=await tlsInfo(host,port,{address:resolveMap.get(host.toLowerCase()),...timeoutMs===void 0?{}:{timeoutS:timeoutMs/1000}});if(info===void 0)return{target:input,error:`TLS handshake failed for ${host}:${port}`};let warnings=warningsOf({cert:info.cert,authorizationError:info.authorizationError,tooManyRedirects:!1});return{target:input,host,port,protocol:info.protocol,cipher:info.cipher,alpn:info.alpn??null,certificate:info.cert??null,authorizationError:info.authorizationError??null,warnings}})),[only]=results;if(results.length===1&&only!==void 0&&"error"in only)fail(only.error,1);if(values.json===!0)return printJson(results.length===1?only:results),results.some((r)=>("error"in r))?1:0;let label=role("label",process15.stdout),row=(name,text)=>console.log(`${label(name.padEnd(LABEL_WIDTH))} ${text}`);for(let[at,result]of results.entries()){if(at>0)console.log("");if("error"in result){console.error(marked("problem",result.error,process15.stderr));continue}if(console.log(`${role("accent",process15.stdout)(result.protocol)} ${role("path",process15.stdout)(`${result.host}:${result.port}`)}`),row("cipher",result.cipher),result.alpn!==null)row("alpn",result.alpn);if(result.certificate!==null)row("subject",result.certificate.subject),row("issuer",result.certificate.issuer),row("expires",`${result.certificate.validTo.slice(0,10)} (${daysLeftLabel(result.certificate.daysLeft)})`),row("names",result.certificate.names.join(", "));for(let warning of result.warnings)console.log(marked("warn",warning,process15.stdout))}return results.some((r)=>("error"in r))?1:0}async function ipCmd(args){let{values}=parse(args,IP_USAGE,IP_OPTIONS,{positionals:[],exits:IP_EXITS,examples:["probe ip","probe ip -4 --json"]});if(values[4]===!0&&values[6]===!0)badUsage("pass -4 or -6, not both");let family;if(values[4]===!0)family=4;else if(values[6]===!0)family=6;try{let ip=await publicIp(family);if(values.json===!0)printJson({ip});else console.log(ip);return 0}catch(error){fail(error instanceof Error?error.message:String(error),1)}}process15.exitCode=await runCli({name:"probe",about:"HTTP, DNS, CORS, TLS and public IP diagnostics",replaces:"curl -sI chains, openssl s_client, dig @server one-liners and ip lookups",defaultCommand:"http",examples:["probe example.com",["probe a.test b.test","one line each"],"probe dns -t MX,TXT example.com","probe cors https://app.test https://api.test/items","probe tls example.com","probe ip"],commands:{http:{summary:"HTTP version, redirect chain, timings, TLS, headers and security audit (default)",run:httpCmd},dns:{summary:"compare DNS resolvers or query specific record types (-t MX,TXT,CAA,NS,SOA)",run:dnsCmd},cors:{summary:"send a browser CORS preflight and explain whether it succeeds",run:corsCmd},tls:{summary:"direct TLS handshake and certificate inspection without HTTP",run:tlsCmd},ip:{summary:"public IPv4/IPv6 address of this machine",run:ipCmd}}});
82
+ A bare domain is tried over https first, then http, following up to ${MAX_HOPS} redirects.`,HTTP_EXITS=[[0,"every site answered (and had no warnings with --fail-on-warn)"],[1,"a site could not be reached, redirects where nothing answers, or warned with --fail-on-warn"],[2,"a usage error"]],HTTP_OPTIONS={insecure:{type:"boolean",short:"k",description:"let curl go on with a certificate it does not trust"},header:{type:"string",short:"H",multiple:!0,description:"a `Name: value` header sent with every request, repeatable"},resolve:{type:"string",multiple:!0,description:"host:ip, reach the host at that address instead of the DNS answer, repeatable"},timeout:{type:"string",short:"t",description:"longest one request may take (20s): 5s, 1m, a bare number in seconds"},verbose:{type:"boolean",description:"print the full table for every target (default for a single target)"},compact:{type:"boolean",description:"print one line per target (default for multiple targets)"},"all-headers":{type:"boolean",description:"include all response headers, not just the notable ones"},"fail-on-warn":{type:"boolean",description:"exit 1 when any target reports a warning"},json:jsonOption("one object per target {target, url, version, status, chain, timings, addresses, tls, certificate, headers, securityHeaders, cookies, cdn, offers, httpRedirect, failedHop, warnings}, or an array for several")},DNS_USAGE="probe dns [options] <domain>...: compares DNS answers across system, public and authoritative resolvers, or queries specific record types (-t MX,TXT,CAA,NS,SOA)",DNS_EXITS=[[0,"every domain resolved (and had no warnings with --fail-on-warn)"],[1,"no resolver found records for a domain or warned with --fail-on-warn"],[2,"a usage error"]],DNS_OPTIONS={type:{type:"string",short:"t",description:`record types to query, comma separated: ${RECORD_TYPES.join(", ")}`},timeout:{type:"string",description:"per-query timeout (3s): 5s, 500ms, a bare number in seconds"},"fail-on-warn":{type:"boolean",description:"exit 1 when any target reports a warning"},json:jsonOption("resolver comparison report (with records when -t is passed)")},CORS_USAGE="probe cors [options] <origin> <url>...: sends a browser CORS preflight and reports whether the request would be allowed, and why not",CORS_EXITS=[[0,"preflight allowed for every target"],[1,"preflight refused or target unreachable"],[2,"a usage error"]],CORS_OPTIONS={method:{type:"string",short:"m",description:"Access-Control-Request-Method (POST)"},"cors-headers":{type:"string",description:"Access-Control-Request-Headers, comma separated, empty for none (content-type)"},header:{type:"string",short:"H",multiple:!0,description:"extra `Name: value` request header, repeatable"},resolve:{type:"string",multiple:!0,description:"host:ip override, repeatable"},insecure:{type:"boolean",short:"k",description:"ignore untrusted TLS certificates"},timeout:{type:"string",short:"t",description:"request timeout (20s)"},json:jsonOption("{target, url, status, request, allowed, reasons, warnings, headers}")},TLS_USAGE="probe tls [options] <host[:port]|url>...: inspects TLS protocol, cipher, ALPN and certificate directly without sending an HTTP request",TLS_EXITS=[[0,"TLS handshake succeeded (and had no warnings with --fail-on-warn)"],[1,"could not complete TLS handshake or warned with --fail-on-warn"],[2,"a usage error"]],TLS_OPTIONS={resolve:{type:"string",multiple:!0,description:"host:ip override, repeatable"},timeout:{type:"string",short:"t",description:"handshake timeout (10s)"},"fail-on-warn":{type:"boolean",description:"exit 1 when any target reports a warning"},json:jsonOption("{target, host, port, protocol, cipher, alpn, certificate, authorizationError, warnings}")},TCP_USAGE="probe tcp [options] <host:port>...: opens a direct non-TLS TCP connection and reports remote IP, port and DNS/connect latency",TCP_EXITS=[[0,"every target accepted a TCP connection"],[1,"a target refused, timed out or could not be resolved"],[2,"a usage error"]],TCP_OPTIONS={resolve:{type:"string",multiple:!0,description:"host:ip override, repeatable"},timeout:{type:"string",short:"t",description:`connect timeout (${DEFAULT_TCP_TIMEOUT_MS/1000}s): 5s, 500ms, a bare number in seconds`},json:jsonOption("{target, host, port, connected, remoteIp, remotePort, timings} (or {target, host, port, connected, error, timings} on failure), or an array for several")},IP_USAGE="probe ip [-4|-6] [--json]: prints this machine's public IP address",IP_EXITS=[[0,"printed public IP"],[1,"could not reach IP service"],[2,"a usage error"]],IP_OPTIONS={4:{type:"boolean",description:"IPv4 address only"},6:{type:"boolean",description:"IPv6 address only"},json:jsonOption("{ip}")},BRACKETS2=/^\[|\]$/g,HEADER_LINE=/^[\w!#$%&'*+.^`|~-]+:/;async function follow(start,{insecure,wire},http3){let chain=[],url=start;while(chain.length<=MAX_HOPS){let{hop,errormsg}=await curlHop(url,{...wire,http3:http3&&url.startsWith("https:"),insecure,get:!1});if(hop===void 0)return{chain,failed:{url,error:errormsg??"no response"},tooMany:!1};chain.push(hop);let next=hop.location===void 0?void 0:nextUrl(hop.url,hop.location);if(!isRedirect(hop.status)||next===void 0)return{chain,tooMany:!1};url=next}return{chain,tooMany:!0}}async function probeOne(target,input,settings){let{wire}=settings,http3=await curlHasHttp3(),followed=await follow(target.url.href,settings,http3),httpsError;if(followed.chain.length===0&&target.bare){let plain=new URL(target.url.href);plain.protocol="http:";let second=await follow(plain.href,settings,http3);if(second.chain.length>0)httpsError=followed.failed?.error,followed=second}let final=followed.chain.at(-1);if(final===void 0)return{target:input,error:`could not reach ${target.url.host}: ${followed.failed?.error??"no response"}`};let finalUrl=new URL(final.url),secure=finalUrl.protocol==="https:",[addresses,tls,twin]=await Promise.all([addressesOf(target.url.hostname,wire.resolve),secure?tlsInfo(finalUrl.hostname,portOf(finalUrl),{address:wire.resolve?.get(finalUrl.hostname),...wire.timeoutS===void 0?{}:{timeoutS:wire.timeoutS}}):Promise.resolve(void 0),wantsHttpCheck(target)&&secure?twinOf(target.url,settings):Promise.resolve(void 0)]),httpRedirect=httpRedirectOf(twin),offers=offersOf({alpn:tls?.alpn,version:final.version,altSvc:final.headers["alt-svc"]}),cookies=auditCookies(final.setCookies??[],secure),warnings=warningsOf({cert:tls?.cert,authorizationError:tls?.authorizationError,httpRedirect,cookies,tooManyRedirects:followed.tooMany});if(followed.failed!==void 0)warnings.unshift(`the redirect to ${followed.failed.url} got no answer: ${followed.failed.error}`);if(!secure)warnings.push(httpsError===void 0?"the site is not served over https":`the site is not served over https: ${httpsError}`);return{target:input,url:final.url,version:final.version,status:final.status,chain:followed.chain.map((hop)=>({url:hop.url,status:hop.status,version:hop.version,...hop.location===void 0?{}:{location:hop.location},ms:hop.timings.total})),timings:final.timings,addresses,tls:tls===void 0?null:{protocol:tls.protocol,cipher:tls.cipher,...tls.alpn===void 0?{}:{alpn:tls.alpn}},certificate:tls?.cert??null,headers:settings.allHeaders?final.headers:worthKnowing(final.headers),securityHeaders:securityAudit(final.headers,secure),cookies,cdn:cdnHint(final.headers)??null,offers,httpRedirect:httpRedirect??null,failedHop:followed.failed??null,warnings}}var unreached=(report)=>("error"in report)||report.failedHop!==null;async function twinOf(url,{insecure,wire}){let plain=new URL(url.href);return plain.protocol="http:",(await curlHop(plain.href,{...wire,http3:!1,insecure,get:!1})).hop}function resolvesOf(entries){let resolve=new Map;for(let entry of entries){let at=entry.indexOf(":"),address=entry.slice(at+1).replace(BRACKETS2,"");if(at<1||isIP3(address)===0)badUsage(`--resolve takes host:ip, not ${entry}`);resolve.set(entry.slice(0,at).toLowerCase(),address)}return resolve}function validateHeaders(headers){for(let header of headers)if(!HEADER_LINE.test(header))badUsage(`-H takes "Name: value", not ${header}`)}function ms2(value){return`${value}ms`}function compact(report){let{dim}=paint(process15.stdout),redirects=report.chain.length-1,parts=[`${role("accent",process15.stdout)(versionLabel(report.version))} ${role("value",process15.stdout)(String(report.status))} ${role("path",process15.stdout)(report.url)}`,ms2(report.timings.total)],address=report.addresses.a[0]??report.addresses.aaaa[0];if(redirects>0)parts.push(`${redirects} ${redirects===1?"redirect":"redirects"}`);if(report.certificate!==null)parts.push(`cert ${daysLeftLabel(report.certificate.daysLeft)}`);if(address!==void 0)parts.push(address);let line=parts.join(dim(" "));return report.warnings.length===0?line:`${line} ${marked("warn",report.warnings.join("; "),process15.stdout)}`}function print(report){let label=role("label",process15.stdout),value=role("value",process15.stdout),accent=role("accent",process15.stdout),row=(name,text)=>console.log(`${label(name.padEnd(LABEL_WIDTH))} ${text}`);if(console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path",process15.stdout)(report.url)}`),console.log(""),report.chain.length>1)console.log(table(report.chain.map((hop)=>[String(hop.status),versionLabel(hop.version),ms2(hop.ms),hop.url]),{align:["right","left","right","left"]})),console.log("");let{timings}=report;if(row("timings",`dns ${ms2(timings.dns)}, connect ${ms2(timings.connect)}, tls ${ms2(timings.tls)}, first byte ${ms2(timings.firstByte)}, total ${ms2(timings.total)}`),row("addresses",[...report.addresses.a,...report.addresses.aaaa].join(", ")||"none found"),report.tls!==null)row("tls",`${report.tls.protocol} ${report.tls.cipher}`);let cert=report.certificate;if(cert!==null)row("issuer",cert.issuer),row("expires",`${cert.validTo.slice(0,10)} (${daysLeftLabel(cert.daysLeft)})`),row("names",cert.names.join(", "));row("offers",`h2 ${report.offers.h2?"yes":"no"}, h3 ${report.offers.h3?"yes":"no"}${report.offers.altSvc.length===0?"":` (alt-svc ${report.offers.altSvc.join(" ")})`}`);for(let[name,text]of Object.entries(report.headers))row(name==="strict-transport-security"?"hsts":name,text);if(report.securityHeaders.missing.length>0)row("security",`missing ${report.securityHeaders.missing.join(", ")}`);else row("security","all key headers present");if(report.cookies.length>0)row("cookies",report.cookies.map((cookie)=>cookie.issues.length===0?`${cookie.name} (ok)`:`${cookie.name} (${cookie.issues.join(", ")})`).join("; "));if(report.cdn!==null)row("cdn",report.cdn);if(report.httpRedirect!==null)row("http://",report.httpRedirect.toHttps?`redirects to https (${report.httpRedirect.status})`:`answers ${report.httpRedirect.status}`);for(let warning of report.warnings)console.log(marked("warn",warning,process15.stdout))}async function httpCmd(args){let{values,positionals}=parse(args,HTTP_USAGE,HTTP_OPTIONS,{positionals:["<url|domain>..."],exits:HTTP_EXITS,examples:["probe example.com",["probe a.test b.test","one line each"],["probe https://example.com --all-headers","include every response header"],["probe example.com --fail-on-warn","exit 1 on any warning"]]});if(values.verbose===!0&&values.compact===!0)badUsage("pass either --verbose or --compact, not both");let headers=values.header??[];validateHeaders(headers);let failOnWarn=values["fail-on-warn"]===!0,timeoutMs=values.timeout===void 0?void 0:duration(values.timeout,"timeout",0,"s"),wire={headers,resolve:resolvesOf(values.resolve??[]),...timeoutMs===void 0?{}:{timeoutS:timeoutMs/1000}},targets=positionals.map((input)=>{let target=parseTarget(input);if(target===void 0)badUsage(`not a URL or domain: ${input}`);return{input,target}}),reports=await Promise.all(targets.map(async({input,target})=>probeOne(target,input,{insecure:values.insecure===!0,wire,allHeaders:values["all-headers"]===!0}))),[only]=reports;if(reports.length===1&&only!==void 0&&"error"in only)fail(only.error,1);let hasFailure=reports.some((report)=>unreached(report)||failOnWarn&&!("error"in report)&&report.warnings.length>0);if(values.json===!0)return printJson(reports.length===1?only:reports),hasFailure?1:0;let detailed=values.verbose===!0||values.compact!==!0&&reports.length===1,first=!0;for(let report of reports){if("error"in report)writeErr(marked("problem",report.error,process15.stderr));else if(detailed){if(!first)console.log("");if(reports.length>1)console.log(role("label",process15.stdout)(report.target));print(report)}else console.log(compact(report));first=!1}return hasFailure?1:0}function printDns(report,records){let label=role("label",process15.stdout),listed=(values)=>values.length===0?"-":values.join(" ");if(console.log(`${role("path",process15.stdout)(report.target)} ${label(report.zone===null?"no zone found":`zone ${report.zone}`)}`),console.log(table([["RESOLVER","SERVER","A","AAAA","CNAME","TTL"],...report.answers.map((answer)=>[answer.authoritative?`${answer.resolver} (ns)`:answer.resolver,answer.server,...answer.error===void 0?[listed(answer.a),listed(answer.aaaa),listed(answer.cname)]:[answer.error,"",""],answer.ttl===null?"-":`${answer.ttl}s`])],{header:!0})),records!==void 0&&records.length>0)console.log(""),console.log(table([["TYPE","VALUES"],...records.map((entry)=>[entry.type,entry.error??(entry.values.length===0?"-":entry.values.join("; "))])],{header:!0}));if(report.agree)console.log(marked("ok","every resolver gives the same answer",process15.stdout));for(let warning of report.warnings)console.log(marked("warn",warning,process15.stdout))}async function dnsCmd(args){let{values,positionals}=parse(args,DNS_USAGE,DNS_OPTIONS,{positionals:["<domain>..."],exits:DNS_EXITS,examples:["probe dns example.com",["probe dns -t MX,TXT,CAA example.com","query mail, TXT and CAA records"],["probe dns example.com --fail-on-warn","exit 1 if resolvers disagree or fail"]]}),failOnWarn=values["fail-on-warn"]===!0,timeoutMs=values.timeout===void 0?void 0:duration(values.timeout,"timeout",0,"s"),types;if(values.type!==void 0){let raw=values.type.split(",").map((item)=>item.trim().toUpperCase()).filter(Boolean);if(raw.find((item)=>!RECORD_TYPES.includes(item))!==void 0||raw.length===0)badUsage(`--type takes ${RECORD_TYPES.join(", ")}, not ${values.type}`);types=raw}let hosts=positionals.map((input)=>{let host=parseTarget(input)?.url.hostname;if(host===void 0)badUsage(`not a URL or domain: ${input}`);if(isIP3(host.replace(BRACKETS2,""))!==0)badUsage(`probe dns takes a name, not the address ${input}`);return{input,host}});if(types!==void 0){let results=await Promise.all(hosts.map(async({input,host})=>({target:input,records:await queryRecordTypes(host,types,timeoutMs)})));if(values.json===!0)printJson(results.length===1?results[0]:results);else for(let[at,result]of results.entries()){if(at>0)console.log("");console.log(role("path",process15.stdout)(result.target)),console.log(table([["TYPE","VALUES"],...result.records.map((r)=>[r.type,r.error??(r.values.length===0?"-":r.values.join(`
83
+ `))])],{header:!0}))}return results.every((r)=>r.records.some((rec)=>rec.values.length>0)&&(!failOnWarn||r.records.every((rec)=>rec.error===void 0)))?0:1}let client=network(timeoutMs),reports=await Promise.all(hosts.map(async({input,host})=>dnsReport(input,host,client)));if(values.json===!0)printJson(reports.length===1?reports[0]:reports);else for(let[at,report]of reports.entries()){if(at>0)console.log("");printDns(report)}return reports.every((report)=>known(report)&&(!failOnWarn||report.warnings.length===0))?0:1}function printCors(report){let label=role("label",process15.stdout),{request}=report,asked=`from ${request.origin}, ${request.method}${request.headers.length===0?"":` with ${request.headers.join(", ")}`}`;console.log(`${marked(report.allowed?"ok":"problem",report.allowed?"allowed":"refused",process15.stdout)} ${role("value",process15.stdout)(String(report.status))} ${role("path",process15.stdout)(report.url)} ${label(asked)}`);for(let[name,value]of Object.entries(report.headers))console.log(` ${label(name)} ${value}`);for(let reason of report.reasons)console.log(marked("problem",reason,process15.stdout));for(let warning of report.warnings)console.log(marked("warn",warning,process15.stdout))}async function corsCmd(args){let{values,positionals}=parse(args,CORS_USAGE,CORS_OPTIONS,{positionals:["<origin>","<url>..."],exits:CORS_EXITS,examples:[["probe cors https://app.example.com https://api.example.com/items --method PUT","check whether a browser preflight succeeds"]]}),[rawOrigin,...inputs]=positionals,origin=originOf(rawOrigin);if(origin===void 0)badUsage(`origin takes an origin such as https://app.example.com, not ${rawOrigin}`);let headers=values.header??[];validateHeaders(headers);let timeoutMs=values.timeout===void 0?void 0:duration(values.timeout,"timeout",0,"s"),wire={headers,resolve:resolvesOf(values.resolve??[]),...timeoutMs===void 0?{}:{timeoutS:timeoutMs/1000}},targets=inputs.map((input)=>{let target=parseTarget(input);if(target===void 0)badUsage(`not a URL or domain: ${input}`);return{input,target}}),request={origin,method:methodOf(values.method??"POST"),headers:requestedHeaders(values["cors-headers"]??"content-type")},reports=await Promise.all(targets.map(async({input,target})=>{let{hop,errormsg}=await curlPreflight(target.url.href,request,{...wire,insecure:values.insecure===!0});if(hop===void 0)return{target:input,error:`could not reach ${target.url.host}: ${errormsg??"no response"}`};return{target:input,url:hop.url,status:hop.status,request,...corsVerdict(hop.status,hop.headers,request)}})),[only]=reports;if(reports.length===1&&only!==void 0&&"error"in only)fail(only.error,1);if(values.json===!0)printJson(reports.length===1?only:reports);else for(let report of reports)if("error"in report)writeErr(marked("problem",report.error,process15.stderr));else printCors(report);return reports.every((report)=>("allowed"in report)&&report.allowed)?0:1}async function tlsCmd(args){let{values,positionals}=parse(args,TLS_USAGE,TLS_OPTIONS,{positionals:["<host[:port]|url>..."],exits:TLS_EXITS,examples:["probe tls example.com","probe tls localhost:8443 --json",["probe tls example.com --fail-on-warn","exit 1 if cert is expiring or untrusted"]]}),failOnWarn=values["fail-on-warn"]===!0,timeoutMs=values.timeout===void 0?void 0:duration(values.timeout,"timeout",0,"s"),resolveMap=resolvesOf(values.resolve??[]),targets=positionals.map((input)=>{let target=parseTarget(input);if(target===void 0)badUsage(`not a URL or host: ${input}`);return{input,host:target.url.hostname,port:portOf(target.url)}}),results=await Promise.all(targets.map(async({input,host,port})=>{let info=await tlsInfo(host,port,{address:resolveMap.get(host.toLowerCase()),...timeoutMs===void 0?{}:{timeoutS:timeoutMs/1000}});if(info===void 0)return{target:input,error:`TLS handshake failed for ${host}:${port}`};let warnings=warningsOf({cert:info.cert,authorizationError:info.authorizationError,tooManyRedirects:!1});return{target:input,host,port,protocol:info.protocol,cipher:info.cipher,alpn:info.alpn??null,certificate:info.cert??null,authorizationError:info.authorizationError??null,warnings}})),[only]=results;if(results.length===1&&only!==void 0&&"error"in only)fail(only.error,1);let hasFailure=results.some((r)=>("error"in r)||failOnWarn&&r.warnings.length>0);if(values.json===!0)return printJson(results.length===1?only:results),hasFailure?1:0;let label=role("label",process15.stdout),row=(name,text)=>console.log(`${label(name.padEnd(LABEL_WIDTH))} ${text}`);for(let[at,result]of results.entries()){if(at>0)console.log("");if("error"in result){writeErr(marked("problem",result.error,process15.stderr));continue}if(console.log(`${role("accent",process15.stdout)(result.protocol)} ${role("path",process15.stdout)(`${result.host}:${result.port}`)}`),row("cipher",result.cipher),result.alpn!==null)row("alpn",result.alpn);if(result.certificate!==null)row("subject",result.certificate.subject),row("issuer",result.certificate.issuer),row("expires",`${result.certificate.validTo.slice(0,10)} (${daysLeftLabel(result.certificate.daysLeft)})`),row("names",result.certificate.names.join(", "));for(let warning of result.warnings)console.log(marked("warn",warning,process15.stdout))}return hasFailure?1:0}async function tcpCmd(args){let{values,positionals}=parse(args,TCP_USAGE,TCP_OPTIONS,{positionals:["<host:port>..."],exits:TCP_EXITS,examples:["probe tcp example.com:443",["probe tcp localhost:5432 localhost:6379","check multiple ports"],"probe tcp db.internal:5432 --resolve db.internal:127.0.0.1 --json"]}),timeoutMs=values.timeout===void 0?DEFAULT_TCP_TIMEOUT_MS:duration(values.timeout,"timeout",0,"s"),resolveMap=resolvesOf(values.resolve??[]),targets=positionals.map((input)=>{let parsed=parseTcpTarget(input);if(parsed===void 0)badUsage(`expected host:port, not ${input}`);return{input,...parsed}}),results=await Promise.all(targets.map(async({input,host,port})=>tcpProbe(input,host,port,{address:resolveMap.get(host.toLowerCase()),timeoutMs}))),[only]=results;if(values.json===!0)return printJson(results.length===1?only:results),results.some((result)=>!result.connected)?1:0;if(results.length===1&&only!==void 0&&!only.connected)fail(`${only.target}: ${only.error}`,1);for(let result of results){if(!result.connected){writeErr(marked("problem",`${result.target}: ${result.error}`,process15.stderr));continue}let remote=`${isIP3(result.remoteIp)===6?`[${result.remoteIp}]`:result.remoteIp}:${result.remotePort}`,{timings}=result;console.log(`${marked("ok","connected",process15.stdout)} ${role("path",process15.stdout)(result.target)} ${role("value",process15.stdout)(remote)} dns ${ms2(timings.dns)}, connect ${ms2(timings.connect)}, total ${ms2(timings.total)}`)}return results.some((result)=>!result.connected)?1:0}async function ipCmd(args){let{values}=parse(args,IP_USAGE,IP_OPTIONS,{positionals:[],exits:IP_EXITS,examples:["probe ip","probe ip -4 --json"]});if(values[4]===!0&&values[6]===!0)badUsage("pass -4 or -6, not both");let family;if(values[4]===!0)family=4;else if(values[6]===!0)family=6;try{let ip=await publicIp(family);if(values.json===!0)printJson({ip});else console.log(ip);return 0}catch(error){fail(error instanceof Error?error.message:String(error),1)}}process15.exitCode=await runCli({name:"probe",about:"HTTP, DNS, CORS, TLS, TCP and public IP diagnostics",replaces:"curl -sI chains, openssl s_client, nc -zv, dig @server one-liners and ip lookups",defaultCommand:"http",examples:["probe example.com",["probe a.test b.test","one line each"],"probe dns -t MX,TXT example.com","probe cors https://app.test https://api.test/items","probe tls example.com","probe tcp example.com:443","probe ip"],commands:{http:{summary:"HTTP version, redirect chain, timings, TLS, headers, cookies and security audit (default)",run:httpCmd},dns:{summary:"compare DNS resolvers or query specific record types (-t MX,TXT,CAA,NS,SOA)",run:dnsCmd},cors:{summary:"send a browser CORS preflight and explain whether it succeeds",run:corsCmd},tls:{summary:"direct TLS handshake and certificate inspection without HTTP",run:tlsCmd},tcp:{summary:"direct non-TLS TCP connect check with DNS and connect latency",run:tcpCmd},ip:{summary:"public IPv4/IPv6 address of this machine",run:ipCmd}}});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-probe",
3
3
  "type": "module",
4
- "version": "0.5.0",
4
+ "version": "0.6.0",
5
5
  "description": "probe: a site's HTTP version, redirect chain, timings, addresses, TLS certificate and notable headers in one call, with warnings.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -32,6 +32,6 @@
32
32
  "probe": "$npm_execpath src/probe.ts"
33
33
  },
34
34
  "devDependencies": {
35
- "@kaynooo/cli-kit": "0.50.0"
35
+ "@kaynooo/cli-kit": "0.52.1"
36
36
  }
37
37
  }