Skip to content

Commit 09b3b63

Browse files
anonriglemire
andcommitted
cli: implement node run <script-in-package-json>
Co-authored-by: Daniel Lemire <[email protected]>
1 parent d1d5da2 commit 09b3b63

File tree

16 files changed

+330
-0
lines changed

16 files changed

+330
-0
lines changed

doc/api/cli.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,53 @@ entry point, the `node` command will accept as input only files with `.js`,
5151
[`--experimental-wasm-modules`][] is enabled; and with no extension when
5252
[`--experimental-default-type=module`][] is passed.
5353

54+
## Sub-commands
55+
56+
### `node run <command> [<arguments>]`
57+
58+
<!-- YAML
59+
added: REPLACEME
60+
-->
61+
62+
> Stability: 1.1 - Active development
63+
64+
This runs a specified command from a package.json's `"scripts"` object.
65+
If no `"command"` is provided, it will list the available scripts.
66+
67+
`node run` prepends `./node_modules/.bin`, relative to the current
68+
working directory, to the `PATH` in order to execute the binaries from
69+
dependencies.
70+
71+
For example, the following command will run the `test` script of
72+
the `package.json` in the current folder:
73+
74+
```console
75+
$ node run test
76+
```
77+
78+
You can also pass arguments to the command. Any argument after the script
79+
name will be appended to the script:
80+
81+
```console
82+
$ node run test --verbose
83+
```
84+
85+
#### Intentional limitations
86+
87+
`node run` is not meant to match the behaviors of `npm run` or of the `run`
88+
commands of other package managers. The Node.js implementation is intentionally
89+
more limited, in order to focus on top performance for the most common use
90+
cases.
91+
Some features of other `run` implementations that are intentionally excluded
92+
are:
93+
94+
* Searching for `package.json` files outside the current folder.
95+
* Prepending the `.bin` or `node_modules/.bin` paths of folders outside the
96+
current folder.
97+
* Running `pre` or `post` scripts in addition to the specified script.
98+
* Defining package manager-specific environment variables.
99+
* Setting `process.title`.
100+
54101
## Options
55102

56103
<!-- YAML

lib/internal/main/run.js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
'use strict';
2+
/* eslint-disable node-core/prefer-primordials */
3+
4+
// There is no need to add primordials to this file.
5+
// `run.js` is a script only executed when `node run <script>` is called.
6+
const {
7+
prepareMainThreadExecution,
8+
markBootstrapComplete,
9+
} = require('internal/process/pre_execution');
10+
const { getPackageJSONScripts } = internalBinding('modules');
11+
const { execSync } = require('child_process');
12+
const { resolve, delimiter } = require('path');
13+
const { escapeShell } = require('internal/shell');
14+
15+
prepareMainThreadExecution(false, false);
16+
17+
markBootstrapComplete();
18+
19+
// TODO(@anonrig): Search for all package.json's until root folder.
20+
const json_string = getPackageJSONScripts();
21+
22+
// Check if package.json exists and is parseable
23+
if (json_string === undefined) {
24+
process.exit(1);
25+
return;
26+
}
27+
const scripts = JSON.parse(json_string);
28+
// Remove the first two arguments, which are the node binary and the command "run"
29+
const args = process.argv.slice(2);
30+
const id = args.shift();
31+
let command = scripts[id];
32+
33+
if (!command) {
34+
const { error } = require('internal/console/global');
35+
36+
error(`Missing script: "${id}"`);
37+
38+
const keys = Object.keys(scripts);
39+
if (keys.length === 0) {
40+
error('There are no scripts available in package.json');
41+
} else {
42+
error('Available scripts are:\n');
43+
for (const script of keys) {
44+
error(` ${script}: ${scripts[script]}`);
45+
}
46+
}
47+
process.exit(1);
48+
return;
49+
}
50+
51+
const env = process.env;
52+
const cwd = process.cwd();
53+
const binPath = resolve(cwd, 'node_modules/.bin');
54+
55+
// Filter all environment variables that contain the word "path"
56+
const keys = Object.keys(env).filter((key) => /^path$/i.test(key));
57+
const PATH = keys.map((key) => env[key]);
58+
59+
// Append only the current folder bin path to the PATH variable.
60+
// TODO(@anonrig): Prepend the bin path of all parent folders.
61+
const paths = [binPath, PATH].join(delimiter);
62+
for (const key of keys) {
63+
env[key] = paths;
64+
}
65+
66+
// If there are any remaining arguments left, append them to the command.
67+
// This is useful if you want to pass arguments to the script, such as
68+
// `node run linter --help` which runs `biome --check . --help`
69+
if (args.length > 0) {
70+
command += ' ' + escapeShell(args.map((arg) => arg.trim()).join(' '));
71+
}
72+
execSync(command, { stdio: 'inherit', env, shell: true });

