Skip to content

Conversation

@yannbf
Copy link
Member

@yannbf yannbf commented Jan 15, 2026

What I did

This PR improves code that handles error and addon name sanitization, to cover more use cases than previously.

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

No manual tests required

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

  • Bug Fixes

    • Sanitize home and working directory paths in telemetry outputs.
    • Safer error handling during telemetry collection.
  • New Features

    • Improved addon name normalization for clearer telemetry categorization.
    • Added a public Storybook metadata computation function for richer telemetry.
  • Tests

    • Expanded test coverage for path sanitization and addon normalization across OS/path variants.

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

@nx-cloud
Copy link

nx-cloud bot commented Jan 15, 2026

View your CI Pipeline Execution ↗ for commit 9fc3b51

Command Status Duration Result
nx run-many -t compile,check,knip,test,pretty-d... ❌ Failed 21m 59s View ↗

☁️ Nx Cloud last updated this comment at 2026-01-19 12:07:16 UTC

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 15, 2026

📝 Walkthrough

Walkthrough

Reworked path sanitization and addon-name normalization; added exported computeStorybookMetadata to aggregate Storybook metadata. Tests updated to reflect new sanitization/normalization across pnpm, Yarn Berry, Windows, and Linux. Error sanitization catch handling made more robust.

Changes

Cohort / File(s) Summary
Path sanitization logic
code/core/src/telemetry/sanitize.ts
Rewrote cleanPaths to consider multiple base targets (cwd, home) and multiple separators (platform sep, /, \), replacing single- and doubled-separator occurrences; tightened sanitizeError catch binding to unknown and improved message derivation.
Path sanitization tests
code/core/src/telemetry/sanitize.test.ts
Added extensive tests covering pnpm, Yarn Berry caches, inside/outside cwd, Windows backslash/forward-slash cases; added node:os import and afterEach to restore mocks; uses inline snapshots to assert sanitized outputs.
Addon name normalization & metadata
code/core/src/telemetry/storybook-metadata.ts
Enhanced sanitizeAddonName (normalizes separators, strips node_modules and cache prefixes, removes file:/dist/suffixes, returns CUSTOM: for filesystem/absolute-like paths, extracts scoped/addon-like names). Added exported computeStorybookMetadata({ packageJsonPath, packageJson, mainConfig, configDir }) to assemble Storybook metadata (packages, addons, versions, flags, file counts).
Addon metadata tests
code/core/src/telemetry/storybook-metadata.test.ts
Updated and expanded tests to expect CUSTOM: mapping for local/relative addon paths and to validate normalization of node_modules, pnpm, Yarn Berry cache, and file-path addon references across OS variants.

Sequence Diagram(s)

sequenceDiagram
  participant Caller as "Caller"
  participant Metadata as "computeStorybookMetadata()"
  participant Package as "package.json / mainConfig"
  participant FS as "Filesystem (configDir)"
  participant Sanitizer as "sanitizeAddonName / cleanPaths"
  Caller->>Metadata: invoke(packageJsonPath, packageJson, mainConfig, configDir)
  Metadata->>Package: read/inspect packageJson & mainConfig
  Metadata->>FS: read configDir (addons, presets, preview)
  Metadata->>Sanitizer: normalize addon names and sanitize paths
  Sanitizer-->>Metadata: sanitized addon identifiers and redacted paths
  Metadata-->>Caller: return StorybookMetadata (packages, addons, flags, counts)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

✨ Finishing touches
  • 📝 Generate docstrings

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

@yannbf yannbf added ci:daily Run the CI jobs that normally run in the daily job. and removed ci:normal labels Jan 16, 2026
@storybook-app-bot
Copy link

storybook-app-bot bot commented Jan 16, 2026

Package Benchmarks

Commit: 9fc3b51, ran on 19 January 2026 at 11:51:45 UTC

The following packages have significant changes to their size or dependencies:

@storybook/react-native-web-vite

Before After Difference
Dependency count 159 159 0
Self size 30 KB 30 KB 🚨 +8 B 🚨
Dependency size 23.00 MB 23.12 MB 🚨 +115 KB 🚨
Bundle Size Analyzer Link Link

@storybook/cli

Before After Difference
Dependency count 183 183 0
Self size 775 KB 775 KB 🚨 +139 B 🚨
Dependency size 67.38 MB 67.46 MB 🚨 +75 KB 🚨
Bundle Size Analyzer Link Link

@storybook/codemod

Before After Difference
Dependency count 176 176 0
Self size 30 KB 30 KB 🎉 -4 B 🎉
Dependency size 65.95 MB 66.03 MB 🚨 +75 KB 🚨
Bundle Size Analyzer Link Link
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: 1

