Skip to content

feat: save-fixture fetches component master node trees (#16)#19

Merged
let-sunny merged 4 commits intomainfrom
fix/save-fixture-component-master
Mar 24, 2026
Merged

feat: save-fixture fetches component master node trees (#16)#19
let-sunny merged 4 commits intomainfrom
fix/save-fixture-component-master

Conversation

@let-sunny
Copy link
Copy Markdown
Owner

@let-sunny let-sunny commented Mar 24, 2026

Summary

  • save-fixture에서 INSTANCE가 참조하는 컴포넌트 마스터 노드 트리를 자동으로 fetch하여 저장
  • componentDefinitions 필드 추가 (optional, 기존 fixture 호환)
  • 2-pass resolution으로 중첩된 컴포넌트 참조도 해결

변경 사항

  • AnalysisFileSchemacomponentDefinitions: Record<string, AnalysisNode> 추가 (optional)
  • component-resolver.ts 신규: collectComponentIds + resolveComponentDefinitions
  • figma-transformer.ts: transformComponentMasterNodes 추가
  • figma-file-loader.ts: 저장된 fixture에서 componentDefinitions 보존
  • cli/index.ts: save-fixture 플로우에 마스터 resolve 연결

동작 방식

save-fixture <figma-url>
  → scoped 노드 fetch
  → INSTANCE 노드에서 componentId 수집
  → Pass 1: 마스터 노드 fetch (배치 50개씩)
  → Pass 2: 마스터 내부 중첩 컴포넌트 resolve
  → componentDefinitions에 저장
  → data.json 출력

외부 라이브러리 컴포넌트(다른 파일)는 자동 skip.

이후 활용

Test plan

  • pnpm test:run — 270 tests passed (9 new)
  • pnpm lint — clean
  • 기존 fixture 로드 호환성 (optional field)

Closes #16

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Fixtures now auto-resolve and attach Figma component master definitions when a token is available, enriching nested component analysis.
    • Loader accepts fixture files that include saved component definitions for richer local analysis.
  • Tests

    • Added tests covering component ID collection and multi-pass component-resolution behavior.
  • Bug Fixes

    • Resolution failures are downgraded to warnings so saving proceeds uninterrupted.

When saving a fixture with node-id scoping, INSTANCE nodes reference
component masters that live outside the scope. Now save-fixture:

1. Collects all componentId references from the scoped tree
2. Fetches master node trees via getFileNodes (batched at 50)
3. Does a 2nd pass to resolve nested component references
4. Stores masters in new optional `componentDefinitions` field

This enables design-tree, analysis rules, and converters to access
the full component structure for better analysis and code generation.

- New: componentDefinitions field in AnalysisFile schema (optional, backward-compatible)
- New: component-resolver.ts with collectComponentIds + resolveComponentDefinitions
- New: transformComponentMasterNodes in figma-transformer.ts
- Updated: figma-file-loader preserves componentDefinitions from saved fixtures
- 9 new tests, 270 total passing

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 24, 2026

Warning

Rate limit exceeded

@let-sunny has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 1 minutes and 36 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 89db41e7-6c78-441c-83dc-1c74531f6ae9

📥 Commits

Reviewing files that changed from the base of the PR and between 3b992b7 and 6d6515d.

📒 Files selected for processing (3)
  • src/core/adapters/component-resolver.ts
  • src/core/adapters/figma-file-loader.ts
  • src/core/engine/loader.ts
📝 Walkthrough

Walkthrough

Adds a multi-pass component master resolution flow: collect component IDs from INSTANCE nodes, fetch their master COMPONENT node trees from Figma in batched passes, transform those nodes into AnalysisNode form, and attach them to fixtures as componentDefinitions. Failures are logged as warnings and do not block saving.

Changes

Cohort / File(s) Summary
CLI Integration
src/cli/index.ts
When a Figma token is available, dynamically import client + resolver, attempt to resolve component masters for the saved fixture, assign returned componentDefinitions to the fixture, and warn (not fail) on errors.
Component Resolver
src/core/adapters/component-resolver.ts, src/core/adapters/component-resolver.test.ts
New collectComponentIds to recurse INSTANCE nodes and gather component IDs; resolveComponentDefinitions performs multi-pass, batched (50) fetches via getFileNodes, transforms masters, accumulates results, and stops early when no pending IDs remain. Tests cover collection, multi-pass behavior, batching, skipping missing IDs, and maxPasses.
Transformer Addition
src/core/adapters/figma-transformer.ts
Added transformComponentMasterNodes(response, requestedIds) to map GetFileNodes responses to Record<string, AnalysisNode> for requested IDs.
File Loader
src/core/adapters/figma-file-loader.ts
loadFigmaFileFromJson now accepts fixture JSON with optional componentDefinitions, validates entries with AnalysisNodeSchema, logs invalid entries, and attaches a componentDefinitions map when applicable.
Schema Update
src/core/contracts/figma-node.ts
AnalysisFileSchema extended with optional componentDefinitions: record(string, AnalysisNodeSchema) to permit persisted master definitions.
Engine Loader
src/core/engine/loader.ts
After transforming API responses, calls resolveComponentDefinitions(client, fileKey, file.document) and attaches returned definitions to file.componentDefinitions when non-empty.
Module Exports
src/core/adapters/index.ts
Re-exported component-resolver to expose the new resolver functions from the adapters module.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant CLI as CLI (save-fixture)
    participant Resolver as Component Resolver
    participant Client as Figma Client
    participant Transformer as Figma Transformer
    participant Storage as Fixture Storage

    CLI->>Resolver: collectComponentIds(document)
    Resolver-->>CLI: Set(component IDs)

    loop multi-pass (batch by 50)
        CLI->>Client: getFileNodes(fileKey, batchIDs)
        Client-->>CLI: GetFileNodesResponse
        CLI->>Transformer: transformComponentMasterNodes(response, batchIDs)
        Transformer-->>CLI: Record<ID, AnalysisNode>
        CLI->>Resolver: extract component IDs from new masters
        Resolver-->>CLI: pending IDs for next pass
    end

    CLI->>Storage: write fixture (with componentDefinitions)
    Storage-->>CLI: save complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I hopped through nodes to fetch each master root,

gathered IDs, fetched batches, then stitched each root,
now INSTANCE and COMPONENT are kept together true,
a rabbit's tiny patch of design brought through,
✨ saved fixtures bloom with structure fresh and new.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive The PR includes one scope expansion beyond save-fixture: loader.ts now also resolves component masters in the live API path (loadFromApi) for canicode analyze, which provides complementary benefit for accurate component-based analysis but goes beyond the original save-fixture issue scope. Clarify whether resolving component masters in the live API path (loadFromApi for canicode analyze) is intentional scope expansion or an oversight, and confirm this aligns with team priorities.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: save-fixture fetches component master node trees (#16)' directly and clearly summarizes the main change—implementing automatic fetching and storage of component master node trees in the save-fixture CLI flow.
Linked Issues check ✅ Passed All coding requirements from issue #16 are met: component IDs are collected from INSTANCE nodes [component-resolver.ts], master nodes are fetched in batches via the Figma API [component-resolver.ts], componentDefinitions are stored in fixture JSON [figma-node.ts schema], and the save-fixture flow is wired to resolve masters [cli/index.ts].

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/save-fixture-component-master

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

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 the current code and only fix it if needed.

Inline comments:
In `@src/core/adapters/component-resolver.ts`:
- Around line 74-82: The loop that repopulates pendingIds currently iterates
over allDefinitions each pass; change it to only iterate over the definitions
fetched in the current pass (the variable representing the current pass's nodes)
instead of allDefinitions to avoid re-scanning already-known definitions; update
the code that builds pendingIds (currently referencing pendingIds,
allDefinitions, resolvedIds and calling collectComponentIds) to use the
current-pass collection of nodes (the variable that holds nodes returned this
iteration) so you only add ids not in resolvedIds from that subset.
- Around line 64-66: The catch block in component-resolver.ts that currently
swallows errors should log the failure at debug level: inside the catch in the
resolveComponents (or the batch-processing function) replace the empty body with
a debug log that includes the caught error and identifying batch/component
metadata (e.g., batch index or component names/ids) using the module's existing
logger instance so you can trace which batch failed without changing behavior
for production (keep it debug-level).

In `@src/core/adapters/figma-file-loader.ts`:
- Around line 39-50: Summary: validation failures in parsing
data.componentDefinitions are currently silent—add logging for failed
validations. Modify the loop that iterates data.componentDefinitions (the block
using AnalysisNodeSchema.safeParse and assigning file.componentDefinitions) so
that when result.success is false you log the id, the raw entry (or a short
summary) and the validation errors; use the repository's existing logger (e.g.,
processLogger or module logger) or console.debug if none exists, and keep the
current behavior of skipping invalid entries.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0586185b-7c86-475a-8052-120aa2802330

📥 Commits

Reviewing files that changed from the base of the PR and between 7ebbf1d and ee3cc11.

📒 Files selected for processing (7)
  • src/cli/index.ts
  • src/core/adapters/component-resolver.test.ts
  • src/core/adapters/component-resolver.ts
  • src/core/adapters/figma-file-loader.ts
  • src/core/adapters/figma-transformer.ts
  • src/core/adapters/index.ts
  • src/core/contracts/figma-node.ts

let-sunny and others added 3 commits March 24, 2026 23:16
Previously componentDefinitions was only populated during save-fixture.
Now loadFromApi also resolves component masters so that `canicode analyze`
with a Figma URL gets full component structure for accurate scoring.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add debug logging for failed batch fetches in component-resolver
- Add debug logging for validation failures in figma-file-loader
- Optimize next-pass ID collection to scan only current-pass results

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Addresses docstring coverage check (62.5% → 80%+ threshold).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@let-sunny let-sunny merged commit 8eff03f into main Mar 24, 2026
2 checks passed
@let-sunny let-sunny deleted the fix/save-fixture-component-master branch March 24, 2026 14:24
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.

fix: save-fixture가 컴포넌트 마스터 노드를 저장하지 않음

1 participant