{"_id":"@animaapp/entities-generator","_rev":"4-d99862d7499456b3327256ddd665e2e7","name":"@animaapp/entities-generator","dist-tags":{"latest":"1.3.0"},"versions":{"1.3.0":{"name":"@animaapp/entities-generator","version":"1.3.0","keywords":["entity","json","generator","ai","llm","frontend","codebase","typescript"],"author":{"name":"Anima Team"},"license":"MIT","_id":"@animaapp/entities-generator@1.3.0","maintainers":[{"name":"animaapp-npm","email":"support@animaapp.com"},{"name":"moez_anima","email":"moez@animaapp.com"},{"name":"aymeric_animaapp","email":"aymeric@animaapp.com"},{"name":"ofer-animaapp","email":"ofer@animaapp.com"},{"name":"haim_anima","email":"haim@animaapp.com"},{"name":"macabeus-anima","email":"bruno@animaapp.com"},{"name":"omerpr","email":"omer@animaapp.com"},{"name":"anima-emilio","email":"emilio@animaapp.com"},{"name":"federico_anima","email":"federico@animaapp.com"}],"homepage":"https://github.com/AnimaApp/anima-design-to-code/tree/main/packages/entities-generator#readme","bugs":{"url":"https://github.com/AnimaApp/anima-design-to-code/issues"},"dist":{"shasum":"ffeedd004a07b30f863b5432b0c4b42337f90d73","tarball":"https://registry.npmjs.org/@animaapp/entities-generator/-/entities-generator-1.3.0.tgz","fileCount":5,"integrity":"sha512-fJZOFfd2twmU8bXylT/dw39ptz3HLOZyLEMwap4/JrqZKyYnd/bK6tFMnL0gejUXykvT3s1qC+Az0ylFvvGXJA==","signatures":[{"sig":"MEYCIQDiYAY+aiLLAfpifOhrWXbUUmm3uBrGj4Lgr6mCHOHW8wIhAJAbbrgl6Afo+hOxfboPEgk6MWhPW8L9yEQSrg+VT9OV","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":185925},"main":"dist/index.js","type":"module","types":"dist/index.d.ts","engines":{"node":">=18.0.0"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"}},"gitHead":"bb1b15fe507d6571dea139932b3b5ef9d5d3ba27","scripts":{"dev":"tsup --watch","lint":"eslint src tests --ext .ts","test":"vitest run","build":"tsup","clean":"rm -rf ./dist","start":"npx @langchain/langgraph-cli dev","deploy":"yarn run build && npm publish --access public --no-workspaces","typecheck":"tsc --noEmit","test:watch":"vitest","test:coverage":"vitest run --coverage"},"_npmUser":{"name":"anima-emilio","email":"emilio@animaapp.com"},"repository":{"url":"git+https://github.com/AnimaApp/anima-design-to-code.git","type":"git","directory":"packages/entities-generator"},"_npmVersion":"10.8.3","description":"DB Entity JSON generator from frontend project codebases","directories":{},"sideEffects":false,"_nodeVersion":"22.9.0","dependencies":{"zod":"^4.0.5","p-retry":"^7.0.0","@langchain/core":"^0.3.62","@langchain/openai":"^0.6.0","@langchain/community":"^0.3.48","@langchain/langgraph":"^0.3.8"},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.19.2","tsup":"^8.5.0","eslint":"^8.57.0","vitest":"^1.0.0","typescript":"^5.9.3","@types/node":"^24.1.0","@typescript-eslint/parser":"^8.46.0","@typescript-eslint/eslint-plugin":"^6.21.0"},"_npmOperationalInternal":{"tmp":"tmp/entities-generator_1.3.0_1760691134873_0.7823809868924496","host":"s3://npm-registry-packages-npm-production"}}},"time":{"created":"2025-10-17T08:52:14.763Z","modified":"2026-08-12T10:24:57.566Z","1.3.0":"2025-10-17T08:52:15.094Z"},"bugs":{"url":"https://github.com/AnimaApp/anima-design-to-code/issues"},"author":{"name":"Anima Team"},"license":"MIT","homepage":"https://github.com/AnimaApp/anima-design-to-code/tree/main/packages/entities-generator#readme","keywords":["entity","json","generator","ai","llm","frontend","codebase","typescript"],"repository":{"url":"git+https://github.com/AnimaApp/anima-design-to-code.git","type":"git","directory":"packages/entities-generator"},"description":"DB Entity JSON generator from frontend project codebases","maintainers":[{"email":"support@animaapp.com","name":"animaapp-npm"},{"email":"moez@animaapp.com","name":"moez_anima"},{"email":"aymeric@animaapp.com","name":"aymeric_animaapp"},{"email":"marin@animaapp.com","name":"marin_anima"},{"email":"ofer@animaapp.com","name":"ofer-animaapp"},{"email":"haim@animaapp.com","name":"haim_anima"},{"email":"bruno@animaapp.com","name":"macabeus-anima"},{"email":"emilio@animaapp.com","name":"anima-emilio"}],"readme":"# @animaapp/entities-generator\n\nLangGraph agent for generating Entity JSON definitions from frontend codebases. Analyzes React/TypeScript code to produce database entity schemas with security patterns.\n\n## Installation\n\n```bash\nnpm install @animaapp/entities-generator\n```\n\n## Quick Start\n\n```typescript\nimport { EntitiesAgent } from '@animaapp/entities-generator';\n\nconst agent = new EntitiesAgent();\n\nconst result = await agent.run({\n  files: {\n    'src/components/UserProfile.tsx': '...',\n    'src/components/ProductCard.tsx': '...',\n    'src/pages/Dashboard.tsx': '...'\n  },\n  keys: {\n    openrouterApiKey: process.env.OPENROUTER_API_KEY\n  },\n  settings: {\n    maxEntities: 10\n  }\n});\n\nif (result.success) {\n  console.log('Generated entities:', result.entities);\n} else {\n  console.error('Errors:', result.errors);\n}\n```\n\n## LangGraph Studio\n\nThis package is designed to work with [LangGraph Studio](https://github.com/langchain-ai/langgraph-studio). The `langgraph.json` configuration enables visual debugging and monitoring of the agent workflow.\n\n### Running with LangGraph CLI\n\n```bash\n# Start the development server\ncd packages/entities-generator\nnpm run start\n\n# Or use the LangGraph CLI directly\nnpx @langchain/langgraph-cli dev\n```\n\nThis will start LangGraph Studio where you can:\n- Visualize the agent's execution graph\n- Inspect intermediate states\n- Debug entity generation step-by-step\n- Monitor token usage in real-time\n\n## LLM Models via OpenRouter\n\nAll models are accessed through [OpenRouter](https://openrouter.ai/), which provides unified access to multiple AI providers. Currently hardcoded to use `x-ai/grok-4-fast`, but supports the following models:\n\n### Supported Models\n\n```typescript\nimport type { OpenRouterModel } from '@animaapp/entities-generator';\n\n// Available models through OpenRouter\ntype Models = \n  | 'openai/gpt-5'\n  | 'openai/gpt-5-mini'\n  | 'openai/gpt-5-nano'\n  | 'openai/gpt-4.1'\n  | 'anthropic/claude-sonnet-4-5'\n  | 'anthropic/claude-sonnet-4-0'\n  | 'anthropic/claude-3-7-sonnet-latest'\n  | 'google/gemini-2.5-flash'\n  | 'x-ai/grok-4-fast';  // Currently used by default\n```\n\n### Getting an OpenRouter API Key\n\n1. Sign up at [openrouter.ai](https://openrouter.ai/)\n2. Generate an API key from your dashboard\n3. Set it in your environment: `OPENROUTER_API_KEY=your-key-here`\n\n## API Reference\n\n### `EntitiesAgent`\n\nLangGraph agent that orchestrates the entity generation workflow.\n\n#### Constructor\n\n```typescript\nconst agent = new EntitiesAgent();\n```\n\n#### `agent.run(input)`\n\nExecutes the entity generation workflow.\n\n**Parameters:**\n\n```typescript\ninterface EntitiesAgentInput {\n  files: Record<string, string>;  // file path -> content\n  keys: {\n    openrouterApiKey?: string;    // Required if not in env\n  };\n  settings?: {\n    maxEntities?: number;         // Default: 10, Max: 50\n  };\n}\n```\n\n**Returns:**\n\n```typescript\ninterface EntitiesAgentOutput {\n  entities: EntityJSON[];\n  success: boolean;\n  errors?: string[];\n  warnings?: string[];\n}\n\ninterface EntityJSON {\n  name: string;                   // CamelCase entity name\n  description: string;\n  properties: Record<string, PropertyDefinition>;\n  security?: SecurityConstraints;\n}\n\ninterface PropertyDefinition {\n  type: 'string' | 'number' | 'boolean' | 'date';\n  description: string;\n  optional?: boolean;\n}\n\ninterface SecurityConstraints {\n  create?: 'admin' | 'creator' | 'authenticated' | 'public';\n  read?: 'admin' | 'creator' | 'authenticated' | 'public';\n  update?: 'admin' | 'creator' | 'authenticated' | 'public';\n  delete?: 'admin' | 'creator' | 'authenticated' | 'public';\n}\n```\n\n#### `agent.getGraph()`\n\nReturns the compiled LangGraph workflow for inspection or visualization.\n\n```typescript\nconst graph = agent.getGraph();\n// Use with LangGraph Studio or for custom execution\n```\n\n## Security Patterns\n\nThe agent automatically detects and applies one of five security patterns to each entity:\n\n### 1. Admin Control\n\n**Use case:** System configs, settings, admin-only data  \n**Permissions:** All operations require admin access\n\n```typescript\n{\n  create: 'admin',\n  read: 'admin',\n  update: 'admin',\n  delete: 'admin'\n}\n```\n\n### 2. Public Info\n\n**Use case:** Blog posts, product catalogs, public content  \n**Permissions:** Public can read, only admins can modify\n\n```typescript\n{\n  create: 'admin',\n  read: 'public',\n  update: 'admin',\n  delete: 'admin'\n}\n```\n\n### 3. Personal Data\n\n**Use case:** User profiles, preferences, private settings  \n**Permissions:** Only the creator can access their own data\n\n```typescript\n{\n  create: 'creator',\n  read: 'creator',\n  update: 'creator',\n  delete: 'creator'\n}\n```\n\n### 4. Collect Input\n\n**Use case:** Contact forms, feedback submissions, surveys  \n**Permissions:** Anyone can submit, only admins can view\n\n```typescript\n{\n  create: 'public',\n  read: 'admin',\n  update: 'admin',\n  delete: 'admin'\n}\n```\n\n### 5. Share Publicly\n**Use case:** User posts, reviews, public contributions  \n**Permissions:** Authenticated users create, everyone reads, creators edit own\n```typescript\n{\n  create: 'authenticated',\n  read: 'public',\n  update: 'creator',\n  delete: 'creator'\n}\n```\n\n## How It Works\n\nThe agent follows a multi-step workflow:\n\n1. **Preprocessing** - Analyzes codebase structure, extracts data patterns from TypeScript interfaces, React props, API calls, and form submissions\n2. **Context Building** - Identifies security patterns (auth, roles, permissions) and categorizes files (components, pages, utilities)\n3. **LLM Generation** - Sends preprocessed context to LLM via OpenRouter\n4. **Postprocessing** - Validates output, applies security patterns, fixes naming conventions\n5. **Output** - Returns validated EntityJSON array with metadata\n\n## Configuration\n\n### Environment Variables\n\n```bash\n# Required\nOPENROUTER_API_KEY=your-openrouter-api-key\n\n# Optional - Debug logging\nENTITIES_GENERATOR_DEBUG=debug   # Show all logs\nENTITIES_GENERATOR_DEBUG=info    # Show info, warnings, errors  \nENTITIES_GENERATOR_DEBUG=warn    # Show warnings, errors only (default)\nENTITIES_GENERATOR_DEBUG=error   # Show errors only\n```\n\n## Examples\n\n### E-commerce Project\n\n```typescript\nimport { EntitiesAgent } from '@animaapp/entities-generator';\n\nconst agent = new EntitiesAgent();\n\nconst result = await agent.run({\n  files: {\n    'src/components/ProductCard.tsx': `\n      interface Product {\n        id: string;\n        name: string;\n        price: number;\n        category: string;\n        inStock: boolean;\n      }\n      \n      export function ProductCard({ product }: { product: Product }) {\n        return <div>{product.name} - ${product.price}</div>;\n      }\n    `,\n    'src/components/UserProfile.tsx': `\n      interface User {\n        id: string;\n        email: string;\n        name: string;\n        orders: Order[];\n        createdAt: Date;\n      }\n    `\n  },\n  keys: {\n    openrouterApiKey: process.env.OPENROUTER_API_KEY\n  },\n  settings: {\n    maxEntities: 5\n  }\n});\n\nif (result.success) {\n  console.log('Generated entities:', result.entities);\n  // Expected output:\n  // [\n  //   {\n  //     name: 'Product',\n  //     description: 'E-commerce product entity',\n  //     properties: {\n  //       id: { type: 'string', description: 'Unique identifier' },\n  //       name: { type: 'string', description: 'Product name' },\n  //       price: { type: 'number', description: 'Product price' },\n  //       category: { type: 'string', description: 'Product category' },\n  //       inStock: { type: 'boolean', description: 'Availability status' }\n  //     },\n  //     security: {\n  //       create: 'admin',\n  //       read: 'public',\n  //       update: 'admin',\n  //       delete: 'admin'\n  //     }\n  //   },\n  //   {\n  //     name: 'User',\n  //     description: 'User account entity',\n  //     properties: { ... },\n  //     security: {\n  //       create: 'creator',\n  //       read: 'creator',\n  //       update: 'creator',\n  //       delete: 'creator'\n  //     }\n  //   }\n  // ]\n}\n```\n\n### Blog Platform\n\n```typescript\nimport { EntitiesAgent } from '@animaapp/entities-generator';\n\nconst agent = new EntitiesAgent();\n\nconst result = await agent.run({\n  files: {\n    'src/pages/BlogPost.tsx': `\n      interface BlogPost {\n        id: string;\n        title: string;\n        content: string;\n        author: Author;\n        publishedAt: Date;\n        tags: string[];\n        isPublished: boolean;\n      }\n      \n      export function BlogPostPage({ post }: { post: BlogPost }) {\n        return (\n          <article>\n            <h1>{post.title}</h1>\n            <p>By {post.author.name}</p>\n            <div>{post.content}</div>\n          </article>\n        );\n      }\n    `,\n    'src/components/ContactForm.tsx': `\n      interface ContactSubmission {\n        name: string;\n        email: string;\n        message: string;\n        submittedAt: Date;\n      }\n      \n      export function ContactForm() {\n        const [form, setForm] = useState<ContactSubmission>();\n        // Form submission logic\n      }\n    `\n  },\n  keys: {\n    openrouterApiKey: process.env.OPENROUTER_API_KEY\n  }\n});\n```\n\n### Custom Max Entities\n\n```typescript\nconst agent = new EntitiesAgent();\n\n// Generate up to 20 entities from a large codebase\nconst result = await agent.run({\n  files: yourLargeCodebase,\n  keys: {\n    openrouterApiKey: process.env.OPENROUTER_API_KEY\n  },\n  settings: {\n    maxEntities: 20  // Default is 10, max is 50\n  }\n});\n```\n\n## Error Handling\n\n```typescript\nconst agent = new EntitiesAgent();\n\ntry {\n  const result = await agent.run({\n    files: yourFiles,\n    keys: {\n      openrouterApiKey: process.env.OPENROUTER_API_KEY\n    }\n  });\n\n  if (!result.success) {\n    console.error('Generation failed:', result.errors);\n    // Handle errors gracefully\n  }\n\n  if (result.warnings) {\n    console.warn('Warnings encountered:', result.warnings);\n    // Log warnings but continue\n  }\n\n  // Process successful results\n  result.entities.forEach(entity => {\n    console.log(`Entity: ${entity.name}`);\n    console.log(`Properties: ${Object.keys(entity.properties).length}`);\n    console.log(`Security pattern applied: ${JSON.stringify(entity.security)}`);\n  });\n} catch (error) {\n  console.error('Agent execution failed:', error);\n}\n```\n\n## Development\n\n### Building\n\n```bash\nnpm run build\n```\n\n### Testing\n\n```bash\nnpm test\nnpm run test:watch\nnpm run test:coverage\n```\n\n### Type Checking\n\n```bash\nnpm run lint\n```\n\n### Development Mode\n\n```bash\n# Watch mode for development\nnpm run dev\n\n# Run with LangGraph Studio\nnpm run start\n```\n\n## Architecture\n\nThis package is built with:\n\n- **LangGraph** - Agent orchestration and workflow management\n- **LangChain** - LLM integration and message handling\n- **Zod** - Runtime type validation and schemas\n- **OpenRouter** - Unified access to multiple LLM providers\n- **TypeScript** - Full type safety throughout\n\n### Project Structure\n\n```\nsrc/\n├── agent/              # LangGraph agent implementation\n│   ├── index.ts       # EntitiesAgent class & workflow\n│   ├── state.ts       # State management\n│   └── nodes/         # Workflow nodes\n├── modules/           # Core business logic\n│   ├── entities-generator/\n│   │   ├── generator.ts      # Main generation logic\n│   │   ├── preprocessor.ts   # File analysis\n│   │   ├── postprocessor.ts  # Validation & cleanup\n│   │   └── prompts.ts        # LLM prompts\n│   └── shared-types/  # Type definitions\n├── providers/         # LLM provider clients\n│   └── openrouter.ts\n└── utils/            # Utilities (logger, parsing, validation)\n```\n\n## Publishing\n\nTo publish a new version:\n\n```bash\n# Build and publish to npm\nyarn deploy\n\n# Or manually\nyarn build\nnpm publish --access public --no-workspaces\n```\n\n## License\n\nMIT\n\n## Contributing\n\nThis package is part of the [Anima Design to Code](https://github.com/AnimaApp/anima-design-to-code) monorepo. See the main repository for contribution guidelines.\n","readmeFilename":"README.md"}