diff --git a/.cursor/rules/prompts/update-project-structure-documentation.md b/.cursor/rules/prompts/update-project-structure-documentation.md new file mode 100644 index 0000000..1b24032 --- /dev/null +++ b/.cursor/rules/prompts/update-project-structure-documentation.md @@ -0,0 +1,563 @@ +# Update Project Structure Documentation + +## Purpose + +This prompt provides comprehensive instructions for updating the complete Project Structure Documentation of the DyingStar repository. Use this when the repository structure has changed significantly or when documentation needs to be refreshed. + +## Target Files + +The following files must be updated: + +1. `Documentation/Guidelines/architecture/FolderStructure.md` - High-level architecture overview +2. `Documentation/Guidelines/architecture/ProjectTreeFolder.md` - Complete file tree documentation +3. `Documentation/Guidelines/architecture/FileTypes.md` - File naming conventions (update if new patterns emerge) +4. `Documentation/Guidelines/architecture/Architecture.md` - Reference links (usually no changes needed) + +--- + +## Prerequisites + +Before starting, ensure you have: + +- Full context of the repository structure +- Access to all directories and files +- Understanding of Next.js 15 App Router architecture +- Knowledge of the project's tech stack + +--- + +## Step-by-Step Instructions + +### Phase 1: Reconnaissance - Explore the Repository + +#### 1.1 Scan Root Directory + +``` +List and document: +- Configuration files (.nvmrc, .prettierrc, eslint.config.mjs, etc.) +- Package management files (package.json, pnpm-lock.yaml) +- Build & deployment files (Makefile, middleware.ts, docker/, etc.) +- Documentation files (README.md, LICENSE) +``` + +#### 1.2 Scan app/ Directory (Next.js App Router) + +``` +Recursively explore: +- app/ root level files (layout.tsx, error.tsx, sitemap.tsx, etc.) +- app/[locale]/ structure + - Route groups: (landing), (layout), (logged-in) + - Parallel routes: @modal + - Dynamic routes: docs/[slug] + - Special files: globals.css, providers.tsx, manifest.ts +- For each route segment, document: + - page.tsx + - layout.tsx + - loading.tsx + - error.tsx + - not-found.tsx + - _components/ folders +``` + +#### 1.3 Scan src/ Directory (Application Code) + +``` +Explore and categorize: +- src/components/ + - DS/ (Design System components) + - ui/ (shadcn/ui primitives) + - svg/ (SVG components) + - utils/ (Component utilities) + +- src/features/ (Vertical slices) + - List each feature folder + - Document file patterns (*.tsx, *.type.ts, *.hook.ts, etc.) + +- src/hooks/ (Cross-cutting hooks) + - List all hook files + +- src/i18n/ (Internationalization) + - config.ts, routing.ts, navigation.ts, request.ts + +- src/lib/ (Libraries & utilities) + - actions/ + - env/ + - errors/ + - format/ + - Individual utility files + +- src/types/ (Global types) + +- Root level src/ files (middleware.ts, site-config.ts) +``` + +#### 1.4 Scan content/ Directory + +``` +Document: +- content/news/en/ - English articles +- content/news/fr/ - French articles +- Any other content folders +``` + +#### 1.5 Scan public/ Directory + +``` +List: +- public/images/ +- public/assets/ +- Root level SVG/PNG files +``` + +#### 1.6 Scan messages/ Directory + +``` +Document: +- Translation files (en.json, fr.json, etc.) +``` + +#### 1.7 Scan docker/ & Documentation/ Directories + +``` +Docker: +- Dockerfile.dev +- Dockerfile.prod +- docker-compose.yml + +Documentation: +- Guidelines/architecture/ +- Guidelines/ (process docs) +- Guidelines/pictures/ +``` + +--- + +### Phase 2: Update FolderStructure.md + +**File:** `Documentation/Guidelines/architecture/FolderStructure.md` + +**Structure:** + +```markdown +# Folder Structure + +[Introduction paragraph about Next.js 15 App Router architecture] + +## Global Structure + +[ASCII tree showing top-level folders with brief descriptions] + +## πŸ“ `app/` - Next.js App Router + +[Description] +[ASCII tree of app/ structure] +[Key Concepts section] + +## πŸ“ `src/` - Application source code + +[Description] +[ASCII tree of src/ structure] +[Feature-based architecture explanation] + +## πŸ“ `content/` - Editorial content + +[Description and purpose] + +## πŸ“ `public/` - Static assets + +[Description and access pattern] + +## πŸ“ `messages/` - i18n translations + +[Description, structure, and usage example] + +## πŸ“ `docker/` - Containerization + +[Description and file listing] + +## πŸ“ `Documentation/` - Internal documentation + +[Description and structure] + +## TypeScript path aliases + +[Configuration from tsconfig.json with usage examples] + +## File naming conventions + +[Quick reference with links to FileTypes.md] + +## References + +[Links to Next.js docs and other internal docs] +``` + +**Key Requirements:** + +- Use emojis (πŸ“) for main sections +- Keep ASCII trees clean and aligned +- Include brief but clear descriptions +- Limit depth to 2-3 levels maximum +- Focus on HIGH-LEVEL overview, not every file + +**Format Example:** + +``` +## πŸ“ `app/` - Next.js App Router + +Handles **routing**, **layouts**, and **entry points** of the application following Next.js 15 conventions. + +``` + +app/ +β”œβ”€β”€ πŸ“ [locale]/ # Internationalized routes (en, fr, etc.) +β”‚ β”œβ”€β”€ πŸ“ (layout)/ # Route group - Static pages +β”‚ β”‚ └── πŸ“ pageName/ # Page folder +β”‚ β”œβ”€β”€ πŸ“ @modal/ # Parallel route - Modal system +β”‚ └── πŸ“ docs/ # User documentation + +``` + +**Key Concepts:** +- **Route Groups** `(name)`: Organize without affecting URL +- **Parallel Routes** `@modal`: Display multiple pages simultaneously +``` + +--- + +### Phase 3: Update ProjectTreeFolder.md + +**File:** `Documentation/Guidelines/architecture/ProjectTreeFolder.md` + +**Structure:** + +```markdown +# Project Tree - Complete File Structure + +[Introduction and link to FolderStructure.md] + +--- + +## πŸ“‚ Root Directory + +### Configuration Files + +[Bullet list of ALL config files with descriptions] + +### Package Management + +[package.json, pnpm-lock.yaml with descriptions] + +### Build & Development + +[Makefile, middleware.ts with descriptions] + +### Documentation & Legal + +[README.md, LICENSE with descriptions] + +--- + +## πŸ“‚ app/ β€” Next.js App Router + +[Detailed explanation of routing layer] + +### Root Level (app/) + +[ASCII tree with ALL files and descriptions] + +### Internationalized Routes (app/[locale]/) + +[Complete ASCII tree showing EVERY route segment and file] + +**Key Concepts:** +[Explanations of route groups, parallel routes, etc.] + +--- + +## πŸ“‚ src/ β€” Application Source Code + +[Introduction] + +### src/components/ β€” Reusable UI Components + +[Complete tree showing DS/, ui/, svg/, utils/ with ALL files] + +### src/features/ β€” Business Features + +[Complete tree showing each feature folder with its files] + +### src/hooks/ β€” Cross-cutting React Hooks + +[List all hook files] + +### src/i18n/ β€” Internationalization Configuration + +[List all i18n files] + +### src/lib/ β€” Libraries and Utilities + +[Complete tree with all subdirectories and files] + +### src/types/ β€” Global TypeScript Types + +[List type files] + +### Other src/ Files + +[middleware.ts, site-config.ts] + +--- + +## πŸ“‚ content/ β€” Editorial Content + +[Structure and explanation of MDX organization] + +--- + +## πŸ“‚ public/ β€” Static Assets + +[Complete listing with explanations] + +--- + +## πŸ“‚ messages/ β€” i18n Translation Dictionaries + +[Structure, JSON format example, usage example] + +--- + +## πŸ“‚ docker/ β€” Containerization + +[List all Docker files] + +--- + +## πŸ“‚ Documentation/ β€” Internal Documentation + +[Complete tree of all documentation files] + +--- + +## πŸ”„ Data Flow Examples + +### News Pipeline + +[Diagram showing data flow] + +### Component Import Flow + +[Diagram showing component hierarchy] + +### i18n Flow + +[Diagram showing internationalization flow] + +--- + +## πŸ“ Notes + +[Important notes about path aliases, file types, auto-generated files] + +--- + +## πŸ”— References + +[Links to related documentation] +``` + +**Key Requirements:** + +- EXHAUSTIVE listing of ALL important files +- Use emojis for major sections (πŸ“‚, πŸ”„, πŸ“, πŸ”—) +- Group files logically (config, package management, etc.) +- Include clear descriptions for each file/folder +- Add data flow diagrams +- Keep ASCII trees properly formatted +- List shadcn/ui components completely + +**Format Example:** + +``` +### src/components/ui/ β€” shadcn/ui primitives + +``` + +src/components/ui/ +β”œβ”€β”€ accordion.tsx +β”œβ”€β”€ alert.tsx +β”œβ”€β”€ alert-dialog.tsx +β”œβ”€β”€ button.tsx +β”œβ”€β”€ card.tsx +β”œβ”€β”€ dialog.tsx +β”œβ”€β”€ form.tsx +β”œβ”€β”€ input.tsx +└── ... + +``` + +[Continue with complete list] +``` + +--- + +### Phase 4: Review and Update FileTypes.md (if needed) + +**File:** `Documentation/Guidelines/architecture/FileTypes.md` + +**When to Update:** + +Only update if you discover: + +- New file type patterns (e.g., `*.service.ts`, `*.util.ts`) +- Changes to existing patterns +- New conventions being used + +**What to Update:** + +1. File Type Reference table +2. Add new detailed explanation section +3. Update examples if patterns changed + +**What NOT to Change:** + +- Existing well-documented patterns +- The overall structure of the document +- Examples that are still valid + +--- + +### Phase 5: Verify Architecture.md + +**File:** `Documentation/Guidelines/architecture/Architecture.md` + +**Check:** + +- Section "Project Structure Documentation" exists +- Links to FolderStructure.md, ProjectTreeFolder.md, FileTypes.md are correct +- No duplication of content + +**Expected Structure:** + +```markdown +## Project Structure Documentation + +The project structure is documented in multiple files for better organization: + +- **[FolderStructure.md](./FolderStructure.md)** β€” High-level architecture overview, key concepts, and folder organization +- **[ProjectTreeFolder.md](./ProjectTreeFolder.md)** β€” Complete file-by-file breakdown of the entire repository +- **[FileTypes.md](./FileTypes.md)** β€” Detailed file naming conventions and patterns +``` + +--- + +## Quality Checklist + +After completing all updates, verify: + +### Content Accuracy + +- [ ] All directories accurately documented +- [ ] No missing important files +- [ ] All paths are correct +- [ ] File descriptions are accurate + +### Formatting + +- [ ] ASCII trees are properly aligned +- [ ] Markdown rendering is correct +- [ ] Code blocks use correct syntax highlighting +- [ ] Emojis are used consistently + +### Completeness + +- [ ] FolderStructure.md covers all major folders +- [ ] ProjectTreeFolder.md lists all important files +- [ ] FileTypes.md documents all file patterns +- [ ] Architecture.md links are correct + +### Readability + +- [ ] Human-friendly language +- [ ] Clear hierarchical structure +- [ ] Logical grouping of information +- [ ] Not overly verbose + +### Cross-references + +- [ ] Links between documents work +- [ ] References to Next.js docs are valid +- [ ] Internal links are correct + +--- + +## Common Pitfalls to Avoid + +1. **Too Much Detail in FolderStructure.md** + - Keep it high-level + - Don't list every single file + - Focus on architecture overview + +2. **Missing Files in ProjectTreeFolder.md** + - Be thorough + - Check all subdirectories + - Don't skip "boring" config files + +3. **Outdated Examples** + - Verify code examples actually exist in repo + - Update import paths if changed + - Check that patterns are still in use + +4. **Broken Links** + - Test all markdown links + - Verify file paths + - Check external links + +5. **Inconsistent Formatting** + - Use same emoji style throughout + - Keep ASCII tree alignment consistent + - Follow markdown conventions + +6. **Forgetting Data Flows** + - Update data flow diagrams in ProjectTreeFolder.md + - Ensure they reflect current architecture + - Add new flows if patterns emerged + +--- + +## Tips for Efficiency + +1. **Use Tools** + - Use `list_dir` extensively + - Use `glob_file_search` for finding file patterns + - Read actual files to verify content + +2. **Work Systematically** + - Complete Phase 1 fully before moving to Phase 2 + - Don't skip the reconnaissance phase + - Document as you explore + +3. **Maintain Context** + - Keep track of what you've documented + - Note any inconsistencies found + - Mark areas that need clarification + +4. **Stay Organized** + - Update one file at a time + - Complete each section before moving on + - Test your changes + +--- + +## Final Notes + +- This is COMPREHENSIVE documentation work +- Expect 100-200+ tool calls for complete update +- Take your time to be thorough +- The goal is to create documentation that truly reflects the repository +- Humans should be able to understand the project structure just by reading these docs +- When in doubt, BE MORE DETAILED rather than less + +**Remember:** This documentation is critical for onboarding, maintenance, and project understanding. Quality matters more than speed. + +--- diff --git a/.github/ISSUE_TEMPLATE/feat.yml b/.github/ISSUE_TEMPLATE/feat.yml index ebba492..efce0e6 100644 --- a/.github/ISSUE_TEMPLATE/feat.yml +++ b/.github/ISSUE_TEMPLATE/feat.yml @@ -59,11 +59,10 @@ body: id: before attributes: label: Avant de vous jeter dans le code + placeholder: "Quelques conseils avant de vous jeter dans le code..." value: | Avant de vous jeter dans le code, assurez-vous de bien avoir compris ce qu'il faut faire et comment faire. Au besoin, pingez le lead Web dans le salon Discord et posez vos questions. Plusieurs personnes peuvent travailler ensemble sur cette issue. - - [Post Discord]() validations: required: false diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3836125..3ddfae2 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -60,7 +60,7 @@ jobs: uses: actions/cache@v4 with: path: .next/cache - key: next-cache-${{ runner.os }}-${{ hashFiles('next.config.mjs') }} + key: next-cache-${{ runner.os }}-${{ hashFiles('next.config.ts') }} restore-keys: | next-cache-${{ runner.os }}- diff --git a/.vscode/settings.json b/.vscode/settings.json index 5cf7dac..1360f3e 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -7,7 +7,8 @@ "Versions", "API", "Webhook", - "Internationalisation" + "Internationalisation", + "Documentation" ], "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.tabSize": 2, diff --git a/Documentation/Guidelines/CodeReviewProcess.md b/Documentation/Guidelines/CodeReviewProcess.md new file mode 100644 index 0000000..b93e1d3 --- /dev/null +++ b/Documentation/Guidelines/CodeReviewProcess.md @@ -0,0 +1,394 @@ +# Code Review Process + +This document describes the complete code review process for the DyingStar project, from creating a feature to deploying to staging. + +## Table of Contents + +- [Introduction](#introduction) +- [Prerequisites](#prerequisites) +- [Development Process](#development-process) +- [Before Creating the Pull Request](#before-creating-the-pull-request) +- [Creating the Pull Request](#creating-the-pull-request) +- [Automated CI/CD Pipeline](#automated-cicd-pipeline) +- [Review Process](#review-process) +- [Merge and Deployment](#merge-and-deployment) +- [Quick Checklist](#quick-checklist) + +## Introduction + +The DyingStar project uses the **git-flow** model to manage development. All development is done in feature branches, which are then merged into `develop` via Pull Request after validation. + +The code review process ensures code quality, architectural consistency, and adherence to best practices before a change is integrated. + +> πŸ“– More information on git-flow: [DevelopmentProcess Documentation](./DevelopmentProcess.md) + +## Prerequisites + +Before starting development: + +1. **Get issue details** from GitHub Projects +2. **Ask your questions** to the Website Lead on Discord in the post linked to the issue +3. **Request assignment** of the issue from the Website Lead +4. **Fully understand the requirements** listed in the issue (Design, Frontend, Backend, Integration) + +## Development Process + +### 1. Update the `develop` branch + +Make sure you have the latest version of `develop`: + +```bash +git checkout develop +git pull origin develop +``` + +### 2. Create the feature branch + +Create your branch following the naming convention: + +```bash +git checkout -b feat/{issue-number}-{ShortIssueName} +``` + +**Examples:** + +- `feat/123-AddUserProfile` +- `fix/456-FixLoginBug` + +### 3. Development + +Develop the features according to the issue requirements. + +**Best practices:** + +- Make regular commits with clear messages +- Test your changes locally with `make up` then `make pnpm dev` +- Follow the project's code conventions + +## Before Creating the Pull Request + +### 1. Synchronization with `develop` + +Before creating your PR, synchronize your branch with `develop` to avoid conflicts: + +```bash +git pull origin develop +``` + +If conflicts appear, resolve them locally and test that everything works. + +### 2. Mandatory local checks + +Before pushing, run the following commands to ensure your code meets the standards: + +#### a) Clean (Lint + Typecheck + Prettier) + +```bash +make pnpm clean +``` + +This command executes: + +- `eslint . --fix`: Analyzes and automatically fixes lint errors +- `tsc --noEmit`: Checks TypeScript types without generating files +- `prettier --write .`: Formats the code according to project rules + +#### b) Build + +```bash +make pnpm build +``` + +This command compiles the Next.js application with Turbopack. The build must succeed without errors. + +> ⚠️ **Important**: These two steps are **mandatory** before creating a PR. If the build fails, do not create the PR. + +### 3. Commit and push + +Once all checks pass: + +```bash +git add . +git commit -m "feat: description of your feature" +git push origin feat/{issue-number}-{ShortIssueName} +``` + +## Creating the Pull Request + +### 1. Open the Pull Request on GitHub + +- Go to the GitHub repository +- Click on "Compare & pull request" or create a new PR +- **Base branch**: `develop` +- **Compare branch**: your feature branch + +### 2. Fill in the PR description + +A good description should contain: + +**Title:** + +- Format: `[#{issue-number}] Short feature title` +- Example: `[#123] Add user profile page` + +**Description:** + +```markdown +## Context + +Describe the context and objective of this PR. + +## Changes + +- List of main modifications +- New features added +- Bugs fixed + +## Screenshots (if applicable) + +Add screenshots for UI changes + +## Requirements Checklist + +- [ ] Design: [description if applicable] +- [ ] Frontend: [description] +- [ ] Backend: [description] +- [ ] Integration: [description] + +## Tests Performed + +- [ ] Local tests OK +- [ ] Build successful +- [ ] Lint/Typecheck/Prettier OK +``` + +### 3. Link the GitHub issue + +In the PR description, add: + +```markdown +Closes #123 +``` + +This will automatically link the issue to the PR and close it upon merge. + +### 4. Verify the requirements + +Make sure you have addressed **all requirements** listed in the original issue: + +- βœ… Design +- βœ… Frontend +- βœ… Backend +- βœ… Integration (CI/CD, observability, documentation) + +## Automated CI/CD Pipeline + +As soon as the PR is created, **GitHub Actions** automatically triggers to validate your code. + +### Pipeline steps + +The pipeline executes the following steps (defined in `.github/workflows/build.yml`): + +1. **Environment setup** + - Node.js 22 + - pnpm (version from `package.json`) + - Dependency cache + +2. **Install dependencies** + + ```bash + pnpm install --frozen-lockfile + ``` + +3. **Type generation** + + ```bash + pnpm type:generate + ``` + +4. **Lint CI** + + ```bash + pnpm lint:ci + ``` + + This command executes: + - `eslint . --max-warnings 0`: Lint with zero tolerance for warnings + - `tsc --noEmit`: Type checking + - `prettier --check .`: Format checking (without modification) + +5. **Build Next.js** + + ```bash + pnpm build + ``` + +6. **Build Docker Image** (without push for PRs) + +### Check the pipeline status + +- The pipeline status is displayed directly in the PR +- βœ… **Checks passed**: All tests are OK, the PR can be reviewed +- ❌ **Checks failed**: Errors have been detected, you must fix them + +> ⚠️ **Important**: A PR can only be merged if all checks are green. + +### In case of failure + +If the pipeline fails: + +1. Check the detailed logs in the "Checks" tab of the PR +2. Fix the errors locally +3. Re-run `make pnpm clean` and `make pnpm build` +4. Commit and push the fixes +5. The pipeline will rerun automatically + +## Review Process + +### 1. Notification + +Once the PR is created and checks have passed, **notify the team on Discord**: + +``` +πŸ”” PR ready for review: [PR Link] +Issue: #123 - Issue title +``` + +### 2. Review by another developer (recommended) + +Another developer can perform a review for: + +**Review criteria:** + +- βœ… **Code quality**: Readability, variable/function naming +- βœ… **Architecture**: Respect for project patterns +- βœ… **Performance**: No unnecessary blocking code +- βœ… **Security**: No obvious vulnerabilities +- βœ… **Documentation**: Comments / Documentation.md if necessary + +The reviewer can: + +- βœ… **Approve** the PR if everything is OK +- πŸ’¬ **Comment** to request clarifications +- ❌ **Request changes** if corrections are needed + +### 3. Mandatory review by the Website Lead + +The **Website Lead** must review and approve the PR before merge. + +They verify: + +- Compliance with issue requirements +- Consistency with overall architecture +- Alignment with project vision + +### 4. Address review comments + +If changes are requested: + +1. Make the requested modifications +2. Re-run `make pnpm clean` and `make pnpm build` +3. Commit and push +4. Respond to review comments +5. Re-request review if necessary + +## Merge and Deployment + +### 1. Final approval + +Once all reviews are passed and approved: + +- βœ… All GitHub Actions checks are green +- βœ… At least one approval from the Website Lead +- βœ… All review comments are resolved + +### 2. Merge into `develop` + +**Only the Website Lead can merge the PR.** + +The merge is done via the GitHub interface: + +1. Click on "Merge pull request" +2. Choose the merge type (usually "Squash and merge") +3. Confirm the merge + +### 3. Automatic deployment to staging + +As soon as the code is merged into `develop`, **GitHub Actions automatically triggers** the staging deployment: + +**Deployment pipeline:** + +1. **Application build** (job `build`) +2. **Docker image build** (job `docker-image`) + - Tag: `ghcr.io/dyingstar-game/website:staging` + - Tag: `ghcr.io/dyingstar-game/website:staging-{sha}` +3. **Image push** to GitHub Container Registry (GHCR) +4. **SSH deployment** (job `deploy`) + - Connection to staging server + - Pull of new Docker image + - Container restart via `docker-compose` + +**Estimated duration:** 5-10 minutes + +### 4. Staging verification + +After deployment: + +1. **Wait** for the deployment pipeline to finish (green checks) +2. **Verify** that the application works on the staging environment +3. **Test** your feature on staging +4. **Report** any issues to the Website Lead + +## Quick Checklist + +Use this checklist to make sure you don't forget anything: + +### Before developing + +- [ ] Issue read and understood +- [ ] Issue assignment obtained +- [ ] `develop` branch up to date +- [ ] Feature branch created with correct convention + +### During development + +- [ ] Code developed according to requirements +- [ ] Local tests performed +- [ ] Regular commits with clear messages + +### Before the PR + +- [ ] Merge of `develop` into my branch +- [ ] Conflicts resolved (if applicable) +- [ ] `make pnpm clean` executed successfully βœ… +- [ ] `make pnpm build` executed successfully βœ… +- [ ] Code committed and pushed + +### Creating the PR + +- [ ] PR created with complete description +- [ ] Issue linked with `Closes #xxx` +- [ ] All issue requirements addressed +- [ ] Screenshots added (if UI) +- [ ] Team notified on Discord + +### After the PR + +- [ ] GitHub Actions pipeline green βœ… +- [ ] Review comments addressed +- [ ] Website Lead approval obtained +- [ ] PR merged by Website Lead +- [ ] Staging deployment verified + +--- + +## Useful Resources + +- [Git-flow model](https://nvie.com/posts/a-successful-git-branching-model/) +- [Development Process Documentation](./DevelopmentProcess.md) +- [Architecture Documentation](./architecture/Architecture.md) +- [Makefile commands](../../Makefile) + +--- + +**Questions?** Contact the Website Lead on Discord πŸ’¬ diff --git a/Documentation/Guidelines/DevelopmentProcess.md b/Documentation/Guidelines/DevelopmentProcess.md new file mode 100644 index 0000000..d58c3c3 --- /dev/null +++ b/Documentation/Guidelines/DevelopmentProcess.md @@ -0,0 +1,142 @@ +# Development Process + +The application is developed using the git-flow model. Developers cannot commit to **master** and **develop** branches. All features are developed in feature branches. A feature can then be merged into develop using Pull/merge request. + +You can find more information about the git-flow model [here](https://nvie.com/posts/a-successful-git-branching-model/). + +Here is a screenshot of the git-flow model : ![Git-flow Model](./pictures/git-flow-model.png) + +All branches must be named using the following conventions : + +- `feat/{issue-number}-{ShortIssueName}` : use for application new features +- `fix/{issue-number}-{ShortIssueName}` : use for fixing application bugs / issues +- `release/release-{semantic-version-number}` : use for release tasks + +examples : + +- feat/15469-AddNewFeature +- fix/15469-FixBug +- release/release-1.2.3 + +## Merging process + +### Merging process for `feat` or `fix` branch into `develop` branch + +_Only the Website Lead can merge the `feat` or `fix` branch into the `develop` branch_ + +- Get all details from the issue on github projects +- Ask the Website Lead for any questions about the issue on discord post related to the issue +- Ask the Website Lead to be assigned to the issue +- Updated the `develop` : `git pull origin develop` +- Create feature branch : `git checkout -b feat/15469-AddNewFeature` +- Develop the specified requirements +- Run the formater, linter, tests, build and make sure they are passing +- Commit and Push the code +- Create a Pull request to merge the feature branch into the `develop` branch +- Indicate on discord post that the PR is ready for review +- Address the required review comments (if any) +- Approve the PR when the code is ready to be merged by the Website Lead +- Website Lead merge the PR into the `develop` branch + +### Creating hotfix process : + +#### 1. Creating the hotfix branch + +Create the branch from `main` (not from `develop`): + +```bash +git checkout main +git pull origin main +git checkout -b hotfix/hotfix-1.2.4 +``` + +> πŸ“ **Note**: The hotfix increments the PATCH number (1.2.3 β†’ 1.2.4) + +#### 2. Fixing the critical bug + +- Fix **only** the critical bug +- Do **not** make other changes +- Test locally + +```bash +make pnpm clean +make pnpm build +``` + +#### 3. Updating the version + +Edit `package.json`: + +```json +{ + "version": "1.2.4" +} +``` + +#### 4. Commit and push + +```bash +git add . +git commit -m "hotfix(Build Process): fix critical bug in production" +git push origin hotfix/hotfix-1.2.4 +``` + +#### 5. Pull Request to `main` + +- Create a PR from `hotfix/hotfix-1.2.4` to `main` +- **Title**: `[HOTFIX] v1.2.4 - Description of the critical bug` +- Mark the PR as urgent +- Immediately notify the Website Lead + +#### 6. Express review and merge + +- Quick but thorough review by the Website Lead +- Merge into `main` + +#### 7. Tag creation + +```bash +git checkout main +git pull origin main +git tag -a v1.2.4 -m "Hotfix 1.2.4" +git push origin v1.2.4 +``` + +Production deployment is triggered automatically. + +#### 8. Merge-back to `develop` + +**IMPORTANT**: The hotfix must also be integrated into `develop`: + +```bash +git checkout develop +git pull origin develop +git merge main +git push origin develop +``` + +This triggers a staging deployment with the fix. + +#### 9. Creating the GitHub Release + +Create a release on GitHub documenting the hotfix. + +### Creating release process : + +_Only the Website Lead can create a release_ + +- Updated the `develop` : `git pull origin develop` +- Create release branch : `git checkout -b release/release-1.2.3` +- Update the version number in the `package.json` file +- _On this branch: small fixes and preparation of metadata (changelog, dates, etc.). No big features_ +- Update changelog, version notes, build numbers... +- Commit and Push the code +- Create a Pull request to merge the release branch into the `master` branch +- Indicate on discord post that the PR is ready for review +- Address the required review comments (if any) +- Approve the PR when the code is ready to be merged by the Website Lead +- Merge the PR into the `master` branch +- Create tag with the new version number : `git tag -a v1.2.3 -m "Release 1.2.3"` +- Push the tag : `git push origin v1.2.3` +- Merge the `master` branch into the `develop` branch +- Create a new release on github with the new version number diff --git a/Documentation/Guidelines/Onboarding.md b/Documentation/Guidelines/Onboarding.md new file mode 100644 index 0000000..b8a126b --- /dev/null +++ b/Documentation/Guidelines/Onboarding.md @@ -0,0 +1,49 @@ +# [DyingStar - Webapp] Tools + +Please install following tools + +| Tool | Version | Required | +| -------------------------------------------------- | ----------------- | -------- | +| [Node.js](https://nodejs.org/en) | 22.20.0 or higher | Yes | +| [Docker](https://www.docker.com/) | 24.0.0 or higher | Yes | +| [Docker Compose](https://docs.docker.com/compose/) | 2.20.0 or higher | Yes | +| [Make](https://www.gnu.org/software/make/) | 3.81 or higher | Yes | +| [Git](https://git-scm.com/) | 2.50.0 or higher | Yes | +| [pnpm](https://pnpm.io/) | 10.17.1 or higher | Yes | + +# Git command-line configuration + +Make sure you have configured your user with Git. This information will be used by Git. + +``` +git config --global user.name "Your Fullname" +git config --global user.email "Your Email" +``` + +Windows users should use Git bash for better command-line experience. If you are not well-versed with Git then you can read the [tutorial](https://github.com/shekhargulati/git-the-missing-tutorial). + +# Connecting to Github using SSH + +Refer to this [link](https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/connecting-to-github-with-ssh) to setup SSH for your Github account. + +# Get your access to the repository + +Ask to the Website Lead on this [discord channel](https://discord.com/channels/1399325839665004554/1417133740810833940) to get push permissions to the repository. + +# Clone the application + +Clone the application using the following command. + +``` +git clone git@github.com:DyingStar-game/website.git +``` + +# Local Development + +## Setup + +1. Copy `.env.sample` to `.env.local` and fill in the required environment variables +2. Run `make up` to start the development environment (MeiliSearch service) +3. Run `make pnpm dev` to start the Next.js development server +4. Open your browser and navigate to `http://localhost:3000` to see the website. +5. To stop the development server, press `Ctrl+C` in the terminal where `make pnpm dev` was run. diff --git a/Documentation/Guidelines/ReleaseAndDeployment.md b/Documentation/Guidelines/ReleaseAndDeployment.md new file mode 100644 index 0000000..22e2bf9 --- /dev/null +++ b/Documentation/Guidelines/ReleaseAndDeployment.md @@ -0,0 +1,711 @@ +# Release and Deployment Process + +This document describes the complete release creation and deployment process for the DyingStar project, based on the git-flow model and the GitHub Actions CI/CD pipeline. + +## Table of Contents + +- [Introduction](#introduction) +- [Environments](#environments) +- [Release Process](#release-process) +- [Detailed CI/CD Pipeline](#detailed-cicd-pipeline) +- [Hotfix Process](#hotfix-process) +- [Rollback and Recovery](#rollback-and-recovery) +- [Verification and Tests](#verification-and-tests) +- [Release Checklist](#release-checklist) + +## Introduction + +The DyingStar project uses the **git-flow** model for release and deployment management. The process is automated via GitHub Actions and ensures reliable deployments to staging and production. + +### Roles and Responsibilities + +**Only the Website Lead can:** + +- Create releases +- Merge release branches to `main` +- Create version tags +- Trigger production deployments + +### Versioning + +The project uses **Semantic Versioning** (SemVer): + +- `vMAJOR.MINOR.PATCH` (e.g., `v1.2.3`) +- **MAJOR**: Incompatible API changes +- **MINOR**: New backwards-compatible features +- **PATCH**: Backwards-compatible bug fixes + +> πŸ“– More information: [https://semver.org/](https://semver.org/) + +## Environments + +### Staging + +**Trigger:** Automatic on push to the `develop` branch + +**Characteristics:** + +- Docker tag: `ghcr.io/dyingstar-game/website:staging` +- Secondary tag: `ghcr.io/dyingstar-game/website:staging-{sha}` +- Architecture: `linux/amd64` only +- Port: `8101` (according to `docker/staging.compose.yml`) + +**Usage:** + +- Testing new features +- Pre-production validation +- Demonstrations + +### Production + +**Trigger:** Automatic on creation of a `v*` tag (e.g., `v1.2.3`) + +**Characteristics:** + +- Primary Docker tag: `ghcr.io/dyingstar-game/website:v{version}` +- Secondary tag: `ghcr.io/dyingstar-game/website:prod` +- Architecture: Multi-platform (`linux/amd64`, `linux/arm64`) +- Deployment via SSH to production server + +**Specifics:** + +- Multi-architecture build for maximum compatibility +- Protected environment requiring approvals +- Active monitoring and alerts + +## Release Process + +### Prerequisites + +Before creating a release, ensure that: + +- βœ… All features for the release are merged into `develop` +- βœ… The staging environment is stable +- βœ… Staging tests are conclusive +- βœ… The changelog is ready + +### Release Creation Steps + +#### 1. Update `develop` + +```bash +git checkout develop +git pull origin develop +``` + +#### 2. Create the release branch + +Create a release branch following the naming convention: + +```bash +git checkout -b release/release-1.2.3 +``` + +> πŸ“ **Note**: Replace `1.2.3` with the appropriate version number according to SemVer + +#### 3. Update the version number + +Edit the `package.json` file and update the version: + +```json +{ + "name": "dying-star", + "version": "1.2.3", + ... +} +``` + +#### 4. Prepare metadata + +On this branch, only perform: + +- βœ… CHANGELOG update +- βœ… Version notes addition +- βœ… Minor documentation fixes +- βœ… Small critical bugfixes discovered + +❌ **No major new features** + +#### 5. Local verification + +Before creating the PR, run the verifications: + +```bash +make pnpm clean +make pnpm build +``` + +#### 6. Commit and push + +```bash +git add . +git commit -m "chore: prepare release 1.2.3" +git push origin release/release-1.2.3 +``` + +#### 7. Pull Request creation + +- Create a PR from `release/release-1.2.3` to `main` +- **Title**: `[Release] v1.2.3` +- **Description**: + +```markdown +## Release v1.2.3 + +### New features + +- Feature 1 +- Feature 2 + +### Bug fixes + +- Fix 1 +- Fix 2 + +### Improvements + +- Improvement 1 + +### Breaking Changes (if applicable) + +- Breaking change 1 + +### Migration notes (if applicable) + +Instructions for users/developers +``` + +- Notify the team on Discord + +#### 8. Review and Approval + +- The Website Lead reviews the PR +- Other developers can review (recommended) +- Address comments if necessary +- Final approval by the Website Lead + +#### 9. PR Merge + +**The Website Lead merges the PR into `main`:** + +``` +1. Merge pull request +2. Merge type: usually "Squash and merge" +3. Confirm the merge +``` + +#### 10. Version tag creation + +Once the PR is merged into `main`: + +```bash +git checkout main +git pull origin main +git tag -a v1.2.3 -m "Release 1.2.3" +git push origin v1.2.3 +``` + +> ⚑ **Important**: Pushing the tag automatically triggers production deployment + +#### 11. Merge-back to `develop` + +After production deployment, merge changes back into `develop`: + +```bash +git checkout develop +git pull origin develop +git merge main +git push origin develop +``` + +#### 12. GitHub Release creation + +1. Go to GitHub β†’ Releases β†’ Draft a new release +2. Choose the tag `v1.2.3` +3. Title: `Release v1.2.3` +4. Description: Copy the release notes from the PR +5. Add binaries/assets if necessary +6. Publish the release + +## Detailed CI/CD Pipeline + +The pipeline is defined in `.github/workflows/build.yml` and consists of 3 main jobs. + +### Job 1: Build Next.js + +**Trigger:** + +- Push to `develop` +- Push of `v*` tags +- Pull Requests to `main` or `develop` +- Manual workflow (workflow_dispatch) + +**Steps:** + +1. **Code checkout** + + ```yaml + uses: actions/checkout@v4 + ``` + +2. **Environment setup** + - Container: `node:22-alpine` + - Installation of tar and jq + - CPU: 2 cores + +3. **pnpm configuration** + + ```bash + corepack enable + VERSION=$(jq -r '.packageManager|capture("pnpm@(?.*)$").v' package.json) + corepack prepare pnpm@${VERSION} --activate + ``` + +4. **Dependency caching** + - pnpm cache based on `pnpm-lock.yaml` + - Next.js cache based on `next.config.ts` + +5. **Dependency installation** + + ```bash + pnpm fetch --silent + pnpm install --frozen-lockfile --prefer-offline + ``` + +6. **Allowed scripts configuration** + + ```bash + pnpm config set allow-scripts "@parcel/watcher,@tailwindcss/oxide,esbuild,sharp" + ``` + +7. **Environment files recreation** + - `.env` from the `WEBSITE_ENV_FILE` secret + - `.env.production` from the same secret + +8. **Type generation** + + ```bash + pnpm type:generate + ``` + +9. **Lint CI** + + ```bash + pnpm lint:ci + ``` + + This command executes: + - `eslint . --max-warnings 0` + - `tsc --noEmit` + - `prettier --check .` + +10. **Next.js Build** + + ```bash + NODE_OPTIONS=--max-old-space-size=4096 pnpm build + ``` + +11. **Dev dependencies cleanup** + + ```bash + pnpm prune --prod + ``` + +12. **Runtime artifact creation** + + ```bash + tar -czf runtime.tar.gz \ + .next/standalone \ + .next/static \ + public \ + package.json \ + pnpm-lock.yaml + ``` + +13. **Artifact upload** + - Name: `next-runtime` + - Retention: 1 day + +### Job 2: Docker Image + +**Dependencies:** Requires the `build` job + +**Steps:** + +1. **Download runtime artifact** + +2. **Artifact extraction** + + ```bash + tar -xzf artifact/runtime.tar.gz + ``` + +3. **Target decision (prod/staging/none)** + - **Production**: if `v*` tag + - Platforms: `linux/amd64,linux/arm64` + - **Staging**: if `develop` branch or manual workflow + - Platforms: `linux/amd64` + - **None**: for PRs (build only, no push) + +4. **Docker tags calculation** + + **For staging:** + + ``` + Primary tag: ghcr.io/dyingstar-game/website:staging + Secondary tag: ghcr.io/dyingstar-game/website:staging-{sha} + ``` + + **For production:** + + ``` + Primary tag: ghcr.io/dyingstar-game/website:v1.2.3 + Secondary tag: ghcr.io/dyingstar-game/website:prod + ``` + +5. **Docker Buildx & QEMU Setup** + - Buildx for multi-platform + - QEMU if ARM64 architecture needed + +6. **Push and cache policy** + - **PR**: No push, GitHub Actions cache + - **Staging/Prod**: Push to GHCR, registry cache + +7. **GitHub Container Registry login** + + ```bash + docker login ghcr.io -u ${{ github.actor }} + ``` + +8. **Build & Push image** + - Dockerfile: `docker/Dockerfile.prod` + - Cache from: `ghcr.io/dyingstar-game/website:buildcache` + - Cache to: same reference + +### Job 3: Deploy + +**Dependencies:** Requires the `docker-image` job + +**Condition:** Only if target = `staging` or `prod` + +**Environment:** + +- `staging`: if `develop` branch +- `prod`: if `v*` tag + +**Steps:** + +1. **Checkout compose files** + +2. **Compose file selection** + - Production: `${{ secrets.COMPOSE_FILE_PROD }}` + - Staging: `${{ secrets.COMPOSE_FILE_STAGING }}` + +3. **SSH deployment** + + Connection to server via SSH with: + - Host: `${{ secrets.SSH_HOST }}` + - User: `${{ secrets.SSH_USER }}` + - Key: `${{ secrets.SSH_KEY }}` + - Port: `${{ secrets.SSH_PORT || 22 }}` + + Executed script: + + ```bash + # Registry login + echo "${{ secrets.GHCR_PAT }}" | docker login ghcr.io -u "${{ secrets.GHCR_USERNAME }}" --password-stdin + + # Pull new image + cd docker + docker compose -f {compose-file} pull --ignore-pull-failures + + # Container restart + docker compose -f {compose-file} up -d --no-deps + + # Verification + docker compose -f {compose-file} ps + ``` + +**Total estimated duration:** 5-10 minutes + +## Hotfix Process + +Hotfixes are used to fix critical bugs in production that cannot wait for the next release. + +### When to create a hotfix? + +- ❌ Critical bug in production +- ❌ Security vulnerability +- ❌ Data loss +- ❌ Service unavailable + +❌ **Do not use for:** + +- Minor non-critical bugs +- New features +- Non-urgent performance improvements + +## Rollback and Recovery + +### Rollback Scenarios + +A rollback may be necessary if: + +- The deployment causes critical errors +- Features don't work as expected +- Severe performance issues appear + +### Rollback Procedure + +#### Option 1: Docker Rollback (Fast) + +**On production/staging server:** + +1. **Identify the previous stable version** + + Available Docker tags: + - `ghcr.io/dyingstar-game/website:v1.2.2` (previous version) + - `ghcr.io/dyingstar-game/website:v1.2.3` (current problematic version) + +2. **Modify the compose file** + + SSH to the server: + + ```bash + ssh user@server + cd docker + ``` + + Edit the compose file (staging.compose.yml or prod.compose.yml): + + ```yaml + services: + app: + image: ghcr.io/dyingstar-game/website:v1.2.2 # Stable version + ``` + +3. **Restart containers** + + ```bash + docker compose -f {compose-file} pull + docker compose -f {compose-file} up -d --force-recreate + docker compose -f {compose-file} ps + ``` + +4. **Verify rollback** + - Test the application + - Check logs: `docker compose -f {compose-file} logs -f app` + +**Estimated duration:** 2-5 minutes + +#### Option 2: Git Rollback (Complete) + +If the issue requires a complete code rollback: + +1. **Create a release revert** + + ```bash + git checkout main + git pull origin main + git revert -m 1 + git push origin main + ``` + +2. **Create a new patch tag** + + ```bash + git tag -a v1.2.4 -m "Rollback to 1.2.2" + git push origin v1.2.4 + ``` + +3. **Wait for automatic deployment** + +### Recovery Procedure + +After a rollback, to recover and fix: + +1. **Identify the root cause** + - Analyze logs + - Reproduce the bug locally + +2. **Create a hotfix** + Follow the [Hotfix Process](#hotfix-process) + +3. **Test thoroughly** + - Local tests + - Staging tests + - Non-regression tests + +4. **Redeploy** + Create a new tag once the fix is validated + +## Verification and Tests + +### Pre-Release Tests + +Before creating a release, verify: + +#### Local Tests + +```bash +# Start development environment +make up +make pnpm dev + +# In another terminal, test +# - Navigation on all pages +# - Main features +# - Responsive design +``` + +#### Build Tests + +```bash +# Clean and build +make pnpm clean +make pnpm build + +# Verify there are no errors +``` + +#### Staging Tests + +Once merged into `develop`: + +1. Wait for automatic staging deployment +2. Test all new features +3. Verify existing features (non-regression) +4. Test on different browsers +5. Test responsive (mobile/tablet/desktop) + +### Post-Deployment Verification + +After a production deployment: + +#### Immediate Verification (0-5 min) + +- [ ] Site is accessible +- [ ] No 500 errors +- [ ] Homepage loads correctly +- [ ] Authentication works +- [ ] Main navigation works + +#### In-Depth Verification (5-30 min) + +- [ ] All new features work +- [ ] Existing critical features OK +- [ ] External integrations OK (GitHub, Meilisearch) +- [ ] Acceptable performance (loading times) +- [ ] No JavaScript errors in console + +#### Continuous Monitoring (30 min - 24h) + +- [ ] Monitor error logs +- [ ] Check performance metrics +- [ ] Monitor user errors +- [ ] Team and user feedback + +### Verification Commands + +#### Check Docker containers + +```bash +# SSH to server +ssh user@server +cd docker + +# Container status +docker compose -f {compose-file} ps + +# Application logs +docker compose -f {compose-file} logs -f app + +# Meilisearch logs +docker compose -f {compose-file} logs -f meilisearch +``` + +#### Check Docker images + +```bash +# List images on server +docker images | grep website + +# Check available tags on GHCR +# Via GitHub UI: Packages β†’ website β†’ View all tagged versions +``` + +## Release Checklist + +Use this checklist to ensure a flawless release process. + +### Phase 1: Preparation + +- [ ] All planned features are merged into `develop` +- [ ] CHANGELOG prepared with all modifications +- [ ] Documentation updated if necessary +- [ ] Team notified of upcoming release + +### Phase 2: Release Creation + +- [ ] Local `develop` branch up to date +- [ ] `release/release-X.Y.Z` branch created +- [ ] Version in `package.json` updated +- [ ] CHANGELOG finalized +- [ ] `make pnpm clean` executed successfully βœ… +- [ ] `make pnpm build` executed successfully βœ… +- [ ] Changes committed and pushed +- [ ] PR created to `main` with complete description +- [ ] Team notified on Discord + +### Phase 3: Review and Validation + +- [ ] Code reviewed by at least 1 developer +- [ ] Website Lead approval obtained +- [ ] All review comments addressed +- [ ] GitHub Actions pipeline green βœ… +- [ ] Final deployment confirmation obtained + +### Phase 4: Merge and Tag + +- [ ] PR merged into `main` by Website Lead +- [ ] Local `main` branch up to date +- [ ] Tag `vX.Y.Z` created +- [ ] Tag pushed to GitHub +- [ ] Production deployment pipeline launched + +### Phase 5: Deployment + +- [ ] GitHub Actions pipeline completed successfully +- [ ] Production deployment confirmed +- [ ] Immediate post-deployment verifications OK +- [ ] Site accessible and functional +- [ ] No critical errors detected + +### Phase 6: Finalization + +- [ ] Changes merged from `main` to `develop` +- [ ] GitHub Release created and published +- [ ] 24h monitoring activated +- [ ] Team notified of successful deployment +- [ ] Communication to users (if necessary) + +### Phase 7: Follow-up (24h-48h) + +- [ ] Error monitoring: no critical errors +- [ ] Stable performance +- [ ] Positive team feedback +- [ ] No rollback needed +- [ ] Post-mortem documentation if incidents + +## Useful Resources + +- [Git-flow model](https://nvie.com/posts/a-successful-git-branching-model/) +- [Semantic Versioning](https://semver.org/) +- [Development Process Documentation](./DevelopmentProcess.md) +- [Code Review Documentation](./CodeReviewProcess.md) +- [GitHub Actions Workflow](.github/workflows/build.yml) +- [Makefile](../../Makefile) + +--- + +**Questions?** Contact the Website Lead on Discord πŸ’¬ diff --git a/Documentation/Guidelines/architecture/ADR/000-Template.md b/Documentation/Guidelines/architecture/ADR/000-Template.md new file mode 100644 index 0000000..ae8f69d --- /dev/null +++ b/Documentation/Guidelines/architecture/ADR/000-Template.md @@ -0,0 +1,72 @@ +# [short title of solved problem and solution] + +- Status: [proposed | rejected | accepted | deprecated | … | superseded by [ADR-0005](0005-example.md)] +- Deciders: [list everyone involved in the decision] +- Date: [YYYY-MM-DD when the decision was last updated] + +Technical Story: [description | ticket/issue URL] + +## Context and Problem Statement + +[Describe the context and problem statement, e.g., in free form using two to three sentences. You may want to articulate the problem in form of a question.] + +## Decision Drivers + +- [driver 1, e.g., a force, facing concern, …] +- [driver 2, e.g., a force, facing concern, …] +- … + +## Considered Options + +- [option 1] +- [option 2] +- [option 3] +- … + +## Decision Outcome + +Chosen option: "[option 1]", because [justification. e.g., only option, which meets k.o. criterion decision driver | which resolves force force | … | comes out best (see below)]. + +### Positive Consequences + +- [e.g., improvement of quality attribute satisfaction, follow-up decisions required, …] +- … + +### Negative Consequences + +- [e.g., compromising quality attribute, follow-up decisions required, …] +- … + +## Pros and Cons of the Options + +### [option 1] + +[example | description | pointer to more information | …] + +- Good, because [argument a] +- Good, because [argument b] +- Bad, because [argument c] +- … + +### [option 2] + +[example | description | pointer to more information | …] + +- Good, because [argument a] +- Good, because [argument b] +- Bad, because [argument c] +- … + +### [option 3] + +[example | description | pointer to more information | …] + +- Good, because [argument a] +- Good, because [argument b] +- Bad, because [argument c] +- … + +## Links + +- [Link type] [Link to ADR] +- … diff --git a/Documentation/Guidelines/architecture/ADRs.md b/Documentation/Guidelines/architecture/ADRs.md new file mode 100644 index 0000000..c12bccd --- /dev/null +++ b/Documentation/Guidelines/architecture/ADRs.md @@ -0,0 +1,5 @@ + + +- [ADR-000](ADR/000-Template.md) - [short title of solved problem and solution] + + diff --git a/Documentation/Guidelines/architecture/Architecture.md b/Documentation/Guidelines/architecture/Architecture.md new file mode 100644 index 0000000..025187e --- /dev/null +++ b/Documentation/Guidelines/architecture/Architecture.md @@ -0,0 +1,89 @@ +# [DyingStar - Webapp] Webapp Architecture + +## Architecture Decision Records + +All ADRs are stored in the [ADR](./ADR) folder and referenced in the [ADRs.md](./ADRs.md) file. + +## Technologies + +The list of technologies we will use to build the application are as follows: + +| Technology | Description | Version | +| -------------------------------- | ------------------------- | -------- | +| [Next.js] | Base framework | 15.5.6 | +| [React] | UI library | 19.1.1 | +| [TypeScript] | Type safety | 5.9.2 | +| [pnpm] | Package manager | 10.17.1 | +| [@t3-oss/env-nextjs] | Environment variables | 0.13.8 | +| [Tailwind CSS] | Styling | 4.1.13 | +| [tailwind-merge] | Merge Tailwind classes | 3.3.1 | +| [class-variance-authority] | Component variants | 0.7.1 | +| [clsx] | Conditional classnames | 2.1.1 | +| [Radix UI] | Headless UI components | Various | +| [lucide-react] | Icon library | 0.542.0 | +| [cmdk] | Command menu | 1.1.1 | +| [better-auth] | Authentication | 1.3.8 | +| [next-intl] | Internationalization | 4.3.9 | +| [@tanstack/react-query] | Server state management | 5.87.1 | +| [@tanstack/react-query-devtools] | React Query DevTools | 5.87.1 | +| [Zustand] | Client state management | 5.0.8 | +| [Zod] | Schema validation | 4.1.5 | +| [react-hook-form] | Form management | 7.62.0 | +| [@hookform/resolvers] | Form validation resolvers | 5.2.1 | +| [Framer Motion] | Animations | 12.23.15 | +| [motion] | Animation library | 12.23.12 | +| [next-safe-action] | Type-safe server actions | 8.0.11 | +| [next-themes] | Theme management | 0.4.6 | +| [next-zod-route] | Zod route validation | 1.0.0 | +| [next-mdx-remote-client] | MDX rendering | 2.1.3 | +| [Shiki] | Syntax highlighting | 3.12.2 | +| [recharts] | Data visualization | 3.1.2 | +| [tslog] | Logging | 4.9.3 | +| [sonner] | Toast notifications | 2.0.7 | +| [nprogress] | Progress bar | 0.2.0 | +| [nuqs] | URL state management | 2.6.0 | +| [date-fns] | Date utilities | 4.1.0 | +| [nanoid] | Unique ID generation | 5.1.5 | +| [up-fetch] | HTTP client | 2.4.0 | +| [react-hotkeys-hook] | Keyboard shortcuts | 5.1.0 | +| [react-use] | React hooks collection | 17.6.0 | +| [markdown-to-jsx] | Markdown to JSX | 7.7.13 | +| [front-matter] | Front matter parser | 4.0.2 | +| [rehype-autolink-headings] | Auto-link headings | 7.1.0 | +| [rehype-slug] | Add slugs to headings | 6.0.0 | +| [remark-gfm] | GitHub Flavored Markdown | 4.0.1 | +| [sass] | CSS preprocessor | 1.92.1 | +| [styled-jsx] | CSS-in-JS | 5.1.7 | +| [ESLint] | Linting | 9.35.0 | +| [Prettier] | Code formatting | 3.6.2 | + +## Non-functional Requirements + +Non-functional requirement for the project are: + +| Quality Attribute | Description | Target | +| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | +| Performance | Transaction Response Time | 2 seconds | +| Availability | System Uptime | 99.9 | +| Throughput | Number of requests/transactions per second at peak time | 1000 RPS | +| Auditability | Ability of the application to show what has happened to it, who did it and when | A log file that captures the event with the timestamp | +| Reliability | Mean time to recovery | System should be able to recover from failure under 5 mins | +| Usability | Usability can be described as the capacity of a system to provide a condition for its users to perform the tasks safely, effectively, and efficiently while enjoying the experience | Browsers: Chrome, IE, Firefox | + +## Services + +The list of services we will use to build the application are as follows: + +| Service | Description | Version | +| ------------- | ------------- | ------- | +| [Meilisearch] | Search engine | 1.22.3 | + +HLD for the services is available in the [web excalidraw](https://excalidraw.com/#room=605670133765d25f7dad,ilvMr8eaNTosJ5krQmHY9A) file. + +## Project Structure Documentation + +The project structure is documented in multiple files for better organization: + +- **[FolderStructure.md](./FolderStructure.md)** β€” High-level architecture overview, key concepts, and folder organization +- **[ProjectTreeFolder.md](./ProjectTreeFolder.md)** β€” Complete file-by-file breakdown of the entire repository +- **[FileTypes.md](./FileTypes.md)** β€” Detailed file naming conventions and patterns diff --git a/Documentation/Guidelines/architecture/FileTypes.md b/Documentation/Guidelines/architecture/FileTypes.md new file mode 100644 index 0000000..866e0bd --- /dev/null +++ b/Documentation/Guidelines/architecture/FileTypes.md @@ -0,0 +1,974 @@ +# File Types and Naming Conventions + +## Overview + +This document provides a comprehensive guide to the file naming conventions and architectural patterns used throughout the DyingStar codebase. Each file type serves a specific purpose and follows strict conventions to maintain code organization, readability, and maintainability. + +--- + +## Table of Contents + +1. [File Type Reference](#file-type-reference) +2. [Detailed Explanations](#detailed-explanations) +3. [Directory Structure Patterns](#directory-structure-patterns) +4. [Path Aliases](#path-aliases) +5. [Best Practices](#best-practices) + +--- + +## File Type Reference + +Quick reference table for all file types: + +| Extension/Pattern | Purpose | Location | Example | +| -------------------- | --------------------------------------------------- | -------------------------------------------------------------- | ---------------------------------- | +| `*.tsx` | React components with JSX | `src/components/`, `src/features/`, `app/` | `button.tsx`, `header.tsx` | +| `*.ts` | Pure TypeScript logic (utilities, configs, helpers) | `src/lib/`, `src/hooks/`, `src/i18n/`, `src/features/`, `app/` | `utils.ts`, `logger.ts` | +| `*.model.ts` | Type definitions and Zod schemas | Any `src/` subdirectory | `navigation.model.ts` | +| `*.hook.ts` | Custom React hooks (outside `src/hooks/`) | `src/features/*/` | `use-news-filter.hook.ts` | +| `*.link.ts` | Navigation link logic and definitions | `src/features/navigation/` | `footer.link.tsx`, `Links.ts` | +| `*.query.ts` | Prisma database queries | `src/lib/queries/` | `user.query.ts` | +| `*.query.hook.ts` | TanStack Query (React Query) queries | `src/features/*/` | `news.query.hook.ts` | +| `*.mutation.hook.ts` | TanStack Query mutations | `src/features/*/` | `create-user.mutation.hook.ts` | +| `*.action.ts` | Server actions (Next.js Server Actions) | `src/lib/actions/` | `newsletter.action.ts` | +| `*.mdx` | Markdown with JSX for content-driven pages | `content/news/`, `app/` | `demo.mdx` | +| `*.config.ts` | Configuration files | Root, `src/i18n/` | `next.config.ts`, `site-config.ts` | +| `middleware.ts` | Next.js middleware (routing, i18n, auth) | Root, `src/` | `middleware.ts` | +| `layout.tsx` | Next.js layouts | `app/` segments | `layout.tsx` | +| `page.tsx` | Next.js pages/routes | `app/` segments | `page.tsx` | +| `loading.tsx` | Next.js loading UI | `app/` segments | `loading.tsx` | +| `error.tsx` | Next.js error boundaries | `app/` segments | `error.tsx`, `global-error.tsx` | +| `not-found.tsx` | Next.js 404 pages | `app/` segments | `not-found.tsx` | +| `route.ts` | Next.js API routes | `app/api/` | `route.ts` | + +--- + +## Detailed Explanations + +### 1. `*.tsx` - React Components + +**Purpose**: Files containing React components that use JSX syntax. + +**Location**: + +- `src/components/` - Reusable UI components +- `src/features/` - Feature-specific components +- `app/` - Next.js App Router pages and layouts + +**Conventions**: + +- Use PascalCase for component names +- Use camelCase for file names +- One primary component per file +- Export component and related types + +**Example**: + +```tsx +// src/components/ui/button.tsx +import * as React from "react"; + +import { cn } from "@lib/utils"; +import { Slot } from "@radix-ui/react-slot"; +import { type VariantProps, cva } from "class-variance-authority"; + +const buttonVariants = cva("justify-center... inline-flex items-center", { + variants: { + variant: { + default: "text-primary-foreground... bg-primary", + destructive: "text-white... bg-destructive", + }, + size: { + default: "px-6 py-2", + sm: "px-5 py-2", + }, + }, +}); + +export type ButtonProps = React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean; + }; + +function Button({ + className, + variant, + size, + asChild = false, + ...props +}: ButtonProps) { + const Comp = asChild ? Slot : "button"; + return ( + + ); +} + +export { Button, buttonVariants }; +``` + +**Usage Scenarios**: + +- UI components (buttons, inputs, cards) +- Layout components (headers, footers, sidebars) +- Feature components (news items, forms, dialogs) +- Page components in the App Router + +--- + +### 2. `*.ts` - Pure TypeScript Logic + +**Purpose**: Pure TypeScript files without JSX, containing business logic, utilities, configurations, or helper functions. + +**Location**: + +- `src/lib/` - Core utilities and libraries +- `src/hooks/` - React hooks +- `src/i18n/` - Internationalization logic +- Root directory - Configuration files + +**Conventions**: + +- Use camelCase for file names (except configs) +- Pure functions without side effects (when possible) +- No React or JSX imports +- Thoroughly documented with JSDoc + +**Example**: + +```ts +// src/lib/utils.ts +import { type ClassValue, clsx } from "clsx"; +import { twMerge } from "tailwind-merge"; + +/** + * Combines class names using clsx and merges Tailwind classes + */ +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} +``` + +**Usage Scenarios**: + +- Utility functions (`utils.ts`, `format.ts`) +- Configuration (`site-config.ts`, `routing.ts`) +- Non-React helpers (`logger.ts`, `server-url.ts`) + +--- + +### 3. `*.model.ts` - Type Definitions and Schemas + +**Purpose**: Dedicated files for TypeScript type definitions and Zod validation schemas. This pattern centralizes type safety and runtime validation. + +**Location**: Any `src/` subdirectory, typically alongside related logic + +**Conventions**: + +- Define both Zod schemas and TypeScript types +- Export schemas and infer types from them +- Group related types logically +- Use clear, descriptive region comments + +**Example**: + +```ts +// src/features/issue/get/IssuesCount.model.ts +import type { FacetHit } from "meilisearch"; +import { z } from "zod"; + +export const IssuesCountSchema = z.object({ + openIssueCount: z.number(), + openIssueWithAssigneeCount: z.number(), + countByProject: z.array(z.custom()), +}); + +export type IssuesCountType = z.infer; +``` + +**Why This Pattern**: + +- **Type Safety**: Compile-time type checking via TypeScript +- **Runtime Validation**: Zod schemas validate data at runtime +- **Single Source of Truth**: Types are inferred from schemas +- **Documentation**: Schemas serve as self-documenting contracts + +**Usage Scenarios**: + +- API response/request types +- Component prop types +- Database model types +- Form validation schemas + +--- + +### 4. `*.hook.ts` - Custom React Hooks (Feature-Specific) + +**Purpose**: Custom React hooks that are specific to a feature and not general enough to belong in `src/hooks/`. + +**Location**: Within feature directories (`src/features/*/`) + +**Conventions**: + +- File name should match hook name +- Use `use` prefix for hook functions +- Export one primary hook per file +- Include TypeScript types for parameters and return values + +**Example**: + +```ts +// src/features/news/use-news-filter.hook.ts +import { useMemo, useState } from "react"; + +import type { NewsItem } from "./news.type"; + +export function useNewsFilter(items: NewsItem[]) { + const [searchTerm, setSearchTerm] = useState(""); + const [category, setCategory] = useState(null); + + const filteredItems = useMemo(() => { + return items.filter((item) => { + const matchesSearch = item.title + .toLowerCase() + .includes(searchTerm.toLowerCase()); + const matchesCategory = !category || item.category === category; + return matchesSearch && matchesCategory; + }); + }, [items, searchTerm, category]); + + return { + filteredItems, + searchTerm, + setSearchTerm, + category, + setCategory, + }; +} +``` + +**Difference from `src/hooks/`**: + +- `src/hooks/*.ts` - General-purpose, reusable across features +- `*.hook.ts` - Feature-specific, co-located with feature code + +**Usage Scenarios**: + +- Feature-specific state management +- Complex component logic extraction +- Business logic hooks tied to a feature + +--- + +### 5. `*.link.ts` / `*.link.tsx` - Navigation Link Definitions + +**Purpose**: Centralized navigation link definitions and logic, providing type-safe routing throughout the application. + +**Location**: `src/features/navigation/` + +**Conventions**: + +- Define link structure with params +- Use link generator functions for dynamic routes +- Export typed link objects +- Support both static and parameterized links + +**Example**: + +```ts +// src/features/navigation/Links.ts +import { z } from "zod"; + +import type { NavigationLink } from "./navigation.type"; + +const PATHS = { + NEWS: `/news/:newsSlug`, +}; + +export const EmptyLinkParamsSchema = z.object({}).strict(); + +export const NewsLinkParamsSchema = EmptyLinkParamsSchema.extend({ + newsSlug: z.string(), +}).strict(); + +// Utility to create link generators +const createLinkGenerator = (path: string, needsParams = false) => { + if (!needsParams) { + return () => path; + } + + return (params: Record = {}) => { + let result = path; + Object.entries(params).forEach(([key, value]) => { + result = result.replace(`:${key}`, value); + }); + return result; + }; +}; + +const createLink = ( + href: string, + label: string, + options: Partial> = {}, + needsParams = false, +): NavigationLink => ({ + href: createLinkGenerator(href, needsParams), + label, + ...options, +}); + +export const LINKS = { + Landing: { + Landing: createLink("/", "Project", undefined, false), + }, + News: { + All: createLink("/news", "All News", undefined, false), + News: createLink(`${PATHS.NEWS}`, "News", { Icon: Info }, true), + }, +}; +``` + +**Benefits**: + +- Type-safe navigation +- Centralized route definitions +- Easy refactoring (change route in one place) +- Auto-complete for links throughout the app + +**Usage Scenarios**: + +- Navigation menus +- Footer links +- Programmatic navigation +- Link generation with parameters + +--- + +### 6. `*.query.ts` - Prisma Database Queries + +**Purpose**: Encapsulates Prisma database queries in reusable, testable functions. + +**Location**: `src/lib/queries/` or within feature directories + +**Conventions**: + +- One query function per operation +- Use descriptive function names +- Include error handling +- Return typed results + +**Example**: + +```ts +// src/lib/queries/user.query.ts +import { prisma } from "@lib/prisma"; +import type { User } from "@prisma/client"; + +export async function getUserById(userId: string): Promise { + return prisma.user.findUnique({ + where: { id: userId }, + include: { + profile: true, + }, + }); +} + +export async function getUsersByRole(role: string): Promise { + return prisma.user.findMany({ + where: { role }, + orderBy: { createdAt: "desc" }, + }); +} +``` + +**Why Separate Query Files**: + +- **Testability**: Easy to mock in tests +- **Reusability**: Share queries across features +- **Maintainability**: Database logic in one place +- **Performance**: Optimize queries independently + +--- + +### 7. `*.query.hook.ts` - TanStack Query (React Query) + +**Purpose**: React hooks that use TanStack Query for server state management, caching, and synchronization. + +**Location**: Within feature directories + +**Conventions**: + +- Use `useQuery` from TanStack Query +- Define query keys at the top +- Include proper TypeScript types +- Handle loading and error states + +**Example**: + +```ts +// src/features/news/news.query.hook.ts +import { useQuery } from "@tanstack/react-query"; + +import type { NewsItem } from "./news.type"; + +// Query keys +export const newsKeys = { + all: ["news"] as const, + lists: () => [...newsKeys.all, "list"] as const, + list: (filters: string) => [...newsKeys.lists(), { filters }] as const, + details: () => [...newsKeys.all, "detail"] as const, + detail: (slug: string) => [...newsKeys.details(), slug] as const, +}; + +// Fetch function +async function fetchNewsItem(slug: string): Promise { + const res = await fetch(`/api/news/${slug}`); + if (!res.ok) throw new Error("Failed to fetch news"); + return res.json(); +} + +// React Query hook +export function useNewsItem(slug: string) { + return useQuery({ + queryKey: newsKeys.detail(slug), + queryFn: () => fetchNewsItem(slug), + staleTime: 5 * 60 * 1000, // 5 minutes + }); +} +``` + +**Benefits**: + +- Automatic caching +- Background refetching +- Optimistic updates +- Request deduplication + +--- + +### 8. `*.mutation.hook.ts` - TanStack Query Mutations + +**Purpose**: React hooks for data mutations (create, update, delete) using TanStack Query. + +**Location**: Within feature directories + +**Conventions**: + +- Use `useMutation` from TanStack Query +- Include optimistic updates +- Invalidate relevant queries +- Handle success/error callbacks + +**Example**: + +```ts +// src/features/news/create-news.mutation.hook.ts +import { useMutation, useQueryClient } from "@tanstack/react-query"; + +import { newsKeys } from "./news.query.hook"; +import type { CreateNewsInput, NewsItem } from "./news.type"; + +async function createNews(data: CreateNewsInput): Promise { + const res = await fetch("/api/news", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(data), + }); + if (!res.ok) throw new Error("Failed to create news"); + return res.json(); +} + +export function useCreateNews() { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: createNews, + onSuccess: () => { + // Invalidate and refetch news list + queryClient.invalidateQueries({ queryKey: newsKeys.lists() }); + }, + }); +} +``` + +**Usage**: + +```tsx +function CreateNewsForm() { + const createNews = useCreateNews(); + + const handleSubmit = (data: CreateNewsInput) => { + createNews.mutate(data, { + onSuccess: () => { + toast.success("News created!"); + }, + }); + }; + + return
...
; +} +``` + +--- + +### 9. `*.action.ts` - Next.js Server Actions + +**Purpose**: Server-side functions that can be called from client components, providing type-safe RPC-style endpoints. + +**Location**: `src/lib/actions/` or within feature directories + +**Conventions**: + +- Use `"use server"` directive +- Use `next-safe-action` for validation +- Define input schemas with Zod +- Handle errors gracefully + +**Example**: + +```ts +// src/lib/actions/newsletter.action.ts +"use server"; + +import { action } from "@lib/actions/safe-actions"; +import { z } from "zod"; + +// src/lib/actions/newsletter.action.ts + +const subscribeNewsletterSchema = z.object({ + email: z.string().email(), + name: z.string().optional(), +}); + +export const subscribeNewsletter = action + .inputSchema(subscribeNewsletterSchema) + .action(async ({ parsedInput: { email, name } }) => { + // Add to newsletter service + await addToMailingList(email, name); + + return { success: true, message: "Successfully subscribed!" }; + }); +``` + +**Usage in Client Component**: + +```tsx +"use client"; + +import { subscribeNewsletter } from "@lib/actions/newsletter.action"; + +export function NewsletterForm() { + const [, execute, isPending] = useAction(subscribeNewsletter); + + const handleSubmit = async (formData: FormData) => { + const result = await execute({ + email: formData.get("email") as string, + }); + + if (result.data?.success) { + toast.success(result.data.message); + } + }; + + return
...
; +} +``` + +**Benefits**: + +- Type-safe client-server communication +- Automatic validation +- No need for API routes for simple operations +- Direct database access from actions + +--- + +### 10. `*.mdx` - Markdown with JSX + +**Purpose**: Content-driven pages that combine Markdown for text content with React components for interactive elements. + +**Location**: + +- `content/news/` - Editorial content (articles, blog posts) +- `app/` - Static/semi-static pages + +**Conventions**: + +- Frontmatter for metadata +- Localized content (separate files per language) +- Use JSX components when needed + +**Example**: + +````mdx +--- +title: Introducing Our New Feature +titleIcon: πŸŽ‰ +category: announcement +description: We're excited to announce a new feature that will change how you work +keywords: + - feature + - announcement + - update +tags: + - product + - release +coverUrl: https://example.com/cover.jpg +date: 2025-01-15T10:00:00 +author: Team DyingStar +authorRoles: + - Product Manager +--- + +# Introducing Our New Feature + +We're thrilled to announce our latest feature! + +## What's New + +Here's what you can expect: + +- **Feature 1**: Description +- **Feature 2**: Description + +```ts +// Code example +const example = "You can include code blocks"; +``` +```` + + + +## Get Started + +Try it out today! + +```` + +**Processing Pipeline**: +1. MDX file stored in `content/` +2. Parsed by `features/markdown/` +3. Managed by feature-specific manager (e.g., `news-manager.ts`) +4. Rendered in App Router pages +5. Metadata extracted for SEO + +**Benefits**: +- Easy content authoring +- Mix static content with dynamic components +- Type-safe component usage +- Great for non-technical content editors + +--- + +### 11. Configuration Files + +#### `site-config.ts` + +**Purpose**: Central configuration for site-wide settings. + +**Example**: + +```ts +// src/site-config.ts +export const SiteConfig = { + title: "Dying Star", + description: "Collect and showcase powerful video and text testimonials", + prodUrl: "https://demo.dyingstar.app", + appId: "dyingstar", + domain: "demo.dyingstar.app", + appIcon: "/images/icon.png", +}; +```` + +#### `middleware.ts` + +**Purpose**: Next.js middleware for request interception and modification. + +**Example**: + +```ts +// middleware.ts +import { routing } from "i18n/routing"; +import createMiddleware from "next-intl/middleware"; + +export default createMiddleware(routing); + +export const config = { + matcher: [ + "/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)", + ], + runtime: "nodejs", +}; +``` + +--- + +### 12. Next.js App Router Special Files + +#### `layout.tsx` + +**Purpose**: Shared UI that wraps pages within a route segment. + +**Key Features**: + +- Persists across navigation +- Can fetch data +- Can be nested + +**Example**: + +```tsx +// app/[locale]/layout.tsx +export default function LocaleLayout({ + children, + params: { locale }, +}: { + children: React.ReactNode; + params: { locale: string }; +}) { + return ( + + +
+ {children} +