Skip to content

fix: custom GraphQL typeDefs silently ignored on Windows - #3419

Merged
hellofanny merged 10 commits into
vtex:devfrom
ossmate:fix/cli-windows-typedefs-glob
Aug 12, 2026
Merged

hellofanny merged 10 commits into
vtex:devfrom
ossmate:fix/cli-windows-typedefs-glob

Conversation

@ossmate

@ossmate ossmate commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

What's the purpose of this pull request?

On Windows, custom GraphQL type definitions placed in src/graphql/**/typeDefs/*.graphql are silently dropped when the CLI merges the store's GraphQL schema. Any custom Query/Mutation extension is missing from the merged schema, and codegen fails with:

Cannot query field "<customField>" on type "Query"

There is no warning that the typeDefs folder was skipped, which makes this very hard to debug — the schema extension guide works on macOS/Linux but fails on Windows with no indication why.

How it works?

getTypeDefsFromFolder (packages/cli/src/utils/generate-types.ts) builds the globby pattern with path.join(...). On Windows this produces backslash-separated paths, and globby/fast-glob treat \ in patterns as an escape character, not a path separator (documented globby behavior — patterns must always use forward slashes). The pattern therefore matches nothing and the custom typeDefs never reach mergeTypeDefs.

The fix normalizes the joined path with globby's own convertPathToPattern helper before calling globbySync. This is a no-op on POSIX systems and also handles glob-special characters in the path (e.g. parentheses in a user's directory name). The helper is now exported so it can be unit-tested, and a unit test with a real on-disk fixture is added — on Windows it fails without the fix (globby returns []) and passes with it.

How to test it?

  • On a Windows machine, scaffold a store with a custom schema extension, e.g. src/graphql/thirdParty/typeDefs/hello.graphql (extend type Query { hello: String! }) with a matching resolver, add a query using the new field, and run faststore generate.
    • Before this change: codegen fails with Cannot query field "hello" on type "Query".
    • After this change: the typeDefs are merged and codegen succeeds (same as on macOS/Linux).
  • Unit test: packages/cli/src/utils/generate-types.test.ts (pnpm exec vitest run src/utils/generate-types.test.ts in packages/cli).

How it was tested:

  • Windows 11 / Node 24:
    • New unit test fails before the fix (globby returns an empty array) and passes after it — verified in both directions.
    • pnpm turbo run build --filter "@faststore/cli..." passes.
    • Full CLI vitest suite: 101 passed; the 5 remaining failures are pre-existing Windows-environment issues in unrelated test files (temp-dir EPERM cleanup, symlink privileges, backslash comparisons in cp-schema tests) and are untouched by this change.
  • Real-world verification on Windows 11 in a production FastStore 4.4.0 storefront with custom typeDefs (src/graphql/thirdParty): with the unpatched CLI, faststore generate fails with Cannot query field "storeBrands" on type "Query"; with exactly this normalization applied to the installed CLI bundle, faststore generate and tsc --noEmit both pass.
  • Linux/macOS: no behavior change expected (the normalization is a no-op on POSIX); CI should confirm.

References

Summary by CodeRabbit

  • Bug Fixes
    • Improved GraphQL type definition discovery by generating forward-slash-safe glob patterns (including Windows-compatible path handling).
    • Ensures type generation returns an empty result when the requested custom folder contains no matching .graphql files.
  • Tests
    • Expanded test coverage with an additional fixture where the root path includes glob-special characters.
    • Added assertions confirming type definition parsing still returns the expected single document and that the empty-folder scenario is handled correctly.

On Windows, getTypeDefsFromFolder built the globby pattern with
path.join, which produces backslash-separated paths. globby/fast-glob
treat backslashes in patterns as escape characters, so the pattern
matched nothing and custom typeDefs under src/graphql/**/typeDefs were
silently dropped from the merged schema, making codegen fail with
`Cannot query field ... on type Query`.

Normalize the pattern with globby's convertPathToPattern before
globbing. No-op on POSIX systems.
@ossmate
ossmate requested a review from a team as a code owner July 27, 2026 12:10
@ossmate
ossmate requested review from gabpaladino and renatomaurovtex and removed request for a team July 27, 2026 12:10
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

