nestgen-cli 0.0.7 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/engine/architecture-profile.js +10 -0
  2. package/dist/engine/file-transaction.js +166 -0
  3. package/dist/engine/generated-code.js +26 -0
  4. package/dist/engine/generation-manifest.js +118 -0
  5. package/dist/engine/migration-plan.js +78 -0
  6. package/dist/engine/module-generator.js +157 -0
  7. package/dist/engine/project-config.js +42 -0
  8. package/dist/engine/project-path.js +25 -0
  9. package/dist/engine/project-preflight.js +96 -0
  10. package/dist/engine/resource-generator.js +1153 -0
  11. package/dist/engine/resource-spec.js +287 -0
  12. package/examples/store-api/README.md +76 -0
  13. package/examples/store-api/definitions/customers.resource.json +14 -0
  14. package/examples/store-api/definitions/order-items.resource.json +26 -0
  15. package/examples/store-api/definitions/orders.resource.json +22 -0
  16. package/examples/store-api/definitions/products.resource.json +19 -0
  17. package/examples/store-api/nestgen.example.json +7 -0
  18. package/nestgen.js +700 -86
  19. package/nestjs-generator/features/add_module.sh +68 -24
  20. package/nestjs-generator/features/configure_bootstrap.mjs +42 -0
  21. package/nestjs-generator/features/docker.sh +169 -36
  22. package/nestjs-generator/features/git.sh +4 -2
  23. package/nestjs-generator/features/inject_module_to_app.sh +22 -69
  24. package/nestjs-generator/features/operational_foundation.mjs +210 -0
  25. package/nestjs-generator/features/operations.sh +16 -0
  26. package/nestjs-generator/features/preflight.mjs +13 -0
  27. package/nestjs-generator/features/prisma.sh +48 -8
  28. package/nestjs-generator/features/resource_name.mjs +57 -0
  29. package/nestjs-generator/features/swagger.sh +7 -20
  30. package/nestjs-generator/features/typeorm.sh +68 -7
  31. package/nestjs-generator/features/update_app_module.mjs +146 -0
  32. package/nestjs-generator/features/utils.sh +52 -14
  33. package/nestjs-generator/generate_project.sh +46 -70
  34. package/package.json +63 -31
  35. package/readme.md +298 -120
package/readme.md CHANGED
@@ -1,175 +1,353 @@
1
- # NestGen
1
+ # NestGen CLI
2
2
 
