Skip to content

Conversation

@valentinpalkovic
Copy link
Contributor

@valentinpalkovic valentinpalkovic commented Dec 2, 2025

Closes #33246

What I did

Checklist for Contributors

Testing

The changes in this PR are covered in the following automated tests:

  • stories
  • unit tests
  • integration tests
  • end-to-end tests

Manual testing

This section is mandatory for all contributions. If you believe no manual test is necessary, please state so explicitly. Thanks!

Documentation

  • Add or update documentation reflecting your changes
  • If you are deprecating/removing a feature, make sure to update
    MIGRATION.MD

Checklist for Maintainers

  • When this PR is ready for testing, make sure to add ci:normal, ci:merged or ci:daily GH label to it to run a specific set of sandboxes. The particular set of sandboxes can be found in code/lib/cli-storybook/src/sandbox-templates.ts

  • Make sure this PR contains one of the labels below:

    Available labels
    • bug: Internal changes that fixes incorrect behavior.
    • maintenance: User-facing maintenance tasks.
    • dependencies: Upgrading (sometimes downgrading) dependencies.
    • build: Internal-facing build tooling & test updates. Will not show up in release changelog.
    • cleanup: Minor cleanup style change. Will not show up in release changelog.
    • documentation: Documentation only changes. Will not show up in release changelog.
    • feature request: Introducing a new feature.
    • BREAKING CHANGE: Changes that break compatibility in some way with current major version.
    • other: Changes that don't fit in the above categories.

🦋 Canary release

This PR does not have a canary release associated. You can request a canary release of this pull request by mentioning the @storybookjs/core team here.

core team members can create a canary release here or locally with gh workflow run --repo storybookjs/storybook publish.yml --field pr=<PR_NUMBER>

Summary by CodeRabbit

  • Refactor
    • Enhanced code formatter with improved type safety and fallback handling when the external formatter is unavailable, ensuring more consistent formatting operations across the application.

✏️ Tip: You can customize this high-level summary in your review settings.

@nx-cloud
Copy link

nx-cloud bot commented Dec 2, 2025

View your CI Pipeline Execution ↗ for commit a243195

Command Status Duration Result
nx run-many -t compile,check,knip,test,pretty-d... ✅ Succeeded 3m 10s View ↗

☁️ Nx Cloud last updated this comment at 2025-12-03 06:45:19 UTC

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 2, 2025

📝 Walkthrough

Walkthrough

Updated the Prettier API integration in the formatter utility by introducing a local Prettier interface and changing getPrettier() to return Promise<Prettier> instead of Promise<any>. The implementation now attempts dynamic import with a comprehensive fallback providing stubbed Prettier methods.

Changes

Cohort / File(s) Summary
Prettier API Type Safety
code/core/src/common/utils/formatter.ts
Introduced local Prettier interface to define the Prettier API shape. Updated getPrettier() return type from Promise<any> to Promise<Prettier>. Enhanced fallback implementation with stubbed methods (AstPath, doc, util, version, resolveConfig, format, check, clearConfigCache, formatWithCursor, getFileInfo, getSupportInfo, resolveConfigFile). Added explicit Promise<string> return type to formatWithEditorConfig helper.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Prettier interface completeness: Verify that the local Prettier interface accurately captures the necessary API surface and matches the expected type contract used throughout the codebase.
  • Fallback implementation robustness: Review the stubbed methods in the fallback implementation to ensure they provide sufficient mimicry of the real Prettier API and handle edge cases gracefully.
  • Type propagation: Confirm that all existing call sites of getPrettier() properly align with the new Promise<Prettier> type and no type mismatches are introduced.
  • Dynamic import error handling: Assess the logic for gracefully handling import failures and ensure the fallback activates correctly under various conditions.
✨ Finishing touches
  • 📝 Generate docstrings

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

Copy link
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: 0

🧹 Nitpick comments (2)
code/core/src/common/utils/formatter.ts (2)

38-38: Minor: formatWithCursor fallback returns empty string instead of original content.

Other fallbacks like format (line 35) preserve the input content. For consistency, formatWithCursor should return the original content as formatted.