getTypeDefsFromFolder is exported, accepts string or array paths, and constructs forward-slash-compatible globby patterns. Vitest coverage verifies GraphQL parsing with native and glob-special paths, plus empty results.

Changes

GraphQL type definition discovery

Layer / File(s) Summary
Normalized folder matching and validation
packages/cli/src/utils/generate-types.ts, packages/cli/src/utils/generate-types.test.ts
getTypeDefsFromFolder now supports string or array custom paths and normalized globby patterns. Tests cover native separators, glob-special root paths, populated folders, and empty results.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested reviewers: gabpaladino

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the Windows-specific fix for custom GraphQL type definitions, which is the main change in the pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codesandbox-ci

codesandbox-ci Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/cli/src/utils/generate-types.test.ts (2)

25-28: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add the required trailing comma.

The multiline writeFileSync call should include a trailing comma after the GraphQL fixture string.

As per coding guidelines, TypeScript files use “single quotes, no semicolons, ES5 trailing commas, 2-space indentation.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/utils/generate-types.test.ts` around lines 25 - 28, Add the
required trailing comma after the GraphQL fixture string in the multiline
fs.writeFileSync call within the generate-types test, preserving the existing
single-quote style, indentation, and no-semicolon convention.

Source: Coding guidelines


42-46: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Test an existing empty folder, not only a missing path.

vtex is never created, so this verifies nonexistent-path behavior. Create src/graphql/vtex/typeDefs before the assertion to cover an existing custom folder with no definitions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/utils/generate-types.test.ts` around lines 42 - 46, Update
the test case around getTypeDefsFromFolder to create the existing
src/graphql/vtex/typeDefs directory before invoking it, using the test’s
established filesystem setup utilities. Keep the empty-array assertion unchanged
so the test specifically covers an existing custom folder with no type
definitions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/cli/src/utils/generate-types.ts`:
- Around line 135-140: Update getTypeDefsFromFolder’s signature to explicitly
accept string or string[] for customPath, preserving its existing array
normalization. Replace the any cast around the dynamic globby import with a
typed adapter or named imports for globbySync and convertPathToPattern.

---

Nitpick comments:
In `@packages/cli/src/utils/generate-types.test.ts`:
- Around line 25-28: Add the required trailing comma after the GraphQL fixture
string in the multiline fs.writeFileSync call within the generate-types test,
preserving the existing single-quote style, indentation, and no-semicolon
convention.
- Around line 42-46: Update the test case around getTypeDefsFromFolder to create
the existing src/graphql/vtex/typeDefs directory before invoking it, using the
test’s established filesystem setup utilities. Keep the empty-array assertion
unchanged so the test specifically covers an existing custom folder with no type
definitions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 57a97e16-780c-4d12-a0f9-7baf08534510

📥 Commits

Reviewing files that changed from the base of the PR and between de1f02c and 283d7b7.

📒 Files selected for processing (2)
  • packages/cli/src/utils/generate-types.test.ts
  • packages/cli/src/utils/generate-types.ts

ossmate added 3 commits July 27, 2026 14:21
Type customPath as string | string[] to match the runtime
normalization, and type the dynamic globby import instead of casting
to any. Addresses PR review feedback.
Addresses SonarQube finding on the changed line.

@renatomaurovtex renatomaurovtex left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the diff and validated the root cause against globby/fast-glob docs and the repo state. Summary of what I checked:

  • Root cause is real and the fix is the right one. fast-glob treats \ in patterns as an escape character, so path.join-built patterns match nothing on Windows. convertPathToPattern is the purpose-built helper for exactly this, and globby@^15.0.0 (what packages/cli depends on) exports it. On POSIX it's a no-op for plain paths, so no behavior change for macOS/Linux users.
  • Both call sites (vtex, thirdParty at generate-types.ts:100-101) pass strings, so widening the signature to string | string[] is just making the type honest about the pre-existing array normalization. CodeRabbit's typing comment is already addressed in c49f7fe — the typed GlobbyModule adapter replacing the as any cast is a nice cleanup.

packages/cli/src/utils/generate-types.test.ts

🟡 [tests] The regression test only bites on Windows, but CI runs on Linux — on POSIX, path.join already produces forward slashes, so this test passes with or without the fix. The only place it guards the regression is a contributor's Windows machine. Since the PR also claims convertPathToPattern "handles glob-special characters in the path", consider a second fixture that makes the fix observable on Linux CI too, e.g.:

root = fs.mkdtempSync(path.join(os.tmpdir(), 'faststore-typedefs-(x86)-'))

A directory with parentheses breaks the raw-path.join pattern on POSIX as well, so this variant fails before the fix and passes after it — turning the Windows-only regression into one Linux CI can catch. One thing worth confirming when you try it: expandDirectories needs to stat the pattern to decide whether to expand it, so please verify the escaped-parentheses pattern still expands to **/*.graphql correctly — if it doesn't, that's valuable to know before the "glob-special characters" claim ships in the description.

💬 Exporting getTypeDefsFromFolder purely to unit-test it is a pragmatic trade-off and fine by me — the alternative (driving generateSchemaFile end-to-end) is much heavier for what this needs.

CI

The SonarQube failure is the new-code coverage gate (27.3% < 75%). The PR does add tests for everything it touches, so this looks like the usual case of packages/cli coverage not being fed into Sonar rather than a real gap — a maintainer can confirm/override. All build/test checks are green.

Verdict: Approved with comments

Blocking (🔴/🟠):

  • None.

Non-blocking (🟡/💬):

  • 🟡 Add a POSIX-reproducible fixture (glob-special chars in the temp dir name) so Linux CI actually guards the regression, and to verify the special-character claim end-to-end.
  • 💬 Export-for-test is fine as is.

Checks to confirm before merge: SonarQube coverage gate (maintainer override likely) · pnpm turbo run build --filter "@faststore/cli..." · CLI vitest suite.

Add a fixture whose root contains glob-special characters
(parentheses): a raw path.join pattern matches nothing on POSIX as
well, so Linux CI now guards the regression, not only Windows machines.

Verifying this surfaced a gap in the fix: expandDirectories stats the
escaped pattern string, so it never expands paths that needed escaping.
Spell out the /**/*.graphql glob explicitly instead — same matching
behavior for plain paths, and escaped paths now work.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/cli/src/utils/generate-types.test.ts`:
- Around line 14-25: Add trailing commas to the multiline argument lists in the
test setup around typeDefsDir, fs.mkdirSync, and fs.writeFileSync, including the
final path and GraphQL string arguments, to satisfy the repository’s ES5
trailing-comma lint rule.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 96b4b0d8-7ded-4d2a-966b-a1e49c879798

