Skip to content

feat: adjusts GraphQL caching logic#3295

Open
eduardoformiga wants to merge 2 commits intocanary-v2from
chore/adjust-cache-graphql
Open

feat: adjusts GraphQL caching logic#3295
eduardoformiga wants to merge 2 commits intocanary-v2from
chore/adjust-cache-graphql

Conversation

@eduardoformiga
Copy link
Copy Markdown
Member

@eduardoformiga eduardoformiga commented May 5, 2026

What's the purpose of this pull request?

This pull request significantly improves how the CLI command updates the cachedOperations property in the GraphQL discovery config file. Instead of reconstructing and formatting the entire config object, it now performs a targeted string update of only the experimental.cachedOperations array, preserving the rest of the file (including comments and formatting) and then normalizing the result with Prettier. Several helper functions were added to locate and patch the relevant block in the file.

- Introduced `recast` as a new dependency in the CLI package.
- Refactored the GraphQL caching command to utilize `recast` for updating cached operations while preserving formatting and comments in the configuration file.
- Removed the previous usage of `prettier` for formatting within the caching logic, replacing it with a more robust solution that integrates `recast` for AST manipulation.
@eduardoformiga eduardoformiga requested a review from a team as a code owner May 5, 2026 18:48
@eduardoformiga eduardoformiga requested review from gabpaladino and lemagnetic and removed request for a team May 5, 2026 18:48
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 5, 2026

Walkthrough

Added recast dependency to enable AST-based source code patching. Modified the cache-graphql command to parse and patch the discovery config file's abstract syntax tree instead of re-importing and re-serializing it via JSON, preserving code structure and formatting.

Changes

AST-Based Config Patching

Layer / File(s) Summary
Dependency Addition
packages/cli/package.json
Added recast (^0.23.11) to dependencies for AST parsing and rewriting.
Import Wiring
packages/cli/src/commands/cache-graphql.ts (lines 1–11)
Replaced Prettier format import with recast + Babel parser and Prettier default module for config-based formatting.
Core AST Transformation
packages/cli/src/commands/cache-graphql.ts (lines 177–256)
Added updateCachedOperations(source, cachedQueries) function that parses config source with Babel, locates module.exports.experimental, replaces or appends cachedOperations property with query array, and throws on structural mismatches.
Post-Processing Cleanup
packages/cli/src/commands/cache-graphql.ts (lines 258–283)
Added removeRecastBlankLinesInExperimental(code) to collapse excess blank lines within the experimental block introduced by recast output.
Integration
packages/cli/src/commands/cache-graphql.ts (lines 82–91)
Updated run() method to read config as raw source, apply AST patch, resolve Prettier config, format, and write back—replacing the prior JSON.stringify + static Prettier approach.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • vtex/faststore#3228: Also modifies packages/cli/src/commands/cache-graphql.ts with GraphQL import changes in the same file.

Suggested reviewers

  • gabpaladino
  • lemagnetic
  • lariciamota

Poem

🌳 Abstract syntax trees take root,
No JSON strings left to moot,
Recast now crafts with AST's might,
Config patches, structured right.
Code preserved, format true, delight! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.
Title check ✅ Passed The title 'feat: adjusts GraphQL caching logic' refers to a real aspect of the changeset (the caching logic refactor) but does not capture the main addition of the recast dependency or the comprehensive AST-based approach to config updates.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/adjust-cache-graphql

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 and usage tips.

@codesandbox-ci
Copy link
Copy Markdown

