create-standards 1.0.0

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 (83) hide show
  1. package/README.md +89 -0
  2. package/bin/create-standards.js +3 -0
  3. package/package.json +32 -0
  4. package/src/cli.js +355 -0
  5. package/src/discover.js +113 -0
  6. package/src/ide-config.js +57 -0
  7. package/src/install.js +77 -0
  8. package/standards/nodejs-express-standards/README.md +59 -0
  9. package/standards/nodejs-express-standards/antigravity/.agents/skills/nodejs-express-standards/SKILL.md +40 -0
  10. package/standards/nodejs-express-standards/antigravity/.agents/skills/nodejs-express-standards/references/01-project-structure.md +33 -0
  11. package/standards/nodejs-express-standards/antigravity/.agents/skills/nodejs-express-standards/references/02-api-design-standards.md +41 -0
  12. package/standards/nodejs-express-standards/antigravity/.agents/skills/nodejs-express-standards/references/03-error-handling-validation.md +27 -0
  13. package/standards/nodejs-express-standards/antigravity/.agents/skills/nodejs-express-standards/references/04-security-standards.md +17 -0
  14. package/standards/nodejs-express-standards/antigravity/.agents/skills/nodejs-express-standards/references/05-database-model-standards.md +10 -0
  15. package/standards/nodejs-express-standards/antigravity/.agents/skills/nodejs-express-standards/references/06-testing-standards.md +10 -0
  16. package/standards/nodejs-express-standards/antigravity/.agents/skills/nodejs-express-standards/references/07-new-component-checklist.md +16 -0
  17. package/standards/nodejs-express-standards/antigravity/.agents/skills/nodejs-express-standards/references/08-code-style-general.md +9 -0
  18. package/standards/nodejs-express-standards/claude-code/.claude/skills/nodejs-express-standards/SKILL.md +40 -0
  19. package/standards/nodejs-express-standards/claude-code/.claude/skills/nodejs-express-standards/references/01-project-structure.md +33 -0
  20. package/standards/nodejs-express-standards/claude-code/.claude/skills/nodejs-express-standards/references/02-api-design-standards.md +41 -0
  21. package/standards/nodejs-express-standards/claude-code/.claude/skills/nodejs-express-standards/references/03-error-handling-validation.md +27 -0
  22. package/standards/nodejs-express-standards/claude-code/.claude/skills/nodejs-express-standards/references/04-security-standards.md +17 -0
  23. package/standards/nodejs-express-standards/claude-code/.claude/skills/nodejs-express-standards/references/05-database-model-standards.md +10 -0
  24. package/standards/nodejs-express-standards/claude-code/.claude/skills/nodejs-express-standards/references/06-testing-standards.md +10 -0
  25. package/standards/nodejs-express-standards/claude-code/.claude/skills/nodejs-express-standards/references/07-new-component-checklist.md +16 -0
  26. package/standards/nodejs-express-standards/claude-code/.claude/skills/nodejs-express-standards/references/08-code-style-general.md +9 -0
  27. package/standards/nodejs-express-standards/cursor/.cursor/rules/00-index.mdc +25 -0
  28. package/standards/nodejs-express-standards/cursor/.cursor/rules/01-project-structure.mdc +38 -0
  29. package/standards/nodejs-express-standards/cursor/.cursor/rules/02-api-design.mdc +46 -0
  30. package/standards/nodejs-express-standards/cursor/.cursor/rules/03-error-handling-validation.mdc +32 -0
  31. package/standards/nodejs-express-standards/cursor/.cursor/rules/04-security.mdc +22 -0
  32. package/standards/nodejs-express-standards/cursor/.cursor/rules/05-database-models.mdc +15 -0
  33. package/standards/nodejs-express-standards/cursor/.cursor/rules/06-testing.mdc +15 -0
  34. package/standards/nodejs-express-standards/cursor/.cursor/rules/07-new-component-checklist.mdc +21 -0
  35. package/standards/nodejs-express-standards/cursor/.cursor/rules/08-code-style.mdc +14 -0
  36. package/standards/nodejs-express-standards/shared-reference/01-project-structure.md +33 -0
  37. package/standards/nodejs-express-standards/shared-reference/02-api-design-standards.md +41 -0
  38. package/standards/nodejs-express-standards/shared-reference/03-error-handling-validation.md +27 -0
  39. package/standards/nodejs-express-standards/shared-reference/04-security-standards.md +17 -0
  40. package/standards/nodejs-express-standards/shared-reference/05-database-model-standards.md +10 -0
  41. package/standards/nodejs-express-standards/shared-reference/06-testing-standards.md +10 -0
  42. package/standards/nodejs-express-standards/shared-reference/07-new-component-checklist.md +16 -0
  43. package/standards/nodejs-express-standards/shared-reference/08-code-style-general.md +8 -0
  44. package/standards/rails-standards/README.md +86 -0
  45. package/standards/rails-standards/antigravity/.agents/skills/rails-standards/SKILL.md +66 -0
  46. package/standards/rails-standards/antigravity/.agents/skills/rails-standards/references/00-quick-scaffold.md +83 -0
  47. package/standards/rails-standards/antigravity/.agents/skills/rails-standards/references/01-project-structure.md +44 -0
  48. package/standards/rails-standards/antigravity/.agents/skills/rails-standards/references/02-api-design-standards.md +46 -0
  49. package/standards/rails-standards/antigravity/.agents/skills/rails-standards/references/03-error-handling-validation.md +35 -0
  50. package/standards/rails-standards/antigravity/.agents/skills/rails-standards/references/04-security-standards.md +32 -0
  51. package/standards/rails-standards/antigravity/.agents/skills/rails-standards/references/05-database-model-standards.md +25 -0
  52. package/standards/rails-standards/antigravity/.agents/skills/rails-standards/references/06-testing-standards.md +26 -0
  53. package/standards/rails-standards/antigravity/.agents/skills/rails-standards/references/07-new-component-checklist.md +26 -0
  54. package/standards/rails-standards/antigravity/.agents/skills/rails-standards/references/08-code-style-general.md +47 -0
  55. package/standards/rails-standards/claude-code/.claude/skills/rails-standards/SKILL.md +66 -0
  56. package/standards/rails-standards/claude-code/.claude/skills/rails-standards/references/00-quick-scaffold.md +83 -0
  57. package/standards/rails-standards/claude-code/.claude/skills/rails-standards/references/01-project-structure.md +44 -0
  58. package/standards/rails-standards/claude-code/.claude/skills/rails-standards/references/02-api-design-standards.md +46 -0
  59. package/standards/rails-standards/claude-code/.claude/skills/rails-standards/references/03-error-handling-validation.md +35 -0
  60. package/standards/rails-standards/claude-code/.claude/skills/rails-standards/references/04-security-standards.md +32 -0
  61. package/standards/rails-standards/claude-code/.claude/skills/rails-standards/references/05-database-model-standards.md +25 -0
  62. package/standards/rails-standards/claude-code/.claude/skills/rails-standards/references/06-testing-standards.md +26 -0
  63. package/standards/rails-standards/claude-code/.claude/skills/rails-standards/references/07-new-component-checklist.md +26 -0
  64. package/standards/rails-standards/claude-code/.claude/skills/rails-standards/references/08-code-style-general.md +47 -0
  65. package/standards/rails-standards/cursor/.cursor/rules/00-always-on.mdc +26 -0
  66. package/standards/rails-standards/cursor/.cursor/rules/01-project-structure.mdc +49 -0
  67. package/standards/rails-standards/cursor/.cursor/rules/02-api-design.mdc +51 -0
  68. package/standards/rails-standards/cursor/.cursor/rules/03-error-handling-validation.mdc +40 -0
  69. package/standards/rails-standards/cursor/.cursor/rules/04-security.mdc +37 -0
  70. package/standards/rails-standards/cursor/.cursor/rules/05-database-models.mdc +30 -0
  71. package/standards/rails-standards/cursor/.cursor/rules/06-testing.mdc +31 -0
  72. package/standards/rails-standards/cursor/.cursor/rules/07-new-component-checklist.mdc +31 -0
  73. package/standards/rails-standards/cursor/.cursor/rules/08-code-style.mdc +52 -0
  74. package/standards/rails-standards/cursor/.cursor/rules/09-quick-scaffold.mdc +88 -0
  75. package/standards/rails-standards/shared-reference/00-quick-scaffold.md +83 -0
  76. package/standards/rails-standards/shared-reference/01-project-structure.md +44 -0
  77. package/standards/rails-standards/shared-reference/02-api-design-standards.md +46 -0
  78. package/standards/rails-standards/shared-reference/03-error-handling-validation.md +35 -0
  79. package/standards/rails-standards/shared-reference/04-security-standards.md +32 -0
  80. package/standards/rails-standards/shared-reference/05-database-model-standards.md +25 -0
  81. package/standards/rails-standards/shared-reference/06-testing-standards.md +26 -0
  82. package/standards/rails-standards/shared-reference/07-new-component-checklist.md +26 -0
  83. package/standards/rails-standards/shared-reference/08-code-style-general.md +47 -0