📥 Commits

Reviewing files that changed from the base of the PR and between c49f7fe and a481473.

📒 Files selected for processing (2)
  • packages/cli/src/utils/generate-types.test.ts
  • packages/cli/src/utils/generate-types.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/cli/src/utils/generate-types.ts

@ossmate
ossmate requested a review from renatomaurovtex July 27, 2026 15:03
@lemagnetic lemagnetic changed the title fix(cli): custom GraphQL typeDefs silently ignored on Windows fix: custom GraphQL typeDefs silently ignored on Windows Aug 10, 2026
@sonar-workflows

Copy link
Copy Markdown

Failed Quality Gate failed

  • 19.40% Coverage on New Code (is less than 75.00%)

Project ID: vtex_faststore_f0a862d5-9557-49f9-8d09-de40caa76622

View in SonarQube

@hellofanny
hellofanny merged commit bdeb6a7 into vtex:dev Aug 12, 2026
5 of 6 checks passed
hellofanny added a commit that referenced this pull request Aug 14, 2026
…#3440)

## What's the purpose of this pull request?

The generated `.faststore` package has no `node_modules` of its own
(`node_modules` is in the generate step's `ignorePaths`, and nothing
installs dependencies in there). The scripts we inject into
`.faststore/package.json` do rely on binaries, though:

```
'dev-only': 'next dev --webpack',
predev: 'na run partytown',
prebuild: 'na run partytown',
```

