util#promisify TypeScript Examples

The following examples show how to use util#promisify. 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: utils.ts    From solidity-utils with MIT License 7 votes vote down vote up
export async function countInstructions (txHash: string, instructions: string[]) {
    if (!web3.currentProvider || typeof web3.currentProvider === 'string' || !web3.currentProvider.send) {
        throw new Error('Unsupported provider');
    }
    const trace = await promisify(web3.currentProvider.send.bind(web3.currentProvider))({
        jsonrpc: '2.0',
        method: 'debug_traceTransaction',
        params: [txHash, {}],
        id: new Date().getTime(),
    });

    const str = JSON.stringify(trace);

    return instructions.map(instr => {
        return str.split('"' + instr.toUpperCase() + '"').length - 1;
    });
}
Example #2
Source File: renderer_utils.ts    From 3Speak-app with GNU General Public License v3.0 6 votes vote down vote up
hive.broadcast.comment = promisify(hive.broadcast.comment)
Example #3
Source File: vm.ts    From Assistive-Webdriver with MIT License 6 votes vote down vote up
async takePNGScreenshot(): Promise<PNG> {
    const resolution = await this.vboxDisplay!.getScreenResolution(0);
    const screenshot = await this.vboxDisplay!.takeScreenShotToArray(
      0,
      resolution.width,
      resolution.height,
      BitmapFormat.PNG
    );
    const imageBuffer = Buffer.from(screenshot, "base64");
    const image = new PNG();
    const parseImage = promisify(image.parse.bind(image));
    await parseImage(imageBuffer);
    return image;
  }
Example #4
Source File: utils.ts    From CloudProxy with MIT License 6 votes vote down vote up
sleep = promisify(setTimeout)
Example #5
Source File: wrap-provider.ts    From openzeppelin-upgrades with MIT License 6 votes vote down vote up
export function wrapProvider(provider: TruffleProvider): EthereumProvider {
  const sendAsync = ('sendAsync' in provider ? provider.sendAsync : provider.send).bind(provider);
  const send = promisify(sendAsync);
  return {
    async send(method: string, params: unknown[]) {
      const id = crypto.randomBytes(4).toString('hex');
      const { result, error } = await send({ jsonrpc: '2.0', method, params, id });
      if (error) {
        throw new Error(error.message);
      } else {
        return result;
      }
    },
  };
}
Example #6
Source File: state-storage.ts    From SideQuest with MIT License 6 votes vote down vote up
private async loadAsync(): Promise<StorageDatabase> {
        try {
            const readFile = promisify(fs.readFile);
            this.lastFlushedSerializedDatabase = (await readFile(this.dbPath)).toString();

            return JSON.parse(this.lastFlushedSerializedDatabase);
        } catch (error) {
            if (error.code !== 'ENOENT') {
                this.onError(error);
            }

            return {};
        }
    }
Example #7
Source File: UserSystemFunctions.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(app: App, private plugin: TemplaterPlugin) {
        if (
            Platform.isMobileApp ||
            !(app.vault.adapter instanceof FileSystemAdapter)
        ) {
            this.cwd = "";
        } else {
            this.cwd = app.vault.adapter.getBasePath();
            this.exec_promise = promisify(exec);
        }
    }
