From 3438170d954a2a5bc513fc4d0aa5f687e36d0f34 Mon Sep 17 00:00:00 2001 From: ccbikai Date: Tue, 27 May 2025 20:07:03 +0800 Subject: [PATCH] docs: Add project overview, development guidelines, API design patterns, and component design pattern documentation. --- .cursor/rules/api-patterns.mdc | 88 ++++++++ .cursor/rules/coding-standards.mdc | 205 ++++++++++++++++++ .cursor/rules/component-patterns.mdc | 156 +++++++++++++ .../rules/deployment-and-infrastructure.mdc | 139 ++++++++++++ .cursor/rules/development-guidelines.mdc | 64 ++++++ .cursor/rules/project-overview.mdc | 50 +++++ 6 files changed, 702 insertions(+) create mode 100644 .cursor/rules/api-patterns.mdc create mode 100644 .cursor/rules/coding-standards.mdc create mode 100644 .cursor/rules/component-patterns.mdc create mode 100644 .cursor/rules/deployment-and-infrastructure.mdc create mode 100644 .cursor/rules/development-guidelines.mdc create mode 100644 .cursor/rules/project-overview.mdc diff --git a/.cursor/rules/api-patterns.mdc b/.cursor/rules/api-patterns.mdc new file mode 100644 index 0000000..9cefd24 --- /dev/null +++ b/.cursor/rules/api-patterns.mdc @@ -0,0 +1,88 @@ +--- +description: +globs: +alwaysApply: false +--- +# API Design Patterns + +## API Route Structure + +### Link Management API +Located in the `server/api/link/` directory, containing the following endpoints: + +- [create.post.ts](mdc:server/api/link/create.post.ts): Create new short links +- [edit.put.ts](mdc:server/api/link/edit.put.ts): Edit existing links +- [delete.post.ts](mdc:server/api/link/delete.post.ts): Delete links +- [list.get.ts](mdc:server/api/link/list.get.ts): Get link lists +- [query.get.ts](mdc:server/api/link/query.get.ts): Query specific links +- [search.get.ts](mdc:server/api/link/search.get.ts): Search links +- [upsert.post.ts](mdc:server/api/link/upsert.post.ts): Create or update links +- [ai.get.ts](mdc:server/api/link/ai.get.ts): AI-generated slugs + +### Other APIs +- [location.ts](mdc:server/api/location.ts): Geographic location information +- [verify.ts](mdc:server/api/verify.ts): Authentication +- `stats/`: Analytics-related APIs +- `logs/`: Logging-related APIs +- `ws/`: WebSocket-related APIs + +## API Design Conventions + +### HTTP Methods +- `GET`: Retrieve data (queries, lists) +- `POST`: Create resources or perform operations +- `PUT`: Update resources +- `DELETE`: Remove resources + +### Response Format +```typescript +// Success response +{ + success: true, + data: any +} + +// Error response +{ + success: false, + error: string, + code?: number +} +``` + +### Authentication +- Use Site Token for authentication +- Pass token in request header: `Authorization: Bearer ` + +### Data Validation +- Use Zod for input validation +- Define validation schemas in `schemas/` directory +- Unified error handling and response format + +### Cloudflare Integration +- Use Cloudflare Workers KV for data storage +- Leverage Cloudflare Analytics Engine for statistics +- Use Cloudflare AI for slug generation + +## Error Handling + +### Common Error Codes +- `400`: Bad request parameters +- `401`: Unauthorized access +- `403`: Insufficient permissions +- `404`: Resource not found +- `429`: Rate limit exceeded +- `500`: Internal server error + +### Error Handling Pattern +```typescript +try { + // API logic + return { success: true, data: result } +} catch (error) { + return createError({ + statusCode: 400, + statusMessage: error.message + }) +} +``` diff --git a/.cursor/rules/coding-standards.mdc b/.cursor/rules/coding-standards.mdc new file mode 100644 index 0000000..4189fcd --- /dev/null +++ b/.cursor/rules/coding-standards.mdc @@ -0,0 +1,205 @@ +--- +description: +globs: +alwaysApply: false +--- +# Coding Standards + +## Code Quality + +### TypeScript Requirements +- All new code must use TypeScript +- Enable strict type checking +- Avoid using `any` type, prefer specific types +- Define interfaces or type aliases for complex objects + +```typescript +// ✅ Good practice +interface LinkData { + slug: string + url: string + createdAt: Date + expiresAt?: Date +} + +// ❌ Avoid +const linkData: any = { ... } +``` + +### Function and Variable Naming +- Use descriptive names +- Function names should start with verbs +- Boolean variables use `is`, `has`, `should` prefixes +- Constants use UPPER_SNAKE_CASE + +```typescript +// ✅ Good practice +const isValidUrl = (url: string): boolean => { ... } +const hasExpired = computed(() => { ... }) +const MAX_SLUG_LENGTH = 50 + +// ❌ Avoid +const check = (u: string) => { ... } +const expired = computed(() => { ... }) +const maxLen = 50 +``` + +## Security Requirements + +### Input Validation +- All user input must be validated using Zod +- API endpoints must validate request parameters +- Frontend forms use vee-validate + Zod + +```typescript +// API input validation +import { z } from 'zod' + +const createLinkSchema = z.object({ + url: z.string().url(), + slug: z.string().min(1).max(50).optional(), + expiresAt: z.string().datetime().optional() +}) + +export default defineEventHandler(async (event) => { + const body = await readBody(event) + const validatedData = createLinkSchema.parse(body) + // ... +}) +``` + +### Authentication +- Use Site Token for authentication +- Sensitive operations require permission verification +- Don't store sensitive information on the client + +### Data Sanitization +- Sanitize user-input HTML content +- Validate URL format and security +- Prevent XSS and injection attacks + +## Performance Best Practices + +### Reactive Data +- Use `ref` and `reactive` appropriately +- Avoid unnecessary reactive wrapping +- Use `readonly` to protect data + +```typescript +// ✅ Good practice +const { data: links, pending } = await $fetch('/api/links') +const filteredLinks = computed(() => + links.value.filter(link => link.isActive) +) + +// ❌ Avoid +const links = ref([]) +const filteredLinks = ref([]) +watch(links, () => { + filteredLinks.value = links.value.filter(link => link.isActive) +}) +``` + +### Async Operations +- Use `async/await` instead of Promise chains +- Handle errors and loading states properly +- Avoid blocking UI operations + +```typescript +// ✅ Good practice +const { data, error, pending } = await useFetch('/api/links') + +// Error handling +try { + const result = await $fetch('/api/link/create', { ... }) +} catch (error) { + // Handle error +} +``` + +## Code Organization + +### File Structure +- Each file should export only one main functionality +- Group related functionality in the same directory +- Use `index.ts` as directory entry point + +### Import/Export +- Use ES6 module syntax +- Organize imports alphabetically +- Separate third-party and local imports + +```typescript +// Third-party libraries +import { ref, computed } from 'vue' +import { z } from 'zod' + +// Local imports +import type { LinkData } from '~/types' +import { validateUrl } from '~/utils/validation' +``` + +### Comments and Documentation +- Add comments for complex logic +- Use JSDoc comments for public APIs +- Keep comments in sync with code + +```typescript +/** + * Create a new short link + * @param url - Original URL + * @param slug - Custom slug (optional) + * @returns Created link data + */ +export async function createLink(url: string, slug?: string): Promise { + // Implementation logic +} +``` + +## Testing Requirements + +### Type Checking +- Resolve all TypeScript errors +- Use strict type configuration + +### Code Style +- Follow ESLint rules +- Use Prettier for code formatting +- Automatically run lint-staged on commit + +### Manual Testing +- Test main user flows +- Verify API endpoint functionality +- Check responsive design + +## Git Commit Conventions + +### Commit Message Format +``` +type(scope): description + +body (optional) + +footer (optional) +``` + +### Commit Types +- `feat`: New feature +- `fix`: Bug fix +- `docs`: Documentation update +- `style`: Code style (no functional impact) +- `refactor`: Refactoring +- `perf`: Performance optimization +- `test`: Testing related +- `chore`: Build process or auxiliary tool changes + +### Example +``` +feat(api): add AI-powered slug generation + +- Integrate Cloudflare AI for automatic slug creation +- Add new /api/link/ai endpoint +- Update link creation flow to support AI suggestions + +Closes #123 +``` diff --git a/.cursor/rules/component-patterns.mdc b/.cursor/rules/component-patterns.mdc new file mode 100644 index 0000000..8f4245c --- /dev/null +++ b/.cursor/rules/component-patterns.mdc @@ -0,0 +1,156 @@ +--- +description: +globs: +alwaysApply: false +--- +# Vue Component Design Patterns + +## Component Directory Structure + +### UI Components (`app/components/ui/`) +Reusable UI components based on shadcn-vue: +- Buttons, inputs, dialogs, and other fundamental components +- Follow shadcn-vue design system +- Styled with Tailwind CSS +- Support theme switching (light/dark mode) + +### Business Components +- `dashboard/`: Dashboard-related components +- `home/`: Homepage-related components +- `login/`: Login-related components +- `layouts/`: Layout components +- `spark-ui/`: Special UI components + +### Global Components +- [SwitchLanguage.vue](mdc:app/components/SwitchLanguage.vue): Language switching component +- [SwitchTheme.vue](mdc:app/components/SwitchTheme.vue): Theme switching component + +## Component Development Standards + +### Component Structure +```vue + + + + + +``` + +### Naming Conventions +- Component files use PascalCase: `MyComponent.vue` +- Internal variables use camelCase +- CSS class names use Tailwind CSS utility classes +- Event names use kebab-case + +### Props and Events +```typescript +// Props type definition +interface Props { + title: string + isVisible?: boolean + items: Array +} + +// Events type definition +const emit = defineEmits<{ + update: [value: string] + close: [] + select: [item: Item] +}>() +``` + +## State Management + +### Composables (`app/composables/`) +- Use VueUse utility functions +- Create custom composables for shared state management +- Follow `use` prefix naming convention + +### Reactive State +```typescript +// composables/useAuth.ts +export function useAuth() { + const isAuthenticated = ref(false) + const user = ref(null) + + const login = async (token: string) => { + // login logic + } + + const logout = () => { + // logout logic + } + + return { + isAuthenticated: readonly(isAuthenticated), + user: readonly(user), + login, + logout + } +} +``` + +## Styling and Theming + +### Tailwind CSS +- Use Tailwind utility classes for styling +- Configuration file: [tailwind.config.js](mdc:tailwind.config.js) +- Support responsive design and dark mode + +### Theme System +- Use `@nuxtjs/color-mode` module +- Support automatic system theme detection +- Theme switching component: [SwitchTheme.vue](mdc:app/components/SwitchTheme.vue) + +### Animation Effects +- Use `@vueuse/motion` for animations +- Use animation classes provided by `tailwindcss-animate` +- Keep animations simple and performance-friendly + +## Internationalization + +### Multi-language Support +- Use `@nuxtjs/i18n` module +- Language switching component: [SwitchLanguage.vue](mdc:app/components/SwitchLanguage.vue) +- Store translation files in `i18n/` directory + +### Usage +```vue + +``` diff --git a/.cursor/rules/deployment-and-infrastructure.mdc b/.cursor/rules/deployment-and-infrastructure.mdc new file mode 100644 index 0000000..5d230a8 --- /dev/null +++ b/.cursor/rules/deployment-and-infrastructure.mdc @@ -0,0 +1,139 @@ +--- +description: +globs: +alwaysApply: false +--- +# Deployment and Infrastructure + +## Cloudflare Platform + +Sink runs entirely on the Cloudflare platform, leveraging the following services: + +### Cloudflare Workers +- Serverless computing platform +- Global edge network deployment +- Configuration file: [wrangler.jsonc](mdc:wrangler.jsonc) + +### Cloudflare Pages +- Static website hosting +- Automatic build and deployment +- Preview deployment support + +### Cloudflare Workers KV +- Key-value storage database +- Globally distributed storage +- Used for storing link data and configuration + +### Cloudflare Analytics Engine +- Real-time analytics data collection +- High-performance time-series database +- Used for link click statistics + +### Cloudflare AI +- AI model inference service +- Used for automatic slug generation +- Model: `@cf/meta/llama-3.1-8b-instruct` + +## Deployment Configuration + +### Environment Variables +Defined in `runtimeConfig` in [nuxt.config.ts](mdc:nuxt.config.ts): + +```typescript +runtimeConfig: { + siteToken: 'SinkCool', // Site access token + redirectStatusCode: '301', // Redirect status code + linkCacheTtl: 60, // Link cache time + redirectWithQuery: false, // Whether to preserve query parameters + homeURL: '', // Home URL + cfAccountId: '', // Cloudflare Account ID + cfApiToken: '', // Cloudflare API token + dataset: 'sink', // Analytics dataset name + aiModel: '@cf/meta/llama-3.1-8b-instruct', // AI model + caseSensitive: false, // Case sensitivity + listQueryLimit: 500, // List query limit + disableBotAccessLog: false, // Disable bot access logging +} +``` + +### Build Scripts +- `pnpm build`: Build for production +- `pnpm build:map`: Build map data +- `pnpm build:colo`: Build Cloudflare data center information + +### Deployment Commands +```bash +# Preview deployment +pnpm preview + +# Production deployment +pnpm deploy + +# Using Wrangler CLI +wrangler pages deploy dist +``` + +## Performance Optimization + +### Caching Strategy +- Static assets cached using Cloudflare CDN +- Configurable link data cache TTL +- Leverage edge computing to reduce latency + +### Route Rules +Configured in [nuxt.config.ts](mdc:nuxt.config.ts): + +```typescript +routeRules: { + '/': { + prerender: true, // Prerender homepage + }, + '/dashboard/**': { + prerender: true, // Prerender dashboard + ssr: false, // Disable server-side rendering + }, + '/dashboard': { + redirect: '/dashboard/links', // Redirect to links page + }, +} +``` + +### Build Optimization +- Use `NODE_OPTIONS=--max-old-space-size=8192` to increase memory limit +- Enable Nuxt's built-in optimization features +- Code splitting and lazy loading + +## Monitoring and Logging + +### Analytics Engine +- Real-time click data collection +- Geographic location statistics +- User agent analysis +- Referrer statistics + +### Error Handling +- Unified error response format +- Error logging +- Performance monitoring + +### Security +- Site Token authentication +- CORS configuration +- Input validation and sanitization +- Malicious link prevention + +## Development Environment + +### Local Development +```bash +# Start development server +pnpm dev + +# Code style checking +pnpm lint +``` + +### Environment Configuration +- Use `.env` file for local environment variables +- Use Cloudflare Workers local simulator during development +- Support hot reload and live preview diff --git a/.cursor/rules/development-guidelines.mdc b/.cursor/rules/development-guidelines.mdc new file mode 100644 index 0000000..8b8c096 --- /dev/null +++ b/.cursor/rules/development-guidelines.mdc @@ -0,0 +1,64 @@ +--- +description: +globs: +alwaysApply: false +--- +# Development Guidelines + +## Code Style and Standards + +### TypeScript/JavaScript +- Use TypeScript for type-safe development +- Follow ESLint rules defined in [eslint.config.mjs](mdc:eslint.config.mjs) +- Use `@antfu/eslint-config` as the base configuration +- Run `pnpm lint` to check code style, `pnpm lint:fix` to auto-fix issues + +### Vue Components +- Use Composition API with `