Those binaries only exist in the `node_modules/.bin` of an ancestor
directory — the store root or, on hoisted monorepos, the workspace root.
We spawn all three scripts with `cwd` pointing at `.faststore` and never
add those directories to `PATH`: `runCommandSync` calls `execSync` with
`cwd` only, and the `spawn`/`spawnSync` calls pass `env` without
touching `PATH`.

On native Windows with a monorepo this fails outright:

```
yarn.cmd predev
'na' is not recognized as an internal command

yarn.cmd dev-only --port 3001
'next' is not recognized as an internal command
```

This PR adds a `withNodeModulesBins` helper that walks up from
`.faststore` collecting every existing `node_modules/.bin` and prepends
them to `PATH`, and wires it into the four places that run a script
inside `.faststore`: `predev` and `dev-only` in `dev`, `run build` in
`build`, and `run test:e2e` in `test`.

Note that `build` is affected for the same reason (`prebuild: 'na run
partytown'`), so fixing only `dev` would leave `faststore build` broken
on the same setups. `test` runs the `test:e2e` script inherited from
`@faststore/core` (`cypress open`), which has the same gap.

## Implementation notes

- **Nearest ancestor wins.** A dependency installed at the store level
takes precedence over the workspace root one. This mirrors what npm/yarn
already do when running a script.
- **Reordering, not just prepending.** Package managers already put some
of these directories in `PATH` when they run a script, so the helper
cannot simply prepend the missing ones: doing that would let a
workspace-root binary that was absent from `PATH` jump ahead of the
store-level one that was already there, inverting the precedence above.
It removes every discovered bin directory from its current position and
reinserts the whole set nearest-first, leaving unrelated `PATH` entries
in their original order. Each call rebuilds from `process.env`, so
nothing accumulates across runs.
- **Windows `PATH` casing.** Environment variables are case-insensitive
on Windows, where the key is usually `Path`. The helper reuses whichever
key already exists instead of blindly writing `PATH`, otherwise the
child process would receive both keys and could keep using the old value
— i.e. the fix would silently not work on the only platform that needs
it. Covered by a test.
- **No-op when there is nothing to add.** If no ancestor
`node_modules/.bin` exists, the helper returns a copy of the
environment, which is indistinguishable from today's behavior.

## Is this a breaking change?

No. The main thing to be careful about is that passing `env` to
`execSync`/`spawn` replaces the environment instead of extending it —
the helper always starts from a spread of `process.env`, so nothing is
lost. The other `runCommandSync` call sites (`cp-schema`,
`generate-graphql`, `dependencies`) don't pass `env`, so they get
`undefined`, which Node treats as "use `process.env`": same behavior as
before, and covered by a test.

The one behavioral change is that project binaries now take precedence
over the system `PATH` inside these child processes, which is the same
precedence a package manager applies to its own scripts.

Left out on purpose:

- `generate-graphql.ts` also runs `${packageManager} run
generate:schema` inside `.faststore` and has the same gap, but that
command is orphaned on v4 — nothing invokes it (`dev` and `build` call
`generate-types`, `cache-graphql` and `generate-i18n`) and the
`generate:schema` / `generate:codegen` scripts no longer exist in
`@faststore/core`'s `package.json`.
- `start.ts` looks similar but is **not** affected: it spawns from the
store root without `cwd: tmpDir`, so the package manager resolves the
binary the usual way.

## How to test it?

Unit tests: `packages/cli/src/utils/binPaths.test.ts` and
`packages/cli/src/utils/runCommandSync.test.ts` (`pnpm vitest run
src/utils` in `packages/cli`). They build a fixture that mimics a
hoisted monorepo and assert ordering, ancestor skipping, deduplication,
the no-op case, the `env` passthrough and the Windows `Path` casing.

One of them goes further than asserting on the returned object: it
writes an executable probe into the fixture's `node_modules/.bin` and
spawns it by bare name from `.faststore`, against a `PATH` that cannot
resolve it on its own. The assertion can only pass because of the
directories the helper adds, so it covers the resolution mechanism end
to end rather than the string we build. It is skipped on Windows, where
the fixture would need a `.cmd` shim.