Example #8
Source File: installation.ts    From vscode-windows-terminal with MIT License 6 votes vote down vote up
export async function detectInstallation(): Promise<IWTInstallation | undefined> {
  const config = vscode.workspace.getConfiguration('windowsTerminal');
  const channelConfig = config.get<Channel | 'auto'>('channel') || 'auto';

  let channel: Channel;
  if (channelConfig === 'auto') {
    const pathExists = await promisify(exists)(getExecutablePath('stable'));
    channel = 'stable';
    if (!pathExists) {
      // Switch to preview only if it exists, we want the stable store page to open if not
      const previewExists = await promisify(exists)(getExecutablePath('preview'));
      if (previewExists) {
        channel = 'preview';
      }
    }
  } else {
    channel = channelConfig;
  }

  const installation: IWTInstallation = {
    executablePath: getExecutablePath(channel),
    settingsPath: getSettingsPath(channel)
  };

  const exeExists = await promisify(exists)(installation.executablePath);
  if (!exeExists) {
    const selection = await vscode.window.showErrorMessage('Could not detect Windows Terminal installation', 'Open Microsoft Store');
    if (selection === 'Open Microsoft Store') {
      const url = channel === 'stable'
        ? 'https://www.microsoft.com/en-us/p/windows-terminal/9n0dx20hk701'
        : 'https://www.microsoft.com/en-us/p/windows-terminal-preview/9n8g5rfz9xk3';
      await vscode.env.openExternal(vscode.Uri.parse(url));
    }
    return undefined;
  }

  return installation;
}
Example #9
Source File: gameService.ts    From project-tauntaun with GNU Lesser General Public License v3.0 6 votes vote down vote up
async function receiveUpdateMessage(event: any) {
  const time_end = performance.now();
  if (time_start !== null) {
    console.log(`Roundtrip: ${time_end - time_start}ms`);
    time_start = null;
  }

  const data = Buffer.from(Buffer.from(event.data, 'base64'), 4);
  const do_unzip = promisify(inflate);
  const unzipped_data = await do_unzip(data);

  const message = JSON.parse(unzipped_data as unknown as string);
  if (message.key === 'mission_updated') {
    Object.keys(missionUpdateListeners).forEach(key => missionUpdateListeners[key](message.value));
  } else if (message.key === 'sessionid') {
    Object.keys(sessionIdUpdateListeners).forEach(key => sessionIdUpdateListeners[key](message.value));
  } else if (message.key === 'sessions_updated') {
    Object.keys(sessionsUpdateListeners).forEach(key => sessionsUpdateListeners[key](message.value));
  } else {
    Object.keys(genericUpdateListeners).forEach(key => genericUpdateListeners[key](message));
  }
}
Example #10
Source File: JWT.ts    From nodejs-backend-architecture-typescript with Apache License 2.0 6 votes vote down vote up
/**
   * This method checks the token and returns the decoded data when token is valid in all respect
   */
  public static async validate(token: string): Promise<JwtPayload> {
    const cert = await this.readPublicKey();
    try {
      // @ts-ignore
      return (await promisify(verify)(token, cert)) as JwtPayload;
    } catch (e) {
      Logger.debug(e);
      if (e && e.name === 'TokenExpiredError') throw new TokenExpiredError();
      // throws error if the token has not been encrypted by the private key
      throw new BadTokenError();
    }
  }
Example #11
Source File: fetch.ts    From polar with MIT License 6 votes vote down vote up
/**
 * Downloads repo from git url to destination path
 * @param url git url (<organization/repo>)
 * @param destination location to download repo
 */
