@mirage-cli/dataforseo-cli 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +22 -43
- package/dist/dfs.js +22 -43
- package/dist/index.js +22 -43
- package/package.json +2 -2
package/dist/bin.js
CHANGED
|
@@ -1,33 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
|
|
4
|
-
`)
|
|
5
|
-
|
|
6
|
-
`),l=" ".
|
|
7
|
-
|
|
8
|
-
`)
|
|
9
|
-
|
|
10
|
-
(Did you mean one of ${a.join(", ")}?)`;if(a.length===1)return`
|
|
11
|
-
(Did you mean ${a[0]}?)`;return""}It.suggestSimilar=Tt});var De=O((Dt)=>{var Lt=K("node:events").EventEmitter,ce=K("node:child_process"),D=K("node:path"),le=K("node:fs"),T=K("node:process"),{Argument:At,humanReadableArgName:Gt}=$(),{CommanderError:pe}=C(),{Help:Ut}=ne(),{Option:Ge,DualOptions:Pt}=de(),{suggestSimilar:Ue}=Ae();class he extends Lt{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:(o)=>T.stdout.write(o),writeErr:(o)=>T.stderr.write(o),getOutHelpWidth:()=>T.stdout.isTTY?T.stdout.columns:void 0,getErrHelpWidth:()=>T.stderr.isTTY?T.stderr.columns:void 0,outputError:(o,t)=>t(o)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let o=this;o;o=o.parent)e.push(o);return e}command(e,o,t){let a=o,s=t;if(typeof a==="object"&&a!==null)s=a,a=null;s=s||{};let[,i,n]=e.match(/([^ ]+) *(.*)/),r=this.createCommand(i);if(a)r.description(a),r._executableHandler=!0;if(s.isDefault)this._defaultCommandName=r._name;if(r._hidden=!!(s.noHelp||s.hidden),r._executableFile=s.executableFile||null,n)r.arguments(n);if(this._registerCommand(r),r.parent=this,r.copyInheritedSettings(this),a)return this;return r}createCommand(e){return new he(e)}createHelp(){return Object.assign(new Ut,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,e),this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,o){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
|
|
12
|
-
- specify the name in Command constructor or using .name()`);if(o=o||{},o.isDefault)this._defaultCommandName=e._name;if(o.noHelp||o.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,o){return new At(e,o)}argument(e,o,t,a){let s=this.createArgument(e,o);if(typeof t==="function")s.default(a).argParser(t);else s.default(t);return this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach((o)=>{this.argument(o)}),this}addArgument(e){let o=this.registeredArguments.slice(-1)[0];if(o&&o.variadic)throw Error(`only the last argument can be variadic '${o.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,o){if(typeof e==="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,t,a]=e.match(/([^ ]+) *(.*)/),s=o??"display help for command",i=this.createCommand(t);if(i.helpOption(!1),a)i.arguments(a);if(s)i.description(s);return this._addImplicitHelpCommand=!0,this._helpCommand=i,this}addHelpCommand(e,o){if(typeof e!=="object")return this.helpCommand(e,o),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,o){let t=["preSubcommand","preAction","postAction"];if(!t.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
-
Expecting one of '${t.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(o);else this._lifeCycleHooks[e]=[o];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(o)=>{if(o.code!=="commander.executeSubCommandAsync")throw o};return this}_exit(e,o,t){if(this._exitCallback)this._exitCallback(new pe(e,o,t));T.exit(e)}action(e){let o=(t)=>{let a=this.registeredArguments.length,s=t.slice(0,a);if(this._storeOptionsAsProperties)s[a]=this;else s[a]=this.opts();return s.push(this),e.apply(this,s)};return this._actionHandler=o,this}createOption(e,o){return new Ge(e,o)}_callParseArg(e,o,t,a){try{return e.parseArg(o,t)}catch(s){if(s.code==="commander.invalidArgument"){let i=`${a} ${s.message}`;this.error(i,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let o=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(o){let t=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${t}'
|
|
14
|
-
- already used by option '${o.flags}'`)}this.options.push(e)}_registerCommand(e){let o=(a)=>{return[a.name()].concat(a.aliases())},t=o(e).find((a)=>this._findCommand(a));if(t){let a=o(this._findCommand(t)).join("|"),s=o(e).join("|");throw Error(`cannot add command '${s}' as already have command '${a}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let o=e.name(),t=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");if(!this._findOption(s))this.setOptionValueWithSource(t,e.defaultValue===void 0?!0:e.defaultValue,"default")}else if(e.defaultValue!==void 0)this.setOptionValueWithSource(t,e.defaultValue,"default");let a=(s,i,n)=>{if(s==null&&e.presetArg!==void 0)s=e.presetArg;let r=this.getOptionValue(t);if(s!==null&&e.parseArg)s=this._callParseArg(e,s,r,i);else if(s!==null&&e.variadic)s=e._concatValue(s,r);if(s==null)if(e.negate)s=!1;else if(e.isBoolean()||e.optional)s=!0;else s="";this.setOptionValueWithSource(t,s,n)};if(this.on("option:"+o,(s)=>{let i=`error: option '${e.flags}' argument '${s}' is invalid.`;a(s,i,"cli")}),e.envVar)this.on("optionEnv:"+o,(s)=>{let i=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;a(s,i,"env")});return this}_optionEx(e,o,t,a,s){if(typeof o==="object"&&o instanceof Ge)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let i=this.createOption(o,t);if(i.makeOptionMandatory(!!e.mandatory),typeof a==="function")i.default(s).argParser(a);else if(a instanceof RegExp){let n=a;a=(r,d)=>{let l=n.exec(r);return l?l[0]:d},i.default(s).argParser(a)}else i.default(a);return this.addOption(i)}option(e,o,t,a){return this._optionEx({},e,o,t,a)}requiredOption(e,o,t,a){return this._optionEx({mandatory:!0},e,o,t,a)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,o){return this.setOptionValueWithSource(e,o,void 0)}setOptionValueWithSource(e,o,t){if(this._storeOptionsAsProperties)this[e]=o;else this._optionValues[e]=o;return this._optionValueSources[e]=t,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let o;return this._getCommandAndAncestors().forEach((t)=>{if(t.getOptionValueSource(e)!==void 0)o=t.getOptionValueSource(e)}),o}_prepareUserArgs(e,o){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(o=o||{},e===void 0&&o.from===void 0){if(T.versions?.electron)o.from="electron";let a=T.execArgv??[];if(a.includes("-e")||a.includes("--eval")||a.includes("-p")||a.includes("--print"))o.from="eval"}if(e===void 0)e=T.argv;this.rawArgs=e.slice();let t;switch(o.from){case void 0:case"node":this._scriptPath=e[1],t=e.slice(2);break;case"electron":if(T.defaultApp)this._scriptPath=e[1],t=e.slice(2);else t=e.slice(1);break;case"user":t=e.slice(0);break;case"eval":t=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${o.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",t}parse(e,o){let t=this._prepareUserArgs(e,o);return this._parseCommand([],t),this}async parseAsync(e,o){let t=this._prepareUserArgs(e,o);return await this._parseCommand([],t),this}_executeSubCommand(e,o){o=o.slice();let t=!1,a=[".js",".ts",".tsx",".mjs",".cjs"];function s(l,_){let b=D.resolve(l,_);if(le.existsSync(b))return b;if(a.includes(D.extname(_)))return;let U=a.find((S)=>le.existsSync(`${b}${S}`));if(U)return`${b}${U}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,n=this._executableDir||"";if(this._scriptPath){let l;try{l=le.realpathSync(this._scriptPath)}catch(_){l=this._scriptPath}n=D.resolve(D.dirname(l),n)}if(n){let l=s(n,i);if(!l&&!e._executableFile&&this._scriptPath){let _=D.basename(this._scriptPath,D.extname(this._scriptPath));if(_!==this._name)l=s(n,`${_}-${e._name}`)}i=l||i}t=a.includes(D.extname(i));let r;if(T.platform!=="win32")if(t)o.unshift(i),o=Pe(T.execArgv).concat(o),r=ce.spawn(T.argv[0],o,{stdio:"inherit"});else r=ce.spawn(i,o,{stdio:"inherit"});else o.unshift(i),o=Pe(T.execArgv).concat(o),r=ce.spawn(T.execPath,o,{stdio:"inherit"});if(!r.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((_)=>{T.on(_,()=>{if(r.killed===!1&&r.exitCode===null)r.kill(_)})});let d=this._exitCallback;r.on("close",(l)=>{if(l=l??1,!d)T.exit(l);else d(new pe(l,"commander.executeSubCommandAsync","(close)"))}),r.on("error",(l)=>{if(l.code==="ENOENT"){let _=n?`searched for local subcommand relative to directory '${n}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",b=`'${i}' does not exist
|
|
15
|
-
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
|
-
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
-
- ${_}`;throw Error(b)}else if(l.code==="EACCES")throw Error(`'${i}' not executable`);if(!d)T.exit(1);else{let _=new pe(1,"commander.executeSubCommandAsync","(error)");_.nestedError=l,d(_)}}),this.runningCommand=r}_dispatchSubcommand(e,o,t){let a=this._findCommand(e);if(!a)this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,a,"preSubcommand"),s=this._chainOrCall(s,()=>{if(a._executableHandler)this._executeSubCommand(a,o.concat(t));else return a._parseCommand(o,t)}),s}_dispatchHelpCommand(e){if(!e)this.help();let o=this._findCommand(e);if(o&&!o._executableHandler)o.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,o)=>{if(e.required&&this.args[o]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(t,a,s)=>{let i=a;if(a!==null&&t.parseArg){let n=`error: command-argument value '${a}' is invalid for argument '${t.name()}'.`;i=this._callParseArg(t,a,s,n)}return i};this._checkNumberOfArguments();let o=[];this.registeredArguments.forEach((t,a)=>{let s=t.defaultValue;if(t.variadic){if(a<this.args.length){if(s=this.args.slice(a),t.parseArg)s=s.reduce((i,n)=>{return e(t,n,i)},t.defaultValue)}else if(s===void 0)s=[]}else if(a<this.args.length){if(s=this.args[a],t.parseArg)s=e(t,s,t.defaultValue)}o[a]=s}),this.processedArgs=o}_chainOrCall(e,o){if(e&&e.then&&typeof e.then==="function")return e.then(()=>o());return o()}_chainOrCallHooks(e,o){let t=e,a=[];if(this._getCommandAndAncestors().reverse().filter((s)=>s._lifeCycleHooks[o]!==void 0).forEach((s)=>{s._lifeCycleHooks[o].forEach((i)=>{a.push({hookedCommand:s,callback:i})})}),o==="postAction")a.reverse();return a.forEach((s)=>{t=this._chainOrCall(t,()=>{return s.callback(s.hookedCommand,this)})}),t}_chainOrCallSubCommandHook(e,o,t){let a=e;if(this._lifeCycleHooks[t]!==void 0)this._lifeCycleHooks[t].forEach((s)=>{a=this._chainOrCall(a,()=>{return s(this,o)})});return a}_parseCommand(e,o){let t=this.parseOptions(o);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(t.operands),o=t.unknown,this.args=e.concat(o),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),o);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(o),this._dispatchSubcommand(this._defaultCommandName,e,o);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(t.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let a=()=>{if(t.unknown.length>0)this.unknownOption(t.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){a(),this._processArguments();let i;if(i=this._chainOrCallHooks(i,"preAction"),i=this._chainOrCall(i,()=>this._actionHandler(this.processedArgs)),this.parent)i=this._chainOrCall(i,()=>{this.parent.emit(s,e,o)});return i=this._chainOrCallHooks(i,"postAction"),i}if(this.parent&&this.parent.listenerCount(s))a(),this._processArguments(),this.parent.emit(s,e,o);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,o);if(this.listenerCount("command:*"))this.emit("command:*",e,o);else if(this.commands.length)this.unknownCommand();else a(),this._processArguments()}else if(this.commands.length)a(),this.help({error:!0});else a(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((o)=>o._name===e||o._aliases.includes(e))}_findOption(e){return this.options.find((o)=>o.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((o)=>{if(o.mandatory&&e.getOptionValue(o.attributeName())===void 0)e.missingMandatoryOptionValue(o)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((t)=>{let a=t.attributeName();if(this.getOptionValue(a)===void 0)return!1;return this.getOptionValueSource(a)!=="default"});e.filter((t)=>t.conflictsWith.length>0).forEach((t)=>{let a=e.find((s)=>t.conflictsWith.includes(s.attributeName()));if(a)this._conflictingOption(t,a)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let o=[],t=[],a=o,s=e.slice();function i(r){return r.length>1&&r[0]==="-"}let n=null;while(s.length){let r=s.shift();if(r==="--"){if(a===t)a.push(r);a.push(...s);break}if(n&&!i(r)){this.emit(`option:${n.name()}`,r);continue}if(n=null,i(r)){let d=this._findOption(r);if(d){if(d.required){let l=s.shift();if(l===void 0)this.optionMissingArgument(d);this.emit(`option:${d.name()}`,l)}else if(d.optional){let l=null;if(s.length>0&&!i(s[0]))l=s.shift();this.emit(`option:${d.name()}`,l)}else this.emit(`option:${d.name()}`);n=d.variadic?d:null;continue}}if(r.length>2&&r[0]==="-"&&r[1]!=="-"){let d=this._findOption(`-${r[1]}`);if(d){if(d.required||d.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${d.name()}`,r.slice(2));else this.emit(`option:${d.name()}`),s.unshift(`-${r.slice(2)}`);continue}}if(/^--[^=]+=/.test(r)){let d=r.indexOf("="),l=this._findOption(r.slice(0,d));if(l&&(l.required||l.optional)){this.emit(`option:${l.name()}`,r.slice(d+1));continue}}if(i(r))a=t;if((this._enablePositionalOptions||this._passThroughOptions)&&o.length===0&&t.length===0){if(this._findCommand(r)){if(o.push(r),s.length>0)t.push(...s);break}else if(this._getHelpCommand()&&r===this._getHelpCommand().name()){if(o.push(r),s.length>0)o.push(...s);break}else if(this._defaultCommandName){if(t.push(r),s.length>0)t.push(...s);break}}if(this._passThroughOptions){if(a.push(r),s.length>0)a.push(...s);break}a.push(r)}return{operands:o,unknown:t}}opts(){if(this._storeOptionsAsProperties){let e={},o=this.options.length;for(let t=0;t<o;t++){let a=this.options[t].attributeName();e[a]=a===this._versionOptionName?this._version:this[a]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,o)=>Object.assign(e,o.opts()),{})}error(e,o){if(this._outputConfiguration.outputError(`${e}
|
|
18
|
-
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
|
-
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
20
|
-
`),this.outputHelp({error:!0});let t=o||{},a=t.exitCode||1,s=t.code||"commander.error";this._exit(a,s,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in T.env){let o=e.attributeName();if(this.getOptionValue(o)===void 0||["default","config","env"].includes(this.getOptionValueSource(o)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,T.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new Pt(this.options),o=(t)=>{return this.getOptionValue(t)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(t))};this.options.filter((t)=>t.implied!==void 0&&o(t.attributeName())&&e.valueFromOption(this.getOptionValue(t.attributeName()),t)).forEach((t)=>{Object.keys(t.implied).filter((a)=>!o(a)).forEach((a)=>{this.setOptionValueWithSource(a,t.implied[a],"implied")})})}missingArgument(e){let o=`error: missing required argument '${e}'`;this.error(o,{code:"commander.missingArgument"})}optionMissingArgument(e){let o=`error: option '${e.flags}' argument missing`;this.error(o,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let o=`error: required option '${e.flags}' not specified`;this.error(o,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,o){let t=(i)=>{let n=i.attributeName(),r=this.getOptionValue(n),d=this.options.find((_)=>_.negate&&n===_.attributeName()),l=this.options.find((_)=>!_.negate&&n===_.attributeName());if(d&&(d.presetArg===void 0&&r===!1||d.presetArg!==void 0&&r===d.presetArg))return d;return l||i},a=(i)=>{let n=t(i),r=n.attributeName();if(this.getOptionValueSource(r)==="env")return`environment variable '${n.envVar}'`;return`option '${n.flags}'`},s=`error: ${a(e)} cannot be used with ${a(o)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let o="";if(e.startsWith("--")&&this._showSuggestionAfterError){let a=[],s=this;do{let i=s.createHelp().visibleOptions(s).filter((n)=>n.long).map((n)=>n.long);a=a.concat(i),s=s.parent}while(s&&!s._enablePositionalOptions);o=Ue(e,a)}let t=`error: unknown option '${e}'${o}`;this.error(t,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let o=this.registeredArguments.length,t=o===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${o} argument${t} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],o="";if(this._showSuggestionAfterError){let a=[];this.createHelp().visibleCommands(this).forEach((s)=>{if(a.push(s.name()),s.alias())a.push(s.alias())}),o=Ue(e,a)}let t=`error: unknown command '${e}'${o}`;this.error(t,{code:"commander.unknownCommand"})}version(e,o,t){if(e===void 0)return this._version;this._version=e,o=o||"-V, --version",t=t||"output the version number";let a=this.createOption(o,t);return this._versionOptionName=a.attributeName(),this._registerOption(a),this.on("option:"+a.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,o){if(e===void 0&&o===void 0)return this._description;if(this._description=e,o)this._argsDescription=o;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let o=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)o=this.commands[this.commands.length-1];if(e===o._name)throw Error("Command alias can't be the same as its name");let t=this.parent?._findCommand(e);if(t){let a=[t.name()].concat(t.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${a}'`)}return o._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((o)=>this.alias(o)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let o=this.registeredArguments.map((t)=>{return Gt(t)});return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?o:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}nameFromFilename(e){return this._name=D.basename(e,D.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let o=this.createHelp();if(o.helpWidth===void 0)o.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return o.formatHelp(this,o)}_getHelpContext(e){e=e||{};let o={error:!!e.error},t;if(o.error)t=(a)=>this._outputConfiguration.writeErr(a);else t=(a)=>this._outputConfiguration.writeOut(a);return o.write=e.write||t,o.command=this,o}outputHelp(e){let o;if(typeof e==="function")o=e,e=void 0;let t=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach((s)=>s.emit("beforeAllHelp",t)),this.emit("beforeHelp",t);let a=this.helpInformation(t);if(o){if(a=o(a),typeof a!=="string"&&!Buffer.isBuffer(a))throw Error("outputHelp callback must return a string or a Buffer")}if(t.write(a),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",t),this._getCommandAndAncestors().forEach((s)=>s.emit("afterAllHelp",t))}helpOption(e,o){if(typeof e==="boolean"){if(e)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return e=e??"-h, --help",o=o??"display help for command",this._helpOption=this.createOption(e,o),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let o=T.exitCode||0;if(o===0&&e&&typeof e!=="function"&&e.error)o=1;this._exit(o,"commander.help","(outputHelp)")}addHelpText(e,o){let t=["beforeAll","before","after","afterAll"];if(!t.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
22
|
-
Expecting one of '${t.join("', '")}'`);let a=`${e}Help`;return this.on(a,(s)=>{let i;if(typeof o==="function")i=o({error:s.error,command:s.command});else i=o;if(i)s.write(`${i}
|
|
23
|
-
`)}),this}_outputHelpIfRequested(e){let o=this._getHelpOption();if(o&&e.find((a)=>o.is(a)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function Pe(e){return e.map((o)=>{if(!o.startsWith("--inspect"))return o;let t,a="127.0.0.1",s="9229",i;if((i=o.match(/^(--inspect(-brk)?)$/))!==null)t=i[1];else if((i=o.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(t=i[1],/^\d+$/.test(i[3]))s=i[3];else a=i[3];else if((i=o.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)t=i[1],a=i[3],s=i[4];if(t&&s!=="0")return`${t}=${a}:${parseInt(s)+1}`;return o})}Dt.Command=he});var ze=O((zt)=>{var{Argument:xe}=$(),{Command:ge}=De(),{CommanderError:Rt,InvalidArgumentError:Re}=C(),{Help:Et}=ne(),{Option:Ee}=de();zt.program=new ge;zt.createCommand=(e)=>new ge(e);zt.createOption=(e,o)=>new Ee(e,o);zt.createArgument=(e,o)=>new xe(e,o);zt.Command=ge;zt.Option=Ee;zt.Argument=xe;zt.Help=Et;zt.CommanderError=Rt;zt.InvalidArgumentError=Re;zt.InvalidOptionArgumentError=Re});var Be=at(ze(),1),{program:_s,createCommand:ys,createArgument:ks,createOption:ws,CommanderError:bs,InvalidArgumentError:Ts,InvalidOptionArgumentError:Is,Command:N,Argument:Ss,Option:Oe,Help:Ls}=Be.default;var c=Object.freeze({NONE:"none",PATH:"path",TEXT:"text"});class p{short;long;valueKind;numericShorthand;description;defaultValue;required;constructor(e={}){this.short=e.short??null,this.long=e.long??null,this.valueKind=e.valueKind??c.NONE,this.numericShorthand=e.numericShorthand??!1,this.description=e.description??null,this.defaultValue=e.defaultValue??null,this.required=e.required??!1,Object.freeze(this)}get name(){return this.long??this.short??""}}class q{kind;name;variadic;required;constructor(e={}){this.kind=e.kind??c.PATH,this.name=e.name??"arg",this.variadic=e.variadic??!1,this.required=e.required??!0,Object.freeze(this)}}class h{options;positional;rest;ignoreTokens;description;constructor(e={}){this.options=Object.freeze([...e.options??[]]),this.positional=Object.freeze([...e.positional??[]]),this.rest=e.rest??null,this.ignoreTokens=new Set(e.ignoreTokens??[]),this.description=e.description??null,Object.freeze(this)}}class qe{flags;args;cachePaths;pathFlagValues;constructor(e){this.flags=e.flags,this.args=e.args,this.cachePaths=e.cachePaths??[],this.pathFlagValues=e.pathFlagValues??[]}paths(){return this.args.filter(([,e])=>e===c.PATH).map(([e])=>e)}routingPaths(){return[...this.paths(),...this.pathFlagValues]}texts(){return this.args.filter(([,e])=>e===c.TEXT).map(([e])=>e)}flag(e,o=null){return this.flags[e]??o}}class L{stdout;stderr;exitCode;reads;writes;cache;streamSource;constructor(e={}){this.stdout=Ye(e.stdout??null),this.stderr=Ye(e.stderr??null),this.exitCode=e.exitCode??0,this.reads=e.reads??{},this.writes=e.writes??{},this.cache=e.cache??[],this.streamSource=null}}function Ye(e){if(e===null||e===void 0)return null;if(e instanceof Uint8Array)return e;if(typeof e==="string")return new TextEncoder().encode(e);return null}function g(e){return Object.freeze({name:e.name,resource:e.resource??null,spec:e.spec,fn:e.fn,description:e.description??e.spec.description??null})}function A(e){return Object.freeze({name:e.name,description:e.description??null,commands:Object.freeze([...e.commands??[]]),groups:Object.freeze([...e.groups??[]])})}var Wt=new TextDecoder;async function Jt(e,o={}){let t=Array.isArray(o)?Me(e.spec,o):o,a={flags:t.flags??{},stdin:t.stdin??null},s=await e.fn({},t.paths??[],t.texts??[],a),[i,n]=jt(s),r=await Fe(i??n.stdout);return{bytes:r,text:Wt.decode(r),result:n}}function jt(e){if(!e)return[null,new L];return e}async function Fe(e){if(e===null)return new Uint8Array;if(e instanceof Uint8Array)return e;let o=[];for await(let i of e)o.push(i);let t=0;for(let i of o)t+=i.byteLength;let a=new Uint8Array(t),s=0;for(let i of o)a.set(i,s),s+=i.byteLength;return a}function Me(e,o){let t={},a=[];for(let r of e.options)if(r.defaultValue!==null&&r.defaultValue!==void 0)t[r.name]=r.defaultValue;else if(r.valueKind===c.NONE)t[r.name]=!1;let s=0;while(s<o.length){let r=o[s]??"";if(r==="--"){a.push(...o.slice(s+1));break}let d=$t(e,r);if(d){s+=Qt(d,r,o,s,t);continue}a.push(r),s+=1}let{paths:i,texts:n}=Vt(e,a);return{paths:i,texts:n,flags:t}}function $t(e,o){if(o.startsWith("--")){let t=o.slice(2).split("=")[0];return e.options.find((a)=>a.long===t)}if(o.startsWith("-")&&o.length>1){let t=o[1];return e.options.find((a)=>a.short===t)}return}function Qt(e,o,t,a,s){if(e.valueKind===c.NONE)return s[e.name]=!0,1;if(o.includes("="))return s[e.name]=o.slice(o.indexOf("=")+1),1;return s[e.name]=t[a+1]??"",2}function Vt(e,o){let t=[],a=[],s=0;for(let i of e.positional){if(s>=o.length)break;if(i.variadic){Q(i.kind,o.slice(s),t,a),s=o.length;break}Q(i.kind,[o[s]],t,a),s+=1}if(s<o.length&&e.rest)Q(e.rest.kind,o.slice(s),t,a);return{paths:t,texts:a}}function Q(e,o,t,a){if(e===c.PATH)t.push(...o);else if(e===c.TEXT)a.push(...o)}function x(e){let o=new N(e.name);if(e.description)o.description(e.description);return Zt(o,e.spec),o.action(async(...t)=>{let a=t[t.length-1],s=t[t.length-2],i=t.slice(0,-2),{paths:n,texts:r,flags:d}=ta(e.spec,i,s),l=await e.fn({},n,r,{flags:d}),[_,b]=l??[null,new L],U=await Fe(_??b.stdout);if(U.byteLength>0)process.stdout.write(U);if(b.stderr)process.stderr.write(b.stderr);if(b.exitCode!==0)process.exit(b.exitCode)}),o}function P(e,o){let t=new N(o.name);if(o.description)t.description(o.description);for(let a of o.groups)P(t,a);for(let a of o.commands)t.addCommand(x(a));return e.addCommand(t),t}function Zt(e,o){for(let t of o.positional){let a=t.variadic?`<${t.name}...>`:t.required?`<${t.name}>`:`[${t.name}]`;e.argument(a)}if(o.rest)e.argument(`[${o.rest.name}...]`);for(let t of o.options)e.addOption(ea(t))}function ea(e){let o=new Oe(oa(e),e.description??void 0);if(e.defaultValue!==null)o.default(e.defaultValue);if(e.required)o.makeOptionMandatory(!0);return o}function oa(e){let o=[];if(e.short)o.push(`-${e.short}`);if(e.long)o.push(`--${e.long}`);let t=o.join(", ");if(e.valueKind!==c.NONE)t+=` <${e.long??e.short}>`;return t}function ta(e,o,t){let a=[],s=[];e.positional.forEach((n,r)=>{let d=o[r];if(d===void 0||d===null)return;let l=Array.isArray(d)?d:[String(d)];Q(n.kind,l,a,s)});let i={};for(let n of e.options){let r=aa(n.long??n.short??"");if(r in t){let d=t[r];if(typeof d==="string"||typeof d==="boolean")i[n.name]=d}}return{paths:a,texts:s,flags:i}}function aa(e){return e.replace(/-([a-z])/g,(o,t)=>t.toUpperCase())}function sa(e,o={}){return[typeof e==="string"?new TextEncoder().encode(e):e,new L({exitCode:o.exitCode??0,stderr:o.stderr??null})]}import{existsSync as ia,mkdirSync as ra,readFileSync as na,writeFileSync as da,chmodSync as ca}from"node:fs";import{homedir as la}from"node:os";import{dirname as pa,join as ha}from"node:path";var Y=ha(la(),".config","dataforseo","config.json");function Ke(){return Y}function H(){let e=ga();if(e)return e;if(ia(Y)){let o=na(Y,"utf8"),t=JSON.parse(o);if(t.login&&t.password)return{login:t.login,password:t.password}}throw Error(`No DataForSEO credentials found.
|
|
24
|
-
Either set DATAFORSEO_LOGIN and DATAFORSEO_PASSWORD env vars, or run: dfs login --login <email> --password <api_password>`)}function Ce(e){return ra(pa(Y),{recursive:!0}),da(Y,JSON.stringify(e,null,2)),ca(Y,384),Y}function me({login:e,password:o}){return"Basic "+Buffer.from(`${e}:${o}`).toString("base64")}function ga(){let e=process.env.DATAFORSEO_LOGIN,o=process.env.DATAFORSEO_PASSWORD;if(e&&o)return{login:e,password:o};return null}var ma="https://api.dataforseo.com";async function v(e,o,t={}){let a=H(),s=Ne(e,t.baseUrl),i=fa(o,t.wrapAsTaskArray??!0),n=new AbortController,r=setTimeout(()=>n.abort(),t.timeoutMs??120000),d;try{d=await fetch(s,{method:"POST",headers:{Authorization:me(a),"Content-Type":"application/json","User-Agent":"dataforseo-cli/0.1.0"},body:i===void 0?void 0:JSON.stringify(i),signal:n.signal})}finally{clearTimeout(r)}let l=await d.text(),_;try{_=l?JSON.parse(l):{}}catch{throw Error(`HTTP ${d.status}: non-JSON response: ${l.slice(0,500)}`)}if(!d.ok){let b=_.status_message??`HTTP ${d.status}`;throw Error(`DataForSEO error: ${b}`)}return _}async function R(e,o={}){let t=H(),a=Ne(e,o.baseUrl),s=new AbortController,i=setTimeout(()=>s.abort(),o.timeoutMs??60000),n;try{n=await fetch(a,{method:"GET",headers:{Authorization:me(t),"User-Agent":"dataforseo-cli/0.1.0"},signal:s.signal})}finally{clearTimeout(i)}let r=await n.text(),d=r?JSON.parse(r):{};if(!n.ok)throw Error(`DataForSEO error: ${d.status_message??`HTTP ${n.status}`}`);return d}function Ne(e,o){let t=e.trim();if(!t.startsWith("/"))t="/"+t;if(!t.startsWith("/v3/"))t="/v3"+t;return(o??ma)+t}function fa(e,o){if(e===void 0||e===null)return;if(Array.isArray(e))return e;if(o&&typeof e==="object")return[e];return e}function He(e){let o=e.tasks??[],t=[];for(let a of o){let s=a.result;if(!Array.isArray(s))continue;for(let i of s)if(i&&typeof i==="object"&&Array.isArray(i.items))t.push(...i.items);else t.push(i)}return t}function Je(e,o){if(o.format==="raw")return JSON.stringify(e,null,2);let t=o.full?e:He(e);switch(o.format){case"json":return JSON.stringify(t,null,2);case"ndjson":return Array.isArray(t)?t.map((a)=>JSON.stringify(a)).join(`
|
|
25
|
-
`):JSON.stringify(t);case"table":return ua(Xe(t),o.columns);case"csv":return va(Xe(t),o.columns)}}function Xe(e){if(Array.isArray(e))return e.filter((o)=>o!==null&&typeof o==="object"&&!Array.isArray(o));if(e&&typeof e==="object")return[e];return[]}function ua(e,o){if(e.length===0)return"(no rows)";let t=o??je(e),a=t.map((i)=>Math.max(i.length,...e.map((n)=>fe(n[i]).length))),s=[];s.push(t.map((i,n)=>i.padEnd(a[n]??i.length)).join(" ")),s.push(a.map((i)=>"-".repeat(i)).join(" "));for(let i of e)s.push(t.map((n,r)=>fe(i[n]).padEnd(a[r]??0)).join(" "));return s.join(`
|
|
26
|
-
`)}function va(e,o){if(e.length===0)return"";let t=o??je(e),a=[t.map(We).join(",")];for(let s of e)a.push(t.map((i)=>We(fe(s[i]))).join(","));return a.join(`
|
|
27
|
-
`)}function je(e){let o=new Set;for(let t of e)for(let a of Object.keys(t))o.add(a);return[...o]}function fe(e){if(e===null||e===void 0)return"";if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function We(e){if(/[",\n\r]/.test(e))return`"${e.replace(/"/g,'""')}"`;return e}var _a=new TextEncoder,m=Object.freeze([new p({short:"o",long:"output",valueKind:c.TEXT,description:"Output format: json|ndjson|table|csv|raw (default json).",defaultValue:"json"}),new p({long:"columns",valueKind:c.TEXT,description:"Comma-separated columns for table/csv output."}),new p({long:"full",valueKind:c.NONE,description:"Emit the full response (skip the items extraction)."}),new p({long:"no-cost",valueKind:c.NONE,description:"Don't print the response cost on stderr."})]);function f(e,o){let t=o.flags??{},a=t.output??"json",s=t.full===!0,i=t["no-cost"]===!0,n=t.columns,r=typeof n==="string"?n.split(",").map((b)=>b.trim()).filter(Boolean):void 0,d=Je(e,{format:a,full:s,columns:r}),l=_a.encode(d.endsWith(`
|
|
28
|
-
`)?d:d+`
|
|
29
|
-
`),_=!i&&typeof e.cost==="number"&&e.cost>0?`[cost] $${e.cost.toFixed(4)}
|
|
30
|
-
`:null;return[l,new L({exitCode:0,stderr:_})]}var w=Object.freeze([new p({long:"location",valueKind:c.TEXT,description:'Location name (default "United States").',defaultValue:"United States"}),new p({long:"location-code",valueKind:c.TEXT,description:"Location code, overrides --location."}),new p({long:"language",valueKind:c.TEXT,description:'Language name (default "English").',defaultValue:"English"}),new p({long:"language-code",valueKind:c.TEXT,description:"Language code, overrides --language."})]);function k(e){let o=e.flags??{},t={},a=o["location-code"];if(typeof a==="string"&&a)t.locationCode=Number(a);else t.locationName=o.location??"United States";let s=o["language-code"];if(typeof s==="string"&&s)t.languageCode=s;else t.languageName=o.language??"English";return t}function u(e,o={}){return new q({kind:c.TEXT,name:e,...o})}function y(e,o,t){let a=e.flags?.[o];return typeof a==="string"?a:t??""}function G(e,o){return e.flags?.[o]===!0}function I(e,o,t){let a=e.flags?.[o];if(typeof a==="string"&&a)return Number(a);return t}function X(e){let o={};if(e.locationCode!==void 0)o.location_code=e.locationCode;else o.location_name=e.locationName??"United States";if(e.languageCode!==void 0)o.language_code=e.languageCode;else o.language_name=e.languageName??"English";return o}var ya={chatgpt:"ai_optimization/chat_gpt/llm_responses/live",claude:"ai_optimization/claude/llm_responses/live",gemini:"ai_optimization/gemini/llm_responses/live",perplexity:"ai_optimization/perplexity/llm_responses/live"};async function $e(e){return v("ai_optimization/ai_keyword_data/keywords_search_volume/live",{...X(e),keywords:e.keywords})}async function Qe(e){return v("ai_optimization/llm_mentions/search/live",{...X(e),target:e.keywords.map((o)=>({keyword:o}))})}async function Ve(e){return v("ai_optimization/llm_mentions/top_pages/live",{...X(e),target:e.keywords.map((o)=>({keyword:o}))})}async function Ze(e){return v("ai_optimization/llm_mentions/top_domains/live",{...X(e),target:e.keywords.map((o)=>({keyword:o}))})}async function eo(e){return v("ai_optimization/llm_mentions/aggregated_metrics/live",{...X(e),target:e.keywords.map((o)=>({keyword:o}))})}async function oo(e){return v(ya[e.model],{system_message:e.systemMessage,message_chain:[{role:"user",message:e.message}],max_output_tokens:e.maxOutputTokens??512,temperature:e.temperature??0.3,top_p:e.topP??0.5})}var F="ram",ka=g({name:"search-volume",resource:F,spec:new h({description:"AI-tool search volume — how often a keyword is typed at LLMs.",positional:[u("keywords",{variadic:!0})],options:[...w,...m]}),fn:async(e,o,t,a)=>{let s=await $e({...k(a),keywords:[...t]});return f(s,a)}}),wa=g({name:"mentions",resource:F,spec:new h({description:"Search LLM mentions for one or more keyword targets.",positional:[u("keywords",{variadic:!0})],options:[...w,...m]}),fn:async(e,o,t,a)=>{let s=await Qe({...k(a),keywords:[...t]});return f(s,a)}}),ba=g({name:"top-pages",resource:F,spec:new h({description:"Top pages cited by AI for the given keyword targets.",positional:[u("keywords",{variadic:!0})],options:[...w,...m]}),fn:async(e,o,t,a)=>{let s=await Ve({...k(a),keywords:[...t]});return f(s,a)}}),Ta=g({name:"top-domains",resource:F,spec:new h({description:"Top domains cited by AI for the given keyword targets.",positional:[u("keywords",{variadic:!0})],options:[...w,...m]}),fn:async(e,o,t,a)=>{let s=await Ze({...k(a),keywords:[...t]});return f(s,a)}}),Ia=g({name:"metrics",resource:F,spec:new h({description:"Aggregated LLM mention metrics (volume, sentiment) for keyword targets.",positional:[u("keywords",{variadic:!0})],options:[...w,...m]}),fn:async(e,o,t,a)=>{let s=await eo({...k(a),keywords:[...t]});return f(s,a)}}),Sa=g({name:"ask",resource:F,spec:new h({description:"Ask a specific LLM via DataForSEO's metered proxy.",positional:[u("message")],options:[new p({long:"model",valueKind:c.TEXT,description:"chatgpt | claude | gemini | perplexity.",defaultValue:"chatgpt"}),new p({long:"system",valueKind:c.TEXT,description:"Optional system message."}),new p({long:"max-tokens",valueKind:c.TEXT,description:"Max output tokens (default 512).",defaultValue:"512"}),new p({long:"temperature",valueKind:c.TEXT,description:"Sampling temperature (default 0.3).",defaultValue:"0.3"}),...m]}),fn:async(e,o,t,a)=>{let s=y(a,"model","chatgpt"),i=y(a,"system")||void 0,n=await oo({model:s,message:t[0]??"",systemMessage:i,maxOutputTokens:I(a,"max-tokens",512),temperature:Number(y(a,"temperature","0.3"))});return f(n,a)}}),to=A({name:"ai",description:"AI Optimization: LLM mentions, top pages/domains, AI search volume, LLM proxy.",commands:[ka,wa,ba,Ta,Ia,Sa]});async function ao(e){return v("backlinks/summary/live",{target:e})}async function so(e){return v("backlinks/backlinks/live",{target:e.target,limit:e.limit??100,mode:e.mode??"as_is"})}async function io(e){return v("backlinks/referring_domains/live",{target:e.target,limit:e.limit??100})}async function ro(e){return v("backlinks/anchors/live",{target:e.target,limit:e.limit??100})}async function no(e){return v("backlinks/competitors/live",{target:e.target,limit:e.limit??100})}async function co(e){return v("backlinks/bulk_ranks/live",{targets:e})}var M="ram",V=new p({long:"limit",valueKind:c.TEXT,description:"Max results.",defaultValue:"100"}),La=g({name:"summary",resource:M,spec:new h({description:"High-level backlink summary for a target.",positional:[u("target")],options:[...m]}),fn:async(e,o,t,a)=>{let s=await ao(t[0]??"");return f(s,a)}}),Aa=g({name:"list",resource:M,spec:new h({description:"List individual backlinks.",positional:[u("target")],options:[V,new p({long:"mode",valueKind:c.TEXT,description:"as_is | one_per_domain | one_per_anchor.",defaultValue:"as_is"}),...m]}),fn:async(e,o,t,a)=>{let s=await so({target:t[0]??"",limit:I(a,"limit",100),mode:y(a,"mode","as_is")});return f(s,a)}}),Ga=g({name:"referring-domains",resource:M,spec:new h({description:"Referring domains pointing to a target.",positional:[u("target")],options:[V,...m]}),fn:async(e,o,t,a)=>{let s=await io({target:t[0]??"",limit:I(a,"limit",100)});return f(s,a)}}),Ua=g({name:"anchors",resource:M,spec:new h({description:"Anchor text distribution for a target.",positional:[u("target")],options:[V,...m]}),fn:async(e,o,t,a)=>{let s=await ro({target:t[0]??"",limit:I(a,"limit",100)});return f(s,a)}}),Pa=g({name:"competitors",resource:M,spec:new h({description:"Domains with similar backlink profiles.",positional:[u("target")],options:[V,...m]}),fn:async(e,o,t,a)=>{let s=await no({target:t[0]??"",limit:I(a,"limit",100)});return f(s,a)}}),Da=g({name:"ranks",resource:M,spec:new h({description:"Bulk DataForSEO domain rank for up to 1000 targets.",positional:[u("targets",{variadic:!0})],options:[...m]}),fn:async(e,o,t,a)=>{let s=await co([...t]);return f(s,a)}}),lo=A({name:"backlinks",description:"Backlink profiles, referring domains, anchors.",commands:[La,Aa,Ga,Ua,Pa,Da]});var po=[{path:"/v3/serp/id_list",method:"post",operationId:"IdList",tag:"Serp",description:`This endpoint is designed to provide you with a list of IDs and metadata for all SERP tasks created within the specified time period, including both successful and uncompleted tasks.
|
|
2
|
+
import{Command as zt}from"commander";var r=Object.freeze({NONE:"none",PATH:"path",TEXT:"text"});class n{short;long;valueKind;numericShorthand;description;defaultValue;required;constructor(e={}){this.short=e.short??null,this.long=e.long??null,this.valueKind=e.valueKind??r.NONE,this.numericShorthand=e.numericShorthand??!1,this.description=e.description??null,this.defaultValue=e.defaultValue??null,this.required=e.required??!1,Object.freeze(this)}get name(){return this.long??this.short??""}}class E{kind;name;variadic;required;constructor(e={}){this.kind=e.kind??r.PATH,this.name=e.name??"arg",this.variadic=e.variadic??!1,this.required=e.required??!0,Object.freeze(this)}}class d{options;positional;rest;ignoreTokens;description;constructor(e={}){this.options=Object.freeze([...e.options??[]]),this.positional=Object.freeze([...e.positional??[]]),this.rest=e.rest??null,this.ignoreTokens=new Set(e.ignoreTokens??[]),this.description=e.description??null,Object.freeze(this)}}class se{flags;args;cachePaths;pathFlagValues;constructor(e){this.flags=e.flags,this.args=e.args,this.cachePaths=e.cachePaths??[],this.pathFlagValues=e.pathFlagValues??[]}paths(){return this.args.filter(([,e])=>e===r.PATH).map(([e])=>e)}routingPaths(){return[...this.paths(),...this.pathFlagValues]}texts(){return this.args.filter(([,e])=>e===r.TEXT).map(([e])=>e)}flag(e,t=null){return this.flags[e]??t}}class w{stdout;stderr;exitCode;reads;writes;cache;streamSource;constructor(e={}){this.stdout=ae(e.stdout??null),this.stderr=ae(e.stderr??null),this.exitCode=e.exitCode??0,this.reads=e.reads??{},this.writes=e.writes??{},this.cache=e.cache??[],this.streamSource=null}}function ae(e){if(e===null||e===void 0)return null;if(e instanceof Uint8Array)return e;if(typeof e==="string")return new TextEncoder().encode(e);return null}import{Command as ie,Option as yo}from"commander";function c(e){return Object.freeze({name:e.name,resource:e.resource??null,spec:e.spec,fn:e.fn,description:e.description??e.spec.description??null})}function b(e){return Object.freeze({name:e.name,description:e.description??null,commands:Object.freeze([...e.commands??[]]),groups:Object.freeze([...e.groups??[]])})}var ko=new TextDecoder;async function wo(e,t={}){let a=Array.isArray(t)?ne(e.spec,t):t,o={flags:a.flags??{},stdin:a.stdin??null},s=await e.fn({},a.paths??[],a.texts??[],o),[i,g]=bo(s),m=await re(i??g.stdout);return{bytes:m,text:ko.decode(m),result:g}}function bo(e){if(!e)return[null,new w];return e}async function re(e){if(e===null)return new Uint8Array;if(e instanceof Uint8Array)return e;let t=[];for await(let i of e)t.push(i);let a=0;for(let i of t)a+=i.byteLength;let o=new Uint8Array(a),s=0;for(let i of t)o.set(i,s),s+=i.byteLength;return o}function ne(e,t){let a={},o=[];for(let m of e.options)if(m.defaultValue!==null&&m.defaultValue!==void 0)a[m.name]=m.defaultValue;else if(m.valueKind===r.NONE)a[m.name]=!1;let s=0;while(s<t.length){let m=t[s]??"";if(m==="--"){o.push(...t.slice(s+1));break}let u=To(e,m);if(u){s+=Io(u,m,t,s,a);continue}o.push(m),s+=1}let{paths:i,texts:g}=So(e,o);return{paths:i,texts:g,flags:a}}function To(e,t){if(t.startsWith("--")){let a=t.slice(2).split("=")[0];return e.options.find((o)=>o.long===a)}if(t.startsWith("-")&&t.length>1){let a=t[1];return e.options.find((o)=>o.short===a)}return}function Io(e,t,a,o,s){if(e.valueKind===r.NONE)return s[e.name]=!0,1;if(t.includes("="))return s[e.name]=t.slice(t.indexOf("=")+1),1;return s[e.name]=a[o+1]??"",2}function So(e,t){let a=[],o=[],s=0;for(let i of e.positional){if(s>=t.length)break;if(i.variadic){q(i.kind,t.slice(s),a,o),s=t.length;break}q(i.kind,[t[s]],a,o),s+=1}if(s<t.length&&e.rest)q(e.rest.kind,t.slice(s),a,o);return{paths:a,texts:o}}function q(e,t,a,o){if(e===r.PATH)a.push(...t);else if(e===r.TEXT)o.push(...t)}function L(e){let t=new ie(e.name);if(e.description)t.description(e.description);return Ao(t,e.spec),t.action(async(...a)=>{let o=a[a.length-1],s=a[a.length-2],i=a.slice(0,-2),{paths:g,texts:m,flags:u}=xo(e.spec,i,s),I=await e.fn({},g,m,{flags:u}),[D,A]=I??[null,new w],te=await re(D??A.stdout);if(te.byteLength>0)process.stdout.write(te);if(A.stderr)process.stderr.write(A.stderr);if(A.exitCode!==0)process.exit(A.exitCode)}),t}function S(e,t){let a=new ie(t.name);if(t.description)a.description(t.description);for(let o of t.groups)S(a,o);for(let o of t.commands)a.addCommand(L(o));return e.addCommand(a),a}function Ao(e,t){for(let a of t.positional){let o=a.variadic?`<${a.name}...>`:a.required?`<${a.name}>`:`[${a.name}]`;e.argument(o)}if(t.rest)e.argument(`[${t.rest.name}...]`);for(let a of t.options)e.addOption(Lo(a))}function Lo(e){let t=new yo(Go(e),e.description??void 0);if(e.defaultValue!==null)t.default(e.defaultValue);if(e.required)t.makeOptionMandatory(!0);return t}function Go(e){let t=[];if(e.short)t.push(`-${e.short}`);if(e.long)t.push(`--${e.long}`);let a=t.join(", ");if(e.valueKind!==r.NONE)a+=` <${e.long??e.short}>`;return a}function xo(e,t,a){let o=[],s=[];e.positional.forEach((g,m)=>{let u=t[m];if(u===void 0||u===null)return;let I=Array.isArray(u)?u:[String(u)];q(g.kind,I,o,s)});let i={};for(let g of e.options){let m=Uo(g.long??g.short??"");if(m in a){let u=a[m];if(typeof u==="string"||typeof u==="boolean")i[g.name]=u}}return{paths:o,texts:s,flags:i}}function Uo(e){return e.replace(/-([a-z])/g,(t,a)=>a.toUpperCase())}function Do(e,t={}){return[typeof e==="string"?new TextEncoder().encode(e):e,new w({exitCode:t.exitCode??0,stderr:t.stderr??null})]}import{existsSync as Po,mkdirSync as Eo,readFileSync as Ro,writeFileSync as Oo,chmodSync as zo}from"node:fs";import{homedir as Co}from"node:os";import{dirname as Bo,join as Fo}from"node:path";var P=Fo(Co(),".config","dataforseo","config.json");function de(){return P}function z(){let e=Yo();if(e)return e;if(Po(P)){let t=Ro(P,"utf8"),a=JSON.parse(t);if(a.login&&a.password)return{login:a.login,password:a.password}}throw Error(`No DataForSEO credentials found.
|
|
3
|
+
Either set DATAFORSEO_LOGIN and DATAFORSEO_PASSWORD env vars, or run: dfs login --login <email> --password <api_password>`)}function ce(e){return Eo(Bo(P),{recursive:!0}),Oo(P,JSON.stringify(e,null,2)),zo(P,384),P}function X({login:e,password:t}){return"Basic "+Buffer.from(`${e}:${t}`).toString("base64")}function Yo(){let e=process.env.DATAFORSEO_LOGIN,t=process.env.DATAFORSEO_PASSWORD;if(e&&t)return{login:e,password:t};return null}var qo="https://api.dataforseo.com";async function f(e,t,a={}){let o=z(),s=le(e,a.baseUrl),i=Ko(t,a.wrapAsTaskArray??!0),g=new AbortController,m=setTimeout(()=>g.abort(),a.timeoutMs??120000),u;try{u=await fetch(s,{method:"POST",headers:{Authorization:X(o),"Content-Type":"application/json","User-Agent":"dataforseo-cli/0.1.0"},body:i===void 0?void 0:JSON.stringify(i),signal:g.signal})}finally{clearTimeout(m)}let I=await u.text(),D;try{D=I?JSON.parse(I):{}}catch{throw Error(`HTTP ${u.status}: non-JSON response: ${I.slice(0,500)}`)}if(!u.ok){let A=D.status_message??`HTTP ${u.status}`;throw Error(`DataForSEO error: ${A}`)}return D}async function G(e,t={}){let a=z(),o=le(e,t.baseUrl),s=new AbortController,i=setTimeout(()=>s.abort(),t.timeoutMs??60000),g;try{g=await fetch(o,{method:"GET",headers:{Authorization:X(a),"User-Agent":"dataforseo-cli/0.1.0"},signal:s.signal})}finally{clearTimeout(i)}let m=await g.text(),u=m?JSON.parse(m):{};if(!g.ok)throw Error(`DataForSEO error: ${u.status_message??`HTTP ${g.status}`}`);return u}function le(e,t){let a=e.trim();if(!a.startsWith("/"))a="/"+a;if(!a.startsWith("/v3/"))a="/v3"+a;return(t??qo)+a}function Ko(e,t){if(e===void 0||e===null)return;if(Array.isArray(e))return e;if(t&&typeof e==="object")return[e];return e}function pe(e){let t=e.tasks??[],a=[];for(let o of t){let s=o.result;if(!Array.isArray(s))continue;for(let i of s)if(i&&typeof i==="object"&&Array.isArray(i.items))a.push(...i.items);else a.push(i)}return a}function me(e,t){if(t.format==="raw")return JSON.stringify(e,null,2);let a=t.full?e:pe(e);switch(t.format){case"json":return JSON.stringify(a,null,2);case"ndjson":return Array.isArray(a)?a.map((o)=>JSON.stringify(o)).join(`
|
|
4
|
+
`):JSON.stringify(a);case"table":return Mo(he(a),t.columns);case"csv":return No(he(a),t.columns)}}function he(e){if(Array.isArray(e))return e.filter((t)=>t!==null&&typeof t==="object"&&!Array.isArray(t));if(e&&typeof e==="object")return[e];return[]}function Mo(e,t){if(e.length===0)return"(no rows)";let a=t??fe(e),o=a.map((i)=>Math.max(i.length,...e.map((g)=>J(g[i]).length))),s=[];s.push(a.map((i,g)=>i.padEnd(o[g]??i.length)).join(" ")),s.push(o.map((i)=>"-".repeat(i)).join(" "));for(let i of e)s.push(a.map((g,m)=>J(i[g]).padEnd(o[m]??0)).join(" "));return s.join(`
|
|
5
|
+
`)}function No(e,t){if(e.length===0)return"";let a=t??fe(e),o=[a.map(ge).join(",")];for(let s of e)o.push(a.map((i)=>ge(J(s[i]))).join(","));return o.join(`
|
|
6
|
+
`)}function fe(e){let t=new Set;for(let a of e)for(let o of Object.keys(a))t.add(o);return[...t]}function J(e){if(e===null||e===void 0)return"";if(typeof e==="string")return e;if(typeof e==="number"||typeof e==="boolean")return String(e);return JSON.stringify(e)}function ge(e){if(/[",\n\r]/.test(e))return`"${e.replace(/"/g,'""')}"`;return e}var Ho=new TextEncoder,l=Object.freeze([new n({short:"o",long:"output",valueKind:r.TEXT,description:"Output format: json|ndjson|table|csv|raw (default json).",defaultValue:"json"}),new n({long:"columns",valueKind:r.TEXT,description:"Comma-separated columns for table/csv output."}),new n({long:"full",valueKind:r.NONE,description:"Emit the full response (skip the items extraction)."}),new n({long:"no-cost",valueKind:r.NONE,description:"Don't print the response cost on stderr."})]);function p(e,t){let a=t.flags??{},o=a.output??"json",s=a.full===!0,i=a["no-cost"]===!0,g=a.columns,m=typeof g==="string"?g.split(",").map((A)=>A.trim()).filter(Boolean):void 0,u=me(e,{format:o,full:s,columns:m}),I=Ho.encode(u.endsWith(`
|
|
7
|
+
`)?u:u+`
|
|
8
|
+
`),D=!i&&typeof e.cost==="number"&&e.cost>0?`[cost] $${e.cost.toFixed(4)}
|
|
9
|
+
`:null;return[I,new w({exitCode:0,stderr:D})]}var y=Object.freeze([new n({long:"location",valueKind:r.TEXT,description:'Location name (default "United States").',defaultValue:"United States"}),new n({long:"location-code",valueKind:r.TEXT,description:"Location code, overrides --location."}),new n({long:"language",valueKind:r.TEXT,description:'Language name (default "English").',defaultValue:"English"}),new n({long:"language-code",valueKind:r.TEXT,description:"Language code, overrides --language."})]);function _(e){let t=e.flags??{},a={},o=t["location-code"];if(typeof o==="string"&&o)a.locationCode=Number(o);else a.locationName=t.location??"United States";let s=t["language-code"];if(typeof s==="string"&&s)a.languageCode=s;else a.languageName=t.language??"English";return a}function h(e,t={}){return new E({kind:r.TEXT,name:e,...t})}function v(e,t,a){let o=e.flags?.[t];return typeof o==="string"?o:a??""}function T(e,t){return e.flags?.[t]===!0}function k(e,t,a){let o=e.flags?.[t];if(typeof o==="string"&&o)return Number(o);return a}function C(e){let t={};if(e.locationCode!==void 0)t.location_code=e.locationCode;else t.location_name=e.locationName??"United States";if(e.languageCode!==void 0)t.language_code=e.languageCode;else t.language_name=e.languageName??"English";return t}var Vo={chatgpt:"ai_optimization/chat_gpt/llm_responses/live",claude:"ai_optimization/claude/llm_responses/live",gemini:"ai_optimization/gemini/llm_responses/live",perplexity:"ai_optimization/perplexity/llm_responses/live"};async function ue(e){return f("ai_optimization/ai_keyword_data/keywords_search_volume/live",{...C(e),keywords:e.keywords})}async function ve(e){return f("ai_optimization/llm_mentions/search/live",{...C(e),target:e.keywords.map((t)=>({keyword:t}))})}async function _e(e){return f("ai_optimization/llm_mentions/top_pages/live",{...C(e),target:e.keywords.map((t)=>({keyword:t}))})}async function ye(e){return f("ai_optimization/llm_mentions/top_domains/live",{...C(e),target:e.keywords.map((t)=>({keyword:t}))})}async function ke(e){return f("ai_optimization/llm_mentions/aggregated_metrics/live",{...C(e),target:e.keywords.map((t)=>({keyword:t}))})}async function we(e){return f(Vo[e.model],{system_message:e.systemMessage,message_chain:[{role:"user",message:e.message}],max_output_tokens:e.maxOutputTokens??512,temperature:e.temperature??0.3,top_p:e.topP??0.5})}var R="ram",jo=c({name:"search-volume",resource:R,spec:new d({description:"AI-tool search volume — how often a keyword is typed at LLMs.",positional:[h("keywords",{variadic:!0})],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await ue({..._(o),keywords:[...a]});return p(s,o)}}),Wo=c({name:"mentions",resource:R,spec:new d({description:"Search LLM mentions for one or more keyword targets.",positional:[h("keywords",{variadic:!0})],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await ve({..._(o),keywords:[...a]});return p(s,o)}}),Xo=c({name:"top-pages",resource:R,spec:new d({description:"Top pages cited by AI for the given keyword targets.",positional:[h("keywords",{variadic:!0})],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await _e({..._(o),keywords:[...a]});return p(s,o)}}),Jo=c({name:"top-domains",resource:R,spec:new d({description:"Top domains cited by AI for the given keyword targets.",positional:[h("keywords",{variadic:!0})],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await ye({..._(o),keywords:[...a]});return p(s,o)}}),$o=c({name:"metrics",resource:R,spec:new d({description:"Aggregated LLM mention metrics (volume, sentiment) for keyword targets.",positional:[h("keywords",{variadic:!0})],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await ke({..._(o),keywords:[...a]});return p(s,o)}}),Qo=c({name:"ask",resource:R,spec:new d({description:"Ask a specific LLM via DataForSEO's metered proxy.",positional:[h("message")],options:[new n({long:"model",valueKind:r.TEXT,description:"chatgpt | claude | gemini | perplexity.",defaultValue:"chatgpt"}),new n({long:"system",valueKind:r.TEXT,description:"Optional system message."}),new n({long:"max-tokens",valueKind:r.TEXT,description:"Max output tokens (default 512).",defaultValue:"512"}),new n({long:"temperature",valueKind:r.TEXT,description:"Sampling temperature (default 0.3).",defaultValue:"0.3"}),...l]}),fn:async(e,t,a,o)=>{let s=v(o,"model","chatgpt"),i=v(o,"system")||void 0,g=await we({model:s,message:a[0]??"",systemMessage:i,maxOutputTokens:k(o,"max-tokens",512),temperature:Number(v(o,"temperature","0.3"))});return p(g,o)}}),be=b({name:"ai",description:"AI Optimization: LLM mentions, top pages/domains, AI search volume, LLM proxy.",commands:[jo,Wo,Xo,Jo,$o,Qo]});async function Te(e){return f("backlinks/summary/live",{target:e})}async function Ie(e){return f("backlinks/backlinks/live",{target:e.target,limit:e.limit??100,mode:e.mode??"as_is"})}async function Se(e){return f("backlinks/referring_domains/live",{target:e.target,limit:e.limit??100})}async function Ae(e){return f("backlinks/anchors/live",{target:e.target,limit:e.limit??100})}async function Le(e){return f("backlinks/competitors/live",{target:e.target,limit:e.limit??100})}async function Ge(e){return f("backlinks/bulk_ranks/live",{targets:e})}var O="ram",K=new n({long:"limit",valueKind:r.TEXT,description:"Max results.",defaultValue:"100"}),Zo=c({name:"summary",resource:O,spec:new d({description:"High-level backlink summary for a target.",positional:[h("target")],options:[...l]}),fn:async(e,t,a,o)=>{let s=await Te(a[0]??"");return p(s,o)}}),et=c({name:"list",resource:O,spec:new d({description:"List individual backlinks.",positional:[h("target")],options:[K,new n({long:"mode",valueKind:r.TEXT,description:"as_is | one_per_domain | one_per_anchor.",defaultValue:"as_is"}),...l]}),fn:async(e,t,a,o)=>{let s=await Ie({target:a[0]??"",limit:k(o,"limit",100),mode:v(o,"mode","as_is")});return p(s,o)}}),ot=c({name:"referring-domains",resource:O,spec:new d({description:"Referring domains pointing to a target.",positional:[h("target")],options:[K,...l]}),fn:async(e,t,a,o)=>{let s=await Se({target:a[0]??"",limit:k(o,"limit",100)});return p(s,o)}}),tt=c({name:"anchors",resource:O,spec:new d({description:"Anchor text distribution for a target.",positional:[h("target")],options:[K,...l]}),fn:async(e,t,a,o)=>{let s=await Ae({target:a[0]??"",limit:k(o,"limit",100)});return p(s,o)}}),at=c({name:"competitors",resource:O,spec:new d({description:"Domains with similar backlink profiles.",positional:[h("target")],options:[K,...l]}),fn:async(e,t,a,o)=>{let s=await Le({target:a[0]??"",limit:k(o,"limit",100)});return p(s,o)}}),st=c({name:"ranks",resource:O,spec:new d({description:"Bulk DataForSEO domain rank for up to 1000 targets.",positional:[h("targets",{variadic:!0})],options:[...l]}),fn:async(e,t,a,o)=>{let s=await Ge([...a]);return p(s,o)}}),xe=b({name:"backlinks",description:"Backlink profiles, referring domains, anchors.",commands:[Zo,et,ot,tt,at,st]});var Ue=[{path:"/v3/serp/id_list",method:"post",operationId:"IdList",tag:"Serp",description:`This endpoint is designed to provide you with a list of IDs and metadata for all SERP tasks created within the specified time period, including both successful and uncompleted tasks.
|
|
31
10
|
for more info please visit 'https://docs.dataforseo.com/v3/serp/id_list/?bash'`,docUrl:"https://docs.dataforseo.com/v3/serp/id_list/",example:[{datetime_from:"2026-04-12 04:39:39 +00:00",datetime_to:"2026-04-14 04:39:39 +00:00",limit:100,offset:0,sort:"desc",include_metadata:!0}]},{path:"/v3/serp/errors",method:"post",operationId:"Errors",tag:"Serp",description:`By calling this endpoint you will receive information about the SERP API tasks that returned an error within the past 7 days.
|
|
32
11
|
for more info please visit 'https://docs.dataforseo.com/v3/serp/errors/?bash'`,docUrl:"https://docs.dataforseo.com/v3/serp/errors/",example:[{limit:10,offset:0,filtered_function:"pingback_url"}]},{path:"/v3/serp/screenshot",method:"post",operationId:"Screenshot",tag:"Serp",description:`Using the Live Page Screenshot endpoint, you can capture a screenshot of any SERP page.
|
|
33
12
|
for more info please visit 'https://docs.dataforseo.com/v3/serp/screenshot/?bash'`,docUrl:"https://docs.dataforseo.com/v3/serp/screenshot/",example:[{task_id:"06211235-0696-0139-1000-36727fbd3c90",browser_screen_scale_factor:0.5}]},{path:"/v3/serp/ai_summary",method:"post",operationId:"AiSummary",tag:"Serp",description:`The purpose of the Live SERP API AI Summary endpoint is to provide a summary of the content found on any SERP and generate a response based on the user’s specified prompt.
|
|
@@ -659,12 +638,12 @@ for more info please visit 'https://docs.dataforseo.com/v3/appendix/user_data/?b
|
|
|
659
638
|
for more info please visit 'https://docs.dataforseo.com/v3/appendix/errors/?bash'`,docUrl:"https://docs.dataforseo.com/v3/appendix/errors/"},{path:"/v3/appendix/webhook_resend",method:"post",operationId:"WebhookResend",tag:"Appendix",description:`Using this endpoint you can resend webhooks (pingbacks and postbacks) for up to 100 specified tasks.
|
|
660
639
|
Note: Your account will not be double-charged for resending a webhook.
|
|
661
640
|
for more info please visit 'https://docs.dataforseo.com/v3/appendix/webhook_resend/?bash'`,docUrl:"https://docs.dataforseo.com/v3/appendix/webhook_resend/",example:[{id:"08161139-0001-0066-1000-06491d097ed5"}]},{path:"/v3/appendix/status",method:"get",operationId:"AppendixStatus",tag:"Appendix",description:`By calling this API you will receive detailed information about the current status of all our APIs and endpoints. You will also get a full issue description if a problem occurs.
|
|
662
|
-
for more info please visit 'https://docs.dataforseo.com/v3/appendix/status/?bash'`,docUrl:"https://docs.dataforseo.com/v3/appendix/status/"}];var
|
|
663
|
-
`),new
|
|
664
|
-
`);return[
|
|
665
|
-
`),new
|
|
641
|
+
for more info please visit 'https://docs.dataforseo.com/v3/appendix/status/?bash'`,docUrl:"https://docs.dataforseo.com/v3/appendix/status/"}];var $=Ue;function Pe(){return $}function M(e){let t=De(e);return $.find((a)=>De(a.path)===t)}function Ee(e,t){let a=e.toLowerCase();return $.filter((o)=>{if(t&&o.tag?.toLowerCase()!==t.toLowerCase())return!1;if(!a)return!0;return o.path.toLowerCase().includes(a)||o.operationId?.toLowerCase().includes(a)||o.description?.toLowerCase().includes(a)})}function De(e){let t=e.trim();if(!t.startsWith("/"))t="/"+t;if(!t.startsWith("/v3/"))t="/v3"+t;return t.replace(/\/+$/,"")}var Q="ram",N=new TextEncoder,rt=c({name:"list",resource:Q,spec:new d({description:"List endpoints, optionally filtered by tag and/or query.",options:[new n({short:"t",long:"tag",valueKind:r.TEXT,description:"Filter by tag."}),new n({short:"q",long:"query",valueKind:r.TEXT,description:"Substring match."}),new n({long:"json",valueKind:r.NONE,description:"Emit JSON instead of lines."})]}),fn:async(e,t,a,o)=>{let s=v(o,"tag")||void 0,i=Ee(v(o,"query",""),s);if(T(o,"json"))return[N.encode(JSON.stringify(i,null,2)+`
|
|
642
|
+
`),new w];let g=i.map((m)=>`${m.method.toUpperCase().padEnd(4)} ${m.path}`).join(`
|
|
643
|
+
`);return[N.encode(g+`
|
|
644
|
+
`),new w({stderr:`
|
|
666
645
|
(${i.length} endpoints)
|
|
667
|
-
`})]}}),
|
|
646
|
+
`})]}}),nt=c({name:"show",resource:Q,spec:new d({description:"Show details for one endpoint.",positional:[h("path")]}),fn:async(e,t,a)=>{let o=a[0]??"",s=M(o);if(!s)return[null,new w({exitCode:1,stderr:`No endpoint matches ${o}
|
|
668
647
|
`})];let i=`${s.method.toUpperCase()} ${s.path}
|
|
669
648
|
`;if(s.tag)i+=`tag: ${s.tag}
|
|
670
649
|
`;if(s.operationId)i+=`operationId: ${s.operationId}
|
|
@@ -674,14 +653,14 @@ ${s.description}
|
|
|
674
653
|
`;if(s.example!==void 0)i+=`
|
|
675
654
|
example body:
|
|
676
655
|
${JSON.stringify(s.example,null,2)}
|
|
677
|
-
`;return[
|
|
678
|
-
`);return[
|
|
679
|
-
`),new
|
|
656
|
+
`;return[N.encode(i),new w]}}),dt=c({name:"tags",resource:Q,spec:new d({description:"List all tags and how many endpoints each has."}),fn:async()=>{let e=new Map;for(let o of Pe()){let s=o.tag??"(untagged)";e.set(s,(e.get(s)??0)+1)}let a=[...e.entries()].sort((o,s)=>s[1]-o[1]).map(([o,s])=>`${String(s).padStart(4)} ${o}`).join(`
|
|
657
|
+
`);return[N.encode(a+`
|
|
658
|
+
`),new w]}}),Re=b({name:"endpoints",description:"Discover and inspect DataForSEO endpoints.",commands:[rt,nt,dt]});function H(e){let t={};if(e.locationCode!==void 0)t.location_code=e.locationCode;else t.location_name=e.locationName??"United States";if(e.languageCode!==void 0)t.language_code=e.languageCode;else t.language_name=e.languageName??"English";return t}async function Oe(e){return f("keywords_data/google_ads/search_volume/live",{...H(e),keywords:e.keywords,include_serp_info:e.includeSerpInfo??!1})}async function ze(e){return f("dataforseo_labs/google/keyword_ideas/live",{...H(e),keywords:e.keywords,limit:e.limit??100})}async function Ce(e){return f("dataforseo_labs/google/keyword_suggestions/live",{...H(e),keyword:e.keyword,limit:e.limit??100})}async function Be(e){return f("dataforseo_labs/google/ranked_keywords/live",{...H(e),target:e.target,limit:e.limit??100})}var V="ram";function j(e){return _(e)}var ct=c({name:"search-volume",resource:V,spec:new d({description:"Get monthly search volume / CPC / competition for keywords.",positional:[h("keywords",{variadic:!0})],options:[...y,new n({long:"include-serp-info",valueKind:r.NONE,description:"Also return SERP feature snapshot."}),...l]}),fn:async(e,t,a,o)=>{let s=await Oe({...j(o),keywords:[...a],includeSerpInfo:T(o,"include-serp-info")});return p(s,o)}}),lt=c({name:"ideas",resource:V,spec:new d({description:"Get keyword ideas (DataForSEO Labs).",positional:[h("keywords",{variadic:!0})],options:[...y,new n({long:"limit",valueKind:r.TEXT,description:"Max results.",defaultValue:"100"}),...l]}),fn:async(e,t,a,o)=>{let s=await ze({...j(o),keywords:[...a],limit:k(o,"limit",100)});return p(s,o)}}),pt=c({name:"suggestions",resource:V,spec:new d({description:"Get keyword suggestions for a seed keyword.",positional:[h("keyword")],options:[...y,new n({long:"limit",valueKind:r.TEXT,description:"Max results.",defaultValue:"100"}),...l]}),fn:async(e,t,a,o)=>{let s=await Ce({...j(o),keyword:a[0]??"",limit:k(o,"limit",100)});return p(s,o)}}),ht=c({name:"ranked",resource:V,spec:new d({description:"Keywords a target domain or URL ranks for.",positional:[h("target")],options:[...y,new n({long:"limit",valueKind:r.TEXT,description:"Max results.",defaultValue:"100"}),...l]}),fn:async(e,t,a,o)=>{let s=await Be({...j(o),target:a[0]??"",limit:k(o,"limit",100)});return p(s,o)}}),Fe=b({name:"keywords",description:"Search volume, ideas, suggestions.",commands:[ct,lt,pt,ht]});function x(e){let t={};if(e.locationCode!==void 0)t.location_code=e.locationCode;else t.location_name=e.locationName??"United States";if(e.languageCode!==void 0)t.language_code=e.languageCode;else t.language_name=e.languageName??"English";return t}async function Ye(e){return f("dataforseo_labs/google/competitors_domain/live",{...x(e),target:e.target,limit:e.limit??100})}async function qe(e){return f("dataforseo_labs/google/domain_intersection/live",{...x(e),target1:e.target1,target2:e.target2,limit:e.limit??100})}async function Ke(e){return f("dataforseo_labs/google/domain_rank_overview/live",{...x(e),target:e.target})}async function Me(e){return f("dataforseo_labs/google/related_keywords/live",{...x(e),keyword:e.keyword,limit:e.limit??100})}async function Ne(e){return f("dataforseo_labs/google/keyword_overview/live",{...x(e),keywords:e.keywords,include_serp_info:e.includeSerpInfo??!1,include_clickstream_data:e.includeClickstream??!1})}async function He(e){return f("dataforseo_labs/google/bulk_keyword_difficulty/live",{...x(e),keywords:e.keywords})}async function Ve(e){return f("dataforseo_labs/google/search_intent/live",{...x(e),keywords:e.keywords})}async function je(e){return f("dataforseo_labs/google/top_searches/live",{...x(e),limit:e.limit??100})}async function We(e){return f("dataforseo_labs/google/historical_rank_overview/live",{...x(e),target:e.target})}var U="ram",W=new n({long:"limit",valueKind:r.TEXT,description:"Max results.",defaultValue:"100"}),gt=c({name:"competitors",resource:U,spec:new d({description:"Domains competing with the target on organic search.",positional:[h("target")],options:[...y,W,...l]}),fn:async(e,t,a,o)=>{let s=await Ye({..._(o),target:a[0]??"",limit:k(o,"limit",100)});return p(s,o)}}),mt=c({name:"intersection",resource:U,spec:new d({description:"Keyword overlap between two domains.",positional:[h("target1"),h("target2")],options:[...y,W,...l]}),fn:async(e,t,a,o)=>{let s=await qe({..._(o),target1:a[0]??"",target2:a[1]??"",limit:k(o,"limit",100)});return p(s,o)}}),ft=c({name:"overview",resource:U,spec:new d({description:"Domain rank overview (organic + paid traffic estimates).",positional:[h("target")],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await Ke({..._(o),target:a[0]??""});return p(s,o)}}),ut=c({name:"related",resource:U,spec:new d({description:"Semantically related keywords.",positional:[h("keyword")],options:[...y,W,...l]}),fn:async(e,t,a,o)=>{let s=await Me({..._(o),keyword:a[0]??"",limit:k(o,"limit",100)});return p(s,o)}}),vt=c({name:"keyword-overview",resource:U,spec:new d({description:"Full keyword profile: KD + volume + intent + SERP + backlinks for keywords.",positional:[h("keywords",{variadic:!0})],options:[...y,new n({long:"include-serp-info",valueKind:r.NONE,description:"Include SERP feature snapshot."}),new n({long:"include-clickstream",valueKind:r.NONE,description:"Include clickstream-derived volume."}),...l]}),fn:async(e,t,a,o)=>{let s=await Ne({..._(o),keywords:[...a],includeSerpInfo:T(o,"include-serp-info"),includeClickstream:T(o,"include-clickstream")});return p(s,o)}}),_t=c({name:"bulk-difficulty",resource:U,spec:new d({description:"Bulk keyword difficulty (KD) for up to 1000 keywords in one call.",positional:[h("keywords",{variadic:!0})],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await He({..._(o),keywords:[...a]});return p(s,o)}}),yt=c({name:"intent",resource:U,spec:new d({description:"Classify search intent (informational/navigational/commercial/transactional) for keywords.",positional:[h("keywords",{variadic:!0})],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await Ve({..._(o),keywords:[...a]});return p(s,o)}}),kt=c({name:"top-searches",resource:U,spec:new d({description:"Currently-trending top searches in a location.",options:[...y,W,...l]}),fn:async(e,t,a,o)=>{let s=await je({..._(o),limit:k(o,"limit",100)});return p(s,o)}}),wt=c({name:"historical",resource:U,spec:new d({description:"Historical rank overview for a domain (month-by-month position counts).",positional:[h("target")],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await We({..._(o),target:a[0]??""});return p(s,o)}}),Xe=b({name:"labs",description:"DataForSEO Labs: competitors, gap analysis, keyword overview, intent, historical.",commands:[gt,mt,ft,ut,vt,_t,yt,kt,wt]});var Je="ram",$e=new TextEncoder,Qe=c({name:"login",resource:Je,spec:new d({description:"Save DataForSEO credentials to ~/.config/dataforseo/config.json (chmod 600).",options:[new n({short:"l",long:"login",valueKind:r.TEXT,description:"API login (email).",required:!0}),new n({short:"p",long:"password",valueKind:r.TEXT,description:"API password.",required:!0}),new n({long:"no-verify",valueKind:r.NONE,description:"Skip the verification call."})]}),fn:async(e,t,a,o)=>{let s=v(o,"login"),i=v(o,"password");if(!T(o,"no-verify")){process.env.DATAFORSEO_LOGIN=s,process.env.DATAFORSEO_PASSWORD=i;try{await G("/v3/appendix/user_data")}catch(m){return[null,new w({exitCode:1,stderr:`Credentials rejected: ${m.message}
|
|
680
659
|
Run with --no-verify to save anyway.
|
|
681
|
-
`})]}}let
|
|
682
|
-
`),new
|
|
683
|
-
config: ${
|
|
684
|
-
`,
|
|
685
|
-
`;return[
|
|
686
|
-
`})];let i=
|
|
660
|
+
`})]}}let g=ce({login:s,password:i});return[$e.encode(`Saved credentials to ${g}
|
|
661
|
+
`),new w]}}),Ze=c({name:"whoami",resource:Je,spec:new d({description:"Show the configured login (and verify against DataForSEO)."}),fn:async()=>{let t=`login: ${z().login}
|
|
662
|
+
config: ${de()}
|
|
663
|
+
`,o=(await G("/v3/appendix/user_data")).tasks?.[0]?.result?.[0];if(o?.money?.balance!==void 0)t+=`balance: $${o.money.balance.toFixed(2)}
|
|
664
|
+
`;return[$e.encode(t),new w]}});async function eo(e="serp/google"){return G(`${e}/locations`)}async function oo(e="serp/google"){return G(`${e}/languages`)}async function to(){return G("/v3/appendix/user_data")}var Z="ram",ao=c({name:"locations",resource:Z,spec:new d({description:"List supported locations for a given API.",options:[new n({long:"api",valueKind:r.TEXT,description:"API path under /v3.",defaultValue:"serp/google"}),...l]}),fn:async(e,t,a,o)=>{let s=await eo(v(o,"api","serp/google"));return p(s,o)}}),so=c({name:"languages",resource:Z,spec:new d({description:"List supported languages for a given API.",options:[new n({long:"api",valueKind:r.TEXT,description:"API path under /v3.",defaultValue:"serp/google"}),...l]}),fn:async(e,t,a,o)=>{let s=await oo(v(o,"api","serp/google"));return p(s,o)}}),io=c({name:"user",resource:Z,spec:new d({description:"Show DataForSEO account info (balance, plan, limits).",options:[...l]}),fn:async(e,t,a,o)=>{let s=await to();return p(s,{...o,flags:{...o.flags,full:!0}})}});import{readFileSync as bt}from"node:fs";var Tt="ram",ro=c({name:"raw",resource:Tt,spec:new d({description:"Hit any DataForSEO endpoint by path (escape hatch over the full 437-endpoint API).",positional:[h("path")],options:[new n({short:"d",long:"data",valueKind:r.TEXT,description:"Inline JSON body."}),new n({short:"f",long:"data-file",valueKind:r.TEXT,description:"Read JSON body from file. '-' for stdin."}),new n({long:"kv",valueKind:r.TEXT,description:"Shorthand body fields, comma-separated, e.g. keyword=seo,location_code=2840."}),new n({long:"example",valueKind:r.NONE,description:"Use the spec's example body."}),new n({long:"method",valueKind:r.TEXT,description:"Override HTTP method."}),new n({long:"no-wrap",valueKind:r.NONE,description:"Don't auto-wrap a single task as [task]."}),...l],rest:new E({kind:r.TEXT,name:"kvpairs"})}),fn:async(e,t,a,o)=>{let s=a[0]??"";if(!s)return[null,new w({exitCode:2,stderr:`raw: missing <path>
|
|
665
|
+
`})];let i=M(s),m=(v(o,"method")||i?.method||"post").toLowerCase(),u=await It(o,i?.example,a.slice(1)),I;if(m==="get")I=await G(s);else I=await f(s,u,{wrapAsTaskArray:!T(o,"no-wrap")});return p(I,o)}});async function It(e,t,a){if(T(e,"example")){if(t===void 0)throw Error("No example body in spec for this endpoint.");return t}let o=v(e,"data");if(o)return JSON.parse(o);let s=v(e,"data-file");if(s){let m=s==="-"?await Lt():bt(s,"utf8");return JSON.parse(m)}let i=v(e,"kv"),g=[];if(i)g.push(...i.split(","));if(g.push(...a.filter((m)=>m.includes("="))),g.length>0)return St(g);return}function St(e){let t={};for(let a of e){let o=a.indexOf("=");if(o===-1)continue;t[a.slice(0,o).trim()]=At(a.slice(o+1))}return t}function At(e){if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(/^-?\d+$/.test(e))return Number(e);if(/^-?\d*\.\d+$/.test(e))return Number(e);if(e.startsWith("[")&&e.endsWith("]")||e.startsWith("{")&&e.endsWith("}"))try{return JSON.parse(e)}catch{return e}return e}async function Lt(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function B(e){let t={};if(e.locationCode!==void 0)t.location_code=e.locationCode;else t.location_name=e.locationName??"United States";if(e.languageCode!==void 0)t.language_code=e.languageCode;else t.language_name=e.languageName??"English";return t}async function no(e){let t=e.advanced?"serp/google/organic/live/advanced":"serp/google/organic/live/regular";return f(t,{...B(e),keyword:e.keyword,device:e.device??"desktop",depth:e.depth??100})}async function co(e){return f("serp/google/maps/live/advanced",{...B(e),keyword:e.keyword,device:e.device??"desktop",depth:e.depth??100})}async function lo(e){return f("serp/youtube/organic/live/advanced",{...B(e),keyword:e.keyword,depth:e.depth??100})}async function po(e){return f("serp/google/news/live/advanced",{...B(e),keyword:e.keyword,device:e.device??"desktop",depth:e.depth??100})}async function ho(e){return f("serp/google/images/live/advanced",{...B(e),keyword:e.keyword,device:e.device??"desktop",depth:e.depth??100})}var F="ram",Y=[...y,new n({long:"device",valueKind:r.TEXT,description:"desktop | mobile.",defaultValue:"desktop"}),new n({long:"depth",valueKind:r.TEXT,description:"Result depth.",defaultValue:"100"})],Gt=c({name:"organic",resource:F,spec:new d({description:"Live Google organic SERP for a keyword.",positional:[h("keyword")],options:[...Y,new n({long:"advanced",valueKind:r.NONE,description:"Use the advanced endpoint with featured snippet detail."}),...l]}),fn:async(e,t,a,o)=>{let s=await no({..._(o),keyword:a[0]??"",device:v(o,"device","desktop"),depth:k(o,"depth",100),advanced:T(o,"advanced")});return p(s,o)}}),xt=c({name:"maps",resource:F,spec:new d({description:"Google Maps / local pack results.",positional:[h("keyword")],options:[...Y,...l]}),fn:async(e,t,a,o)=>{let s=await co({..._(o),keyword:a[0]??"",device:v(o,"device","desktop"),depth:k(o,"depth",100)});return p(s,o)}}),Ut=c({name:"news",resource:F,spec:new d({description:"Google News results for a keyword.",positional:[h("keyword")],options:[...Y,...l]}),fn:async(e,t,a,o)=>{let s=await po({..._(o),keyword:a[0]??"",device:v(o,"device","desktop"),depth:k(o,"depth",100)});return p(s,o)}}),Dt=c({name:"images",resource:F,spec:new d({description:"Google Images results for a keyword.",positional:[h("keyword")],options:[...Y,...l]}),fn:async(e,t,a,o)=>{let s=await ho({..._(o),keyword:a[0]??"",device:v(o,"device","desktop"),depth:k(o,"depth",100)});return p(s,o)}}),Pt=c({name:"organic",resource:F,spec:new d({description:"YouTube organic search results.",positional:[h("keyword")],options:[...Y,...l]}),fn:async(e,t,a,o)=>{let s=await lo({..._(o),keyword:a[0]??"",depth:k(o,"depth",100)});return p(s,o)}}),go=b({name:"serp",description:"SERP queries against Google / YouTube.",groups:[b({name:"google",description:"Google SERPs.",commands:[Gt,xt,Ut,Dt]}),b({name:"youtube",description:"YouTube SERPs.",commands:[Pt]})]});function ee(e){let t={};if(e.locationCode!==void 0)t.location_code=e.locationCode;else t.location_name=e.locationName??"United States";if(e.languageCode!==void 0)t.language_code=e.languageCode;return t}async function mo(e){return f("keywords_data/google_trends/explore/live",{...ee(e),keywords:e.keywords,type:e.type??"web",date_from:e.dateFrom,date_to:e.dateTo})}async function fo(e){return f("keywords_data/dataforseo_trends/demography/live",{...ee(e),keywords:e.keywords})}async function uo(e){return f("keywords_data/dataforseo_trends/subregion_interests/live",{...ee(e),keywords:e.keywords})}var oe="ram",Et=c({name:"explore",resource:oe,spec:new d({description:"Google Trends 'Explore' — popularity time series for keywords.",positional:[h("keywords",{variadic:!0})],options:[...y,new n({long:"type",valueKind:r.TEXT,description:"web | news | youtube | images | shopping.",defaultValue:"web"}),new n({long:"date-from",valueKind:r.TEXT,description:"Start date (YYYY-MM-DD)."}),new n({long:"date-to",valueKind:r.TEXT,description:"End date (YYYY-MM-DD)."}),...l]}),fn:async(e,t,a,o)=>{let s=await mo({..._(o),keywords:[...a],type:v(o,"type","web"),dateFrom:v(o,"date-from")||void 0,dateTo:v(o,"date-to")||void 0});return p(s,o)}}),Rt=c({name:"demography",resource:oe,spec:new d({description:"Age/gender demographics for keyword interest (DataForSEO Trends).",positional:[h("keywords",{variadic:!0})],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await fo({..._(o),keywords:[...a]});return p(s,o)}}),Ot=c({name:"subregion",resource:oe,spec:new d({description:"Regional popularity heatmap for keywords (DataForSEO Trends).",positional:[h("keywords",{variadic:!0})],options:[...y,...l]}),fn:async(e,t,a,o)=>{let s=await uo({..._(o),keywords:[...a]});return p(s,o)}}),vo=b({name:"trends",description:"Google Trends + DataForSEO Trends (time series, demography, region).",commands:[Et,Rt,Ot]});function _o(){let e=new zt;return e.name("dfs").description("Ergonomic CLI for the DataForSEO API.\n\nCurated commands cover ~40 high-value endpoints.\nUse `dfs raw <path>` to hit any of the 437 endpoints by path,\nand `dfs endpoints list` / `dfs endpoints show` to discover them.").version("0.3.0"),e.addCommand(L(Qe)),e.addCommand(L(Ze)),e.addCommand(L(ao)),e.addCommand(L(so)),e.addCommand(L(io)),e.addCommand(L(ro)),S(e,Fe),S(e,go),S(e,xe),S(e,Xe),S(e,be),S(e,vo),S(e,Re),e}_o().parseAsync(process.argv).catch((e)=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(JSON.stringify({error:t})+`
|
|
687
666
|
`),process.exit(1)});
|