What the unit tests cannot prove is the original symptom, which is
native Windows. That needs a manual run with the CodeSandbox preview of
this PR, in a monorepo store: `faststore dev` should complete `predev`
and reach Next's `Ready`, and `faststore build` should get past
`prebuild`, with `na` and `next` resolved without a global install or a
manual `PATH` change.

## References

Reported by a partner alongside the FastStore v4 migration, as item 1
(P0) of their handoff document. The other two items are #3439 (argument
order, merged) and #3419 (Windows glob for GraphQL typeDefs).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Build, development, and test commands now automatically locate locally
installed command-line tools across nested project directories.
* Command execution preserves existing environment variables and avoids
duplicate path entries.
* **Bug Fixes**
* Improved compatibility with platform-specific PATH casing and empty or
missing PATH environments.
* **Tests**
* Added coverage for nested installations, missing directories, path
ordering, deduplication, environment preservation, and custom command
environments.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Cursor <[email protected]>
thiagopereira-vtex pushed a commit that referenced this pull request Aug 25, 2026
…#3440)

## What's the purpose of this pull request?

The generated `.faststore` package has no `node_modules` of its own
(`node_modules` is in the generate step's `ignorePaths`, and nothing
installs dependencies in there). The scripts we inject into
`.faststore/package.json` do rely on binaries, though:

```
'dev-only': 'next dev --webpack',
predev: 'na run partytown',
prebuild: 'na run partytown',
```

Those binaries only exist in the `node_modules/.bin` of an ancestor
directory — the store root or, on hoisted monorepos, the workspace root.
We spawn all three scripts with `cwd` pointing at `.faststore` and never
add those directories to `PATH`: `runCommandSync` calls `execSync` with
`cwd` only, and the `spawn`/`spawnSync` calls pass `env` without
touching `PATH`.

On native Windows with a monorepo this fails outright:

```
yarn.cmd predev
'na' is not recognized as an internal command

yarn.cmd dev-only --port 3001
'next' is not recognized as an internal command
```

This PR adds a `withNodeModulesBins` helper that walks up from
`.faststore` collecting every existing `node_modules/.bin` and prepends
them to `PATH`, and wires it into the four places that run a script
inside `.faststore`: `predev` and `dev-only` in `dev`, `run build` in
`build`, and `run test:e2e` in `test`.

Note that `build` is affected for the same reason (`prebuild: 'na run
partytown'`), so fixing only `dev` would leave `faststore build` broken
on the same setups. `test` runs the `test:e2e` script inherited from
`@faststore/core` (`cypress open`), which has the same gap.

## Implementation notes

- **Nearest ancestor wins.** A dependency installed at the store level
takes precedence over the workspace root one. This mirrors what npm/yarn
already do when running a script.
- **Reordering, not just prepending.** Package managers already put some
of these directories in `PATH` when they run a script, so the helper
cannot simply prepend the missing ones: doing that would let a
workspace-root binary that was absent from `PATH` jump ahead of the
store-level one that was already there, inverting the precedence above.
It removes every discovered bin directory from its current position and
reinserts the whole set nearest-first, leaving unrelated `PATH` entries
in their original order. Each call rebuilds from `process.env`, so
nothing accumulates across runs.
- **Windows `PATH` casing.** Environment variables are case-insensitive
on Windows, where the key is usually `Path`. The helper reuses whichever
key already exists instead of blindly writing `PATH`, otherwise the
child process would receive both keys and could keep using the old value
— i.e. the fix would silently not work on the only platform that needs
it. Covered by a test.
- **No-op when there is nothing to add.** If no ancestor
`node_modules/.bin` exists, the helper returns a copy of the
environment, which is indistinguishable from today's behavior.

## Is this a breaking change?

No. The main thing to be careful about is that passing `env` to
`execSync`/`spawn` replaces the environment instead of extending it —
the helper always starts from a spread of `process.env`, so nothing is
lost. The other `runCommandSync` call sites (`cp-schema`,
`generate-graphql`, `dependencies`) don't pass `env`, so they get
`undefined`, which Node treats as "use `process.env`": same behavior as
before, and covered by a test.

