본문으로 건너뛰기
cccskills
무료GitHub에 공개

anima-sdk-patterns

Structure Anima SDK workflows with a reusable client, preset settings, source-aware caching, output normalization, and bounded retries. These patterns help teams make design-to-code generation more consistent while controlling cache scope and recovery behavior.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

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 with: "anima SDK patterns", "anima best practices", "anima code patterns".

연동 도구Figma

실행 점수 미검증

설치 방법 보기

이럴 때 유용합니다

  • Create a shared Anima SDK client for a project
  • Avoid repeat generation with a source-aware cache
  • Normalize generated files to match project conventions
  • Retry temporary API failures within set limits

포함된 파일(2)

  • SKILL.md9.8 KB
  • references/official-docs.md788 B

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Anima SDK Patterns

Overview

Build a backend @animaapp/anima-sdk wrapper with a pinned client, supported settings, source-bound caching, contained output normalization, and bounded error recovery. Reject unsupported framework values and ambiguous cache entries.

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 },
  reactPlainCss: { language: 'typescript' as const, framework: 'react' as const, styling: 'plain_css' as const },
  static: { language: 'javascript' as const, framework: 'html' as const, styling: 'plain_css' as const },
} as const;

Step 2: Generation Cache

// src/anima/cache.ts
import crypto from 'crypto';
import fs from 'fs';

interface CacheEntry {
  files: Record<string, { content: string; isBinary: boolean }>;
  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, sourceRevision: string, nodeId: string, settings: object): string {
    const hash = crypto.createHash('sha256')
      .update(`${fileKey}:${sourceRevision}:${nodeId}:${JSON.stringify(settings)}`)
      .digest('hex');
    return hash;
  }

  get(fileKey: string, sourceRevision: string, nodeId: string, settings: object): CacheEntry | null {
    const key = this.getKey(fileKey, sourceRevision, nodeId, settings);
    const path = `${this.cacheDir}/${key}.json`;
    if (!fs.existsSync(path)) return null;
    return JSON.parse(fs.readFileSync(path, 'utf8'));
  }

  set(fileKey: string, sourceRevision: string, nodeId: string, settings: object, files: CacheEntry['files']): void {
    const key = this.getKey(fileKey, sourceRevision, 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: Record<string, { content: string; isBinary: boolean }>,
  config: NormalizationConfig,
): Record<string, { content: string; isBinary: boolean }> {
  return Object.fromEntries(Object.entries(files).map(([fileName, file]) => {
    if (file.isBinary) return [fileName, file];
    let content = file.content;

    if (config.wrapWithCn && 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 && fileName.endsWith('.tsx')) {
      content = content.replace(
        /export default function (\w+)\(\)/g,
        'export default function $1(): React.ReactElement'
      );
    }

    return [fileName, { ...file, content }];
  }));
}

export { normalizeOutput, NormalizationConfig };

Step 4: Error Recovery Pattern

// src/anima/retry.ts
import { Anima } from '@animaapp/anima-sdk';

async function generateWithRetry(
  anima: Anima,
  params: Parameters<Anima['generateCode']>[0],
  maxAttempts = 3,
  maxElapsedMs = 15_000,
): Promise<Awaited<ReturnType<Anima['generateCode']>>> {
  const started = Date.now();
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await anima.generateCode(params);
    } catch (error: unknown) {
      const status = typeof error === 'object' && error !== null && 'status' in error
        ? Number(error.status)
        : undefined;
      const retryable = status === 429 || (status !== undefined && status >= 500);
      const delay = Math.min(2_000 * 2 ** (attempt - 1) + Math.floor(Math.random() * 250), 8_000);
      if (!retryable || attempt === maxAttempts || Date.now() + delay - started > maxElapsedMs) {
        throw error;
      }
      console.warn({ event: 'anima-retry', attempt, delay, status });
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
  throw new Error('Retry loop exhausted');
}

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 sourceRevision = 'synthetic-version-1';
const nodeId = 'button-primary-fixture';
const cache = new AnimaCache('/var/lib/anima-cache/sandbox');

const cached = cache.get(fileKey, sourceRevision, nodeId, settings);
const files = cached?.files ?? (await getAnimaClient().generateCode({
  fileKey,
  figmaToken: process.env.FIGMA_TOKEN!,
  nodesId: [nodeId],
  settings,
})).files;

if (!cached) cache.set(fileKey, sourceRevision, nodeId, settings, files);
const normalized = normalizeOutput(files, {
  componentNameCase: 'PascalCase',
  addBarrelExport: true,
  wrapWithCn: false,
  addTypeAnnotations: true,
});
console.log(JSON.stringify({ fileKey, nodeCount: 1, files: Object.keys(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.

Tool Discipline

Use Read and Grep to inspect the existing integration and generated diff before changing anything. Use Write or Edit only inside the approved generated-code, test, or configuration paths. Use the declared Bash commands only for the explicit install, validation, or diagnostic steps in this workflow; never print tokens, source designs, generated source, or private website captures.

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

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Add a synthetic-data CI gate for customer-owned Abridge integration code. Test consent handling, note-review handoffs, redaction, and rollback behavior with mocked vendor boundaries, without connecting CI to a live Abridge or EHR tenant.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Adding regression checks to an Abridge integration repository
  • Testing consent and note-release handling
  • Checking logs for sensitive data exposure
jeremylongshore/tons-of-skills-marketplace2.9천2026년 10월 25일 업데이트

Triage Abridge recording, note review, Epic handoff, and access problems using observed symptoms and approved guidance. Identify the affected workflow stage, organize a minimal timeline, and prepare a redacted escalation record for the responsible team.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Separate recording problems from upload failures
  • Investigate note creation delays and editor issues
  • Identify the responsible team for Epic handoff failures
jeremylongshore/tons-of-skills-marketplace2.9천2026년 10월 25일 업데이트

Map and review an Abridge clinical documentation workflow from consent and recording through draft review, evidence checks, edits, and final disposition. Keep clinician approval explicit, identify failure exits, and separate verified facts from tenant-specific details and pending approvals.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Map a clinical note workflow for a care setting
  • Check where consent and patient identity are verified
  • Review draft notes against linked evidence before sign-off
jeremylongshore/tons-of-skills-marketplace2.9천2026년 10월 25일 업데이트

Audit how clinician-reviewed Abridge note sections map into Epic templates and downstream workflows. Use approved test records to document destinations, exceptions, evidence, rollback steps, and a go or no-go decision for a specific environment.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Checking Abridge note section mappings to Epic templates
  • Auditing a department’s approved documentation handoff
  • Preparing test evidence and a go or no-go decision
jeremylongshore/tons-of-skills-marketplace2.9천2026년 10월 25일 업데이트

Review Abridge adoption and workflow value using local usage records, clinician feedback, and verified contract costs. Build an evidence based decision table covering adoption, quality, support burden, and options to expand, hold, or improve the rollout.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Reviewing adoption after an Abridge rollout
  • Preparing evidence for a renewal decision
  • Comparing workflow outcomes across care settings
jeremylongshore/tons-of-skills-marketplace2.9천2026년 10월 25일 업데이트

Prepare a bounded support bundle for an Abridge issue using allowlisted operational details such as versions, coarse timestamps, and correlation references. Exclude recordings, transcripts, patient identifiers, credentials, and unrestricted logs, then document redactions and review details.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Preparing reviewed evidence for an Abridge support case
  • Documenting redactions and excluded data
  • Collecting approved operational details for an incident
jeremylongshore/tons-of-skills-marketplace2.9천2026년 10월 25일 업데이트

jeremylongshore의 스킬 모두 보기

이 스킬의 문제 신고