Cursor plugin specification and official plugins
TypeScript
Setting up Cursor plugin repository
ericzakariasson8762e7519ed1
diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.jsonnew file mode 100644index 00000000..19620bb4--- /dev/null+++ b/.cursor-plugin/marketplace.json@@ -0,0 +1,137 @@+{+ "name": "cursor-plugins",+ "owner": {+ "name": "Cursor",+ "email": "[email protected]"+ },+ "metadata": {+ "description": "Official Cursor plugin marketplace — developer tools, framework rules, MCP integrations, and agent skills"+ },+ "plugins": [+ {+ "name": "deep-learning-python",+ "source": "deep-learning-python",+ "description": "Deep learning, transformers, and diffusion model development rules by Yu Changqian (cursor.directory)"+ },+ {+ "name": "django-python",+ "source": "django-python",+ "description": "Django and scalable Python web application development rules by Caio Barbieri (cursor.directory)"+ },+ {+ "name": "docker",+ "source": "docker",+ "description": "Cursor plugin for Docker — Dockerfiles, Compose, multi-stage builds, and container best practices"+ },+ {+ "name": "elixir-phoenix",+ "source": "elixir-phoenix",+ "description": "Elixir, Phoenix, LiveView, and Tailwind development rules by Ilyich Vismara (cursor.directory)"+ },+ {+ "name": "fastapi-python",+ "source": "fastapi-python",+ "description": "FastAPI and scalable Python API development rules by Caio Barbieri (cursor.directory)"+ },+ {+ "name": "firebase",+ "source": "firebase",+ "description": "Cursor plugin for Firebase — Firestore, Authentication, Cloud Functions, Hosting, and Storage"+ },+ {+ "name": "flutter-dart",+ "source": "flutter-dart",+ "description": "Flutter and Dart clean architecture development rules by Sercan Yusuf (cursor.directory)"+ },+ {+ "name": "frontend-developer",+ "source": "frontend-developer",+ "description": "Expert React, Next.js, TypeScript, and Tailwind CSS development rules by Mohammadali Karimi (cursor.directory)"+ },+ {+ "name": "github",+ "source": "github",+ "description": "Cursor plugin for GitHub — Actions, API, CLI, Pull Requests, and repository management"+ },+ {+ "name": "go-api-development",+ "source": "go-api-development",+ "description": "Go API development with standard library (1.22+) rules by Marvin Kaunda (cursor.directory)"+ },+ {+ "name": "laravel-tallstack",+ "source": "laravel-tallstack",+ "description": "Laravel TALL Stack (Tailwind, Alpine.js, Livewire, Laravel) with DaisyUI rules by Ismael Fi (cursor.directory)"+ },+ {+ "name": "launchdarkly",+ "source": "launchdarkly",+ "description": "Cursor plugin for LaunchDarkly — feature flags, experimentation, progressive rollouts, and targeting"+ },+ {+ "name": "mongodb",+ "source": "mongodb",+ "description": "Cursor plugin for MongoDB — schema design, queries, aggregation, indexes, and Mongoose ODM"+ },+ {+ "name": "nextjs-react-typescript",+ "source": "nextjs-react-typescript",+ "description": "Next.js App Router, React, Shadcn UI, and Tailwind development rules by Pontus Abrahamsson (cursor.directory)"+ },+ {+ "name": "playwright-testing",+ "source": "playwright-testing",+ "description": "Playwright end-to-end testing and QA automation rules by Douglas Urrea Ocampo (cursor.directory)"+ },+ {+ "name": "rails-ruby",+ "source": "rails-ruby",+ "description": "Ruby on Rails, PostgreSQL, Hotwire, and Tailwind development rules by Theo Vararu (cursor.directory)"+ },+ {+ "name": "rust-async",+ "source": "rust-async",+ "description": "Rust async programming and concurrent systems development rules by Sheng-Yan, Zhang (cursor.directory)"+ },+ {+ "name": "sentry",+ "source": "sentry",+ "description": "Cursor plugin for Sentry — error monitoring, performance tracking, session replay, and alerting"+ },+ {+ "name": "slack",+ "source": "slack",+ "description": "Cursor plugin for Slack — Bolt framework, Block Kit, Events API, and Slack app development"+ },+ {+ "name": "solidity-web3",+ "source": "solidity-web3",+ "description": "Solidity smart contract security and development best practices by Alfredo Bonilla (cursor.directory)"+ },+ {+ "name": "sveltekit-development",+ "source": "sveltekit-development",+ "description": "Svelte 5 and SvelteKit modern web development guide by MMBytes (cursor.directory)"+ },+ {+ "name": "swiftui-ios",+ "source": "swiftui-ios",+ "description": "SwiftUI and Swift iOS/macOS development rules by Josh Pigford (cursor.directory)"+ },+ {+ "name": "terraform-iac",+ "source": "terraform-iac",+ "description": "Terraform and cloud Infrastructure as Code best practices by Abdeldjalil Sichaib (cursor.directory)"+ },+ {+ "name": "twilio",+ "source": "twilio",+ "description": "Cursor plugin for Twilio — SMS, Voice, WhatsApp, Verify, and communications APIs"+ },+ {+ "name": "unity-gamedev",+ "source": "unity-gamedev",+ "description": "C# Unity game development and design patterns rules by Pontus Abrahamsson (cursor.directory)"+ }+ ]+}diff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..43cc77f4--- /dev/null+++ b/.gitignore@@ -0,0 +1,35 @@+# OS files+.DS_Store+Thumbs.db++# Editor files+*.swp+*.swo+*~+.idea/+.vscode/++# Environment files+.env+.env.local+.env.*.local++# Node modules (for plugins with JS/TS)+node_modules/++# Python (for plugins with Python)+__pycache__/+*.py[cod]+.venv/+venv/++# Local plugin settings+*.local.md+*.local.json++# Build outputs+dist/+build/++# Logs+*.logdiff --git a/README.md b/README.mdnew file mode 100644index 00000000..63962431--- /dev/null+++ b/README.md@@ -0,0 +1,57 @@+# Cursor Plugins++Official Cursor plugins for popular developer tools, frameworks, and SaaS products. Each plugin is a standalone directory at the repository root with its own `.cursor-plugin/plugin.json` manifest.++## Plugins++| Plugin | Category | Description |+|:-------|:---------|:------------|+| [GitHub](github/) | Developer Tools | Actions, API, CLI, Pull Requests, and repository management |+| [Docker](docker/) | Developer Tools | Dockerfiles, Compose, multi-stage builds, and containers |+| [LaunchDarkly](launchdarkly/) | Developer Tools | Feature flags, experimentation, and progressive rollouts |+| [Sentry](sentry/) | Observability | Error monitoring, performance tracking, and alerting |+| [Firebase](firebase/) | Backend | Firestore, Cloud Functions, Authentication, and Hosting |+| [MongoDB](mongodb/) | Backend | Schema design, queries, aggregation, indexes, and Mongoose |+| [Twilio](twilio/) | SaaS | SMS, Voice, WhatsApp, Verify, and communications APIs |+| [Slack](slack/) | SaaS | Bolt framework, Block Kit, Events API, and app development |+| [Next.js React TypeScript](nextjs-react-typescript/) | Frontend | Next.js App Router, React, Shadcn UI, and Tailwind rules |+| [Frontend Developer](frontend-developer/) | Frontend | React, Next.js, TypeScript, and Tailwind CSS development rules |+| [SvelteKit](sveltekit-development/) | Frontend | Svelte 5 and SvelteKit modern web development guide |+| [Flutter Dart](flutter-dart/) | Mobile | Flutter and Dart clean architecture development rules |+| [SwiftUI iOS](swiftui-ios/) | Mobile | SwiftUI and Swift iOS/macOS development rules |+| [FastAPI Python](fastapi-python/) | Backend | FastAPI and scalable Python API development rules |+| [Django Python](django-python/) | Backend | Django and scalable Python web application rules |+| [Rails Ruby](rails-ruby/) | Backend | Ruby on Rails, PostgreSQL, Hotwire, and Tailwind rules |+| [Elixir Phoenix](elixir-phoenix/) | Backend | Elixir, Phoenix, LiveView, and Tailwind development rules |+| [Laravel TALL Stack](laravel-tallstack/) | Backend | Laravel TALL Stack (Tailwind, Alpine.js, Livewire) with DaisyUI |+| [Go API Development](go-api-development/) | Backend | Go API development with standard library (1.22+) rules |+| [Rust Async](rust-async/) | Systems | Rust async programming and concurrent systems rules |+| [Playwright Testing](playwright-testing/) | Testing | Playwright end-to-end testing and QA automation rules |+| [Unity GameDev](unity-gamedev/) | GameDev | C# Unity game development and design patterns rules |+| [Deep Learning Python](deep-learning-python/) | ML | Deep learning, transformers, and diffusion model rules |+| [Terraform IaC](terraform-iac/) | DevOps | Terraform and cloud Infrastructure as Code best practices |+| [Solidity Web3](solidity-web3/) | Blockchain | Solidity smart contract security and development rules |++## Repository Structure++This is a multi-plugin marketplace repository. The root `.cursor-plugin/marketplace.json` lists all plugins, and each plugin has its own manifest:++```+plugins/+├── .cursor-plugin/+│ └── marketplace.json # Marketplace manifest (lists all plugins)+├── plugin-name/+│ ├── .cursor-plugin/+│ │ └── plugin.json # Per-plugin manifest+│ ├── skills/ # Agent skills (SKILL.md with frontmatter)+│ ├── rules/ # Cursor rules (.mdc files)+│ ├── mcp.json # MCP server definitions+│ ├── README.md+│ ├── CHANGELOG.md+│ └── LICENSE+└── ...+```++## License++MITdiff --git a/deep-learning-python/.cursor-plugin/plugin.json b/deep-learning-python/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..45058eaf--- /dev/null+++ b/deep-learning-python/.cursor-plugin/plugin.json@@ -0,0 +1,27 @@+{+ "name": "deep-learning-python",+ "version": "1.0.0",+ "description": "Deep learning, transformers, and diffusion model development rules by Yu Changqian (cursor.directory)",+ "author": {+ "name": "Yu Changqian",+ "url": "https://cursor.directory/deep-learning-developer-python-cursor-rules"+ },+ "homepage": "https://cursor.directory/deep-learning-developer-python-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "python",+ "pytorch",+ "deep-learning",+ "transformers",+ "diffusion"+ ],+ "category": "ml",+ "tags": [+ "python",+ "pytorch",+ "deep-learning",+ "transformers"+ ],+ "rules": "./rules/"+}diff --git a/deep-learning-python/README.md b/deep-learning-python/README.mdnew file mode 100644index 00000000..a92fbc6a--- /dev/null+++ b/deep-learning-python/README.md@@ -0,0 +1,29 @@+# deep-learning-python++Deep learning, transformers, and diffusion model development rules by Yu Changqian (cursor.directory)++## Installation++```bash+agent install deep-learning-python+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `deep_learning_python` | Deep learning development with PyTorch, Transformers, Diffusers, and Gradio | `**/*.py, **/*.ipynb` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/deep-learning-developer-python-cursor-rules).++- **Original Author**: Yu Changqian+- **Tags**: python, pytorch, deep-learning, transformers, diffusion+- **Category**: ml++## License++MITdiff --git a/deep-learning-python/rules/deep_learning_python.mdc b/deep-learning-python/rules/deep_learning_python.mdcnew file mode 100644index 00000000..a25f6c1f--- /dev/null+++ b/deep-learning-python/rules/deep_learning_python.mdc@@ -0,0 +1,77 @@+---+description: Deep learning development with PyTorch, Transformers, Diffusers, and Gradio+globs:+ - "**/*.py"+ - "**/*.ipynb"+alwaysApply: false+---++You are an expert in deep learning, transformers, diffusion models, and LLM development, with a focus on Python libraries such as PyTorch, Diffusers, Transformers, and Gradio.++Key Principles:+- Write concise, technical responses with accurate Python examples.+- Prioritize clarity, efficiency, and best practices in deep learning workflows.+- Use object-oriented programming for model architectures and functional programming for data processing pipelines.+- Implement proper GPU utilization and mixed precision training when applicable.+- Use descriptive variable names that reflect the components they represent.+- Follow PEP 8 style guidelines for Python code.++Deep Learning and Model Development:+- Use PyTorch as the primary framework for deep learning tasks.+- Implement custom nn.Module classes for model architectures.+- Utilize PyTorch's autograd for automatic differentiation.+- Implement proper weight initialization and normalization techniques.+- Use appropriate loss functions and optimization algorithms.++Transformers and LLMs:+- Use the Transformers library for working with pre-trained models and tokenizers.+- Implement attention mechanisms and positional encodings correctly.+- Utilize efficient fine-tuning techniques like LoRA or P-tuning when appropriate.+- Implement proper tokenization and sequence handling for text data.++Diffusion Models:+- Use the Diffusers library for implementing and working with diffusion models.+- Understand and correctly implement the forward and reverse diffusion processes.+- Utilize appropriate noise schedulers and sampling methods.+- Understand and correctly implement the different pipeline, e.g., StableDiffusionPipeline and StableDiffusionXLPipeline, etc.++Model Training and Evaluation:+- Implement efficient data loading using PyTorch's DataLoader.+- Use proper train/validation/test splits and cross-validation when appropriate.+- Implement early stopping and learning rate scheduling.+- Use appropriate evaluation metrics for the specific task.+- Implement gradient clipping and proper handling of NaN/Inf values.++Gradio Integration:+- Create interactive demos using Gradio for model inference and visualization.+- Design user-friendly interfaces that showcase model capabilities.+- Implement proper error handling and input validation in Gradio apps.++Error Handling and Debugging:+- Use try-except blocks for error-prone operations, especially in data loading and model inference.+- Implement proper logging for training progress and errors.+- Use PyTorch's built-in debugging tools like autograd.detect_anomaly() when necessary.++Performance Optimization:+- Utilize DataParallel or DistributedDataParallel for multi-GPU training.+- Implement gradient accumulation for large batch sizes.+- Use mixed precision training with torch.cuda.amp when appropriate.+- Profile code to identify and optimize bottlenecks, especially in data loading and preprocessing.++Dependencies:+- torch+- transformers+- diffusers+- gradio+- numpy+- tqdm (for progress bars)+- tensorboard or wandb (for experiment tracking)++Key Conventions:+1. Begin projects with clear problem definition and dataset analysis.+2. Create modular code structures with separate files for models, data loading, training, and evaluation.+3. Use configuration files (e.g., YAML) for hyperparameters and model settings.+4. Implement proper experiment tracking and model checkpointing.+5. Use version control (e.g., git) for tracking changes in code and configurations.++Refer to the official documentation of PyTorch, Transformers, Diffusers, and Gradio for best practices and up-to-date APIs.diff --git a/django-python/.cursor-plugin/plugin.json b/django-python/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..085a0989--- /dev/null+++ b/django-python/.cursor-plugin/plugin.json@@ -0,0 +1,24 @@+{+ "name": "django-python",+ "version": "1.0.0",+ "description": "Django and scalable Python web application development rules by Caio Barbieri (cursor.directory)",+ "author": {+ "name": "Caio Barbieri",+ "url": "https://cursor.directory/django-python-cursor-rules"+ },+ "homepage": "https://cursor.directory/django-python-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "python",+ "django",+ "orm",+ "web"+ ],+ "category": "backend",+ "tags": [+ "django",+ "python"+ ],+ "rules": "./rules/"+}diff --git a/django-python/README.md b/django-python/README.mdnew file mode 100644index 00000000..baa2b0ef--- /dev/null+++ b/django-python/README.md@@ -0,0 +1,29 @@+# django-python++Django and scalable Python web application development rules by Caio Barbieri (cursor.directory)++## Installation++```bash+agent install django-python+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `django_python` | Django Python development best practices and web application patterns | `**/*.py, **/templates/**/*.html` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/django-python-cursor-rules).++- **Original Author**: Caio Barbieri+- **Tags**: django, python+- **Category**: backend++## License++MITdiff --git a/django-python/rules/django_python.mdc b/django-python/rules/django_python.mdcnew file mode 100644index 00000000..1cbf72c6--- /dev/null+++ b/django-python/rules/django_python.mdc@@ -0,0 +1,61 @@+---+description: Django Python development best practices and web application patterns+globs:+ - "**/*.py"+ - "**/templates/**/*.html"+alwaysApply: false+---++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.diff --git a/docker/.cursor-plugin/plugin.json b/docker/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..5cef8900--- /dev/null+++ b/docker/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "docker",+ "version": "1.0.0",+ "description": "Cursor plugin for Docker \u2014 Dockerfiles, Compose, multi-stage builds, and container best practices",+ "author": {+ "name": "Cursor",+ "email": "[email protected]"+ },+ "homepage": "https://github.com/cursor/plugins",+ "repository": "https://github.com/cursor/plugins",+ "license": "MIT",+ "keywords": [+ "docker",+ "containers",+ "dockerfile",+ "compose",+ "devops"+ ],+ "category": "developer-tools",+ "tags": [+ "containers",+ "devops",+ "infrastructure"+ ],+ "logo": "./docker.svg",+ "skills": "./skills/",+ "mcpServers": "./mcp.json"+}diff --git a/docker/CHANGELOG.md b/docker/CHANGELOG.mdnew file mode 100644index 00000000..5f2859de--- /dev/null+++ b/docker/CHANGELOG.md@@ -0,0 +1,13 @@+# Changelog++All notable changes to this plugin will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [Unreleased]++## [1.0.0] - 2026-02-07++### Added+- Initial plugin with skills and MCP server configurationdiff --git a/docker/LICENSE b/docker/LICENSEnew file mode 100644index 00000000..ca2bba77--- /dev/null+++ b/docker/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Cursor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/docker/README.md b/docker/README.mdnew file mode 100644index 00000000..ea986641--- /dev/null+++ b/docker/README.md@@ -0,0 +1,28 @@+# Docker Plugin++Cursor plugin for Docker — Dockerfiles, Compose, multi-stage builds, and container best practices.++## Installation++```bash+agent install docker+```++## Components++### Skills++| Skill | Description |+|:------|:------------|+| `containerize-app` | Language-specific Dockerfiles for Node.js, Python, Go, Java, and Rust with multi-stage builds |+| `setup-docker-compose` | Multi-service development environments with databases, caches, and queues |++### MCP Server++Provides Docker management via `mcp/docker` container image.++Requires Docker socket access.++## License++MITdiff --git a/docker/docker.svg b/docker/docker.svgnew file mode 100644index 00000000..7e44bc63--- /dev/null+++ b/docker/docker.svg@@ -0,0 +1 @@+<svg width="64" height="64" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Docker</title><path d="M13.983 11.078h2.119a.186.186 0 00.186-.185V9.006a.186.186 0 00-.186-.186h-2.119a.185.185 0 00-.185.185v1.888c0 .102.083.185.185.185m-2.954-5.43h2.118a.186.186 0 00.186-.186V3.574a.186.186 0 00-.186-.185h-2.118a.185.185 0 00-.185.185v1.888c0 .102.082.185.185.185m0 2.716h2.118a.187.187 0 00.186-.186V6.29a.186.186 0 00-.186-.185h-2.118a.185.185 0 00-.185.185v1.887c0 .102.082.185.185.186m-2.93 0h2.12a.186.186 0 00.184-.186V6.29a.185.185 0 00-.185-.185H8.1a.185.185 0 00-.185.185v1.887c0 .102.083.185.185.186m-2.964 0h2.119a.186.186 0 00.185-.186V6.29a.185.185 0 00-.185-.185H5.136a.186.186 0 00-.186.185v1.887c0 .102.084.185.186.186m5.893 2.715h2.118a.186.186 0 00.186-.185V9.006a.186.186 0 00-.186-.186h-2.118a.185.185 0 00-.185.185v1.888c0 .102.082.185.185.185m-2.93 0h2.12a.185.185 0 00.184-.185V9.006a.185.185 0 00-.184-.186h-2.12a.185.185 0 00-.184.185v1.888c0 .102.083.185.185.185m-2.964 0h2.119a.185.185 0 00.185-.185V9.006a.185.185 0 00-.184-.186h-2.12a.186.186 0 00-.186.186v1.887c0 .102.084.185.186.185m-2.92 0h2.12a.185.185 0 00.184-.185V9.006a.185.185 0 00-.184-.186h-2.12a.185.185 0 00-.184.185v1.888c0 .102.082.185.185.185M23.763 9.89c-.065-.051-.672-.51-1.954-.51-.338.001-.676.03-1.01.087-.248-1.7-1.653-2.53-1.716-2.566l-.344-.199-.226.327c-.284.438-.49.922-.612 1.43-.23.97-.09 1.882.403 2.661-.595.332-1.55.413-1.744.42H.751a.751.751 0 00-.75.748 11.376 11.376 0 00.692 4.062c.545 1.428 1.355 2.48 2.41 3.124 1.18.723 3.1 1.137 5.275 1.137.983.003 1.963-.086 2.93-.266a12.248 12.248 0 003.823-1.389c.98-.567 1.86-1.288 2.61-2.136 1.252-1.418 1.998-2.997 2.553-4.4h.221c1.372 0 2.215-.549 2.68-1.009.309-.293.55-.65.707-1.046l.098-.288Z"/></svg>diff --git a/docker/mcp.json b/docker/mcp.jsonnew file mode 100644index 00000000..20bf6c7a--- /dev/null+++ b/docker/mcp.json@@ -0,0 +1,16 @@+{+ "$schema": "https://cursor.com/schemas/mcp.json",+ "mcpServers": {+ "docker-mcp": {+ "command": "docker",+ "args": [+ "run", "-i", "--rm",+ "-v", "/var/run/docker.sock:/var/run/docker.sock:ro",+ "mcp/docker:latest"+ ],+ "description": "Docker MCP server — manage containers, images, volumes, and networks via the Docker socket",+ "env": {},+ "enabled": true+ }+ }+}diff --git a/docker/skills/containerize-app/SKILL.md b/docker/skills/containerize-app/SKILL.mdnew file mode 100644index 00000000..e9f8f13e--- /dev/null+++ b/docker/skills/containerize-app/SKILL.md@@ -0,0 +1,348 @@+---+name: containerize-app+description: Language-specific Dockerfiles for Node.js, Python, Go, Java, and Rust with multi-stage builds+---++# Skill: Containerize an Application++## Description++Generate a production-ready Dockerfile for an application, tailored to its language, framework, and deployment requirements. Includes multi-stage builds, security hardening, and optimization best practices.++## Trigger++Use this skill when a user wants to:+- Create a Dockerfile for their application+- Containerize an existing project+- Convert a development Dockerfile to production-ready+- Add Docker support to a project++## Inputs++1. **Language/Runtime** — Detected from project files (package.json, go.mod, requirements.txt, Cargo.toml, pom.xml, etc.)+2. **Framework** — Detected from dependencies (Express, FastAPI, Gin, Spring Boot, Actix, etc.)+3. **Entry point** — The main file or command to run the application+4. **Port** — The port the application listens on+5. **Build command** — If applicable (npm run build, go build, cargo build, etc.)++## Steps++### Step 1: Detect Project Type++Scan the project root for dependency/config files to determine the language and framework:++| File | Language | Common Frameworks |+|---------------------|------------|------------------------------|+| `package.json` | Node.js | Express, Next.js, Fastify |+| `requirements.txt` | Python | Flask, FastAPI, Django |+| `pyproject.toml` | Python | FastAPI, Django, Poetry |+| `go.mod` | Go | Gin, Echo, Fiber |+| `Cargo.toml` | Rust | Actix, Axum, Rocket |+| `pom.xml` | Java | Spring Boot, Quarkus |+| `build.gradle` | Java/Kotlin| Spring Boot, Ktor |+| `Gemfile` | Ruby | Rails, Sinatra |+| `composer.json` | PHP | Laravel, Symfony |++### Step 2: Generate Dockerfile++#### Node.js (Express / Fastify / NestJS)++```dockerfile+# Build stage+FROM node:20-alpine AS builder+WORKDIR /app++# Install dependencies first for better caching+COPY package.json package-lock.json ./+RUN npm ci++# Copy source and build+COPY . .+RUN npm run build++# Production stage+FROM node:20-alpine AS production+WORKDIR /app++# Install production dependencies only+COPY package.json package-lock.json ./+RUN npm ci --only=production && npm cache clean --force++# Copy built application+COPY --from=builder /app/dist ./dist++# Security: run as non-root+RUN addgroup -S appgroup && adduser -S appuser -G appgroup+USER appuser++# Health check+HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \+ CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1++EXPOSE 3000+CMD ["node", "dist/index.js"]+```++#### Next.js++```dockerfile+# Dependencies stage+FROM node:20-alpine AS deps+WORKDIR /app+COPY package.json package-lock.json ./+RUN npm ci++# Build stage+FROM node:20-alpine AS builder+WORKDIR /app+COPY --from=deps /app/node_modules ./node_modules+COPY . .+RUN npm run build++# Production stage+FROM node:20-alpine AS production+WORKDIR /app+ENV NODE_ENV=production++# Copy only the necessary files for standalone output+COPY --from=builder /app/public ./public+COPY --from=builder /app/.next/standalone ./+COPY --from=builder /app/.next/static ./.next/static++RUN addgroup -S appgroup && adduser -S appuser -G appgroup+USER appuser++HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \+ CMD wget --no-verbose --tries=1 --spider http://localhost:3000/ || exit 1++EXPOSE 3000+CMD ["node", "server.js"]+```++#### Python (FastAPI / Flask / Django)++```dockerfile+# Build stage+FROM python:3.12-slim AS builder+WORKDIR /app++# Install build dependencies+RUN apt-get update && \+ apt-get install -y --no-install-recommends gcc libpq-dev && \+ rm -rf /var/lib/apt/lists/*++# Install Python dependencies+COPY requirements.txt .+RUN pip install --no-cache-dir --prefix=/install -r requirements.txt++# Production stage+FROM python:3.12-slim AS production+WORKDIR /app++# Copy installed packages from builder+COPY --from=builder /install /usr/local++# Install runtime-only system dependencies+RUN apt-get update && \+ apt-get install -y --no-install-recommends libpq5 curl && \+ rm -rf /var/lib/apt/lists/*++# Copy application+COPY . .++# Security: run as non-root+RUN useradd --create-home --shell /bin/bash appuser+USER appuser++HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \+ CMD curl -f http://localhost:8000/health || exit 1++EXPOSE 8000+CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]+```++#### Go (Gin / Echo / Fiber)++```dockerfile+# Build stage+FROM golang:1.22-alpine AS builder+WORKDIR /app++# Install CA certificates for HTTPS and timezone data+RUN apk add --no-cache ca-certificates tzdata++# Download dependencies first for caching+COPY go.mod go.sum ./+RUN go mod download++# Build the binary+COPY . .+RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o /app/server ./cmd/server++# Production stage — scratch for minimal image+FROM scratch AS production+WORKDIR /app++# Copy CA certs and timezone data from builder+COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/+COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo++# Copy the binary+COPY --from=builder /app/server .++# Run as non-root (numeric UID since scratch has no user database)+USER 65534:65534++HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \+ CMD ["/app/server", "healthcheck"]++EXPOSE 8080+ENTRYPOINT ["/app/server"]+```++#### Java (Spring Boot)++```dockerfile+# Build stage+FROM eclipse-temurin:21-jdk-alpine AS builder+WORKDIR /app++# Copy gradle files for dependency caching+COPY build.gradle settings.gradle ./+COPY gradle ./gradle+COPY gradlew ./+RUN chmod +x gradlew && ./gradlew dependencies --no-daemon++# Build application+COPY src ./src+RUN ./gradlew bootJar --no-daemon -x test++# Extract layers for optimized Docker layering+FROM eclipse-temurin:21-jdk-alpine AS extractor+WORKDIR /app+COPY --from=builder /app/build/libs/*.jar app.jar+RUN java -Djarmode=layertools -jar app.jar extract++# Production stage+FROM eclipse-temurin:21-jre-alpine AS production+WORKDIR /app++# Copy extracted layers (ordered by change frequency)+COPY --from=extractor /app/dependencies/ ./+COPY --from=extractor /app/spring-boot-loader/ ./+COPY --from=extractor /app/snapshot-dependencies/ ./+COPY --from=extractor /app/application/ ./++# Security: run as non-root+RUN addgroup -S appgroup && adduser -S appuser -G appgroup+USER appuser++HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \+ CMD wget --no-verbose --tries=1 --spider http://localhost:8080/actuator/health || exit 1++EXPOSE 8080+ENTRYPOINT ["java", "org.springframework.boot.loader.launch.JarLauncher"]+```++#### Rust (Actix / Axum)++```dockerfile+# Build stage+FROM rust:1.76-alpine AS builder+WORKDIR /app++# Install build dependencies+RUN apk add --no-cache musl-dev++# Cache dependencies — build a dummy project first+COPY Cargo.toml Cargo.lock ./+RUN mkdir src && echo 'fn main() {}' > src/main.rs+RUN cargo build --release && rm -rf src target/release/deps/$(basename $(pwd))*++# Build the real application+COPY src ./src+RUN cargo build --release++# Production stage+FROM alpine:3.19 AS production+WORKDIR /app++# Install runtime dependencies+RUN apk add --no-cache ca-certificates++# Copy the binary+COPY --from=builder /app/target/release/app .++# Security: run as non-root+RUN addgroup -S appgroup && adduser -S appuser -G appgroup+USER appuser++HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \+ CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1++EXPOSE 8080+CMD ["./app"]+```++### Step 3: Generate .dockerignore++Create a `.dockerignore` file appropriate for the detected language:++```+# Version control+.git+.gitignore++# IDE and editor files+.vscode+.idea+*.swp+*.swo++# Docker files (prevent recursive context)+Dockerfile*+docker-compose*.yml+.dockerignore++# Documentation+*.md+LICENSE++# CI/CD+.github+.gitlab-ci.yml++# Environment files+.env+.env.*+!.env.example++# Test and coverage+coverage+__tests__+*.test.*+*.spec.*++# Language-specific (added based on detection)+# Node.js: node_modules, .next, .nuxt, dist+# Python: __pycache__, *.pyc, .venv, .pytest_cache+# Go: vendor (if not vendoring)+# Rust: target+# Java: build, .gradle, target+```++### Step 4: Validate++After generating the Dockerfile:++1. Verify the Dockerfile builds successfully: `docker build -t app:test .`+2. Verify the container runs: `docker run --rm -p PORT:PORT app:test`+3. Verify the health check passes: `docker inspect --format='{{.State.Health.Status}}' <container>`+4. Check image size: `docker images app:test`+5. Scan for vulnerabilities: `docker scout cves app:test`++## Output++- `Dockerfile` — Production-ready, multi-stage Dockerfile+- `.dockerignore` — Properly configured ignore file+- Inline comments explaining each instruction and optimization choicediff --git a/docker/skills/setup-docker-compose/SKILL.md b/docker/skills/setup-docker-compose/SKILL.mdnew file mode 100644index 00000000..e0806e89--- /dev/null+++ b/docker/skills/setup-docker-compose/SKILL.md@@ -0,0 +1,422 @@+---+name: setup-docker-compose+description: Multi-service development environments with databases, caches, and queues+---++# Skill: Set Up Docker Compose++## Description++Generate a complete Docker Compose configuration for a multi-service development environment. Includes databases, caches, message queues, and development utilities — all properly configured with health checks, networking, and volume persistence.++## Trigger++Use this skill when a user wants to:+- Set up a local development environment with Docker Compose+- Add services (databases, caches, queues) to their Docker stack+- Create a multi-service architecture with Docker Compose+- Configure a compose file for their project++## Inputs++1. **Application services** — The user's application(s) to run+2. **Data stores** — Required databases (Postgres, MySQL, MongoDB, etc.)+3. **Caches** — Required caching layers (Redis, Memcached, etc.)+4. **Message queues** — Required brokers (RabbitMQ, Kafka, NATS, etc.)+5. **Dev tools** — Optional development utilities (Adminer, Mailhog, etc.)++## Steps++### Step 1: Assess Requirements++Scan the project to determine required services:++| Dependency Indicator | Service | Default Image |+|-------------------------------|---------------------|------------------------------------|+| `pg`, `postgres`, `prisma` | PostgreSQL | `postgres:16.2-alpine` |+| `mysql`, `mysql2` | MySQL | `mysql:8.3` |+| `mongodb`, `mongoose` | MongoDB | `mongo:7.0` |+| `redis`, `ioredis` | Redis | `redis:7.2-alpine` |+| `amqplib`, `rabbitmq` | RabbitMQ | `rabbitmq:3.13-management-alpine` |+| `kafkajs`, `kafka` | Kafka | `confluentinc/cp-kafka:7.6.0` |+| `elasticsearch`, `@elastic` | Elasticsearch | `elasticsearch:8.12.2` |+| `minio`, `s3` | MinIO (S3-compat) | `minio/minio:latest` |+| `nats` | NATS | `nats:2.10-alpine` |++### Step 2: Generate Compose File++#### Full-Stack Web Application (Node.js + Postgres + Redis)++```yaml+# compose.yaml+services:+ # Application+ app:+ build:+ context: .+ dockerfile: Dockerfile+ target: development+ ports:+ - "${APP_PORT:-3000}:3000"+ environment:+ - NODE_ENV=development+ - DATABASE_URL=postgresql://postgres:postgres@db:5432/app_dev+ - REDIS_URL=redis://redis:6379+ env_file:+ - .env+ volumes:+ - ./src:/app/src+ depends_on:+ db:+ condition: service_healthy+ redis:+ condition: service_healthy+ restart: unless-stopped+ networks:+ - app-network+ develop:+ watch:+ - action: sync+ path: ./src+ target: /app/src+ - action: rebuild+ path: package.json++ # PostgreSQL Database+ db:+ image: postgres:16.2-alpine+ ports:+ - "${DB_PORT:-5432}:5432"+ environment:+ POSTGRES_USER: ${POSTGRES_USER:-postgres}+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}+ POSTGRES_DB: ${POSTGRES_DB:-app_dev}+ volumes:+ - postgres_data:/var/lib/postgresql/data+ - ./scripts/init-db.sql:/docker-entrypoint-initdb.d/init.sql:ro+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres}"]+ interval: 10s+ timeout: 5s+ retries: 5+ start_period: 30s+ restart: unless-stopped+ networks:+ - app-network+ deploy:+ resources:+ limits:+ cpus: "1.0"+ memory: 512M++ # Redis Cache+ redis:+ image: redis:7.2-alpine+ ports:+ - "${REDIS_PORT:-6379}:6379"+ command: redis-server --appendonly yes --maxmemory 256mb --maxmemory-policy allkeys-lru+ volumes:+ - redis_data:/data+ healthcheck:+ test: ["CMD", "redis-cli", "ping"]+ interval: 10s+ timeout: 5s+ retries: 5+ restart: unless-stopped+ networks:+ - app-network+ deploy:+ resources:+ limits:+ cpus: "0.5"+ memory: 256M++ # Database Admin UI (development only)+ adminer:+ image: adminer:4.8.1+ ports:+ - "${ADMINER_PORT:-8080}:8080"+ depends_on:+ db:+ condition: service_healthy+ networks:+ - app-network+ profiles:+ - dev++ # Mail catcher (development only)+ mailhog:+ image: mailhog/mailhog:v1.0.1+ ports:+ - "${MAILHOG_SMTP_PORT:-1025}:1025"+ - "${MAILHOG_UI_PORT:-8025}:8025"+ networks:+ - app-network+ profiles:+ - dev++volumes:+ postgres_data:+ driver: local+ redis_data:+ driver: local++networks:+ app-network:+ driver: bridge+```++#### Microservices Architecture++```yaml+# compose.yaml+services:+ # API Gateway+ gateway:+ build:+ context: ./services/gateway+ target: development+ ports:+ - "3000:3000"+ environment:+ - AUTH_SERVICE_URL=http://auth:3001+ - USER_SERVICE_URL=http://users:3002+ - ORDER_SERVICE_URL=http://orders:3003+ depends_on:+ auth:+ condition: service_healthy+ users:+ condition: service_healthy+ orders:+ condition: service_healthy+ networks:+ - frontend+ - backend+ restart: unless-stopped++ # Auth Service+ auth:+ build:+ context: ./services/auth+ target: development+ environment:+ - DATABASE_URL=postgresql://postgres:postgres@auth-db:5432/auth+ - REDIS_URL=redis://redis:6379+ - JWT_SECRET=${JWT_SECRET}+ depends_on:+ auth-db:+ condition: service_healthy+ redis:+ condition: service_healthy+ healthcheck:+ test: ["CMD", "wget", "--spider", "-q", "http://localhost:3001/health"]+ interval: 10s+ timeout: 5s+ retries: 3+ networks:+ - backend+ restart: unless-stopped++ # User Service+ users:+ build:+ context: ./services/users+ target: development+ environment:+ - DATABASE_URL=postgresql://postgres:postgres@users-db:5432/users+ - NATS_URL=nats://nats:4222+ depends_on:+ users-db:+ condition: service_healthy+ nats:+ condition: service_started+ healthcheck:+ test: ["CMD", "wget", "--spider", "-q", "http://localhost:3002/health"]+ interval: 10s+ timeout: 5s+ retries: 3+ networks:+ - backend+ restart: unless-stopped++ # Order Service+ orders:+ build:+ context: ./services/orders+ target: development+ environment:+ - DATABASE_URL=postgresql://postgres:postgres@orders-db:5432/orders+ - NATS_URL=nats://nats:4222+ - REDIS_URL=redis://redis:6379+ depends_on:+ orders-db:+ condition: service_healthy+ nats:+ condition: service_started+ redis:+ condition: service_healthy+ healthcheck:+ test: ["CMD", "wget", "--spider", "-q", "http://localhost:3003/health"]+ interval: 10s+ timeout: 5s+ retries: 3+ networks:+ - backend+ restart: unless-stopped++ # Databases+ auth-db:+ image: postgres:16.2-alpine+ environment:+ POSTGRES_DB: auth+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ volumes:+ - auth_db_data:/var/lib/postgresql/data+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U postgres"]+ interval: 10s+ timeout: 5s+ retries: 5+ networks:+ - backend+ restart: unless-stopped++ users-db:+ image: postgres:16.2-alpine+ environment:+ POSTGRES_DB: users+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ volumes:+ - users_db_data:/var/lib/postgresql/data+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U postgres"]+ interval: 10s+ timeout: 5s+ retries: 5+ networks:+ - backend+ restart: unless-stopped++ orders-db:+ image: postgres:16.2-alpine+ environment:+ POSTGRES_DB: orders+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ volumes:+ - orders_db_data:/var/lib/postgresql/data+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U postgres"]+ interval: 10s+ timeout: 5s+ retries: 5+ networks:+ - backend+ restart: unless-stopped++ # Shared Infrastructure+ redis:+ image: redis:7.2-alpine+ command: redis-server --appendonly yes+ volumes:+ - redis_data:/data+ healthcheck:+ test: ["CMD", "redis-cli", "ping"]+ interval: 10s+ timeout: 5s+ retries: 5+ networks:+ - backend+ restart: unless-stopped++ nats:+ image: nats:2.10-alpine+ ports:+ - "8222:8222" # Monitoring+ command: "--js --sd /data"+ volumes:+ - nats_data:/data+ networks:+ - backend+ restart: unless-stopped++volumes:+ auth_db_data:+ users_db_data:+ orders_db_data:+ redis_data:+ nats_data:++networks:+ frontend:+ driver: bridge+ backend:+ driver: bridge+ internal: true+```++### Step 3: Generate Environment Template++Create a `.env.example` file:++```env+# Application+APP_PORT=3000+NODE_ENV=development++# Database+POSTGRES_USER=postgres+POSTGRES_PASSWORD=postgres+POSTGRES_DB=app_dev+DB_PORT=5432++# Redis+REDIS_PORT=6379++# Dev Tools+ADMINER_PORT=8080+MAILHOG_SMTP_PORT=1025+MAILHOG_UI_PORT=8025++# Secrets (change in production)+JWT_SECRET=change-me-in-production+```++### Step 4: Generate Override File for Development++Create `compose.override.yaml` for local development additions:++```yaml+# compose.override.yaml — automatically loaded in development+services:+ app:+ build:+ target: development+ volumes:+ - ./src:/app/src+ - ./tests:/app/tests+ environment:+ - DEBUG=true+ - LOG_LEVEL=debug+ command: ["npm", "run", "dev"]+```++### Step 5: Validate++After generating the Compose configuration:++1. Validate syntax: `docker compose config`+2. Start services: `docker compose up -d`+3. Check health: `docker compose ps` (all services should be "healthy")+4. Verify connectivity between services: `docker compose exec app ping db`+5. Check logs for errors: `docker compose logs --tail=50`+6. Start with dev profile: `docker compose --profile dev up -d`++## Output++- `compose.yaml` — Main compose configuration+- `compose.override.yaml` — Development overrides+- `.env.example` — Environment variable template+- Service-specific initialization scripts if neededdiff --git a/elixir-phoenix/.cursor-plugin/plugin.json b/elixir-phoenix/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..551a18d4--- /dev/null+++ b/elixir-phoenix/.cursor-plugin/plugin.json@@ -0,0 +1,27 @@+{+ "name": "elixir-phoenix",+ "version": "1.0.0",+ "description": "Elixir, Phoenix, LiveView, and Tailwind development rules by Ilyich Vismara (cursor.directory)",+ "author": {+ "name": "Ilyich Vismara",+ "url": "https://cursor.directory/elixir-phoenix-cursor-rules"+ },+ "homepage": "https://cursor.directory/elixir-phoenix-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "elixir",+ "phoenix",+ "liveview",+ "ecto",+ "tailwind"+ ],+ "category": "backend",+ "tags": [+ "phoenix",+ "elixir",+ "ecto",+ "live_view"+ ],+ "rules": "./rules/"+}diff --git a/elixir-phoenix/README.md b/elixir-phoenix/README.mdnew file mode 100644index 00000000..5e08da11--- /dev/null+++ b/elixir-phoenix/README.md@@ -0,0 +1,29 @@+# elixir-phoenix++Elixir, Phoenix, LiveView, and Tailwind development rules by Ilyich Vismara (cursor.directory)++## Installation++```bash+agent install elixir-phoenix+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `elixir_phoenix` | Elixir and Phoenix development with LiveView, Ecto, and Tailwind CSS | `**/*.ex, **/*.exs, **/*.heex` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/elixir-phoenix-cursor-rules).++- **Original Author**: Ilyich Vismara+- **Tags**: phoenix, elixir, ecto, live_view+- **Category**: backend++## License++MITdiff --git a/elixir-phoenix/rules/elixir_phoenix.mdc b/elixir-phoenix/rules/elixir_phoenix.mdcnew file mode 100644index 00000000..7eba8839--- /dev/null+++ b/elixir-phoenix/rules/elixir_phoenix.mdc@@ -0,0 +1,68 @@+---+description: Elixir and Phoenix development with LiveView, Ecto, and Tailwind CSS+globs:+ - "**/*.ex"+ - "**/*.exs"+ - "**/*.heex"+alwaysApply: false+---++You are an expert in Elixir, Phoenix, PostgreSQL, LiveView, and Tailwind CSS.++Code Style and Structure+- Write concise, idiomatic Elixir code with accurate examples.+- Follow Phoenix conventions and best practices.+- Use functional programming patterns and leverage immutability.+- Prefer higher-order functions and recursion over imperative loops.+- Use descriptive variable and function names (e.g., user_signed_in?, calculate_total).+- Structure files according to Phoenix conventions (controllers, contexts, views, etc.).++Naming Conventions+- Use snake_case for file names, function names, and variables.+- Use PascalCase for module names.+- Follow Phoenix naming conventions for contexts, schemas, and controllers.++Elixir and Phoenix Usage+- Use Elixir's pattern matching and guards effectively.+- Leverage Phoenix's built-in functions and macros.+- Use Ecto effectively for database operations.++Syntax and Formatting+- Follow the Elixir Style Guide (https://github.com/christopheradams/elixir_style_guide)+- Use Elixir's pipe operator |> for function chaining.+- Prefer single quotes for charlists and double quotes for strings.++Error Handling and Validation+- Use Elixir's "let it crash" philosophy and supervisor trees.+- Implement proper error logging and user-friendly messages.+- Use Ecto changesets for data validation.+- Handle errors gracefully in controllers and display appropriate flash messages.++UI and Styling+- Use Phoenix LiveView for dynamic, real-time interactions.+- Implement responsive design with Tailwind CSS.+- Use Phoenix view helpers and templates to keep views DRY.++Performance Optimization+- Use database indexing effectively.+- Implement caching strategies (ETS, Redis).+- Use Ecto's preload to avoid N+1 queries.+- Optimize database queries using preload, joins, or select.++Key Conventions+- Follow RESTful routing conventions.+- Use contexts for organizing related functionality.+- Implement GenServers for stateful processes and background jobs.+- Use Tasks for concurrent, isolated jobs.++Testing+- Write comprehensive tests using ExUnit.+- Follow TDD practices.+- Use ExMachina for test data generation.++Security+- Implement proper authentication and authorization (e.g., Guardian, Pow).+- Use strong parameters in controllers (params validation).+- Protect against common web vulnerabilities (XSS, CSRF, SQL injection).++Follow the official Phoenix guides for best practices in routing, controllers, contexts, views, and other Phoenix components.diff --git a/fastapi-python/.cursor-plugin/plugin.json b/fastapi-python/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..00bfe821--- /dev/null+++ b/fastapi-python/.cursor-plugin/plugin.json@@ -0,0 +1,27 @@+{+ "name": "fastapi-python",+ "version": "1.0.0",+ "description": "FastAPI and scalable Python API development rules by Caio Barbieri (cursor.directory)",+ "author": {+ "name": "Caio Barbieri",+ "url": "https://cursor.directory/fastapi-python-cursor-rules"+ },+ "homepage": "https://cursor.directory/fastapi-python-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "python",+ "fastapi",+ "api",+ "pydantic",+ "async"+ ],+ "category": "backend",+ "tags": [+ "python",+ "fastapi",+ "api",+ "pydantic"+ ],+ "rules": "./rules/"+}diff --git a/fastapi-python/README.md b/fastapi-python/README.mdnew file mode 100644index 00000000..b309b1c7--- /dev/null+++ b/fastapi-python/README.md@@ -0,0 +1,29 @@+# fastapi-python++FastAPI and scalable Python API development rules by Caio Barbieri (cursor.directory)++## Installation++```bash+agent install fastapi-python+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `fastapi_python` | FastAPI Python development best practices and API design patterns | `**/*.py` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/fastapi-python-cursor-rules).++- **Original Author**: Caio Barbieri+- **Tags**: python, fastapi, api, pydantic, async+- **Category**: backend++## License++MITdiff --git a/fastapi-python/rules/fastapi_python.mdc b/fastapi-python/rules/fastapi_python.mdcnew file mode 100644index 00000000..7fbe3266--- /dev/null+++ b/fastapi-python/rules/fastapi_python.mdc@@ -0,0 +1,68 @@+---+description: FastAPI Python development best practices and API design patterns+globs:+ - "**/*.py"+alwaysApply: false+---++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.diff --git a/firebase/.cursor-plugin/plugin.json b/firebase/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..3f686179--- /dev/null+++ b/firebase/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "firebase",+ "version": "1.0.0",+ "description": "Cursor plugin for Firebase \u2014 Firestore, Authentication, Cloud Functions, Hosting, and Storage",+ "author": {+ "name": "Cursor",+ "email": "[email protected]"+ },+ "homepage": "https://github.com/cursor/plugins",+ "repository": "https://github.com/cursor/plugins",+ "license": "MIT",+ "keywords": [+ "firebase",+ "firestore",+ "cloud-functions",+ "authentication",+ "hosting"+ ],+ "category": "backend",+ "tags": [+ "baas",+ "google-cloud",+ "real-time"+ ],+ "logo": "./firebase.svg",+ "skills": "./skills/",+ "mcpServers": "./mcp.json"+}diff --git a/firebase/CHANGELOG.md b/firebase/CHANGELOG.mdnew file mode 100644index 00000000..5f2859de--- /dev/null+++ b/firebase/CHANGELOG.md@@ -0,0 +1,13 @@+# Changelog++All notable changes to this plugin will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [Unreleased]++## [1.0.0] - 2026-02-07++### Added+- Initial plugin with skills and MCP server configurationdiff --git a/firebase/LICENSE b/firebase/LICENSEnew file mode 100644index 00000000..ca2bba77--- /dev/null+++ b/firebase/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Cursor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/firebase/README.md b/firebase/README.mdnew file mode 100644index 00000000..475f301e--- /dev/null+++ b/firebase/README.md@@ -0,0 +1,28 @@+# Firebase Plugin++Cursor plugin for Firebase — Firestore, Authentication, Cloud Functions, Hosting, and Storage.++## Installation++```bash+agent install firebase+```++## Components++### Skills++| Skill | Description |+|:------|:------------|+| `setup-firebase` | Project initialization, SDK setup, emulator configuration, and deployment |+| `design-firestore-schema` | Data modeling patterns, subcollections, denormalization, and security rules |++### MCP Server++Provides Firebase management via `firebase-mcp-server`.++Requires `FIREBASE_TOKEN` environment variable.++## License++MITdiff --git a/firebase/firebase.svg b/firebase/firebase.svgnew file mode 100644index 00000000..c45ada80--- /dev/null+++ b/firebase/firebase.svg@@ -0,0 +1 @@+<svg width="64" height="64" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Firebase</title><path d="M19.455 8.369c-.538-.748-1.778-2.285-3.681-4.569-.826-.991-1.535-1.832-1.884-2.245a146 146 0 0 0-.488-.576l-.207-.245-.113-.133-.022-.032-.01-.005L12.57 0l-.609.488c-1.555 1.246-2.828 2.851-3.681 4.64-.523 1.064-.864 2.105-1.043 3.176-.047.241-.088.489-.121.738-.209-.017-.421-.028-.632-.033-.018-.001-.035-.002-.059-.003a7.46 7.46 0 0 0-2.28.274l-.317.089-.163.286c-.765 1.342-1.198 2.869-1.252 4.416-.07 2.01.477 3.954 1.583 5.625 1.082 1.633 2.61 2.882 4.42 3.611l.236.095.071.025.003-.001a9.59 9.59 0 0 0 2.941.568q.171.006.342.006c1.273 0 2.513-.249 3.69-.742l.008.004.313-.145a9.63 9.63 0 0 0 3.927-3.335c1.01-1.49 1.577-3.234 1.641-5.042.075-2.161-.643-4.304-2.133-6.371m-7.083 6.695c.328 1.244.264 2.44-.191 3.558-1.135-1.12-1.967-2.352-2.475-3.665-.543-1.404-.87-2.74-.974-3.975.48.157.922.366 1.315.622 1.132.737 1.914 1.902 2.325 3.461zm.207 6.022c.482.368.99.712 1.513 1.028-.771.21-1.565.302-2.369.273a8 8 0 0 1-.373-.022c.458-.394.869-.823 1.228-1.279zm1.347-6.431c-.516-1.957-1.527-3.437-3.002-4.398-.647-.421-1.385-.741-2.194-.95.011-.134.026-.268.043-.4.014-.113.03-.216.046-.313.133-.689.332-1.37.589-2.025.099-.25.206-.499.321-.74l.004-.008c.177-.358.376-.719.61-1.105l.092-.152-.003-.001c.544-.851 1.197-1.627 1.942-2.311l.288.341c.672.796 1.304 1.548 1.878 2.237 1.291 1.549 2.966 3.583 3.612 4.48 1.277 1.771 1.893 3.579 1.83 5.375-.049 1.395-.461 2.755-1.195 3.933-.694 1.116-1.661 2.05-2.8 2.708-.636-.318-1.559-.839-2.539-1.599.79-1.575.952-3.28.479-5.072zm-2.575 5.397c-.725.939-1.587 1.55-2.09 1.856-.081-.029-.163-.06-.243-.093l-.065-.026c-1.49-.616-2.747-1.656-3.635-3.01-.907-1.384-1.356-2.993-1.298-4.653.041-1.19.338-2.327.882-3.379.316-.07.638-.114.96-.131l.084-.002c.162-.003.324-.003.478 0 .227.011.454.035.677.07.073 1.513.445 3.145 1.105 4.852.637 1.644 1.694 3.162 3.144 4.515z"/></svg>diff --git a/firebase/mcp.json b/firebase/mcp.jsonnew file mode 100644index 00000000..54033524--- /dev/null+++ b/firebase/mcp.json@@ -0,0 +1,14 @@+{+ "$schema": "https://cursor.com/schemas/mcp.json",+ "mcpServers": {+ "firebase": {+ "command": "npx",+ "args": ["-y", "firebase-mcp-server"],+ "description": "Firebase MCP server for Firestore, Auth, and Cloud Functions management",+ "env": {+ "GOOGLE_APPLICATION_CREDENTIALS": "${workspaceFolder}/service-account-key.json",+ "FIREBASE_PROJECT_ID": "${config:firebase.projectId}"+ }+ }+ }+}diff --git a/firebase/skills/design-firestore-schema/SKILL.md b/firebase/skills/design-firestore-schema/SKILL.mdnew file mode 100644index 00000000..03d3f961--- /dev/null+++ b/firebase/skills/design-firestore-schema/SKILL.md@@ -0,0 +1,293 @@+---+name: design-firestore-schema+description: Data modeling patterns, subcollections, denormalization, and security rules for Firestore+---++# Design Firestore Schema++## Description++Design and implement a Firestore data model with proper collection structures, security rules, and composite indexes optimized for your application's query patterns.++## Prerequisites++- Firebase project initialized (`firebase init firestore`)+- Firebase Emulator Suite configured for local testing+- Understanding of the application's primary query patterns++## Steps++### 1. Identify Query Patterns++Before designing your schema, list every query your application will perform. Firestore schemas are designed around queries, not entity relationships.++Common questions to answer:+- What data does each screen/page need?+- Which fields will be used for filtering and sorting?+- What are the access control requirements per collection?+- How frequently will each document be read vs. written?++### 2. Design the Collection Hierarchy++Organize data into collections and subcollections based on query patterns and access control boundaries.++**Pattern: Root Collections** — Use when data is queried independently across the entire app.++```+├── users/{userId}+│ ├── displayName: string+│ ├── email: string+│ ├── photoURL: string+│ ├── createdAt: timestamp+│ └── updatedAt: timestamp+│+├── posts/{postId}+│ ├── title: string+│ ├── content: string+│ ├── authorId: string+│ ├── authorName: string ← denormalized for display+│ ├── tags: array<string>+│ ├── status: string ("draft" | "published")+│ ├── createdAt: timestamp+│ └── updatedAt: timestamp+```++**Pattern: Subcollections** — Use for 1:N relationships where child data is queried within a parent scope.++```+├── posts/{postId}+│ └── comments/{commentId} ← subcollection+│ ├── text: string+│ ├── authorId: string+│ ├── authorName: string+│ └── createdAt: timestamp+```++**Pattern: Denormalization** — Duplicate data across documents to support queries without joins.++```+├── posts/{postId}+│ ├── authorId: string+│ ├── authorName: string ← duplicated from users/{authorId}+│ └── authorPhotoURL: string ← duplicated from users/{authorId}+```++Keep denormalized data up to date with Cloud Functions triggers:++```typescript+export const onUserUpdated = onDocumentUpdated("users/{userId}", async (event) => {+ const before = event.data?.before.data();+ const after = event.data?.after.data();+ if (!before || !after) return;++ if (before.displayName !== after.displayName || before.photoURL !== after.photoURL) {+ const postsQuery = query(+ collection(db, "posts"),+ where("authorId", "==", event.params.userId)+ );+ const posts = await getDocs(postsQuery);+ const batch = writeBatch(db);+ posts.docs.forEach((doc) => {+ batch.update(doc.ref, {+ authorName: after.displayName,+ authorPhotoURL: after.photoURL,+ });+ });+ await batch.commit();+ }+});+```++### 3. Define Data Validation in Security Rules++Write security rules that validate every field on create and update operations.++```rules+rules_version = '2';+service cloud.firestore {+ match /databases/{database}/documents {++ function isAuthenticated() {+ return request.auth != null;+ }++ function isOwner(userId) {+ return request.auth.uid == userId;+ }++ match /users/{userId} {+ allow read: if isAuthenticated();+ allow create: if isOwner(userId)+ && request.resource.data.keys().hasAll(["displayName", "email", "createdAt"])+ && request.resource.data.displayName is string+ && request.resource.data.displayName.size() > 0+ && request.resource.data.displayName.size() <= 100+ && request.resource.data.email is string+ && request.resource.data.createdAt == request.time;+ allow update: if isOwner(userId)+ && request.resource.data.diff(resource.data).affectedKeys()+ .hasOnly(["displayName", "photoURL", "updatedAt"])+ && request.resource.data.updatedAt == request.time;+ allow delete: if false;+ }++ match /posts/{postId} {+ allow read: if isAuthenticated();+ allow create: if isAuthenticated()+ && request.resource.data.authorId == request.auth.uid+ && request.resource.data.title is string+ && request.resource.data.title.size() > 0+ && request.resource.data.title.size() <= 200+ && request.resource.data.status in ["draft", "published"]+ && request.resource.data.createdAt == request.time;+ allow update: if isOwner(resource.data.authorId);+ allow delete: if isOwner(resource.data.authorId);++ match /comments/{commentId} {+ allow read: if isAuthenticated();+ allow create: if isAuthenticated()+ && request.resource.data.authorId == request.auth.uid+ && request.resource.data.text is string+ && request.resource.data.text.size() > 0+ && request.resource.data.text.size() <= 5000;+ allow delete: if isOwner(resource.data.authorId);+ }+ }+ }+}+```++### 4. Create Composite Indexes++Define composite indexes in `firestore.indexes.json` for queries that filter or order on multiple fields.++```json+{+ "indexes": [+ {+ "collectionGroup": "posts",+ "queryScope": "COLLECTION",+ "fields": [+ { "fieldPath": "status", "order": "ASCENDING" },+ { "fieldPath": "createdAt", "order": "DESCENDING" }+ ]+ },+ {+ "collectionGroup": "posts",+ "queryScope": "COLLECTION",+ "fields": [+ { "fieldPath": "authorId", "order": "ASCENDING" },+ { "fieldPath": "createdAt", "order": "DESCENDING" }+ ]+ },+ {+ "collectionGroup": "comments",+ "queryScope": "COLLECTION_GROUP",+ "fields": [+ { "fieldPath": "authorId", "order": "ASCENDING" },+ { "fieldPath": "createdAt", "order": "DESCENDING" }+ ]+ }+ ],+ "fieldOverrides": []+}+```++Deploy indexes:++```bash+firebase deploy --only firestore:indexes+```++### 5. Implement Type-Safe Data Access Layer++Create a typed data access layer using Firestore converters:++```typescript+import {+ collection,+ doc,+ getDoc,+ getDocs,+ setDoc,+ query,+ where,+ orderBy,+ limit,+ startAfter,+ serverTimestamp,+ FirestoreDataConverter,+ QueryDocumentSnapshot,+ DocumentData,+ Timestamp,+} from "firebase/firestore";++// Types+interface User {+ id: string;+ displayName: string;+ email: string;+ photoURL?: string;+ createdAt: Timestamp;+ updatedAt?: Timestamp;+}++// Converter+const userConverter: FirestoreDataConverter<User> = {+ toFirestore(user: User): DocumentData {+ const { id, ...data } = user;+ return data;+ },+ fromFirestore(snapshot: QueryDocumentSnapshot): User {+ const data = snapshot.data();+ return {+ id: snapshot.id,+ displayName: data.displayName,+ email: data.email,+ photoURL: data.photoURL,+ createdAt: data.createdAt,+ updatedAt: data.updatedAt,+ };+ },+};++// Typed collection reference+const usersRef = collection(db, "users").withConverter(userConverter);++// Typed queries+async function getUserById(userId: string): Promise<User | null> {+ const snap = await getDoc(doc(usersRef, userId));+ return snap.exists() ? snap.data() : null;+}++async function getRecentUsers(pageSize = 25, lastDoc?: QueryDocumentSnapshot): Promise<User[]> {+ let q = query(usersRef, orderBy("createdAt", "desc"), limit(pageSize));+ if (lastDoc) {+ q = query(usersRef, orderBy("createdAt", "desc"), startAfter(lastDoc), limit(pageSize));+ }+ const snapshot = await getDocs(q);+ return snapshot.docs.map((doc) => doc.data());+}+```++### 6. Test with the Emulator++Start the Firestore emulator:++```bash+firebase emulators:start --only firestore+```++Write and run security rule tests:++```bash+npm test+```++## Validation++- Verify all queries return expected results in the Emulator UI+- Run security rule unit tests — all must pass+- Deploy indexes with `firebase deploy --only firestore:indexes` and verify no errors+- Test pagination with datasets larger than the page size+- Verify denormalized data updates propagate correctly via Cloud Functionsdiff --git a/firebase/skills/setup-firebase/SKILL.md b/firebase/skills/setup-firebase/SKILL.mdnew file mode 100644index 00000000..24bac329--- /dev/null+++ b/firebase/skills/setup-firebase/SKILL.md@@ -0,0 +1,231 @@+---+name: setup-firebase+description: Project initialization, SDK setup, emulator configuration, and deployment for Firebase+---++# Setup Firebase Project++## Description++Initialize a new Firebase project with the Firebase CLI, configure services (Firestore, Auth, Cloud Functions, Hosting, Storage), set up the Firebase Emulator Suite for local development, and prepare for deployment.++## Prerequisites++- Node.js 18+ installed+- A Google account with access to the Firebase Console+- Firebase CLI installed (`npm install -g firebase-tools`)++## Steps++### 1. Install the Firebase CLI++```bash+npm install -g firebase-tools+```++Verify the installation:++```bash+firebase --version+```++### 2. Authenticate with Firebase++```bash+firebase login+```++This opens a browser window for Google account authentication. For CI environments, use:++```bash+firebase login:ci+```++### 3. Create a Firebase Project++Create a new project via the Firebase Console (https://console.firebase.google.com) or use the CLI:++```bash+firebase projects:create my-project-id --display-name "My Project"+```++### 4. Initialize Firebase in Your Project Directory++```bash+mkdir my-firebase-app && cd my-firebase-app+firebase init+```++Select the services you need:+- **Firestore** — Database rules and indexes+- **Functions** — Cloud Functions (TypeScript recommended)+- **Hosting** — Static site hosting+- **Storage** — Cloud Storage rules+- **Emulators** — Local development emulators++Alternatively, initialize specific services directly:++```bash+firebase init firestore functions hosting storage emulators+```++### 5. Configure Firestore++After initialization, you will have:+- `firestore.rules` — Security rules file+- `firestore.indexes.json` — Composite index definitions+- `firebase.json` — Project configuration++Set up initial security rules in `firestore.rules`:++```rules+rules_version = '2';+service cloud.firestore {+ match /databases/{database}/documents {+ match /{document=**} {+ allow read, write: if request.auth != null;+ }+ }+}+```++### 6. Configure Cloud Functions++Navigate to the functions directory and install dependencies:++```bash+cd functions+npm install+```++Set the Node.js runtime version in `functions/package.json`:++```json+{+ "engines": {+ "node": "20"+ }+}+```++Create your first function in `functions/src/index.ts`:++```typescript+import { onRequest } from "firebase-functions/v2/https";+import { onDocumentCreated } from "firebase-functions/v2/firestore";++export const helloWorld = onRequest((req, res) => {+ res.json({ message: "Hello from Firebase Cloud Functions!" });+});++export const onUserCreated = onDocumentCreated("users/{userId}", async (event) => {+ const snapshot = event.data;+ if (!snapshot) return;+ console.log("New user created:", snapshot.id, snapshot.data());+});+```++### 7. Set Up Firebase Emulators++Configure emulators in `firebase.json`:++```json+{+ "emulators": {+ "auth": { "port": 9099 },+ "functions": { "port": 5001 },+ "firestore": { "port": 8080 },+ "hosting": { "port": 5000 },+ "storage": { "port": 9199 },+ "ui": { "enabled": true, "port": 4000 }+ }+}+```++Start the emulators:++```bash+firebase emulators:start+```++Access the Emulator UI at `http://localhost:4000`.++### 8. Configure the Firebase SDK in Your App++Install the Firebase SDK:++```bash+npm install firebase+```++Initialize Firebase in your application:++```typescript+import { initializeApp } from "firebase/app";+import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";+import { getAuth, connectAuthEmulator } from "firebase/auth";++const firebaseConfig = {+ apiKey: "your-api-key",+ authDomain: "your-project.firebaseapp.com",+ projectId: "your-project-id",+ storageBucket: "your-project.appspot.com",+ messagingSenderId: "123456789",+ appId: "1:123456789:web:abcdef",+};++const app = initializeApp(firebaseConfig);+const db = getFirestore(app);+const auth = getAuth(app);++// Connect to emulators in development+if (process.env.NODE_ENV === "development") {+ connectFirestoreEmulator(db, "localhost", 8080);+ connectAuthEmulator(auth, "http://localhost:9099");+}+```++### 9. Deploy to Firebase++Deploy all services:++```bash+firebase deploy+```++Deploy specific services:++```bash+firebase deploy --only firestore:rules+firebase deploy --only functions+firebase deploy --only hosting+firebase deploy --only storage+```++### 10. Set Up Multiple Environments++Use Firebase project aliases for staging and production:++```bash+firebase use --add # Add a project alias+firebase use staging # Switch to staging+firebase use production # Switch to production+```++Configure environment-specific settings in `.firebaserc`:++```json+{+ "projects": {+ "staging": "my-project-staging",+ "production": "my-project-production"+ }+}+```++## Validation++- Run `firebase emulators:start` and verify the Emulator UI loads at `http://localhost:4000`+- Create a test document in Firestore via the Emulator UI+- Trigger a Cloud Function and check the emulator logs+- Deploy to a staging project and verify all services are runningdiff --git a/flutter-dart/.cursor-plugin/plugin.json b/flutter-dart/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..22566b8a--- /dev/null+++ b/flutter-dart/.cursor-plugin/plugin.json@@ -0,0 +1,27 @@+{+ "name": "flutter-dart",+ "version": "1.0.0",+ "description": "Flutter and Dart clean architecture development rules by Sercan Yusuf (cursor.directory)",+ "author": {+ "name": "Sercan Yusuf",+ "url": "https://cursor.directory/flutter-cursor-rules"+ },+ "homepage": "https://cursor.directory/flutter-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "flutter",+ "dart",+ "riverpod",+ "freezed",+ "mobile"+ ],+ "category": "mobile",+ "tags": [+ "Riverpod",+ "Freezed",+ "AutoRoute",+ "GetIt"+ ],+ "rules": "./rules/"+}diff --git a/flutter-dart/README.md b/flutter-dart/README.mdnew file mode 100644index 00000000..f3ed33ca--- /dev/null+++ b/flutter-dart/README.md@@ -0,0 +1,29 @@+# flutter-dart++Flutter and Dart clean architecture development rules by Sercan Yusuf (cursor.directory)++## Installation++```bash+agent install flutter-dart+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `flutter_dart` | Flutter and Dart development with Riverpod, Freezed, and clean architecture | `**/*.dart, **/pubspec.yaml` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/flutter-cursor-rules).++- **Original Author**: Sercan Yusuf+- **Tags**: Riverpod, Freezed, AutoRoute, GetIt+- **Category**: mobile++## License++MITdiff --git a/flutter-dart/rules/flutter_dart.mdc b/flutter-dart/rules/flutter_dart.mdcnew file mode 100644index 00000000..fa792fa6--- /dev/null+++ b/flutter-dart/rules/flutter_dart.mdc@@ -0,0 +1,135 @@+---+description: Flutter and Dart development with Riverpod, Freezed, and clean architecture+globs:+ - "**/*.dart"+ - "**/pubspec.yaml"+alwaysApply: false+---++You are a senior Dart programmer with experience in the Flutter framework and a preference for clean programming and design patterns.++Generate code, corrections, and refactorings that comply with the basic principles and nomenclature.++## Dart General Guidelines++### Basic Principles++- Use English for all code and documentation.+- Always declare the type of each variable and function (parameters and return value).+- Avoid using any.+- Create necessary types.+- Don't leave blank lines within a function.+- One export per file.++### Nomenclature++- Use PascalCase for classes.+- Use camelCase for variables, functions, and methods.+- Use underscores_case for file and directory names.+- Use UPPERCASE for environment variables.+- Avoid magic numbers and define constants.+- Start each function with a verb.+- Use verbs for boolean variables. Example: isLoading, hasError, canDelete, etc.+- Use complete words instead of abbreviations and correct spelling.+- Except for standard abbreviations like API, URL, etc.+- Except for well-known abbreviations:+ - i, j for loops+ - err for errors+ - ctx for contexts+ - req, res, next for middleware function parameters++### Functions++- In this context, what is understood as a function will also apply to a method.+- Write short functions with a single purpose. Less than 20 instructions.+- Name functions with a verb and something else.+- If it returns a boolean, use isX or hasX, canX, etc.+- If it doesn't return anything, use executeX or saveX, etc.+- Avoid nesting blocks by:+- Early checks and returns.+- Extraction to utility functions.+- Use higher-order functions (map, filter, reduce, etc.) to avoid function nesting.+- Use arrow functions for simple functions (less than 3 instructions).+- Use named functions for non-simple functions.+- Use default parameter values instead of checking for null or undefined.+- Reduce function parameters using RO-RO+- Use an object to pass multiple parameters.+- Use an object to return results.+- Declare necessary types for input arguments and output.+- Use a single level of abstraction.++### Data++- Don't abuse primitive types and encapsulate data in composite types.+- Avoid data validations in functions and use classes with internal validation.+- Prefer immutability for data.+- Use readonly for data that doesn't change.+- Use as const for literals that don't change.++### Classes++- Follow SOLID principles.+- Prefer composition over inheritance.+- Declare interfaces to define contracts.+- Write small classes with a single purpose.+- Less than 200 instructions.+- Less than 10 public methods.+- Less than 10 properties.++### Exceptions++- Use exceptions to handle errors you don't expect.+- If you catch an exception, it should be to:+- Fix an expected problem.+- Add context.+- Otherwise, use a global handler.++### Testing++- Follow the Arrange-Act-Assert convention for tests.+- Name test variables clearly.+- Follow the convention: inputX, mockX, actualX, expectedX, etc.+- Write unit tests for each public function.+- Use test doubles to simulate dependencies.+ - Except for third-party dependencies that are not expensive to execute.+- Write acceptance tests for each module.+- Follow the Given-When-Then convention.++## Specific to Flutter++### Basic Principles++- Use clean architecture+- see modules if you need to organize code into modules+- see controllers if you need to organize code into controllers+- see services if you need to organize code into services+- see repositories if you need to organize code into repositories+- see entities if you need to organize code into entities+- Use repository pattern for data persistence+- see cache if you need to cache data+- Use controller pattern for business logic with Riverpod+- Use Riverpod to manage state+- see keepAlive if you need to keep the state alive+- Use freezed to manage UI states+- Controller always takes methods as input and updates the UI state that effects the UI+- Use getIt to manage dependencies+- Use singleton for services and repositories+- Use factory for use cases+- Use lazy singleton for controllers+- Use AutoRoute to manage routes+- Use extras to pass data between pages+- Use extensions to manage reusable code+- Use ThemeData to manage themes+- Use AppLocalizations to manage translations+- Use constants to manage constants values+- When a widget tree becomes too deep, it can lead to longer build times and increased memory usage. Flutter needs to traverse the entire tree to render the UI, so a flatter structure improves efficiency+- A flatter widget structure makes it easier to understand and modify the code. Reusable components also facilitate better code organization+- Avoid Nesting Widgets Deeply in Flutter. Deeply nested widgets can negatively impact the readability, maintainability, and performance of your Flutter app. Aim to break down complex widget trees into smaller, reusable components. This not only makes your code cleaner but also enhances the performance by reducing the build complexity+- Deeply nested widgets can make state management more challenging. By keeping the tree shallow, it becomes easier to manage state and pass data between widgets+- Break down large widgets into smaller, focused widgets+- Utilize const constructors wherever possible to reduce rebuilds++### Testing++- Use the standard widget testing for flutter+- Use integration tests for each api module.diff --git a/frontend-developer/.cursor-plugin/plugin.json b/frontend-developer/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..78990d70--- /dev/null+++ b/frontend-developer/.cursor-plugin/plugin.json@@ -0,0 +1,27 @@+{+ "name": "frontend-developer",+ "version": "1.0.0",+ "description": "Expert React, Next.js, TypeScript, and Tailwind CSS development rules by Mohammadali Karimi (cursor.directory)",+ "author": {+ "name": "Mohammadali Karimi",+ "url": "https://cursor.directory/front-end-cursor-rules"+ },+ "homepage": "https://cursor.directory/front-end-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "react",+ "nextjs",+ "typescript",+ "tailwindcss",+ "shadcn",+ "radix"+ ],+ "category": "frontend",+ "tags": [+ "Tailwind CSS",+ "Shadcn UI",+ "Radix UI"+ ],+ "rules": "./rules/"+}diff --git a/frontend-developer/README.md b/frontend-developer/README.mdnew file mode 100644index 00000000..c90f43d4--- /dev/null+++ b/frontend-developer/README.md@@ -0,0 +1,29 @@+# frontend-developer++Expert React, Next.js, TypeScript, and Tailwind CSS development rules by Mohammadali Karimi (cursor.directory)++## Installation++```bash+agent install frontend-developer+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `frontend_developer` | Frontend development best practices for React, Next.js, TypeScript and Tailwind CSS | `**/*.ts, **/*.tsx, **/*.jsx` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/front-end-cursor-rules).++- **Original Author**: Mohammadali Karimi+- **Tags**: Tailwind CSS, Shadcn UI, Radix UI+- **Category**: frontend++## License++MITdiff --git a/frontend-developer/rules/frontend_developer.mdc b/frontend-developer/rules/frontend_developer.mdcnew file mode 100644index 00000000..59aa6ffd--- /dev/null+++ b/frontend-developer/rules/frontend_developer.mdc@@ -0,0 +1,45 @@+---+description: Frontend development best practices for React, Next.js, TypeScript and Tailwind CSS+globs:+ - "**/*.ts"+ - "**/*.tsx"+ - "**/*.jsx"+ - "**/*.js"+ - "**/*.css"+ - "**/*.html"+alwaysApply: false+---++You are a Senior Front-End Developer and an Expert in ReactJS, NextJS, JavaScript, TypeScript, HTML, CSS and modern UI/UX frameworks (e.g., TailwindCSS, Shadcn, Radix). You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.++- Follow the user’s requirements carefully & to the letter.+- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.+- Confirm, then write code!+- Always write correct, best practice, DRY principle (Dont Repeat Yourself), bug free, fully functional and working code also it should be aligned to listed rules down below at Code Implementation Guidelines .+- Focus on easy and readability code, over being performant.+- Fully implement all requested functionality.+- Leave NO todo’s, placeholders or missing pieces.+- Ensure code is complete! Verify thoroughly finalised.+- Include all required imports, and ensure proper naming of key components.+- Be concise Minimize any other prose.+- 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.++### Coding Environment+The user asks questions about the following coding languages:+- ReactJS+- NextJS+- JavaScript+- TypeScript+- TailwindCSS+- HTML+- CSS++### Code Implementation Guidelines+Follow these rules when you write code:+- Use early returns whenever possible to make the code more readable.+- Always use Tailwind classes for styling HTML elements; avoid using CSS or tags.+- Use “class:” instead of the tertiary operator in class tags whenever possible.+- Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.+- Implement accessibility features on elements. For example, a tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes.+- Use consts instead of functions, for example, “const toggle = () =>”. Also, define a type if possible.diff --git a/github/.cursor-plugin/plugin.json b/github/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..f42c8f55--- /dev/null+++ b/github/.cursor-plugin/plugin.json@@ -0,0 +1,29 @@+{+ "name": "github",+ "version": "1.0.0",+ "description": "Cursor plugin for GitHub \u2014 Actions, API, CLI, Pull Requests, and repository management",+ "author": {+ "name": "Cursor",+ "email": "[email protected]"+ },+ "homepage": "https://github.com/cursor/plugins",+ "repository": "https://github.com/cursor/plugins",+ "license": "MIT",+ "keywords": [+ "github",+ "git",+ "actions",+ "ci-cd",+ "pull-requests",+ "api"+ ],+ "category": "developer-tools",+ "tags": [+ "version-control",+ "ci-cd",+ "collaboration"+ ],+ "logo": "./github.svg",+ "skills": "./skills/",+ "mcpServers": "./mcp.json"+}diff --git a/github/CHANGELOG.md b/github/CHANGELOG.mdnew file mode 100644index 00000000..5f2859de--- /dev/null+++ b/github/CHANGELOG.md@@ -0,0 +1,13 @@+# Changelog++All notable changes to this plugin will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [Unreleased]++## [1.0.0] - 2026-02-07++### Added+- Initial plugin with skills and MCP server configurationdiff --git a/github/LICENSE b/github/LICENSEnew file mode 100644index 00000000..ca2bba77--- /dev/null+++ b/github/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Cursor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/github/README.md b/github/README.mdnew file mode 100644index 00000000..7fb7bc09--- /dev/null+++ b/github/README.md@@ -0,0 +1,28 @@+# GitHub Plugin++Cursor plugin for GitHub — Actions, API, CLI, Pull Requests, and repository management.++## Installation++```bash+agent install github+```++## Components++### Skills++| Skill | Description |+|:------|:------------|+| `create-github-action` | Step-by-step guide for creating composite and JavaScript GitHub Actions |+| `setup-ci-pipeline` | CI/CD pipeline patterns for Node.js, Python, Docker, and cloud deployments |++### MCP Server++Provides access to the GitHub API via `@modelcontextprotocol/server-github`.++Requires `GITHUB_TOKEN` environment variable.++## License++MITdiff --git a/github/github.svg b/github/github.svgnew file mode 100644index 00000000..c242e500--- /dev/null+++ b/github/github.svg@@ -0,0 +1 @@+<svg width="64" height="64" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>GitHub</title><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>diff --git a/github/mcp.json b/github/mcp.jsonnew file mode 100644index 00000000..7d0892bf--- /dev/null+++ b/github/mcp.json@@ -0,0 +1,36 @@+{+ "$schema": "https://cursor.com/schemas/mcp.json",+ "mcpServers": {+ "github": {+ "command": "npx",+ "args": [+ "-y",+ "@modelcontextprotocol/server-github"+ ],+ "env": {+ "GITHUB_TOKEN": "${GITHUB_TOKEN}"+ },+ "description": "MCP server providing access to the GitHub API for repository management, issues, pull requests, code search, and more",+ "capabilities": [+ "search_repositories — Search for GitHub repositories",+ "get_repository — Get details about a specific repository",+ "list_issues — List and filter issues in a repository",+ "create_issue — Create a new issue",+ "get_issue — Get details of a specific issue",+ "update_issue — Update an existing issue",+ "list_pull_requests — List and filter pull requests",+ "get_pull_request — Get details of a specific pull request",+ "create_pull_request — Create a new pull request",+ "merge_pull_request — Merge a pull request",+ "list_commits — List commits in a repository",+ "get_file_contents — Read file contents from a repository",+ "create_or_update_file — Create or update a file in a repository",+ "search_code — Search for code across repositories",+ "list_branches — List branches in a repository",+ "create_branch — Create a new branch",+ "list_workflow_runs — List GitHub Actions workflow runs",+ "get_workflow_run — Get details of a workflow run"+ ]+ }+ }+}diff --git a/github/skills/create-github-action/SKILL.md b/github/skills/create-github-action/SKILL.mdnew file mode 100644index 00000000..fc9c82bb--- /dev/null+++ b/github/skills/create-github-action/SKILL.md@@ -0,0 +1,370 @@+---+name: create-github-action+description: Step-by-step guide for creating composite and JavaScript GitHub Actions+---++# Skill: Create a Custom GitHub Action++## When to Use++Use this skill when the user wants to:++- Create a new custom GitHub Action (composite or JavaScript/TypeScript)+- Package reusable CI/CD logic as a shareable action+- Publish an action to the GitHub Marketplace+- Convert an existing script or workflow steps into a standalone action++## Prerequisites++- A GitHub repository to host the action+- Node.js 20+ (for JavaScript/TypeScript actions)+- Basic familiarity with GitHub Actions workflow syntax++## Decision: Composite vs. JavaScript Action++| Factor | Composite Action | JavaScript Action |+|--------|-----------------|-------------------|+| Complexity | Simple — shell scripts and existing actions | Complex — custom logic, API calls, rich output |+| Language | Any (runs shell commands) | JavaScript or TypeScript |+| Dependencies | None (uses runner tools) | Node.js runtime, `node_modules` bundled |+| Performance | Faster startup (no Node.js boot) | Slightly slower startup |+| Maintenance | Lower — no build step | Higher — requires bundling with ncc |+| Best for | Orchestrating existing actions/scripts | Custom logic, GitHub API integration, rich logging |++## Option A: Create a Composite Action++### Step 1 — Scaffold the action directory++Create the action at the repository root or in a subdirectory:++```+my-action/+├── action.yml # Action metadata+├── scripts/+│ └── run.sh # Implementation script(s)+└── README.md # Usage documentation+```++### Step 2 — Define `action.yml`++```yaml+name: "My Custom Action"+description: "One-line description of what this action does"+author: "Your Name or Org"++branding:+ icon: "check-circle"+ color: "green"++inputs:+ target:+ description: "Deployment target environment"+ required: true+ version:+ description: "Version to deploy"+ required: false+ default: "latest"+ dry-run:+ description: "If true, simulate the deployment without making changes"+ required: false+ default: "false"++outputs:+ result:+ description: "The result of the action"+ value: ${{ steps.run.outputs.result }}+ duration:+ description: "Execution duration in seconds"+ value: ${{ steps.run.outputs.duration }}++runs:+ using: "composite"+ steps:+ - name: Validate inputs+ shell: bash+ run: |+ if [[ -z "${{ inputs.target }}" ]]; then+ echo "::error::Input 'target' is required"+ exit 1+ fi++ - name: Run action logic+ id: run+ shell: bash+ env:+ TARGET: ${{ inputs.target }}+ VERSION: ${{ inputs.version }}+ DRY_RUN: ${{ inputs.dry-run }}+ run: |+ start_time=$(date +%s)++ echo "Deploying version ${VERSION} to ${TARGET}..."+ if [[ "${DRY_RUN}" == "true" ]]; then+ echo "Dry run — no changes made."+ echo "result=dry-run-success" >> "$GITHUB_OUTPUT"+ else+ # Actual deployment logic here+ echo "result=success" >> "$GITHUB_OUTPUT"+ fi++ end_time=$(date +%s)+ echo "duration=$((end_time - start_time))" >> "$GITHUB_OUTPUT"+```++### Step 3 — Write the README++Document the action's purpose, all inputs/outputs, and provide a usage example:++```markdown+## Usage++\`\`\`yaml+- uses: your-org/my-action@v1+ with:+ target: production+ version: "2.1.0"+ dry-run: "true"+\`\`\`+```++### Step 4 — Test locally++Test the action in a workflow within the same repository:++```yaml+# .github/workflows/test-action.yml+name: Test My Action+on: [push]++jobs:+ test:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1+ - uses: ./my-action+ id: action+ with:+ target: staging+ dry-run: "true"+ - run: |+ echo "Result: ${{ steps.action.outputs.result }}"+ echo "Duration: ${{ steps.action.outputs.duration }}s"+```++## Option B: Create a JavaScript/TypeScript Action++### Step 1 — Scaffold the project++```bash+mkdir my-js-action && cd my-js-action+npm init -y+npm install @actions/core @actions/github @actions/exec @actions/io+npm install -D @vercel/ncc typescript @types/node+```++### Step 2 — Define `action.yml`++```yaml+name: "My JS Action"+description: "One-line description of what this action does"+author: "Your Name or Org"++branding:+ icon: "zap"+ color: "blue"++inputs:+ github-token:+ description: "GitHub token for API access"+ required: true+ default: ${{ github.token }}+ label:+ description: "Label to apply to the issue or PR"+ required: true++outputs:+ applied:+ description: "Whether the label was successfully applied"++runs:+ using: "node20"+ main: "dist/index.js"+```++### Step 3 — Write the action logic++```typescript+// src/index.ts+import * as core from "@actions/core";+import * as github from "@actions/github";++async function run(): Promise<void> {+ try {+ const token = core.getInput("github-token", { required: true });+ const label = core.getInput("label", { required: true });++ const octokit = github.getOctokit(token);+ const { owner, repo } = github.context.repo;+ const issueNumber = github.context.issue.number;++ if (!issueNumber) {+ core.setFailed("This action must run in the context of an issue or pull request.");+ return;+ }++ core.info(`Adding label "${label}" to #${issueNumber}`);++ await octokit.rest.issues.addLabels({+ owner,+ repo,+ issue_number: issueNumber,+ labels: [label],+ });++ core.setOutput("applied", "true");+ core.info(`Label "${label}" applied successfully.`);+ } catch (error) {+ if (error instanceof Error) {+ core.setFailed(error.message);+ }+ }+}++run();+```++### Step 4 — Configure TypeScript++```json+// tsconfig.json+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "commonjs",+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true+ },+ "include": ["src/**/*"]+}+```++### Step 5 — Build and bundle++Add scripts to `package.json`:++```json+{+ "scripts": {+ "build": "tsc && ncc build dist/index.js -o dist --minify",+ "test": "jest"+ }+}+```++Run the build:++```bash+npm run build+```++Commit the `dist/` directory — GitHub Actions requires the bundled output to be checked in.++### Step 6 — Test with a workflow++```yaml+# .github/workflows/test-js-action.yml+name: Test JS Action+on:+ issues:+ types: [opened]++permissions:+ issues: write++jobs:+ label:+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1+ - uses: ./+ with:+ github-token: ${{ secrets.GITHUB_TOKEN }}+ label: "triage"+```++## Publishing to the Marketplace++1. Tag a release with semantic versioning:+ ```bash+ git tag -a v1.0.0 -m "Initial release"+ git push origin v1.0.0+ ```++2. Create a GitHub Release from the tag. Check **"Publish this action to the GitHub Marketplace"**.++3. Maintain a floating major tag for consumers:+ ```bash+ git tag -fa v1 -m "Update v1 tag"+ git push origin v1 --force+ ```++4. Set up Dependabot to keep action dependencies updated:+ ```yaml+ # .github/dependabot.yml+ version: 2+ updates:+ - package-ecosystem: "github-actions"+ directory: "/"+ schedule:+ interval: "weekly"+ - package-ecosystem: "npm"+ directory: "/"+ schedule:+ interval: "weekly"+ ```++## Available Tools++- `gh` CLI — Test actions locally with `act` or trigger workflow runs with `gh workflow run`.+- `actionlint` — Lint workflow files for syntax and semantic errors.+- `@vercel/ncc` — Bundle JavaScript actions into a single file.+- `act` — Run GitHub Actions locally for rapid iteration (https://github.com/nektos/act).++## Common Patterns++### Posting a PR comment from an action++```typescript+await octokit.rest.issues.createComment({+ owner,+ repo,+ issue_number: prNumber,+ body: `### Action Report\n\n${summary}`,+});+```++### Setting a commit status++```typescript+await octokit.rest.repos.createCommitStatus({+ owner,+ repo,+ sha: github.context.sha,+ state: "success",+ context: "my-action/check",+ description: "All checks passed",+ target_url: "https://example.com/report",+});+```++### Using problem matchers for inline annotations++```typescript+// Register a problem matcher for ESLint-style output+core.info("::add-matcher::.github/eslint-matcher.json");+```diff --git a/github/skills/setup-ci-pipeline/SKILL.md b/github/skills/setup-ci-pipeline/SKILL.mdnew file mode 100644index 00000000..72ff892b--- /dev/null+++ b/github/skills/setup-ci-pipeline/SKILL.md@@ -0,0 +1,407 @@+---+name: setup-ci-pipeline+description: CI/CD pipeline patterns for Node.js, Python, Docker, and cloud deployments+---++# Skill: Set Up a CI/CD Pipeline with GitHub Actions++## When to Use++Use this skill when the user wants to:++- Set up continuous integration (CI) for a new or existing project+- Add continuous deployment (CD) to staging or production environments+- Create a complete CI/CD pipeline from scratch+- Migrate from another CI/CD platform (Jenkins, CircleCI, Travis CI, GitLab CI) to GitHub Actions++## Prerequisites++- A GitHub repository with source code+- Understanding of the project's build and test commands+- For deployment: target environment credentials stored as GitHub secrets++## Step 1 — Detect the Project Stack++Examine the repository root for configuration files to determine the stack:++| File | Stack | Build Tool |+|------|-------|------------|+| `package.json` | Node.js | npm / yarn / pnpm |+| `package-lock.json` | Node.js (npm) | npm |+| `yarn.lock` | Node.js (yarn) | yarn |+| `pnpm-lock.yaml` | Node.js (pnpm) | pnpm |+| `pyproject.toml` | Python | pip / poetry / hatch |+| `requirements.txt` | Python | pip |+| `Pipfile` | Python | pipenv |+| `go.mod` | Go | go |+| `Cargo.toml` | Rust | cargo |+| `build.gradle` / `build.gradle.kts` | Java/Kotlin | Gradle |+| `pom.xml` | Java | Maven |+| `Gemfile` | Ruby | bundler |+| `Dockerfile` | Docker | docker |+| `docker-compose.yml` | Docker Compose | docker compose |++## Step 2 — Choose a Pipeline Pattern++### Pattern A: Node.js CI++```yaml+# .github/workflows/ci.yml+name: CI++on:+ push:+ branches: [main]+ pull_request:+ branches: [main]++permissions:+ contents: read++concurrency:+ group: ci-${{ github.ref }}+ cancel-in-progress: true++jobs:+ lint:+ name: Lint+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1+ - uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 # v4.0.2+ with:+ node-version: 20+ cache: npm+ - run: npm ci+ - run: npm run lint++ test:+ name: Test (Node ${{ matrix.node-version }})+ runs-on: ubuntu-latest+ timeout-minutes: 15+ strategy:+ fail-fast: false+ matrix:+ node-version: [18, 20, 22]+ steps:+ - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1+ - uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 # v4.0.2+ with:+ node-version: ${{ matrix.node-version }}+ cache: npm+ - run: npm ci+ - run: npm test -- --coverage+ - uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1+ if: matrix.node-version == 20+ with:+ name: coverage-report+ path: coverage/+ retention-days: 7++ build:+ name: Build+ runs-on: ubuntu-latest+ timeout-minutes: 10+ needs: [lint, test]+ steps:+ - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1+ - uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 # v4.0.2+ with:+ node-version: 20+ cache: npm+ - run: npm ci+ - run: npm run build+ - uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1+ with:+ name: build-output+ path: dist/+ retention-days: 7+```++### Pattern B: Python CI++```yaml+# .github/workflows/ci.yml+name: CI++on:+ push:+ branches: [main]+ pull_request:+ branches: [main]++permissions:+ contents: read++concurrency:+ group: ci-${{ github.ref }}+ cancel-in-progress: true++jobs:+ lint:+ name: Lint & Format+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1+ - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0+ with:+ python-version: "3.12"+ cache: pip+ - run: pip install ruff mypy+ - run: ruff check .+ - run: ruff format --check .+ - run: mypy src/++ test:+ name: Test (Python ${{ matrix.python-version }})+ runs-on: ubuntu-latest+ timeout-minutes: 15+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.10", "3.11", "3.12"]+ steps:+ - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1+ - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0+ with:+ python-version: ${{ matrix.python-version }}+ cache: pip+ - run: pip install -e ".[test]"+ - run: pytest --cov=src --cov-report=xml+ - uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1+ if: matrix.python-version == '3.12'+ with:+ name: coverage-report+ path: coverage.xml+ retention-days: 7+```++### Pattern C: Docker Build and Push++```yaml+# .github/workflows/docker.yml+name: Docker Build & Push++on:+ push:+ branches: [main]+ tags: ["v*"]+ pull_request:+ branches: [main]++permissions:+ contents: read+ packages: write++concurrency:+ group: docker-${{ github.ref }}+ cancel-in-progress: true++env:+ REGISTRY: ghcr.io+ IMAGE_NAME: ${{ github.repository }}++jobs:+ build:+ name: Build & Push+ runs-on: ubuntu-latest+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1++ - uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0++ - uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0+ if: github.event_name != 'pull_request'+ with:+ registry: ${{ env.REGISTRY }}+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}++ - uses: docker/metadata-action@8e5442c4ef9f78752691e2d8f8d19755c6f78e81 # v5.5.1+ id: meta+ with:+ images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}+ tags: |+ type=ref,event=branch+ type=semver,pattern={{version}}+ type=semver,pattern={{major}}.{{minor}}+ type=sha++ - uses: docker/build-push-action@4a13e500e55cf31b7a5d59a38ab2040ab0f42f56 # v5.1.0+ with:+ context: .+ push: ${{ github.event_name != 'pull_request' }}+ tags: ${{ steps.meta.outputs.tags }}+ labels: ${{ steps.meta.outputs.labels }}+ cache-from: type=gha+ cache-to: type=gha,mode=max+```++### Pattern D: Deploy to Cloud++```yaml+# .github/workflows/deploy.yml+name: Deploy++on:+ push:+ branches: [main]+ workflow_dispatch:+ inputs:+ environment:+ description: "Target environment"+ required: true+ type: choice+ options:+ - staging+ - production+ default: staging++permissions:+ contents: read+ id-token: write # Required for OIDC++concurrency:+ group: deploy-${{ github.event.inputs.environment || 'staging' }}+ cancel-in-progress: false++jobs:+ deploy-staging:+ name: Deploy to Staging+ runs-on: ubuntu-latest+ timeout-minutes: 20+ environment:+ name: staging+ url: https://staging.example.com+ if: github.event_name == 'push' || github.event.inputs.environment == 'staging'+ steps:+ - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1++ - name: Configure AWS credentials (OIDC)+ uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2+ with:+ role-to-assume: ${{ secrets.AWS_ROLE_ARN }}+ aws-region: us-east-1++ - name: Deploy+ run: |+ echo "Deploying to staging..."+ # aws s3 sync dist/ s3://my-staging-bucket/+ # aws cloudfront create-invalidation --distribution-id $CF_DIST_ID --paths "/*"++ deploy-production:+ name: Deploy to Production+ runs-on: ubuntu-latest+ timeout-minutes: 20+ needs: deploy-staging+ environment:+ name: production+ url: https://example.com+ if: github.event.inputs.environment == 'production'+ steps:+ - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1++ - name: Configure AWS credentials (OIDC)+ uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2+ with:+ role-to-assume: ${{ secrets.AWS_PROD_ROLE_ARN }}+ aws-region: us-east-1++ - name: Deploy+ run: |+ echo "Deploying to production..."+ # Your deployment commands here+```++## Step 3 — Configure Required Secrets++Guide the user to add secrets in **Settings > Secrets and variables > Actions**:++| Secret Name | Description | Required For |+|-------------|-------------|-------------|+| `AWS_ROLE_ARN` | IAM role ARN for OIDC auth | AWS deployments |+| `DOCKER_USERNAME` | Docker Hub username | Docker Hub pushes |+| `DOCKER_PASSWORD` | Docker Hub access token | Docker Hub pushes |+| `NPM_TOKEN` | npm publish token | Package publishing |+| `DEPLOY_KEY` | SSH deploy key | Server deployments |+| `SONAR_TOKEN` | SonarQube/SonarCloud token | Code quality analysis |++## Step 4 — Set Up Branch Protection++Recommend the following branch protection rules for `main`:++1. **Require status checks to pass** — Select the CI jobs as required checks.+2. **Require branches to be up to date** — Ensures PRs are tested against the latest `main`.+3. **Require pull request reviews** — At least one approval before merge.+4. **Require linear history** — Enforces squash or rebase merges for a clean history.+5. **Do not allow bypassing** — Even admins must follow the rules.++## Step 5 — Add Dependabot for Automated Updates++```yaml+# .github/dependabot.yml+version: 2+updates:+ - package-ecosystem: "github-actions"+ directory: "/"+ schedule:+ interval: "weekly"+ groups:+ actions:+ patterns: ["*"]+ - package-ecosystem: "npm" # or pip, cargo, gomod, etc.+ directory: "/"+ schedule:+ interval: "weekly"+ groups:+ dependencies:+ patterns: ["*"]+ exclude-patterns: ["@types/*"]+ types:+ patterns: ["@types/*"]+```++## Configuration Options++### Environment Variables++| Variable | Default | Description |+|----------|---------|-------------|+| `NODE_VERSION` | `20` | Node.js version for Node.js pipelines |+| `PYTHON_VERSION` | `3.12` | Python version for Python pipelines |+| `REGISTRY` | `ghcr.io` | Container registry for Docker pipelines |+| `DEPLOY_ENVIRONMENT` | `staging` | Default deployment target |++### Workflow Dispatch Inputs++Add `workflow_dispatch` with inputs to allow manual triggering with parameters:++```yaml+on:+ workflow_dispatch:+ inputs:+ environment:+ type: choice+ options: [staging, production]+ skip-tests:+ type: boolean+ default: false+ version:+ type: string+ description: "Version to deploy (e.g., v1.2.3)"+```++## Common Extensions++After setting up the base pipeline, consider adding:++- **Code coverage** reporting with Codecov or Coveralls+- **Security scanning** with CodeQL (`github/codeql-action`) or Snyk+- **Release automation** with `release-please` or `semantic-release`+- **Deployment previews** for PRs (Vercel, Netlify, Cloudflare Pages)+- **Slack/Discord notifications** on deployment success or failure+- **Performance benchmarks** with `github/codeql-action` or custom scripts+- **Changelog generation** with `conventional-changelog` or `release-please`diff --git a/go-api-development/.cursor-plugin/plugin.json b/go-api-development/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..9451f43b--- /dev/null+++ b/go-api-development/.cursor-plugin/plugin.json@@ -0,0 +1,27 @@+{+ "name": "go-api-development",+ "version": "1.0.0",+ "description": "Go API development with standard library (1.22+) rules by Marvin Kaunda (cursor.directory)",+ "author": {+ "name": "Marvin Kaunda",+ "url": "https://cursor.directory/go-api-standard-library-1-22"+ },+ "homepage": "https://cursor.directory/go-api-standard-library-1-22",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "go",+ "golang",+ "api",+ "net/http",+ "stdlib"+ ],+ "category": "backend",+ "tags": [+ "go",+ "golang",+ "api",+ "net/http"+ ],+ "rules": "./rules/"+}diff --git a/go-api-development/README.md b/go-api-development/README.mdnew file mode 100644index 00000000..1e74d1e6--- /dev/null+++ b/go-api-development/README.md@@ -0,0 +1,29 @@+# go-api-development++Go API development with standard library (1.22+) rules by Marvin Kaunda (cursor.directory)++## Installation++```bash+agent install go-api-development+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `go_api_development` | Go API development using the standard library net/http package and ServeMux | `**/*.go, **/go.mod` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/go-api-standard-library-1-22).++- **Original Author**: Marvin Kaunda+- **Tags**: go, golang, api, net/http, stdlib+- **Category**: backend++## License++MITdiff --git a/go-api-development/rules/go_api_development.mdc b/go-api-development/rules/go_api_development.mdcnew file mode 100644index 00000000..d05ba127--- /dev/null+++ b/go-api-development/rules/go_api_development.mdc@@ -0,0 +1,36 @@+---+description: Go API development using the standard library net/http package and ServeMux+globs:+ - "**/*.go"+ - "**/go.mod"+alwaysApply: false+---++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:+ - Utilize the new ServeMux introduced in Go 1.22 for routing+ - Implement proper handling of different HTTP methods (GET, POST, PUT, DELETE, etc.)+ - Use method handlers with appropriate signatures (e.g., func(w http.ResponseWriter, r *http.Request))+ - Leverage new features like wildcard matching and regex support in routes+- 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.diff --git a/laravel-tallstack/.cursor-plugin/plugin.json b/laravel-tallstack/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..ee3e06b8--- /dev/null+++ b/laravel-tallstack/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "laravel-tallstack",+ "version": "1.0.0",+ "description": "Laravel TALL Stack (Tailwind, Alpine.js, Livewire, Laravel) with DaisyUI rules by Ismael Fi (cursor.directory)",+ "author": {+ "name": "Ismael Fi",+ "url": "https://cursor.directory/tallstack-cursor-rules"+ },+ "homepage": "https://cursor.directory/tallstack-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "laravel",+ "php",+ "livewire",+ "alpine",+ "tailwind",+ "daisyui"+ ],+ "category": "backend",+ "tags": [+ "laravel",+ "tailwindcss",+ "livewire",+ "alpinejs"+ ],+ "rules": "./rules/"+}diff --git a/laravel-tallstack/README.md b/laravel-tallstack/README.mdnew file mode 100644index 00000000..e55ad05d--- /dev/null+++ b/laravel-tallstack/README.md@@ -0,0 +1,29 @@+# laravel-tallstack++Laravel TALL Stack (Tailwind, Alpine.js, Livewire, Laravel) with DaisyUI rules by Ismael Fi (cursor.directory)++## Installation++```bash+agent install laravel-tallstack+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `laravel_tallstack` | Laravel TALL Stack development with Livewire, Alpine.js, TailwindCSS, and DaisyUI | `**/*.php, **/*.blade.php, **/*.js` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/tallstack-cursor-rules).++- **Original Author**: Ismael Fi+- **Tags**: laravel, tailwindcss, livewire, alpinejs+- **Category**: backend++## License++MITdiff --git a/laravel-tallstack/rules/laravel_tallstack.mdc b/laravel-tallstack/rules/laravel_tallstack.mdcnew file mode 100644index 00000000..334dacc5--- /dev/null+++ b/laravel-tallstack/rules/laravel_tallstack.mdc@@ -0,0 +1,98 @@+---+description: Laravel TALL Stack development with Livewire, Alpine.js, TailwindCSS, and DaisyUI+globs:+ - "**/*.php"+ - "**/*.blade.php"+ - "**/*.js"+alwaysApply: false+---++You are an expert in Laravel, PHP, Livewire, Alpine.js, TailwindCSS, and DaisyUI.++Key Principles++- Write concise, technical responses with accurate PHP and Livewire examples.+- Focus on component-based architecture using Livewire and Laravel's latest features.+- Follow Laravel and Livewire best practices and conventions.+- Use object-oriented programming with a focus on SOLID principles.+- Prefer iteration and modularization over duplication.+- Use descriptive variable, method, and component names.+- Use lowercase with dashes for directories (e.g., app/Http/Livewire).+- Favor dependency injection and service containers.++PHP/Laravel++- Use PHP 8.1+ features when appropriate (e.g., typed properties, match expressions).+- Follow PSR-12 coding standards.+- Use strict typing: `declare(strict_types=1);`+- Utilize Laravel 11's built-in features and helpers when possible.+- Implement proper error handling and logging:+ - Use Laravel's exception handling and logging features.+ - Create custom exceptions when necessary.+ - Use try-catch blocks for expected exceptions.+- Use Laravel's validation features for form and request validation.+- Implement middleware for request filtering and modification.+- Utilize Laravel's Eloquent ORM for database interactions.+- Use Laravel's query builder for complex database queries.+- Implement proper database migrations and seeders.++Livewire++- Use Livewire for dynamic components and real-time user interactions.+- Favor the use of Livewire's lifecycle hooks and properties.+- Use the latest Livewire (3.5+) features for optimization and reactivity.+- Implement Blade components with Livewire directives (e.g., wire:model).+- Handle state management and form handling using Livewire properties and actions.+- Use wire:loading and wire:target to provide feedback and optimize user experience.+- Apply Livewire's security measures for components.++Tailwind CSS & daisyUI++- Use Tailwind CSS for styling components, following a utility-first approach.+- Leverage daisyUI's pre-built components for quick UI development.+- Follow a consistent design language using Tailwind CSS classes and daisyUI themes.+- Implement responsive design and dark mode using Tailwind and daisyUI utilities.+- Optimize for accessibility (e.g., aria-attributes) when using components.++Dependencies++- Laravel 11 (latest stable version)+- Livewire 3.5+ for real-time, reactive components+- Alpine.js for lightweight JavaScript interactions+- Tailwind CSS for utility-first styling+- daisyUI for pre-built UI components and themes+- Composer for dependency management+- NPM/Yarn for frontend dependencies++ Laravel Best Practices++- Use Eloquent ORM instead of raw SQL queries when possible.+- Implement Repository pattern for data access layer.+- Use Laravel's built-in authentication and authorization features.+- Utilize Laravel's caching mechanisms for improved performance.+- Implement job queues for long-running tasks.+- Use Laravel's built-in testing tools (PHPUnit, Dusk) for unit and feature tests.+- Implement API versioning for public APIs.+- Use Laravel's localization features for multi-language support.+- Implement proper CSRF protection and security measures.+- Use Laravel Mix or Vite for asset compilation.+- Implement proper database indexing for improved query performance.+- Use Laravel's built-in pagination features.+- Implement proper error logging and monitoring.+- Implement proper database transactions for data integrity.+- Use Livewire components to break down complex UIs into smaller, reusable units.+- Use Laravel's event and listener system for decoupled code.+- Implement Laravel's built-in scheduling features for recurring tasks.++Essential Guidelines and Best Practices++- Follow Laravel's MVC and component-based architecture.+- Use Laravel's routing system for defining application endpoints.+- Implement proper request validation using Form Requests.+- Use Livewire and Blade components for interactive UIs.+- Implement proper database relationships using Eloquent.+- Use Laravel's built-in authentication scaffolding.+- Implement proper API resource transformations.+- Use Laravel's event and listener system for decoupled code.+- Use Tailwind CSS and daisyUI for consistent and efficient styling.+- Implement complex UI patterns using Livewire and Alpine.js.diff --git a/launchdarkly/.cursor-plugin/plugin.json b/launchdarkly/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..39382f1f--- /dev/null+++ b/launchdarkly/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "launchdarkly",+ "version": "1.0.0",+ "description": "Cursor plugin for LaunchDarkly \u2014 feature flags, experimentation, progressive rollouts, and targeting",+ "author": {+ "name": "Cursor",+ "email": "[email protected]"+ },+ "homepage": "https://github.com/cursor/plugins",+ "repository": "https://github.com/cursor/plugins",+ "license": "MIT",+ "keywords": [+ "launchdarkly",+ "feature-flags",+ "experimentation",+ "rollouts",+ "targeting"+ ],+ "category": "developer-tools",+ "tags": [+ "feature-flags",+ "experimentation",+ "release-management"+ ],+ "logo": "./launchdarkly.svg",+ "skills": "./skills/",+ "mcpServers": "./mcp.json"+}diff --git a/launchdarkly/CHANGELOG.md b/launchdarkly/CHANGELOG.mdnew file mode 100644index 00000000..5f2859de--- /dev/null+++ b/launchdarkly/CHANGELOG.md@@ -0,0 +1,13 @@+# Changelog++All notable changes to this plugin will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [Unreleased]++## [1.0.0] - 2026-02-07++### Added+- Initial plugin with skills and MCP server configurationdiff --git a/launchdarkly/LICENSE b/launchdarkly/LICENSEnew file mode 100644index 00000000..ca2bba77--- /dev/null+++ b/launchdarkly/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Cursor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/launchdarkly/README.md b/launchdarkly/README.mdnew file mode 100644index 00000000..215ca337--- /dev/null+++ b/launchdarkly/README.md@@ -0,0 +1,28 @@+# LaunchDarkly Plugin++Cursor plugin for LaunchDarkly — feature flags, experimentation, progressive rollouts, and targeting.++## Installation++```bash+agent install launchdarkly+```++## Components++### Skills++| Skill | Description |+|:------|:------------|+| `setup-launchdarkly` | SDK integration, client initialization, context setup, React provider, and testing |+| `create-feature-flag` | Flag lifecycle from creation through rollout, experimentation, and cleanup |++### MCP Server++Provides LaunchDarkly flag management via `@launchdarkly/mcp-server`.++Requires `LAUNCHDARKLY_ACCESS_TOKEN` environment variable.++## License++MITdiff --git a/launchdarkly/launchdarkly.svg b/launchdarkly/launchdarkly.svgnew file mode 100644index 00000000..89abf296--- /dev/null+++ b/launchdarkly/launchdarkly.svg@@ -0,0 +1 @@+<svg width="64" height="64" preserveAspectRatio="xMidYMid" viewBox="-.00348466 0 256.88728835 255.31014671" xmlns="http://www.w3.org/2000/svg"><path d="m129.865 255.306a5.637 5.637 0 0 1 -5.073-3.157 5.355 5.355 0 0 1 .507-5.637l59.98-82.584-105.02 42.899a5.778 5.778 0 0 1 -2.255.479 5.637 5.637 0 0 1 -5.384-4.059 5.412 5.412 0 0 1 2.311-6.172l92.365-54.54-162.632-9.357a5.637 5.637 0 0 1 0-11.106l162.717-9.33-92.393-54.538a5.412 5.412 0 0 1 -2.311-6.173 5.637 5.637 0 0 1 5.355-4.059c.78-.003 1.55.17 2.255.507l105.048 42.955-59.98-82.555a5.355 5.355 0 0 1 -.507-5.638 5.637 5.637 0 0 1 5.046-3.241c1.48.01 2.894.62 3.917 1.691l119.536 119.509a9.076 9.076 0 0 1 0 12.824l-119.592 119.648a5.442 5.442 0 0 1 -3.89 1.634z"/></svg>diff --git a/launchdarkly/mcp.json b/launchdarkly/mcp.jsonnew file mode 100644index 00000000..f7e177cc--- /dev/null+++ b/launchdarkly/mcp.json@@ -0,0 +1,65 @@+{+ "$schema": "https://cursor.com/schemas/mcp.json",+ "mcpServers": {+ "launchdarkly": {+ "command": "npx",+ "args": ["-y", "@launchdarkly/mcp-server"],+ "description": "LaunchDarkly MCP server — manage feature flags, segments, environments, and experiments directly from Cursor",+ "env": {+ "LAUNCHDARKLY_ACCESS_TOKEN": "${LAUNCHDARKLY_ACCESS_TOKEN}",+ "LAUNCHDARKLY_PROJECT_KEY": "${LAUNCHDARKLY_PROJECT_KEY:-default}",+ "LAUNCHDARKLY_ENVIRONMENT_KEY": "${LAUNCHDARKLY_ENVIRONMENT_KEY:-production}"+ },+ "tools": [+ {+ "name": "list_flags",+ "description": "List all feature flags in the project with their status, variations, and targeting state"+ },+ {+ "name": "get_flag",+ "description": "Get detailed information about a specific feature flag including targeting rules, prerequisites, and variations"+ },+ {+ "name": "create_flag",+ "description": "Create a new feature flag with specified key, name, description, type, and variations"+ },+ {+ "name": "toggle_flag",+ "description": "Turn a feature flag on or off in a specific environment"+ },+ {+ "name": "update_flag_targeting",+ "description": "Update targeting rules, percentage rollouts, and individual targeting for a flag"+ },+ {+ "name": "evaluate_flag",+ "description": "Evaluate a feature flag for a given context and return the variation and reason"+ },+ {+ "name": "list_segments",+ "description": "List user segments in the project"+ },+ {+ "name": "get_flag_status",+ "description": "Get the status of a flag: active, launched, inactive, or new"+ },+ {+ "name": "list_environments",+ "description": "List all environments in the project (development, staging, production, etc.)"+ },+ {+ "name": "get_audit_log",+ "description": "Get recent audit log entries for flag changes, targeting updates, and other modifications"+ },+ {+ "name": "search_flags",+ "description": "Search for flags by name, key, tag, or description"+ },+ {+ "name": "archive_flag",+ "description": "Archive a feature flag that is no longer needed"+ }+ ]+ }+ }+}diff --git a/launchdarkly/skills/create-feature-flag/SKILL.md b/launchdarkly/skills/create-feature-flag/SKILL.mdnew file mode 100644index 00000000..170f2174--- /dev/null+++ b/launchdarkly/skills/create-feature-flag/SKILL.md@@ -0,0 +1,404 @@+---+name: create-feature-flag+description: Flag lifecycle from creation through rollout, experimentation, and cleanup with LaunchDarkly+---++# Skill: Create and Manage Feature Flags++## Description++This skill covers the end-to-end process of creating, implementing, rolling out, and cleaning up feature flags with LaunchDarkly — from planning the flag in the dashboard to removing it from the codebase after full rollout.++## Prerequisites++- LaunchDarkly account with at least Writer access+- LaunchDarkly SDK integrated in your project (see `setup-launchdarkly` skill)+- Access to the LaunchDarkly dashboard or API+- LaunchDarkly CLI (optional): `npm install -g @launchdarkly/ldcli`++## Steps++### 1. Plan the Feature Flag++Before creating a flag, answer these questions:++| Question | Example Answer |+|----------|---------------|+| What feature are you gating? | New checkout flow |+| Is this flag **temporary** or **permanent**? | Temporary (remove after rollout) |+| What type of flag? | Boolean (on/off) |+| What is the default (off) behavior? | Show the existing checkout |+| Who should see it first? | Internal users, then beta testers |+| What metrics indicate success? | Checkout conversion rate ≥ current baseline |+| When should the flag be removed? | 2 weeks after reaching 100% rollout |+| Who owns this flag? | @checkout-team |++### 2. Create the Flag in the Dashboard++1. Navigate to **Feature Flags** → **Create Flag**.+2. Fill in the details:++| Field | Value |+|-------|-------|+| **Name** | Checkout V2 |+| **Key** | `checkout-v2` |+| **Description** | Gates the new checkout flow with improved UX and express pay |+| **Tags** | `checkout`, `q1-2026`, `temporary` |+| **Flag type** | Boolean |+| **Variations** | `true` (new checkout), `false` (legacy checkout) |+| **Default (off)** | `false` |+| **Client-side availability** | Check if the flag is needed in the frontend |+| **Temporary** | Yes |++3. Click **Save Flag**.++### 3. Create the Flag via CLI or API (Alternative)++Using the LaunchDarkly CLI:++```bash+ldcli flags create \+ --project default \+ --key checkout-v2 \+ --name "Checkout V2" \+ --description "Gates the new checkout flow with improved UX and express pay" \+ --kind boolean \+ --tags checkout,q1-2026,temporary \+ --temporary+```++Using the LaunchDarkly REST API:++```bash+curl -X POST 'https://app.launchdarkly.com/api/v2/flags/default' \+ -H "Authorization: YOUR_API_ACCESS_TOKEN" \+ -H "Content-Type: application/json" \+ -d '{+ "key": "checkout-v2",+ "name": "Checkout V2",+ "description": "Gates the new checkout flow with improved UX and express pay",+ "tags": ["checkout", "q1-2026", "temporary"],+ "variations": [+ { "value": true, "name": "New Checkout", "description": "Show the new checkout flow" },+ { "value": false, "name": "Legacy Checkout", "description": "Show the existing checkout" }+ ],+ "defaults": {+ "onVariation": 0,+ "offVariation": 1+ },+ "temporary": true,+ "clientSideAvailability": {+ "usingMobileKey": false,+ "usingEnvironmentId": true+ }+ }'+```++### 4. Implement the Flag in Code++#### Server-Side (Node.js)++```typescript+import { getLDClient } from "../lib/launchdarkly";+import { buildUserContext } from "../lib/ld-context";++export async function handleCheckout(req: Request, res: Response) {+ const client = await getLDClient();+ const context = buildUserContext(req.user);++ const useNewCheckout = await client.boolVariation("checkout-v2", context, false);++ if (useNewCheckout) {+ return newCheckoutHandler(req, res);+ }+ return legacyCheckoutHandler(req, res);+}+```++#### Client-Side (React)++```tsx+import { useFlags } from "launchdarkly-react-client-sdk";++function CheckoutPage() {+ const { checkoutV2 } = useFlags();++ if (checkoutV2) {+ return <NewCheckout />;+ }+ return <LegacyCheckout />;+}+```++#### With Event Tracking++```typescript+// Track conversion event for experimentation+function onCheckoutComplete(orderId: string, revenue: number) {+ const client = await getLDClient();+ const context = buildUserContext(currentUser);++ client.track("checkout-completed", context, { orderId }, revenue);+}+```++### 5. Set Up Targeting Rules++Configure targeting in the LaunchDarkly dashboard:++#### Rule 1: Internal Users (100%)++```+If user.email ends with "@yourcompany.com"+ Serve: true+```++#### Rule 2: Beta Testers (100%)++```+If user is in segment "beta-testers"+ Serve: true+```++#### Rule 3: Enterprise Customers (100%)++```+If organization.plan = "enterprise"+ Serve: true+```++#### Rule 4: Default Rule — Progressive Rollout++```+Default rule: Percentage rollout+ true: 0% → gradually increase+ false: 100%+ Bucket by: user.key+```++### 6. Execute the Progressive Rollout++Follow this phased plan:++```+Day 1: Internal users only (targeting rule) → Monitor for 4 hours+Day 1: Add beta testers (targeting rule) → Monitor for 24 hours+Day 2: Default rule → 5% → Monitor for 24 hours+Day 3: Default rule → 10% → Monitor for 24 hours+Day 5: Default rule → 25% → Monitor for 48 hours+Day 7: Default rule → 50% → Monitor for 48 hours+Day 9: Default rule → 100% → Monitor for 1 week+Day 16: Remove flag from code, archive in dashboard+```++### Monitoring at Each Phase++Check these metrics at each rollout phase:++- **Error rate**: Should not increase beyond baseline + 0.1%+- **Latency** (p50, p95, p99): Should not regress more than 10%+- **Conversion rate**: Should be ≥ baseline+- **Support tickets**: No spike in checkout-related issues+- **Client-side errors**: No new JavaScript exceptions++### Rollback Procedure++If any metric exceeds thresholds:++1. In the LaunchDarkly dashboard, toggle the flag **off** → all users see legacy checkout instantly.+2. Investigate the issue using LaunchDarkly's flag evaluation debugger and your application logs.+3. Fix the issue, deploy, and resume the rollout from the previous safe percentage.++### 7. Create a Multivariate Flag (for Experiments)++For A/B tests or experiments with multiple variations:++```bash+ldcli flags create \+ --project default \+ --key checkout-button-experiment \+ --name "Checkout Button Experiment" \+ --kind multivariate \+ --variations '[+ {"key": "control", "name": "Control", "value": "control"},+ {"key": "green-cta", "name": "Green CTA", "value": "green-cta"},+ {"key": "animated", "name": "Animated", "value": "animated"}+ ]'+```++Implementation:++```typescript+const variant = await client.stringVariation(+ "checkout-button-experiment",+ context,+ "control"+);++switch (variant) {+ case "green-cta":+ return <GreenCheckoutButton onClick={handleCheckout} />;+ case "animated":+ return <AnimatedCheckoutButton onClick={handleCheckout} />;+ default:+ return <DefaultCheckoutButton onClick={handleCheckout} />;+}+```++### 8. Create a JSON Configuration Flag++For complex runtime configuration:++```json+{+ "key": "dashboard-config",+ "name": "Dashboard Configuration",+ "kind": "json",+ "variations": [+ {+ "value": {+ "maxWidgets": 5,+ "refreshInterval": 60,+ "theme": "light",+ "enableExport": false+ },+ "name": "Default Config"+ },+ {+ "value": {+ "maxWidgets": 20,+ "refreshInterval": 15,+ "theme": "dark",+ "enableExport": true+ },+ "name": "Power User Config"+ }+ ]+}+```++```typescript+interface DashboardConfig {+ maxWidgets: number;+ refreshInterval: number;+ theme: "light" | "dark";+ enableExport: boolean;+}++const config = await client.jsonVariation<DashboardConfig>(+ "dashboard-config",+ context,+ { maxWidgets: 5, refreshInterval: 60, theme: "light", enableExport: false }+);+```++### 9. Write Tests for Flagged Code++```typescript+import { createTestClient } from "../test/ld-test-helper";++describe("CheckoutHandler", () => {+ it("routes to new checkout when flag is on", async () => {+ const { client } = await createTestClient({ "checkout-v2": true });+ const context = { kind: "user" as const, key: "user-123" };++ const useNew = await client.boolVariation("checkout-v2", context, false);+ expect(useNew).toBe(true);++ await client.close();+ });++ it("routes to legacy checkout when flag is off", async () => {+ const { client } = await createTestClient({ "checkout-v2": false });+ const context = { kind: "user" as const, key: "user-123" };++ const useNew = await client.boolVariation("checkout-v2", context, false);+ expect(useNew).toBe(false);++ await client.close();+ });++ it("defaults to legacy checkout when client is unavailable", async () => {+ // When the client cannot connect, variation calls return the default value+ const { client } = await createTestClient({});+ const context = { kind: "user" as const, key: "user-123" };++ const useNew = await client.boolVariation("checkout-v2", context, false);+ expect(useNew).toBe(false);++ await client.close();+ });+});+```++### 10. Clean Up After Full Rollout++Once the flag has been at 100% for the agreed-upon period:++#### Step 1: Archive the Flag in LaunchDarkly++```bash+# Archive via CLI+ldcli flags archive --project default --key checkout-v2++# Or via API+curl -X PATCH 'https://app.launchdarkly.com/api/v2/flags/default/checkout-v2' \+ -H "Authorization: YOUR_API_ACCESS_TOKEN" \+ -H "Content-Type: application/json" \+ -d '[{ "op": "replace", "path": "/archived", "value": true }]'+```++#### Step 2: Remove the Flag from Code++Before:++```typescript+const useNewCheckout = await client.boolVariation("checkout-v2", context, false);+if (useNewCheckout) {+ return newCheckoutHandler(req, res);+}+return legacyCheckoutHandler(req, res);+```++After:++```typescript+return newCheckoutHandler(req, res);+```++#### Step 3: Remove Dead Code++- Delete `legacyCheckoutHandler` and any associated legacy components.+- Remove imports and test cases that reference the old code path.+- Remove the flag key from any configuration files or constants.++#### Step 4: Verify++```bash+# Search for any remaining references to the flag key+grep -r "checkout-v2" --include="*.ts" --include="*.tsx" --include="*.js"++# Run tests to ensure nothing breaks+npm test+```++## Creating Flags — Quick Reference++| Flag Type | Use Case | Example Key | Cleanup |+|-----------|----------|-------------|---------|+| Boolean (temporary) | Feature rollout | `checkout-v2` | Remove after GA |+| Boolean (permanent) | Kill switch | `payments-kill-switch` | Keep forever |+| String (multivariate) | A/B experiment | `checkout-button-experiment` | Remove after experiment concludes |+| Number | Runtime config | `api-rate-limit` | Keep as operational control |+| JSON | Complex config | `dashboard-config` | Keep as operational control |++## Troubleshooting++| Issue | Solution |+|-------|---------|+| Flag not evaluating as expected | Check targeting rules order — rules are evaluated top-down, first match wins |+| Percentage rollout not sticky | Ensure `bucketBy` is set to a stable attribute (e.g., `key`) |+| Flag changes not taking effect | Check if streaming is enabled; verify the correct environment |+| Cannot find flag in code references | Ensure the LaunchDarkly GitHub integration is configured |+| Experiment results inconclusive | Increase sample size or run longer; check that `track()` calls are firing |+| Flag default value type mismatch | Ensure the default value type matches the flag type |diff --git a/launchdarkly/skills/setup-launchdarkly/SKILL.md b/launchdarkly/skills/setup-launchdarkly/SKILL.mdnew file mode 100644index 00000000..6007d37e--- /dev/null+++ b/launchdarkly/skills/setup-launchdarkly/SKILL.md@@ -0,0 +1,471 @@+---+name: setup-launchdarkly+description: SDK integration, client initialization, context setup, React provider, and testing for LaunchDarkly+---++# Skill: Set Up LaunchDarkly++## Description++This skill walks through integrating LaunchDarkly into a TypeScript/JavaScript project from scratch, including SDK installation, client initialization, context construction, React provider setup, testing configuration, and production readiness.++## Prerequisites++- Node.js >= 18 installed+- A LaunchDarkly account with access to a project and environment+- Your LaunchDarkly SDK key (server-side) and/or client-side ID+- For React apps: React 18+ with a bundler (Vite, Next.js, webpack)++## Steps++### 1. Install the LaunchDarkly SDK++Choose the SDK(s) based on your application type:++```bash+# Server-side (Node.js, Express, Fastify, NestJS, etc.)+npm install @launchdarkly/node-server-sdk++# Client-side (React)+npm install launchdarkly-react-client-sdk++# Client-side (vanilla JS / non-React)+npm install launchdarkly-js-client-sdk++# Both (e.g., Next.js with SSR)+npm install @launchdarkly/node-server-sdk launchdarkly-react-client-sdk+```++### 2. Configure Environment Variables++Store your SDK keys securely — never commit them to source control:++```bash+# .env (add to .gitignore)+LAUNCHDARKLY_SDK_KEY=sdk-your-server-side-key+LAUNCHDARKLY_CLIENT_SIDE_ID=your-client-side-id+```++Add the `.env` file to `.gitignore`:++```bash+echo ".env" >> .gitignore+```++### 3. Initialize the Server-Side Client (Singleton)++Create a module that initializes the LaunchDarkly client once and exports it:++`src/lib/launchdarkly.ts`:++```typescript+import * as LaunchDarkly from "@launchdarkly/node-server-sdk";++let ldClient: LaunchDarkly.LDClient | null = null;+let initializationPromise: Promise<LaunchDarkly.LDClient> | null = null;++/**+ * Returns the singleton LaunchDarkly client.+ * Initializes on first call and reuses for subsequent calls.+ */+export function getLDClient(): Promise<LaunchDarkly.LDClient> {+ if (initializationPromise) {+ return initializationPromise;+ }++ initializationPromise = (async () => {+ const sdkKey = process.env.LAUNCHDARKLY_SDK_KEY;+ if (!sdkKey) {+ throw new Error(+ "LAUNCHDARKLY_SDK_KEY environment variable is not set. " ++ "Get your SDK key from the LaunchDarkly dashboard: " ++ "Account Settings → Projects → Your Project → Environments."+ );+ }++ ldClient = LaunchDarkly.init(sdkKey, {+ // Optional: customize the logger+ logger: LaunchDarkly.basicLogger({+ level: process.env.NODE_ENV === "production" ? "warn" : "info",+ }),+ });++ try {+ await ldClient.waitForInitialization({ timeout: 10 });+ console.log("[LaunchDarkly] Client initialized successfully");+ } catch (error) {+ console.error("[LaunchDarkly] Client initialization failed:", error);+ // In production, you may want to fail fast or continue with defaults+ // ldClient is still usable — variation calls return defaults+ }++ return ldClient;+ })();++ return initializationPromise;+}++/**+ * Flush events and close the client. Call on application shutdown.+ */+export async function closeLDClient(): Promise<void> {+ if (ldClient) {+ await ldClient.flush();+ await ldClient.close();+ ldClient = null;+ initializationPromise = null;+ console.log("[LaunchDarkly] Client closed");+ }+}+```++### 4. Build a Context Factory++Create a helper that constructs well-formed LaunchDarkly contexts from your application's user/session data:++`src/lib/ld-context.ts`:++```typescript+import type { LDContext } from "@launchdarkly/node-server-sdk";++interface User {+ id: string;+ email: string;+ name: string;+ plan: "free" | "pro" | "enterprise";+ role: "admin" | "member" | "viewer";+ createdAt: string;+}++interface Organization {+ id: string;+ name: string;+ plan: string;+ industry?: string;+ employeeCount?: number;+}++/**+ * Build a LaunchDarkly context from authenticated user data.+ */+export function buildUserContext(user: User): LDContext {+ return {+ kind: "user",+ key: user.id,+ name: user.name,+ email: user.email,+ custom: {+ plan: user.plan,+ role: user.role,+ createdAt: user.createdAt,+ },+ };+}++/**+ * Build a multi-context for user + organization targeting.+ */+export function buildMultiContext(user: User, org: Organization): LDContext {+ return {+ kind: "multi",+ user: {+ key: user.id,+ name: user.name,+ email: user.email,+ custom: {+ plan: user.plan,+ role: user.role,+ },+ },+ organization: {+ key: org.id,+ name: org.name,+ custom: {+ plan: org.plan,+ industry: org.industry,+ employeeCount: org.employeeCount,+ },+ },+ };+}++/**+ * Build an anonymous context for unauthenticated users.+ */+export function buildAnonymousContext(sessionId: string): LDContext {+ return {+ kind: "user",+ key: sessionId,+ anonymous: true,+ };+}+```++### 5. Use Flags in an Express/Fastify Endpoint++`src/routes/features.ts`:++```typescript+import { Router } from "express";+import { getLDClient } from "../lib/launchdarkly";+import { buildUserContext } from "../lib/ld-context";++const router = Router();++router.get("/api/features", async (req, res) => {+ const client = await getLDClient();+ const context = buildUserContext(req.user);++ const [showNewDashboard, maxUploadSizeMb, checkoutMode] = await Promise.all([+ client.boolVariation("dashboard-v2", context, false),+ client.numberVariation("max-upload-size-mb", context, 10),+ client.stringVariation("checkout-mode", context, "standard"),+ ]);++ res.json({+ showNewDashboard,+ maxUploadSizeMb,+ checkoutMode,+ });+});++export default router;+```++### 6. Set Up the React Client-Side Provider++`src/app/providers/LaunchDarklyProvider.tsx`:++```tsx+import { LDProvider } from "launchdarkly-react-client-sdk";+import type { LDContext } from "launchdarkly-js-client-sdk";+import type { ReactNode } from "react";++interface Props {+ user: { id: string; email: string; name: string; plan: string };+ children: ReactNode;+}++export function LaunchDarklyProvider({ user, children }: Props) {+ const context: LDContext = {+ kind: "user",+ key: user.id,+ name: user.name,+ email: user.email,+ custom: {+ plan: user.plan,+ },+ };++ return (+ <LDProvider+ clientSideID={process.env.REACT_APP_LD_CLIENT_SIDE_ID!}+ context={context}+ options={{+ streaming: true, // Real-time flag updates+ }}+ >+ {children}+ </LDProvider>+ );+}+```++Use flags in components with hooks:++```tsx+import { useFlags, useLDClient } from "launchdarkly-react-client-sdk";++function PricingBanner() {+ const { showPromoBanner, promoBannerText } = useFlags();+ const ldClient = useLDClient();++ if (!showPromoBanner) return null;++ const handleDismiss = () => {+ ldClient?.track("promo-banner-dismissed");+ };++ return (+ <div className="banner">+ <p>{promoBannerText ?? "Check out our new plans!"}</p>+ <button onClick={handleDismiss}>Dismiss</button>+ </div>+ );+}+```++### 7. Register Shutdown Handlers++Ensure the LaunchDarkly client is closed on application shutdown to flush pending events:++`src/server.ts`:++```typescript+import { closeLDClient } from "./lib/launchdarkly";++async function gracefulShutdown(signal: string): Promise<void> {+ console.log(`Received ${signal}. Shutting down gracefully...`);+ await closeLDClient();+ process.exit(0);+}++process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));+process.on("SIGINT", () => gracefulShutdown("SIGINT"));+```++### 8. Set Up Testing with TestData++Create a test helper that provides a deterministic LaunchDarkly client:++`src/test/ld-test-helper.ts`:++```typescript+import * as LaunchDarkly from "@launchdarkly/node-server-sdk";+import { TestData } from "@launchdarkly/node-server-sdk/integrations";++export interface TestFlags {+ [flagKey: string]: boolean | string | number | Record<string, unknown>;+}++/**+ * Create a LaunchDarkly test client with predetermined flag values.+ */+export async function createTestClient(+ flags: TestFlags+): Promise<{ client: LaunchDarkly.LDClient; td: ReturnType<typeof TestData> }> {+ const td = TestData();++ for (const [key, value] of Object.entries(flags)) {+ if (typeof value === "boolean") {+ td.update(td.flag(key).booleanFlag().variationForAll(value));+ } else if (typeof value === "string") {+ td.update(+ td.flag(key).valueForAll(value)+ );+ } else if (typeof value === "number") {+ td.update(+ td.flag(key).valueForAll(value)+ );+ } else {+ td.update(+ td.flag(key).valueForAll(value)+ );+ }+ }++ const client = LaunchDarkly.init("test-sdk-key", {+ updateProcessor: td,+ });++ await client.waitForInitialization();+ return { client, td };+}+```++Usage in tests:++```typescript+import { createTestClient } from "../test/ld-test-helper";++describe("feature: checkout-v2", () => {+ it("renders new checkout when flag is on", async () => {+ const { client } = await createTestClient({+ "checkout-v2": true,+ "max-upload-size-mb": 50,+ });++ const context = { kind: "user" as const, key: "test-user" };+ const result = await client.boolVariation("checkout-v2", context, false);+ expect(result).toBe(true);++ await client.close();+ });+});+```++### 9. Set Up Next.js Integration (SSR + Client)++For Next.js applications that need flags on both server and client:++`src/lib/ld-server.ts` (server-side):++```typescript+import { getLDClient } from "./launchdarkly";+import { buildUserContext } from "./ld-context";++export async function getServerFlags(user: User) {+ const client = await getLDClient();+ const context = buildUserContext(user);++ return {+ showNewDashboard: await client.boolVariation("dashboard-v2", context, false),+ maxUploadSizeMb: await client.numberVariation("max-upload-size-mb", context, 10),+ };+}+```++`pages/_app.tsx` (client-side bootstrap):++```tsx+import { LDProvider } from "launchdarkly-react-client-sdk";++export default function App({ Component, pageProps }: AppProps) {+ return (+ <LDProvider+ clientSideID={process.env.NEXT_PUBLIC_LD_CLIENT_SIDE_ID!}+ context={pageProps.ldContext}+ options={{+ bootstrap: pageProps.ldFlags, // Prevents flicker on hydration+ }}+ >+ <Component {...pageProps} />+ </LDProvider>+ );+}+```++### 10. Verify the Integration++Run through this checklist to confirm everything is working:++```bash+# 1. Verify the server-side client connects+node -e "+ const LD = require('@launchdarkly/node-server-sdk');+ const c = LD.init(process.env.LAUNCHDARKLY_SDK_KEY);+ c.waitForInitialization({ timeout: 5 })+ .then(() => { console.log('✓ Connected'); c.close(); })+ .catch(e => { console.error('✗ Failed:', e.message); process.exit(1); });+"++# 2. Create a test flag in the dashboard called "test-flag" (boolean, default false)+# 3. Evaluate it from your app and verify the value+# 4. Toggle it in the dashboard and verify the value changes+# 5. Check the LaunchDarkly dashboard for evaluation events+```++## Best Practices Checklist++- [ ] SDK key stored in environment variables (never committed)+- [ ] Client initialized once using the singleton pattern+- [ ] Contexts include stable keys and relevant targeting attributes+- [ ] Shutdown handler registered to flush events and close the client+- [ ] Test helper configured with `TestData` for deterministic unit tests+- [ ] React provider wraps the app root with the client-side ID+- [ ] Flag values are logged during development for debugging+- [ ] `.env` added to `.gitignore`+- [ ] Server-side SDK key and client-side ID use the correct environment (dev/staging/prod)+- [ ] Anonymous contexts used for unauthenticated users++## Troubleshooting++| Issue | Solution |+|-------|---------|+| `LAUNCHDARKLY_SDK_KEY is not set` | Set the environment variable in `.env` or your deployment config |+| Client never initializes | Check network connectivity and SDK key validity; ensure the key matches the environment |+| Flags always return defaults | Client may be in offline mode or not initialized; check logs for errors |+| React hydration mismatch | Bootstrap the client SDK with server-evaluated flag values |+| Stale flag values in browser | Ensure streaming is enabled in the client SDK options |+| Events not appearing in dashboard | Call `client.flush()` or wait for the default flush interval (5 seconds) |+| `TypeError: client.boolVariation is not a function` | You may be using an older SDK version; upgrade or use `client.variation()` |diff --git a/mongodb/.cursor-plugin/plugin.json b/mongodb/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..a4fe5f7c--- /dev/null+++ b/mongodb/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "mongodb",+ "version": "1.0.0",+ "description": "Cursor plugin for MongoDB \u2014 schema design, queries, aggregation, indexes, and Mongoose ODM",+ "author": {+ "name": "Cursor",+ "email": "[email protected]"+ },+ "homepage": "https://github.com/cursor/plugins",+ "repository": "https://github.com/cursor/plugins",+ "license": "MIT",+ "keywords": [+ "mongodb",+ "mongoose",+ "nosql",+ "database",+ "aggregation"+ ],+ "category": "backend",+ "tags": [+ "database",+ "nosql",+ "odm"+ ],+ "logo": "./mongodb.svg",+ "skills": "./skills/",+ "mcpServers": "./mcp.json"+}diff --git a/mongodb/CHANGELOG.md b/mongodb/CHANGELOG.mdnew file mode 100644index 00000000..5f2859de--- /dev/null+++ b/mongodb/CHANGELOG.md@@ -0,0 +1,13 @@+# Changelog++All notable changes to this plugin will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [Unreleased]++## [1.0.0] - 2026-02-07++### Added+- Initial plugin with skills and MCP server configurationdiff --git a/mongodb/LICENSE b/mongodb/LICENSEnew file mode 100644index 00000000..ca2bba77--- /dev/null+++ b/mongodb/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Cursor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/mongodb/README.md b/mongodb/README.mdnew file mode 100644index 00000000..9a99218c--- /dev/null+++ b/mongodb/README.md@@ -0,0 +1,28 @@+# MongoDB Plugin++Cursor plugin for MongoDB — schema design, queries, aggregation, indexes, and Mongoose ODM.++## Installation++```bash+agent install mongodb+```++## Components++### Skills++| Skill | Description |+|:------|:------------|+| `setup-mongodb` | Connect Node.js/TypeScript to MongoDB with native driver and Mongoose, including Docker Compose setup |+| `design-schema` | Document schema design, embedding vs referencing, index strategies, and aggregation pipelines |++### MCP Server++Provides MongoDB access via `mongodb-mcp-server`.++Requires `MONGODB_URI` environment variable.++## License++MITdiff --git a/mongodb/mcp.json b/mongodb/mcp.jsonnew file mode 100644index 00000000..cfb978e0--- /dev/null+++ b/mongodb/mcp.json@@ -0,0 +1,20 @@+{+ "$schema": "https://cursor.com/schemas/mcp.json",+ "mcpServers": {+ "mongodb": {+ "command": "npx",+ "args": ["-y", "mongodb-mcp-server"],+ "description": "MongoDB MCP server for database introspection, collection management, querying, and aggregation operations",+ "env": {+ "MDB_MCP_CONNECTION_STRING": "${env:MONGODB_URI}"+ },+ "capabilities": [+ "collection-introspection",+ "query-execution",+ "aggregation-pipelines",+ "index-management",+ "database-health-check"+ ]+ }+ }+}diff --git a/mongodb/mongodb.svg b/mongodb/mongodb.svgnew file mode 100644index 00000000..045b8af6--- /dev/null+++ b/mongodb/mongodb.svg@@ -0,0 +1 @@+<svg width="64" height="64" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>MongoDB</title><path d="M17.193 9.555c-1.264-5.58-4.252-7.414-4.573-8.115-.28-.394-.53-.954-.735-1.44-.036.495-.055.685-.523 1.184-.723.566-4.438 3.682-4.74 10.02-.282 5.912 4.27 9.435 4.888 9.884l.07.05A73.49 73.49 0 0111.91 24h.481c.114-1.032.284-2.056.51-3.07.417-.296.604-.463.85-.693a11.342 11.342 0 003.639-8.464c.01-.814-.103-1.662-.197-2.218zm-5.336 8.195s0-8.291.275-8.29c.213 0 .49 10.695.49 10.695-.381-.045-.765-1.76-.765-2.405z"/></svg>diff --git a/mongodb/skills/design-schema/SKILL.md b/mongodb/skills/design-schema/SKILL.mdnew file mode 100644index 00000000..00d985ac--- /dev/null+++ b/mongodb/skills/design-schema/SKILL.md@@ -0,0 +1,389 @@+---+name: design-schema+description: Document schema design, embedding vs referencing, index strategies, and aggregation pipelines for MongoDB+---++# Skill: Designing MongoDB Schemas and Indexes++## Description++This skill covers the complete workflow for designing MongoDB document schemas and indexes, including choosing embedding vs referencing strategies, applying common MongoDB design patterns, creating effective indexes, and validating schema design decisions.++## Prerequisites++- A running MongoDB instance (local, Docker, or Atlas)+- Basic understanding of the application's data entities and access patterns+- Node.js + Mongoose or the native MongoDB driver installed++## Steps++### 1. Identify Entities and Access Patterns++Before writing any schema, document your application's data requirements:++```markdown+## Entity: Product+- Fields: name, description, price, category, tags, inventory, images, reviews+- Read patterns:+ - List products by category (high frequency)+ - Search products by name/tags (high frequency)+ - Get product detail with recent reviews (high frequency)+ - Get all reviews for a product (medium frequency)+- Write patterns:+ - Create/update product info (low frequency)+ - Add review (medium frequency)+ - Update inventory (high frequency)+- Cardinality:+ - Products: ~10,000+ - Reviews per product: 0–10,000 (unbounded)+ - Images per product: 1–10 (bounded)+ - Tags per product: 1–20 (bounded)+```++### 2. Choose Embedding vs Referencing++Apply these decision rules for each relationship:++| Criterion | Embed | Reference |+|-----------|-------|-----------|+| Read together with parent? | Yes → Embed | No → Reference |+| Cardinality | Bounded (1:few) → Embed | Unbounded (1:many, many:many) → Reference |+| Updated independently? | No → Embed | Yes → Reference |+| Queried independently? | No → Embed | Yes → Reference |+| Document size risk? | Under 16MB → Embed | Near or over → Reference |+| Data duplication acceptable? | Yes → Embed / Extended Ref | No → Reference |++**Example decision for Product:**++```+- Images (1:few, bounded, read together) → EMBED+- Tags (1:few, bounded, read together) → EMBED+- Reviews (1:many, unbounded, queried independently) → REFERENCE+ - Apply Subset Pattern: embed latest 3 reviews for fast display+- Category (many:1, shared, queried independently) → REFERENCE+ - Apply Extended Reference: embed category name for display+```++### 3. Design the Schema++Translate your decisions into Mongoose schemas:++```typescript+import { Schema, model, Types } from 'mongoose';++// --- Category (referenced by products) ---+const categorySchema = new Schema({+ name: { type: String, required: true, unique: true },+ slug: { type: String, required: true, unique: true, lowercase: true },+ description: String,+ parentCategory: { type: Schema.Types.ObjectId, ref: 'Category' },+}, { timestamps: true });++export const Category = model('Category', categorySchema);++// --- Review (separate collection, referenced by product) ---+const reviewSchema = new Schema({+ product: { type: Schema.Types.ObjectId, ref: 'Product', required: true, index: true },+ author: { type: Schema.Types.ObjectId, ref: 'User', required: true, index: true },+ rating: { type: Number, required: true, min: 1, max: 5 },+ title: { type: String, required: true, maxlength: 200 },+ body: { type: String, maxlength: 5000 },+ helpful: { type: Number, default: 0 },+ verified: { type: Boolean, default: false },+}, { timestamps: true });++// Compound index: one review per user per product+reviewSchema.index({ product: 1, author: 1 }, { unique: true });+// For sorting reviews on product page+reviewSchema.index({ product: 1, createdAt: -1 });++export const Review = model('Review', reviewSchema);++// --- Product (main entity) ---+const productSchema = new Schema({+ name: { type: String, required: true, trim: true },+ slug: { type: String, required: true, unique: true, lowercase: true },+ description: { type: String, required: true },+ price: { type: Schema.Types.Decimal128, required: true },+ compareAtPrice: Schema.Types.Decimal128,+ currency: { type: String, default: 'USD', enum: ['USD', 'EUR', 'GBP'] },+ sku: { type: String, unique: true, sparse: true },++ // REFERENCE with Extended Reference Pattern — embed category name for display+ category: {+ _id: { type: Schema.Types.ObjectId, ref: 'Category', required: true },+ name: String,+ slug: String,+ },++ // EMBED — bounded, always read together+ tags: [{ type: String, lowercase: true, trim: true }],+ images: [{+ url: { type: String, required: true },+ alt: String,+ isPrimary: { type: Boolean, default: false },+ }],++ // SUBSET PATTERN — embed recent reviews, full reviews in separate collection+ recentReviews: [{+ _id: Schema.Types.ObjectId,+ author: String,+ rating: Number,+ title: String,+ createdAt: Date,+ }],++ // Computed values (Computed Pattern)+ averageRating: { type: Number, default: 0, min: 0, max: 5 },+ reviewCount: { type: Number, default: 0 },++ // Inventory+ inventory: {+ quantity: { type: Number, required: true, default: 0, min: 0 },+ warehouse: String,+ lowStockThreshold: { type: Number, default: 10 },+ },++ status: {+ type: String,+ enum: ['draft', 'active', 'archived'],+ default: 'draft',+ },+}, { timestamps: true });++export const Product = model('Product', productSchema);+```++### 4. Design Indexes++Create indexes that support your identified query patterns:++```typescript+// --- Product Indexes ---++// List products by category (high frequency)+productSchema.index({ 'category._id': 1, status: 1, createdAt: -1 });++// Search products by tags+productSchema.index({ tags: 1 });++// Filter by status + sort by price+productSchema.index({ status: 1, price: 1 });++// Text search on name and description+productSchema.index(+ { name: 'text', description: 'text', tags: 'text' },+ { weights: { name: 10, tags: 5, description: 1 }, name: 'idx_product_text_search' }+);++// Inventory alerts: find low-stock products+productSchema.index(+ { 'inventory.quantity': 1, status: 1 },+ { partialFilterExpression: { status: 'active' } }+);++// Unique slug+productSchema.index({ slug: 1 }, { unique: true });++// --- Category Indexes ---+categorySchema.index({ slug: 1 }, { unique: true });+categorySchema.index({ parentCategory: 1 });++// --- Review Indexes ---+// Already defined above: { product: 1, author: 1 } unique+// Already defined above: { product: 1, createdAt: -1 }+reviewSchema.index({ author: 1, createdAt: -1 }); // user's review history+```++### 5. Implement Common Operations++#### Add a Review (with Subset Pattern Update)++```typescript+import { Types } from 'mongoose';++async function addReview(+ productId: string,+ authorId: string,+ data: { rating: number; title: string; body?: string }+) {+ const session = await mongoose.startSession();+ session.startTransaction();++ try {+ // 1. Create the review+ const [review] = await Review.create([{+ product: new Types.ObjectId(productId),+ author: new Types.ObjectId(authorId),+ ...data,+ }], { session });++ // 2. Update product: recalculate average, update recent reviews+ const stats = await Review.aggregate([+ { $match: { product: new Types.ObjectId(productId) } },+ { $group: {+ _id: null,+ avgRating: { $avg: '$rating' },+ count: { $sum: 1 },+ }},+ ]).session(session);++ const recentReviews = await Review.find({ product: productId })+ .sort({ createdAt: -1 })+ .limit(3)+ .select('author rating title createdAt')+ .populate('author', 'name')+ .session(session)+ .lean();++ await Product.findByIdAndUpdate(productId, {+ $set: {+ averageRating: Math.round((stats[0]?.avgRating ?? 0) * 10) / 10,+ reviewCount: stats[0]?.count ?? 0,+ recentReviews: recentReviews.map(r => ({+ _id: r._id,+ author: (r.author as any).name,+ rating: r.rating,+ title: r.title,+ createdAt: r.createdAt,+ })),+ },+ }, { session });++ await session.commitTransaction();+ return review;+ } catch (error) {+ await session.abortTransaction();+ throw error;+ } finally {+ session.endSession();+ }+}+```++#### Cursor-Based Product Listing++```typescript+async function listProducts(categoryId: string, cursor?: string, limit = 20) {+ const query: any = {+ 'category._id': new Types.ObjectId(categoryId),+ status: 'active',+ };++ if (cursor) {+ query._id = { $lt: new Types.ObjectId(cursor) };+ }++ const products = await Product.find(query)+ .sort({ _id: -1 })+ .limit(limit + 1)+ .select('name slug price currency images averageRating reviewCount')+ .lean();++ const hasNext = products.length > limit;+ const items = hasNext ? products.slice(0, -1) : products;+ const nextCursor = hasNext ? items[items.length - 1]._id.toString() : null;++ return { items, nextCursor, hasNext };+}+```++### 6. Validate Schema with explain()++Verify that your indexes support your queries:++```typescript+// Check category listing query+const plan = await Product.find({+ 'category._id': categoryId,+ status: 'active',+})+ .sort({ _id: -1 })+ .limit(20)+ .explain('executionStats');++const stats = plan.executionStats;+console.log({+ executionTimeMs: stats.executionTimeMillis,+ totalDocsExamined: stats.totalDocsExamined,+ totalKeysExamined: stats.totalKeysExamined,+ nReturned: stats.nReturned,+ indexUsed: stats.executionStages.inputStage?.indexName ?? 'NONE',+});++// GOOD: totalDocsExamined ≈ nReturned, stage = IXSCAN+// BAD: totalDocsExamined >> nReturned or stage = COLLSCAN+```++### 7. Add Collection Validation (Native Driver)++For additional safety, add JSON Schema validation at the database level:++```javascript+db.runCommand({+ collMod: 'products',+ validator: {+ $jsonSchema: {+ bsonType: 'object',+ required: ['name', 'slug', 'price', 'category', 'status'],+ properties: {+ name: { bsonType: 'string', minLength: 1, maxLength: 500 },+ slug: { bsonType: 'string', pattern: '^[a-z0-9-]+$' },+ price: { bsonType: 'decimal' },+ status: { bsonType: 'string', enum: ['draft', 'active', 'archived'] },+ 'inventory.quantity': { bsonType: 'int', minimum: 0 },+ },+ },+ },+ validationLevel: 'moderate', // only validate inserts and updates to valid docs+ validationAction: 'error',+});+```++### 8. Monitor Index Usage++Periodically check that all indexes are being used:++```javascript+// Check index usage statistics+db.products.aggregate([{ $indexStats: {} }]).forEach(stat => {+ console.log(`${stat.name}: ${stat.accesses.ops} operations since ${stat.accesses.since}`);+});++// Drop unused indexes (after verifying they're truly unused)+// db.products.dropIndex('index_name');+```++## Verification++After designing your schema:++1. **Verify all queries use indexes:**+ ```bash+ mongosh --eval "db.products.find({'category._id': ObjectId('...')}).explain('executionStats')"+ ```++2. **Check document sizes are within bounds:**+ ```bash+ mongosh --eval "db.products.aggregate([{\$project: {size: {\$bsonSize: '$$ROOT'}}}, {\$sort: {size: -1}}, {\$limit: 5}])"+ ```++3. **Validate schema enforcement:**+ ```bash+ mongosh --eval "db.getCollectionInfos({name: 'products'})[0].options.validator"+ ```++4. **Test all CRUD operations** in application code and verify expected behavior.++## Common Pitfalls++| Pitfall | Solution |+|---------|----------|+| Unbounded array growth | Reference instead of embed; use Bucket or Subset pattern |+| Missing indexes on query fields | Run `explain()` on all frequent queries; add compound indexes |+| Redundant indexes | `{ a: 1, b: 1 }` covers `{ a: 1 }` — drop the single-field index |+| Monotonic shard keys | Use hashed or compound shard keys for even distribution |+| Deep nesting (>3 levels) | Flatten schema or extract to separate collection |+| Storing ObjectId as string | Always use `Schema.Types.ObjectId` / `new ObjectId()` |+| No validation on collections | Add JSON Schema validators or Mongoose validators |+| Over-populating in Mongoose | Use `$lookup` in aggregation for complex joins instead of chained `.populate()` |diff --git a/mongodb/skills/setup-mongodb/SKILL.md b/mongodb/skills/setup-mongodb/SKILL.mdnew file mode 100644index 00000000..55b3806a--- /dev/null+++ b/mongodb/skills/setup-mongodb/SKILL.md@@ -0,0 +1,416 @@+---+name: setup-mongodb+description: Connect Node.js/TypeScript to MongoDB with native driver and Mongoose, including Docker Compose setup+---++# Skill: Setting Up MongoDB with Node.js++## Description++This skill covers the complete workflow for connecting a Node.js/TypeScript application to MongoDB, using both the native MongoDB driver and Mongoose ODM, including connection configuration, model creation, and health checks.++## Prerequisites++- Node.js (v18 or later)+- npm, yarn, or pnpm+- A running MongoDB instance (local, Docker, or MongoDB Atlas)++## Steps++### 1. Choose Your Driver++| Feature | Native Driver (`mongodb`) | Mongoose |+|---------|--------------------------|----------|+| Schema validation | JSON Schema at DB level | Schema definitions + validators |+| Middleware / Hooks | No | Yes (pre/post hooks) |+| TypeScript support | Built-in generics | HydratedDocument, InferSchemaType |+| Population (joins) | Manual `$lookup` | `.populate()` |+| Performance | Minimal overhead | Slight overhead from hydration |+| Best for | Performance-critical, infrastructure | Application CRUD, rapid development |++### 2. Install Dependencies++**Option A — Mongoose (recommended for most applications):**++```bash+npm install mongoose+npm install -D @types/mongoose # only if using older Mongoose < 8+```++**Option B — Native MongoDB Driver:**++```bash+npm install mongodb+```++**Both (for apps that use Mongoose models + native driver for aggregations):**++```bash+npm install mongoose mongodb+```++### 3. Set Up Environment Variables++Create a `.env` file at the project root:++```env+# Local MongoDB+MONGODB_URI="mongodb://localhost:27017/myapp"++# MongoDB Atlas+MONGODB_URI="mongodb+srv://username:[email protected]/myapp?retryWrites=true&w=majority"++# With authentication (local)+MONGODB_URI="mongodb://admin:password@localhost:27017/myapp?authSource=admin"+```++Add `.env` to `.gitignore`:++```gitignore+.env+.env.local+```++### 4. Create the Database Connection (Mongoose)++Create `src/lib/database.ts`:++```typescript+import mongoose from 'mongoose';++const MONGODB_URI = process.env.MONGODB_URI;++if (!MONGODB_URI) {+ throw new Error('Please define the MONGODB_URI environment variable');+}++/**+ * Global cache for the Mongoose connection to prevent multiple+ * connections in development (hot reloading) and serverless environments.+ */+interface MongooseCache {+ conn: typeof mongoose | null;+ promise: Promise<typeof mongoose> | null;+}++declare global {+ var mongooseCache: MongooseCache | undefined;+}++const cached: MongooseCache = global.mongooseCache ?? { conn: null, promise: null };+global.mongooseCache = cached;++export async function connectToDatabase(): Promise<typeof mongoose> {+ if (cached.conn) {+ return cached.conn;+ }++ if (!cached.promise) {+ cached.promise = mongoose.connect(MONGODB_URI!, {+ maxPoolSize: 10,+ minPoolSize: 2,+ serverSelectionTimeoutMS: 5000,+ socketTimeoutMS: 45000,+ retryWrites: true,+ w: 'majority',+ });+ }++ cached.conn = await cached.promise;+ return cached.conn;+}++// Connection event handlers+mongoose.connection.on('connected', () => {+ console.log('MongoDB connected successfully');+});++mongoose.connection.on('error', (err) => {+ console.error('MongoDB connection error:', err);+});++mongoose.connection.on('disconnected', () => {+ console.warn('MongoDB disconnected');+});++// Graceful shutdown+async function gracefulShutdown(signal: string) {+ console.log(`Received ${signal}. Closing MongoDB connection...`);+ await mongoose.connection.close();+ process.exit(0);+}++process.on('SIGINT', () => gracefulShutdown('SIGINT'));+process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));+```++### 5. Create the Database Connection (Native Driver)++Create `src/lib/mongodb.ts`:++```typescript+import { MongoClient, Db } from 'mongodb';++const MONGODB_URI = process.env.MONGODB_URI;+const DB_NAME = process.env.MONGODB_DB_NAME || 'myapp';++if (!MONGODB_URI) {+ throw new Error('Please define the MONGODB_URI environment variable');+}++interface MongoCache {+ client: MongoClient | null;+ db: Db | null;+ promise: Promise<MongoClient> | null;+}++declare global {+ var mongoCache: MongoCache | undefined;+}++const cached: MongoCache = global.mongoCache ?? { client: null, db: null, promise: null };+global.mongoCache = cached;++export async function getDatabase(): Promise<Db> {+ if (cached.db) {+ return cached.db;+ }++ if (!cached.promise) {+ const client = new MongoClient(MONGODB_URI!, {+ maxPoolSize: 10,+ minPoolSize: 2,+ serverSelectionTimeoutMS: 5000,+ socketTimeoutMS: 45000,+ retryWrites: true,+ w: 'majority',+ });++ cached.promise = client.connect();+ }++ cached.client = await cached.promise;+ cached.db = cached.client.db(DB_NAME);+ return cached.db;+}++export async function getClient(): Promise<MongoClient> {+ if (cached.client) {+ return cached.client;+ }+ await getDatabase();+ return cached.client!;+}+```++### 6. Define Models (Mongoose)++Create `src/models/User.ts`:++```typescript+import { Schema, model, models, type HydratedDocument } from 'mongoose';++export interface IUser {+ email: string;+ name: string;+ role: 'user' | 'admin' | 'moderator';+ avatar?: string;+ lastLoginAt?: Date;+ createdAt: Date;+ updatedAt: Date;+}++export type UserDocument = HydratedDocument<IUser>;++const userSchema = new Schema<IUser>(+ {+ email: {+ type: String,+ required: [true, 'Email is required'],+ unique: true,+ lowercase: true,+ trim: true,+ match: [/^\S+@\S+\.\S+$/, 'Please provide a valid email'],+ },+ name: {+ type: String,+ required: [true, 'Name is required'],+ trim: true,+ minlength: [2, 'Name must be at least 2 characters'],+ maxlength: [100, 'Name must be at most 100 characters'],+ },+ role: {+ type: String,+ enum: {+ values: ['user', 'admin', 'moderator'],+ message: '{VALUE} is not a valid role',+ },+ default: 'user',+ },+ avatar: String,+ lastLoginAt: Date,+ },+ {+ timestamps: true,+ toJSON: {+ transform(_doc, ret) {+ ret.id = ret._id.toString();+ delete ret._id;+ delete ret.__v;+ return ret;+ },+ },+ }+);++// Indexes+userSchema.index({ role: 1, createdAt: -1 });+userSchema.index({ lastLoginAt: -1 });++export const User = models.User || model<IUser>('User', userSchema);+```++### 7. Define Collection Types (Native Driver)++Create `src/types/collections.ts`:++```typescript+import type { ObjectId } from 'mongodb';++export interface UserDocument {+ _id: ObjectId;+ email: string;+ name: string;+ role: 'user' | 'admin' | 'moderator';+ avatar?: string;+ lastLoginAt?: Date;+ createdAt: Date;+ updatedAt: Date;+}++export interface PostDocument {+ _id: ObjectId;+ title: string;+ content: string;+ authorId: ObjectId;+ tags: string[];+ published: boolean;+ createdAt: Date;+ updatedAt: Date;+}+```++### 8. Use in Application Code++```typescript+// With Mongoose+import { connectToDatabase } from '@/lib/database';+import { User } from '@/models/User';++await connectToDatabase();+const users = await User.find({ role: 'admin' }).sort({ createdAt: -1 }).lean();++// With native driver+import { getDatabase } from '@/lib/mongodb';+import type { UserDocument } from '@/types/collections';++const db = await getDatabase();+const users = await db.collection<UserDocument>('users')+ .find({ role: 'admin' })+ .sort({ createdAt: -1 })+ .toArray();+```++### 9. Run MongoDB Locally (Docker)++Create a `docker-compose.yml` for local development:++```yaml+version: '3.8'+services:+ mongodb:+ image: mongo:7+ container_name: mongodb-dev+ ports:+ - '27017:27017'+ environment:+ MONGO_INITDB_ROOT_USERNAME: admin+ MONGO_INITDB_ROOT_PASSWORD: password+ MONGO_INITDB_DATABASE: myapp+ volumes:+ - mongodb_data:/data/db+ restart: unless-stopped++volumes:+ mongodb_data:+```++Start MongoDB:++```bash+docker compose up -d+```++### 10. Seed the Database++Create `src/scripts/seed.ts`:++```typescript+import mongoose from 'mongoose';+import { connectToDatabase } from '../lib/database';+import { User } from '../models/User';++async function seed() {+ await connectToDatabase();++ // Clear existing data+ await User.deleteMany({});++ // Insert seed data+ const users = await User.insertMany([+ { email: '[email protected]', name: 'Alice', role: 'admin' },+ { email: '[email protected]', name: 'Bob', role: 'user' },+ { email: '[email protected]', name: 'Carol', role: 'moderator' },+ ]);++ console.log(`Seeded ${users.length} users`);+ await mongoose.connection.close();+}++seed().catch((err) => {+ console.error('Seed failed:', err);+ process.exit(1);+});+```++Run the seed script:++```bash+npx tsx src/scripts/seed.ts+```++## Verification++After setup, verify the connection works:++```bash+# Test connection with mongosh+mongosh "mongodb://localhost:27017/myapp" --eval "db.runCommand({ ping: 1 })"++# Run the seed script+npx tsx src/scripts/seed.ts++# Verify data was inserted+mongosh "mongodb://localhost:27017/myapp" --eval "db.users.find().pretty()"+```++## Troubleshooting++| Problem | Solution |+|---------|----------|+| `MONGODB_URI` not set | Ensure `.env` file exists and is loaded (use `dotenv` or framework built-in) |+| `ECONNREFUSED` | Verify MongoDB is running: `mongosh --eval "db.runCommand({ping:1})"` |+| Authentication failed | Check username/password and `authSource` parameter in URI |+| `MongoServerSelectionError` | Check network connectivity, firewall rules, and Atlas IP whitelist |+| Slow connections in dev | Hot reloading creates multiple connections — use the global cache pattern above |+| `querySrv ENOTFOUND` | DNS issue with Atlas SRV URI — check network or use standard URI format |diff --git a/nextjs-react-typescript/.cursor-plugin/plugin.json b/nextjs-react-typescript/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..792ec881--- /dev/null+++ b/nextjs-react-typescript/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "nextjs-react-typescript",+ "version": "1.0.0",+ "description": "Next.js App Router, React, Shadcn UI, and Tailwind development rules by Pontus Abrahamsson (cursor.directory)",+ "author": {+ "name": "Pontus Abrahamsson",+ "url": "https://cursor.directory/nextjs-react-typescript-cursor-rules"+ },+ "homepage": "https://cursor.directory/nextjs-react-typescript-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "nextjs",+ "react",+ "typescript",+ "shadcn",+ "radix",+ "tailwind"+ ],+ "category": "frontend",+ "tags": [+ "shadcn",+ "radix",+ "tailwind",+ "nuqs"+ ],+ "rules": "./rules/"+}diff --git a/nextjs-react-typescript/README.md b/nextjs-react-typescript/README.mdnew file mode 100644index 00000000..aa6b2331--- /dev/null+++ b/nextjs-react-typescript/README.md@@ -0,0 +1,29 @@+# nextjs-react-typescript++Next.js App Router, React, Shadcn UI, and Tailwind development rules by Pontus Abrahamsson (cursor.directory)++## Installation++```bash+agent install nextjs-react-typescript+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `nextjs_react_typescript` | Next.js App Router with React, Shadcn UI, and Tailwind conventions | `**/*.ts, **/*.tsx, **/*.jsx` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/nextjs-react-typescript-cursor-rules).++- **Original Author**: Pontus Abrahamsson+- **Tags**: shadcn, radix, tailwind, nuqs+- **Category**: frontend++## License++MITdiff --git a/nextjs-react-typescript/rules/nextjs_react_typescript.mdc b/nextjs-react-typescript/rules/nextjs_react_typescript.mdcnew file mode 100644index 00000000..3f55dfa8--- /dev/null+++ b/nextjs-react-typescript/rules/nextjs_react_typescript.mdc@@ -0,0 +1,51 @@+---+description: Next.js App Router with React, Shadcn UI, and Tailwind conventions+globs:+ - "**/*.ts"+ - "**/*.tsx"+ - "**/*.jsx"+alwaysApply: false+---++You are an expert in TypeScript, Node.js, Next.js App Router, React, Shadcn UI, Radix UI and Tailwind.++Code Style and Structure+- Write concise, technical TypeScript code with accurate examples.+- Use functional and declarative programming patterns; avoid classes.+- Prefer iteration and modularization over code duplication.+- Use descriptive variable names with auxiliary verbs (e.g., isLoading, hasError).+- Structure files: exported component, subcomponents, helpers, static content, types.++Naming Conventions+- Use lowercase with dashes for directories (e.g., components/auth-wizard).+- Favor named exports for components.++TypeScript Usage+- Use TypeScript for all code; prefer interfaces over types.+- Avoid enums; use maps instead.+- Use functional components with TypeScript interfaces.++Syntax and Formatting+- Use the "function" keyword for pure functions.+- Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements.+- Use declarative JSX.++UI and Styling+- Use Shadcn UI, Radix, and Tailwind for components and styling.+- Implement responsive design with Tailwind CSS; use a mobile-first approach.++Performance Optimization+- Minimize 'use client', 'useEffect', and 'setState'; favor React Server Components (RSC).+- Wrap client components in Suspense with fallback.+- Use dynamic loading for non-critical components.+- Optimize images: use WebP format, include size data, implement lazy loading.++Key Conventions+- Use 'nuqs' for URL search parameter state management.+- Optimize Web Vitals (LCP, CLS, FID).+- Limit 'use client':+ - Favor server components and Next.js SSR.+ - Use only for Web API access in small components.+ - Avoid for data fetching or state management.++Follow Next.js docs for Data Fetching, Rendering, and Routing.diff --git a/playwright-testing/.cursor-plugin/plugin.json b/playwright-testing/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..63ef8cfc--- /dev/null+++ b/playwright-testing/.cursor-plugin/plugin.json@@ -0,0 +1,24 @@+{+ "name": "playwright-testing",+ "version": "1.0.0",+ "description": "Playwright end-to-end testing and QA automation rules by Douglas Urrea Ocampo (cursor.directory)",+ "author": {+ "name": "Douglas Urrea Ocampo",+ "url": "https://cursor.directory/playwright-cursor-rules"+ },+ "homepage": "https://cursor.directory/playwright-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "playwright",+ "testing",+ "e2e",+ "automation",+ "qa"+ ],+ "category": "testing",+ "tags": [+ "playwright"+ ],+ "rules": "./rules/"+}diff --git a/playwright-testing/README.md b/playwright-testing/README.mdnew file mode 100644index 00000000..550cbc32--- /dev/null+++ b/playwright-testing/README.md@@ -0,0 +1,29 @@+# playwright-testing++Playwright end-to-end testing and QA automation rules by Douglas Urrea Ocampo (cursor.directory)++## Installation++```bash+agent install playwright-testing+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `playwright_testing` | Playwright end-to-end testing best practices and QA automation patterns | `**/*.spec.ts, **/*.test.ts, **/tests/**` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/playwright-cursor-rules).++- **Original Author**: Douglas Urrea Ocampo+- **Tags**: playwright+- **Category**: testing++## License++MITdiff --git a/playwright-testing/rules/playwright_testing.mdc b/playwright-testing/rules/playwright_testing.mdcnew file mode 100644index 00000000..c2eb6fcb--- /dev/null+++ b/playwright-testing/rules/playwright_testing.mdc@@ -0,0 +1,34 @@+---+description: Playwright end-to-end testing best practices and QA automation patterns+globs:+ - "**/*.spec.ts"+ - "**/*.test.ts"+ - "**/tests/**"+ - "**/e2e/**"+ - "**/playwright.config.*"+alwaysApply: false+---++You are a Senior QA Automation Engineer expert in TypeScript, JavaScript, Frontend development, Backend development, and Playwright end-to-end testing.+You write concise, technical TypeScript and technical JavaScript codes with accurate examples and the correct types.++- Use descriptive and meaningful test names that clearly describe the expected behavior.+- Utilize Playwright fixtures (e.g., `test`, `page`, `expect`) to maintain test isolation and consistency.+- Use `test.beforeEach` and `test.afterEach` for setup and teardown to ensure a clean state for each test.+- Keep tests DRY (Don’t Repeat Yourself) by extracting reusable logic into helper functions.+- Avoid using `page.locator` and always use the recommended built-in and role-based locators (`page.getByRole`, `page.getByLabel`, `page.getByText`, `page.getByTitle`, etc.) over complex selectors.+- Use `page.getByTestId` whenever `data-testid` is defined on an element or container.+- Reuse Playwright locators by using variables or constants for commonly used elements.+- Use the `playwright.config.ts` file for global configuration and environment setup.+- Implement proper error handling and logging in tests to provide clear failure messages.+- Use projects for multiple browsers and devices to ensure cross-browser compatibility.+- Use built-in config objects like `devices` whenever possible.+- Prefer to use web-first assertions (`toBeVisible`, `toHaveText`, etc.) whenever possible.+- Use `expect` matchers for assertions (`toEqual`, `toContain`, `toBeTruthy`, `toHaveLength`, etc.) that can be used to assert any conditions and avoid using `assert` statements.+- Avoid hardcoded timeouts.+- Use `page.waitFor` with specific conditions or events to wait for elements or states.+- Ensure tests run reliably in parallel without shared state conflicts.+- Avoid commenting on the resulting code.+- Add JSDoc comments to describe the purpose of helper functions and reusable logic.+- Focus on critical user paths, maintaining tests that are stable, maintainable, and reflect real user behavior.+- Follow the guidance and best practices described on "https://playwright.dev/docs/writing-tests".diff --git a/rails-ruby/.cursor-plugin/plugin.json b/rails-ruby/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..41594de1--- /dev/null+++ b/rails-ruby/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "rails-ruby",+ "version": "1.0.0",+ "description": "Ruby on Rails, PostgreSQL, Hotwire, and Tailwind development rules by Theo Vararu (cursor.directory)",+ "author": {+ "name": "Theo Vararu",+ "url": "https://cursor.directory/rails-ruby-cursor-rules"+ },+ "homepage": "https://cursor.directory/rails-ruby-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "ruby",+ "rails",+ "hotwire",+ "turbo",+ "stimulus",+ "tailwind"+ ],+ "category": "backend",+ "tags": [+ "rails",+ "ruby",+ "hotwire",+ "tailwind"+ ],+ "rules": "./rules/"+}diff --git a/rails-ruby/README.md b/rails-ruby/README.mdnew file mode 100644index 00000000..114a30b3--- /dev/null+++ b/rails-ruby/README.md@@ -0,0 +1,29 @@+# rails-ruby++Ruby on Rails, PostgreSQL, Hotwire, and Tailwind development rules by Theo Vararu (cursor.directory)++## Installation++```bash+agent install rails-ruby+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `rails_ruby` | Ruby on Rails development with Hotwire, Turbo, Stimulus, and Tailwind CSS | `**/*.rb, **/*.erb, **/Gemfile` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/rails-ruby-cursor-rules).++- **Original Author**: Theo Vararu+- **Tags**: rails, ruby, hotwire, tailwind+- **Category**: backend++## License++MITdiff --git a/rails-ruby/rules/rails_ruby.mdc b/rails-ruby/rules/rails_ruby.mdcnew file mode 100644index 00000000..8867fe48--- /dev/null+++ b/rails-ruby/rules/rails_ruby.mdc@@ -0,0 +1,68 @@+---+description: Ruby on Rails development with Hotwire, Turbo, Stimulus, and Tailwind CSS+globs:+ - "**/*.rb"+ - "**/*.erb"+ - "**/Gemfile"+alwaysApply: false+---++You are an expert in Ruby on Rails, PostgreSQL, Hotwire (Turbo and Stimulus), and Tailwind CSS.++Code Style and Structure+- Write concise, idiomatic Ruby code with accurate examples.+- Follow Rails 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 Rails conventions (MVC, concerns, helpers, etc.).++Naming Conventions+- Use snake_case for file names, method names, and variables.+- Use CamelCase for class and module names.+- Follow Rails naming conventions for models, controllers, and views.++Ruby and Rails Usage+- Use Ruby 3.x features when appropriate (e.g., pattern matching, endless methods).+- Leverage Rails' built-in helpers and methods.+- Use ActiveRecord effectively for database operations.++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.+- Use ActiveModel validations in models.+- Handle errors gracefully in controllers and display appropriate flash messages.++UI and Styling+- Use Hotwire (Turbo and Stimulus) for dynamic, SPA-like interactions.+- Implement responsive design with Tailwind CSS.+- Use Rails view helpers and partials to keep views DRY.++Performance Optimization+- Use database indexing effectively.+- Implement caching strategies (fragment caching, Russian Doll caching).+- Use eager loading to avoid N+1 queries.+- Optimize database queries using includes, joins, or select.++Key Conventions+- Follow RESTful routing conventions.+- Use concerns for shared behavior across models or controllers.+- Implement service objects for complex business logic.+- Use background jobs (e.g., Sidekiq) for time-consuming tasks.++Testing+- Write comprehensive tests using RSpec or Minitest.+- Follow TDD/BDD practices.+- Use factories (FactoryBot) for test data generation.++Security+- Implement proper authentication and authorization (e.g., Devise, Pundit).+- Use strong parameters in controllers.+- Protect against common web vulnerabilities (XSS, CSRF, SQL injection).++Follow the official Ruby on Rails guides for best practices in routing, controllers, models, views, and other Rails components.diff --git a/rust-async/.cursor-plugin/plugin.json b/rust-async/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..bea4acd3--- /dev/null+++ b/rust-async/.cursor-plugin/plugin.json@@ -0,0 +1,27 @@+{+ "name": "rust-async",+ "version": "1.0.0",+ "description": "Rust async programming and concurrent systems development rules by Sheng-Yan, Zhang (cursor.directory)",+ "author": {+ "name": "Sheng-Yan, Zhang",+ "url": "https://cursor.directory/rust-async-development-rules"+ },+ "homepage": "https://cursor.directory/rust-async-development-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "rust",+ "async",+ "tokio",+ "concurrency",+ "systems"+ ],+ "category": "systems",+ "tags": [+ "Rust",+ "tokio",+ "anyhow",+ "serde"+ ],+ "rules": "./rules/"+}diff --git a/rust-async/README.md b/rust-async/README.mdnew file mode 100644index 00000000..0aa9d925--- /dev/null+++ b/rust-async/README.md@@ -0,0 +1,29 @@+# rust-async++Rust async programming and concurrent systems development rules by Sheng-Yan, Zhang (cursor.directory)++## Installation++```bash+agent install rust-async+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `rust_async` | Rust async programming with tokio, concurrency patterns, and systems development | `**/*.rs, **/Cargo.toml` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/rust-async-development-rules).++- **Original Author**: Sheng-Yan, Zhang+- **Tags**: Rust, tokio, anyhow, serde+- **Category**: systems++## License++MITdiff --git a/rust-async/rules/rust_async.mdc b/rust-async/rules/rust_async.mdcnew file mode 100644index 00000000..dbb63b10--- /dev/null+++ b/rust-async/rules/rust_async.mdc@@ -0,0 +1,67 @@+---+description: Rust async programming with tokio, concurrency patterns, and systems development+globs:+ - "**/*.rs"+ - "**/Cargo.toml"+alwaysApply: false+---++You are an expert in Rust, async programming, and concurrent systems.++Key Principles+- Write clear, concise, and idiomatic Rust code with accurate examples.+- Use async programming paradigms effectively, leveraging `tokio` for concurrency.+- Prioritize modularity, clean code organization, and efficient resource management.+- Use expressive variable names that convey intent (e.g., `is_ready`, `has_data`).+- Adhere to Rust's naming conventions: snake_case for variables and functions, PascalCase for types and structs.+- Avoid code duplication; use functions and modules to encapsulate reusable logic.+- Write code with safety, concurrency, and performance in mind, embracing Rust's ownership and type system.++Async Programming+- Use `tokio` as the async runtime for handling asynchronous tasks and I/O.+- Implement async functions using `async fn` syntax.+- Leverage `tokio::spawn` for task spawning and concurrency.+- Use `tokio::select!` for managing multiple async tasks and cancellations.+- Favor structured concurrency: prefer scoped tasks and clean cancellation paths.+- Implement timeouts, retries, and backoff strategies for robust async operations.++Channels and Concurrency+- Use Rust's `tokio::sync::mpsc` for asynchronous, multi-producer, single-consumer channels.+- Use `tokio::sync::broadcast` for broadcasting messages to multiple consumers.+- Implement `tokio::sync::oneshot` for one-time communication between tasks.+- Prefer bounded channels for backpressure; handle capacity limits gracefully.+- Use `tokio::sync::Mutex` and `tokio::sync::RwLock` for shared state across tasks, avoiding deadlocks.++Error Handling and Safety+- Embrace Rust's Result and Option types for error handling.+- Use `?` operator to propagate errors in async functions.+- Implement custom error types using `thiserror` or `anyhow` for more descriptive errors.+- Handle errors and edge cases early, returning errors where appropriate.+- Use `.await` responsibly, ensuring safe points for context switching.++Testing+- Write unit tests with `tokio::test` for async tests.+- Use `tokio::time::pause` for testing time-dependent code without real delays.+- Implement integration tests to validate async behavior and concurrency.+- Use mocks and fakes for external dependencies in tests.++Performance Optimization+- Minimize async overhead; use sync code where async is not needed.+- Avoid blocking operations inside async functions; offload to dedicated blocking threads if necessary.+- Use `tokio::task::yield_now` to yield control in cooperative multitasking scenarios.+- Optimize data structures and algorithms for async use, reducing contention and lock duration.+- Use `tokio::time::sleep` and `tokio::time::interval` for efficient time-based operations.++Key Conventions+1. Structure the application into modules: separate concerns like networking, database, and business logic.+2. Use environment variables for configuration management (e.g., `dotenv` crate).+3. Ensure code is well-documented with inline comments and Rustdoc.++Async Ecosystem+- Use `tokio` for async runtime and task management.+- Leverage `hyper` or `reqwest` for async HTTP requests.+- Use `serde` for serialization/deserialization.+- Use `sqlx` or `tokio-postgres` for async database interactions.+- Utilize `tonic` for gRPC with async support.++Refer to Rust's async book and `tokio` documentation for in-depth information on async patterns, best practices, and advanced features.diff --git a/sentry/.cursor-plugin/plugin.json b/sentry/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..6942c81f--- /dev/null+++ b/sentry/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "sentry",+ "version": "1.0.0",+ "description": "Cursor plugin for Sentry \u2014 error monitoring, performance tracking, session replay, and alerting",+ "author": {+ "name": "Cursor",+ "email": "[email protected]"+ },+ "homepage": "https://github.com/cursor/plugins",+ "repository": "https://github.com/cursor/plugins",+ "license": "MIT",+ "keywords": [+ "sentry",+ "error-monitoring",+ "performance",+ "observability",+ "debugging"+ ],+ "category": "observability",+ "tags": [+ "monitoring",+ "error-tracking",+ "performance"+ ],+ "logo": "./sentry.svg",+ "skills": "./skills/",+ "mcpServers": "./mcp.json"+}diff --git a/sentry/CHANGELOG.md b/sentry/CHANGELOG.mdnew file mode 100644index 00000000..5f2859de--- /dev/null+++ b/sentry/CHANGELOG.md@@ -0,0 +1,13 @@+# Changelog++All notable changes to this plugin will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [Unreleased]++## [1.0.0] - 2026-02-07++### Added+- Initial plugin with skills and MCP server configurationdiff --git a/sentry/LICENSE b/sentry/LICENSEnew file mode 100644index 00000000..ca2bba77--- /dev/null+++ b/sentry/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Cursor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/sentry/README.md b/sentry/README.mdnew file mode 100644index 00000000..c0b100da--- /dev/null+++ b/sentry/README.md@@ -0,0 +1,28 @@+# Sentry Plugin++Cursor plugin for Sentry — error monitoring, performance tracking, session replay, and alerting.++## Installation++```bash+agent install sentry+```++## Components++### Skills++| Skill | Description |+|:------|:------------|+| `setup-sentry` | Framework-specific setup for Next.js, React, Node.js, and Python with source maps and releases |+| `configure-alerts` | Issue alerts, metric alerts, uptime monitors, and cron monitors |++### MCP Server++Provides access to Sentry via `@sentry/mcp-server`.++Requires `SENTRY_AUTH_TOKEN` environment variable.++## License++MITdiff --git a/sentry/mcp.json b/sentry/mcp.jsonnew file mode 100644index 00000000..b5ea68bd--- /dev/null+++ b/sentry/mcp.json@@ -0,0 +1,54 @@+{+ "$schema": "https://cursor.com/schemas/mcp.json",+ "mcpServers": {+ "sentry": {+ "command": "npx",+ "args": [+ "-y",+ "@sentry/mcp-server@latest"+ ],+ "env": {+ "SENTRY_AUTH_TOKEN": "${SENTRY_AUTH_TOKEN}",+ "SENTRY_ORG": "${SENTRY_ORG}",+ "SENTRY_PROJECT": "${SENTRY_PROJECT}"+ },+ "description": "Sentry MCP server — exposes Sentry issues, events, releases, and performance data to AI agents.",+ "capabilities": {+ "tools": [+ {+ "name": "list_issues",+ "description": "List recent unresolved issues for the project, with optional query filters."+ },+ {+ "name": "get_issue",+ "description": "Get detailed information about a specific Sentry issue, including events, tags, and assignee."+ },+ {+ "name": "get_event",+ "description": "Retrieve a specific error event with full stack trace, breadcrumbs, and context."+ },+ {+ "name": "list_releases",+ "description": "List releases for the project with deploy and commit information."+ },+ {+ "name": "search_events",+ "description": "Search for events matching a Sentry query string."+ },+ {+ "name": "resolve_issue",+ "description": "Resolve or unresolve a Sentry issue."+ },+ {+ "name": "assign_issue",+ "description": "Assign a Sentry issue to a user or team."+ },+ {+ "name": "get_performance_summary",+ "description": "Get performance summary for transactions — p50, p95, throughput, failure rate."+ }+ ]+ }+ }+ }+}diff --git a/sentry/sentry.svg b/sentry/sentry.svgnew file mode 100644index 00000000..19cf27c8--- /dev/null+++ b/sentry/sentry.svg@@ -0,0 +1 @@+<svg width="64" height="64" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Sentry</title><path d="M13.91 2.505c-.873-1.448-2.972-1.448-3.844 0L6.904 7.92a15.478 15.478 0 0 1 8.53 12.811h-2.221A13.301 13.301 0 0 0 5.784 9.814l-2.926 5.06a7.65 7.65 0 0 1 4.435 5.848H2.194a.365.365 0 0 1-.298-.534l1.413-2.402a5.16 5.16 0 0 0-1.614-.913L.296 19.275a2.182 2.182 0 0 0 .812 2.999 2.24 2.24 0 0 0 1.086.288h6.983a9.322 9.322 0 0 0-3.845-8.318l1.11-1.922a11.47 11.47 0 0 1 4.95 10.24h5.915a17.242 17.242 0 0 0-7.885-15.28l2.244-3.845a.37.37 0 0 1 .504-.13c.255.14 9.75 16.708 9.928 16.9a.365.365 0 0 1-.327.543h-2.287c.029.612.029 1.223 0 1.831h2.297a2.206 2.206 0 0 0 1.922-3.31z"/></svg>diff --git a/sentry/skills/configure-alerts/SKILL.md b/sentry/skills/configure-alerts/SKILL.mdnew file mode 100644index 00000000..5fbba9e4--- /dev/null+++ b/sentry/skills/configure-alerts/SKILL.md@@ -0,0 +1,310 @@+---+name: configure-alerts+description: Issue alerts, metric alerts, uptime monitors, and cron monitors for Sentry+---++# Skill: Configure Sentry Alerts++Configure Sentry alerts to get notified about errors, performance degradations, and uptime issues. This skill covers issue alerts, metric alerts, and uptime monitors.++## Prerequisites++- A Sentry account with a configured project+- Owner or Manager role in the Sentry organization (required to create alerts)+- Notification integrations set up (Slack, PagerDuty, email, etc.)++---++## Issue Alerts++Issue alerts trigger when a new or existing issue matches specific conditions. They are the most common alert type.++### Creating an Issue Alert (UI)++1. Go to **Alerts → Create Alert → Issues**.+2. Select the project.+3. Configure conditions:++| Section | Description | Example |+|---|---|---|+| **When** | The trigger event | "A new issue is created" |+| **If** | Filter conditions | "The issue's level is `error` or `fatal`" |+| **Then** | Actions to perform | "Send a Slack notification to #engineering-alerts" |++### Creating an Issue Alert (API)++```bash+curl -X POST "https://sentry.io/api/0/projects/${SENTRY_ORG}/${SENTRY_PROJECT}/rules/" \+ -H "Authorization: Bearer ${SENTRY_AUTH_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "name": "Critical Error Alert",+ "actionMatch": "all",+ "filterMatch": "all",+ "conditions": [+ {+ "id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition"+ }+ ],+ "filters": [+ {+ "id": "sentry.rules.filters.level.LevelFilter",+ "match": "gte",+ "level": "40"+ }+ ],+ "actions": [+ {+ "id": "sentry.integrations.slack.notify_action.SlackNotifyServiceAction",+ "workspace": "<slack-workspace-id>",+ "channel": "#engineering-alerts",+ "tags": "environment,release,level"+ }+ ],+ "frequency": 30+ }'+```++### Recommended Issue Alert Rules++#### 1. New Critical Errors++- **When:** A new issue is created+- **If:** Level is `error` or `fatal`+- **Then:** Notify Slack channel + assign to on-call++#### 2. Regression Alert++- **When:** A resolved issue changes state from resolved to unresolved (regression)+- **Then:** Notify the issue owner and the team Slack channel++#### 3. High-Volume Error Spike++- **When:** Number of events in an issue exceeds 100 in 1 hour+- **If:** Level is `error` or higher+- **Then:** Page on-call via PagerDuty++#### 4. First Error in New Release++- **When:** A new issue is created+- **If:** The issue's tag `release` matches the latest release+- **Then:** Notify the release channel++---++## Metric Alerts++Metric alerts trigger based on aggregate data over time — error counts, transaction durations, failure rates, crash rates, etc.++### Creating a Metric Alert (UI)++1. Go to **Alerts → Create Alert → Metric**.+2. Choose the metric type:+ - **Number of Errors** — Total error event count.+ - **Users Experiencing Errors** — Unique users hitting errors.+ - **Transaction Duration** — p50, p75, p95, or p99 latency.+ - **Failure Rate** — Percentage of transactions with non-OK status.+ - **Apdex** — Application Performance Index score.+ - **Crash Free Session Rate** — For mobile/desktop apps.++3. Configure thresholds:+ - **Critical:** Immediate action required.+ - **Warning:** Something to watch.+ - **Resolved:** When the metric returns to normal.++### Creating a Metric Alert (API)++```bash+curl -X POST "https://sentry.io/api/0/organizations/${SENTRY_ORG}/alert-rules/" \+ -H "Authorization: Bearer ${SENTRY_AUTH_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "name": "High P95 Latency — API",+ "dataset": "transactions",+ "query": "transaction:/api/*",+ "aggregate": "p95(transaction.duration)",+ "timeWindow": 5,+ "thresholdType": 0,+ "triggers": [+ {+ "label": "critical",+ "alertThreshold": 5000,+ "actions": [+ {+ "type": "slack",+ "targetIdentifier": "#sre-alerts",+ "targetType": "specific"+ }+ ]+ },+ {+ "label": "warning",+ "alertThreshold": 3000,+ "actions": [+ {+ "type": "email",+ "targetIdentifier": "team-backend",+ "targetType": "team"+ }+ ]+ }+ ],+ "projects": ["my-project"],+ "environment": "production"+ }'+```++### Recommended Metric Alerts++#### 1. Error Rate Spike++- **Metric:** `count()` on error events+- **Threshold:** > 50 errors in 5 minutes (warning), > 200 in 5 minutes (critical)+- **Filter:** `environment:production`+- **Action:** Slack + PagerDuty (critical)++#### 2. P95 Latency Regression++- **Metric:** `p95(transaction.duration)`+- **Threshold:** > 3 s warning, > 5 s critical+- **Filter:** `transaction:/api/*`+- **Window:** 5 minutes+- **Action:** Slack notification++#### 3. Apdex Drop++- **Metric:** `apdex(300)` (300 ms threshold)+- **Threshold:** < 0.9 warning, < 0.7 critical+- **Window:** 10 minutes+- **Action:** Email the team lead++#### 4. Failure Rate Surge++- **Metric:** `failure_rate()`+- **Threshold:** > 5 % warning, > 15 % critical+- **Filter:** `transaction:/api/checkout`+- **Window:** 5 minutes+- **Action:** Page on-call++#### 5. Crash Free Rate Drop (Mobile)++- **Metric:** `crash_free_rate(session)`+- **Threshold:** < 99.5 % warning, < 98 % critical+- **Window:** 1 hour+- **Action:** Slack + mobile team email++---++## Uptime Monitors++Uptime monitors check whether your endpoints are reachable and responding correctly.++### Creating an Uptime Monitor (UI)++1. Go to **Alerts → Uptime Monitors → Create Monitor**.+2. Configure:+ - **URL:** `https://api.myapp.com/health`+ - **Interval:** every 1 minute+ - **Regions:** US, EU (checks from multiple locations)+ - **Expected status:** 200+ - **Timeout:** 10 seconds++### Creating an Uptime Monitor (API)++```bash+curl -X POST "https://sentry.io/api/0/organizations/${SENTRY_ORG}/monitors/" \+ -H "Authorization: Bearer ${SENTRY_AUTH_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "name": "API Health Check",+ "type": "uptime",+ "config": {+ "url": "https://api.myapp.com/health",+ "schedule_type": "interval",+ "schedule": [1, "minute"],+ "checkin_margin": 2,+ "max_runtime": 10,+ "timezone": "UTC"+ },+ "alert_rule": {+ "targets": [+ { "target_type": "specific", "target_identifier": "#sre-alerts" }+ ]+ }+ }'+```++### Recommended Uptime Monitors++| Monitor | URL | Interval | Alert After |+|---|---|---|---|+| API Health | `/health` or `/api/healthz` | 1 min | 2 consecutive failures |+| Homepage | `https://myapp.com` | 1 min | 2 consecutive failures |+| Auth Service | `/api/auth/health` | 1 min | 1 failure |+| Webhook Endpoint | `/api/webhooks/status` | 5 min | 3 consecutive failures |++---++## Cron Monitors++For scheduled jobs and background tasks, use Sentry Crons to detect missed or failed runs.++### Setup++```ts+// Wrap your cron job+import * as Sentry from "@sentry/node";++const checkInId = Sentry.captureCheckIn({+ monitorSlug: "daily-report-generation",+ status: "in_progress",+});++try {+ await generateDailyReport();++ Sentry.captureCheckIn({+ checkInId,+ monitorSlug: "daily-report-generation",+ status: "ok",+ });+} catch (error) {+ Sentry.captureCheckIn({+ checkInId,+ monitorSlug: "daily-report-generation",+ status: "error",+ });+ Sentry.captureException(error);+}+```++### Configuration (API)++```bash+curl -X POST "https://sentry.io/api/0/organizations/${SENTRY_ORG}/monitors/" \+ -H "Authorization: Bearer ${SENTRY_AUTH_TOKEN}" \+ -H "Content-Type: application/json" \+ -d '{+ "name": "Daily Report Generation",+ "slug": "daily-report-generation",+ "type": "cron_job",+ "config": {+ "schedule_type": "crontab",+ "schedule": "0 2 * * *",+ "checkin_margin": 10,+ "max_runtime": 30,+ "timezone": "UTC"+ }+ }'+```++---++## Alert Routing Best Practices++1. **Route by severity:** Critical alerts → PagerDuty / on-call. Warnings → Slack. Info → email digest.+2. **Set rate limits:** Use the `frequency` field (in minutes) to avoid alert fatigue — e.g., at most once per 30 minutes per issue.+3. **Use ownership rules:** Assign issues to teams based on file path or URL pattern so alerts go to the right people.+4. **Create environment-specific alerts:** Production alerts should have stricter thresholds and faster notification than staging.+5. **Review and tune regularly:** Audit alert rules monthly. Disable or tune noisy alerts. Add alerts for new critical paths.+6. **Use alert actions wisely:** Combine multiple actions (Slack + PagerDuty + assign issue) for critical alerts; use a single action (email) for low-priority alerts.diff --git a/sentry/skills/setup-sentry/SKILL.md b/sentry/skills/setup-sentry/SKILL.mdnew file mode 100644index 00000000..fef36355--- /dev/null+++ b/sentry/skills/setup-sentry/SKILL.md@@ -0,0 +1,378 @@+---+name: setup-sentry+description: Framework-specific Sentry setup for Next.js, React, Node.js, and Python with source maps and releases+---++# Skill: Set Up Sentry++Set up Sentry error monitoring and performance tracking in a project, with framework-specific guidance for Next.js, React, Node.js, and Python.++## Prerequisites++- A Sentry account and project (https://sentry.io)+- Your project's DSN (found in **Settings → Projects → [Project] → Client Keys**)+- A Sentry auth token for source-map uploads (found in **Settings → Auth Tokens**)++## Environment Variables++Set these in your `.env` file (and CI/CD secrets):++```bash+SENTRY_DSN=https://[email protected]/0+SENTRY_ORG=my-org+SENTRY_PROJECT=my-project+SENTRY_AUTH_TOKEN=sntrys_XXXXXXXX+SENTRY_ENVIRONMENT=production # or staging, development+SENTRY_RELEASE= # set automatically in CI, e.g. git SHA+```++---++## Next.js Setup++### 1. Install Dependencies++```bash+npx @sentry/wizard@latest -i nextjs+```++This automatically:+- Installs `@sentry/nextjs`+- Creates `sentry.client.config.ts`, `sentry.server.config.ts`, `sentry.edge.config.ts`+- Updates `next.config.js` with `withSentryConfig`+- Creates or updates `instrumentation.ts`++### 2. Configure the SDK++**`sentry.client.config.ts`**:+```ts+import * as Sentry from "@sentry/nextjs";++Sentry.init({+ dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,+ environment: process.env.NEXT_PUBLIC_SENTRY_ENVIRONMENT ?? "development",+ release: process.env.NEXT_PUBLIC_SENTRY_RELEASE,++ integrations: [+ Sentry.browserTracingIntegration(),+ Sentry.replayIntegration({+ maskAllText: true,+ blockAllMedia: true,+ }),+ ],++ tracesSampleRate: 0.2,+ replaysSessionSampleRate: 0.1,+ replaysOnErrorSampleRate: 1.0,+});+```++**`sentry.server.config.ts`**:+```ts+import * as Sentry from "@sentry/nextjs";++Sentry.init({+ dsn: process.env.SENTRY_DSN,+ environment: process.env.SENTRY_ENVIRONMENT ?? "development",+ release: process.env.SENTRY_RELEASE,+ tracesSampleRate: 0.2,+});+```++### 3. Source Maps++The `@sentry/nextjs` Webpack/Turbopack plugin handles source map upload automatically during `next build` when `SENTRY_AUTH_TOKEN`, `SENTRY_ORG`, and `SENTRY_PROJECT` are set.++```js+// next.config.js+const { withSentryConfig } = require("@sentry/nextjs");++module.exports = withSentryConfig(nextConfig, {+ org: process.env.SENTRY_ORG,+ project: process.env.SENTRY_PROJECT,+ silent: !process.env.CI,+ widenClientFileUpload: true,+ hideSourceMaps: true,+ disableLogger: true,+});+```++### 4. Error Boundary++Wrap your root layout with the Sentry error boundary:++```tsx+// app/global-error.tsx+"use client";+import * as Sentry from "@sentry/nextjs";+import { useEffect } from "react";++export default function GlobalError({+ error,+ reset,+}: {+ error: Error & { digest?: string };+ reset: () => void;+}) {+ useEffect(() => {+ Sentry.captureException(error);+ }, [error]);++ return (+ <html>+ <body>+ <h2>Something went wrong!</h2>+ <button onClick={() => reset()}>Try again</button>+ </body>+ </html>+ );+}+```++---++## React (Vite / CRA) Setup++### 1. Install Dependencies++```bash+npm install @sentry/react+# For source maps with Vite:+npm install @sentry/vite-plugin --save-dev+```++### 2. Initialize Sentry++```ts+// src/instrument.ts — import this FIRST in main.tsx+import * as Sentry from "@sentry/react";++Sentry.init({+ dsn: import.meta.env.VITE_SENTRY_DSN,+ environment: import.meta.env.VITE_SENTRY_ENVIRONMENT ?? "development",+ release: import.meta.env.VITE_SENTRY_RELEASE,+ integrations: [+ Sentry.browserTracingIntegration(),+ Sentry.replayIntegration(),+ ],+ tracesSampleRate: 0.2,+ replaysSessionSampleRate: 0.1,+ replaysOnErrorSampleRate: 1.0,+});+```++```tsx+// src/main.tsx+import "./instrument"; // MUST be first+import React from "react";+import ReactDOM from "react-dom/client";+import App from "./App";++ReactDOM.createRoot(document.getElementById("root")!).render(+ <React.StrictMode>+ <App />+ </React.StrictMode>+);+```++### 3. Error Boundary++```tsx+import * as Sentry from "@sentry/react";++function App() {+ return (+ <Sentry.ErrorBoundary fallback={<p>An error has occurred.</p>} showDialog>+ <Router />+ </Sentry.ErrorBoundary>+ );+}+```++### 4. Source Maps (Vite)++```ts+// vite.config.ts+import { defineConfig } from "vite";+import react from "@vitejs/plugin-react";+import { sentryVitePlugin } from "@sentry/vite-plugin";++export default defineConfig({+ build: { sourcemap: true },+ plugins: [+ react(),+ sentryVitePlugin({+ org: process.env.SENTRY_ORG,+ project: process.env.SENTRY_PROJECT,+ authToken: process.env.SENTRY_AUTH_TOKEN,+ }),+ ],+});+```++---++## Node.js (Express / Fastify) Setup++### 1. Install Dependencies++```bash+npm install @sentry/node @sentry/profiling-node+```++### 2. Initialize Sentry++```ts+// src/instrument.ts — import FIRST in your entry file+import * as Sentry from "@sentry/node";+import { nodeProfilingIntegration } from "@sentry/profiling-node";++Sentry.init({+ dsn: process.env.SENTRY_DSN,+ environment: process.env.NODE_ENV,+ release: process.env.SENTRY_RELEASE,+ integrations: [nodeProfilingIntegration()],+ tracesSampleRate: 0.2,+ profilesSampleRate: 0.1,+});+```++### 3. Express Integration++```ts+// src/app.ts+import "./instrument"; // MUST be first+import express from "express";+import * as Sentry from "@sentry/node";++const app = express();++// Routes+app.get("/api/health", (_req, res) => res.json({ status: "ok" }));+app.get("/api/users/:id", getUserHandler);++// Sentry error handler — MUST be after all routes and before other error handlers+Sentry.setupExpressErrorHandler(app);++// Fallback error handler+app.use((err, _req, res, _next) => {+ res.status(500).json({ error: "Internal Server Error" });+});++app.listen(3000);+```++### 4. Source Maps++Use `sentry-cli` in your build/deploy pipeline:++```bash+sentry-cli releases new "$SENTRY_RELEASE"+sentry-cli releases files "$SENTRY_RELEASE" upload-sourcemaps ./dist \+ --url-prefix "~/" \+ --rewrite+sentry-cli releases finalize "$SENTRY_RELEASE"+```++---++## Python (Django / Flask / FastAPI) Setup++### 1. Install Dependencies++```bash+pip install sentry-sdk+```++### 2. Django++```python+# settings.py+import sentry_sdk++sentry_sdk.init(+ dsn=os.environ.get("SENTRY_DSN"),+ environment=os.environ.get("SENTRY_ENVIRONMENT", "development"),+ release=os.environ.get("SENTRY_RELEASE"),+ traces_sample_rate=0.2,+ profiles_sample_rate=0.1,+ send_default_pii=False,+)+```++The Django integration is auto-enabled and instruments views, middleware, template rendering, and database queries.++### 3. Flask++```python+# app.py+import sentry_sdk+from flask import Flask++sentry_sdk.init(+ dsn=os.environ.get("SENTRY_DSN"),+ environment=os.environ.get("SENTRY_ENVIRONMENT", "development"),+ release=os.environ.get("SENTRY_RELEASE"),+ traces_sample_rate=0.2,+)++app = Flask(__name__)+```++### 4. FastAPI++```python+# main.py+import sentry_sdk+from fastapi import FastAPI++sentry_sdk.init(+ dsn=os.environ.get("SENTRY_DSN"),+ environment=os.environ.get("SENTRY_ENVIRONMENT", "development"),+ release=os.environ.get("SENTRY_RELEASE"),+ traces_sample_rate=0.2,+ profiles_sample_rate=0.1,+)++app = FastAPI()+```++---++## Releases and Environments++### Creating a Release++```bash+export SENTRY_RELEASE=$(git rev-parse --short HEAD)++sentry-cli releases new "$SENTRY_RELEASE"+sentry-cli releases set-commits "$SENTRY_RELEASE" --auto+sentry-cli releases files "$SENTRY_RELEASE" upload-sourcemaps ./dist+sentry-cli releases finalize "$SENTRY_RELEASE"+sentry-cli releases deploys "$SENTRY_RELEASE" new \+ --env "$SENTRY_ENVIRONMENT" \+ --name "deploy-$(date +%s)"+```++### Environment Best Practices++- Use consistent environment names across all projects: `production`, `staging`, `development`.+- Set the environment in `Sentry.init()` and when creating deploys.+- Use Sentry's environment filter in the Issues and Performance dashboards to focus on the right data.++---++## Verification Checklist++After setup, verify everything works:++1. **Trigger a test error:**+ ```ts+ // Temporarily add to a route or page+ Sentry.captureException(new Error("Sentry setup verification"));+ ```+2. **Check Sentry dashboard** — The test error should appear within 30 seconds.+3. **Verify source maps** — The stack trace should show your original source code, not minified bundles.+4. **Check performance** — Navigate your app and verify transactions appear in the Performance dashboard.+5. **Remove the test error** after verification.diff --git a/slack/.cursor-plugin/plugin.json b/slack/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..667ec26f--- /dev/null+++ b/slack/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "slack",+ "version": "1.0.0",+ "description": "Cursor plugin for Slack \u2014 Bolt framework, Block Kit, Events API, and Slack app development",+ "author": {+ "name": "Cursor",+ "email": "[email protected]"+ },+ "homepage": "https://github.com/cursor/plugins",+ "repository": "https://github.com/cursor/plugins",+ "license": "MIT",+ "keywords": [+ "slack",+ "bolt",+ "block-kit",+ "chatbot",+ "integrations"+ ],+ "category": "saas",+ "tags": [+ "messaging",+ "chatbot",+ "collaboration"+ ],+ "logo": "./slack.svg",+ "skills": "./skills/",+ "mcpServers": "./mcp.json"+}diff --git a/slack/CHANGELOG.md b/slack/CHANGELOG.mdnew file mode 100644index 00000000..5f2859de--- /dev/null+++ b/slack/CHANGELOG.md@@ -0,0 +1,13 @@+# Changelog++All notable changes to this plugin will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [Unreleased]++## [1.0.0] - 2026-02-07++### Added+- Initial plugin with skills and MCP server configurationdiff --git a/slack/LICENSE b/slack/LICENSEnew file mode 100644index 00000000..ca2bba77--- /dev/null+++ b/slack/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Cursor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/slack/README.md b/slack/README.mdnew file mode 100644index 00000000..27856519--- /dev/null+++ b/slack/README.md@@ -0,0 +1,28 @@+# Slack Plugin++Cursor plugin for Slack — Bolt framework, Block Kit, Events API, and Slack app development.++## Installation++```bash+agent install slack+```++## Components++### Skills++| Skill | Description |+|:------|:------------|+| `create-slack-bot` | End-to-end bot setup with event listeners, interactive components, and deployment |+| `setup-slash-commands` | Slash command handlers with subcommand routing, modals, and deferred responses |++### MCP Server++Provides Slack API access via `@anthropic/mcp-server-slack`.++Requires `SLACK_BOT_TOKEN` and `SLACK_APP_TOKEN` environment variables.++## License++MITdiff --git a/slack/mcp.json b/slack/mcp.jsonnew file mode 100644index 00000000..55813617--- /dev/null+++ b/slack/mcp.json@@ -0,0 +1,28 @@+{+ "$schema": "https://cursor.com/schemas/mcp.json",+ "mcpServers": {+ "slack": {+ "command": "npx",+ "args": [+ "-y",+ "@anthropic/mcp-server-slack"+ ],+ "env": {+ "SLACK_BOT_TOKEN": "${SLACK_BOT_TOKEN}",+ "SLACK_TEAM_ID": "${SLACK_TEAM_ID}"+ },+ "description": "MCP server providing access to the Slack API for messaging, channel management, user lookup, and workspace operations",+ "capabilities": [+ "list_channels — List public and private channels in the workspace",+ "post_message — Post a message to a channel or DM",+ "reply_to_thread — Reply to a specific message thread",+ "add_reaction — Add an emoji reaction to a message",+ "get_channel_history — Retrieve recent messages from a channel",+ "get_thread_replies — Get all replies in a message thread",+ "get_users — List users in the workspace",+ "get_user_profile — Get detailed profile info for a user",+ "search_messages — Search for messages across the workspace"+ ]+ }+ }+}diff --git a/slack/skills/create-slack-bot/SKILL.md b/slack/skills/create-slack-bot/SKILL.mdnew file mode 100644index 00000000..6ba4d230--- /dev/null+++ b/slack/skills/create-slack-bot/SKILL.md@@ -0,0 +1,467 @@+---+name: create-slack-bot+description: End-to-end Slack bot setup with event listeners, interactive components, and deployment+---++# Skill: Create a Slack Bot++## When to Use++Use this skill when the user wants to:++- Create a new Slack bot from scratch using the Bolt framework+- Set up a bot that responds to messages, mentions, or reactions+- Build a conversational bot with interactive components+- Add a bot to an existing project with proper project structure++## Prerequisites++- A Slack workspace where you have permission to install apps+- Node.js 18+ installed+- A Slack App created at https://api.slack.com/apps (or willingness to create one)++## Step 1 — Create the Slack App in the Dashboard++1. Go to [https://api.slack.com/apps](https://api.slack.com/apps) and click **Create New App**.+2. Choose **From scratch**. Enter a name and select the workspace.+3. Navigate to **OAuth & Permissions** and add these Bot Token Scopes:+ - `app_mentions:read` — receive `@bot` mentions+ - `chat:write` — send messages+ - `commands` — handle slash commands (optional)+ - `im:history` — read DM history (for DM bots)+ - `reactions:read` — track emoji reactions (optional)+4. Navigate to **Socket Mode** and enable it. Create an App-Level Token with the `connections:write` scope. Save the token (`xapp-1-...`).+5. Navigate to **Event Subscriptions**, enable events, and subscribe to:+ - `app_mention` — bot is @mentioned+ - `message.im` — direct messages to the bot (optional)+6. Install the app to your workspace. Copy the **Bot User OAuth Token** (`xoxb-...`).++## Step 2 — Scaffold the Project++```bash+mkdir my-slack-bot && cd my-slack-bot+npm init -y+npm install @slack/bolt dotenv+npm install -D typescript @types/node ts-node nodemon+```++Create the TypeScript configuration:++```json+// tsconfig.json+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "commonjs",+ "outDir": "./dist",+ "rootDir": "./src",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true+ },+ "include": ["src/**/*"]+}+```++Set up environment variables:++```bash+# .env+SLACK_BOT_TOKEN=xoxb-your-bot-token+SLACK_SIGNING_SECRET=your-signing-secret+SLACK_APP_TOKEN=xapp-1-your-app-level-token+```++Add `.env` to `.gitignore`:++```+# .gitignore+node_modules/+dist/+.env+```++## Step 3 — Write the Bot++```typescript+// src/app.ts+import { App, LogLevel } from "@slack/bolt";+import "dotenv/config";++const app = new App({+ token: process.env.SLACK_BOT_TOKEN!,+ signingSecret: process.env.SLACK_SIGNING_SECRET!,+ appToken: process.env.SLACK_APP_TOKEN!,+ socketMode: true,+ logLevel: LogLevel.INFO,+});++// ─── Respond to @mentions ──────────────────────────────────────────────────────++app.event("app_mention", async ({ event, say, logger }) => {+ try {+ const text = event.text.replace(/<@[A-Z0-9]+>/g, "").trim();++ if (!text) {+ await say({+ blocks: [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `Hey <@${event.user}>! 👋 Here's what I can do:`,+ },+ },+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: "• Mention me with `help` for available commands\n• Mention me with `status` for a system check\n• Send me a DM to chat privately",+ },+ },+ ],+ text: `Hey <@${event.user}>! Here's what I can do.`,+ });+ return;+ }++ if (text.toLowerCase() === "help") {+ await say({+ blocks: [+ {+ type: "header",+ text: { type: "plain_text", text: "📖 Help" },+ },+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: "*Available commands:*\n• `@bot help` — Show this message\n• `@bot status` — Check system status\n• `@bot greet <name>` — Send a greeting",+ },+ },+ ],+ text: "Help — Available commands",+ });+ } else if (text.toLowerCase() === "status") {+ await say({+ blocks: [+ {+ type: "header",+ text: { type: "plain_text", text: "🟢 System Status" },+ },+ {+ type: "section",+ fields: [+ { type: "mrkdwn", text: `*Uptime:*\n${formatUptime(process.uptime())}` },+ { type: "mrkdwn", text: `*Memory:*\n${Math.round(process.memoryUsage().heapUsed / 1024 / 1024)} MB` },+ { type: "mrkdwn", text: `*Node:*\n${process.version}` },+ { type: "mrkdwn", text: `*Platform:*\n${process.platform}` },+ ],+ },+ ],+ text: "System Status — All systems operational",+ });+ } else if (text.toLowerCase().startsWith("greet ")) {+ const name = text.slice(6).trim();+ await say(`Hello, ${name}! 👋 Welcome to the channel.`);+ } else {+ await say(`I didn't understand that. Try mentioning me with \`help\` for available commands.`);+ }+ } catch (error) {+ logger.error("Error handling app_mention", error);+ await say("Sorry, something went wrong. Please try again.");+ }+});++// ─── Handle Direct Messages ────────────────────────────────────────────────────++app.message(async ({ message, say, logger }) => {+ try {+ // Only handle standard user messages (not bot messages, not edits)+ if (message.subtype) return;+ if (!("text" in message) || !message.text) return;++ await say({+ blocks: [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `Thanks for the message! You said: _${message.text}_`,+ },+ },+ {+ type: "actions",+ elements: [+ {+ type: "button",+ text: { type: "plain_text", text: "👍 Helpful" },+ action_id: "feedback_helpful",+ style: "primary",+ },+ {+ type: "button",+ text: { type: "plain_text", text: "👎 Not Helpful" },+ action_id: "feedback_not_helpful",+ },+ ],+ },+ ],+ text: `Thanks for the message! You said: ${message.text}`,+ });+ } catch (error) {+ logger.error("Error handling message", error);+ }+});++// ─── Handle Button Clicks ──────────────────────────────────────────────────────++app.action("feedback_helpful", async ({ ack, say }) => {+ await ack();+ await say("Glad I could help! 🎉");+});++app.action("feedback_not_helpful", async ({ ack, say }) => {+ await ack();+ await say("Sorry about that. I'll try to do better! 🙏");+});++// ─── Handle Reactions ──────────────────────────────────────────────────────────++app.event("reaction_added", async ({ event, client, logger }) => {+ try {+ if (event.reaction === "eyes") {+ await client.reactions.add({+ channel: event.item.channel,+ timestamp: event.item.ts,+ name: "white_check_mark",+ });+ }+ } catch (error) {+ logger.error("Error handling reaction", error);+ }+});++// ─── App Home Tab ──────────────────────────────────────────────────────────────++app.event("app_home_opened", async ({ event, client, logger }) => {+ try {+ await client.views.publish({+ user_id: event.user,+ view: {+ type: "home",+ blocks: [+ {+ type: "header",+ text: { type: "plain_text", text: "🏠 Welcome Home" },+ },+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: "I'm your friendly Slack bot. Here's a quick overview of what I can do.",+ },+ },+ { type: "divider" },+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: "*💬 Mention me*\nMention me in any channel with a command like `help` or `status`.",+ },+ },+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: "*📩 Direct Message*\nSend me a DM and I'll respond with helpful information.",+ },+ },+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: "*👀 Reactions*\nAdd the :eyes: reaction to any message and I'll mark it as reviewed.",+ },+ },+ ],+ },+ });+ } catch (error) {+ logger.error("Error publishing App Home", error);+ }+});++// ─── Utilities ─────────────────────────────────────────────────────────────────++function formatUptime(seconds: number): string {+ const d = Math.floor(seconds / 86400);+ const h = Math.floor((seconds % 86400) / 3600);+ const m = Math.floor((seconds % 3600) / 60);+ const s = Math.floor(seconds % 60);+ const parts: string[] = [];+ if (d > 0) parts.push(`${d}d`);+ if (h > 0) parts.push(`${h}h`);+ if (m > 0) parts.push(`${m}m`);+ parts.push(`${s}s`);+ return parts.join(" ");+}++// ─── Start ─────────────────────────────────────────────────────────────────────++(async () => {+ await app.start();+ console.log("⚡️ Slack bot is running in Socket Mode!");+})();+```++## Step 4 — Add Development Scripts++Add these scripts to `package.json`:++```json+{+ "scripts": {+ "build": "tsc",+ "start": "node dist/app.js",+ "dev": "nodemon --exec ts-node src/app.ts --ext ts",+ "lint": "eslint src/"+ }+}+```++## Step 5 — Run and Test Locally++```bash+# Start in development mode+npm run dev+```++Test your bot:++1. Open Slack and navigate to a channel where the bot is a member.+2. Type `@YourBot help` — you should see the help message with Block Kit formatting.+3. Type `@YourBot status` — you should see system status with uptime and memory usage.+4. Send a direct message to the bot — you should receive a response with feedback buttons.+5. Click the "Helpful" or "Not Helpful" button — you should see a follow-up message.+6. Add the 👀 (`:eyes:`) reaction to any message — the bot should add a ✅ reaction.+7. Click on the bot's name and go to the **Home** tab — you should see the App Home content.++## Step 6 — Deploy to Production++### Option A: Deploy to Railway / Render / Fly.io++Switch from Socket Mode to HTTP mode for production:++```typescript+// src/app.ts — production configuration+const isProduction = process.env.NODE_ENV === "production";++const app = new App({+ token: process.env.SLACK_BOT_TOKEN!,+ signingSecret: process.env.SLACK_SIGNING_SECRET!,+ ...(isProduction+ ? { /* HTTP mode — no socketMode, no appToken */ }+ : {+ appToken: process.env.SLACK_APP_TOKEN!,+ socketMode: true,+ }),+});++(async () => {+ const port = Number(process.env.PORT) || 3000;+ await app.start(port);+ console.log(`⚡️ Slack bot is running on port ${port}`);+})();+```++Update the Slack App dashboard:+1. Go to **Event Subscriptions** → set the Request URL to `https://your-app.example.com/slack/events`.+2. Go to **Interactivity & Shortcuts** → set the Request URL to `https://your-app.example.com/slack/events`.++### Option B: Deploy to AWS Lambda++```bash+npm install @slack/bolt aws-lambda serverless-http+```++```typescript+// src/lambda.ts+import { App, AwsLambdaReceiver } from "@slack/bolt";++const awsLambdaReceiver = new AwsLambdaReceiver({+ signingSecret: process.env.SLACK_SIGNING_SECRET!,+});++const app = new App({+ token: process.env.SLACK_BOT_TOKEN!,+ receiver: awsLambdaReceiver,+});++// Register listeners...++export const handler = async (event: any, context: any, callback: any) => {+ const handler = await awsLambdaReceiver.start();+ return handler(event, context, callback);+};+```++## Project Structure++```+my-slack-bot/+├── src/+│ └── app.ts # Main bot application+├── dist/ # Compiled JavaScript (gitignored)+├── .env # Environment variables (gitignored)+├── .gitignore+├── package.json+├── tsconfig.json+└── README.md+```++## Common Patterns++### Responding in a Thread++```typescript+app.event("app_mention", async ({ event, say }) => {+ await say({+ text: "Here's my response in the thread!",+ thread_ts: event.ts, // Reply in thread+ });+});+```++### Sending an Ephemeral Message++```typescript+app.command("/secret", async ({ ack, command, client }) => {+ await ack();+ await client.chat.postEphemeral({+ channel: command.channel_id,+ user: command.user_id,+ text: "This message is only visible to you.",+ });+});+```++### Scheduled Messages++```typescript+await client.chat.scheduleMessage({+ channel: "C12345678",+ text: "Reminder: standup in 5 minutes!",+ post_at: Math.floor(Date.now() / 1000) + 300, // 5 minutes from now+});+```++## Available Tools++- `@slack/bolt` — The official Slack framework for building apps.+- `@slack/web-api` — Low-level Slack Web API client (bundled with Bolt).+- `ngrok` — Expose local server for HTTP mode testing: `ngrok http 3000`.+- Block Kit Builder — https://app.slack.com/block-kit-builder for designing messages.+- Slack CLI — https://api.slack.com/automation/cli for next-gen platform apps.diff --git a/slack/skills/setup-slash-commands/SKILL.md b/slack/skills/setup-slash-commands/SKILL.mdnew file mode 100644index 00000000..52abedf9--- /dev/null+++ b/slack/skills/setup-slash-commands/SKILL.md@@ -0,0 +1,478 @@+---+name: setup-slash-commands+description: Slash command handlers with subcommand routing, modals, and deferred responses+---++# Skill: Set Up Slash Commands++## When to Use++Use this skill when the user wants to:++- Add slash commands to an existing Slack app+- Build a command-driven bot with argument parsing and subcommands+- Implement slash commands that open modals for data entry+- Create commands with deferred responses for long-running operations++## Prerequisites++- An existing Slack app with the `commands` scope (see **create-slack-bot** skill for initial setup)+- `@slack/bolt` installed in the project+- The Slack App dashboard configured with Interactivity enabled++## Step 1 — Register the Command in the Slack Dashboard++1. Go to [https://api.slack.com/apps](https://api.slack.com/apps) and select your app.+2. Navigate to **Slash Commands** → **Create New Command**.+3. Fill in the details:+ - **Command**: `/deploy` (example)+ - **Request URL**: `https://your-app.example.com/slack/events` (or leave blank for Socket Mode)+ - **Short Description**: "Deploy a service to an environment"+ - **Usage Hint**: `[service] [environment]`+4. Save the command.+5. Reinstall the app to your workspace so the new command is registered.++## Step 2 — Implement a Basic Slash Command++```typescript+// src/commands/deploy.ts+import { App } from "@slack/bolt";++export function registerDeployCommand(app: App): void {+ app.command("/deploy", async ({ ack, command, say, client, logger }) => {+ await ack(); // Always ack first++ const args = command.text.trim().split(/\s+/);+ const service = args[0];+ const environment = args[1] || "staging";++ // Validate input+ if (!service) {+ await client.chat.postEphemeral({+ channel: command.channel_id,+ user: command.user_id,+ text: "Usage: `/deploy <service> [environment]`\nExample: `/deploy api production`",+ });+ return;+ }++ const validEnvironments = ["staging", "production", "development"];+ if (!validEnvironments.includes(environment)) {+ await client.chat.postEphemeral({+ channel: command.channel_id,+ user: command.user_id,+ text: `Invalid environment \`${environment}\`. Must be one of: ${validEnvironments.join(", ")}`,+ });+ return;+ }++ // Post a visible message to the channel+ await say({+ blocks: [+ {+ type: "header",+ text: { type: "plain_text", text: "🚀 Deployment Started" },+ },+ {+ type: "section",+ fields: [+ { type: "mrkdwn", text: `*Service:*\n\`${service}\`` },+ { type: "mrkdwn", text: `*Environment:*\n\`${environment}\`` },+ { type: "mrkdwn", text: `*Triggered by:*\n<@${command.user_id}>` },+ { type: "mrkdwn", text: `*Status:*\n⏳ In progress…` },+ ],+ },+ ],+ text: `Deployment of ${service} to ${environment} started by <@${command.user_id}>`,+ });+ });+}+```++## Step 3 — Add Subcommand Routing++For commands with multiple subcommands, use a router pattern:++```typescript+// src/commands/ticket.ts+import { App, SlashCommand } from "@slack/bolt";++type SubcommandHandler = (params: {+ command: SlashCommand;+ args: string[];+ client: any;+ say: any;+}) => Promise<void>;++const subcommands: Record<string, SubcommandHandler> = {+ create: async ({ command, client }) => {+ // Open a modal for ticket creation+ await client.views.open({+ trigger_id: command.trigger_id,+ view: {+ type: "modal",+ callback_id: "create_ticket_modal",+ title: { type: "plain_text", text: "Create Ticket" },+ submit: { type: "plain_text", text: "Create" },+ blocks: [+ {+ type: "input",+ block_id: "title_block",+ label: { type: "plain_text", text: "Title" },+ element: {+ type: "plain_text_input",+ action_id: "title_input",+ placeholder: { type: "plain_text", text: "Brief description of the issue" },+ },+ },+ {+ type: "input",+ block_id: "priority_block",+ label: { type: "plain_text", text: "Priority" },+ element: {+ type: "static_select",+ action_id: "priority_select",+ options: [+ { text: { type: "plain_text", text: "🔴 Critical" }, value: "critical" },+ { text: { type: "plain_text", text: "🟠 High" }, value: "high" },+ { text: { type: "plain_text", text: "🟡 Medium" }, value: "medium" },+ { text: { type: "plain_text", text: "🟢 Low" }, value: "low" },+ ],+ },+ },+ {+ type: "input",+ block_id: "description_block",+ label: { type: "plain_text", text: "Description" },+ element: {+ type: "plain_text_input",+ action_id: "description_input",+ multiline: true,+ placeholder: { type: "plain_text", text: "Detailed description…" },+ },+ optional: true,+ },+ ],+ },+ });+ },++ list: async ({ args, say }) => {+ const status = args[0] || "open";+ const tickets = await fetchTickets({ status });++ if (tickets.length === 0) {+ await say(`No ${status} tickets found.`);+ return;+ }++ const ticketBlocks = tickets.slice(0, 10).map((ticket) => ({+ type: "section" as const,+ text: {+ type: "mrkdwn" as const,+ text: `*<${ticket.url}|${ticket.id}>*: ${ticket.title}\n_${ticket.priority} · ${ticket.status} · assigned to <@${ticket.assignee}>_`,+ },+ }));++ await say({+ blocks: [+ {+ type: "header",+ text: { type: "plain_text", text: `📋 ${status.charAt(0).toUpperCase() + status.slice(1)} Tickets` },+ },+ ...ticketBlocks,+ {+ type: "context",+ elements: [+ {+ type: "mrkdwn",+ text: `Showing ${Math.min(tickets.length, 10)} of ${tickets.length} tickets`,+ },+ ],+ },+ ],+ text: `${tickets.length} ${status} tickets`,+ });+ },++ assign: async ({ args, say }) => {+ const ticketId = args[0];+ const userId = args[1]?.replace(/[<@>]/g, "");++ if (!ticketId || !userId) {+ await say("Usage: `/ticket assign <ticket-id> @user`");+ return;+ }++ await assignTicket(ticketId, userId);+ await say(`Ticket \`${ticketId}\` assigned to <@${userId}> ✓`);+ },+};++export function registerTicketCommand(app: App): void {+ app.command("/ticket", async ({ ack, command, say, client, logger }) => {+ await ack();++ const [subcommand, ...args] = command.text.trim().split(/\s+/);++ if (!subcommand || !subcommands[subcommand]) {+ await client.chat.postEphemeral({+ channel: command.channel_id,+ user: command.user_id,+ text: [+ "*Available subcommands:*",+ "• `/ticket create` — Create a new ticket (opens a form)",+ "• `/ticket list [status]` — List tickets (default: open)",+ "• `/ticket assign <id> @user` — Assign a ticket",+ ].join("\n"),+ });+ return;+ }++ try {+ await subcommands[subcommand]({ command, args, client, say });+ } catch (error) {+ logger.error(`Error in /ticket ${subcommand}`, error);+ await client.chat.postEphemeral({+ channel: command.channel_id,+ user: command.user_id,+ text: `Something went wrong with \`/ticket ${subcommand}\`. Please try again.`,+ });+ }+ });+}++// Placeholder functions — replace with your actual implementation+async function fetchTickets(filter: { status: string }): Promise<any[]> {+ return [];+}++async function assignTicket(ticketId: string, userId: string): Promise<void> {+ // Implementation+}+```++## Step 4 — Handle Modal Submissions++When a slash command opens a modal, handle the submission in a separate view listener:++```typescript+// src/views/create-ticket.ts+import { App } from "@slack/bolt";++export function registerTicketViews(app: App): void {+ app.view("create_ticket_modal", async ({ ack, view, body, client, logger }) => {+ const values = view.state.values;+ const title = values.title_block.title_input.value!;+ const priority = values.priority_block.priority_select.selected_option!.value;+ const description = values.description_block?.description_input?.value || "";++ // Validate+ const errors: Record<string, string> = {};+ if (title.length < 5) {+ errors.title_block = "Title must be at least 5 characters";+ }+ if (title.length > 200) {+ errors.title_block = "Title must be under 200 characters";+ }++ if (Object.keys(errors).length > 0) {+ await ack({ response_action: "errors", errors });+ return;+ }++ await ack();++ try {+ const ticket = await createTicket({ title, priority, description, createdBy: body.user.id });++ // Notify the user in DM+ await client.chat.postMessage({+ channel: body.user.id,+ blocks: [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `✅ Ticket *<${ticket.url}|${ticket.id}>* created successfully!\n*Title:* ${title}\n*Priority:* ${priority}`,+ },+ },+ ],+ text: `Ticket ${ticket.id} created: ${title}`,+ });+ } catch (error) {+ logger.error("Error creating ticket", error);+ await client.chat.postMessage({+ channel: body.user.id,+ text: "Sorry, there was an error creating your ticket. Please try again.",+ });+ }+ });+}++// Placeholder — replace with your actual implementation+async function createTicket(data: {+ title: string;+ priority: string;+ description: string;+ createdBy: string;+}): Promise<{ id: string; url: string }> {+ return { id: "TICK-001", url: "https://example.com/tickets/TICK-001" };+}+```++## Step 5 — Handle Deferred Responses for Long Operations++When a command triggers a long-running operation (> 3 seconds), acknowledge immediately and send follow-up updates using `response_url` or `chat.postMessage`.++```typescript+// src/commands/report.ts+import { App } from "@slack/bolt";++export function registerReportCommand(app: App): void {+ app.command("/report", async ({ ack, command, client, respond, logger }) => {+ // Acknowledge immediately with a loading message+ await ack({+ response_type: "ephemeral",+ text: "⏳ Generating your report… This may take a moment.",+ });++ try {+ // Long-running operation+ const report = await generateReport(command.text);++ // Send the result using respond() (uses response_url)+ await respond({+ response_type: "in_channel",+ replace_original: false,+ blocks: [+ {+ type: "header",+ text: { type: "plain_text", text: "📊 Report Generated" },+ },+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: `*Period:* ${report.period}\n*Total:* ${report.total}\n*Average:* ${report.average}`,+ },+ },+ {+ type: "actions",+ elements: [+ {+ type: "button",+ text: { type: "plain_text", text: "Download CSV" },+ url: report.csvUrl,+ action_id: "download_report",+ },+ ],+ },+ ],+ text: `Report generated: ${report.period}`,+ });+ } catch (error) {+ logger.error("Error generating report", error);+ await respond({+ response_type: "ephemeral",+ replace_original: true,+ text: "❌ Failed to generate the report. Please try again.",+ });+ }+ });+}++// Placeholder — replace with your actual implementation+async function generateReport(query: string): Promise<{+ period: string;+ total: number;+ average: number;+ csvUrl: string;+}> {+ await new Promise((r) => setTimeout(r, 5000)); // Simulate long operation+ return {+ period: "Last 30 days",+ total: 1234,+ average: 41.1,+ csvUrl: "https://example.com/reports/latest.csv",+ };+}+```++## Step 6 — Wire Everything Together++```typescript+// src/app.ts+import { App, LogLevel } from "@slack/bolt";+import "dotenv/config";+import { registerDeployCommand } from "./commands/deploy";+import { registerTicketCommand } from "./commands/ticket";+import { registerReportCommand } from "./commands/report";+import { registerTicketViews } from "./views/create-ticket";++const app = new App({+ token: process.env.SLACK_BOT_TOKEN!,+ signingSecret: process.env.SLACK_SIGNING_SECRET!,+ appToken: process.env.SLACK_APP_TOKEN!,+ socketMode: true,+ logLevel: LogLevel.INFO,+});++// Register commands+registerDeployCommand(app);+registerTicketCommand(app);+registerReportCommand(app);++// Register view handlers+registerTicketViews(app);++(async () => {+ await app.start();+ console.log("⚡️ Slack app with slash commands is running!");+})();+```++## Step 7 — Test Locally++1. Start the app: `npm run dev`+2. In Slack, type `/deploy api production` — you should see a deployment message.+3. Type `/deploy` with no arguments — you should see an ephemeral usage hint.+4. Type `/ticket create` — a modal should open for ticket creation.+5. Type `/ticket list` — you should see a list of tickets (or "no tickets" message).+6. Type `/report monthly` — you should see a loading message, then the report.++## Project Structure++```+my-slack-bot/+├── src/+│ ├── app.ts # Entry point — registers all handlers+│ ├── commands/+│ │ ├── deploy.ts # /deploy command handler+│ │ ├── ticket.ts # /ticket command with subcommands+│ │ └── report.ts # /report command with deferred response+│ └── views/+│ └── create-ticket.ts # Modal submission handler+├── dist/+├── .env+├── package.json+└── tsconfig.json+```++## Best Practices Summary++- **Always `await ack()`** before any other work in a command handler.+- **Use ephemeral messages** for errors, validation feedback, and help text so they don't clutter the channel.+- **Open modals** for multi-field input instead of parsing complex command text.+- **Use `respond()`** (via `response_url`) for deferred follow-ups to slash commands.+- **Validate early** — check arguments before doing any work.+- **Route subcommands** with a map/object pattern for clean separation of concerns.+- **Handle errors gracefully** — always catch and notify the user.+- **Use Block Kit** for rich, structured responses instead of plain text.++## Available Tools++- `@slack/bolt` — Slash command handling, modal triggers, and response management.+- Block Kit Builder — https://app.slack.com/block-kit-builder for designing responses.+- `ngrok` — Expose local server for HTTP mode testing: `ngrok http 3000`.+- Slack CLI — https://api.slack.com/automation/cli for next-gen slash commands.diff --git a/slack/slack.svg b/slack/slack.svgnew file mode 100644index 00000000..acae73d6--- /dev/null+++ b/slack/slack.svg@@ -0,0 +1 @@+<svg width="64" height="64" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Slack</title><path d="M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313zM8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312zM18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zM17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312zM15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zM15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z"/></svg>diff --git a/solidity-web3/.cursor-plugin/plugin.json b/solidity-web3/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..6f6ef667--- /dev/null+++ b/solidity-web3/.cursor-plugin/plugin.json@@ -0,0 +1,24 @@+{+ "name": "solidity-web3",+ "version": "1.0.0",+ "description": "Solidity smart contract security and development best practices by Alfredo Bonilla (cursor.directory)",+ "author": {+ "name": "Alfredo Bonilla",+ "url": "https://cursor.directory/solidity-development-best-practices"+ },+ "homepage": "https://cursor.directory/solidity-development-best-practices",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "solidity",+ "ethereum",+ "smart-contracts",+ "web3",+ "openzeppelin"+ ],+ "category": "blockchain",+ "tags": [+ "OpenZeppelin"+ ],+ "rules": "./rules/"+}diff --git a/solidity-web3/README.md b/solidity-web3/README.mdnew file mode 100644index 00000000..8c500726--- /dev/null+++ b/solidity-web3/README.md@@ -0,0 +1,29 @@+# solidity-web3++Solidity smart contract security and development best practices by Alfredo Bonilla (cursor.directory)++## Installation++```bash+agent install solidity-web3+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `solidity_web3` | Solidity smart contract development with security best practices | `**/*.sol, **/hardhat.config.*, **/foundry.toml` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/solidity-development-best-practices).++- **Original Author**: Alfredo Bonilla+- **Tags**: OpenZeppelin+- **Category**: blockchain++## License++MITdiff --git a/solidity-web3/rules/solidity_web3.mdc b/solidity-web3/rules/solidity_web3.mdcnew file mode 100644index 00000000..d1825c4f--- /dev/null+++ b/solidity-web3/rules/solidity_web3.mdc@@ -0,0 +1,91 @@+---+description: Solidity smart contract development with security best practices+globs:+ - "**/*.sol"+ - "**/hardhat.config.*"+ - "**/foundry.toml"+alwaysApply: false+---++You are an expert in Solidity and smart contract security.++General Rules+- Cut the fluff. Code or detailed explanations only.+- Keep it casual and brief.+- Accuracy and depth matter.+- Answer first, explain later if needed.+- Logic trumps authority. Don't care about sources.+- Embrace new tech and unconventional ideas.+- Wild speculation's fine, just flag it.+- Save the ethics talk.+- Only mention safety for non-obvious, critical issues.+- Push content limits if needed, explain after.+- Sources at the end, not mid-text.+- Skip the AI self-references and knowledge date stuff.+- Stick to my code style.+- Use multiple responses for complex answers.+- For code tweaks, show minimal context - a few lines around changes max.+- Don't be lazy, write all the code to implement features I ask for.++Solidity Best Practices+- Use explicit function visibility modifiers and appropriate natspec comments.+- Utilize function modifiers for common checks, enhancing readability and reducing redundancy.+- Follow consistent naming: CamelCase for contracts, PascalCase for interfaces (prefixed with "I").+- Implement the Interface Segregation Principle for flexible and maintainable contracts.+- Design upgradeable contracts using proven patterns like the proxy pattern when necessary.+- Implement comprehensive events for all significant state changes.+- Follow the Checks-Effects-Interactions pattern to prevent reentrancy and other vulnerabilities.+- Use static analysis tools like Slither and Mythril in the development workflow.+- Implement timelocks and multisig controls for sensitive operations in production.+- Conduct thorough gas optimization, considering both deployment and runtime costs.+- Use OpenZeppelin's AccessControl for fine-grained permissions.+- Use Solidity 0.8.0+ for built-in overflow/underflow protection.+- Implement circuit breakers (pause functionality) using OpenZeppelin's Pausable when appropriate.+- Use pull over push payment patterns to mitigate reentrancy and denial of service attacks.+- Implement rate limiting for sensitive functions to prevent abuse.+- Use OpenZeppelin's SafeERC20 for interacting with ERC20 tokens.+- Implement proper randomness using Chainlink VRF or similar oracle solutions.+- Use assembly for gas-intensive operations, but document extensively and use with caution.+- Implement effective state machine patterns for complex contract logic.+- Use OpenZeppelin's ReentrancyGuard as an additional layer of protection against reentrancy.+- Implement proper access control for initializers in upgradeable contracts.+- Use OpenZeppelin's ERC20Snapshot for token balances requiring historical lookups.+- Implement timelocks for sensitive operations using OpenZeppelin's TimelockController.+- Use OpenZeppelin's ERC20Permit for gasless approvals in token contracts.+- Implement proper slippage protection for DEX-like functionalities.+- Use OpenZeppelin's ERC20Votes for governance token implementations.+- Implement effective storage patterns to optimize gas costs (e.g., packing variables).+- Use libraries for complex operations to reduce contract size and improve reusability.+- Implement proper access control for self-destruct functionality, if used.+- Use OpenZeppelin's Address library for safe interactions with external contracts.+- Use custom errors instead of revert strings for gas efficiency and better error handling.+- Implement NatSpec comments for all public and external functions.+- Use immutable variables for values set once at construction time.+- Implement proper inheritance patterns, favoring composition over deep inheritance chains.+- Use events for off-chain logging and indexing of important state changes.+- Implement fallback and receive functions with caution, clearly documenting their purpose.+- Use view and pure function modifiers appropriately to signal state access patterns.+- Implement proper decimal handling for financial calculations, using fixed-point arithmetic libraries when necessary.+- Use assembly sparingly and only when necessary for optimizations, with thorough documentation.+- Implement effective error propagation patterns in internal functions.++Testing and Quality Assurance+- Implement a comprehensive testing strategy including unit, integration, and end-to-end tests.+- Use property-based testing to uncover edge cases.+- Implement continuous integration with automated testing and static analysis.+- Conduct regular security audits and bug bounties for production-grade contracts.+- Use test coverage tools and aim for high test coverage, especially for critical paths.++Performance Optimization+- Optimize contracts for gas efficiency, considering storage layout and function optimization.+- Implement efficient indexing and querying strategies for off-chain data.++Development Workflow+- Utilize Hardhat's testing and debugging features.+- Implement a robust CI/CD pipeline for smart contract deployments.+- Use static type checking and linting tools in pre-commit hooks.++Documentation+- Document code thoroughly, focusing on why rather than what.+- Maintain up-to-date API documentation for smart contracts.+- Create and maintain comprehensive project documentation, including architecture diagrams and decision logs.diff --git a/sveltekit-development/.cursor-plugin/plugin.json b/sveltekit-development/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..f9cd4bba--- /dev/null+++ b/sveltekit-development/.cursor-plugin/plugin.json@@ -0,0 +1,27 @@+{+ "name": "sveltekit-development",+ "version": "1.0.0",+ "description": "Svelte 5 and SvelteKit modern web development guide by MMBytes (cursor.directory)",+ "author": {+ "name": "MMBytes",+ "url": "https://cursor.directory/svelte5-sveltekit-development-guide"+ },+ "homepage": "https://cursor.directory/svelte5-sveltekit-development-guide",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "svelte",+ "sveltekit",+ "typescript",+ "tailwind",+ "web"+ ],+ "category": "frontend",+ "tags": [+ "svelte",+ "sveltekit",+ "tailwind",+ "paraglide-js"+ ],+ "rules": "./rules/"+}diff --git a/sveltekit-development/README.md b/sveltekit-development/README.mdnew file mode 100644index 00000000..139c74ae--- /dev/null+++ b/sveltekit-development/README.md@@ -0,0 +1,29 @@+# sveltekit-development++Svelte 5 and SvelteKit modern web development guide by MMBytes (cursor.directory)++## Installation++```bash+agent install sveltekit-development+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `sveltekit_development` | Svelte 5 and SvelteKit development with TypeScript, runes, and modern patterns | `**/*.svelte, **/*.ts, **/svelte.config.*` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/svelte5-sveltekit-development-guide).++- **Original Author**: MMBytes+- **Tags**: svelte, sveltekit, tailwind, paraglide-js+- **Category**: frontend++## License++MITdiff --git a/sveltekit-development/rules/sveltekit_development.mdc b/sveltekit-development/rules/sveltekit_development.mdcnew file mode 100644index 00000000..da4ca8b4--- /dev/null+++ b/sveltekit-development/rules/sveltekit_development.mdc@@ -0,0 +1,223 @@+---+description: Svelte 5 and SvelteKit development with TypeScript, runes, and modern patterns+globs:+ - "**/*.svelte"+ - "**/*.ts"+ - "**/svelte.config.*"+alwaysApply: false+---++You are an expert in Svelte 5, SvelteKit, TypeScript, and modern web development.++Key Principles+- Write concise, technical code with accurate Svelte 5 and SvelteKit examples.+- Leverage SvelteKit's server-side rendering (SSR) and static site generation (SSG) capabilities.+- Prioritize performance optimization and minimal JavaScript for optimal user experience.+- Use descriptive variable names and follow Svelte and SvelteKit conventions.+- Organize files using SvelteKit's file-based routing system.++Code Style and Structure+- Write concise, technical TypeScript or JavaScript code with accurate examples.+- Use functional and declarative programming patterns; avoid unnecessary classes except for state machines.+- Prefer iteration and modularization over code duplication.+- Structure files: component logic, markup, styles, helpers, types.+- Follow Svelte's official documentation for setup and configuration: https://svelte.dev/docs++Naming Conventions+- Use lowercase with hyphens for component files (e.g., `components/auth-form.svelte`).+- Use PascalCase for component names in imports and usage.+- Use camelCase for variables, functions, and props.++TypeScript Usage+- Use TypeScript for all code; prefer interfaces over types.+- Avoid enums; use const objects instead.+- Use functional components with TypeScript interfaces for props.+- Enable strict mode in TypeScript for better type safety.++Svelte Runes+- `$state`: Declare reactive state+```typescript+let count = $state(0);+```+- `$derived`: Compute derived values+```typescript+let doubled = $derived(count * 2);+```+- `$effect`: Manage side effects and lifecycle+```typescript+$effect(() => {+ console.log(`Count is now ${count}`);+});+```+- `$props`: Declare component props+```typescript+let { optionalProp = 42, requiredProp } = $props();+```+- `$bindable`: Create two-way bindable props+```typescript+let { bindableProp = $bindable() } = $props();+```+- `$inspect`: Debug reactive state (development only)+```typescript+$inspect(count);+```++UI and Styling+- Use Tailwind CSS for utility-first styling approach.+- Leverage Shadcn components for pre-built, customizable UI elements.+- Import Shadcn components from `$lib/components/ui`.+- Organize Tailwind classes using the `cn()` utility from `$lib/utils`.+- Use Svelte's built-in transition and animation features.++Shadcn Color Conventions+- Use `background` and `foreground` convention for colors.+- Define CSS variables without color space function:+```css+--primary: 222.2 47.4% 11.2%;+--primary-foreground: 210 40% 98%;+```+- Usage example:+```svelte+<div class="bg-primary text-primary-foreground">Hello</div>+```+- Key color variables:+- `--background`, `--foreground`: Default body colors+- `--muted`, `--muted-foreground`: Muted backgrounds+- `--card`, `--card-foreground`: Card backgrounds+- `--popover`, `--popover-foreground`: Popover backgrounds+- `--border`: Default border color+- `--input`: Input border color+- `--primary`, `--primary-foreground`: Primary button colors+- `--secondary`, `--secondary-foreground`: Secondary button colors+- `--accent`, `--accent-foreground`: Accent colors+- `--destructive`, `--destructive-foreground`: Destructive action colors+- `--ring`: Focus ring color+- `--radius`: Border radius for components++SvelteKit Project Structure+- Use the recommended SvelteKit project structure:+```+- src/+ - lib/+ - routes/+ - app.html+- static/+- svelte.config.js+- vite.config.js+```++Component Development+- Create .svelte files for Svelte components.+- Use .svelte.ts files for component logic and state machines.+- Implement proper component composition and reusability.+- Use Svelte's props for data passing.+- Leverage Svelte's reactive declarations for local state management.++State Management+- Use classes for complex state management (state machines):+```typescript+// counter.svelte.ts+class Counter {+ count = $state(0);+ incrementor = $state(1);++ increment() {+ this.count += this.incrementor;+ }++ resetCount() {+ this.count = 0;+ }++ resetIncrementor() {+ this.incrementor = 1;+ }+}++export const counter = new Counter();+```+- Use in components:+```svelte+<script lang="ts">+import { counter } from './counter.svelte.ts';+</script>++<button on:click={() => counter.increment()}>+ Count: {counter.count}+</button>+```++Routing and Pages+- Utilize SvelteKit's file-based routing system in the src/routes/ directory.+- Implement dynamic routes using [slug] syntax.+- Use load functions for server-side data fetching and pre-rendering.+- Implement proper error handling with +error.svelte pages.++Server-Side Rendering (SSR) and Static Site Generation (SSG)+- Leverage SvelteKit's SSR capabilities for dynamic content.+- Implement SSG for static pages using prerender option.+- Use the adapter-auto for automatic deployment configuration.++Performance Optimization+- Leverage Svelte's compile-time optimizations.+- Use `{#key}` blocks to force re-rendering of components when needed.+- Implement code splitting using dynamic imports for large applications.+- Profile and monitor performance using browser developer tools.+- Use `$effect.tracking()` to optimize effect dependencies.+- Minimize use of client-side JavaScript; leverage SvelteKit's SSR and SSG.+- Implement proper lazy loading for images and other assets.++Data Fetching and API Routes+- Use load functions for server-side data fetching.+- Implement proper error handling for data fetching operations.+- Create API routes in the src/routes/api/ directory.+- Implement proper request handling and response formatting in API routes.+- Use SvelteKit's hooks for global API middleware.++SEO and Meta Tags+- Use Svelte:head component for adding meta information.+- Implement canonical URLs for proper SEO.+- Create reusable SEO components for consistent meta tag management.++Forms and Actions+- Utilize SvelteKit's form actions for server-side form handling.+- Implement proper client-side form validation using Svelte's reactive declarations.+- Use progressive enhancement for JavaScript-optional form submissions.++Internationalization (i18n) with Paraglide.js+- Use Paraglide.js for internationalization: https://inlang.com/m/gerre34r/library-inlang-paraglideJs+- Install Paraglide.js: `npm install @inlang/paraglide-js`+- Set up language files in the `languages` directory.+- Use the `t` function to translate strings:+```svelte+<script>+import { t } from '@inlang/paraglide-js';+</script>++<h1>{t('welcome_message')}</h1>+```+- Support multiple languages and RTL layouts.+- Ensure text scaling and font adjustments for accessibility.++Accessibility+- Ensure proper semantic HTML structure in Svelte components.+- Implement ARIA attributes where necessary.+- Ensure keyboard navigation support for interactive elements.+- Use Svelte's bind:this for managing focus programmatically.++Key Conventions+1. Embrace Svelte's simplicity and avoid over-engineering solutions.+2. Use SvelteKit for full-stack applications with SSR and API routes.+3. Prioritize Web Vitals (LCP, FID, CLS) for performance optimization.+4. Use environment variables for configuration management.+5. Follow Svelte's best practices for component composition and state management.+6. Ensure cross-browser compatibility by testing on multiple platforms.+7. Keep your Svelte and SvelteKit versions up to date.++Documentation+- Svelte 5 Runes: https://svelte-5-preview.vercel.app/docs/runes+- Svelte Documentation: https://svelte.dev/docs+- SvelteKit Documentation: https://kit.svelte.dev/docs+- Paraglide.js Documentation: https://inlang.com/m/gerre34r/library-inlang-paraglideJs/usage++Refer to Svelte, SvelteKit, and Paraglide.js documentation for detailed information on components, internationalization, and best practices.diff --git a/swiftui-ios/.cursor-plugin/plugin.json b/swiftui-ios/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..cb366934--- /dev/null+++ b/swiftui-ios/.cursor-plugin/plugin.json@@ -0,0 +1,27 @@+{+ "name": "swiftui-ios",+ "version": "1.0.0",+ "description": "SwiftUI and Swift iOS/macOS development rules by Josh Pigford (cursor.directory)",+ "author": {+ "name": "Josh Pigford",+ "url": "https://cursor.directory/swiftui-swift-cursor-rules"+ },+ "homepage": "https://cursor.directory/swiftui-swift-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "swift",+ "swiftui",+ "ios",+ "macos",+ "apple"+ ],+ "category": "mobile",+ "tags": [+ "swift",+ "swiftui",+ "ios",+ "macos"+ ],+ "rules": "./rules/"+}diff --git a/swiftui-ios/README.md b/swiftui-ios/README.mdnew file mode 100644index 00000000..2a75df73--- /dev/null+++ b/swiftui-ios/README.md@@ -0,0 +1,29 @@+# swiftui-ios++SwiftUI and Swift iOS/macOS development rules by Josh Pigford (cursor.directory)++## Installation++```bash+agent install swiftui-ios+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `swiftui_ios` | SwiftUI and Swift development best practices for iOS and macOS | `**/*.swift` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/swiftui-swift-cursor-rules).++- **Original Author**: Josh Pigford+- **Tags**: swift, swiftui, ios, macos, apple+- **Category**: mobile++## License++MITdiff --git a/swiftui-ios/rules/swiftui_ios.mdc b/swiftui-ios/rules/swiftui_ios.mdcnew file mode 100644index 00000000..f0212935--- /dev/null+++ b/swiftui-ios/rules/swiftui_ios.mdc@@ -0,0 +1,25 @@+---+description: SwiftUI and Swift development best practices for iOS and macOS+globs:+ - "**/*.swift"+alwaysApply: false+---++# Original instructions: https://forum.cursor.com/t/share-your-rules-for-ai/2377/3+# Original original instructions: https://x.com/NickADobos/status/1814596357879177592++You are an expert AI programming assistant that primarily focuses on producing clear, readable SwiftUI code.++You always use the latest version of SwiftUI and Swift, 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.+- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.+- Confirm, then write code!+- 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.+- 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.diff --git a/terraform-iac/.cursor-plugin/plugin.json b/terraform-iac/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..5d9c7f49--- /dev/null+++ b/terraform-iac/.cursor-plugin/plugin.json@@ -0,0 +1,28 @@+{+ "name": "terraform-iac",+ "version": "1.0.0",+ "description": "Terraform and cloud Infrastructure as Code best practices by Abdeldjalil Sichaib (cursor.directory)",+ "author": {+ "name": "Abdeldjalil Sichaib",+ "url": "https://cursor.directory/terraform-cloud-infrastructure-as-code-best-practices"+ },+ "homepage": "https://cursor.directory/terraform-cloud-infrastructure-as-code-best-practices",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "terraform",+ "iac",+ "aws",+ "azure",+ "gcp",+ "devops"+ ],+ "category": "devops",+ "tags": [+ "AWS",+ "Azure",+ "GCP",+ "Vault"+ ],+ "rules": "./rules/"+}diff --git a/terraform-iac/README.md b/terraform-iac/README.mdnew file mode 100644index 00000000..6ed22b18--- /dev/null+++ b/terraform-iac/README.md@@ -0,0 +1,29 @@+# terraform-iac++Terraform and cloud Infrastructure as Code best practices by Abdeldjalil Sichaib (cursor.directory)++## Installation++```bash+agent install terraform-iac+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `terraform_iac` | Terraform Infrastructure as Code best practices for AWS, Azure, and GCP | `**/*.tf, **/*.tfvars, **/terraform/**` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/terraform-cloud-infrastructure-as-code-best-practices).++- **Original Author**: Abdeldjalil Sichaib+- **Tags**: AWS, Azure, GCP, Vault+- **Category**: devops++## License++MITdiff --git a/terraform-iac/rules/terraform_iac.mdc b/terraform-iac/rules/terraform_iac.mdcnew file mode 100644index 00000000..0ca259db--- /dev/null+++ b/terraform-iac/rules/terraform_iac.mdc@@ -0,0 +1,64 @@+---+description: Terraform Infrastructure as Code best practices for AWS, Azure, and GCP+globs:+ - "**/*.tf"+ - "**/*.tfvars"+ - "**/terraform/**"+alwaysApply: false+---++You are an expert in Terraform and Infrastructure as Code (IaC) for cloud platforms such as AWS, Azure, and GCP.++Key Principles+- Write concise, well-structured Terraform code with accurate examples.+- Organize infrastructure resources into reusable modules.+- Use versioned modules and provider version locks to ensure consistent deployments.+- Avoid hardcoded values; always use variables for flexibility.+- Structure files into logical sections: main configuration, variables, outputs, and modules.++Terraform Best Practices+- Use remote backends (e.g., S3, Azure Blob, GCS) for state management.+- Enable state locking and use encryption for security.+- Utilize workspaces for environment separation (e.g., dev, staging, prod).+- Organize resources by service or application domain (e.g., networking, compute).+- Always run `terraform fmt` to maintain consistent code formatting.+- Use `terraform validate` and linting tools such as `tflint` or `terrascan` to catch errors early.+- Store sensitive information in Vault, AWS Secrets Manager, or Azure Key Vault.++Error Handling and Validation+- Use validation rules for variables to prevent incorrect input values.+- Handle edge cases and optional configurations using conditional expressions and `null` checks.+- Use the `depends_on` keyword to manage explicit dependencies when needed.++Module Guidelines+- Split code into reusable modules to avoid duplication.+- Use outputs from modules to pass information between configurations.+- Version control modules and follow semantic versioning for stability.+- Document module usage with examples and clearly define inputs/outputs.++Security Practices+- Avoid hardcoding sensitive values (e.g., passwords, API keys); instead, use Vault or environment variables.+- Ensure encryption for storage and communication (e.g., enable encryption for S3 buckets, Azure Storage).+- Define access controls and security groups for each cloud resource.+- Follow cloud provider-specific security guidelines (e.g., AWS, Azure, GCP) for best practices.++Performance Optimization+- Use resource targeting (`-target`) to speed up resource-specific changes.+- Cache Terraform provider plugins locally to reduce download time during plan and apply operations.+- Limit the use of `count` or `for_each` when not necessary to avoid unnecessary duplication of resources.++Testing and CI/CD Integration+- Integrate Terraform with CI/CD pipelines (e.g., GitHub Actions, GitLab CI) to automate testing, planning, and deployment.+- Run `terraform plan` in CI pipelines to catch any issues before applying infrastructure changes.+- Use tools like `terratest` to write unit tests for Terraform modules.+- Set up automated tests for critical infrastructure paths (e.g., network connectivity, IAM policies).++Key Conventions+1. Always lock provider versions to avoid breaking changes.+2. Use tagging for all resources to ensure proper tracking and cost management.+3. Ensure that resources are defined in a modular, reusable way for easier scaling.+4. Document your code and configurations with `README.md` files, explaining the purpose of each module.++Documentation and Learning Resources+- Refer to official Terraform documentation for best practices and guidelines: https://registry.terraform.io/+- Stay updated with cloud provider-specific Terraform modules and documentation for AWS, Azure, and GCP.diff --git a/twilio/.cursor-plugin/plugin.json b/twilio/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..aeed0641--- /dev/null+++ b/twilio/.cursor-plugin/plugin.json@@ -0,0 +1,29 @@+{+ "name": "twilio",+ "version": "1.0.0",+ "description": "Cursor plugin for Twilio \u2014 SMS, Voice, WhatsApp, Verify, and communications APIs",+ "author": {+ "name": "Cursor",+ "email": "[email protected]"+ },+ "homepage": "https://github.com/cursor/plugins",+ "repository": "https://github.com/cursor/plugins",+ "license": "MIT",+ "keywords": [+ "twilio",+ "sms",+ "voice",+ "whatsapp",+ "communications",+ "verify"+ ],+ "category": "saas",+ "tags": [+ "communications",+ "sms",+ "voice"+ ],+ "logo": "./twilio.svg",+ "skills": "./skills/",+ "mcpServers": "./mcp.json"+}diff --git a/twilio/CHANGELOG.md b/twilio/CHANGELOG.mdnew file mode 100644index 00000000..5f2859de--- /dev/null+++ b/twilio/CHANGELOG.md@@ -0,0 +1,13 @@+# Changelog++All notable changes to this plugin will be documented in this file.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [Unreleased]++## [1.0.0] - 2026-02-07++### Added+- Initial plugin with skills and MCP server configurationdiff --git a/twilio/LICENSE b/twilio/LICENSEnew file mode 100644index 00000000..ca2bba77--- /dev/null+++ b/twilio/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Cursor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/twilio/README.md b/twilio/README.mdnew file mode 100644index 00000000..640b4435--- /dev/null+++ b/twilio/README.md@@ -0,0 +1,28 @@+# Twilio Plugin++Cursor plugin for Twilio — SMS, Voice, WhatsApp, Verify, and communications APIs.++## Installation++```bash+agent install twilio+```++## Components++### Skills++| Skill | Description |+|:------|:------------|+| `setup-sms` | Send and receive SMS/MMS with webhook handlers and delivery tracking |+| `setup-verify` | Phone verification with Twilio Verify, multi-channel fallback, and error handling |++### MCP Server++Provides Twilio API access via `@anthropic/twilio-mcp-server`.++Requires `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` environment variables.++## License++MITdiff --git a/twilio/mcp.json b/twilio/mcp.jsonnew file mode 100644index 00000000..1599b02d--- /dev/null+++ b/twilio/mcp.json@@ -0,0 +1,14 @@+{+ "$schema": "https://cursor.com/schemas/mcp.json",+ "mcpServers": {+ "twilio": {+ "command": "npx",+ "args": ["-y", "@anthropic/twilio-mcp-server", "--account-sid=${TWILIO_ACCOUNT_SID}", "--auth-token=${TWILIO_AUTH_TOKEN}"],+ "description": "Twilio MCP server — interact with Twilio APIs directly from Cursor. Supports sending SMS, managing phone numbers, configuring Messaging Services, checking message logs, and more.",+ "env": {+ "TWILIO_ACCOUNT_SID": "${TWILIO_ACCOUNT_SID}",+ "TWILIO_AUTH_TOKEN": "${TWILIO_AUTH_TOKEN}"+ }+ }+ }+}diff --git a/twilio/skills/setup-sms/SKILL.md b/twilio/skills/setup-sms/SKILL.mdnew file mode 100644index 00000000..7978db46--- /dev/null+++ b/twilio/skills/setup-sms/SKILL.md@@ -0,0 +1,360 @@+---+name: setup-sms+description: Send and receive SMS/MMS with webhook handlers and delivery tracking via Twilio+---++# Setting Up SMS Messaging with Twilio++## When to Use++Use this skill when:+- The user wants to send SMS or MMS messages from their application+- The user is setting up Twilio Programmable Messaging+- The user asks about sending text message notifications, alerts, or reminders+- The user needs to receive and reply to incoming SMS messages+- The user wants to set up a Messaging Service for production SMS++## Overview++Twilio Programmable Messaging lets you send and receive SMS and MMS messages globally. For production workloads, Twilio recommends using Messaging Services, which provide number pooling, sticky sender, compliance features, and higher throughput than sending from a single number.++## Prerequisites++- A [Twilio account](https://www.twilio.com/try-twilio) (free trial works for testing)+- A Twilio phone number with SMS capability+- `TWILIO_ACCOUNT_SID` environment variable set+- `TWILIO_AUTH_TOKEN` environment variable set+- `TWILIO_PHONE_NUMBER` environment variable set (E.164 format)+- For production: a Messaging Service SID (`TWILIO_MESSAGING_SERVICE_SID`)++## Instructions++### Step 1: Install the Twilio SDK++```bash+npm install twilio+```++### Step 2: Initialize the Twilio Client++```typescript+// lib/twilio.ts+import twilio from 'twilio';++if (!process.env.TWILIO_ACCOUNT_SID || !process.env.TWILIO_AUTH_TOKEN) {+ throw new Error(+ 'Missing TWILIO_ACCOUNT_SID or TWILIO_AUTH_TOKEN environment variables. ' ++ 'Get your credentials at https://console.twilio.com'+ );+}++const client = twilio(+ process.env.TWILIO_ACCOUNT_SID,+ process.env.TWILIO_AUTH_TOKEN+);++export default client;+```++### Step 3: Send an SMS Message++#### Simple SMS (Development)++```typescript+import client from './lib/twilio';++async function sendSMS(to: string, body: string) {+ const message = await client.messages.create({+ body,+ from: process.env.TWILIO_PHONE_NUMBER!, // Your Twilio number in E.164 format+ to, // Recipient number in E.164 format, e.g. '+14155551234'+ });++ console.log(`Message sent: SID=${message.sid}, Status=${message.status}`);+ return message;+}++// Usage+await sendSMS('+14155551234', 'Your order #1234 has shipped!');+```++#### Production SMS with Messaging Service++```typescript+import client from './lib/twilio';++async function sendSMS(to: string, body: string, statusCallbackUrl?: string) {+ const message = await client.messages.create({+ body,+ messagingServiceSid: process.env.TWILIO_MESSAGING_SERVICE_SID!,+ to,+ statusCallback: statusCallbackUrl || `${process.env.APP_URL}/api/webhooks/twilio/message-status`,+ });++ console.log(`Message sent: SID=${message.sid}, Status=${message.status}`);+ return message;+}++// Usage+await sendSMS('+14155551234', 'Your appointment is confirmed for tomorrow at 2pm.');+```++#### Send MMS (with Media)++```typescript+async function sendMMS(to: string, body: string, mediaUrls: string[]) {+ const message = await client.messages.create({+ body,+ messagingServiceSid: process.env.TWILIO_MESSAGING_SERVICE_SID!,+ to,+ mediaUrl: mediaUrls, // Array of publicly accessible media URLs+ });++ console.log(`MMS sent: SID=${message.sid}`);+ return message;+}++// Usage+await sendMMS(+ '+14155551234',+ 'Here is your receipt.',+ ['https://yourapp.com/receipts/1234.pdf']+);+```++### Step 4: Handle Incoming SMS (Webhook)++#### Express.js++```typescript+import express from 'express';+import twilio from 'twilio';++const app = express();++app.post(+ '/api/webhooks/twilio/sms',+ express.urlencoded({ extended: false }),+ twilio.webhook({ authToken: process.env.TWILIO_AUTH_TOKEN }),+ (req, res) => {+ const { From, Body, MessageSid, NumMedia } = req.body;++ console.log(`Incoming SMS from ${From}: ${Body} (SID: ${MessageSid})`);++ // Build a TwiML response+ const response = new twilio.twiml.MessagingResponse();++ // Simple auto-reply based on message content+ const lowerBody = Body?.toLowerCase() || '';++ if (lowerBody.includes('help')) {+ response.message(+ 'Available commands:\n' ++ 'HELP — Show this menu\n' ++ 'STATUS — Check your order status\n' ++ 'STOP — Unsubscribe from messages'+ );+ } else if (lowerBody.includes('status')) {+ response.message('Your order #1234 is out for delivery. Expected arrival: 3pm today.');+ } else {+ response.message('Thanks for your message! Reply HELP for available commands.');+ }++ res.type('text/xml').send(response.toString());+ }+);+```++#### Next.js App Router++```typescript+// app/api/webhooks/twilio/sms/route.ts+import twilio from 'twilio';+import { validateRequest } from 'twilio';+import { headers } from 'next/headers';++export async function POST(req: Request) {+ const body = await req.text();+ const headersList = await headers();+ const params = Object.fromEntries(new URLSearchParams(body));++ // Validate webhook signature+ const signature = headersList.get('x-twilio-signature') || '';+ const url = `${process.env.APP_URL}/api/webhooks/twilio/sms`;++ if (!validateRequest(process.env.TWILIO_AUTH_TOKEN!, signature, url, params)) {+ return new Response('Forbidden', { status: 403 });+ }++ const { From, Body, MessageSid } = params;+ console.log(`Incoming SMS from ${From}: ${Body} (SID: ${MessageSid})`);++ const response = new twilio.twiml.MessagingResponse();+ response.message('Message received! We\'ll get back to you shortly.');++ return new Response(response.toString(), {+ status: 200,+ headers: { 'Content-Type': 'text/xml' },+ });+}+```++### Step 5: Handle Delivery Status Callbacks++```typescript+// Track message delivery status+app.post(+ '/api/webhooks/twilio/message-status',+ express.urlencoded({ extended: false }),+ twilio.webhook({ authToken: process.env.TWILIO_AUTH_TOKEN }),+ async (req, res) => {+ const { MessageSid, MessageStatus, To, ErrorCode, ErrorMessage } = req.body;++ console.log(`Status update for ${MessageSid}: ${MessageStatus}`);++ // Update your database+ await db.message.update({+ where: { twilioSid: MessageSid },+ data: {+ status: MessageStatus,+ errorCode: ErrorCode || null,+ errorMessage: ErrorMessage || null,+ updatedAt: new Date(),+ },+ });++ // Handle failures+ if (MessageStatus === 'failed' || MessageStatus === 'undelivered') {+ console.error(`Message ${MessageSid} to ${To} failed: ${ErrorCode} — ${ErrorMessage}`);++ // Optionally: retry via a different channel (email, push notification, etc.)+ if (ErrorCode === '30003' || ErrorCode === '30005') {+ await notifyViaAlternateChannel(To, MessageSid);+ }+ }++ res.sendStatus(200);+ }+);+```++### Step 6: Add Error Handling and Retry Logic++```typescript+import client from './lib/twilio';++async function sendSMSWithRetry(+ to: string,+ body: string,+ maxRetries = 3+): Promise<{ sid: string; status: string }> {+ // Validate phone number format+ if (!to.match(/^\+[1-9]\d{1,14}$/)) {+ throw new Error(`Invalid phone number format: ${to}. Use E.164 format (e.g., +14155551234).`);+ }++ for (let attempt = 0; attempt <= maxRetries; attempt++) {+ try {+ const message = await client.messages.create({+ body,+ messagingServiceSid: process.env.TWILIO_MESSAGING_SERVICE_SID!,+ to,+ statusCallback: `${process.env.APP_URL}/api/webhooks/twilio/message-status`,+ });++ return { sid: message.sid, status: message.status };+ } catch (err: any) {+ console.error(`SMS send attempt ${attempt + 1} failed:`, err.code, err.message);++ // Don't retry on non-retryable errors+ const nonRetryable = [21211, 21608, 21610, 21614, 21612];+ if (nonRetryable.includes(err.code)) {+ throw err;+ }++ // Retry on rate limits or server errors+ if (attempt < maxRetries && (err.code === 20429 || err.status >= 500)) {+ const delay = Math.pow(2, attempt) * 1000;+ console.warn(`Retrying in ${delay}ms...`);+ await new Promise((resolve) => setTimeout(resolve, delay));+ continue;+ }++ throw err;+ }+ }++ throw new Error('Max retries exceeded');+}+```++### Step 7: Set Up a Messaging Service (Production)++1. Go to the [Twilio Console → Messaging → Services](https://console.twilio.com/us1/develop/sms/services)+2. Click **Create Messaging Service**+3. Give it a name (e.g., "My App Notifications")+4. Add your Twilio phone number(s) to the service's sender pool+5. Configure the incoming message webhook URL (e.g., `https://yourapp.com/api/webhooks/twilio/sms`)+6. Copy the Messaging Service SID and set it as `TWILIO_MESSAGING_SERVICE_SID`+7. For US traffic: complete A2P 10DLC brand and campaign registration++### Step 8: Test Locally with ngrok++```bash+# 1. Start your development server+npm run dev++# 2. In another terminal, start ngrok+ngrok http 3000++# 3. Copy the ngrok URL (e.g., https://abc123.ngrok.io)++# 4. Configure the webhook URL in the Twilio Console:+# Go to Phone Numbers → Manage → Active Numbers → Your Number+# Set the "A MESSAGE COMES IN" webhook to:+# https://abc123.ngrok.io/api/webhooks/twilio/sms++# 5. Send a text message to your Twilio number to test++# 6. Test sending outbound messages from your app+curl -X POST http://localhost:3000/api/send-sms \+ -H "Content-Type: application/json" \+ -d '{"to": "+14155551234", "body": "Hello from my app!"}'+```++### Environment Variables++Add these to your `.env` file:++```env+TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+TWILIO_AUTH_TOKEN=your_auth_token_here+TWILIO_PHONE_NUMBER=+15017122661+TWILIO_MESSAGING_SERVICE_SID=MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+APP_URL=http://localhost:3000+```++## Common Pitfalls++1. **Wrong phone number format**: Always use E.164 format (`+14155551234`). Local formats like `(415) 555-1234` will fail.+2. **Trial account limitations**: Trial accounts can only send to verified phone numbers. Upgrade your account for production.+3. **Missing A2P 10DLC registration**: US carriers require A2P 10DLC registration. Unregistered traffic may be filtered or blocked.+4. **No webhook signature validation**: Always validate `X-Twilio-Signature` on incoming webhooks to prevent spoofed requests.+5. **Slow webhook responses**: Twilio expects a response within 15 seconds. Process heavy tasks asynchronously.+6. **Not handling opt-outs**: Always honor STOP/UNSUBSCRIBE requests. Twilio Messaging Services handle this automatically.+7. **Hardcoded credentials**: Never commit Account SID or Auth Token to source control.++## Checklist++- [ ] Twilio SDK installed (`npm install twilio`)+- [ ] Twilio client initialized with environment variables+- [ ] Outbound SMS sending implemented+- [ ] Incoming SMS webhook handler with signature validation+- [ ] Delivery status callback endpoint+- [ ] Error handling with Twilio error codes+- [ ] Retry logic for transient failures+- [ ] Messaging Service configured (production)+- [ ] A2P 10DLC registration completed (US traffic)+- [ ] Webhook tested locally with ngrok+- [ ] Phone numbers validated in E.164 format+- [ ] Opt-out handling implemented (STOP/UNSUBSCRIBE)diff --git a/twilio/skills/setup-verify/SKILL.md b/twilio/skills/setup-verify/SKILL.mdnew file mode 100644index 00000000..170375f9--- /dev/null+++ b/twilio/skills/setup-verify/SKILL.md@@ -0,0 +1,499 @@+---+name: setup-verify+description: Phone verification with Twilio Verify, multi-channel fallback, and error handling+---++# Setting Up Phone Verification with Twilio Verify++## When to Use++Use this skill when:+- The user wants to verify phone numbers during registration or login+- The user needs to implement two-factor authentication (2FA)+- The user asks about sending OTP (one-time password) codes+- The user wants phone verification via SMS, voice call, email, or WhatsApp+- The user needs to add identity verification to their application++## Overview++Twilio Verify is a purpose-built API for sending and checking verification codes. Unlike sending raw SMS with verification codes, Twilio Verify includes built-in rate limiting, fraud detection, multi-channel delivery (SMS, voice, email, WhatsApp), and automatic code generation and expiration. You only pay for successful verifications, making it more cost-effective than raw SMS for verification use cases.++**Why use Verify instead of raw SMS?**+- Built-in fraud guard — blocks verification pumping attacks+- Rate limiting per phone number — prevents abuse+- Automatic code generation and expiration (10-minute default)+- Multi-channel fallback (SMS → Voice → WhatsApp)+- Only charged for successful verifications+- Managed templates with localization++## Prerequisites++- A [Twilio account](https://www.twilio.com/try-twilio)+- A Twilio Verify Service (created in the Console or via API)+- `TWILIO_ACCOUNT_SID` environment variable set+- `TWILIO_AUTH_TOKEN` environment variable set+- `TWILIO_VERIFY_SERVICE_SID` environment variable set++## Instructions++### Step 1: Create a Verify Service++#### Via the Twilio Console++1. Go to [Twilio Console → Verify → Services](https://console.twilio.com/us1/develop/verify/services)+2. Click **Create new** to create a Verify Service+3. Give it a friendly name (e.g., "My App Verification")+4. Configure settings:+ - Code length: 6 digits (default)+ - Code expiry: 10 minutes (default)+ - Enable fraud guard: Yes+5. Copy the Service SID (starts with `VA`) and set as `TWILIO_VERIFY_SERVICE_SID`++#### Via the API++```typescript+import twilio from 'twilio';++const client = twilio(process.env.TWILIO_ACCOUNT_SID!, process.env.TWILIO_AUTH_TOKEN!);++const service = await client.verify.v2.services.create({+ friendlyName: 'My App Verification',+ codeLength: 6,+ lookupEnabled: true, // Validate numbers before sending+});++console.log(`Verify Service SID: ${service.sid}`);+// Set this as TWILIO_VERIFY_SERVICE_SID+```++### Step 2: Install the Twilio SDK++```bash+npm install twilio+```++### Step 3: Create the Verification Service Module++```typescript+// lib/verify.ts+import twilio from 'twilio';++const client = twilio(+ process.env.TWILIO_ACCOUNT_SID!,+ process.env.TWILIO_AUTH_TOKEN!+);++const verifyServiceSid = process.env.TWILIO_VERIFY_SERVICE_SID!;++export type VerifyChannel = 'sms' | 'call' | 'email' | 'whatsapp';++/**+ * Send a verification code to the specified phone number or email.+ */+export async function sendVerificationCode(+ to: string,+ channel: VerifyChannel = 'sms'+): Promise<{ status: string; sid: string }> {+ try {+ const verification = await client.verify.v2+ .services(verifyServiceSid)+ .verifications.create({ to, channel });++ console.log(`Verification sent to ${to} via ${channel}: ${verification.status}`);++ return {+ status: verification.status, // 'pending'+ sid: verification.sid,+ };+ } catch (err: any) {+ console.error(`Failed to send verification to ${to}:`, err.code, err.message);++ switch (err.code) {+ case 60200: // Invalid parameter+ throw new Error('Invalid phone number or email address.');+ case 60203: // Max send attempts reached+ throw new Error('Too many verification attempts. Please wait before trying again.');+ case 60205: // SMS not supported for this region+ throw new Error('SMS verification is not available for this number. Try voice or WhatsApp.');+ default:+ throw new Error('Failed to send verification code. Please try again later.');+ }+ }+}++/**+ * Check a verification code submitted by the user.+ */+export async function checkVerificationCode(+ to: string,+ code: string+): Promise<{ status: string; valid: boolean }> {+ try {+ const check = await client.verify.v2+ .services(verifyServiceSid)+ .verificationChecks.create({ to, code });++ console.log(`Verification check for ${to}: ${check.status}`);++ return {+ status: check.status, // 'approved' or 'pending'+ valid: check.status === 'approved',+ };+ } catch (err: any) {+ console.error(`Verification check failed for ${to}:`, err.code, err.message);++ switch (err.code) {+ case 20404: // Verification not found+ throw new Error('Verification code expired or not found. Please request a new code.');+ case 60202: // Max check attempts reached+ throw new Error('Too many incorrect attempts. Please request a new code.');+ default:+ throw new Error('Verification check failed. Please try again.');+ }+ }+}+```++### Step 4: Create API Endpoints++#### Express.js++```typescript+import express from 'express';+import { sendVerificationCode, checkVerificationCode } from './lib/verify';++const app = express();+app.use(express.json());++// POST /api/verify/send — Send a verification code+app.post('/api/verify/send', async (req, res) => {+ try {+ const { phoneNumber, channel = 'sms' } = req.body;++ if (!phoneNumber) {+ return res.status(400).json({ error: 'Phone number is required' });+ }++ // Validate E.164 format+ if (!phoneNumber.match(/^\+[1-9]\d{1,14}$/)) {+ return res.status(400).json({+ error: 'Phone number must be in E.164 format (e.g., +14155551234)',+ });+ }++ const result = await sendVerificationCode(phoneNumber, channel);+ res.json({ status: result.status, message: 'Verification code sent' });+ } catch (err: any) {+ res.status(400).json({ error: err.message });+ }+});++// POST /api/verify/check — Check a verification code+app.post('/api/verify/check', async (req, res) => {+ try {+ const { phoneNumber, code } = req.body;++ if (!phoneNumber || !code) {+ return res.status(400).json({ error: 'Phone number and code are required' });+ }++ const result = await checkVerificationCode(phoneNumber, code);++ if (result.valid) {+ // Verification successful — mark the user as verified+ // (integrate with your user/session management here)+ res.json({ status: 'approved', message: 'Phone number verified successfully' });+ } else {+ res.status(400).json({ status: 'pending', message: 'Invalid verification code' });+ }+ } catch (err: any) {+ res.status(400).json({ error: err.message });+ }+});+```++#### Next.js App Router++```typescript+// app/api/verify/send/route.ts+import { NextResponse } from 'next/server';+import { sendVerificationCode } from '@/lib/verify';++export async function POST(req: Request) {+ try {+ const { phoneNumber, channel = 'sms' } = await req.json();++ if (!phoneNumber?.match(/^\+[1-9]\d{1,14}$/)) {+ return NextResponse.json(+ { error: 'Valid phone number in E.164 format is required' },+ { status: 400 }+ );+ }++ const result = await sendVerificationCode(phoneNumber, channel);+ return NextResponse.json({ status: result.status });+ } catch (err: any) {+ return NextResponse.json({ error: err.message }, { status: 400 });+ }+}+```++```typescript+// app/api/verify/check/route.ts+import { NextResponse } from 'next/server';+import { checkVerificationCode } from '@/lib/verify';++export async function POST(req: Request) {+ try {+ const { phoneNumber, code } = await req.json();++ if (!phoneNumber || !code) {+ return NextResponse.json(+ { error: 'Phone number and code are required' },+ { status: 400 }+ );+ }++ const result = await checkVerificationCode(phoneNumber, code);++ if (result.valid) {+ // Mark user as verified in your database+ return NextResponse.json({+ status: 'approved',+ message: 'Phone number verified',+ });+ }++ return NextResponse.json(+ { status: 'pending', message: 'Invalid code' },+ { status: 400 }+ );+ } catch (err: any) {+ return NextResponse.json({ error: err.message }, { status: 400 });+ }+}+```++### Step 5: Add Frontend Verification Flow++```typescript+// React component example+import { useState } from 'react';++export function PhoneVerification() {+ const [phone, setPhone] = useState('');+ const [code, setCode] = useState('');+ const [step, setStep] = useState<'phone' | 'code' | 'verified'>('phone');+ const [error, setError] = useState('');+ const [loading, setLoading] = useState(false);++ async function handleSendCode() {+ setError('');+ setLoading(true);++ try {+ const res = await fetch('/api/verify/send', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ phoneNumber: phone, channel: 'sms' }),+ });++ const data = await res.json();++ if (!res.ok) throw new Error(data.error);++ setStep('code');+ } catch (err: any) {+ setError(err.message);+ } finally {+ setLoading(false);+ }+ }++ async function handleVerifyCode() {+ setError('');+ setLoading(true);++ try {+ const res = await fetch('/api/verify/check', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ phoneNumber: phone, code }),+ });++ const data = await res.json();++ if (!res.ok) throw new Error(data.error);++ setStep('verified');+ } catch (err: any) {+ setError(err.message);+ } finally {+ setLoading(false);+ }+ }++ if (step === 'verified') {+ return <div>✓ Phone number verified successfully!</div>;+ }++ return (+ <div>+ {step === 'phone' ? (+ <div>+ <label htmlFor="phone">Phone Number</label>+ <input+ id="phone"+ type="tel"+ placeholder="+14155551234"+ value={phone}+ onChange={(e) => setPhone(e.target.value)}+ />+ <button onClick={handleSendCode} disabled={loading}>+ {loading ? 'Sending...' : 'Send Verification Code'}+ </button>+ </div>+ ) : (+ <div>+ <p>Enter the 6-digit code sent to {phone}</p>+ <input+ type="text"+ inputMode="numeric"+ maxLength={6}+ placeholder="123456"+ value={code}+ onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))}+ />+ <button onClick={handleVerifyCode} disabled={loading}>+ {loading ? 'Verifying...' : 'Verify'}+ </button>+ <button onClick={handleSendCode} disabled={loading}>+ Resend Code+ </button>+ </div>+ )}+ {error && <p style={{ color: 'red' }}>{error}</p>}+ </div>+ );+}+```++### Step 6: Multi-Channel Fallback++```typescript+/**+ * Send verification with automatic channel fallback.+ * Tries SMS first, then voice, then WhatsApp.+ */+export async function sendVerificationWithFallback(+ to: string+): Promise<{ status: string; channel: string }> {+ const channels: VerifyChannel[] = ['sms', 'call', 'whatsapp'];++ for (const channel of channels) {+ try {+ const result = await sendVerificationCode(to, channel);+ return { status: result.status, channel };+ } catch (err: any) {+ console.warn(`Verification via ${channel} failed for ${to}:`, err.message);++ // If it's a rate limit or abuse error, don't try other channels+ if (err.message.includes('Too many')) {+ throw err;+ }+ // Otherwise, try the next channel+ }+ }++ throw new Error('All verification channels failed. Please try again later.');+}+```++### Step 7: Test the Integration++```bash+# 1. Start your development server+npm run dev++# 2. Test sending a verification code+curl -X POST http://localhost:3000/api/verify/send \+ -H "Content-Type: application/json" \+ -d '{"phoneNumber": "+14155551234", "channel": "sms"}'+# Response: {"status": "pending", "message": "Verification code sent"}++# 3. Check the verification code (use the code received via SMS)+curl -X POST http://localhost:3000/api/verify/check \+ -H "Content-Type: application/json" \+ -d '{"phoneNumber": "+14155551234", "code": "123456"}'+# Response: {"status": "approved", "message": "Phone number verified successfully"}++# 4. Test error cases+# Invalid phone number+curl -X POST http://localhost:3000/api/verify/send \+ -H "Content-Type: application/json" \+ -d '{"phoneNumber": "not-a-number"}'+# Response: 400 {"error": "Phone number must be in E.164 format..."}++# Wrong code+curl -X POST http://localhost:3000/api/verify/check \+ -H "Content-Type: application/json" \+ -d '{"phoneNumber": "+14155551234", "code": "000000"}'+# Response: 400 {"status": "pending", "message": "Invalid verification code"}+```++### Environment Variables++Add these to your `.env` file:++```env+TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+TWILIO_AUTH_TOKEN=your_auth_token_here+TWILIO_VERIFY_SERVICE_SID=VAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+```++## Common Pitfalls++1. **Using raw SMS instead of Verify for OTP**: Twilio Verify includes fraud protection, rate limiting, and multi-channel support. Raw SMS for OTP is more expensive and less secure.+2. **Not handling expired codes**: Verification codes expire after 10 minutes (default). Handle the 20404 error code gracefully.+3. **Missing rate limit handling**: Twilio Verify has built-in rate limits. Handle the 60203 error to inform users when they've exceeded the limit.+4. **Wrong phone number format**: Always use E.164 format. Validate on both client and server.+5. **Not checking the response status**: A successful API call doesn't mean the code is correct — always check `status === 'approved'`.+6. **Storing verification codes locally**: Never generate and store your own codes when using Verify. The API manages code lifecycle for you.++## Database Schema (Prisma Example)++```prisma+model User {+ id String @id @default(cuid())+ email String @unique+ phone String? @unique+ phoneVerified Boolean @default(false)+ phoneVerifiedAt DateTime?+}++model VerificationAttempt {+ id String @id @default(cuid())+ phone String+ channel String // sms, call, email, whatsapp+ status String // pending, approved, canceled, expired+ createdAt DateTime @default(now())+ userId String?++ @@index([phone, createdAt])+}+```++## Checklist++- [ ] Twilio Verify Service created in the Console+- [ ] Twilio SDK installed (`npm install twilio`)+- [ ] Verification service module created (`lib/verify.ts`)+- [ ] Send verification endpoint implemented+- [ ] Check verification endpoint implemented+- [ ] E.164 phone number validation on both client and server+- [ ] Error handling with user-friendly messages+- [ ] Frontend verification flow (phone input → code input → success)+- [ ] Environment variables configured (`TWILIO_ACCOUNT_SID`, `TWILIO_AUTH_TOKEN`, `TWILIO_VERIFY_SERVICE_SID`)+- [ ] Rate limit handling for repeated attempts+- [ ] Multi-channel fallback (optional)+- [ ] Integration tested end-to-enddiff --git a/twilio/twilio.svg b/twilio/twilio.svgnew file mode 100644index 00000000..e88affd6--- /dev/null+++ b/twilio/twilio.svg@@ -0,0 +1 @@+<svg width="64" height="64" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Twilio</title><path d="M12 0C5.381-.008.008 5.352 0 11.971V12c0 6.64 5.359 12 12 12 6.64 0 12-5.36 12-12 0-6.641-5.36-12-12-12zm0 20.801c-4.846.015-8.786-3.904-8.801-8.75V12c-.014-4.846 3.904-8.786 8.75-8.801H12c4.847-.014 8.786 3.904 8.801 8.75V12c.015 4.847-3.904 8.786-8.75 8.801H12zm5.44-11.76c0 1.359-1.12 2.479-2.481 2.479-1.366-.007-2.472-1.113-2.479-2.479 0-1.361 1.12-2.481 2.479-2.481 1.361 0 2.481 1.12 2.481 2.481zm0 5.919c0 1.36-1.12 2.48-2.481 2.48-1.367-.008-2.473-1.114-2.479-2.48 0-1.359 1.12-2.479 2.479-2.479 1.361-.001 2.481 1.12 2.481 2.479zm-5.919 0c0 1.36-1.12 2.48-2.479 2.48-1.368-.007-2.475-1.113-2.481-2.48 0-1.359 1.12-2.479 2.481-2.479 1.358-.001 2.479 1.12 2.479 2.479zm0-5.919c0 1.359-1.12 2.479-2.479 2.479-1.367-.007-2.475-1.112-2.481-2.479 0-1.361 1.12-2.481 2.481-2.481 1.358 0 2.479 1.12 2.479 2.481z"/></svg>diff --git a/unity-gamedev/.cursor-plugin/plugin.json b/unity-gamedev/.cursor-plugin/plugin.jsonnew file mode 100644index 00000000..11984727--- /dev/null+++ b/unity-gamedev/.cursor-plugin/plugin.json@@ -0,0 +1,26 @@+{+ "name": "unity-gamedev",+ "version": "1.0.0",+ "description": "C# Unity game development and design patterns rules by Pontus Abrahamsson (cursor.directory)",+ "author": {+ "name": "Pontus Abrahamsson",+ "url": "https://cursor.directory/c-unity-game-development-cursor-rules"+ },+ "homepage": "https://cursor.directory/c-unity-game-development-cursor-rules",+ "repository": "https://github.com/pontusab/cursor.directory",+ "license": "MIT",+ "keywords": [+ "unity",+ "csharp",+ "gamedev",+ "game-development"+ ],+ "category": "gamedev",+ "tags": [+ "unity",+ "csharp",+ "gamedev",+ "game-development"+ ],+ "rules": "./rules/"+}diff --git a/unity-gamedev/README.md b/unity-gamedev/README.mdnew file mode 100644index 00000000..82ebdd0b--- /dev/null+++ b/unity-gamedev/README.md@@ -0,0 +1,29 @@+# unity-gamedev++C# Unity game development and design patterns rules by Pontus Abrahamsson (cursor.directory)++## Installation++```bash+agent install unity-gamedev+```++## What's Included++### Rules++| Rule | Description | Applies To |+|:-----|:------------|:-----------|+| `unity_gamedev` | Unity and C# game development best practices and design patterns | `**/*.cs, **/*.unity, **/*.prefab` |++## Source++This plugin is sourced from [cursor.directory](https://cursor.directory/c-unity-game-development-cursor-rules).++- **Original Author**: Pontus Abrahamsson+- **Tags**: unity, csharp, gamedev, game-development+- **Category**: gamedev++## License++MITdiff --git a/unity-gamedev/rules/unity_gamedev.mdc b/unity-gamedev/rules/unity_gamedev.mdcnew file mode 100644index 00000000..9478058c--- /dev/null+++ b/unity-gamedev/rules/unity_gamedev.mdc@@ -0,0 +1,61 @@+---+description: Unity and C# game development best practices and design patterns+globs:+ - "**/*.cs"+ - "**/*.unity"+ - "**/*.prefab"+alwaysApply: false+---++You are an expert in C#, Unity, and scalable game development.++Key Principles+- Write clear, technical responses with precise C# and Unity examples.+- Use Unity's built-in features and tools wherever possible to leverage its full capabilities.+- Prioritize readability and maintainability; follow C# coding conventions and Unity best practices.+- Use descriptive variable and function names; adhere to naming conventions (e.g., PascalCase for public members, camelCase for private members).+- Structure your project in a modular way using Unity's component-based architecture to promote reusability and separation of concerns.++C#/Unity+- Use MonoBehaviour for script components attached to GameObjects; prefer ScriptableObjects for data containers and shared resources.+- Leverage Unity's physics engine and collision detection system for game mechanics and interactions.+- Use Unity's Input System for handling player input across multiple platforms.+- Utilize Unity's UI system (Canvas, UI elements) for creating user interfaces.+- Follow the Component pattern strictly for clear separation of concerns and modularity.+- Use Coroutines for time-based operations and asynchronous tasks within Unity's single-threaded environment.++Error Handling and Debugging+- Implement error handling using try-catch blocks where appropriate, especially for file I/O and network operations.+- Use Unity's Debug class for logging and debugging (e.g., Debug.Log, Debug.LogWarning, Debug.LogError).+- Utilize Unity's profiler and frame debugger to identify and resolve performance issues.+- Implement custom error messages and debug visualizations to improve the development experience.+- Use Unity's assertion system (Debug.Assert) to catch logical errors during development.++Dependencies+- Unity Engine+- .NET Framework (version compatible with your Unity version)+- Unity Asset Store packages (as needed for specific functionality)+- Third-party plugins (carefully vetted for compatibility and performance)++Unity-Specific Guidelines+- Use Prefabs for reusable game objects and UI elements.+- Keep game logic in scripts; use the Unity Editor for scene composition and initial setup.+- Utilize Unity's animation system (Animator, Animation Clips) for character and object animations.+- Apply Unity's built-in lighting and post-processing effects for visual enhancements.+- Use Unity's built-in testing framework for unit testing and integration testing.+- Leverage Unity's asset bundle system for efficient resource management and loading.+- Use Unity's tag and layer system for object categorization and collision filtering.++Performance Optimization+- Use object pooling for frequently instantiated and destroyed objects.+- Optimize draw calls by batching materials and using atlases for sprites and UI elements.+- Implement level of detail (LOD) systems for complex 3D models to improve rendering performance.+- Use Unity's Job System and Burst Compiler for CPU-intensive operations.+- Optimize physics performance by using simplified collision meshes and adjusting fixed timestep.++Key Conventions+1. Follow Unity's component-based architecture for modular and reusable game elements.+2. Prioritize performance optimization and memory management in every stage of development.+3. Maintain a clear and logical project structure to enhance readability and asset management.++Refer to Unity documentation and C# programming guides for best practices in scripting, game architecture, and performance optimization.