anima-pack
Claude Code skill pack for Anima (18 skills)
Installation
Open Claude Code and run this command:
/plugin install anima-pack@claude-code-plugins-plus
Use --global to install for all projects, or --project for current project only.
What It Does
> Claude Code skills for Anima design-to-code automation — Figma to React/Vue/HTML with Tailwind, MUI, shadcn (18 skills)
Anima converts Figma designs into production-ready code using AI-powered code generation. These skills use the real @animaapp/anima-sdk npm package with the generateCode API supporting React, Vue, HTML, TypeScript, Tailwind, MUI, AntD, and shadcn output.
Skills (18) plugin-local skills
Configure CI/CD pipeline for automated Figma-to-code generation with Anima.
Anima CI Integration
Overview
This workflow turns explicitly approved Figma nodes into a reviewable generated code change. The CI identity receives design credentials only at runtime and must never merge or deploy generated output without the repository’s normal quality and ownership controls.
Prerequisites
- A read-only Anima/Figma integration token stored as CI secrets and limited to the intended design file.
- An allowlisted component/node registry, deterministic output directory, and generated-code ownership/review policy.
- A branch workflow that validates generated output before any human-approved merge; scheduled generation alone is not release authorization.
Instructions
Step 1: GitHub Actions Workflow
# .github/workflows/design-sync.yml
name: Design-to-Code Sync
on:
schedule:
- cron: '0 9 * * 1-5' # Weekdays at 9am
workflow_dispatch: # Manual trigger
jobs:
generate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: '20' }
- run: npm ci
- name: Generate components from Figma
env:
ANIMA_TOKEN: ${{ secrets.ANIMA_TOKEN }}
FIGMA_TOKEN: ${{ secrets.FIGMA_TOKEN }}
FIGMA_FILE_KEY: ${{ secrets.FIGMA_FILE_KEY }}
run: npx tsx scripts/generate-components.ts
- name: Lint generated code
run: npx eslint src/components/generated/ --fix
- name: Check for changes
id: changes
run: |
if git diff --quiet src/components/generated/; then
echo "changed=false" >> $GITHUB_OUTPUT
else
echo "changed=true" >> $GITHUB_OUTPUT
fi
- name: Create PR with generated components
if: steps.changes.outputs.changed == 'true'
run: |
git checkout -b design-sync/$(date +%Y%m%d)
git add src/components/generated/
git commit -m "chore: sync generated components from Figma"
git push -u origin HEAD
gh pr create --title "Design sync: updated generated components" \
--body "Auto-generated from Figma via Anima SDK"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Step 2: Generation Script for CI
// scripts/generate-components.ts
import { Anima } from '@animaapp/anima-sdk';
import fs from 'fs';
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
const COMPONENTS = [
{ nodeId: '1:2', name: 'Hero' },
{ nodeId: '3:4', name: 'Card' },
{ nodeId: '5:6', name: 'Navigation' },
];
async function main() {
const outputDir = 'src/components/generated';
fs.mkdirSync(outputDir, { recursiv…Diagnose and fix common Anima SDK design-to-code errors.
Anima Common Errors
Overview
Use this guide to diagnose design-to-code failures without widening design-file access or leaking tokens. Start from a reproducible file/node/settings tuple and use a least-privilege development credential for all verification.
Prerequisites
- A sanitized error record with the design file identifier, node identifier, selected generation settings, timestamp, and request ID where available.
- Scoped Anima and Figma credentials held in a secret store; never paste a personal access token into a ticket, source file, or shared diagnostic log.
- A staging or disposable design fixture so fixes can be reproduced without mutating a production design file.
Instructions
- Classify the failure as authentication, file/node resolution, generator configuration, timeout/rate limit, or rendered-output quality.
- Reproduce it with the smallest approved frame/component and the diagnostic commands, capturing only sanitized results.
- Correct the matching design input, entitlement, or generation configuration and rerun only that fixture.
- Validate the generated file location, lint/build result, and visual review before updating a broader component set.
Error Reference
Authentication Errors
| Error | Root Cause | Fix |
|---|---|---|
Invalid Anima token |
Token not provisioned or expired | Request new token from Anima team |
Invalid Figma token |
PAT expired or revoked | Generate new PAT: Figma > Settings > Access Tokens |
Unauthorized |
Token lacks file access | Ensure Figma PAT has file read permission |
File & Node Errors
| Error | Root Cause | Fix |
|---|---|---|
File not found |
Wrong file key | Extract from Figma URL: figma.com/file/{KEY}/... |
Node not found |
Invalid node ID | Copy node link from Figma: right-click > Copy link |
No renderable content |
Selected a page or group | Select a frame, component, or component set |
Empty files array |
Node is empty or hidden | Unhide layers; ensure node has visible content |
Code Generation Errors
// Common generation error handler
async function safeGenerate(anima: Anima, params: any) {
try {
return await anima.generateCode(params);
} catch (err: any) {
if (err.message?.includes('rate limit')) {
console.error('Rate limited — wait 60s before retrying');
} else if (err.message?.includes('timeout…Build automated Figma-to-React pipeline with the Anima SDK.
Anima Core Workflow A — Figma-to-React Pipeline
Overview
Primary workflow: automated pipeline that watches a Figma file, generates React components whenever the design changes, and integrates them into your codebase. This replaces manual design handoff with continuous design-to-code automation.
Prerequisites
- Completed
anima-install-authsetup - Figma file with organized components (auto-layout recommended)
- React project (Next.js, Vite, or CRA)
Instructions
Step 1: Design System Scanner
// src/pipeline/figma-scanner.ts
import { Anima } from '@animaapp/anima-sdk';
interface FigmaComponent {
nodeId: string;
name: string;
type: 'COMPONENT' | 'FRAME' | 'COMPONENT_SET';
}
const anima = new Anima({
auth: { token: process.env.ANIMA_TOKEN! },
});
// Fetch all top-level components from a Figma page
async function scanFigmaComponents(fileKey: string): Promise<FigmaComponent[]> {
const response = await fetch(
`https://api.figma.com/v1/files/${fileKey}/components`,
{ headers: { 'X-Figma-Token': process.env.FIGMA_TOKEN! } }
);
const data = await response.json();
return data.meta.components.map((comp: any) => ({
nodeId: comp.node_id,
name: comp.name,
type: comp.containing_frame?.type || 'COMPONENT',
}));
}
Step 2: Batch Code Generator
// src/pipeline/batch-generator.ts
import { Anima } from '@animaapp/anima-sdk';
import fs from 'fs';
import path from 'path';
const anima = new Anima({
auth: { token: process.env.ANIMA_TOKEN! },
});
interface GenerationConfig {
fileKey: string;
outputDir: string;
settings: {
language: 'typescript' | 'javascript';
framework: 'react' | 'vue' | 'html';
styling: 'tailwind' | 'css' | 'styled-components';
uiLibrary?: 'none' | 'mui' | 'antd' | 'shadcn';
};
}
async function generateComponentBatch(
config: GenerationConfig,
nodeIds: string[],
): Promise<{ generated: number; failed: string[] }> {
const failed: string[] = [];
let generated = 0;
fs.mkdirSync(config.outputDir, { recursive: true });
// Generate each component (Anima processes one node at a time)
for (const nodeId of nodeIds) {
try {
const { files } = await anima.generateCode({
fileKey: config.fileKey,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: [nodeId],
settings: config.settings,
});
for (const file of files) {
const filePath = path.join(config.outputDir, file.fileName);
fs.writeFileSync(filePath, file.content);
console.log(`Generated: ${file.fileName}`);
}
generated++;
} catch (err) {
console.error(`Faile…Clone websites to React/HTML code and customize Anima output with AI.
Anima Core Workflow B — Website-to-Code & AI Customization
Overview
Secondary workflow: use Anima to clone live websites into React/HTML code and customize generated output with AI-powered code modification. Anima supports URL-to-code conversion alongside Figma-to-code.
Prerequisites
- Completed
anima-install-authsetup - Understanding of Anima's code generation settings
Instructions
Step 1: Website-to-Code Conversion
// src/workflows/website-to-code.ts
// Anima can clone any public website and generate React or HTML code
import { Anima } from '@animaapp/anima-sdk';
const anima = new Anima({
auth: { token: process.env.ANIMA_TOKEN! },
});
// Note: URL-to-code may use a different API endpoint
// Check docs.animaapp.com for current availability
async function cloneWebsiteToReact(url: string, outputDir: string) {
// Anima's website-to-code feature captures the page and generates code
// This is available via the Anima Playground or API (partner access)
// For Figma-based workflow, use the Figma plugin to import website screenshots
// then generate code from the imported frames
console.log(`Cloning ${url} to React components...`);
// Process via Figma intermediary:
// 1. Use Anima Figma plugin to capture website layout
// 2. Generate code from the captured frames
// 3. Customize with AI post-processing
}
Step 2: Post-Generation Customization
// src/workflows/customize-output.ts
import fs from 'fs';
import path from 'path';
interface CustomizationRule {
pattern: RegExp;
replacement: string;
description: string;
}
// Apply project-specific customizations to Anima output
function customizeGeneratedCode(
files: Array<{ fileName: string; content: string }>,
rules: CustomizationRule[],
): Array<{ fileName: string; content: string }> {
return files.map(file => {
let content = file.content;
for (const rule of rules) {
content = content.replace(rule.pattern, rule.replacement);
}
return { ...file, content };
});
}
// Common customization rules
const PROJECT_RULES: CustomizationRule[] = [
{
pattern: /className="([^"]+)"/g,
replacement: 'className={cn("$1")}',
description: 'Wrap Tailwind classes with cn() utility',
},
{
pattern: /import React from 'react'/g,
replacement: "import React from 'react';\nimport { cn } from '@/lib/utils'",
description: 'Add cn import for className merging',
},
{
pattern: /export default function (\w+)/g,
replacement: 'export const $1: React.FC = function $1',
description: 'Use React.FC type annotation',
},
];
Step 3: Design Token Mapper
…
Optimize Anima API costs through caching, incremental generation, and tier selection.
Anima Cost Tuning
Overview
Optimize design-to-code generation by measuring approved usage, avoiding duplicate work, and retaining only reusable outputs. Treat cost projections as planning inputs until the account owner confirms current contractual terms.
Pricing Context
Anima uses partner-based pricing (not self-service). API access is currently granted to partners with custom agreements. Costs are typically per-generation or per-seat.
Prerequisites
- A current agreement or account report from the authorized Anima owner; do not infer consumption limits from the illustrative optimization table.
- Aggregate generation telemetry that records file/node identifiers, generation version, cache state, and duration without exposing design tokens or content.
- An explicit cache freshness and invalidation policy agreed by design and code owners so cached output cannot silently lag an approved design change.
Cost Optimization Strategies
| Strategy | Savings | Implementation |
|---|---|---|
| Generation cache | 60-80% | Cache results; only regenerate on design change |
| Incremental generation | 40-60% | Detect changed components; skip unchanged |
| Batch scheduling | 20-30% | Generate during off-peak; avoid real-time |
| Output reuse | 30-50% | Generate once, customize programmatically |
Instructions
Step 1: Usage Tracker
// src/cost/usage-tracker.ts
interface GenerationRecord {
timestamp: string;
fileKey: string;
nodeId: string;
cached: boolean;
durationMs: number;
}
class AnimaUsageTracker {
private records: GenerationRecord[] = [];
record(entry: GenerationRecord): void { this.records.push(entry); }
getReport(): { total: number; cached: number; savings: string } {
const total = this.records.length;
const cached = this.records.filter(r => r.cached).length;
return {
total,
cached,
savings: total > 0 ? `${((cached / total) * 100).toFixed(0)}% saved by caching` : 'No data',
};
}
}
Step 2: Smart Generation Policy
// Only generate when:
// 1. Figma file version changed (check via Figma API)
// 2. Cache is expired (>1 hour for active dev, >24h for CI)
// 3. Settings changed (new framework/styling)
// 4. Force flag passed (manual override)
async function shouldGenerate(
fileKey: string,
nodeId: string,
cache: any,
): Promise<boolean> {
// Check cache first
const cached = cache.get(fileKey, nodeId);
if (cached && Date.now() - new Date(cached.generatedAt).getTime() < 3600000) {
console.log('Using cached generation (< 1 hour old)');
return false;
}
re…Collect Anima SDK debug evidence for support tickets and troubleshooting.
Anima Debug Bundle
Overview
Collect a narrowly scoped, redactable diagnostic artifact for a reproducible Anima or Figma integration failure. Review the file locally before sharing it: token-presence indicators are acceptable; credential values, private design content, and personal identity data are not.
Prerequisites
- A scoped development credential and a disposable/staging design fixture that reproduces the issue without exposing a customer or private production file.
- The expected file/node/settings tuple, timestamp, and sanitized error or request ID to correlate the bundle with the reported issue.
- A support-sharing review process and an owner able to rotate credentials if a diagnostic artifact is found to contain sensitive material.
Instructions
Step 1: Generate Debug Bundle
// src/debug/anima-debug.ts
import fs from 'fs';
async function generateDebugBundle() {
const bundle = {
timestamp: new Date().toISOString(),
environment: {
nodeVersion: process.version,
sdkVersion: require('@animaapp/anima-sdk/package.json').version,
animaToken: process.env.ANIMA_TOKEN ? 'SET (redacted)' : 'NOT SET',
figmaToken: process.env.FIGMA_TOKEN ? 'SET (redacted)' : 'NOT SET',
},
figmaAccess: await testFigmaAccess(),
generationTest: await testGeneration(),
};
const filename = `anima-debug-${Date.now()}.json`;
fs.writeFileSync(filename, JSON.stringify(bundle, null, 2));
console.log(`Debug bundle: ${filename}`);
return bundle;
}
async function testFigmaAccess() {
try {
const res = await fetch('https://api.figma.com/v1/me', {
headers: { 'X-Figma-Token': process.env.FIGMA_TOKEN! },
});
const data = await res.json();
return { status: res.ok ? 'ok' : 'failed', user: data.handle || data.err };
} catch (err: any) {
return { status: 'failed', error: err.message };
}
}
async function testGeneration() {
try {
const { Anima } = await import('@animaapp/anima-sdk');
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
return { status: 'sdk_loaded', version: 'check package.json' };
} catch (err: any) {
return { status: 'sdk_failed', error: err.message };
}
}
generateDebugBundle().catch(console.error);
Output
- JSON debug bundle with SDK version, token status, and connectivity test
- Figma API access verification
- Safe for sharing with Anima support (tokens redacted)
Examples
When generation fails against a staging component, run the bundle generator with scoped credentials and inspect the JSON before attaching it to a support ticket. Confirm that it contains SDK version, token state, and sanitized connectivity result—but not token values,…
Deploy Anima design-to-code service as a backend API endpoint.
Anima Deploy Integration
Overview
Deploy the Anima SDK as a backend service. The SDK is server-side only, so deploy it behind an API endpoint that accepts Figma file/node references and returns generated code.
Prerequisites
- A private or authenticated service boundary with an allowlisted design-file registry; do not expose arbitrary
fileKeyandnodesIdgeneration to the public internet. - Managed Anima and Figma secrets, separate staging/production credentials, request limits, and an audit trail that excludes token values and design content.
- An approved generated-output path, validation pipeline, and rollback target for every deployment revision.
Instructions
Step 1: Express API Wrapper
// src/server.ts
import express from 'express';
import { Anima } from '@animaapp/anima-sdk';
const app = express();
app.use(express.json());
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
app.post('/api/generate', async (req, res) => {
const { fileKey, nodesId, settings } = req.body;
if (!fileKey || !nodesId?.length) {
return res.status(400).json({ error: 'fileKey and nodesId required' });
}
try {
const { files } = await anima.generateCode({
fileKey,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId,
settings: settings || { language: 'typescript', framework: 'react', styling: 'tailwind' },
});
res.json({ files, count: files.length });
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
app.get('/health', (_req, res) => res.json({ status: 'ok' }));
app.listen(3000, () => console.log('Anima service on :3000'));
Step 2: Vercel Serverless Function
// api/generate.ts
import { Anima } from '@animaapp/anima-sdk';
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
export default async function handler(req: any, res: any) {
if (req.method !== 'POST') return res.status(405).end();
const { fileKey, nodesId, settings } = req.body;
const { files } = await anima.generateCode({
fileKey, figmaToken: process.env.FIGMA_TOKEN!, nodesId,
settings: settings || { language: 'typescript', framework: 'react', styling: 'tailwind' },
});
res.json({ files });
}
Step 3: Deploy Commands
# Vercel
vercel secrets add anima_token "$ANIMA_TOKEN"
vercel secrets add figma_token "$FIGMA_TOKEN"
vercel --prod
# Cloud Run
gcloud run deploy anima-service \
--source . \
--set-secrets=ANIMA_TOKEN=anima-token:latest,FIGMA_TOKEN=figma-token:latest \
--region us-central1 --allow-unauthenticated
Output
- Express API wrapp…
Generate React/Vue/HTML code from a Figma design using the Anima SDK.
Anima Hello World
Overview
Generate production-ready React, Vue, or HTML code from a Figma design using the @animaapp/anima-sdk. This example converts a Figma component into clean TypeScript React with Tailwind CSS.
Prerequisites
- Completed
anima-install-authsetup - A Figma file with at least one frame/component
- Know your file key and node ID
Instructions
Step 1: Generate React + Tailwind Code
// src/hello-world.ts
import { Anima } from '@animaapp/anima-sdk';
import fs from 'fs';
import path from 'path';
const anima = new Anima({
auth: { token: process.env.ANIMA_TOKEN! },
});
async function generateReactComponent() {
const { files } = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!, // From Figma URL
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: [process.env.FIGMA_NODE_ID!], // e.g., '1:2'
settings: {
language: 'typescript',
framework: 'react',
styling: 'tailwind',
uiLibrary: 'none', // or 'mui', 'antd', 'shadcn'
},
});
// Write generated files to disk
const outputDir = './generated';
fs.mkdirSync(outputDir, { recursive: true });
for (const file of files) {
const filePath = path.join(outputDir, file.fileName);
fs.writeFileSync(filePath, file.content);
console.log(`Generated: ${filePath} (${file.content.length} chars)`);
}
return files;
}
generateReactComponent().catch(console.error);
Step 2: Try Different Framework Outputs
// Generate Vue + Tailwind
const vueFiles = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: ['1:2'],
settings: {
language: 'typescript',
framework: 'vue',
styling: 'tailwind',
},
});
// Generate HTML + CSS (no framework)
const htmlFiles = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: ['1:2'],
settings: {
language: 'javascript',
framework: 'html',
styling: 'css',
},
});
// Generate React + shadcn/ui
const shadcnFiles = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: ['1:2'],
settings: {
language: 'typescript',
framework: 'react',
styling: 'tailwind',
uiLibrary: 'shadcn',
},
});
Step 3: Inspect Generated Output
// The generated files array contains:
interface GeneratedFile {
fileName: string; // e.g., 'HeroSection.tsx', 'styles.css'
content: string; // Full file content…Install the Anima SDK and configure authentication for Figma-to-code generation.
Anima Install & Auth
Overview
Install @animaapp/anima-sdk and configure authentication tokens. Anima converts Figma designs into production-ready React, Vue, or HTML code with Tailwind, MUI, AntD, or shadcn styling. The SDK runs server-side only.
Prerequisites
- Node.js 18+ (SDK is server-side only)
- Figma account with API access
- Anima API token (request at animaapp.com)
- Figma Personal Access Token
Instructions
Step 1: Install the Anima SDK
npm install @animaapp/anima-sdk
Step 2: Get Your Tokens
# 1. Figma Personal Access Token:
# Figma > Settings > Account > Personal Access Tokens > Generate
# 2. Anima API Token:
# Request from Anima team (currently limited partner access)
# https://docs.animaapp.com/docs/anima-api
# Store securely
cat > .env << 'EOF'
ANIMA_TOKEN=your-anima-api-token
FIGMA_TOKEN=your-figma-personal-access-token
EOF
echo ".env" >> .gitignore
chmod 600 .env
Step 3: Initialize and Verify
// src/anima-client.ts
import { Anima } from '@animaapp/anima-sdk';
const anima = new Anima({
auth: {
token: process.env.ANIMA_TOKEN!,
},
});
// Verify connection by generating code from a known Figma file
async function verifySetup() {
try {
const { files } = await anima.generateCode({
fileKey: 'your-figma-file-key', // From Figma URL: figma.com/file/{fileKey}/...
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: ['1:2'], // Specific node to convert
settings: {
language: 'typescript',
framework: 'react',
styling: 'tailwind',
},
});
console.log(`Generated ${files.length} files`);
for (const file of files) {
console.log(` ${file.fileName} (${file.content.length} chars)`);
}
return true;
} catch (error) {
console.error('Setup verification failed:', error);
return false;
}
}
verifySetup();
Step 4: Get Your Figma File Key
Figma URL format:
https://www.figma.com/file/ABC123xyz/My-Design?node-id=1:2
File Key: ABC123xyz
Node ID: 1:2 (from the URL query parameter)
Output
@animaapp/anima-sdkinstalled- Anima token and Figma token configured in
.env - Verified code generation from a Figma design
- Understanding of file key and node ID extraction
Examples
Create a dedicated staging Figma file with one approved frame and request a least-privilege Anima token for that file. Store both credentials through the development secret workflow, run verifySetup, and confirm the result names …
Set up iterative design-to-code development loop with Anima SDK.
Anima Local Dev Loop
Overview
Iterative development workflow for Anima design-to-code: generate from Figma, preview in browser, tweak settings, regenerate. Includes side-by-side comparison of React vs Vue vs HTML output.
Prerequisites
- A staging Figma file and allowlisted node IDs, with scoped credentials loaded from an ignored local environment file or development secret store.
- A disposable generated-output directory that is not imported by the production application until code and visual review pass.
- Agreed comparison criteria for accessibility, design-token use, responsive behavior, dependencies, and generation settings.
Instructions
Step 1: Project Setup
mkdir anima-dev && cd anima-dev
npm init -y
npm install @animaapp/anima-sdk dotenv
npm install -D vite @vitejs/plugin-react typescript
Step 2: Generate and Preview Script
// scripts/generate-preview.ts
import { Anima } from '@animaapp/anima-sdk';
import fs from 'fs';
import 'dotenv/config';
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
const SETTINGS_PRESETS = {
'react-tailwind': { language: 'typescript' as const, framework: 'react' as const, styling: 'tailwind' as const },
'react-shadcn': { language: 'typescript' as const, framework: 'react' as const, styling: 'tailwind' as const, uiLibrary: 'shadcn' as const },
'vue-tailwind': { language: 'typescript' as const, framework: 'vue' as const, styling: 'tailwind' as const },
'html-css': { language: 'javascript' as const, framework: 'html' as const, styling: 'css' as const },
};
async function generateWithPreset(preset: keyof typeof SETTINGS_PRESETS, nodeId: string) {
const settings = SETTINGS_PRESETS[preset];
const outputDir = `./generated/${preset}`;
fs.mkdirSync(outputDir, { recursive: true });
const { files } = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: [nodeId],
settings,
});
for (const file of files) {
fs.writeFileSync(`${outputDir}/${file.fileName}`, file.content);
}
console.log(`${preset}: ${files.length} files generated`);
}
// Compare all presets
async function compareOutputs(nodeId: string) {
for (const preset of Object.keys(SETTINGS_PRESETS) as Array<keyof typeof SETTINGS_PRESETS>) {
await generateWithPreset(preset, nodeId);
await new Promise(r => setTimeout(r, 2000)); // Rate limit
}
console.log('\nAll presets generated in ./generated/');
}
const nodeId = process.argv[2] || '1:2';
compareOutputs(nodeId).catch(console.error);
Step 3: Development Scripts
…
Optimize Anima code generation performance with caching, parallelism, and output tuning.
Anima Performance Tuning
Overview
Improve design-to-code throughput without treating cache hits or smaller output as success unless the result still matches the approved design version, accessibility expectations, and project build contract.
Performance Targets
| Operation | Target | Notes |
|---|---|---|
| Single component generation | < 10s | Depends on complexity |
| Batch (10 components) | < 2 min | With rate limit delays |
| Cache hit | < 10ms | File-based cache |
| Full design system (50 components) | < 15 min | Sequential with 6s delays |
Prerequisites
- A representative staging fixture and a baseline measurement of generation duration, cache hit rate, failure rate, and generated-code validation result.
- A version-aware cache key and retention policy that ties each artifact to Figma source version, node ID, and generation settings.
- Review gates for generated output so performance changes cannot automatically replace approved components or strip required licenses/accessibility content.
Instructions
Step 1: File-Based Generation Cache
// src/performance/cache.ts
import crypto from 'crypto';
import fs from 'fs';
class GenerationCache {
private dir: string;
constructor(cacheDir = '.anima-cache') {
this.dir = cacheDir;
fs.mkdirSync(cacheDir, { recursive: true });
}
private hash(fileKey: string, nodeId: string, settings: any): string {
return crypto.createHash('md5').update(`${fileKey}:${nodeId}:${JSON.stringify(settings)}`).digest('hex');
}
async getOrGenerate(
anima: any,
params: any,
maxAgeMs: number = 3600000, // 1 hour
): Promise<any> {
const key = this.hash(params.fileKey, params.nodesId[0], params.settings);
const path = `${this.dir}/${key}.json`;
if (fs.existsSync(path)) {
const stat = fs.statSync(path);
if (Date.now() - stat.mtimeMs < maxAgeMs) {
return JSON.parse(fs.readFileSync(path, 'utf8'));
}
}
const result = await anima.generateCode(params);
fs.writeFileSync(path, JSON.stringify(result));
return result;
}
clearOlderThan(maxAgeMs: number): number {
let cleared = 0;
for (const file of fs.readdirSync(this.dir)) {
const path = `${this.dir}/${file}`;
if (Date.now() - fs.statSync(path).mtimeMs > maxAgeMs) {
fs.unlinkSync(path);
cleared++;
}
}
return cleared;
}
}
export { GenerationCache };
Step 2: Incremental Generation (Only Changed Components)
// src/performance/incremental.ts
// Only regenerate components whose Figma nodes changed
…Production readiness checklist for Anima design-to-code pipelines.
Anima Production Checklist
Overview
Anima converts Figma designs into production-ready code for React, Vue, and HTML. A failed design-to-code pipeline means engineers receive broken components, mismatched tokens, or stale screens that drift from the source of truth. This checklist ensures your Anima integration produces reliable, framework-compliant output before it reaches CI/CD.
Prerequisites
- Named design, engineering, security, and operations owners who can make a go/no-go decision and own the rollback path.
- A staging environment using separate managed Anima/Figma credentials, an allowlisted design registry, and a reproducible generated-code fixture.
- Defined output quality gates: source-version traceability, lint/type/build, visual/accessibility review, and no secrets in artifacts or logs.
Instructions
- Assign an owner and evidence link to every required checklist item.
- Run the readiness script with the deployment identity in staging and retain only its redacted result.
- Exercise a generation and rollback/disable path with an approved design component, then verify downstream code-quality and visual gates.
- Approve progressive release only when all required checks pass; any failed security, credential, output, or fallback control is a no-go condition.
Authentication & Secrets
- [ ]
ANIMA_API_KEYstored in secrets manager (never in source) - [ ] Figma personal access token scoped to read-only with expiration
- [ ] Separate API keys for dev/staging/prod environments
- [ ] Key rotation schedule documented (90-day cycle recommended)
- [ ] Tokens excluded from client bundles and build artifacts
API Integration
- [ ] Production base URL configured (
https://api.animaapp.com) - [ ] Rate limit handling for standard tier (10 generations/min)
- [ ] Generation cache prevents redundant API calls for unchanged screens
- [ ] Figma file version polling detects design changes automatically
- [ ] Webhook or polling configured for async generation completion
- [ ] Component mapping rules tested for target framework (React/Vue/HTML)
Error Handling & Resilience
- [ ] Circuit breaker configured for Anima API outages
- [ ] Retry with exponential backoff for 429/5xx responses
- [ ] Graceful fallback when Figma PAT expires mid-pipeline
- [ ] Generated code validated against ESLint/Prettier before merge
- [ ] Design token mismatches flagged before component output
- [ ] Empty generation results handled (missing layers, unsupported elements)
Monitoring & Alerting
- [ ] API latency tracked per generation request
- [ ] Error rate alerts set (threshold: >5% over 5 minutes)
- [ ] Generation quali…
Implement rate limiting for Anima API code generation requests.
Anima Rate Limits
Overview
Anima API has per-minute rate limits on code generation. Each generateCode call processes one Figma node through AI — it's compute-intensive and rate-limited accordingly.
Rate Limit Tiers
| Tier | Generations/min | Concurrent | Notes |
|---|---|---|---|
| Partner (standard) | 10 | 2 | Most common |
| Enterprise | 30 | 5 | Custom agreement |
Prerequisites
- Confirm the account's current generation quota and concurrency contract before choosing
reservoir,reservoirRefreshAmount, ormaxConcurrent; treat the table above as a starting point, not authorization to exceed a plan. - Store
ANIMA_TOKEN,FIGMA_TOKEN, andFIGMA_FILE_KEYin the runtime secret manager or injected environment, and verify that the token has only the scopes required for the selected file. Never put tokens in source, fixtures, logs, generated receipts, or retry payloads. - Define an explicit allowlist of Figma files and node IDs, a bounded batch size, a maximum retry budget, and an approved output directory. Use synthetic or sandbox designs for load tests and confirm that generated output contains no customer data before persisting it.
- Install the pinned SDK and Bottleneck versions, and decide whether a generation is safe to repeat. If the upstream operation is not idempotent, persist a redacted request fingerprint and resume only the failed node IDs.
Instructions
Step 1: Throttled Generator with Bottleneck
// src/anima/throttled-generator.ts
import Bottleneck from 'bottleneck';
import { Anima } from '@animaapp/anima-sdk';
const limiter = new Bottleneck({
maxConcurrent: 2,
minTime: 6000, // 10 per minute = 1 every 6 seconds
reservoir: 10,
reservoirRefreshInterval: 60000,
reservoirRefreshAmount: 10,
});
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
async function throttledGenerate(params: any) {
return limiter.schedule(() => anima.generateCode(params));
}
// Batch generate with automatic throttling
async function batchGenerate(nodeIds: string[], settings: any) {
const results = [];
for (const nodeId of nodeIds) {
const result = await throttledGenerate({
fileKey: process.env.FIGMA_FILE_KEY!,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: [nodeId],
settings,
});
results.push({ nodeId, files: result.files });
console.log(`Generated ${nodeId}: ${result.files.length} files`);
}
return results;
}
export { throttledGenerate, batchGenerate };
Step 2: 429 Retry Handler
async function generateWithRetry(anima: A…Implement reference architecture for Anima design-to-code automation.
Anima Reference Architecture
Overview
This architecture separates design-source intake, authenticated code generation, deterministic post-processing, and reviewed delivery. It is intended for repeatable Figma-to-code pipelines where each run is bounded to approved files and nodes, produces inspectable artifacts, and can be stopped or rolled back without exposing design content or credentials.
Prerequisites
- Define the target framework, repository layout, supported Anima/Figma SDK versions, and the owner who approves generated changes. Pin dependencies and create a sandbox Figma file with synthetic components for pipeline tests.
- Obtain Figma and Anima credentials through the deployment secret manager, using least-privilege scopes and short-lived credentials where supported. Verify webhook signatures before accepting events; never commit, print, or place tokens in generated code, cache files, pull requests, or receipts.
- Establish allowlists for Figma file IDs, node IDs, webhook sources, output repositories, and branch names. Define retention and deletion rules for source snapshots, generated output, and logs before enabling automation.
- Prepare a dry-run mode, an artifact-diff gate, a staged canary environment, and a rollback reference to the last approved generated revision. Do not allow a webhook to publish directly to production.
System Architecture
┌────────────────┐ ┌──────────────┐ ┌─────────────────┐
│ Figma Design │────▶│ Figma API │────▶│ Anima SDK │
│ (Components) │ │ (Webhooks) │ │ (Code Gen) │
└────────────────┘ └──────────────┘ └────────┬────────┘
│
┌─────────▼────────┐
│ Post-Processing │
│ - Token mapping │
│ - Normalization │
│ - Lint/format │
└─────────┬────────┘
│
┌─────────▼────────┐
│ Output │
│ - React/Vue/HTML │
│ - PR creation │
│ - Storybook sync │
└──────────────────┘
Instructions
- Ingest and authorize. Use
Readto inspect the existing repository conventions and the signed event payload. Check the file/node allowlist, event freshness, source revision, and suppression/deletion rules before requesting any generation. - Generate in isolation. Run the pinned SDK in a sandbox worker wit…
Apply production-ready patterns for the Anima SDK design-to-code pipeline.
Anima SDK Patterns
Overview
Production patterns for @animaapp/anima-sdk: singleton client, generation caching, output normalization, and configurable settings presets.
Prerequisites
- Pin the Anima SDK and TypeScript runtime versions, define the supported framework presets, and provide a sandbox Figma file containing synthetic components for tests and examples.
- Inject
ANIMA_TOKENand any Figma credentials from a secret manager at runtime. Authentication failures must be distinguishable from generation failures; never hard-code, log, cache, or include credentials in generated output or receipts. - Make
.anima-cacheprivate to the worker, exclude it from version control and artifact uploads, and define a retention/deletion policy. Cache keys may identify a request, but cached design source and generated content must not be sent to telemetry. - Set an allowlist for input file/node IDs and output paths, a maximum cache size, a bounded retry count, and an owner-approved normalization configuration before enabling the wrapper in CI or production.
Instructions
Step 1: Singleton Client with Configuration
// src/anima/client.ts
import { Anima } from '@animaapp/anima-sdk';
let instance: Anima | null = null;
export function getAnimaClient(): Anima {
if (!instance) {
if (!process.env.ANIMA_TOKEN) throw new Error('ANIMA_TOKEN not set');
instance = new Anima({ auth: { token: process.env.ANIMA_TOKEN } });
}
return instance;
}
// Preset configurations for different project needs
export const PRESETS = {
nextjs: { language: 'typescript' as const, framework: 'react' as const, styling: 'tailwind' as const, uiLibrary: 'shadcn' as const },
vite: { language: 'typescript' as const, framework: 'react' as const, styling: 'tailwind' as const },
vue: { language: 'typescript' as const, framework: 'vue' as const, styling: 'tailwind' as const },
static: { language: 'javascript' as const, framework: 'html' as const, styling: 'css' as const },
} as const;
Step 2: Generation Cache
// src/anima/cache.ts
import crypto from 'crypto';
import fs from 'fs';
interface CacheEntry {
files: Array<{ fileName: string; content: string }>;
generatedAt: string;
settingsHash: string;
}
class AnimaCache {
private cacheDir: string;
constructor(cacheDir: string = '.anima-cache') {
this.cacheDir = cacheDir;
fs.mkdirSync(cacheDir, { recursive: true });
}
private getKey(fileKey: string, nodeId: string, settings: object): string {
const hash = crypto.createHash('md5')
.update(`${fileKey}:${nodeId}:${JSON.stringify(settings)}`)
.digest('hex…Secure Anima and Figma tokens for design-to-code pipelines.
Anima Security Basics
Overview
This workflow protects the Anima and Figma credentials used by a design-to-code pipeline while keeping generated output reviewable. It applies least privilege to the design source, keeps tokens on the server, and makes secret exposure or unexpected file access a fail-closed condition.
Prerequisites
- A managed secret store and separate development, staging, and production bindings for
ANIMA_TOKENandFIGMA_TOKEN. - An allowlist of Figma file keys and component node IDs, with an owner for each design source and a documented rotation/revocation contact.
- A non-production fixture and a disposable staging workspace for testing token scope, generated artifacts, and rollback behavior.
- Repository secret scanning and a deterministic generated-code directory; never use real customer or personal design data as the test fixture.
Security Checklist
- [ ] Anima token stored in secret manager (not .env in prod)
- [ ] Figma PAT has minimum required scope (file:read only)
- [ ] SDK runs server-side only (never ship tokens to browser)
- [ ]
.envfiles gitignored and chmod 600 - [ ] CI secrets stored in GitHub Secrets, not workflow files
- [ ] Generated code reviewed before committing (no embedded tokens)
Instructions
Step 1: Figma Token Scope Restriction
# When creating a Figma Personal Access Token:
# - Give it the MINIMUM scope needed: File Content (read-only)
# - Do NOT grant write access unless you need Figma plugin features
# - Set an expiration date (90 days recommended)
# - Create separate tokens for dev vs CI environments
Step 2: Server-Side Only Enforcement
// src/anima/safety.ts
// Anima SDK is designed for server-side use only
function validateEnvironment(): void {
if (typeof window !== 'undefined') {
throw new Error('Anima SDK must run server-side only — never import in browser code');
}
if (!process.env.ANIMA_TOKEN) throw new Error('ANIMA_TOKEN not set');
if (!process.env.FIGMA_TOKEN) throw new Error('FIGMA_TOKEN not set');
}
// Call this at startup
validateEnvironment();
Error Handling
| Failure | Required response |
|---|---|
| Secret manager is unavailable or a required token is empty | Abort before any Figma or Anima request; emit only a redacted reason and retry through the deployment system. |
| A browser bundle imports the SDK or contains a token | Fail the build, remove the artifact, and rotate any credential that may have been exposed. |
| Figma returns an authorization or scope error | Stop the run and review the file/node allowlist; do no… |
Upgrade @animaapp/anima-sdk versions and handle API changes.
Anima Upgrade & Migration
Overview
This workflow moves an Anima integration between SDK versions or from manual Figma exports to automation while preserving a reviewable, reversible design source of truth. It uses a pinned dependency and a staging canary so API or generated-code changes are detected before production output is replaced.
Prerequisites
- A clean working tree, committed lockfile, current SDK version, and a reviewed changelog or release note for the proposed target version.
- A fixture registry containing synthetic or approved design nodes, expected output paths, and a baseline artifact digest for the current workflow.
- Separate staging credentials with read-only design access, an owner for generated-code review, and a rollback revision that can restore the prior SDK and generated output.
- CI gates for install, lint, type checking, tests, and secret scanning; do not test an upgrade against customer designs or live production writes.
Migration Paths
| From | To | Complexity |
|---|---|---|
| Figma plugin (manual) | SDK automation | Medium |
| SDK v1 → v2 | SDK latest | Low |
| Anima Playground | SDK API | Low |
Instructions
Step 1: Upgrade SDK
# Check current version
npm list @animaapp/anima-sdk
# Upgrade to latest
npm install @animaapp/anima-sdk@latest
# Check for breaking changes
npm info @animaapp/anima-sdk changelog
Step 2: Migrate from Manual Plugin to SDK
// BEFORE: Manual Figma plugin workflow
// 1. Open Figma → Plugins → Anima
// 2. Select component → Export → React
// 3. Copy-paste generated code into project
// 4. Manually repeat for each component change
// AFTER: Automated SDK workflow
import { Anima } from '@animaapp/anima-sdk';
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
// Automated: runs in CI on Figma file version change
async function syncDesignToCode() {
const { files } = await anima.generateCode({
fileKey: process.env.FIGMA_FILE_KEY!,
figmaToken: process.env.FIGMA_TOKEN!,
nodesId: ['1:2', '3:4', '5:6'], // All design system components
settings: { language: 'typescript', framework: 'react', styling: 'tailwind' },
});
// Write to project, run through linter, create PR
for (const file of files) {
require('fs').writeFileSync(`src/components/generated/${file.fileName}`, file.content);
}
}
Step 3: API Changes Checklist
// Common API changes between versions:
// - New settings options (e.g., uiLibrary: 'shadcn' added later)
// - New frameworks (e.g., Next.js-specific output)
// …Use Figma webhooks to trigger automatic Anima code generation on design changes.
Anima Webhooks & Events
Overview
Anima doesn't have its own webhooks, but you can use Figma Webhooks (v2 API) to detect design changes and trigger Anima code generation automatically. This creates an event-driven design-to-code pipeline.
Prerequisites
- Team-level Figma webhook permission, a publicly reachable HTTPS endpoint, and a webhook passcode stored in a secret manager rather than source or request logs.
- An allowlist mapping approved file keys and component node IDs to their generated output directories and responsible owners.
- A durable event-id/version store, queue with retry and dead-letter handling, and a staging workspace containing synthetic design data.
- A rate-limit budget, replay/duplicate policy, and an explicit approval gate before generated code can be merged or deployed.
Instructions
Step 1: Register Figma Webhook
# Figma Webhooks API (requires team-level access)
curl -X POST "https://api.figma.com/v2/webhooks" \
-H "X-Figma-Token: ${FIGMA_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"event_type": "FILE_VERSION_UPDATE",
"team_id": "YOUR_TEAM_ID",
"endpoint": "https://your-server.com/webhooks/figma",
"passcode": "your-webhook-secret",
"description": "Trigger Anima code generation on design changes"
}'
Step 2: Webhook Handler
// src/webhooks/figma-handler.ts
import express from 'express';
import { Anima } from '@animaapp/anima-sdk';
const router = express.Router();
const anima = new Anima({ auth: { token: process.env.ANIMA_TOKEN! } });
interface FigmaWebhookEvent {
event_type: 'FILE_VERSION_UPDATE' | 'FILE_UPDATE' | 'FILE_DELETE';
file_key: string;
file_name: string;
triggered_by: { id: string; handle: string };
timestamp: string;
passcode: string;
}
router.post('/webhooks/figma', express.json(), async (req, res) => {
const event = req.body as FigmaWebhookEvent;
// Verify passcode
if (event.passcode !== process.env.FIGMA_WEBHOOK_SECRET) {
return res.status(401).json({ error: 'Invalid passcode' });
}
// Only process file version updates
if (event.event_type !== 'FILE_VERSION_UPDATE') {
return res.status(200).json({ skipped: true });
}
console.log(`Design changed: ${event.file_name} by ${event.triggered_by.handle}`);
// Trigger async generation — respond immediately
regenerateComponents(event.file_key).catch(console.error);
res.status(200).json({ accepted: true });
});
async function regenerateComponents(fileKey: string) {
const COMPONENT_NODES = ['1:2', '3:4', '5:6']; // Your component node IDs
for …Ready to use anima-pack?
Related Plugins
supabase-pack
Complete Supabase integration skill pack with 30 skills covering authentication, database, storage, realtime, edge functions, and production operations. Flagship+ tier vendor pack.
/plugin install supabase-pack@claude-code-plugins-plus
vercel-pack
Complete Vercel integration skill pack with 30 skills covering deployments, edge functions, preview environments, performance optimization, and production operations. Flagship+ tier vendor pack.
/plugin install vercel-pack@claude-code-plugins-plus
clay-pack
Complete Clay integration skill pack with 30 skills covering data enrichment, waterfall workflows, AI agents, and GTM automation. Flagship+ tier vendor pack.
/plugin install clay-pack@claude-code-plugins-plus
cursor-pack
Complete Cursor integration skill pack with 30 skills covering AI code editing, composer workflows, codebase indexing, and productivity features. Flagship+ tier vendor pack.
/plugin install cursor-pack@claude-code-plugins-plus
exa-pack
Complete Exa integration skill pack with 30 skills covering neural search, semantic retrieval, web search API, and AI-powered discovery. Flagship+ tier vendor pack.
/plugin install exa-pack@claude-code-plugins-plus
firecrawl-pack
Complete Firecrawl integration skill pack with 30 skills covering web scraping, crawling, markdown conversion, and LLM-ready data extraction. Flagship+ tier vendor pack.
/plugin install firecrawl-pack@claude-code-plugins-plus