Repository: nodejs/node
Pull request: watch: fix watch args not being properly filtered

Currently the [logic for filtering out watch related flags](https://github.com/nodejs/node/blob/25842c5e35efb45df169e591c775a3c4f853556d/lib/internal/main/watch_mode.js#L42-L55) before passing them to the watch target script is flawed, as it includes any flag (starting with `-`) that follows a flag starting with `--watch` ([code](https://github.com/nodejs/node/blob/25842c5e35efb45df169e591c775a3c4f853556d/lib/internal/main/watch_mode.js#L49-L51)), this allows some watch flags to make it pass the filtering resulting in the generation of multiple watch processes which is both wasteful and can cause duplicate terminal logs (alongside other issues if the target script is side-effectful).

For example if I run
```sh
node --watch --watch index.js
```
the current implementation [will spawn](https://github.com/nodejs/node/blob/25842c5e35efb45df169e591c775a3c4f853556d/lib/internal/main/watch_mode.js#L69) a process equivalent to:
```sh
node --watch index.js
```
which will then finally spawn the correct:
```sh
node index.js
```

Here I'm addressing the incorrect filtering so that all the watch flags are correctly filtered out (making the extra process spawning disappear)

___

Fixes https://github.com/nodejs/node/issues/57124

<!--
Before submitting a pull request, please read:

- the CONTRIBUTING guide at https://github.com/nodejs/node/blob/HEAD/CONTRIBUTING.md
- the commit message formatting guidelines at
  https://github.com/nodejs/node/blob/HEAD/doc/contributing/pull-requests.md#commit-message-guidelines

For code changes:
1. Include tests for any bug fixes or new features.
2. Update documentation if relevant.
3. Ensure that `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes.

If you believe this PR should be highlighted in the Node.js CHANGELOG
please add the `notable-change` label.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
-->


Changed files:
filename: lib/internal/main/watch_mode.js
patch: @@ -43,11 +43,26 @@ const argsWithoutWatchOptions = [];
 
 for (let i = 0; i < process.execArgv.length; i++) {
   const arg = process.execArgv[i];
-  if (StringPrototypeStartsWith(arg, '--watch')) {
-    i++;
-    const nextArg = process.execArgv[i];
-    if (nextArg && nextArg[0] === '-') {
-      ArrayPrototypePush(argsWithoutWatchOptions, nextArg);
+  if (StringPrototypeStartsWith(arg, '--watch=')) {
+    continue;
+  }
+  if (arg === '--watch') {
+    const nextArg = process.execArgv[i + 1];
+    if (nextArg && nextArg[0] !== '-') {
+      // If `--watch` doesn't include `=` and the next
+      // argument is not a flag then it is interpreted as
+      // the watch argument, so we need to skip that as well
+      i++;
+    }
+    continue;
+  }
+  if (StringPrototypeStartsWith(arg, '--watch-path')) {
+    const lengthOfWatchPathStr = 12;
+    if (arg[lengthOfWatchPathStr] !== '=') {
+      // if --watch-path doesn't include `=` it means
+      // that the next arg is the target path, so we
+      // need to skip that as well
+      i++;
     }
     continue;
   }

filename: test/sequential/test-watch-mode.mjs
patch: @@ -791,4 +791,54 @@ process.on('message', (message) => {
       `Completed running ${inspect(file)}. Waiting for file changes before restarting...`,
     ]);
   });
+
+  it('when multiple `--watch` flags are provided should run as if only one was', async () => {
+    const projectDir = tmpdir.resolve('project-multi-flag');
+    mkdirSync(projectDir);
+
+    const file = createTmpFile(`
+      console.log(
+        process.argv.some(arg => arg === '--watch')
+        ? 'Error: unexpected --watch args present'
+        : 'no --watch args present'
+      );`, '.js', projectDir);
+    const args = ['--watch', '--watch', file];
+    const { stdout, stderr } = await runWriteSucceed({
+      file, watchedFile: file, watchFlag: null, args, options: { cwd: projectDir }
+    });
+
+    assert.strictEqual(stderr, '');
+    assert.deepStrictEqual(stdout, [
+      'no --watch args present',
+      `Completed running ${inspect(file)}`,
+      `Restarting ${inspect(file)}`,
+      'no --watch args present',
+      `Completed running ${inspect(file)}`,
+    ]);
+  });
+
+  it('`--watch-path` ars without `=` used alongside `--watch` should not make it into the script', async () => {
+    const projectDir = tmpdir.resolve('project-watch-watch-path-args');
+    mkdirSync(projectDir);
+
+    const file = createTmpFile(`
+      console.log(
+        process.argv.slice(2).some(arg => arg.endsWith('.js'))
+        ? 'some cli args end with .js'
+        : 'no cli arg ends with .js'
+      );`, '.js', projectDir);
+    const args = ['--watch', `--watch-path`, file, file];
+    const { stdout, stderr } = await runWriteSucceed({
+      file, watchedFile: file, watchFlag: null, args, options: { cwd: projectDir }
+    });
+
+    assert.strictEqual(stderr, '');
+    assert.deepStrictEqual(stdout, [
+      'no cli arg ends with .js',
+      `Completed running ${inspect(file)}`,
+      `Restarting ${inspect(file)}`,
+      'no cli arg ends with .js',
+      `Completed running ${inspect(file)}`,
+    ]);
+  });
 });