util#inspect TypeScript Examples

The following examples show how to use util#inspect. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: run.ts    From dt-mergebot with MIT License 6 votes vote down vote up
show = (name: string, value: unknown) => {
    console.log(`  === ${name} ===`);
    value = xform(value, (s: string) =>
        s.replace(/\n---+\s*<details><summary>(Diagnostic Information)[^]*?<\/details>/g, "...$1..."));
    let str = args.format === "json" ? JSON.stringify(value, undefined, 2)
        : args.format === "yaml" ? render(value)
        : inspect(value, { depth: null, colors: true });
    str = str.replace(/^/mg, "  ");
    console.log(str);
}
Example #2
Source File: torrent.ts    From cross-seed with Apache License 2.0 6 votes vote down vote up
export async function getTorrentByCriteria(
	criteria: TorrentLocator
): Promise<Metafile> {
	await indexNewTorrents();

	const findResult = db.data.indexedTorrents.find(
		(e) =>
			(!criteria.infoHash || criteria.infoHash === e.infoHash) &&
			(!criteria.name || criteria.name === e.name)
	);
	if (findResult === undefined) {
		const message = `could not find a torrent with the criteria ${inspect(
			criteria
		)}`;
		throw new Error(message);
	}
	return parseTorrentFromFilename(findResult.filepath);
}
Example #3
Source File: Logger.ts    From l2beat with MIT License 6 votes vote down vote up
function getPrettyParameters(parameters: LoggerParameters | undefined) {
  if (parameters === undefined) {
    return ''
  }
  const previous = inspect.styles
  const newStyles = { ...previous }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  ;(newStyles as any).name = 'magenta'
  newStyles.string = ''
  newStyles.number = ''
  newStyles.boolean = ''
  inspect.styles = newStyles
  const str = ` ${inspect(parameters, { colors: true, breakLength: Infinity })}`
  inspect.styles = previous
  if (str === ' {}') {
    return ''
  }
  return str
}
Example #4
Source File: Logger.ts    From fsxa-api with Apache License 2.0 6 votes vote down vote up
formatOutput = (...args: any[]) => {
  args = args.map((entry) => {
    if (typeof entry === 'object') return JSON.stringify(entry)
    return entry
  })
  return inspect(args.join(' | '), {
    showHidden: false,
    depth: null,
    colors: false,
    compact: true,
    breakLength: Infinity,
  }).replace(/\'/g, '')
}
Example #5
Source File: Admiral.ts    From eris-fleet with MIT License 6 votes vote down vote up
private emitLog(type: "log" | "info" | "error" | "warn" | "debug", message: unknown, source?: string) {
		let log = message;
		if (this.objectLogging) {
			log = {
				source,
				message: message,
				timestamp: new Date().getTime(),
			};
		} else {
			if (source) {
				log = `${source} | ${typeof message === "string" ? message : inspect(message)}`;
			}
		}
		this.emit(type, log);
	}
Example #6
Source File: netmd.ts    From netmd-js with GNU General Public License v2.0 6 votes vote down vote up
public async readReply(useFactoryCommand: boolean = false) {
        let { len } = await this.getReplyLength();
        let i = 0;
        while (len === 0) {
            await sleep(NetMD.readReplyRetryIntervalInMsec * Math.pow(2, ~~(i / 10))); // Double wait time every 10 attempts
            ({ len } = await this.getReplyLength());
            i++;
        }

        let result = await this.device.controlTransferIn(
            {
                requestType: 'vendor',
                recipient: 'interface',
                request: useFactoryCommand ? 0xff : 0x81,
                value: 0,
                index: 0,
            },
            len
        );
        this.logger?.debug({ action: 'readReply', result: inspect(result) });
        return result;
    }
Example #7
Source File: log.ts    From project-loved-web with MIT License 6 votes vote down vote up
export function systemLog(message: unknown, level: SyslogLevel): void {
  if (config.syslogLevelPrefix) {
    if (typeof message !== 'string') {
      message = inspect(message, { depth: null });
    }

    message = (message as string)
      .trim()
      .split('\n')
      .map((line) => `<${level}>${line}`)
      .join('\n');
  }

  if (level <= SyslogLevel.warning) {
    console.error(message);
  } else {
    console.log(message);
  }
}
Example #8
Source File: generalTools.ts    From smil-player with MIT License 6 votes vote down vote up
// seq-6a985ce1ebe94055895763ce85e1dcaf93cd9620
export function generateParentId(tagName: string, value: PlaylistElement): string {
	try {
		let clone = cloneDeep(value);
		removeNestedProperties(clone, parentGenerationRemove);
		return `${tagName}-${hashSortCoerce.hash(inspect(clone))}`;
	} catch (err) {
		debug('Error during parent generation: %O', err);
		return `${tagName}-undefined`;
	}
}
Example #9
Source File: conf.ts    From Pterodactyl-Discord-Bot with MIT License 6 votes vote down vote up
run: RunFunction = async (
    client,
    message,
    [action, key, ...value]
) => {
    if (action === 'edit') {
        if (!key) return message.reply('Please specify a key to edit');
        if (!defaultSettings[key])
            return message.reply('This key does not exist in the settings');
        if (value.length < 1)
            return message.reply('Please specify a new value');

        defaultSettings[key] = value.join(' ');

        client.settings.set('default', defaultSettings);
        message.reply(`${key} successfully edited to ${value.join(' ')}`);
    }
    // Display a key's default value
    else if (action === 'get') {
        if (!key) return message.reply('Please specify a key to view');
        if (!defaultSettings[key])
            return message.reply('This key does not exist in the settings');
        message.reply(
            `The value of ${key} is currently ${defaultSettings[key]}`
        );
    }
    // Display all default settings.
    else {
        await message.channel.send(
            `***__Bot Default Settings__***\n\`\`\`json\n${inspect(
                defaultSettings
            )}\n\`\`\``
        );
    }
}
Example #10
Source File: Logger.ts    From Advanced-Command-Handler with MIT License 6 votes vote down vote up
/**
	 * Log something in the console and transform the ColorResolvable into an ASCII Escape Sequence containing the color.
	 *
	 * @param text - The text to log.
	 * @param color - The color of the text.
	 * @param title - The title of the text.
	 * @internal
	 */
	protected static process(text: any, color: ColorResolvable = 'debug', title: string = '') {
		if (Logger.LEVEL === LogLevel.OFF) return;
		const datePart = `[${dayjs().format('YYYY/MM/DD HH:mm:ss.SSS')}]`;
		const titlePart = `[${title.toUpperCase()}]`;
		text = typeof text === 'object' ? inspect(text) : text.toString();
		let textPart = text as string;

		text = text
			.split(' ')
			.map((word: string) =>
				/\d/.test(word) && !/\x1b\[\d+((;\d+){1,4})?m/.test(word) ? word.replace(/\d+/, (match: string) => chalk.yellow(match)) : word
			)
			.join(' ');

		color = propertyInEnum(LogType, color) ?? color;
		text = `${Logger.setColor('#847270', datePart)}${Logger.setColor(color, `${titlePart} ${text + chalk.reset()}`)}`;
		console.log(text);
		Logger.savingFiles.forEach((s, index) => {
			if (!fs.existsSync(s)) {
				Logger.savingFiles.splice(index, 1);
				Logger.warn(`File ${Logger.setColor('violet', s)} not found, removed from files to save logs.`, 'LoggingWriter');
			} else {
				textPart = textPart.replace(/\[(\d{1,3};){0,6}\d{1,3}m/gm, '');
				fs.appendFileSync(s, `${datePart}${titlePart} ${textPart}\n`);
			}
		});
	}
Example #11
Source File: eval.ts    From steve with GNU General Public License v3.0 6 votes vote down vote up
// Eval the input
	private async eval(msg: KlasaMessage, code: string) {
		const { flagArgs: flags } = msg;
		code = code.replace(/[“”]/g, '"').replace(/[‘’]/g, "'");
		const stopwatch = new Stopwatch();
		// eslint-disable-next-line @typescript-eslint/init-declarations, one-var
		let success, syncTime, asyncTime, result, type;
		let thenable = false;
		try {
			if (flags.async) code = `(async () => {\n${code}\n})();`;
			// eslint-disable-next-line no-eval
			result = eval(code);
			syncTime = stopwatch.toString();
			type = new Type(result);
			if (util.isThenable(result)) {
				thenable = true;
				stopwatch.restart();
				result = await result;
				asyncTime = stopwatch.toString();
			}
			success = true;
		} catch (error) {
			if (!syncTime) syncTime = stopwatch.toString();
			if (!type) type = new Type(error);
			if (thenable && !asyncTime) asyncTime = stopwatch.toString();
			if (error && error.stack) this.client.emit('error', error.stack);
			result = error;
			success = false;
		}

		stopwatch.stop();
		if (typeof result !== 'string') {
			result = inspect(result, {
				depth: flags.depth ? parseInt(flags.depth, 10) || 0 : 0,
				showHidden: Boolean(flags.showHidden)
			});
		}
		return { success, type, time: this.formatTime(syncTime, asyncTime), result: util.clean(result) };
	}
Example #12
Source File: clipboardUtils.ts    From memo with MIT License 6 votes vote down vote up
/* These utils borrowed from https://github.com/andrewdotn/2md */

export function run(cmd: string, args: string[]): Promise<{ stdout: string; stderr: string }> {
  const proc = spawn(cmd, args, {
    stdio: ['ignore', 'pipe', 'pipe'],
  });

  const output = { stdout: '', stderr: '' };

  proc.stdio[1]!.on('data', (data) => (output.stdout += data));
  proc.stdio[2]!.on('data', (data) => (output.stderr += data));

  return new Promise((resolve, reject) => {
    proc.on('error', (e) => reject(e));
    proc.on('exit', (code, signal) => {
      if (code === 1 && /\(-1700\)$/m.test(output.stderr)) {
        return reject(new Error('The clipboard does not currently contain HTML-formatted data.'));
      }

      if (code !== 0 || signal) {
        return reject(
          new Error(`${inspect(cmd)} returned [${code}, ${signal}]; output was ${inspect(output)}`),
        );
      }

      return resolve(output);
    });
  });
}
Example #13
Source File: interactionCreate.ts    From steve with GNU General Public License v3.0 6 votes vote down vote up
public run(interaction: APIApplicationCommandInteraction) {
		switch (interaction.data.name) {
			case 'animal':
				this.client.emit(ApplicationCommands.Animal, interaction);
				break;
			case 'assign':
				this.client.emit(ApplicationCommands.Assign, interaction);
				break;
			case 'avatar':
				this.client.emit(ApplicationCommands.Avatar, interaction);
				break;
			case 'convert':
				this.client.emit(ApplicationCommands.Convert, interaction);
				break;
			case 'dftba':
				this.client.emit(ApplicationCommands.Dftba, interaction);
				break;
			case 'roleinfo':
				this.client.emit(ApplicationCommands.RoleInfo, interaction);
				break;
			case 'rps':
				this.client.emit(ApplicationCommands.Rps, interaction);
				break;
			case 'serverinfo':
				this.client.emit(ApplicationCommands.ServerInfo, interaction);
				break;
			case 'whois':
				this.client.emit(ApplicationCommands.Whois, interaction);
				break;
			default:
				this.client.console.log(inspect(interaction, { depth: 4 }));
		}
	}
Example #14
Source File: log-delivery.ts    From cloudformation-cli-typescript-plugin with Apache License 2.0 6 votes vote down vote up
constructor(defaultOptions: InspectOptions = {}) {
        // Allow passing Node.js inspect options,
        // and change default depth from 4 to 10
        inspect.defaultOptions = {
            ...inspect.defaultOptions,
            depth: 10,
            ...defaultOptions,
        };
    }
Example #15
Source File: layer-collection-facade.ts    From open-design-sdk with Apache License 2.0 5 votes vote down vote up
/** @internal */
  toString(): string {
    const layers = this.toJSON()
    return `DesignLayerCollection ${inspect(layers)}`
  }
Example #16
Source File: Eval.ts    From yumeko with GNU Affero General Public License v3.0 5 votes vote down vote up
@constantly
    public async eval(msg: Message, code: string,  depth: number, isAsync: boolean, isCanvas: boolean, showStack: boolean): Promise<ReturnEval> {
        const stopwatch = new Stopwatch();
        let isPromise = false;
        let succes = false;
        let promiseConstructor = "Promise";
        let syncTime: string|void;
        let asyncTime: string|void;
        let type: string|void;
        let result: any;
        try {
            if (isCanvas) {
                if (!code.startsWith("new Canvas")) throw new TypeError("Initialize new Canvas using 'new Canvas(width, height)'");
                isAsync = true;
                code = `return ${code}`;
            }
            // eslint-disable-next-line no-eval
            let evaled = eval(isAsync ? `(async () => { ${code} })()` : code);
            syncTime = stopwatch.toString();
            if (evaled instanceof Promise && typeof evaled.then === "function" && typeof evaled.catch === "function") {
                promiseConstructor = evaled.constructor.name;
                evaled = await evaled;
                isPromise = true;
                asyncTime = stopwatch.toString();
            }
            type = isPromise ? `${promiseConstructor}<${this.parseType(evaled)}>` : this.parseType(evaled);
            result = evaled;
            succes = true;
        } catch(e) {
            if (!syncTime) syncTime = stopwatch.toString();
            if (isPromise && !asyncTime) asyncTime = stopwatch.toString();
            if (!type) type = isPromise ? `${promiseConstructor}<${this.parseType(e)}>` : this.parseType(e);
            result = showStack ? e.stack : String(e);
        }
        if (result instanceof Canvas && isCanvas) result = await result.toBufferAsync();
        result = typeof result === "string" || (isCanvas && result instanceof Buffer && msg.guild!.me!.hasPermission("ATTACH_FILES")) ? result : inspect(result, { depth });
        if (typeof result === "string") result = this.replaceSensitive(result);
        const time = asyncTime ? `${syncTime}<${asyncTime}>` : syncTime;
        return { succes, result, time, type };
    }
Example #17
Source File: artboard-facade.ts    From open-design-sdk with Apache License 2.0 5 votes vote down vote up
/** @internal */
  toString(): string {
    const artboardInfo = this.toJSON()
    return `Artboard ${inspect(artboardInfo)}`
  }
Example #18
Source File: console.ts    From stellar-anchor-tests with Apache License 2.0 5 votes vote down vote up
inspect.styles.string = "yellow";
Example #19
Source File: setupTests.ts    From pybricks-code with MIT License 5 votes vote down vote up
// https://github.com/facebook/jest/issues/11698
function fail(reason: unknown): never {
    if (typeof reason === 'string') {
        throw new Error(reason);
    }
    throw new Error(inspect(reason));
}
Example #20
Source File: sdk.ts    From open-design-sdk with Apache License 2.0 5 votes vote down vote up
/** @internal */
  [inspect.custom](): string {
    return this.toString()
  }
Example #21
Source File: cmd.ts    From cross-seed with Apache License 2.0 5 votes vote down vote up
createCommandWithSharedOptions("search", "Search for cross-seeds")
	.requiredOption(
		"-o, --offset <offset>",
		"Offset to start from",
		(n) => parseInt(n),
		0
	)
	.requiredOption(
		"-d, --delay <delay>",
		"Pause duration (seconds) between searches",
		parseFloat,
		fallback(fileConfig.delay, 10)
	)
	.addOption(
		new Option(
			"--torrents <torrents...>",
			"torrent files separated by spaces. This is a debug option and may be removed without warning."
		).hideHelp()
	)
	.action(async (options) => {
		try {
			const runtimeConfig = processOptions(options);
			setRuntimeConfig(runtimeConfig);
			initializeLogger();
			initializePushNotifier();
			logger.verbose({
				label: Label.CONFIGDUMP,
				message: inspect(runtimeConfig),
			});
			if (process.env.DOCKER_ENV === "true") {
				generateConfig({ docker: true });
			}
			await doStartupValidation();
			await main();
		} catch (e) {
			if (e instanceof CrossSeedError) {
				e.print();
				process.exitCode = 1;
				return;
			}
			throw e;
		}
	});
Example #22
Source File: EvalCommand.ts    From Mandroc with GNU General Public License v3.0 5 votes vote down vote up
public async exec(message: Message, args: args) {
    let code = args.code;
    if (args.async || code.includes("await")) {
      code = `(async () => {${code}})()`;
    }
    message.member?.getProfile();

    let res;
    try {
      res = eval(code);
      if (isPromise(res)) res = await res;
    } catch (e) {
      const embed = new MessageEmbed()
        .setColor(Color.Danger)
        .setDescription([
          "Ran into an error while evaluating...",
          cb("js")`${e.stack}`
        ]);

      return message.util?.send(embed);
    }

    if (!args.silent) {
      if (typeof res !== "string") {
        res = inspect(res, {
          depth: args.depth,
          getters: true
        });
      }

      if (res.length >= 2048) {
        res = res.slice(0, 2000);
        res += "\n...";
      }

      res = res
        .replace(/[\w\d]{24}\.[\w\d]{6}\.[\w\d-_]{27}/g, (t: string) =>
          censorToken(t)
        )
        .replace(/`/g, `\`${String.fromCharCode(8203)}`)
        .replace(/@/g, `@${String.fromCharCode(8203)}`);

      const embed = new MessageEmbed()
        .setColor(Color.Primary)
        .setDescription(cb("js")`${res}`);

      return message.util?.send(embed);
    }

    return message.react("✅");
  }
Example #23
Source File: logger.ts    From express-zod-api with MIT License 5 votes vote down vote up
export function createLogger(loggerConfig: LoggerConfig): winston.Logger {
  const prettyPrint = (meta: any) => {
    delete meta[LEVEL];
    delete meta[MESSAGE];
    delete meta[SPLAT];
    return inspect(meta, false, 1, loggerConfig.color);
  };

  const getOutputFormat = (isPretty?: boolean) =>
    printf(
      ({ timestamp, message, level, durationMs, ...meta }) =>
        `${timestamp} ${level}: ${message}` +
        (durationMs === undefined ? "" : ` duration: ${durationMs}ms`) +
        (Object.keys(meta).length === 0
          ? ""
          : " " + (isPretty ? prettyPrint(meta) : JSON.stringify(meta)))
    );

  const formats: Format[] = [useTimestamp()];

  const consoleOutputOptions: Transport.TransportStreamOptions = {
    handleExceptions: true,
  };

  if (loggerConfig.color) {
    formats.push(colorize());
  }

  switch (loggerConfig.level) {
    case "debug":
      consoleOutputOptions.level = "debug";
      formats.push(getOutputFormat(true));
      break;
    case "silent":
    case "warn":
    default:
      consoleOutputOptions.level = "warn";
      formats.push(getOutputFormat());
  }

  consoleOutputOptions.format = combine(...formats);

  return winston.createLogger({
    silent: loggerConfig.level === "silent",
    levels: winston.config.npm.levels,
    transports: [new winston.transports.Console(consoleOutputOptions)],
    exitOnError: false,
  });
}
Example #24
Source File: Coordinates.ts    From sandstone with MIT License 5 votes vote down vote up
constructor(values: T) {
    if (!Array.isArray(values) || !values.every((i) => typeof i === 'string')) {
      throw new Error(`Expected array of string for Vector values, got ${inspect(values)}`)
    }

    this.values = values
  }
Example #25
Source File: main.ts    From WowUp with GNU General Public License v3.0 5 votes vote down vote up
app.on("child-process-gone", (e, details) => {
  log.warn("child-process-gone", inspect(details));
  if (details.reason === "killed") {
    app.quit();
  }
});
Example #26
Source File: Eval.ts    From Lavalink-Music-Bot with GNU Affero General Public License v3.0 5 votes vote down vote up
async exec(message: Message, args: string[]) {
        const code = args.join(" ");
        const { flags } = this.parseQuery(code);
        const embed = new MessageEmbed()
            .setTitle(`${this.client.user?.tag}'s Evaled`)
            .setColor("RANDOM")
            .addField("Input", `\`\`\`js\n${code}\`\`\``)
            .setFooter(`Request for ${message.author.tag}`, message.author.avatarURL({ dynamic: true }) as string);

        try {
            if (args.length < 1) return;
            let parsed = args.join(" ");
            let depth: any = 0;
            if (flags.includes("async")) {
                parsed = `(async() => {${parsed}})`;
            }
            if (flags.some((x: any) => x.inclues("dept"))) {
                depth = flags.find((x: any) => x.includes("dept").split("=")[1]);
                depth = parseInt(depth, 10);
            }

            let { evaled, type } = await this.parseEval(eval(parsed));
            if (flags.includes("silent")) return;

            if (typeof evaled !== "string") { evaled = inspect(evaled, { depth }); }
            evaled = evaled
                .replace(/`/g, `\`${String.fromCharCode(8203)}`)
                .replace(/@​/g, `@​${String.fromCharCode(8203)}`);
            evaled = evaled.replace(new RegExp(this.client.token!, "g"), "[REDACTED]");
            if (code.toLowerCase().includes("token")) return message.channel.send("トークンがありません");

            if (evaled.length > 1024) {
                const { body } = await req.post("http://tk-bin.glitch.me/documents").send(evaled) as any;
                embed.addField("Output", `http://tk-bin.glitch.me/${body.key}.js`);
                embed.addField("Type", typeof type);
            } else {
                embed.addField("Output", `\`\`\`js\n${evaled}\`\`\``);
                embed.addField("Type", typeof type);
            }
        } catch (e) {
            const error: any = (e);
            if (error.length > 1024) {
                const { body } = await req.post("http://tk-bin.glitch.me/documents").send(error) as any;
                embed.addField("Error", `http://tk-bin.glitch.me/${body.key}.js`);
            } else {
                embed.addField("Error", `\`\`\`js\n${error}\`\`\``);
            }
        }
        return message.channel.send({ embeds: [embed] });
    }
Example #27
Source File: typeCase.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
inspect() {
    return `${inspect(this.possibleTypes)} -> ${inspect(collectAndMergeFields(this, false).map(field => field.responseKey))} ${inspect(
      this.fragmentSpreads.map(fragmentSpread => fragmentSpread.fragmentName)
    )}\n`;
  }
Example #28
Source File: bots.test.ts    From js-sdk with MIT License 5 votes vote down vote up
describe("Bots Test", () => {
    let koreanbots: Koreanbots
    let botInfo: Bot

    beforeAll(async () => {
        koreanbots = new Koreanbots({
            clientID: process.env.CLIENT_ID!,
            api: {
                token: process.env.KOREANBOTS_TOKEN!,
                unstable: false 
            }
        })

        koreanbots.api.client.on("timeout", a => console.log(`Timeout: ${inspect(a)}`))
        koreanbots.api.client.on("rateLimit", a => console.log(`Rate limit: ${inspect(a)}`))

        botInfo = await koreanbots.bots.fetch(process.env.CLIENT_ID!)
    })

    afterAll(() => {
        koreanbots.api.client.destroy()

        koreanbots.users.cache.clear()
        koreanbots.widgets.cache.clear()
        koreanbots.bots.cache.clear()
    })

    it("should be able to fetch other bot information", async () => {
        expect(typeof botInfo).toBe("object")
        expect(botInfo.id).toBe(process.env.CLIENT_ID)

        const owners = await botInfo.owners.fetch()

        expect(owners.every(f => typeof f?.username === "string")).toBe(true)
        expect(owners.every(f => typeof f?.id === "string")).toBe(true)

        const votes = await botInfo.fetchVotes()

        expect(typeof votes).toBe("number")

        if (botInfo.discord) expect(botInfo.discord.url).toMatch(/https?:\/\/discord\.com\/invite\/(.{6,10})/i)

        return 
    })
})
Example #29
Source File: verify-code.ts    From solita with Apache License 2.0 5 votes vote down vote up
export function deepLog(obj: any) {
  console.log(inspect(obj, { depth: 15, colors: true }))
}