@stacksjs/dnsx
Version:
A command-line & library DNS client. Like dig & dog, but for TypeScript.
43 lines (34 loc) • 35.6 kB
JavaScript
import{a as wz,h as U6,i as F6,r as G6,s as Nz,t as H6}from"../chunk-zyb8fbk3.js";import b from"node:process";import{existsSync as V6}from"node:fs";import y from"node:fs/promises";import p from"node:os";import S from"node:path";import N from"node:process";import{EventEmitter as W6}from"node:events";import M from"node:process";import l from"node:process";import m from"node:process";import R from"node:process";import B from"node:process";import s from"node:tty";import Zz,{stdin as _z,stdout as fz}from"node:process";import o,{stdin as Yz,stdout as qz}from"node:process";import jz from"node:readline";class z6{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let z=p.homedir(),J=S.join(z,".config","clapp");this.configPath=S.join(J,"telemetry.json")}async isEnabled(){if(N.env.DO_NOT_TRACK==="1"||N.env.DO_NOT_TRACK==="true")return!1;if(N.env.NO_TELEMETRY==="1"||N.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let z=await this.loadConfig();if(z.enabled=!0,!z.userId)z.userId=this.generateUserId();await this.saveConfig(z)}async disable(){let z=await this.loadConfig();z.enabled=!1,await this.saveConfig(z)}async track(z,J){if(!await this.isEnabled())return;let $={event:z,...J,timestamp:Date.now(),platform:p.platform(),nodeVersion:N.version};if(this.events.push($),this.events.length>=10)await this.send()}async trackCommand(z,J){await this.track("command",{command:z,duration:J})}async trackError(z,J){await this.track("error",{error:z,command:J})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let J=await this.loadConfig();return J.lastSent=Date.now(),await this.saveConfig(J),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let J=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(J),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(z){return new Promise((J)=>setTimeout(J,z))}async status(){let z=await this.loadConfig();return{enabled:z.enabled,doNotTrack:N.env.DO_NOT_TRACK==="1"||N.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(V6(this.configPath)){let z=await y.readFile(this.configPath,"utf-8");return this.config=JSON.parse(z),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(z){this.config=z;try{let J=S.dirname(this.configPath);await y.mkdir(J,{recursive:!0}),await y.writeFile(this.configPath,JSON.stringify(z,null,2),"utf-8")}catch{}}generateUserId(){let z=Math.random().toString(36).substring(2,15),J=Date.now().toString(36);return`${z}-${J}`}}var Bz=new z6;function D6(z,J={}){let Z={_:[]},$=J.alias||{},Q=new Set(J.boolean||[]),j={};for(let q of Object.keys($))for(let Y of $[q])j[Y]=q;for(let q of Q)if($[q])for(let Y of $[q])Q.add(Y);function X(q,Y){let U=j[q]||q;if(Z[U]=Y,$[U])for(let F of $[U])Z[F]=Y;if(j[q]&&$[j[q]])for(let F of $[j[q]])Z[F]=Y;Z[q]=Y}for(let q=0;q<z.length;q++){let Y=z[q];if(Y==="--"){Z._.push(...z.slice(q+1));break}if(Y.startsWith("--")){let U=Y.indexOf("=");if(U!==-1){let F=Y.slice(2,U),G=Y.slice(U+1);X(F,G)}else{let F=Y.slice(2);if(F.startsWith("no-")){let H=F.slice(3);X(H,!1);continue}let G=j[F]||F;if(Q.has(G)||Q.has(F))X(F,!0);else{let H=z[q+1];if(H!==void 0&&!H.startsWith("-"))X(F,H),q++;else X(F,!0)}}}else if(Y.startsWith("-")&&Y.length>1){let U=Y.slice(1);for(let F=0;F<U.length;F++){let G=U[F],H=j[G]||G;if(F===U.length-1&&!Q.has(H)&&!Q.has(G)){let K=z[q+1];if(K!==void 0&&!K.startsWith("-"))X(G,K),q++;else X(G,!0)}else X(G,!0)}}else Z._.push(Y)}return Z}function f(z){return z.replace(/[<[].+/,"").trim()}function L6(z){let J=/<([^>]+)>/g,Z=/\[([^\]]+)\]/g,$=[],Q=(q)=>{let Y=!1,U=q[1];if(U.startsWith("..."))U=U.slice(3),Y=!0;return{required:q[0].startsWith("<"),value:U,variadic:Y}},j;while(j=J.exec(z))$.push(Q(j));let X;while(X=Z.exec(z))$.push(Q(X));return $}function M6(z){let J={alias:{},boolean:[]};for(let[Z,$]of z.entries()){if($.names.length>1)J.alias[$.names[0]]=$.names.slice(1);if($.isBoolean)if($.negated){if(!z.some((j,X)=>{return X!==Z&&j.names.some((q)=>$.names.includes(q))&&typeof j.required==="boolean"}))J.boolean.push($.names[0])}else J.boolean.push($.names[0])}return J}function r(z){return z.reduce((J,Z)=>J.length>=Z.length?J:Z,"")}function g(z,J){return z.length>=J?z:`${z}${" ".repeat(J-z.length)}`}function w6(z){return z.replace(/([a-z])-([a-z])/g,(J,Z,$)=>{return Z+$.toUpperCase()})}function N6(z,J,Z){let $=0,Q=J.length,j=z,X;for(;$<Q;++$)X=j[J[$]],j=j[J[$]]=$===Q-1?Z:X!=null?X:!!~J[$+1].indexOf(".")||!(+J[$+1]>-1)?{}:[]}function P6(z,J){for(let Z of Object.keys(J)){let $=J[Z];if($.shouldTransform){if(z[Z]=Array.prototype.concat.call([],z[Z]),typeof $.transformFunction==="function")z[Z]=z[Z].map($.transformFunction)}}}function x6(z){let J=/([^\\/]+)$/.exec(z);return J?J[1]:""}function J6(z){return z.split(".").map((J,Z)=>{return Z===0?w6(J):J}).join(".")}class A extends Error{exitCode=2;isUsageError=!0;constructor(z){super(z);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(z).stack}format(z=!1){if(z&&this.stack)return`${this.message}
Stack trace:
${this.stack}`;return this.message}}function O6(){let{env:z}=l,{TERM:J,TERM_PROGRAM:Z}=z;if(l.platform!=="win32")return J!=="linux";return Boolean(z.WT_SESSION)||Boolean(z.TERMINUS_SUBLIME)||z.ConEmuTask==="{cmd::Cmder}"||Z==="Terminus-Sublime"||Z==="vscode"||J==="xterm-256color"||J==="alacritty"||J==="rxvt-unicode"||J==="rxvt-unicode-256color"||z.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var h="\x1B",D=`${h}[`;var L={to(z,J){if(!J)return`${D}${z+1}G`;return`${D}${J+1};${z+1}H`},move(z,J){let Z="";if(z<0)Z+=`${D}${-z}D`;else if(z>0)Z+=`${D}${z}C`;if(J<0)Z+=`${D}${-J}A`;else if(J>0)Z+=`${D}${J}B`;return Z},up:(z=1)=>`${D}${z}A`,down:(z=1)=>`${D}${z}B`,forward:(z=1)=>`${D}${z}C`,backward:(z=1)=>`${D}${z}D`,nextLine:(z=1)=>`${D}E`.repeat(z),prevLine:(z=1)=>`${D}F`.repeat(z),left:`${D}G`,hide:`${D}?25l`,show:`${D}?25h`,save:`${h}7`,restore:`${h}8`};var _={screen:`${D}2J`,up:(z=1)=>`${D}1J`.repeat(z),down:(z=1)=>`${D}J`.repeat(z),line:`${D}2K`,lineEnd:`${D}K`,lineStart:`${D}1K`,lines(z){let J="";for(let Z=0;Z<z;Z++)J+=this.line+(Z<z-1?L.up():"");if(z)J+=L.left;return J}},Rz={screen:`${h}c`};function T6(z,J){let Z=[];for(let $=0;$<=J.length;$++)Z[$]=[$];for(let $=0;$<=z.length;$++)Z[0][$]=$;for(let $=1;$<=J.length;$++)for(let Q=1;Q<=z.length;Q++)if(J.charAt($-1)===z.charAt(Q-1))Z[$][Q]=Z[$-1][Q-1];else Z[$][Q]=Math.min(Z[$-1][Q-1]+1,Z[$][Q-1]+1,Z[$-1][Q]+1);return Z[J.length][z.length]}function Z6(z,J,Z=2,$=3){return J.map((Q)=>({cmd:Q,distance:T6(z,Q)})).filter(({distance:Q})=>Q<=Z).sort((Q,j)=>Q.distance-j.distance).slice(0,$).map(({cmd:Q})=>Q)}class $6{rawName;description;name;names;isBoolean;required;config;negated;constructor(z,J,Z){if(this.rawName=z,this.description=J,this.config=Object.assign({},Z),z=z.replace(/\.\*/g,""),this.negated=!1,this.names=f(z).split(",").map(($)=>{let Q=$.trim().replace(/^-{1,2}/,"");if(Q.startsWith("no-"))this.negated=!0,Q=Q.replace(/^no-/,"");return J6(Q)}).sort(($,Q)=>$.length>Q.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(z.includes("<"))this.required=!0;else if(z.includes("["))this.required=!1;else this.isBoolean=!0}}var kz=m.argv,E6=`${m.platform}-${m.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,a=R.argv,B6=`${R.platform}-${R.arch} node-${R.version}`;class d{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(z,J,Z,$){this.rawName=z,this.description=J,this.config=Z,this.cli=$,this.options=[],this.aliasNames=[],this.name=f(z);let Q=f(z),j=Q.indexOf(":");if(j>0)this.namespace=Q.substring(0,j),this.name=Q.substring(j+1);if(this.args=L6(z),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Z)this.config={}}usage(z){return this.usageText=z,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(z,J="-v, --version"){return this.versionNumber=z,this.option(J,"Display version number"),this}example(z){return this.examples.push(z),this}option(z,J,Z){let $=new $6(z,J,Z);return this.options.push($),this}alias(z){return this.aliasNames.push(z),this}action(z){return this.commandAction=z,this}before(z){return this.beforeHooks.push(z),this}after(z){return this.afterHooks.push(z),this}use(z){return this.middleware.push(z),this}isMatched(z){return this.name===z||this.aliasNames.includes(z)}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof u}hasOption(z){return z=z.split(".")[0],!!this.options.find((J)=>{return J.names.includes(z)})}outputHelp(){let{name:z,commands:J}=this.cli,{versionNumber:Z,options:$,helpCallback:Q}=this.cli.globalCommand,j=[{body:`${z}${Z?`/${Z}`:""}`}];if(j.push({title:"Usage",body:` $ ${z} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&J.length>0){let Y=r(J.map((K)=>K.rawName)),U=new Map,F=[];for(let K of J)if(K.namespace){if(!U.has(K.namespace))U.set(K.namespace,[]);U.get(K.namespace).push(K)}else F.push(K);let G="";if(F.length>0)G+=F.map((K)=>{return` ${g(K.rawName,Y.length)} ${K.description}`}).join(`
`);let H=Array.from(U.keys()).sort();for(let K of H){let K6=U.get(K);if(G.length>0)G+=`
`;G+=` ${K}:
`,G+=K6.map((n)=>{return` ${g(n.rawName,Y.length-2)} ${n.description}`}).join(`
`)}j.push({title:"Commands",body:G}),j.push({title:"For more info, run any command with the `--help` flag",body:J.map((K)=>` $ ${z}${K.name===""?"":` ${K.name}`} --help`).join(`
`)})}let q=this.isGlobalCommand?$:[...this.options,...$||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)q=q.filter((Y)=>Y.name!=="version");if(q.length>0){let Y=r(q.map((U)=>U.rawName));j.push({title:"Options",body:q.map((U)=>{return` ${g(U.rawName,Y.length)} ${U.description} ${U.config.default===void 0?"":`(default: ${U.config.default})`}`}).join(`
`)})}if(this.examples.length>0)j.push({title:"Examples",body:this.examples.map((Y)=>{if(typeof Y==="function")return Y(z);return Y}).join(`
`)});if(Q)j=Q(j)||j;console.log(j.map((Y)=>{return Y.title?`${Y.title}:
${Y.body}`:Y.body}).join(`
`))}outputVersion(){let{name:z}=this.cli,{versionNumber:J}=this.cli.globalCommand;if(J)console.log(`${z}/${J} ${typeof Bun<"u"?E6:B6}`)}checkRequiredArgs(){let z=this.args.filter((J)=>J.required).length;if(this.cli.args.length<z){let Z=this.args.filter((Q)=>Q.required).slice(this.cli.args.length),$=Z.map((Q)=>`<${Q.value}>`).join(" ");throw new A(`Missing required argument${Z.length>1?"s":""}: ${$}
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:z,globalCommand:J}=this.cli;if(!this.config.allowUnknownOptions){for(let Z of Object.keys(z))if(Z!=="--"&&!this.hasOption(Z)&&!J.hasOption(Z)){let Q=[...J.options,...this.options].flatMap((Y)=>Y.names),j=Z.length>1?`--${Z}`:`-${Z}`,X=Z6(Z,Q),q=`Unknown option \`${j}\``;if(X.length>0)q+=`
Did you mean one of these?`,X.forEach((Y)=>{let U=Y.length>1?`--${Y}`:`-${Y}`;q+=`
• ${U}`});throw q+=`
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new A(q)}}}checkOptionValue(){let{options:z,globalCommand:J}=this.cli,Z=[...J.options,...this.options];for(let $ of Z){let Q=z[$.name.split(".")[0]];if($.required){let j=Z.some((X)=>X.negated&&X.names.includes($.name));if(Q===!0||Q===!1&&!j)throw new A(`Option \`${$.rawName}\` requires a value.
Example: ${this.cli.name} ${this.rawName} ${$.rawName} <value>`)}}}}class u extends d{constructor(z){super("@@global@@","",{},z)}}var b6=d,w={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var T={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function I6(){return!0}function A6(){let z={};z.supportsColor=I6();function J($,Q=[]){let j=$===""?[]:[...Q,$],X=function(Y){if(!z.supportsColor)return Y;let U="",F="";for(let G of j)if(G in T&&T[G]in w){let H=T[G];U+=w[H][0],F=w[H][1]+F}else if(G in w)U+=w[G][0],F=w[G][1]+F;return U+Y+F},q=[...Object.keys(w),...Object.keys(T)];for(let Y of q)if(!(Y in X))Object.defineProperty(X,Y,{get(){return J(Y,j)}});return X}let Z=[...Object.keys(w),...Object.keys(T)];for(let $ of Z)if(!($ in z))Object.defineProperty(z,$,{get(){return J($)}});return z}var E=A6();class Q6 extends W6{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(z=""){super();this.name=z,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new u(this),this.globalCommand.usage("<command> [options]")}handleSignals(z){if(this.signalHandlersSet)return this;let J=async(Z)=>{if(console.log(`
Received ${Z}, cleaning up...`),z)try{await z()}catch($){console.error("Error during cleanup:",$)}M.exit(0)};return M.on("SIGINT",()=>J("SIGINT")),M.on("SIGTERM",()=>J("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(z=!0){return this.enableDidYouMean=z,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(z){return this.globalCommand.usage(z),this}command(z,J,Z){if(!Z)Z={};let $=new b6(z,J||"",Z,this);return $.globalCommand=this.globalCommand,this.commands.push($),$}option(z,J,Z){return this.globalCommand.option(z,J,Z),this}help(z){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=z,this.showHelpOnExit=!0,this}version(z,J="-v, --version"){return this.globalCommand.version(z,J),this.showVersionOnExit=!0,this}example(z){return this.globalCommand.example(z),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:z,options:J},Z,$){if(this.args=z,this.options=J,Z)this.matchedCommand=Z;if($)this.matchedCommandName=$;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(z){if(console.log(E.red(`
✗ Command "${z}" not found.
`)),this.enableDidYouMean){let J=[];for(let $ of this.commands){if($.name)J.push($.name);if($.aliasNames)J.push(...$.aliasNames)}let Z=Z6(z,J);if(Z.length>0)console.log(E.yellow("Did you mean one of these?")),Z.forEach(($)=>console.log(` ${E.dim("•")} ${this.name} ${$}`)),console.log("")}console.log(E.dim("Run"),`${this.name} --help`,E.dim("to see all available commands")),M.exit(1)}async parse(z=a,J={}){let{run:Z=!0,exitOnError:$=!1}=J;if($)try{return await this.parse(z,{run:Z})}catch(Y){throw this.handleUsageError(Y),Y}if(this.rawArgs=z,!this.name)this.name=z[1]?x6(z[1]):"cli";let Q=!0,j=z.slice(2),X=j[0];if(X&&!X.startsWith("-")){for(let Y of this.commands)if(Y.isMatched(X)){let U=this.mri(j,Y);Q=!1;let F={...U,args:U.args.slice(1)};this.setParsedInfo(F,Y,X),this.emit(`command:${X}`,Y);break}}if(Q){for(let Y of this.commands)if(Y.name===""){Q=!1;let U=this.mri(j,Y);this.setParsedInfo(U,Y),this.emit("command:!",Y);break}}if(Q){let Y=this.mri(z.slice(2));this.setParsedInfo(Y)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),Z=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),Z=!1,this.unsetMatchedCommand();let q={args:this.args,options:this.options};if(Z)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return q}mri(z,J){let Z=[...this.globalCommand.options,...J?J.options:[]],$=M6(Z),Q=[],j=z.indexOf("--");if(j>-1)Q=z.slice(j+1),z=z.slice(0,j);let X=D6(z,$),q={_:X._};for(let H of Object.keys(X))if(H!=="_")q[J6(H)]=X[H];let Y=q._,U={"--":Q},F=J&&J.config.ignoreOptionDefaultValue?J.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,G=Object.create(null);for(let H of Z){if(!F&&H.config.default!==void 0)for(let K of H.names)U[K]=H.config.default;if(Array.isArray(H.config.type)){if(G[H.name]===void 0)G[H.name]={shouldTransform:!0,transformFunction:H.config.type[0]}}}for(let H of Object.keys(q))if(H!=="_"){let K=H.split(".");N6(U,K,q[H]),P6(U,G)}return{args:Y,options:U}}async run(z=a){return this.parse(z,{run:!0,exitOnError:!0})}handleUsageError(z){if(!(!!z&&typeof z==="object"&&z.name==="ClappError"&&z.isUsageError!==!1))return;let $=z,Q=$.message??"command-line error",j=this.name?`${this.name}: `:"",X=/--help/.test(Q)?"":`
Run \`${this.name??"cli"} --help\` for usage.`;M.stderr.write(`${j}${Q}${X}
`),M.exit($.exitCode??2)}async runMatchedCommand(){let{args:z,options:J,matchedCommand:Z}=this;if(!Z||!Z.commandAction)return;Z.checkUnknownOptions(),Z.checkOptionValue(),Z.checkRequiredArgs();let $=[];Z.args.forEach((q,Y)=>{if(q.variadic)$.push(z.slice(Y));else $.push(z[Y])}),$.push(J);let Q={command:Z,args:$,options:J};for(let q of Z.beforeHooks)await q(Q);let j,X=async()=>{let q=Z.commandAction.apply(this,$);if(q instanceof Promise)j=await q;else j=q;return j};if(Z.middleware.length>0){let q=0,Y=async()=>{if(q<Z.middleware.length){let U=Z.middleware[q++];await U({...Q,next:Y})}else await X()};await Y()}else await X();for(let q of Z.afterHooks)await q(Q);return j}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return M.removeAllListeners("SIGINT"),M.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}var Y6=(z="")=>new Q6(z);class q6{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(z){if(!this.enabled){this.misses++;return}let J=this.cache.get(z);if(!J){this.misses++;return}if(Date.now()-J.timestamp>J.ttl){this.cache.delete(z),this.misses++;return}return this.hits++,J.value}set(z,J,Z=5000){if(!this.enabled)return;this.cache.set(z,{value:J,timestamp:Date.now(),ttl:Z})}has(z){if(!this.enabled)return!1;let J=this.cache.get(z);if(!J)return!1;if(Date.now()-J.timestamp>J.ttl)return this.cache.delete(z),!1;return!0}delete(z){this.cache.delete(z)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let z=Date.now();for(let[J,Z]of this.cache.entries())if(z-Z.timestamp>Z.ttl)this.cache.delete(J)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var vz=new q6;function R6(){if("FORCE_COLOR"in B.env)return B.env.FORCE_COLOR!=="0";if("NO_COLOR"in B.env||B.env.TERM==="dumb")return!1;if(B.platform==="win32")return!0;return s.isatty(1)&&s.isatty(2)}var j6=R6();function W(z,J){if(!j6)return(Z)=>Z;return(Z)=>z+Z+J}var C6=W("\x1B[0m","\x1B[0m"),k6=W("\x1B[31m","\x1B[39m"),h6=W("\x1B[32m","\x1B[39m"),v6=W("\x1B[33m","\x1B[39m"),y6=W("\x1B[34m","\x1B[39m"),S6=W("\x1B[35m","\x1B[39m"),g6=W("\x1B[36m","\x1B[39m"),_6=W("\x1B[37m","\x1B[39m"),f6=W("\x1B[90m","\x1B[39m"),m6=W("\x1B[1m","\x1B[22m"),d6=W("\x1B[3m","\x1B[23m"),u6=W("\x1B[4m","\x1B[24m"),c6=W("\x1B[2m","\x1B[22m"),i6=W("\x1B[7m","\x1B[27m"),n6=W("\x1B[8m","\x1B[28m"),p6=W("\x1B[9m","\x1B[29m"),l6=W("\x1B[41m","\x1B[49m"),r6=W("\x1B[42m","\x1B[49m"),a6=W("\x1B[43m","\x1B[49m"),s6=W("\x1B[44m","\x1B[49m"),t6=W("\x1B[45m","\x1B[49m"),o6=W("\x1B[46m","\x1B[49m"),e6=W("\x1B[47m","\x1B[49m"),zz=j6,Jz={reset:C6,red:k6,green:h6,yellow:v6,blue:y6,magenta:S6,cyan:g6,white:_6,gray:f6,bold:m6,italic:d6,underline:u6,dim:c6,inverse:i6,hidden:n6,strikethrough:p6,bgRed:l6,bgGreen:r6,bgYellow:a6,bgBlue:s6,bgMagenta:t6,bgCyan:o6,bgWhite:e6,isColorSupported:zz},C=Jz,$z=["up","down","left","right","space","enter","cancel"],k={actions:new Set($z),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function X6(z,J){if(typeof z==="string")return k.aliases.get(z)===J;for(let Z of z){if(Z===void 0)continue;if(X6(Z,J))return!0}return!1}function Qz(z,J){if(z===J)return[];let Z=z.split(`
`),$=J.split(`
`),Q=[];for(let j=0;j<Math.max(Z.length,$.length);j++)if(Z[j]!==$[j])Q.push(j);return Q}var mz=Zz.platform.startsWith("win"),t=Symbol("clapp:cancel");function I(z,J){let Z=z;if(Z.isTTY)Z.setRawMode(J)}function Xz(z){return z.replace(/\x1b\[[0-9;]*m/g,"")}function Uz(z){return Xz(z).length}function e(z,J,Z){if(!J||J<1)return z;let $=Z?.hard??!1,Q=Z?.trim??!0,j=z.split(`
`),X=[];for(let q of j){if(Uz(q)<=J){X.push(Q?q.trimEnd():q);continue}if($){let Y="",U=0,F=0;while(F<q.length){let G=q.slice(F).match(/^\x1b\[[0-9;]*m/);if(G){Y+=G[0],F+=G[0].length;continue}if(U>=J)X.push(Q?Y.trimEnd():Y),Y="",U=0;Y+=q[F],U++,F++}if(Y)X.push(Q?Y.trimEnd():Y)}else X.push(Q?q.trimEnd():q)}return X.join(`
`)}class c{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor(z,J=!0){let{input:Z=Yz,output:$=qz,render:Q,signal:j,...X}=z;this.opts=X,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=Q.bind(this),this._track=J,this._abortSignal=j,this.input=Z,this.output=$}unsubscribe(){this._subscribers.clear()}setSubscriber(z,J){let Z=this._subscribers.get(z)??[];Z.push(J),this._subscribers.set(z,Z)}on(z,J){return this.setSubscriber(z,{cb:J}),this}once(z,J){return this.setSubscriber(z,{cb:J,once:!0}),this}emit(z,...J){let Z=this._subscribers.get(z)??[],$=[];for(let Q of Z)if(Q.cb(...J),Q.once)$.push(()=>Z.splice(Z.indexOf(Q),1));for(let Q of $)Q();return this}prompt(){return new Promise((z)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),z(t);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=jz.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),I(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(L.show),this.output.off("resize",this.render),I(this.input,!1),z(this.value)}),this.once("cancel",()=>{this.output.write(L.show),this.output.off("resize",this.render),I(this.input,!1),z(t)})})}_isActionKey(z,J){return z==="\t"}_setValue(z){this.value=z,this.emit("value",this.value)}_setUserInput(z,J){if(this.userInput=z??"",this.emit("userInput",this.userInput),J&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(z,J){if(this._track&&J.name!=="return"){if(J.name&&this._isActionKey(z,J))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Z=J.name==="tab"||J.name==="escape"||J.name==="backspace"||J.name==="delete"||J.name==="enter"||J.name==="return"||J.name&&["up","down","left","right"].includes(J.name);if(z&&!Z&&z.length===1&&z>=" ")this._manualLine+=z;else if(J.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let $=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput($)}if(this.state==="error")this.state="active",this.error="";if(J?.name){if(!this._track&&k.aliases.has(J.name))this.emit("cursor",k.aliases.get(J.name));if(k.actions.has(J.name))this.emit("cursor",J.name)}if(z&&(z.toLowerCase()==="y"||z.toLowerCase()==="n"))this.emit("confirm",z.toLowerCase()==="y");if(this.emit("key",z?.toLowerCase(),J),J?.name==="return"){if(this.opts.validate){let Z=this.opts.validate(this.value);if(Z)this.error=Z instanceof Error?Z.message:Z,this.state="error"}if(this.state!=="error")this.state="submit"}if(X6([z,J?.name,J?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
`),I(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let z=e(this._prevFrame,o.stdout.columns,{hard:!0,trim:!1}).split(`
`).length-1;this.output.write(L.move(-999,z*-1))}render(){let z=e(this._render(this)??"",o.stdout.columns,{hard:!0,trim:!1});if(z===this._prevFrame)return;if(this.state==="initial")this.output.write(L.hide);else{let J=Qz(this._prevFrame,z);if(this.restoreCursor(),J&&J?.length===1){let Z=J[0];this.output.write(L.move(0,Z)),this.output.write(_.lines(1));let $=z.split(`
`);this.output.write($[Z]),this._prevFrame=z,this.output.write(L.move(0,$.length-Z-1));return}if(J&&J?.length>1){let Z=J[0];this.output.write(L.move(0,Z)),this.output.write(_.down());let Q=z.split(`
`).slice(Z);this.output.write(Q.join(`
`)),this._prevFrame=z;return}this.output.write(_.down())}if(this.output.write(z),this.state==="initial")this.state="active";this._prevFrame=z}}function Fz(z,J){if(z===void 0)return 0;if(J.length===0)return 0;let $=J.findIndex((Q)=>Q.value===z);return $!==-1?$:0}function Gz(z,J){return(J.label??String(J.value)).toLowerCase().includes(z.toLowerCase())}function Hz(z,J){if(!J)return;if(z)return J;return J[0]}class Kz extends c{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#z=0;#Z="";#$;#J;get cursor(){return this.#z}get userInputWithCursor(){if(!this.userInput)return C.inverse(C.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let z=this.userInput.slice(0,this._cursor),[J,...Z]=this.userInput.slice(this._cursor);return`${z}${C.inverse(J)}${Z.join("")}`}get options(){if(typeof this.#J==="function")return this.#J();return this.#J}constructor(z){super(z);this.#J=z.options;let J=this.options;this.filteredOptions=[...J],this.multiple=z.multiple===!0,this.#$=z.filter??Gz;let Z;if(z.initialValue&&Array.isArray(z.initialValue))if(this.multiple)Z=z.initialValue;else Z=z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Z=[this.options[0].value];if(Z)for(let $ of Z){let Q=J.findIndex((j)=>j.value===$);if(Q!==-1)this.toggleSelected($),this.#z=Q}this.focusedValue=this.options[this.#z]?.value,this.on("key",($,Q)=>this.#Q($,Q)),this.on("userInput",($)=>this.#Y($))}_isActionKey(z,J){return z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&z!==void 0&&z!==""}#Q(z,J){let Z=J.name==="up",$=J.name==="down",Q=J.name==="return";if(Z||$){if(this.#z=Math.max(0,Math.min(this.#z+(Z?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(Q)this.value=Hz(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(z))this.selectedValues=this.selectedValues.filter((J)=>J!==z);else this.selectedValues=[...this.selectedValues,z];else this.selectedValues=[z]}#Y(z){if(z!==this.#Z){this.#Z=z;let J=this.options;if(z)this.filteredOptions=J.filter((Z)=>this.#$(z,Z));else this.filteredOptions=[...J];if(this.#z=Fz(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class Vz extends c{options;cursor=0;#z;getGroupItems(z){return this.options.filter((J)=>J.group===z)}isGroupSelected(z){let J=this.getGroupItems(z),Z=this.value;if(Z===void 0)return!1;return J.every(($)=>Z.includes($.value))}toggleValue(){let z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(z.group===!0){let J=z.value,Z=this.getGroupItems(J);if(this.isGroupSelected(J))this.value=this.value.filter(($)=>Z.findIndex((Q)=>Q.value===$)===-1);else this.value=[...this.value,...Z.map(($)=>$.value)];this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(z.value);this.value=J?this.value.filter((Z)=>Z!==z.value):[...this.value,z.value]}}constructor(z){super(z,!1);let{options:J}=z;this.#z=z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Z,$])=>[{value:Z,group:!0,label:Z},...$.map((Q)=>({...Q,group:Z}))]),this.value=[...z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Z})=>Z===z.cursorAt),this.#z?0:1),this.on("cursor",(Z)=>{switch(Z){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let $=this.options[this.cursor]?.group===!0;if(!this.#z&&$)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let $=this.options[this.cursor]?.group===!0;if(!this.#z&&$)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var Wz=O6();var V=(z,J)=>Wz?z:J,cz=V("◆","*"),iz=V("■","x"),nz=V("▲","x"),pz=V("◇","o"),lz=V("┌","T"),Dz=V("│","|"),rz=V("└","—"),az=V("●",">"),sz=V("○"," "),tz=V("◻","[•]"),oz=V("◼","[+]"),ez=V("◻","[ ]"),z4=V("▪","•"),J4=V("─","-"),Z4=V("╮","+"),$4=V("├","+"),Q4=V("╯","+"),Y4=V("●","•"),q4=V("◆","*"),j4=V("▲","!"),X4=V("■","x");var U4={light:V("─","-"),heavy:V("━","="),block:V("█","#")};function Lz(){return`${C.gray(Dz)} `}var F4=Lz();var P=wz(Nz(),1);var i="0.2.3";var v={error:(z)=>P.default.red(z),warning:(z)=>P.default.yellow(z),success:(z)=>P.default.green(z),info:(z)=>P.default.blue(z),dim:(z)=>P.default.dim(z)},O=Y6("dnsx"),x=new U6("dnsx:cli");O.command("[...args]","Perform DNS lookup for specified domains").option("-q, --query <HOST>","Host name or domain name to query").option("-t, --type <TYPE>","Type of the DNS record being queried (A, MX, NS...)").option("-n, --nameserver <ADDR>","Address of the nameserver to send packets to").option("--class <CLASS>","Network class of DNS record (IN, CH, HS)").option("--edns <SETTING>","Whether to OPT in to EDNS (disable, hide, show)").option("--txid <NUMBER>","Set transaction ID to specific value").option("-Z <TWEAKS>","Set uncommon protocol tweaks").option("-U, --udp","Use DNS over UDP",{default:!1}).option("-T, --tcp","Use DNS over TCP",{default:!1}).option("-S, --tls","Use DNS-over-TLS",{default:!1}).option("-H, --https","Use DNS-over-HTTPS",{default:!1}).option("-1, --short","Display nothing but first result",{default:!1}).option("-J, --json","Display output as JSON",{default:!1}).option("--color <WHEN>","When to colorize output (always, auto, never)").option("--seconds","Display durations in seconds",{default:!1}).option("--time","Print response time",{default:!1}).option("--verbose","Print additional debugging information",{default:!1}).example("dnsx example.com").example("dnsx example.com MX").example("dnsx example.com A AAAA NS MX").example("dnsx example.com -t MX -n 1.1.1.1 -T").action(async(z,J)=>{try{let Z=new Set(["A","AAAA","NS","MX","TXT","SRV","PTR","CNAME","SOA","CAA"]),$=[],Q=[];if(z.length>0)$.push(z[0]);for(let F=1;F<z.length;F++){let G=z[F].toUpperCase();if(Z.has(G))Q.push(G);else $.push(G)}if(J.query)$.push(...Array.isArray(J.query)?J.query:[J.query]);if(J.type)Q.push(...Array.isArray(J.type)?J.type:[J.type]);if($.length===0)x.error(v.error("Error: No domains specified")),b.exit(1);let j=new G6({domains:$,nameserver:J.nameserver,type:Q.length>0?Q:void 0,class:J.class,udp:J.udp,tcp:J.tcp,tls:J.tls,https:J.https,edns:J.edns,txid:J.txid,tweaks:F6(J.Z),verbose:J.verbose}),X=Date.now(),q=await j.query(),Y=Date.now()-X,U=H6(q,{json:Boolean(J.json),short:Boolean(J.short),showDuration:J.time?Y:void 0,colors:{enabled:J.color==="always"||J.color!=="never"&&b.stdout.isTTY},rawSeconds:Boolean(J.seconds)});if(await x.info(U),q.length===0)b.exit(1)}catch(Z){if(await x.error(v.error(`Error: ${Z.message}`)),J.verbose&&Z.stack)await x.debug(v.dim(`Stack trace:
${Z.stack.split(`
`).map(($)=>` ${$}`).join(`
`)}`));b.exit(1)}});O.command("version","Show the version of dtsx").action(async()=>{await x.info(i)});O.help();O.version(i);O.parse();O.on("error",async(z)=>{await x.error(v.error(`Error: ${z.message}`)),b.exit(1)});export{v as colors};