Commit 9d28d8f

Anton Golub <antongolub@antongolub.com>
2025-04-26 13:50:42
refactor(cli): optimize `main()` inners
1 parent dc448d4
build/cli.cjs
@@ -140,6 +140,16 @@ var import_node_process2 = __toESM(require("process"), 1);
 var import_meta = {};
 var EXT = ".mjs";
 var EXT_RE = /^\.[mc]?[jt]sx?$/;
+var argv = (0, import_index.parseArgv)(import_node_process2.default.argv.slice(2), {
+  default: (0, import_index.resolveDefaults)({ ["prefer-local"]: false }, "ZX_", import_node_process2.default.env, /* @__PURE__ */ new Set(["env", "install", "registry"])),
+  // exclude 'prefer-local' to let minimist infer the type
+  string: ["shell", "prefix", "postfix", "eval", "cwd", "ext", "registry", "env"],
+  boolean: ["version", "help", "quiet", "verbose", "install", "repl", "experimental"],
+  alias: { e: "eval", i: "install", v: "version", h: "help", l: "prefer-local", "env-file": "env" },
+  stopEarly: true,
+  parseBoolean: true,
+  camelCase: true
+});
 isMain() && main().catch((err) => {
   if (err instanceof import_index.ProcessOutput) {
     console.error("Error:", err.message);
@@ -177,21 +187,17 @@ function printUsage() {
  ${import_index.chalk.italic("Full documentation:")} ${import_index.chalk.underline("https://google.github.io/zx/")}
 `);
 }
-var argv = (0, import_index.parseArgv)(import_node_process2.default.argv.slice(2), {
-  default: { ["prefer-local"]: false },
-  // exclude 'prefer-local' to let minimist infer the type
-  string: ["shell", "prefix", "postfix", "eval", "cwd", "ext", "registry", "env"],
-  boolean: ["version", "help", "quiet", "verbose", "install", "repl", "experimental"],
-  alias: { e: "eval", i: "install", v: "version", h: "help", l: "prefer-local", "env-file": "env" },
-  stopEarly: true,
-  parseBoolean: true,
-  camelCase: true
-}, (0, import_index.resolveDefaults)({}, "ZX_", import_node_process2.default.env, /* @__PURE__ */ new Set(["env", "install", "registry"])));
 function main() {
   return __async(this, null, function* () {
     var _a2;
-    yield require("./globals.cjs");
-    argv.ext = normalizeExt(argv.ext);
+    if (argv.version) {
+      console.log(import_index.VERSION);
+      return;
+    }
+    if (argv.help) {
+      printUsage();
+      return;
+    }
     if (argv.cwd) import_index.$.cwd = argv.cwd;
     if (argv.env) {
       const envfile = import_index.path.resolve((_a2 = import_index.$.cwd) != null ? _a2 : import_node_process2.default.cwd(), argv.env);
@@ -204,18 +210,12 @@ function main() {
     if (argv.prefix) import_index.$.prefix = argv.prefix;
     if (argv.postfix) import_index.$.postfix = argv.postfix;
     if (argv.preferLocal) import_index.$.preferLocal = argv.preferLocal;
-    if (argv.version) {
-      console.log(import_index.VERSION);
-      return;
-    }
-    if (argv.help) {
-      printUsage();
-      return;
-    }
+    yield require("./globals.cjs");
     if (argv.repl) {
       yield startRepl();
       return;
     }
+    argv.ext = normalizeExt(argv.ext);
     const { script, scriptPath, tempPath } = yield readScript();
     yield runScript(script, scriptPath, tempPath);
   });
build/cli.d.ts
@@ -1,8 +1,8 @@
 #!/usr/bin/env node
 import { transformMarkdown } from './md.js';
 import { type minimist } from './vendor.js';
-export declare function printUsage(): void;
 export declare const argv: minimist.ParsedArgs;
+export declare function printUsage(): void;
 export declare function main(): Promise<void>;
 export { transformMarkdown };
 export declare function injectGlobalRequire(origin: string): void;
build/cli.js
build/index.cjs
@@ -1,7 +1,6 @@
 "use strict";
 const {
   __pow,
-  __spreadValues,
   __export,
   __reExport,
   __toESM,
@@ -69,11 +68,11 @@ var parseArgv = (args = import_node_process.default.argv.slice(2), opts = {}, de
     m[_k] = _v;
     return m;
   },
-  __spreadValues({}, defs)
+  defs
 );
 function updateArgv(args, opts) {
   for (const k in argv) delete argv[k];
-  Object.assign(argv, parseArgv(args, opts));
+  parseArgv(args, opts, argv);
 }
 var argv = parseArgv();
 function sleep(duration) {
@@ -88,7 +87,7 @@ var responseToReadable = (response, rs) => {
     rs.push(null);
     return rs;
   }
-  rs._read = () => __async(void 0, null, function* () {
+  rs._read = () => __async(null, null, function* () {
     const result = yield reader.read();
     if (!result.done) rs.push(import_node_buffer.Buffer.from(result.value));
     else rs.push(null);
@@ -238,7 +237,7 @@ function spinner(title, callback) {
     let i = 0;
     const stream = import_core.$.log.output || import_node_process.default.stderr;
     const spin = () => stream.write(`  ${"\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F"[i++ % 10]} ${title}\r`);
-    return (0, import_core.within)(() => __async(this, null, function* () {
+    return (0, import_core.within)(() => __async(null, null, function* () {
       import_core.$.verbose = false;
       const id = setInterval(spin, 100);
       try {
build/vendor-core.cjs
@@ -19,7 +19,7 @@ var require_posix = __commonJS({
     exports2.sync = exports2.isexe = void 0;
     var fs_1 = require("fs");
     var promises_1 = require("fs").promises;
-    var isexe = (_0, ..._1) => __async(exports2, [_0, ..._1], function* (path, options = {}) {
+    var isexe = (_0, ..._1) => __async(null, [_0, ..._1], function* (path, options = {}) {
       const { ignoreErrors = false } = options;
       try {
         return checkStat(yield (0, promises_1.stat)(path), options);
@@ -73,7 +73,7 @@ var require_win32 = __commonJS({
     exports2.sync = exports2.isexe = void 0;
     var fs_1 = require("fs");
     var promises_1 = require("fs").promises;
-    var isexe = (_0, ..._1) => __async(exports2, [_0, ..._1], function* (path, options = {}) {
+    var isexe = (_0, ..._1) => __async(null, [_0, ..._1], function* (path, options = {}) {
       const { ignoreErrors = false } = options;
       try {
         return checkStat(yield (0, promises_1.stat)(path), path, options);
@@ -208,7 +208,7 @@ var require_lib = __commonJS({
       const prefix = !pathPart && rRel.test(cmd) ? cmd.slice(0, 2) : "";
       return prefix + join(pathPart, cmd);
     };
-    var which2 = (_0, ..._1) => __async(exports2, [_0, ..._1], function* (cmd, opt = {}) {
+    var which2 = (_0, ..._1) => __async(null, [_0, ..._1], function* (cmd, opt = {}) {
       const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
       const found = [];
       for (const envPart of pathEnv) {
@@ -1273,7 +1273,7 @@ var _tree = ({
     return Promise.reject(err);
   }
 };
-var tree = (opts, cb) => __async(void 0, null, function* () {
+var tree = (opts, cb) => __async(null, null, function* () {
   return _tree({ opts, cb });
 });
 var treeSync = (opts, cb) => _tree({ opts, cb, sync: true });
build/vendor-extra.cjs
@@ -6923,7 +6923,7 @@ var require_make_dir = __commonJS({
       if (typeof options === "number") return options;
       return __spreadValues(__spreadValues({}, defaults), options).mode;
     };
-    module2.exports.makeDir = (dir, options) => __async(exports2, null, function* () {
+    module2.exports.makeDir = (dir, options) => __async(null, null, function* () {
       checkPath(dir);
       return fs6.mkdir(dir, {
         mode: getMode(options),
@@ -11577,7 +11577,7 @@ var init_node = __esm({
       const { body: o3 } = i[H];
       return o3 === null ? 0 : yr(o3) ? o3.size : import_node_buffer2.Buffer.isBuffer(o3) ? o3.length : o3 && typeof o3.getLengthSync == "function" && o3.hasKnownLength && o3.hasKnownLength() ? o3.getLengthSync() : null;
     }, "getTotalBytes");
-    Xs = n2((_0, _1) => __async(void 0, [_0, _1], function* (i, { body: o3 }) {
+    Xs = n2((_0, _1) => __async(null, [_0, _1], function* (i, { body: o3 }) {
       o3 === null ? i.end() : yield Zs(o3, i);
     }), "writeToStream");
     gr = typeof import_node_http2.default.validateHeaderName == "function" ? import_node_http2.default.validateHeaderName : (i) => {
@@ -12335,7 +12335,7 @@ _streams = new WeakMap();
 _ended = new WeakMap();
 _aborted = new WeakMap();
 _onFinished = new WeakMap();
-var onMergedStreamFinished = (passThroughStream, streams) => __async(void 0, null, function* () {
+var onMergedStreamFinished = (passThroughStream, streams) => __async(null, null, function* () {
   updateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_COUNT);
   const controller = new AbortController();
   try {
@@ -12348,10 +12348,10 @@ var onMergedStreamFinished = (passThroughStream, streams) => __async(void 0, nul
     updateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_COUNT);
   }
 });
-var onMergedStreamEnd = (_0, _1) => __async(void 0, [_0, _1], function* (passThroughStream, { signal }) {
+var onMergedStreamEnd = (_0, _1) => __async(null, [_0, _1], function* (passThroughStream, { signal }) {
   yield (0, import_promises.finished)(passThroughStream, { signal, cleanup: true });
 });
-var onInputStreamsUnpipe = (_0, _1, _2) => __async(void 0, [_0, _1, _2], function* (passThroughStream, streams, { signal }) {
+var onInputStreamsUnpipe = (_0, _1, _2) => __async(null, [_0, _1, _2], function* (passThroughStream, streams, { signal }) {
   try {
     for (var iter = __forAwait((0, import_node_events.on)(passThroughStream, "unpipe", { signal })), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
       const [unpipedStream] = temp.value;
@@ -12375,7 +12375,7 @@ var validateStream = (stream) => {
     throw new TypeError(`Expected a readable stream, got: \`${typeof stream}\`.`);
   }
 };
-var endWhenStreamsDone = (_0) => __async(void 0, [_0], function* ({ passThroughStream, stream, streams, ended, aborted, onFinished }) {
+var endWhenStreamsDone = (_0) => __async(null, [_0], function* ({ passThroughStream, stream, streams, ended, aborted, onFinished }) {
   updateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_PER_STREAM);
   const controller = new AbortController();
   try {
@@ -12397,7 +12397,7 @@ var endWhenStreamsDone = (_0) => __async(void 0, [_0], function* ({ passThroughS
   }
 });
 var isAbortError = (error) => (error == null ? void 0 : error.code) === "ERR_STREAM_PREMATURE_CLOSE";
-var afterMergedStreamFinished = (onFinished, stream) => __async(void 0, null, function* () {
+var afterMergedStreamFinished = (onFinished, stream) => __async(null, null, function* () {
   try {
     yield onFinished;
     abortStream(stream);
@@ -12409,7 +12409,7 @@ var afterMergedStreamFinished = (onFinished, stream) => __async(void 0, null, fu
     }
   }
 });
-var onInputStreamEnd = (_0) => __async(void 0, [_0], function* ({ passThroughStream, stream, streams, ended, aborted, controller: { signal } }) {
+var onInputStreamEnd = (_0) => __async(null, [_0], function* ({ passThroughStream, stream, streams, ended, aborted, controller: { signal } }) {
   try {
     yield (0, import_promises.finished)(stream, { signal, cleanup: true, readable: true, writable: false });
     if (streams.has(stream)) {
@@ -12426,7 +12426,7 @@ var onInputStreamEnd = (_0) => __async(void 0, [_0], function* ({ passThroughStr
     }
   }
 });
-var onInputStreamUnpipe = (_0) => __async(void 0, [_0], function* ({ stream, streams, ended, aborted, controller: { signal } }) {
+var onInputStreamUnpipe = (_0) => __async(null, [_0], function* ({ stream, streams, ended, aborted, controller: { signal } }) {
   yield (0, import_node_events.once)(stream, unpipeEvent, { signal });
   streams.delete(stream);
   ended.delete(stream);
@@ -12578,7 +12578,7 @@ var normalizeOptions = (options = {}) => {
     ignore: [...(_b2 = options.ignore) != null ? _b2 : [], ...defaultIgnoredDirectories]
   };
 };
-var isIgnoredByIgnoreFiles = (patterns, options) => __async(void 0, null, function* () {
+var isIgnoredByIgnoreFiles = (patterns, options) => __async(null, null, function* () {
   const { cwd, suppressErrors, deep, ignore } = normalizeOptions(options);
   const paths = yield (0, import_fast_glob.default)(patterns, __spreadValues({
     cwd,
@@ -12587,7 +12587,7 @@ var isIgnoredByIgnoreFiles = (patterns, options) => __async(void 0, null, functi
     ignore
   }, ignoreFilesGlobOptions));
   const files = yield Promise.all(
-    paths.map((filePath) => __async(void 0, null, function* () {
+    paths.map((filePath) => __async(null, null, function* () {
       return {
         filePath,
         content: yield import_promises3.default.readFile(filePath, "utf8")
@@ -12627,13 +12627,13 @@ var getDirectoryGlob = ({ directoryPath, files, extensions }) => {
   const extensionGlob = (extensions == null ? void 0 : extensions.length) > 0 ? `.${extensions.length > 1 ? `{${extensions.join(",")}}` : extensions[0]}` : "";
   return files ? files.map((file) => import_node_path3.default.posix.join(directoryPath, `**/${import_node_path3.default.extname(file) ? file : `${file}${extensionGlob}`}`)) : [import_node_path3.default.posix.join(directoryPath, `**${extensionGlob ? `/*${extensionGlob}` : ""}`)];
 };
-var directoryToGlob = (_0, ..._1) => __async(void 0, [_0, ..._1], function* (directoryPaths, {
+var directoryToGlob = (_0, ..._1) => __async(null, [_0, ..._1], function* (directoryPaths, {
   cwd = import_node_process2.default.cwd(),
   files,
   extensions
 } = {}) {
   const globs = yield Promise.all(
-    directoryPaths.map((directoryPath) => __async(void 0, null, function* () {
+    directoryPaths.map((directoryPath) => __async(null, null, function* () {
       return (yield isDirectory(normalizePathForDirectoryGlob(directoryPath, cwd))) ? getDirectoryGlob({ directoryPath, files, extensions }) : directoryPath;
     }))
   );
@@ -12673,7 +12673,7 @@ var normalizeOptions2 = (options = {}) => {
   checkCwdOption(options.cwd);
   return options;
 };
-var normalizeArguments = (function_) => (patterns, options) => __async(void 0, null, function* () {
+var normalizeArguments = (function_) => (patterns, options) => __async(null, null, function* () {
   return function_(toPatternsArray(patterns), normalizeOptions2(options));
 });
 var normalizeArgumentsSync = (function_) => (patterns, options) => function_(toPatternsArray(patterns), normalizeOptions2(options));
@@ -12685,7 +12685,7 @@ var getIgnoreFilesPatterns = (options) => {
   }
   return patterns;
 };
-var getFilter = (options) => __async(void 0, null, function* () {
+var getFilter = (options) => __async(null, null, function* () {
   const ignoreFilesPatterns = getIgnoreFilesPatterns(options);
   return createFilterFunction(
     ignoreFilesPatterns.length > 0 && (yield isIgnoredByIgnoreFiles(ignoreFilesPatterns, options))
@@ -12738,7 +12738,7 @@ var convertNegativePatterns = (patterns, options) => {
   return tasks;
 };
 var normalizeExpandDirectoriesOption = (options, cwd) => __spreadValues(__spreadValues({}, cwd ? { cwd } : {}), Array.isArray(options) ? { files: options } : options);
-var generateTasks = (patterns, options) => __async(void 0, null, function* () {
+var generateTasks = (patterns, options) => __async(null, null, function* () {
   const globTasks = convertNegativePatterns(patterns, options);
   const { cwd, expandDirectories } = options;
   if (!expandDirectories) {
@@ -12746,7 +12746,7 @@ var generateTasks = (patterns, options) => __async(void 0, null, function* () {
   }
   const directoryToGlobOptions = normalizeExpandDirectoriesOption(expandDirectories, cwd);
   return Promise.all(
-    globTasks.map((task) => __async(void 0, null, function* () {
+    globTasks.map((task) => __async(null, null, function* () {
       let { patterns: patterns2, options: options2 } = task;
       [
         patterns2,
@@ -12773,7 +12773,7 @@ var generateTasksSync = (patterns, options) => {
     return { patterns: patterns2, options: options2 };
   });
 };
-var globby = normalizeArguments((patterns, options) => __async(void 0, null, function* () {
+var globby = normalizeArguments((patterns, options) => __async(null, null, function* () {
   const [
     tasks,
     filter
src/cli.ts
@@ -39,6 +39,18 @@ import process from 'node:process'
 const EXT = '.mjs'
 const EXT_RE = /^\.[mc]?[jt]sx?$/
 
+// prettier-ignore
+export const argv: minimist.ParsedArgs = parseArgv(process.argv.slice(2), {
+  default: resolveDefaults({ ['prefer-local']: false } as any, 'ZX_', process.env, new Set(['env', 'install', 'registry'])),
+  // exclude 'prefer-local' to let minimist infer the type
+  string: ['shell', 'prefix', 'postfix', 'eval', 'cwd', 'ext', 'registry', 'env'],
+  boolean: ['version', 'help', 'quiet', 'verbose', 'install', 'repl', 'experimental'],
+  alias: { e: 'eval', i: 'install', v: 'version', h: 'help', l: 'prefer-local', 'env-file': 'env' },
+  stopEarly: true,
+  parseBoolean: true,
+  camelCase: true,
+})
+
 isMain() &&
   main().catch((err) => {
     if (err instanceof ProcessOutput) {
@@ -80,21 +92,15 @@ export function printUsage() {
 `)
 }
 
-// prettier-ignore
-export const argv: minimist.ParsedArgs = parseArgv(process.argv.slice(2), {
-  default: { ['prefer-local']: false },
-  // exclude 'prefer-local' to let minimist infer the type
-  string: ['shell', 'prefix', 'postfix', 'eval', 'cwd', 'ext', 'registry', 'env'],
-  boolean: ['version', 'help', 'quiet', 'verbose', 'install', 'repl', 'experimental'],
-  alias: { e: 'eval', i: 'install', v: 'version', h: 'help', l: 'prefer-local', 'env-file': 'env' },
-  stopEarly: true,
-  parseBoolean: true,
-  camelCase: true,
-}, resolveDefaults({} as any, 'ZX_', process.env, new Set(['env', 'install', 'registry'])))
-
 export async function main(): Promise<void> {
-  await import('zx/globals')
-  argv.ext = normalizeExt(argv.ext)
+  if (argv.version) {
+    console.log(VERSION)
+    return
+  }
+  if (argv.help) {
+    printUsage()
+    return
+  }
   if (argv.cwd) $.cwd = argv.cwd
   if (argv.env) {
     const envfile = path.resolve($.cwd ?? process.cwd(), argv.env)
@@ -107,18 +113,13 @@ export async function main(): Promise<void> {
   if (argv.prefix) $.prefix = argv.prefix
   if (argv.postfix) $.postfix = argv.postfix
   if (argv.preferLocal) $.preferLocal = argv.preferLocal
-  if (argv.version) {
-    console.log(VERSION)
-    return
-  }
-  if (argv.help) {
-    printUsage()
-    return
-  }
+
+  await import('zx/globals')
   if (argv.repl) {
     await startRepl()
     return
   }
+  argv.ext = normalizeExt(argv.ext)
 
   const { script, scriptPath, tempPath } = await readScript()
   await runScript(script, scriptPath, tempPath)
src/goods.ts
@@ -49,12 +49,12 @@ export const parseArgv = (
       m[_k] = _v
       return m
     },
-    { ...defs } as minimist.ParsedArgs
+    defs as minimist.ParsedArgs
   )
 
 export function updateArgv(args?: string[], opts?: ArgvOpts) {
   for (const k in argv) delete argv[k]
-  Object.assign(argv, parseArgv(args, opts))
+  parseArgv(args, opts, argv)
 }
 
 export const argv: minimist.ParsedArgs = parseArgv()
.size-limit.json
@@ -24,7 +24,7 @@
   {
     "name": "js parts",
     "path": "build/*.{js,cjs}",
-    "limit": "816.30 kB",
+    "limit": "816.20 kB",
     "brotli": false,
     "gzip": false
   },
@@ -38,14 +38,14 @@
   {
     "name": "vendor",
     "path": "build/vendor-*",
-    "limit": "769.15 kB",
+    "limit": "769.10 kB",
     "brotli": false,
     "gzip": false
   },
   {
     "name": "all",
     "path": ["build/*", "man/*", "README.md", "LICENSE"],
-    "limit": "872.70 kB",
+    "limit": "872.50 kB",
     "brotli": false,
     "gzip": false
   }