Socket
Socket
Sign inDemoInstall

zx

Package Overview
Dependencies
4
Maintainers
2
Versions
111
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 7.2.3-dev.7e728f6 to 7.2.3-dev.c2cda4a

35

build/core.d.ts

@@ -1,2 +0,2 @@

import { ChildProcess, spawn, StdioNull, StdioPipe } from 'node:child_process';
import { spawn, spawnSync, StdioNull, StdioPipe } from 'node:child_process';
import { Readable, Writable } from 'node:stream';

@@ -6,13 +6,28 @@ import { inspect } from 'node:util';

import { Duration, noop, quote } from './util.js';
export type Shell = (pieces: TemplateStringsArray, ...args: any[]) => ProcessPromise;
export interface Shell {
(pieces: TemplateStringsArray, ...args: any[]): ProcessPromise;
(opts: Partial<Options>): Shell;
sync: {
(pieces: TemplateStringsArray, ...args: any[]): ProcessOutput;
(opts: Partial<Options>): Shell;
};
}
declare const processCwd: unique symbol;
declare const syncExec: unique symbol;
export interface Options {
[processCwd]: string;
[syncExec]: boolean;
cwd?: string;
ac?: AbortController;
input?: string | Buffer | Readable | ProcessOutput | ProcessPromise;
verbose: boolean;
sync: boolean;
env: NodeJS.ProcessEnv;
shell: string | boolean;
nothrow: boolean;
prefix: string;
quote: typeof quote;
quiet: boolean;
spawn: typeof spawn;
spawnSync: typeof spawnSync;
log: typeof log;

@@ -25,3 +40,2 @@ }

export declare class ProcessPromise extends Promise<ProcessOutput> {
child?: ChildProcess;
private _command;

@@ -33,9 +47,11 @@ private _from;

private _stdio;
private _nothrow;
private _quiet;
private _nothrow?;
private _quiet?;
private _timeout?;
private _timeoutSignal?;
private _timeoutSignal;
private _resolved;
private _halted;
private _piped;
private _zurk;
private _output;
_prerun: typeof noop;

@@ -45,2 +61,3 @@ _postrun: typeof noop;

run(): ProcessPromise;
get child(): import("child_process").ChildProcess | undefined;
get stdin(): Writable;

@@ -53,2 +70,3 @@ get stdout(): Readable;

pipe(dest: Writable | ProcessPromise): ProcessPromise;
abort(reason?: string): void;
kill(signal?: string): Promise<void>;

@@ -58,5 +76,7 @@ stdio(stdin: IO, stdout?: IO, stderr?: IO): ProcessPromise;

quiet(): ProcessPromise;
isVerbose(): boolean;
timeout(d: Duration, signal?: string): ProcessPromise;
halt(): ProcessPromise;
get isHalted(): boolean;
get output(): ProcessOutput | null;
}

@@ -71,2 +91,3 @@ export declare class ProcessOutput extends Error {

toString(): string;
valueOf(): string;
get stdout(): string;

@@ -76,2 +97,4 @@ get stderr(): string;

get signal(): NodeJS.Signals | null;
static getExitMessage(code: number | null, signal: NodeJS.Signals | null, stderr: string, from: string): string;
static getErrorMessage(err: NodeJS.ErrnoException, from: string): string;
[inspect.custom](): string;

@@ -78,0 +101,0 @@ }

244

build/core.js
// src/core.ts
import assert from "node:assert";
import { spawn } from "node:child_process";
import { spawn, spawnSync } from "node:child_process";
import { AsyncLocalStorage, createHook } from "node:async_hooks";
import { inspect } from "node:util";
import {
exec,
buildCmd,
chalk,
which
which,
ps
} from "./vendor.js";