codesandbox-ci Bot commented May 5, 2026

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.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 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/commands/cache-graphql.ts`:
- Around line 217-225: The parser currently returns false when it doesn't find
an 'experimental' property on node.right; instead, if node.right is an
ObjectExpression, synthesize a new 'experimental' ObjectExpression property
(using the same AST builders where other properties are created) and assign it
to node.right.properties so downstream code can mutate it; only keep the
hard-fail when node.right is not an ObjectExpression (i.e., module.exports is
not an object). Apply the same change to the second occurrence that checks
experimental (the block around the other isPropertyNamed/experimentalProp
check).
- Around line 255-283: The removeRecastBlankLinesInExperimental text-based
cleanup is unsafe; remove its use and keep the recast/prettier output unchanged
by returning recast.print(ast).code instead of calling
removeRecastBlankLinesInExperimental, and delete the
removeRecastBlankLinesInExperimental function (or stop exporting/using it) to
avoid non-syntax-aware regex edits; locate references to
removeRecastBlankLinesInExperimental and the return that currently wraps
recast.print(ast).code and update accordingly.
- Around line 233-241: The current code replaces the whole property node when
updating cachedOperations (props[idx] = newProp), which loses Recast
metadata/comments; instead locate the existing property node (the element at
props[idx]) and mutate its value to newArray (e.g., set existingProp.value =
newArray) so comments/formatting are preserved; update the branch that pushes
newProp only when no existing property exists. Also replace broad any
annotations in this function with the correct AST types for nodes (e.g.,
Property, ArrayExpression, Identifier) to improve TypeScript safety.
🪄 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

Run ID: 2b35c2fd-c24d-428b-b50b-103259f3bdc2

📥 Commits

Reviewing files that changed from the base of the PR and between d18bee0 and e2c80fc.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (2)
  • packages/cli/package.json
  • packages/cli/src/commands/cache-graphql.ts

Comment on lines +217 to +225
const experimentalProp = node.right.properties.find((p: any) =>
isPropertyNamed(p, 'experimental')
)

if (
!experimentalProp ||
experimentalProp.value.type !== 'ObjectExpression'
) {
return false
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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Create experimental when it is missing.

This now hard-fails for any valid discovery.config that does not already declare experimental as an object. Since the command accepts a custom --config, it should synthesize that wrapper and only error when module.exports itself is not an object.

Suggested fix
-      const experimentalProp = node.right.properties.find((p: any) =>
-        isPropertyNamed(p, 'experimental')
-      )
-
-      if (
-        !experimentalProp ||
-        experimentalProp.value.type !== 'ObjectExpression'
-      ) {
-        return false
-      }
+      let experimentalProp = node.right.properties.find((p: any) =>
+        isPropertyNamed(p, 'experimental')
+      )
+
+      if (!experimentalProp) {
+        experimentalProp = b.objectProperty(
+          b.identifier('experimental'),
+          b.objectExpression([])
+        )
+        node.right.properties.push(experimentalProp)
+      }
+
+      if (experimentalProp.value.type !== 'ObjectExpression') {
+        return false
+      }

Also applies to: 249-253

🤖 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/commands/cache-graphql.ts` around lines 217 - 225, The
parser currently returns false when it doesn't find an 'experimental' property
on node.right; instead, if node.right is an ObjectExpression, synthesize a new
'experimental' ObjectExpression property (using the same AST builders where
other properties are created) and assign it to node.right.properties so
downstream code can mutate it; only keep the hard-fail when node.right is not an
ObjectExpression (i.e., module.exports is not an object). Apply the same change
to the second occurrence that checks experimental (the block around the other
isPropertyNamed/experimentalProp check).

Comment thread packages/cli/src/commands/cache-graphql.ts Outdated
Comment thread packages/cli/src/commands/cache-graphql.ts Outdated
- Eliminated the `recast` dependency from the CLI package.
- Refactored the GraphQL caching command to remove the use of `recast`, simplifying the logic for updating cached operations.
- Updated the method for handling the `experimental.cachedOperations` property in the configuration file, ensuring comments and formatting are preserved without AST manipulation.
@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new Bot commented May 5, 2026

Open in StackBlitz

@faststore/api

yarn add https://pkg.pr.new/vtex/faststore/@faststore/api@fb83b85.tgz

@faststore/cli

yarn add https://pkg.pr.new/vtex/faststore/@faststore/cli@fb83b85.tgz

@faststore/components

yarn add https://pkg.pr.new/vtex/faststore/@faststore/components@fb83b85.tgz

@faststore/core

yarn add https://pkg.pr.new/vtex/faststore/@faststore/core@fb83b85.tgz

@faststore/diagnostics

yarn add https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@fb83b85.tgz

@faststore/lighthouse

yarn add https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@fb83b85.tgz

@faststore/sdk

yarn add https://pkg.pr.new/vtex/faststore/@faststore/sdk@fb83b85.tgz

@faststore/ui

yarn add https://pkg.pr.new/vtex/faststore/@faststore/ui@fb83b85.tgz

commit: fb83b85

@eduardoformiga eduardoformiga changed the title feat: add recast dependency and update GraphQL caching logic feat: adjusts GraphQL caching logic May 5, 2026
@eduardoformiga eduardoformiga requested review from hellofanny and ommeirelles and removed request for gabpaladino May 5, 2026 20:00
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.

1 participant