🤖 Fix all issues with AI agents
In `@code/core/src/telemetry/storybook-metadata.ts`:
- Line 62: The replace call in storybook-metadata.ts is using the regex
`\$SNIP?` which makes the "P" optional and can match unintended `$SNI`; update
the replacement to target the exact marker produced by sanitize.ts's cleanPaths
(i.e., `$SNIP`) by changing the regex used in the .replace invocation in
storybook-metadata.ts so it matches the full `$SNIP` token only (use a regex
that matches the literal `$SNIP` globally).
🧹 Nitpick comments (1)
code/core/src/telemetry/storybook-metadata.ts (1)

64-72: Consider narrowing the 'file' prefix check to avoid false positives.

The condition cleaned.startsWith('file') on line 66 could incorrectly apply the CUSTOM: prefix to legitimate npm packages that happen to start with "file" (e.g., file-saver, file-loader).

Since file:// is already stripped on line 57, and file: would be caught by includes(':') on line 69, the startsWith('file') check may be redundant or overly broad.

Proposed fix
   let prefix = '';
   if (
-    cleaned.startsWith('file') ||
     cleaned.startsWith('.') ||
     cleaned.startsWith('/') ||
     cleaned.includes(':')
   ) {
     prefix = 'CUSTOM:';
   }
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e705722 and f64ae1e.

📒 Files selected for processing (1)
  • code/core/src/telemetry/storybook-metadata.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{js,jsx,ts,tsx,json,md,html,css,scss}

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

Format code using Prettier with yarn prettier --write <file>

Files:

  • code/core/src/telemetry/storybook-metadata.ts
**/*.{js,jsx,json,html,ts,tsx,mjs}

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

Run ESLint checks using yarn lint:js:cmd <file> or the full command cross-env NODE_ENV=production eslint --cache --cache-location=../.cache/eslint --ext .js,.jsx,.json,.html,.ts,.tsx,.mjs --report-unused-disable-directives to fix linting errors before committing

Files:

  • code/core/src/telemetry/storybook-metadata.ts
**/*.{ts,tsx}

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

Enable TypeScript strict mode across all packages

Files:

  • code/core/src/telemetry/storybook-metadata.ts
**/*.{ts,tsx,js,jsx}

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

**/*.{ts,tsx,js,jsx}: Export functions from modules if they need to be tested
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/telemetry/storybook-metadata.ts
code/{core,lib,addons,builders,frameworks,presets}/**/*.{ts,tsx,js,jsx}

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

Use logger from storybook/internal/node-logger for server-side logging in Node.js code

Files:

  • code/core/src/telemetry/storybook-metadata.ts
🧠 Learnings (1)
📓 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`.
🧬 Code graph analysis (1)
code/core/src/telemetry/storybook-metadata.ts (1)
code/core/src/telemetry/sanitize.ts (1)
  • cleanPaths (19-51)
⏰ 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). (2)
  • GitHub Check: daily-generated
  • GitHub Check: nx
🔇 Additional comments (1)
code/core/src/telemetry/storybook-metadata.ts (1)

46-97: Overall improvements to addon sanitization look good.

The enhanced normalization pipeline handles various edge cases well:

  • Cross-platform path normalization
  • Package manager cache/pnp mode paths via node_modules segment extraction
  • Cleaning of dist paths, extensions, and common entry point suffixes
  • Scoped package detection
  • Fallback chain for deriving addon names

The logic improvements should provide more accurate telemetry data for addon usage.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

.replace(/\/manager$/, '')
.replace(/\/preset$/, '');
.replace(/\/(register|manager|preset|index)$/, '')
.replace(/\$SNIP?/g, '');
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Regex likely matches unintended pattern.

The regex \$SNIP? makes the P optional, so it matches both $SNI and $SNIP. Based on the cleanPaths function in sanitize.ts which produces $SNIP markers, this should likely be /\$SNIP/g without the ?.

Proposed fix
-    .replace(/\$SNIP?/g, '');
+    .replace(/\$SNIP/g, '');
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.replace(/\$SNIP?/g, '');
.replace(/\$SNIP/g, '');
🤖 Prompt for AI Agents
In `@code/core/src/telemetry/storybook-metadata.ts` at line 62, The replace call
in storybook-metadata.ts is using the regex `\$SNIP?` which makes the "P"
optional and can match unintended `$SNI`; update the replacement to target the
exact marker produced by sanitize.ts's cleanPaths (i.e., `$SNIP`) by changing
the regex used in the .replace invocation in storybook-metadata.ts so it matches
the full `$SNIP` token only (use a regex that matches the literal `$SNIP`
globally).
@yannbf yannbf force-pushed the yann/fix-addon-sanitization branch from f64ae1e to 5c844db Compare January 19, 2026 09:50
@yannbf yannbf force-pushed the yann/fix-addon-sanitization branch from 5cf9d00 to 9fc3b51 Compare January 19, 2026 11:43
@yannbf yannbf merged commit 0c2192a into next Jan 19, 2026
296 of 302 checks passed
@yannbf yannbf deleted the yann/fix-addon-sanitization branch January 19, 2026 13:07
@github-actions github-actions bot mentioned this pull request Jan 19, 2026
18 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug ci:daily Run the CI jobs that normally run in the daily job. core

3 participants