The one behavioral change is that project binaries now take precedence
over the system `PATH` inside these child processes, which is the same
precedence a package manager applies to its own scripts.

Left out on purpose:

- `generate-graphql.ts` also runs `${packageManager} run
generate:schema` inside `.faststore` and has the same gap, but that
command is orphaned on v4 — nothing invokes it (`dev` and `build` call
`generate-types`, `cache-graphql` and `generate-i18n`) and the
`generate:schema` / `generate:codegen` scripts no longer exist in
`@faststore/core`'s `package.json`.
- `start.ts` looks similar but is **not** affected: it spawns from the
store root without `cwd: tmpDir`, so the package manager resolves the
binary the usual way.

## How to test it?

Unit tests: `packages/cli/src/utils/binPaths.test.ts` and
`packages/cli/src/utils/runCommandSync.test.ts` (`pnpm vitest run
src/utils` in `packages/cli`). They build a fixture that mimics a
hoisted monorepo and assert ordering, ancestor skipping, deduplication,
the no-op case, the `env` passthrough and the Windows `Path` casing.

One of them goes further than asserting on the returned object: it
writes an executable probe into the fixture's `node_modules/.bin` and
spawns it by bare name from `.faststore`, against a `PATH` that cannot
resolve it on its own. The assertion can only pass because of the
directories the helper adds, so it covers the resolution mechanism end
to end rather than the string we build. It is skipped on Windows, where
the fixture would need a `.cmd` shim.

What the unit tests cannot prove is the original symptom, which is
native Windows. That needs a manual run with the CodeSandbox preview of
this PR, in a monorepo store: `faststore dev` should complete `predev`
and reach Next's `Ready`, and `faststore build` should get past
`prebuild`, with `na` and `next` resolved without a global install or a
manual `PATH` change.

## References

Reported by a partner alongside the FastStore v4 migration, as item 1
(P0) of their handoff document. The other two items are #3439 (argument
order, merged) and #3419 (Windows glob for GraphQL typeDefs).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Build, development, and test commands now automatically locate locally
installed command-line tools across nested project directories.
* Command execution preserves existing environment variables and avoids
duplicate path entries.
* **Bug Fixes**
* Improved compatibility with platform-specific PATH casing and empty or
missing PATH environments.
* **Tests**
* Added coverage for nested installations, missing directories, path
ordering, deduplication, environment preservation, and custom command
environments.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Cursor <[email protected]>
thiagopereira-vtex pushed a commit that referenced this pull request Aug 25, 2026
…#3440)

The generated `.faststore` package has no `node_modules` of its own
(`node_modules` is in the generate step's `ignorePaths`, and nothing
installs dependencies in there). The scripts we inject into
`.faststore/package.json` do rely on binaries, though:

```
'dev-only': 'next dev --webpack',
predev: 'na run partytown',
prebuild: 'na run partytown',
```

Those binaries only exist in the `node_modules/.bin` of an ancestor
directory — the store root or, on hoisted monorepos, the workspace root.
We spawn all three scripts with `cwd` pointing at `.faststore` and never
add those directories to `PATH`: `runCommandSync` calls `execSync` with
`cwd` only, and the `spawn`/`spawnSync` calls pass `env` without
touching `PATH`.

On native Windows with a monorepo this fails outright:

```
yarn.cmd predev
'na' is not recognized as an internal command

yarn.cmd dev-only --port 3001
'next' is not recognized as an internal command
```

This PR adds a `withNodeModulesBins` helper that walks up from
`.faststore` collecting every existing `node_modules/.bin` and prepends
them to `PATH`, and wires it into the four places that run a script
inside `.faststore`: `predev` and `dev-only` in `dev`, `run build` in
`build`, and `run test:e2e` in `test`.

Note that `build` is affected for the same reason (`prebuild: 'na run
partytown'`), so fixing only `dev` would leave `faststore build` broken
on the same setups. `test` runs the `test:e2e` script inherited from
`@faststore/core` (`cypress open`), which has the same gap.