-      formatWithCursor: () => Promise.resolve({ formatted: '', cursorOffset: 0 }),
+      formatWithCursor: (content: string) => Promise.resolve({ formatted: content, cursorOffset: 0 }),

80-83: Minor inconsistency: Consider using await for consistency with line 60.

The formatFileContent function uses await format(...) (line 60), but here format is returned directly. While both work correctly due to async function semantics, using await consistently improves readability and provides better stack traces if errors occur.

-  return format(content, {
+  return await format(content, {
     ...(config as any),
     filepath: filePath,
   });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 453d754 and a243195.

📒 Files selected for processing (1)
  • code/core/src/common/utils/formatter.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{js,jsx,json,html,ts,tsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use ESLint and Prettier configurations that are enforced in the codebase

Files:

  • code/core/src/common/utils/formatter.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Enable TypeScript strict mode

Files:

  • code/core/src/common/utils/formatter.ts
code/**/*.{ts,tsx,js,jsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

code/**/*.{ts,tsx,js,jsx,mjs}: Use server-side logger from 'storybook/internal/node-logger' for Node.js code
Use client-side logger from 'storybook/internal/client-logger' for browser code
Do not use console.log, console.warn, or console.error directly unless in isolated files where importing loggers would significantly increase bundle size

Files:

  • code/core/src/common/utils/formatter.ts
code/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Export functions that need to be tested from their modules

Files:

  • code/core/src/common/utils/formatter.ts
code/**/*.{js,jsx,json,html,ts,tsx,mjs}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

code/**/*.{js,jsx,json,html,ts,tsx,mjs}: Run Prettier with --write flag to format code before committing
Run ESLint with yarn lint:js:cmd to check for linting issues and fix errors before committing

Files:

  • code/core/src/common/utils/formatter.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: mrginglymus
Repo: storybookjs/storybook PR: 32556
File: code/core/package.json:309-313
Timestamp: 2025-09-29T13:20:23.346Z
Learning: The `fast-printf` dependency in Storybook's core package is bundled into the final distribution during the build process, so it should remain in devDependencies rather than being moved to dependencies, following the same pattern as other bundled dependencies like `open`.
Learnt from: CR
Repo: storybookjs/storybook PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-28T14:50:24.872Z
Learning: Applies to code/**/*.{js,jsx,json,html,ts,tsx,mjs} : Run Prettier with --write flag to format code before committing
📚 Learning: 2025-11-28T14:50:24.872Z
Learnt from: CR
Repo: storybookjs/storybook PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-28T14:50:24.872Z
Learning: Applies to code/**/*.{js,jsx,json,html,ts,tsx,mjs} : Run Prettier with --write flag to format code before committing

Applied to files:

  • code/core/src/common/utils/formatter.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: normal
  • GitHub Check: Core Unit Tests, windows-latest
  • GitHub Check: nx
🔇 Additional comments (2)
code/core/src/common/utils/formatter.ts (2)

1-23: Well-designed interface to avoid the hard prettier dependency.

The local interface cleanly solves the issue from #33246 by avoiding direct type imports from prettier. The signature Promise<string> | string for format correctly accommodates both prettier v2 (sync) and v3 (async) APIs.


51-68: LGTM!

The function correctly destructures from the typed Prettier interface, uses await to handle the dual return type of format, and has appropriate fallback behavior.

@valentinpalkovic valentinpalkovic merged commit 83c5db1 into next Dec 3, 2025
69 of 77 checks passed
@valentinpalkovic valentinpalkovic deleted the valentin/fix-prettier-type branch December 3, 2025 06:13
@github-actions github-actions bot mentioned this pull request Dec 3, 2025
18 tasks
@valentinpalkovic valentinpalkovic added the patch:yes Bugfix & documentation PR that need to be picked to main branch label Dec 3, 2025
@github-actions github-actions bot mentioned this pull request Dec 3, 2025
5 tasks
valentinpalkovic added a commit that referenced this pull request Dec 3, 2025
@github-actions github-actions bot added the patch:done Patch/release PRs already cherry-picked to main/release branch label Dec 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug ci:normal core patch:done Patch/release PRs already cherry-picked to main/release branch patch:yes Bugfix & documentation PR that need to be picked to main branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: prettier is now a mandatory dependency of core (since 10.1.0)

3 participants