From 63b5a4ecd8ab89701fe9edb604cb97325494c00f Mon Sep 17 00:00:00 2001 From: Peppa Date: Sat, 21 Nov 2026 13:59:13 +0000 Subject: [PATCH 1/5] =?UTF-8?q?INA-2:=20=D0=BF=D0=BB=D0=B0=D0=BD=20=D0=B8?= =?UTF-8?q?=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D1=8F=20(proposal,?= =?UTF-8?q?=20design,=20spec,=20tasks)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../ina-2-business-card-site/.openspec.yaml | 2 + .../ina-2-business-card-site/design.md | 45 +++++++++++ .../ina-2-business-card-site/proposal.md | 49 ++++++++++++ .../specs/business-card-site/spec.md | 80 +++++++++++++++++++ .../changes/ina-2-business-card-site/tasks.md | 20 +++++ 5 files changed, 196 insertions(+) create mode 100644 openspec/changes/ina-2-business-card-site/.openspec.yaml create mode 100644 openspec/changes/ina-2-business-card-site/design.md create mode 100644 openspec/changes/ina-2-business-card-site/proposal.md create mode 100644 openspec/changes/ina-2-business-card-site/specs/business-card-site/spec.md create mode 100644 openspec/changes/ina-2-business-card-site/tasks.md diff --git a/openspec/changes/ina-2-business-card-site/.openspec.yaml b/openspec/changes/ina-2-business-card-site/.openspec.yaml new file mode 100644 index 0000000..137e8c3 --- /dev/null +++ b/openspec/changes/ina-2-business-card-site/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-21 diff --git a/openspec/changes/ina-2-business-card-site/design.md b/openspec/changes/ina-2-business-card-site/design.md new file mode 100644 index 0000000..e52420c --- /dev/null +++ b/openspec/changes/ina-2-business-card-site/design.md @@ -0,0 +1,45 @@ +# Design: INA-2 сайт-визитка + +## Context + +Пустой проект из шаблона Пеппы. Нужен минимальный сайт, который собирается в Docker, +слушает `$PORT`, отвечает на `/healthz` и проходит проверки CI. Тексты — в файлах переводов +на трёх языках, на странице только русский. + +## Goals / Non-Goals + +**Goals:** одна страница с тремя блоками; переводы в отдельных файлах; адаптивность; +healthcheck; настроенные проверки; основа для следующих задач. + +**Non-Goals:** переключатель языка, CMS, формы, аналитика, дизайн/брендинг. + +## Decisions + +1. **Стек: Node.js 22 + TypeScript, встроенный `node:http`, без фреймворка.** Для одной + статической страницы фреймворк (Next.js и т. п.) — лишний вес и время сборки. Сервер + рендерит HTML из шаблона и словаря при старте. Альтернатива — статический nginx-сайт — + отклонена: тексты всё равно надо собирать из переводов, а тесты на Node проще. +2. **Переводы — JSON-файлы `locales/{ru,kk,en}.json`** с одинаковыми плоскими ключами + (`meta.title`, `about.heading` …). Тест сверяет, что набор ключей во всех файлах + совпадает и значения непустые. Язык страницы — константа `DEFAULT_LOCALE = "ru"`; + переключатель появится отдельной задачей. +3. **Все значения экранируются** при подстановке в HTML (защита на будущее, когда тексты + будут настоящими). +4. **Заглушки** помечены «[ЗАГЛУШКА]» (kk — «[ҮЛГІ]», en — «[PLACEHOLDER]»). Тест проверяет + метку в каждом видимом тексте `ru`. +5. **Вёрстка:** один встроенный ` + + +${body} + + +`; +} + +export function renderHomePage(locale: Locale, m: Messages): string { + const e = escapeHtml; + const body = `
+
+

${e(m["site.name"])}

+

${e(m["site.tagline"])}

+
+
+
+
+

${e(m["about.heading"])}

+

${e(m["about.text"])}

+
+
+

${e(m["services.heading"])}

+

${e(m["services.text"])}

+
    +
  • ${e(m["services.item1"])}
  • +
  • ${e(m["services.item2"])}
  • +
  • ${e(m["services.item3"])}
  • +
+
+
+

${e(m["contacts.heading"])}

+

${e(m["contacts.text"])}