3
- <div align="center">
4
- <img src="https://raw.githubusercontent.com/outis25/nestgen-js/main/assets/logo.png" alt="NestGen Logo" width="200" />
5
- <h3>Générateur modulaire autonome pour projets NestJS</h3>
6
- <p>Architecture DDD • CQRS • Hexagonal • Prisma/TypeORM • Docker/Swagger</p>
3
+ [![npm](https://img.shields.io/npm/v/nestgen-cli?label=npm)](https://www.npmjs.com/package/nestgen-cli)
4
+ [![CI](https://github.com/el-hack/nestgen-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/el-hack/nestgen-cli/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/npm/l/nestgen-cli)](LICENSE)
7
6
 
8
- ![npm](https://img.shields.io/npm/v/@outis25/nestgen?color=crimson&style=for-the-badge)
9
- ![nestjs](https://img.shields.io/badge/NestJS-Scaffolded-red?style=for-the-badge&logo=nestjs)
10
- ![standalone](https://img.shields.io/badge/100%25-Autonome-brightgreen?style=for-the-badge)
11
- ![license](https://img.shields.io/npm/l/@outis25/nestgen?color=blue&style=for-the-badge)
12
- ![downloads](https://img.shields.io/npm/dm/@outis25/nestgen?color=green&style=for-the-badge)
13
- </div>
7
+ NestGen CLI generates NestJS project scaffolding and TypeORM or Prisma resources. The canonical package is [`nestgen-cli`](https://www.npmjs.com/package/nestgen-cli); the canonical repository is [`el-hack/nestgen-cli`](https://github.com/el-hack/nestgen-cli).
14
8
 
15
- ## 📋 Table des matières
9
+ ## Published in 0.2.1 / Disponible dans 0.2.1
16
10
 
17
- - [Introduction](#-introduction)
18
- - [Fonctionnalités](#-fonctionnalités)
19
- - [Installation](#-installation)
20
- - [Guide d'utilisation](#-guide-dutilisation)
21
- - [Architecture générée](#-architecture-générée)
22
- - [Roadmap](#-roadmap)
23
- - [FAQ](#-faq)
24
- - [Contribuer](#-contribuer)
25
- - [Licence](#-licence)
11
+ | Available now / Disponible maintenant | Evidence / Preuve |
12
+ | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
13
+ | Nest project, module and TypeORM or Prisma resource generation | The commands are shipped by `nestgen-cli@0.2.1` and covered by the CLI contract tests. |
14
+ | Declarative resource relations, safe updates and migration plans | The generated manifest protects manual edits; migrations remain explicitly reviewed and applied by the developer. |
15
+ | Operational foundation and authorization metadata | Both are optional extension points; NestGen does not configure an identity provider, a global guard or an external monitoring service. |
16
+ | Store API example | The package ships the [version-pinned example](examples/store-api/README.md), which CI reconstructs from its resource definitions. |
26
17
 
27
- ## 🚀 Introduction
18
+ ## Planned (not released) / Prévu (non publié)
28
19
 
29
- **NestGen** est un générateur de code 100% autonome pour NestJS qui vous permet de créer rapidement des projets et des modules respectant les principes d'architecture avancés. Ce package n'a aucune dépendance externe et embarque tous les templates nécessaires pour générer des applications NestJS suivant les modèles Domain-Driven Design (DDD), Command Query Responsibility Segregation (CQRS) et l'architecture hexagonale.
20
+ The [roadmap](roadmap.md) contains topics under consideration after 0.2.1. They have no release date and are not part of the npm contract until they appear in a versioned guide and `CHANGELOG.md`. La roadmap recense des pistes après 0.2.1 ; elles n’ont ni date de sortie ni engagement de compatibilité avant leur publication dans un guide versionné et le changelog.
30
21
 
31
- Idéal pour les développeurs qui souhaitent maintenir une architecture propre et évolutive, NestGen accélère la phase de setup et garantit la cohérence structurelle de votre application, le tout sans nécessiter d'installation ou de configuration supplémentaire.
22
+ ## Supported contract
32
23
 
33
- ## ✨ Fonctionnalités
24
+ - Node.js `>=24.15.0 <27` (24, 25 and 26), npm 11, pnpm 10 or Yarn Berry 4. Windows is supported through WSL2 because project generation requires Bash.
25
+ - `init` creates a NestJS project interactively with TypeORM or Prisma.
26
+ - `module <name>` adds the advanced module layout for TypeORM or Prisma.
27
+ - `resource <name>` generates a TypeORM or Prisma REST CRUD: entity or model, DTOs, repository, controller, validation, pagination, `404` and unique-constraint `409`.
28
+ - `doctor`, `--dry-run`, `--help`, `--version`, `--no-interactive` and `--quiet` are scriptable CLI features.
29
+ - Existing Nest projects are supported when `nest-cli.json` declares a custom `sourceRoot`. In a workspace with several applications, pass `--application <name>` to target one application explicitly.
34
30
 
35
- - **100% autonome** - Aucune dépendance externe, tout est intégré
36
- - **Zéro configuration** - Fonctionne immédiatement après installation
37
- - **Génération complète** - Projets et modules prêts à l'emploi en quelques secondes
38
- - **Architecture avancée** - Support intégré pour DDD, CQRS et architecture hexagonale
39
- - **Templates embarqués** - Tous les templates sont inclus dans le package
40
- - **Support multiple d'ORM** - TypeORM et Prisma intégrés nativement
41
- - **DevOps ready** - Configurations Docker, Swagger et CI/CD incluses
42
- - **Mode interactif** - Interface CLI intuitive avec prompts pour une configuration guidée
31
+ The repository CI executes generator contracts on the declared Node lines and on Linux and macOS. Windows users are supported through WSL2, whose Linux environment is covered by the Ubuntu runner. On Ubuntu/Node 24.15 it additionally validates Prisma, a TypeORM HTTP/PostgreSQL integration, generated Docker configurations, package-manager lockfile creation and locked reinstallation for npm, pnpm and Yarn, and the npm tarball. It does not publish releases or deploy applications. See [COMPATIBILITY.md](COMPATIBILITY.md) for the exact coverage and exclusions.
43
32
 
44
- ## 📦 Installation
33
+ ## Releases
34
+
35
+ Create releases from an annotated `vX.Y.Z` tag that points to the commit containing the same version in `package.json` and `package-lock.json`, plus a matching `CHANGELOG.md` section. The tag triggers the release workflow, which builds the package, verifies the tag/commit/version/archive SHA-512 relationship, publishes with npm Trusted Publishing (GitHub OIDC, no npm token in the repository), checks the npm `latest` dist-tag and archive integrity, then installs and runs the published binary in a clean directory.
36
+
37
+ Before the first release, configure `el-hack/nestgen-cli` as a Trusted Publisher in npm for the `Release` workflow. If publication fails before npm accepts the version, repair the release commit and replace the unpublished tag. If npm has accepted the version but a later registry check fails, do not republish that version: investigate the immutable tarball, correct the issue in a new SemVer version, then publish a new tag. The workflow creates the GitHub release only after the isolated install succeeds.
38
+
39
+ ## Outputs by ORM
40
+
41
+ | Command | ORM | Persistence output |
42
+ | ------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ |
43
+ | `resource` (simple or advanced) | TypeORM | Entity and repository using TypeORM; `resource.json` records `orm: "typeorm"`. No Prisma file or import. |
44
+ | `resource` | Prisma | Prisma model, Nest module, DTOs, repository and REST controller; `resource.json` records `orm: "prisma"`. No TypeORM file or import. |
45
+ | `module` | TypeORM | TypeORM entity and repository, registered with `TypeOrmModule.forFeature`. No Prisma runtime or schema change. |
46
+ | `module` | Prisma | Prisma repository, model added to `prisma/schema.prisma`, shared Prisma runtime if absent. No TypeORM file or import. |
47
+
48
+ For Prisma, run `npx prisma generate` and apply the schema with `npx prisma db push` or an explicit migration after generating a resource. Selecting an ORM does not convert an existing resource or remove files produced by older generator versions.
49
+
50
+ ## Public demo / Démonstration publique
51
+
52
+ Install the announced release and verify the exact binary before generating anything. Installez la version annoncée et vérifiez le binaire exact avant toute génération.
45
53
 
46
54
  ```bash
47
- npm install -g @outis25/nestgen
55
+ npm install --global nestgen-cli@0.2.1
56
+ nestgen --version # 0.2.1
48
57
  ```
49
58
 
50
- C'est tout! Aucune configuration supplémentaire n'est nécessaire. Tous les templates et dépendances sont embarqués dans le package.
59
+ Then follow the [Store API example](examples/store-api/README.md): it generates customers, products, orders and order items; starts PostgreSQL; creates an explicit migration; and runs generated tests. The versioned [guide](docs/versions/0.2.1.md) documents the commands and constraints used by the demo. Ensuite, suivez l’exemple Store API : il couvre la génération, PostgreSQL, une migration explicite, les tests générés et la documentation de la version.
60
+
61
+ The CI verifies the public commands against the announced package version, reconstructs the example and installs the npm tarball in a clean consumer. It validates reproducibility of these flows, not a production certification / pas une certification de production.
51
62
 
52
- ## 🔧 Guide d'utilisation
63
+ ## Quickstart — TypeORM resource
53
64
 
54
- ### Initialiser un nouveau projet
65
+ The following flow is the supported end-to-end TypeORM path. Prerequisites: Node.js `>=24.15.0 <27`, npm 11 and Docker with Compose. It uses Docker for PostgreSQL and creates an explicit migration.
55
66
 
56
67
  ```bash
68
+ npm install --global nestgen-cli@0.2.1
69
+ nestgen --version
57
70
  nestgen init
58
71
  ```
59
72
 
60
- Cette commande lance un assistant interactif qui vous guidera à travers les étapes de configuration :
61
- - Nom du projet
62
- - Répertoire d'installation
63
- - Sélection de l'ORM (TypeORM ou Prisma)
64
- - Modules à générer automatiquement
65
- - Options additionnelles (Git, Swagger, Docker, etc.)
73
+ In the interactive prompts, choose `npm`, `typeorm`, Docker enabled, then name the project `store-api`. Continue in the generated project:
66
74
 
67
- ### Générer un nouveau module
75
+ ```bash
76
+ cd store-api
77
+ nestgen doctor
78
+ nestgen resource product \
79
+ --orm typeorm \
80
+ --fields sku:string!,price:number,published:boolean \
81
+ --route catalog/products \
82
+ --table catalog_products
83
+
84
+ cp .env.example .env
85
+ docker compose up --detach postgres
86
+ npx typeorm-ts-node-commonjs migration:generate \
87
+ src/database/migrations/CreateProducts \
88
+ --dataSource src/database/data-source.ts
89
+ npx typeorm-ts-node-commonjs migration:run \
90
+ --dataSource src/database/data-source.ts
91
+ npm run start:dev
92
+ ```
93
+
94
+ In another terminal, verify the generated endpoint:
68
95
 
69
96
  ```bash
70
- nestgen module <nom-du-module> [options]
97
+ curl --request POST http://localhost:3000/catalog/products \
98
+ --header 'content-type: application/json' \
99
+ --data '{"sku":"sku-001","price":19.9,"published":true}'
100
+
101
+ curl 'http://localhost:3000/catalog/products?page=1&limit=20'
102
+
103
+ # Swagger UI, when selected during init
104
+ open http://localhost:3000/api
105
+
106
+ # Generated unit and database-backed REST tests
107
+ npm test
108
+ docker compose -f test/compose.e2e.yaml up -d --wait
109
+ npm run test:e2e -- product.e2e-spec.ts
110
+ docker compose -f test/compose.e2e.yaml down -v
111
+
112
+ # Stop the development database when finished
113
+ docker compose down -v
71
114
  ```
72
115
 
73
- Options disponibles :
74
- - `--orm=<typeorm|prisma>` - Spécifie l'ORM à utiliser pour ce module
75
- - `--crud` - Génère les opérations CRUD de base
76
- - `--path=<chemin>` - Définit un chemin personnalisé pour le module
116
+ A duplicate `sku` returns HTTP `409`; a malformed `price` returns HTTP `400`; an unknown identifier returns HTTP `404`. The REST test database runs separately on `127.0.0.1:5433`, is reset during the test suite and is removed by the cleanup command. On Windows, open `http://localhost:3000/api` in a browser instead of using `open`.
117
+
118
+ ### English quickstart
119
+
120
+ Install `nestgen-cli`, run `nestgen init`, choose **npm**, **typeorm** and Docker, then run the same commands above. `resource product --fields sku:string!,price:number,published:boolean` creates the TypeORM CRUD. Start PostgreSQL with `docker compose up -d postgres`, generate and run the migration through `typeorm-ts-node-commonjs`, start NestJS, then use the two `curl` commands to verify create and list operations.
121
+
122
+ ## Maintained Store API example
123
+
124
+ The published package includes a version-pinned [Store API example](examples/store-api/README.md) with customers, products, orders and order items. Its resource definitions are rebuilt by the CLI in CI, including relation constraints and a migration plan, so the guide stays aligned with the distributed generator. Use it when you need a complete multi-resource starting point rather than the single-product quickstart.
125
+
126
+ ## Commands
127
+
128
+ ```text
129
+ nestgen init
130
+ nestgen module <name> [--orm typeorm|prisma] [--application name] [--dry-run]
131
+ nestgen resource <name> --fields name:type[,name:type] [--route route] [--table table] [--profile simple|advanced] [--application name]
132
+ nestgen config init [--orm typeorm|prisma] [--profile simple|advanced] [--package-manager npm|pnpm|yarn]
133
+ nestgen config show
134
+ nestgen doctor
135
+ ```
136
+
137
+ Pour la CI, `init` accepte toutes les réponses interactives sous forme d’options :
77
138
 
78
- Exemples :
79
139
  ```bash
80
- nestgen module user --orm=typeorm
81
- nestgen module transaction --orm=prisma --crud
140
+ nestgen init store-api --no-interactive --project-path ./generated --package-manager npm --orm typeorm --docker --swagger --git --modules user,product
82
141
  ```
83
142
 
84
- ### Vérifier l'installation
143
+ Utilisez `--no-docker`, `--no-swagger`, `--no-operations`, `--no-git` ou `--modules ''` pour les désactiver. En mode non interactif, une option manquante est signalée avant toute écriture ou installation.
144
+
145
+ ### Socle d’exploitation optionnel
146
+
147
+ Ajoutez `--operations` à `init` pour générer un socle local d’exploitation, sans dépendance à un service tiers. Il expose `GET /health/live` pour la disponibilité du processus et `GET /health/ready` pour la disponibilité de PostgreSQL ; le second renvoie `503` avec l’état de la dépendance lorsque la base est indisponible. Le projet reçoit aussi un middleware `x-request-id`, un logger JSON qui masque les clés sensibles (`password`, `secret`, `token`, `authorization`, `cookie`, `apiKey`) et `enableShutdownHooks()` pour fermer proprement TypeORM ou Prisma sur `SIGTERM` et `SIGINT`. Le contrat et ses limites sont documentés dans `src/operations/README.md` du projet généré.
148
+
149
+ ### Points d’extension d’autorisation
150
+
151
+ Chaque contrôleur de ressource porte désormais `@ResourceAction('create' | 'list' | 'read' | 'update' | 'delete')`, défini dans `src/app/<ressource>/authorization/resource-policy.ts`. Cette métadonnée est destinée à un guard d’application existant via `Reflector`; NestGen ne configure ni fournisseur d’identité, ni stratégie de connexion, ni guard global.
152
+
153
+ Pour une règle de propriété, déclarez explicitement le propriétaire (`ownerId:uuid`) puis faites charger la ressource par votre guard avant les actions `read`, `update` et `delete`. Le guard compare l’identité déjà établie par votre application avec `resource.ownerId` et retourne `false` lorsqu’elles diffèrent : Nest renvoie alors `403`, y compris pour les accès inter-utilisateurs. Les actions et le nom de ressource restent disponibles dans `ResourcePolicyMetadata`, ce qui permet de centraliser une politique pour plusieurs ressources tout en conservant les conventions Nest standard.
154
+
155
+ Fields accepted by `resource` are `string`, `number`, `integer`, `decimal(precision;scale)`, `enum(VALUE|VALUE)`, `boolean`, `date` and `uuid`. Add `?` for a nullable field and `!` for a unique field. A decimal uses a semicolon between precision and scale so a field list can still be separated by commas. Decimals are exposed as JSON strings to preserve their database precision; enums use uppercase values separated by `|`.
156
+
157
+ `integer` maps to PostgreSQL `integer` / Prisma `Int` and is validated with `@IsInt()`. `decimal(precision;scale)` maps to PostgreSQL `numeric(precision, scale)` / Prisma `Decimal @db.Decimal(precision, scale)` and is validated as a decimal string. `enum(...)` maps to a PostgreSQL enum / a generated Prisma enum and is validated against its declared values.
158
+
159
+ ## Contraintes et index métier
160
+
161
+ Ajoutez des contraintes après le type entre accolades, séparées par `;` : `length` pour une chaîne, `min` et `max` pour un nombre ou un entier, `default` pour une valeur par défaut compatible, et `index` pour un index simple. Les index composites sont déclarés avec `--indexes`, chaque colonne étant séparée par `+`.
85
162
 
86
163
  ```bash
87
- nestgen doctor
164
+ nestgen resource product \
165
+ --fields sku:string{length=64;index}!,title:string{length=120},quantity:integer{min=0;max=100;default=0},status:enum(DRAFT|ACTIVE){default=DRAFT} \
166
+ --indexes sku+status
167
+ ```
168
+
169
+ NestGen refuse les combinaisons incompatibles, les bornes inversées et les index qui ciblent un champ absent. Les contraintes sont reflétées dans les DTOs, OpenAPI lorsque Swagger est installé, et les schémas TypeORM ou Prisma. Les index reçoivent un nom déterministe fondé sur la table et leurs colonnes, y compris lorsque PostgreSQL impose une limite de longueur.
170
+
171
+ ## Définition de ressource dans un fichier
172
+
173
+ `nestgen resource --file product.resource.json` lit un JSON versionné. La version actuelle est `1`. Les options de ligne de commande (`<name>`, `--fields`, `--route`, `--table`, `--orm`, `--profile`, `--indexes`) remplacent la valeur du fichier lorsqu’elles sont présentes. Ajoutez `uniqueIndexes` au fichier pour les contraintes d’unicité composites, par exemple `"uniqueIndexes": ["userId+roleId"]`.
174
+
175
+ ```json
176
+ {
177
+ "version": 1,
178
+ "name": "product",
179
+ "route": "catalog/products",
180
+ "table": "catalog_products",
181
+ "orm": "prisma",
182
+ "profile": "advanced",
183
+ "fields": ["sku:string!", "status:enum(DRAFT|ACTIVE)"],
184
+ "indexes": ["sku+status"],
185
+ "relations": [{ "type": "belongsTo", "target": "category", "onDelete": "RESTRICT" }]
186
+ }
187
+ ```
188
+
189
+ Le fichier doit être situé dans le projet courant. Les diagnostics indiquent le fichier et le champ ou l’index concerné, et `--dry-run` produit le même plan que la définition équivalente en flags.
190
+
191
+ ### Filtres, recherche et tri contrôlés
192
+
193
+ Ajoutez `list` à la définition pour autoriser explicitement les filtres et tris exposés par l’endpoint de liste. Les champs ou opérateurs absents de cette liste sont refusés avec `400`. Les paramètres de filtre sont convertis selon le type déclaré (`number`, `integer`, `boolean` et `date`) et les requêtes ORM restent paramétrées.
194
+
195
+ ```json
196
+ {
197
+ "version": 1,
198
+ "name": "product",
199
+ "fields": ["sku:string!", "price:number", "published:boolean"],
200
+ "list": {
201
+ "filters": {
202
+ "sku": ["eq", "contains"],
203
+ "price": ["gte", "lt"],
204
+ "published": ["eq"]
205
+ },
206
+ "search": ["sku"],
207
+ "sort": ["sku", "price"]
208
+ }
209
+ }
88
210
  ```
89
211
 
90
- Cette commande vérifie que :
91
- - Le package est correctement installé
92
- - Tous les templates embarqués sont disponibles
93
- - Aucune dépendance n'est manquante
212
+ Les opérateurs autorisés dépendent du type : `eq` et `neq` pour tous les champs, `contains` pour les chaînes, et `gt`, `gte`, `lt`, `lte` pour les nombres, entiers, décimaux et dates. Une requête telle que `GET /products?skuContains=pro&priceGte=10&sort=price:desc` combine les filtres, applique un ordre déterministe (avec `id` comme brise-égalité) et respecte `page` et `limit`. `q` recherche sur les champs déclarés dans `search`.
213
+
214
+ Ajoutez `"cursor": true` dans `list` pour inclure `nextCursor` dans les réponses. Reprenez la liste avec `?after=<nextCursor>` : le curseur opaque est validé et suit l’ordre stable `id:asc`, après application des mêmes filtres et de la même recherche. Un tri métier ne produit donc pas de curseur et ne peut pas être combiné avec `after`; ce choix évite les doublons ou omissions lors de la progression. Les changements concurrents peuvent toujours modifier les données restantes entre deux requêtes, comme avec toute pagination sans snapshot transactionnel.
215
+
216
+ ## Relations entre ressources
217
+
218
+ Une relation est déclarée dans le fichier de définition de la ressource enfant. La ressource cible doit déjà avoir été générée avec le même ORM. `belongsTo` crée la clé étrangère, un index et la propriété inverse sur la cible pour former une relation un-à-plusieurs cohérente.
219
+
220
+ ```json
221
+ {
222
+ "version": 1,
223
+ "name": "order",
224
+ "fields": ["reference:string!"],
225
+ "relations": [
226
+ {
227
+ "type": "belongsTo",
228
+ "target": "customer",
229
+ "field": "customer",
230
+ "inverse": "orders",
231
+ "nullable": false,
232
+ "onDelete": "RESTRICT"
233
+ }
234
+ ]
235
+ }
236
+ ```
94
237
 
95
- ## 📁 Architecture générée
238
+ `field` et `inverse` sont optionnels : NestGen utilise le nom de la ressource cible et un pluriel du nom de la ressource enfant. `nullable` vaut `false` par défaut et `onDelete` vaut `RESTRICT`; les suppressions liées ne déclenchent donc aucune cascade implicite. `SET NULL` est accepté seulement avec `nullable: true`.
96
239
 
97
- NestGen génère une structure de projet suivant les meilleures pratiques d'architecture :
240
+ `manyToMany` crée une table de liaison avec ses deux clés étrangères et une contrainte d’unicité sur la paire. La ressource qui déclare la relation en est propriétaire et reçoit les routes `POST /<ressource>/:id/<relation>/:targetId` et `DELETE /<ressource>/:id/<relation>/:targetId` pour associer et dissocier sans supprimer les deux entités.
98
241
 
242
+ ```json
243
+ {
244
+ "version": 1,
245
+ "name": "user",
246
+ "fields": ["email:string!"],
247
+ "relations": [{ "type": "manyToMany", "target": "role", "field": "roles", "inverse": "users" }]
248
+ }
99
249
  ```
100
- src/app/<module>/
101
- ├── core/ # Cœur du domaine métier
102
- │ ├── application/ # Cas d'utilisation
103
- │ │ ├── commands/ # Commandes CQRS
104
- │ │ ├── events/ # Événements domaine
105
- │ │ └── queries/ # Requêtes CQRS
106
- │ └── domain/ # Modèle du domaine
107
- │ ├── entities/ # Entités métier
108
- │ └── ports/ # Interfaces pour l'hexagonal
109
- ├── infrastructure/ # Implémentations techniques
110
- │ ├── adapters/ # Adaptateurs pour l'hexagonal
111
- │ └── persistences/ # Couche de persistance
112
- │ └── repositories/ # Implémentations des repos
113
- └── interfaces/ # Points d'entrée de l'app
114
- ├── controllers/ # Contrôleurs REST
115
- └── dtos/ # Objets de transfert
250
+
251
+ Lorsqu’une association porte ses propres données métier, générez-la comme ressource explicite avec deux relations `belongsTo`, puis protégez le couple de clés avec `uniqueIndexes`. Par exemple, une ressource `membership` peut définir `userId`, `roleId` et `grantedAt`, avec `"uniqueIndexes": ["userId+roleId"]`. Cette forme permet de versionner et valider les attributs de l’association, ce que la table de liaison implicite ne fait pas.
252
+
253
+ On creation, non-nullable fields are required. On PATCH, omitted fields are preserved;
254
+ `null` clears only nullable fields and is rejected for other fields. Values such as
255
+ `false`, `0` and an empty string are preserved when valid for the field type.
256
+
257
+ ```bash
258
+ nestgen resource invoice \
259
+ --fields number:string!,lineCount:integer,amount:decimal(12;2),status:enum(DRAFT|ISSUED),paid:boolean,dueAt:date? \
260
+ --route billing/invoices \
261
+ --table billing_invoices
116
262
  ```
117
263
 
118
- Cette structure facilite :
119
- - La séparation des préoccupations
120
- - Les tests unitaires et d'intégration
121
- - L'évolutivité du code
122
- - Le remplacement des composants techniques
264
+ Use `nestgen --help` for the complete accepted option set. Do not rely on undocumented options such as `--crud` or `--path`.
265
+
266
+ `--dry-run` emits a versioned JSON plan for `module` and `resource`. Each entry identifies the creation or replacement, and includes the exact unified diff that generation would apply. Conflicts are reported in `conflicts`; no file, dependency or installation is changed.
267
+
268
+ Use `--json` in automation to receive one versioned result on stdout. Failures produce a versioned JSON error on stderr with a stable `USAGE`, `PROJECT_INVALID`, `CONFLICT` or `INTERNAL` code; `--json` also enables non-interactive, quiet and no-color behavior.
123
269
 
124
- ## 🔮 Roadmap
270
+ `nestgen doctor` is read-only. It reports version support, generator availability, Nest dependencies, ORM coherence, NestGen configuration, lockfile consistency and Nest integration. Every diagnostic has an identifier, severity, cause and concrete corrective action; use `nestgen doctor --json` for the same contract in automation.
125
271
 
126
- - ✅ Génération de projet complet
127
- - ✅ Génération de module modulaire (DDD, CQRS, Repo)
128
- - ✅ Support Prisma et TypeORM
129
- - ✅ Mode interactif
130
- - ✅ Docker, Swagger, Git
131
- - ✅ Templates intégrés
132
- - ✅ Package 100% autonome
133
- - ⬜ `nestgen resource <name>` (CRUD complet)
134
- - ⬜ `nestgen destroy module <name>`
135
- - ⬜ `nestgen preset ecommerce` (Templates d'applications)
136
- - ⬜ `nestgen --interactive` (menu CLI avancé)
137
- - ⬜ Support pour MongoDB et Mongoose
138
- - ⬜ Génération de tests unitaires et d'intégration
272
+ ## Generation metadata
139
273
 
140
- ## ❓ FAQ
274
+ Every successful `module` or `resource` generation updates `.nestgen/generation-manifest.json` in the same atomic transaction as the generated files. The versioned manifest records the generator version, a safe structural definition and SHA-256 fingerprints for each generated file. Paths are always project-relative; field default values are deliberately excluded so the manifest can be committed without copying secrets. Later tooling can compare these fingerprints to detect manual edits before proposing an update. An unknown manifest version stops generation before any write.
141
275
 
142
- **Q: NestGen nécessite-t-il des dépendances externes ?**
143
- R: Non, NestGen est 100% autonome. Tous les templates et outils nécessaires sont embarqués dans le package.
276
+ Use `resource <name> --update` to regenerate a resource after changing its fields, route, table or definition file. NestGen previews the same transaction with `--dry-run`; a generated file edited since its recorded generation is reported as a conflict and blocks all writes. Files not tracked by the resource manifest are left untouched, and the manifest is refreshed only after the complete update commits successfully.
144
277
 
145
- **Q: Puis-je utiliser NestGen avec un projet NestJS existant ?**
146
- R: Oui, vous pouvez ajouter des modules générés par NestGen à un projet existant. La structure générée s'intègre parfaitement aux projets NestJS standards.
278
+ Add `--migration-name <name>` to an update to prepare the matching migration command and schema-risk review. TypeORM uses `typeorm-ts-node-commonjs migration:generate`; Prisma uses `prisma migrate dev --create-only`. The CLI never runs this command or applies a migration: review the reported column removals, type changes, mandatory fields, unique constraints and relation removals, then run the printed command explicitly in the generated project.
147
279
 
148
- **Q: Comment puis-je personnaliser les templates générés ?**
149
- R: Par défaut, NestGen utilise ses templates intégrés. Leurs structures sont optimisées pour les meilleures pratiques et ne nécessitent généralement pas de modifications.
280
+ ## Project configuration and profiles
150
281
 
151
- **Q: NestGen supporte-t-il les microservices ?**
152
- R: Pas encore nativement, mais c'est prévu dans les prochaines versions. En attendant, vous pouvez adapter manuellement la structure générée.
282
+ `nestgen config init` writes a versioned `nestgen.config.json` in the current project. For `resource`, the resolution order is flags, then the resource definition file, then configuration, then defaults. For `module`, `--orm` overrides configuration, then the default. `profile` is consumed by `resource`; `packageManager` is consumed by `init` and recorded for tooling, but neither `resource` nor `module` installs packages, so it has no runtime effect there. The generator resolves the effective source root from `nest-cli.json`; use `--application <name>` when a Nest workspace contains more than one application.
153
283
 
154
- ## 👥 Contribuer
284
+ ```bash
285
+ nestgen config init --orm typeorm --profile advanced --package-manager npm
286
+ nestgen config show
287
+ nestgen resource order --fields reference:string!,total:number
288
+ ```
155
289
 
156
- Les contributions sont les bienvenues ! Pour contribuer :
290
+ The `simple` profile generates a direct CRUD. The `advanced` profile adds application contracts, a repository port and a framework-independent application service between HTTP and the TypeORM adapter.
157
291
 
158
- 1. Forkez le dépôt
159
- 2. Créez une branche pour votre fonctionnalité (`git checkout -b feature/amazing-feature`)
160
- 3. Commitez vos changements (`git commit -m 'feat: add amazing feature'`)
161
- 4. Poussez vers la branche (`git push origin feature/amazing-feature`)
162
- 5. Ouvrez une Pull Request
292
+ ## OpenAPI when Swagger is enabled
163
293
 
164
- <!-- Veuillez consulter le fichier `CONTRIBUTING.md` pour plus de détails. -->
294
+ If the project contains `@nestjs/swagger` (selected during `nestgen init`), generated resources enrich the OpenAPI document with DTO property schemas, examples, required and nullable fields, UUID/date formats, endpoint summaries, pagination parameters, and documented `400`, `404`, `409` and success responses. Projects without Swagger keep the same generated REST code and do not receive Swagger imports.
165
295
 
166
- ## 📄 Licence
296
+ ## Tests generated with a resource
297
+
298
+ Each generated resource includes a Jest unit test next to its implementation. In a standard project created by Nest, run the complete suite with `npm test`, or one resource with:
299
+
300
+ ```bash
301
+ npm test -- product.repository.spec.ts
302
+ npm test -- order.service.spec.ts
303
+ ```
304
+
305
+ The simple profile test exercises persistence success, a missing record and a unique-constraint conflict. The advanced profile test exercises the application service output and the HTTP translation of application errors to `404` and `409`. The tests use in-memory doubles; each resource also has a generated REST test backed by PostgreSQL.
306
+
307
+ ## Generated REST tests on an isolated database
308
+
309
+ The first generated resource adds `test/.env.e2e` and `test/compose.e2e.yaml`; every resource adds `test/<resource>.e2e-spec.ts`. The test assigns `DATABASE_NAME` from `DATABASE_TEST_NAME`, resets the schema before every scenario, and drops it when the suite ends. It therefore never targets the development or production database.
310
+
311
+ ```bash
312
+ docker compose -f test/compose.e2e.yaml up -d --wait
313
+ npm run test:e2e -- product.e2e-spec.ts
314
+ docker compose -f test/compose.e2e.yaml down -v
315
+ ```
316
+
317
+ The generated suite covers create, read, partial update, pagination and delete, plus invalid input, malformed UUIDs, missing resources, and duplicate values when the resource declares a unique field with `!`.
318
+
319
+ ## Docker generated by `init`
320
+
321
+ When Docker is enabled, NestGen writes:
322
+
323
+ - `compose.yaml` for local development, with PostgreSQL 16, a healthcheck and a code mount;
324
+ - `Dockerfile` with a `development` target and a separate minimal `production` target;
325
+ - `.dockerignore` and `.env.example` without overwriting existing environment examples.
326
+
327
+ Use development with `docker compose up`. Build the deployable image independently:
328
+
329
+ ```bash
330
+ docker build --target production --tag store-api:local .
331
+ docker run --rm --env-file .env --publish 3000:3000 store-api:local
332
+ ```
333
+
334
+ ## Development
335
+
336
+ ```bash
337
+ npm ci
338
+ npm run check
339
+ npm run landing:check
340
+ npm run format:check
341
+ npm test
342
+ npm run test:docker
343
+ npm run test:prisma
344
+ npm run test:typeorm
345
+ npm run test:example
346
+ npm run test:package
347
+ ```
167
348
 
168
- NestGen est distribué sous licence MIT. Voir le fichier `LICENSE` pour plus d'informations.
349
+ See [COMPATIBILITY.md](COMPATIBILITY.md) for supported versions and [ARCHITECTURE.md](ARCHITECTURE.md) for generator design decisions.
169
350
 
170
- ---
351
+ ## Licence
171
352
 
172
- <div align="center">
173
- <p>Développé avec ❤️ par <a href="https://github.com/el-hack">@el-hack</a></p>
174
- <p>Si vous trouvez ce projet utile, n'hésitez pas à lui donner une ⭐️ sur GitHub !</p>
175
- </div>
353
+ MIT. See [LICENSE](LICENSE).