export async function fetchRepository (url: string, destination: string): Promise<void> {
  try {
    // eslint-disable-next-line @typescript-eslint/no-misused-promises
    await promisify(download)(url, destination);
  } catch (error) {
    console.error(`Failed to initialize ${url}`);
    throw error;
  }
}
Example #12
Source File: util.ts    From omegga with ISC License 6 votes vote down vote up
createCertificate: (
  options: pem.CertificateCreationOptions
) => Promise<pem.CertificateCreationResult> = promisify(pem.createCertificate)
Example #13
Source File: writeGitIgnore.ts    From engine with MIT License 6 votes vote down vote up
pReadFile = promisify(readFile)
Example #14
Source File: index.ts    From farrow with MIT License 6 votes vote down vote up
cors = (
  options?: CorsOptions | CorsOptionsDelegate<IncomingMessage>,
): Middleware<any, MaybeAsyncResponse> => {
  const cors = promisify(
    Cors(
      typeof options === 'function'
        ? options
        : {
            ...options,
            preflightContinue: true,
          },
    ),
  )

  return async (request, next) => {
    const req = useReq()
    const res = useRes()

    try {
      await cors(req, res)
      if (req.method?.toLowerCase() === 'options') {
        if (typeof options === 'object') {
          if (options.preflightContinue) {
            return next(request)
          }
        }
        return Response.status(204).string('')
      }
      return next(request)
    } catch (error: any) {
      return Response.status(500).text(error.message)
    }
  }
}
Example #15
Source File: utils.ts    From heroku-docker-deploy with MIT License 6 votes vote down vote up
exec = promisify(ChildProcess.exec)
Example #16
Source File: test-runner.ts    From riju with MIT License 6 votes vote down vote up
async function writeLog(
  lang: string,
  type: string,
  result: string,
  log: string
) {
  log = `${result.toUpperCase()}: ${lang}/${type}\n` + log;
  await promisify(fs.mkdir)(`tests/${lang}`, { recursive: true });
  await promisify(fs.writeFile)(`tests/${lang}/${type}.log`, log);
  await promisify(fs.mkdir)(`tests-run/${lang}`, { recursive: true });
  await promisify(fs.symlink)(
    `../../tests/${lang}/${type}.log`,
    `tests-run/${lang}/${type}.log`
  );
  await promisify(fs.mkdir)(`tests-${result}/${lang}`, { recursive: true });
  await promisify(fs.symlink)(
    `../../tests/${lang}/${type}.log`,
    `tests-${result}/${lang}/${type}.log`
  );
}
Example #17
Source File: utils.ts    From node-question-answering with Apache License 2.0 6 votes vote down vote up
exists = promisify(fs.exists)
Example #18
Source File: dataDump.ts    From cloud-pricing-api with Apache License 2.0 6 votes vote down vote up
async function dumpFile(client: PoolClient, outfile: string): Promise<void> {
  const promisifiedPipeline = promisify(pipeline);

  const copyStream = client.query(
    copyTo(
      format(
        `
      COPY %I TO STDOUT WITH (
      FORMAT csv,
      HEADER true,
      DELIMITER ','
    )`,
        config.productTableName
      )
    )
  );

  const gzip = zlib.createGzip().on('error', (e) => {
    config.logger.info(e);
    process.exit(1);
  });

  const fileStream = fs.createWriteStream(`${outfile}`);

  return promisifiedPipeline(copyStream, gzip, fileStream);
}
Example #19
Source File: util.ts    From hackium with ISC License 6 votes vote down vote up
exists = promisify(origFs.exists)
Example #20
Source File: check.ts    From merkle-stellar with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
async checkSigAgainstStellar(pathAndSigs: PathAndSigsJSON, expectedHash: Sha256Hash): Promise<TreeRoots> {
    // First check that the hash of the signature was reflected in the
    // stellar blockchain, as expected.
    const reporter = this.reporter.step(`check hash equality for ${chalk.italic(expectedHash)}`)
    reporter.start()
    const sig = pathAndSigs.root.sigs[keybaseRootKid].sig
    const sigDecoded = Buffer.from(sig, 'base64')
    const gotHash = sha256(sigDecoded)
    if (expectedHash != gotHash) {
      throw new Error('hash mismatch for grove sig and stellar memo')
    }

    // Verify the signature is valid, and signed with the expected key
    const f = promisify(kb.verify)
    const sigPayload = await f({binary: sigDecoded, kid: keybaseRootKid})

    // The next 5 lines aren't necessary, since they are already performed inside
    // of kb.verify, but we repeat them here to be explicit that the `sig` object
    // also contains the text of what the signature was over.
    const object = decode(sigDecoded) as KeybaseSig
    const treeRootsEncoded = Buffer.from(object.body.payload)
    if (sigPayload.compare(treeRootsEncoded) != 0) {
      throw new Error('buffer comparison failed and should have been the same')
    }

    // Parse and return the root sig payload
    reporter.success('match')
    return JSON.parse(treeRootsEncoded.toString('ascii')) as TreeRoots
  }
