Commit 323d19a

Anton Golub <antongolub@antongolub.com>
2025-04-08 20:19:33
fix: workaround jsr global types (#1189)
relates #1188
1 parent 698b53b
build/cli.cjs
@@ -37,8 +37,9 @@ var import_node_repl = __toESM(require("repl"), 1);
 var import_node_util = require("util");
 var import_core = require("./core.cjs");
 var import_vendor_core = require("./vendor-core.cjs");
+var import_node_process = __toESM(require("process"), 1);
 var _a;
-var HISTORY = (_a = process.env.ZX_REPL_HISTORY) != null ? _a : import_node_path.default.join(import_node_os.default.homedir(), ".zx_repl_history");
+var HISTORY = (_a = import_node_process.default.env.ZX_REPL_HISTORY) != null ? _a : import_node_path.default.join(import_node_os.default.homedir(), ".zx_repl_history");
 function startRepl() {
   return __async(this, arguments, function* (history = HISTORY) {
     import_core.defaults.verbose = false;
@@ -135,6 +136,7 @@ function transformMarkdown(buf) {
 
 // src/cli.ts
 var import_vendor = require("./vendor.cjs");
+var import_node_process2 = __toESM(require("process"), 1);
 var import_meta = {};
 var EXT = ".mjs";
 var EXT_RE = /^\.[mc]?[jt]sx?$/;
@@ -144,7 +146,7 @@ isMain() && main().catch((err) => {
   } else {
     console.error(err);
   }
-  process.exitCode = 1;
+  import_node_process2.default.exitCode = 1;
 });
 function printUsage() {
   console.log(`
@@ -175,7 +177,7 @@ function printUsage() {
  ${import_index.chalk.italic("Full documentation:")} ${import_index.chalk.underline("https://google.github.io/zx/")}
 `);
 }
-var argv = (0, import_index.parseArgv)(process.argv.slice(2), {
+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"],
@@ -184,15 +186,15 @@ var argv = (0, import_index.parseArgv)(process.argv.slice(2), {
   stopEarly: true,
   parseBoolean: true,
   camelCase: true
-}, (0, import_index.resolveDefaults)({}, "ZX_", process.env, /* @__PURE__ */ new Set(["env", "install", "registry"])));
+}, (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 import("./globals.cjs");
+    yield require("./globals.cjs");
     argv.ext = normalizeExt(argv.ext);
     if (argv.cwd) import_index.$.cwd = argv.cwd;
     if (argv.env) {
-      const envfile = import_index.path.resolve((_a2 = import_index.$.cwd) != null ? _a2 : process.cwd(), argv.env);
+      const envfile = import_index.path.resolve((_a2 = import_index.$.cwd) != null ? _a2 : import_node_process2.default.cwd(), argv.env);
       import_index.dotenv.config(envfile);
       (0, import_index.resolveDefaults)();
     }
@@ -238,7 +240,7 @@ function runScript(script, scriptPath, tempPath) {
         yield (0, import_deps.installDeps)((0, import_deps.parseDeps)(script), cwd, argv.registry);
       }
       injectGlobalRequire(scriptPath);
-      process.once("exit", rmTemp);
+      import_node_process2.default.once("exit", rmTemp);
       yield import(import_node_url.default.pathToFileURL(scriptPath).toString());
     } finally {
       rmTemp();
@@ -269,7 +271,7 @@ function readScript() {
       tempPath = getFilepath(import_index.$.cwd, "zx", argv.ext);
       if (script.length === 0) {
         printUsage();
-        process.exitCode = 1;
+        import_node_process2.default.exitCode = 1;
         throw new Error("No script provided");
       }
     } else if (/^https?:/.test(firstArg)) {
@@ -294,7 +296,7 @@ function readScript() {
 }
 function readScriptFromStdin() {
   return __async(this, null, function* () {
-    return !process.stdin.isTTY ? (0, import_index.stdin)() : "";
+    return !import_node_process2.default.stdin.isTTY ? (0, import_index.stdin)() : "";
   });
 }
 function readScriptFromHttp(remote) {
@@ -302,7 +304,7 @@ function readScriptFromHttp(remote) {
     const res = yield (0, import_index.fetch)(remote);
     if (!res.ok) {
       console.error(`Error: Can't get ${remote}`);
-      process.exit(1);
+      import_node_process2.default.exit(1);
     }
     return res.text();
   });
@@ -313,7 +315,7 @@ function injectGlobalRequire(origin) {
   const require2 = (0, import_vendor.createRequire)(origin);
   Object.assign(globalThis, { __filename, __dirname, require: require2 });
 }
-function isMain(metaurl = import_meta_url, scriptpath = process.argv[1]) {
+function isMain(metaurl = import_meta_url, scriptpath = import_node_process2.default.argv[1]) {
   if (metaurl.startsWith("file:")) {
     const modulePath = import_node_url.default.fileURLToPath(metaurl).replace(/\.\w+$/, "");
     const mainPath = import_index.fs.realpathSync(scriptpath).replace(/\.\w+$/, "");
@@ -329,7 +331,7 @@ function getFilepath(cwd = ".", name = "zx", _ext) {
   return [
     name + ext,
     name + "-" + (0, import_util2.randomId)() + ext
-  ].map((f) => import_index.path.resolve(process.cwd(), cwd, f)).find((f) => !import_index.fs.existsSync(f));
+  ].map((f) => import_index.path.resolve(import_node_process2.default.cwd(), cwd, f)).find((f) => !import_index.fs.existsSync(f));
 }
 /* c8 ignore next 100 */
 // Annotate the CommonJS export names for ESM import in node:
build/core.cjs
@@ -252,6 +252,7 @@ var import_util = require("./util.cjs");
 // src/log.ts
 var import_vendor_core = require("./vendor-core.cjs");
 var import_node_util = require("util");
+var import_node_process = __toESM(require("process"), 1);
 var formatters = {
   cmd({ cmd }) {
     return formatCmd(cmd);
@@ -287,7 +288,7 @@ var formatters = {
 var log = function(entry) {
   var _a;
   if (!entry.verbose) return;
-  const stream = log.output || process.stderr;
+  const stream = log.output || import_node_process.default.stderr;
   const format = ((_a = log.formatters) == null ? void 0 : _a[entry.kind]) || formatters[entry.kind];
   if (!format) return;
   const data = format(entry);
@@ -386,11 +387,13 @@ function formatCmd(cmd) {
 // src/core.ts
 var import_node_path = __toESM(require("path"), 1);
 var os = __toESM(require("os"), 1);
+var import_node_buffer = require("buffer");
+var import_node_process2 = __toESM(require("process"), 1);
 var import_vendor_core3 = require("./vendor-core.cjs");
 var import_util2 = require("./util.cjs");
 var CWD = Symbol("processCwd");
 var SYNC = Symbol("syncExec");
-var EOL = Buffer.from(import_node_os.EOL);
+var EOL = import_node_buffer.Buffer.from(import_node_os.EOL);
 var BR_CC = "\n".charCodeAt(0);
 var SIGTERM = "SIGTERM";
 var ENV_PREFIX = "ZX_";
@@ -415,10 +418,10 @@ function within(callback) {
   return storage.run(__spreadValues({}, getStore()), callback);
 }
 var defaults = resolveDefaults({
-  [CWD]: process.cwd(),
+  [CWD]: import_node_process2.default.cwd(),
   [SYNC]: false,
   verbose: false,
-  env: process.env,
+  env: import_node_process2.default.env,
   sync: false,
   shell: true,
   stdio: "pipe",
@@ -459,9 +462,9 @@ var $ = new Proxy(
     );
     const sync = snapshot[SYNC];
     bound.push([cmd, from, snapshot]);
-    const process2 = new ProcessPromise(import_util.noop);
-    if (!process2.isHalted() || sync) process2.run();
-    return sync ? process2.output : process2;
+    const process3 = new ProcessPromise(import_util.noop);
+    if (!process3.isHalted() || sync) process3.run();
+    return sync ? process3.output : process3;
   },
   {
     set(_, key, value) {
@@ -895,7 +898,7 @@ var _ProcessOutput = class _ProcessOutput extends Error {
     return JSON.parse(this.stdall);
   }
   buffer() {
-    return Buffer.from(this.stdall);
+    return import_node_buffer.Buffer.from(this.stdall);
   }
   blob(type = "text/plain") {
     if (!globalThis.Blob)
@@ -979,30 +982,30 @@ function syncProcessCwd(flag = true) {
   else cwdSyncHook.disable();
 }
 function syncCwd() {
-  if ($[CWD] != process.cwd()) process.chdir($[CWD]);
+  if ($[CWD] != import_node_process2.default.cwd()) import_node_process2.default.chdir($[CWD]);
 }
 function cd(dir) {
   if (dir instanceof ProcessOutput) {
     dir = dir.toString().trim();
   }
   $.log({ kind: "cd", dir, verbose: !$.quiet && $.verbose });
-  process.chdir(dir);
-  $[CWD] = process.cwd();
+  import_node_process2.default.chdir(dir);
+  $[CWD] = import_node_process2.default.cwd();
 }
 function kill(_0) {
   return __async(this, arguments, function* (pid, signal = $.killSignal) {
     const children = yield import_vendor_core2.ps.tree({ pid, recursive: true });
     for (const p of children) {
       try {
-        process.kill(+p.pid, signal);
+        import_node_process2.default.kill(+p.pid, signal);
       } catch (e) {
       }
     }
     try {
-      process.kill(-pid, signal);
+      import_node_process2.default.kill(-pid, signal);
     } catch (e) {
       try {
-        process.kill(+pid, signal);
+        import_node_process2.default.kill(+pid, signal);
       } catch (e2) {
       }
     }
@@ -1029,7 +1032,7 @@ var promisifyStream = (stream, from) => (0, import_util.proxyOverride)(stream, {
     return piped instanceof ProcessPromise ? piped : promisifyStream(piped, from);
   }
 });
-function resolveDefaults(defs = defaults, prefix = ENV_PREFIX, env = process.env, allowed = ENV_ALLOWED) {
+function resolveDefaults(defs = defaults, prefix = ENV_PREFIX, env = import_node_process2.default.env, allowed = ENV_ALLOWED) {
   return Object.entries(env).reduce((m, [k, v]) => {
     if (v && k.startsWith(prefix)) {
       const _k = (0, import_util.toCamelCase)(k.slice(prefix.length));
build/core.d.ts
@@ -10,6 +10,7 @@ import { type Duration, quote } from './util.js';
 import { log } from './log.js';
 export { default as path } from 'node:path';
 export * as os from 'node:os';
+import { Buffer } from 'node:buffer';
 export { log, type LogEntry } from './log.js';
 export { chalk, which, ps } from './vendor-core.js';
 export { quote, quotePowerShell } from './util.js';
build/goods.cjs
@@ -32,7 +32,9 @@ var import_node_stream = require("stream");
 var import_core = require("./core.cjs");
 var import_util = require("./util.cjs");
 var import_vendor = require("./vendor.cjs");
-var parseArgv = (args = process.argv.slice(2), opts = {}, defs = {}) => Object.entries((0, import_vendor.minimist)(args, opts)).reduce(
+var import_node_buffer = require("buffer");
+var import_node_process = __toESM(require("process"), 1);
+var parseArgv = (args = import_node_process.default.argv.slice(2), opts = {}, defs = {}) => Object.entries((0, import_vendor.minimist)(args, opts)).reduce(
   (m, [k, v]) => {
     const kTrans = opts.camelCase ? import_util.toCamelCase : import_util.identity;
     const vTrans = opts.parseBoolean ? import_util.parseBool : import_util.identity;
@@ -61,7 +63,7 @@ var responseToReadable = (response, rs) => {
   }
   rs._read = () => __async(void 0, null, function* () {
     const result = yield reader.read();
-    if (!result.done) rs.push(Buffer.from(result.value));
+    if (!result.done) rs.push(import_node_buffer.Buffer.from(result.value));
     else rs.push(null);
   });
   return rs;
@@ -109,8 +111,8 @@ function question(query, options) {
       };
     }
     const rl = (0, import_node_readline.createInterface)({
-      input: process.stdin,
-      output: process.stdout,
+      input: import_node_process.default.stdin,
+      output: import_node_process.default.stdout,
       terminal: true,
       completer
     });
@@ -125,9 +127,9 @@ function question(query, options) {
 function stdin() {
   return __async(this, null, function* () {
     let buf = "";
-    process.stdin.setEncoding("utf8");
+    import_node_process.default.stdin.setEncoding("utf8");
     try {
-      for (var iter = __forAwait(process.stdin), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
+      for (var iter = __forAwait(import_node_process.default.stdin), more, temp, error; more = !(temp = yield iter.next()).done; more = false) {
         const chunk = temp.value;
         buf += chunk;
       }
@@ -204,9 +206,9 @@ function spinner(title, callback) {
       callback = title;
       title = "";
     }
-    if (import_core.$.quiet || process.env.CI) return callback();
+    if (import_core.$.quiet || import_node_process.default.env.CI) return callback();
     let i = 0;
-    const spin = () => process.stderr.write(`  ${"\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F"[i++ % 10]} ${title}\r`);
+    const spin = () => import_node_process.default.stderr.write(`  ${"\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F"[i++ % 10]} ${title}\r`);
     return (0, import_core.within)(() => __async(this, null, function* () {
       import_core.$.verbose = false;
       const id = setInterval(spin, 100);
@@ -214,7 +216,7 @@ function spinner(title, callback) {
         return yield callback();
       } finally {
         clearInterval(id);
-        process.stderr.write(" ".repeat((process.stdout.columns || 1) - 1) + "\r");
+        import_node_process.default.stderr.write(" ".repeat((import_node_process.default.stdout.columns || 1) - 1) + "\r");
       }
     }));
   });
build/index.cjs
@@ -39,11 +39,11 @@ __reExport(index_exports, require("./goods.cjs"), module.exports);
 var import_vendor2 = require("./vendor.cjs");
 var import_util = require("./util.cjs");
 var import_meta = {};
-var _a;
-var VERSION = (_a = import_vendor.fs.readJsonSync(
-  new URL("../package.json", import_meta_url),
-  { throws: false }
-)) == null ? void 0 : _a.version;
+var VERSION = (() => {
+  var _a;
+  const f = (file) => import_vendor.fs.readJsonSync(new URL(file, import_meta_url), { throws: false });
+  return (_a = f("../package.json") || f("../jsr.json")) == null ? void 0 : _a.version;
+})();
 var version = VERSION;
 function nothrow(promise) {
   return promise.nothrow();
build/log.d.ts
@@ -1,4 +1,5 @@
 import { type RequestInfo, type RequestInit } from './vendor-core.js';
+import { type Buffer } from 'node:buffer';
 export type LogEntry = {
     verbose?: boolean;
 } & ({
build/md.d.ts
@@ -1,1 +1,2 @@
+import { type Buffer } from 'node:buffer';
 export declare function transformMarkdown(buf: Buffer | string): string;
build/util.cjs
@@ -35,6 +35,7 @@ module.exports = __toCommonJS(util_exports);
 var import_node_os = __toESM(require("os"), 1);
 var import_node_path = __toESM(require("path"), 1);
 var import_node_fs = __toESM(require("fs"), 1);
+var import_node_process = __toESM(require("process"), 1);
 var import_vendor_core = require("./vendor-core.cjs");
 function tempdir(prefix = `zx-${randomId()}`, mode) {
   const dirpath = import_node_path.default.join(import_node_os.default.tmpdir(), prefix);
@@ -63,7 +64,7 @@ var bufToString = (buf) => isString(buf) ? buf : utf8Decoder.decode(buf);
 var bufArrJoin = (arr) => arr.reduce((acc, buf) => acc + bufToString(buf), "");
 var getLast = (arr) => arr[arr.length - 1];
 function preferLocalBin(env, ...dirs) {
-  const pathKey = process.platform === "win32" ? Object.keys(env).reverse().find((key) => key.toUpperCase() === "PATH") || "Path" : "PATH";
+  const pathKey = import_node_process.default.platform === "win32" ? Object.keys(env).reverse().find((key) => key.toUpperCase() === "PATH") || "Path" : "PATH";
   const pathValue = dirs.map(
     (c) => c && [
       import_node_path.default.resolve(c, "node_modules", ".bin"),
build/util.d.ts
@@ -1,4 +1,5 @@
 import { type Mode } from 'node:fs';
+import { type Buffer } from 'node:buffer';
 import { type TSpawnStoreChunks } from './vendor-core.js';
 export { isStringLiteral } from './vendor-core.js';
 export declare function tempdir(prefix?: string, mode?: Mode): string;
build/vendor-core.cjs
@@ -1378,7 +1378,8 @@ var wrap = (name, api) => {
   override(name, api);
   return new Proxy(api, {
     get(_, key) {
-      return store.get(name)[key];
+      var _a, _b;
+      return store.get(name)[key] || ((_b = (_a = store.get(name)) == null ? void 0 : _a.default) == null ? void 0 : _b[key]);
     },
     apply(_, self, args) {
       return store.get(name).apply(self, args);
build/vendor-core.d.ts
@@ -347,7 +347,9 @@ export declare const bus: {
 	wrap: <T extends object>(name: string, api: T) => T;
 };
 export type RequestInfo = Parameters<typeof globalThis.fetch>[0];
-type RequestInit$1 = Parameters<typeof globalThis.fetch>[1];
+type RequestInit$1 = Parameters<typeof globalThis.fetch>[1] & {
+	signal?: AbortSignal;
+};
 declare const chalk$1: typeof chalk;
 declare const which$1: typeof which;
 export declare const ps: typeof _default;
build/vendor-extra.cjs
@@ -19647,7 +19647,8 @@ var config = (def = DOTENV, ...files) => populate(process.env, loadSafe(def, ...
 var index_default = { parse: parse2, stringify: stringify4, load, loadSafe, config };
 
 // src/vendor-extra.ts
-global.AbortController = global.AbortController || A;
+var globalVar = "Deno" in globalThis ? globalThis : global;
+globalVar.AbortController = globalVar.AbortController || A;
 var createRequire = import_create_require.default;
 var globbyModule = {
   convertPathToPattern,
scripts/build-js.mjs
@@ -64,7 +64,7 @@ const entryPoints = entry.includes('*')
   : entries.map((p) => path.relative(cwd, path.resolve(cwd, p)))
 
 const _bundle = bundle && bundle !== 'none'
-const _external = _bundle ? external.split(',') : undefined // https://github.com/evanw/esbuild/issues/1466
+const _external = ['zx/globals', ...(_bundle ? external.split(',') : [])] // https://github.com/evanw/esbuild/issues/1466
 
 const plugins = [
   esbuildResolvePlugin({
@@ -156,6 +156,10 @@ plugins.push(
               /\/\/ Annotate the CommonJS export names for ESM import in node:/,
               ($0) => `/* c8 ignore next 100 */\n${$0}`
             )
+            .replace(
+              'yield import("zx/globals")',
+              'yield require("./globals.cjs")'
+            )
         },
       },
     ],
scripts/build-jsr.mjs
@@ -56,9 +56,11 @@ fs.writeFileSync(
         '.': './src/index.ts',
         './core': './src/core.ts',
         './cli': './src/cli.ts',
+        './globals': './src/globals-jsr.ts',
       },
       publish: {
         include: ['src', 'README.md', 'LICENSE'],
+        exclude: ['src/globals.ts'],
       },
       nodeModulesDir: 'auto',
       imports: Object.entries(deps).reduce(
@@ -71,6 +73,7 @@ fs.writeFileSync(
         },
         {
           'zurk/spawn': `jsr:@webpod/zurk@${deps.zurk}`,
+          'zx/globals': './src/globals-jsr.ts',
         }
       ),
     },
src/cli.ts
@@ -93,7 +93,7 @@ export const argv: minimist.ParsedArgs = parseArgv(process.argv.slice(2), {
 }, resolveDefaults({} as any, 'ZX_', process.env, new Set(['env', 'install', 'registry'])))
 
 export async function main(): Promise<void> {
-  await import('./globals.ts')
+  await import('zx/globals')
   argv.ext = normalizeExt(argv.ext)
   if (argv.cwd) $.cwd = argv.cwd
   if (argv.env) {
src/globals-jsr.ts
@@ -0,0 +1,16 @@
+// Copyright 2025 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.ts'
+Object.assign(globalThis, _)
package.json
@@ -64,10 +64,10 @@
     "fmt:check": "prettier --check .",
     "prebuild": "rm -rf build",
     "build": "npm run build:js && npm run build:dts && npm run build:tests",
-    "build:js": "node scripts/build-js.mjs --format=cjs --hybrid --entry=src/*.ts:!src/error.ts:!src/repl.ts:!src/md.ts:!src/log.ts && npm run build:vendor",
+    "build:js": "node scripts/build-js.mjs --format=cjs --hybrid --entry=src/*.ts:!src/error.ts:!src/repl.ts:!src/md.ts:!src/log.ts:!src/globals-jsr.ts && npm run build:vendor",
     "build:vendor": "node scripts/build-js.mjs --format=cjs --entry=src/vendor-*.ts --bundle=all",
     "build:tests": "node scripts/build-tests.mjs",
-    "build:dts": "tsc --project tsconfig.json && rm build/error.d.ts build/repl.d.ts && node scripts/build-dts.mjs",
+    "build:dts": "tsc --project tsconfig.json && rm build/error.d.ts build/repl.d.ts build/globals-jsr.d.ts && node scripts/build-dts.mjs",
     "build:dcr": "docker build -f ./dcr/Dockerfile . -t zx",
     "build:jsr": "node scripts/build-jsr.mjs",
     "docs:dev": "vitepress dev docs",
@@ -184,5 +184,10 @@
   "license": "Apache-2.0",
   "volta": {
     "node": "22.12.0"
+  },
+  "tsd": {
+    "compilerOptions": {
+      "rootDir": "."
+    }
   }
 }
tsconfig.json
@@ -2,6 +2,7 @@
   "compilerOptions": {
     "target": "ES2021",
     "lib": ["ES2021"],
+    "rootDir": "./src",
     "moduleResolution": "NodeNext",
     "module": "NodeNext",
     "strict": true,