chore: инициализация Nx-монорепозитория

Каркас воркспейса: конфигурация Nx и TypeScript, манифест yarn
workspaces, EditorConfig,
параметры docker-сборки и инструкции со скиллами для ИИ-агентов
(AGENTS.md).
This commit is contained in:
arswarog committed 2026-10-26 20:30:59 +03:00
1 parent 231dd48844
commit 8c368cd68f
12 files changed
+13352 -39

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
node_modules
.git
**/dist
.idea
.vscode
.cursor
.husky
+14
View File
@@ -0,0 +1,14 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
max_line_length = 120
tab_width = 2
trim_trailing_whitespace = true
[{*.json,.html,.babelrc,.eslintrc,.prettierrc,.stylelintrc,jest.config}]
tab_width = 2
+5
View File
@@ -48,3 +48,8 @@ Thumbs.db
.nx/polygraph
.nx/self-healing
.nx/migrate-runs
vite.config.*.timestamp*
vitest.config.*.timestamp*
.env
+5 -1
View File
@@ -1,3 +1,7 @@
{
"recommendations": ["nrwl.angular-console", "esbenp.prettier-vscode"]
"recommendations": [
"nrwl.angular-console",
"esbenp.prettier-vscode",
"dbaeumer.vscode-eslint"
]
}
+141 -9
View File
@@ -1,23 +1,155 @@
# AGENTS.md
Инструкции для ИИ-агентов при работе с этим репозиторием: обзор, команды, архитектура и конвенции,
которые нельзя вывести из кода.
## Project Overview
Монорепозиторий Nx с тремя приложениями:
- **api** — NestJS бэкенд (TypeORM + PostgreSQL), порт 5000, глобальный префикс `/api`, Swagger UI
на `/api/docs`
- **web** — React фронтенд (Vite), порт 5173, проксирует `/api/*` на бэкенд
- **api-e2e** — E2E-тесты на Jest для API
Package manager: **yarn** (v1 classic). Версия указана в поле `packageManager` в `package.json`. Все
задачи запускаются через Nx, а не напрямую через инструменты.
## Common Commands
```bash
# Все задачи через Nx (не напрямую)
yarn nx run api:serve # Запуск бэкенда
yarn nx run web:serve # Запуск фронтенда
yarn nx run-many -t serve # Запуск всех приложений
yarn nx run api:build # Сборка бэкенда (webpack)
yarn nx run web:build # Сборка фронтенда (vite)
yarn nx run api:test # Тесты бэкенда (vitest)
yarn nx run web:test # Тесты фронтенда (vitest)
yarn nx run api:test -- --testPathPattern="users" # Один тест-файл
yarn nx run api-e2e:e2e # E2E-тесты
yarn nx run api:lint # ESLint для api
yarn nx run web:lint # ESLint для web
yarn lint # ESLint + Prettier для всего (с автофиксом)
yarn lint:check # Проверка без автофикса
yarn nx run api:db-show # Список миграций и их статус
yarn nx run api:db-migrate # Применить непримененные миграции
yarn nx run api:db-migrations-list # Перегенерировать список миграций
```
## Architecture
### Backend (apps/api)
- NestJS модульная архитектура: модуль — рамка, внутри которой код разложен по слоям
`Controller → Service → Data Access Layer`; наружу модуль отдаёт только то, что осознанно
экспортирует. Подробности — `docs/50-developing/01-api-layers.md`
- Swagger UI доступен на `/api/docs`
- Сборка: `db-migrations-list` (через `dependsOn`) → `webpack-cli build` (`main.js`) →
`webpack-cli build --config webpack.data-source.config.js` (`data-source.js`), последовательно
(`parallel: false`). Запуск через `@nx/js:node`
#### Миграции БД
- Миграции лежат в `apps/api/src/database/migrations/`
- Список миграций **генерируется статически** (`tools/buildDataSource.ts` →
`apps/api/src/database/migrations.ts`), потому что webpack не умеет runtime-glob
- Имя файла обязано начинаться с **13-значного** timestamp, а имя класса — оканчиваться тем же
timestamp: TypeORM берёт его как `parseInt(className.substr(-13))`. Расхождение валит сборку
- **После добавления или удаления миграции список нужно перегенерировать и закоммитить**
(`yarn nx run api:db-migrations-list`, либо это сделает `yarn nx run api:build` через
`dependsOn`). Иначе CI упадёт на шаге `Check migrations list` (`git diff --exit-code`)
- Деплой применяет миграции автоматически (`migration:run -t each` через `docker exec` на проде /
`docker compose exec` на стейджинге) — на каждый тег на проде и на каждый push/PR на стейджинге.
Автоматического бэкапа перед миграцией нет. Подробнее: `docs/90-deploy/10-migrations.md`
- DDL пишется методами `QueryRunner` (`Table`/`TableColumn`), а не строкой SQL; вывод
`migration:generate` — черновик, который переписывают. `down` обязателен. Имя таблицы — строковым
литералом, а не константой `*_TABLE_NAME`: миграция не должна ломаться от удаления модуля.
Data-миграции — отдельным файлом. Перед коммитом — цикл `db-migrate` → `db-revert` → `db-migrate`.
Подробнее: `docs/50-developing/20-migrations.md`
#### Конвенции кода и тестов
Подробности — `docs/50-developing/`:
- Сущности — в `entities/` внутри модуля; имя таблицы — константа `*_TABLE_NAME` рядом с сущностью
(в коде приложения используется везде, в миграциях — нет); колонки — `camelCase`
- Весь доступ к БД — в `*.dal.ts`: `@InjectRepository`/`Repository`/`DataSource` допустимы только
там. DAL приватен для модуля (не в `exports`), наружу модуль отдаёт публичные сервисы
- Тесты — рядом с тестируемым файлом, расширение `.test.ts`; DAL юнит-тестами не покрывается
### Frontend (apps/web)
- React + Vite + React Router; стили — Tailwind CSS
- Слои идут строго в одну сторону: `app → pages → widgets → entities → shared`, обратные зависимости
запрещены. Подробности — `docs/50-developing/02-web-layers.md`
- Тесты: Vitest с jsdom
### TypeScript Paths
Определены в `tsconfig.base.json`:
- `@geo-platform/api/*` → `apps/api/src/*`
- `@geo-platform/web/*` → `apps/web/src/*`
При переименовании воркспейса правятся и `paths`, и `customConditions`.
## Данные для разработки
- `db-snapshot/*.json` — снапшоты dev-БД для локальной разработки (см. `tools/dbSnapshot.ts` /
`dbRestore.ts`).
## Документация (`docs/`)
- **Весь новый код должен соответствовать документации в `docs/`.** Существующий код под неё не
переписывается — приводится к ней по мере того, как его всё равно затрагивают. Отдельные документы
эту оговорку не повторяют
- `.md`-файлы в `docs/` компилируются как MDX (Docusaurus) — в обычном тексте (вне code fence
` ``` ` и вне inline-код-спанов `` ` ``
`` `) нельзя использовать `{...}` и `<` перед небуквенным/нецифро-небуквенным символом или сразу перед словом (например, `<=`, `<lang>`, `<repo>`), иначе сборка падает с `MDX compilation failed`. Внутри code fence и inline-код-спанов такие символы безопасны — MDX не парсит их содержимое как JSX/выражения. Сравнения вида `<= N` замените на `≤ N` (аналогично `>=` → `≥`), а плейсхолдеры вроде `<lang>` — переносите в backtick-код (``
`<lang>` ``) или переформулируйте текст
## Code Quality
- ESLint 9 flat config (корневой `eslint.config.mjs`)
- Prettier для форматирования
- Husky + lint-staged: автоформатирование при коммите
- `@nx/enforce-module-boundaries` включён
<!-- nx configuration start-->
<!-- Leave the start & end comments to automatically receive updates. -->
# General Guidelines for working with Nx
## General Guidelines for working with Nx
- For navigating/exploring the workspace, invoke the `nx-workspace` skill first - it has patterns for querying projects, targets, and dependencies
- When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task through `nx` (i.e. `nx run`, `nx run-many`, `nx affected`) instead of using the underlying tooling directly
- Prefix nx commands with the workspace's package manager (e.g., `pnpm nx build`, `npm exec nx test`) - avoids using globally installed CLI
- For navigating/exploring the workspace, invoke the `nx-workspace` skill first - it has patterns
for querying projects, targets, and dependencies
- When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task
through `nx` (i.e. `nx run`, `nx run-many`, `nx affected`) instead of using the underlying tooling
directly
- Prefix nx commands with the workspace's package manager (e.g., `pnpm nx build`,
`npm exec nx test`) - avoids using globally installed CLI
- You have access to the Nx MCP server and its tools, use them to help the user
- For Nx plugin best practices, check `node_modules/@nx/<plugin>/PLUGIN.md`. Not all plugins have this file - proceed without it if unavailable.
- For Nx plugin best practices, check `node_modules/@nx/<plugin>/PLUGIN.md`. Not all plugins have
this file - proceed without it if unavailable.
- NEVER guess CLI flags - always check nx_docs or `--help` first when unsure
## Scaffolding & Generators
- For scaffolding tasks (creating apps, libs, project structure, setup), ALWAYS invoke the `nx-generate` skill FIRST before exploring or calling MCP tools
- For scaffolding tasks (creating apps, libs, project structure, setup), ALWAYS invoke the
`nx-generate` skill FIRST before exploring or calling MCP tools
## When to use nx_docs
- USE for: advanced config options, unfamiliar flags, migration guides, plugin configuration, edge cases
- DON'T USE for: basic generator syntax (`nx g @nx/react:app`), standard commands, things you already know
- The `nx-generate` skill handles generator discovery internally - don't call nx_docs just to look up generator syntax
- USE for: advanced config options, unfamiliar flags, migration guides, plugin configuration, edge
cases
- DON'T USE for: basic generator syntax (`nx g @nx/react:app`), standard commands, things you
already know
- The `nx-generate` skill handles generator discovery internally - don't call nx_docs just to look
up generator syntax
<!-- nx configuration end-->
View File
Whitespace-only changes.
+88 -3
View File
@@ -1,8 +1,19 @@
{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"defaultBase": "master",
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"production": ["default"],
"default": [
"{projectRoot}/**/*",
"sharedGlobals"
],
"production": [
"default",
"!{projectRoot}/.eslintrc.json",
"!{projectRoot}/eslint.config.mjs",
"!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)",
"!{projectRoot}/tsconfig.spec.json",
"!{projectRoot}/src/test-setup.[jt]s"
],
"sharedGlobals": []
},
"plugins": [
@@ -19,7 +30,81 @@
"watchDepsName": "watch-deps"
}
}
},
{
"plugin": "@nx/eslint/plugin",
"options": {
"targetName": "lint"
}
},
{
"plugin": "@nx/vite/plugin",
"options": {
"buildTargetName": "build",
"testTargetName": "test",
"serveTargetName": "serve",
"devTargetName": "dev",
"previewTargetName": "preview",
"serveStaticTargetName": "serve-static",
"typecheckTargetName": "typecheck",
"buildDepsTargetName": "build-deps",
"watchDepsTargetName": "watch-deps"
}
},
{
"plugin": "@nx/vitest",
"options": {
"testTargetName": "test",
"ciTargetName": "test-ci",
"testMode": "watch"
}
},
{
"plugin": "@nx/webpack/plugin",
"options": {
"buildTargetName": "build",
"serveTargetName": "serve",
"previewTargetName": "preview",
"buildDepsTargetName": "build-deps",
"watchDepsTargetName": "watch-deps",
"serveStaticTargetName": "serve-static"
}
}
],
"analytics": true
"targetDefaults": {
"test": {
"dependsOn": [
"^build"
]
},
"db-{show,migrate,revert,drop}": {
"options": {
"env": {
"TS_NODE_PROJECT": "apps/api/tsconfig.app.json",
"NODE_OPTIONS": "-r tsconfig-paths/register"
}
}
}
},
"generators": {
"@nx/react": {
"application": {
"babel": true,
"style": "tailwind",
"linter": "eslint",
"bundler": "vite"
},
"component": {
"style": "tailwind"
},
"library": {
"style": "tailwind",
"linter": "eslint"
}
}
},
"tui": {
"enabled": false
},
"analytics": false
}
+98 -15
View File
@@ -1,23 +1,106 @@
{
"name": "@org/source",
"version": "0.0.0",
"license": "MIT",
"scripts": {},
"private": true,
"dependencies": {},
"devDependencies": {
"@nx/js": "24.0.0",
"@swc-node/register": "1.11.1",
"@swc/core": "1.15.8",
"@swc/helpers": "0.5.18",
"@types/node": "^24.0.0",
"nx": "24.0.0",
"prettier": "^3.8.1",
"tslib": "^2.3.0",
"typescript": "~6.0.3"
},
"workspaces": [
"apps/*",
"packages/*"
],
"packageManager": "npm@12.0.2"
"scripts": {
"build": "nx run-many -t build",
"clean": "nx run-many -t clean",
"db-drop": "nx run api:db-drop",
"db-migrate": "nx run api:db-migrate",
"db-migrations-list": "nx run api:db-migrations-list",
"db-restore": "nx run api:db-restore",
"db-revert": "nx run api:db-revert",
"db-show": "nx run api:db-show",
"db-snapshot": "nx run api:db-snapshot",
"lint": "run-s lint:fix",
"lint:fix": "run-s lint:*:fix lint:typecheck",
"lint:branch-name": "validate-branch-name",
"lint:check": "run-s lint:typecheck lint:*:check",
"lint:eslint:check": "nx run-many -t lint-check",
"lint:eslint:fix": "nx run-many -t lint",
"lint:format:check": "nx run-many -t format-check",
"lint:format:fix": "nx run-many -t format",
"lint:typecheck": "nx run-many -t typecheck",
"prepare": "husky",
"rebuild": "nx run-many -t clean && nx run-many -t build",
"start": "nx run-many -t serve --parallel"
},
"lint-staged": {
"*.{json,ts,tsx,js,jsx,js,mjs,md,mdx,yaml,yml}": "prettier --write",
"{src,e2e}/**/*.{ts,tsx}": "eslint --quiet --fix",
"*.{scss,css}": "stylelint --fix",
"package.json": "sort-package-json"
},
"resolutions": {
"vite": "^7.0.0"
},
"dependencies": {
"reflect-metadata": "^0.1.13"
},
"devDependencies": {
"@eslint/js": "^9.8.0",
"@nx/eslint": "^22.5.1",
"@nx/eslint-plugin": "^22.5.1",
"@nx/js": "^22.5.1",
"@nx/nest": "^22.5.1",
"@nx/node": "^22.5.1",
"@nx/react": "^22.5.1",
"@nx/vite": "^22.5.1",
"@nx/vitest": "^22.5.1",
"@nx/web": "^22.5.1",
"@nx/webpack": "^22.5.1",
"@swc-node/register": "^1.11.1",
"@swc/cli": "~0.8.0",
"@swc/core": "^1.15.8",
"@swc/helpers": "^0.5.18",
"@types/lodash": "^4.17.24",
"@types/node": "^20.19.9",
"@types/pg": "^8.20.0",
"@vitest/coverage-v8": "^4.0.0",
"@vitest/ui": "^4.0.0",
"autoprefixer": "^10.4.13",
"eslint": "^9.8.0",
"eslint-config-prettier": "^10.0.0",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-import-x": "^4.16.2",
"eslint-plugin-unused-imports": "^4.4.1",
"husky": "^9.1.7",
"lint-staged": "^16.2.7",
"npm-run-all": "^4.1.5",
"nx": "^22.5.1",
"pg": "^8.20.0",
"prettier": "^3.3.3",
"rimraf": "^6.1.3",
"sort-package-json": "^3.6.1",
"stylelint": "^17.14.1",
"stylelint-config-prettier-scss": "^1.0.0",
"stylelint-config-recess-order": "^7.8.0",
"stylelint-config-standard": "^40.0.0",
"stylelint-config-standard-scss": "^17.0.0",
"stylelint-order": "^8.1.1",
"stylelint-prettier": "^5.0.3",
"stylelint-scss": "^7.2.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"tslib": "^2.3.0",
"typescript": "~5.9.2",
"typescript-eslint": "^8.40.0",
"unplugin-swc": "^1.5.10",
"validate-branch-name": "=1.3.1",
"vite": "^7.0.0",
"vitest": "^4.0.0"
},
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
"nx": {
"includedScripts": []
},
"validate-branch-name": {
"pattern": "(^(i\\d+-)?[a-z0-9-]{2,40}$|^\\(.*)",
"errorMsg": "branch name must be like 'i777-short-description'"
}
}
+25 -9
View File
@@ -5,19 +5,35 @@
"emitDeclarationOnly": true,
"importHelpers": true,
"isolatedModules": true,
"lib": ["es2022"],
"lib": [
"es2022"
],
"module": "nodenext",
"moduleResolution": "nodenext",
"noEmitOnError": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"target": "es2022",
"baseUrl": "./",
"customConditions": [
"@geo-platform/source"
],
"paths": {
"@geo-platform/api/*": [
"apps/api/src/*"
],
"@geo-platform/web/*": [
"apps/web/src/*"
]
},
/* Linting */
"strict": true,
"useUnknownInCatchVariables": false,
"strictPropertyInitialization": false,
"noImplicitAny": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"skipLibCheck": true,
"strict": true,
"target": "es2022",
"customConditions": ["@org/source"],
"noUncheckedSideEffectImports": false,
"types": ["*"]
"noUnusedLocals": false
}
}
+11 -2
View File
@@ -2,6 +2,15 @@
"extends": "./tsconfig.base.json",
"compileOnSave": false,
"files": [],
"references": [],
"compilerOptions": {}
"references": [
{
"path": "./apps/web"
},
{
"path": "./apps/api-e2e"
},
{
"path": "./apps/api"
}
]
}
+1
View File
@@ -0,0 +1 @@
export default ['**/vite.config.{mjs,js,ts,mts}', '**/vitest.config.{mjs,js,ts,mts}'];
+12957
View File
File diff suppressed because it is too large. Load diff