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_TOKEN and 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-cache private 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');
return hash;
}
get(fileKey: string, nodeId: string, settings: object): CacheEntry | null {
const key = this.getKey(fileKey, nodeId, settings);
const path = `${this.cacheDir}/${key}.json`;
if (!fs.existsSync(path)) return null;
return JSON.parse(fs.readFileSync(path, 'utf8'));
}
set(fileKey: string, nodeId: string, settings: object, files: any[]): void {
const key = this.getKey(fileKey, nodeId, settings);
const entry: CacheEntry = {
files,
generatedAt: new Date().toISOString(),
settingsHash: key,
};
fs.writeFileSync(`${this.cacheDir}/${key}.json`, JSON.stringify(entry));
}
}
export { AnimaCache };
Step 3: Output Normalizer
// src/anima/normalizer.ts
// Normalize Anima output to match project conventions
interface NormalizationConfig {
componentNameCase: 'PascalCase' | 'kebab-case';
addBarrelExport: boolean;
wrapWithCn: boolean;
addTypeAnnotations: boolean;
}
function normalizeOutput(
files: Array<{ fileName: string; content: string }>,
config: NormalizationConfig,
): Array<{ fileName: string; content: string }> {
return files.map(file => {
let content = file.content;
if (config.wrapWithCn && file.fileName.endsWith('.tsx')) {
// Add cn() import and wrap className strings
if (!content.includes("import { cn }")) {
content = content.replace(
/^(import .+\n)/m,
"$1import { cn } from '@/lib/utils';\n"
);
}
}
if (config.addTypeAnnotations && file.fileName.endsWith('.tsx')) {
content = content.replace(
/export default function (\w+)\(\)/g,
'export default function $1(): React.ReactElement'
);
}
return { fileName: file.fileName, content };
});
}
export { normalizeOutput, NormalizationConfig };
Step 4: Error Recovery Pattern
// src/anima/retry.ts
async function generateWithRetry(
anima: Anima,
params: any,
maxRetries: number = 3,
): Promise<any> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await anima.generateCode(params);
} catch (err: any) {
if (attempt === maxRetries) throw err;
const delay = 2000 * Math.pow(2, attempt - 1);
console.log(`Generation failed, retry ${attempt}/${maxRetries} in ${delay}ms`);
await new Promise(r => setTimeout(r, delay));
}
}
}
Error Handling
- Fail fast with a redacted configuration error when
ANIMA_TOKEN is missing or rejected, and do not retry 401/403 responses. Check Figma file/node permissions separately from Anima authentication so an operator can correct the smallest scope.
- Treat cache misses as normal, but treat malformed JSON, schema drift, a settings-hash mismatch, or a cache entry outside the approved directory as a cache failure: quarantine or delete that entry and regenerate from the sandbox-approved request rather than trusting it.
- Retry only bounded transient network, timeout, 429, and 5xx failures with exponential backoff and jitter. Cap total attempts and elapsed time; use a request fingerprint to make a resume idempotent and never retry a whole batch when only selected nodes failed.
- If normalization or type-checking fails, retain the raw result only in the private quarantine area, block publication, and report rule IDs plus file counts. Never write generated source, design contents, personal data, or exception payloads to logs.
- On process interruption or partial cache writes, use atomic replacement and restore the previous valid entry. A rollback removes quarantined artifacts, revokes temporary access, and records only the digest, stage, and retention/deletion result.
Examples
The wrapper can keep a sandbox run deterministic while avoiding duplicate generation:
const settings = PRESETS.nextjs;
const fileKey = 'synthetic-design-system';
const nodeId = 'button-primary-fixture';
const cache = new AnimaCache('/var/lib/anima-cache/sandbox');
const cached = cache.get(fileKey, nodeId, settings);
const files = cached?.files ?? (await getAnimaClient().generateCode({
fileKey,
nodesId: [nodeId],
settings,
})).files;
if (!cached) cache.set(fileKey, nodeId, settings, files);
const normalized = normalizeOutput(files, {
componentNameCase: 'PascalCase',
addBarrelExport: true,
wrapWithCn: false,
addTypeAnnotations: true,
});
console.log(JSON.stringify({ fileKey, nodeCount: 1, files: normalized.length, contactsExported: 0 }));
The acceptance receipt for this fixture is cache=miss|hit; source=synthetic; files=bounded; contacts_exported=0; secret_scan=pass. A production run additionally requires an approved file/node allowlist, a reviewed diff, and a tested rollback reference before the normalized files are published.
Output
- Singleton client with preset configurations
- File-based generation cache (avoid redundant API calls)
- Output normalizer for project convention matching
- Retry pattern for API resilience
Resources
Next Steps
Apply patterns in anima-core-workflow-a for automated design pipelines.
1---2name: anima-sdk-patterns3description: Apply production-ready patterns for the Anima SDK design-to-code pipeline. Use when building reusable Anima client wrappers, implementing output caching, or establishing team standards for design-to-code automation. Trigger: "anima SDK patterns", "anima best practices", "anima code patterns".4license: MIT5---6# Anima SDK Patterns
7
8## Overview
9
10Production patterns for `@animaapp/anima-sdk`: singleton client, generation caching, output normalization, and configurable settings presets.
11
12## Prerequisites
13
14- 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.
15- Inject `ANIMA_TOKEN` and 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.
16- Make `.anima-cache` private 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.
17- 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.
18
19## Instructions
20
21### Step 1: Singleton Client with Configuration
22
23```typescript
24// src/anima/client.ts
25import { Anima } from '@animaapp/anima-sdk';
26
27let instance: Anima | null = null;
28
29export function getAnimaClient(): Anima {
30 if (!instance) {
31 if (!process.env.ANIMA_TOKEN) throw new Error('ANIMA_TOKEN not set');
32 instance = new Anima({ auth: { token: process.env.ANIMA_TOKEN } });
33 }
34 return instance;
35}
36
37// Preset configurations for different project needs
38export const PRESETS = {
39 nextjs: { language: 'typescript' as const, framework: 'react' as const, styling: 'tailwind' as const, uiLibrary: 'shadcn' as const },
40 vite: { language: 'typescript' as const, framework: 'react' as const, styling: 'tailwind' as const },
41 vue: { language: 'typescript' as const, framework: 'vue' as const, styling: 'tailwind' as const },
42 static: { language: 'javascript' as const, framework: 'html' as const, styling: 'css' as const },
43} as const;
44```
45
46### Step 2: Generation Cache
47
48```typescript
49// src/anima/cache.ts
50import crypto from 'crypto';
51import fs from 'fs';
52
53interface CacheEntry {
54 files: Array<{ fileName: string; content: string }>;
55 generatedAt: string;
56 settingsHash: string;
57}
58
59class AnimaCache {
60 private cacheDir: string;
61
62 constructor(cacheDir: string = '.anima-cache') {
63 this.cacheDir = cacheDir;
64 fs.mkdirSync(cacheDir, { recursive: true });
65 }
66
67 private getKey(fileKey: string, nodeId: string, settings: object): string {
68 const hash = crypto.createHash('md5')
69 .update(`${fileKey}:${nodeId}:${JSON.stringify(settings)}`)
70 .digest('hex');
71 return hash;
72 }
73
74 get(fileKey: string, nodeId: string, settings: object): CacheEntry | null {
75 const key = this.getKey(fileKey, nodeId, settings);
76 const path = `${this.cacheDir}/${key}.json`;
77 if (!fs.existsSync(path)) return null;
78 return JSON.parse(fs.readFileSync(path, 'utf8'));
79 }
80
81 set(fileKey: string, nodeId: string, settings: object, files: any[]): void {
82 const key = this.getKey(fileKey, nodeId, settings);
83 const entry: CacheEntry = {
84 files,
85 generatedAt: new Date().toISOString(),
86 settingsHash: key,
87 };
88 fs.writeFileSync(`${this.cacheDir}/${key}.json`, JSON.stringify(entry));
89 }
90}
91
92export { AnimaCache };
93```
94
95### Step 3: Output Normalizer
96
97```typescript
98// src/anima/normalizer.ts
99// Normalize Anima output to match project conventions
100
101interface NormalizationConfig {
102 componentNameCase: 'PascalCase' | 'kebab-case';
103 addBarrelExport: boolean;
104 wrapWithCn: boolean;
105 addTypeAnnotations: boolean;
106}
107
108function normalizeOutput(
109 files: Array<{ fileName: string; content: string }>,
110 config: NormalizationConfig,
111): Array<{ fileName: string; content: string }> {
112 return files.map(file => {
113 let content = file.content;
114
115 if (config.wrapWithCn && file.fileName.endsWith('.tsx')) {
116 // Add cn() import and wrap className strings
117 if (!content.includes("import { cn }")) {
118 content = content.replace(
119 /^(import .+\n)/m,
120 "$1import { cn } from '@/lib/utils';\n"
121 );
122 }
123 }
124
125 if (config.addTypeAnnotations && file.fileName.endsWith('.tsx')) {
126 content = content.replace(
127 /export default function (\w+)\(\)/g,
128 'export default function $1(): React.ReactElement'
129 );
130 }
131
132 return { fileName: file.fileName, content };
133 });
134}
135
136export { normalizeOutput, NormalizationConfig };
137```
138
139### Step 4: Error Recovery Pattern
140
141```typescript
142// src/anima/retry.ts
143async function generateWithRetry(
144 anima: Anima,
145 params: any,
146 maxRetries: number = 3,
147): Promise<any> {
148 for (let attempt = 1; attempt <= maxRetries; attempt++) {
149 try {
150 return await anima.generateCode(params);
151 } catch (err: any) {
152 if (attempt === maxRetries) throw err;
153 const delay = 2000 * Math.pow(2, attempt - 1);
154 console.log(`Generation failed, retry ${attempt}/${maxRetries} in ${delay}ms`);
155 await new Promise(r => setTimeout(r, delay));
156 }
157 }
158}
159```
160
161## Error Handling
162
163- Fail fast with a redacted configuration error when `ANIMA_TOKEN` is missing or rejected, and do not retry 401/403 responses. Check Figma file/node permissions separately from Anima authentication so an operator can correct the smallest scope.
164- Treat cache misses as normal, but treat malformed JSON, schema drift, a settings-hash mismatch, or a cache entry outside the approved directory as a cache failure: quarantine or delete that entry and regenerate from the sandbox-approved request rather than trusting it.
165- Retry only bounded transient network, timeout, 429, and 5xx failures with exponential backoff and jitter. Cap total attempts and elapsed time; use a request fingerprint to make a resume idempotent and never retry a whole batch when only selected nodes failed.
166- If normalization or type-checking fails, retain the raw result only in the private quarantine area, block publication, and report rule IDs plus file counts. Never write generated source, design contents, personal data, or exception payloads to logs.
167- On process interruption or partial cache writes, use atomic replacement and restore the previous valid entry. A rollback removes quarantined artifacts, revokes temporary access, and records only the digest, stage, and retention/deletion result.
168
169## Examples
170
171The wrapper can keep a sandbox run deterministic while avoiding duplicate generation:
172
173```typescript
174const settings = PRESETS.nextjs;
175const fileKey = 'synthetic-design-system';
176const nodeId = 'button-primary-fixture';
177const cache = new AnimaCache('/var/lib/anima-cache/sandbox');
178
179const cached = cache.get(fileKey, nodeId, settings);
180const files = cached?.files ?? (await getAnimaClient().generateCode({
181 fileKey,
182 nodesId: [nodeId],
183 settings,
184})).files;
185
186if (!cached) cache.set(fileKey, nodeId, settings, files);
187const normalized = normalizeOutput(files, {
188 componentNameCase: 'PascalCase',
189 addBarrelExport: true,
190 wrapWithCn: false,
191 addTypeAnnotations: true,
192});
193console.log(JSON.stringify({ fileKey, nodeCount: 1, files: normalized.length, contactsExported: 0 }));
194```
195
196The acceptance receipt for this fixture is `cache=miss|hit; source=synthetic; files=bounded; contacts_exported=0; secret_scan=pass`. A production run additionally requires an approved file/node allowlist, a reviewed diff, and a tested rollback reference before the normalized files are published.
197
198## Output
199
200- Singleton client with preset configurations
201- File-based generation cache (avoid redundant API calls)
202- Output normalizer for project convention matching
203- Retry pattern for API resilience
204
205## Resources
206
207- [Anima SDK GitHub](https://github.com/AnimaApp/anima-sdk)
208- [Anima API Docs](https://docs.animaapp.com/docs/anima-api)
209
210## Next Steps
211
212Apply patterns in `anima-core-workflow-a` for automated design pipelines.