parseArgs in runtimes where global is not defined #157
Description
This module is useful as a polyfill for older Node versions. But it could also be useful for other runtimes, such as gjs, that may not want to implement a Node compatibility layer but nevertheless would find a good argument parser helpful.
Right now this module appears to polyfill a bunch of Node internal functions by modifying global (such as in internal/primordials.js). This is fine, even preferrable, when it was to be included in Node, but as a standalone library this has two problems:
-
This pollutes the global namespace, which is inappropriate in non-Node contexts. A hypothetical case is someone wanting to emulate command parsing in the browser and utilizing this library - which works, but their namespace is now polluted.
-
This doesn't work in some runtimes. Some runtimes do not have
global(generally they haveglobalThisthough), so the modification ofglobalmeans this library just doesn't work there, even though it could.My actual use case is that I'm making a command line program with gjs (to make use of GLib).
parseArgs({args: ARGV, options: {...}})would work wonders there, but the polyfilling behavior prevents it from working. (ARGVis gjs's equivelant toprocess.argv.slice(2))Runtimes that have some use and don't have
global:- gjs: has
globalThisinstead - duktape (online REPL): has
globalThisinstead - QuickJS (online REPL based on QuickJS): has
globalThisinstead
- gjs: has
This can be fixed by either:
- Moving away from being a polyfill (which, granted, is quite a big change to make), or
- Falling back to
globalThisifglobaldoesn't exist.
Activity
kisaragi-hiu commentedon Sep 7, 2024
Since globalThis was added in Node 12 and this package requires Node 14+, and since internal/primordials.js even already depends on
globalThisexisting, internal/primordials.js could just be patched to always useglobalThis. This wouldn't solve the namespace pollution, but it does make this library work on gjs.use @pkgjs/parseargs
shadowspawn commentedon Sep 14, 2024
Historical note: this was to make it easy for submitting
parseArgsto Node.js, rather than a fully-functional polyfill of those internals.ljharb commentedon Sep 14, 2024
although a non-broken browser bundler must always transform global into window, it’s fine to change it to use globalThis for server runtimes, given our engines declaration.