lib/internal/shell.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
'use strict';
2+
3+
4+
// There is no need to add primordials to this file.
5+
// `shell.js` is a script only executed when `node run <script>` is called.
6+
7+
const forbiddenCharacters = /[\t\n\r "#$&'()*;<>?\\`|~]/;
8+
9+
/**
10+
* Escapes a string to be used as a shell argument.
11+
*
12+
* Adapted from `promise-spawn` module available under ISC license.
13+
* Ref: https://github.com/npm/promise-spawn/blob/16b36410f9b721dbe190141136432a418869734f/lib/escape.js
14+
* @param {string} input
15+
*/
16+
function escapeShell(input) {
17+
// If the input is an empty string, return a pair of quotes
18+
if (!input.length) {
19+
return '\'\'';
20+
}
21+
22+
// Check if input contains any forbidden characters
23+
// If it doesn't, return the input as is.
24+
if (!forbiddenCharacters.test(input)) {
25+
return input;
26+
}
27+
28+
// Replace single quotes with '\'' and wrap the whole result in a fresh set of quotes
29+
return `'${input.replace(/'/g, '\'\\\'\'')}'`
30+
// If the input string already had single quotes around it, clean those up
31+
.replace(/^(?:'')+(?!$)/, '')
32+
.replace(/\\'''/g, '\\\'');
33+
}
34+
35+
module.exports = {
36+
escapeShell,
37+
};

src/node.cc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,10 @@ MaybeLocal<Value> StartExecution(Environment* env, StartExecutionCallback cb) {
409409
return StartExecution(env, "internal/main/watch_mode");
410410
}
411411

412+
if (!first_argv.empty() && first_argv == "run") {
413+
return StartExecution(env, "internal/main/run");
414+
}
415+
412416
if (!first_argv.empty() && first_argv != "-") {
413417
return StartExecution(env, "internal/main/run_main_module");
414418
}

src/node_modules.cc

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include "base_object-inl.h"
44
#include "node_errors.h"
55
#include "node_external_reference.h"
6+
#include "node_process-inl.h"
67
#include "node_url.h"
78
#include "permission/permission.h"
89
#include "permission/permission_base.h"
@@ -219,6 +220,21 @@ const BindingData::PackageConfig* BindingData::GetPackageJSON(
219220
if (field_value == "commonjs" || field_value == "module") {
220221
package_config.type = field_value;
221222
}
223+
} else if (key == "scripts") {
224+
if (value.type().get(field_type)) {
225+
return throw_invalid_package_config();
226+
}
227+
switch (field_type) {
228+
case simdjson::ondemand::json_type::object: {
229+
if (value.raw_json().get(field_value)) {
230+
return throw_invalid_package_config();
231+
}
232+
package_config.scripts = field_value;
233+
break;
234+
}
235+
default:
236+
break;
237+
}
222238
}
223239
}
224240
// package_config could be quite large, so we should move it instead of
@@ -344,6 +360,33 @@ void BindingData::GetNearestParentPackageJSONType(
344360
args.GetReturnValue().Set(Array::New(realm->isolate(), values, 3));
345361
}
346362

363+
void BindingData::GetPackageJSONScripts(
364+
const FunctionCallbackInfo<Value>& args) {
365+
Realm* realm = Realm::GetCurrent(args);
366+
std::string_view path = "package.json";
367+
368+
USE(ProcessEmitWarningSync(
369+
realm->env(),
370+
"ExperimentalWarning: Task runner is an experimental feature and might "
371+
"change at any time"));
372+
373+
THROW_IF_INSUFFICIENT_PERMISSIONS(
374+
realm->env(), permission::PermissionScope::kFileSystemRead, path);
375+
376+
auto package_json = GetPackageJSON(realm, path);
377+
if (package_json == nullptr) {
378+
printf("Can't read package.json\n");
379+
return;
380+
} else if (!package_json->scripts.has_value()) {
381+
printf("Can't read package.json \"scripts\" object\n");
382+
return;
383+
}
384+
385+
args.GetReturnValue().Set(
386+
ToV8Value(realm->context(), package_json->scripts.value())
387+
.ToLocalChecked());
388+
}
389+
347390
void BindingData::GetPackageScopeConfig(
348391
const FunctionCallbackInfo<Value>& args) {
349392
CHECK_GE(args.Length(), 1);
@@ -424,6 +467,7 @@ void BindingData::CreatePerIsolateProperties(IsolateData* isolate_data,
424467
"getNearestParentPackageJSON",
425468
GetNearestParentPackageJSON);
426469
SetMethod(isolate, target, "getPackageScopeConfig", GetPackageScopeConfig);
470+
SetMethod(isolate, target, "getPackageJSONScripts", GetPackageJSONScripts);
427471
}
428472

429473
void BindingData::CreatePerContextProperties(Local<Object> target,
@@ -440,6 +484,7 @@ void BindingData::RegisterExternalReferences(
440484
registry->Register(GetNearestParentPackageJSONType);
441485
registry->Register(GetNearestParentPackageJSON);
442486
registry->Register(GetPackageScopeConfig);
487+
registry->Register(GetPackageJSONScripts);
443488
}
444489

445490
} // namespace modules

src/node_modules.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ class BindingData : public SnapshotableObject {
3232
std::string type = "none";
3333
std::optional<std::string> exports;
3434
std::optional<std::string> imports;
35+
std::optional<std::string> scripts;
3536
std::string raw_json;
3637

3738
v8::Local<v8::Array> Serialize(Realm* realm) const;
@@ -60,6 +61,8 @@ class BindingData : public SnapshotableObject {
6061
const v8::FunctionCallbackInfo<v8::Value>& args);
6162
static void GetPackageScopeConfig(
6263
const v8::FunctionCallbackInfo<v8::Value>& args);
64+
static void GetPackageJSONScripts(
65+
const v8::FunctionCallbackInfo<v8::Value>& args);
6366

6467
static void CreatePerIsolateProperties(IsolateData* isolate_data,
6568
v8::Local<v8::ObjectTemplate> ctor);

test/fixtures/run-script/.env

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
CUSTOM_ENV="hello world"

test/fixtures/run-script/node_modules/.bin/ada

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

test/fixtures/run-script/node_modules/.bin/ada.bat

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

test/fixtures/run-script/node_modules/.bin/custom-env

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)