@@ -16,3 +19,2 @@ import {

parseDuration,
psTree,
quote,

@@ -22,2 +24,3 @@ quotePowerShell

var processCwd = Symbol("processCwd");
var syncExec = Symbol("syncExec");
var storage = new AsyncLocalStorage();

@@ -34,5 +37,9 @@ var hook = createHook({

[processCwd]: process.cwd(),
[syncExec]: false,
verbose: true,
env: process.env,
sync: false,
shell: true,
nothrow: false,
quiet: false,
prefix: "",

@@ -43,4 +50,6 @@ quote: () => {

spawn,
spawnSync,
log
};
var isWin = process.platform == "win32";
try {

@@ -51,3 +60,3 @@ defaults.shell = which.sync("bash");

} catch (err) {
if (process.platform == "win32") {
if (isWin) {
try {

@@ -65,2 +74,10 @@ defaults.shell = which.sync("powershell.exe");

function(pieces, ...args) {
if (!Array.isArray(pieces)) {
return function(...args2) {
const self = this;
return within(() => {
return Object.assign($, pieces).apply(self, args2);
});
};
}
const from = new Error().stack.split(/^\s*at\s/m)[2].trim();

@@ -72,15 +89,23 @@ if (pieces.some((p) => p == void 0)) {

const promise = new ProcessPromise((...args2) => [resolve, reject] = args2);
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());
setImmediate(() => promise.isHalted || promise.run());
return promise;
const cmd = buildCmd(
$.quote,
pieces,
args
);
const snapshot = getStore();
const sync = snapshot[syncExec];
const callback = () => promise.isHalted || promise.run();
promise._bind(
cmd,
from,
resolve,
(v) => {
reject(v);
if (sync)
throw v;
},
snapshot
);
sync ? callback() : setImmediate(callback);
return sync ? promise.output : promise;
},

@@ -90,6 +115,8 @@ {

const target = key in Function.prototype ? _ : getStore();
Reflect.set(target, key, value);
Reflect.set(target, key === "sync" ? syncExec : key, value);
return true;
},
get(_, key) {
if (key === "sync")
return $({ sync: true });
const target = key in Function.prototype ? _ : getStore();

@@ -100,8 +127,2 @@ return Reflect.get(target, key);

);
function substitute(arg) {
if (arg?.stdout) {
return arg.stdout.replace(/\n$/, "");
}
return `${arg}`;
}
var ProcessPromise = class _ProcessPromise extends Promise {

@@ -116,7 +137,8 @@ constructor() {

this._stdio = ["inherit", "pipe", "pipe"];
this._nothrow = false;
this._quiet = false;
this._timeoutSignal = "SIGTERM";
this._resolved = false;
this._halted = false;
this._piped = false;
this._zurk = null;
this._output = null;
this._prerun = noop;

@@ -133,75 +155,91 @@ this._postrun = noop;

run() {
const $2 = this._snapshot;
if (this.child)
return this;
this._prerun();
const $2 = this._snapshot;
const self = this;
const input = $2.input?.stdout ?? $2.input;
if (input)
this.stdio("pipe");
$2.log({
kind: "cmd",
cmd: this._command,
verbose: $2.verbose && !this._quiet
verbose: self.isVerbose()
});
this.child = $2.spawn($2.prefix + this._command, {
this._zurk = exec({
input,
cmd: $2.prefix + this._command,
cwd: $2.cwd ?? $2[processCwd],
ac: $2.ac,
shell: typeof $2.shell === "string" ? $2.shell : true,
env: $2.env,
spawn: $2.spawn,
spawnSync: $2.spawnSync,
stdio: this._stdio,
windowsHide: true,
env: $2.env
});
this.child.on("close", (code, signal) => {
let message = `exit code: ${code}`;
if (code != 0 || signal != null) {
message = `${stderr || "\n"} at ${this._from}`;
message += `
exit code: ${code}${exitCodeInfo(code) ? " (" + exitCodeInfo(code) + ")" : ""}`;
if (signal != null) {
message += `
signal: ${signal}`;
sync: $2[syncExec],
detached: !isWin,
run: (cb) => cb(),
on: {
start: () => {
if (self._timeout) {
const t = setTimeout(
() => self.kill(self._timeoutSignal),
self._timeout
);
self.finally(() => clearTimeout(t)).catch(noop);
}
},
stdout: (data) => {
if (self._piped)
return;
$2.log({ kind: "stdout", data, verbose: self.isVerbose() });
},
stderr: (data) => {
$2.log({ kind: "stderr", data, verbose: self.isVerbose() });
},
end: ({ error, stdout, stderr, stdall, status, signal }) => {
self._resolved = true;
if (error) {
const message = ProcessOutput.getErrorMessage(error, self._from);
const output = new ProcessOutput(
null,
null,
stdout,
stderr,
stdall,
message
);
self._output = output;
self._reject(output);
} else {
const message = ProcessOutput.getExitMessage(
status,
signal,
stderr,
self._from
);
const output = new ProcessOutput(
status,
signal,
stdout,
stderr,
stdall,
message
);
self._output = output;
if (status === 0 || (self._nothrow ?? $2.nothrow)) {
self._resolve(output);
} else {
self._reject(output);
}
}
}
}
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}
errno: ${err.errno} (${errnoMessage(err.errno)})
code: ${err.code}
at ${this._from}`;
this._reject(
new ProcessOutput(null, null, stdout, stderr, combined, message)
);
this._resolved = true;
});
let stdout = "", stderr = "", combined = "";
let onStdout = (data) => {
$2.log({ kind: "stdout", data, verbose: $2.verbose && !this._quiet });
stdout += data;
combined += data;
};
let onStderr = (data) => {
$2.log({ kind: "stderr", data, verbose: $2.verbose && !this._quiet });
stderr += data;
combined += data;
};
if (!this._piped)
this.child.stdout?.on("data", onStdout);
this.child.stderr?.on("data", onStderr);
this._postrun();
if (this._timeout && this._timeoutSignal) {
const t = setTimeout(() => this.kill(this._timeoutSignal), this._timeout);
this.finally(() => clearTimeout(t)).catch(noop);
}
return this;
}
get child() {
return this._zurk?.child;
}
get stdin() {

@@ -271,2 +309,7 @@ this.stdio("pipe");

}
abort(reason) {
if (!this.child)
throw new Error("Trying to abort a process without creating one.");
this._zurk?.ac.abort(reason);
}
async kill(signal = "SIGTERM") {

@@ -277,6 +320,6 @@ if (!this.child)

throw new Error("The process pid is undefined.");
let children = await psTree(this.child.pid);
let children = await ps.tree({ pid: this.child.pid, recursive: true });
for (const p of children) {
try {
process.kill(+p.PID, signal);
process.kill(+p.pid, signal);
} catch (e) {

@@ -286,3 +329,3 @@ }

try {
process.kill(this.child.pid, signal);
process.kill(-this.child.pid, signal);
} catch (e) {

@@ -303,2 +346,6 @@ }

}
isVerbose() {
const { verbose, quiet } = this._snapshot;
return verbose && !(this._quiet ?? quiet);
}
timeout(d, signal = "SIGTERM") {

@@ -316,2 +363,5 @@ this._timeout = parseDuration(d);

}
get output() {
return this._output;
}
};

@@ -330,2 +380,5 @@ var ProcessOutput = class extends Error {

}
valueOf() {
return this._combined.trim();
}
get stdout() {

@@ -343,2 +396,21 @@ return this._stdout;

}
static getExitMessage(code, signal, stderr, from) {
let message = `exit code: ${code}`;
if (code != 0 || signal != null) {
message = `${stderr || "\n"} at ${from}`;
message += `
exit code: ${code}${exitCodeInfo(code) ? " (" + exitCodeInfo(code) + ")" : ""}`;
if (signal != null) {
message += `
signal: ${signal}`;
}
}
return message;
}
static getErrorMessage(err, from) {
return `${err.message}
errno: ${err.errno} (${errnoMessage(err.errno)})
code: ${err.code}
at ${from}`;
}
[inspect.custom]() {

@@ -345,0 +417,0 @@ let stringify = (s, c) => s.length === 0 ? "''" : c(inspect(s));

import { ProcessPromise } from './core.js';
export * from './core.js';
export * from './goods.js';
export { minimist, chalk, fs, which, YAML, ssh } from './vendor.js';
export { minimist, chalk, fs, which, YAML, ssh, ps } from './vendor.js';
export { type Duration, quote, quotePowerShell } from './util.js';
/**
* @deprecated Use $.nothrow() instead.
* @deprecated Use $`cmd`.nothrow() instead.
*/
export declare function nothrow(promise: ProcessPromise): ProcessPromise;
/**
* @deprecated Use $.quiet() instead.
* @deprecated Use $`cmd`.quiet() instead.
*/
export declare function quiet(promise: ProcessPromise): ProcessPromise;
// src/index.ts
export * from "./core.js";
export * from "./goods.js";
import { minimist, chalk, fs, which, YAML, ssh } from "./vendor.js";
import { minimist, chalk, fs, which, YAML, ssh, ps } from "./vendor.js";
import { quote, quotePowerShell } from "./util.js";

@@ -18,2 +18,3 @@ function nothrow(promise) {

nothrow,
ps,
quiet,

@@ -20,0 +21,0 @@ quote,

@@ -1,3 +0,1 @@

import { psTreeModule } from './vendor.js';
export declare const psTree: (arg1: number) => Promise<readonly psTreeModule.PS[]>;
export declare function noop(): void;

@@ -4,0 +2,0 @@ export declare function randomId(): string;

// src/util.ts
import { promisify } from "node:util";
import { chalk, psTreeModule } from "./vendor.js";
var psTree = promisify(psTreeModule);
import { chalk } from "./vendor.js";
function noop() {

@@ -330,3 +328,2 @@ }

parseDuration,
psTree,
quote,

@@ -333,0 +330,0 @@ quotePowerShell,

@@ -5,3 +5,7 @@ // Generated by dts-bundle-generator v9.3.1

import { default as ps } from '@webpod/ps';
import * as fs from 'fs';
import * as cp from 'node:child_process';
import EventEmitter from 'node:events';
import { Readable, Stream, Writable } from 'node:stream';

@@ -313,2 +317,64 @@ declare type ErrnoException = NodeJS.ErrnoException;

declare const fetch$1: typeof globalThis.fetch;
type TQuote = (input: string) => string;
export declare const buildCmd: (quote: TQuote, pieces: TemplateStringsArray, args: any[], subs?: TSubstitute) => string | Promise<string>;
type TSubstitute = (arg: any) => string;
type TSpawnError = any;
type TSpawnResult = {
stderr: string;
stdout: string;
stdall: string;
stdio: [
Readable | Writable,
Writable,
Writable
];
status: number | null;
signal: NodeJS.Signals | null;
duration: number;
ctx: TSpawnCtxNormalized;
error?: TSpawnError;
child?: TChild;
};
type TSpawnListeners = {
start: (data: TChild, ctx: TSpawnCtxNormalized) => void;
stdout: (data: Buffer, ctx: TSpawnCtxNormalized) => void;
stderr: (data: Buffer, ctx: TSpawnCtxNormalized) => void;
abort: (error: Event, ctx: TSpawnCtxNormalized) => void;
err: (error: Error, ctx: TSpawnCtxNormalized) => void;
end: (result: TSpawnResult, ctx: TSpawnCtxNormalized) => void;
};
type TSpawnCtx = Partial<Omit<TSpawnCtxNormalized, "child">>;
type TChild = ReturnType<typeof cp.spawn>;
type TInput = string | Buffer | Stream;
interface TSpawnCtxNormalized {
id: string;
cwd: string;
cmd: string;
sync: boolean;
args: ReadonlyArray<string>;
input: TInput | null;
stdio: [
"pipe",
"pipe",
"pipe"
];
detached: boolean;
env: Record<string, string | undefined>;
ee: EventEmitter;
on: Partial<TSpawnListeners>;
ac: AbortController;
shell: string | true | undefined;
spawn: typeof cp.spawn;
spawnSync: typeof cp.spawnSync;
spawnOpts: Record<string, any>;
callback: (err: TSpawnError, result: TSpawnResult) => void;
stdin: Readable;
stdout: Writable;
stderr: Writable;
child?: TChild;
fulfilled?: TSpawnResult;
error?: any;
run: (cb: () => void, ctx: TSpawnCtxNormalized) => void;
}
export declare const exec: (ctx: TSpawnCtx) => TSpawnCtxNormalized;
type ColorSupportLevel = 0 | 1 | 2 | 3;

@@ -618,12 +684,2 @@ export interface ChalkInstance {

}
declare namespace ps_tree$1 {
interface PS {
COMMAND: string;
PPID: string;
PID: string;
STAT: string;
}
const prototype: {};
}
declare function ps_tree$1(pid: number, callback: (error: Error | null, children: readonly ps_tree$1.PS[]) => void): void;
type RemoteShell = ((pieces: TemplateStringsArray, ...values: any[]) => Promise<Result>) & {

@@ -648,3 +704,3 @@ exit: () => void;

type SshOption = "AddKeysToAgent" | "AddressFamily" | "BatchMode" | "BindAddress" | "CanonicalDomains" | "CanonicalizeFallbackLocal" | "CanonicalizeHostname" | "CanonicalizeMaxDots" | "CanonicalizePermittedCNAMEs" | "CASignatureAlgorithms" | "CertificateFile" | "ChallengeResponseAuthentication" | "CheckHostIP" | "Ciphers" | "ClearAllForwardings" | "Compression" | "ConnectionAttempts" | "ConnectTimeout" | "ControlMaster" | "ControlPath" | "ControlPersist" | "DynamicForward" | "EscapeChar" | "ExitOnForwardFailure" | "FingerprintHash" | "ForwardAgent" | "ForwardX11" | "ForwardX11Timeout" | "ForwardX11Trusted" | "GatewayPorts" | "GlobalKnownHostsFile" | "GSSAPIAuthentication" | "GSSAPIDelegateCredentials" | "HashKnownHosts" | "Host" | "HostbasedAcceptedAlgorithms" | "HostbasedAuthentication" | "HostKeyAlgorithms" | "HostKeyAlias" | "Hostname" | "IdentitiesOnly" | "IdentityAgent" | "IdentityFile" | "IPQoS" | "KbdInteractiveAuthentication" | "KbdInteractiveDevices" | "KexAlgorithms" | "KnownHostsCommand" | "LocalCommand" | "LocalForward" | "LogLevel" | "MACs" | "Match" | "NoHostAuthenticationForLocalhost" | "NumberOfPasswordPrompts" | "PasswordAuthentication" | "PermitLocalCommand" | "PermitRemoteOpen" | "PKCS11Provider" | "Port" | "PreferredAuthentications" | "ProxyCommand" | "ProxyJump" | "ProxyUseFdpass" | "PubkeyAcceptedAlgorithms" | "PubkeyAuthentication" | "RekeyLimit" | "RemoteCommand" | "RemoteForward" | "RequestTTY" | "SendEnv" | "ServerAliveInterval" | "ServerAliveCountMax" | "SetEnv" | "StreamLocalBindMask" | "StreamLocalBindUnlink" | "StrictHostKeyChecking" | "TCPKeepAlive" | "Tunnel" | "TunnelDevice" | "UpdateHostKeys" | "UseKeychain" | "User" | "UserKnownHostsFile" | "VerifyHostKeyDNS" | "VisualHostKey" | "XAuthLocation";
type RequestInfo$1 = Parameters<typeof fetch$1>[0];
export type RequestInfo = Parameters<typeof fetch$1>[0];
type RequestInit$1 = Parameters<typeof fetch$1>[1];

@@ -669,9 +725,8 @@ export declare const globbyModule: {

Options$1 as GlobbyOptions,
RequestInfo$1 as RequestInfo,
RequestInit$1 as RequestInit,
fetch$1 as nodeFetch,
fs$1 as fs,
ps_tree$1 as psTreeModule,
ps,
};
export {};
{
"name": "zx",
"version": "7.2.3-dev.7e728f6",
"version": "7.2.3-dev.c2cda4a",
"description": "A tool for writing better scripts",

@@ -58,3 +58,3 @@ "type": "module",

"@types/fs-extra": "^11.0.4",
"@types/node": ">=20.11.19"
"@types/node": ">=20.11.28"
},

@@ -66,10 +66,10 @@ "devDependencies": {

"@types/node": ">=20.11.19",
"@types/ps-tree": "^1.1.6",
"@types/which": "^3.0.3",
"@webpod/ps": "^0.0.0-beta.2",
"c8": "^7.13.0",
"chalk": "^5.3.0",
"dts-bundle-generator": "^9.3.1",
"esbuild": "^0.20.1",
"esbuild": "^0.20.2",
"esbuild-node-externals": "^1.13.0",
"esbuild-plugin-entry-chunks": "^0.1.8",
"esbuild-plugin-entry-chunks": "^0.1.11",
"fs-extra": "^11.2.0",

@@ -82,8 +82,8 @@ "fx": "*",

"prettier": "^2.8.8",
"ps-tree": "^1.2.0",
"tsd": "^0.28.1",
"typescript": "^5.0.4",
"tsd": "^0.30.7",
"typescript": "^5.4.3",
"webpod": "^0",
"which": "^3.0.0",
"yaml": "^2.3.4"
"yaml": "^2.4.1",
"zurk": "^0.0.32"
},

@@ -90,0 +90,0 @@ "publishConfig": {

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc