astro + script improvements

This commit is contained in:
Chris Watson
2025-04-16 12:45:23 -06:00
parent 681af8708a
commit 5125f271f2
4 changed files with 272 additions and 303 deletions
+4
View File
@@ -56,6 +56,10 @@
"name": "qwik",
"tags": ["frontend", "framework", "javascript"]
},
{
"name": "astro",
"tags": ["frontend", "framework", "javascript", "ssr"]
},
{
"name": "express",
"tags": ["backend", "framework", "javascript", "nodejs"]
+167 -159
View File
@@ -1,168 +1,176 @@
---
description: Comprehensive best practices and coding standards for Astro projects, including code organization, performance considerations, security, and testing.
description: This rule provides comprehensive best practices and coding standards for developing Astro projects. It covers code organization, performance, security, testing, and common pitfalls.
globs: **/*.astro
---
- # Code Organization and Structure
- ## Directory Structure Best Practices
- `src/`: This is the heart of your Astro project.
- `components/`: Reusable UI elements. Organize components into subdirectories based on functionality or feature.
- `layouts/`: Components that define the overall page structure. Use a `BaseLayout.astro` to provide common elements like `<head>` and `<footer>`.
- `pages/`: Special components that create routes. Each file here becomes a page. Use dynamic routes (`[param].astro`) for data-driven content.
- `content/`: (Required for content collections) Store content collections and an optional `config.ts` or `config.js` file.
- `styles/`: Global CSS or Sass files. Use Astro's CSS Modules for component-specific styles.
- `scripts/`: JavaScript modules or utilities. Consider using TypeScript for type safety.
- `utils/`: Helper functions and utilities.
- `types/`: TypeScript type definitions for your project.
- `public/`: Static assets like images, fonts, and favicons. These are copied directly to the `dist/` folder without processing.
- `dist/`: (Generated) The output directory containing the built website. Usually ignored in version control.
- `node_modules/`: (Generated) Project dependencies managed by npm, pnpm or yarn. Usually ignored in version control.
- `.astro/`: (Generated) Internal Astro files. Should not be manually modified.
- ## File Naming Conventions
- **Components:** `ComponentName.astro` (PascalCase).
- **Pages:** `page-name.astro` (kebab-case). Index pages should be named `index.astro`.
- **Layouts:** `LayoutName.astro` (PascalCase).
- **Styles:** `Component.module.css` (component-specific), `global.css` (global styles).
- **Scripts:** `script-name.js` or `script-name.ts` (kebab-case).
- ## Module Organization
- Favor modularity and reusability.
- Group related components and functions into modules within the appropriate directory (e.g., `components/ui/Button.astro`).
- Use clear and descriptive names for files and folders.
- Expose only the necessary parts of a module using `export` and `import` statements.
- ## Component Architecture Recommendations
- **Atomic Design:** Consider using Atomic Design principles to create a scalable and maintainable component library (Atoms, Molecules, Organisms, Templates, Pages).
- **Composition:** Favor composition over inheritance.
- **Slots:** Utilize Astro's slots to create flexible components that accept dynamic content.
- **Props:** Use TypeScript to define prop types for your components.
- **Keep Components Focused:** A component should ideally handle a single responsibility.
- ## Code Splitting Strategies
- **Automatic Code Splitting:** Astro automatically code-splits JavaScript and CSS, so generally you don't need to manually handle code splitting.
- **Dynamic Imports:** Use dynamic imports (`import('./Component.astro')`) for components or modules that are not immediately needed. This is useful for infrequently used components or large libraries.
- **View Transitions:** Astro's View Transitions API also helps with perceived performance, providing smoother navigation between pages instead of full reloads. Optimize assets for transitions by using the `<Image>` component.
# Astro Library Best Practices and Coding Standards
- # Common Patterns and Anti-patterns
- ## Design Patterns
- **Container/Presentational:** Separate data fetching and logic (container components) from UI rendering (presentational components).
- **Higher-Order Components (HOCs):** Use HOCs or render props (though less common in Astro) to share logic between components.
- **Provider Pattern:** Utilize Astro's `<script context="module">` to provide context values to all components within a scope.
- ## Recommended Approaches
- **Data Fetching:** Fetch data in `<script>` tags inside Astro components using `fetch` or other HTTP libraries. Use `await` to handle asynchronous operations.
- **State Management:** Astro favors a simpler approach with props and events for most use cases. For complex state management, consider using tools like nanostores, zustand or redux if needed.
- **Component Communication:** Pass data down through props. For event handling, use standard JavaScript event listeners and dispatch custom events if needed.
- ## Anti-patterns
- **Mutating Props:** Avoid directly mutating props passed to a component.
- **Over-Complicated State Management:** Don't introduce complex state management libraries unless absolutely necessary.
- **Large Components:** Break down large components into smaller, more manageable pieces.
- **Inline Styles:** Avoid inline styles. Use CSS Modules or global CSS files instead.
- ## State Management Best Practices
- **Local Component State:** Use `Astro.props` for simple local state within a component.
- **Global State (If Needed):** For application-wide state, consider lightweight state management libraries such as nanostores.
- **Avoid Overusing State:** Not every value needs to be reactive state. Consider the complexity trade-off.
- ## Error Handling
- **Try/Catch:** Use `try...catch` blocks to handle errors during data fetching or other asynchronous operations.
- **Error Boundaries (Components):** Create dedicated components to catch errors and display fallback UI.
- **Centralized Logging:** Implement a centralized logging system to track errors in production.
This document outlines the recommended best practices and coding standards for developing Astro projects to ensure maintainability, performance, and security.
- # Performance Considerations
- ## Optimization Techniques
- **Image Optimization:** Use Astro's `<Image>` component for automatic image optimization (resizing, format conversion, lazy loading).
- **Font Optimization:** Use `font-display: swap;` in your CSS to prevent blocking render when loading web fonts.
- **Minification and Bundling:** Astro automatically minifies and bundles CSS and JavaScript during the build process.
- **Remove Unused CSS:** Use tools like PurgeCSS to remove unused CSS from your stylesheets, improving performance.
- **Partial Hydration:** Use Astro's directives (e.g., `client:load`, `client:idle`) to control when components are hydrated, reducing JavaScript overhead.
- ## Memory Management
- **Avoid Memory Leaks:** Be mindful of memory leaks, especially in long-running applications. Properly clean up event listeners and resources when components unmount.
- **Efficient Data Structures:** Choose appropriate data structures for your application's needs.
- ## Rendering Optimization
- **Static Rendering:** Astro favors static rendering, which delivers the fastest possible performance.
- **Server-Side Rendering (SSR):** Use SSR only when necessary for dynamic content or features that require server-side processing.
- **Client-Side Rendering (CSR):** Minimize client-side rendering to improve initial page load time.
- ## Bundle Size Optimization
- **Lazy Loading:** Use lazy loading for images and other assets that are not immediately visible on the page.
- **Tree Shaking:** Astro's build process automatically performs tree shaking to remove unused code from your JavaScript bundles.
- **Code Splitting:** Astro automatically splits your code into smaller chunks, which can improve performance by reducing the amount of code that needs to be downloaded initially.
- ## Lazy Loading Strategies
- **Images:** Use the `loading="lazy"` attribute on `<img>` tags or use the Astro `<Image>` component to automatically lazy load images.
- **Components:** Use dynamic imports to lazy load components that are not immediately needed.
- **Libraries:** Import libraries only when they are needed, using dynamic imports if necessary.
## 1. Code Organization and Structure
- # Security Best Practices
- ## Common Vulnerabilities
- **Cross-Site Scripting (XSS):** Prevent XSS attacks by sanitizing user input and escaping output.
- **Cross-Site Request Forgery (CSRF):** Use CSRF tokens to protect against CSRF attacks.
- **SQL Injection:** Protect against SQL injection attacks by using parameterized queries or an ORM.
- **Man-in-the-Middle (MitM) Attacks:** Use HTTPS to encrypt communication between the client and server.
- ## Input Validation
- **Server-Side Validation:** Always validate user input on the server-side.
- **Client-Side Validation:** Use client-side validation for immediate feedback to the user, but never rely on it as the sole means of validation.
- **Escape Output:** Escape user-provided data when rendering it to prevent XSS.
- ## Authentication and Authorization
- **Use Secure Authentication:** Use a secure authentication mechanism, such as OAuth 2.0 or JWT.
- **Implement Role-Based Access Control (RBAC):** Restrict access to resources based on user roles.
- **Protect API Endpoints:** Require authentication for all API endpoints that require authorization.
- ## Data Protection
- **Encrypt Sensitive Data:** Encrypt sensitive data at rest and in transit.
- **Use Strong Passwords:** Enforce strong password policies.
- **Regularly Back Up Data:** Regularly back up your data in case of data loss or corruption.
- ## Secure API Communication
- **Use HTTPS:** Always use HTTPS to encrypt communication between the client and server.
- **Validate API Responses:** Validate API responses to ensure that they are in the expected format.
- **Rate Limiting:** Implement rate limiting to prevent abuse of your API.
### 1.1 Project Structure
- # Testing Approaches
- ## Unit Testing
- **Test Individual Components:** Test individual components in isolation to ensure that they are working correctly.
- **Mock Dependencies:** Use mocking to isolate components from their dependencies.
- **Assertion Libraries:** Use assertion libraries like Jest or Chai to assert that components are behaving as expected.
- ## Integration Testing
- **Test Component Interactions:** Test the interactions between components to ensure that they are working together correctly.
- **Test Data Flow:** Test the flow of data through your application to ensure that data is being passed correctly between components.
- ## End-to-End Testing
- **Test User Flows:** Test user flows to ensure that users can complete tasks successfully.
- **Automate Tests:** Automate end-to-end tests to ensure that your application is working correctly after changes are made.
- ## Test Organization
- **Locate tests near components:** Keep test files close to the components being tested (e.g. `src/components/MyComponent.test.astro`).
- **Consistent naming:** Use a consistent naming convention for test files (e.g., `MyComponent.test.astro` or `MyComponent.spec.astro`).
- ## Mocking and Stubbing
- **Mock API calls:** Mock API calls to isolate components from the backend.
- **Stub External Dependencies:** Stub external dependencies to control their behavior during testing.
- **Use testing libraries:** Utilize testing libraries such as `jest`, `vitest`, or `mocha` for mocking and stubbing.
- **`src/` Directory:** This directory contains the core source code of your Astro project.
- **`src/pages/`:** This directory is crucial for routing. Every `.astro`, `.md`, or `.mdx` file in this directory automatically becomes a route. Use a clear and consistent naming convention for your pages (e.g., `about.astro`, `blog/index.astro`, `blog/[slug].astro`).
- **`src/components/`:** Store reusable UI components in this directory. Organize components into subdirectories based on their functionality or feature area (e.g., `src/components/Header/`, `src/components/Card/`).
- **`src/layouts/`:** Layouts define the overall structure of your pages (e.g., header, footer, navigation). Use layouts to maintain a consistent look and feel across your website.
- **`src/content/`:** (Recommended for content-driven sites) Use the Content Collections feature to manage structured content like blog posts, documentation, or product listings. Define schemas for your content types to ensure data consistency.
- **`src/styles/`:** Store global styles and CSS variables in this directory. Consider using CSS Modules or a CSS-in-JS solution for component-specific styling.
- **`src/scripts/`:** Place client-side JavaScript files in this directory. Use modules and avoid polluting the global scope.
- **`src/assets/`:** Store static assets like images, fonts, and other media files in this directory.
- **`public/` Directory:** This directory contains static assets that don't need processing, such as `robots.txt`, `favicon.ico`, and other files that should be served directly. Avoid placing images that require optimization in this directory; use the `src/assets/` directory instead.
- **`astro.config.mjs`:** This file contains the Astro configuration options, including integrations, build settings, and more. Keep this file well-organized and documented.
- **`.env`:** Store environment variables in this file. Use a library like `dotenv` to load environment variables into your application.
- # Common Pitfalls and Gotchas
- ## Frequent Mistakes
- **Over-reliance on Client-Side JavaScript:** Remember Astro's focus on minimal JS. Avoid hydrating components unless necessary.
- **Incorrect Component Hydration Directives:** Double-check `client:` directives to make sure components are hydrated at the correct time.
- **Ignoring Performance Metrics:** Pay attention to performance metrics like Lighthouse scores and bundle sizes.
- ## Edge Cases
- **View Transitions with Complex Animations:** Complex animations may need special handling with Astro's View Transitions API.
- **Integrating with Third-Party Libraries:** Some third-party libraries may require custom integration due to Astro's build process.
- ## Version-Specific Issues
- Refer to the Astro documentation and release notes for any version-specific issues or breaking changes.
- ## Compatibility Concerns
- Be aware of compatibility concerns when integrating with other technologies, such as backend frameworks or CMS systems.
- ## Debugging Strategies
- **Browser Developer Tools:** Use browser developer tools to inspect HTML, CSS, and JavaScript.
- **Astro Dev Toolbar:** Take advantage of Astro's built-in Dev Toolbar for component inspection and debugging.
- **Console Logging:** Strategically use `console.log` statements to debug your code.
- **Debugging in VS Code:** Configure VS Code for debugging Astro applications.
### 1.2 Component Design
- # Tooling and Environment
- ## Recommended Development Tools
- **VS Code:** Use VS Code with the official Astro extension for syntax highlighting, code completion, and other features.
- **ESLint:** Configure ESLint with the `eslint-plugin-astro` plugin to lint Astro components.
- **Prettier:** Use Prettier to automatically format your code.
- **EditorConfig:** Use EditorConfig to maintain consistent code style across different editors.
- ## Build Configuration
- **astro.config.mjs:** Configure your Astro project in the `astro.config.mjs` file.
- **Environment Variables:** Use environment variables to configure your application for different environments.
- ## Linting and Formatting
- **ESLint:** Configure ESLint with the recommended rules for Astro projects.
- **Prettier:** Configure Prettier with the recommended options for Astro projects.
- **Husky and Lint-Staged:** Use Husky and Lint-Staged to automatically lint and format your code before committing.
- ## Deployment Best Practices
- **Choose a Deployment Platform:** Choose a deployment platform that is compatible with Astro, such as Netlify, Vercel, or Cloudflare Pages.
- **Configure Build Settings:** Configure your build settings to optimize your application for production.
- **Use a CDN:** Use a CDN to serve your static assets.
- **Optimize Images:** Optimize images for web performance.
- ## CI/CD Integration
- **GitHub Actions:** Use GitHub Actions or other CI/CD tools to automate your build, test, and deployment processes.
- **Automated Testing:** Run automated tests during your CI/CD pipeline to ensure that your application is working correctly before it is deployed.
- **Atomic Design Principles:** Consider using Atomic Design principles to structure your components into atoms, molecules, organisms, templates, and pages. This promotes reusability and maintainability.
- **Single Responsibility Principle:** Each component should have a single, well-defined responsibility. Avoid creating large, complex components that do too much.
- **Props and Slots:** Use props to pass data to components and slots to allow components to accept children. Define prop types using TypeScript to ensure type safety.
## 2. Common Patterns and Anti-patterns
### 2.1 UI Framework Integration
- **Island Architecture:** Embrace Astro's island architecture to minimize JavaScript and improve performance. Only hydrate interactive components.
- **Client Directives:** Use `client:load`, `client:idle`, `client:visible`, `client:media`, and `client:only` directives appropriately to control when components are hydrated. Avoid over-hydrating components.
- **Framework Component Composition:** Compose components from different frameworks (React, Vue, Svelte, etc.) within the same Astro page. This allows you to leverage the strengths of different frameworks.
- **Passing Props and Children:** Pass props and children to framework components from Astro components. Use named slots to organize children.
- **Anti-pattern: Mixing Astro and Framework Components:** Do not import `.astro` components directly into UI framework components (e.g., `.jsx` or `.svelte`). Use slots to pass static content from Astro components to framework components.
### 2.2 Data Fetching
- **`fetch` API:** Use the `fetch` API to fetch data from external sources or internal APIs. Handle errors appropriately.
- **Content Collections API:** Use the Content Collections API to manage structured content like blog posts or documentation. Define schemas for your content types.
- **CMS Integration:** Integrate with a headless CMS like Hygraph, Contentful, or Strapi to manage content. Use the CMS's API to fetch data and display it on your website.
- **GraphQL:** When using a CMS that supports GraphQL (like Hygraph), use GraphQL queries to fetch only the data you need. This can improve performance and reduce data transfer.
### 2.3 Routing
- **File-Based Routing:** Use Astro's file-based routing to create routes automatically. Follow a consistent naming convention for your pages.
- **Dynamic Routes:** Use dynamic routes (e.g., `[slug].astro`) to handle variable segments in the URL. Access the route parameters using `Astro.params`.
- **Nested Routes:** Use nested folders within `src/pages/` to create nested routes.
- **Anti-pattern: Overly Complex Routing:** Avoid creating overly complex routing structures. Keep your routes simple and intuitive.
### 2.4 Styling
- **Scoped CSS:** Use scoped CSS within Astro components to avoid style conflicts. This ensures that component styles are isolated.
- **Global Styles:** Use global styles for site-wide styling. Store global styles in `src/styles/global.css`.
- **CSS Frameworks:** Use CSS frameworks like Tailwind CSS, Bootstrap, or Materialize to speed up development and maintain a consistent look and feel. Install the appropriate integration for your chosen CSS framework.
- **CSS Modules:** Consider using CSS Modules for component-specific styling. CSS Modules generate unique class names to avoid naming collisions.
## 3. Performance Considerations
### 3.1 Minimizing JavaScript
- **Static-First Architecture:** Embrace Astro's static-first architecture to minimize JavaScript and improve performance. Render as much as possible as static HTML.
- **Island Architecture:** Only hydrate interactive components. Avoid over-hydrating components.
- **Code Splitting:** Use code splitting to break up your JavaScript into smaller chunks. This can improve initial load times.
- **Lazy Loading:** Use lazy loading for images and other assets that are not immediately visible. This can improve initial load times.
### 3.2 Image Optimization
- **Astro's `<Image />` Component:** Use Astro's built-in `<Image />` component to optimize images. The `<Image />` component automatically optimizes images, resizes them, and generates responsive versions.
- **Image Formats:** Use modern image formats like WebP to reduce file sizes. Use AVIF for even better compression, where supported.
- **Compression:** Compress images to reduce file sizes. Use tools like ImageOptim or TinyPNG.
- **Lazy Loading:** Use lazy loading for images that are not immediately visible.
- **Responsive Images:** Use responsive images to serve different image sizes based on the user's screen size.
### 3.3 Font Optimization
- **Web Font Formats:** Use modern web font formats like WOFF2. These formats offer better compression and performance.
- **Font Loading:** Use font loading strategies to avoid blocking rendering. Consider using `font-display: swap`.
- **Preloading:** Preload important fonts to improve loading times.
### 3.4 Caching
- **Browser Caching:** Configure browser caching to cache static assets like images, fonts, and JavaScript files. This can improve performance for returning users.
- **CDN:** Use a Content Delivery Network (CDN) to serve static assets from geographically distributed servers. This can improve performance for users around the world.
## 4. Security Best Practices
### 4.1 Input Validation
- **Validate User Input:** Validate all user input to prevent injection attacks and other security vulnerabilities. Use server-side validation in addition to client-side validation.
- **Sanitize User Input:** Sanitize user input to remove potentially malicious code. Use a library like DOMPurify to sanitize HTML.
### 4.2 Cross-Site Scripting (XSS)
- **Escape Output:** Escape all output to prevent XSS attacks. Use Astro's built-in escaping mechanisms or a library like Handlebars.js.
- **Content Security Policy (CSP):** Implement a Content Security Policy (CSP) to control the resources that the browser is allowed to load. This can help prevent XSS attacks.
### 4.3 Cross-Site Request Forgery (CSRF)
- **CSRF Tokens:** Use CSRF tokens to protect against CSRF attacks. Generate a unique CSRF token for each user session and include it in all forms.
### 4.4 Authentication and Authorization
- **Secure Authentication:** Use secure authentication mechanisms to protect user accounts. Use a library like Passport.js or Auth0.
- **Authorization:** Implement authorization to control access to resources. Use roles and permissions to define what users are allowed to do.
### 4.5 Dependency Management
- **Keep Dependencies Up-to-Date:** Keep your dependencies up-to-date to patch security vulnerabilities. Use a tool like `npm audit` or `yarn audit` to identify and fix vulnerabilities.
- **Lock Dependencies:** Lock your dependencies to prevent unexpected changes. Use `package-lock.json` or `yarn.lock`.
### 4.6 Environment Variables
- **Store Secrets Securely:** Store secrets like API keys and database passwords in environment variables. Do not hardcode secrets in your code.
- **Avoid Committing `.env`:** Never commit your `.env` file to version control. Use a `.gitignore` file to exclude it.
## 5. Testing Approaches
### 5.1 Unit Testing
- **Test Individual Components:** Write unit tests to test individual components in isolation. Use a testing framework like Jest or Mocha.
- **Mock Dependencies:** Mock dependencies to isolate components during testing.
### 5.2 Integration Testing
- **Test Component Interactions:** Write integration tests to test how components interact with each other. Use a testing framework like Cypress or Playwright.
### 5.3 End-to-End Testing
- **Test User Flows:** Write end-to-end tests to test complete user flows. Use a testing framework like Cypress or Playwright.
### 5.4 Accessibility Testing
- **Automated Accessibility Testing:** Use automated accessibility testing tools to identify accessibility issues. Use a tool like axe-core.
- **Manual Accessibility Testing:** Perform manual accessibility testing to ensure that your website is accessible to users with disabilities. Use a screen reader to test your website.
## 6. Common Pitfalls and Gotchas
- **Over-Hydration:** Avoid over-hydrating components. Only hydrate interactive components.
- **Incorrect Client Directives:** Use the correct client directives for your components. Using the wrong client directive can lead to performance issues or unexpected behavior.
- **Global Scope Pollution:** Avoid polluting the global scope with JavaScript variables. Use modules to encapsulate your code.
- **Missing `alt` Attributes:** Always include `alt` attributes for images. The `alt` attribute is important for accessibility and SEO.
- **Hardcoded Secrets:** Never hardcode secrets in your code. Store secrets in environment variables.
- **Insecure Dependencies:** Keep your dependencies up-to-date to patch security vulnerabilities.
- **Not handling errors:** Always handle errors gracefully, especially when fetching data or interacting with external APIs.
## 7. Tooling and Environment
### 7.1 Code Editor
- **Visual Studio Code:** Use Visual Studio Code as your code editor. VS Code has excellent support for Astro and other web development technologies.
- **Astro VS Code Extension:** Install the Astro VS Code extension for syntax highlighting, code completion, and other features.
- **ESLint and Prettier:** Install ESLint and Prettier for code linting and formatting.
### 7.2 Package Manager
- **npm, Yarn, or pnpm:** Use npm, Yarn, or pnpm as your package manager. Choose the package manager that best suits your needs.
### 7.3 Build Tool
- **Astro's Built-in Build Tool:** Use Astro's built-in build tool to build your website. The build tool automatically optimizes your code and assets.
### 7.4 Version Control
- **Git:** Use Git for version control. Git allows you to track changes to your code and collaborate with other developers.
- **GitHub, GitLab, or Bitbucket:** Use GitHub, GitLab, or Bitbucket to host your Git repository. These platforms provide a centralized location for managing and collaborating on code.
### 7.5 Deployment
- **Netlify, Vercel, or Cloudflare Pages:** Use Netlify, Vercel, or Cloudflare Pages to deploy your website. These platforms provide easy-to-use deployment workflows and CDN integration.
By following these best practices and coding standards, you can ensure that your Astro projects are maintainable, performant, and secure.
+4
View File
@@ -56,6 +56,10 @@
"name": "qwik",
"tags": ["frontend", "framework", "javascript"]
},
{
"name": "astro",
"tags": ["frontend", "framework", "javascript", "ssr"]
},
{
"name": "express",
"tags": ["backend", "framework", "javascript", "nodejs"]
+97 -144
View File
@@ -192,6 +192,13 @@ class ProgressTracker:
logger.info(f"Found {len(new_libraries)} new libraries to process: {', '.join(new_libraries)}")
return new_libraries
class MDCRuleResponse(BaseModel):
"""Pydantic model for LLM response structure."""
name: str = Field(..., description="Short descriptive name for the rule")
glob_pattern: str = Field(..., description="Valid glob pattern for target files")
description: str = Field(..., description="1-2 sentence description of what the rule does")
content: str = Field(..., description="Formatted rule content using markdown")
def validate_environment_variables() -> bool:
"""Validate that all required environment variables are set."""
required_vars = []
@@ -316,13 +323,13 @@ def generate_mdc_rules_from_exa(library_info: LibraryInfo, exa_results: Dict[str
elif hasattr(citation, 'text') and citation.text:
citation_texts.append(citation.text)
# Combine all citation texts - Gemini can handle much larger inputs
# Combine all citation texts
all_citation_text = "\n\n".join(citation_texts)
# Format tags for prompt - but don't emphasize them too much
# Format tags for prompt
tags_str = ", ".join(library_info.tags)
# Enhanced prompt template for both cases
# Enhanced prompt template
enhanced_prompt_template = """Create a comprehensive Cursor rule file (.mdc) for the {library_name} library following these guidelines:
{mdc_instructions}
@@ -335,79 +342,29 @@ Library Information:
Your task is to create an EXTREMELY DETAILED and COMPREHENSIVE guide that covers:
1. Code Organization and Structure:
- Directory structure best practices for {library_name}
- File naming conventions specific to {library_name}
- Module organization best practices for projects using {library_name}
- Component architecture recommendations for {library_name}
- Code splitting strategies appropriate for {library_name}
1. Code Organization and Structure
2. Common Patterns and Anti-patterns
3. Performance Considerations
4. Security Best Practices
5. Testing Approaches
6. Common Pitfalls and Gotchas
7. Tooling and Environment
2. Common Patterns and Anti-patterns:
- Design patterns specific to {library_name}
- Recommended approaches for common tasks with {library_name}
- Anti-patterns and code smells to avoid when using {library_name}
- State management best practices for {library_name} applications
- Error handling patterns appropriate for {library_name}
You MUST format your response as a valid JSON object with these exact keys:
- name: A short descriptive name for the rule (e.g., "{library_name} Best Practices")
- glob_pattern: The most appropriate glob pattern for this library based on the file types it typically works with
- description: A clear 1-2 sentence description of what the rule covers
- content: The formatted rule content with comprehensive best practices in markdown format
3. Performance Considerations:
- Optimization techniques specific to {library_name}
- Memory management considerations for applications using {library_name}
- Rendering optimization for {library_name} (if applicable)
- Bundle size optimization strategies for projects using {library_name}
- Lazy loading strategies appropriate for {library_name}
4. Security Best Practices:
- Common vulnerabilities and how to prevent them with {library_name}
- Input validation best practices for {library_name}
- Authentication and authorization patterns for {library_name}
- Data protection strategies relevant to {library_name}
- Secure API communication with {library_name}
5. Testing Approaches:
- Unit testing strategies for {library_name} components
- Integration testing approaches for {library_name} applications
- End-to-end testing recommendations for {library_name} projects
- Test organization best practices for {library_name}
- Mocking and stubbing techniques specific to {library_name}
6. Common Pitfalls and Gotchas:
- Frequent mistakes developers make when using {library_name}
- Edge cases to be aware of when using {library_name}
- Version-specific issues with {library_name}
- Compatibility concerns between {library_name} and other technologies
- Debugging strategies for {library_name} applications
7. Tooling and Environment:
- Recommended development tools for {library_name}
- Build configuration best practices for projects using {library_name}
- Linting and formatting recommendations for {library_name} code
- Deployment best practices for {library_name} applications
- CI/CD integration strategies for {library_name} projects
Format your response as a valid JSON object with exactly these keys:
- name: a short descriptive name for the rule (e.g., "{library_name} Best Practices")
- glob_pattern: the most appropriate glob pattern for this library based on the file types it typically works with
- description: a clear 1-2 sentence description of what the rule covers
- content: the formatted rule content with comprehensive best practices in markdown format
"""
DO NOT include any text outside of the JSON object. The response must be a single, valid JSON object."""
# Determine if we need to generate content from scratch
if len(exa_answer.strip()) < 100 and len(all_citation_text.strip()) < 200:
# Not enough content from Exa, generate from scratch
exa_content_section = f"""I need you to research and generate comprehensive best practices for {library_info.name} from your knowledge.
Please be extremely thorough and detailed, covering all aspects of {library_info.name} development.
Your guidance should be useful for both beginners and experienced developers.
"""
prompt = enhanced_prompt_template.format(
library_name=library_info.name,
tags=tags_str,
exa_content_section=exa_content_section,
mdc_instructions=mdc_instructions
)
Your guidance should be useful for both beginners and experienced developers."""
else:
# Use existing Exa content
chunk_size = CONFIG["processing"]["chunk_size"]
exa_content_section = f"""Based on the following information about {library_info.name} best practices:
@@ -418,54 +375,63 @@ Additional information from citations:
{all_citation_text[:chunk_size]}
Please synthesize, enhance, and expand upon this information to create the most comprehensive guide possible.
Add any important best practices that might be missing from the search results.
"""
prompt = enhanced_prompt_template.format(
library_name=library_info.name,
tags=tags_str,
exa_content_section=exa_content_section,
mdc_instructions=mdc_instructions
)
Add any important best practices that might be missing from the search results."""
prompt = enhanced_prompt_template.format(
library_name=library_info.name,
tags=tags_str,
exa_content_section=exa_content_section,
mdc_instructions=mdc_instructions
)
logger.info(f"Sending enhanced prompt to LLM for {library_info.name}")
# Use LiteLLM's completion with JSON mode
response = completion(
model=CONFIG["api"]["llm_model"],
messages=[{"role": "user", "content": prompt}],
response_format={
"type": "json_object",
"schema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Short descriptive name for the rule"
},
"glob_pattern": {
"type": "string",
"description": "Valid glob pattern for target files"
},
"description": {
"type": "string",
"description": "1-2 sentence description of what the rule does"
},
"content": {
"type": "string",
"description": "Formatted rule content using markdown"
}
},
"required": ["name", "glob_pattern", "description", "content"]
}
}
response_format={"type": "json_object"},
max_tokens=4000,
temperature=0.7
)
# Parse the JSON response
json_response = json.loads(response.choices[0].message.content)
logger.info(f"Successfully generated enhanced rule for {library_info.name}")
# Create MDCRule instance from the JSON
rule = MDCRule(**json_response)
return [rule]
# Get the response content and parse it
try:
if hasattr(response.choices[0].message, 'content'):
# Standard response format
content = response.choices[0].message.content
elif hasattr(response.choices[0].message, 'text'):
# Gemini format
content = response.choices[0].message.text
else:
raise ValueError("Unexpected response format from LLM")
# Clean the content to ensure it's valid JSON
content = content.strip()
if content.startswith('```json'):
content = content[7:]
if content.endswith('```'):
content = content[:-3]
content = content.strip()
# Parse the JSON response
json_response = json.loads(content)
# Validate against our schema
rule_data = MDCRuleResponse(**json_response)
# Create MDCRule instance using model_dump instead of dict
rule = MDCRule(**rule_data.model_dump())
logger.info(f"Successfully generated enhanced rule for {library_info.name}")
return [rule]
except json.JSONDecodeError as e:
logger.error(f"Failed to parse JSON response for {library_info.name}: {str(e)}\nResponse content: {content}")
raise
except Exception as e:
logger.error(f"Error processing response for {library_info.name}: {str(e)}")
raise
except Exception as e:
logger.error(f"Error generating MDC rule for {library_info.name}: {str(e)}")
@@ -596,16 +562,32 @@ def process_rules_json(json_path: str, output_dir: str, test_mode: bool = False,
# Filter libraries based on target tag or library if specified
if specific_library:
# When specific library is provided, force process it regardless of progress status
filtered_libraries = [lib for lib in libraries if lib["name"] == specific_library]
if not filtered_libraries:
logger.error(f"Library '{specific_library}' not found in rules.json")
return
libraries_to_process = filtered_libraries
elif specific_tag:
filtered_libraries = [lib for lib in libraries if specific_tag in lib["tags"]]
# For tag filtering, apply normal progress tracking rules
libraries_to_process = []
for library in filtered_libraries:
library_key = library["name"]
if not progress_tracker.is_library_processed(library_key) or retry_failed_only and progress_tracker.is_library_failed(library_key):
libraries_to_process.append(library)
else:
filtered_libraries = libraries
# Normal processing - apply progress tracking rules
libraries_to_process = []
for library in libraries:
library_key = library["name"]
if not progress_tracker.is_library_processed(library_key) or retry_failed_only and progress_tracker.is_library_failed(library_key):
libraries_to_process.append(library)
# If test mode is enabled, just process one library
if test_mode:
if filtered_libraries:
test_library = filtered_libraries[0]
if libraries_to_process:
test_library = libraries_to_process[0]
library_key, success = process_single_library(test_library, output_dir, exa_client)
if success:
progress_tracker.mark_library_completed(library_key)
@@ -615,40 +597,11 @@ def process_rules_json(json_path: str, output_dir: str, test_mode: bool = False,
logger.error("No libraries found to process in test mode")
return
# Prepare list of libraries to process
libraries_to_process = []
# If retry_failed_only is True, only process libraries that have failed before
# and any new libraries that have been added
if retry_failed_only:
failed_libraries = progress_tracker.get_failed_libraries()
new_libraries = progress_tracker.identify_new_libraries(all_library_names)
target_libraries = set(failed_libraries).union(set(new_libraries))
if failed_libraries:
logger.info(f"Retrying {len(failed_libraries)} failed libraries")
if new_libraries:
logger.info(f"Processing {len(new_libraries)} new libraries")
for library in filtered_libraries:
library_key = library["name"]
if library_key in target_libraries:
libraries_to_process.append(library)
else:
# Normal processing - skip completed libraries
for library in filtered_libraries:
library_key = library["name"]
# Skip if already processed
if progress_tracker.is_library_processed(library_key):
logger.info(f"Skipping already processed library: {library['name']}")
continue
# Add to processing list
libraries_to_process.append(library)
if not libraries_to_process:
logger.info("No libraries to process. All libraries may have been completed already.")
if specific_library:
logger.error(f"Library '{specific_library}' was not found or could not be processed")
else:
logger.info("No libraries to process. All libraries may have been completed already.")
return
# Process libraries in parallel