Example #21
Source File: profileEVM.ts    From solidity-utils with MIT License 5 votes vote down vote up
export async function gasspectEVM (txHash: string, gasspectOptions: Record<string, unknown> = {}, optionalTraceFile?: PathLike | fs.FileHandle) {
    const options = { ...gasspectOptionsDefault, ...gasspectOptions };

    if (!web3.currentProvider || typeof web3.currentProvider === 'string' || !web3.currentProvider.send) {
        throw new Error('Unsupported provider');
    }

    const trace = await promisify(web3.currentProvider.send.bind(web3.currentProvider))({
        jsonrpc: '2.0',
        method: 'debug_traceTransaction',
        params: [txHash, {}],
        id: new Date().getTime(),
    });

    const ops: Op[] = trace?.result.structLogs;

    const traceAddress = [0, -1];
    for (const [i, op] of ops.entries()) {
        op.traceAddress = traceAddress.slice(0, traceAddress.length - 1);
        _normalizeOp(ops, i);

        if (op.depth + 2 > traceAddress.length) {
            traceAddress[traceAddress.length - 1] += 1;
            traceAddress.push(-1);
        }

        if (op.depth + 2 < traceAddress.length) {
            traceAddress.pop();
        }
    }

    const result = ops.filter(op => op.gasCost > options.minOpGasCost).map(op => op.traceAddress.join('-') + '-' + op.op +
                        (options.args ? '(' + (op.args || []).join(',') + ')' : '') +
                        (options.res ? (op.res ? ':0x' + op.res : '') : '') +
                        ' = ' + op.gasCost);

    if (optionalTraceFile) {
        await fs.writeFile(optionalTraceFile, JSON.stringify(result));
    }

    return result;
}
Example #22
Source File: hive-client.singleton.ts    From 3Speak-app with GNU General Public License v3.0 5 votes vote down vote up
hive.broadcast.comment = promisify(hive.broadcast.comment)
Example #23
Source File: index.ts    From lfs-warning with MIT License 5 votes vote down vote up
execFileP = promisify(execFile)
Example #24
Source File: cli.ts    From Assistive-Webdriver with MIT License 5 votes vote down vote up
(async () => {
  try {
    const argv = await yargs
      .default("http-host", "0.0.0.0")
      .default("http-port", 7779)
      .default("tcp-host", "127.0.0.1")
      .default("tcp-port", 4449).argv;

    const startListening = function (serverName: string, serverObject: any) {
      serverObject.listen(
        argv[`${serverName}-port`],
        argv[`${serverName}-host`]
      );
      serverObject.on("listening", function () {
        console.log(
          `${serverName} server listening on ${formatAddress(
            serverObject.address()
          )}`
        );
      });
    };

    const { httpServer, screenReaderTcpServer } =
      await createPlaywrightServer();
    let closing = false;
    process.on("SIGINT", async () => {
      if (!closing) {
        closing = true;
        await promisify(httpServer.close.bind(httpServer))();
      }
      process.exit(0);
    });
    sigintWin32();
    startListening("tcp", screenReaderTcpServer);
    startListening("http", httpServer);
  } catch (error) {
    console.error(error);
    process.exit(1);
  }
})();
Example #25
Source File: index.ts    From discord-statuspage-v2 with MIT License 5 votes vote down vote up
status.on('update', async (data) => {
  if (!db.connected) await promisify(setTimeout)(2000)

  const body = generateEmbed(data)

  postUpdate(body, db)
    .catch(console.error)
})
Example #26
Source File: RestAPIHandler.ts    From evolvejs with GNU Affero General Public License v3.0 5 votes vote down vote up
private async _fetch<T>(options: NewIAPIParams): Promise<T> {
		await this._queue.delay();
		const whileExectued = RestAPIHandler.globalTimeout;
		await promisify(setTimeout)(whileExectued);
		RestAPIHandler.globalTimeout -= whileExectued;
		try {
			await promisify(setTimeout)(this._cooldown);
			this._cooldown = 1;
			const res = await fetch(`${CONSTANTS.Api}${options.endpoint}`, {
				method: options.method,
				headers: {
					"Content-Type": "application/json",
					Authorization: `Bot ${this._client.token}`,
				},
				body: options.json_params,
			});

			const json = await res.json();

			if (res.headers) {
				const resetAfter =
					Number(
						res.headers.get("x-ratelimit-reset-after") ?? json.retry_after
					) * 1000;
				if (this._cooldown !== 0) {
					this._cooldown += resetAfter;
				} else this._cooldown = resetAfter;
			}

			if (res.status === 429) {
				if (json.global) RestAPIHandler.globalTimeout += this._cooldown;
				await promisify(setTimeout)(this._cooldown);
				return this._fetch<T>(options);
			}

			if (!res.ok) {
				const rejection = new DiscordRejection({
					code: json.code,
					msg: this._client.transformer.error(json.message),
					http: res.status,
					path: options.endpoint,
				});

				if (this._client.listenerCount(EVENTS.API_ERROR) < 1) {
					throw rejection;
				} else throw this._client.emit(EVENTS.API_ERROR, rejection);
			}
			return json;
		} catch (e) {
			if (this._client.listenerCount(EVENTS.API_ERROR) < 1)
				throw this._client.transformer.error(e);
			else throw this._client.emit(EVENTS.API_ERROR, e);
		} finally {
			this._cooldown = 1;
			this._queue.dequeue();
		}
	}
Example #27
Source File: FileBundle.ts    From arbundles with Apache License 2.0 5 votes vote down vote up
read = promisify(fs.read)
Example #28
Source File: downloader.ts    From Cromwell with MIT License 5 votes vote down vote up
streamPipeline = promisify(require('stream').pipeline)
Example #29
Source File: index.ts    From write-file-action with Apache License 2.0 5 votes vote down vote up
appendFileAsync = promisify(appendFile)