Add node_modules

This commit is contained in:
Anton Medvedev 2023-01-10 16:49:41 +01:00
parent e1f786311a
commit 554eb0b122
994 changed files with 195567 additions and 0 deletions

2
node_modules/zx/build/cli.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
#!/usr/bin/env node
export {};

240
node_modules/zx/build/cli.js generated vendored Executable file
View file

@ -0,0 +1,240 @@
#!/usr/bin/env node
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import fs from 'fs-extra';
import minimist from 'minimist';
import { createRequire } from 'node:module';
import { basename, dirname, extname, join, resolve } from 'node:path';
import url from 'node:url';
import { updateArgv } from './goods.js';
import { $, chalk, fetch, ProcessOutput } from './index.js';
import { startRepl } from './repl.js';
import { randomId } from './util.js';
import { installDeps, parseDeps } from './deps.js';
function printUsage() {
// language=txt
console.log(`
${chalk.bold('zx ' + getVersion())}
A tool for writing better scripts
${chalk.bold('Usage')}
zx [options] <script>
${chalk.bold('Options')}
--quiet don't echo commands
--shell=<path> custom shell binary
--prefix=<command> prefix all commands
--eval=<js>, -e evaluate script
--install, -i install dependencies
--experimental enable experimental features
--version, -v print current zx version
--help, -h print help
--repl start repl
`);
}
const argv = minimist(process.argv.slice(2), {
string: ['shell', 'prefix', 'eval'],
boolean: ['version', 'help', 'quiet', 'install', 'repl', 'experimental'],
alias: { e: 'eval', i: 'install', v: 'version', h: 'help' },
stopEarly: true,
});
await (async function main() {
const globals = './globals.js';
await import(globals);
if (argv.quiet)
$.verbose = false;
if (argv.shell)
$.shell = argv.shell;
if (argv.prefix)
$.prefix = argv.prefix;
if (argv.experimental) {
Object.assign(global, await import('./experimental.js'));
}
if (argv.version) {
console.log(getVersion());
return;
}
if (argv.help) {
printUsage();
return;
}
if (argv.repl) {
startRepl();
return;
}
if (argv.eval) {
await runScript(argv.eval);
return;
}
const firstArg = argv._[0];
updateArgv(argv._.slice(firstArg === undefined ? 0 : 1));
if (!firstArg || firstArg === '-') {
const success = await scriptFromStdin();
if (!success)
printUsage();
return;
}
if (/^https?:/.test(firstArg)) {
await scriptFromHttp(firstArg);
return;
}
const filepath = firstArg.startsWith('file:///')
? url.fileURLToPath(firstArg)
: resolve(firstArg);
await importPath(filepath);
})().catch((err) => {
if (err instanceof ProcessOutput) {
console.error('Error:', err.message);
}
else {
console.error(err);
}
process.exitCode = 1;
});
async function runScript(script) {
const filepath = join(process.cwd(), `zx-${randomId()}.mjs`);
await writeAndImport(script, filepath);
}
async function scriptFromStdin() {
let script = '';
if (!process.stdin.isTTY) {
process.stdin.setEncoding('utf8');
for await (const chunk of process.stdin) {
script += chunk;
}
if (script.length > 0) {
await runScript(script);
return true;
}
}
return false;
}
async function scriptFromHttp(remote) {
const res = await fetch(remote);
if (!res.ok) {
console.error(`Error: Can't get ${remote}`);
process.exit(1);
}
const script = await res.text();
const pathname = new URL(remote).pathname;
const name = basename(pathname);
const ext = extname(pathname) || '.mjs';
const filepath = join(process.cwd(), `${name}-${randomId()}${ext}`);
await writeAndImport(script, filepath);
}
async function writeAndImport(script, filepath, origin = filepath) {
await fs.writeFile(filepath, script.toString());
try {
await importPath(filepath, origin);
}
finally {
await fs.rm(filepath);
}
}
async function importPath(filepath, origin = filepath) {
const ext = extname(filepath);
if (ext === '') {
const tmpFilename = fs.existsSync(`${filepath}.mjs`)
? `${basename(filepath)}-${randomId()}.mjs`
: `${basename(filepath)}.mjs`;
return writeAndImport(await fs.readFile(filepath), join(dirname(filepath), tmpFilename), origin);
}
if (ext === '.md') {
return writeAndImport(transformMarkdown(await fs.readFile(filepath)), join(dirname(filepath), basename(filepath) + '.mjs'), origin);
}
if (argv.install) {
const deps = parseDeps(await fs.readFile(filepath));
await installDeps(deps, dirname(filepath));
}
const __filename = resolve(origin);
const __dirname = dirname(__filename);
const require = createRequire(origin);
Object.assign(global, { __filename, __dirname, require });
await import(url.pathToFileURL(filepath).toString());
}
function transformMarkdown(buf) {
const source = buf.toString();
const output = [];
let state = 'root';
let prevLineIsEmpty = true;
for (let line of source.split('\n')) {
switch (state) {
case 'root':
if (/^( {4}|\t)/.test(line) && prevLineIsEmpty) {
output.push(line);
state = 'tab';
}
else if (/^```(js|javascript)$/.test(line)) {
output.push('');
state = 'js';
}
else if (/^```(sh|bash)$/.test(line)) {
output.push('await $`');
state = 'bash';
}
else if (/^```.*$/.test(line)) {
output.push('');
state = 'other';
}
else {
prevLineIsEmpty = line === '';
output.push('// ' + line);
}
break;
case 'tab':
if (/^( +|\t)/.test(line)) {
output.push(line);
}
else if (line === '') {
output.push('');
}
else {
output.push('// ' + line);
state = 'root';
}
break;
case 'js':
if (/^```$/.test(line)) {
output.push('');
state = 'root';
}
else {
output.push(line);
}
break;
case 'bash':
if (/^```$/.test(line)) {
output.push('`');
state = 'root';
}
else {
output.push(line);
}
break;
case 'other':
if (/^```$/.test(line)) {
output.push('');
state = 'root';
}
else {
output.push('// ' + line);
}
break;
}
}
return output.join('\n');
}
function getVersion() {
return createRequire(import.meta.url)('../package.json').version;
}

101
node_modules/zx/build/core.d.ts generated vendored Normal file
View file

@ -0,0 +1,101 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
import { ChildProcess, spawn, StdioNull, StdioPipe } from 'node:child_process';
import { Readable, Writable } from 'node:stream';
import { inspect } from 'node:util';
import { RequestInfo, RequestInit } from 'node-fetch';
import { Duration, noop, quote } from './util.js';
export declare type Shell = (pieces: TemplateStringsArray, ...args: any[]) => ProcessPromise;
declare const processCwd: unique symbol;
export declare type Options = {
[processCwd]: string;
cwd?: string;
verbose: boolean;
env: NodeJS.ProcessEnv;
shell: string | boolean;
prefix: string;
quote: typeof quote;
spawn: typeof spawn;
log: typeof log;
};
export declare const defaults: Options;
export declare const $: Shell & Options;
declare type Resolve = (out: ProcessOutput) => void;
declare type IO = StdioPipe | StdioNull;
export declare class ProcessPromise extends Promise<ProcessOutput> {
child?: ChildProcess;
private _command;
private _from;
private _resolve;
private _reject;
private _snapshot;
private _stdio;
private _nothrow;
private _quiet;
private _timeout?;
private _timeoutSignal?;
private _resolved;
private _halted;
private _piped;
_prerun: typeof noop;
_postrun: typeof noop;
_bind(cmd: string, from: string, resolve: Resolve, reject: Resolve, options: Options): void;
run(): ProcessPromise;
get stdin(): Writable;
get stdout(): Readable;
get stderr(): Readable;
get exitCode(): Promise<number | null>;
then<R = ProcessOutput, E = ProcessOutput>(onfulfilled?: ((value: ProcessOutput) => PromiseLike<R> | R) | undefined | null, onrejected?: ((reason: ProcessOutput) => PromiseLike<E> | E) | undefined | null): Promise<R | E>;
catch<T = ProcessOutput>(onrejected?: ((reason: ProcessOutput) => PromiseLike<T> | T) | undefined | null): Promise<ProcessOutput | T>;
pipe(dest: Writable | ProcessPromise): ProcessPromise;
kill(signal?: string): Promise<void>;
stdio(stdin: IO, stdout?: IO, stderr?: IO): ProcessPromise;
nothrow(): ProcessPromise;
quiet(): ProcessPromise;
timeout(d: Duration, signal?: string): ProcessPromise;
halt(): ProcessPromise;
get isHalted(): boolean;
}
export declare class ProcessOutput extends Error {
private readonly _code;
private readonly _signal;
private readonly _stdout;
private readonly _stderr;
private readonly _combined;
constructor(code: number | null, signal: NodeJS.Signals | null, stdout: string, stderr: string, combined: string, message: string);
toString(): string;
get stdout(): string;
get stderr(): string;
get exitCode(): number | null;
get signal(): NodeJS.Signals | null;
[inspect.custom](): string;
}
export declare function within<R>(callback: () => R): R;
export declare function cd(dir: string): void;
export declare type LogEntry = {
kind: 'cmd';
verbose: boolean;
cmd: string;
} | {
kind: 'stdout' | 'stderr';
verbose: boolean;
data: Buffer;
} | {
kind: 'cd';
dir: string;
} | {
kind: 'fetch';
url: RequestInfo;
init?: RequestInit;
} | {
kind: 'retry';
error: string;
} | {
kind: 'custom';
data: any;
};
export declare function log(entry: LogEntry): void;
export {};

361
node_modules/zx/build/core.js generated vendored Normal file
View file

@ -0,0 +1,361 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import assert from 'node:assert';
import { spawn } from 'node:child_process';
import { AsyncLocalStorage, createHook } from 'node:async_hooks';
import { inspect } from 'node:util';
import chalk from 'chalk';
import which from 'which';
import { errnoMessage, exitCodeInfo, formatCmd, noop, parseDuration, psTree, quote, quotePowerShell, } from './util.js';
const processCwd = Symbol('processCwd');
const storage = new AsyncLocalStorage();
const hook = createHook({
init: syncCwd,
before: syncCwd,
promiseResolve: syncCwd,
after: syncCwd,
destroy: syncCwd,
});
hook.enable();
export const defaults = {
[processCwd]: process.cwd(),
verbose: true,
env: process.env,
shell: true,
prefix: '',
quote: () => {
throw new Error('No quote function is defined: https://ï.at/no-quote-func');
},
spawn,
log,
};
try {
defaults.shell = which.sync('bash');
defaults.prefix = 'set -euo pipefail;';
defaults.quote = quote;
}
catch (err) {
if (process.platform == 'win32') {
defaults.shell = which.sync('powershell.exe');
defaults.quote = quotePowerShell;
}
}
function getStore() {
return storage.getStore() || defaults;
}
export const $ = new Proxy(function (pieces, ...args) {
const from = new Error().stack.split(/^\s*at\s/m)[2].trim();
if (pieces.some((p) => p == undefined)) {
throw new Error(`Malformed command at ${from}`);
}
let resolve, reject;
const promise = new ProcessPromise((...args) => ([resolve, reject] = args));
let cmd = pieces[0], i = 0;
while (i < args.length) {
let s;
if (Array.isArray(args[i])) {
s = args[i].map((x) => $.quote(substitute(x))).join(' ');
}
else {
s = $.quote(substitute(args[i]));
}
cmd += s + pieces[++i];
}
promise._bind(cmd, from, resolve, reject, getStore());
// Postpone run to allow promise configuration.
setImmediate(() => promise.isHalted || promise.run());
return promise;
}, {
set(_, key, value) {
const target = key in Function.prototype ? _ : getStore();
Reflect.set(target, key, value);
return true;
},
get(_, key) {
const target = key in Function.prototype ? _ : getStore();
return Reflect.get(target, key);
},
});
function substitute(arg) {
if (arg?.stdout) {
return arg.stdout.replace(/\n$/, '');
}
return `${arg}`;
}
export class ProcessPromise extends Promise {
constructor() {
super(...arguments);
this._command = '';
this._from = '';
this._resolve = noop;
this._reject = noop;
this._snapshot = getStore();
this._stdio = ['inherit', 'pipe', 'pipe'];
this._nothrow = false;
this._quiet = false;
this._resolved = false;
this._halted = false;
this._piped = false;
this._prerun = noop;
this._postrun = noop;
}
_bind(cmd, from, resolve, reject, options) {
this._command = cmd;
this._from = from;
this._resolve = resolve;
this._reject = reject;
this._snapshot = { ...options };
}
run() {
const $ = this._snapshot;
if (this.child)
return this; // The _run() can be called from a few places.
this._prerun(); // In case $1.pipe($2), the $2 returned, and on $2._run() invoke $1._run().
$.log({
kind: 'cmd',
cmd: this._command,
verbose: $.verbose && !this._quiet,
});
this.child = $.spawn($.prefix + this._command, {
cwd: $.cwd ?? $[processCwd],
shell: typeof $.shell === 'string' ? $.shell : true,
stdio: this._stdio,
windowsHide: true,
env: $.env,
});
this.child.on('close', (code, signal) => {
let message = `exit code: ${code}`;
if (code != 0 || signal != null) {
message = `${stderr || '\n'} at ${this._from}`;
message += `\n exit code: ${code}${exitCodeInfo(code) ? ' (' + exitCodeInfo(code) + ')' : ''}`;
if (signal != null) {
message += `\n signal: ${signal}`;
}
}
let output = new ProcessOutput(code, signal, stdout, stderr, combined, message);
if (code === 0 || this._nothrow) {
this._resolve(output);
}
else {
this._reject(output);
}
this._resolved = true;
});
this.child.on('error', (err) => {
const message = `${err.message}\n` +
` errno: ${err.errno} (${errnoMessage(err.errno)})\n` +
` code: ${err.code}\n` +
` at ${this._from}`;
this._reject(new ProcessOutput(null, null, stdout, stderr, combined, message));
this._resolved = true;
});
let stdout = '', stderr = '', combined = '';
let onStdout = (data) => {
$.log({ kind: 'stdout', data, verbose: $.verbose && !this._quiet });
stdout += data;
combined += data;
};
let onStderr = (data) => {
$.log({ kind: 'stderr', data, verbose: $.verbose && !this._quiet });
stderr += data;
combined += data;
};
if (!this._piped)
this.child.stdout?.on('data', onStdout); // If process is piped, don't collect or print output.
this.child.stderr?.on('data', onStderr); // Stderr should be printed regardless of piping.
this._postrun(); // In case $1.pipe($2), after both subprocesses are running, we can pipe $1.stdout to $2.stdin.
if (this._timeout && this._timeoutSignal) {
const t = setTimeout(() => this.kill(this._timeoutSignal), this._timeout);
this.finally(() => clearTimeout(t)).catch(noop);
}
return this;
}
get stdin() {
this.stdio('pipe');
this.run();
assert(this.child);
if (this.child.stdin == null)
throw new Error('The stdin of subprocess is null.');
return this.child.stdin;
}
get stdout() {
this.run();
assert(this.child);
if (this.child.stdout == null)
throw new Error('The stdout of subprocess is null.');
return this.child.stdout;
}
get stderr() {
this.run();
assert(this.child);
if (this.child.stderr == null)
throw new Error('The stderr of subprocess is null.');
return this.child.stderr;
}
get exitCode() {
return this.then((p) => p.exitCode, (p) => p.exitCode);
}
then(onfulfilled, onrejected) {
if (this.isHalted && !this.child) {
throw new Error('The process is halted!');
}
return super.then(onfulfilled, onrejected);
}
catch(onrejected) {
return super.catch(onrejected);
}
pipe(dest) {
if (typeof dest == 'string')
throw new Error('The pipe() method does not take strings. Forgot $?');
if (this._resolved) {
if (dest instanceof ProcessPromise)
dest.stdin.end(); // In case of piped stdin, we may want to close stdin of dest as well.
throw new Error("The pipe() method shouldn't be called after promise is already resolved!");
}
this._piped = true;
if (dest instanceof ProcessPromise) {
dest.stdio('pipe');
dest._prerun = this.run.bind(this);
dest._postrun = () => {
if (!dest.child)
throw new Error('Access to stdin of pipe destination without creation a subprocess.');
this.stdout.pipe(dest.stdin);
};
return dest;
}
else {
this._postrun = () => this.stdout.pipe(dest);
return this;
}
}
async kill(signal = 'SIGTERM') {
if (!this.child)
throw new Error('Trying to kill a process without creating one.');
if (!this.child.pid)
throw new Error('The process pid is undefined.');
let children = await psTree(this.child.pid);
for (const p of children) {
try {
process.kill(+p.PID, signal);
}
catch (e) { }
}
try {
process.kill(this.child.pid, signal);
}
catch (e) { }
}
stdio(stdin, stdout = 'pipe', stderr = 'pipe') {
this._stdio = [stdin, stdout, stderr];
return this;
}
nothrow() {
this._nothrow = true;
return this;
}
quiet() {
this._quiet = true;
return this;
}
timeout(d, signal = 'SIGTERM') {
this._timeout = parseDuration(d);
this._timeoutSignal = signal;
return this;
}
halt() {
this._halted = true;
return this;
}
get isHalted() {
return this._halted;
}
}
export class ProcessOutput extends Error {
constructor(code, signal, stdout, stderr, combined, message) {
super(message);
this._code = code;
this._signal = signal;
this._stdout = stdout;
this._stderr = stderr;
this._combined = combined;
}
toString() {
return this._combined;
}
get stdout() {
return this._stdout;
}
get stderr() {
return this._stderr;
}
get exitCode() {
return this._code;
}
get signal() {
return this._signal;
}
[inspect.custom]() {
let stringify = (s, c) => s.length === 0 ? "''" : c(inspect(s));
return `ProcessOutput {
stdout: ${stringify(this.stdout, chalk.green)},
stderr: ${stringify(this.stderr, chalk.red)},
signal: ${inspect(this.signal)},
exitCode: ${(this.exitCode === 0 ? chalk.green : chalk.red)(this.exitCode)}${exitCodeInfo(this.exitCode)
? chalk.grey(' (' + exitCodeInfo(this.exitCode) + ')')
: ''}
}`;
}
}
export function within(callback) {
return storage.run({ ...getStore() }, callback);
}
function syncCwd() {
if ($[processCwd] != process.cwd())
process.chdir($[processCwd]);
}
export function cd(dir) {
$.log({ kind: 'cd', dir });
process.chdir(dir);
$[processCwd] = process.cwd();
}
export function log(entry) {
switch (entry.kind) {
case 'cmd':
if (!entry.verbose)
return;
process.stderr.write(formatCmd(entry.cmd));
break;
case 'stdout':
case 'stderr':
if (!entry.verbose)
return;
process.stderr.write(entry.data);
break;
case 'cd':
if (!$.verbose)
return;
process.stderr.write('$ ' + chalk.greenBright('cd') + ` ${entry.dir}\n`);
break;
case 'fetch':
if (!$.verbose)
return;
const init = entry.init ? ' ' + inspect(entry.init) : '';
process.stderr.write('$ ' + chalk.greenBright('fetch') + ` ${entry.url}${init}\n`);
break;
case 'retry':
if (!$.verbose)
return;
process.stderr.write(entry.error + '\n');
}
}

3
node_modules/zx/build/deps.d.ts generated vendored Normal file
View file

@ -0,0 +1,3 @@
/// <reference types="node" resolution-mode="require"/>
export declare function installDeps(dependencies: Record<string, string>, prefix?: string): Promise<void>;
export declare function parseDeps(content: Buffer): Record<string, string>;

119
node_modules/zx/build/deps.js generated vendored Normal file
View file

@ -0,0 +1,119 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { $ } from './core.js';
import { spinner } from './experimental.js';
export async function installDeps(dependencies, prefix) {
const packages = Object.entries(dependencies).map(([name, version]) => `${name}@${version}`);
const flags = prefix ? `--prefix=${prefix}` : '';
if (packages.length === 0) {
return;
}
await spinner(`npm i ${packages.join(' ')}`, () => $ `npm install --no-save --no-audit --no-fund ${flags} ${packages}`.nothrow());
}
const builtins = new Set([
'_http_agent',
'_http_client',
'_http_common',
'_http_incoming',
'_http_outgoing',
'_http_server',
'_stream_duplex',
'_stream_passthrough',
'_stream_readable',
'_stream_transform',
'_stream_wrap',
'_stream_writable',
'_tls_common',
'_tls_wrap',
'assert',
'async_hooks',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'dns',
'domain',
'events',
'fs',
'http',
'http2',
'https',
'inspector',
'module',
'net',
'os',
'path',
'perf_hooks',
'process',
'punycode',
'querystring',
'readline',
'repl',
'stream',
'string_decoder',
'sys',
'timers',
'tls',
'trace_events',
'tty',
'url',
'util',
'v8',
'vm',
'wasi',
'worker_threads',
'zlib',
]);
const importRe = [
/\bimport\s+['"](?<path>[^'"]+)['"]/,
/\bimport\(['"](?<path>[^'"]+)['"]\)/,
/\brequire\(['"](?<path>[^'"]+)['"]\)/,
/\bfrom\s+['"](?<path>[^'"]+)['"]/,
];
const nameRe = /^(?<name>(@[a-z0-9-]+\/)?[a-z0-9-]+)\/?.*$/i;
const versionRe = /(\/\/|\/\*)\s*@(?<version>[~^]?([\dvx*]+([-.][\dx*]+)*))/i;
export function parseDeps(content) {
const deps = {};
const lines = content.toString().split('\n');
for (let line of lines) {
const tuple = parseImports(line);
if (tuple) {
deps[tuple.name] = tuple.version;
}
}
return deps;
}
function parseImports(line) {
for (let re of importRe) {
const name = parsePackageName(re.exec(line)?.groups?.path);
const version = parseVersion(line);
if (name) {
return { name, version };
}
}
}
function parsePackageName(path) {
if (!path)
return;
const name = nameRe.exec(path)?.groups?.name;
if (name && !builtins.has(name)) {
return name;
}
}
function parseVersion(line) {
return versionRe.exec(line)?.groups?.version || 'latest';
}

6
node_modules/zx/build/experimental.d.ts generated vendored Normal file
View file

@ -0,0 +1,6 @@
import { Duration } from './util.js';
export declare function retry<T>(count: number, callback: () => T): Promise<T>;
export declare function retry<T>(count: number, duration: Duration | Generator<number>, callback: () => T): Promise<T>;
export declare function expBackoff(max?: Duration, rand?: Duration): Generator<number, void, unknown>;
export declare function spinner<T>(callback: () => T): Promise<T>;
export declare function spinner<T>(title: string, callback: () => T): Promise<T>;

94
node_modules/zx/build/experimental.js generated vendored Normal file
View file

@ -0,0 +1,94 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import assert from 'node:assert';
import chalk from 'chalk';
import { $, within } from './core.js';
import { sleep } from './goods.js';
import { parseDuration } from './util.js';
export async function retry(count, a, b) {
const total = count;
let callback;
let delayStatic = 0;
let delayGen;
if (typeof a == 'function') {
callback = a;
}
else {
if (typeof a == 'object') {
delayGen = a;
}
else {
delayStatic = parseDuration(a);
}
assert(b);
callback = b;
}
let lastErr;
let attempt = 0;
while (count-- > 0) {
attempt++;
try {
return await callback();
}
catch (err) {
let delay = 0;
if (delayStatic > 0)
delay = delayStatic;
if (delayGen)
delay = delayGen.next().value;
$.log({
kind: 'retry',
error: chalk.bgRed.white(' FAIL ') +
` Attempt: ${attempt}${total == Infinity ? '' : `/${total}`}` +
(delay > 0 ? `; next in ${delay}ms` : ''),
});
lastErr = err;
if (count == 0)
break;
if (delay)
await sleep(delay);
}
}
throw lastErr;
}
export function* expBackoff(max = '60s', rand = '100ms') {
const maxMs = parseDuration(max);
const randMs = parseDuration(rand);
let n = 1;
while (true) {
const ms = Math.floor(Math.random() * randMs);
yield Math.min(2 ** n++, maxMs) + ms;
}
}
export async function spinner(title, callback) {
if (typeof title == 'function') {
callback = title;
title = '';
}
let i = 0;
const spin = () => process.stderr.write(` ${'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'[i++ % 10]} ${title}\r`);
return within(async () => {
$.verbose = false;
const id = setInterval(spin, 100);
let result;
try {
result = await callback();
}
finally {
clearInterval(id);
process.stderr.write(' '.repeat(process.stdout.columns - 1) + '\r');
}
return result;
});
}

31
node_modules/zx/build/globals.d.ts generated vendored Normal file
View file

@ -0,0 +1,31 @@
/// <reference types="node" resolution-mode="require"/>
/// <reference types="node" resolution-mode="require"/>
/// <reference types="which" />
import * as _ from './index.js';
declare global {
type ProcessPromise = _.ProcessPromise;
type ProcessOutput = _.ProcessOutput;
var ProcessPromise: typeof _.ProcessPromise;
var ProcessOutput: typeof _.ProcessOutput;
var log: typeof _.log;
var $: typeof _.$;
var argv: typeof _.argv;
var cd: typeof _.cd;
var chalk: typeof _.chalk;
var echo: typeof _.echo;
var fs: typeof _.fs;
var glob: typeof _.glob;
var globby: typeof _.globby;
var nothrow: typeof _.nothrow;
var os: typeof _.os;
var path: typeof _.path;
var question: typeof _.question;
var quiet: typeof _.quiet;
var quote: typeof _.quote;
var quotePowerShell: typeof _.quotePowerShell;
var sleep: typeof _.sleep;
var stdin: typeof _.stdin;
var which: typeof _.which;
var within: typeof _.within;
var YAML: typeof _.YAML;
}

15
node_modules/zx/build/globals.js generated vendored Normal file
View file

@ -0,0 +1,15 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as _ from './index.js';
Object.assign(global, _);

21
node_modules/zx/build/goods.d.ts generated vendored Normal file
View file

@ -0,0 +1,21 @@
import * as globbyModule from 'globby';
import minimist from 'minimist';
import { RequestInfo, RequestInit } from 'node-fetch';
import { Duration } from './util.js';
export { default as chalk } from 'chalk';
export { default as fs } from 'fs-extra';
export { default as which } from 'which';
export { default as YAML } from 'yaml';
export { default as path } from 'node:path';
export { default as os } from 'node:os';
export declare let argv: minimist.ParsedArgs;
export declare function updateArgv(args: string[]): void;
export declare const globby: ((patterns: string | readonly string[], options?: globbyModule.Options) => Promise<string[]>) & typeof globbyModule;
export declare const glob: ((patterns: string | readonly string[], options?: globbyModule.Options) => Promise<string[]>) & typeof globbyModule;
export declare function sleep(duration: Duration): Promise<unknown>;
export declare function fetch(url: RequestInfo, init?: RequestInit): Promise<import("node-fetch").Response>;
export declare function echo(...args: any[]): void;
export declare function question(query?: string, options?: {
choices: string[];
}): Promise<string>;
export declare function stdin(): Promise<string>;

92
node_modules/zx/build/goods.js generated vendored Normal file
View file

@ -0,0 +1,92 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as globbyModule from 'globby';
import minimist from 'minimist';
import nodeFetch from 'node-fetch';
import { createInterface } from 'node:readline';
import { $, ProcessOutput } from './core.js';
import { isString, parseDuration } from './util.js';
export { default as chalk } from 'chalk';
export { default as fs } from 'fs-extra';
export { default as which } from 'which';
export { default as YAML } from 'yaml';
export { default as path } from 'node:path';
export { default as os } from 'node:os';
export let argv = minimist(process.argv.slice(2));
export function updateArgv(args) {
argv = minimist(args);
global.argv = argv;
}
export const globby = Object.assign(function globby(patterns, options) {
return globbyModule.globby(patterns, options);
}, globbyModule);
export const glob = globby;
export function sleep(duration) {
return new Promise((resolve) => {
setTimeout(resolve, parseDuration(duration));
});
}
export async function fetch(url, init) {
$.log({ kind: 'fetch', url, init });
return nodeFetch(url, init);
}
export function echo(pieces, ...args) {
let msg;
const lastIdx = pieces.length - 1;
if (Array.isArray(pieces) &&
pieces.every(isString) &&
lastIdx === args.length) {
msg =
args.map((a, i) => pieces[i] + stringify(a)).join('') + pieces[lastIdx];
}
else {
msg = [pieces, ...args].map(stringify).join(' ');
}
console.log(msg);
}
function stringify(arg) {
if (arg instanceof ProcessOutput) {
return arg.toString().replace(/\n$/, '');
}
return `${arg}`;
}
export async function question(query, options) {
let completer = undefined;
if (options && Array.isArray(options.choices)) {
/* c8 ignore next 5 */
completer = function completer(line) {
const completions = options.choices;
const hits = completions.filter((c) => c.startsWith(line));
return [hits.length ? hits : completions, line];
};
}
const rl = createInterface({
input: process.stdin,
output: process.stdout,
terminal: true,
completer,
});
return new Promise((resolve) => rl.question(query ?? '', (answer) => {
rl.close();
resolve(answer);
}));
}
export async function stdin() {
let buf = '';
process.stdin.setEncoding('utf8');
for await (const chunk of process.stdin) {
buf += chunk;
}
return buf;
}

12
node_modules/zx/build/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,12 @@
import { ProcessPromise } from './core.js';
export { $, Shell, Options, ProcessPromise, ProcessOutput, within, cd, log, LogEntry, } from './core.js';
export { argv, chalk, echo, fetch, fs, glob, globby, os, path, question, sleep, stdin, which, YAML, } from './goods.js';
export { Duration, quote, quotePowerShell } from './util.js';
/**
* @deprecated Use $.nothrow() instead.
*/
export declare function nothrow(promise: ProcessPromise): ProcessPromise;
/**
* @deprecated Use $.quiet() instead.
*/
export declare function quiet(promise: ProcessPromise): ProcessPromise;

28
node_modules/zx/build/index.js generated vendored Normal file
View file

@ -0,0 +1,28 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export { $, ProcessPromise, ProcessOutput, within, cd, log, } from './core.js';
export { argv, chalk, echo, fetch, fs, glob, globby, os, path, question, sleep, stdin, which, YAML, } from './goods.js';
export { quote, quotePowerShell } from './util.js';
/**
* @deprecated Use $.nothrow() instead.
*/
export function nothrow(promise) {
return promise.nothrow();
}
/**
* @deprecated Use $.quiet() instead.
*/
export function quiet(promise) {
return promise.quiet();
}

1
node_modules/zx/build/repl.d.ts generated vendored Normal file
View file

@ -0,0 +1 @@
export declare function startRepl(): void;

34
node_modules/zx/build/repl.js generated vendored Normal file
View file

@ -0,0 +1,34 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import chalk from 'chalk';
import os from 'node:os';
import path from 'node:path';
import repl from 'node:repl';
import { inspect } from 'node:util';
import { ProcessOutput, defaults } from './core.js';
export function startRepl() {
defaults.verbose = false;
const r = repl.start({
prompt: chalk.greenBright.bold(' '),
useGlobal: true,
preview: false,
writer(output) {
if (output instanceof ProcessOutput) {
return output.toString().replace(/\n$/, '');
}
return inspect(output, { colors: true });
},
});
r.setupHistory(path.join(os.homedir(), '.zx_repl_history'), () => { });
}

12
node_modules/zx/build/util.d.ts generated vendored Normal file
View file

@ -0,0 +1,12 @@
import psTreeModule from 'ps-tree';
export declare const psTree: (arg1: number) => Promise<readonly psTreeModule.PS[]>;
export declare function noop(): void;
export declare function randomId(): string;
export declare function isString(obj: any): boolean;
export declare function quote(arg: string): string;
export declare function quotePowerShell(arg: string): string;
export declare function exitCodeInfo(exitCode: number | null): string | undefined;
export declare function errnoMessage(errno: number | undefined): string;
export declare type Duration = number | `${number}s` | `${number}ms`;
export declare function parseDuration(d: Duration): number;
export declare function formatCmd(cmd?: string): string;

346
node_modules/zx/build/util.js generated vendored Normal file
View file

@ -0,0 +1,346 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import chalk from 'chalk';
import { promisify } from 'node:util';
import psTreeModule from 'ps-tree';
export const psTree = promisify(psTreeModule);
export function noop() { }
export function randomId() {
return Math.random().toString(36).slice(2);
}
export function isString(obj) {
return typeof obj === 'string';
}
export function quote(arg) {
if (/^[a-z0-9/_.\-@:=]+$/i.test(arg) || arg === '') {
return arg;
}
return (`$'` +
arg
.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(/\f/g, '\\f')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\v/g, '\\v')
.replace(/\0/g, '\\0') +
`'`);
}
export function quotePowerShell(arg) {
if (/^[a-z0-9/_.\-]+$/i.test(arg) || arg === '') {
return arg;
}
return `'` + arg.replace(/'/g, "''") + `'`;
}
export function exitCodeInfo(exitCode) {
return {
2: 'Misuse of shell builtins',
126: 'Invoked command cannot execute',
127: 'Command not found',
128: 'Invalid exit argument',
129: 'Hangup',
130: 'Interrupt',
131: 'Quit and dump core',
132: 'Illegal instruction',
133: 'Trace/breakpoint trap',
134: 'Process aborted',
135: 'Bus error: "access to undefined portion of memory object"',
136: 'Floating point exception: "erroneous arithmetic operation"',
137: 'Kill (terminate immediately)',
138: 'User-defined 1',
139: 'Segmentation violation',
140: 'User-defined 2',
141: 'Write to pipe with no one reading',
142: 'Signal raised by alarm',
143: 'Termination (request to terminate)',
145: 'Child process terminated, stopped (or continued*)',
146: 'Continue if stopped',
147: 'Stop executing temporarily',
148: 'Terminal stop signal',
149: 'Background process attempting to read from tty ("in")',
150: 'Background process attempting to write to tty ("out")',
151: 'Urgent data available on socket',
152: 'CPU time limit exceeded',
153: 'File size limit exceeded',
154: 'Signal raised by timer counting virtual time: "virtual timer expired"',
155: 'Profiling timer expired',
157: 'Pollable event',
159: 'Bad syscall',
}[exitCode || -1];
}
export function errnoMessage(errno) {
if (errno === undefined) {
return 'Unknown error';
}
return ({
0: 'Success',
1: 'Not super-user',
2: 'No such file or directory',
3: 'No such process',
4: 'Interrupted system call',
5: 'I/O error',
6: 'No such device or address',
7: 'Arg list too long',
8: 'Exec format error',
9: 'Bad file number',
10: 'No children',
11: 'No more processes',
12: 'Not enough core',
13: 'Permission denied',
14: 'Bad address',
15: 'Block device required',
16: 'Mount device busy',
17: 'File exists',
18: 'Cross-device link',
19: 'No such device',
20: 'Not a directory',
21: 'Is a directory',
22: 'Invalid argument',
23: 'Too many open files in system',
24: 'Too many open files',
25: 'Not a typewriter',
26: 'Text file busy',
27: 'File too large',
28: 'No space left on device',
29: 'Illegal seek',
30: 'Read only file system',
31: 'Too many links',
32: 'Broken pipe',
33: 'Math arg out of domain of func',
34: 'Math result not representable',
35: 'File locking deadlock error',
36: 'File or path name too long',
37: 'No record locks available',
38: 'Function not implemented',
39: 'Directory not empty',
40: 'Too many symbolic links',
42: 'No message of desired type',
43: 'Identifier removed',
44: 'Channel number out of range',
45: 'Level 2 not synchronized',
46: 'Level 3 halted',
47: 'Level 3 reset',
48: 'Link number out of range',
49: 'Protocol driver not attached',
50: 'No CSI structure available',
51: 'Level 2 halted',
52: 'Invalid exchange',
53: 'Invalid request descriptor',
54: 'Exchange full',
55: 'No anode',
56: 'Invalid request code',
57: 'Invalid slot',
59: 'Bad font file fmt',
60: 'Device not a stream',
61: 'No data (for no delay io)',
62: 'Timer expired',
63: 'Out of streams resources',
64: 'Machine is not on the network',
65: 'Package not installed',
66: 'The object is remote',
67: 'The link has been severed',
68: 'Advertise error',
69: 'Srmount error',
70: 'Communication error on send',
71: 'Protocol error',
72: 'Multihop attempted',
73: 'Cross mount point (not really error)',
74: 'Trying to read unreadable message',
75: 'Value too large for defined data type',
76: 'Given log. name not unique',
77: 'f.d. invalid for this operation',
78: 'Remote address changed',
79: 'Can access a needed shared lib',
80: 'Accessing a corrupted shared lib',
81: '.lib section in a.out corrupted',
82: 'Attempting to link in too many libs',
83: 'Attempting to exec a shared library',
84: 'Illegal byte sequence',
86: 'Streams pipe error',
87: 'Too many users',
88: 'Socket operation on non-socket',
89: 'Destination address required',
90: 'Message too long',
91: 'Protocol wrong type for socket',
92: 'Protocol not available',
93: 'Unknown protocol',
94: 'Socket type not supported',
95: 'Not supported',
96: 'Protocol family not supported',
97: 'Address family not supported by protocol family',
98: 'Address already in use',
99: 'Address not available',
100: 'Network interface is not configured',
101: 'Network is unreachable',
102: 'Connection reset by network',
103: 'Connection aborted',
104: 'Connection reset by peer',
105: 'No buffer space available',
106: 'Socket is already connected',
107: 'Socket is not connected',
108: "Can't send after socket shutdown",
109: 'Too many references',
110: 'Connection timed out',
111: 'Connection refused',
112: 'Host is down',
113: 'Host is unreachable',
114: 'Socket already connected',
115: 'Connection already in progress',
116: 'Stale file handle',
122: 'Quota exceeded',
123: 'No medium (in tape drive)',
125: 'Operation canceled',
130: 'Previous owner died',
131: 'State not recoverable',
}[-errno] || 'Unknown error');
}
export function parseDuration(d) {
if (typeof d == 'number') {
if (isNaN(d) || d < 0)
throw new Error(`Invalid duration: "${d}".`);
return d;
}
else if (/\d+s/.test(d)) {
return +d.slice(0, -1) * 1000;
}
else if (/\d+ms/.test(d)) {
return +d.slice(0, -2);
}
throw new Error(`Unknown duration: "${d}".`);
}
export function formatCmd(cmd) {
if (cmd == undefined)
return chalk.grey('undefined');
const chars = [...cmd];
let out = '$ ';
let buf = '';
let ch;
let state = root;
let wordCount = 0;
while (state) {
ch = chars.shift() || 'EOF';
if (ch == '\n') {
out += style(state, buf) + '\n> ';
buf = '';
continue;
}
const next = ch == 'EOF' ? undefined : state();
if (next != state) {
out += style(state, buf);
buf = '';
}
state = next == root ? next() : next;
buf += ch;
}
function style(state, s) {
if (s == '')
return '';
if (reservedWords.includes(s)) {
return chalk.cyanBright(s);
}
if (state == word && wordCount == 0) {
wordCount++;
return chalk.greenBright(s);
}
if (state == syntax) {
wordCount = 0;
return chalk.cyanBright(s);
}
if (state == dollar)
return chalk.yellowBright(s);
if (state?.name.startsWith('str'))
return chalk.yellowBright(s);
return s;
}
function isSyntax(ch) {
return '()[]{}<>;:+|&='.includes(ch);
}
function root() {
if (/\s/.test(ch))
return space;
if (isSyntax(ch))
return syntax;
if (/[$]/.test(ch))
return dollar;
if (/["]/.test(ch))
return strDouble;
if (/[']/.test(ch))
return strSingle;
return word;
}
function space() {
if (/\s/.test(ch))
return space;
return root;
}
function word() {
if (/[0-9a-z/_.]/i.test(ch))
return word;
return root;
}
function syntax() {
if (isSyntax(ch))
return syntax;
return root;
}
function dollar() {
if (/[']/.test(ch))
return str;
return root;
}
function str() {
if (/[']/.test(ch))
return strEnd;
if (/[\\]/.test(ch))
return strBackslash;
return str;
}
function strBackslash() {
return strEscape;
}
function strEscape() {
return str;
}
function strDouble() {
if (/["]/.test(ch))
return strEnd;
return strDouble;
}
function strSingle() {
if (/[']/.test(ch))
return strEnd;
return strSingle;
}
function strEnd() {
return root;
}
return out + '\n';
}
const reservedWords = [
'if',
'then',
'else',
'elif',
'fi',
'case',
'esac',
'for',
'select',
'while',
'until',
'do',
'done',
'in',
];