+
+
${e(m["contacts.phoneLabel"])}
${e(m["contacts.phone"])}
+
${e(m["contacts.emailLabel"])}
${e(m["contacts.email"])}
+
${e(m["contacts.addressLabel"])}
${e(m["contacts.address"])}
+
+
+
+
+
${e(m["footer.text"])}
+
`; + return layout(locale, m["meta.title"], m["meta.description"], body); +} + +export function renderNotFoundPage(locale: Locale, m: Messages): string { + const e = escapeHtml; + const body = `
+
+

${e(m["notFound.title"])}

+

${e(m["notFound.text"])}

+

${e(m["notFound.link"])}

+
+
`; + return layout(locale, m["notFound.title"], m["meta.description"], body); +} diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..6ab1e90 --- /dev/null +++ b/src/server.ts @@ -0,0 +1,38 @@ +import { createServer, type Server } from "node:http"; +import { DEFAULT_LOCALE, type Locale, loadMessages } from "./i18n.ts"; +import { renderHomePage, renderNotFoundPage } from "./render.ts"; + +const HTML = "text/html; charset=utf-8"; + +export function createApp(locale: Locale = DEFAULT_LOCALE): Server { + const messages = loadMessages(locale); + const home = renderHomePage(locale, messages); + const notFound = renderNotFoundPage(locale, messages); + + return createServer((req, res) => { + const path = new URL(req.url ?? "/", "http://localhost").pathname; + const method = req.method ?? "GET"; + const headOnly = method === "HEAD"; + + if (method !== "GET" && method !== "HEAD") { + res.writeHead(405, { Allow: "GET, HEAD", "Content-Type": "text/plain; charset=utf-8" }); + res.end("Method Not Allowed"); + return; + } + if (path === "/healthz") { + res.writeHead(200, { + "Content-Type": "text/plain; charset=utf-8", + "Cache-Control": "no-store", + }); + res.end(headOnly ? undefined : "ok"); + return; + } + if (path === "/" || path === "/index.html") { + res.writeHead(200, { "Content-Type": HTML, "Cache-Control": "no-cache" }); + res.end(headOnly ? undefined : home); + return; + } + res.writeHead(404, { "Content-Type": HTML }); + res.end(headOnly ? undefined : notFound); + }); +} diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..469ac55 --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..1620908 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "es2023", + "module": "nodenext", + "moduleResolution": "nodenext", + "strict": true, + "noUncheckedIndexedAccess": true, + "resolveJsonModule": true, + "verbatimModuleSyntax": true, + "erasableSyntaxOnly": true, + "allowImportingTsExtensions": true, + "rewriteRelativeImportExtensions": true, + "types": ["node"], + "skipLibCheck": true, + "noEmit": true + }, + "include": ["src", "test"] +} -- 2.45.2 From 7386229c1ac0f77830b5e9e239a1bbdbf1e1c708 Mon Sep 17 00:00:00 2001 From: Peppa Date: Sat, 21 Nov 2026 14:02:32 +0000 Subject: [PATCH 3/5] =?UTF-8?q?INA-2:=20=D1=82=D0=B5=D1=81=D1=82=D1=8B=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D1=81=D1=86=D0=B5=D0=BD=D0=B0=D1=80=D0=B8=D1=8F?= =?UTF-8?q?=D0=BC,=20Dockerfile,=20=D1=81=D0=BB=D0=BE=D0=B2=D0=B0=D1=80?= =?UTF-8?q?=D1=8C=20=D0=B8=20README?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .dockerignore | 4 + Dockerfile | 21 +++ README.md | 13 ++ docs/glossary.md | 12 ++ .../changes/ina-2-business-card-site/tasks.md | 18 +-- test/helpers.ts | 17 +++ test/i18n.test.ts | 61 +++++++++ test/site.test.ts | 120 ++++++++++++++++++ 8 files changed, 257 insertions(+), 9 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 test/helpers.ts create mode 100644 test/i18n.test.ts create mode 100644 test/site.test.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ceb2e70 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,4 @@ +node_modules +dist +.pnpm-store +.git diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c588a32 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +# Сайт-визитка INA (INA-2). Основа — deploy/Dockerfile.node. +# Приложение слушает $PORT и отвечает 200 на GET /healthz (deploy.health). +FROM node:22-bookworm-slim AS build +WORKDIR /app +RUN corepack enable +COPY package.json pnpm-lock.yaml ./ +RUN pnpm install --frozen-lockfile +COPY tsconfig.json tsconfig.build.json ./ +COPY src ./src +RUN pnpm build + +# У сервера нет зависимостей во время работы — в образ идут только сборка и переводы. +FROM node:22-bookworm-slim +WORKDIR /app +ENV NODE_ENV=production PORT=3000 +COPY package.json ./ +COPY --from=build /app/dist ./dist +COPY locales ./locales +USER node +EXPOSE 3000 +CMD ["node", "dist/index.js"] diff --git a/README.md b/README.md index cf036b8..a433f7f 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,16 @@ # inat Проект Peppa FACTORY. Ключ стори: `INA`. Правила — в [AGENTS.md](AGENTS.md). + +Одностраничный сайт-визитка (Node.js 22 + TypeScript, без фреймворка). + +```bash +pnpm install +pnpm dev # http://localhost:3000, порт — $PORT +pnpm lint && pnpm typecheck && pnpm test && pnpm build +pnpm start # запуск собранной версии из dist/ +``` + +- Тексты страницы — `locales/ru.json`, `kk.json`, `en.json` (одинаковые ключи, список — `src/i18n.ts`). + Страница показывает русский (`DEFAULT_LOCALE`). +- `GET /healthz` → `200 ok` — проверка работоспособности при деплое. diff --git a/docs/glossary.md b/docs/glossary.md index 5fa372f..ff72600 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -32,3 +32,15 @@ | Вернуть работу | поправить | реджект, вернуть в бэклог, change request | Кнопка «Поправить» | | Список задач | доска, бэклог | канбан-борд, backlog | «Бэклог» допустим как название колонки | | Ошибки продукта | баги | инциденты, Bugsink, Sentry | Вкладка «Баги» | + +## Сайт-визитка INA + +Слова, которые видит посетитель сайта. Тексты — в `locales/{ru,kk,en}.json`. + +| Понятие | Пишем | Нельзя | Пояснение | +|---|---|---|---| +| Временный текст | [ЗАГЛУШКА] (kk: [ҮЛГІ], en: [PLACEHOLDER]) | lorem ipsum, TODO, тест, placeholder (в ru) | Метка в начале текста, пока нет настоящего; убирается задачей замены текстов | +| Блок о компании | Кто мы | О нас, About | Заголовок первого блока | +| Блок об услугах | Чем занимаемся | Услуги, Services | Заголовок второго блока | +| Блок контактов | Контакты | Связь, Contact us | Заголовок третьего блока | +| Нет страницы | Страница не найдена | 404, Not Found | Ошибка из двух фраз: что случилось и куда перейти | diff --git a/openspec/changes/ina-2-business-card-site/tasks.md b/openspec/changes/ina-2-business-card-site/tasks.md index 074db76..0cd6257 100644 --- a/openspec/changes/ina-2-business-card-site/tasks.md +++ b/openspec/changes/ina-2-business-card-site/tasks.md @@ -1,20 +1,20 @@ ## 1. Каркас проекта и проверки -- [ ] 1.1 `package.json` (pnpm), TypeScript, Biome, `tsconfig.json`/`tsconfig.build.json`, `.gitignore` -- [ ] 1.2 `.peppa/project.json` → `checks` (install, lint, typecheck, test, build) и `deploy` +- [x] 1.1 `package.json` (pnpm), TypeScript, Biome, `tsconfig.json`/`tsconfig.build.json`, `.gitignore` +- [x] 1.2 `.peppa/project.json` → `checks` (install, lint, typecheck, test, build) и `deploy` ## 2. Переводы и страница -- [ ] 2.1 `locales/ru.json`, `kk.json`, `en.json` с заглушками и одинаковыми ключами; загрузка и проверка ключей -- [ ] 2.2 Рендер HTML главной: три блока, title, description, адаптивный CSS, экранирование -- [ ] 2.3 HTTP-сервер: `/`, `/healthz`, 404, 405, порт из `$PORT` +- [x] 2.1 `locales/ru.json`, `kk.json`, `en.json` с заглушками и одинаковыми ключами; загрузка и проверка ключей +- [x] 2.2 Рендер HTML главной: три блока, title, description, адаптивный CSS, экранирование +- [x] 2.3 HTTP-сервер: `/`, `/healthz`, 404, 405, порт из `$PORT` ## 3. Деплой и документация -- [ ] 3.1 `Dockerfile`, проверка `docker build` и `curl /healthz` (если docker доступен) -- [ ] 3.2 `docs/glossary.md` — понятия сайта; README — как запустить +- [x] 3.1 `Dockerfile`; docker в среде агента нет — раскладка образа (dist + locales) проверена запуском `node dist/index.js` и `curl /healthz` +- [x] 3.2 `docs/glossary.md` — понятия сайта; README — как запустить ## 4. Тесты и проверка -- [ ] 4.1 Тесты по сценариям спеки (страница, заглушки, переводы, healthz, 404/405, вёрстка) -- [ ] 4.2 Все проверки `bash .gitea/peppa-check.sh ` зелёные, `openspec validate ina-2-business-card-site` +- [x] 4.1 Тесты по сценариям спеки (страница, заглушки, переводы, healthz, 404/405, вёрстка) +- [x] 4.2 Все проверки `bash .gitea/peppa-check.sh ` зелёные, `openspec validate ina-2-business-card-site` diff --git a/test/helpers.ts b/test/helpers.ts new file mode 100644 index 0000000..b2d8b1d --- /dev/null +++ b/test/helpers.ts @@ -0,0 +1,17 @@ +import type { AddressInfo } from "node:net"; +import { createApp } from "../src/server.ts"; + +export interface Running { + url: string; + close: () => Promise; +} + +export async function startApp(): Promise { + const server = createApp(); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + return { + url: `http://127.0.0.1:${port}`, + close: () => new Promise((resolve) => server.close(() => resolve())), + }; +} diff --git a/test/i18n.test.ts b/test/i18n.test.ts new file mode 100644 index 0000000..6b0b3f2 --- /dev/null +++ b/test/i18n.test.ts @@ -0,0 +1,61 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { describe, it } from "node:test"; +import { + LOCALES, + LOCALES_DIR, + loadMessages, + REQUIRED_KEYS, + validateMessages, +} from "../src/i18n.ts"; + +describe("Требование: файлы переводов на трёх языках", () => { + const ruKeys = Object.keys(JSON.parse(readFileSync(`${LOCALES_DIR}/ru.json`, "utf8"))).sort(); + + for (const locale of LOCALES) { + it(`Scenario Outline: полный файл перевода — ${locale}`, () => { + const data: unknown = JSON.parse(readFileSync(`${LOCALES_DIR}/${locale}.json`, "utf8")); + assert.deepEqual(validateMessages(data), []); + assert.deepEqual(Object.keys(data as object).sort(), ruKeys); + const m = loadMessages(locale); + for (const key of [ + "about.text", + "services.text", + "contacts.text", + "meta.title", + "meta.description", + ] as const) { + assert.ok(m[key].trim().length > 0, `${locale}: ${key} is empty`); + } + }); + } + + it("Scenario: пропущенный ключ", () => { + const ru = loadMessages("ru") as Record; + const { "contacts.heading": _removed, ...broken } = ru; + assert.deepEqual(validateMessages(broken), ["missing key contacts.heading"]); + }); + + it("пустое значение и лишний ключ тоже считаются ошибкой", () => { + const ru = loadMessages("ru") as Record; + const problems = validateMessages({ ...ru, "about.text": " ", "extra.key": "x" }); + assert.deepEqual(problems, ["empty key about.text", "unknown key extra.key"]); + assert.deepEqual(validateMessages([]), ["file must contain a JSON object"]); + }); + + it("заглушки помечены во всех языках", () => { + const markers = { ru: "[ЗАГЛУШКА]", kk: "[ҮЛГІ]", en: "[PLACEHOLDER]" } as const; + const placeholderKeys = REQUIRED_KEYS.filter( + (k) => !k.endsWith("heading") && !k.endsWith("Label") && !k.startsWith("notFound."), + ); + for (const locale of LOCALES) { + const m = loadMessages(locale); + for (const key of placeholderKeys) { + assert.ok( + m[key].startsWith(markers[locale]), + `${locale}: ${key} has no placeholder marker`, + ); + } + } + }); +}); diff --git a/test/site.test.ts b/test/site.test.ts new file mode 100644 index 0000000..3daa5a4 --- /dev/null +++ b/test/site.test.ts @@ -0,0 +1,120 @@ +import assert from "node:assert/strict"; +import { after, before, describe, it } from "node:test"; +import { loadMessages } from "../src/i18n.ts"; +import { escapeHtml, renderHomePage } from "../src/render.ts"; +import { type Running, startApp } from "./helpers.ts"; + +let app: Running; +before(async () => { + app = await startApp(); +}); +after(async () => { + await app.close(); +}); + +const text = (html: string) => + html + .replace(/