Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+263 -195
View File
@@ -1,241 +1,309 @@
---
description: This rule provides best practices for developing with Microsoft Teams, covering code organization, performance, security, testing, and common pitfalls. Adhering to these guidelines will ensure robust, maintainable, and secure Teams applications.
globs: *.js,*.jsx,*.ts,*.tsx
description: This rule file provides opinionated best practices for developing and managing applications within the Microsoft Teams ecosystem, ensuring high-quality, performant, and maintainable solutions.
globs: **/*
---
- # Code Organization and Structure
- Effective code organization is critical for maintainability and scalability in Microsoft Teams application development.
# microsoft-teams Best Practices
- ## Directory Structure Best Practices
- **src/**: Contains all source code.
- **components/**: Reusable UI components.
- **modules/**: Independent, reusable modules with specific functionalities (e.g., authentication, data fetching).
- **pages/** or **views/**: Top-level components representing different application views/pages.
- **services/**: Code interacting with Microsoft Teams APIs or other external services.
- **utils/** or **helpers/**: Utility functions, constants, and helper classes.
- **styles/**: CSS, SCSS, or other styling-related files.
- **types/**: TypeScript type definitions (if using TypeScript).
- **public/**: Static assets (images, fonts, etc.).
- **tests/**: Unit, integration, and end-to-end tests.
- **.cursor/**: Stores Cursor-specific project rules.
Microsoft Teams is the backbone of enterprise collaboration. To build high-quality, maintainable, and performant applications, adhere to these definitive guidelines.
- ## File Naming Conventions
- **Components:** PascalCase (e.g., `MyTeamsComponent.tsx`).
- **Modules:** camelCase (e.g., `teamsAuthentication.ts`).
- **Styles:** kebab-case (e.g., `my-teams-component.scss`).
- **Tests:** `<filename>.test.ts` or `<filename>.spec.ts` (e.g., `MyTeamsComponent.test.tsx`).
- **Interfaces/Types:** Capitalized with a leading `I` if an interface (e.g., `IUser.ts`).
## 1. Code Organization and Structure
- ## Module Organization
- Favor small, focused modules with clear responsibilities.
- Use dependency injection to manage dependencies between modules.
- Consider using an inversion of control (IoC) container for more complex applications.
Always start with a standardized project structure and leverage modern tooling.
- ## Component Architecture
- **Presentational Components:** Responsible for rendering UI; receive data and callbacks as props.
- **Container Components:** Fetch data, manage state, and pass data to presentational components.
- Consider using a state management library like Redux, Zustand, or Jotai for complex applications.
### ✅ Use Microsoft 365 Agents Toolkit for Project Scaffolding
- ## Code Splitting
- Use dynamic imports to lazy-load modules and components.
- Implement route-based code splitting to reduce the initial bundle size.
- Analyze bundle size using tools like Webpack Bundle Analyzer to identify large dependencies.
The `Microsoft 365 Agents Toolkit` (formerly Teams Toolkit) provides the official project structure, linting rules, and CI/CD pipelines. It's the fastest way to a compliant and maintainable app.
- # Common Patterns and Anti-patterns
- Employing established design patterns and avoiding anti-patterns are crucial for writing clean, maintainable code in Microsoft Teams development.
❌ BAD: Manual project setup, inconsistent file organization.
```typescript
// Don't manually create files and folders.
// This leads to inconsistent project structures.
// src/components/MyComponent.tsx
// src/api/teamsApi.ts
// ...
```
- ## Design Patterns
- **Observer Pattern:** Useful for subscribing components to changes in Teams state (e.g., user presence, channel messages).
- **Factory Pattern:** Abstract component creation to simplify management of different Teams context variables or user settings.
- **Strategy Pattern:** To handle different API authentication approaches and use appropriate logic depending on where code is run (webpage or Teams client)
- **Facade Pattern:** Simplify complex Teams API interactions by providing a higher-level interface.
✅ GOOD: Generate with the toolkit.
```bash
# Use the VS Code extension or CLI
# This ensures a consistent, maintainable structure
# and pre-configured build/deploy scripts.
npm install -g @microsoft/teamsfx-cli # Or use the VS Code extension
teamsfx new --app-name my-teams-app --capabilities tab,bot
```
- ## Recommended Approaches
- Use the Microsoft Teams Client SDK for interacting with the Teams client.
- Prefer asynchronous operations to avoid blocking the UI thread.
- Implement proper error handling for API calls and user input.
- Adopt responsive design principles to ensure your application works well on different screen sizes.
### ✅ Prefer TypeScript for All Development
- ## Anti-patterns and Code Smells
- **Deeply Nested Components:** Leads to performance issues and difficulty in understanding the component hierarchy.
- **God Objects:** Modules or components with too many responsibilities.
- **Copy-Pasted Code:** Indicates a lack of proper abstraction and code reuse.
- **Ignoring Errors:** Can lead to unexpected behavior and difficult-to-debug issues.
- **Over-reliance on `any` Type (TypeScript):** Reduces the benefits of TypeScript's type safety.
TypeScript is mandatory for type safety, better tooling, and improved code quality.
- ## State Management
- For simple components, use React's built-in `useState` hook.
- For complex applications, consider using a state management library:
- **Redux:** Predictable state container with a centralized store and unidirectional data flow.
- **Zustand:** Small, fast, and scalable bearbones state-management solution.
- **Jotai:** Primitive and flexible state management with an atomic model.
- Avoid mutating state directly; use immutability techniques.
❌ BAD: JavaScript for Teams app logic.
```javascript
// myBotLogic.js
function handleMessage(context, message) {
// No type checking, prone to runtime errors
if (message.text.startsWith('/hello')) {
context.sendActivity(`Hello ${context.activity.from.name}!`);
}
}
```
- ## Error Handling
- Use `try...catch` blocks to handle exceptions gracefully.
- Implement global error handling to catch unhandled exceptions.
- Log errors to a central location for monitoring and debugging.
- Provide informative error messages to the user.
✅ GOOD: TypeScript with explicit types.
```typescript
// myBotLogic.ts
import { TurnContext, Activity } from 'botbuilder';
- # Performance Considerations
- Optimizing performance is crucial for providing a smooth user experience in Microsoft Teams applications.
export async function handleMessage(context: TurnContext, activity: Activity): Promise<void> {
if (activity.text?.startsWith('/hello')) {
await context.sendActivity(`Hello ${activity.from?.name || 'there'}!`);
}
}
```
- ## Optimization Techniques
- **Memoization:** Cache the results of expensive function calls to avoid redundant computations.
- **Debouncing and Throttling:** Limit the rate at which functions are executed in response to user input.
- **Virtualization:** Render only the visible portion of large lists or tables.
- **Code Splitting:** As mentioned earlier, divide code into smaller chunks to reduce initial load time.
- **Efficient Data Structures:** Use appropriate data structures for optimal performance (e.g., Maps instead of Objects for frequent lookups).
## 2. Common Patterns and Anti-patterns
- ## Memory Management
- Avoid memory leaks by properly cleaning up resources (e.g., event listeners, timers).
- Use weak references when necessary to avoid preventing garbage collection.
- Monitor memory usage using browser developer tools to identify potential issues.
Adopt established patterns for UI, interaction, and data handling.
- ## Rendering Optimization
- Use React.memo or similar techniques to prevent unnecessary re-renders.
- Optimize images and other assets to reduce file size.
- Minimize DOM manipulations.
### ✅ Use Fluent UI React Components for Tabs
- ## Bundle Size Optimization
- Use tree shaking to remove unused code from dependencies.
- Minify and compress code using tools like Terser and Gzip.
- Analyze bundle size to identify large dependencies and consider alternatives.
Ensure a native look and feel. Fluent UI is the official design system for Microsoft 365.
- ## Lazy Loading
- Lazy-load images and other assets that are not immediately visible.
- Use Intersection Observer API to detect when elements are visible.
- Lazy load modules by incorporating `React.lazy` and `Suspense`.
❌ BAD: Custom CSS frameworks or generic UI libraries.
```tsx
// MyTab.tsx
import React from 'react';
import { Button } from 'some-generic-ui-lib'; // Inconsistent look and feel
- # Security Best Practices
- Security is paramount when developing Microsoft Teams applications to protect user data and prevent vulnerabilities.
const MyTab: React.FC = () => {
return <Button className="my-custom-button">Click Me</Button>;
};
```
- ## Common Vulnerabilities
- **Cross-Site Scripting (XSS):** Injecting malicious scripts into the application.
- **Cross-Site Request Forgery (CSRF):** Attacking users into performing actions without their consent.
- **Authentication and Authorization Flaws:** Improperly securing user authentication and authorization mechanisms.
- **Data Injection:** SQL injection, LDAP injection, etc.
✅ GOOD: Fluent UI React components.
```tsx
// MyTab.tsx
import React from 'react';
import { Button, Field } from '@fluentui/react-components'; // Native Teams experience
- ## Prevention Strategies
- **Input Validation:** Sanitize and validate all user input to prevent injection attacks.
- **Output Encoding:** Escape output to prevent XSS attacks.
- **Content Security Policy (CSP):** Configure CSP to restrict the sources of content that the browser is allowed to load.
- **Regular Security Audits:** Conduct regular security audits to identify and address vulnerabilities.
const MyTab: React.FC = () => {
return (
<Field label="Your Name">
<Button appearance="primary">Submit</Button>
</Field>
);
};
```
- ## Authentication and Authorization
- Use OAuth 2.0 for secure authentication and authorization.
- Implement proper role-based access control (RBAC) to restrict access to sensitive data and functionality.
- Store credentials securely using appropriate encryption and hashing techniques.
### ✅ Leverage Adaptive Cards for Bots and Message Extensions
- ## Data Protection
- Encrypt sensitive data at rest and in transit.
- Implement data loss prevention (DLP) policies to prevent sensitive information from being shared inappropriately.
- Follow privacy best practices to protect user data.
Adaptive Cards provide rich, platform-agnostic UI for conversational experiences.
- ## Secure API Communication
- Use HTTPS for all API communication.
- Validate server-side certificate.
- Implement proper authentication and authorization for API endpoints.
- Use rate limiting to prevent denial-of-service attacks.
❌ BAD: Sending plain text or basic HTML from bots.
```typescript
// bot.ts
await context.sendActivity('Here is your task: Buy milk. Due: Tomorrow.');
```
- # Testing Approaches
- Comprehensive testing is essential for ensuring the quality and reliability of Microsoft Teams applications.
✅ GOOD: Adaptive Cards for structured information.
```typescript
// bot.ts
import { CardFactory } from 'botbuilder';
- ## Unit Testing
- Test individual components and modules in isolation.
- Use mocking and stubbing to isolate dependencies.
- Aim for high code coverage to ensure that all parts of the code are tested.
const taskCard = CardFactory.adaptiveCard({
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.3",
"body": [
{ "type": "TextBlock", "text": "New Task", "weight": "bolder", "size": "medium" },
{ "type": "TextBlock", "text": "Buy Milk", "wrap": true },
{ "type": "FactSet", "facts": [{ "title": "Due Date:", "value": "Tomorrow" }] }
]
});
await context.sendActivity({ attachments: [taskCard] });
```
- ## Integration Testing
- Test the interaction between different components and modules.
- Verify that data flows correctly between different parts of the application.
- Test integrations with Microsoft Teams APIs and other external services.
### ✅ Integrate with Microsoft Graph for Data Access
- ## End-to-End Testing
- Test the entire application flow from the user's perspective.
- Simulate real-world user scenarios.
- Use tools like Cypress or Playwright to automate end-to-end tests.
Always use Microsoft Graph for accessing Microsoft 365 data (user profiles, files, calendars, etc.).
- ## Test Organization
- Organize tests into logical groups based on functionality or component.
- Use clear and descriptive test names.
- Keep tests small and focused.
❌ BAD: Directly accessing SharePoint APIs or other M365 services.
```typescript
// teamsApi.ts
// Avoid direct SharePoint REST calls; use Graph API instead.
fetch(`https://{tenant}.sharepoint.com/_api/web/lists/GetByTitle('Documents')/items`);
```
- ## Mocking and Stubbing
- Use mocking libraries like Jest or Sinon.js to create mocks and stubs.
- Mock external dependencies to isolate the code under test.
- Use stubs to provide controlled responses from dependencies.
✅ GOOD: Use Microsoft Graph SDK.
```typescript
// teamsGraphClient.ts
import { Client } from '@microsoft/microsoft-graph-client';
- # Common Pitfalls and Gotchas
- Being aware of common pitfalls and gotchas can save developers time and effort when developing Microsoft Teams applications.
async function getUserProfile(accessToken: string) {
const graphClient = Client.init({
authProvider: (done) => { done(null, accessToken); }
});
const profile = await graphClient.api('/me').get();
return profile;
}
```
- ## Frequent Mistakes
- Improperly handling asynchronous operations.
- Not validating user input.
- Exposing sensitive data in the client-side code.
- Failing to handle errors gracefully.
- Neglecting performance optimization.
- Not localizing application for different locales
## 3. Performance Considerations
- ## Edge Cases
- Handling different Teams client versions and platforms.
- Dealing with network connectivity issues.
- Handling unexpected API responses.
- Managing different user roles and permissions.
- Handling large data sets.
Optimize for speed and responsiveness, especially for tabs.
- ## Version-Specific Issues
- Be aware of breaking changes in Microsoft Teams API updates.
- Test your application with different Teams client versions.
- Use feature detection to adapt to different API capabilities.
### ✅ Optimize Tab Bundle Size and Lazy Load Components
- ## Compatibility Concerns
- Ensure that your application is compatible with different browsers and devices.
- Test your application with different operating systems.
- Use polyfills to support older browsers.
Large JavaScript bundles impact load times. Minimize dependencies and use dynamic imports.
- ## Debugging Strategies
- Use browser developer tools to debug client-side code.
- Use logging to track application flow and identify errors.
- Use remote debugging to debug server-side code.
- Use a debugger to step through code and inspect variables.
❌ BAD: Single large bundle, loading all components upfront.
```tsx
// App.tsx
import HeavyComponent from './HeavyComponent'; // Always loaded
- # Tooling and Environment
- Choosing the right tools and environment can significantly improve the development experience for Microsoft Teams applications.
const App: React.FC = () => <HeavyComponent />;
```
- ## Recommended Development Tools
- **Visual Studio Code:** Code editor with excellent TypeScript support and debugging capabilities.
- **Microsoft Teams Toolkit:** Provides templates and tools for creating and deploying Teams applications.
- **Node.js:** JavaScript runtime environment for server-side development.
- **NPM or Yarn:** Package managers for managing dependencies.
- **Webpack or Parcel:** Module bundlers for bundling code and assets.
- **React Developer Tools:** Browser extension for debugging React components.
✅ GOOD: Lazy load non-critical components.
```tsx
// App.tsx
import React, { Suspense, lazy } from 'react';
- ## Build Configuration
- Use a build system like Webpack or Parcel to automate the build process.
- Configure the build system to optimize code for production (e.g., minification, compression).
- Use environment variables to manage different configuration settings for different environments.
const LazyHeavyComponent = lazy(() => import('./HeavyComponent'));
- ## Linting and Formatting
- Use ESLint or TSLint to enforce coding style and prevent errors.
- Use Prettier to automatically format code.
- Configure the code editor to automatically format code on save.
const App: React.FC = () => (
<Suspense fallback={<div>Loading...</div>}>
<LazyHeavyComponent />
</Suspense>
);
```
- ## Deployment
- Deploy your application to Azure or another cloud provider.
- Use Microsoft Teams App Studio to create and manage your Teams app package.
- Submit your app to the Microsoft Teams app store for wider distribution.
### ✅ Implement Efficient Data Fetching with Caching and Pagination
- ## CI/CD Integration
- Use a CI/CD system like Azure DevOps, GitHub Actions, or Jenkins to automate the build, test, and deployment process.
- Configure the CI/CD system to run tests and linters automatically.
- Use automated deployments to deploy changes to production quickly and reliably.
Minimize network requests and handle large datasets gracefully.
- # Additional Best Practices
- **Accessibility:** Ensure your application is accessible to users with disabilities.
- **Localization:** Localize your application for different languages and regions.
- **Documentation:** Write clear and concise documentation for your code.
- **Collaboration:** Use a version control system like Git to collaborate with other developers.
- **Stay Up-to-Date:** Keep up with the latest Microsoft Teams API updates and best practices.
❌ BAD: Fetching all data at once.
```typescript
// api.ts
async function getAllItems() {
// Fetches potentially thousands of items, slow and memory intensive
const response = await fetch('/api/items?limit=99999');
return response.json();
}
```
✅ GOOD: Paginate and cache data.
```typescript
// api.ts
import { useQuery } from '@tanstack/react-query'; // Example with React Query
By adhering to these best practices, developers can create robust, maintainable, secure, and high-performing Microsoft Teams applications that provide a great user experience.
async function getItems(page: number, pageSize: number) {
const response = await fetch(`/api/items?page=${page}&pageSize=${pageSize}`);
return response.json();
}
// In a component:
// const { data } = useQuery(['items', page, pageSize], () => getItems(page, pageSize));
```
## 4. Common Pitfalls and Gotchas
Avoid these common mistakes to prevent issues in development and deployment.
### ❌ Ignoring Teams App Store Validation Checklist
Failing to meet validation requirements leads to rejection. Always review the latest checklist. This includes ensuring your app adheres to naming conventions, governance policies, and accessibility standards.
✅ GOOD: Proactively test against all validation criteria (e.g., accessibility, branding, functionality, security).
### ❌ Poor Authentication and Authorization Handling
Incorrect SSO or permission scopes lead to security vulnerabilities and broken experiences.
✅ GOOD: Implement Azure AD SSO using the Teams SDK and request only necessary Microsoft Graph permissions.
```typescript
// auth.ts
import * as microsoftTeams from "@microsoft/teams-js";
async function getTeamsSsoToken(): Promise<string> {
try {
await microsoftTeams.app.initialize();
const token = await microsoftTeams.authentication.getAuthToken();
return token;
} catch (error) {
console.error("Failed to get SSO token:", error);
throw error;
}
}
```
### ❌ Not Transitioning from TeamsFx SDK to Teams SDK / Microsoft 365 Agents SDK
The `TeamsFx SDK` is deprecated as of September 2025. Migrate your AI-powered bots and agents immediately.
✅ GOOD: Use the `Teams SDK` for agents within Teams, and `Microsoft 365 Agents SDK` for broader M365 platform integration.
```typescript
// bot.ts (using new Teams SDK for conversational AI)
import { TeamsActivityHandler, TurnContext } from '@microsoft/teams-ai';
class MyTeamsBot extends TeamsActivityHandler {
constructor() {
super();
this.onMessage(async (context, next) => {
// Use Teams SDK specific methods for AI/agent interactions
await context.sendActivity(`You said: ${context.activity.text}`);
await next();
});
}
}
```
## 5. Testing Approaches
Comprehensive testing ensures reliability and stability.
### ✅ Implement Unit, Integration, and End-to-End Testing
A robust testing strategy is non-negotiable.
* **Unit Tests**: For individual functions and components (e.g., Jest, Vitest).
* **Integration Tests**: For interactions between components and APIs.
* **End-to-End Tests**: Simulate user flows with the `Teams App Test Framework`.
❌ BAD: Manual testing only.
```typescript
// No automated tests, relying solely on manual clicks and checks.
```
✅ GOOD: Automated testing suite.
```typescript
// example.test.ts (Unit Test with Jest)
import { add } from './utils';
describe('Utils', () => {
it('should add two numbers', () => {
expect(add(1, 2)).toBe(3);
});
});
// e2e.test.ts (Conceptual End-to-End Test with Teams App Test Framework)
// This framework simulates user interactions within Teams.
// import { TeamsAppTestFramework } from '@microsoft/teams-app-test-framework';
// const framework = new TeamsAppTestFramework();
// await framework.login('user@example.com');
// await framework.openTab('My Teams App');
// await framework.clickButton('Submit');
// expect(await framework.getMessageText()).toContain('Success');
```
### ✅ Test on a Dedicated Developer Tenant
Always test your app in a realistic Teams environment before production deployment. This catches environment-specific issues and permission problems early.
❌ BAD: Only testing locally or on a generic dev environment.
```bash
# Only npm start and local browser testing
```
✅ GOOD: Deploy to a dev tenant for full integration testing.
```bash
# Use Teams Toolkit to provision and deploy to a dev tenant
teamsfx deploy --env dev
```