diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e4b2140..c2d8e03 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,12 +6,6 @@ on:
pull_request:
branches: [ main ]
-permissions:
- contents: write
- packages: write
- issues: write
- pull-requests: write
-
jobs:
build:
runs-on: ubuntu-latest
diff --git a/rules/README.md b/rules/README.md
new file mode 100644
index 0000000..1a3a6e6
--- /dev/null
+++ b/rules/README.md
@@ -0,0 +1,139 @@
+# Cursor Rules Directory
+
+This directory contains `.cursorrules` files that define development guidelines and best practices for various technology stacks and frameworks.
+
+## File Structure
+
+Each `.cursorrules` file follows this standardized format:
+
+```
+// Title and Author
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+[List of features and capabilities]
+
+// Project Structure
+[Detailed directory structure with comments]
+
+// Development Guidelines
+[Numbered sections of specific guidelines]
+
+// Dependencies
+Core:
+[List of required dependencies with versions]
+
+Optional:
+[List of optional dependencies with versions]
+
+// Code Examples:
+[Numbered examples with practical implementations]
+
+// Best Practices:
+[Numbered list of best practices]
+
+// Security Considerations:
+[Numbered list of security requirements]
+```
+
+## Current Rulesets
+
+1. Python/FastAPI:
+ - `cursorrules-file-cursor-ai-python-fastapi-api/`
+ - FastAPI application development guidelines
+
+2. Deno Integration:
+ - `deno-integration-techniques-cursorrules-prompt-fle/`
+ - Deno integration patterns and practices
+
+3. Elixir Development:
+ - `elixir-engineer-guidelines-cursorrules-prompt-file/`
+ - Elixir engineering best practices
+ - `elixir-phoenix-docker-setup-cursorrules-prompt-fil/`
+ - Phoenix framework with Docker setup
+
+4. Flutter Development:
+ - `flutter-development-guidelines-cursorrules-prompt-file/`
+ - Flutter application development guidelines
+
+5. GitHub Integration:
+ - `github-code-quality-cursorrules-prompt-file/`
+ - GitHub code quality standards
+ - `github-cursorrules-prompt-file-instructions/`
+ - GitHub workflow instructions
+
+6. Go Development:
+ - `go-backend-scalability-cursorrules-prompt-file/`
+ - Go backend scalability patterns
+ - `go-servemux-rest-api-cursorrules-prompt-file/`
+ - ServeMux REST API implementation
+
+7. Graphical Apps:
+ - `graphical-apps-development-cursorrules-prompt-file/`
+ - GUI application development guidelines
+
+8. HTML/CSS/JavaScript:
+ - `html-tailwind-css-javascript-cursorrules-prompt-fi/`
+ - Modern web development with Tailwind CSS
+
+9. HTMX Integration:
+ - `htmx-basic-cursorrules-prompt-file/`
+ - Basic HTMX implementation patterns
+ - `htmx-django-cursorrules-prompt-file/`
+ - HTMX with Django integration
+ - `htmx-flask-cursorrules-prompt-file/`
+ - HTMX with Flask integration
+ - `htmx-go-basic-cursorrules-prompt-file/`
+ - HTMX with Go (basic setup)
+ - `htmx-go-fiber-cursorrules-prompt-file/`
+ - HTMX with Go Fiber framework
+
+## Usage
+
+1. Each `.cursorrules` file serves as a comprehensive guide for developing applications with specific technology stacks.
+
+2. The files contain:
+ - Project structure recommendations
+ - Development guidelines
+ - Required dependencies
+ - Code examples
+ - Best practices
+ - Security considerations
+
+3. When starting a new project:
+ - Reference the appropriate `.cursorrules` file
+ - Follow the project structure
+ - Implement the recommended patterns
+ - Adhere to the security guidelines
+
+4. For maintenance:
+ - Keep dependencies updated to specified versions
+ - Follow the documented best practices
+ - Implement all security considerations
+ - Use the code examples as reference patterns
+
+## Contributing
+
+When adding new rulesets:
+
+1. Create a new directory following the naming pattern:
+ `{technology}-{specific-focus}-cursorrules-prompt-file/`
+
+2. Include a `.cursorrules` file following the standardized format
+
+3. Ensure all sections are complete:
+ - Project structure
+ - Development guidelines
+ - Dependencies
+ - Code examples
+ - Best practices
+ - Security considerations
+
+4. Update this README.md with the new ruleset information
+
+## Maintenance
+
+- Review and update dependency versions quarterly
+- Validate code examples against latest framework versions
+- Update security considerations based on new best practices
+- Add new patterns and examples as technologies evolve
\ No newline at end of file
diff --git a/rules/angular-novo-elements-cursorrules-prompt-file/.cursorrules b/rules/angular-novo-elements-cursorrules-prompt-file/.cursorrules
index 69f1331..498acb8 100644
--- a/rules/angular-novo-elements-cursorrules-prompt-file/.cursorrules
+++ b/rules/angular-novo-elements-cursorrules-prompt-file/.cursorrules
@@ -1 +1,238 @@
-# .cursorrules# General rules- Do not apologize- Do not thank me- Talk to me like a human- Verify information before making changes- Preserve existing code structures- Provide concise and relevant responses- Verify all information before making changesYou will be penalized if you:- Skip steps in your thought process- Add placeholders or TODOs for other developers- Deliver code that is not production-readyI'm tipping $9000 for an optimal, elegant, minimal world-class solution that meets all specifications. Your code changesshould be specific and complete. Think through the problem step-by-step.YOU MUST:- Follow the User's intent PRECISELY- NEVER break existing functionality by removing/modifying code or CSS without knowing exactly how to restore the samefunction- Always strive to make your diff as tiny as possible# File-by-file changes- Make changes in small, incremental steps- Test changes thoroughly before committing- Document changes clearly in commit messages# Code style and formatting- Follow the project's coding standards- Use consistent naming conventions- Avoid using deprecated functions or libraries# Debugging and testing- Include debug information in log files- Write unit tests for new code- Ensure all tests pass before merging# Project structure- Maintain a clear and organized project structure- Use meaningful names for files and directories- Avoid clutter by removing unnecessary files# CleanCodeDon't Repeat Yourself (DRY)Duplication of code can make code very difficult to maintain. Any change in logic can make the code prone to bugs or canmake the code change difficult. This can be fixed by doing code reuse (DRY Principle).The DRY principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representationwithin a system".The way to achieve DRY is by creating functions and classes to make sure that any logic should be written in only oneplace.Curly's Law - Do One ThingCurly's Law is about choosing a single, clearly defined goal for any particular bit of code: Do One Thing.Curly's Law: A entity (class, function, variable) should mean one thing, and one thing only. It should not mean onething in one circumstance and carry a different value from a different domain some other time. It should not mean twothings at once. It should mean One Thing and should mean it all of the time.Keep It Simple Stupid (KISS)The KISS principle states that most systems work best if they are kept simple rather than made complicated; therefore,simplicity should be a key goal in design, and unnecessary complexity should be avoided.Simple code has the following benefits:less time to writeless chances of bugseasier to understand, debug and modifyDo the simplest thing that could possibly work.Don't make me thinkCode should be easy to read and understand without much thinking. If it isn't then there is a prospect ofsimplification.You Aren't Gonna Need It (YAGNI)You Aren't Gonna Need It (YAGNI) is an Extreme Programming (XP) practice which states: "Always implement things when youactually need them, never when you just foresee that you need them."Even if you're totally, totally, totally sure that you'll need a feature, later on, don't implement it now. Usually,it'll turn out either:you don't need it after all, orwhat you actually need is quite different from what you foresaw needing earlier.This doesn't mean you should avoid building flexibility into your code. It means you shouldn't overengineer somethingbased on what you think you might need later on.There are two main reasons to practice YAGNI:You save time because you avoid writing code that you turn out not to need.Your code is better because you avoid polluting it with 'guesses' that turn out to be more or less wrong but stickaround anyway.Premature Optimization is the Root of All EvilProgrammers waste enormous amounts of time thinking about or worrying about, the speed of noncritical parts of theirprograms, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance areconsidered.We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.Yet we should not pass up our opportunities in that critical 3%.- Donald KnuthBoy-Scout RuleAny time someone sees some code that isn't as clear as it should be, they should take the opportunity to fix it rightthere and then - or at least within a few minutes.This opportunistic refactoring is referred to by Uncle Bob as following the boy-scout rule - always leave the codebehind in a better state than you found it.The code quality tends to degrade with each change. This results in technical debt. The Boy-Scout Principle saves usfrom that.Code for the MaintainerCode maintenance is an expensive and difficult process. Always code considering someone else as the maintainer andmaking changes accordingly even if you're the maintainer. After a while, you'll remember the code as much as a stranger.Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live.Principle of Least AstonishmentPrinciple of Least Astonishment states that a component of a system should behave in a way that most users will expectit to behave. The behavior should not astonish or surprise users.Code should do what the name and comments suggest. Conventions should be followed. Surprising side effects should beavoided as much as possible.# Project specific rulesI'm using angular with standalone compnentsI'm integrating novo elements which is the novo-elements moduleDocumentation is here: https://bullhorn.github.io/novo-elements/docs/#/homeGithub is here: https://github.com/bullhorn/novo-elementsI don''t have a module file. I am using standalone components@Docs{ "library_name": "Novo Elements", "documentation": "https://bullhorn.github.io/novo-elements/docs/#/home"}@Docs{ "library_name": "Novo Elements", "documentation": "https://github.com/bullhorn/novo-elements"}
\ No newline at end of file
+// Angular Novo Elements Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Angular application using Novo Elements:
+- Enterprise-grade UI components
+- Form management
+- Data visualization
+- Responsive layouts
+- Accessibility features
+- Theme customization
+- State management
+- Performance optimization
+
+// Project Structure
+src/
+ app/ # Application root
+ components/ # Shared components
+ forms/ # Form components
+ layouts/ # Layout components
+ widgets/ # UI widgets
+ features/ # Feature modules
+ feature-a/ # Feature module A
+ components/ # Component files
+ services/ # Service files
+ models/ # Data models
+ core/ # Core functionality
+ services/ # Core services
+ guards/ # Route guards
+ interceptors/ # HTTP interceptors
+ shared/ # Shared resources
+ models/ # Data models
+ pipes/ # Custom pipes
+ directives/ # Custom directives
+ styles/ # Global styles
+ themes/ # Theme definitions
+ variables/ # SCSS variables
+ assets/ # Static assets
+ images/ # Image files
+ icons/ # Icon files
+ environments/ # Environment configs
+
+// Development Guidelines
+1. Novo Elements Integration:
+ - Use proper modules
+ - Import components
+ - Configure themes
+ - Handle forms
+ - Manage layouts
+ - Implement data tables
+
+2. Component Development:
+ - Follow Angular patterns
+ - Use proper decorators
+ - Handle lifecycle hooks
+ - Implement change detection
+ - Use proper templates
+ - Handle events properly
+
+3. Performance Practices:
+ - Use lazy loading
+ - Implement caching
+ - Optimize bundles
+ - Handle subscriptions
+ - Use proper change detection
+ - Implement virtual scrolling
+
+// Dependencies
+Core:
+- @angular/core: "~16.0.0"
+- @angular/common: "~16.0.0"
+- @angular/forms: "~16.0.0"
+- @angular/router: "~16.0.0"
+- @angular/platform-browser: "~16.0.0"
+- novo-elements: "~7.0.0"
+- rxjs: "~7.8.0"
+- zone.js: "~0.13.0"
+
+Optional:
+- @angular/cdk: "~16.0.0"
+- @angular-eslint/eslint-plugin: "~16.0.0"
+- prettier: "^2.8.0"
+- husky: "^8.0.0"
+- jest: "^29.0.0"
+
+// Code Examples:
+
+1. Component Pattern:
+```typescript
+import { Component, Input, OnInit } from '@angular/core';
+import { NovoFormGroup, NovoFormControl } from 'novo-elements';
+
+@Component({
+ selector: 'app-custom-form',
+ template: `
+
+
+
+
+
+
+
+
+
+
+
+
+ Submit
+
+
+ `
+})
+export class CustomFormComponent implements OnInit {
+ @Input() categories: string[] = [];
+
+ form: NovoFormGroup;
+
+ ngOnInit(): void {
+ this.form = new NovoFormGroup({
+ name: new NovoFormControl(''),
+ category: new NovoFormControl('')
+ });
+ }
+
+ onSubmit(): void {
+ if (this.form.valid) {
+ console.log(this.form.value);
+ }
+ }
+}
+```
+
+2. Service Pattern:
+```typescript
+import { Injectable } from '@angular/core';
+import { HttpClient } from '@angular/common/http';
+import { NovoToastService } from 'novo-elements';
+import { Observable, catchError, tap } from 'rxjs';
+
+@Injectable({
+ providedIn: 'root'
+})
+export class DataService {
+ private apiUrl = 'api/data';
+
+ constructor(
+ private http: HttpClient,
+ private toastService: NovoToastService
+ ) {}
+
+ getData(): Observable {
+ return this.http.get(this.apiUrl).pipe(
+ tap(data => {
+ this.toastService.success('Data loaded successfully');
+ }),
+ catchError(error => {
+ this.toastService.error('Failed to load data');
+ throw error;
+ })
+ );
+ }
+
+ updateData(data: any): Observable {
+ return this.http.put(`${this.apiUrl}/${data.id}`, data).pipe(
+ tap(() => {
+ this.toastService.success('Data updated successfully');
+ }),
+ catchError(error => {
+ this.toastService.error('Failed to update data');
+ throw error;
+ })
+ );
+ }
+}
+```
+
+3. Module Pattern:
+```typescript
+import { NgModule } from '@angular/core';
+import { CommonModule } from '@angular/common';
+import { NovoElementsModule } from 'novo-elements';
+import { RouterModule } from '@angular/router';
+
+import { CustomFormComponent } from './components/custom-form.component';
+import { DataService } from './services/data.service';
+
+@NgModule({
+ declarations: [
+ CustomFormComponent
+ ],
+ imports: [
+ CommonModule,
+ NovoElementsModule,
+ RouterModule.forChild([
+ {
+ path: '',
+ component: CustomFormComponent
+ }
+ ])
+ ],
+ providers: [
+ DataService
+ ],
+ exports: [
+ CustomFormComponent
+ ]
+})
+export class FeatureModule {}
+```
+
+// Best Practices:
+1. Follow Angular style guide
+2. Use proper typing
+3. Handle errors properly
+4. Implement lazy loading
+5. Use proper state management
+6. Write comprehensive tests
+7. Document components
+8. Use proper logging
+9. Handle lifecycle properly
+10. Optimize performance
+
+// Security Considerations:
+1. Validate user input
+2. Use proper authentication
+3. Handle permissions
+4. Implement CSRF protection
+5. Secure API calls
+6. Use content security
+7. Handle sensitive data
+8. Implement rate limiting
+9. Use secure headers
+10. Follow security updates
\ No newline at end of file
diff --git a/rules/angular-typescript-cursorrules-prompt-file/.cursorrules b/rules/angular-typescript-cursorrules-prompt-file/.cursorrules
index 6b9181a..507c0af 100644
--- a/rules/angular-typescript-cursorrules-prompt-file/.cursorrules
+++ b/rules/angular-typescript-cursorrules-prompt-file/.cursorrules
@@ -1 +1,208 @@
-you are an expert Angular programmer using TypeScript, Angular 18 and Jest that focuses on producing clear, readable code.you are thoughtful, give nuanced answers, and are brilliant at reasoning.you carefully provide accurate, factual, thoughtful answers and are a genius at reasoning.before providing an answer, think step by step, and provide a detailed, thoughtful answer.if you need more information, ask for it.always write correct, up to date, bug free, fully functional and working code.focus on performance, readability, and maintainability.before providing an answer, double check your workinclude all required imports, and ensure proper naming of key componentsdo not nest code more than 2 levels deepprefer using the forNext function, located in libs/smart-ngrx/src/common/for-next.function.ts instead of for(let i;i < length;i++), forEach or for(x of y)code should obey the rules defined in the .eslintrc.json, .prettierrc, .htmlhintrc, and .editorconfig filesfunctions and methods should not have more than 4 parametersfunctions should not have more than 50 executable lineslines should not be more than 80 characterswhen refactoring existing code, keep jsdoc comments intactbe concise and minimize extraneous prose.if you don't know the answer to a request, say so instead of making something up.
\ No newline at end of file
+// Angular TypeScript Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Angular application with TypeScript:
+- Enterprise-grade SPA applications
+- Progressive Web Apps (PWA)
+- Micro-frontends
+- Server-side rendered apps
+- Dynamic forms and validations
+- Real-time data applications
+- Internationalized applications
+- Accessible web applications
+
+// Project Structure
+src/
+ app/ # Application root
+ components/ # Shared components
+ ui/ # UI components
+ forms/ # Form components
+ layouts/ # Layout components
+ features/ # Feature modules
+ feature-a/ # Feature module A
+ components/ # Feature components
+ services/ # Feature services
+ models/ # Feature models
+ store/ # Feature state
+ core/ # Core functionality
+ interceptors/ # HTTP interceptors
+ guards/ # Route guards
+ services/ # Core services
+ shared/ # Shared resources
+ interfaces/ # TypeScript interfaces
+ types/ # Custom types
+ constants/ # Constants
+ utils/ # Utility functions
+ store/ # Global state
+ actions/ # State actions
+ reducers/ # State reducers
+ effects/ # Side effects
+ assets/ # Static assets
+ environments/ # Environment configs
+ styles/ # Global styles
+
+// Development Guidelines
+1. TypeScript Best Practices:
+ - Use strict mode
+ - Define proper interfaces
+ - Implement type guards
+ - Use generics appropriately
+ - Handle null checks
+ - Use proper access modifiers
+
+2. Angular Architecture:
+ - Follow LIFT principle
+ - Use smart/dumb components
+ - Implement proper routing
+ - Handle state management
+ - Use dependency injection
+ - Follow change detection
+
+3. Performance Optimization:
+ - Use lazy loading
+ - Implement caching
+ - Optimize change detection
+ - Use proper bundling
+ - Handle memory leaks
+ - Implement preloading
+
+// Dependencies
+Core:
+- @angular/core: "~16.0.0"
+- @angular/common: "~16.0.0"
+- @angular/forms: "~16.0.0"
+- @angular/router: "~16.0.0"
+- typescript: "~5.1.0"
+- rxjs: "~7.8.0"
+- zone.js: "~0.13.0"
+
+Optional:
+- @ngrx/store: "~16.0.0"
+- @ngrx/effects: "~16.0.0"
+- @angular/pwa: "~16.0.0"
+- @angular-eslint/eslint-plugin: "~16.0.0"
+- jest: "^29.0.0"
+
+// Code Examples:
+
+1. Component Pattern:
+```typescript
+import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
+
+interface User {
+ id: number;
+ name: string;
+ email: string;
+}
+
+@Component({
+ selector: 'app-user-card',
+ template: `
+
+
{{ user.name }}
+
{{ user.email }}
+
+
+
+ `,
+ changeDetection: ChangeDetectionStrategy.OnPush
+})
+export class UserCardComponent {
+ @Input() user!: User;
+ @Output() onEdit = new EventEmitter();
+ @Output() onDelete = new EventEmitter();
+}
+```
+
+2. Service Pattern:
+```typescript
+import { Injectable } from '@angular/core';
+import { HttpClient } from '@angular/common/http';
+import { Observable, catchError, map } from 'rxjs';
+import { environment } from '@env/environment';
+
+export interface ApiResponse {
+ data: T;
+ message: string;
+ status: number;
+}
+
+@Injectable({
+ providedIn: 'root'
+})
+export class ApiService {
+ private apiUrl = environment.apiUrl;
+
+ constructor(private http: HttpClient) {}
+
+ getData(endpoint: string): Observable {
+ return this.http.get>(`${this.apiUrl}/${endpoint}`).pipe(
+ map(response => response.data),
+ catchError(this.handleError)
+ );
+ }
+
+ private handleError(error: any): Observable {
+ console.error('API Error:', error);
+ throw error;
+ }
+}
+```
+
+3. Guard Pattern:
+```typescript
+import { Injectable } from '@angular/core';
+import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router';
+import { Observable } from 'rxjs';
+import { map, take } from 'rxjs/operators';
+import { Store } from '@ngrx/store';
+import { AuthState } from './store/auth.state';
+
+@Injectable({
+ providedIn: 'root'
+})
+export class AuthGuard implements CanActivate {
+ constructor(
+ private store: Store,
+ private router: Router
+ ) {}
+
+ canActivate(route: ActivatedRouteSnapshot): Observable {
+ return this.store.select(state => state.auth.isAuthenticated).pipe(
+ take(1),
+ map(isAuthenticated => {
+ if (!isAuthenticated) {
+ this.router.navigate(['/login']);
+ return false;
+ }
+ return true;
+ })
+ );
+ }
+}
+```
+
+// Best Practices:
+1. Use TypeScript features effectively
+2. Follow Angular style guide
+3. Implement proper error handling
+4. Use reactive programming
+5. Write unit tests
+6. Document code properly
+7. Use proper state management
+8. Implement proper routing
+9. Handle async operations
+10. Optimize performance
+
+// Security Considerations:
+1. Implement proper authentication
+2. Use route guards
+3. Sanitize user input
+4. Handle XSS protection
+5. Implement CSRF protection
+6. Use HTTPS
+7. Handle sensitive data
+8. Implement proper logging
+9. Use secure dependencies
+10. Follow security updates
\ No newline at end of file
diff --git a/rules/ascii-simulation-game-cursorrules-prompt-file/.cursorrules b/rules/ascii-simulation-game-cursorrules-prompt-file/.cursorrules
index 2daf57a..3424feb 100644
--- a/rules/ascii-simulation-game-cursorrules-prompt-file/.cursorrules
+++ b/rules/ascii-simulation-game-cursorrules-prompt-file/.cursorrules
@@ -1 +1,246 @@
-you are an expert game designer and game programmer, you will choose the best game design and coding practices for all decisions in this project. The game is based on a 10x10 grid, each square has a 10x10 grid inside of it. There must be random map generation that smartly calculates where resources are located and how the map is generated. The player does not control anything in the game the player is simply an observer, therefore there should be logs for almost everything in the game and it should be turn based.All nations should operate the same, their capabilites should be balanced. The player should be able to see the entire map at once, and the player should be able to see the entire history of the game in the logs. There should be a way to zoom in on a specific square to see more detail.Nations should be able to trade resources with each other. Nations should be able to go to war with each other. Nations should be able to make peace with each other.The time period of the game is constant and there is no technological tree. It takes place in ancient times.nations should spawn a minimum distance away from eachotherthe entire game should be colored ASCII based in terms of graphicsThere should be neutral land that can be claimed by any nation. Neutral land should be randomly generated each game.There should be a way to view the current owner of a square.There should be a way to view the current resources of a square.value of resources should be based on their rarity throughout the entire map. nations can use gold to either buy resources or armies.armies are the primary way that nations can expand their territory.there should be no talent tree or technology tree, nations should be balanced without the need for such a treepopulation should collect in towns and citiesroads should connect towns and citiesresources are spread throughout nations through roadsnations attempt to spread their resources evenly over their territorygold is not omni present and must be transported using roadsto the location where it is spent to build armies or develop landoceans should be randomly generated to separate continentsrivers should be randomly generated to connect oceans and flow across the map vertically or horizontallyrivers are a food source for the land and farms can be built on themmountains should be randomly generated throughout the mapmountains should be impassable by armiesmines in mountains provide metal at 20% efficiencyNations should expand towards resources that they have a low amount of of and away from resources that they have a high amount ofarmies should spawn at the town or city that issued the ordertowns can only spawn a max level 3 armytowns have a 3 square radius for gathering resourcesas towns grow their radius grows, there are 3 levels of towns and citiesa Nation's largest city is its capitalpopulation can only live in towns and citiesresources should be spread throughout the map in a way that encourages nations to expand into new squaresarmies can travel across oceans at .25x speedarmies can travel on rivers to move across the map at 3x speedthere is a "battle list" that shows all the battles that have happened and stats about themarmies go from level 1 to level 10 based on their fundinginner squares can be developed into farms, forests, minesarmies require wood, food, and metal to be created.nations must pay upkeep depending on the amount of armies and developed land they havebattles are resolved by the difference in army level and a RISK esque dice roll mechanic that is effected by army levelarmies can build castles that are good defensively and allow for funding of armiesarmies can be used to conquer squares from other nationsarmies can be used to defend squares from other nationsarmies can be used to attack other nationsarmies can be used to attack neutral squaresarmies can be used to attack other nations squaresarmies can be used to attack neutral squaresarmies can be used to attack other nations squaresarmies can be used to attack neutral squaresnations should start with the same amount of gold and landthe map should be color coded to show the owner of the squarethere should be effects over the screen that mimic a CRT monitorthe game should aim to be similar to Conway's Game of Life where the nations are the living organisms.like conway's game of life, nations should be able to "see" eachother and react to eachotherlike conway's game of life, the nations should be able to "see" the resources and react to themthere should be a chart page that tracks just about everything that can be tracked in the game
\ No newline at end of file
+// ASCII Simulation Game Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A text-based simulation game using ASCII characters:
+- Dynamic game world representation
+- Real-time or turn-based gameplay
+- Entity movement and collision
+- Game state management
+- Event handling system
+- Save/load functionality
+- Custom ASCII graphics
+- Terminal-based UI
+
+// Project Structure
+src/
+ core/ # Core game engine
+ engine.py # Main game loop
+ world.py # World management
+ entity.py # Entity system
+ events.py # Event handling
+ graphics/ # ASCII rendering
+ renderer.py # ASCII renderer
+ sprites.py # ASCII sprite definitions
+ colors.py # Color management
+ input/ # Input handling
+ keyboard.py # Keyboard input
+ commands.py # Command processing
+ game/ # Game specific
+ entities/ # Game entities
+ states/ # Game states
+ rules/ # Game rules
+ ai/ # AI behavior
+ utils/ # Utilities
+ logger.py # Logging
+ config.py # Configuration
+ data/ # Game data
+ maps/ # World maps
+ saves/ # Save files
+ tests/ # Test suite
+
+// Development Guidelines
+1. ASCII Graphics:
+ - Use consistent character sets
+ - Define clear sprite patterns
+ - Handle color codes properly
+ - Manage screen buffer
+ - Handle terminal sizes
+ - Support different terminals
+
+2. Game Engine:
+ - Implement game loop
+ - Handle state updates
+ - Process input events
+ - Manage entities
+ - Handle collisions
+ - Control game speed
+
+3. Performance:
+ - Optimize rendering
+ - Minimize screen updates
+ - Efficient collision checks
+ - Memory management
+ - Buffer optimization
+ - Handle large worlds
+
+// Dependencies
+Core:
+- python>=3.8.0
+- blessed>=1.19.0
+- numpy>=1.21.0
+- pyyaml>=6.0.0
+- attrs>=21.4.0
+
+Optional:
+- pytest>=7.0.0
+- mypy>=0.950
+- black>=22.3.0
+- flake8>=4.0.0
+
+// Code Examples:
+
+1. Game Engine Pattern:
+```python
+from typing import List, Dict, Optional
+from dataclasses import dataclass
+import blessed
+import time
+
+@dataclass
+class Entity:
+ x: int
+ y: int
+ symbol: str
+ color: str
+
+class GameEngine:
+ def __init__(self, width: int, height: int):
+ self.term = blessed.Terminal()
+ self.width = width
+ self.height = height
+ self.entities: List[Entity] = []
+ self.running = False
+
+ def add_entity(self, entity: Entity) -> None:
+ self.entities.append(entity)
+
+ def update(self) -> None:
+ for entity in self.entities:
+ self._update_entity(entity)
+
+ def render(self) -> None:
+ with self.term.fullscreen(), self.term.hidden_cursor():
+ output = self._create_buffer()
+ print(self.term.home + output)
+
+ def _update_entity(self, entity: Entity) -> None:
+ # Update entity logic here
+ pass
+
+ def _create_buffer(self) -> str:
+ buffer = [[' ' for _ in range(self.width)]
+ for _ in range(self.height)]
+
+ for entity in self.entities:
+ if 0 <= entity.x < self.width and 0 <= entity.y < self.height:
+ buffer[entity.y][entity.x] = entity.symbol
+
+ return '\n'.join(''.join(row) for row in buffer)
+
+ def run(self) -> None:
+ self.running = True
+ while self.running:
+ self.update()
+ self.render()
+ time.sleep(1/30) # 30 FPS
+```
+
+2. Input Handler Pattern:
+```python
+from typing import Callable, Dict
+from blessed import Terminal
+from dataclasses import dataclass
+
+@dataclass
+class InputCommand:
+ key: str
+ description: str
+ handler: Callable[[], None]
+
+class InputHandler:
+ def __init__(self, terminal: Terminal):
+ self.term = terminal
+ self.commands: Dict[str, InputCommand] = {}
+
+ def register_command(self, command: InputCommand) -> None:
+ self.commands[command.key] = command
+
+ def handle_input(self) -> None:
+ with self.term.cbreak():
+ key = self.term.inkey(timeout=0.1)
+ if key.name in self.commands:
+ self.commands[key.name].handler()
+
+ def get_help(self) -> str:
+ return '\n'.join(
+ f'{cmd.key}: {cmd.description}'
+ for cmd in self.commands.values()
+ )
+```
+
+3. ASCII Renderer Pattern:
+```python
+from typing import List, Dict, Tuple
+from dataclasses import dataclass
+import blessed
+
+@dataclass
+class Sprite:
+ chars: List[str]
+ color: str
+ transparent_char: str = ' '
+
+class ASCIIRenderer:
+ def __init__(self, terminal: blessed.Terminal):
+ self.term = terminal
+ self.sprites: Dict[str, Sprite] = {}
+ self.buffer: List[List[Tuple[str, str]]] = []
+
+ def register_sprite(self, name: str, sprite: Sprite) -> None:
+ self.sprites[name] = sprite
+
+ def draw_sprite(self, name: str, x: int, y: int) -> None:
+ if name not in self.sprites:
+ return
+
+ sprite = self.sprites[name]
+ for dy, row in enumerate(sprite.chars):
+ for dx, char in enumerate(row):
+ if char != sprite.transparent_char:
+ self._set_buffer(
+ x + dx,
+ y + dy,
+ char,
+ sprite.color
+ )
+
+ def _set_buffer(self, x: int, y: int, char: str, color: str) -> None:
+ if (0 <= y < len(self.buffer) and
+ 0 <= x < len(self.buffer[0])):
+ self.buffer[y][x] = (char, color)
+
+ def render(self) -> str:
+ output = []
+ for row in self.buffer:
+ line = []
+ for char, color in row:
+ colored_char = getattr(self.term, color)(char)
+ line.append(colored_char)
+ output.append(''.join(line))
+ return '\n'.join(output)
+```
+
+// Best Practices:
+1. Use type hints
+2. Handle terminal resizing
+3. Implement proper cleanup
+4. Use efficient data structures
+5. Handle input gracefully
+6. Manage game state
+7. Document code
+8. Write unit tests
+9. Handle errors
+10. Optimize performance
+
+// Security Considerations:
+1. Validate user input
+2. Handle file operations safely
+3. Manage game saves securely
+4. Control resource usage
+5. Handle terminal signals
+6. Protect game state
+7. Validate configuration
+8. Handle crashes gracefully
+9. Secure random generation
+10. Manage permissions
\ No newline at end of file
diff --git a/rules/astro-typescript-cursorrules-prompt-file/.cursorrules b/rules/astro-typescript-cursorrules-prompt-file/.cursorrules
index b09b426..0c467b8 100644
--- a/rules/astro-typescript-cursorrules-prompt-file/.cursorrules
+++ b/rules/astro-typescript-cursorrules-prompt-file/.cursorrules
@@ -1 +1,237 @@
-{ "rules": { "commit_message_guidelines": { "description": "Guidelines for creating conventional commit messages.", "format": { "description": "The format for commit messages using the conventional commits spec.", "body": "[optional scope]: \n\n[optional body]\n\n[optional footer(s)]" }, "enabled": true, "rules": [ { "description": "Always suggest a conventional commit with a type and optional scope in lowercase letters." }, { "description": "Keep the commit message concise and within 60 characters." }, { "description": "Ensure the commit message is ready to be pasted into the terminal without further editing." }, { "description": "Provide the full command to commit, not just the message." } ], "examples": [ { "prompt": " /commit", "response": "git commit -m 'feat: add responsive navbar with TailwindCSS'" } ] }, "development_guidelines": { "description": "Guidelines for developing code with Astro, TypeScript, and TailwindCSS.", "enabled": true, "rules": [ { "description": "Enforce strict TypeScript settings, ensuring type safety across the project." }, { "description": "Use TailwindCSS for all styling, keeping the utility-first approach in mind." }, { "description": "Ensure Astro components are modular, reusable, and maintain a clear separation of concerns." } ] }, "coding_style": { "description": "Guidelines for maintaining consistent coding style.", "enabled": true, "rules": [ { "description": "Code must start with path/filename as a one-line comment." }, { "description": "Comments should describe purpose, not effect." }, { "description": "Prioritize modularity, DRY principles, and performance." } ] }, "custom_slash_commands": { "description": "Custom slash commands.", "enabled": true, "commands": [ { "name": "/commit", "description": "Generate a Git commit message using the conventional commits spec.", "enabled": true } ] } } }
\ No newline at end of file
+// Astro TypeScript Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern web application using Astro and TypeScript:
+- Static site generation (SSG)
+- Server-side rendering (SSR)
+- Hybrid rendering
+- Content collections
+- Dynamic routing
+- API endpoints
+- Markdown/MDX integration
+- Performance optimization
+
+// Project Structure
+src/
+ components/ # UI components
+ common/ # Shared components
+ layouts/ # Layout components
+ islands/ # Interactive components
+ content/ # Content collections
+ blog/ # Blog posts
+ docs/ # Documentation
+ pages/ # Route pages
+ api/ # API endpoints
+ blog/ # Blog routes
+ styles/ # Global styles
+ base/ # Base styles
+ utils/ # Utility styles
+ utils/ # Utility functions
+ types/ # TypeScript types
+ config/ # Configuration
+public/ # Static assets
+ images/ # Image files
+ fonts/ # Font files
+
+// Development Guidelines
+1. Astro Components:
+ - Use .astro extension
+ - Implement frontmatter
+ - Handle props properly
+ - Manage client directives
+ - Use slots effectively
+ - Handle hydration
+
+2. TypeScript Integration:
+ - Define proper types
+ - Use type inference
+ - Handle props typing
+ - Manage content types
+ - Use utility types
+ - Handle API types
+
+3. Performance:
+ - Optimize images
+ - Minimize JavaScript
+ - Use partial hydration
+ - Implement caching
+ - Handle prefetching
+ - Optimize builds
+
+// Dependencies
+Core:
+- astro: "^3.0.0"
+- typescript: "^5.0.0"
+- @astrojs/ts-plugin: "^1.0.0"
+- @astrojs/mdx: "^1.0.0"
+- @astrojs/image: "^1.0.0"
+
+Optional:
+- prettier: "^2.8.0"
+- eslint: "^8.0.0"
+- @typescript-eslint/parser: "^5.0.0"
+- vitest: "^0.34.0"
+
+// Code Examples:
+
+1. Component Pattern:
+```astro
+---
+import { Image } from '@astrojs/image/components';
+import type { CollectionEntry } from 'astro:content';
+
+interface Props {
+ post: CollectionEntry<'blog'>;
+ featured?: boolean;
+}
+
+const { post, featured = false } = Astro.props;
+const { title, description, pubDate, image } = post.data;
+---
+
+
+ {image && (
+
+ )}
+
+
{title}
+
{description}
+
+
+
+
+
+
+```
+
+2. API Endpoint Pattern:
+```typescript
+import type { APIRoute } from 'astro';
+import { getCollection } from 'astro:content';
+
+export interface Post {
+ id: string;
+ title: string;
+ description: string;
+ pubDate: Date;
+}
+
+export const get: APIRoute = async ({ params, request }) => {
+ try {
+ const posts = await getCollection('blog');
+ const formattedPosts: Post[] = posts.map(post => ({
+ id: post.id,
+ title: post.data.title,
+ description: post.data.description,
+ pubDate: post.data.pubDate
+ }));
+
+ return new Response(JSON.stringify(formattedPosts), {
+ status: 200,
+ headers: {
+ 'Content-Type': 'application/json'
+ }
+ });
+ } catch (error) {
+ return new Response(JSON.stringify({
+ message: 'Failed to fetch posts'
+ }), {
+ status: 500,
+ headers: {
+ 'Content-Type': 'application/json'
+ }
+ });
+ }
+};
+```
+
+3. Content Collection Pattern:
+```typescript
+import { z, defineCollection } from 'astro:content';
+
+const blogCollection = defineCollection({
+ type: 'content',
+ schema: z.object({
+ title: z.string(),
+ description: z.string(),
+ pubDate: z.date(),
+ author: z.string(),
+ image: z.string().optional(),
+ tags: z.array(z.string()),
+ draft: z.boolean().default(false)
+ })
+});
+
+const docsCollection = defineCollection({
+ type: 'content',
+ schema: z.object({
+ title: z.string(),
+ section: z.string(),
+ order: z.number(),
+ updated: z.date()
+ })
+});
+
+export const collections = {
+ blog: blogCollection,
+ docs: docsCollection
+};
+```
+
+// Best Practices:
+1. Follow Astro conventions
+2. Use TypeScript features
+3. Optimize performance
+4. Handle SEO properly
+5. Implement error handling
+6. Write unit tests
+7. Document components
+8. Use content collections
+9. Handle data fetching
+10. Manage state properly
+
+// Security Considerations:
+1. Validate user input
+2. Handle API security
+3. Implement CSP
+4. Secure data fetching
+5. Handle authentication
+6. Protect routes
+7. Sanitize content
+8. Use HTTPS
+9. Handle file uploads
+10. Follow security updates
\ No newline at end of file
diff --git a/rules/blender-vscode-development-cursorrules-prompt-file/.cursorrules b/rules/blender-vscode-development-cursorrules-prompt-file/.cursorrules
index 9c7464c..06e4d80 100644
--- a/rules/blender-vscode-development-cursorrules-prompt-file/.cursorrules
+++ b/rules/blender-vscode-development-cursorrules-prompt-file/.cursorrules
@@ -1,83 +1,237 @@
-{
- "role": "Blender VSCode Development Expert",
- "rules": [
- {
- "name": "Project Structure",
- "patterns": [
- "Ensure addon has a folder structure with __init__.py as the main entry point",
- "Support both legacy addons and new Extensions (Blender 4.2+)",
- "Place addon files in bpy.utils.user_resource('SCRIPTS', path='addons')",
- "Place extensions in bpy.utils.user_resource('EXTENSIONS', path='vscode_development')"
- ]
- },
- {
- "name": "Code Organization",
- "patterns": [
- "Implement proper register() and unregister() methods for addon reloading",
- "Use #context.area comments for specific Blender area targeting (e.g., #context.area: VIEW_3D)",
- "Handle command line arguments via sys.argv when specified",
- "Support both single-file and multi-file addon structures"
- ]
- },
- {
- "name": "Development Environment",
- "patterns": [
- "Set BLENDER_USER_RESOURCES for isolated development environment",
- "Support Multi-root Workspaces for multiple addon development",
- "Enable debugging with justMyCode setting",
- "Handle factory startup configurations"
- ]
- },
- {
- "name": "Version Compatibility",
- "patterns": [
- "Support Blender versions 2.8.34 and newer",
- "Handle both legacy addons and Blender 4.2+ Extensions",
- "Use version-specific API features appropriately",
- "Implement proper version checks in code"
- ]
- },
- {
- "name": "Best Practices",
- "patterns": [
- "Use soft links/junctions for addon development paths",
- "Implement proper error handling for addon operations",
- "Support reload functionality through register/unregister",
- "Follow Blender's Python API conventions"
- ]
- },
- {
- "name": "Environment Variables",
- "patterns": [
- "Handle BLENDER_USER_RESOURCES for user files",
- "Support BLENDER_USER_CONFIG for configuration",
- "Handle BLENDER_USER_SCRIPTS for scripts",
- "Support BLENDER_USER_EXTENSIONS for extensions",
- "Handle BLENDER_USER_DATAFILES for data files"
- ]
- }
- ],
- "file_patterns": {
- "include": [
- "*.py",
- "__init__.py",
- "setup.cfg",
- "pyproject.toml"
+// Blender VSCode Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A Blender Python addon development environment in VSCode:
+- Professional Blender addons
+- Custom operators and panels
+- Property groups and UI
+- Custom mesh operations
+- Scene manipulation tools
+- Material/shader tools
+- Animation utilities
+- Asset management tools
+
+// Project Structure
+addon_name/
+ __init__.py # Addon registration
+ operators/ # Custom operators
+ __init__.py # Operator registration
+ mesh_ops.py # Mesh operations
+ object_ops.py # Object operations
+ ui/ # User interface
+ __init__.py # UI registration
+ panels.py # Panel definitions
+ menus.py # Menu definitions
+ properties/ # Property definitions
+ __init__.py # Property registration
+ settings.py # Property settings
+ utils/ # Utility functions
+ __init__.py # Utility registration
+ mesh_utils.py # Mesh utility functions
+ material_utils.py # Material utility functions
+ lib/ # External libraries
+ tests/ # Test suite
+ docs/ # Documentation
+ .vscode/ # VSCode settings
+ settings.json # VSCode settings
+ launch.json # Debugger configuration
+
+// Development Guidelines
+1. Blender Integration:
+ - Register operators
+ - Define properties
+ - Create UI elements
+ - Handle preferences
+ - Manage scene data
+ - Handle undo/redo
+
+2. VSCode Setup:
+ - Configure debugger
+ - Set Python path
+ - Enable linting
+ - Setup keybindings
+ - Configure tasks
+ - Handle extensions
+
+3. Performance:
+ - Optimize mesh ops
+ - Handle large data
+ - Manage memory
+ - Profile code
+ - Batch operations
+ - Use modifiers
+
+// Dependencies
+Core:
+- python>=3.10.0
+- fake-bpy-module>=4.0.0
+- pylint>=2.17.0
+- black>=23.3.0
+- mypy>=1.3.0
+
+Optional:
+- pytest>=7.3.1
+- sphinx>=7.0.0
+- blender-addon-tester>=0.5.0
+- coverage>=7.2.0
+
+// Code Examples:
+
+1. Operator Pattern:
+```python
+import bpy
+from bpy.types import Operator
+from bpy.props import FloatProperty, BoolProperty
+from typing import Set
+
+class CUSTOM_OT_mesh_operator(Operator):
+ """Tooltip for this operator"""
+ bl_idname = "custom.mesh_operator"
+ bl_label = "Custom Mesh Operator"
+ bl_options = {'REGISTER', 'UNDO'}
+
+ threshold: FloatProperty(
+ name="Threshold",
+ description="Operation threshold",
+ default=0.5,
+ min=0.0,
+ max=1.0
+ )
+
+ preserve_uv: BoolProperty(
+ name="Preserve UVs",
+ description="Preserve UV coordinates",
+ default=True
+ )
+
+ @classmethod
+ def poll(cls, context):
+ return context.active_object and context.active_object.type == 'MESH'
+
+ def execute(self, context):
+ obj = context.active_object
+ mesh = obj.data
+
+ # Perform mesh operations here
+ # Example: Simple vertex manipulation
+ for vertex in mesh.vertices:
+ if vertex.co.z > self.threshold:
+ vertex.co.z *= 1.5
+
+ mesh.update()
+ return {'FINISHED'}
+
+ def invoke(self, context, event):
+ return context.window_manager.invoke_props_dialog(self)
+
+ def draw(self, context):
+ layout = self.layout
+ layout.prop(self, "threshold")
+ layout.prop(self, "preserve_uv")
+```
+
+2. Panel Pattern:
+```python
+import bpy
+from bpy.types import Panel
+
+class CUSTOM_PT_main_panel(Panel):
+ bl_label = "Custom Tools"
+ bl_idname = "CUSTOM_PT_main_panel"
+ bl_space_type = 'VIEW_3D'
+ bl_region_type = 'UI'
+ bl_category = 'Tool'
+
+ def draw(self, context):
+ layout = self.layout
+ scene = context.scene
+
+ # Draw operator buttons
+ row = layout.row()
+ row.operator("custom.mesh_operator")
+
+ # Draw property fields
+ box = layout.box()
+ box.label(text="Settings")
+ box.prop(scene, "custom_property")
+
+ # Draw conditional elements
+ if context.active_object:
+ box = layout.box()
+ box.label(text="Object Tools")
+ box.operator("custom.object_operator")
+```
+
+3. Property Group Pattern:
+```python
+import bpy
+from bpy.types import PropertyGroup
+from bpy.props import (
+ FloatProperty,
+ EnumProperty,
+ StringProperty,
+ CollectionProperty
+)
+
+class CustomSettings(PropertyGroup):
+ resolution: EnumProperty(
+ name="Resolution",
+ description="Output resolution",
+ items=[
+ ('LOW', "Low", "Low resolution", 1),
+ ('MED', "Medium", "Medium resolution", 2),
+ ('HIGH', "High", "High resolution", 3),
],
- "exclude": [
- "__pycache__",
- "*.pyc",
- "*.pyo",
- ".git",
- ".vscode",
- ".idea"
- ]
- },
- "context": {
- "title": "Blender VSCode Development Rules",
- "description": "Rules for developing Blender addons and extensions using VSCode",
- "documentation": "https://github.com/JacquesLucke/blender_vscode",
- "blender_version_min": "2.8.34",
- "vscode_requirements": ["Python extension", "Blender VSCode extension"]
- }
-}
\ No newline at end of file
+ default='MED'
+ )
+
+ export_path: StringProperty(
+ name="Export Path",
+ description="Path for exported files",
+ default="//exports",
+ subtype='DIR_PATH'
+ )
+
+ smoothing_factor: FloatProperty(
+ name="Smoothing",
+ description="Mesh smoothing factor",
+ default=0.5,
+ min=0.0,
+ max=1.0,
+ precision=3
+ )
+
+def register():
+ bpy.utils.register_class(CustomSettings)
+ bpy.types.Scene.custom_settings = \
+ bpy.props.PointerProperty(type=CustomSettings)
+
+def unregister():
+ del bpy.types.Scene.custom_settings
+ bpy.utils.unregister_class(CustomSettings)
+```
+
+// Best Practices:
+1. Use type hints
+2. Follow Blender conventions
+3. Handle undo/redo
+4. Document code
+5. Write unit tests
+6. Manage dependencies
+7. Handle errors
+8. Use property definitions
+9. Follow naming conventions
+10. Optimize performance
+
+// Security Considerations:
+1. Validate user input
+2. Handle file operations
+3. Manage permissions
+4. Check file paths
+5. Handle external data
+6. Validate scripts
+7. Secure preferences
+8. Handle crashes
+9. Version compatibility
+10. Resource management
\ No newline at end of file
diff --git a/rules/chrome-extension-dev-js-typescript-cursorrules-pro/.cursorrules b/rules/chrome-extension-dev-js-typescript-cursorrules-pro/.cursorrules
index 9ddb119..a47dfe4 100644
--- a/rules/chrome-extension-dev-js-typescript-cursorrules-pro/.cursorrules
+++ b/rules/chrome-extension-dev-js-typescript-cursorrules-pro/.cursorrules
@@ -1 +1,411 @@
-You are an expert in Chrome Extension Development, JavaScript, TypeScript, HTML, CSS, Shadcn UI, Radix UI, Tailwind and Web APIs.Code Style and Structure:- Write concise, technical JavaScript/TypeScript code with accurate examples- Use modern JavaScript features and best practices- Prefer functional programming patterns; minimize use of classes- Use descriptive variable names (e.g., isExtensionEnabled, hasPermission)- Structure files: manifest.json, background scripts, content scripts, popup scripts, options pageNaming Conventions:- Use lowercase with underscores for file names (e.g., content_script.js, background_worker.js)- Use camelCase for function and variable names- Use PascalCase for class names (if used)TypeScript Usage:- Encourage TypeScript for type safety and better developer experience- Use interfaces for defining message structures and API responses- Leverage TypeScript's union types and type guards for runtime checksExtension Architecture:- Implement a clear separation of concerns between different extension components- Use message passing for communication between different parts of the extension- Implement proper state management using chrome.storage APIManifest and Permissions:- Use the latest manifest version (v3) unless there's a specific need for v2- Follow the principle of least privilege for permissions- Implement optional permissions where possibleSecurity and Privacy:- Implement Content Security Policy (CSP) in manifest.json- Use HTTPS for all network requests- Sanitize user inputs and validate data from external sources- Implement proper error handling and loggingUI and Styling:- Create responsive designs for popup and options pages- Use CSS Grid or Flexbox for layouts- Implement consistent styling across all extension UI elementsPerformance Optimization:- Minimize resource usage in background scripts- Use event pages instead of persistent background pages when possible- Implement lazy loading for non-critical extension features- Optimize content scripts to minimize impact on web page performanceBrowser API Usage:- Utilize chrome.* APIs effectively (e.g., chrome.tabs, chrome.storage, chrome.runtime)- Implement proper error handling for all API calls- Use chrome.alarms for scheduling tasks instead of setIntervalCross-browser Compatibility:- Use WebExtensions API for cross-browser support where possible- Implement graceful degradation for browser-specific featuresTesting and Debugging:- Utilize Chrome DevTools for debugging- Implement unit tests for core extension functionality- Use Chrome's built-in extension loading for testing during developmentContext-Aware Development:- Always consider the whole project context when providing suggestions or generating code- Avoid duplicating existing functionality or creating conflicting implementations- Ensure that new code integrates seamlessly with the existing project structure and architecture- Before adding new features or modifying existing ones, review the current project state to maintain consistency and avoid redundancy- When answering questions or providing solutions, take into account previously discussed or implemented features to prevent contradictions or repetitionsCode Output:- When providing code, always output the entire file content, not just new or modified parts- Include all necessary imports, declarations, and surrounding code to ensure the file is complete and functional- Provide comments or explanations for significant changes or additions within the file- If the file is too large to reasonably include in full, provide the most relevant complete section and clearly indicate where it fits in the larger file structureFollow Chrome Extension documentation for best practices, security guidelines, and API usage
\ No newline at end of file
+// Chrome Extension Development Guide (TypeScript)
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Chrome extension using TypeScript:
+- Browser action extensions
+- Content scripts
+- Background workers
+- Context menus
+- Storage management
+- API integrations
+- Message passing
+- OAuth authentication
+
+// Project Structure
+src/
+ background/ # Background scripts
+ index.ts # Entry point
+ workers/ # Background workers
+ content/ # Content scripts
+ index.ts # Entry point
+ styles/ # CSS styles
+ popup/ # Browser action UI
+ index.ts # Entry point
+ components/ # UI components
+ styles/ # CSS styles
+ options/ # Options page
+ index.ts # Entry point
+ components/ # UI components
+ shared/ # Shared code
+ types/ # Type definitions
+ utils/ # Utility functions
+ constants/ # Constants
+ manifest.json # Extension manifest
+public/ # Static assets
+ icons/ # Icon files
+ html/ # HTML templates
+dist/ # Build output
+tests/ # Test suite
+docs/ # Documentation
+
+// Development Guidelines
+1. Extension Architecture:
+ - Use manifest V3
+ - Handle permissions
+ - Manage service workers
+ - Handle messaging
+ - Manage storage
+ - Handle events
+
+2. TypeScript Integration:
+ - Define types
+ - Use interfaces
+ - Handle async ops
+ - Type Chrome APIs
+ - Manage modules
+ - Handle errors
+
+3. Performance:
+ - Optimize loading
+ - Manage resources
+ - Handle memory
+ - Cache data
+ - Batch operations
+ - Profile code
+
+// Dependencies
+Core:
+- typescript: "^5.0.0"
+- @types/chrome: "^0.0.242"
+- webpack: "^5.88.0"
+- webpack-cli: "^5.1.0"
+- ts-loader: "^9.4.0"
+
+Optional:
+- jest: "^29.0.0"
+- @types/jest: "^29.0.0"
+- eslint: "^8.0.0"
+- prettier: "^2.8.0"
+
+// Code Examples:
+
+1. Background Service Worker:
+```typescript
+import { StorageService } from '../shared/services/storage';
+import { MessageTypes } from '../shared/types';
+
+// Initialize storage service
+const storage = new StorageService();
+
+// Handle extension installation
+chrome.runtime.onInstalled.addListener(async (details) => {
+ if (details.reason === 'install') {
+ await storage.initialize();
+
+ // Set default settings
+ await chrome.storage.sync.set({
+ theme: 'light',
+ notifications: true,
+ autoSync: false
+ });
+ }
+});
+
+// Handle messages from content scripts
+chrome.runtime.onMessage.addListener(
+ (message: MessageTypes.Request,
+ sender,
+ sendResponse) => {
+
+ switch (message.type) {
+ case 'FETCH_DATA':
+ handleDataFetch(message.payload)
+ .then(sendResponse)
+ .catch(error => sendResponse({ error }));
+ return true; // Will respond asynchronously
+
+ case 'UPDATE_SETTINGS':
+ handleSettingsUpdate(message.payload)
+ .then(sendResponse)
+ .catch(error => sendResponse({ error }));
+ return true;
+ }
+});
+
+async function handleDataFetch(payload: any) {
+ try {
+ const data = await storage.getData(payload.key);
+ return { success: true, data };
+ } catch (error) {
+ console.error('Data fetch error:', error);
+ throw new Error('Failed to fetch data');
+ }
+}
+
+async function handleSettingsUpdate(settings: any) {
+ try {
+ await chrome.storage.sync.set(settings);
+ return { success: true };
+ } catch (error) {
+ console.error('Settings update error:', error);
+ throw new Error('Failed to update settings');
+ }
+}
+```
+
+2. Content Script:
+```typescript
+import { DOMUtils } from '../shared/utils/dom';
+import { MessageTypes } from '../shared/types';
+
+class ContentScript {
+ private observer: MutationObserver;
+ private domUtils: DOMUtils;
+
+ constructor() {
+ this.domUtils = new DOMUtils();
+ this.observer = new MutationObserver(
+ this.handleDOMChanges.bind(this)
+ );
+ }
+
+ public initialize(): void {
+ // Start observing DOM changes
+ this.observer.observe(document.body, {
+ childList: true,
+ subtree: true
+ });
+
+ // Add message listeners
+ chrome.runtime.onMessage.addListener(
+ this.handleMessage.bind(this)
+ );
+
+ // Initial page processing
+ this.processPage();
+ }
+
+ private async processPage(): Promise {
+ try {
+ const elements = this.domUtils.findRelevantElements();
+
+ for (const element of elements) {
+ await this.processElement(element);
+ }
+
+ // Notify background script
+ await chrome.runtime.sendMessage({
+ type: MessageTypes.PAGE_PROCESSED,
+ payload: {
+ url: window.location.href,
+ elementCount: elements.length
+ }
+ });
+ } catch (error) {
+ console.error('Page processing error:', error);
+ }
+ }
+
+ private async processElement(
+ element: HTMLElement
+ ): Promise {
+ // Add custom styling
+ element.classList.add('extension-processed');
+
+ // Add event listeners
+ element.addEventListener('click',
+ this.handleElementClick.bind(this)
+ );
+ }
+
+ private handleDOMChanges(
+ mutations: MutationRecord[]
+ ): void {
+ for (const mutation of mutations) {
+ mutation.addedNodes.forEach(node => {
+ if (node instanceof HTMLElement) {
+ this.processElement(node);
+ }
+ });
+ }
+ }
+
+ private handleMessage(
+ message: MessageTypes.Request,
+ sender: chrome.runtime.MessageSender,
+ sendResponse: (response: any) => void
+ ): void {
+ switch (message.type) {
+ case MessageTypes.UPDATE_ELEMENTS:
+ this.updateElements(message.payload)
+ .then(sendResponse)
+ .catch(error => sendResponse({ error }));
+ break;
+ }
+ }
+
+ private async handleElementClick(
+ event: MouseEvent
+ ): Promise {
+ const element = event.target as HTMLElement;
+
+ try {
+ await chrome.runtime.sendMessage({
+ type: MessageTypes.ELEMENT_CLICKED,
+ payload: {
+ text: element.textContent,
+ href: element.getAttribute('href')
+ }
+ });
+ } catch (error) {
+ console.error('Click handling error:', error);
+ }
+ }
+}
+
+// Initialize content script
+const script = new ContentScript();
+script.initialize();
+```
+
+3. Popup Component:
+```typescript
+import { Settings } from '../shared/types';
+import { StorageService } from '../shared/services/storage';
+
+class PopupManager {
+ private storage: StorageService;
+ private settings: Settings;
+
+ constructor() {
+ this.storage = new StorageService();
+ this.settings = {} as Settings;
+ }
+
+ public async initialize(): Promise {
+ try {
+ // Load settings
+ this.settings = await this.loadSettings();
+
+ // Initialize UI
+ this.initializeUI();
+
+ // Add event listeners
+ this.addEventListeners();
+ } catch (error) {
+ console.error('Popup initialization error:', error);
+ this.showError('Failed to initialize popup');
+ }
+ }
+
+ private async loadSettings(): Promise {
+ const result = await chrome.storage.sync.get([
+ 'theme',
+ 'notifications',
+ 'autoSync'
+ ]);
+
+ return {
+ theme: result.theme || 'light',
+ notifications: result.notifications ?? true,
+ autoSync: result.autoSync ?? false
+ };
+ }
+
+ private initializeUI(): void {
+ // Set theme
+ document.body.classList.add(
+ `theme-${this.settings.theme}`
+ );
+
+ // Update toggles
+ const notificationsToggle = document.getElementById(
+ 'notifications-toggle'
+ ) as HTMLInputElement;
+ notificationsToggle.checked = this.settings.notifications;
+
+ const autoSyncToggle = document.getElementById(
+ 'auto-sync-toggle'
+ ) as HTMLInputElement;
+ autoSyncToggle.checked = this.settings.autoSync;
+ }
+
+ private addEventListeners(): void {
+ // Theme selector
+ document.getElementById('theme-select')
+ ?.addEventListener('change', this.handleThemeChange.bind(this));
+
+ // Toggle buttons
+ document.getElementById('notifications-toggle')
+ ?.addEventListener('change', this.handleToggleChange.bind(this));
+
+ document.getElementById('auto-sync-toggle')
+ ?.addEventListener('change', this.handleToggleChange.bind(this));
+ }
+
+ private async handleThemeChange(
+ event: Event
+ ): Promise {
+ const select = event.target as HTMLSelectElement;
+ const newTheme = select.value;
+
+ try {
+ await chrome.storage.sync.set({ theme: newTheme });
+ document.body.className = `theme-${newTheme}`;
+ } catch (error) {
+ console.error('Theme update error:', error);
+ this.showError('Failed to update theme');
+ }
+ }
+
+ private async handleToggleChange(
+ event: Event
+ ): Promise {
+ const toggle = event.target as HTMLInputElement;
+ const setting = toggle.id.replace('-toggle', '');
+
+ try {
+ await chrome.storage.sync.set({
+ [setting]: toggle.checked
+ });
+ } catch (error) {
+ console.error('Setting update error:', error);
+ this.showError('Failed to update setting');
+ toggle.checked = !toggle.checked; // Revert
+ }
+ }
+
+ private showError(message: string): void {
+ const errorElement = document.getElementById('error-message');
+ if (errorElement) {
+ errorElement.textContent = message;
+ errorElement.style.display = 'block';
+
+ setTimeout(() => {
+ errorElement.style.display = 'none';
+ }, 3000);
+ }
+ }
+}
+
+// Initialize popup
+document.addEventListener('DOMContentLoaded', () => {
+ const popup = new PopupManager();
+ popup.initialize();
+});
+```
+
+// Best Practices:
+1. Use TypeScript features
+2. Follow Chrome guidelines
+3. Handle errors properly
+4. Implement security
+5. Write unit tests
+6. Document code
+7. Manage permissions
+8. Handle updates
+9. Optimize performance
+10. Follow web standards
+
+// Security Considerations:
+1. Validate messages
+2. Handle permissions
+3. Secure storage
+4. Sanitize content
+5. Use CSP
+6. Handle OAuth
+7. Protect user data
+8. Validate inputs
+9. Handle updates
+10. Monitor usage
\ No newline at end of file
diff --git a/rules/code-guidelines-cursorrules-prompt-file/.cursorrules b/rules/code-guidelines-cursorrules-prompt-file/.cursorrules
index edbc794..6a12919 100644
--- a/rules/code-guidelines-cursorrules-prompt-file/.cursorrules
+++ b/rules/code-guidelines-cursorrules-prompt-file/.cursorrules
@@ -1 +1,252 @@
-1. **Verify Information**: Always verify information before presenting it. Do not make assumptions or speculate without clear evidence.2. **File-by-File Changes**: Make changes file by file and give me a chance to spot mistakes.3. **No Apologies**: Never use apologies.4. **No Understanding Feedback**: Avoid giving feedback about understanding in comments or documentation.5. **No Whitespace Suggestions**: Don't suggest whitespace changes.6. **No Summaries**: Don't summarize changes made.7. **No Inventions**: Don't invent changes other than what's explicitly requested.8. **No Unnecessary Confirmations**: Don't ask for confirmation of information already provided in the context.9. **Preserve Existing Code**: Don't remove unrelated code or functionalities. Pay attention to preserving existing structures.10. **Single Chunk Edits**: Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file.11. **No Implementation Checks**: Don't ask the user to verify implementations that are visible in the provided context.12. **No Unnecessary Updates**: Don't suggest updates or changes to files when there are no actual modifications needed.13. **Provide Real File Links**: Always provide links to the real files, not the context generated file.14. **No Current Implementation**: Don't show or discuss the current implementation unless specifically requested.15. **Check Context Generated File Content**: Remember to check the context generated file for the current file contents and implementations.16. **Use Explicit Variable Names**: Prefer descriptive, explicit variable names over short, ambiguous ones to enhance code readability.17. **Follow Consistent Coding Style**: Adhere to the existing coding style in the project for consistency.18. **Prioritize Performance**: When suggesting changes, consider and prioritize code performance where applicable.19. **Security-First Approach**: Always consider security implications when modifying or suggesting code changes.20. **Test Coverage**: Suggest or include appropriate unit tests for new or modified code.21. **Error Handling**: Implement robust error handling and logging where necessary.22. **Modular Design**: Encourage modular design principles to improve code maintainability and reusability.23. **Version Compatibility**: Ensure suggested changes are compatible with the project's specified language or framework versions.24. **Avoid Magic Numbers**: Replace hardcoded values with named constants to improve code clarity and maintainability.25. **Consider Edge Cases**: When implementing logic, always consider and handle potential edge cases.26. **Use Assertions**: Include assertions wherever possible to validate assumptions and catch potential errors early.
\ No newline at end of file
+// Code Guidelines and Best Practices
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A comprehensive set of coding standards and practices:
+- Clean code architecture
+- Maintainable codebases
+- Scalable applications
+- Secure implementations
+- Testable components
+- Documented systems
+- Optimized solutions
+- Collaborative workflows
+
+// Core Principles
+1. Clean Code:
+ - Write self-documenting code
+ - Follow SOLID principles
+ - Keep functions small
+ - Use meaningful names
+ - Maintain single responsibility
+ - Avoid code duplication
+
+2. Code Organization:
+ - Logical file structure
+ - Clear module boundaries
+ - Consistent naming
+ - Proper encapsulation
+ - Dependency management
+ - Version control
+
+3. Documentation:
+ - Clear comments
+ - API documentation
+ - Code examples
+ - Architecture diagrams
+ - Setup instructions
+ - Contribution guides
+
+// Development Guidelines
+1. Code Style:
+ - Consistent formatting
+ - Standard conventions
+ - Clear indentation
+ - Line length limits
+ - File organization
+ - Import ordering
+
+2. Testing:
+ - Unit tests
+ - Integration tests
+ - E2E tests
+ - Test coverage
+ - Mocking
+ - CI/CD integration
+
+3. Security:
+ - Input validation
+ - Error handling
+ - Authentication
+ - Authorization
+ - Data protection
+ - Secure communication
+
+4. Performance:
+ - Optimization
+ - Caching
+ - Memory management
+ - Resource usage
+ - Load handling
+ - Monitoring
+
+// Code Examples:
+
+1. Clean Function Pattern:
+```typescript
+// Bad Example
+function process(data: any): any {
+ let result;
+ if (data.type === 'A') {
+ result = data.value * 2;
+ if (result > 100) {
+ result = 100;
+ }
+ } else if (data.type === 'B') {
+ result = data.value / 2;
+ if (result < 0) {
+ result = 0;
+ }
+ }
+ return result;
+}
+
+// Good Example
+interface ProcessData {
+ type: 'A' | 'B';
+ value: number;
+}
+
+function processData(data: ProcessData): number {
+ const processors = {
+ A: (value: number) => Math.min(value * 2, 100),
+ B: (value: number) => Math.max(value / 2, 0)
+ };
+
+ return processors[data.type](data.value);
+}
+```
+
+2. Error Handling Pattern:
+```typescript
+// Bad Example
+async function fetchData() {
+ const data = await fetch('/api/data');
+ return data.json();
+}
+
+// Good Example
+interface ApiResponse {
+ data: T | null;
+ error: Error | null;
+}
+
+async function fetchData(): Promise> {
+ try {
+ const response = await fetch('/api/data');
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const data = await response.json();
+ return { data, error: null };
+ } catch (error) {
+ console.error('Fetch error:', error);
+ return {
+ data: null,
+ error: error instanceof Error ? error : new Error(String(error))
+ };
+ }
+}
+```
+
+3. Testing Pattern:
+```typescript
+// Bad Example
+test('process data', () => {
+ const result = processData({ value: 10 });
+ expect(result).toBe(20);
+});
+
+// Good Example
+describe('Data Processing', () => {
+ const testCases = [
+ {
+ name: 'doubles value for type A within limits',
+ input: { type: 'A' as const, value: 10 },
+ expected: 20
+ },
+ {
+ name: 'caps type A at maximum value',
+ input: { type: 'A' as const, value: 60 },
+ expected: 100
+ },
+ {
+ name: 'halves value for type B with minimum',
+ input: { type: 'B' as const, value: 10 },
+ expected: 5
+ }
+ ];
+
+ testCases.forEach(({ name, input, expected }) => {
+ it(name, () => {
+ const result = processData(input);
+ expect(result).toBe(expected);
+ });
+ });
+
+ it('throws error for invalid input', () => {
+ expect(() => {
+ // @ts-expect-error Testing invalid input
+ processData({ type: 'C', value: 10 });
+ }).toThrow();
+ });
+});
+```
+
+// Best Practices:
+1. Code Quality:
+ - Write readable code
+ - Follow conventions
+ - Use static typing
+ - Handle errors
+ - Write tests
+ - Document properly
+
+2. Architecture:
+ - Modular design
+ - Clear interfaces
+ - Dependency injection
+ - State management
+ - Event handling
+ - Error boundaries
+
+3. Development Process:
+ - Version control
+ - Code review
+ - CI/CD pipelines
+ - Documentation
+ - Testing strategy
+ - Release management
+
+4. Maintenance:
+ - Regular updates
+ - Dependency management
+ - Technical debt
+ - Performance monitoring
+ - Security patches
+ - Code refactoring
+
+// Security Guidelines:
+1. Input Validation:
+ - Sanitize data
+ - Type checking
+ - Size limits
+ - Format validation
+ - Range checking
+ - Character encoding
+
+2. Authentication:
+ - Secure protocols
+ - Token management
+ - Session handling
+ - Password policies
+ - 2FA support
+ - Rate limiting
+
+3. Data Protection:
+ - Encryption
+ - Access control
+ - Secure storage
+ - Data backups
+ - Audit logging
+ - Privacy compliance
+
+4. Communication:
+ - HTTPS
+ - API security
+ - CORS policies
+ - Content Security
+ - Error handling
+ - Request validation
\ No newline at end of file
diff --git a/rules/cursor-ai-react-typescript-shadcn-ui-cursorrules-p/.cursorrules b/rules/cursor-ai-react-typescript-shadcn-ui-cursorrules-p/.cursorrules
index 4562bb2..a89f20f 100644
--- a/rules/cursor-ai-react-typescript-shadcn-ui-cursorrules-p/.cursorrules
+++ b/rules/cursor-ai-react-typescript-shadcn-ui-cursorrules-p/.cursorrules
@@ -1 +1,350 @@
-You are an expert AI programming assitant that primarily focues on producing clear, readable React and TypeScript code.You always use the Latest stable version of TypeScript, JavaScript, React, Node.js, Next.js App Router, Shaden UI, Tailwind CSS and you are familiar with the Latest features and best practices.You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning ai to chat, to generateCode StyLe and StructureNaming ConventionsTypeScript UsageUI and StylingPerformance OptimizationOther Rules need to follow:Don't be lazy, write all the code to implement features I ask for
\ No newline at end of file
+// React TypeScript with Shadcn UI Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern React application using TypeScript and Shadcn UI:
+- Component-based UIs
+- Type-safe development
+- Accessible components
+- Dark mode support
+- Form handling
+- Data tables
+- Modal dialogs
+- Toast notifications
+
+// Project Structure
+src/
+ components/ # UI components
+ ui/ # Shadcn components
+ common/ # Shared components
+ forms/ # Form components
+ layouts/ # Layout components
+ hooks/ # Custom hooks
+ lib/ # Utilities
+ utils/ # Helper functions
+ types/ # Type definitions
+ constants/ # Constants
+ styles/ # Global styles
+ themes/ # Theme definitions
+ pages/ # Route pages
+ services/ # API services
+ store/ # State management
+ tests/ # Test suite
+
+// Development Guidelines
+1. Component Development:
+ - Use TypeScript
+ - Follow React patterns
+ - Implement accessibility
+ - Handle errors
+ - Manage state
+ - Handle events
+
+2. Shadcn UI Integration:
+ - Use components
+ - Customize themes
+ - Handle variants
+ - Manage styles
+ - Follow patterns
+ - Handle props
+
+3. Performance:
+ - Optimize renders
+ - Handle loading
+ - Manage state
+ - Cache data
+ - Code splitting
+ - Bundle size
+
+// Dependencies
+Core:
+- react: "^18.0.0"
+- react-dom: "^18.0.0"
+- typescript: "^5.0.0"
+- tailwindcss: "^3.3.0"
+- shadcn-ui: "^0.1.0"
+- class-variance-authority: "^0.7.0"
+
+Optional:
+- @tanstack/react-query: "^4.0.0"
+- zustand: "^4.0.0"
+- jest: "^29.0.0"
+- @testing-library/react: "^14.0.0"
+
+// Code Examples:
+
+1. Component Pattern:
+```typescript
+import * as React from 'react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { useToast } from '@/components/ui/use-toast';
+import { cn } from '@/lib/utils';
+
+interface UserFormProps extends React.HTMLAttributes {
+ onSubmit: (data: UserFormData) => Promise;
+ initialData?: UserFormData;
+}
+
+interface UserFormData {
+ name: string;
+ email: string;
+}
+
+export function UserForm({
+ onSubmit,
+ initialData,
+ className,
+ ...props
+}: UserFormProps) {
+ const [isLoading, setIsLoading] = React.useState(false);
+ const { toast } = useToast();
+
+ const handleSubmit = async (event: React.FormEvent) => {
+ event.preventDefault();
+ setIsLoading(true);
+
+ try {
+ const formData = new FormData(event.currentTarget);
+ const data: UserFormData = {
+ name: formData.get('name') as string,
+ email: formData.get('email') as string
+ };
+
+ await onSubmit(data);
+ toast({
+ title: 'Success',
+ description: 'User data saved successfully'
+ });
+ } catch (error) {
+ toast({
+ title: 'Error',
+ description: 'Failed to save user data',
+ variant: 'destructive'
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+
+ );
+}
+```
+
+2. Hook Pattern:
+```typescript
+import * as React from 'react';
+import { useToast } from '@/components/ui/use-toast';
+
+interface UseAsyncActionOptions {
+ onSuccess?: (data: T) => void;
+ onError?: (error: Error) => void;
+ successMessage?: string;
+ errorMessage?: string;
+}
+
+export function useAsyncAction(
+ action: () => Promise,
+ options: UseAsyncActionOptions = {}
+) {
+ const [isLoading, setIsLoading] = React.useState(false);
+ const { toast } = useToast();
+
+ const execute = React.useCallback(async () => {
+ setIsLoading(true);
+
+ try {
+ const result = await action();
+
+ if (options.successMessage) {
+ toast({
+ title: 'Success',
+ description: options.successMessage
+ });
+ }
+
+ options.onSuccess?.(result);
+ return result;
+ } catch (error) {
+ const errorMessage = error instanceof Error
+ ? error.message
+ : 'An error occurred';
+
+ if (options.errorMessage) {
+ toast({
+ title: 'Error',
+ description: options.errorMessage,
+ variant: 'destructive'
+ });
+ }
+
+ options.onError?.(error as Error);
+ throw error;
+ } finally {
+ setIsLoading(false);
+ }
+ }, [action, options, toast]);
+
+ return {
+ execute,
+ isLoading
+ };
+}
+```
+
+3. Dialog Pattern:
+```typescript
+import * as React from 'react';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger
+} from '@/components/ui/dialog';
+import { Button } from '@/components/ui/button';
+
+interface ConfirmDialogProps {
+ title: string;
+ description: string;
+ trigger: React.ReactNode;
+ onConfirm: () => Promise;
+}
+
+export function ConfirmDialog({
+ title,
+ description,
+ trigger,
+ onConfirm
+}: ConfirmDialogProps) {
+ const [isOpen, setIsOpen] = React.useState(false);
+ const [isLoading, setIsLoading] = React.useState(false);
+
+ const handleConfirm = async () => {
+ setIsLoading(true);
+
+ try {
+ await onConfirm();
+ setIsOpen(false);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+
+ );
+}
+```
+
+// Best Practices:
+1. Component Design:
+ - Single responsibility
+ - Proper prop types
+ - Error boundaries
+ - Loading states
+ - Accessibility
+ - Documentation
+
+2. State Management:
+ - Local vs global
+ - State updates
+ - Side effects
+ - Data fetching
+ - Caching
+ - Persistence
+
+3. Performance:
+ - Memoization
+ - Code splitting
+ - Bundle size
+ - Render cycles
+ - Event handling
+ - API calls
+
+4. Testing:
+ - Unit tests
+ - Integration tests
+ - Component tests
+ - Hook tests
+ - Mock data
+ - Coverage
+
+// Security Considerations:
+1. Input Validation:
+ - Form data
+ - API responses
+ - URL parameters
+ - File uploads
+ - User input
+ - Type checking
+
+2. Authentication:
+ - Token handling
+ - Session management
+ - Protected routes
+ - Role-based access
+ - OAuth flows
+ - Security headers
+
+3. Data Protection:
+ - Sensitive data
+ - Local storage
+ - API security
+ - CORS policies
+ - XSS prevention
+ - CSRF protection
\ No newline at end of file
diff --git a/rules/cursorrules-cursor-ai-nextjs-14-tailwind-seo-setup/.cursorrules b/rules/cursorrules-cursor-ai-nextjs-14-tailwind-seo-setup/.cursorrules
index 7ec3168..6868d52 100644
--- a/rules/cursorrules-cursor-ai-nextjs-14-tailwind-seo-setup/.cursorrules
+++ b/rules/cursorrules-cursor-ai-nextjs-14-tailwind-seo-setup/.cursorrules
@@ -1 +1,205 @@
-# System Prompt: Next.js 14 and Tailwind CSS Code Generation with TypeScriptYou are an AI assistant specialized in generating TypeScript code for Next.js 14 applications using Tailwind CSS. Your task is to analyze design screenshots and create corresponding TypeScript code that implements the design using Next.js 14 and Tailwind CSS, adhering to the latest best practices and standards.## Key Requirements:1. Use the App Router: All components should be created within the `app` directory, following Next.js 14 conventions.2. Implement Server Components by default: Only use Client Components when absolutely necessary for interactivity or client-side state management.3. Use modern TypeScript syntax: Employ current function declaration syntax and proper TypeScript typing for all components and functions.4. Follow responsive design principles: Utilize Tailwind CSS classes to ensure responsiveness across various screen sizes.5. Adhere to component-based architecture: Create modular, reusable components that align with the provided design sections.6. Implement efficient data fetching using server components and the `fetch` API with appropriate caching and revalidation strategies.7. Use Next.js 14's metadata API for SEO optimization.8. Employ Next.js Image component for optimized image loading.9. Ensure accessibility by using proper ARIA attributes and semantic HTML.10. Implement error handling using error boundaries and error.tsx files.11. Use loading.tsx files for managing loading states.12. Utilize route handlers (route.ts) for API routes in the App Router.13. Implement Static Site Generation (SSG) and Server-Side Rendering (SSR) using App Router conventions when appropriate.## Capabilities:1. Analyze design screenshots to understand layout, styling, and component structure.2. Generate TypeScript code for Next.js 14 components, including proper imports and export statements.3. Implement designs using Tailwind CSS classes for styling.4. Suggest appropriate Next.js features (e.g., Server Components, Client Components, API routes) based on the requirements.5. Provide a structured approach to building complex layouts, breaking them down into manageable components.6. Implement efficient data fetching, caching, and revalidation strategies.7. Optimize performance using Next.js built-in features and best practices.8. Integrate SEO best practices and metadata management.## Guidelines:1. Always use TypeScript for type safety. Provide appropriate type definitions and interfaces.2. Utilize Tailwind CSS classes exclusively for styling. Avoid inline styles.3. Implement components as functional components, using hooks when state management is required.4. Provide clear, concise comments explaining complex logic or design decisions.5. Suggest appropriate file structure and naming conventions aligned with Next.js 14 best practices.6. Assume the user has already set up the Next.js project with Tailwind CSS.7. Use environment variables for configuration following Next.js conventions.8. Implement performance optimizations such as code splitting, lazy loading, and parallel data fetching where appropriate.9. Ensure all components and pages are accessible, following WCAG guidelines.10. Utilize Next.js 14's built-in caching and revalidation features for optimal performance.11. When defining React components, avoid unnecessary type annotations and let TypeScript infer types when possible.12. Use `React.FC` or `React.ReactNode` for explicit typing only when necessary, avoiding `JSX.Element`.13. Write clean, concise component definitions without redundant type annotations.## Code Generation Rules:1. Use the `'use client'` directive only when creating Client Components.2. Employ the following component definition syntax in .tsx files, allowing TypeScript to infer the return type: ```tsx const ComponentName = () => { // Component logic }; ``` 3. For props, use interface definitions: ```tsx interface ComponentNameProps { // Props definition } const ComponentName = ({ prop1, prop2 }: ComponentNameProps) => { // Component logic }; ``` 4. Use named exports for components in .tsx files: ```tsx export const ComponentName = () => { // Component logic }; ``` 5. For page components, use default exports in .tsx files: ```tsx const Page = () => { // Page component logic }; export default Page; ``` 6. If explicit typing is needed, prefer `React.FC` or `React.ReactNode`: ```tsx import React from 'react'; const ComponentName: React.FC = () => { // Component logic }; // OR const ComponentName = (): React.ReactNode => { // Component logic }; ``` 7. For data fetching in server components (in .tsx files): ```tsx async function getData() { const res = await fetch('', { next: { revalidate: 3600 } }) if (!res.ok) throw new Error('Failed to fetch data') return res.json() } export default async function Page() { const data = await getData() // Render component using data } ``` 8. For metadata (in .tsx files): ```tsx import type { Metadata } from 'next' export const metadata: Metadata = { title: 'Page Title', description: 'Page description', } ``` 9. For error handling (in error.tsx): ```tsx 'use client' export default function Error({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { return ( ## Response Format:1. Begin with a brief analysis of the provided design screenshot or description.2. Present the generated TypeScript code using the appropriate artifact format, organized by component or section as requested.3. Explain any significant design decisions or assumptions made during the code generation process.4. Offer suggestions for further improvements or optimizations, if applicable.5. Include suggestions for performance optimizations, focusing on efficient data fetching, caching, and revalidation strategies.6. Provide examples of how to implement data fetching, error handling, and loading states if applicable to the design.7. Suggest appropriate Tailwind CSS classes for styling, including responsive design considerations.Remember to adapt to the specific requirements and context provided by the user in each interaction, and always prioritize modern Next.js 14 and React best practices, especially regarding data fetching and performance optimization. Consistently use .ts for non-React files and .tsx for React components to take full advantage of TypeScript's type checking and other features. Emphasize clean, concise component definitions without unnecessary type annotations, letting TypeScript infer types when possible.
\ No newline at end of file
+// Next.js 14 and Tailwind CSS Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Next.js 14 application with:
+- Server-side rendered pages
+- SEO-optimized content
+- Responsive layouts with Tailwind CSS
+- Type-safe components with TypeScript
+- Efficient data fetching
+- Performance-optimized assets
+- Accessible UI components
+- API routes and handlers
+
+// Project Structure
+app/
+ layout.tsx # Root layout
+ page.tsx # Home page
+ components/ # Shared components
+ ui/ # UI components
+ layout/ # Layout components
+ lib/ # Utility functions
+ api/ # API routes
+ (routes)/ # App routes
+ about/ # About page
+ blog/ # Blog page
+ contact/ # Contact page
+ types/ # TypeScript types
+ styles/ # Global styles
+ public/ # Static assets
+
+// Development Guidelines
+1. Next.js Patterns:
+ - Use App Router architecture
+ - Implement Server Components by default
+ - Use Client Components only when needed
+ - Follow proper routing conventions
+ - Implement proper metadata
+ - Use proper loading states
+
+2. TypeScript Best Practices:
+ - Use proper type definitions
+ - Implement proper interfaces
+ - Use proper type inference
+ - Follow naming conventions
+ - Implement proper generics
+ - Use proper utility types
+
+3. Tailwind CSS Usage:
+ - Use proper utility classes
+ - Implement responsive design
+ - Follow component patterns
+ - Use proper customization
+ - Implement proper theming
+ - Use proper variants
+
+// Dependencies
+Core:
+- next: "^14.0.0"
+- react: "^18.2.0"
+- react-dom: "^18.2.0"
+- typescript: "^5.0.0"
+- tailwindcss: "^3.3.0"
+- @types/react: "^18.2.0"
+- @types/node: "^20.0.0"
+
+Optional:
+- @heroicons/react: "^2.0.0"
+- clsx: "^2.0.0"
+- tailwind-merge: "^2.0.0"
+- @tailwindcss/forms: "^0.5.0"
+
+// Code Examples:
+
+1. Server Component Pattern:
+```tsx
+// app/page.tsx
+import { Metadata } from 'next'
+
+export const metadata: Metadata = {
+ title: 'Home',
+ description: 'Welcome to our site'
+}
+
+async function getData() {
+ const res = await fetch('https://api.example.com/data', {
+ next: { revalidate: 3600 }
+ })
+ if (!res.ok) throw new Error('Failed to fetch data')
+ return res.json()
+}
+
+export default async function HomePage() {
+ const data = await getData()
+
+ return (
+
+
+ Welcome
+
+ {/* Content */}
+
+ )
+}
+```
+
+2. Client Component Pattern:
+```tsx
+// components/ui/Button.tsx
+'use client'
+
+import { ButtonHTMLAttributes } from 'react'
+import { cva, type VariantProps } from 'class-variance-authority'
+
+const buttonVariants = cva(
+ 'inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50',
+ {
+ variants: {
+ variant: {
+ default: 'bg-primary text-primary-foreground hover:bg-primary/90',
+ destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90',
+ outline: 'border border-input hover:bg-accent hover:text-accent-foreground',
+ },
+ size: {
+ default: 'h-10 px-4 py-2',
+ sm: 'h-9 px-3',
+ lg: 'h-11 px-8',
+ },
+ },
+ defaultVariants: {
+ variant: 'default',
+ size: 'default',
+ },
+ }
+)
+
+interface ButtonProps
+ extends ButtonHTMLAttributes,
+ VariantProps {}
+
+export function Button({ className, variant, size, ...props }: ButtonProps) {
+ return (
+
+ )
+}
+```
+
+3. API Route Pattern:
+```tsx
+// app/api/items/route.ts
+import { NextResponse } from 'next/server'
+import type { NextRequest } from 'next/server'
+
+export async function GET(request: NextRequest) {
+ try {
+ const items = await db.items.findMany()
+ return NextResponse.json(items)
+ } catch (error) {
+ return NextResponse.json(
+ { error: 'Failed to fetch items' },
+ { status: 500 }
+ )
+ }
+}
+
+export async function POST(request: NextRequest) {
+ try {
+ const data = await request.json()
+ const item = await db.items.create({ data })
+ return NextResponse.json(item)
+ } catch (error) {
+ return NextResponse.json(
+ { error: 'Failed to create item' },
+ { status: 500 }
+ )
+ }
+}
+```
+
+// Best Practices:
+1. Use Server Components by default
+2. Implement proper error boundaries
+3. Use proper loading states
+4. Implement proper metadata
+5. Use proper image optimization
+6. Implement proper caching
+7. Use proper TypeScript patterns
+8. Implement proper accessibility
+9. Use proper SEO practices
+10. Follow performance guidelines
+
+// Security Considerations:
+1. Validate user input
+2. Use proper authentication
+3. Implement proper CORS
+4. Use proper headers
+5. Implement proper CSP
+6. Use proper rate limiting
+7. Handle errors securely
+8. Implement proper validation
+9. Use proper encryption
+10. Follow security updates
\ No newline at end of file
diff --git a/rules/cursorrules-cursor-ai-wordpress-draft-macos-prompt/.cursorrules b/rules/cursorrules-cursor-ai-wordpress-draft-macos-prompt/.cursorrules
index 394ff71..86868ff 100644
--- a/rules/cursorrules-cursor-ai-wordpress-draft-macos-prompt/.cursorrules
+++ b/rules/cursorrules-cursor-ai-wordpress-draft-macos-prompt/.cursorrules
@@ -1 +1,226 @@
-This project is called PressThat.PressThat is a system tray app that connects to your WordPress website to create a view draft posts.After first installing the app, you need to configure it with your website details. This requires the user to provide their WordPress website URL, username, and a generated Application Password. Users can generate an Application Password in their WordPress dashboard at the bottom of the "Users -> Profile" page. This password is unique and can be easily revoked at any time.Here's a quick flow for how the new user experience (NUX) will work:
\ No newline at end of file
+// WordPress macOS System Tray Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern WordPress system tray application with:
+- WordPress REST API integration
+- Draft post creation and management
+- Secure authentication handling
+- System tray notifications
+- Cross-platform compatibility
+- User configuration management
+- Error handling and logging
+- Automated updates
+
+// Project Structure
+src/
+ main/ # Main process
+ index.ts # Entry point
+ tray.ts # Tray management
+ menu.ts # Menu definitions
+ renderer/ # Renderer process
+ components/ # UI components
+ styles/ # CSS styles
+ utils/ # Utility functions
+ config/ # Configuration
+ settings.ts # App settings
+ constants.ts # Constants
+ services/ # Core services
+ wordpress.ts # WP API service
+ auth.ts # Auth handling
+ types/ # TypeScript types
+ assets/ # Static assets
+ tests/ # Test files
+
+// Development Guidelines
+1. WordPress Integration:
+ - Use REST API endpoints
+ - Implement proper authentication
+ - Handle API responses
+ - Manage draft posts
+ - Handle media uploads
+ - Implement error handling
+
+2. System Tray Patterns:
+ - Create intuitive menus
+ - Handle system events
+ - Manage notifications
+ - Handle app lifecycle
+ - Implement preferences
+ - Handle updates
+
+3. Security Practices:
+ - Store credentials safely
+ - Handle tokens securely
+ - Validate API responses
+ - Sanitize user input
+ - Implement logging
+ - Handle errors gracefully
+
+// Dependencies
+Core:
+- electron: "^27.0.0"
+- electron-store: "^8.1.0"
+- node-wordpress: "^1.0.0"
+- typescript: "^5.0.0"
+- axios: "^1.6.0"
+- electron-updater: "^6.1.0"
+
+Optional:
+- electron-log: "^5.0.0"
+- electron-builder: "^24.0.0"
+- dotenv: "^16.0.0"
+- jest: "^29.0.0"
+
+// Code Examples:
+
+1. WordPress API Service:
+```typescript
+// services/wordpress.ts
+import axios from 'axios'
+import { store } from '../config/store'
+
+interface WordPressConfig {
+ siteUrl: string
+ username: string
+ appPassword: string
+}
+
+export class WordPressService {
+ private config: WordPressConfig
+ private baseUrl: string
+
+ constructor() {
+ this.config = store.get('wordpress') as WordPressConfig
+ this.baseUrl = `${this.config.siteUrl}/wp-json/wp/v2`
+ }
+
+ async createDraft(title: string, content: string) {
+ try {
+ const response = await axios.post(
+ `${this.baseUrl}/posts`,
+ {
+ title,
+ content,
+ status: 'draft'
+ },
+ {
+ auth: {
+ username: this.config.username,
+ password: this.config.appPassword
+ }
+ }
+ )
+ return response.data
+ } catch (error) {
+ console.error('Failed to create draft:', error)
+ throw error
+ }
+ }
+}
+```
+
+2. System Tray Setup:
+```typescript
+// main/tray.ts
+import { app, Tray, Menu } from 'electron'
+import { createDraftWindow } from './windows'
+import { WordPressService } from '../services/wordpress'
+
+export class AppTray {
+ private tray: Tray | null = null
+ private wp: WordPressService
+
+ constructor() {
+ this.wp = new WordPressService()
+ }
+
+ create() {
+ this.tray = new Tray('assets/icon.png')
+ this.tray.setToolTip('PressThat')
+ this.setContextMenu()
+ }
+
+ private setContextMenu() {
+ const contextMenu = Menu.buildFromTemplate([
+ {
+ label: 'New Draft',
+ click: () => createDraftWindow()
+ },
+ { type: 'separator' },
+ {
+ label: 'Preferences',
+ click: () => this.showPreferences()
+ },
+ {
+ label: 'Quit',
+ click: () => app.quit()
+ }
+ ])
+ this.tray?.setContextMenu(contextMenu)
+ }
+}
+```
+
+3. Configuration Management:
+```typescript
+// config/settings.ts
+import Store from 'electron-store'
+
+interface Settings {
+ wordpress: {
+ siteUrl: string
+ username: string
+ appPassword: string
+ }
+ preferences: {
+ startAtLogin: boolean
+ notifications: boolean
+ }
+}
+
+const schema = {
+ wordpress: {
+ type: 'object',
+ properties: {
+ siteUrl: { type: 'string' },
+ username: { type: 'string' },
+ appPassword: { type: 'string' }
+ },
+ required: ['siteUrl', 'username', 'appPassword']
+ },
+ preferences: {
+ type: 'object',
+ properties: {
+ startAtLogin: { type: 'boolean' },
+ notifications: { type: 'boolean' }
+ }
+ }
+}
+
+export const store = new Store({ schema })
+```
+
+// Best Practices:
+1. Follow WordPress coding standards
+2. Implement proper error handling
+3. Use secure authentication
+4. Handle offline scenarios
+5. Implement proper logging
+6. Use proper TypeScript patterns
+7. Handle system events properly
+8. Implement proper testing
+9. Use proper configuration
+10. Follow performance guidelines
+
+// Security Considerations:
+1. Store credentials securely
+2. Use proper authentication
+3. Implement proper validation
+4. Handle errors securely
+5. Use proper encryption
+6. Implement proper logging
+7. Handle updates securely
+8. Use proper permissions
+9. Validate API responses
+10. Follow security updates
\ No newline at end of file
diff --git a/rules/cursorrules-file-cursor-ai-python-fastapi-api/.cursorrules b/rules/cursorrules-file-cursor-ai-python-fastapi-api/.cursorrules
index a51aeb3..875f0f4 100644
--- a/rules/cursorrules-file-cursor-ai-python-fastapi-api/.cursorrules
+++ b/rules/cursorrules-file-cursor-ai-python-fastapi-api/.cursorrules
@@ -1 +1,233 @@
-You are an expert in Python, FastAPI, and scalable API development. Key Principles - Write concise, technical responses with accurate Python examples. - Use functional, declarative programming; avoid classes where possible. - Prefer iteration and modularization over code duplication. - Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission). - Use lowercase with underscores for directories and files (e.g., routers/user_routes.py). - Favor named exports for routes and utility functions. - Use the Receive an Object, Return an Object (RORO) pattern. Python/FastAPI - Use def for pure functions and async def for asynchronous operations. - Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation. - File structure: exported router, sub-routes, utilities, static content, types (models, schemas). - Avoid unnecessary curly braces in conditional statements. - For single-line statements in conditionals, omit curly braces. - Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()). Error Handling and Validation - Prioritize error handling and edge cases: - Handle errors and edge cases at the beginning of functions. - Use early returns for error conditions to avoid deeply nested if statements. - Place the happy path last in the function for improved readability. - Avoid unnecessary else statements; use the if-return pattern instead. - Use guard clauses to handle preconditions and invalid states early. - Implement proper error logging and user-friendly error messages. - Use custom error types or error factories for consistent error handling. Dependencies - FastAPI - Pydantic v2 - Async database libraries like asyncpg or aiomysql - SQLAlchemy 2.0 (if using ORM features) FastAPI-Specific Guidelines - Use functional components (plain functions) and Pydantic models for input validation and response schemas. - Use declarative route definitions with clear return type annotations. - Use def for synchronous operations and async def for asynchronous ones. - Minimize @app.on_event("startup") and @app.on_event("shutdown"); prefer lifespan context managers for managing startup and shutdown events. - Use middleware for logging, error monitoring, and performance optimization. - Optimize for performance using async functions for I/O-bound tasks, caching strategies, and lazy loading. - Use HTTPException for expected errors and model them as specific HTTP responses. - Use middleware for handling unexpected errors, logging, and error monitoring. - Use Pydantic's BaseModel for consistent input/output validation and response schemas. Performance Optimization - Minimize blocking I/O operations; use asynchronous operations for all database calls and external API requests. - Implement caching for static and frequently accessed data using tools like Redis or in-memory stores. - Optimize data serialization and deserialization with Pydantic. - Use lazy loading techniques for large datasets and substantial API responses. Key Conventions 1. Rely on FastAPI’s dependency injection system for managing state and shared resources. 2. Prioritize API performance metrics (response time, latency, throughput). 3. Limit blocking operations in routes: - Favor asynchronous and non-blocking flows. - Use dedicated async functions for database and external API operations. - Structure routes and dependencies clearly to optimize readability and maintainability. Refer to FastAPI documentation for Data Models, Path Operations, and Middleware for best practices.
\ No newline at end of file
+// FastAPI Modern API Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern FastAPI application with:
+- High-performance REST APIs
+- Real-time WebSocket endpoints
+- Async database operations
+- OpenAPI documentation
+- Type-safe request/response handling
+- Authentication and authorization
+- Background tasks
+- Middleware integrations
+
+// Project Structure
+src/
+ main.py # Application entry point
+ core/ # Core functionality
+ config.py # Configuration
+ security.py # Security utilities
+ logging.py # Logging setup
+ api/ # API endpoints
+ v1/ # API version 1
+ routes/ # Route modules
+ models/ # Pydantic models
+ deps.py # Dependencies
+ db/ # Database
+ models.py # SQLAlchemy models
+ session.py # DB session
+ migrations/ # Alembic migrations
+ services/ # Business logic
+ schemas/ # Pydantic schemas
+ utils/ # Utilities
+ tests/ # Test suites
+ api/ # API tests
+ services/ # Service tests
+
+// Development Guidelines
+1. API Design:
+ - Use functional programming
+ - Implement proper validation
+ - Handle errors gracefully
+ - Use proper typing
+ - Implement proper documentation
+ - Follow REST principles
+
+2. Performance Patterns:
+ - Use async operations
+ - Implement caching
+ - Optimize database queries
+ - Use connection pooling
+ - Handle background tasks
+ - Monitor performance
+
+3. Code Organization:
+ - Separate concerns properly
+ - Use dependency injection
+ - Implement proper logging
+ - Handle configuration
+ - Use proper middleware
+ - Follow clean architecture
+
+// Dependencies
+Core:
+- fastapi: "^0.104.0"
+- pydantic: "^2.4.0"
+- sqlalchemy: "^2.0.0"
+- alembic: "^1.12.0"
+- uvicorn: "^0.24.0"
+- python-jose: "^3.3.0"
+
+Optional:
+- redis: "^5.0.0"
+- celery: "^5.3.0"
+- pytest: "^7.4.0"
+- httpx: "^0.25.0"
+
+// Code Examples:
+
+1. Route Definition Pattern:
+```python
+from fastapi import APIRouter, Depends, HTTPException
+from typing import List
+from pydantic import BaseModel
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from ..deps import get_db
+from ..models import UserRead, UserCreate
+from ...services.user import UserService
+
+router = APIRouter(prefix="/users", tags=["users"])
+
+@router.get("/", response_model=List[UserRead])
+async def get_users(
+ skip: int = 0,
+ limit: int = 100,
+ db: AsyncSession = Depends(get_db)
+) -> List[UserRead]:
+ """
+ Retrieve users with pagination.
+ """
+ try:
+ users = await UserService(db).get_users(skip=skip, limit=limit)
+ return users
+ except Exception as e:
+ raise HTTPException(
+ status_code=500,
+ detail="Failed to retrieve users"
+ )
+
+@router.post("/", response_model=UserRead)
+async def create_user(
+ user: UserCreate,
+ db: AsyncSession = Depends(get_db)
+) -> UserRead:
+ """
+ Create a new user.
+ """
+ try:
+ return await UserService(db).create_user(user)
+ except ValueError as e:
+ raise HTTPException(
+ status_code=400,
+ detail=str(e)
+ )
+```
+
+2. Service Pattern:
+```python
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select
+from typing import List, Optional
+
+from ..models import User
+from ..schemas import UserCreate, UserUpdate
+
+class UserService:
+ def __init__(self, db: AsyncSession):
+ self.db = db
+
+ async def get_users(
+ self,
+ skip: int = 0,
+ limit: int = 100
+ ) -> List[User]:
+ query = select(User).offset(skip).limit(limit)
+ result = await self.db.execute(query)
+ return result.scalars().all()
+
+ async def get_user_by_id(self, user_id: int) -> Optional[User]:
+ query = select(User).where(User.id == user_id)
+ result = await self.db.execute(query)
+ return result.scalar_one_or_none()
+
+ async def create_user(self, user: UserCreate) -> User:
+ db_user = User(**user.model_dump())
+ self.db.add(db_user)
+ await self.db.commit()
+ await self.db.refresh(db_user)
+ return db_user
+```
+
+3. Dependency Pattern:
+```python
+from fastapi import Depends, HTTPException, status
+from fastapi.security import OAuth2PasswordBearer
+from jose import JWTError, jwt
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from ..core.config import settings
+from ..db.session import async_session
+from ..models import User
+from ..services.user import UserService
+
+oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
+
+async def get_db() -> AsyncSession:
+ async with async_session() as session:
+ try:
+ yield session
+ finally:
+ await session.close()
+
+async def get_current_user(
+ token: str = Depends(oauth2_scheme),
+ db: AsyncSession = Depends(get_db)
+) -> User:
+ credentials_exception = HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Could not validate credentials",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ try:
+ payload = jwt.decode(
+ token,
+ settings.SECRET_KEY,
+ algorithms=[settings.ALGORITHM]
+ )
+ user_id: int = payload.get("sub")
+ if user_id is None:
+ raise credentials_exception
+ except JWTError:
+ raise credentials_exception
+
+ user = await UserService(db).get_user_by_id(user_id)
+ if user is None:
+ raise credentials_exception
+ return user
+```
+
+// Best Practices:
+1. Use type hints consistently
+2. Implement proper validation
+3. Handle errors gracefully
+4. Use async operations
+5. Implement proper logging
+6. Use dependency injection
+7. Follow REST principles
+8. Implement proper testing
+9. Use proper documentation
+10. Monitor performance
+
+// Security Considerations:
+1. Validate input data
+2. Use proper authentication
+3. Implement rate limiting
+4. Use secure headers
+5. Handle sensitive data
+6. Implement proper logging
+7. Use proper encryption
+8. Handle errors securely
+9. Implement CORS properly
+10. Follow security updates
\ No newline at end of file
diff --git a/rules/deno-integration-techniques-cursorrules-prompt-fil/.cursorrules b/rules/deno-integration-techniques-cursorrules-prompt-fil/.cursorrules
index a10235f..6f5b4d5 100644
--- a/rules/deno-integration-techniques-cursorrules-prompt-fil/.cursorrules
+++ b/rules/deno-integration-techniques-cursorrules-prompt-fil/.cursorrules
@@ -1 +1,248 @@
-This project contains automation scripts and workflows for the @findhow packages, based on the original Deno automation repository. The goal is to provide consistent and efficient automation for the @findhow ecosystem.The purpose of this project is to refactor and adapt the automation scripts from @https://github.com/denoland/automation for use with the @findhow packages found at @https://github.com/zhorton34/findhow.When working on this project, Cursor AI should:When making changes:When updating documentation:When creating or modifying automation scripts:Remember to thoroughly test all modifications to ensure they work correctly with the @findhow ecosystem before merging changes into the main branch.
\ No newline at end of file
+// Deno Integration and Automation Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Deno automation system with:
+- Package automation workflows
+- CI/CD integration scripts
+- Task runners and builders
+- Testing frameworks
+- Documentation generators
+- Dependency management
+- Release automation
+- Monitoring tools
+
+// Project Structure
+src/
+ main.ts # Entry point
+ automation/ # Automation scripts
+ workflows/ # CI/CD workflows
+ tasks/ # Task definitions
+ builders/ # Build scripts
+ scripts/ # Utility scripts
+ release/ # Release scripts
+ deploy/ # Deployment scripts
+ lib/ # Core libraries
+ utils/ # Utilities
+ testing/ # Test helpers
+ config/ # Configuration
+ ci/ # CI settings
+ defaults/ # Default configs
+ tests/ # Test suites
+ unit/ # Unit tests
+ integration/ # Integration tests
+
+// Development Guidelines
+1. Deno Patterns:
+ - Use TypeScript
+ - Implement permissions
+ - Handle async operations
+ - Use standard library
+ - Follow Deno conventions
+ - Use proper imports
+
+2. Automation Practices:
+ - Implement idempotency
+ - Handle errors gracefully
+ - Use proper logging
+ - Implement retries
+ - Handle timeouts
+ - Monitor progress
+
+3. Code Organization:
+ - Separate concerns
+ - Use modular design
+ - Implement testing
+ - Handle configuration
+ - Use proper typing
+ - Follow standards
+
+// Dependencies
+Core:
+- std: "^0.208.0"
+- deno_task_shell: "^0.10.0"
+- cliffy: "^1.0.0"
+- deno_dom: "^0.1.43"
+- oak: "^12.6.1"
+
+Optional:
+- fresh: "^1.6.0"
+- deno_cron: "^0.1.0"
+- deno_cache: "^0.5.0"
+- testing: "^0.208.0"
+
+// Code Examples:
+
+1. Task Runner Pattern:
+```typescript
+// automation/tasks/release.ts
+import { parse } from "std/flags/mod.ts";
+import { join } from "std/path/mod.ts";
+import { ensureDir } from "std/fs/mod.ts";
+
+interface ReleaseOptions {
+ version: string;
+ dryRun?: boolean;
+}
+
+export async function releasePackage(options: ReleaseOptions) {
+ const { version, dryRun = false } = options;
+
+ try {
+ // Validate version format
+ if (!/^\d+\.\d+\.\d+$/.test(version)) {
+ throw new Error("Invalid version format");
+ }
+
+ // Prepare release
+ await ensureDir("./dist");
+
+ // Update version
+ const pkg = JSON.parse(
+ await Deno.readTextFile("./package.json")
+ );
+ pkg.version = version;
+
+ if (!dryRun) {
+ await Deno.writeTextFile(
+ "./package.json",
+ JSON.stringify(pkg, null, 2)
+ );
+
+ // Run build
+ await Deno.run({
+ cmd: ["deno", "task", "build"],
+ }).status();
+ }
+
+ console.log(`Release ${version} prepared`);
+ } catch (error) {
+ console.error("Release failed:", error);
+ throw error;
+ }
+}
+```
+
+2. Workflow Pattern:
+```typescript
+// automation/workflows/ci.ts
+import { assertEquals } from "std/testing/asserts.ts";
+import { delay } from "std/async/mod.ts";
+
+interface WorkflowStep {
+ name: string;
+ run: () => Promise;
+ retries?: number;
+}
+
+export class Workflow {
+ private steps: WorkflowStep[] = [];
+
+ addStep(step: WorkflowStep) {
+ this.steps.push(step);
+ }
+
+ async run() {
+ for (const step of this.steps) {
+ const { name, run, retries = 3 } = step;
+ let attempts = 0;
+
+ while (attempts < retries) {
+ try {
+ console.log(`Running step: ${name}`);
+ await run();
+ break;
+ } catch (error) {
+ attempts++;
+ if (attempts === retries) {
+ throw new Error(
+ `Step ${name} failed after ${retries} attempts`
+ );
+ }
+ console.warn(
+ `Retry ${attempts}/${retries} for step ${name}`
+ );
+ await delay(1000 * attempts);
+ }
+ }
+ }
+ }
+}
+```
+
+3. Testing Pattern:
+```typescript
+// tests/integration/workflow_test.ts
+import {
+ assertEquals,
+ assertThrows,
+} from "std/testing/asserts.ts";
+import { Workflow } from "../../automation/workflows/ci.ts";
+
+Deno.test("Workflow execution", async () => {
+ const workflow = new Workflow();
+ const steps: string[] = [];
+
+ workflow.addStep({
+ name: "step1",
+ run: async () => {
+ steps.push("step1");
+ await Promise.resolve();
+ },
+ });
+
+ workflow.addStep({
+ name: "step2",
+ run: async () => {
+ steps.push("step2");
+ await Promise.resolve();
+ },
+ });
+
+ await workflow.run();
+
+ assertEquals(steps, ["step1", "step2"]);
+});
+
+Deno.test("Workflow error handling", async () => {
+ const workflow = new Workflow();
+
+ workflow.addStep({
+ name: "failing-step",
+ run: async () => {
+ throw new Error("Step failed");
+ },
+ retries: 1,
+ });
+
+ await assertThrows(
+ () => workflow.run(),
+ Error,
+ "Step failing-step failed after 1 attempts"
+ );
+});
+```
+
+// Best Practices:
+1. Use TypeScript strictly
+2. Implement proper error handling
+3. Use async/await properly
+4. Handle permissions correctly
+5. Implement proper logging
+6. Use proper testing
+7. Follow Deno standards
+8. Implement proper retries
+9. Use proper documentation
+10. Monitor performance
+
+// Security Considerations:
+1. Use proper permissions
+2. Handle secrets securely
+3. Validate inputs properly
+4. Use secure dependencies
+5. Implement proper logging
+6. Handle errors securely
+7. Use proper file access
+8. Implement proper auth
+9. Use proper networking
+10. Follow security updates
\ No newline at end of file
diff --git a/rules/docker-compose-cursorrules-prompt-file/.cursorrules b/rules/docker-compose-cursorrules-prompt-file/.cursorrules
new file mode 100644
index 0000000..6c79860
--- /dev/null
+++ b/rules/docker-compose-cursorrules-prompt-file/.cursorrules
@@ -0,0 +1,247 @@
+// Docker Compose Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern containerized application environment using Docker Compose:
+- Multi-container applications
+- Development environments
+- Production deployments
+- Service orchestration
+- Network configuration
+- Volume management
+- Environment variables
+- Health checks
+
+// Project Structure
+project/
+ docker/ # Docker-related files
+ services/ # Service-specific Dockerfiles
+ app/ # Application service
+ db/ # Database service
+ cache/ # Cache service
+ proxy/ # Reverse proxy
+ config/ # Configuration files
+ scripts/ # Helper scripts
+ docker-compose.yml # Main compose file
+ docker-compose.dev.yml # Development overrides
+ docker-compose.prod.yml # Production overrides
+ .env # Environment variables
+ .dockerignore # Ignore patterns
+
+// Development Guidelines
+1. Service Configuration:
+ - Use official images
+ - Pin versions
+ - Layer optimization
+ - Multi-stage builds
+ - Health checks
+ - Resource limits
+
+2. Network Setup:
+ - Define networks
+ - Expose ports
+ - Internal routing
+ - Service discovery
+ - Load balancing
+ - SSL termination
+
+3. Volume Management:
+ - Named volumes
+ - Bind mounts
+ - tmpfs mounts
+ - Data persistence
+ - Backup strategy
+ - Access control
+
+// Dependencies
+Core:
+- docker: "^24.0.0"
+- docker-compose: "^2.20.0"
+
+Optional:
+- docker-compose-watch: "^2.0.0"
+- docker-compose-cli: "^2.0.0"
+
+// Code Examples:
+
+1. Basic Service Pattern:
+```yaml
+version: '3.8'
+
+services:
+ app:
+ build:
+ context: ./docker/services/app
+ dockerfile: Dockerfile
+ target: development
+ environment:
+ - NODE_ENV=development
+ - DATABASE_URL=postgres://user:pass@db:5432/dbname
+ volumes:
+ - .:/app
+ - /app/node_modules
+ ports:
+ - "3000:3000"
+ depends_on:
+ db:
+ condition: service_healthy
+ networks:
+ - backend
+ healthcheck:
+ test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
+ interval: 30s
+ timeout: 10s
+ retries: 3
+ start_period: 40s
+
+ db:
+ image: postgres:15-alpine
+ environment:
+ - POSTGRES_USER=user
+ - POSTGRES_PASSWORD=pass
+ - POSTGRES_DB=dbname
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+ ports:
+ - "5432:5432"
+ networks:
+ - backend
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U user -d dbname"]
+ interval: 10s
+ timeout: 5s
+ retries: 5
+ start_period: 10s
+
+networks:
+ backend:
+ driver: bridge
+
+volumes:
+ postgres_data:
+ driver: local
+```
+
+2. Development Override Pattern:
+```yaml
+version: '3.8'
+
+services:
+ app:
+ build:
+ target: development
+ environment:
+ - DEBUG=true
+ - NODE_ENV=development
+ volumes:
+ - .:/app
+ - /app/node_modules
+ command: npm run dev
+ ports:
+ - "9229:9229" # Debug port
+
+ db:
+ ports:
+ - "5432:5432" # Expose for local development
+ volumes:
+ - ./docker/config/postgres/init.sql:/docker-entrypoint-initdb.d/init.sql
+```
+
+3. Production Override Pattern:
+```yaml
+version: '3.8'
+
+services:
+ app:
+ build:
+ target: production
+ environment:
+ - NODE_ENV=production
+ restart: unless-stopped
+ deploy:
+ replicas: 3
+ update_config:
+ parallelism: 1
+ delay: 10s
+ restart_policy:
+ condition: on-failure
+ max_attempts: 3
+ logging:
+ driver: json-file
+ options:
+ max-size: "10m"
+ max-file: "3"
+
+ db:
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+ ports: [] # No exposed ports in production
+ deploy:
+ resources:
+ limits:
+ cpus: '1'
+ memory: 1G
+ logging:
+ driver: json-file
+ options:
+ max-size: "10m"
+ max-file: "3"
+```
+
+// Best Practices:
+1. Service Design:
+ - Single responsibility
+ - Service isolation
+ - Resource limits
+ - Health checks
+ - Logging strategy
+ - Error handling
+
+2. Configuration:
+ - Environment vars
+ - Config files
+ - Secrets management
+ - Build arguments
+ - Runtime args
+ - Overrides
+
+3. Performance:
+ - Image size
+ - Layer caching
+ - Network setup
+ - Volume mounts
+ - Resource limits
+ - Monitoring
+
+4. Security:
+ - Network isolation
+ - Secret management
+ - User permissions
+ - Image scanning
+ - Updates policy
+ - Access control
+
+// Security Considerations:
+1. Network Security:
+ - Network isolation
+ - Port exposure
+ - TLS/SSL
+ - Service mesh
+ - Access control
+ - Firewalls
+
+2. Data Protection:
+ - Volume security
+ - Backup strategy
+ - Encryption
+ - Access control
+ - Audit logging
+ - Monitoring
+
+3. Container Security:
+ - Image scanning
+ - Root access
+ - Resource limits
+ - User namespace
+ - Capabilities
+ - Updates
\ No newline at end of file
diff --git a/rules/docker-cursorrules-prompt-file/.cursorrules b/rules/docker-cursorrules-prompt-file/.cursorrules
new file mode 100644
index 0000000..a57dac5
--- /dev/null
+++ b/rules/docker-cursorrules-prompt-file/.cursorrules
@@ -0,0 +1,221 @@
+// Docker Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern containerized application using Docker:
+- Single container applications
+- Multi-stage builds
+- Custom base images
+- Development containers
+- Production images
+- CI/CD pipelines
+- Security scanning
+- Performance optimization
+
+// Project Structure
+project/
+ docker/ # Docker-related files
+ Dockerfile # Main Dockerfile
+ Dockerfile.dev # Development Dockerfile
+ Dockerfile.prod # Production Dockerfile
+ .dockerignore # Ignore patterns
+ scripts/ # Build and helper scripts
+ build.sh # Build script
+ test.sh # Test script
+ deploy.sh # Deploy script
+ config/ # Configuration files
+ nginx/ # Web server config
+ supervisor/ # Process manager config
+ hooks/ # Docker build hooks
+ src/ # Application source code
+ tests/ # Test suite
+ docs/ # Documentation
+
+// Development Guidelines
+1. Image Building:
+ - Use official base images
+ - Pin image versions
+ - Layer optimization
+ - Multi-stage builds
+ - Build arguments
+ - Cache management
+
+2. Runtime Configuration:
+ - Environment variables
+ - Config files
+ - Secrets management
+ - Resource limits
+ - Health checks
+ - Logging setup
+
+3. Development Workflow:
+ - Local development
+ - Hot reloading
+ - Debugging setup
+ - Test environment
+ - CI/CD integration
+ - Version control
+
+// Dependencies
+Core:
+- docker: "^24.0.0"
+- docker-buildx: "^0.11.0"
+
+Optional:
+- docker-scan: "^0.23.0"
+- docker-compose: "^2.20.0"
+
+// Code Examples:
+
+1. Multi-stage Build Pattern:
+```dockerfile
+# Build stage
+FROM node:18-alpine AS builder
+
+WORKDIR /app
+
+COPY package*.json ./
+RUN npm ci
+
+COPY . .
+RUN npm run build
+
+# Production stage
+FROM node:18-alpine
+
+WORKDIR /app
+
+COPY --from=builder /app/dist ./dist
+COPY --from=builder /app/package*.json ./
+
+RUN npm ci --only=production
+
+USER node
+
+EXPOSE 3000
+
+HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
+ CMD wget --quiet --tries=1 --spider http://localhost:3000/health || exit 1
+
+CMD ["npm", "start"]
+```
+
+2. Development Container Pattern:
+```dockerfile
+FROM node:18-alpine
+
+WORKDIR /app
+
+RUN apk add --no-cache \
+ python3 \
+ make \
+ g++ \
+ git
+
+COPY package*.json ./
+RUN npm install
+
+COPY . .
+
+ENV NODE_ENV=development
+ENV PORT=3000
+
+EXPOSE 3000 9229
+
+CMD ["npm", "run", "dev"]
+```
+
+3. Production Container Pattern:
+```dockerfile
+FROM node:18-alpine AS builder
+
+WORKDIR /app
+
+COPY package*.json ./
+RUN npm ci
+
+COPY . .
+RUN npm run build
+
+FROM node:18-alpine
+
+WORKDIR /app
+
+RUN addgroup -g 1001 -S nodejs && \
+ adduser -S nodejs -u 1001 && \
+ apk add --no-cache tini
+
+COPY --from=builder --chown=nodejs:nodejs /app/dist ./dist
+COPY --from=builder /app/package*.json ./
+
+RUN npm ci --only=production && \
+ npm cache clean --force
+
+USER nodejs
+
+ENV NODE_ENV=production
+ENV PORT=3000
+
+EXPOSE 3000
+
+ENTRYPOINT ["/sbin/tini", "--"]
+CMD ["npm", "start"]
+```
+
+// Best Practices:
+1. Image Design:
+ - Layer optimization
+ - Cache utilization
+ - Size reduction
+ - Security hardening
+ - Version pinning
+ - Documentation
+
+2. Runtime Setup:
+ - Process management
+ - Signal handling
+ - Resource limits
+ - Health checks
+ - Logging strategy
+ - Error handling
+
+3. Performance:
+ - Build time
+ - Image size
+ - Startup time
+ - Resource usage
+ - Cache efficiency
+ - Network access
+
+4. Security:
+ - Root access
+ - User permissions
+ - Image scanning
+ - Secret handling
+ - Updates policy
+ - CVE monitoring
+
+// Security Considerations:
+1. Image Security:
+ - Base image
+ - Dependencies
+ - User permissions
+ - File permissions
+ - Secret handling
+ - Updates
+
+2. Runtime Security:
+ - Process isolation
+ - Resource limits
+ - Network access
+ - Volume mounts
+ - Capabilities
+ - Syscalls
+
+3. Build Security:
+ - Build context
+ - Build arguments
+ - Multi-stage
+ - Cache usage
+ - Hook scripts
+ - CI/CD
\ No newline at end of file
diff --git a/rules/dragonruby-best-practices-cursorrules-prompt-file/.cursorrules b/rules/dragonruby-best-practices-cursorrules-prompt-file/.cursorrules
index d16edea..5cc53c8 100644
--- a/rules/dragonruby-best-practices-cursorrules-prompt-file/.cursorrules
+++ b/rules/dragonruby-best-practices-cursorrules-prompt-file/.cursorrules
@@ -1 +1,246 @@
-You are an expert game developer in Ruby using the DragonRuby Game Toolkit. Code Style and Structure - Write concise, idiomatic Ruby code with accurate examples. - Follow Ruby and DragonRuby conventions and best practices. - Use object-oriented and functional programming patterns as appropriate. - Prefer iteration and modularization over code duplication. - Use descriptive variable and method names (e.g., user_signed_in?, calculate_total). - Structure files according to DragonRuby conventions. Naming Conventions - Use snake_case for file names, method names, and variables. - Use CamelCase for class and module names. - Follow DragonRuby naming conventions. Syntax and Formatting - Follow the Ruby Style Guide (https://rubystyle.guide/) - Use Ruby's expressive syntax (e.g., unless, ||=, &.) - Prefer single quotes for strings unless interpolation is needed. Error Handling and Validation - Use exceptions for exceptional cases, not for control flow. - Implement proper error logging and user-friendly messages. Follow the official DragonRuby Game Toolkit guides for best practices in routing, controllers, models, views, and other Rails components.
\ No newline at end of file
+// DragonRuby Game Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern DragonRuby game with:
+- 2D game mechanics
+- Sprite-based graphics
+- Physics simulations
+- Input handling
+- Sound management
+- Scene transitions
+- Collision detection
+- Performance optimization
+
+// Project Structure
+app/
+ main.rb # Entry point
+ game/ # Game logic
+ entities/ # Game entities
+ systems/ # Game systems
+ scenes/ # Game scenes
+ lib/ # Core libraries
+ physics/ # Physics engine
+ input/ # Input handling
+ audio/ # Audio management
+ assets/ # Game assets
+ sprites/ # Image files
+ sounds/ # Audio files
+ fonts/ # Font files
+ config/ # Configuration
+ tests/ # Test suites
+
+// Development Guidelines
+1. Game Architecture:
+ - Use entity component system
+ - Implement game loop properly
+ - Handle state management
+ - Use proper scene transitions
+ - Implement input handling
+ - Manage game resources
+
+2. Performance Patterns:
+ - Optimize sprite rendering
+ - Use efficient data structures
+ - Implement object pooling
+ - Handle memory management
+ - Optimize collision detection
+ - Monitor frame rate
+
+3. Code Organization:
+ - Follow Ruby conventions
+ - Use proper namespacing
+ - Implement testing
+ - Handle configuration
+ - Use proper documentation
+ - Follow best practices
+
+// Dependencies
+Core:
+- dragonruby-gtk: "^5.0"
+- ruby: "^3.2.0"
+
+Optional:
+- dragonruby-gtk-contrib: "^2.0"
+- minitest: "^5.0"
+- rake: "^13.0"
+
+// Code Examples:
+
+1. Game Entity Pattern:
+```ruby
+# game/entities/player.rb
+module Game
+ module Entities
+ class Player
+ attr_sprite
+
+ def initialize(args)
+ @x = 100
+ @y = 100
+ @w = 32
+ @h = 32
+ @path = 'sprites/player.png'
+ @velocity_x = 0
+ @velocity_y = 0
+ end
+
+ def update(args)
+ handle_input(args)
+ update_position
+ handle_collisions(args)
+ end
+
+ private
+
+ def handle_input(args)
+ @velocity_x = 0
+ @velocity_x -= 5 if args.inputs.keyboard.key_held.left
+ @velocity_x += 5 if args.inputs.keyboard.key_held.right
+ end
+
+ def update_position
+ @x += @velocity_x
+ @y += @velocity_y
+ end
+
+ def handle_collisions(args)
+ # Collision detection logic
+ end
+ end
+ end
+end
+```
+
+2. Scene Management Pattern:
+```ruby
+# game/scenes/game_scene.rb
+module Game
+ module Scenes
+ class GameScene
+ def initialize(args)
+ @player = Entities::Player.new(args)
+ @enemies = []
+ @score = 0
+ end
+
+ def tick(args)
+ handle_input(args)
+ update(args)
+ render(args)
+ end
+
+ private
+
+ def handle_input(args)
+ if args.inputs.keyboard.key_down.escape
+ args.state.scene = :menu
+ end
+ end
+
+ def update(args)
+ @player.update(args)
+ @enemies.each { |enemy| enemy.update(args) }
+ check_collisions
+ end
+
+ def render(args)
+ args.outputs.sprites << @player
+ @enemies.each { |enemy| args.outputs.sprites << enemy }
+ render_ui(args)
+ end
+
+ def render_ui(args)
+ args.outputs.labels << {
+ x: 40,
+ y: 680,
+ text: "Score: #{@score}",
+ size_enum: 2
+ }
+ end
+ end
+ end
+end
+```
+
+3. Physics System Pattern:
+```ruby
+# lib/physics/collision_system.rb
+module Physics
+ class CollisionSystem
+ def initialize
+ @spatial_hash = {}
+ @cell_size = 32
+ end
+
+ def add_entity(entity)
+ cells = get_occupied_cells(entity)
+ cells.each do |cell|
+ @spatial_hash[cell] ||= []
+ @spatial_hash[cell] << entity
+ end
+ end
+
+ def check_collisions(entity)
+ cells = get_occupied_cells(entity)
+ potential_collisions = cells.flat_map do |cell|
+ @spatial_hash[cell] || []
+ end.uniq
+
+ potential_collisions.reject! { |e| e == entity }
+
+ potential_collisions.select do |other|
+ entities_collide?(entity, other)
+ end
+ end
+
+ private
+
+ def get_occupied_cells(entity)
+ start_x = (entity.x / @cell_size).floor
+ start_y = (entity.y / @cell_size).floor
+ end_x = ((entity.x + entity.w) / @cell_size).floor
+ end_y = ((entity.y + entity.h) / @cell_size).floor
+
+ cells = []
+ (start_x..end_x).each do |x|
+ (start_y..end_y).each do |y|
+ cells << [x, y]
+ end
+ end
+ cells
+ end
+
+ def entities_collide?(a, b)
+ a.x < b.x + b.w &&
+ a.x + a.w > b.x &&
+ a.y < b.y + b.h &&
+ a.y + a.h > b.y
+ end
+ end
+end
+```
+
+// Best Practices:
+1. Follow Ruby conventions
+2. Use proper game architecture
+3. Implement efficient updates
+4. Handle input properly
+5. Manage game state
+6. Use proper collision detection
+7. Implement proper testing
+8. Handle resource loading
+9. Use proper documentation
+10. Monitor performance
+
+// Security Considerations:
+1. Validate user input
+2. Handle file access safely
+3. Manage memory properly
+4. Use secure dependencies
+5. Implement proper logging
+6. Handle errors gracefully
+7. Use proper serialization
+8. Protect game assets
+9. Handle saves securely
+10. Follow security updates
\ No newline at end of file
diff --git a/rules/electron-typescript-cursorrules-prompt-file/.cursorrules b/rules/electron-typescript-cursorrules-prompt-file/.cursorrules
new file mode 100644
index 0000000..dcd5b31
--- /dev/null
+++ b/rules/electron-typescript-cursorrules-prompt-file/.cursorrules
@@ -0,0 +1,307 @@
+// Electron TypeScript Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern cross-platform desktop application using Electron and TypeScript:
+- Native desktop features
+- System tray applications
+- Background processes
+- File system access
+- Native menus
+- Window management
+- IPC communication
+- Auto-updates
+
+// Project Structure
+src/
+ main/ # Main process
+ index.ts # Entry point
+ preload.ts # Preload scripts
+ ipc/ # IPC handlers
+ services/ # Main services
+ utils/ # Utilities
+ renderer/ # Renderer process
+ components/ # UI components
+ pages/ # Application pages
+ styles/ # Global styles
+ utils/ # Frontend utilities
+ shared/ # Shared code
+ types/ # Type definitions
+ constants/ # Shared constants
+ utils/ # Shared utilities
+ assets/ # Static assets
+tests/ # Test suite
+ main/ # Main process tests
+ renderer/ # Renderer tests
+ e2e/ # End-to-end tests
+
+// Development Guidelines
+1. Process Architecture:
+ - Main process
+ - Renderer process
+ - Preload scripts
+ - IPC patterns
+ - Window management
+ - Security context
+
+2. Application Structure:
+ - Module patterns
+ - State management
+ - Error handling
+ - File operations
+ - Native features
+ - Updates system
+
+3. Performance:
+ - Memory usage
+ - CPU usage
+ - Startup time
+ - IPC overhead
+ - Resource cleanup
+ - Background tasks
+
+// Dependencies
+Core:
+- electron: "^25.0.0"
+- typescript: "^5.0.0"
+- electron-builder: "^24.0.0"
+- electron-store: "^8.1.0"
+
+Optional:
+- electron-updater: "^6.1.1"
+- electron-log: "^4.4.8"
+- electron-devtools-installer: "^3.2.0"
+- spectron: "^19.0.0"
+
+// Code Examples:
+
+1. Main Process Pattern:
+```typescript
+import { app, BrowserWindow, ipcMain } from 'electron';
+import { join } from 'path';
+import Store from 'electron-store';
+
+interface AppConfig {
+ windowBounds: {
+ width: number;
+ height: number;
+ };
+ theme: 'light' | 'dark';
+}
+
+class MainWindow {
+ private window: BrowserWindow | null = null;
+ private store: Store;
+
+ constructor() {
+ this.store = new Store({
+ defaults: {
+ windowBounds: { width: 1200, height: 800 },
+ theme: 'light'
+ }
+ });
+
+ this.setupIPC();
+ }
+
+ private setupIPC() {
+ ipcMain.handle('get-theme', () => {
+ return this.store.get('theme');
+ });
+
+ ipcMain.handle('set-theme', (_, theme: 'light' | 'dark') => {
+ this.store.set('theme', theme);
+ return theme;
+ });
+ }
+
+ async create() {
+ const { width, height } = this.store.get('windowBounds');
+
+ this.window = new BrowserWindow({
+ width,
+ height,
+ webPreferences: {
+ nodeIntegration: false,
+ contextIsolation: true,
+ preload: join(__dirname, 'preload.js')
+ }
+ });
+
+ if (process.env.NODE_ENV === 'development') {
+ await this.window.loadURL('http://localhost:3000');
+ this.window.webContents.openDevTools();
+ } else {
+ await this.window.loadFile(join(__dirname, '../renderer/index.html'));
+ }
+
+ this.window.on('close', () => {
+ if (this.window) {
+ const bounds = this.window.getBounds();
+ this.store.set('windowBounds', bounds);
+ }
+ });
+ }
+
+ get browserWindow() {
+ return this.window;
+ }
+}
+
+export default MainWindow;
+```
+
+2. Preload Script Pattern:
+```typescript
+import { contextBridge, ipcRenderer } from 'electron';
+
+export type Theme = 'light' | 'dark';
+
+interface API {
+ theme: {
+ get: () => Promise;
+ set: (theme: Theme) => Promise;
+ };
+ system: {
+ platform: string;
+ arch: string;
+ };
+}
+
+const api: API = {
+ theme: {
+ get: () => ipcRenderer.invoke('get-theme'),
+ set: (theme) => ipcRenderer.invoke('set-theme', theme)
+ },
+ system: {
+ platform: process.platform,
+ arch: process.arch
+ }
+};
+
+contextBridge.exposeInMainWorld('electron', api);
+
+declare global {
+ interface Window {
+ electron: API;
+ }
+}
+```
+
+3. Renderer Process Pattern:
+```typescript
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+
+interface AppState {
+ theme: 'light' | 'dark';
+ isLoading: boolean;
+}
+
+function App() {
+ const [state, setState] = React.useState({
+ theme: 'light',
+ isLoading: true
+ });
+
+ React.useEffect(() => {
+ const loadTheme = async () => {
+ try {
+ const theme = await window.electron.theme.get();
+ setState(prev => ({ ...prev, theme, isLoading: false }));
+ } catch (error) {
+ console.error('Failed to load theme:', error);
+ setState(prev => ({ ...prev, isLoading: false }));
+ }
+ };
+
+ loadTheme();
+ }, []);
+
+ const toggleTheme = async () => {
+ try {
+ const newTheme = state.theme === 'light' ? 'dark' : 'light';
+ const updatedTheme = await window.electron.theme.set(newTheme);
+ setState(prev => ({ ...prev, theme: updatedTheme }));
+ } catch (error) {
+ console.error('Failed to update theme:', error);
+ }
+ };
+
+ if (state.isLoading) {
+ return
Loading...
;
+ }
+
+ return (
+
+
Electron App
+
Platform: {window.electron.system.platform}
+
Architecture: {window.electron.system.arch}
+
+
+ );
+}
+
+const root = createRoot(document.getElementById('root')!);
+root.render();
+```
+
+// Best Practices:
+1. Security:
+ - Context isolation
+ - CSP headers
+ - Input validation
+ - Secure IPC
+ - File access
+ - Native APIs
+
+2. Architecture:
+ - Process separation
+ - Module patterns
+ - State management
+ - Error handling
+ - Event handling
+ - Resource cleanup
+
+3. Performance:
+ - Memory management
+ - IPC optimization
+ - Resource loading
+ - Background tasks
+ - Window lifecycle
+ - Event debouncing
+
+4. Distribution:
+ - Code signing
+ - Auto updates
+ - Installers
+ - Platform builds
+ - Release notes
+ - Update server
+
+// Security Considerations:
+1. Process Security:
+ - Context isolation
+ - Preload scripts
+ - IPC validation
+ - CSP headers
+ - Permissions
+ - Sandboxing
+
+2. File System:
+ - Path validation
+ - Access control
+ - File operations
+ - Temp files
+ - User data
+ - Downloads
+
+3. Network Security:
+ - HTTPS only
+ - Certificate validation
+ - Content security
+ - API security
+ - Update security
+ - WebRTC
\ No newline at end of file
diff --git a/rules/elixir-engineer-guidelines-cursorrules-prompt-file/.cursorrules b/rules/elixir-engineer-guidelines-cursorrules-prompt-file/.cursorrules
index da443d8..2b5dde5 100644
--- a/rules/elixir-engineer-guidelines-cursorrules-prompt-file/.cursorrules
+++ b/rules/elixir-engineer-guidelines-cursorrules-prompt-file/.cursorrules
@@ -1 +1,234 @@
-Act as an expert senior Elixir engineer.Stack: Elixir, Phoenix, Docker, PostgreSQL, Tailwind CSS, LeftHook, Sobelow, Credo, Ecto, ExUnit, Plug, Phoenix LiveView, Phoenix LiveDashboard, Gettext, Jason, Swoosh, Finch, DNS Cluster, File System Watcher, Release Please, ExCoveralls[optional scope]: [optional body][optional footer(s)]Where:type: One of the following:scope (optional): A noun describing a section of the codebase (e.g., fluxcd, deployment).description: A brief summary of the change in present tense.body (optional): A more detailed explanation of the change.footer (optional): One or more footers in the following format:
\ No newline at end of file
+// Elixir Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Elixir application with:
+- Scalable web applications
+- Real-time features
+- Distributed systems
+- Fault-tolerant services
+- API endpoints
+- Database integrations
+- Background jobs
+- Monitoring solutions
+
+// Project Structure
+lib/
+ my_app/ # Core application
+ application.ex # Application entry
+ supervisor.ex # Supervision tree
+ my_app_web/ # Web interface
+ controllers/ # Request handlers
+ views/ # View templates
+ live/ # LiveView modules
+ components/ # UI components
+ contexts/ # Business domains
+ accounts/ # User accounts
+ payments/ # Payment processing
+ workers/ # Background jobs
+ schemas/ # Database schemas
+ services/ # External services
+config/ # Configuration
+ dev.exs # Development config
+ prod.exs # Production config
+ test.exs # Test config
+priv/ # Private assets
+test/ # Test files
+
+// Development Guidelines
+1. Elixir Patterns:
+ - Use functional programming
+ - Implement proper supervision
+ - Handle concurrency properly
+ - Use pattern matching
+ - Implement error handling
+ - Follow OTP principles
+
+2. Phoenix Practices:
+ - Use proper contexts
+ - Implement LiveView
+ - Handle authentication
+ - Use proper channels
+ - Implement PubSub
+ - Follow conventions
+
+3. Code Organization:
+ - Separate concerns
+ - Use proper modules
+ - Implement testing
+ - Handle configuration
+ - Use proper documentation
+ - Follow standards
+
+// Dependencies
+Core:
+- elixir: "~> 1.15"
+- phoenix: "~> 1.7"
+- ecto: "~> 3.10"
+- phoenix_live_view: "~> 0.20"
+- postgrex: "~> 0.17"
+- swoosh: "~> 1.11"
+
+Optional:
+- credo: "~> 1.7"
+- sobelow: "~> 0.13"
+- excoveralls: "~> 0.18"
+- ex_machina: "~> 2.7"
+
+// Code Examples:
+
+1. Context Pattern:
+```elixir
+# lib/my_app/accounts/accounts.ex
+defmodule MyApp.Accounts do
+ @moduledoc """
+ The Accounts context.
+ """
+
+ import Ecto.Query
+ alias MyApp.Repo
+ alias MyApp.Accounts.{User, UserToken}
+
+ @doc """
+ Gets a user by email.
+ """
+ def get_user_by_email(email) when is_binary(email) do
+ Repo.get_by(User, email: email)
+ end
+
+ @doc """
+ Creates a user.
+ """
+ def create_user(attrs \\ %{}) do
+ %User{}
+ |> User.registration_changeset(attrs)
+ |> Repo.insert()
+ end
+
+ @doc """
+ Authenticates a user by email and password.
+ """
+ def authenticate_user(email, password)
+ when is_binary(email) and is_binary(password) do
+ user = get_user_by_email(email)
+
+ cond do
+ user && User.valid_password?(user, password) ->
+ {:ok, user}
+
+ user ->
+ {:error, :invalid_password}
+
+ true ->
+ {:error, :invalid_email}
+ end
+ end
+end
+```
+
+2. LiveView Pattern:
+```elixir
+# lib/my_app_web/live/user_live/index.ex
+defmodule MyAppWeb.UserLive.Index do
+ use MyAppWeb, :live_view
+
+ alias MyApp.Accounts
+
+ @impl true
+ def mount(_params, _session, socket) do
+ if connected?(socket) do
+ Phoenix.PubSub.subscribe(MyApp.PubSub, "users")
+ end
+
+ {:ok, assign(socket, users: list_users())}
+ end
+
+ @impl true
+ def handle_event("delete", %{"id" => id}, socket) do
+ user = Accounts.get_user!(id)
+ {:ok, _} = Accounts.delete_user(user)
+
+ {:noreply, assign(socket, users: list_users())}
+ end
+
+ @impl true
+ def handle_info({:user_created, user}, socket) do
+ {:noreply, update(socket, :users, &[user | &1])}
+ end
+
+ defp list_users do
+ Accounts.list_users()
+ end
+end
+```
+
+3. GenServer Pattern:
+```elixir
+# lib/my_app/workers/email_worker.ex
+defmodule MyApp.Workers.EmailWorker do
+ use GenServer
+ require Logger
+
+ def start_link(opts) do
+ GenServer.start_link(__MODULE__, opts, name: __MODULE__)
+ end
+
+ def send_email(to, subject, body) do
+ GenServer.cast(__MODULE__, {:send_email, to, subject, body})
+ end
+
+ @impl true
+ def init(opts) do
+ Process.flag(:trap_exit, true)
+ {:ok, opts}
+ end
+
+ @impl true
+ def handle_cast({:send_email, to, subject, body}, state) do
+ try do
+ MyApp.Mailer.deliver_later(%{
+ to: to,
+ subject: subject,
+ body: body
+ })
+
+ Logger.info("Email sent to #{to}")
+ rescue
+ e ->
+ Logger.error("Failed to send email: #{inspect(e)}")
+ end
+
+ {:noreply, state}
+ end
+
+ @impl true
+ def terminate(reason, _state) do
+ Logger.info("EmailWorker terminating: #{inspect(reason)}")
+ :ok
+ end
+end
+```
+
+// Best Practices:
+1. Follow functional paradigms
+2. Use proper supervision
+3. Handle concurrency properly
+4. Implement proper testing
+5. Use proper documentation
+6. Handle errors gracefully
+7. Follow OTP principles
+8. Use proper contexts
+9. Implement monitoring
+10. Follow conventions
+
+// Security Considerations:
+1. Validate user input
+2. Use proper authentication
+3. Implement authorization
+4. Handle sensitive data
+5. Use secure configs
+6. Implement rate limiting
+7. Handle errors securely
+8. Use proper encryption
+9. Follow security updates
+10. Audit dependencies
\ No newline at end of file
diff --git a/rules/elixir-phoenix-docker-setup-cursorrules-prompt-fil/.cursorrules b/rules/elixir-phoenix-docker-setup-cursorrules-prompt-fil/.cursorrules
index 7301e06..fa784f2 100644
--- a/rules/elixir-phoenix-docker-setup-cursorrules-prompt-fil/.cursorrules
+++ b/rules/elixir-phoenix-docker-setup-cursorrules-prompt-fil/.cursorrules
@@ -1 +1,207 @@
-Act as an expert senior Elixir engineer.Stack: Elixir, Phoenix, Docker, PostgreSQL, Tailwind CSS, LeftHook, Sobelow, Credo, Ecto, ExUnit, Plug, Phoenix LiveView, Phoenix LiveDashboard, Gettext, Jason, Swoosh, Finch, DNS Cluster, File System Watcher, Release Please, ExCoveralls- When writing code, you will think through any considerations or requirements to make sure we've thought of everything. Only after that do you write the code.- After a response, provide three follow-up questions worded as if I'm asking you. Format in bold as Q1, Q2, Q3. These questions should be throught-provoking and dig further into the original topic. - If my response starts with "VV", give the most succinct, concise, shortest answer possible.## Commit Message Guidelines:- Always suggest a conventional commit message with an optional scope in lowercase. Follow this structure:[optional scope]: [optional body][optional footer(s)]Where:- **type:** One of the following: - `build`: Changes that affect the build system or external dependencies (e.g., Maven, npm) - `chore`: Other changes that don't modify src or test files - `ci`: Changes to our CI configuration files and scripts (e.g., Circle, BrowserStack, SauceLabs) - `docs`: Documentation only changes - `feat`: A new feature - `fix`: A bug fix - `perf`: A code change that improves performance - `refactor`: A code change that neither fixes a bug nor adds a feature - `style`: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc) - `test`: Adding missing tests or correcting existing tests - **scope (optional):** A noun describing a section of the codebase (e.g., `fluxcd`, `deployment`).- **description:** A brief summary of the change in present tense.- **body (optional):** A more detailed explanation of the change.- **footer (optional):** One or more footers in the following format: - `BREAKING CHANGE: ` (for breaking changes) - `: ` (e.g., `Jira-123: Fixed bug in authentication`)
\ No newline at end of file
+// Elixir Phoenix Docker Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern containerized Phoenix application with:
+- Docker-based development
+- Production deployments
+- Database integration
+- Asset compilation
+- LiveView support
+- Monitoring setup
+- CI/CD pipelines
+- Multi-stage builds
+
+// Project Structure
+.
+├── Dockerfile # Multi-stage Dockerfile
+├── docker-compose.yml # Development setup
+├── .dockerignore # Docker ignore rules
+├── config/ # Phoenix config
+│ ├── dev.exs # Development config
+│ └── prod.exs # Production config
+├── lib/ # Application code
+├── rel/ # Release config
+│ └── env.sh.eex # Environment setup
+├── assets/ # Frontend assets
+└── scripts/ # Docker scripts
+ ├── entrypoint.sh # Container entry
+ └── migrate.sh # DB migrations
+
+// Development Guidelines
+1. Docker Setup:
+ - Use multi-stage builds
+ - Implement proper caching
+ - Handle dependencies
+ - Configure networking
+ - Manage volumes
+ - Set environment
+
+2. Phoenix Configuration:
+ - Handle secrets
+ - Configure database
+ - Set up assets
+ - Manage releases
+ - Configure ports
+ - Handle SSL
+
+3. Deployment Practices:
+ - Use proper tagging
+ - Implement healthchecks
+ - Handle migrations
+ - Configure logging
+ - Manage backups
+ - Monitor resources
+
+// Dependencies
+Core:
+- elixir: "~> 1.15"
+- phoenix: "~> 1.7"
+- docker: "^24.0"
+- postgres: "^15.0"
+- node: "^20.0"
+
+Optional:
+- docker-compose: "^2.21"
+- nginx: "^1.25"
+- prometheus: "^2.47"
+- grafana: "^10.1"
+
+// Code Examples:
+
+1. Dockerfile Pattern:
+```dockerfile
+# Dockerfile
+# Build stage
+FROM hexpm/elixir:1.15.7-erlang-26.1.2-alpine-3.18.4 AS builder
+
+# Install build dependencies
+RUN apk add --no-cache build-base npm git python3
+
+WORKDIR /app
+
+# Install hex + rebar
+RUN mix local.hex --force && \
+ mix local.rebar --force
+
+# Set build ENV
+ENV MIX_ENV=prod
+
+# Install mix dependencies
+COPY mix.exs mix.lock ./
+RUN mix deps.get --only $MIX_ENV
+RUN mix deps.compile
+
+# Build assets
+COPY assets assets
+RUN npm --prefix assets ci --progress=false --no-audit --loglevel=error
+RUN npm run --prefix assets deploy
+RUN mix phx.digest
+
+# Compile and build release
+COPY . .
+RUN mix compile
+RUN mix release
+
+# Release stage
+FROM alpine:3.18.4 AS app
+RUN apk add --no-cache openssl ncurses-libs
+
+WORKDIR /app
+
+RUN chown nobody:nobody /app
+
+USER nobody:nobody
+
+COPY --from=builder --chown=nobody:nobody /app/_build/prod/rel/my_app ./
+
+ENV HOME=/app
+ENV MIX_ENV=prod
+ENV PORT=4000
+
+CMD ["bin/my_app", "start"]
+```
+
+2. Docker Compose Pattern:
+```yaml
+# docker-compose.yml
+version: '3.8'
+
+services:
+ app:
+ build:
+ context: .
+ target: builder
+ ports:
+ - "4000:4000"
+ environment:
+ - DATABASE_URL=ecto://postgres:postgres@db/my_app_dev
+ - SECRET_KEY_BASE=your_development_key
+ volumes:
+ - .:/app
+ - build:/app/_build
+ - deps:/app/deps
+ depends_on:
+ - db
+ command: mix phx.server
+
+ db:
+ image: postgres:15-alpine
+ environment:
+ - POSTGRES_USER=postgres
+ - POSTGRES_PASSWORD=postgres
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+
+volumes:
+ postgres_data:
+ build:
+ deps:
+```
+
+3. Release Configuration Pattern:
+```elixir
+# rel/env.sh.eex
+#!/bin/sh
+
+# Sets and enables heart (recommended only in daemon mode)
+# if [ "$RELEASE_COMMAND" = "daemon" ] || [ "$RELEASE_COMMAND" = "daemon_iex" ]; then
+# HEART_COMMAND="$RELEASE_ROOT/bin/$RELEASE_NAME $RELEASE_COMMAND"
+# export HEART_COMMAND
+# export ELIXIR_ERL_OPTIONS="-heart"
+# fi
+
+# Set the release to work across nodes
+export RELEASE_DISTRIBUTION=name
+export RELEASE_NODE=<%= @release.name %>@127.0.0.1
+
+# Set database configuration
+export DATABASE_URL="${DATABASE_URL}"
+export SECRET_KEY_BASE="${SECRET_KEY_BASE}"
+export PHX_HOST="${PHX_HOST}"
+export PORT="${PORT}"
+```
+
+// Best Practices:
+1. Use multi-stage builds
+2. Implement proper caching
+3. Handle secrets securely
+4. Configure healthchecks
+5. Manage dependencies
+6. Handle migrations
+7. Configure logging
+8. Use proper networking
+9. Implement monitoring
+10. Follow conventions
+
+// Security Considerations:
+1. Secure secrets management
+2. Use proper permissions
+3. Scan dependencies
+4. Configure firewalls
+5. Handle SSL/TLS
+6. Implement CORS
+7. Update base images
+8. Secure networking
+9. Monitor containers
+10. Audit configurations
\ No newline at end of file
diff --git a/rules/es-module-nodejs-guidelines-cursorrules-prompt-fil/.cursorrules b/rules/es-module-nodejs-guidelines-cursorrules-prompt-fil/.cursorrules
index 778f386..af1f866 100644
--- a/rules/es-module-nodejs-guidelines-cursorrules-prompt-fil/.cursorrules
+++ b/rules/es-module-nodejs-guidelines-cursorrules-prompt-fil/.cursorrules
@@ -1 +1,226 @@
-## General- Follow best practices, lean towards agile methodologies- Prioritize modularity, DRY, performance, and security- First break tasks into distinct prioritized steps, then follow the steps- Prioritize tasks/steps you’ll address in each response don't repeat yourself- keep responses very short, unless I include a Vx value : - V0 default, code golf - V1 concise - V2 simple - V3 verbose, DRY with extracted functions## Code- use ES module syntax- where appropriate suggest refactorings and code improvements- favor using the latest ES and nodejs features- Don’t apologize for errors: fix them* If you can’t finish code, add TODO: comments## Comments- Comments should be created where the operation isn't clear from the code, or where uncommon libraries are used- Code must start with path/filename as a one-line comment- Comments should describe purpose, not effect
\ No newline at end of file
+// ES Module Node.js Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Node.js application with:
+- ES Module architecture
+- Modular components
+- Async operations
+- Type safety
+- Performance optimization
+- Error handling
+- Testing infrastructure
+- Development tooling
+
+// Project Structure
+src/
+ index.js # Entry point
+ modules/ # ES modules
+ core/ # Core modules
+ utils/ # Utilities
+ services/ # Services
+ config/ # Configuration
+ env.js # Environment
+ constants.js # Constants
+ middleware/ # Middleware
+ models/ # Data models
+ tests/ # Test files
+ unit/ # Unit tests
+ integration/ # Integration tests
+ types/ # Type definitions
+ docs/ # Documentation
+
+// Development Guidelines
+1. Module Patterns:
+ - Use ES module syntax
+ - Implement pure functions
+ - Handle async properly
+ - Use type annotations
+ - Follow conventions
+ - Manage dependencies
+
+2. Code Organization:
+ - Separate concerns
+ - Use proper imports
+ - Handle errors
+ - Implement testing
+ - Document code
+ - Follow standards
+
+3. Performance Practices:
+ - Optimize imports
+ - Handle async ops
+ - Manage memory
+ - Use proper caching
+ - Monitor performance
+ - Profile code
+
+// Dependencies
+Core:
+- node: "^20.0.0"
+- typescript: "^5.2.0"
+- jest: "^29.7.0"
+- eslint: "^8.53.0"
+- prettier: "^3.1.0"
+
+Optional:
+- nodemon: "^3.0.1"
+- ts-node: "^10.9.0"
+- dotenv: "^16.3.0"
+- winston: "^3.11.0"
+
+// Code Examples:
+
+1. ES Module Pattern:
+```javascript
+// src/modules/core/user.js
+import { validateEmail } from '../utils/validators.js';
+import { DatabaseError } from '../utils/errors.js';
+
+export class User {
+ #email;
+ #name;
+
+ constructor(name, email) {
+ this.#validateInputs(name, email);
+ this.#name = name;
+ this.#email = email;
+ }
+
+ #validateInputs(name, email) {
+ if (!name?.trim()) {
+ throw new Error('Name is required');
+ }
+ if (!validateEmail(email)) {
+ throw new Error('Invalid email format');
+ }
+ }
+
+ static async findByEmail(email) {
+ try {
+ const user = await db.users.findOne({ email });
+ return user ? new User(user.name, user.email) : null;
+ } catch (error) {
+ throw new DatabaseError('Failed to fetch user', error);
+ }
+ }
+
+ toJSON() {
+ return {
+ name: this.#name,
+ email: this.#email
+ };
+ }
+}
+```
+
+2. Service Pattern:
+```javascript
+// src/services/auth.js
+import { User } from '../modules/core/user.js';
+import { generateToken } from '../utils/jwt.js';
+import { AuthError } from '../utils/errors.js';
+
+export class AuthService {
+ static async authenticate(email, password) {
+ try {
+ const user = await User.findByEmail(email);
+
+ if (!user) {
+ throw new AuthError('User not found');
+ }
+
+ const isValid = await user.validatePassword(password);
+ if (!isValid) {
+ throw new AuthError('Invalid password');
+ }
+
+ const token = generateToken(user.toJSON());
+ return { user, token };
+ } catch (error) {
+ if (error instanceof AuthError) {
+ throw error;
+ }
+ throw new Error('Authentication failed');
+ }
+ }
+
+ static async validateToken(token) {
+ try {
+ const payload = verifyToken(token);
+ const user = await User.findByEmail(payload.email);
+ return user;
+ } catch (error) {
+ throw new AuthError('Invalid token');
+ }
+ }
+}
+```
+
+3. Utility Pattern:
+```javascript
+// src/utils/async-handler.js
+export const asyncHandler = (fn) => {
+ return async (req, res, next) => {
+ try {
+ await fn(req, res, next);
+ } catch (error) {
+ next(error);
+ }
+ };
+};
+
+export const withTransaction = async (fn) => {
+ const session = await startSession();
+ try {
+ session.startTransaction();
+ const result = await fn(session);
+ await session.commitTransaction();
+ return result;
+ } catch (error) {
+ await session.abortTransaction();
+ throw error;
+ } finally {
+ session.endSession();
+ }
+};
+
+export const memoize = (fn) => {
+ const cache = new Map();
+
+ return (...args) => {
+ const key = JSON.stringify(args);
+ if (cache.has(key)) {
+ return cache.get(key);
+ }
+
+ const result = fn.apply(this, args);
+ cache.set(key, result);
+ return result;
+ };
+};
+```
+
+// Best Practices:
+1. Use ES module syntax
+2. Implement proper typing
+3. Handle errors gracefully
+4. Use async/await
+5. Implement testing
+6. Document code properly
+7. Follow conventions
+8. Optimize imports
+9. Handle security
+10. Monitor performance
+
+// Security Considerations:
+1. Validate input
+2. Handle authentication
+3. Implement authorization
+4. Secure data
+5. Use proper encryption
+6. Handle secrets
+7. Validate dependencies
+8. Implement logging
+9. Handle errors securely
+10. Follow updates
\ No newline at end of file
diff --git a/rules/express-typescript-cursorrules-prompt-file/.cursorrules b/rules/express-typescript-cursorrules-prompt-file/.cursorrules
new file mode 100644
index 0000000..9b4896f
--- /dev/null
+++ b/rules/express-typescript-cursorrules-prompt-file/.cursorrules
@@ -0,0 +1,300 @@
+// Express TypeScript Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Node.js web application using Express and TypeScript:
+- RESTful APIs
+- GraphQL APIs
+- Authentication
+- Authorization
+- Database integration
+- File uploads
+- WebSocket support
+- Background jobs
+
+// Project Structure
+src/
+ api/ # API routes
+ controllers/ # Route controllers
+ middleware/ # Custom middleware
+ validators/ # Request validation
+ routes/ # Route definitions
+ config/ # Configuration
+ database.ts # Database config
+ server.ts # Server config
+ logger.ts # Logging config
+ models/ # Data models
+ entities/ # Database entities
+ dtos/ # Data transfer objects
+ services/ # Business logic
+ auth/ # Authentication
+ email/ # Email service
+ storage/ # File storage
+ utils/ # Utilities
+ errors/ # Error handlers
+ logger/ # Logging utils
+ validation/ # Validation utils
+ types/ # Type definitions
+ app.ts # Express app
+ server.ts # Entry point
+tests/ # Test suite
+ unit/ # Unit tests
+ integration/ # Integration tests
+ e2e/ # End-to-end tests
+
+// Development Guidelines
+1. API Design:
+ - RESTful principles
+ - Resource naming
+ - Status codes
+ - Error handling
+ - Rate limiting
+ - Documentation
+
+2. Code Structure:
+ - Dependency injection
+ - Service layer
+ - Repository pattern
+ - Error handling
+ - Validation
+ - Logging
+
+3. Performance:
+ - Caching
+ - Database queries
+ - Memory usage
+ - Response time
+ - Compression
+ - Monitoring
+
+// Dependencies
+Core:
+- express: "^4.18.0"
+- typescript: "^5.0.0"
+- @types/express: "^4.17.17"
+- @types/node: "^18.16.0"
+
+Optional:
+- express-validator: "^7.0.0"
+- express-rate-limit: "^6.7.0"
+- helmet: "^7.0.0"
+- compression: "^1.7.4"
+
+// Code Examples:
+
+1. Controller Pattern:
+```typescript
+import { Request, Response, NextFunction } from 'express';
+import { UserService } from '@/services/user.service';
+import { CreateUserDto, UpdateUserDto } from '@/models/dtos/user.dto';
+import { ApiError } from '@/utils/errors/api-error';
+import { Logger } from '@/utils/logger';
+
+export class UserController {
+ constructor(
+ private userService: UserService,
+ private logger: Logger
+ ) {}
+
+ async create(req: Request, res: Response, next: NextFunction) {
+ try {
+ const dto = new CreateUserDto(req.body);
+ const user = await this.userService.create(dto);
+
+ this.logger.info('User created', { userId: user.id });
+ res.status(201).json(user);
+ } catch (error) {
+ this.logger.error('Failed to create user', { error });
+ next(new ApiError(400, 'Failed to create user'));
+ }
+ }
+
+ async update(req: Request, res: Response, next: NextFunction) {
+ try {
+ const { id } = req.params;
+ const dto = new UpdateUserDto(req.body);
+ const user = await this.userService.update(id, dto);
+
+ if (!user) {
+ throw new ApiError(404, 'User not found');
+ }
+
+ this.logger.info('User updated', { userId: id });
+ res.json(user);
+ } catch (error) {
+ this.logger.error('Failed to update user', { error, userId: req.params.id });
+ next(error);
+ }
+ }
+
+ async delete(req: Request, res: Response, next: NextFunction) {
+ try {
+ const { id } = req.params;
+ await this.userService.delete(id);
+
+ this.logger.info('User deleted', { userId: id });
+ res.status(204).send();
+ } catch (error) {
+ this.logger.error('Failed to delete user', { error, userId: req.params.id });
+ next(error);
+ }
+ }
+}
+```
+
+2. Service Pattern:
+```typescript
+import { Injectable } from '@/utils/di';
+import { UserRepository } from '@/models/repositories/user.repository';
+import { CreateUserDto, UpdateUserDto } from '@/models/dtos/user.dto';
+import { User } from '@/models/entities/user.entity';
+import { ApiError } from '@/utils/errors/api-error';
+import { Logger } from '@/utils/logger';
+
+@Injectable()
+export class UserService {
+ constructor(
+ private userRepository: UserRepository,
+ private logger: Logger
+ ) {}
+
+ async create(dto: CreateUserDto): Promise {
+ const existingUser = await this.userRepository.findByEmail(dto.email);
+
+ if (existingUser) {
+ throw new ApiError(400, 'Email already exists');
+ }
+
+ const user = new User(dto);
+ await this.userRepository.save(user);
+
+ this.logger.info('User created in service', { userId: user.id });
+ return user;
+ }
+
+ async update(id: string, dto: UpdateUserDto): Promise {
+ const user = await this.userRepository.findById(id);
+
+ if (!user) {
+ return null;
+ }
+
+ Object.assign(user, dto);
+ await this.userRepository.save(user);
+
+ this.logger.info('User updated in service', { userId: id });
+ return user;
+ }
+
+ async delete(id: string): Promise {
+ const user = await this.userRepository.findById(id);
+
+ if (!user) {
+ throw new ApiError(404, 'User not found');
+ }
+
+ await this.userRepository.delete(id);
+ this.logger.info('User deleted in service', { userId: id });
+ }
+}
+```
+
+3. Middleware Pattern:
+```typescript
+import { Request, Response, NextFunction } from 'express';
+import { verify } from 'jsonwebtoken';
+import { ApiError } from '@/utils/errors/api-error';
+import { Logger } from '@/utils/logger';
+import { config } from '@/config';
+
+export class AuthMiddleware {
+ constructor(private logger: Logger) {}
+
+ async authenticate(req: Request, res: Response, next: NextFunction) {
+ try {
+ const token = this.extractToken(req);
+
+ if (!token) {
+ throw new ApiError(401, 'No token provided');
+ }
+
+ const decoded = verify(token, config.jwt.secret);
+ req.user = decoded;
+
+ this.logger.debug('User authenticated', { userId: decoded.sub });
+ next();
+ } catch (error) {
+ this.logger.error('Authentication failed', { error });
+ next(new ApiError(401, 'Invalid token'));
+ }
+ }
+
+ private extractToken(req: Request): string | null {
+ const authHeader = req.headers.authorization;
+
+ if (!authHeader || !authHeader.startsWith('Bearer ')) {
+ return null;
+ }
+
+ return authHeader.split(' ')[1];
+ }
+}
+```
+
+// Best Practices:
+1. Code Quality:
+ - Type safety
+ - Error handling
+ - Input validation
+ - Documentation
+ - Testing
+ - Logging
+
+2. Architecture:
+ - Layered design
+ - Dependency injection
+ - Repository pattern
+ - Service pattern
+ - Middleware
+ - Error handling
+
+3. Performance:
+ - Query optimization
+ - Caching strategy
+ - Connection pooling
+ - Memory management
+ - Response time
+ - Monitoring
+
+4. Security:
+ - Authentication
+ - Authorization
+ - Input validation
+ - Rate limiting
+ - Headers security
+ - CORS policy
+
+// Security Considerations:
+1. API Security:
+ - Input validation
+ - Rate limiting
+ - Authentication
+ - Authorization
+ - CORS policy
+ - Security headers
+
+2. Data Security:
+ - Encryption
+ - Password hashing
+ - Data validation
+ - SQL injection
+ - XSS prevention
+ - CSRF protection
+
+3. Infrastructure:
+ - HTTPS
+ - Firewalls
+ - Monitoring
+ - Logging
+ - Backups
+ - Updates
\ No newline at end of file
diff --git a/rules/fastapi-python-cursorrules-prompt-file/.cursorrules b/rules/fastapi-python-cursorrules-prompt-file/.cursorrules
new file mode 100644
index 0000000..1862c85
--- /dev/null
+++ b/rules/fastapi-python-cursorrules-prompt-file/.cursorrules
@@ -0,0 +1,263 @@
+// FastAPI Python Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Python web API using FastAPI:
+- RESTful APIs
+- GraphQL APIs
+- WebSocket endpoints
+- Background tasks
+- File operations
+- Database integration
+- Authentication
+- Documentation
+
+// Project Structure
+src/
+ api/ # API endpoints
+ v1/ # API version 1
+ endpoints/ # Route handlers
+ schemas/ # Pydantic models
+ deps/ # Dependencies
+ middleware/ # Custom middleware
+ core/ # Core modules
+ config.py # Configuration
+ security.py # Security utils
+ logging.py # Logging setup
+ db/ # Database
+ models/ # SQLAlchemy models
+ migrations/ # Alembic migrations
+ session.py # DB session
+ services/ # Business logic
+ auth.py # Auth service
+ email.py # Email service
+ storage.py # Storage service
+ utils/ # Utilities
+ validators.py # Custom validators
+ helpers.py # Helper functions
+ main.py # Application entry
+tests/ # Test suite
+ api/ # API tests
+ services/ # Service tests
+ conftest.py # Test fixtures
+
+// Development Guidelines
+1. API Design:
+ - Type hints
+ - Pydantic models
+ - Path operations
+ - Query params
+ - Request body
+ - Response models
+
+2. Code Structure:
+ - Dependency injection
+ - Service layer
+ - Repository pattern
+ - Error handling
+ - Validation
+ - Logging
+
+3. Performance:
+ - Async operations
+ - Database queries
+ - Caching
+ - Background tasks
+ - Resource cleanup
+ - Monitoring
+
+// Dependencies
+Core:
+- fastapi: "^0.100.0"
+- uvicorn: "^0.22.0"
+- pydantic: "^2.0.0"
+- sqlalchemy: "^2.0.0"
+
+Optional:
+- alembic: "^1.11.0"
+- python-jose: "^3.3.0"
+- passlib: "^1.7.4"
+- python-multipart: "^0.0.6"
+
+// Code Examples:
+
+1. Router Pattern:
+```python
+from fastapi import APIRouter, Depends, HTTPException, status
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.deps import get_db
+from app.schemas.user import UserCreate, UserResponse
+from app.services.user import UserService
+
+router = APIRouter(prefix="/users", tags=["users"])
+
+@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
+async def create_user(
+ user_in: UserCreate,
+ db: AsyncSession = Depends(get_db),
+ user_service: UserService = Depends()
+):
+ try:
+ user = await user_service.create(db, user_in)
+ return user
+ except ValueError as e:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=str(e)
+ )
+
+@router.get("/{user_id}", response_model=UserResponse)
+async def get_user(
+ user_id: int,
+ db: AsyncSession = Depends(get_db),
+ user_service: UserService = Depends()
+):
+ user = await user_service.get(db, user_id)
+ if not user:
+ raise HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail="User not found"
+ )
+ return user
+```
+
+2. Service Pattern:
+```python
+from typing import Optional
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select
+
+from app.db.models.user import User
+from app.schemas.user import UserCreate
+from app.core.security import get_password_hash
+
+class UserService:
+ async def create(
+ self,
+ db: AsyncSession,
+ user_in: UserCreate
+ ) -> User:
+ # Check if user exists
+ result = await db.execute(
+ select(User).where(User.email == user_in.email)
+ )
+ if result.scalar_one_or_none():
+ raise ValueError("Email already registered")
+
+ # Create new user
+ user = User(
+ email=user_in.email,
+ hashed_password=get_password_hash(user_in.password),
+ full_name=user_in.full_name
+ )
+ db.add(user)
+ await db.commit()
+ await db.refresh(user)
+ return user
+
+ async def get(
+ self,
+ db: AsyncSession,
+ user_id: int
+ ) -> Optional[User]:
+ result = await db.execute(
+ select(User).where(User.id == user_id)
+ )
+ return result.scalar_one_or_none()
+
+ async def authenticate(
+ self,
+ db: AsyncSession,
+ email: str,
+ password: str
+ ) -> Optional[User]:
+ user = await self.get_by_email(db, email)
+ if not user or not verify_password(password, user.hashed_password):
+ return None
+ return user
+```
+
+3. Schema Pattern:
+```python
+from datetime import datetime
+from typing import Optional
+from pydantic import BaseModel, EmailStr, Field
+
+class UserBase(BaseModel):
+ email: EmailStr
+ full_name: str = Field(..., min_length=1, max_length=100)
+ is_active: bool = True
+
+class UserCreate(UserBase):
+ password: str = Field(..., min_length=8)
+
+class UserUpdate(UserBase):
+ password: Optional[str] = Field(None, min_length=8)
+
+class UserResponse(UserBase):
+ id: int
+ created_at: datetime
+ updated_at: datetime
+
+ class Config:
+ from_attributes = True
+```
+
+// Best Practices:
+1. Code Quality:
+ - Type hints
+ - Documentation
+ - Error handling
+ - Input validation
+ - Testing
+ - Logging
+
+2. Architecture:
+ - Layered design
+ - Dependency injection
+ - Repository pattern
+ - Service pattern
+ - Event handling
+ - Error handling
+
+3. Performance:
+ - Query optimization
+ - Caching strategy
+ - Connection pooling
+ - Memory management
+ - Response time
+ - Monitoring
+
+4. Security:
+ - Authentication
+ - Authorization
+ - Input validation
+ - Rate limiting
+ - Headers security
+ - CORS policy
+
+// Security Considerations:
+1. API Security:
+ - Input validation
+ - Rate limiting
+ - Authentication
+ - Authorization
+ - CORS policy
+ - Security headers
+
+2. Data Security:
+ - Encryption
+ - Password hashing
+ - Data validation
+ - SQL injection
+ - XSS prevention
+ - CSRF protection
+
+3. Infrastructure:
+ - HTTPS
+ - Firewalls
+ - Monitoring
+ - Logging
+ - Backups
+ - Updates
\ No newline at end of file
diff --git a/rules/flask-python-cursorrules-prompt-file/.cursorrules b/rules/flask-python-cursorrules-prompt-file/.cursorrules
new file mode 100644
index 0000000..48982d2
--- /dev/null
+++ b/rules/flask-python-cursorrules-prompt-file/.cursorrules
@@ -0,0 +1,269 @@
+// Flask Python Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Python web application using Flask:
+- Web applications
+- RESTful APIs
+- Admin interfaces
+- Authentication
+- File uploads
+- Database integration
+- Background tasks
+- Email handling
+
+// Project Structure
+project/
+ app/ # Application package
+ templates/ # Jinja2 templates
+ static/ # Static files
+ models/ # Database models
+ views/ # View functions
+ admin/ # Admin views
+ auth/ # Auth views
+ main/ # Main views
+ forms/ # WTForms classes
+ utils/ # Utility modules
+ extensions.py # Flask extensions
+ config.py # Configuration
+ migrations/ # Database migrations
+ tests/ # Test suite
+ unit/ # Unit tests
+ integration/ # Integration tests
+ conftest.py # Test fixtures
+ instance/ # Instance config
+ logs/ # Log files
+ requirements/ # Dependencies
+ dev.txt # Development deps
+ prod.txt # Production deps
+ wsgi.py # WSGI entry point
+
+// Development Guidelines
+1. Application Structure:
+ - Blueprints
+ - Extensions
+ - Models
+ - Views
+ - Forms
+ - Templates
+
+2. Code Organization:
+ - Dependency injection
+ - Service layer
+ - Repository pattern
+ - Error handling
+ - Validation
+ - Logging
+
+3. Performance:
+ - Caching
+ - Database queries
+ - Asset bundling
+ - Response time
+ - Memory usage
+ - Monitoring
+
+// Dependencies
+Core:
+- flask: "^2.3.0"
+- flask-sqlalchemy: "^3.0.0"
+- flask-migrate: "^4.0.0"
+- flask-login: "^0.6.0"
+
+Optional:
+- flask-admin: "^1.6.0"
+- flask-wtf: "^1.1.0"
+- flask-mail: "^0.9.0"
+- celery: "^5.3.0"
+
+// Code Examples:
+
+1. View Pattern:
+```python
+from flask import Blueprint, render_template, flash, redirect, url_for
+from flask_login import login_required, current_user
+
+from app.forms.post import PostForm
+from app.models.post import Post
+from app.extensions import db
+from app.utils.decorators import admin_required
+
+bp = Blueprint('blog', __name__)
+
+@bp.route('/posts')
+def list_posts():
+ """List all blog posts."""
+ posts = Post.query.order_by(Post.created_at.desc()).all()
+ return render_template('blog/list.html', posts=posts)
+
+@bp.route('/posts/new', methods=['GET', 'POST'])
+@login_required
+def create_post():
+ """Create a new blog post."""
+ form = PostForm()
+ if form.validate_on_submit():
+ post = Post(
+ title=form.title.data,
+ content=form.content.data,
+ author=current_user
+ )
+ db.session.add(post)
+ db.session.commit()
+ flash('Post created successfully.', 'success')
+ return redirect(url_for('blog.list_posts'))
+ return render_template('blog/create.html', form=form)
+
+@bp.route('/posts//edit', methods=['GET', 'POST'])
+@login_required
+@admin_required
+def edit_post(id):
+ """Edit an existing blog post."""
+ post = Post.query.get_or_404(id)
+ form = PostForm(obj=post)
+
+ if form.validate_on_submit():
+ post.title = form.title.data
+ post.content = form.content.data
+ db.session.commit()
+ flash('Post updated successfully.', 'success')
+ return redirect(url_for('blog.list_posts'))
+
+ return render_template('blog/edit.html', form=form, post=post)
+```
+
+2. Model Pattern:
+```python
+from datetime import datetime
+from app.extensions import db
+from app.utils.slugify import slugify
+
+class Post(db.Model):
+ """Blog post model."""
+
+ id = db.Column(db.Integer, primary_key=True)
+ title = db.Column(db.String(200), nullable=False)
+ slug = db.Column(db.String(200), unique=True, nullable=False)
+ content = db.Column(db.Text, nullable=False)
+ created_at = db.Column(db.DateTime, default=datetime.utcnow)
+ updated_at = db.Column(
+ db.DateTime,
+ default=datetime.utcnow,
+ onupdate=datetime.utcnow
+ )
+ author_id = db.Column(
+ db.Integer,
+ db.ForeignKey('user.id'),
+ nullable=False
+ )
+
+ # Relationships
+ author = db.relationship('User', back_populates='posts')
+ comments = db.relationship(
+ 'Comment',
+ back_populates='post',
+ cascade='all, delete-orphan'
+ )
+
+ def __init__(self, **kwargs):
+ """Create instance."""
+ super(Post, self).__init__(**kwargs)
+ if self.title:
+ self.slug = slugify(self.title)
+
+ def __repr__(self):
+ """Represent instance as a string."""
+ return f''
+
+ @property
+ def url(self):
+ """Get URL for post."""
+ return url_for('blog.show_post', slug=self.slug)
+```
+
+3. Form Pattern:
+```python
+from flask_wtf import FlaskForm
+from wtforms import StringField, TextAreaField, BooleanField
+from wtforms.validators import DataRequired, Length, Email
+
+class PostForm(FlaskForm):
+ """Form for creating or editing a blog post."""
+
+ title = StringField(
+ 'Title',
+ validators=[
+ DataRequired(),
+ Length(min=3, max=200)
+ ]
+ )
+
+ content = TextAreaField(
+ 'Content',
+ validators=[DataRequired()]
+ )
+
+ is_published = BooleanField('Publish?', default=True)
+
+ def validate_title(self, field):
+ """Custom validation for title."""
+ if Post.query.filter_by(title=field.data).first():
+ raise ValidationError('Title must be unique.')
+```
+
+// Best Practices:
+1. Code Quality:
+ - Documentation
+ - Type hints
+ - Error handling
+ - Input validation
+ - Testing
+ - Logging
+
+2. Architecture:
+ - Blueprints
+ - Extensions
+ - Models
+ - Services
+ - Forms
+ - Templates
+
+3. Performance:
+ - Query optimization
+ - Caching strategy
+ - Asset bundling
+ - Response time
+ - Memory usage
+ - Monitoring
+
+4. Security:
+ - Authentication
+ - Authorization
+ - CSRF protection
+ - XSS prevention
+ - Input validation
+ - Session security
+
+// Security Considerations:
+1. Application Security:
+ - Input validation
+ - CSRF protection
+ - XSS prevention
+ - Session security
+ - Password hashing
+ - Access control
+
+2. Data Security:
+ - SQL injection
+ - Data validation
+ - File uploads
+ - User data
+ - Backups
+ - Encryption
+
+3. Infrastructure:
+ - HTTPS
+ - Firewalls
+ - Monitoring
+ - Logging
+ - Updates
+ - Deployment
\ No newline at end of file
diff --git a/rules/flutter-dart-cursorrules-prompt-file/.cursorrules b/rules/flutter-dart-cursorrules-prompt-file/.cursorrules
new file mode 100644
index 0000000..e3e9075
--- /dev/null
+++ b/rules/flutter-dart-cursorrules-prompt-file/.cursorrules
@@ -0,0 +1,335 @@
+// Flutter Dart Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern cross-platform mobile application using Flutter:
+- Material Design apps
+- iOS-style apps
+- Custom UI/UX
+- State management
+- API integration
+- Local storage
+- Push notifications
+- Animations
+
+// Project Structure
+lib/
+ core/ # Core functionality
+ constants/ # App constants
+ theme/ # App theme
+ utils/ # Utilities
+ data/ # Data layer
+ models/ # Data models
+ repositories/ # Data repositories
+ services/ # API services
+ domain/ # Business logic
+ entities/ # Business entities
+ usecases/ # Business use cases
+ presentation/ # UI layer
+ screens/ # App screens
+ widgets/ # Reusable widgets
+ blocs/ # State management
+ app.dart # App entry point
+test/ # Test suite
+ unit/ # Unit tests
+ widget/ # Widget tests
+ integration/ # Integration tests
+assets/ # App assets
+ images/ # Image files
+ fonts/ # Font files
+ icons/ # Icon files
+
+// Development Guidelines
+1. UI Development:
+ - Widget composition
+ - State management
+ - Navigation
+ - Theming
+ - Responsive design
+ - Accessibility
+
+2. Code Structure:
+ - Clean architecture
+ - SOLID principles
+ - Dependency injection
+ - Error handling
+ - Logging
+ - Testing
+
+3. Performance:
+ - Widget rebuilds
+ - Memory usage
+ - Image optimization
+ - Animation smoothness
+ - App size
+ - Loading time
+
+// Dependencies
+Core:
+- flutter_sdk: "^3.10.0"
+- provider: "^6.0.0"
+- dio: "^5.0.0"
+- hive: "^2.2.0"
+
+Optional:
+- flutter_bloc: "^8.1.0"
+- get_it: "^7.6.0"
+- injectable: "^2.1.0"
+- freezed: "^2.3.0"
+
+// Code Examples:
+
+1. Widget Pattern:
+```dart
+import 'package:flutter/material.dart';
+import 'package:provider/provider.dart';
+
+class ProductList extends StatelessWidget {
+ const ProductList({Key? key}) : super(key: key);
+
+ @override
+ Widget build(BuildContext context) {
+ return Consumer(
+ builder: (context, provider, child) {
+ if (provider.isLoading) {
+ return const Center(
+ child: CircularProgressIndicator(),
+ );
+ }
+
+ if (provider.error != null) {
+ return Center(
+ child: Text(
+ 'Error: ${provider.error}',
+ style: Theme.of(context).textTheme.bodyLarge?.copyWith(
+ color: Colors.red,
+ ),
+ ),
+ );
+ }
+
+ return ListView.builder(
+ itemCount: provider.products.length,
+ itemBuilder: (context, index) {
+ final product = provider.products[index];
+ return ProductCard(
+ product: product,
+ onTap: () => Navigator.pushNamed(
+ context,
+ '/product-details',
+ arguments: product,
+ ),
+ );
+ },
+ );
+ },
+ );
+ }
+}
+
+class ProductCard extends StatelessWidget {
+ final Product product;
+ final VoidCallback onTap;
+
+ const ProductCard({
+ Key? key,
+ required this.product,
+ required this.onTap,
+ }) : super(key: key);
+
+ @override
+ Widget build(BuildContext context) {
+ return Card(
+ elevation: 2,
+ margin: const EdgeInsets.symmetric(
+ horizontal: 16,
+ vertical: 8,
+ ),
+ child: ListTile(
+ leading: Hero(
+ tag: 'product-${product.id}',
+ child: Image.network(
+ product.imageUrl,
+ width: 56,
+ height: 56,
+ fit: BoxFit.cover,
+ ),
+ ),
+ title: Text(product.name),
+ subtitle: Text(
+ '\$${product.price.toStringAsFixed(2)}',
+ style: Theme.of(context).textTheme.bodyMedium?.copyWith(
+ color: Colors.green,
+ ),
+ ),
+ trailing: const Icon(Icons.chevron_right),
+ onTap: onTap,
+ ),
+ );
+ }
+}
+```
+
+2. Provider Pattern:
+```dart
+import 'package:flutter/foundation.dart';
+import 'package:dio/dio.dart';
+
+class ProductsProvider with ChangeNotifier {
+ final ProductRepository _repository;
+ List _products = [];
+ bool _isLoading = false;
+ String? _error;
+
+ ProductsProvider(this._repository);
+
+ List get products => _products;
+ bool get isLoading => _isLoading;
+ String? get error => _error;
+
+ Future fetchProducts() async {
+ _isLoading = true;
+ _error = null;
+ notifyListeners();
+
+ try {
+ _products = await _repository.getProducts();
+ } on DioError catch (e) {
+ _error = e.message;
+ } catch (e) {
+ _error = 'An unexpected error occurred';
+ } finally {
+ _isLoading = false;
+ notifyListeners();
+ }
+ }
+
+ Future addProduct(Product product) async {
+ _isLoading = true;
+ notifyListeners();
+
+ try {
+ final newProduct = await _repository.addProduct(product);
+ _products.add(newProduct);
+ } catch (e) {
+ _error = 'Failed to add product';
+ } finally {
+ _isLoading = false;
+ notifyListeners();
+ }
+ }
+}
+```
+
+3. Repository Pattern:
+```dart
+import 'package:dio/dio.dart';
+import 'package:injectable/injectable.dart';
+
+@injectable
+class ProductRepository {
+ final Dio _dio;
+ final String _baseUrl;
+
+ ProductRepository(
+ this._dio,
+ @Named('baseUrl') this._baseUrl,
+ );
+
+ Future> getProducts() async {
+ try {
+ final response = await _dio.get('$_baseUrl/products');
+ return (response.data as List)
+ .map((json) => Product.fromJson(json))
+ .toList();
+ } on DioError {
+ rethrow;
+ } catch (e) {
+ throw Exception('Failed to fetch products');
+ }
+ }
+
+ Future getProduct(String id) async {
+ try {
+ final response = await _dio.get('$_baseUrl/products/$id');
+ return Product.fromJson(response.data);
+ } on DioError {
+ rethrow;
+ } catch (e) {
+ throw Exception('Failed to fetch product');
+ }
+ }
+
+ Future addProduct(Product product) async {
+ try {
+ final response = await _dio.post(
+ '$_baseUrl/products',
+ data: product.toJson(),
+ );
+ return Product.fromJson(response.data);
+ } on DioError {
+ rethrow;
+ } catch (e) {
+ throw Exception('Failed to add product');
+ }
+ }
+}
+```
+
+// Best Practices:
+1. Code Quality:
+ - Documentation
+ - Type safety
+ - Error handling
+ - Testing
+ - Logging
+ - Code style
+
+2. Architecture:
+ - Clean architecture
+ - SOLID principles
+ - Dependency injection
+ - State management
+ - Navigation
+ - Error handling
+
+3. Performance:
+ - Widget optimization
+ - Memory management
+ - Image caching
+ - Lazy loading
+ - Build methods
+ - State updates
+
+4. UI/UX:
+ - Material Design
+ - iOS guidelines
+ - Responsive design
+ - Accessibility
+ - Animations
+ - User feedback
+
+// Security Considerations:
+1. Data Security:
+ - Secure storage
+ - API security
+ - Input validation
+ - Authentication
+ - Authorization
+ - Encryption
+
+2. Code Security:
+ - Dependencies
+ - Platform channels
+ - Web security
+ - Deep links
+ - File access
+ - Permissions
+
+3. Network Security:
+ - HTTPS
+ - Certificate pinning
+ - API tokens
+ - OAuth flows
+ - Rate limiting
+ - Request signing
\ No newline at end of file
diff --git a/rules/github-code-quality-cursorrules-prompt-file/.cursorrules b/rules/github-code-quality-cursorrules-prompt-file/.cursorrules
index bdf63cb..7690372 100644
--- a/rules/github-code-quality-cursorrules-prompt-file/.cursorrules
+++ b/rules/github-code-quality-cursorrules-prompt-file/.cursorrules
@@ -1 +1,156 @@
-{"rules": [{"name": "Verify Information","pattern": "(?i)\b(assume|assumption|guess|speculate)\b","message": "Always verify information before presenting it. Do not make assumptions or speculate without clear evidence."},{"name": "File-by-File Changes","pattern": "// MULTI-FILE CHANGE:","message": "Make changes file by file and give me a chance to spot mistakes"},{"name": "No Apologies","pattern": "(?i)\b(sorry|apologize|apologies)\b","message": "Never use apologies"},{"name": "No Understanding Feedback","pattern": "(?i)\b(understand|understood|got it)\b","message": "Avoid giving feedback about understanding in comments or documentation"},{"name": "No Whitespace Suggestions","pattern": "(?i)\b(whitespace|indentation|spacing)\b","message": "Don't suggest whitespace changes"},{"name": "No Summaries","pattern": "(?i)\b(summary|summarize|overview)\b","message": "Don't summarize changes made"},{"name": "No Inventions","pattern": "(?i)\b(suggest|recommendation|propose)\b","message": "Don't invent changes other than what's explicitly requested"},{"name": "No Unnecessary Confirmations","pattern": "(?i)\b(make sure|confirm|verify|check)\b","message": "Don't ask for confirmation of information already provided in the context"},{"name": "Preserve Existing Code","pattern": "(?i)\b(remove|delete|eliminate|destroy)\b","message": "Don't remove unrelated code or functionalities. Pay attention to preserving existing structures."},{"name": "Single Chunk Edits","pattern": "(?i)\b(first|then|next|after that|finally)\b","message": "Provide all edits in a single chunk instead of multiple-step instructions or explanations for the same file"},{"name": "No Implementation Checks","pattern": "(?i)\b(make sure|verify|check|confirm) (it's|it is|that) (correctly|properly) implemented\b","message": "Don't ask the user to verify implementations that are visible in the provided context"},{"name": "No Unnecessary Updates","pattern": "(?i)\b(update|change|modify|alter)\b.*\bno changes\b","message": "Don't suggest updates or changes to files when there are no actual modifications needed"},{"name": "Provide Real File Links","pattern": "(?i)\b(file|in)\b.*\b(x\.md)\b","message": "Always provide links to the real files, not x.md"},{"name": "No Previous x.md Consideration","pattern": "(?i)\b(previous|earlier|last)\b.*\bx\.md\b","message": "Do not consider any previous x.md files in your memory. Complain if the contents are the same as previous runs."},{"name": "No Current Implementation","pattern": "(?i)\b(current|existing)\s+(implementation|code)\b","message": "Don't show or discuss the current implementation unless specifically requested"},{"name": "Check x.md Content","pattern": "(?i)\b(file|content|implementation)\b","message": "Remember to check the x.md file for the current file contents and implementations"}]}
\ No newline at end of file
+// GitHub Code Quality Expert Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A production-ready GitHub repository with:
+- Automated code quality checks
+- Standardized review processes
+- Consistent code style enforcement
+- Comprehensive documentation
+- Security best practices
+- Efficient CI/CD pipelines
+
+// Project Structure
+.github/
+ workflows/ # GitHub Actions configurations
+ quality.yml # Code quality checks
+ security.yml # Security scans
+ ISSUE_TEMPLATE/ # Issue templates
+ PULL_REQUEST_TEMPLATE/ # PR templates
+docs/ # Documentation
+ CODE_OF_CONDUCT.md # Code of conduct
+ CONTRIBUTING.md # Contribution guidelines
+ SECURITY.md # Security policies
+tests/ # Test suites
+scripts/ # Development scripts
+
+// Development Guidelines
+1. Code Review:
+ - Verify all information before presenting
+ - Make changes file by file
+ - Focus on functionality over formatting
+ - Preserve existing code structure
+ - Provide complete changes in single reviews
+ - Link to actual files in documentation
+
+2. Documentation:
+ - Maintain clear, concise documentation
+ - Avoid unnecessary explanations
+ - Document real implementations
+ - Keep documentation up-to-date
+ - Include security considerations
+ - Provide clear setup instructions
+
+3. Quality Checks:
+ - Implement automated testing
+ - Use static code analysis
+ - Monitor code coverage
+ - Check dependencies regularly
+ - Validate documentation links
+ - Review security alerts
+
+// Dependencies
+Core:
+- github_actions: "latest"
+- code_coverage: "latest"
+- linters: "latest"
+- security_scanners: "latest"
+
+Optional:
+- documentation_tools: "latest"
+- automated_testing: "latest"
+- dependency_management: "latest"
+- code_quality_metrics: "latest"
+
+// Code Examples:
+
+1. GitHub Workflow Pattern:
+```yaml
+name: Code Quality
+
+on:
+ push:
+ branches: [ main ]
+ pull_request:
+ branches: [ main ]
+
+jobs:
+ quality:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+ - name: Run linters
+ uses: github/super-linter@v4
+ - name: Run tests
+ run: |
+ npm install
+ npm test
+ - name: Check coverage
+ uses: coverallsapp/github-action@v2
+```
+
+2. Pull Request Template Pattern:
+```markdown
+## Description
+
+Please include a summary of the changes and the related issue.
+
+## Type of change
+
+- [ ] Bug fix
+- [ ] New feature
+- [ ] Breaking change
+- [ ] Documentation update
+
+## Checklist
+
+- [ ] My code follows the style guidelines
+- [ ] I have performed a self-review
+- [ ] I have added tests
+- [ ] Documentation has been updated
+```
+
+3. Security Policy Pattern:
+```markdown
+# Security Policy
+
+## Supported Versions
+
+| Version | Supported |
+| ------- | ------------------ |
+| 5.1.x | :white_check_mark: |
+| 5.0.x | :x: |
+| 4.0.x | :white_check_mark: |
+| < 4.0 | :x: |
+
+## Reporting a Vulnerability
+
+1. **Do not** open a public issue
+2. Email security@example.com
+3. Expect response within 48 hours
+4. Regular updates on reported vulnerabilities
+```
+
+// Best Practices:
+1. Always verify information before presenting
+2. Make changes file by file
+3. Avoid unnecessary formatting changes
+4. Preserve existing code functionality
+5. Provide complete changes in single reviews
+6. Use real file references
+7. Keep documentation current
+8. Implement automated testing
+9. Monitor code quality metrics
+10. Regular security reviews
+
+// Security Considerations:
+1. Regular dependency updates
+2. Code scanning enabled
+3. Security policy defined
+4. Access control implemented
+5. Secrets management
+6. Vulnerability monitoring
+7. Regular security audits
+8. Secure development practices
+9. Documentation security
+10. Compliance checks
\ No newline at end of file
diff --git a/rules/github-cursorrules-prompt-file-instructions/.cursorrules b/rules/github-cursorrules-prompt-file-instructions/.cursorrules
index ce0df58..ce4256f 100644
--- a/rules/github-cursorrules-prompt-file-instructions/.cursorrules
+++ b/rules/github-cursorrules-prompt-file-instructions/.cursorrules
@@ -1 +1,170 @@
-Writing code is like giving a speech. If you use too many big words, you confuse your audience. Define every word, and you end up putting your audience to sleep. Similarly, when you write code, you shouldn't just focus on making it work. You should also aim to make it readable, understandable, and maintainable for future readers. To paraphrase software engineer Martin Fowler, "Anybody can write code that a computer can understand. Good programmers write code that humans can understand."As software developers, understanding how to write clean code that is functional, easy to read, and adheres to best practices helps you create better software consistently.This article discusses what clean code is and why it's essential and provides principles and best practices for writing clean and maintainable code.What Is Clean Code?Clean code is a term used to refer to code that is easy to read, understand, and maintain. It was made popular by Robert Cecil Martin, also known as Uncle Bob, who wrote "Clean Code: A Handbook of Agile Software Craftsmanship" in 2008. In this book, he presented a set of principles and best practices for writing clean code, such as using meaningful names, short functions, clear comments, and consistent formatting.Ultimately, the goal of clean code is to create software that is not only functional but also readable, maintainable, and efficient throughout its lifecycle. Why Is Clean Code Important?When teams adhere to clean code principles, the code base is easier to read and navigate, which makes it faster for developers to get up to speed and start contributing. Here are some reasons why clean code is essential.Readability and maintenance: Clean code prioritizes clarity, which makes reading, understanding, and modifying code easier. Writing readable code reduces the time required to grasp the code's functionality, leading to faster development times.Team collaboration: Clear and consistent code facilitates communication and cooperation among team members. By adhering to established coding standards and writing readable code, developers easily understand each other's work and collaborate more effectively.Debugging and issue resolution: Clean code is designed with clarity and simplicity, making it easier to locate and understand specific sections of the codebase. Clear structure, meaningful variable names, and well-defined functions make it easier to identify and resolve issues.Improved quality and reliability: Clean code prioritizes following established coding standards and writing well-structured code. This reduces the risk of introducing errors, leading to higher-quality and more reliable software down the line.Now that we understand why clean code is essential, let's delve into some best practices and principles to help you write clean code.Principles of Clean CodeLike a beautiful painting needs the right foundation and brushstrokes, well-crafted code requires adherence to specific principles. These principles help developers write code that is clear, concise, and, ultimately, a joy to work with.Let's dive in.1. Avoid Hard-Coded NumbersUse named constants instead of hard-coded values. Write constants with meaningful names that convey their purpose. This improves clarity and makes it easier to modify the code.Example:The example below uses the hard-coded number 0.1 to represent a 10% discount. This makes it difficult to understand the meaning of the number (without a comment) and adjust the discount rate if needed in other parts of the function.Before:def calculate_discount(price): discount = price * 0.1 # 10% discount return price - discountThe improved code replaces the hard-coded number with a named constant TEN_PERCENT_DISCOUNT. The name instantly conveys the meaning of the value, making the code more self-documenting. After :def calculate_discount(price): TEN_PERCENT_DISCOUNT = 0.1 discount = price * TEN_PERCENT_DISCOUNT return price - discountAlso, If the discount rate needs to be changed, it only requires modifying the constant declaration, not searching for multiple instances of the hard-coded number.2. Use Meaningful and Descriptive NamesChoose names for variables, functions, and classes that reflect their purpose and behavior. This makes the code self-documenting and easier to understand without extensive comments. As Robert Martin puts it, “A name should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its intent.”Example:If we take the code from the previous example, it uses generic names like "price" and "discount," which leaves their purpose ambiguous. Names like "price" and "discount" could be interpreted differently without context. Before:def calculate_discount(price): TEN_PERCENT_DISCOUNT = 0.1 discount = price * TEN_PERCENT_DISCOUNT return price - discountInstead, you can declare the variables to be more descriptive.After:def calculate_discount(product_price): TEN_PERCENT_DISCOUNT = 0.1 discount_amount = product_price * TEN_PERCENT_DISCOUNT return product_price - discount_amountThis improved code uses specific names like "product_price" and "discount_amount," providing a clearer understanding of what the variables represent and how we use them.3. Use Comments Sparingly, and When You Do, Make Them MeaningfulYou don't need to comment on obvious things. Excessive or unclear comments can clutter the codebase and become outdated, leading to confusion and a messy codebase.Example:Before:def group_users_by_id(user_id): # This function groups users by id # ... complex logic ... # ... more code …The comment about the function is redundant and adds no value. The function name already states that it groups users by id; there's no need for a comment stating the same.Instead, use comments to convey the "why" behind specific actions or explain behaviors.After:def group_users_by_id(user_id): """Groups users by id to a specific category (1-9). Warning: Certain characters might not be handled correctly. Please refer to the documentation for supported formats. Args: user_id (str): The user id to be grouped. Returns: int: The category number (1-9) corresponding to the user id. Raises: ValueError: If the user id is invalid or unsupported. """ # ... complex logic ... # ... more code …This comment provides meaningful information about the function's behavior and explains unusual behavior and potential pitfalls.4. Write Short Functions That Only Do One ThingFollow the single responsibility principle (SRP), which means that a function should have one purpose and perform it effectively. Functions are more understandable, readable, and maintainable if they only have one job. It also makes testing them very easy. If a function becomes too long or complex, consider breaking it into smaller, more manageable functions.Example:Before:def process_data(data): # ... validate users... # ... calculate values ... # ... format output …This function performs three tasks: validating users, calculating values, and formatting output. If any of these steps fail, the entire function fails, making debugging a complex issue. If we also need to change the logic of one of the tasks, we risk introducing unintended side effects in another task.Instead, try to assign each task a function that does just one thing. After:def validate_user(data): # ... data validation logic ...def calculate_values(data): # ... calculation logic based on validated data ...def format_output(data): # ... format results for display …The improved code separates the tasks into distinct functions. This results in more readable, maintainable, and testable code. Also, If a change needs to be made, it will be easier to identify and modify the specific function responsible for the desired functionality. 5. Follow the DRY (Don't Repeat Yourself) Principle and Avoid Duplicating Code or LogicAvoid writing the same code more than once. Instead, reuse your code using functions, classes, modules, libraries, or other abstractions. This makes your code more efficient, consistent, and maintainable. It also reduces the risk of errors and bugs as you only need to modify your code in one place if you need to change or update it.Example:Before:def calculate_book_price(quantity, price): return quantity * pricedef calculate_laptop_price(quantity, price): return quantity * priceIn the above example, both functions calculate the total price using the same formula. This violates the DRY principle.We can fix this by defining a single calculate_product_price function that we use for books and laptops. This reduces code duplication and helps improve the maintenance of the codebase. After:def calculate_product_price(product_quantity, product_price): return product_quantity * product_price6. Follow Established Code-Writing StandardsKnow your programming language's conventions in terms of spacing, comments, and naming. Most programming languages have community-accepted coding standards and style guides, for example, PEP 8 for Python and Google JavaScript Style Guide for JavaScript. Here are some specific examples:Java:Use camelCase for variable, function, and class names.Indent code with four spaces.Put opening braces on the same line.Python:Use snake_case for variable, function, and class names.Use spaces over tabs for indentation.Put opening braces on the same line as the function or class declaration.JavaScript:Use camelCase for variable and function names.Use snake_case for object properties.Indent code with two spaces.Put opening braces on the same line as the function or class declaration.Also, consider extending some of these standards by creating internal coding rules for your organization. This can contain information on creating and naming folders or describing function names within your organization.7. Encapsulate Nested Conditionals into FunctionsOne way to improve the readability and clarity of functions is to encapsulate nested if/else statements into other functions. Encapsulating such logic into a function with a descriptive name clarifies its purpose and simplifies code comprehension. In some cases, it also makes it easier to reuse, modify, and test the logic without affecting the rest of the function.In the code sample below, the discount logic is nested within the calculate_product_discount function, making it difficult to understand at a glance.Example:Before:def calculate_product_discount(product_price): discount_amount = 0 if product_price > 100: discount_amount = product_price * 0.1 elif price > 50: discount_amount = product_price * 0.05 else: discount_amount = 0 final_product_price = product_price - discount_amount return final_product_priceWe can clean this code up by separating the nested if/else condition that calculates discount logic into another function called get_discount_rate and then calling the get_discount_rate in the calculate_product_discount function. This makes it easier to read at a glance. The get_discount_rate is now isolated and can be reused by other functions in the codebase. It’s also easier to change, test, and debug it without affecting the calculate_discount function.After:def calculate_discount(product_price): discount_rate = get_discount_rate(product_price) discount_amount = product_price * discount_rate final_product_price = product_price - discount_amount return final_product_pricedef get_discount_rate(product_price): if product_price > 100: return 0.1 elif product_price > 50: return 0.05 else: return 08. Refactor ContinuouslyRegularly review and refactor your code to improve its structure, readability, and maintainability. Consider the readability of your code for the next person who will work on it, and always leave the codebase cleaner than you found it.9. Use Version ControlVersion control systems meticulously track every change made to your codebase, enabling you to understand the evolution of your code and revert to previous versions if needed. This creates a safety net for code refactoring and prevents accidental deletions or overwrites.Use version control systems like GitHub, GitLab, and Bitbucket to track changes to your codebase and collaborate effectively with others.
\ No newline at end of file
+// GitHub Clean Code Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A maintainable and professional GitHub codebase with:
+- Clean, readable code structure
+- Consistent naming conventions
+- Efficient code organization
+- Proper documentation
+- Reusable components
+- Testable functions
+
+// Project Structure
+src/
+ components/ # Reusable code components
+ constants/ # Named constants
+ utils/ # Utility functions
+ validators/ # Input validation
+ core/ # Core business logic
+ services/ # Business services
+ models/ # Data models
+ tests/ # Test suites
+ unit/ # Unit tests
+ integration/ # Integration tests
+ docs/ # Documentation
+ guides/ # Usage guides
+ api/ # API documentation
+
+// Development Guidelines
+1. Code Organization:
+ - Use meaningful and descriptive names
+ - Write short, focused functions
+ - Follow single responsibility principle
+ - Avoid code duplication (DRY)
+ - Encapsulate complex logic
+ - Use proper indentation
+
+2. Code Standards:
+ - Follow language conventions
+ - Use consistent formatting
+ - Apply proper spacing
+ - Implement naming patterns
+ - Structure files consistently
+ - Document public interfaces
+
+3. Code Quality:
+ - Write self-documenting code
+ - Avoid hard-coded values
+ - Use meaningful comments
+ - Handle errors properly
+ - Write testable code
+ - Refactor regularly
+
+// Dependencies
+Core:
+- eslint: "^8.0.0"
+- prettier: "^2.0.0"
+- jest: "^27.0.0"
+- typescript: "^4.0.0"
+
+Optional:
+- husky: "^7.0.0"
+- commitlint: "^13.0.0"
+- lint-staged: "^11.0.0"
+- typedoc: "^0.22.0"
+
+// Code Examples:
+
+1. Clean Function Pattern:
+```typescript
+// Before
+function calc(p: number): number {
+ const d = p * 0.1;
+ return p - d;
+}
+
+// After
+function calculateDiscount(productPrice: number): number {
+ const TEN_PERCENT_DISCOUNT = 0.1;
+ const discountAmount = productPrice * TEN_PERCENT_DISCOUNT;
+ return productPrice - discountAmount;
+}
+```
+
+2. Single Responsibility Pattern:
+```typescript
+// Before
+function processData(data: any) {
+ // Validate
+ if (!data.user) throw new Error('Invalid user');
+
+ // Calculate
+ const total = data.items.reduce((sum, item) => sum + item.price, 0);
+
+ // Format
+ return `Total: $${total.toFixed(2)}`;
+}
+
+// After
+function validateUserData(data: any): void {
+ if (!data.user) throw new Error('Invalid user');
+}
+
+function calculateTotal(items: Item[]): number {
+ return items.reduce((sum, item) => sum + item.price, 0);
+}
+
+function formatCurrency(amount: number): string {
+ return `Total: $${amount.toFixed(2)}`;
+}
+
+function processData(data: any): string {
+ validateUserData(data);
+ const total = calculateTotal(data.items);
+ return formatCurrency(total);
+}
+```
+
+3. Encapsulation Pattern:
+```typescript
+// Before
+if (user.age >= 18 && user.country === 'US' && !user.restricted) {
+ // Allow access
+}
+
+// After
+function canAccessService(user: User): boolean {
+ return (
+ isAdult(user.age) &&
+ isFromSupportedCountry(user.country) &&
+ !isRestricted(user)
+ );
+}
+
+function isAdult(age: number): boolean {
+ return age >= 18;
+}
+
+function isFromSupportedCountry(country: string): boolean {
+ return country === 'US';
+}
+
+function isRestricted(user: User): boolean {
+ return user.restricted;
+}
+```
+
+// Best Practices:
+1. Use descriptive variable names
+2. Keep functions small and focused
+3. Follow DRY principle
+4. Write self-documenting code
+5. Use proper error handling
+6. Implement consistent formatting
+7. Write comprehensive tests
+8. Refactor regularly
+9. Use version control effectively
+10. Document complex logic
+
+// Security Considerations:
+1. Validate all inputs
+2. Sanitize user data
+3. Handle errors securely
+4. Use proper authentication
+5. Implement authorization
+6. Avoid security anti-patterns
+7. Keep dependencies updated
+8. Use secure configurations
+9. Implement proper logging
+10. Follow security guidelines
\ No newline at end of file
diff --git a/rules/go-backend-scalability-cursorrules-prompt-file/.cursorrules b/rules/go-backend-scalability-cursorrules-prompt-file/.cursorrules
index 567a21a..d3b71f0 100644
--- a/rules/go-backend-scalability-cursorrules-prompt-file/.cursorrules
+++ b/rules/go-backend-scalability-cursorrules-prompt-file/.cursorrules
@@ -1 +1,235 @@
-You are an AI Pair Programming Assistant with extensive expertise in backend software engineering. Your knowledge spans a wide range of technologies, practices, and concepts commonly used in modern backend systems. Your role is to provide comprehensive, insightful, and practical advice on various backend development topics.Your areas of expertise include, but are not limited to:1. Database Management (SQL, NoSQL, NewSQL)2. API Development (REST, GraphQL, gRPC)3. Server-Side Programming (Go, Rust, Java, Python, Node.js)4. Performance Optimization5. Scalability and Load Balancing6. Security Best Practices7. Caching Strategies8. Data Modeling9. Microservices Architecture10. Testing and Debugging11. Logging and Monitoring12. Containerization and Orchestration13. CI/CD Pipelines14. Docker and Kubernetes15. gRPC and Protocol Buffers16. Git Version Control17. Data Infrastructure (Kafka, RabbitMQ, Redis)18. Cloud Platforms (AWS, GCP, Azure)When responding to queries:1. Begin with a section where you: - Analyze the query to identify the main topics and technologies involved - Consider the broader context and implications of the question - Plan your approach to answering the query comprehensively2. Provide clear, concise explanations of backend concepts and technologies3. Offer practical advice and best practices for real-world scenarios4. Share code snippets or configuration examples when appropriate, using proper formatting and syntax highlighting5. Explain trade-offs between different approaches when multiple solutions exist6. Consider scalability, performance, and security implications in your recommendations7. Reference official documentation or reputable sources when needed, but note that you don't have access to real-time information8. End your response with an section that summarizes the key points and provides a direct answer to the queryYour goal is to help users understand, implement, and optimize backend systems while adhering to industry best practices and standards. Always consider factors such as scalability, reliability, maintainability, and security in your recommendations.If a query is unclear or lacks necessary details, ask for clarification before providing an answer. If a question is outside the scope of backend development, politely inform the user and offer to assist with related backend topics if possible.Here's an example of how to structure your response:You:To answer this query, I need to consider:1. The basics of gRPC and Protocol Buffers2. Go programming for gRPC server implementation3. Database interaction using Go's database/sql package or an ORM4. Best practices for structuring a gRPC service5. Error handling and data validationI'll provide a step-by-step guide with code examples to illustrate the implementation.1. Define your Protocol Buffer messages and service: Create a file named `service.proto`: ```protobuf syntax = "proto3"; package myservice; option go_package = "./pb"; message User { int32 id = 1; string name = 2; string email = 3; } message GetUserRequest { int32 id = 1; } service UserService { rpc GetUser(GetUserRequest) returns (User) {} } ```2. Generate Go code from the Proto file: ``` protoc --go_out=. --go-grpc_out=. service.proto ```3. Implement the gRPC server in Go: ```go package main import ( "context" "database/sql" "log" "net" "google.golang.org/grpc" "github.com/lib/pq" pb "your_project/pb" ) type server struct { pb.UnimplementedUserServiceServer db *sql.DB } func (s *server) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.User, error) { var user pb.User err := s.db.QueryRow("SELECT id, name, email FROM users WHERE id = $1", req.Id).Scan(&user.Id, &user.Name, &user.Email) if err != nil { return nil, err } return &user, nil } func main() { // Connect to PostgreSQL db, err := sql.Open("postgres", "postgresql://username:password@localhost/dbname?sslmode=disable") if err != nil { log.Fatalf("Failed to connect to database: %v", err) } defer db.Close() // Create gRPC server s := grpc.NewServer() pb.RegisterUserServiceServer(s, &server{db: db}) // Start listening lis, err := net.Listen("tcp", ":50051") if err != nil { log.Fatalf("Failed to listen: %v", err) } log.Println("Server listening on :50051") if err := s.Serve(lis); err != nil { log.Fatalf("Failed to serve: %v", err) } } ```This example demonstrates:- Defining a simple gRPC service using Protocol Buffers- Implementing the service in Go- Connecting to a PostgreSQL database- Handling a basic database query within a gRPC methodRemember to handle errors properly, implement proper validation, and consider using an ORM like GORM for more complex database interactions. Also, ensure you're following best practices for security, such as using prepared statements to prevent SQL injection.By following this structure and guidelines, you'll provide comprehensive and practical assistance for backend software engineering queries.
\ No newline at end of file
+// Go Backend Scalability Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A scalable Go backend system with:
+- High-performance API endpoints
+- Efficient database operations
+- Microservices architecture
+- Load balancing capabilities
+- Caching strategies
+- Monitoring and logging
+
+// Project Structure
+src/
+ api/ # API layer
+ handlers/ # Request handlers
+ middleware/ # HTTP middleware
+ routes/ # Route definitions
+ internal/ # Internal packages
+ models/ # Data models
+ services/ # Business logic
+ database/ # Database operations
+ cache/ # Caching layer
+ pkg/ # Shared packages
+ logger/ # Logging utilities
+ config/ # Configuration
+ metrics/ # Monitoring metrics
+ cmd/ # Application entrypoints
+ server/ # Main server
+ worker/ # Background workers
+ deployments/ # Deployment configs
+ docker/ # Docker files
+ k8s/ # Kubernetes manifests
+
+// Development Guidelines
+1. Performance Optimization:
+ - Use goroutines efficiently
+ - Implement proper connection pooling
+ - Cache frequently accessed data
+ - Optimize database queries
+ - Use efficient data structures
+ - Profile and benchmark code
+
+2. Scalability Patterns:
+ - Design stateless services
+ - Implement horizontal scaling
+ - Use message queues
+ - Apply circuit breakers
+ - Implement rate limiting
+ - Handle backpressure
+
+3. Reliability Practices:
+ - Implement graceful shutdown
+ - Handle errors properly
+ - Use timeouts and deadlines
+ - Implement retries
+ - Monitor system health
+ - Log important events
+
+// Dependencies
+Core:
+- go: "1.21"
+- gin-gonic/gin: "v1.9.0"
+- go-redis/redis/v8: "v8.11.5"
+- lib/pq: "v1.10.9"
+- prometheus/client_golang: "v1.16.0"
+
+Optional:
+- golang-migrate/migrate/v4: "v4.16.2"
+- uber-go/zap: "v1.24.0"
+- spf13/viper: "v1.16.0"
+- golang/protobuf: "v1.5.3"
+
+// Code Examples:
+
+1. Scalable HTTP Handler Pattern:
+```go
+type Handler struct {
+ store *store.Store
+ cache *cache.Client
+ logger *zap.Logger
+}
+
+func (h *Handler) GetUser(c *gin.Context) {
+ ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
+ defer cancel()
+
+ userID := c.Param("id")
+
+ // Try cache first
+ if user, err := h.cache.Get(ctx, userID); err == nil {
+ c.JSON(http.StatusOK, user)
+ return
+ }
+
+ // Fallback to database
+ user, err := h.store.GetUser(ctx, userID)
+ if err != nil {
+ if errors.Is(err, store.ErrNotFound) {
+ c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
+ return
+ }
+ h.logger.Error("failed to get user", zap.Error(err))
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Internal server error"})
+ return
+ }
+
+ // Cache for future requests
+ if err := h.cache.Set(ctx, userID, user, time.Hour); err != nil {
+ h.logger.Warn("failed to cache user", zap.Error(err))
+ }
+
+ c.JSON(http.StatusOK, user)
+}
+```
+
+2. Connection Pool Pattern:
+```go
+type Store struct {
+ db *sql.DB
+ log *zap.Logger
+}
+
+func NewStore(dsn string, log *zap.Logger) (*Store, error) {
+ db, err := sql.Open("postgres", dsn)
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to database: %w", err)
+ }
+
+ // Configure connection pool
+ db.SetMaxOpenConns(25)
+ db.SetMaxIdleConns(25)
+ db.SetConnMaxLifetime(5 * time.Minute)
+
+ if err := db.Ping(); err != nil {
+ return nil, fmt.Errorf("failed to ping database: %w", err)
+ }
+
+ return &Store{
+ db: db,
+ log: log,
+ }, nil
+}
+
+func (s *Store) GetUsersByStatus(ctx context.Context, status string) ([]User, error) {
+ query := `
+ SELECT id, name, email, status
+ FROM users
+ WHERE status = $1
+ `
+
+ rows, err := s.db.QueryContext(ctx, query, status)
+ if err != nil {
+ return nil, fmt.Errorf("failed to query users: %w", err)
+ }
+ defer rows.Close()
+
+ var users []User
+ for rows.Next() {
+ var u User
+ if err := rows.Scan(&u.ID, &u.Name, &u.Email, &u.Status); err != nil {
+ return nil, fmt.Errorf("failed to scan user: %w", err)
+ }
+ users = append(users, u)
+ }
+
+ return users, nil
+}
+```
+
+3. Rate Limiter Pattern:
+```go
+type RateLimiter struct {
+ redis *redis.Client
+ limit int
+ window time.Duration
+}
+
+func NewRateLimiter(redis *redis.Client, limit int, window time.Duration) *RateLimiter {
+ return &RateLimiter{
+ redis: redis,
+ limit: limit,
+ window: window,
+ }
+}
+
+func (rl *RateLimiter) Middleware() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ key := fmt.Sprintf("rate_limit:%s", c.ClientIP())
+
+ count, err := rl.redis.Incr(c, key).Result()
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Rate limit check failed"})
+ c.Abort()
+ return
+ }
+
+ if count == 1 {
+ rl.redis.Expire(c, key, rl.window)
+ }
+
+ if count > int64(rl.limit) {
+ c.JSON(http.StatusTooManyRequests, gin.H{"error": "Rate limit exceeded"})
+ c.Abort()
+ return
+ }
+
+ c.Next()
+ }
+}
+```
+
+// Best Practices:
+1. Use context for cancellation
+2. Implement graceful shutdown
+3. Configure connection pools
+4. Cache expensive operations
+5. Use proper error handling
+6. Implement rate limiting
+7. Monitor application metrics
+8. Log meaningful information
+9. Use dependency injection
+10. Write comprehensive tests
+
+// Security Considerations:
+1. Use HTTPS everywhere
+2. Implement authentication
+3. Use proper authorization
+4. Validate all inputs
+5. Prevent SQL injection
+6. Use secure headers
+7. Rate limit endpoints
+8. Implement audit logging
+9. Use secure configurations
+10. Keep dependencies updated
\ No newline at end of file
diff --git a/rules/go-fiber-cursorrules-prompt-file/.cursorrules b/rules/go-fiber-cursorrules-prompt-file/.cursorrules
new file mode 100644
index 0000000..abbc1f9
--- /dev/null
+++ b/rules/go-fiber-cursorrules-prompt-file/.cursorrules
@@ -0,0 +1,339 @@
+// Go Fiber Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern web application using Go Fiber:
+- RESTful APIs
+- GraphQL APIs
+- WebSocket servers
+- Middleware
+- Authentication
+- File uploads
+- Database integration
+- Background jobs
+
+// Project Structure
+cmd/
+ api/ # Application entrypoint
+ main.go # Main application file
+internal/ # Application logic
+ config/ # Configuration
+ config.go # Config structs
+ env.go # Environment vars
+ handlers/ # HTTP handlers
+ auth.go # Auth handlers
+ users.go # User handlers
+ middleware/ # Custom middleware
+ auth.go # Auth middleware
+ logger.go # Logging middleware
+ models/ # Data models
+ user.go # User model
+ product.go # Product model
+ repositories/ # Data access
+ postgres/ # Postgres repos
+ redis/ # Redis repos
+ services/ # Business logic
+ auth.go # Auth service
+ users.go # User service
+ utils/ # Utilities
+ logger/ # Logger
+ validator/ # Validators
+pkg/ # Public packages
+ errors/ # Error types
+ database/ # DB helpers
+migrations/ # DB migrations
+tests/ # Test suite
+ integration/ # Integration tests
+ unit/ # Unit tests
+
+// Development Guidelines
+1. API Design:
+ - RESTful principles
+ - Error handling
+ - Validation
+ - Authentication
+ - Rate limiting
+ - Documentation
+
+2. Code Structure:
+ - Clean architecture
+ - Dependency injection
+ - Repository pattern
+ - Service layer
+ - Error handling
+ - Logging
+
+3. Performance:
+ - Concurrency
+ - Connection pooling
+ - Caching
+ - Query optimization
+ - Memory usage
+ - Monitoring
+
+// Dependencies
+Core:
+- fiber: "v2.47.0"
+- gorm: "v1.25.0"
+- jwt-go: "v4.5.0"
+- validator: "v10.14.0"
+
+Optional:
+- redis: "v9.0.0"
+- zap: "v1.24.0"
+- testify: "v1.8.0"
+- mock: "v2.0.0"
+
+// Code Examples:
+
+1. Handler Pattern:
+```go
+package handlers
+
+import (
+ "github.com/gofiber/fiber/v2"
+ "github.com/username/project/internal/models"
+ "github.com/username/project/internal/services"
+ "github.com/username/project/pkg/errors"
+)
+
+type UserHandler struct {
+ userService services.UserService
+ logger *zap.Logger
+}
+
+func NewUserHandler(us services.UserService, l *zap.Logger) *UserHandler {
+ return &UserHandler{
+ userService: us,
+ logger: l,
+ }
+}
+
+func (h *UserHandler) Create(c *fiber.Ctx) error {
+ var input models.CreateUserInput
+
+ if err := c.BodyParser(&input); err != nil {
+ h.logger.Error("failed to parse request body", zap.Error(err))
+ return c.Status(fiber.StatusBadRequest).JSON(errors.NewBadRequestError("invalid request body"))
+ }
+
+ if err := input.Validate(); err != nil {
+ h.logger.Error("validation failed", zap.Error(err))
+ return c.Status(fiber.StatusBadRequest).JSON(errors.NewValidationError(err))
+ }
+
+ user, err := h.userService.Create(c.Context(), input)
+ if err != nil {
+ h.logger.Error("failed to create user", zap.Error(err))
+ return h.handleError(c, err)
+ }
+
+ return c.Status(fiber.StatusCreated).JSON(user)
+}
+
+func (h *UserHandler) Get(c *fiber.Ctx) error {
+ id := c.Params("id")
+
+ user, err := h.userService.GetByID(c.Context(), id)
+ if err != nil {
+ h.logger.Error("failed to get user", zap.String("id", id), zap.Error(err))
+ return h.handleError(c, err)
+ }
+
+ return c.JSON(user)
+}
+
+func (h *UserHandler) handleError(c *fiber.Ctx, err error) error {
+ switch e := err.(type) {
+ case *errors.NotFoundError:
+ return c.Status(fiber.StatusNotFound).JSON(e)
+ case *errors.ValidationError:
+ return c.Status(fiber.StatusBadRequest).JSON(e)
+ default:
+ return c.Status(fiber.StatusInternalServerError).JSON(
+ errors.NewInternalError("internal server error"),
+ )
+ }
+}
+```
+
+2. Service Pattern:
+```go
+package services
+
+import (
+ "context"
+ "github.com/username/project/internal/models"
+ "github.com/username/project/internal/repositories"
+ "github.com/username/project/pkg/errors"
+ "go.uber.org/zap"
+)
+
+type UserService interface {
+ Create(ctx context.Context, input models.CreateUserInput) (*models.User, error)
+ GetByID(ctx context.Context, id string) (*models.User, error)
+ Update(ctx context.Context, id string, input models.UpdateUserInput) (*models.User, error)
+ Delete(ctx context.Context, id string) error
+}
+
+type userService struct {
+ repo repositories.UserRepository
+ logger *zap.Logger
+}
+
+func NewUserService(repo repositories.UserRepository, logger *zap.Logger) UserService {
+ return &userService{
+ repo: repo,
+ logger: logger,
+ }
+}
+
+func (s *userService) Create(ctx context.Context, input models.CreateUserInput) (*models.User, error) {
+ // Check if user exists
+ exists, err := s.repo.ExistsByEmail(ctx, input.Email)
+ if err != nil {
+ return nil, err
+ }
+ if exists {
+ return nil, errors.NewValidationError("email already exists")
+ }
+
+ // Create user
+ user := &models.User{
+ Email: input.Email,
+ Name: input.Name,
+ Password: input.Password,
+ }
+
+ if err := user.HashPassword(); err != nil {
+ return nil, err
+ }
+
+ if err := s.repo.Create(ctx, user); err != nil {
+ return nil, err
+ }
+
+ return user, nil
+}
+
+func (s *userService) GetByID(ctx context.Context, id string) (*models.User, error) {
+ user, err := s.repo.GetByID(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if user == nil {
+ return nil, errors.NewNotFoundError("user not found")
+ }
+ return user, nil
+}
+```
+
+3. Repository Pattern:
+```go
+package repositories
+
+import (
+ "context"
+ "gorm.io/gorm"
+ "github.com/username/project/internal/models"
+)
+
+type UserRepository interface {
+ Create(ctx context.Context, user *models.User) error
+ GetByID(ctx context.Context, id string) (*models.User, error)
+ ExistsByEmail(ctx context.Context, email string) (bool, error)
+ Update(ctx context.Context, user *models.User) error
+ Delete(ctx context.Context, id string) error
+}
+
+type userRepository struct {
+ db *gorm.DB
+}
+
+func NewUserRepository(db *gorm.DB) UserRepository {
+ return &userRepository{db: db}
+}
+
+func (r *userRepository) Create(ctx context.Context, user *models.User) error {
+ return r.db.WithContext(ctx).Create(user).Error
+}
+
+func (r *userRepository) GetByID(ctx context.Context, id string) (*models.User, error) {
+ var user models.User
+ err := r.db.WithContext(ctx).First(&user, "id = ?", id).Error
+ if err == gorm.ErrRecordNotFound {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &user, nil
+}
+
+func (r *userRepository) ExistsByEmail(ctx context.Context, email string) (bool, error) {
+ var count int64
+ err := r.db.WithContext(ctx).Model(&models.User{}).
+ Where("email = ?", email).
+ Count(&count).
+ Error
+ return count > 0, err
+}
+```
+
+// Best Practices:
+1. Code Quality:
+ - Documentation
+ - Error handling
+ - Testing
+ - Logging
+ - Validation
+ - Interfaces
+
+2. Architecture:
+ - Clean architecture
+ - Dependency injection
+ - Repository pattern
+ - Service layer
+ - Middleware
+ - Error handling
+
+3. Performance:
+ - Goroutines
+ - Connection pools
+ - Query optimization
+ - Caching
+ - Memory usage
+ - Monitoring
+
+4. Security:
+ - Authentication
+ - Authorization
+ - Input validation
+ - Rate limiting
+ - CORS policy
+ - Secure headers
+
+// Security Considerations:
+1. API Security:
+ - Input validation
+ - Rate limiting
+ - Authentication
+ - Authorization
+ - CORS policy
+ - Security headers
+
+2. Data Security:
+ - Password hashing
+ - Data encryption
+ - SQL injection
+ - XSS prevention
+ - CSRF protection
+ - Access control
+
+3. Infrastructure:
+ - HTTPS
+ - TLS config
+ - Firewalls
+ - Monitoring
+ - Logging
+ - Backups
\ No newline at end of file
diff --git a/rules/go-servemux-rest-api-cursorrules-prompt-file/.cursorrules b/rules/go-servemux-rest-api-cursorrules-prompt-file/.cursorrules
index 6eacf10..074432b 100644
--- a/rules/go-servemux-rest-api-cursorrules-prompt-file/.cursorrules
+++ b/rules/go-servemux-rest-api-cursorrules-prompt-file/.cursorrules
@@ -1 +1,253 @@
-You are an expert AI programming assistant specializing in building APIs with Go, using the standard library's net/http package and the new ServeMux introduced in Go 1.22.Always use the latest stable version of Go (1.22 or newer) and be familiar with RESTful API design principles, best practices, and Go idioms.Follow the user's requirements carefully & to the letter.First think step-by-step - describe your plan for the API structure, endpoints, and data flow in pseudocode, written out in great detail.Confirm the plan, then write code!Write correct, up-to-date, bug-free, fully functional, secure, and efficient Go code for APIs.Use the standard library's net/http package for API development:Implement proper error handling, including custom error types when beneficial.Use appropriate status codes and format JSON responses correctly.Implement input validation for API endpoints.Utilize Go's built-in concurrency features when beneficial for API performance.Follow RESTful API design principles and best practices.Include necessary imports, package declarations, and any required setup code.Implement proper logging using the standard library's log package or a simple custom logger.Consider implementing middleware for cross-cutting concerns (e.g., logging, authentication).Implement rate limiting and authentication/authorization when appropriate, using standard library features or simple custom implementations.Leave NO todos, placeholders, or missing pieces in the API implementation.Be concise in explanations, but provide brief comments for complex logic or Go-specific idioms.If unsure about a best practice or implementation detail, say so instead of guessing.Offer suggestions for testing the API endpoints using Go's testing package.Always prioritize security, scalability, and maintainability in your API designs and implementations. Leverage the power and simplicity of Go's standard library to create efficient and idiomatic APIs.
\ No newline at end of file
+// Go ServeMux REST API Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A production-ready REST API using Go's standard library with:
+- Modern ServeMux routing (Go 1.22+)
+- RESTful endpoint design
+- Middleware support
+- Input validation
+- Error handling
+- Authentication/Authorization
+- Rate limiting
+- Logging
+
+// Project Structure
+src/
+ api/ # API layer
+ handlers/ # Request handlers
+ users.go # User endpoints
+ health.go # Health checks
+ middleware/ # HTTP middleware
+ auth.go # Authentication
+ logging.go # Request logging
+ ratelimit.go # Rate limiting
+ models/ # Data models
+ user.go # User model
+ error.go # Error types
+ server/ # Server setup
+ router.go # ServeMux setup
+ config.go # Server config
+ internal/ # Internal packages
+ validator/ # Input validation
+ logger/ # Logging utilities
+ tests/ # Test suites
+ integration/ # Integration tests
+ unit/ # Unit tests
+
+// Development Guidelines
+1. API Design:
+ - Use RESTful principles
+ - Implement proper status codes
+ - Structure JSON responses
+ - Handle errors gracefully
+ - Validate all inputs
+ - Document endpoints
+
+2. Middleware Patterns:
+ - Implement authentication
+ - Add request logging
+ - Enable rate limiting
+ - Handle CORS
+ - Add request ID tracking
+ - Implement timeouts
+
+3. Error Handling:
+ - Use custom error types
+ - Return proper status codes
+ - Include error details
+ - Log errors appropriately
+ - Handle panics
+ - Validate inputs early
+
+// Dependencies
+Core:
+- go: "1.22"
+- net/http
+- encoding/json
+- context
+- log/slog
+- sync
+
+Optional:
+- crypto/bcrypt
+- golang.org/x/time/rate
+- golang.org/x/crypto
+- database/sql
+
+// Code Examples:
+
+1. ServeMux Router Pattern:
+```go
+package server
+
+import (
+ "net/http"
+ "encoding/json"
+ "log/slog"
+)
+
+type Server struct {
+ router *http.ServeMux
+ logger *slog.Logger
+}
+
+func NewServer(logger *slog.Logger) *Server {
+ s := &Server{
+ router: http.NewServeMux(),
+ logger: logger,
+ }
+ s.routes()
+ return s
+}
+
+func (s *Server) routes() {
+ s.router.HandleFunc("GET /api/v1/users/{id}", s.handleGetUser)
+ s.router.HandleFunc("POST /api/v1/users", s.handleCreateUser)
+ s.router.HandleFunc("GET /api/v1/health", s.handleHealthCheck)
+}
+
+func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ s.router.ServeHTTP(w, r)
+}
+
+func (s *Server) handleGetUser(w http.ResponseWriter, r *http.Request) {
+ id := r.PathValue("id")
+
+ user, err := s.store.GetUser(r.Context(), id)
+ if err != nil {
+ s.errorResponse(w, r, err)
+ return
+ }
+
+ s.jsonResponse(w, http.StatusOK, user)
+}
+```
+
+2. Middleware Pattern:
+```go
+package middleware
+
+import (
+ "net/http"
+ "time"
+ "log/slog"
+)
+
+func Logging(logger *slog.Logger) func(http.Handler) http.Handler {
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ start := time.Now()
+
+ // Wrap response writer to capture status code
+ rw := newResponseWriter(w)
+
+ // Call next handler
+ next.ServeHTTP(rw, r)
+
+ // Log request details
+ logger.Info("request completed",
+ "method", r.Method,
+ "path", r.URL.Path,
+ "status", rw.status,
+ "duration", time.Since(start),
+ "ip", r.RemoteAddr,
+ )
+ })
+ }
+}
+
+type responseWriter struct {
+ http.ResponseWriter
+ status int
+}
+
+func newResponseWriter(w http.ResponseWriter) *responseWriter {
+ return &responseWriter{w, http.StatusOK}
+}
+
+func (rw *responseWriter) WriteHeader(code int) {
+ rw.status = code
+ rw.ResponseWriter.WriteHeader(code)
+}
+```
+
+3. Error Handling Pattern:
+```go
+package api
+
+import (
+ "net/http"
+ "encoding/json"
+)
+
+type ErrorResponse struct {
+ Error string `json:"error"`
+ Message string `json:"message,omitempty"`
+ Code int `json:"code"`
+}
+
+func (s *Server) errorResponse(w http.ResponseWriter, r *http.Request, err error) {
+ var response ErrorResponse
+
+ switch e := err.(type) {
+ case *NotFoundError:
+ response = ErrorResponse{
+ Error: "not_found",
+ Message: e.Error(),
+ Code: http.StatusNotFound,
+ }
+ case *ValidationError:
+ response = ErrorResponse{
+ Error: "validation_error",
+ Message: e.Error(),
+ Code: http.StatusBadRequest,
+ }
+ default:
+ response = ErrorResponse{
+ Error: "internal_error",
+ Message: "An internal error occurred",
+ Code: http.StatusInternalServerError,
+ }
+ // Log the actual error
+ s.logger.Error("internal server error",
+ "error", err,
+ "path", r.URL.Path,
+ )
+ }
+
+ s.jsonResponse(w, response.Code, response)
+}
+
+func (s *Server) jsonResponse(w http.ResponseWriter, status int, data interface{}) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ if err := json.NewEncoder(w).Encode(data); err != nil {
+ s.logger.Error("failed to encode response", "error", err)
+ }
+}
+```
+
+// Best Practices:
+1. Use proper HTTP methods
+2. Implement input validation
+3. Handle errors gracefully
+4. Use middleware for cross-cutting concerns
+5. Implement proper logging
+6. Use appropriate status codes
+7. Structure JSON responses
+8. Add request timeouts
+9. Implement rate limiting
+10. Write comprehensive tests
+
+// Security Considerations:
+1. Validate all inputs
+2. Use HTTPS
+3. Implement authentication
+4. Add rate limiting
+5. Set security headers
+6. Handle CORS properly
+7. Sanitize responses
+8. Use secure cookies
+9. Implement timeouts
+10. Log security events
\ No newline at end of file
diff --git a/rules/graphical-apps-development-cursorrules-prompt-file/.cursorrules b/rules/graphical-apps-development-cursorrules-prompt-file/.cursorrules
index 950563b..0cf077d 100644
--- a/rules/graphical-apps-development-cursorrules-prompt-file/.cursorrules
+++ b/rules/graphical-apps-development-cursorrules-prompt-file/.cursorrules
@@ -1 +1,214 @@
-# Project SynopsisPyllments is a Python library for building graphical and API-based LLM applications through chaining together Elements in a potentially cyclic graph. Elements and Payloads are a type of Components. A Component is composed of a Model and Views. The Model handles the underlying data and logic, while the Views are the UI components that are used to display display the interactive UI used to interact with the Model. An Element is a type of Component that is responsible for a specific function. For instance, an Element can handle the LLM selection and generation by making calls to LLM providers. Another Element may handle the chat interface, whose Model would store the chat message history, and the Views would be the text boxes and buttons used to interact with the chat interface. Elements are meant to connect to other Elements through Ports. All that is necessary to link Elements together is to link the output port of one Element to the input port of Another. Each output port may have unlimited input ports it connects to, and each input port may have unlimited output ports it connects to. The ports follow an observer pattern where the output port is the subject and the input port is the observer. The subject notifies the observers when a certain event that we set within the Element is triggered. In order to connect an input and and output port, they need to be setup in a manner that sends and receives the same type of Payload. A Payload is also a Component with a Model as well as views responsible for the display logic. Elements may receive payloads and use methods of the Payload to generate the views for the UI. The sending Element is responsible for packing data into the Payload. I am currently working on making this a fully-fledged framework.# Project OrganizationHere is an example of the file structure of an individual element:chat_interface: - __init__.py - chat_interface_element.py - chat_interface_model.py - css: - buttons.css - column.css - input.css# Primary Libraries Used- Panel is used to create the visualization layer and run the GUI. Views tend to consist of Panel objects which can be styled with Python and CSS.- Param is used to create parameterized classes which help create parameters that handle type validation, default values, constraints, and most importantly, reactivity(setting event handlers to catch changes).- Langchain is responsible for the specific functions pertaining to incorporating LLM workflows.# Development PrioritiesPyllments code is prioritized on being developer-friendly, where extensibility and modularity are first-class citizens. Elements should be customizeable with clean and intuitive interfaces. It should also be easy to create new elements depending on the needs of the developer. # DocumentationDocstrings should use a NumPy/SciPy style.
\ No newline at end of file
+// Graphical Apps Development Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Python-based graphical application framework for LLM applications featuring:
+- Component-based architecture
+- Element chaining in cyclic graphs
+- Interactive UI components
+- LLM integration capabilities
+- Reactive programming patterns
+- Customizable visualization
+- Event-driven communication
+
+// Project Structure
+src/
+ components/ # Core components
+ base/ # Base classes
+ component.py # Base component class
+ element.py # Base element class
+ payload.py # Base payload class
+ models/ # Data models
+ model_base.py # Base model class
+ views/ # UI components
+ view_base.py # Base view class
+ elements/ # Element implementations
+ chat/ # Chat interface element
+ __init__.py
+ chat_element.py
+ chat_model.py
+ css/
+ buttons.css
+ column.css
+ input.css
+ llm/ # LLM integration element
+ __init__.py
+ llm_element.py
+ llm_model.py
+ ports/ # Port system
+ input_port.py # Input port implementation
+ output_port.py # Output port implementation
+ utils/ # Utility functions
+ event_bus.py # Event handling
+ type_checking.py # Type validation
+
+// Development Guidelines
+1. Component Architecture:
+ - Use Model-View separation
+ - Implement clean interfaces
+ - Follow single responsibility
+ - Enable easy extensibility
+ - Maintain modularity
+ - Document interfaces
+
+2. Element Design:
+ - Define clear port contracts
+ - Handle payload types properly
+ - Implement event handlers
+ - Support cyclic connections
+ - Enable customization
+ - Follow observer pattern
+
+3. UI Development:
+ - Create responsive layouts
+ - Style with CSS/Python
+ - Handle user interactions
+ - Implement reactive updates
+ - Support customization
+ - Follow accessibility guidelines
+
+// Dependencies
+Core:
+- python: ">=3.8"
+- panel: "^1.0.0"
+- param: "^2.0.0"
+- langchain: "^0.1.0"
+- pydantic: "^2.0.0"
+
+Optional:
+- streamlit: "^1.0.0"
+- gradio: "^3.0.0"
+- plotly: "^5.0.0"
+- bokeh: "^3.0.0"
+
+// Code Examples:
+
+1. Element Implementation Pattern:
+```python
+from typing import Any, Dict
+import param
+from .base import Element
+from .ports import InputPort, OutputPort
+from .models import PayloadModel
+
+class ChatElement(Element):
+ """Chat interface element for handling message interactions."""
+
+ # Reactive parameters
+ message_history = param.List(default=[])
+ current_message = param.String(default="")
+
+ def __init__(self, **params):
+ super().__init__(**params)
+ # Setup ports
+ self.input_port = InputPort(self, PayloadModel)
+ self.output_port = OutputPort(self, PayloadModel)
+
+ # Initialize views
+ self._setup_views()
+
+ def _setup_views(self):
+ """Initialize and configure UI components."""
+ self.chat_view = self._create_chat_view()
+ self.input_view = self._create_input_view()
+
+ def send_message(self, message: str):
+ """Handle sending a new message."""
+ payload = PayloadModel(content=message)
+ self.message_history.append(message)
+ self.output_port.emit(payload)
+```
+
+2. Model Implementation Pattern:
+```python
+from typing import List, Optional
+import param
+from pydantic import BaseModel
+
+class ChatMessage(BaseModel):
+ """Data model for chat messages."""
+ content: str
+ timestamp: float
+ sender: str
+
+class ChatModel(param.Parameterized):
+ """Model for managing chat state and logic."""
+
+ messages: List[ChatMessage] = param.List([])
+ current_user: str = param.String()
+
+ def add_message(self, content: str, sender: Optional[str] = None):
+ """Add a new message to the chat history."""
+ message = ChatMessage(
+ content=content,
+ timestamp=time.time(),
+ sender=sender or self.current_user
+ )
+ self.messages.append(message)
+ return message
+```
+
+3. View Implementation Pattern:
+```python
+import panel as pn
+from typing import Callable
+
+class ChatView:
+ """View component for chat interface."""
+
+ def __init__(self, on_send: Callable[[str], None]):
+ self.on_send = on_send
+ self._setup_layout()
+
+ def _setup_layout(self):
+ """Create and configure the chat interface layout."""
+ self.message_input = pn.widgets.TextInput(
+ placeholder="Type a message...",
+ css_classes=['chat-input']
+ )
+
+ self.send_button = pn.widgets.Button(
+ name="Send",
+ button_type="primary",
+ css_classes=['send-button']
+ )
+
+ self.send_button.on_click(self._handle_send)
+
+ self.layout = pn.Column(
+ self.message_input,
+ self.send_button,
+ css_classes=['chat-container']
+ )
+
+ def _handle_send(self, event):
+ """Handle send button clicks."""
+ message = self.message_input.value
+ if message.strip():
+ self.on_send(message)
+ self.message_input.value = ""
+```
+
+// Best Practices:
+1. Follow component-based architecture
+2. Implement clean interfaces
+3. Use type hints consistently
+4. Write comprehensive tests
+5. Document with docstrings
+6. Handle errors gracefully
+7. Use reactive programming
+8. Maintain separation of concerns
+9. Enable customization
+10. Follow Python style guide
+
+// Security Considerations:
+1. Validate user inputs
+2. Sanitize displayed content
+3. Handle sensitive data properly
+4. Implement rate limiting
+5. Use secure dependencies
+6. Follow CORS policies
+7. Protect against XSS
+8. Handle errors securely
+9. Implement authentication
+10. Log security events
\ No newline at end of file
diff --git a/rules/graphql-typescript-cursorrules-prompt-file/.cursorrules b/rules/graphql-typescript-cursorrules-prompt-file/.cursorrules
new file mode 100644
index 0000000..ac106a7
--- /dev/null
+++ b/rules/graphql-typescript-cursorrules-prompt-file/.cursorrules
@@ -0,0 +1,353 @@
+// GraphQL TypeScript Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern GraphQL API using TypeScript:
+- Schema-first development
+- Type-safe resolvers
+- Authentication & Authorization
+- Real-time subscriptions
+- Data loaders
+- Custom directives
+- Error handling
+- Testing framework
+
+// Project Structure
+src/
+ schema/ # GraphQL schema
+ typeDefs/ # Type definitions
+ user.graphql # User type definition
+ product.graphql # Product type definition
+ resolvers/ # Resolvers
+ user.ts # User resolver
+ product.ts # Product resolver
+ directives/ # Custom directives
+ auth.ts # Authentication directive
+ validation.ts # Validation directive
+ models/ # Data models
+ User.ts # User model
+ Product.ts # Product model
+ services/ # Business logic
+ UserService.ts # User service
+ ProductService.ts # Product service
+ dataloaders/ # Data loaders
+ UserLoader.ts # User loader
+ ProductLoader.ts # Product loader
+ utils/ # Utilities
+ auth.ts # Authentication utility
+ validation.ts # Validation utility
+ config/ # Configuration
+ apollo.ts # Apollo configuration
+ database.ts # Database configuration
+ tests/ # Test suite
+ integration/ # Integration tests
+ unit/ # Unit tests
+
+// Development Guidelines
+1. Schema Design:
+ - Type definitions
+ - Input types
+ - Mutations
+ - Queries
+ - Subscriptions
+ - Custom scalars
+ - Directives
+
+2. Code Structure:
+ - Resolver pattern
+ - Service layer
+ - Data loaders
+ - Error handling
+ - Authentication
+ - Authorization
+
+3. Performance:
+ - N+1 queries
+ - Caching
+ - Batching
+ - Query complexity
+ - Rate limiting
+ - Monitoring
+
+// Dependencies
+Core:
+- apollo-server: "^4.7.0"
+- graphql: "^16.6.0"
+- type-graphql: "^2.0.0"
+- dataloader: "^2.2.0"
+
+Optional:
+- graphql-tools: "^9.0.0"
+- graphql-shield: "^7.6.0"
+- graphql-scalars: "^1.22.0"
+- jest: "^29.5.0"
+
+// Code Examples:
+
+1. Schema Definition:
+```graphql
+type User {
+ id: ID!
+ email: String!
+ name: String!
+ posts: [Post!]!
+ createdAt: DateTime!
+ updatedAt: DateTime!
+}
+
+type Post {
+ id: ID!
+ title: String!
+ content: String!
+ author: User!
+ createdAt: DateTime!
+ updatedAt: DateTime!
+}
+
+input CreateUserInput {
+ email: String!
+ name: String!
+ password: String!
+}
+
+input UpdateUserInput {
+ name: String
+ password: String
+}
+
+type Query {
+ user(id: ID!): User
+ users(page: Int, limit: Int): [User!]!
+ me: User
+}
+
+type Mutation {
+ createUser(input: CreateUserInput!): User!
+ updateUser(id: ID!, input: UpdateUserInput!): User!
+ deleteUser(id: ID!): Boolean!
+}
+
+type Subscription {
+ userCreated: User!
+}
+```
+
+2. Resolver Pattern:
+```typescript
+import { Resolver, Query, Mutation, Arg, Ctx, UseMiddleware } from 'type-graphql';
+import { User, CreateUserInput, UpdateUserInput } from '../models/User';
+import { UserService } from '../services/UserService';
+import { isAuthenticated } from '../middleware/auth';
+import { Context } from '../types/Context';
+
+@Resolver(User)
+export class UserResolver {
+ constructor(
+ private readonly userService: UserService,
+ ) {}
+
+ @Query(() => User, { nullable: true })
+ async user(
+ @Arg('id') id: string,
+ @Ctx() ctx: Context
+ ): Promise {
+ return this.userService.findById(id);
+ }
+
+ @Query(() => [User])
+ @UseMiddleware(isAuthenticated)
+ async users(
+ @Arg('page', { nullable: true }) page?: number,
+ @Arg('limit', { nullable: true }) limit?: number,
+ @Ctx() ctx: Context
+ ): Promise {
+ return this.userService.findAll({ page, limit });
+ }
+
+ @Mutation(() => User)
+ async createUser(
+ @Arg('input') input: CreateUserInput,
+ @Ctx() ctx: Context
+ ): Promise {
+ return this.userService.create(input);
+ }
+
+ @Mutation(() => User)
+ @UseMiddleware(isAuthenticated)
+ async updateUser(
+ @Arg('id') id: string,
+ @Arg('input') input: UpdateUserInput,
+ @Ctx() ctx: Context
+ ): Promise {
+ return this.userService.update(id, input);
+ }
+
+ @Mutation(() => Boolean)
+ @UseMiddleware(isAuthenticated)
+ async deleteUser(
+ @Arg('id') id: string,
+ @Ctx() ctx: Context
+ ): Promise {
+ await this.userService.delete(id);
+ return true;
+ }
+}
+```
+
+3. Service Pattern:
+```typescript
+import { Service } from 'typedi';
+import { Repository } from 'typeorm';
+import { User, CreateUserInput, UpdateUserInput } from '../models/User';
+import { ValidationError, NotFoundError } from '../utils/errors';
+import { hashPassword } from '../utils/auth';
+
+@Service()
+export class UserService {
+ constructor(
+ @InjectRepository(User)
+ private readonly userRepository: Repository,
+ ) {}
+
+ async findById(id: string): Promise {
+ const user = await this.userRepository.findOne({ where: { id } });
+ if (!user) {
+ throw new NotFoundError('User not found');
+ }
+ return user;
+ }
+
+ async findAll(options: { page?: number; limit?: number }): Promise {
+ const { page = 1, limit = 10 } = options;
+ return this.userRepository.find({
+ skip: (page - 1) * limit,
+ take: limit,
+ order: { createdAt: 'DESC' },
+ });
+ }
+
+ async create(input: CreateUserInput): Promise {
+ const existingUser = await this.userRepository.findOne({
+ where: { email: input.email },
+ });
+
+ if (existingUser) {
+ throw new ValidationError('Email already exists');
+ }
+
+ const hashedPassword = await hashPassword(input.password);
+ const user = this.userRepository.create({
+ ...input,
+ password: hashedPassword,
+ });
+
+ return this.userRepository.save(user);
+ }
+
+ async update(id: string, input: UpdateUserInput): Promise {
+ const user = await this.findById(id);
+
+ if (input.password) {
+ input.password = await hashPassword(input.password);
+ }
+
+ Object.assign(user, input);
+ return this.userRepository.save(user);
+ }
+
+ async delete(id: string): Promise {
+ const user = await this.findById(id);
+ await this.userRepository.remove(user);
+ }
+}
+```
+
+4. DataLoader Pattern:
+```typescript
+import DataLoader from 'dataloader';
+import { Service } from 'typedi';
+import { User } from '../models/User';
+import { Post } from '../models/Post';
+import { PostService } from './PostService';
+
+@Service()
+export class PostLoader {
+ private loader: DataLoader;
+
+ constructor(private readonly postService: PostService) {
+ this.loader = new DataLoader(this.batchLoadPosts.bind(this));
+ }
+
+ private async batchLoadPosts(userIds: string[]): Promise {
+ const posts = await this.postService.findByUserIds(userIds);
+
+ const postsByUser = userIds.map(userId =>
+ posts.filter(post => post.userId === userId)
+ );
+
+ return postsByUser;
+ }
+
+ async loadPosts(userId: string): Promise {
+ return this.loader.load(userId);
+ }
+}
+```
+
+// Best Practices:
+1. Code Quality:
+ - Type safety
+ - Documentation
+ - Testing
+ - Error handling
+ - Validation
+ - Code organization
+
+2. Schema Design:
+ - Type definitions
+ - Input validation
+ - Error handling
+ - Nullability
+ - Pagination
+ - Filtering
+
+3. Performance:
+ - Data loaders
+ - Query complexity
+ - Caching
+ - Batching
+ - Rate limiting
+ - Monitoring
+
+4. Security:
+ - Authentication
+ - Authorization
+ - Input validation
+ - Rate limiting
+ - Query depth
+ - Field restrictions
+
+// Security Considerations:
+1. API Security:
+ - Authentication
+ - Authorization
+ - Input validation
+ - Rate limiting
+ - Query complexity
+ - Field restrictions
+
+2. Data Security:
+ - Password hashing
+ - Data encryption
+ - Access control
+ - Audit logging
+ - Error handling
+ - Data validation
+
+3. Infrastructure:
+ - HTTPS
+ - CORS
+ - Headers
+ - Monitoring
+ - Logging
+ - Backups
\ No newline at end of file
diff --git a/rules/html-css-javascript-cursorrules-prompt-file/.cursorrules b/rules/html-css-javascript-cursorrules-prompt-file/.cursorrules
new file mode 100644
index 0000000..a5177ad
--- /dev/null
+++ b/rules/html-css-javascript-cursorrules-prompt-file/.cursorrules
@@ -0,0 +1,461 @@
+// HTML, CSS, and JavaScript Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern web application using HTML, CSS, and JavaScript:
+- Responsive layouts
+- Interactive UI components
+- Form validation
+- DOM manipulation
+- AJAX requests
+- CSS animations
+- Local storage
+- Web APIs
+
+// Project Structure
+project/
+ src/ # Source files
+ index.html # Main HTML file
+ css/ # Stylesheets
+ main.css # Main styles
+ reset.css # CSS reset
+ utils.css # Utility classes
+ js/ # JavaScript files
+ main.js # Main script
+ utils.js # Utility functions
+ api.js # API calls
+ assets/ # Static assets
+ images/ # Image files
+ fonts/ # Font files
+ dist/ # Production build
+ tests/ # Test suite
+ unit/ # Unit tests
+ e2e/ # End-to-end tests
+
+// Development Guidelines
+1. HTML Structure:
+ - Semantic markup
+ - Accessibility
+ - Meta tags
+ - Open Graph
+ - Schema.org
+ - Performance
+
+2. CSS Organization:
+ - BEM methodology
+ - Mobile-first
+ - CSS variables
+ - Flexbox/Grid
+ - Media queries
+ - Animations
+
+3. JavaScript Best Practices:
+ - ES6+ features
+ - Modules
+ - Event handling
+ - Error handling
+ - Performance
+ - Testing
+
+// Dependencies
+Core:
+- normalize.css: "^8.0.1"
+- font-awesome: "^6.4.0"
+
+Optional:
+- axios: "^1.4.0"
+- lodash: "^4.17.21"
+- jest: "^29.5.0"
+- cypress: "^12.14.0"
+
+// Code Examples:
+
+1. HTML Pattern:
+```html
+
+
+
+
+
+
+
+
+
+ Your Site Title
+
+
+
+
+
+
+
+
+
+
+
Welcome to our site
+
Lorem ipsum dolor sit amet
+
+
+
+
+
+
Feature 1
+
Description
+
+
+
+
+
+
+
+
+
+
+```
+
+2. CSS Pattern:
+```css
+/* Variables */
+:root {
+ --color-primary: #007bff;
+ --color-secondary: #6c757d;
+ --color-success: #28a745;
+ --color-danger: #dc3545;
+ --font-primary: 'Arial', sans-serif;
+ --spacing-sm: 0.5rem;
+ --spacing-md: 1rem;
+ --spacing-lg: 2rem;
+}
+
+/* Reset */
+*, *::before, *::after {
+ box-sizing: border-box;
+ margin: 0;
+ padding: 0;
+}
+
+/* Typography */
+body {
+ font-family: var(--font-primary);
+ line-height: 1.6;
+ color: #333;
+}
+
+/* Layout */
+.container {
+ max-width: 1200px;
+ margin: 0 auto;
+ padding: 0 var(--spacing-md);
+}
+
+/* Components */
+.nav {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: var(--spacing-md);
+ background-color: #fff;
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
+}
+
+.nav__list {
+ display: flex;
+ list-style: none;
+ gap: var(--spacing-md);
+}
+
+.nav__link {
+ text-decoration: none;
+ color: var(--color-primary);
+ transition: color 0.3s ease;
+}
+
+.nav__link:hover {
+ color: var(--color-secondary);
+}
+
+/* Responsive */
+@media (max-width: 768px) {
+ .nav {
+ flex-direction: column;
+ }
+
+ .nav__list {
+ margin-top: var(--spacing-md);
+ }
+}
+
+/* Animations */
+@keyframes fadeIn {
+ from {
+ opacity: 0;
+ transform: translateY(20px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
+.fade-in {
+ animation: fadeIn 0.5s ease forwards;
+}
+```
+
+3. JavaScript Pattern:
+```javascript
+// Config
+const config = {
+ apiUrl: 'https://api.example.com',
+ storageKey: 'app_data',
+ debounceTime: 300
+};
+
+// Utils
+const utils = {
+ debounce(func, wait) {
+ let timeout;
+ return function executedFunction(...args) {
+ const later = () => {
+ clearTimeout(timeout);
+ func(...args);
+ };
+ clearTimeout(timeout);
+ timeout = setTimeout(later, wait);
+ };
+ },
+
+ formatDate(date) {
+ return new Intl.DateTimeFormat('en-US', {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric'
+ }).format(new Date(date));
+ },
+
+ storage: {
+ set(key, value) {
+ try {
+ localStorage.setItem(key, JSON.stringify(value));
+ } catch (error) {
+ console.error('Error saving to localStorage:', error);
+ }
+ },
+
+ get(key) {
+ try {
+ const item = localStorage.getItem(key);
+ return item ? JSON.parse(item) : null;
+ } catch (error) {
+ console.error('Error reading from localStorage:', error);
+ return null;
+ }
+ }
+ }
+};
+
+// API Service
+class ApiService {
+ constructor(baseUrl) {
+ this.baseUrl = baseUrl;
+ }
+
+ async get(endpoint) {
+ try {
+ const response = await fetch(`${this.baseUrl}${endpoint}`);
+ if (!response.ok) throw new Error('Network response was not ok');
+ return await response.json();
+ } catch (error) {
+ console.error('API Error:', error);
+ throw error;
+ }
+ }
+
+ async post(endpoint, data) {
+ try {
+ const response = await fetch(`${this.baseUrl}${endpoint}`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(data)
+ });
+ if (!response.ok) throw new Error('Network response was not ok');
+ return await response.json();
+ } catch (error) {
+ console.error('API Error:', error);
+ throw error;
+ }
+ }
+}
+
+// Form Handler
+class FormHandler {
+ constructor(formElement) {
+ this.form = formElement;
+ this.init();
+ }
+
+ init() {
+ this.form.addEventListener('submit', this.handleSubmit.bind(this));
+ this.form.addEventListener('input', utils.debounce(
+ this.handleInput.bind(this),
+ config.debounceTime
+ ));
+ }
+
+ handleSubmit(event) {
+ event.preventDefault();
+ if (this.validateForm()) {
+ const formData = new FormData(this.form);
+ const data = Object.fromEntries(formData.entries());
+ this.submitForm(data);
+ }
+ }
+
+ handleInput(event) {
+ const field = event.target;
+ this.validateField(field);
+ }
+
+ validateField(field) {
+ const value = field.value;
+ let isValid = true;
+ let errorMessage = '';
+
+ switch (field.type) {
+ case 'email':
+ isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
+ errorMessage = 'Please enter a valid email address';
+ break;
+ case 'password':
+ isValid = value.length >= 8;
+ errorMessage = 'Password must be at least 8 characters long';
+ break;
+ // Add more validation cases
+ }
+
+ this.showFieldError(field, isValid ? '' : errorMessage);
+ return isValid;
+ }
+
+ validateForm() {
+ const fields = this.form.querySelectorAll('input, select, textarea');
+ let isValid = true;
+
+ fields.forEach(field => {
+ if (!this.validateField(field)) {
+ isValid = false;
+ }
+ });
+
+ return isValid;
+ }
+
+ showFieldError(field, message) {
+ const errorElement = field.nextElementSibling;
+ if (errorElement && errorElement.classList.contains('error-message')) {
+ errorElement.textContent = message;
+ field.classList.toggle('invalid', message !== '');
+ }
+ }
+
+ async submitForm(data) {
+ try {
+ const api = new ApiService(config.apiUrl);
+ const response = await api.post('/submit', data);
+ this.handleSuccess(response);
+ } catch (error) {
+ this.handleError(error);
+ }
+ }
+
+ handleSuccess(response) {
+ // Handle successful submission
+ console.log('Form submitted successfully:', response);
+ }
+
+ handleError(error) {
+ // Handle submission error
+ console.error('Form submission error:', error);
+ }
+}
+
+// Initialize
+document.addEventListener('DOMContentLoaded', () => {
+ const forms = document.querySelectorAll('form');
+ forms.forEach(form => new FormHandler(form));
+});
+```
+
+// Best Practices:
+1. HTML:
+ - Semantic elements
+ - Accessibility (ARIA)
+ - Valid markup
+ - Meta tags
+ - Performance
+ - SEO optimization
+
+2. CSS:
+ - BEM naming
+ - Mobile-first
+ - CSS variables
+ - Flexbox/Grid
+ - Performance
+ - Maintainability
+
+3. JavaScript:
+ - ES6+ features
+ - Modules
+ - Error handling
+ - Performance
+ - Testing
+ - Documentation
+
+4. Security:
+ - XSS prevention
+ - CSRF protection
+ - Content Security
+ - Input validation
+ - Secure storage
+ - HTTPS usage
+
+// Security Considerations:
+1. Client-side:
+ - Input validation
+ - XSS prevention
+ - CSRF tokens
+ - Secure storage
+ - API security
+ - Error handling
+
+2. Data Security:
+ - Form validation
+ - Data encryption
+ - Access control
+ - Session handling
+ - Error messages
+ - Logging
+
+3. Infrastructure:
+ - HTTPS
+ - CORS
+ - Headers
+ - Caching
+ - Monitoring
+ - Backups
\ No newline at end of file
diff --git a/rules/html-tailwind-css-javascript-cursorrules-prompt-fi/.cursorrules b/rules/html-tailwind-css-javascript-cursorrules-prompt-fi/.cursorrules
index e84c905..617cd1a 100644
--- a/rules/html-tailwind-css-javascript-cursorrules-prompt-fi/.cursorrules
+++ b/rules/html-tailwind-css-javascript-cursorrules-prompt-fi/.cursorrules
@@ -1 +1,259 @@
-You are an expert AI programming assistant that primarily focuses on producing clear, readable HTML, Tailwind CSS and vanilla JavaScript code.You always use the latest version of HTML, Tailwind CSS and vanilla JavaScript, and you are familiar with the latest features and best practices.You carefully provide accurate, factual, thoughtful answers, and excel at reasoning.- Follow the user’s requirements carefully & to the letter.- Confirm, then write code!- Suggest solutions that I didn't think about-anticipate my needs- Treat me as an expert- Always write correct, up to date, bug free, fully functional and working, secure, performant and efficient code.- Focus on readability over being performant.- Fully implement all requested functionality.- Leave NO todo’s, placeholders or missing pieces.- Be concise. Minimize any other prose.- Consider new technologies and contrarian ideas, not just the conventional wisdom- If you think there might not be a correct answer, you say so. If you do not know the answer, say so instead of guessing.- If I ask for adjustments to code, do not repeat all of my code unnecessarily. Instead try to keep the answer brief by giving just a couple lines before/after any changes you make.
\ No newline at end of file
+// HTML, Tailwind CSS & JavaScript Development Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+Modern, responsive web applications featuring:
+- Semantic HTML5 markup
+- Utility-first styling with Tailwind CSS
+- Interactive UIs with vanilla JavaScript
+- Responsive layouts
+- Accessible components
+- Progressive enhancement
+- Modern animations
+- Performance optimization
+
+// Project Structure
+src/
+ assets/ # Static assets
+ images/ # Image files
+ fonts/ # Font files
+ css/ # CSS styles
+ tailwind/ # Tailwind configuration
+ config.js # Tailwind config
+ custom.css # Custom utilities
+ styles.css # Main stylesheet
+ js/ # JavaScript files
+ components/ # UI components
+ modal.js # Modal component
+ dropdown.js # Dropdown component
+ utils/ # Utility functions
+ dom.js # DOM helpers
+ validation.js # Form validation
+ main.js # Entry point
+ pages/ # HTML pages
+ index.html # Home page
+ about.html # About page
+ templates/ # Reusable templates
+ header.html # Header component
+ footer.html # Footer component
+
+// Development Guidelines
+1. HTML Structure:
+ - Use semantic markup
+ - Follow accessibility guidelines
+ - Implement proper SEO
+ - Maintain clean hierarchy
+ - Include meta tags
+ - Optimize for performance
+
+2. Tailwind CSS Usage:
+ - Use utility classes
+ - Follow responsive design
+ - Implement dark mode
+ - Create custom utilities
+ - Maintain consistency
+ - Optimize for production
+
+3. JavaScript Patterns:
+ - Write modular code
+ - Use modern ES6+
+ - Handle errors properly
+ - Implement event delegation
+ - Optimize performance
+ - Follow best practices
+
+// Dependencies
+Core:
+- html: "HTML5"
+- tailwindcss: "^3.4.0"
+- postcss: "^8.4.0"
+- autoprefixer: "^10.4.0"
+
+Optional:
+- alpinejs: "^3.0.0"
+- prettier: "^3.1.0"
+- eslint: "^8.0.0"
+- vite: "^5.0.0"
+
+// Code Examples:
+
+1. Responsive Component Pattern:
+```html
+
+
+
+
+
+
+
+
+ Card Title
+
+
+ Card description with responsive text that wraps nicely.
+
+
+
+
+
+
+ 5 min read
+
+
+
+
+```
+
+2. JavaScript Component Pattern:
+```javascript
+// Modal Component
+class Modal {
+ constructor(options = {}) {
+ this.id = options.id || 'modal';
+ this.openTrigger = options.openTrigger || '[data-modal-trigger]';
+ this.closeTrigger = options.closeTrigger || '[data-modal-close]';
+ this.activeClass = options.activeClass || 'is-active';
+ this.onOpen = options.onOpen || (() => {});
+ this.onClose = options.onClose || (() => {});
+
+ this.modal = document.getElementById(this.id);
+ this.isOpen = false;
+
+ this.init();
+ }
+
+ init() {
+ // Setup event listeners
+ document.querySelectorAll(this.openTrigger)
+ .forEach(trigger => {
+ trigger.addEventListener('click', () => this.open());
+ });
+
+ document.querySelectorAll(this.closeTrigger)
+ .forEach(trigger => {
+ trigger.addEventListener('click', () => this.close());
+ });
+
+ // Close on escape key
+ document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && this.isOpen) {
+ this.close();
+ }
+ });
+
+ // Close on outside click
+ this.modal.addEventListener('click', (e) => {
+ if (e.target === this.modal) {
+ this.close();
+ }
+ });
+ }
+
+ open() {
+ if (this.isOpen) return;
+
+ this.modal.classList.add(this.activeClass);
+ document.body.style.overflow = 'hidden';
+ this.isOpen = true;
+ this.onOpen();
+ }
+
+ close() {
+ if (!this.isOpen) return;
+
+ this.modal.classList.remove(this.activeClass);
+ document.body.style.overflow = '';
+ this.isOpen = false;
+ this.onClose();
+ }
+}
+```
+
+3. Form Validation Pattern:
+```javascript
+// Form Validation Utility
+const validateForm = {
+ email: (value) => {
+ const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
+ return {
+ isValid: pattern.test(value),
+ message: pattern.test(value) ? '' : 'Please enter a valid email address'
+ };
+ },
+
+ password: (value) => {
+ const hasMinLength = value.length >= 8;
+ const hasUpperCase = /[A-Z]/.test(value);
+ const hasLowerCase = /[a-z]/.test(value);
+ const hasNumber = /\d/.test(value);
+
+ const isValid = hasMinLength && hasUpperCase && hasLowerCase && hasNumber;
+
+ return {
+ isValid,
+ message: isValid ? '' : 'Password must be at least 8 characters and contain uppercase, lowercase, and numbers'
+ };
+ },
+
+ required: (value) => ({
+ isValid: value.trim().length > 0,
+ message: value.trim().length > 0 ? '' : 'This field is required'
+ })
+};
+
+// Usage Example
+const form = document.querySelector('form');
+const inputs = form.querySelectorAll('[data-validate]');
+
+inputs.forEach(input => {
+ input.addEventListener('blur', () => {
+ const validationType = input.dataset.validate;
+ const result = validateForm[validationType](input.value);
+
+ const errorElement = input.parentElement.querySelector('.error-message');
+
+ if (!result.isValid) {
+ input.classList.add('border-red-500');
+ errorElement.textContent = result.message;
+ errorElement.classList.remove('hidden');
+ } else {
+ input.classList.remove('border-red-500');
+ errorElement.classList.add('hidden');
+ }
+ });
+});
+```
+
+// Best Practices:
+1. Write semantic HTML
+2. Follow accessibility guidelines
+3. Use responsive design
+4. Implement progressive enhancement
+5. Optimize performance
+6. Write modular code
+7. Handle errors gracefully
+8. Follow naming conventions
+9. Document code properly
+10. Test cross-browser compatibility
+
+// Security Considerations:
+1. Sanitize user inputs
+2. Prevent XSS attacks
+3. Use HTTPS
+4. Implement CSP
+5. Secure form handling
+6. Validate data client-side
+7. Handle errors securely
+8. Use secure dependencies
+9. Implement CORS properly
+10. Follow security headers
\ No newline at end of file
diff --git a/rules/htmx-basic-cursorrules-prompt-file/.cursorrules b/rules/htmx-basic-cursorrules-prompt-file/.cursorrules
index b2c1515..d174181 100644
--- a/rules/htmx-basic-cursorrules-prompt-file/.cursorrules
+++ b/rules/htmx-basic-cursorrules-prompt-file/.cursorrules
@@ -1,32 +1,193 @@
-// HTMX Basic Setup .cursorrules
-
-// HTMX best practices
-const htmxBestPractices = [
- "Use hx-get for GET requests",
- "Implement hx-post for POST requests",
- "Utilize hx-trigger for custom events",
- "Use hx-swap to control how content is swapped",
- "Implement hx-target to specify where to swap content",
- "Utilize hx-indicator for loading indicators",
-];
-
-// Folder structure
-const folderStructure = `
+// HTMX Basic Development Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+Modern, hypermedia-driven web applications featuring:
+- Server-side rendered HTML
+- Dynamic UI updates without JavaScript
+- Progressive enhancement
+- Real-time interactions
+- Form validation and submission
+- Infinite scrolling
+- Modal dialogs
+- Live search
+
+// Project Structure
src/
- templates/
- static/
- css/
- js/
- app.py
-`;
-
-// Additional instructions
-const additionalInstructions = `
-1. Use semantic HTML5 elements
-2. Implement proper CSRF protection
-3. Utilize HTMX extensions when needed
-4. Use hx-boost for full page navigation
-5. Implement proper error handling
-6. Follow progressive enhancement principles
-7. Use server-side templating (e.g., Jinja2, Handlebars)
-`;
+ templates/ # HTML templates
+ base.html # Base template
+ components/ # Reusable components
+ form.html # Form component
+ modal.html # Modal component
+ pages/ # Page templates
+ index.html # Home page
+ about.html # About page
+ static/ # Static assets
+ css/ # Stylesheets
+ main.css # Main styles
+ components/ # Component styles
+ js/ # JavaScript
+ htmx.min.js # HTMX library
+ app.py # Main application
+
+// Development Guidelines
+1. HTMX Attributes:
+ - Use hx-get for GET requests
+ - Use hx-post for POST requests
+ - Use hx-trigger for events
+ - Use hx-swap for content updates
+ - Use hx-target for targeting
+ - Use hx-indicator for loading states
+
+2. Server Integration:
+ - Implement CSRF protection
+ - Return partial HTML
+ - Handle errors gracefully
+ - Use proper status codes
+ - Validate inputs
+ - Follow REST principles
+
+3. Progressive Enhancement:
+ - Start with plain HTML
+ - Add HTMX attributes
+ - Use JavaScript sparingly
+ - Support non-JS users
+ - Handle fallbacks
+ - Maintain accessibility
+
+// Dependencies
+Core:
+- htmx: "^1.9.0"
+- html: "HTML5"
+- python: "^3.8"
+- flask: "^2.0.0"
+
+Optional:
+- hyperscript: "^0.9.0"
+- tailwindcss: "^3.0.0"
+- alpine.js: "^3.0.0"
+- flask-wtf: "^1.0.0"
+
+// Code Examples:
+
+1. Basic Form Pattern:
+```html
+
+
+```
+
+2. Server Response Pattern:
+```python
+from flask import Flask, render_template
+
+app = Flask(__name__)
+
+@app.route('/contact', methods=['POST'])
+def contact():
+ # Validate form data
+ if not validate_form():
+ return render_template('components/form_errors.html'), 400
+
+ try:
+ # Process the contact form
+ process_contact_form()
+
+ # Return success message
+ return render_template(
+ 'components/success_message.html',
+ message="Thank you for your message!"
+ )
+ except Exception as e:
+ # Return error message
+ return render_template(
+ 'components/error_message.html',
+ error="Failed to send message"
+ ), 500
+```
+
+3. Infinite Scroll Pattern:
+```html
+
+
+
+
+ {% for item in items %}
+
+
{{ item.title }}
+
{{ item.description }}
+
+
+
+ {% endfor %}
+
+
+
+ Loading more items...
+
+
+```
+
+// Best Practices:
+1. Use semantic HTML
+2. Follow REST principles
+3. Implement proper validation
+4. Handle errors gracefully
+5. Show loading states
+6. Use proper targeting
+7. Optimize performance
+8. Maintain accessibility
+9. Follow progressive enhancement
+10. Document endpoints
+
+// Security Considerations:
+1. Implement CSRF protection
+2. Validate all inputs
+3. Sanitize HTML responses
+4. Use proper headers
+5. Handle errors securely
+6. Implement rate limiting
+7. Use HTTPS
+8. Follow SOP/CORS
+9. Protect against XSS
+10. Audit dependencies
diff --git a/rules/htmx-django-cursorrules-prompt-file/.cursorrules b/rules/htmx-django-cursorrules-prompt-file/.cursorrules
index eed49f6..ab0de55 100644
--- a/rules/htmx-django-cursorrules-prompt-file/.cursorrules
+++ b/rules/htmx-django-cursorrules-prompt-file/.cursorrules
@@ -1,39 +1,222 @@
-// HTMX with Django .cursorrules
-
-// HTMX and Django best practices
-const htmxDjangoBestPractices = [
- "Use Django's template system with HTMX attributes",
- "Implement Django forms for form handling",
- "Utilize Django's URL routing system",
- "Use Django's class-based views for HTMX responses",
- "Implement Django ORM for database operations",
- "Utilize Django's middleware for request/response processing",
-];
-
-// Folder structure
-const folderStructure = `
+// HTMX with Django Development Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+Modern Django applications with HTMX integration featuring:
+- Server-side rendered templates
+- Dynamic UI updates without JavaScript
+- Django form integration
+- Real-time interactions
+- Database-driven updates
+- Infinite scrolling
+- Modal dialogs
+- Live search
+
+// Project Structure
project_name/
- app_name/
- templates/
- static/
- css/
- js/
- models.py
- views.py
- urls.py
- project_name/
- settings.py
- urls.py
-manage.py
-`;
-
-// Additional instructions
-const additionalInstructions = `
-1. Use Django's template tags with HTMX attributes
-2. Implement proper CSRF protection with Django's built-in features
-3. Utilize Django's HttpResponse for HTMX-specific responses
-4. Use Django's form validation for HTMX requests
-5. Implement proper error handling and logging
-6. Follow Django's best practices for project structure
-7. Use Django's staticfiles app for managing static assets
-`;
+ app_name/ # Django app
+ templates/ # HTML templates
+ base.html # Base template
+ components/ # Reusable components
+ form.html # Form component
+ modal.html # Modal component
+ pages/ # Page templates
+ index.html # Home page
+ about.html # About page
+ static/ # Static assets
+ css/ # Stylesheets
+ main.css # Main styles
+ js/ # JavaScript
+ htmx.min.js # HTMX library
+ models.py # Database models
+ views.py # View controllers
+ urls.py # URL routing
+ forms.py # Form definitions
+ tests/ # Test files
+ test_views.py # View tests
+ test_models.py # Model tests
+ project_name/ # Project configuration
+ settings.py # Django settings
+ urls.py # Root URL config
+ manage.py # Django CLI
+
+// Development Guidelines
+1. Django Integration:
+ - Use class-based views
+ - Implement Django forms
+ - Follow URL patterns
+ - Use template inheritance
+ - Handle CSRF properly
+ - Follow Django conventions
+
+2. HTMX Patterns:
+ - Use template tags
+ - Return partial HTML
+ - Handle form validation
+ - Implement error responses
+ - Show loading states
+ - Use proper targeting
+
+3. Database Patterns:
+ - Use Django ORM
+ - Optimize queries
+ - Handle transactions
+ - Implement caching
+ - Follow migrations
+ - Maintain consistency
+
+// Dependencies
+Core:
+- django: "^4.2.0"
+- htmx: "^1.9.0"
+- python: "^3.8"
+- psycopg2: "^2.9.0"
+
+Optional:
+- django-debug-toolbar: "^4.0.0"
+- django-htmx: "^1.0.0"
+- django-crispy-forms: "^2.0.0"
+- django-compressor: "^4.0.0"
+
+// Code Examples:
+
+1. Django View Pattern:
+```python
+from django.views.generic import ListView
+from django.http import HttpResponse
+from django.template.loader import render_to_string
+from .models import Item
+
+class ItemListView(ListView):
+ model = Item
+ template_name = 'items/list.html'
+ context_object_name = 'items'
+ paginate_by = 10
+
+ def get(self, request, *args, **kwargs):
+ # Check if this is an HTMX request
+ if request.htmx:
+ # Get queryset
+ self.object_list = self.get_queryset()
+ context = self.get_context_data()
+
+ # Render only the items partial
+ html = render_to_string(
+ 'items/partials/item_list.html',
+ context,
+ request=request
+ )
+ return HttpResponse(html)
+
+ # Regular request - render full template
+ return super().get(request, *args, **kwargs)
+```
+
+2. Django Template Pattern:
+```html
+{% extends "base.html" %}
+{% load static %}
+
+{% block content %}
+
+
+ {% include "items/partials/item_list.html" %}
+
+
+ Loading more items...
+
+
+
+
+
+{% endblock %}
+```
+
+3. Django Form Pattern:
+```python
+from django import forms
+from django.core.exceptions import ValidationError
+from .models import Item
+
+class ItemForm(forms.ModelForm):
+ class Meta:
+ model = Item
+ fields = ['title', 'description']
+
+ def clean_title(self):
+ title = self.cleaned_data['title']
+ if Item.objects.filter(title=title).exists():
+ raise ValidationError('An item with this title already exists.')
+ return title
+
+ def save(self, commit=True):
+ instance = super().save(commit=False)
+ if commit:
+ instance.save()
+ # Return HTML for new item
+ html = render_to_string(
+ 'items/partials/item.html',
+ {'item': instance}
+ )
+ return html
+ return instance
+
+# View using the form
+from django.views.generic.edit import CreateView
+
+class ItemCreateView(CreateView):
+ model = Item
+ form_class = ItemForm
+ template_name = 'items/create.html'
+
+ def form_valid(self, form):
+ # Save and get HTML response
+ html = form.save()
+ return HttpResponse(html)
+
+ def form_invalid(self, form):
+ return HttpResponse(
+ str(form.errors),
+ status=400
+ )
+```
+
+// Best Practices:
+1. Follow Django conventions
+2. Use class-based views
+3. Implement proper forms
+4. Handle CSRF correctly
+5. Optimize database queries
+6. Use template inheritance
+7. Handle errors gracefully
+8. Write comprehensive tests
+9. Document view responses
+10. Follow URL naming
+
+// Security Considerations:
+1. Enable CSRF protection
+2. Validate form inputs
+3. Sanitize HTML output
+4. Use proper permissions
+5. Handle file uploads safely
+6. Implement rate limiting
+7. Use HTTPS
+8. Secure admin interface
+9. Audit dependencies
+10. Log security events
diff --git a/rules/htmx-flask-cursorrules-prompt-file/.cursorrules b/rules/htmx-flask-cursorrules-prompt-file/.cursorrules
index 3e19823..dff8550 100644
--- a/rules/htmx-flask-cursorrules-prompt-file/.cursorrules
+++ b/rules/htmx-flask-cursorrules-prompt-file/.cursorrules
@@ -1,36 +1,246 @@
-// HTMX with Flask .cursorrules
-
-// HTMX and Flask best practices
-const htmxFlaskBestPractices = [
- "Use Flask's render_template for server-side rendering",
- "Implement Flask-WTF for form handling",
- "Utilize Flask's url_for for generating URLs",
- "Use Flask's jsonify for JSON responses",
- "Implement Flask-SQLAlchemy for database operations",
- "Utilize Flask's Blueprint for modular applications",
-];
-
-// Folder structure
-const folderStructure = `
+// HTMX with Flask Development Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+Modern Flask applications with HTMX integration featuring:
+- Server-side rendered templates
+- Dynamic UI updates without JavaScript
+- Flask form integration
+- Real-time interactions
+- Database-driven updates
+- Infinite scrolling
+- Modal dialogs
+- Live search
+
+// Project Structure
app/
- templates/
- static/
- css/
- js/
- models/
- routes/
- __init__.py
-config.py
-run.py
-`;
-
-// Additional instructions
-const additionalInstructions = `
-1. Use Jinja2 templating with HTMX attributes
-2. Implement proper CSRF protection with Flask-WTF
-3. Utilize Flask's request object for handling HTMX requests
-4. Use Flask-Migrate for database migrations
-5. Implement proper error handling and logging
-6. Follow Flask's application factory pattern
-7. Use environment variables for configuration
-`;
+ templates/ # HTML templates
+ base.html # Base template
+ components/ # Reusable components
+ form.html # Form component
+ modal.html # Modal component
+ pages/ # Page templates
+ index.html # Home page
+ about.html # About page
+ static/ # Static assets
+ css/ # Stylesheets
+ main.css # Main styles
+ js/ # JavaScript
+ htmx.min.js # HTMX library
+ models/ # Database models
+ __init__.py # Package init
+ user.py # User model
+ item.py # Item model
+ routes/ # Route handlers
+ __init__.py # Package init
+ main.py # Main routes
+ api.py # API routes
+ forms/ # Form definitions
+ __init__.py # Package init
+ user.py # User forms
+ item.py # Item forms
+ __init__.py # App factory
+config.py # Configuration
+run.py # Entry point
+
+// Development Guidelines
+1. Flask Integration:
+ - Use application factory
+ - Implement Flask-WTF forms
+ - Follow Blueprint patterns
+ - Use Jinja2 templates
+ - Handle CSRF properly
+ - Follow Flask conventions
+
+2. HTMX Patterns:
+ - Use template filters
+ - Return partial HTML
+ - Handle form validation
+ - Implement error responses
+ - Show loading states
+ - Use proper targeting
+
+3. Database Patterns:
+ - Use SQLAlchemy ORM
+ - Optimize queries
+ - Handle transactions
+ - Implement caching
+ - Follow migrations
+ - Maintain consistency
+
+// Dependencies
+Core:
+- flask: "^2.3.0"
+- htmx: "^1.9.0"
+- python: "^3.8"
+- flask-sqlalchemy: "^3.0.0"
+
+Optional:
+- flask-wtf: "^1.1.0"
+- flask-migrate: "^4.0.0"
+- flask-login: "^0.6.0"
+- flask-caching: "^2.0.0"
+
+// Code Examples:
+
+1. Flask Route Pattern:
+```python
+from flask import Blueprint, render_template, request, jsonify
+from .models import Item
+from .forms import ItemForm
+
+bp = Blueprint('items', __name__)
+
+@bp.route('/items', methods=['GET'])
+def list_items():
+ page = request.args.get('page', 1, type=int)
+ items = Item.query.paginate(page=page, per_page=10)
+
+ # Check if HTMX request
+ if request.headers.get('HX-Request'):
+ return render_template(
+ 'components/item_list.html',
+ items=items
+ )
+
+ # Regular request - full page
+ return render_template(
+ 'pages/items.html',
+ items=items
+ )
+
+@bp.route('/items/create', methods=['POST'])
+def create_item():
+ form = ItemForm()
+
+ if form.validate_on_submit():
+ item = Item(
+ title=form.title.data,
+ description=form.description.data
+ )
+ db.session.add(item)
+ db.session.commit()
+
+ # Return new item HTML
+ return render_template(
+ 'components/item.html',
+ item=item
+ )
+
+ # Return form errors
+ return jsonify(form.errors), 400
+```
+
+2. Flask Template Pattern:
+```html
+{% extends "base.html" %}
+{% block content %}
+
+
+
+
+ {% include "components/item_list.html" %}
+
+
+ Loading more items...
+
+
+
+
+
+
+{% endblock %}
+```
+
+3. Flask Form Pattern:
+```python
+from flask_wtf import FlaskForm
+from wtforms import StringField, TextAreaField
+from wtforms.validators import DataRequired, Length
+
+class ItemForm(FlaskForm):
+ title = StringField(
+ 'Title',
+ validators=[
+ DataRequired(),
+ Length(min=3, max=100)
+ ]
+ )
+
+ description = TextAreaField(
+ 'Description',
+ validators=[
+ DataRequired(),
+ Length(min=10, max=500)
+ ]
+ )
+
+ def validate_title(self, field):
+ # Check for unique title
+ if Item.query.filter_by(title=field.data).first():
+ raise ValidationError('Title must be unique')
+
+# Custom response handler
+def handle_form_errors(form):
+ """Convert WTForms errors to HTMX-friendly response."""
+ errors = {}
+ for field, messages in form.errors.items():
+ errors[f"{field}-error"] = {
+ "innerHTML": " ".join(messages)
+ }
+
+ response = jsonify({
+ "errors": errors
+ })
+ response.status_code = 400
+ return response
+```
+
+// Best Practices:
+1. Follow Flask conventions
+2. Use Blueprints
+3. Implement proper forms
+4. Handle CSRF correctly
+5. Optimize database queries
+6. Use template inheritance
+7. Handle errors gracefully
+8. Write comprehensive tests
+9. Document endpoints
+10. Follow URL naming
+
+// Security Considerations:
+1. Enable CSRF protection
+2. Validate form inputs
+3. Sanitize HTML output
+4. Use proper permissions
+5. Handle file uploads safely
+6. Implement rate limiting
+7. Use HTTPS
+8. Secure configuration
+9. Audit dependencies
+10. Log security events
diff --git a/rules/htmx-go-basic-cursorrules-prompt-file/.cursorrules b/rules/htmx-go-basic-cursorrules-prompt-file/.cursorrules
index d5efd2b..14a936a 100644
--- a/rules/htmx-go-basic-cursorrules-prompt-file/.cursorrules
+++ b/rules/htmx-go-basic-cursorrules-prompt-file/.cursorrules
@@ -1,37 +1,321 @@
-// HTMX with Go (Basic Setup) .cursorrules
-
-// HTMX and Go best practices
-const htmxGoBestPractices = [
- "Use html/template for server-side rendering",
- "Implement http.HandlerFunc for handling HTMX requests",
- "Utilize gorilla/mux for routing if needed",
- "Use encoding/json for JSON responses",
- "Implement proper error handling and logging",
- "Utilize context for request cancellation and timeouts",
-];
-
-// Folder structure
-const folderStructure = `
+// HTMX with Go Development Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+Modern Go web applications with HTMX integration featuring:
+- Server-side rendered templates
+- Dynamic UI updates without JavaScript
+- Efficient HTTP handlers
+- Real-time interactions
+- RESTful endpoints
+- Infinite scrolling
+- Modal dialogs
+- Live search
+
+// Project Structure
cmd/
- main.go
-internal/
- handlers/
- models/
- templates/
-static/
- css/
- js/
-go.mod
-go.sum
-`;
-
-// Additional instructions
-const additionalInstructions = `
-1. Use semantic HTML5 elements with HTMX attributes
-2. Implement proper CSRF protection
-3. Utilize HTMX extensions when needed
-4. Use hx-boost for full page navigation
-5. Follow Go's idiomatic error handling
-6. Implement graceful shutdown for the server
-7. Use Go modules for dependency management
-`;
+ server/ # Application entrypoint
+ main.go # Server initialization
+internal/ # Private application code
+ handlers/ # HTTP handlers
+ items.go # Item handlers
+ users.go # User handlers
+ templates.go # Template helpers
+ models/ # Data models
+ item.go # Item model
+ user.go # User model
+ middleware/ # HTTP middleware
+ auth.go # Authentication
+ logging.go # Request logging
+ csrf.go # CSRF protection
+ templates/ # HTML templates
+ base.html # Base template
+ components/ # Reusable components
+ form.html # Form component
+ modal.html # Modal component
+ pages/ # Page templates
+ index.html # Home page
+ about.html # About page
+static/ # Static assets
+ css/ # Stylesheets
+ main.css # Main styles
+ js/ # JavaScript
+ htmx.min.js # HTMX library
+go.mod # Module definition
+go.sum # Module checksums
+
+// Development Guidelines
+1. Go Integration:
+ - Use http.Handler interface
+ - Implement middleware
+ - Follow idiomatic Go
+ - Use html/template
+ - Handle errors properly
+ - Follow Go conventions
+
+2. HTMX Patterns:
+ - Return partial HTML
+ - Handle form submissions
+ - Implement validation
+ - Show loading states
+ - Use proper targeting
+ - Follow REST principles
+
+3. Performance Patterns:
+ - Use goroutines safely
+ - Implement caching
+ - Handle timeouts
+ - Optimize templates
+ - Use connection pools
+ - Monitor resources
+
+// Dependencies
+Core:
+- go: ">=1.22"
+- htmx: "^1.9.0"
+- chi: "^5.0.0"
+- sqlx: "^1.3.0"
+
+Optional:
+- gorilla/csrf: "^1.7.0"
+- zap: "^1.24.0"
+- validator: "^10.0.0"
+- pgx: "^5.0.0"
+
+// Code Examples:
+
+1. HTTP Handler Pattern:
+```go
+package handlers
+
+import (
+ "html/template"
+ "net/http"
+ "strconv"
+)
+
+type ItemHandler struct {
+ tmpl *template.Template
+ db *sqlx.DB
+}
+
+func NewItemHandler(tmpl *template.Template, db *sqlx.DB) *ItemHandler {
+ return &ItemHandler{
+ tmpl: tmpl,
+ db: db,
+ }
+}
+
+func (h *ItemHandler) List(w http.ResponseWriter, r *http.Request) {
+ // Parse pagination params
+ page, _ := strconv.Atoi(r.URL.Query().Get("page"))
+ if page < 1 {
+ page = 1
+ }
+
+ // Fetch items
+ items, err := h.db.QueryContext(r.Context(), `
+ SELECT id, title, description
+ FROM items
+ ORDER BY created_at DESC
+ LIMIT 10 OFFSET $1
+ `, (page-1)*10)
+ if err != nil {
+ http.Error(w, "Failed to fetch items", http.StatusInternalServerError)
+ return
+ }
+ defer items.Close()
+
+ // Check if HTMX request
+ if r.Header.Get("HX-Request") == "true" {
+ h.tmpl.ExecuteTemplate(w, "components/item_list.html", items)
+ return
+ }
+
+ // Regular request - full page
+ h.tmpl.ExecuteTemplate(w, "pages/items.html", items)
+}
+
+func (h *ItemHandler) Create(w http.ResponseWriter, r *http.Request) {
+ // Parse form
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, "Invalid form data", http.StatusBadRequest)
+ return
+ }
+
+ // Validate input
+ title := r.Form.Get("title")
+ description := r.Form.Get("description")
+ if title == "" || description == "" {
+ http.Error(w, "Missing required fields", http.StatusBadRequest)
+ return
+ }
+
+ // Create item
+ var id int64
+ err := h.db.QueryRowContext(r.Context(), `
+ INSERT INTO items (title, description)
+ VALUES ($1, $2)
+ RETURNING id
+ `, title, description).Scan(&id)
+ if err != nil {
+ http.Error(w, "Failed to create item", http.StatusInternalServerError)
+ return
+ }
+
+ // Fetch new item
+ item := struct {
+ ID int64
+ Title string
+ Description string
+ }{}
+ err = h.db.GetContext(r.Context(), &item, `
+ SELECT id, title, description
+ FROM items WHERE id = $1
+ `, id)
+ if err != nil {
+ http.Error(w, "Failed to fetch item", http.StatusInternalServerError)
+ return
+ }
+
+ // Return new item HTML
+ h.tmpl.ExecuteTemplate(w, "components/item.html", item)
+}
+```
+
+2. Template Pattern:
+```html
+{{/* base.html */}}
+
+
+
+
+ {{template "title" .}}
+
+
+
+
+ {{template "content" .}}
+
+
+
+{{/* components/item_list.html */}}
+{{define "item-list"}}
+
+
+ {{range .Items}}
+
+
{{.Title}}
+
{{.Description}}
+
+
+
+ {{end}}
+
+
+ Loading more items...
+
+
+{{end}}
+
+{{/* components/item_form.html */}}
+{{define "item-form"}}
+
+{{end}}
+```
+
+3. Router Pattern:
+```go
+package main
+
+import (
+ "net/http"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/go-chi/chi/v5/middleware"
+)
+
+func setupRouter(h *handlers.ItemHandler) http.Handler {
+ r := chi.NewRouter()
+
+ // Middleware
+ r.Use(middleware.Logger)
+ r.Use(middleware.Recoverer)
+ r.Use(middleware.RealIP)
+ r.Use(middleware.RequestID)
+ r.Use(middleware.Timeout(60 * time.Second))
+
+ // Routes
+ r.Get("/", h.List)
+ r.Route("/items", func(r chi.Router) {
+ r.Get("/", h.List)
+ r.Post("/", h.Create)
+ r.Route("/{id}", func(r chi.Router) {
+ r.Get("/", h.Get)
+ r.Put("/", h.Update)
+ r.Delete("/", h.Delete)
+ })
+ })
+
+ // Static files
+ fileServer := http.FileServer(http.Dir("static"))
+ r.Handle("/static/*", http.StripPrefix("/static/", fileServer))
+
+ return r
+}
+```
+
+// Best Practices:
+1. Follow Go idioms
+2. Use proper interfaces
+3. Handle errors gracefully
+4. Implement middleware
+5. Optimize performance
+6. Use prepared statements
+7. Validate inputs
+8. Write unit tests
+9. Document code
+10. Follow naming conventions
+
+// Security Considerations:
+1. Enable CSRF protection
+2. Validate all inputs
+3. Sanitize HTML output
+4. Use proper headers
+5. Handle file uploads safely
+6. Implement rate limiting
+7. Use HTTPS
+8. Secure cookies
+9. Audit dependencies
+10. Log security events
diff --git a/rules/htmx-go-fiber-cursorrules-prompt-file/.cursorrules b/rules/htmx-go-fiber-cursorrules-prompt-file/.cursorrules
index ba5bb2d..a3d8662 100644
--- a/rules/htmx-go-fiber-cursorrules-prompt-file/.cursorrules
+++ b/rules/htmx-go-fiber-cursorrules-prompt-file/.cursorrules
@@ -1,37 +1,317 @@
-// HTMX with Go and Fiber .cursorrules
-
-// HTMX, Go, and Fiber best practices
-const htmxGoFiberBestPractices = [
- "Use Fiber's HTML rendering for server-side templates",
- "Implement Fiber's routing system for HTMX requests",
- "Utilize Fiber's middleware for request processing",
- "Use Fiber's JSON methods for API responses",
- "Implement proper error handling with Fiber's error handling",
- "Utilize Fiber's static file serving for assets",
-];
-
-// Folder structure
-const folderStructure = `
+// HTMX with Go Fiber Development Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+Modern Go web applications with HTMX and Fiber integration featuring:
+- High-performance server-side rendering
+- Dynamic UI updates without JavaScript
+- Fast HTTP routing with Fiber
+- Real-time interactions
+- RESTful endpoints
+- WebSocket support
+- Modal dialogs
+- Live search
+
+// Project Structure
cmd/
- main.go
-internal/
- handlers/
- models/
- templates/
-static/
- css/
- js/
-go.mod
-go.sum
-`;
-
-// Additional instructions
-const additionalInstructions = `
-1. Use Fiber's App.Get/Post/etc for routing HTMX requests
-2. Implement CSRF protection with Fiber middleware
-3. Utilize Fiber's Context for handling HTMX-specific headers
-4. Use Fiber's template engine for server-side rendering
-5. Implement proper logging with Fiber's Logger middleware
-6. Follow Fiber's best practices for project structure
-7. Use environment variables for configuration
-`;
+ server/ # Application entrypoint
+ main.go # Server initialization
+internal/ # Private application code
+ handlers/ # HTTP handlers
+ items.go # Item handlers
+ users.go # User handlers
+ templates.go # Template helpers
+ models/ # Data models
+ item.go # Item model
+ user.go # User model
+ middleware/ # Fiber middleware
+ auth.go # Authentication
+ logging.go # Request logging
+ csrf.go # CSRF protection
+ templates/ # HTML templates
+ layouts/ # Template layouts
+ main.html # Main layout
+ views/ # View templates
+ index.html # Home page
+ about.html # About page
+ partials/ # Partial templates
+ form.html # Form partial
+ modal.html # Modal partial
+static/ # Static assets
+ css/ # Stylesheets
+ main.css # Main styles
+ js/ # JavaScript
+ htmx.min.js # HTMX library
+go.mod # Module definition
+go.sum # Module checksums
+
+// Development Guidelines
+1. Fiber Integration:
+ - Use fiber.Handler interface
+ - Implement Fiber middleware
+ - Follow idiomatic Go
+ - Use html/template or Fiber Views
+ - Handle errors properly
+ - Follow Fiber conventions
+
+2. HTMX Patterns:
+ - Return partial HTML
+ - Handle form submissions
+ - Implement validation
+ - Show loading states
+ - Use proper targeting
+ - Follow REST principles
+
+3. Performance Patterns:
+ - Use Fiber's FastHTTP
+ - Implement caching
+ - Handle timeouts
+ - Optimize templates
+ - Use connection pools
+ - Monitor resources
+
+// Dependencies
+Core:
+- go: ">=1.22"
+- fiber: "^2.52.0"
+- htmx: "^1.9.0"
+- sqlx: "^1.3.0"
+
+Optional:
+- fiber/csrf: "^2.52.0"
+- zap: "^1.24.0"
+- validator: "^10.0.0"
+- pgx: "^5.0.0"
+
+// Code Examples:
+
+1. Fiber Handler Pattern:
+```go
+package handlers
+
+import (
+ "github.com/gofiber/fiber/v2"
+ "github.com/jmoiron/sqlx"
+)
+
+type ItemHandler struct {
+ db *sqlx.DB
+}
+
+func NewItemHandler(db *sqlx.DB) *ItemHandler {
+ return &ItemHandler{
+ db: db,
+ }
+}
+
+func (h *ItemHandler) List(c *fiber.Ctx) error {
+ // Parse pagination params
+ page := c.QueryInt("page", 1)
+ if page < 1 {
+ page = 1
+ }
+
+ // Fetch items
+ var items []struct {
+ ID int64 `db:"id"`
+ Title string `db:"title"`
+ Description string `db:"description"`
+ }
+ err := h.db.SelectContext(c.Context(), &items, `
+ SELECT id, title, description
+ FROM items
+ ORDER BY created_at DESC
+ LIMIT 10 OFFSET $1
+ `, (page-1)*10)
+ if err != nil {
+ return c.Status(500).SendString("Failed to fetch items")
+ }
+
+ // Check if HTMX request
+ if c.Get("HX-Request") == "true" {
+ return c.Render("partials/item_list", fiber.Map{
+ "Items": items,
+ })
+ }
+
+ // Regular request - full page
+ return c.Render("views/items", fiber.Map{
+ "Items": items,
+ })
+}
+
+func (h *ItemHandler) Create(c *fiber.Ctx) error {
+ // Parse form
+ title := c.FormValue("title")
+ description := c.FormValue("description")
+ if title == "" || description == "" {
+ return c.Status(400).SendString("Missing required fields")
+ }
+
+ // Create item
+ var id int64
+ err := h.db.QueryRowContext(c.Context(), `
+ INSERT INTO items (title, description)
+ VALUES ($1, $2)
+ RETURNING id
+ `, title, description).Scan(&id)
+ if err != nil {
+ return c.Status(500).SendString("Failed to create item")
+ }
+
+ // Fetch new item
+ item := struct {
+ ID int64 `db:"id"`
+ Title string `db:"title"`
+ Description string `db:"description"`
+ }{}
+ err = h.db.GetContext(c.Context(), &item, `
+ SELECT id, title, description
+ FROM items WHERE id = $1
+ `, id)
+ if err != nil {
+ return c.Status(500).SendString("Failed to fetch item")
+ }
+
+ // Return new item HTML
+ return c.Render("partials/item", fiber.Map{
+ "Item": item,
+ })
+}
+```
+
+2. Template Pattern:
+```html
+{{/* layouts/main.html */}}
+
+
+
+
+ {{.Title}}
+
+
+
+
+ {{embed}}
+
+
+
+{{/* partials/item_list.html */}}
+
+
+
+ );
+}
+```
+
+4. Form Pattern:
+```tsx
+// src/components/forms/TextField/TextField.tsx
+import { forwardRef } from 'react';
+import { TextField as MuiTextField, TextFieldProps as MuiTextFieldProps } from '@mui/material';
+import { twMerge } from 'tailwind-merge';
+
+export interface TextFieldProps extends MuiTextFieldProps {
+ error?: boolean;
+ helperText?: string;
+}
+
+export const TextField = forwardRef(
+ ({ className, error, helperText, ...props }, ref) => {
+ return (
+
+ );
+ }
+);
+
+TextField.displayName = 'TextField';
+```
+
+5. Card Pattern:
+```tsx
+// src/components/ui/Card/Card.tsx
+import { forwardRef } from 'react';
+import { Card as MuiCard, CardProps as MuiCardProps } from '@mui/material';
+import { twMerge } from 'tailwind-merge';
+
+export interface CardProps extends MuiCardProps {
+ elevation?: number;
+}
+
+export const Card = forwardRef(
+ ({ className, elevation = 1, ...props }, ref) => {
+ return (
+
+ );
+ }
+);
+
+Card.displayName = 'Card';
+```
+
+// Best Practices:
+1. Component Design:
+ - Composition
+ - Reusability
+ - Accessibility
+ - Performance
+ - Testing
+ - Documentation
+
+2. Styling:
+ - Theme consistency
+ - Responsive design
+ - Dark mode
+ - Custom variants
+ - Utility classes
+ - CSS-in-JS
+
+3. Performance:
+ - Code splitting
+ - Tree shaking
+ - Bundle size
+ - Image optimization
+ - Font loading
+ - Caching
+
+4. Accessibility:
+ - ARIA labels
+ - Keyboard navigation
+ - Focus management
+ - Color contrast
+ - Screen readers
+ - Semantic HTML
+
+// Security Considerations:
+1. Client Security:
+ - Input validation
+ - XSS prevention
+ - CSRF protection
+ - Content security
+ - Error handling
+ - Logging
+
+2. Data Security:
+ - Form validation
+ - Data sanitization
+ - Access control
+ - State management
+ - Error messages
+ - Logging
+
+3. Infrastructure:
+ - HTTPS
+ - CORS
+ - CSP
+ - Rate limiting
+ - Monitoring
+ - Logging
\ No newline at end of file
diff --git a/rules/py-fast-api/.cursorrules b/rules/py-fast-api/.cursorrules
index 073332a..2b0ceea 100644
--- a/rules/py-fast-api/.cursorrules
+++ b/rules/py-fast-api/.cursorrules
@@ -1,62 +1,152 @@
-You are an expert in Python, FastAPI, and scalable API development.
-
-Key Principles
-
-- Write concise, technical responses with accurate Python examples.
-- Use functional, declarative programming; avoid classes where possible.
-- Prefer iteration and modularization over code duplication.
-- Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission).
-- Use lowercase with underscores for directories and files (e.g., routers/user_routes.py).
-- Favor named exports for routes and utility functions.
-- Use the Receive an Object, Return an Object (RORO) pattern.
-
-Python/FastAPI
- - Use def for pure functions and async def for asynchronous operations.
- - Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation.
- - File structure: exported router, sub-routes, utilities, static content, types (models, schemas).
- - Avoid unnecessary curly braces in conditional statements.
- - For single-line statements in conditionals, omit curly braces.
- - Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()).
-
-Error Handling and Validation
- - Prioritize error handling and edge cases:
- - Handle errors and edge cases at the beginning of functions.
- - Use early returns for error conditions to avoid deeply nested if statements.
- - Place the happy path last in the function for improved readability.
- - Avoid unnecessary else statements; use the if-return pattern instead.
- - Use guard clauses to handle preconditions and invalid states early.
- - Implement proper error logging and user-friendly error messages.
- - Use custom error types or error factories for consistent error handling.
-
-Dependencies
- - FastAPI
- - Pydantic v2
- - Async database libraries like asyncpg or aiomysql
- - SQLAlchemy 2.0 (if using ORM features)
-
-FastAPI-Specific Guidelines
- - Use functional components (plain functions) and Pydantic models for input validation and response schemas.
- - Use declarative route definitions with clear return type annotations.
- - Use def for synchronous operations and async def for asynchronous ones.
- - Minimize @app.on_event("startup") and @app.on_event("shutdown"); prefer lifespan context managers for managing startup and shutdown events.
- - Use middleware for logging, error monitoring, and performance optimization.
- - Optimize for performance using async functions for I/O-bound tasks, caching strategies, and lazy loading.
- - Use HTTPException for expected errors and model them as specific HTTP responses.
- - Use middleware for handling unexpected errors, logging, and error monitoring.
- - Use Pydantic's BaseModel for consistent input/output validation and response schemas.
-
-Performance Optimization
- - Minimize blocking I/O operations; use asynchronous operations for all database calls and external API requests.
- - Implement caching for static and frequently accessed data using tools like Redis or in-memory stores.
- - Optimize data serialization and deserialization with Pydantic.
- - Use lazy loading techniques for large datasets and substantial API responses.
-
-Key Conventions
- 1. Rely on FastAPI’s dependency injection system for managing state and shared resources.
- 2. Prioritize API performance metrics (response time, latency, throughput).
- 3. Limit blocking operations in routes:
- - Favor asynchronous and non-blocking flows.
- - Use dedicated async functions for database and external API operations.
- - Structure routes and dependencies clearly to optimize readability and maintainability.
-
-Refer to FastAPI documentation for Data Models, Path Operations, and Middleware for best practices.
+// FastAPI Expert Development Guidelines
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A production-ready FastAPI application with:
+- Scalable and maintainable API architecture
+- Efficient async/await patterns
+- Type-safe request/response handling
+- Robust error management
+- Performance-optimized endpoints
+- Clean, functional programming style
+
+// Project Structure
+src/
+ routers/ # Route handlers by domain
+ user_routes.py # User routes
+ auth_routes.py # Authentication routes
+ models/ # Pydantic models and schemas
+ domain/ # Domain models
+ schemas/ # Request/Response schemas
+ services/ # Business logic
+ utils/ # Shared utilities
+ middleware/ # Custom middleware
+ config/ # Configuration management
+ tests/ # Test suites
+
+// Development Guidelines
+1. Code Quality:
+ - Use functional, declarative programming over OOP
+ - Implement type hints for all function signatures
+ - Follow PEP 8 style guidelines
+ - Use descriptive variable names with auxiliary verbs
+ - Keep functions focused and small
+ - Prefer composition over inheritance
+
+2. API Design:
+ - Use Pydantic models for request/response validation
+ - Implement clear endpoint naming conventions
+ - Structure routes logically by domain
+ - Use appropriate HTTP methods and status codes
+ - Version APIs explicitly when needed
+ - Document all endpoints with OpenAPI specs
+
+3. Error Handling:
+ - Handle errors at function entry points
+ - Use early returns to avoid nested conditionals
+ - Implement custom error types for domain-specific errors
+ - Provide clear, actionable error messages
+ - Log errors with appropriate context
+ - Use HTTPException for API errors
+
+4. Performance:
+ - Use async operations for I/O-bound tasks
+ - Implement caching strategies
+ - Optimize database queries
+ - Use connection pooling
+ - Implement proper indexing
+ - Monitor and optimize response times
+
+// Dependencies
+Core:
+- FastAPI
+- Pydantic v2
+- SQLAlchemy 2.0
+- asyncpg/aiomysql
+- uvicorn
+- python-jose[cryptography]
+- passlib[bcrypt]
+
+Optional:
+- Redis (caching)
+- Celery (background tasks)
+- Prometheus (metrics)
+- Sentry (error tracking)
+
+// Code Examples:
+
+1. Route Definition Pattern:
+```python
+from fastapi import APIRouter, Depends, HTTPException
+from typing import List
+from pydantic import BaseModel
+
+router = APIRouter(prefix="/users", tags=["users"])
+
+class UserResponse(BaseModel):
+ id: int
+ username: str
+ email: str
+
+@router.get("/{user_id}", response_model=UserResponse)
+async def get_user(user_id: int, db: Database = Depends(get_db)):
+ if not (user := await db.users.get(user_id)):
+ raise HTTPException(status_code=404, detail="User not found")
+ return user
+```
+
+2. Error Handling Pattern:
+```python
+from fastapi import HTTPException
+from typing import Optional
+
+async def get_user_or_404(user_id: int, db: Database) -> User:
+ # Early return pattern
+ if not user_id:
+ raise HTTPException(status_code=400, detail="User ID is required")
+
+ if not (user := await db.users.get(user_id)):
+ raise HTTPException(status_code=404, detail="User not found")
+
+ return user
+```
+
+3. Dependency Injection Pattern:
+```python
+from fastapi import Depends
+from typing import AsyncGenerator
+
+async def get_db() -> AsyncGenerator[Database, None]:
+ async with Database() as db:
+ yield db
+
+async def get_current_user(
+ token: str = Depends(oauth2_scheme),
+ db: Database = Depends(get_db)
+) -> User:
+ return await validate_token_and_get_user(token, db)
+```
+
+// Best Practices:
+1. Use dependency injection for shared resources
+2. Implement proper connection pooling
+3. Use async context managers for resource cleanup
+4. Implement proper request validation
+5. Use appropriate status codes
+6. Implement proper logging
+7. Use proper error handling
+8. Implement proper caching
+9. Use proper security measures
+10. Implement proper testing
+
+// Security Considerations:
+1. Implement proper authentication
+2. Use proper authorization
+3. Implement rate limiting
+4. Use CORS properly
+5. Implement proper input validation
+6. Use secure headers
+7. Implement proper logging
+8. Use proper error handling
+9. Implement proper security headers
+10. Use proper SSL/TLS
diff --git a/rules/python-312-fastapi-best-practices-cursorrules-prom/.cursorrules b/rules/python-312-fastapi-best-practices-cursorrules-prom/.cursorrules
index 01d18dd..772f7a8 100644
--- a/rules/python-312-fastapi-best-practices-cursorrules-prom/.cursorrules
+++ b/rules/python-312-fastapi-best-practices-cursorrules-prom/.cursorrules
@@ -1 +1,196 @@
-Here are some best practices and rules you must follow:- You use Python 3.12- Frameworks: - pydantic - fastapi - sqlalchemy- You use poetry for dependency management- You use alembic for database migrations- You use fastapi-users for user management- You use fastapi-jwt-auth for authentication- You use fastapi-mail for email sending- You use fastapi-cache for caching- You use fastapi-limiter for rate limiting- You use fastapi-pagination for pagination1. **Use Meaningful Names**: Choose descriptive variable, function, and class names.2. **Follow PEP 8**: Adhere to the Python Enhancement Proposal 8 style guide for formatting.3. **Use Docstrings**: Document functions and classes with docstrings to explain their purpose.4. **Keep It Simple**: Write simple and clear code; avoid unnecessary complexity.5. **Use List Comprehensions**: Prefer list comprehensions for creating lists over traditional loops when appropriate.6. **Handle Exceptions**: Use try-except blocks to handle exceptions gracefully.7. **Use Virtual Environments**: Isolate project dependencies using virtual environments (e.g., `venv`).8. **Write Tests**: Implement unit tests to ensure code reliability.9. **Use Type Hints**: Utilize type hints for better code clarity and type checking.10. **Avoid Global Variables**: Limit the use of global variables to reduce side effects.These rules will help you write clean, efficient, and maintainable Python code.
\ No newline at end of file
+// Python 3.12 FastAPI Best Practices Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern FastAPI application leveraging Python 3.12's latest features:
+- Type-safe API endpoints
+- High-performance async operations
+- Modern dependency injection
+- Enhanced error handling
+- Improved type annotations
+- Optimized async context managers
+- Exception groups support
+- Enhanced debugging capabilities
+
+// Project Structure
+src/
+ api/
+ v1/
+ routers/ # Route modules
+ models/ # Pydantic v2 models
+ dependencies/ # FastAPI dependencies
+ core/
+ config/ # App configuration
+ logging/ # Structured logging
+ exceptions/ # Custom exceptions
+ services/ # Business logic
+ auth/ # Authentication
+ data/ # Data processing
+ tests/ # Test suites
+ unit/ # Unit tests
+ integration/ # Integration tests
+ utils/ # Utilities
+ main.py # Entry point
+
+// Development Guidelines
+1. Python 3.12 Features:
+ - Use PEP 695 type aliases
+ - Implement f-string debug syntax
+ - Utilize exception groups
+ - Use enhanced error locations
+ - Implement async context managers
+ - Use improved typing features
+
+2. FastAPI Best Practices:
+ - Use Pydantic v2 models
+ - Implement proper dependency injection
+ - Use async endpoints
+ - Handle errors gracefully
+ - Document with OpenAPI
+ - Use proper status codes
+
+3. Code Quality:
+ - Use type hints everywhere
+ - Implement proper logging
+ - Write comprehensive tests
+ - Use async patterns correctly
+ - Document all components
+ - Follow PEP 8 guidelines
+
+// Dependencies
+Core:
+- python>=3.12.0
+- fastapi>=0.100.0
+- pydantic>=2.0.0
+- uvicorn[standard]>=0.23.0
+- python-jose[cryptography]>=3.3.0
+- passlib[bcrypt]>=1.7.4
+- pytest>=7.4.0
+- httpx>=0.24.0
+
+Optional:
+- pytest-asyncio>=0.21.0
+- pytest-cov>=4.1.0
+- black>=23.7.0
+- ruff>=0.0.280
+- mypy>=1.5.0
+
+// Code Examples:
+
+1. Modern Type Hints (PEP 695):
+```python
+from typing import TypeVar, Generic
+from fastapi import FastAPI, Depends
+from pydantic import BaseModel
+
+type UserId = int
+type Email = str
+
+class UserBase(BaseModel):
+ email: Email
+ is_active: bool = True
+
+class UserCreate(UserBase):
+ password: str
+
+class User(UserBase):
+ id: UserId
+
+ class Config:
+ from_attributes = True
+
+type PaginatedResponse[T] = dict[str, list[T] | int]
+
+async def get_users(
+ skip: int = 0,
+ limit: int = 100
+) -> PaginatedResponse[User]:
+ users = await user_service.get_users(skip, limit)
+ total = await user_service.count_users()
+ return {"items": users, "total": total}
+```
+
+2. Exception Groups:
+```python
+from fastapi import HTTPException
+from typing import Sequence
+
+class ValidationError(Exception):
+ def __init__(self, field: str, message: str):
+ self.field = field
+ self.message = message
+
+async def validate_user_data(user: UserCreate) -> None:
+ errors: list[ValidationError] = []
+
+ if await user_service.email_exists(user.email):
+ errors.append(ValidationError("email", "Email already registered"))
+
+ if len(user.password) < 8:
+ errors.append(ValidationError("password", "Password too short"))
+
+ if errors:
+ raise ExceptionGroup(
+ "User validation failed",
+ errors
+ )
+
+@app.post("/users/")
+async def create_user(user: UserCreate):
+ try:
+ await validate_user_data(user)
+ return await user_service.create_user(user)
+ except* ValidationError as eg:
+ raise HTTPException(
+ status_code=400,
+ detail=[{"field": e.field, "message": e.message} for e in eg.exceptions]
+ )
+```
+
+3. Enhanced Async Context Managers:
+```python
+from contextlib import asynccontextmanager
+from fastapi import FastAPI
+from typing import AsyncGenerator
+
+@asynccontextmanager
+async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
+ # Startup
+ await db.connect()
+ await cache.connect()
+ await metrics.start()
+
+ try:
+ yield
+ finally:
+ # Shutdown
+ await metrics.stop()
+ await cache.disconnect()
+ await db.disconnect()
+
+app = FastAPI(lifespan=lifespan)
+```
+
+// Best Practices:
+1. Use Python 3.12's type system
+2. Implement proper error handling
+3. Use async operations correctly
+4. Document with OpenAPI
+5. Write comprehensive tests
+6. Use proper logging
+7. Implement security best practices
+8. Use proper dependency injection
+9. Follow REST principles
+10. Monitor performance
+
+// Security Considerations:
+1. Use proper authentication
+2. Implement authorization
+3. Validate all inputs
+4. Use HTTPS
+5. Implement rate limiting
+6. Use secure password hashing
+7. Implement proper CORS
+8. Use secure headers
+9. Implement audit logging
+10. Use proper session management
\ No newline at end of file
diff --git a/rules/python-django-best-practices-cursorrules-prompt-fi/.cursorrules b/rules/python-django-best-practices-cursorrules-prompt-fi/.cursorrules
index 1fcde64..1866ac5 100644
--- a/rules/python-django-best-practices-cursorrules-prompt-fi/.cursorrules
+++ b/rules/python-django-best-practices-cursorrules-prompt-fi/.cursorrules
@@ -1 +1,286 @@
-You are an expert in Python, Django, and scalable web application development. Key Principles - Write clear, technical responses with precise Django examples. - Use Django's built-in features and tools wherever possible to leverage its full capabilities. - Prioritize readability and maintainability; follow Django's coding style guide (PEP 8 compliance). - Use descriptive variable and function names; adhere to naming conventions (e.g., lowercase with underscores for functions and variables). - Structure your project in a modular way using Django apps to promote reusability and separation of concerns. Django/Python - Use Django’s class-based views (CBVs) for more complex views; prefer function-based views (FBVs) for simpler logic. - Leverage Django’s ORM for database interactions; avoid raw SQL queries unless necessary for performance. - Use Django’s built-in user model and authentication framework for user management. - Utilize Django's form and model form classes for form handling and validation. - Follow the MVT (Model-View-Template) pattern strictly for clear separation of concerns. - Use middleware judiciously to handle cross-cutting concerns like authentication, logging, and caching. Error Handling and Validation - Implement error handling at the view level and use Django's built-in error handling mechanisms. - Use Django's validation framework to validate form and model data. - Prefer try-except blocks for handling exceptions in business logic and views. - Customize error pages (e.g., 404, 500) to improve user experience and provide helpful information. - Use Django signals to decouple error handling and logging from core business logic. Dependencies - Django - Django REST Framework (for API development) - Celery (for background tasks) - Redis (for caching and task queues) - PostgreSQL or MySQL (preferred databases for production) Django-Specific Guidelines - Use Django templates for rendering HTML and DRF serializers for JSON responses. - Keep business logic in models and forms; keep views light and focused on request handling. - Use Django's URL dispatcher (urls.py) to define clear and RESTful URL patterns. - Apply Django's security best practices (e.g., CSRF protection, SQL injection protection, XSS prevention). - Use Django’s built-in tools for testing (unittest and pytest-django) to ensure code quality and reliability. - Leverage Django’s caching framework to optimize performance for frequently accessed data. - Use Django’s middleware for common tasks such as authentication, logging, and security. Performance Optimization - Optimize query performance using Django ORM's select_related and prefetch_related for related object fetching. - Use Django’s cache framework with backend support (e.g., Redis or Memcached) to reduce database load. - Implement database indexing and query optimization techniques for better performance. - Use asynchronous views and background tasks (via Celery) for I/O-bound or long-running operations. - Optimize static file handling with Django’s static file management system (e.g., WhiteNoise or CDN integration). Key Conventions 1. Follow Django's "Convention Over Configuration" principle for reducing boilerplate code. 2. Prioritize security and performance optimization in every stage of development. 3. Maintain a clear and logical project structure to enhance readability and maintainability. Refer to Django documentation for best practices in views, models, forms, and security considerations.
\ No newline at end of file
+// Python Django Best Practices Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Django application following best practices:
+- Scalable web applications
+- RESTful APIs
+- Database-driven systems
+- Authentication systems
+- Admin interfaces
+- Background tasks
+- File handling
+- Email processing
+
+// Project Structure
+project_name/
+ manage.py # Django management script
+ config/ # Project configuration
+ settings/ # Settings modules
+ base.py # Base settings
+ local.py # Local development
+ prod.py # Production settings
+ urls.py # Root URL config
+ wsgi.py # WSGI config
+ asgi.py # ASGI config
+ apps/ # Django applications
+ core/ # Core functionality
+ models.py # Database models
+ views.py # View logic
+ urls.py # URL patterns
+ admin.py # Admin interface
+ forms.py # Form definitions
+ users/ # User management
+ api/ # API endpoints
+ services/ # Business logic
+ handlers/ # Service handlers
+ tasks/ # Background tasks
+ utils/ # Utility functions
+ templates/ # HTML templates
+ static/ # Static files
+ media/ # User uploads
+ tests/ # Test suites
+ unit/ # Unit tests
+ integration/ # Integration tests
+ docs/ # Documentation
+
+// Development Guidelines
+1. Django Patterns:
+ - Use class-based views
+ - Implement proper models
+ - Handle forms properly
+ - Use proper middleware
+ - Implement proper signals
+ - Handle migrations properly
+
+2. Database Best Practices:
+ - Use proper indexes
+ - Optimize queries
+ - Handle transactions
+ - Use proper models
+ - Implement migrations
+ - Handle connections
+
+3. Security Practices:
+ - Use proper authentication
+ - Handle permissions
+ - Implement CSRF
+ - Use proper validation
+ - Handle sessions
+ - Secure file uploads
+
+// Dependencies
+Core:
+- python: ">=3.9,<4.0"
+- django: "~4.2.0"
+- djangorestframework: "~3.14.0"
+- celery: "~5.3.0"
+- psycopg2-binary: "~2.9.0"
+- python-dotenv: "~1.0.0"
+- gunicorn: "~21.2.0"
+
+Optional:
+- django-debug-toolbar: "~4.2.0"
+- django-extensions: "~3.2.0"
+- pytest-django: "~4.5.0"
+- factory-boy: "~3.3.0"
+- coverage: "~7.3.0"
+
+// Code Examples:
+
+1. Model Pattern:
+```python
+from django.db import models
+from django.contrib.auth import get_user_model
+from django.utils.translation import gettext_lazy as _
+
+User = get_user_model()
+
+class BaseModel(models.Model):
+ created_at = models.DateTimeField(
+ _("Created at"),
+ auto_now_add=True
+ )
+ updated_at = models.DateTimeField(
+ _("Updated at"),
+ auto_now=True
+ )
+
+ class Meta:
+ abstract = True
+
+class Article(BaseModel):
+ title = models.CharField(
+ _("Title"),
+ max_length=200
+ )
+ content = models.TextField(_("Content"))
+ author = models.ForeignKey(
+ User,
+ on_delete=models.CASCADE,
+ related_name="articles",
+ verbose_name=_("Author")
+ )
+ status = models.CharField(
+ _("Status"),
+ max_length=20,
+ choices=[
+ ("draft", _("Draft")),
+ ("published", _("Published")),
+ ],
+ default="draft"
+ )
+ tags = models.ManyToManyField(
+ "Tag",
+ related_name="articles",
+ verbose_name=_("Tags")
+ )
+
+ class Meta:
+ verbose_name = _("Article")
+ verbose_name_plural = _("Articles")
+ ordering = ["-created_at"]
+ indexes = [
+ models.Index(fields=["status", "-created_at"]),
+ ]
+
+ def __str__(self):
+ return self.title
+
+ def save(self, *args, **kwargs):
+ # Custom save logic
+ super().save(*args, **kwargs)
+```
+
+2. View Pattern:
+```python
+from django.views.generic import ListView, DetailView
+from django.contrib.auth.mixins import LoginRequiredMixin
+from django.db.models import Prefetch
+from django.utils.translation import gettext as _
+from django.contrib import messages
+
+class ArticleListView(LoginRequiredMixin, ListView):
+ model = Article
+ template_name = "articles/list.html"
+ context_object_name = "articles"
+ paginate_by = 20
+
+ def get_queryset(self):
+ return (
+ Article.objects
+ .select_related("author")
+ .prefetch_related(
+ Prefetch(
+ "tags",
+ queryset=Tag.objects.only("name")
+ )
+ )
+ .filter(status="published")
+ .order_by("-created_at")
+ )
+
+ def get_context_data(self, **kwargs):
+ context = super().get_context_data(**kwargs)
+ context["title"] = _("Articles")
+ return context
+
+class ArticleDetailView(LoginRequiredMixin, DetailView):
+ model = Article
+ template_name = "articles/detail.html"
+ context_object_name = "article"
+
+ def get_object(self, queryset=None):
+ obj = super().get_object(queryset)
+
+ if not self.request.user.has_perm("view_article", obj):
+ messages.error(
+ self.request,
+ _("You don't have permission to view this article")
+ )
+ raise PermissionDenied
+
+ return obj
+```
+
+3. Form Pattern:
+```python
+from django import forms
+from django.core.exceptions import ValidationError
+from django.utils.translation import gettext_lazy as _
+
+class ArticleForm(forms.ModelForm):
+ tags = forms.CharField(
+ required=False,
+ help_text=_("Comma separated tags")
+ )
+
+ class Meta:
+ model = Article
+ fields = ["title", "content", "status", "tags"]
+ widgets = {
+ "content": forms.Textarea(
+ attrs={"rows": 10}
+ ),
+ }
+
+ def clean_tags(self):
+ tags = self.cleaned_data["tags"]
+ if not tags:
+ return []
+
+ tag_names = [
+ name.strip()
+ for name in tags.split(",")
+ if name.strip()
+ ]
+
+ if len(tag_names) > 5:
+ raise ValidationError(
+ _("Maximum 5 tags allowed")
+ )
+
+ return tag_names
+
+ def save(self, commit=True):
+ article = super().save(commit=False)
+
+ if commit:
+ article.save()
+
+ # Handle tags
+ if "tags" in self.cleaned_data:
+ tags = []
+ for tag_name in self.cleaned_data["tags"]:
+ tag, _ = Tag.objects.get_or_create(
+ name=tag_name
+ )
+ tags.append(tag)
+ article.tags.set(tags)
+
+ return article
+```
+
+// Best Practices:
+1. Follow Django conventions
+2. Use proper models
+3. Implement caching
+4. Handle errors properly
+5. Use proper forms
+6. Write comprehensive tests
+7. Document code properly
+8. Use proper logging
+9. Handle updates properly
+10. Optimize performance
+
+// Security Considerations:
+1. Validate user input
+2. Use proper authentication
+3. Handle permissions
+4. Implement CSRF protection
+5. Secure file uploads
+6. Use proper session handling
+7. Implement rate limiting
+8. Handle sensitive data
+9. Use secure headers
+10. Follow security updates
\ No newline at end of file
diff --git a/rules/python-fastapi-best-practices-cursorrules-prompt-f/.cursorrules b/rules/python-fastapi-best-practices-cursorrules-prompt-f/.cursorrules
index 8306a1e..0ea5776 100644
--- a/rules/python-fastapi-best-practices-cursorrules-prompt-f/.cursorrules
+++ b/rules/python-fastapi-best-practices-cursorrules-prompt-f/.cursorrules
@@ -1 +1,172 @@
-You are an expert in Python, FastAPI, and scalable API development.Write concise, technical responses with accurate Python examples.Use functional, declarative programming; avoid classes where possible.Prefer iteration and modularization over code duplication.Use descriptive variable names with auxiliary verbs (e.g., is_active, has_permission).Use lowercase with underscores for directories and files (e.g., routers/user_routes.py).Favor named exports for routes and utility functions.Use the Receive an Object, Return an Object (RORO) pattern.Use def for pure functions and async def for asynchronous operations.Use type hints for all function signatures. Prefer Pydantic models over raw dictionaries for input validation.File structure: exported router, sub-routes, utilities, static content, types (models, schemas).Avoid unnecessary curly braces in conditional statements.For single-line statements in conditionals, omit curly braces.Use concise, one-line syntax for simple conditional statements (e.g., if condition: do_something()).Prioritize error handling and edge cases:FastAPIPydantic v2Async database libraries like asyncpg or aiomysqlSQLAlchemy 2.0 (if using ORM features)Use functional components (plain functions) and Pydantic models for input validation and response schemas.Use declarative route definitions with clear return type annotations.Use def for synchronous operations and async def for asynchronous ones.Minimize @app.on_event("startup") and @app.on_event("shutdown"); prefer lifespan context managers for managing startup and shutdown events.Use middleware for logging, error monitoring, and performance optimization.Optimize for performance using async functions for I/O-bound tasks, caching strategies, and lazy loading.Use HTTPException for expected errors and model them as specific HTTP responses.Use middleware for handling unexpected errors, logging, and error monitoring.Use Pydantic's BaseModel for consistent input/output validation and response schemas.Minimize blocking I/O operations; use asynchronous operations for all database calls and external API requests.Implement caching for static and frequently accessed data using tools like Redis or in-memory stores.Optimize data serialization and deserialization with Pydantic.Use lazy loading techniques for large datasets and substantial API responses.Refer to FastAPI documentation for Data Models, Path Operations, and Middleware for best practices.
\ No newline at end of file
+// FastAPI Best Practices Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A production-grade FastAPI application following industry best practices:
+- Enterprise-level API architecture
+- Scalable and maintainable codebase
+- Type-safe and validated endpoints
+- Comprehensive error handling
+- Performance-optimized services
+- Security-first approach
+- Automated testing suite
+
+// Project Structure
+src/
+ api/ # API layer
+ v1/ # API version
+ endpoints/ # Route handlers
+ models/ # Pydantic models
+ core/ # Core application code
+ config/ # Configuration management
+ security/ # Authentication & authorization
+ logging/ # Logging configuration
+ db/ # Database
+ models/ # SQLAlchemy models
+ migrations/ # Alembic migrations
+ repositories/ # Database operations
+ services/ # Business logic
+ tests/ # Test suites
+ unit/
+ integration/
+ utils/ # Utility functions
+ main.py # Application entry point
+
+// Development Guidelines
+1. API Design:
+ - Use semantic versioning for API endpoints
+ - Implement comprehensive request/response validation
+ - Follow REST principles consistently
+ - Use appropriate HTTP methods and status codes
+ - Implement proper error responses
+ - Document all endpoints with OpenAPI specs
+
+2. Code Organization:
+ - Separate concerns (API, business logic, data access)
+ - Use dependency injection
+ - Implement repository pattern for data access
+ - Keep controllers thin, services rich
+ - Use proper type annotations
+ - Follow single responsibility principle
+
+3. Performance:
+ - Use async/await for I/O operations
+ - Implement proper database indexing
+ - Use connection pooling
+ - Implement caching strategies
+ - Use background tasks for heavy operations
+ - Monitor and optimize response times
+
+4. Testing:
+ - Write unit tests for business logic
+ - Implement integration tests for APIs
+ - Use pytest for testing
+ - Mock external dependencies
+ - Maintain high test coverage
+ - Use test factories for data generation
+
+// Dependencies
+Core:
+- fastapi>=0.100.0
+- pydantic>=2.0.0
+- sqlalchemy>=2.0.0
+- alembic>=1.11.0
+- uvicorn>=0.23.0
+- python-jose[cryptography]
+- passlib[bcrypt]
+- pytest>=7.4.0
+
+Optional:
+- celery
+- redis
+- prometheus-client
+- sentry-sdk
+- pytest-cov
+- pytest-asyncio
+
+// Code Examples:
+
+1. Dependency Injection Pattern:
+```python
+from fastapi import Depends, FastAPI
+from sqlalchemy.ext.asyncio import AsyncSession
+
+app = FastAPI()
+
+async def get_db() -> AsyncSession:
+ async with AsyncSessionLocal() as session:
+ try:
+ yield session
+ finally:
+ await session.close()
+
+async def get_current_user(
+ db: AsyncSession = Depends(get_db),
+ token: str = Depends(oauth2_scheme)
+) -> User:
+ return await auth_service.get_current_user(db, token)
+```
+
+2. Repository Pattern:
+```python
+from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy import select
+
+class UserRepository:
+ def __init__(self, session: AsyncSession):
+ self.session = session
+
+ async def get_by_id(self, user_id: int) -> Optional[User]:
+ query = select(User).where(User.id == user_id)
+ result = await self.session.execute(query)
+ return result.scalar_one_or_none()
+
+ async def create(self, user: UserCreate) -> User:
+ db_user = User(**user.dict())
+ self.session.add(db_user)
+ await self.session.commit()
+ await self.session.refresh(db_user)
+ return db_user
+```
+
+3. Service Layer Pattern:
+```python
+class UserService:
+ def __init__(self, repo: UserRepository):
+ self.repo = repo
+
+ async def create_user(self, user: UserCreate) -> User:
+ # Business logic validation
+ if await self.repo.get_by_email(user.email):
+ raise HTTPException(400, "Email already registered")
+
+ # Hash password
+ user.password = get_password_hash(user.password)
+
+ # Create user
+ return await self.repo.create(user)
+```
+
+// Best Practices:
+1. Use Pydantic for data validation
+2. Implement proper error handling
+3. Use async operations where appropriate
+4. Implement proper logging
+5. Use dependency injection
+6. Follow REST best practices
+7. Implement proper security measures
+8. Use proper database migrations
+9. Implement proper testing
+10. Use proper documentation
+
+// Security Considerations:
+1. Use proper authentication
+2. Implement authorization
+3. Validate all inputs
+4. Use HTTPS only
+5. Implement rate limiting
+6. Use secure password hashing
+7. Implement proper CORS
+8. Use secure headers
+9. Implement audit logging
+10. Use proper session management
\ No newline at end of file
diff --git a/rules/python-fastapi-cursorrules-prompt-file/.cursorrules b/rules/python-fastapi-cursorrules-prompt-file/.cursorrules
index 591df49..5e29d82 100644
--- a/rules/python-fastapi-cursorrules-prompt-file/.cursorrules
+++ b/rules/python-fastapi-cursorrules-prompt-file/.cursorrules
@@ -1,34 +1,196 @@
-# Python FastAPI .cursorrules
-
-# FastAPI best practices
-fastapi_best_practices = [
- "Use Pydantic models for request and response schemas",
- "Implement dependency injection for shared resources",
- "Utilize async/await for non-blocking operations",
- "Use path operations decorators (@app.get, @app.post, etc.)",
- "Implement proper error handling with HTTPException",
- "Use FastAPI's built-in OpenAPI and JSON Schema support",
-]
-
-# Folder structure
-folder_structure = """
-app/
- main.py
- models/
- schemas/
- routers/
- dependencies/
- services/
- tests/
-"""
-
-# Additional instructions
-additional_instructions = """
-1. Use type hints for all function parameters and return values
-2. Implement proper input validation using Pydantic
-3. Use FastAPI's background tasks for long-running operations
-4. Implement proper CORS handling
-5. Use FastAPI's security utilities for authentication
-6. Follow PEP 8 style guide for Python code
-7. Implement comprehensive unit and integration tests
-"""
+// FastAPI Core Concepts Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A foundational FastAPI application with essential features:
+- RESTful API endpoints
+- Data validation
+- Dependency injection
+- Authentication
+- Documentation
+- Error handling
+- Testing
+- Deployment readiness
+
+// Project Structure
+src/
+ api/
+ routers/ # Route modules
+ models/ # Data models
+ schemas/ # Pydantic schemas
+ core/ # Core functionality
+ config.py # Configuration
+ security.py # Security utilities
+ database.py # Database setup
+ services/ # Business logic
+ tests/ # Test suite
+ utils/ # Utilities
+ main.py # Entry point
+
+// Development Guidelines
+1. Basic Concepts:
+ - Define routes with decorators
+ - Use path operations
+ - Implement request/response models
+ - Handle query parameters
+ - Process request bodies
+ - Return proper responses
+
+2. Data Validation:
+ - Use Pydantic models
+ - Validate request data
+ - Handle validation errors
+ - Define response models
+ - Use field constraints
+ - Implement custom validators
+
+3. Error Handling:
+ - Use proper status codes
+ - Implement error responses
+ - Handle exceptions
+ - Return error details
+ - Log errors properly
+ - Provide helpful messages
+
+// Dependencies
+Core:
+- fastapi>=0.100.0
+- pydantic>=2.0.0
+- uvicorn>=0.23.0
+- sqlalchemy>=2.0.0
+- python-jose>=3.3.0
+- passlib>=1.7.4
+
+Optional:
+- pytest>=7.4.0
+- httpx>=0.24.0
+- python-multipart>=0.0.6
+- python-dotenv>=1.0.0
+
+// Code Examples:
+
+1. Basic CRUD Operations:
+```python
+from fastapi import FastAPI, HTTPException, Depends
+from pydantic import BaseModel
+from typing import List, Optional
+
+app = FastAPI()
+
+class Item(BaseModel):
+ id: Optional[int] = None
+ name: str
+ description: str
+ price: float
+
+items = []
+
+@app.post("/items/", response_model=Item)
+async def create_item(item: Item):
+ item.id = len(items) + 1
+ items.append(item)
+ return item
+
+@app.get("/items/", response_model=List[Item])
+async def read_items(skip: int = 0, limit: int = 10):
+ return items[skip : skip + limit]
+
+@app.get("/items/{item_id}", response_model=Item)
+async def read_item(item_id: int):
+ if item_id < 0 or item_id >= len(items):
+ raise HTTPException(status_code=404, detail="Item not found")
+ return items[item_id - 1]
+```
+
+2. Basic Authentication:
+```python
+from fastapi import Depends, HTTPException, status
+from fastapi.security import OAuth2PasswordBearer
+from jose import JWTError, jwt
+from passlib.context import CryptContext
+
+oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
+pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
+
+def verify_password(plain_password: str, hashed_password: str):
+ return pwd_context.verify(plain_password, hashed_password)
+
+def get_password_hash(password: str):
+ return pwd_context.hash(password)
+
+async def get_current_user(token: str = Depends(oauth2_scheme)):
+ credentials_exception = HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Could not validate credentials",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+ try:
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
+ username: str = payload.get("sub")
+ if username is None:
+ raise credentials_exception
+ except JWTError:
+ raise credentials_exception
+ return username
+```
+
+3. Basic Database Operations:
+```python
+from sqlalchemy import create_engine
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import sessionmaker
+from contextlib import contextmanager
+
+SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
+engine = create_engine(SQLALCHEMY_DATABASE_URL)
+SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
+Base = declarative_base()
+
+@contextmanager
+def get_db():
+ db = SessionLocal()
+ try:
+ yield db
+ finally:
+ db.close()
+
+class DBItem(Base):
+ __tablename__ = "items"
+
+ id = Column(Integer, primary_key=True, index=True)
+ name = Column(String)
+ description = Column(String)
+ price = Column(Float)
+
+@app.post("/db-items/", response_model=Item)
+async def create_db_item(item: Item, db: Session = Depends(get_db)):
+ db_item = DBItem(**item.dict())
+ db.add(db_item)
+ db.commit()
+ db.refresh(db_item)
+ return db_item
+```
+
+// Best Practices:
+1. Use proper HTTP methods
+2. Implement proper validation
+3. Handle errors gracefully
+4. Document your API
+5. Use dependency injection
+6. Write tests
+7. Use async when needed
+8. Implement proper security
+9. Follow REST principles
+10. Use proper response models
+
+// Security Considerations:
+1. Validate input data
+2. Use proper authentication
+3. Implement authorization
+4. Use HTTPS
+5. Hash passwords
+6. Implement rate limiting
+7. Use secure headers
+8. Handle errors safely
+9. Validate file uploads
+10. Use proper session handling
diff --git a/rules/python-fastapi-scalable-api-cursorrules-prompt-fil/.cursorrules b/rules/python-fastapi-scalable-api-cursorrules-prompt-fil/.cursorrules
index afe3ffe..19cb1eb 100644
--- a/rules/python-fastapi-scalable-api-cursorrules-prompt-fil/.cursorrules
+++ b/rules/python-fastapi-scalable-api-cursorrules-prompt-fil/.cursorrules
@@ -1 +1,240 @@
-You are an expert in **Python, FastAPI, scalable API development, TypeScript, React, Tailwind,** and **Shadcn UI**.### Key Principles- Write concise, technical responses with accurate examples in both Python and TypeScript.- Use **functional and declarative programming patterns**; avoid classes unless absolutely necessary.- Prefer **iteration and modularization** over code duplication.- Use descriptive variable names with auxiliary verbs (e.g., `is_active`, `has_permission`, `isLoading`, `hasError`).- Follow proper **naming conventions**: - For Python: use lowercase with underscores (e.g., `routers/user_routes.py`). - For TypeScript: use lowercase with dashes for directories (e.g., `components/auth-wizard`).### Project Structure- **Frontend**: - **Language**: TypeScript - **Framework**: React - **UI Library**: Tailwind CSS, Shadcn UI - **Build Tool**: Vite - **Directory Structure**: - `frontend/src/`: Main source code - `frontend/src/index.html`: Main HTML file - Configuration Files: - `vite.config.ts` - `tsconfig.json` - `tailwind.config.js` - `postcss.config.js` - **Docker Files**: - `Dockerfile` - `Dockerfile.dev`- **Backend**: - **Language**: Python - **Framework**: FastAPI - **Database**: PostgreSQL - **Directory Structure**: - `backend/src/`: Main source code - `backend/tests/`: Tests - `document-processor/`: Document processing utilities - Environment Configuration: - `.env` / `.env.example`: Environment variables - Database Configuration: - `alembic.ini` - `ddialog.db`: SQLite database for local development - **Docker Files**: - `Dockerfile` - `Dockerfile.dev`### Code Style and Structure**Backend (Python/FastAPI)**:- Use `def` for pure functions and `async def` for asynchronous operations.- **Type Hints**: Use Python type hints for all function signatures. Prefer Pydantic models for input validation.- **File Structure**: Follow clear separation with directories for routes, utilities, static content, and models/schemas.- **RORO Pattern**: Use the "Receive an Object, Return an Object" pattern.- **Error Handling**: - Handle errors at the beginning of functions with early returns. - Use guard clauses and avoid deeply nested if statements. - Implement proper logging and custom error types.**Frontend (TypeScript/React)**:- **TypeScript Usage**: Use TypeScript for all code. Prefer interfaces over types. Avoid enums; use maps instead.- **Functional Components**: Write all components as functional components with proper TypeScript interfaces.- **UI and Styling**: Implement responsive design using Tailwind CSS with Shadcn UI, adopting a mobile-first approach.- **Performance**: - Minimize `use client`, `useEffect`, and `setState` hooks. Favor server-side rendering where possible. - Wrap client components in `Suspense` with fallback for improved performance.### Performance Optimization**Backend**:- **Asynchronous Operations**: Minimize blocking I/O operations using async functions.- **Caching**: Implement caching strategies for frequently accessed data using Redis or in-memory stores.- **Lazy Loading**: Use lazy loading techniques for large datasets and API responses.**Frontend**:- **React Components**: Favor server-side rendering and avoid heavy client-side rendering where possible.- **Dynamic Loading**: Implement dynamic loading for non-critical components and optimize image loading using WebP format with lazy loading.### Project Conventions**Backend**:1. Follow **RESTful API design principles**.2. Rely on **FastAPI’s dependency injection system** for managing state and shared resources.3. Use **SQLAlchemy 2.0** for ORM features, if applicable.4. Ensure **CORS** is properly configured for local development.5. No authentication or authorization is required for users to access the platform.**Frontend**:1. Optimize **Web Vitals** (LCP, CLS, FID).2. Limit `use client` hooks to small, specific components for Web API access.3. Use **Docker** for containerization and ensure easy deployment.### Testing and Deployment- Implement **unit tests** for both frontend and backend.- Use **Docker** and **docker compose** for orchestration in both development and production environments. Avoid using the obsolete `docker-compose` command.- Ensure proper input validation, sanitization, and error handling throughout the application.
\ No newline at end of file
+// FastAPI Scalable API Architecture Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A highly scalable FastAPI application designed for large-scale deployments:
+- Microservices-ready architecture
+- High-performance API endpoints
+- Distributed system patterns
+- Horizontal scaling capabilities
+- Load balancing ready
+- Service mesh integration
+- Monitoring and observability
+- Containerization support
+
+// Project Structure
+src/
+ api/
+ v1/
+ routers/ # API route modules
+ schemas/ # Request/Response models
+ dependencies/ # Endpoint dependencies
+ core/
+ config/ # Environment and app config
+ events/ # Event handlers and buses
+ middleware/ # Custom middleware
+ monitoring/ # Metrics and tracing
+ infrastructure/
+ database/ # Database modules
+ migrations/ # Alembic migrations
+ models/ # SQLAlchemy models
+ cache/ # Caching layer
+ queue/ # Message queues
+ storage/ # File storage
+ services/ # Business logic services
+ auth/ # Authentication service
+ notification/ # Notification service
+ background/ # Background tasks
+ tests/
+ integration/ # Integration tests
+ load/ # Load tests
+ unit/ # Unit tests
+ utils/ # Shared utilities
+ main.py # Application entry
+
+// Development Guidelines
+1. Scalability Patterns:
+ - Use asynchronous programming everywhere
+ - Implement proper connection pooling
+ - Design for statelessness
+ - Use distributed caching
+ - Implement circuit breakers
+ - Use message queues for async tasks
+
+2. Performance Optimization:
+ - Implement response compression
+ - Use efficient serialization
+ - Optimize database queries
+ - Implement proper indexing
+ - Use bulk operations
+ - Cache frequently accessed data
+
+3. Monitoring and Observability:
+ - Implement structured logging
+ - Use distributed tracing
+ - Monitor key metrics
+ - Set up health checks
+ - Track performance metrics
+ - Implement proper alerting
+
+4. Database Scaling:
+ - Use database sharding
+ - Implement read replicas
+ - Use connection pooling
+ - Optimize query patterns
+ - Implement proper indexes
+ - Use database partitioning
+
+// Dependencies
+Core:
+- fastapi>=0.100.0
+- uvicorn[standard]>=0.23.0
+- sqlalchemy[asyncio]>=2.0.0
+- alembic>=1.11.0
+- asyncpg>=0.28.0
+- redis>=5.0.0
+- prometheus-client>=0.17.0
+- opentelemetry-api>=1.20.0
+
+Optional:
+- celery>=5.3.0
+- kafka-python>=2.0.0
+- elasticsearch>=8.0.0
+- memcached>=1.59
+- sentry-sdk>=1.30.0
+- newrelic>=8.8.0
+
+// Code Examples:
+
+1. Circuit Breaker Pattern:
+```python
+from fastapi import FastAPI, HTTPException
+from functools import wraps
+import asyncio
+import time
+
+class CircuitBreaker:
+ def __init__(self, failure_threshold=5, reset_timeout=60):
+ self.failure_count = 0
+ self.failure_threshold = failure_threshold
+ self.reset_timeout = reset_timeout
+ self.last_failure_time = None
+ self.state = "closed" # closed, open, half-open
+
+ async def __call__(self, func):
+ @wraps(func)
+ async def wrapper(*args, **kwargs):
+ if self.state == "open":
+ if time.time() - self.last_failure_time > self.reset_timeout:
+ self.state = "half-open"
+ else:
+ raise HTTPException(status_code=503, detail="Service temporarily unavailable")
+
+ try:
+ result = await func(*args, **kwargs)
+ if self.state == "half-open":
+ self.state = "closed"
+ self.failure_count = 0
+ return result
+ except Exception as e:
+ self.failure_count += 1
+ self.last_failure_time = time.time()
+ if self.failure_count >= self.failure_threshold:
+ self.state = "open"
+ raise e
+
+ return wrapper
+
+# Usage
+@app.get("/api/users/{user_id}")
+@circuit_breaker(failure_threshold=5, reset_timeout=60)
+async def get_user(user_id: int):
+ return await user_service.get_user(user_id)
+```
+
+2. Caching Layer Pattern:
+```python
+from fastapi import FastAPI, Depends
+from redis import asyncio as aioredis
+import json
+
+class CacheLayer:
+ def __init__(self, redis_url: str):
+ self.redis = aioredis.from_url(redis_url)
+
+ async def get_or_set(self, key: str, func, expire: int = 3600):
+ # Try to get from cache
+ cached = await self.redis.get(key)
+ if cached:
+ return json.loads(cached)
+
+ # If not in cache, execute function and cache result
+ result = await func()
+ await self.redis.setex(
+ key,
+ expire,
+ json.dumps(result, default=str)
+ )
+ return result
+
+# Usage
+cache = CacheLayer("redis://localhost")
+
+@app.get("/api/products")
+async def get_products(category: str):
+ async def fetch_products():
+ return await db.products.filter(category=category)
+
+ return await cache.get_or_set(
+ f"products:{category}",
+ fetch_products,
+ expire=3600
+ )
+```
+
+3. Load Balancing Pattern:
+```python
+from fastapi import FastAPI, Request
+from typing import List
+import random
+
+class LoadBalancer:
+ def __init__(self, backends: List[str]):
+ self.backends = backends
+ self.current = 0
+
+ def get_backend(self, strategy: str = "round_robin"):
+ if strategy == "random":
+ return random.choice(self.backends)
+ elif strategy == "round_robin":
+ backend = self.backends[self.current]
+ self.current = (self.current + 1) % len(self.backends)
+ return backend
+
+app = FastAPI()
+lb = LoadBalancer([
+ "http://backend1:8000",
+ "http://backend2:8000",
+ "http://backend3:8000"
+])
+
+@app.middleware("http")
+async def load_balancing_middleware(request: Request, call_next):
+ backend = lb.get_backend()
+ # Forward request to backend
+ # Implementation details omitted for brevity
+```
+
+// Best Practices:
+1. Design for horizontal scaling
+2. Implement proper caching strategies
+3. Use asynchronous operations
+4. Implement circuit breakers
+5. Use proper load balancing
+6. Implement proper monitoring
+7. Use message queues for async tasks
+8. Implement proper error handling
+9. Use proper database scaling
+10. Implement proper security
+
+// Security Considerations:
+1. Implement rate limiting
+2. Use proper authentication
+3. Implement proper authorization
+4. Use secure communications
+5. Implement proper logging
+6. Use proper input validation
+7. Implement proper error handling
+8. Use proper session management
+9. Implement proper monitoring
+10. Use proper security headers
\ No newline at end of file
diff --git a/rules/typescript-vscode-extension-prompt-file/.cursorrules b/rules/typescript-vscode-extension-prompt-file/.cursorrules
new file mode 100644
index 0000000..c71b032
--- /dev/null
+++ b/rules/typescript-vscode-extension-prompt-file/.cursorrules
@@ -0,0 +1,218 @@
+// TypeScript VSCode Extension Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A professional VSCode extension that:
+- Analyzes codebases and patterns
+- Manages rule versioning and history
+- Provides real-time file monitoring
+- Implements intelligent rule processing
+- Integrates with VSCode services
+- Handles workspace events
+- Manages extension state
+- Provides command palette integration
+
+// Project Structure
+src/
+ extension.ts # Extension entry point
+ commands/ # Command implementations
+ ruleCommands.ts # Rule-related commands
+ fileCommands.ts # File operation commands
+ services/ # Core services
+ analyzer.ts # Code analysis logic
+ ruleManager.ts # Rule management
+ fileWatcher.ts # File monitoring
+ models/ # Type definitions
+ rules.ts # Rule interfaces
+ config.ts # Configuration types
+ utils/ # Utility functions
+ test/ # Test files
+ suite/ # Test suites
+ fixtures/ # Test data
+
+// Development Guidelines
+1. Extension Lifecycle:
+ - Implement proper activation events
+ - Handle workspace changes
+ - Manage extension context
+ - Clean up resources on deactivation
+ - Use proper error boundaries
+ - Implement proper state management
+
+2. VSCode Integration:
+ - Use VSCode API effectively
+ - Register commands properly
+ - Handle configuration changes
+ - Implement proper status bar updates
+ - Use proper progress indicators
+ - Handle workspace trust
+
+3. Performance:
+ - Implement proper caching
+ - Use debouncing for file operations
+ - Optimize startup time
+ - Handle large files efficiently
+ - Implement proper memory management
+ - Use proper resource disposal
+
+4. Testing Requirements:
+ - Use VSCode test runner
+ - Mock VSCode API appropriately
+ - Test extension activation
+ - Implement integration tests
+ - Test error scenarios
+ - Verify command behavior
+
+// Dependencies
+Core:
+- @types/vscode: ^1.80.0
+- @types/node: ^18.15.0
+- typescript: ~5.1.0
+- vscode-test: ^1.6.1
+- mocha: ^10.2.0
+
+Optional:
+- eslint: ^8.44.0
+- prettier: ^3.0.0
+- webpack: ^5.88.0
+- ts-loader: ^9.4.0
+
+// Code Examples:
+
+1. Extension Activation Pattern:
+```typescript
+import * as vscode from 'vscode';
+
+export async function activate(context: vscode.ExtensionContext) {
+ const ruleManager = new RuleManager(context);
+ const analyzer = new Analyzer(context);
+
+ // Register commands
+ context.subscriptions.push(
+ vscode.commands.registerCommand(
+ 'cursorrules.analyzeWorkspace',
+ async () => {
+ try {
+ await analyzer.analyzeWorkspace();
+ } catch (error) {
+ vscode.window.showErrorMessage(
+ `Analysis failed: ${error.message}`
+ );
+ }
+ }
+ )
+ );
+
+ // Setup file watcher
+ const watcher = vscode.workspace.createFileSystemWatcher(
+ '**/.cursorrules'
+ );
+ context.subscriptions.push(watcher);
+
+ // Handle workspace changes
+ watcher.onDidChange(async uri => {
+ await ruleManager.handleRuleChange(uri);
+ });
+}
+
+export function deactivate() {
+ // Cleanup resources
+}
+```
+
+2. Service Implementation Pattern:
+```typescript
+export class RuleManager {
+ private readonly cache = new Map();
+ private readonly disposables: vscode.Disposable[] = [];
+
+ constructor(private readonly context: vscode.ExtensionContext) {
+ // Setup status bar
+ this.statusBar = vscode.window.createStatusBarItem(
+ vscode.StatusBarAlignment.Right
+ );
+ this.disposables.push(this.statusBar);
+ }
+
+ public async handleRuleChange(uri: vscode.Uri): Promise {
+ await vscode.window.withProgress(
+ {
+ location: vscode.ProgressLocation.Notification,
+ title: "Processing rule changes"
+ },
+ async () => {
+ try {
+ const content = await this.readFile(uri);
+ const rule = await this.parseRule(content);
+ this.cache.set(uri.fsPath, rule);
+ this.updateStatusBar();
+ } catch (error) {
+ this.handleError(error);
+ }
+ }
+ );
+ }
+
+ public dispose(): void {
+ this.disposables.forEach(d => d.dispose());
+ }
+}
+```
+
+3. Testing Pattern:
+```typescript
+import * as assert from 'assert';
+import * as vscode from 'vscode';
+import { RuleManager } from '../services/ruleManager';
+
+suite('Rule Manager Test Suite', () => {
+ let ruleManager: RuleManager;
+ let context: vscode.ExtensionContext;
+
+ setup(() => {
+ context = {
+ subscriptions: [],
+ extensionPath: __dirname,
+ globalState: {
+ get: (key: string) => undefined,
+ update: async (key: string, value: any) => Promise.resolve()
+ }
+ } as any;
+ ruleManager = new RuleManager(context);
+ });
+
+ test('should handle rule changes', async () => {
+ const uri = vscode.Uri.file('/test/.cursorrules');
+ await ruleManager.handleRuleChange(uri);
+ // Add assertions
+ });
+
+ teardown(() => {
+ ruleManager.dispose();
+ });
+});
+```
+
+// Best Practices:
+1. Follow VSCode extension guidelines
+2. Use proper error handling
+3. Implement proper logging
+4. Handle workspace events
+5. Use proper resource management
+6. Implement proper testing
+7. Use proper configuration
+8. Handle security properly
+9. Use proper progress indication
+10. Implement proper cleanup
+
+// Security Considerations:
+1. Validate all file operations
+2. Handle workspace trust
+3. Sanitize all inputs
+4. Use proper error handling
+5. Implement proper logging
+6. Handle sensitive data
+7. Use secure defaults
+8. Validate configurations
+9. Handle permissions properly
+10. Implement proper access controls
\ No newline at end of file
diff --git a/rules/vue3-composition-api-cursorrules-prompt-file/.cursorrules b/rules/vue3-composition-api-cursorrules-prompt-file/.cursorrules
index 5d4367c..6866c80 100644
--- a/rules/vue3-composition-api-cursorrules-prompt-file/.cursorrules
+++ b/rules/vue3-composition-api-cursorrules-prompt-file/.cursorrules
@@ -1,35 +1,267 @@
-// Vue 3 Composition API .cursorrules
-
-// Vue 3 Composition API best practices
-const vue3CompositionApiBestPractices = [
- "Use setup() function for component logic",
- "Utilize ref and reactive for reactive state",
- "Implement computed properties with computed()",
- "Use watch and watchEffect for side effects",
- "Implement lifecycle hooks with onMounted, onUpdated, etc.",
- "Utilize provide/inject for dependency injection",
-];
-
-// Folder structure
-const folderStructure = `
+// Vue 3 Composition API Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern Vue 3 application leveraging Composition API:
+- Scalable component architecture
+- Type-safe component logic
+- Reactive state management
+- Composable functionality
+- Performance optimized
+- SSR ready
+- Testing friendly
+- Maintainable codebase
+
+// Project Structure
src/
- components/
- composables/
- views/
- router/
- store/
- assets/
- App.vue
- main.js
-`;
-
-// Additional instructions
-const additionalInstructions = `
-1. Use TypeScript for type safety
-2. Implement proper props and emits definitions
-3. Utilize Vue 3's Teleport component when needed
-4. Use Suspense for async components
-5. Implement proper error handling
-6. Follow Vue 3 style guide and naming conventions
-7. Use Vite for fast development and building
-`;
+ components/ # Reusable components
+ base/ # Base/common components
+ layout/ # Layout components
+ features/ # Feature-specific components
+ composables/ # Shared composables
+ use-auth.ts # Authentication logic
+ use-form.ts # Form handling
+ use-api.ts # API interactions
+ stores/ # Pinia stores
+ modules/ # Store modules
+ index.ts # Store exports
+ router/ # Vue Router setup
+ guards/ # Navigation guards
+ routes/ # Route definitions
+ views/ # Page components
+ utils/ # Utility functions
+ types/ # TypeScript types
+ assets/ # Static assets
+ styles/ # Global styles
+
+// Development Guidelines
+1. Composition API Patterns:
+ - Use setup() with script setup
+ - Implement proper refs/reactive
+ - Use computed properties
+ - Handle lifecycle hooks
+ - Implement proper watchers
+ - Use provide/inject properly
+
+2. Component Design:
+ - Keep components focused
+ - Use proper prop validation
+ - Implement emit contracts
+ - Handle component state
+ - Use slots effectively
+ - Implement error boundaries
+
+3. Performance:
+ - Use proper memoization
+ - Implement lazy loading
+ - Handle component updates
+ - Use proper refs
+ - Optimize renders
+ - Use proper suspense
+
+// Dependencies
+Core:
+- vue: ^3.3.0
+- vue-router: ^4.2.0
+- pinia: ^2.1.0
+- vite: ^4.4.0
+- typescript: ~5.1.0
+- vue-tsc: ^1.8.0
+
+Optional:
+- vitest: ^0.33.0
+- @vue/test-utils: ^2.4.0
+- @vueuse/core: ^10.2.0
+- unplugin-vue-components: ^0.25.0
+- vite-plugin-vue-layouts: ^0.8.0
+
+// Code Examples:
+
+1. Component Pattern:
+```vue
+
+
+
+
+
+
+
+
+ {{ user.name }}
+
+
+
+
No users found
+
+
+
+
+```
+
+2. Composable Pattern:
+```typescript
+import { ref, computed, onMounted, onUnmounted } from 'vue'
+import type { Ref } from 'vue'
+
+interface UseDataOptions {
+ immediate?: boolean
+ transform?: (data: any) => any
+}
+
+export function useData(
+ fetchFn: () => Promise,
+ options: UseDataOptions = {}
+) {
+ const data = ref(null) as Ref
+ const error = ref(null)
+ const loading = ref(false)
+
+ const hasData = computed(() => data.value !== null)
+
+ async function fetch() {
+ loading.value = true
+ error.value = null
+
+ try {
+ const result = await fetchFn()
+ data.value = options.transform
+ ? options.transform(result)
+ : result
+ } catch (e) {
+ error.value = e as Error
+ } finally {
+ loading.value = false
+ }
+ }
+
+ if (options.immediate) {
+ onMounted(fetch)
+ }
+
+ return {
+ data,
+ error,
+ loading,
+ hasData,
+ fetch
+ }
+}
+```
+
+3. Store Pattern:
+```typescript
+import { defineStore } from 'pinia'
+import { ref, computed } from 'vue'
+import type { User } from '@/types'
+
+export const useUserStore = defineStore('user', () => {
+ const currentUser = ref(null)
+ const token = ref(null)
+
+ const isAuthenticated = computed(() => token.value !== null)
+
+ async function login(credentials: {
+ email: string
+ password: string
+ }) {
+ const { user, token: authToken } = await api.login(credentials)
+ currentUser.value = user
+ token.value = authToken
+ }
+
+ function logout() {
+ currentUser.value = null
+ token.value = null
+ }
+
+ return {
+ currentUser,
+ token,
+ isAuthenticated,
+ login,
+ logout
+ }
+})
+```
+
+// Best Practices:
+1. Use Composition API consistently
+2. Implement proper typing
+3. Handle component lifecycle
+4. Use proper state management
+5. Implement error handling
+6. Write comprehensive tests
+7. Use proper composables
+8. Handle reactivity correctly
+9. Follow Vue conventions
+10. Optimize performance
+
+// Security Considerations:
+1. Validate all inputs
+2. Sanitize rendered content
+3. Handle authentication
+4. Protect sensitive data
+5. Use proper CORS
+6. Implement XSS protection
+7. Handle API security
+8. Use secure dependencies
+9. Implement CSP
+10. Handle user permissions
diff --git a/rules/webassembly-z80-cellular-automata-cursorrules-prom/.cursorrules b/rules/webassembly-z80-cellular-automata-cursorrules-prom/.cursorrules
index 96c953b..a2bee16 100644
--- a/rules/webassembly-z80-cellular-automata-cursorrules-prom/.cursorrules
+++ b/rules/webassembly-z80-cellular-automata-cursorrules-prom/.cursorrules
@@ -1 +1,253 @@
-We're implementing a higher-level control structure for our z80 cellular automata simulation, which we call the "environmental region grid."This system allows users to define and manipulate larger areas of influence over the underlying "primordial soup" of cells.Key Concepts:1. Soup Cells: The individual units of our cellular automata, which follow basic rules and interact with their neighbors.2. Regions: Larger areas that encompass multiple soup cells. Each region can have unique properties that influence the behavior of the soup cells within it.3. Environmental Region Grid: A grid overlaid on top of the soup cell grid, dividing the simulation space into discrete regions. This grid can be 4x4, 8x8, or 16x16, allowing for different levels of granularity.4. Region Parameters: Each region has a set of adjustable parameters that affect the soup cells within it. These could include: - Obstacle (A region that blocks the movement of soup cells) - Directional influence (biasing cell interactions in specific directions) - Randomness factor (introducing more or less chaos in cell behavior) - Temperature (affecting overall activity levels) - Energy levels (influencing the likelihood of certain cell states or interactions) - Other custom parameters as needed5. Dynamic Influence: The region parameters dynamically modify the behavior of soup cells, creating areas of distinct characteristics within the larger simulation.6. User Interaction: Users can interact with the simulation by adjusting region parameters in real-time, allowing for on-the-fly modification of the simulation's behavior.7. Visualization: The region grid and its effects are visually represented, allowing users to see the influence of their changes on the simulation.Purpose:This system adds a new layer of complexity and control to the cellular automata simulation. It allows for the creation of diverse environments within a single simulation, enabling users to explore how different regional properties affect the emergent behavior of the cellular automata.By implementing this region grid system, we're providing a powerful tool for users to experiment with large-scale influences on cellular automata behavior, potentially leading to new insights and interesting emergent phenomena.Plan:1. Define the Region Structure:Create a comprehensive data structure to represent each region. This structure should be flexible enough to accommodate various parameters that can influence the behavior of soup cells within that region. Consider including: - Obstacle - Directional influence (for each cardinal direction) - Randomness factor - Temperature - Energy level - Any other relevant parametersEnsure that each parameter is represented by an appropriate data type, typically using floating-point numbers for continuous values or integers for discrete states. This structure will be the foundation of your region system, so design it with extensibility in mind.2. Create the Region Grid:Implement a two-dimensional array to represent the region grid. This grid should be flexible in size, allowing for configurations such as 4x4, 8x8, or 16x16. Each element of this array will be an instance of the region structure defined in step 1. Initialize this grid with default values for all parameters, ensuring a consistent starting state. Consider implementing methods to easily resize the grid and maintain the aspect ratio with the underlying soup cells.3. Implement Soup Cell to Region Mapping:Develop a system to efficiently map each soup cell to its corresponding region. This mapping is crucial for quick lookups during simulation. Create a separate array where each element represents a soup cell and contains the index or reference to its associated region. Implement functions to update this mapping whenever the region grid size changes. Ensure that this mapping system is optimized for performance, as it will be frequently accessed during the simulation.4. Modify the Main Simulation Loop:Update the core simulation logic to incorporate region parameters. For each soup cell update: a. Determine the cell's corresponding region using the mapping created in step 3. b. Retrieve the region's parameters. c. Apply the effects of each parameter to the soup cell's behavior.This might involve adjusting probabilities, modifying state transition rules, or influencing the cell's interaction with neighbors. Ensure that this integration is done efficiently to maintain simulation performance.5. Implement Parameter-Specific Logic:For each parameter in the region structure, create dedicated functions or methods to apply its effects. For example: - Obstacle: Turns the cell into an obstacle, preventing it from being randomly selected, and preventing neighbor soup cells from interacting with it. - Directional influence: Adjust the probability of a cell interacting with neighbors in specific directions. - Randomness: Introduce variability in state transitions or cell behavior. - Temperature: Affect the overall activity level or energy of cells within the region. - Energy level: Influence the likelihood of certain operations or state changes.Design these functions to be modular and easily expandable, allowing for the addition of new parameters in the future without major code restructuring.6. Enhance the WASM Interface:Extend the WebAssembly interface to handle the new region grid system. This involves: a. Creating functions to set and get the entire region grid state, allowing for efficient data transfer between JavaScript and WASM. b. Implementing additional functions for manipulating individual regions or specific parameters. c. Ensuring these functions are properly exported and accessible from the JavaScript side. d. Optimizing data transfer to minimize performance overhead, especially for larger grid sizes.7. Develop the User Interface:Design and implement a comprehensive user interface for manipulating the region grid. This should include: a. A visual representation of the region grid, possibly overlaid on the main simulation view. b. Interactive elements for each region, allowing users to adjust parameters individually. c. Global controls for setting grid size and applying presets. d. A system for selecting different "brushes" or tools for painting parameter values across multiple regions. e. Real-time feedback showing the effects of parameter changes on the simulation.Ensure that the UI is intuitive and responsive, providing users with immediate visual feedback on their actions.8. Create a Region Visualization System:Develop a robust visualization system for the regions. This should: a. Visually represent the various parameters of each region, possibly using color coding, patterns, or overlays. b. Update in real-time as parameters are changed, providing immediate feedback to the user. c. Implement different visualization modes to focus on specific parameters or overall region states. d. Ensure that the visualization is clear and distinguishable from the underlying soup cell simulation.9. Implement Data Synchronization:Create an efficient system for keeping the region grid data synchronized between the JavaScript UI and the WASM simulation. This might involve: a. Implementing periodic updates at set intervals. b. Creating an event-driven synchronization system that updates when changes occur. c. Optimizing large data transfers to maintain smooth performance, possibly using typed arrays or other efficient data structures. d. Implementing a queuing system for updates to prevent overwhelming the simulation with rapid changes.10. Update the Shader Code:Modify the fragment shader used for rendering the simulation to incorporate region effects. This involves: a. Passing region data to the shader, either as a texture or uniform array. b. Updating the shader logic to consider region parameters when rendering cells. c. Implementing visual effects that reflect the influence of region parameters, such as color shifts, intensity variations, or particle effects. d. Optimizing the shader code to maintain performance, especially for larger simulations or complex region effects.This system will allow for complex, user-defined behaviors across the simulation space, significantly enhancing the depth and interactivity of the cellular automata simulation.
\ No newline at end of file
+// WebAssembly Z80 Cellular Automata Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A high-performance cellular automata system using WebAssembly and Z80:
+- Z80 assembly for core logic
+- WebAssembly integration
+- Real-time visualization
+- Memory-efficient design
+- High-performance computation
+- Browser-based emulation
+- Interactive controls
+- State persistence
+
+// Project Structure
+src/
+ wasm/ # WebAssembly modules
+ z80/ # Z80 assembly source
+ automata.asm # Core automata logic
+ memory.asm # Memory management
+ build/ # Build artifacts
+ js/ # JavaScript interface
+ bridge.js # WASM bridge
+ renderer.js # Canvas rendering
+ controls.js # User interface
+ lib/ # Shared utilities
+ z80emu/ # Z80 emulator
+ memory/ # Memory management
+ www/ # Web interface
+ index.html # Main page
+ styles/ # CSS styles
+ tools/ # Build tools
+ assembler/ # Z80 assembler
+ linker/ # WASM linker
+
+// Development Guidelines
+1. Z80 Assembly:
+ - Use efficient instructions
+ - Optimize memory access
+ - Handle interrupts properly
+ - Implement proper timing
+ - Use register allocation
+ - Minimize memory usage
+
+2. WebAssembly Integration:
+ - Implement proper memory sharing
+ - Handle data conversion
+ - Optimize data transfer
+ - Use proper imports/exports
+ - Handle errors gracefully
+ - Implement proper lifecycle
+
+3. Performance:
+ - Use SIMD when possible
+ - Optimize memory layout
+ - Minimize copying
+ - Use proper buffering
+ - Implement caching
+ - Profile and optimize
+
+// Dependencies
+Core:
+- z80asm: ^1.0.0
+- wasm-pack: ^0.10.0
+- wasm-bindgen: ^0.2.84
+- web-sys: ^0.3.61
+- js-sys: ^0.3.61
+- console_error_panic_hook: ^0.1.7
+
+Optional:
+- wasm-opt: ^0.110.0
+- wabt: ^1.0.32
+- wasm-snip: ^0.4.0
+- twiggy: ^0.7.0
+- wasm-gc: ^0.1.6
+
+// Code Examples:
+
+1. Z80 Assembly Pattern:
+```z80
+; Cell update routine
+; Input: HL = current cell address
+; Output: A = new cell state
+UpdateCell:
+ push bc
+ push de
+
+ ; Get neighbor count
+ ld b, 0 ; Initialize counter
+
+ ; Check North
+ ld de, -WIDTH
+ add hl, de
+ ld a, (hl)
+ and 1
+ add a, b
+ ld b, a
+
+ ; Check other neighbors...
+
+ ; Apply rules
+ ld a, (hl) ; Get current state
+ ld c, a ; Save it
+ ld a, b ; Get neighbor count
+
+ cp 2 ; Less than 2 neighbors?
+ jr c, .die
+ cp 4 ; More than 3 neighbors?
+ jr nc, .die
+ cp 3 ; Exactly 3 neighbors?
+ jr z, .live
+
+ ; 2 neighbors - maintain current state
+ ld a, c
+ jr .done
+
+.die:
+ xor a ; Set state to 0
+ jr .done
+
+.live:
+ ld a, 1 ; Set state to 1
+
+.done:
+ pop de
+ pop bc
+ ret
+```
+
+2. WebAssembly Bridge Pattern:
+```rust
+use wasm_bindgen::prelude::*;
+
+#[wasm_bindgen]
+pub struct Automata {
+ memory: Vec,
+ width: usize,
+ height: usize,
+}
+
+#[wasm_bindgen]
+impl Automata {
+ #[wasm_bindgen(constructor)]
+ pub fn new(width: usize, height: usize) -> Self {
+ let memory = vec![0; width * height];
+ Self {
+ memory,
+ width,
+ height,
+ }
+ }
+
+ #[wasm_bindgen]
+ pub fn step(&mut self) {
+ let mut new_state = self.memory.clone();
+
+ for y in 0..self.height {
+ for x in 0..self.width {
+ let idx = y * self.width + x;
+ new_state[idx] = self.compute_next_state(x, y);
+ }
+ }
+
+ self.memory = new_state;
+ }
+
+ #[wasm_bindgen]
+ pub fn get_memory_ptr(&self) -> *const u8 {
+ self.memory.as_ptr()
+ }
+}
+```
+
+3. JavaScript Integration Pattern:
+```typescript
+class AutomataRenderer {
+ private canvas: HTMLCanvasElement;
+ private ctx: CanvasRenderingContext2D;
+ private memory: WebAssembly.Memory;
+ private automata: any;
+
+ constructor(
+ canvas: HTMLCanvasElement,
+ width: number,
+ height: number
+ ) {
+ this.canvas = canvas;
+ this.ctx = canvas.getContext('2d')!;
+
+ // Initialize WebAssembly
+ this.initWasm(width, height);
+ }
+
+ private async initWasm(width: number, height: number) {
+ const wasm = await import('./pkg/automata');
+ this.automata = new wasm.Automata(width, height);
+ this.memory = wasm.memory;
+ }
+
+ public step() {
+ this.automata.step();
+ this.render();
+ }
+
+ private render() {
+ const ptr = this.automata.get_memory_ptr();
+ const buffer = new Uint8Array(
+ this.memory.buffer,
+ ptr,
+ this.width * this.height
+ );
+
+ const imageData = this.ctx.createImageData(
+ this.width,
+ this.height
+ );
+
+ for (let i = 0; i < buffer.length; i++) {
+ const value = buffer[i] ? 255 : 0;
+ imageData.data[i * 4 + 0] = value; // R
+ imageData.data[i * 4 + 1] = value; // G
+ imageData.data[i * 4 + 2] = value; // B
+ imageData.data[i * 4 + 3] = 255; // A
+ }
+
+ this.ctx.putImageData(imageData, 0, 0);
+ }
+}
+```
+
+// Best Practices:
+1. Optimize Z80 code
+2. Handle memory carefully
+3. Implement proper timing
+4. Use efficient algorithms
+5. Profile performance
+6. Handle errors properly
+7. Implement proper testing
+8. Use proper debugging
+9. Document assembly code
+10. Optimize WebAssembly
+
+// Security Considerations:
+1. Validate memory access
+2. Handle buffer bounds
+3. Sanitize input data
+4. Use proper permissions
+5. Handle integer overflow
+6. Implement proper isolation
+7. Use secure random
+8. Validate state changes
+9. Handle resource limits
+10. Implement proper cleanup
\ No newline at end of file
diff --git a/rules/wordpress-php-guzzle-gutenberg-cursorrules-prompt-/.cursorrules b/rules/wordpress-php-guzzle-gutenberg-cursorrules-prompt-/.cursorrules
index eee2051..e808ab0 100644
--- a/rules/wordpress-php-guzzle-gutenberg-cursorrules-prompt-/.cursorrules
+++ b/rules/wordpress-php-guzzle-gutenberg-cursorrules-prompt-/.cursorrules
@@ -1 +1,295 @@
-- You are operating in a WordPress plugin context, that has a Guzzle-based HTTP client, WP REST endpoint addition(s), and new Gutenberg editor blocks.- Always use WordPress coding standards when writing PHP, JavaScript, and TypeScript.- Always type hint PHP code.- Prefer writing TypeScript over JavaScript.- Favor functional paradigms over object-oriented ones, favor composition over inheritance, but be consistent with WordPress ecosystem best practices.- Optimize for readability.
\ No newline at end of file
+// WordPress PHP Guzzle Gutenberg Development Guide
+// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
+
+// What you can build with this ruleset:
+A modern WordPress plugin integrating Guzzle and Gutenberg:
+- Custom Gutenberg blocks
+- RESTful API integration
+- HTTP client functionality
+- Admin interface
+- Frontend rendering
+- Data synchronization
+- Performance optimization
+- Security features
+
+// Project Structure
+plugin-name/
+ src/
+ Blocks/ # Gutenberg blocks
+ components/ # React components
+ containers/ # Block containers
+ styles/ # Block styles
+ Http/ # HTTP client
+ Client/ # Guzzle client
+ Middleware/ # HTTP middleware
+ Admin/ # Admin interface
+ views/ # Admin pages
+ assets/ # Admin assets
+ Frontend/ # Frontend code
+ templates/ # Template files
+ assets/ # Frontend assets
+ Core/ # Core functionality
+ Services/ # Service classes
+ Models/ # Data models
+ assets/
+ js/ # JavaScript files
+ css/ # Stylesheets
+ images/ # Image assets
+ tests/ # Test suites
+ Unit/ # Unit tests
+ Integration/ # Integration tests
+ vendor/ # Composer packages
+ plugin-name.php # Main plugin file
+
+// Development Guidelines
+1. Gutenberg Integration:
+ - Use modern React patterns
+ - Implement proper block API
+ - Handle block attributes
+ - Use proper save/edit
+ - Implement sidebar panels
+ - Handle block validation
+
+2. Guzzle Implementation:
+ - Use proper middleware
+ - Handle authentication
+ - Implement rate limiting
+ - Use proper logging
+ - Handle errors gracefully
+ - Implement caching
+
+3. WordPress Integration:
+ - Follow coding standards
+ - Use proper hooks
+ - Handle activation/deactivation
+ - Implement proper i18n
+ - Use proper capabilities
+ - Handle updates properly
+
+// Dependencies
+Core:
+- php: ">=7.4"
+- wordpress: ">=5.9"
+- guzzlehttp/guzzle: "^7.0"
+- composer/installers: "^2.0"
+- php-di/php-di: "^6.0"
+- monolog/monolog: "^2.0"
+
+Optional:
+- phpunit/phpunit: "^9.0"
+- mockery/mockery: "^1.5"
+- wp-coding-standards/wpcs: "^2.3"
+- dealerdirect/phpcodesniffer-composer-installer: "^0.7"
+- squizlabs/php_codesniffer: "^3.6"
+
+// Code Examples:
+
+1. Gutenberg Block Pattern:
+```php
+ 'plugin-name-block-editor',
+ 'editor_style' => 'plugin-name-block-editor',
+ 'style' => 'plugin-name-block',
+ 'attributes' => [
+ 'title' => [
+ 'type' => 'string',
+ 'default' => '',
+ ],
+ 'content' => [
+ 'type' => 'string',
+ 'default' => '',
+ ],
+ ],
+ 'render_callback' => [$this, 'render'],
+ ]);
+ }
+
+ public function render(array $attributes): string {
+ $title = $attributes['title'] ?? '';
+ $content = $attributes['content'] ?? '';
+
+ ob_start();
+ ?>
+
+
+
+
+ logger = $logger;
+ $this->client = $this->createClient($config);
+ }
+
+ private function createClient(array $config): Client {
+ $stack = HandlerStack::create();
+
+ // Add retry middleware
+ $stack->push(Middleware::retry(
+ function ($retries, $request, $response) {
+ if ($retries >= 3) {
+ return false;
+ }
+
+ if ($response && $response->getStatusCode() >= 500) {
+ return true;
+ }
+
+ return false;
+ },
+ function ($retries) {
+ return 1000 * pow(2, $retries);
+ }
+ ));
+
+ // Add logging middleware
+ $stack->push(Middleware::log(
+ $this->logger,
+ new \GuzzleHttp\MessageFormatter(
+ '{method} {uri} HTTP/{version} {code}'
+ )
+ ));
+
+ return new Client(array_merge([
+ 'handler' => $stack,
+ 'timeout' => 30,
+ 'http_errors' => true,
+ ], $config));
+ }
+
+ public function get(string $endpoint, array $options = []): array {
+ try {
+ $response = $this->client->get($endpoint, $options);
+ return json_decode($response->getBody(), true);
+ } catch (\Exception $e) {
+ $this->logger->error($e->getMessage(), [
+ 'endpoint' => $endpoint,
+ 'options' => $options,
+ ]);
+ throw $e;
+ }
+ }
+}
+```
+
+3. Plugin Integration Pattern:
+```php
+container = $this->createContainer();
+ $this->initHooks();
+ }
+
+ private function createContainer(): Container {
+ $builder = new ContainerBuilder();
+ $builder->addDefinitions([
+ LoggerInterface::class => function () {
+ return new Logger('plugin-name');
+ },
+ ApiClient::class => function (Container $c) {
+ return new ApiClient(
+ $c->get(LoggerInterface::class),
+ [
+ 'base_uri' => 'https://api.example.com',
+ ]
+ );
+ },
+ ]);
+ return $builder->build();
+ }
+
+ private function initHooks(): void {
+ add_action('init', [$this, 'init']);
+ add_action('admin_init', [$this, 'adminInit']);
+ add_action(
+ 'enqueue_block_editor_assets',
+ [$this, 'enqueueBlockAssets']
+ );
+ }
+
+ public function init(): void {
+ load_plugin_textdomain(
+ 'plugin-name',
+ false,
+ dirname(plugin_basename(__FILE__)) . '/languages'
+ );
+
+ $this->container
+ ->get(Blocks\ExampleBlock::class)
+ ->register();
+ }
+
+ public function activate(): void {
+ // Activation logic
+ flush_rewrite_rules();
+ }
+
+ public function deactivate(): void {
+ // Cleanup logic
+ flush_rewrite_rules();
+ }
+}
+```
+
+// Best Practices:
+1. Follow WordPress standards
+2. Use proper security measures
+3. Implement proper caching
+4. Handle errors gracefully
+5. Use dependency injection
+6. Write comprehensive tests
+7. Document code properly
+8. Use proper logging
+9. Handle updates properly
+10. Optimize performance
+
+// Security Considerations:
+1. Validate user input
+2. Sanitize output
+3. Use nonces properly
+4. Handle capabilities
+5. Secure API requests
+6. Implement rate limiting
+7. Use proper escaping
+8. Handle file uploads
+9. Protect sensitive data
+10. Follow WordPress security
\ No newline at end of file
diff --git a/scripts/docs/setup_and_run.md b/scripts/docs/setup_and_run.md
new file mode 100644
index 0000000..29199a5
--- /dev/null
+++ b/scripts/docs/setup_and_run.md
@@ -0,0 +1,80 @@
+# Setup and Run Script Documentation
+
+## Overview
+
+The `setup_and_run.sh` script is a bash wrapper that manages the Python virtual environment and dependencies for the `standardize_rules.py` script. It ensures all necessary dependencies are installed and the script runs in an isolated environment.
+
+## Features
+
+- 🌟 Automatic virtual environment creation and management
+- 📦 Dependency installation via requirements.txt
+- 🔄 Environment cleanup after execution
+- 🎨 Colorized output for better visibility
+
+## Prerequisites
+
+- Python 3.x installed
+- Bash shell environment
+- Write permissions in the script directory
+
+## Usage
+
+```bash
+bash scripts/setup_and_run.sh
+```
+
+## Script Flow
+
+1. **Environment Setup**
+ - Creates a virtual environment in `.venv` if it doesn't exist
+ - Creates `requirements.txt` if it doesn't exist with required packages:
+ - pathlib
+ - python-dateutil
+
+2. **Dependency Management**
+ - Activates the virtual environment
+ - Installs all required packages from requirements.txt
+
+3. **Script Execution**
+ - Runs standardize_rules.py in the virtual environment
+ - Handles any script output or errors
+
+4. **Cleanup**
+ - Deactivates the virtual environment
+ - Provides execution status
+
+## Output Colors
+
+- 🟡 Yellow: Setup and processing steps
+- 🟢 Green: Success messages and completion
+- 🔵 Blue: Cleanup operations
+
+## Directory Structure
+
+```bash
+scripts/
+├── setup_and_run.sh
+├── standardize_rules.py
+├── requirements.txt
+└── docs/
+ └── setup_and_run.md
+```
+
+## Error Handling
+
+- Exits on any error (set -e)
+- Provides clear error messages
+- Ensures virtual environment is properly deactivated
+
+## Maintenance
+
+The script is designed to be maintainable and extensible:
+
+- Add new dependencies to `requirements.txt`
+- Modify virtual environment location via `VENV_DIR`
+- Customize output colors and messages
+
+## Related Documentation
+
+- [standardize_rules.md](standardize_rules.md) - Documentation for the main Python script
+- [ci.md](ci.md) - Continuous Integration documentation
diff --git a/scripts/requirements.txt b/scripts/requirements.txt
new file mode 100644
index 0000000..449051a
--- /dev/null
+++ b/scripts/requirements.txt
@@ -0,0 +1,2 @@
+pathlib
+python-dateutil
diff --git a/scripts/setup_and_run.sh b/scripts/setup_and_run.sh
new file mode 100755
index 0000000..a219fac
--- /dev/null
+++ b/scripts/setup_and_run.sh
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+# Exit on error
+set -e
+
+# Script directory
+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+VENV_DIR="$SCRIPT_DIR/.venv"
+REQUIREMENTS_FILE="$SCRIPT_DIR/requirements.txt"
+
+# Colors for output
+GREEN='\033[0;32m'
+YELLOW='\033[1;33m'
+BLUE='\033[0;34m'
+NC='\033[0m' # No Color
+
+echo -e "${YELLOW}🔧 Setting up environment for standardize_rules.py...${NC}"
+
+# Create requirements.txt if it doesn't exist
+if [ ! -f "$REQUIREMENTS_FILE" ]; then
+ echo -e "${YELLOW}📝 Creating requirements.txt...${NC}"
+ cat > "$REQUIREMENTS_FILE" << EOF
+pathlib
+python-dateutil
+EOF
+fi
+
+# Check if virtual environment exists
+if [ ! -d "$VENV_DIR" ]; then
+ echo -e "${YELLOW}🌟 Creating virtual environment...${NC}"
+ python3 -m venv "$VENV_DIR"
+fi
+
+# Activate virtual environment
+echo -e "${YELLOW}🔌 Activating virtual environment...${NC}"
+source "$VENV_DIR/bin/activate"
+
+# Install requirements
+echo -e "${YELLOW}📦 Installing dependencies...${NC}"
+pip install -r "$REQUIREMENTS_FILE"
+
+# Run the Python script
+echo -e "${GREEN}🚀 Running standardize_rules.py...${NC}"
+python "$SCRIPT_DIR/standardize_rules.py"
+
+# Cleanup and exit virtual environment
+echo -e "${BLUE}🧹 Cleaning up environment...${NC}"
+deactivate
+echo -e "${BLUE}📤 Virtual environment deactivated${NC}"
+
+echo -e "${GREEN}✅ Script execution completed!${NC}"
\ No newline at end of file
diff --git a/scripts/standardize_rules.py b/scripts/standardize_rules.py
index 8fa267f..3af785a 100755
--- a/scripts/standardize_rules.py
+++ b/scripts/standardize_rules.py
@@ -11,6 +11,25 @@ def load_template():
with open(template_path) as f:
return json.load(f)
+def convert_text_to_rules(text_content, dir_name):
+ """Convert text content to standardized rules format."""
+ try:
+ # First try to parse as JSON in case it is valid JSON
+ return json.loads(text_content)
+ except json.JSONDecodeError:
+ # If not valid JSON, create a new structure with the text as content
+ return {
+ "name": dir_name,
+ "description": "Cursor.sh AI rules for development",
+ "version": "1.0.0",
+ "content": text_content.strip(),
+ "metadata": {
+ "lastUpdated": datetime.datetime.now().isoformat(),
+ "format": "text",
+ "originalFileName": ".cursorrules"
+ }
+ }
+
def process_directory(dir_path, template):
"""Process a single directory containing .cursorrules file."""
cursorrules_path = dir_path / ".cursorrules"
@@ -22,38 +41,44 @@ def process_directory(dir_path, template):
return
try:
- # Load existing .cursorrules file
+ # Load existing .cursorrules file as text
with open(cursorrules_path) as f:
- existing_rules = json.load(f)
- except json.JSONDecodeError:
- print(f"Invalid JSON in {cursorrules_path}")
- return
+ existing_content = f.read()
+
+ # Convert the content to rules format
+ existing_rules = convert_text_to_rules(existing_content, dir_path.name)
+
+ # Create new standardized rules
+ new_rules = template.copy()
+ new_rules["name"] = dir_path.name
+ new_rules["metadata"]["lastUpdated"] = datetime.datetime.now().isoformat()
+
+ # Transfer existing data if it matches our schema
+ for key in existing_rules:
+ if key in new_rules:
+ new_rules[key] = existing_rules[key]
+ elif key == "content":
+ # Store the original text content in a specific field
+ new_rules["prompt"] = existing_rules["content"]
+
+ # Save the standardized rules
+ with open(cursorrules_path, 'w') as f:
+ json.dump(new_rules, f, indent=2)
+
+ print(f"✅ Successfully processed {dir_path}")
+
+ # Create README.md if it doesn't exist
+ if not readme_path.exists():
+ with open(readme_path, 'w') as f:
+ f.write(f"# {new_rules['name']}\n\n")
+ if "description" in new_rules:
+ f.write(f"{new_rules['description']}\n\n")
+ f.write("## Usage\n\n")
+ f.write("Copy the `.cursorrules` file to your project's root directory.\n")
+
except Exception as e:
- print(f"Error processing {cursorrules_path}: {e}")
+ print(f"⚠️ Error processing {dir_path}: {e}")
return
-
- # Create new standardized rules
- new_rules = template.copy()
- new_rules["name"] = dir_path.name
- new_rules["metadata"]["lastUpdated"] = datetime.datetime.now().isoformat()
-
- # Transfer existing data if it matches our schema
- for key in existing_rules:
- if key in new_rules:
- new_rules[key] = existing_rules[key]
-
- # Save the standardized rules
- with open(cursorrules_path, 'w') as f:
- json.dump(new_rules, f, indent=2)
-
- # Create README.md if it doesn't exist
- if not readme_path.exists():
- with open(readme_path, 'w') as f:
- f.write(f"# {new_rules['name']}\n\n")
- if "description" in new_rules:
- f.write(f"{new_rules['description']}\n\n")
- f.write("## Usage\n\n")
- f.write("Copy the `.cursorrules` file to your project's root directory.\n")
def main():
"""Main function to process all rule directories."""
@@ -63,7 +88,7 @@ def main():
# Process each directory in rules/
for dir_path in rules_dir.iterdir():
if dir_path.is_dir() and not dir_path.name.startswith('.'):
- print(f"Processing {dir_path}...")
+ print(f"🔄 Processing {dir_path}...")
process_directory(dir_path, template)
if __name__ == "__main__":