- **Nearest ancestor wins.** A dependency installed at the store level
takes precedence over the workspace root one. This mirrors what npm/yarn
already do when running a script.
- **Reordering, not just prepending.** Package managers already put some
of these directories in `PATH` when they run a script, so the helper
cannot simply prepend the missing ones: doing that would let a
workspace-root binary that was absent from `PATH` jump ahead of the
store-level one that was already there, inverting the precedence above.
It removes every discovered bin directory from its current position and
reinserts the whole set nearest-first, leaving unrelated `PATH` entries
in their original order. Each call rebuilds from `process.env`, so
nothing accumulates across runs.
- **Windows `PATH` casing.** Environment variables are case-insensitive
on Windows, where the key is usually `Path`. The helper reuses whichever
key already exists instead of blindly writing `PATH`, otherwise the
child process would receive both keys and could keep using the old value
— i.e. the fix would silently not work on the only platform that needs
it. Covered by a test.
- **No-op when there is nothing to add.** If no ancestor
`node_modules/.bin` exists, the helper returns a copy of the
environment, which is indistinguishable from today's behavior.

No. The main thing to be careful about is that passing `env` to
`execSync`/`spawn` replaces the environment instead of extending it —
the helper always starts from a spread of `process.env`, so nothing is
lost. The other `runCommandSync` call sites (`cp-schema`,
`generate-graphql`, `dependencies`) don't pass `env`, so they get
`undefined`, which Node treats as "use `process.env`": same behavior as
before, and covered by a test.

The one behavioral change is that project binaries now take precedence
over the system `PATH` inside these child processes, which is the same
precedence a package manager applies to its own scripts.

Left out on purpose:

- `generate-graphql.ts` also runs `${packageManager} run
generate:schema` inside `.faststore` and has the same gap, but that
command is orphaned on v4 — nothing invokes it (`dev` and `build` call
`generate-types`, `cache-graphql` and `generate-i18n`) and the
`generate:schema` / `generate:codegen` scripts no longer exist in
`@faststore/core`'s `package.json`.
- `start.ts` looks similar but is **not** affected: it spawns from the
store root without `cwd: tmpDir`, so the package manager resolves the
binary the usual way.

Unit tests: `packages/cli/src/utils/binPaths.test.ts` and
`packages/cli/src/utils/runCommandSync.test.ts` (`pnpm vitest run
src/utils` in `packages/cli`). They build a fixture that mimics a
hoisted monorepo and assert ordering, ancestor skipping, deduplication,
the no-op case, the `env` passthrough and the Windows `Path` casing.

One of them goes further than asserting on the returned object: it
writes an executable probe into the fixture's `node_modules/.bin` and
spawns it by bare name from `.faststore`, against a `PATH` that cannot
resolve it on its own. The assertion can only pass because of the
directories the helper adds, so it covers the resolution mechanism end
to end rather than the string we build. It is skipped on Windows, where
the fixture would need a `.cmd` shim.

What the unit tests cannot prove is the original symptom, which is
native Windows. That needs a manual run with the CodeSandbox preview of
this PR, in a monorepo store: `faststore dev` should complete `predev`
and reach Next's `Ready`, and `faststore build` should get past
`prebuild`, with `na` and `next` resolved without a global install or a
manual `PATH` change.

Reported by a partner alongside the FastStore v4 migration, as item 1
(P0) of their handoff document. The other two items are #3439 (argument
order, merged) and #3419 (Windows glob for GraphQL typeDefs).

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

