Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .claude/hooks/format-and-lint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# PostToolUse hook: format the file Claude just edited and report lint errors back to it.
# Input: the hook JSON on stdin (tool_input.file_path). Exit 2 sends stderr to Claude.
set -euo pipefail

file=$(jq -r '.tool_input.file_path // empty')
[[ -z "$file" || ! -f "$file" ]] && exit 0

cd "$CLAUDE_PROJECT_DIR"

# Only files inside this repository.
case "$(realpath "$file")" in
"$(realpath "$CLAUDE_PROJECT_DIR")"/*) ;;
*) exit 0 ;;
esac

case "$file" in
*.ts | *.js | *.mjs | *.cjs | *.json | *.md | *.yml | *.yaml) ;;
*) exit 0 ;;
esac

# Respects .prettierignore; unknown file types are skipped.
npx --no-install prettier --write --ignore-unknown --log-level warn "$file" >/dev/null

case "$file" in
*.ts | *.js | *.mjs | *.cjs)
if ! out=$(npx --no-install eslint --fix --no-warn-ignored "$file" 2>&1); then
echo "ESLint errors in $file (fix them before finishing):" >&2
echo "$out" >&2
exit 2
fi
;;
esac

exit 0
39 changes: 39 additions & 0 deletions .claude/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"permissions": {
"allow": [
"Bash(npm run lint:*)",
"Bash(npm run typecheck:*)",
"Bash(npm run format:*)",
"Bash(npm test:*)",
"Bash(npm run test:*)",
"Bash(npm run build:*)",
"Bash(npm run openapi:*)",
"Bash(npx vitest:*)",
"Bash(npx eslint:*)",
"Bash(npx prettier:*)",
"Bash(git status:*)",
"Bash(git diff:*)",
"Bash(git log:*)",
"Bash(git show:*)",
"Bash(gh pr view:*)",
"Bash(gh pr list:*)",
"Bash(gh pr checks:*)"
],
"deny": ["Read(./.env)", "Read(./.env.local)", "Read(./.env.production)"]
},
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write|MultiEdit",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-and-lint.sh",
"timeout": 60
}
]
}
]
}
}
27 changes: 27 additions & 0 deletions .claude/skills/add-endpoint/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
name: add-endpoint
description: "Add or change a REST endpoint of the email template editor API. Use when adding a route, changing a request or response shape, or adding a feature module under src/modules."
---

# Add or change an endpoint

Follow the layers in order. Look at `src/modules/elements/` as the reference module.

1. **Schema** — `src/modules/<m>/<m>.schemas.ts`: zod schemas for the body and path params, plus `z.infer` types. Trim and require keys (`z.string().trim().min(1)`).
2. **Service** — `<m>.service.ts`: the business rule. Read and write through `TemplateStore` (`store.read()` / `store.update()`). Throw `NotFoundError`, `ConflictError` or `AppError(status, "CODE", message)`; never touch `req`/`res`.
3. **Controller** — `<m>.controller.ts`: arrow-function methods that read the validated `req`, call the service and set the status (`201` + body for create, `204` for update/delete).
4. **Router** — `<m>.router.ts`: `validate({ body, params })` before the controller method.
5. **Wire it** — new module: construct it in `src/routes.ts`.
6. **Contract** — add the operation to `buildOpenApiDocument()` in `src/openapi.ts` (register new named schemas in `components`), then `npm run openapi` to regenerate `openapi.json`.
7. **Tests**
- HTTP: `test/app.test.ts` with Supertest — success status and body, 400 for invalid input, 404/409 where they apply, and that `db.json` changed as expected.
- Pure logic (helpers): `*.test.ts` next to the code.
- `test/openapi.test.ts` fails until `openapi.json` is regenerated and catches documented routes that do not exist.
8. **Docs** — the endpoint table in `README.md`.
9. **Frontend** — if the shape or path changed, the frontend's `src/api/main.ts` and `main.types.ts` need a matching PR in `email-template-editor-reactjs`.

## Check

```bash
npm run lint && npm run typecheck && npm run format:check && npm test && npm run build
```
2 changes: 2 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Reviewers requested automatically for every pull request.
* @vadim9999
31 changes: 31 additions & 0 deletions .github/ISSUE_TEMPLATE/bug.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Bug report
description: An endpoint does not behave as documented in openapi.json.
labels: [bug]
body:
- type: textarea
id: request
attributes:
label: Request
description: Method, path and body (a curl command is ideal).
placeholder: |
curl -X PATCH localhost:9000/tree/nodes/abc -H 'content-type: application/json' -d '{"title":"x"}'
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected response
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual response
description: Status, body and the requestId from the error, if any.
validations:
required: true
- type: textarea
id: environment
attributes:
label: Environment
description: Commit or image tag, how it runs (npm run dev, Docker), relevant env vars.
5 changes: 5 additions & 0 deletions .github/ISSUE_TEMPLATE/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
blank_issues_enabled: true
contact_links:
- name: Editor UI issue
url: https://github.com/LLazyEmail/email-template-editor-reactjs/issues
about: Problems in the editor interface belong to the frontend repository.
31 changes: 31 additions & 0 deletions .github/ISSUE_TEMPLATE/feature.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Feature request
description: A new endpoint or a change to an existing one.
labels: [enhancement]
body:
- type: textarea
id: problem
attributes:
label: Problem
description: What the editor (or another client) cannot do today.
validations:
required: true
- type: textarea
id: api
attributes:
label: Proposed API
description: Method, path, request and response bodies, error cases.
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance criteria
description: Checkable statements that define "done". They become the tests.
validations:
required: true
- type: checkboxes
id: frontend
attributes:
label: Frontend impact
options:
- label: Needs a matching change in email-template-editor-reactjs
19 changes: 19 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
## What

<!-- What changed, in a few bullets. -->

## Why

<!-- The problem or issue this solves. Link it: Closes #123 -->

## How to verify

<!-- Commands you ran, requests a reviewer can send. -->

## Checklist

- [ ] One concern per PR
- [ ] `npm run lint`, `npm run typecheck`, `npm run format:check` pass
- [ ] `npm test` passes; new behavior has a test
- [ ] Routes or schemas changed → `npm run openapi` run, `openapi.json` and the README endpoint table updated
- [ ] Breaking API change → matching PR in email-template-editor-reactjs linked
15 changes: 11 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,21 @@ on:
pull_request:
branches: [main]

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
node-version-file: .nvmrc
cache: npm
- run: npm ci
- run: npm run lint
Expand All @@ -25,5 +32,5 @@ jobs:
docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- run: docker build -t email-template-editor-nodejs .
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ dist
coverage
.env
*.tmp

# Claude Code: personal overrides (shared settings are in .claude/settings.json)
.claude/settings.local.json
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
24
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ public
db.json
package-lock.json
test/fixtures
# generated by `npm run openapi`
openapi.json
71 changes: 71 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# AI Agent Guide — email-template-editor-nodejs

> **Audience:** AI coding agents (Claude Code, Cursor, Copilot, Codex) and people working on this repository.
> **Purpose:** enough context to make safe, consistent changes without rediscovering the layout.

REST API for the [email template editor](https://github.com/LLazyEmail/email-template-editor-reactjs). It stores a tree of template parts and a library of reusable elements, and renders the tree into one HTML email. Read [`README.md`](README.md) for configuration, the endpoint table and Docker.

**Stack:** Node 24 (`.nvmrc`), TypeScript 6 (strict, ESM, `NodeNext`), Express 5, zod 4, pino, Vitest + Supertest, ESLint 10 + typescript-eslint, Prettier.

## Commands

```bash
npm run dev # http://localhost:9000, hot reload (tsx)
npm run lint # ESLint
npm run typecheck # tsc --noEmit
npm run format # Prettier (format:check runs in CI)
npm test # unit + HTTP integration tests
npm run build # compile to dist/
npm run openapi # regenerate openapi.json after changing a route or schema
```

## Architecture

```
request → helmet → cors → request-id → pino-http → json → static
→ router src/modules/<m>/<m>.router.ts routes + validate({ body, params }) with zod
→ controller src/modules/<m>/<m>.controller.ts HTTP only: read req, write res
→ service src/modules/<m>/<m>.service.ts business rules, throws AppError
→ store src/storage/template-store.ts interface; JsonFileStore (db.json)
→ not-found → error-handler one JSON error shape for everything
```

- `src/routes.ts` is the composition root: it wires store → services → controllers → routers and serves `/health` and `/openapi.json`.
- `src/openapi.ts` builds the OpenAPI 3.1 document from the same zod schemas the routers use.
- `src/config/env.ts` validates environment variables with zod; invalid config stops the server at startup.

## API contract

- **Source of truth:** [`openapi.json`](openapi.json), generated from the zod schemas and served at `GET /openapi.json`. `test/openapi.test.ts` fails if the committed file is stale or documents a route the app does not have.
- The frontend's request types (`src/api/main.types.ts` in the frontend repo) must match it. A breaking change here needs a matching frontend PR.
- Errors are always `{ error: { code, message, details?, requestId } }` (see `src/common/middleware/error-handler.ts`).
- Keys in paths are URL-encoded by the client.

## Rules

- Validate every body and path parameter with a zod schema in `<module>.schemas.ts` through `validate()`. Controllers trust `req.body` / `req.params` after that.
- Services throw `AppError` subclasses (`ValidationError`, `NotFoundError`, `ConflictError`, or `AppError(status, CODE, message)`); never write responses from a service.
- Persistence only through the `TemplateStore` interface. Do not read or write `db.json` elsewhere.
- No `console.*` (ESLint `no-console`); log with the request logger `req.log` or the injected `logger`.
- ESM with `.js` extensions in relative imports (`NodeNext`). `import type` for types (`consistent-type-imports`).
- Tests: HTTP behavior in `test/*.test.ts` with Supertest against `createApp()` and a temp `db.json`; pure logic next to the code (`*.test.ts`). Never touch the real `db.json` from tests.
- Keep `README.md`'s endpoint table in sync with `openapi.json`.

## Agent tooling

- `.claude/settings.json`: common checks run without a prompt; `.env` is not readable. Personal overrides go to `.claude/settings.local.json` (git-ignored).
- PostToolUse hook `.claude/hooks/format-and-lint.sh`: Prettier and `eslint --fix` after each edit; remaining ESLint errors go back to the agent.
- Skill `add-endpoint`: the full checklist for a new or changed route.

## Workflow

1. Branch from `main`. One concern per PR.
2. Make the change and add or update tests.
3. `npm run lint && npm run typecheck && npm run format:check && npm test && npm run build`; `npm run openapi` if routes or schemas changed.
4. Open a PR using `.github/pull_request_template.md`.

## Things to avoid

- Do not commit `.env` or real data in `db.json` (it is sample data that seeds the Docker image).
- Do not add routes without schemas, tests and an `openapi.json` update.
- Do not change the error shape or route paths without a matching frontend change.
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# syntax=docker/dockerfile:1

FROM node:22-alpine AS build
FROM node:24-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY tsconfig.json tsconfig.build.json ./
COPY src ./src
RUN npm run build

FROM node:22-alpine AS runtime
FROM node:24-alpine AS runtime
ENV NODE_ENV=production \
PORT=9000 \
DB_FILE=/app/data/db.json \
Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
REST API for the [LLazyEmail email template editor](https://github.com/LLazyEmail/email-template-editor-reactjs).
It stores a tree of template parts and reusable elements, and renders the tree into a single HTML email.

Stack: Node 22, TypeScript (strict), Express 5, zod, pino, Vitest + Supertest.
Stack: Node 24, TypeScript (strict), Express 5, zod, pino, Vitest + Supertest.

## Quick start

Expand All @@ -22,6 +22,7 @@ npm run dev # http://localhost:9000, hot reload, pretty logs
| `npm run typecheck` | `tsc --noEmit` |
| `npm run lint` | ESLint |
| `npm run format` | Prettier (`format:check` is used in CI) |
| `npm run openapi` | Regenerate `openapi.json` from the schemas |

## Architecture

Expand Down Expand Up @@ -69,6 +70,8 @@ Invalid values stop the server at startup with a clear message.

## API

The machine-readable contract is [`openapi.json`](openapi.json) (OpenAPI 3.1, generated from the zod schemas, also served at `GET /openapi.json`). Agents and contributors: see [`AGENTS.md`](AGENTS.md).

| Method | Path | Body | Success | Errors |
| ------ | ------------------ | -------------------------- | --------------------------- | ------------- |
| GET | `/health` | – | 200 `{ "status": "ok" }` | |
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Development: runs the API with hot reload against the local db.json
services:
api:
image: node:22-alpine
image: node:24-alpine
command: sh -c "npm ci && npm run dev"
working_dir: /app
environment:
Expand Down
Loading