package/src/install.js ADDED
@@ -0,0 +1,77 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ // selectedIdeFolders empty = install every IDE pack for the stack
5
+ function copyStandardsIntoProject({
6
+ stack,
7
+ selectedIdeFolders = [],
8
+ targetFolder,
9
+ force = false,
10
+ dryRun = false,
11
+ includeSharedReference = true,
12
+ }) {
13
+ const target = path.resolve(targetFolder);
14
+
15
+ const idePacksToCopy =
16
+ selectedIdeFolders.length === 0
17
+ ? stack.idePacks
18
+ : stack.idePacks.filter((pack) => selectedIdeFolders.includes(pack.ideFolder));
19
+
20
+ if (
21
+ selectedIdeFolders.length > 0 &&
22
+ idePacksToCopy.length !== selectedIdeFolders.length
23
+ ) {
24
+ const found = new Set(idePacksToCopy.map((pack) => pack.ideFolder));
25
+ const missing = selectedIdeFolders.filter((name) => !found.has(name));
26
+ const availableFlags = stack.idePacks.flatMap((pack) =>
27
+ pack.flags.map((flag) => `--${flag}`)
28
+ );
29
+ throw new Error(
30
+ `IDE pack(s) not found for stack "${stack.shortName}": ${missing.join(', ')}.\n` +
31
+ `Available flags: ${availableFlags.length ? availableFlags.join(', ') : '(none)'}`
32
+ );
33
+ }
34
+
35
+ if (
36
+ idePacksToCopy.length === 0 &&
37
+ !(includeSharedReference && stack.hasSharedReference)
38
+ ) {
39
+ throw new Error(`Nothing to install for stack "${stack.shortName}".`);
40
+ }
41
+
42
+ const copyPlan = idePacksToCopy.map((pack) => ({
43
+ from: pack.sourcePath,
44
+ to: path.join(target, pack.installAs),
45
+ }));
46
+
47
+ if (includeSharedReference && stack.hasSharedReference && stack.sharedReferencePath) {
48
+ copyPlan.push({
49
+ from: stack.sharedReferencePath,
50
+ to: path.join(target, 'shared-reference'),
51
+ });
52
+ }
53
+
54
+ const alreadyExists = copyPlan.filter((item) => fs.existsSync(item.to));
55
+ if (alreadyExists.length > 0 && !force) {
56
+ const list = alreadyExists.map((item) => ` - ${item.to}`).join('\n');
57
+ throw new Error(
58
+ `Destination already exists (use --force to overwrite):\n${list}`
59
+ );
60
+ }
61
+
62
+ const createdPaths = [];
63
+
64
+ for (const item of copyPlan) {
65
+ if (dryRun) {
66
+ createdPaths.push(item.to);
67
+ continue;
68
+ }
69
+ fs.mkdirSync(path.dirname(item.to), { recursive: true });
70
+ fs.cpSync(item.from, item.to, { recursive: true, force: true });
71
+ createdPaths.push(item.to);
72
+ }
73
+
74
+ return { copyPlan, createdPaths };
75
+ }
76
+
77
+ module.exports = { copyStandardsIntoProject };
@@ -0,0 +1,59 @@
1
+ # Node.js + Express Standards — Skills Pack
2
+
3
+ Senior-architect-level standards for Node.js/Express backend work, packaged for three AI coding
4
+ tools. Drop the relevant folder's contents into your project (paths already match what each tool
5
+ expects), and the standards get applied automatically or on request — you don't have to retype
6
+ them into every prompt.
7
+
8
+ ## What's inside
9
+
10
+ - **`shared-reference/`** — the master content (8 topic files). This is the source of truth;
11
+ the other three folders are just this content repackaged into each tool's native format.
12
+ - **`cursor/.cursor/rules/`** — Cursor `.mdc` rule files.
13
+ - **`claude-code/.claude/skills/nodejs-express-standards/`** — a Claude Code Skill (`SKILL.md` +
14
+ `references/`).
15
+ - **`antigravity/.agents/skills/nodejs-express-standards/`** — an Antigravity Skill, same
16
+ `SKILL.md` format as Claude Code (the format is now a shared open standard across tools).
17
+
18
+ ## How to install per tool
19
+
20
+ ### Cursor
21
+ Copy the `cursor/.cursor/` folder into your project root, so you end up with
22
+ `your-project/.cursor/rules/*.mdc`. Cursor loads these automatically:
23
+ - `00-index.mdc`, `04-security.mdc`, `08-code-style.mdc` are **always applied**.
24
+ - The rest **auto-attach** based on the file glob you're editing (e.g. editing anything in
25
+ `src/models/**` pulls in the database/model rules automatically).
26
+ - `07-new-component-checklist.mdc` is manual-only — pull it in explicitly by typing
27
+ `@07-new-component-checklist` in chat before asking Cursor to scaffold something new.
28
+
29
+ ### Claude Code
30
+ Copy the `claude-code/.claude/` folder into your project root (or into `~/.claude/` for a global,
31
+ cross-project skill), so you end up with
32
+ `your-project/.claude/skills/nodejs-express-standards/SKILL.md`. Claude Code discovers it
33
+ automatically and loads it whenever a task involves Express routes, controllers, services,
34
+ models, or migrations. You can also invoke it explicitly by name in a prompt, e.g. "follow the
35
+ nodejs-express-standards skill."
36
+
37
+ ### Antigravity
38
+ Copy the `antigravity/.agents/` folder into your project root (or into
39
+ `~/.gemini/config/skills/` for a global skill), so you end up with
40
+ `your-project/.agents/skills/nodejs-express-standards/SKILL.md`. Same format and behavior as the
41
+ Claude Code skill above — Antigravity semantically triggers it when relevant, or you can ask
42
+ for it by name / run `/skills` to confirm it's loaded.
43
+
44
+ ## Editing the standards
45
+
46
+ Treat `shared-reference/` as the source of truth. If you update a rule there, copy the change into
47
+ the corresponding `cursor/*.mdc` file and into both `references/` copies under `claude-code/` and
48
+ `antigravity/` so all three tools stay in sync.
49
+
50
+ ## Topics covered
51
+
52
+ 1. Project structure & layered architecture
53
+ 2. REST API design (routing, status codes, response envelope, pagination)
54
+ 3. Error handling & request validation
55
+ 4. Security defaults (auth, secrets, rate limiting, sanitization)
56
+ 5. Database & model conventions (repository pattern, migrations, indexing)
57
+ 6. Testing standards (unit, integration, coverage gate)
58
+ 7. Checklist to run before scaffolding any new model/route/component
59
+ 8. General code style, linting, logging, and commit conventions
@@ -0,0 +1,40 @@
1
+ ---
2
+ name: nodejs-express-standards
3
+ description: Senior-architect-level standards for Node.js + Express backend work — project structure, REST API design, error handling, security, database/model conventions, and testing. Use this skill whenever creating, editing, or reviewing any Express route, controller, service, repository, model, or migration, or before scaffolding any new backend component/endpoint, even if the user doesn't explicitly ask for "standards" or "best practices."
4
+ ---
5
+
6
+ # Node.js + Express Standards
7
+
8
+ Layered architecture is mandatory for this stack: `route -> validator -> controller -> service -> repository -> model`.
9
+ Before writing or modifying backend code, apply the relevant reference file(s) below. Don't wait to be asked —
10
+ if the task touches routes, controllers, services, models, or migrations, these standards apply by default.
11
+
12
+ ## When to consult which reference
13
+
14
+ | Task involves... | Read |
15
+ |--------------------------------------------|------------------------------------------------|
16
+ | New file/folder, overall app layout | `references/01-project-structure.md` |
17
+ | Any route or controller | `references/02-api-design-standards.md` |
18
+ | Error handling, validation middleware | `references/03-error-handling-validation.md` |
19
+ | Anything auth/security related | `references/04-security-standards.md` |
20
+ | Models, repositories, migrations | `references/05-database-model-standards.md` |
21
+ | Writing or reviewing tests | `references/06-testing-standards.md` |
22
+ | Scaffolding any new model/route/component | `references/07-new-component-checklist.md` |
23
+ | Lint/format/logging/commit conventions | `references/08-code-style-general.md` |
24
+
25
+ ## Core non-negotiables (always apply)
26
+
27
+ - No business logic in routes; controllers never query the DB directly.
28
+ - Every request is validated at the boundary before it reaches the controller body.
29
+ - Every error flows through the centralized error-handling middleware — no scattered bare `try/catch`.
30
+ - Every new endpoint ships with an updated OpenAPI/Swagger doc and at least a happy-path + failure-path test.
31
+ - Security defaults (helmet, rate limiting, input sanitization, no hardcoded secrets) apply to every service, not opt-in.
32
+
33
+ ## Workflow for a new feature
34
+
35
+ 1. Read `07-new-component-checklist.md` first — run through it before writing any code.
36
+ 2. Check `01-project-structure.md` to place the new files in the correct layer/folder.
37
+ 3. Design the endpoint per `02-api-design-standards.md` (path, verb, status codes, response envelope).
38
+ 4. Write the validation schema, then the controller/service/repository, applying `03`, `04`, and `05` as relevant.
39
+ 5. Write tests per `06-testing-standards.md`.
40
+ 6. Run lint/format per `08-code-style-general.md` before considering the task done.
@@ -0,0 +1,33 @@
1
+ # Project Structure Standards (Node.js + Express)
2
+
3
+ ## Standard folder layout
4
+
5
+ ```
6
+ src/
7
+ config/ # env loading + validation, db config, third-party config
8
+ routes/ # express.Router() definitions only — no logic
9
+ controllers/ # HTTP layer: parse req, call service, shape res
10
+ services/ # business logic, orchestration — framework-agnostic
11
+ repositories/ # data access layer (DB queries), one per model/table
12
+ models/ # ORM/schema definitions
13
+ validators/ # request schema validation (zod/joi/celebrate)
14
+ middlewares/ # auth, error handler, rate limit, logging
15
+ utils/ # pure helper functions
16
+ jobs/ # cron / queue workers
17
+ events/ # event emitters / pub-sub handlers
18
+ constants/ # enums, error codes, status strings
19
+ app.js # express app assembly (middleware + routes), NO app.listen()
20
+ server.js # imports app.js, calls app.listen(), handles graceful shutdown
21
+ tests/
22
+ unit/
23
+ integration/
24
+ ```
25
+
26
+ ## Rules
27
+
28
+ - **Layered architecture is mandatory**: `route → controller → service → repository → model`. A controller never talks to the DB directly, and a service never touches `req`/`res`.
29
+ - Split `app.js` (the Express app object) from `server.js` (the process/listener) so the app can be imported into supertest without binding a port.
30
+ - Config must be loaded and **validated at startup** (e.g. with `envalid`, `zod`, or `joi`) — fail fast if a required env var is missing, don't let it fail later at runtime.
31
+ - No business logic in `routes/`. Routes only wire `path + method → middleware chain → controller`.
32
+ - One repository per aggregate/model. Repositories are the only files allowed to import the ORM/query builder directly.
33
+ - Barrel files (`index.js`) per folder are optional but if used, keep them to re-exports only — no logic.
@@ -0,0 +1,41 @@
1
+ # REST API Design Standards
2
+
3
+ ## Resource naming & routing
4
+
5
+ - Use plural nouns for resources: `/users`, `/orders`, not `/user` or `/getUsers`.
6
+ - Nest resources only one level deep: `/orders/:orderId/items`, avoid deeper nesting.
7
+ - Version the API from day one: `/api/v1/...`. Never ship an unversioned public API.
8
+ - Use HTTP verbs correctly, never verbs in the path:
9
+
10
+ | Verb | Path | Action |
11
+ |--------|-------------------|-------------------------|
12
+ | GET | /users | list |
13
+ | GET | /users/:id | read one |
14
+ | POST | /users | create |
15
+ | PUT | /users/:id | full replace |
16
+ | PATCH | /users/:id | partial update |
17
+ | DELETE | /users/:id | delete |
18
+
19
+ ## Status codes
20
+
21
+ - `200` OK (read/update), `201` Created (with `Location` header), `204` No Content (delete/no body).
22
+ - `400` validation error, `401` unauthenticated, `403` unauthorized, `404` not found, `409` conflict, `422` semantically invalid, `429` rate-limited, `500` unhandled server error.
23
+ - Never return `200` with an error payload — the HTTP status must reflect the outcome.
24
+
25
+ ## Response envelope (consistent across all endpoints)
26
+
27
+ ```json
28
+ // success
29
+ { "success": true, "data": { }, "meta": { "page": 1, "totalPages": 4 } }
30
+
31
+ // error
32
+ { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "email is required", "details": [] } }
33
+ ```
34
+
35
+ ## Other requirements
36
+
37
+ - **Pagination** is required on every list endpoint (`?page=&limit=` or cursor-based `?cursor=`) — never return an unbounded array.
38
+ - **Filtering/sorting** via query params (`?status=active&sort=-createdAt`), validated against an allow-list of fields (never pass raw query straight into a DB `WHERE`/`ORDER BY`).
39
+ - **Idempotency**: `PUT`/`DELETE` must be idempotent. For `POST` on payment/order-creation style endpoints, support an `Idempotency-Key` header.
40
+ - **Document every endpoint** with OpenAPI/Swagger (`swagger-jsdoc` or a maintained `openapi.yaml`) — a new endpoint is not done until it's documented.
41
+ - Never expose internal DB IDs/structure verbatim if it leaks implementation details; DTOs/serializers shape what the client sees.
@@ -0,0 +1,27 @@
1
+ # Error Handling & Validation Standards
2
+
3
+ ## Custom error class
4
+
5
+ ```js
6
+ class AppError extends Error {
7
+ constructor(message, statusCode, code) {
8
+ super(message);
9
+ this.statusCode = statusCode;
10
+ this.code = code;
11
+ this.isOperational = true; // distinguishes expected errors from bugs
12
+ Error.captureStackTrace(this, this.constructor);
13
+ }
14
+ }
15
+ ```
16
+
17
+ ## Rules
18
+
19
+ - **Never use raw `try/catch` scattered in controllers.** Wrap async route handlers with a `catchAsync`/`asyncHandler` utility that forwards rejected promises to `next(err)`.
20
+ - **One centralized error-handling middleware**, registered last in `app.js`, that:
21
+ - Logs the error (with request id / correlation id).
22
+ - Returns the standard error envelope.
23
+ - Hides stack traces and internal messages in production (`isOperational === false` → generic "Something went wrong").
24
+ - **Validate every request at the boundary**, before it reaches the controller body — use a schema library (`zod`, `joi`, or `celebrate`) as route middleware, not manual `if` checks sprinkled through the controller.
25
+ - Validation errors return `400`/`422` with a `details` array listing each failing field.
26
+ - Distinguish **operational errors** (bad input, not found, auth failure — expected, safe to show a message) from **programmer errors** (bugs — log, alert, return generic 500).
27
+ - Async code must never produce an unhandled promise rejection — catch at the boundary, always.
@@ -0,0 +1,17 @@
1
+ # Security Standards
2
+
3
+ Apply all of these by default on every new Express service — don't wait to be asked:
4
+
5
+ - **Helmet**: `app.use(helmet())` for secure headers (CSP, HSTS, X-Frame-Options, etc.) — configure CSP explicitly rather than leaving it wide open.
6
+ - **CORS**: explicit origin allow-list via the `cors` package, never `origin: '*'` on an authenticated API.
7
+ - **Rate limiting**: `express-rate-limit` (or a Redis-backed store in multi-instance deployments) on all public endpoints, stricter limits on auth endpoints (`/login`, `/register`, `/forgot-password`).
8
+ - **Input sanitization**: strip/escape untrusted input against NoSQL/SQL injection and XSS (`express-mongo-sanitize`, parameterized queries/ORM query builders — never string-concatenate SQL).
9
+ - **AuthN/AuthZ**:
10
+ - Short-lived JWT access tokens + refresh token rotation, or session cookies with `httpOnly`, `secure`, `sameSite`.
11
+ - Passwords hashed with `bcrypt`/`argon2`, never stored or logged in plaintext.
12
+ - Role/permission checks live in middleware, applied per-route, not scattered inside controller `if` statements.
13
+ - **Secrets**: only via environment variables / a secrets manager. Never commit `.env`, never hardcode API keys or DB credentials.
14
+ - **Request limits**: `express.json({ limit: '10kb' })` (or an appropriate cap) to prevent payload-based DoS.
15
+ - **Dependency hygiene**: run `npm audit` (or Snyk/Dependabot) as part of CI; block merges on high/critical vulnerabilities.
16
+ - **HTTPS only** in production; redirect HTTP → HTTPS at the load balancer/proxy layer.
17
+ - Never leak stack traces, internal file paths, or library versions in API responses or headers.
@@ -0,0 +1,10 @@
1
+ # Database & Model Standards
2
+
3
+ - **Repository pattern**: all DB queries live in `repositories/`, never directly inside services or controllers. Services call repository methods; they don't know it's Postgres/Mongo/etc.
4
+ - **Migrations are mandatory** for schema changes (e.g. `knex`, `sequelize-cli`, `prisma migrate`, `typeorm migration`). Never use `sync({ alter: true })` or manual schema edits against a shared/production DB.
5
+ - Every table/collection gets `createdAt` and `updatedAt` timestamps by default.
6
+ - Prefer **soft deletes** (`deletedAt` column + default query scope excluding it) over hard deletes for user-facing/business-critical records; hard-delete only where there's a clear compliance/retention reason.
7
+ - Index every foreign key and every column used in a frequent `WHERE`/`sort` — check the query plan (`EXPLAIN`) for anything added to a hot path.
8
+ - **Transactions** wrap any operation that writes to more than one table/collection, so a partial failure can't leave data inconsistent.
9
+ - Naming: `snake_case` for DB columns/tables, `camelCase` in JS — handle the mapping in the ORM config, don't hand-convert per query.
10
+ - Never return raw ORM model instances straight from a controller — map to a DTO/serializer so DB shape and API shape can evolve independently.
@@ -0,0 +1,10 @@
1
+ # Testing Standards
2
+
3
+ - **Unit tests** (Jest/Vitest) for every service function — mock the repository layer, test business logic in isolation.
4
+ - **Integration tests** (Supertest against the exported `app.js`, not a running server) for every route — exercise the real middleware chain, validation, and error handler.
5
+ - Use a dedicated test database (or transactional rollback per test) — tests must never touch dev/prod data, and must be safely re-runnable/parallelizable.
6
+ - Follow **Arrange–Act–Assert** structure in every test; one logical assertion focus per test case.
7
+ - Mock external services/network calls (payment providers, email, third-party APIs) — tests must not depend on network access.
8
+ - Minimum coverage threshold: **80%** on services and controllers, enforced in CI (fail the build below threshold).
9
+ - Every new endpoint or model ships with at least: one happy-path integration test, one validation-failure test, one auth-failure test (if protected).
10
+ - CI must run lint → unit → integration → coverage gate, in that order, before a PR can merge.
@@ -0,0 +1,16 @@
1
+ # Checklist: Before Creating Any New Model, Route, or Component
2
+
3
+ Run through this before writing code for a new feature — this is what a senior architect reviews for in a PR:
4
+
5
+ 1. **Check for an existing pattern first.** Look at a similar existing model/route/service in the codebase and follow its shape — don't introduce a new pattern for something that already has one.
6
+ 2. **Confirm the layer boundaries**: route (wiring only) → validator (schema) → controller (HTTP glue) → service (logic) → repository (DB) → model. No shortcuts (e.g. controller querying the DB directly).
7
+ 3. **Write the validation schema** for every input (body/params/query) before writing the controller.
8
+ 4. **Define the DB migration** (not a live schema edit) if a new table/column is needed, with indexes on any FK/frequently-queried column.
9
+ 5. **Handle errors explicitly**: use `AppError`/`catchAsync`, no bare `try/catch` with silent `console.log`.
10
+ 6. **Add authorization checks** if the resource is user/role-scoped — don't rely on the client to hide UI for unauthorized actions.
11
+ 7. **Write tests**: at minimum one integration test (happy path) and one validation/error-path test.
12
+ 8. **Update API documentation** (OpenAPI/Swagger) for any new or changed endpoint.
13
+ 9. **Run lint + format** (ESLint + Prettier) — no new lint warnings introduced.
14
+ 10. **No secrets, no hardcoded config** — anything environment-specific goes through `config/`.
15
+ 11. **Consider pagination/rate-limits** if it's a list endpoint or public-facing.
16
+ 12. Keep the diff focused — one feature/concern per PR/commit.
@@ -0,0 +1,9 @@
1
+ # General Code Style Standards
2
+
3
+ - ESLint (Airbnb-base or `eslint-config-standard`) + Prettier, enforced via a pre-commit hook (`husky` + `lint-staged`) and in CI — not just "run it locally sometimes."
4
+ - `async/await` everywhere; no mixing with raw `.then()` chains or callback-style APIs in new code.
5
+ - No `console.log` in committed code — use a structured logger (`pino` or `winston`) with log levels, and include a request/correlation id in every log line.
6
+ - One export/responsibility per file; avoid god-files that mix routing, business logic, and DB access.
7
+ - Environment-based configuration only (`dotenv` + a validated config schema) — never branch behavior on `NODE_ENV` scattered through business logic; centralize environment differences in `config/`.
8
+ - Commit messages follow Conventional Commits (`feat:`, `fix:`, `refactor:`, `test:`, `chore:`) so history and changelogs stay meaningful.
9
+ - Prefer explicit, readable code over clever one-liners — this codebase is read far more often than it's written.
@@ -0,0 +1,40 @@
1
+ ---
2
+ name: nodejs-express-standards
3
+ description: Senior-architect-level standards for Node.js + Express backend work — project structure, REST API design, error handling, security, database/model conventions, and testing. Use this skill whenever creating, editing, or reviewing any Express route, controller, service, repository, model, or migration, or before scaffolding any new backend component/endpoint, even if the user doesn't explicitly ask for "standards" or "best practices."
4
+ ---
5
+
6
+ # Node.js + Express Standards
7
+
8
+ Layered architecture is mandatory for this stack: `route -> validator -> controller -> service -> repository -> model`.
9
+ Before writing or modifying backend code, apply the relevant reference file(s) below. Don't wait to be asked —
10
+ if the task touches routes, controllers, services, models, or migrations, these standards apply by default.
11
+
12
+ ## When to consult which reference
13
+
14
+ | Task involves... | Read |
15
+ |--------------------------------------------|------------------------------------------------|
16
+ | New file/folder, overall app layout | `references/01-project-structure.md` |
17
+ | Any route or controller | `references/02-api-design-standards.md` |
18
+ | Error handling, validation middleware | `references/03-error-handling-validation.md` |
19
+ | Anything auth/security related | `references/04-security-standards.md` |
20
+ | Models, repositories, migrations | `references/05-database-model-standards.md` |
21
+ | Writing or reviewing tests | `references/06-testing-standards.md` |
22
+ | Scaffolding any new model/route/component | `references/07-new-component-checklist.md` |
23
+ | Lint/format/logging/commit conventions | `references/08-code-style-general.md` |
24
+
25
+ ## Core non-negotiables (always apply)
26
+
27
+ - No business logic in routes; controllers never query the DB directly.
28
+ - Every request is validated at the boundary before it reaches the controller body.
29
+ - Every error flows through the centralized error-handling middleware — no scattered bare `try/catch`.
30
+ - Every new endpoint ships with an updated OpenAPI/Swagger doc and at least a happy-path + failure-path test.
31
+ - Security defaults (helmet, rate limiting, input sanitization, no hardcoded secrets) apply to every service, not opt-in.
32
+
33
+ ## Workflow for a new feature
34
+
35
+ 1. Read `07-new-component-checklist.md` first — run through it before writing any code.
36
+ 2. Check `01-project-structure.md` to place the new files in the correct layer/folder.
37
+ 3. Design the endpoint per `02-api-design-standards.md` (path, verb, status codes, response envelope).
38
+ 4. Write the validation schema, then the controller/service/repository, applying `03`, `04`, and `05` as relevant.
39
+ 5. Write tests per `06-testing-standards.md`.
40
+ 6. Run lint/format per `08-code-style-general.md` before considering the task done.
@@ -0,0 +1,33 @@
1
+ # Project Structure Standards (Node.js + Express)
2
+
3
+ ## Standard folder layout
4
+
5
+ ```
6
+ src/
7
+ config/ # env loading + validation, db config, third-party config
8
+ routes/ # express.Router() definitions only — no logic
9
+ controllers/ # HTTP layer: parse req, call service, shape res
10
+ services/ # business logic, orchestration — framework-agnostic
11
+ repositories/ # data access layer (DB queries), one per model/table
12
+ models/ # ORM/schema definitions
13
+ validators/ # request schema validation (zod/joi/celebrate)
14
+ middlewares/ # auth, error handler, rate limit, logging
15
+ utils/ # pure helper functions
16
+ jobs/ # cron / queue workers
17
+ events/ # event emitters / pub-sub handlers
18
+ constants/ # enums, error codes, status strings
19
+ app.js # express app assembly (middleware + routes), NO app.listen()
20
+ server.js # imports app.js, calls app.listen(), handles graceful shutdown
21
+ tests/
22
+ unit/
23
+ integration/
24
+ ```
25
+
26
+ ## Rules
27
+
28
+ - **Layered architecture is mandatory**: `route → controller → service → repository → model`. A controller never talks to the DB directly, and a service never touches `req`/`res`.
29
+ - Split `app.js` (the Express app object) from `server.js` (the process/listener) so the app can be imported into supertest without binding a port.
30
+ - Config must be loaded and **validated at startup** (e.g. with `envalid`, `zod`, or `joi`) — fail fast if a required env var is missing, don't let it fail later at runtime.
31
+ - No business logic in `routes/`. Routes only wire `path + method → middleware chain → controller`.
32
+ - One repository per aggregate/model. Repositories are the only files allowed to import the ORM/query builder directly.
33
+ - Barrel files (`index.js`) per folder are optional but if used, keep them to re-exports only — no logic.
@@ -0,0 +1,41 @@
1
+ # REST API Design Standards
2
+
3
+ ## Resource naming & routing
4
+
5
+ - Use plural nouns for resources: `/users`, `/orders`, not `/user` or `/getUsers`.
6
+ - Nest resources only one level deep: `/orders/:orderId/items`, avoid deeper nesting.
7
+ - Version the API from day one: `/api/v1/...`. Never ship an unversioned public API.
8
+ - Use HTTP verbs correctly, never verbs in the path:
9
+
10
+ | Verb | Path | Action |
11
+ |--------|-------------------|-------------------------|
12
+ | GET | /users | list |
13
+ | GET | /users/:id | read one |
14
+ | POST | /users | create |
15
+ | PUT | /users/:id | full replace |
16
+ | PATCH | /users/:id | partial update |
17
+ | DELETE | /users/:id | delete |
18
+
19
+ ## Status codes
20
+
21
+ - `200` OK (read/update), `201` Created (with `Location` header), `204` No Content (delete/no body).
22
+ - `400` validation error, `401` unauthenticated, `403` unauthorized, `404` not found, `409` conflict, `422` semantically invalid, `429` rate-limited, `500` unhandled server error.
23
+ - Never return `200` with an error payload — the HTTP status must reflect the outcome.
24
+
25
+ ## Response envelope (consistent across all endpoints)
26
+
27
+ ```json
28
+ // success
29
+ { "success": true, "data": { }, "meta": { "page": 1, "totalPages": 4 } }
30
+
31
+ // error
32
+ { "success": false, "error": { "code": "VALIDATION_ERROR", "message": "email is required", "details": [] } }
33
+ ```
34
+
35
+ ## Other requirements
36
+
37
+ - **Pagination** is required on every list endpoint (`?page=&limit=` or cursor-based `?cursor=`) — never return an unbounded array.
38
+ - **Filtering/sorting** via query params (`?status=active&sort=-createdAt`), validated against an allow-list of fields (never pass raw query straight into a DB `WHERE`/`ORDER BY`).
39
+ - **Idempotency**: `PUT`/`DELETE` must be idempotent. For `POST` on payment/order-creation style endpoints, support an `Idempotency-Key` header.
40
+ - **Document every endpoint** with OpenAPI/Swagger (`swagger-jsdoc` or a maintained `openapi.yaml`) — a new endpoint is not done until it's documented.
41
+ - Never expose internal DB IDs/structure verbatim if it leaks implementation details; DTOs/serializers shape what the client sees.
@@ -0,0 +1,27 @@
1
+ # Error Handling & Validation Standards
2
+
3
+ ## Custom error class
4
+
5
+ ```js
6
+ class AppError extends Error {
7
+ constructor(message, statusCode, code) {
8
+ super(message);
9
+ this.statusCode = statusCode;
10
+ this.code = code;
11
+ this.isOperational = true; // distinguishes expected errors from bugs
12
+ Error.captureStackTrace(this, this.constructor);
13
+ }
14
+ }
15
+ ```
16
+
17
+ ## Rules
18
+
19
+ - **Never use raw `try/catch` scattered in controllers.** Wrap async route handlers with a `catchAsync`/`asyncHandler` utility that forwards rejected promises to `next(err)`.
20
+ - **One centralized error-handling middleware**, registered last in `app.js`, that:
21
+ - Logs the error (with request id / correlation id).
22
+ - Returns the standard error envelope.
23
+ - Hides stack traces and internal messages in production (`isOperational === false` → generic "Something went wrong").
24
+ - **Validate every request at the boundary**, before it reaches the controller body — use a schema library (`zod`, `joi`, or `celebrate`) as route middleware, not manual `if` checks sprinkled through the controller.
25
+ - Validation errors return `400`/`422` with a `details` array listing each failing field.
26
+ - Distinguish **operational errors** (bad input, not found, auth failure — expected, safe to show a message) from **programmer errors** (bugs — log, alert, return generic 500).
27
+ - Async code must never produce an unhandled promise rejection — catch at the boundary, always.
@@ -0,0 +1,17 @@
1
+ # Security Standards
2
+
3
+ Apply all of these by default on every new Express service — don't wait to be asked:
4
+
5
+ - **Helmet**: `app.use(helmet())` for secure headers (CSP, HSTS, X-Frame-Options, etc.) — configure CSP explicitly rather than leaving it wide open.
6
+ - **CORS**: explicit origin allow-list via the `cors` package, never `origin: '*'` on an authenticated API.
7
+ - **Rate limiting**: `express-rate-limit` (or a Redis-backed store in multi-instance deployments) on all public endpoints, stricter limits on auth endpoints (`/login`, `/register`, `/forgot-password`).
8
+ - **Input sanitization**: strip/escape untrusted input against NoSQL/SQL injection and XSS (`express-mongo-sanitize`, parameterized queries/ORM query builders — never string-concatenate SQL).
9
+ - **AuthN/AuthZ**:
10
+ - Short-lived JWT access tokens + refresh token rotation, or session cookies with `httpOnly`, `secure`, `sameSite`.
11
+ - Passwords hashed with `bcrypt`/`argon2`, never stored or logged in plaintext.
12
+ - Role/permission checks live in middleware, applied per-route, not scattered inside controller `if` statements.
13
+ - **Secrets**: only via environment variables / a secrets manager. Never commit `.env`, never hardcode API keys or DB credentials.
14
+ - **Request limits**: `express.json({ limit: '10kb' })` (or an appropriate cap) to prevent payload-based DoS.
15
+ - **Dependency hygiene**: run `npm audit` (or Snyk/Dependabot) as part of CI; block merges on high/critical vulnerabilities.
16
+ - **HTTPS only** in production; redirect HTTP → HTTPS at the load balancer/proxy layer.
17
+ - Never leak stack traces, internal file paths, or library versions in API responses or headers.
@@ -0,0 +1,10 @@
1
+ # Database & Model Standards
2
+
3
+ - **Repository pattern**: all DB queries live in `repositories/`, never directly inside services or controllers. Services call repository methods; they don't know it's Postgres/Mongo/etc.
4
+ - **Migrations are mandatory** for schema changes (e.g. `knex`, `sequelize-cli`, `prisma migrate`, `typeorm migration`). Never use `sync({ alter: true })` or manual schema edits against a shared/production DB.
5
+ - Every table/collection gets `createdAt` and `updatedAt` timestamps by default.
6
+ - Prefer **soft deletes** (`deletedAt` column + default query scope excluding it) over hard deletes for user-facing/business-critical records; hard-delete only where there's a clear compliance/retention reason.
7
+ - Index every foreign key and every column used in a frequent `WHERE`/`sort` — check the query plan (`EXPLAIN`) for anything added to a hot path.
8
+ - **Transactions** wrap any operation that writes to more than one table/collection, so a partial failure can't leave data inconsistent.
9
+ - Naming: `snake_case` for DB columns/tables, `camelCase` in JS — handle the mapping in the ORM config, don't hand-convert per query.
10
+ - Never return raw ORM model instances straight from a controller — map to a DTO/serializer so DB shape and API shape can evolve independently.
@@ -0,0 +1,10 @@
1
+ # Testing Standards
2
+
3
+ - **Unit tests** (Jest/Vitest) for every service function — mock the repository layer, test business logic in isolation.
4
+ - **Integration tests** (Supertest against the exported `app.js`, not a running server) for every route — exercise the real middleware chain, validation, and error handler.
5
+ - Use a dedicated test database (or transactional rollback per test) — tests must never touch dev/prod data, and must be safely re-runnable/parallelizable.
6
+ - Follow **Arrange–Act–Assert** structure in every test; one logical assertion focus per test case.
7
+ - Mock external services/network calls (payment providers, email, third-party APIs) — tests must not depend on network access.
8
+ - Minimum coverage threshold: **80%** on services and controllers, enforced in CI (fail the build below threshold).
9
+ - Every new endpoint or model ships with at least: one happy-path integration test, one validation-failure test, one auth-failure test (if protected).
10
+ - CI must run lint → unit → integration → coverage gate, in that order, before a PR can merge.
@@ -0,0 +1,16 @@
1
+ # Checklist: Before Creating Any New Model, Route, or Component
2
+
3
+ Run through this before writing code for a new feature — this is what a senior architect reviews for in a PR:
4
+
5
+ 1. **Check for an existing pattern first.** Look at a similar existing model/route/service in the codebase and follow its shape — don't introduce a new pattern for something that already has one.
6
+ 2. **Confirm the layer boundaries**: route (wiring only) → validator (schema) → controller (HTTP glue) → service (logic) → repository (DB) → model. No shortcuts (e.g. controller querying the DB directly).
7
+ 3. **Write the validation schema** for every input (body/params/query) before writing the controller.
8
+ 4. **Define the DB migration** (not a live schema edit) if a new table/column is needed, with indexes on any FK/frequently-queried column.
9
+ 5. **Handle errors explicitly**: use `AppError`/`catchAsync`, no bare `try/catch` with silent `console.log`.
10
+ 6. **Add authorization checks** if the resource is user/role-scoped — don't rely on the client to hide UI for unauthorized actions.
11
+ 7. **Write tests**: at minimum one integration test (happy path) and one validation/error-path test.
12
+ 8. **Update API documentation** (OpenAPI/Swagger) for any new or changed endpoint.
13
+ 9. **Run lint + format** (ESLint + Prettier) — no new lint warnings introduced.
14
+ 10. **No secrets, no hardcoded config** — anything environment-specific goes through `config/`.
15
+ 11. **Consider pagination/rate-limits** if it's a list endpoint or public-facing.
16
+ 12. Keep the diff focused — one feature/concern per PR/commit.
@@ -0,0 +1,9 @@
1
+ # General Code Style Standards
2
+
3
+ - ESLint (Airbnb-base or `eslint-config-standard`) + Prettier, enforced via a pre-commit hook (`husky` + `lint-staged`) and in CI — not just "run it locally sometimes."
4
+ - `async/await` everywhere; no mixing with raw `.then()` chains or callback-style APIs in new code.
5
+ - No `console.log` in committed code — use a structured logger (`pino` or `winston`) with log levels, and include a request/correlation id in every log line.
6
+ - One export/responsibility per file; avoid god-files that mix routing, business logic, and DB access.
7
+ - Environment-based configuration only (`dotenv` + a validated config schema) — never branch behavior on `NODE_ENV` scattered through business logic; centralize environment differences in `config/`.
8
+ - Commit messages follow Conventional Commits (`feat:`, `fix:`, `refactor:`, `test:`, `chore:`) so history and changelogs stay meaningful.
9
+ - Prefer explicit, readable code over clever one-liners — this codebase is read far more often than it's written.
@@ -0,0 +1,25 @@
1
+ ---
2
+ description: Node.js + Express senior-architect standards — always apply as the baseline for this project
3
+ globs:
4
+ alwaysApply: true
5
+ ---
6
+
7
+ # Node.js + Express Standards (index)
8
+
9
+ This project follows layered architecture: `route -> validator -> controller -> service -> repository -> model`.
10
+ Before creating or editing any model, route, controller, or service, also consult the more specific rules in this
11
+ folder — they auto-attach based on the file you're touching:
12
+
13
+ - `01-project-structure.mdc` — folder layout & layering rules
14
+ - `02-api-design.mdc` — REST conventions, status codes, response shape
15
+ - `03-error-handling-validation.mdc` — error classes, validation middleware
16
+ - `04-security.mdc` — security defaults (helmet, rate limiting, auth, secrets)
17
+ - `05-database-models.mdc` — repository pattern, migrations, indexing
18
+ - `06-testing.mdc` — unit/integration test requirements
19
+ - `07-new-component-checklist.mdc` — run this checklist before scaffolding anything new
20
+ - `08-code-style.mdc` — lint/format/logging/commit conventions
21
+
22
+ Core non-negotiables:
23
+ - No business logic in routes or controllers talking directly to the DB.
24
+ - Every new input is validated at the boundary; every error goes through the centralized error handler.
25
+ - Every new endpoint ships with tests and updated API docs.