* **New Features**
* Build, development, and test commands now automatically locate locally
installed command-line tools across nested project directories.
* Command execution preserves existing environment variables and avoids
duplicate path entries.
* **Bug Fixes**
* Improved compatibility with platform-specific PATH casing and empty or
missing PATH environments.
* **Tests**
* Added coverage for nested installations, missing directories, path
ordering, deduplication, environment preservation, and custom command
environments.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Cursor <[email protected]>
hellofanny added a commit that referenced this pull request Sep 10, 2026
Unit tests alone did not cover the CLI paths where the Windows bugs
shipped to partners (#3337, #3419, #3440) actually fail. Pack the
workspace and build starter.store on windows-latest, which is where the
CLI is really invoked.

Yarn 1 resolutions get a relative POSIX tarball path: an absolute
Windows path is parsed as a protocol because of the drive letter. The
pack loop checks LASTEXITCODE by hand, since GitHub only propagates the
exit code of the last command in a block.

Co-authored-by: Cursor <[email protected]>
eduardoformiga pushed a commit that referenced this pull request Sep 28, 2026
…fs (#3502)

## What's the purpose of this pull request?

If a store lives in a folder whose name ends with `.faststore` (some of
our store repos are cloned as `<client>.faststore`), `faststore build`
silently drops every custom typeDef from the merged schema. The build
then fails on the first query that uses a custom field:

```
Cannot query field "reproHello" on type "Query".
```

The cause is this check in `generateSchemaFile`:

```ts
rootPath.endsWith('.faststore') ? [rootPath, '..'].join('/') : rootPath
```

It's there to detect the `.faststore` temp dir and go back up to the
store root. But `faststore build` runs `generate <storeRoot>`, and a
store root named `x.faststore` passes the same string check. So the CLI
goes up one level too far and looks for `src/graphql` in the parent
folder, finds nothing, and moves on.

`faststore dev` passes `<store>/.faststore`, so dev works fine. That's
what made this annoying to track down: dev works, build breaks, and the
error points at your own query.

Not Windows specific. We've been carrying a patch-package patch on the
CLI dist for this line in a few stores, and I'd like to get rid of it.

## How it works?

I added `resolveStoreRoot(rootPath)`. It resolves the path and compares
the last segment with `.faststore` instead of checking the string
suffix. If it is the `.faststore` dir, it returns the parent, otherwise
the path itself.

It also covers a `.faststore` path passed with a trailing separator
(`...\store\.faststore\`), which the old check missed. No CLI caller
produces that today, it only happens if you type the path by hand.

Nothing changes for stores whose folder name doesn't end with
`.faststore`.

## How to test it?

Everything below I ran on Windows 11 / Node 24.

**Unit + integration tests**

`cd packages/cli && pnpm exec vitest run
src/utils/generate-types.test.ts`: 13/13 pass. With `generate-types.ts`
reverted to `dev`, 6 of them fail, including the two integration tests
(`Cannot query field "hello"`).

**End to end with the built CLI**

I made two identical minimal stores: same custom typeDef (`extend type
Query { reproHello: String }`), same resolver, same query. The only
difference is the folder name: `repro-control` and `repro.faststore`.
Then I ran `faststore generate <store root>` on both, which is the first
step `faststore build` spawns.

| CLI | `repro-control` | `repro.faststore` |
| --- | --- | --- |
| `dev` | passes, `reproHello` in the schema | fails with `Cannot query
field "reproHello" on type "Query"`, field missing from `schema.graphql`
|
| this branch | passes | passes, `reproHello` in the schema and in
`graphql.ts` |

I did not run the full `faststore build` (the `next build` part) on a
real store. The bug is in the `generate` step, which is what I ran.

**Full CLI suite**

185 passed, 5 failed. Those same 5 fail on `dev` without this change on
my machine (`generate-i18n` ×2, `cp-schema` `getExistingCpDirs` ×2,
`generate.test` "shell metacharacters"). They look like Windows
environment issues and are unrelated to this PR.

**Reproducing by hand**

Put any store in a folder named `something.faststore`, add a custom
typeDef that a query uses, and run `faststore build`.

### Starters Deploy Preview

N/A, CLI only change.

## References

- #3419 fixed the Windows glob in the same flow
(`getTypeDefsFromFolder`).

## Checklist

**PR Title and Commit Messages**

- [x] PR title and commit messages follow the [Conventional
Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification

**PR Description**

- [ ] Added a label according to the PR goal: I can't add labels from a
fork. This is a `bug`.

**Dependencies**

- [x] No package changes, `pnpm-lock.yaml` untouched

**Documentation**

- [x] PR description
lokinmodar pushed a commit to lokinmodar/faststore that referenced this pull request Nov 20, 2026
Every path-handling bug we shipped to partners (vtex#3337, vtex#3419, vtex#3440) was
found on Windows, in production, because nothing in the pipeline has ever
run there. This job is informational while we measure how the suite behaves
on a real runner, so it cannot block merges yet.

Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants