From fc74c8f543c86cbb64d37d1b96130b98f5f43c09 Mon Sep 17 00:00:00 2001 From: Coder Date: Tue, 25 Aug 2026 21:28:55 +0700 Subject: [PATCH] =?UTF-8?q?Initial=20commit:=20AI-=D1=84=D0=BE=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=B5=D0=B4=D0=B0=D0=BA=D1=82=D0=BE=D1=80=20(Codex-?= =?UTF-8?q?=D1=80=D0=B5=D0=B4=D0=B0=D0=BA=D1=82=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B5,=20ComfyUI=20upscale,=20HEIC,=20=D0=B8?= =?UTF-8?q?=D1=81=D1=82=D0=BE=D1=80=D0=B8=D1=8F=20=D0=B2=D0=B5=D1=80=D1=81?= =?UTF-8?q?=D0=B8=D0=B9,=20Docker,=20Gitea=20Actions)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 16 + .gitea/workflows/build.yml | 51 ++ .gitignore | 17 + Dockerfile | 42 + README.md | 70 ++ codex/config.toml | 11 + docker-compose.yml | 19 + package-lock.json | 1053 ++++++++++++++++++++++++ package.json | 18 + public/app.js | 575 +++++++++++++ public/index.html | 229 ++++++ public/style.css | 955 ++++++++++++++++++++++ server.js | 1572 ++++++++++++++++++++++++++++++++++++ 13 files changed, 4628 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitea/workflows/build.yml create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 codex/config.toml create mode 100644 docker-compose.yml create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 public/app.js create mode 100644 public/index.html create mode 100644 public/style.css create mode 100644 server.js diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..503caeb --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +# Зависимости и состояние — не попадают в образ +node_modules +history +.codex-jobs +npm-debug.log* + +# Временные и тестовые файлы +_* +*.tmp + +# VCS и прочее +.git +.gitignore +README.md +Dockerfile +docker-compose.yml diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml new file mode 100644 index 0000000..b95f03a --- /dev/null +++ b/.gitea/workflows/build.yml @@ -0,0 +1,51 @@ +name: build-container + +# Запуск вручную: вкладка Actions → кнопка «Run workflow» +on: + workflow_dispatch: + +concurrency: + group: container + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + # Логин во встроенный registry Gitea. + # GITHUB_TOKEN выдаётся автоматически; если понадобится PAT — + # создайте секрет GITEA_TOKEN и замените password на него. + - name: Login to Gitea container registry + uses: docker/login-action@v3 + with: + registry: git.byte-mate.ru + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: . + push: true + tags: | + git.byte-mate.ru/${{ github.repository }}:latest + git.byte-mate.ru/${{ github.repository }}:${{ github.ref_name }} + labels: | + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + + - name: Summary + run: | + echo "## Образ собран и опубликован" >> $GITHUB_STEP_SUMMARY + echo "Теги: \`git.byte-mate.ru/${{ github.repository }}:latest\`" >> $GITHUB_STEP_SUMMARY diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ecc297b --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +# Зависимости +node_modules/ + +# Данные приложения (история версий, временные рабочие каталоги Codex) +history/ +.codex-jobs/ + +# Временные и тестовые файлы +_* +*.tmp +*.log + +# ОС / редакторы +.DS_Store +Thumbs.db +.idea/ +.vscode/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a03ca2d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,42 @@ +# Кадр — локальный AI-фоторедактор +# Образ: Node.js 22 на Debian bookworm-slim. +# Debian (glibc) обязателен: Codex CLI поставляется как бинарник под glibc, +# на Alpine (musl) он не запускается. +FROM node:22-bookworm-slim + +# Утилиты для healthcheck +RUN apt-get update \ + && apt-get install -y --no-install-recommends wget ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +# Codex CLI — движок редактирования фотографий по текстовому промпту. +# Авторизация: смонтируйте ~/.codex в /root/.codex (см. docker-compose.yml) +# или задайте переменную окружения OPENAI_API_KEY. +RUN npm install -g @openai/codex + +WORKDIR /app + +# Сначала зависимости — слой кэшируется до копирования кода +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev + +# Код приложения +COPY server.js ./ +COPY public ./public + +# Конфиг Codex по умолчанию (используется, если ~/.codex не смонтирован) +COPY codex/config.toml /root/.codex/config.toml + +ENV NODE_ENV=production +ENV COMFY_URL=http://192.168.31.240:8188 + +# История версий должна жить на томе — иначе версии пропадут +# при пересоздании контейнера. +VOLUME ["/app/history"] + +EXPOSE 3000 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ + CMD wget -qO- http://127.0.0.1:3000/api/health >/dev/null 2>&1 || exit 1 + +CMD ["node", "server.js"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..79de004 --- /dev/null +++ b/README.md @@ -0,0 +1,70 @@ +# Кадр — локальный AI-фоторедактор + +Веб-приложение редактирует фотографии по текстовому промпту (через локальный +Codex CLI) и увеличивает разрешение через домашний сервер ComfyUI. + +Поддерживаются фотографии JPEG, PNG, WebP и HEIC/HEIF. Файлы HEIC/HEIF +преобразуются на сервере в JPEG с помощью `heic-convert` до передачи в ComfyUI +или Codex. + +## Как это работает + +- **История версий**: каждая загрузка и каждый результат (редактирование или + апскейл) сохраняется в папке `history/` как отдельная версия. Можно вернуться + к любой версии кликом по ней в ленте «История версий» и продолжить правки + именно с неё — например, отредактировать фото, а затем увеличить разрешение + уже отредактированного варианта. История переживает перезапуск сервера и + обновление страницы; хранится последние 50 версий. +- **Редактирование**: сервер передаёт выбранную версию и промпт агенту Codex + CLI (`codex exec`). Агент редактирует изображение и сохраняет результат. + Обработка обычно занимает 1–3 минуты. +- **Увеличение разрешения**: 4× upscale через ComfyUI моделью + `RealESRGAN_x4plus.safetensors` — применяется к выбранной (в том числе + отредактированной) версии. + +## Требования + +- Node.js 20 или новее +- Локальный Codex CLI (`codex`) с выполненным входом в аккаунт OpenAI +- Доступ к ComfyUI: `http://192.168.31.240:8188` +- Checkpoint: `sdxl_turbo.safetensors` +- Upscale-модель: `RealESRGAN_x4plus.safetensors` +- Установленные зависимости проекта, включая `heic-convert` (ставится + командой `npm install`) + +## Запуск + +```powershell +npm install +npm start +``` + +## Docker + +Образ собирается на базе `node:22-bookworm-slim` (Debian, glibc) — Codex CLI +распространяется как бинарник под glibc и не работает на Alpine/musl. + +```powershell +# сборка и запуск +docker compose up -d --build + +# или вручную: +docker build -t kadr-photo-editor . +docker run -d --name kadr-photo-editor -p 3000:3000 ^ + -v "$env:USERPROFILE\.codex:/root/.codex" ^ + -v "${PWD}\history:/app/history" ^ + -e COMFY_URL=http://192.168.31.240:8188 ^ + kadr-photo-editor +``` + +Что важно знать: + +- **Авторизация Codex**: контейнер монтирует `~/.codex` хоста в `/root/.codex` + (auth + config + навыки). Альтернатива — переменная окружения + `OPENAI_API_KEY`. +- **История версий**: каталог `history/` смонтирован томом, версии переживают + пересоздание контейнера. +- **ComfyUI**: задаётся через `COMFY_URL` (по умолчанию + `http://192.168.31.240:8188`); из контейнера адрес доступен как исходящий + адрес локальной сети. +- **Порт**: по умолчанию 3000, меняется через `PORT`. diff --git a/codex/config.toml b/codex/config.toml new file mode 100644 index 0000000..858750e --- /dev/null +++ b/codex/config.toml @@ -0,0 +1,11 @@ +# Конфигурация Codex CLI внутри контейнера. +# Используется только если папка ~/.codex хоста не смонтирована в /root/.codex +# (при монтировании действует ваш собственный config.toml). + +model = "gpt-5.6-sol" +model_reasoning_effort = "high" +service_tier = "priority" +approval_policy = "never" + +# Авторизация Codex: смонтируйте ~/.codex (auth.json) или задайте +# переменную окружения OPENAI_API_KEY при запуске контейнера. diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..4432a0a --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,19 @@ +services: + photo-editor: + build: . + container_name: kadr-photo-editor + ports: + - "3000:3000" + volumes: + # История версий на хосте — переживает пересоздание контейнера + - ./history:/app/history + # Аутентификация и конфиг Codex из домашней папки пользователя + # (auth.json, config.toml, навыки). Если не монтировать — задайте + # OPENAI_API_KEY в environment. + - ~/.codex:/root/.codex + environment: + # Адрес ComfyUI (доступен из контейнера как исходящий адрес LAN) + - COMFY_URL=http://192.168.31.240:8188 + # Альтернатива монтированию ~/.codex (раскомментируйте при необходимости): + # - OPENAI_API_KEY=${OPENAI_API_KEY} + restart: unless-stopped diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..fde8770 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1053 @@ +{ + "name": "prompt-photo-editor", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "prompt-photo-editor", + "version": "1.0.0", + "dependencies": { + "express": "^4.19.2", + "heic-convert": "^2.1.0", + "multer": "^1.4.5-lts.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==", + "license": "MIT" + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", + "license": "MIT" + }, + "node_modules/body-parser": { + "version": "1.20.6", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.6.tgz", + "integrity": "sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.15.1", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "license": "MIT" + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "engines": [ + "node >= 0.8" + ], + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", + "license": "MIT" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.22.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz", + "integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.5", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.15.1", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "statuses": "~2.0.2", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/heic-convert": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/heic-convert/-/heic-convert-2.1.0.tgz", + "integrity": "sha512-1qDuRvEHifTVAj3pFIgkqGgJIr0M3X7cxEPjEp0oG4mo8GFjq99DpCo8Eg3kg17Cy0MTjxpFdoBHOatj7ZVKtg==", + "license": "ISC", + "dependencies": { + "heic-decode": "^2.0.0", + "jpeg-js": "^0.4.4", + "pngjs": "^6.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/heic-decode": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/heic-decode/-/heic-decode-2.1.0.tgz", + "integrity": "sha512-0fB3O3WMk38+PScbHLVp66jcNhsZ/ErtQ6u2lMYu/YxXgbBtl+oKOhGQHa4RpvE68k8IzbWkABzHnyAIjR758A==", + "license": "ISC", + "dependencies": { + "libheif-js": "^1.19.8" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/jpeg-js": { + "version": "0.4.4", + "resolved": "https://registry.npmjs.org/jpeg-js/-/jpeg-js-0.4.4.tgz", + "integrity": "sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==", + "license": "BSD-3-Clause" + }, + "node_modules/libheif-js": { + "version": "1.19.8", + "resolved": "https://registry.npmjs.org/libheif-js/-/libheif-js-1.19.8.tgz", + "integrity": "sha512-vQJWusIxO7wavpON1dusciL8Go9jsIQ+EUrckauFYAiSTjcmLAsuJh3SszLpvkwPci3JcL41ek2n+LUZGFpPIQ==", + "license": "LGPL-3.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "license": "MIT", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" + }, + "node_modules/multer": { + "version": "1.4.5-lts.2", + "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.2.tgz", + "integrity": "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==", + "deprecated": "Multer 1.x is impacted by a number of vulnerabilities, which have been patched in 2.x. You should upgrade to the latest 2.x version.", + "license": "MIT", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.0.0", + "concat-stream": "^1.5.2", + "mkdirp": "^0.5.4", + "object-assign": "^4.1.1", + "type-is": "^1.6.4", + "xtend": "^4.0.0" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" + }, + "node_modules/pngjs": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-6.0.0.tgz", + "integrity": "sha512-TRzzuFRRmEoSW/p1KVAmiOgPco2Irlah+bGFCeNfJXxxYGwSw7YwAOAcd7X28K/m5bjBWKsC29KyoMfHbypayg==", + "license": "MIT", + "engines": { + "node": ">=12.13.0" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/qs": { + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/readable-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", + "license": "MIT", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "~2.4.1", + "range-parser": "~1.2.1", + "statuses": "~2.0.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/serve-static": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", + "license": "MIT", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", + "license": "MIT" + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "license": "MIT", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..df29e96 --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "prompt-photo-editor", + "version": "1.0.0", + "private": true, + "description": "Локальный веб-редактор фотографий на базе ComfyUI", + "main": "server.js", + "scripts": { + "start": "node server.js" + }, + "engines": { + "node": ">=20" + }, + "dependencies": { + "express": "^4.19.2", + "heic-convert": "^2.1.0", + "multer": "^1.4.5-lts.1" + } +} diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..35d14f5 --- /dev/null +++ b/public/app.js @@ -0,0 +1,575 @@ +"use strict"; + +const MAX_FILE_SIZE = 25 * 1024 * 1024; +const ACCEPTED_TYPES = new Set([ + "image/jpeg", + "image/jpg", + "image/png", + "image/webp", + "image/heic", + "image/heif" +]); + +const healthStatus = document.querySelector("#health-status"); +const healthText = document.querySelector("#health-text"); + +const dropZone = document.querySelector("#drop-zone"); +const photoInput = document.querySelector("#photo-input"); +const dropTitle = document.querySelector("#drop-title"); +const fileMeta = document.querySelector("#file-meta"); + +const promptInput = document.querySelector("#prompt"); +const promptCounter = document.querySelector("#prompt-counter"); + +const editButton = document.querySelector("#edit-button"); +const upscaleButton = document.querySelector("#upscale-button"); + +const workspace = document.querySelector("#workspace"); +const sourceImage = document.querySelector("#source-image"); +const sourcePlaceholder = document.querySelector("#source-placeholder"); +const resultImage = document.querySelector("#result-image"); +const resultPlaceholder = document.querySelector("#result-placeholder"); +const resultLabel = document.querySelector("#result-label"); + +const jobStatus = document.querySelector("#job-status"); +const jobStatusText = document.querySelector("#job-status-text"); +const downloadLink = document.querySelector("#download-link"); + +let currentVersionId = null; +let historyVersions = []; +let sourceObjectUrl = null; +let isBusy = false; +let fileSelectionSequence = 0; + +function isHeicFile(file) { + const type = String(file?.type || "").toLowerCase(); + const name = String(file?.name || "").toLowerCase(); + + return ( + type === "image/heic" || + type === "image/heif" || + name.endsWith(".heic") || + name.endsWith(".heif") + ); +} + +function formatFileSize(bytes) { + if (bytes < 1024 * 1024) { + return `${Math.max(1, Math.round(bytes / 1024))} КБ`; + } + + return `${(bytes / (1024 * 1024)).toFixed(1)} МБ`; +} + +function setHealthState(state, message, title = "") { + healthStatus.className = `health-status health-${state}`; + healthText.textContent = message; + healthStatus.title = title; +} + +function setJobStatus(kind, message) { + if (!message) { + jobStatus.hidden = true; + jobStatus.removeAttribute("data-kind"); + jobStatusText.textContent = ""; + return; + } + + jobStatus.hidden = false; + jobStatus.dataset.kind = kind; + jobStatusText.textContent = message; +} + +function setBusy(busy) { + isBusy = busy; + workspace.setAttribute("aria-busy", String(busy)); + + editButton.disabled = busy || !currentVersionId; + upscaleButton.disabled = busy || !currentVersionId; + promptInput.disabled = busy; + photoInput.disabled = busy; + + dropZone.setAttribute("aria-disabled", String(busy)); +} + +function resetResult() { + resultImage.hidden = true; + resultImage.removeAttribute("src"); + resultPlaceholder.hidden = false; + resultLabel.textContent = ""; + downloadLink.hidden = true; + downloadLink.removeAttribute("href"); + downloadLink.removeAttribute("download"); +} + +function clearSourcePreview() { + if (sourceObjectUrl) { + URL.revokeObjectURL(sourceObjectUrl); + sourceObjectUrl = null; + } + + sourceImage.hidden = true; + sourceImage.removeAttribute("src"); + sourcePlaceholder.hidden = false; +} + +function showSourcePreview(url) { + if (sourceObjectUrl) { + URL.revokeObjectURL(sourceObjectUrl); + sourceObjectUrl = null; + } + + sourceImage.src = url; + sourceImage.hidden = false; + sourcePlaceholder.hidden = true; +} + +function showSourcePreviewFromUrl(url, title, meta) { + showSourcePreview(url); + + dropZone.classList.add("has-file"); + dropTitle.textContent = title || "Текущая фотография"; + fileMeta.textContent = meta || "Готово к обработке"; +} + +async function selectFile(file) { + const selectionToken = ++fileSelectionSequence; + + if (!file) { + return; + } + + const fileType = String(file.type || "").toLowerCase(); + + if (!ACCEPTED_TYPES.has(fileType) && !isHeicFile(file)) { + setJobStatus( + "error", + "Поддерживаются только фотографии JPEG, PNG, WebP или HEIC." + ); + return; + } + + if (file.size > MAX_FILE_SIZE) { + setJobStatus( + "error", + "Файл слишком большой. Максимальный размер — 25 МБ." + ); + return; + } + + setBusy(true); + setJobStatus("loading", "Загружаем фотографию в историю…"); + + const form = new FormData(); + form.append("photo", file, file.name); + + try { + const response = await fetch("/api/history/import", { + method: "POST", + body: form, + cache: "no-store" + }); + + if (!response.ok) { + let message = `Не удалось загрузить фотографию. HTTP ${response.status}.`; + const contentType = response.headers.get("content-type") || ""; + + if (contentType.includes("application/json")) { + const data = await response.json().catch(() => null); + + if (data?.error) { + message = data.error; + } + } + + throw new Error(message); + } + + const data = await response.json(); + + if (selectionToken !== fileSelectionSequence) { + return; + } + + historyVersions.push(data.version); + currentVersionId = data.version.id; + + renderHistory(); + resetResult(); + showSourcePreviewFromUrl( + data.version.url, + file.name, + `${formatFileSize(file.size)} · готово к обработке` + ); + setJobStatus("", ""); + setBusy(false); + } catch (error) { + if (selectionToken !== fileSelectionSequence) { + return; + } + + setBusy(false); + setJobStatus( + "error", + error instanceof Error + ? error.message + : "Не удалось загрузить фотографию." + ); + } +} + +function openFilePicker() { + if (!isBusy) { + photoInput.click(); + } +} + +function preventDragDefaults(event) { + event.preventDefault(); + event.stopPropagation(); +} + +async function readJsonResponse(response) { + const contentType = response.headers.get("content-type") || ""; + + if (!contentType.includes("application/json")) { + throw new Error( + `Сервер вернул неожиданный ответ HTTP ${response.status}.` + ); + } + + return response.json(); +} + +async function runJob(kind) { + if (isBusy) { + return; + } + + if (!currentVersionId) { + setJobStatus("error", "Сначала выберите фотографию."); + return; + } + + const prompt = promptInput.value.trim(); + + if (kind === "edit" && !prompt) { + setJobStatus( + "error", + "Введите промпт — опишите, как нужно изменить фотографию." + ); + promptInput.focus(); + return; + } + + const isEdit = kind === "edit"; + const endpoint = isEdit ? "/api/edit" : "/api/upscale"; + const form = new FormData(); + + form.append("sourceId", currentVersionId); + + if (isEdit) { + form.append("prompt", prompt); + } + + resetResult(); + setBusy(true); + setJobStatus( + "loading", + isEdit + ? "Codex редактирует фотографию… Обычно 1–3 минуты." + : "Увеличиваем разрешение фотографии…" + ); + + try { + const response = await fetch(endpoint, { + method: "POST", + body: form, + cache: "no-store" + }); + + const data = await readJsonResponse(response); + + if (!response.ok || !data.ok) { + throw new Error(data.error || "Не удалось обработать фотографию."); + } + + const version = data.version; + + if (version) { + historyVersions.push(version); + currentVersionId = version.id; + renderHistory(); + } + + const url = version?.url || data.result?.url; + + resultImage.src = url; + resultImage.hidden = false; + resultPlaceholder.hidden = true; + + resultLabel.textContent = isEdit ? "Редактирование · Codex" : "4× upscale"; + + downloadLink.href = url; + downloadLink.download = + data.result?.filename || + (isEdit ? "edited-photo.jpg" : "upscaled-photo.png"); + downloadLink.hidden = false; + + const summary = isEdit && data.summary + ? String(data.summary).replace(/\s+/g, " ").trim().slice(0, 180) + : ""; + + setJobStatus( + "success", + isEdit + ? summary + ? `Готово — фотография отредактирована. Codex: ${summary}` + : "Готово — фотография отредактирована." + : `Готово — разрешение увеличено с помощью ${data.job?.model || "upscale-модели"}.` + ); + + if (window.matchMedia("(max-width: 1040px)").matches) { + resultImage.scrollIntoView({ + behavior: "smooth", + block: "center" + }); + } + } catch (error) { + setJobStatus( + "error", + error instanceof Error + ? error.message + : "Не удалось обработать фотографию." + ); + } finally { + setBusy(false); + } +} + +function formatHistoryDate(iso) { + try { + return new Date(iso).toLocaleString("ru-RU", { + day: "2-digit", + month: "2-digit", + hour: "2-digit", + minute: "2-digit" + }); + } catch { + return ""; + } +} + +function historyItemBadge(version) { + if (version.kind === "original") { + return "загрузка"; + } + + if (version.kind === "upscale") { + return "4× upscale"; + } + + return "Codex"; +} + +function renderHistory() { + const list = document.querySelector("#history-list"); + const empty = document.querySelector("#history-empty"); + + list.querySelectorAll(".history-item").forEach((item) => item.remove()); + empty.hidden = historyVersions.length > 0; + + for (const version of historyVersions) { + const item = document.createElement("button"); + item.type = "button"; + item.className = "history-item"; + item.dataset.id = version.id; + item.setAttribute("aria-label", version.label || "Версия"); + + if (version.id === currentVersionId) { + item.classList.add("is-current"); + } + + const thumb = document.createElement("img"); + thumb.src = version.url; + thumb.alt = ""; + thumb.loading = "lazy"; + + const meta = document.createElement("span"); + meta.className = "history-item-meta"; + + const title = document.createElement("strong"); + title.textContent = version.label || "Версия"; + + const sub = document.createElement("span"); + const size = + version.width && version.height + ? ` · ${version.width}×${version.height}` + : ""; + sub.textContent = `${formatHistoryDate(version.createdAt)}${size}`; + + meta.append(title, sub); + + const badge = document.createElement("span"); + badge.className = "history-item-badge"; + badge.textContent = historyItemBadge(version); + + item.append(thumb, meta, badge); + item.addEventListener("click", () => selectHistoryVersion(version)); + list.appendChild(item); + } +} + +function selectHistoryVersion(version) { + if (isBusy) { + return; + } + + currentVersionId = version.id; + + resetResult(); + showSourcePreviewFromUrl( + version.url, + version.label || "Версия", + version.width && version.height + ? `${version.width}×${version.height}` + : "Готово к обработке" + ); + renderHistory(); + setJobStatus("", ""); +} + +async function loadHistoryOnStart() { + try { + const response = await fetch("/api/history", { + cache: "no-store" + }); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}`); + } + + const data = await response.json(); + historyVersions = Array.isArray(data.versions) ? data.versions : []; + + if (historyVersions.length > 0) { + const latest = historyVersions[historyVersions.length - 1]; + currentVersionId = latest.id; + showSourcePreviewFromUrl( + latest.url, + latest.label || "Текущая фотография", + latest.width && latest.height + ? `${latest.width}×${latest.height}` + : "Готово к обработке" + ); + } + } catch { + historyVersions = []; + } finally { + renderHistory(); + setBusy(false); + } +} + +async function checkHealth() { + setHealthState("loading", "Проверяем сервер обработки…"); + + try { + const response = await fetch("/api/health", { + cache: "no-store" + }); + const data = await readJsonResponse(response); + + if (data.ok) { + const modelTitle = data.selectedUpscaleModel + ? `Upscale: ${data.selectedUpscaleModel}` + : ""; + + setHealthState( + "ok", + "Сервер обработки: доступен", + modelTitle + ); + return; + } + + if (data.comfyAvailable) { + const missing = Array.isArray(data.missingNodes) + ? data.missingNodes.join(", ") + : ""; + + setHealthState( + "warning", + data.message || "Сервер настроен не полностью", + missing ? `Отсутствуют узлы: ${missing}` : "" + ); + return; + } + + setHealthState( + "error", + "Сервер обработки: недоступен", + data.message || "" + ); + } catch (error) { + setHealthState( + "error", + "Сервер обработки: недоступен", + error instanceof Error ? error.message : "" + ); + } +} + +dropZone.addEventListener("click", openFilePicker); + +dropZone.addEventListener("keydown", (event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + openFilePicker(); + } +}); + +photoInput.addEventListener("change", () => { + selectFile(photoInput.files?.[0]); + photoInput.value = ""; +}); + +["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => { + dropZone.addEventListener(eventName, preventDragDefaults); +}); + +["dragenter", "dragover"].forEach((eventName) => { + dropZone.addEventListener(eventName, () => { + if (!isBusy) { + dropZone.classList.add("is-dragging"); + } + }); +}); + +["dragleave", "drop"].forEach((eventName) => { + dropZone.addEventListener(eventName, () => { + dropZone.classList.remove("is-dragging"); + }); +}); + +dropZone.addEventListener("drop", (event) => { + if (!isBusy) { + selectFile(event.dataTransfer?.files?.[0]); + } +}); + +promptInput.addEventListener("input", () => { + promptCounter.textContent = `${promptInput.value.length} / 1000`; +}); + +editButton.addEventListener("click", () => runJob("edit")); +upscaleButton.addEventListener("click", () => runJob("upscale")); + +window.addEventListener("beforeunload", () => { + if (sourceObjectUrl) { + URL.revokeObjectURL(sourceObjectUrl); + } +}); + +checkHealth(); +loadHistoryOnStart(); diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..e08970c --- /dev/null +++ b/public/index.html @@ -0,0 +1,229 @@ + + + + + + + Кадр — AI-фоторедактор + + + + +
+ + + Кадр + + +
+ + Проверяем сервер обработки… +
+
+ +
+
+
+

Локальная AI-студия

+

Меняйте кадр словами.

+

+ Загрузите фотографию, опишите желаемое изменение или увеличьте + разрешение одним нажатием. +

+
+ +
+
+ Фотография + +
+ + + + + + Перетащите фото сюда + + или нажмите, чтобы выбрать JPEG, PNG или WebP + + + + Выбрать +
+
+ +
+ + +
+ Опишите свет, настроение и нужные детали. + 0 / 1000 +
+
+ +
+ + + +
+ +

+ Фото передаётся только вашему локальному серверу ComfyUI. +

+
+
+ +
+
+
+

Предпросмотр

+

До и после

+
+ LAN · локально +
+ +
+
+
Исходник
+ +
+ + +
+ + Здесь появится фотография + Выберите файл слева, чтобы начать +
+
+
+ +
+
+ Результат + +
+ +
+ + +
+ + Результат появится здесь + Редактирование через Codex — 1–3 минуты, апскейл — несколько секунд +
+
+
+
+ + + + + +
+
+

История версий

+ + Нажмите на версию, чтобы вернуться к ней и продолжить правки + +
+
+
+ Пока пусто — загрузите фото, и все версии появятся здесь +
+
+
+
+
+ + + + + + diff --git a/public/style.css b/public/style.css new file mode 100644 index 0000000..1efd4be --- /dev/null +++ b/public/style.css @@ -0,0 +1,955 @@ +:root { + color-scheme: light; + --paper: #f3f0e8; + --panel: #fbfaf6; + --ink: #171817; + --muted: #666962; + --line: #d9d7ce; + --dark: #202321; + --accent: #6c5ce7; + --accent-dark: #5544d2; + --accent-soft: #e7e2ff; + --success: #20825c; + --warning: #b06e1f; + --danger: #b84343; + --shadow: 0 26px 70px rgba(28, 31, 29, 0.12); + --radius-large: 28px; + --radius-medium: 18px; + --radius-small: 12px; +} + +* { + box-sizing: border-box; +} + +[hidden] { + display: none !important; +} + +html { + min-width: 320px; + min-height: 100%; + background: var(--paper); +} + +body { + min-height: 100vh; + margin: 0; + color: var(--ink); + background: + radial-gradient(circle at 85% 10%, rgba(108, 92, 231, 0.12), transparent 28rem), + linear-gradient(135deg, rgba(255, 255, 255, 0.28), transparent 55%), + var(--paper); + font-family: + Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, + "Segoe UI", sans-serif; + -webkit-font-smoothing: antialiased; +} + +button, +textarea, +input { + font: inherit; +} + +button, +[role="button"], +a { + -webkit-tap-highlight-color: transparent; +} + +.topbar { + display: flex; + min-height: 78px; + align-items: center; + justify-content: space-between; + gap: 24px; + padding: 16px clamp(20px, 4vw, 64px); + border-bottom: 1px solid rgba(23, 24, 23, 0.1); +} + +.brand { + display: inline-flex; + align-items: center; + gap: 11px; + color: inherit; + text-decoration: none; +} + +.brand-mark { + display: grid; + width: 38px; + height: 38px; + place-items: center; + border-radius: 11px; + color: white; + background: var(--dark); + font-size: 18px; + font-weight: 750; + transform: rotate(-3deg); +} + +.brand-name { + font-size: 19px; + font-weight: 760; + letter-spacing: -0.03em; +} + +.health-status { + display: inline-flex; + max-width: 440px; + align-items: center; + gap: 9px; + color: var(--muted); + font-size: 13px; + font-weight: 620; + text-align: right; +} + +.health-dot { + width: 9px; + height: 9px; + flex: 0 0 auto; + border-radius: 50%; + background: #a9aaa6; + box-shadow: 0 0 0 4px rgba(169, 170, 166, 0.15); +} + +.health-loading .health-dot { + animation: health-pulse 1.4s ease-in-out infinite; +} + +.health-ok .health-dot { + background: var(--success); + box-shadow: 0 0 0 4px rgba(32, 130, 92, 0.13); +} + +.health-warning .health-dot { + background: var(--warning); + box-shadow: 0 0 0 4px rgba(176, 110, 31, 0.13); +} + +.health-error .health-dot { + background: var(--danger); + box-shadow: 0 0 0 4px rgba(184, 67, 67, 0.13); +} + +.editor-layout { + display: grid; + grid-template-columns: minmax(310px, 0.72fr) minmax(520px, 1.45fr); + gap: clamp(24px, 4vw, 58px); + width: min(1500px, 100%); + margin: 0 auto; + padding: clamp(28px, 5vw, 72px) clamp(20px, 4vw, 64px) 64px; +} + +.control-panel { + align-self: start; +} + +.intro { + margin-bottom: 36px; +} + +.eyebrow, +.workspace-kicker { + margin: 0 0 10px; + color: var(--accent-dark); + font-size: 11px; + font-weight: 800; + letter-spacing: 0.15em; + text-transform: uppercase; +} + +h1, +h2, +p { + margin-top: 0; +} + +h1 { + max-width: 520px; + margin-bottom: 18px; + font-size: clamp(40px, 5vw, 70px); + font-weight: 720; + line-height: 0.96; + letter-spacing: -0.065em; +} + +.lead { + max-width: 520px; + margin-bottom: 0; + color: var(--muted); + font-size: clamp(15px, 1.5vw, 18px); + line-height: 1.65; +} + +.control-stack { + display: grid; + gap: 23px; +} + +.field-group { + display: grid; + gap: 10px; +} + +.field-label { + font-size: 13px; + font-weight: 750; +} + +.drop-zone { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: center; + gap: 15px; + min-height: 104px; + padding: 17px; + border: 1.5px dashed #bdbbb1; + border-radius: var(--radius-medium); + background: rgba(251, 250, 246, 0.65); + cursor: pointer; + outline: none; + transition: + border-color 160ms ease, + background 160ms ease, + box-shadow 160ms ease, + transform 160ms ease; +} + +.drop-zone:hover, +.drop-zone:focus-visible, +.drop-zone.is-dragging { + border-color: var(--accent); + background: #faf8ff; + box-shadow: 0 0 0 4px rgba(108, 92, 231, 0.1); + transform: translateY(-1px); +} + +.drop-zone.has-file { + border-style: solid; + border-color: rgba(32, 130, 92, 0.45); + background: rgba(239, 250, 245, 0.72); +} + +.upload-symbol { + display: grid; + width: 46px; + height: 46px; + flex: 0 0 auto; + place-items: center; + border-radius: 14px; + color: var(--accent-dark); + background: var(--accent-soft); + font-size: 27px; + font-weight: 300; +} + +.has-file .upload-symbol { + color: var(--success); + background: rgba(32, 130, 92, 0.11); +} + +.drop-copy { + display: grid; + min-width: 0; + gap: 4px; +} + +.drop-copy strong { + overflow: hidden; + font-size: 14px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.drop-copy span { + overflow: hidden; + color: var(--muted); + font-size: 12px; + line-height: 1.4; + text-overflow: ellipsis; + white-space: nowrap; +} + +.choose-chip { + padding: 8px 11px; + border-radius: 999px; + color: var(--dark); + background: #e8e7e1; + font-size: 11px; + font-weight: 750; +} + +textarea { + width: 100%; + min-height: 120px; + resize: vertical; + padding: 16px 17px; + border: 1px solid var(--line); + border-radius: var(--radius-medium); + outline: none; + color: var(--ink); + background: var(--panel); + line-height: 1.55; + box-shadow: 0 1px 0 rgba(255, 255, 255, 0.8) inset; + transition: + border-color 160ms ease, + box-shadow 160ms ease; +} + +textarea::placeholder { + color: #9a9b96; +} + +textarea:focus { + border-color: var(--accent); + box-shadow: 0 0 0 4px rgba(108, 92, 231, 0.1); +} + +textarea:disabled { + cursor: wait; + opacity: 0.72; +} + +.field-foot { + display: flex; + justify-content: space-between; + gap: 14px; + color: var(--muted); + font-size: 11px; + line-height: 1.4; +} + +.actions { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px; +} + +.button { + min-height: 54px; + padding: 13px 16px; + border: 0; + border-radius: 15px; + cursor: pointer; + font-size: 13px; + font-weight: 760; + transition: + transform 150ms ease, + background 150ms ease, + box-shadow 150ms ease, + opacity 150ms ease; +} + +.button:not(:disabled):hover { + transform: translateY(-2px); +} + +.button:not(:disabled):active { + transform: translateY(0); +} + +.button:focus-visible { + outline: 3px solid rgba(108, 92, 231, 0.28); + outline-offset: 2px; +} + +.button:disabled { + cursor: not-allowed; + opacity: 0.43; +} + +.button-primary { + display: flex; + align-items: center; + justify-content: space-between; + color: white; + background: var(--accent); + box-shadow: 0 10px 25px rgba(108, 92, 231, 0.24); +} + +.button-primary:not(:disabled):hover { + background: var(--accent-dark); + box-shadow: 0 14px 28px rgba(108, 92, 231, 0.29); +} + +.button-arrow { + font-size: 20px; + font-weight: 400; +} + +.button-secondary { + display: flex; + align-items: center; + justify-content: center; + gap: 9px; + color: var(--ink); + background: #deddd6; +} + +.button-secondary:not(:disabled):hover { + background: #d2d0c8; +} + +.spark { + color: var(--accent-dark); + font-size: 15px; +} + +.privacy-note { + margin: -4px 0 0; + color: var(--muted); + font-size: 11px; + line-height: 1.5; +} + +.workspace { + min-width: 0; + padding: clamp(20px, 3vw, 32px); + border: 1px solid rgba(23, 24, 23, 0.08); + border-radius: var(--radius-large); + background: rgba(251, 250, 246, 0.84); + box-shadow: var(--shadow); + backdrop-filter: blur(16px); +} + +.workspace-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + margin-bottom: 22px; +} + +.workspace-kicker { + margin-bottom: 5px; +} + +.workspace h2 { + margin-bottom: 0; + font-size: clamp(24px, 3vw, 34px); + letter-spacing: -0.045em; +} + +.local-badge { + padding: 8px 11px; + border: 1px solid #dad8d0; + border-radius: 999px; + color: var(--muted); + background: rgba(255, 255, 255, 0.58); + font-size: 10px; + font-weight: 760; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.comparison { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; +} + +.photo-frame { + min-width: 0; + margin: 0; +} + +.photo-frame figcaption { + display: flex; + min-height: 28px; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 0 2px; + color: var(--muted); + font-size: 11px; + font-weight: 760; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.result-kind { + overflow: hidden; + max-width: 60%; + color: var(--accent-dark); + font-size: 9px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.image-stage { + position: relative; + display: grid; + min-height: clamp(360px, 54vw, 660px); + overflow: hidden; + place-items: center; + border-radius: 18px; + background: + linear-gradient(45deg, #252826 25%, transparent 25%), + linear-gradient(-45deg, #252826 25%, transparent 25%), + linear-gradient(45deg, transparent 75%, #252826 75%), + linear-gradient(-45deg, transparent 75%, #252826 75%), + #2b2e2c; + background-position: 0 0, 0 8px, 8px -8px, -8px 0; + background-size: 16px 16px; +} + +.image-stage::after { + position: absolute; + inset: 0; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: inherit; + content: ""; + pointer-events: none; +} + +.image-stage img { + display: block; + width: 100%; + height: 100%; + max-height: 660px; + object-fit: contain; +} + +.placeholder { + position: absolute; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + flex-direction: column; + gap: 8px; + padding: 30px; + color: rgba(255, 255, 255, 0.76); + text-align: center; +} + +.placeholder strong { + font-size: 14px; +} + +.placeholder > span:last-child { + color: rgba(255, 255, 255, 0.45); + font-size: 11px; + line-height: 1.5; +} + +.placeholder-frame { + position: relative; + width: 58px; + height: 47px; + margin-bottom: 8px; + border: 1.5px solid rgba(255, 255, 255, 0.27); + border-radius: 9px; +} + +.placeholder-frame::before { + position: absolute; + right: 9px; + bottom: 9px; + left: 9px; + height: 17px; + background: + linear-gradient(140deg, transparent 45%, rgba(255, 255, 255, 0.19) 46% 69%, transparent 70%), + linear-gradient(40deg, transparent 35%, rgba(255, 255, 255, 0.13) 36% 62%, transparent 63%); + content: ""; +} + +.placeholder-frame::after { + position: absolute; + top: 9px; + right: 10px; + width: 7px; + height: 7px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.28); + content: ""; +} + +.placeholder-spark { + display: grid; + width: 52px; + height: 52px; + margin-bottom: 7px; + place-items: center; + border: 1px solid rgba(255, 255, 255, 0.13); + border-radius: 50%; + color: #bcb2ff !important; + background: rgba(108, 92, 231, 0.17); + font-size: 20px !important; +} + +.job-status { + margin-top: 16px; + padding: 14px 16px; + border: 1px solid #dedbd0; + border-radius: 14px; + background: #f2f0e8; +} + +.status-row { + display: flex; + align-items: center; + gap: 10px; + min-height: 19px; + color: var(--muted); + font-size: 12px; + font-weight: 650; +} + +.status-spinner { + width: 14px; + height: 14px; + flex: 0 0 auto; + border: 2px solid rgba(108, 92, 231, 0.2); + border-top-color: var(--accent); + border-radius: 50%; + animation: spin 0.75s linear infinite; +} + +.progress-track { + height: 3px; + overflow: hidden; + margin-top: 12px; + border-radius: 999px; + background: #dbd7ca; +} + +.progress-bar { + display: block; + width: 42%; + height: 100%; + border-radius: inherit; + background: var(--accent); + animation: progress-slide 1.7s ease-in-out infinite; +} + +.job-status[data-kind="success"] { + border-color: rgba(32, 130, 92, 0.22); + background: rgba(32, 130, 92, 0.07); +} + +.job-status[data-kind="success"] .status-row { + color: var(--success); +} + +.job-status[data-kind="success"] .status-spinner { + border: 0; + animation: none; +} + +.job-status[data-kind="success"] .status-spinner::after { + content: "✓"; + font-weight: 800; +} + +.job-status[data-kind="success"] .progress-track { + display: none; +} + +.job-status[data-kind="error"] { + border-color: rgba(184, 67, 67, 0.22); + background: rgba(184, 67, 67, 0.07); +} + +.job-status[data-kind="error"] .status-row { + color: var(--danger); +} + +.job-status[data-kind="error"] .status-spinner { + border: 0; + animation: none; +} + +.job-status[data-kind="error"] .status-spinner::after { + content: "!"; + font-weight: 850; +} + +.job-status[data-kind="error"] .progress-track { + display: none; +} + +.result-actions { + display: flex; + justify-content: flex-end; + min-height: 0; +} + +.download-link { + display: inline-flex; + align-items: center; + gap: 10px; + margin-top: 16px; + padding: 11px 14px; + border-radius: 12px; + color: white; + background: var(--dark); + font-size: 12px; + font-weight: 740; + text-decoration: none; + transition: + transform 150ms ease, + background 150ms ease; +} + +.download-link:hover { + background: #303531; + transform: translateY(-1px); +} + +.download-link:focus-visible { + outline: 3px solid rgba(108, 92, 231, 0.28); + outline-offset: 2px; +} + +.noscript { + margin: 20px; + padding: 16px; + border-radius: 12px; + color: #7a2424; + background: #ffe4e4; + text-align: center; +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +@keyframes health-pulse { + 50% { + opacity: 0.4; + transform: scale(0.82); + } +} + +@keyframes progress-slide { + 0% { + transform: translateX(-115%); + } + + 50% { + transform: translateX(85%); + } + + 100% { + transform: translateX(245%); + } +} + +@media (max-width: 1040px) { + .editor-layout { + grid-template-columns: 1fr; + } + + .control-panel { + display: grid; + grid-template-columns: minmax(260px, 0.75fr) minmax(330px, 1fr); + gap: 36px; + } + + .intro { + margin-bottom: 0; + } + + h1 { + font-size: clamp(42px, 7vw, 68px); + } + + .image-stage { + min-height: min(62vw, 600px); + } +} + +@media (max-width: 720px) { + .topbar { + min-height: 68px; + padding: 14px 18px; + } + + .health-status { + max-width: 58%; + font-size: 11px; + } + + .editor-layout { + gap: 34px; + padding: 34px 16px 40px; + } + + .control-panel { + display: block; + } + + .intro { + margin-bottom: 30px; + } + + h1 { + max-width: 450px; + font-size: clamp(40px, 13vw, 58px); + } + + .actions { + grid-template-columns: 1fr; + } + + .workspace { + padding: 18px 14px; + border-radius: 22px; + } + + .comparison { + grid-template-columns: 1fr; + gap: 18px; + } + + .image-stage { + min-height: min(105vw, 520px); + } + + .field-foot span:first-child { + max-width: 70%; + } +} + +@media (max-width: 460px) { + .brand-name { + display: none; + } + + .health-status { + max-width: calc(100% - 56px); + } + + .drop-zone { + grid-template-columns: auto minmax(0, 1fr); + } + + .choose-chip { + display: none; + } + + .workspace-head { + align-items: flex-start; + } + + .local-badge { + padding: 7px 9px; + } +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + scroll-behavior: auto !important; + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} + +/* -- ------------------------------------------- */ + +.history-section { + margin-top: 30px; +} + +.history-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 14px; + flex-wrap: wrap; + margin-bottom: 12px; +} + +.history-head h2 { + margin: 0; + font-size: 17px; + letter-spacing: -0.01em; +} + +.history-hint { + font-size: 12.5px; + color: var(--muted); +} + +.history-list { + display: flex; + gap: 12px; + overflow-x: auto; + padding: 4px 4px 10px; +} + +.history-item { + display: flex; + flex-direction: column; + gap: 7px; + flex: 0 0 150px; + width: 150px; + padding: 9px; + border: 1.5px solid var(--line); + border-radius: var(--radius-small); + background: var(--panel); + cursor: pointer; + text-align: left; + font: inherit; + transition: border-color 0.15s ease, box-shadow 0.15s ease, transform 0.15s ease; +} + +.history-item:hover { + border-color: var(--accent); + transform: translateY(-1px); +} + +.history-item.is-current { + border-color: var(--accent); + box-shadow: 0 0 0 3px var(--accent-soft); +} + +.history-item img { + width: 100%; + height: 92px; + object-fit: cover; + border-radius: 8px; + background: #ecece6; +} + +.history-item-meta strong { + display: block; + font-size: 12.5px; + line-height: 1.3; + color: var(--ink); + word-break: break-word; +} + +.history-item-meta span { + display: block; + margin-top: 2px; + font-size: 11px; + color: var(--muted); +} + +.history-item-badge { + align-self: flex-start; + font-size: 10px; + font-weight: 600; + letter-spacing: 0.02em; + text-transform: uppercase; + padding: 2px 7px; + border-radius: 999px; + background: var(--accent-soft); + color: var(--accent-dark); +} + +.history-empty { + padding: 10px 2px; + font-size: 13px; + color: var(--muted); +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..25c4b61 --- /dev/null +++ b/server.js @@ -0,0 +1,1572 @@ +"use strict"; + +const crypto = require("crypto"); +const path = require("path"); +const { Readable } = require("stream"); +const { pipeline } = require("stream/promises"); + +const fs = require("fs"); +const { spawn } = require("child_process"); + +const express = require("express"); +const multer = require("multer"); +const convert = require("heic-convert"); + +const COMFY_URL = process.env.COMFY_URL || "http://192.168.31.240:8188"; +const CHECKPOINT = "sdxl_turbo.safetensors"; +const PORT_CANDIDATES = process.env.PORT + ? [Number(process.env.PORT)] + : [3000, 8080, 8090]; + +const POLL_INTERVAL_MS = 1500; +const JOB_TIMEOUT_MS = 125000; +const REQUEST_TIMEOUT_MS = 15000; +const MAX_UPLOAD_BYTES = 25 * 1024 * 1024; + +const UPSCALE_MAX_DIMENSION = 2048; + +const CODEX_JOBS_DIR = path.join(__dirname, ".codex-jobs"); +const CODEX_EDIT_TIMEOUT_MS = 420000; +const CODEX_EXE = resolveCodexExe(); + +const HISTORY_DIR = path.join(__dirname, "history"); +const HISTORY_MANIFEST = path.join(HISTORY_DIR, "history.json"); +const HISTORY_LIMIT = 50; + +const REQUIRED_NODES = [ + "CheckpointLoaderSimple", + "CLIPTextEncode", + "LoadImage", + "ImageScale", + "VAEEncode", + "KSampler", + "VAEDecode", + "SaveImage", + "UpscaleModelLoader", + "ImageUpscaleWithModel" +]; + +const app = express(); + +app.disable("x-powered-by"); +// Статика без длинного кэша: index.html должен всегда получать свежие +// версии app.js/style.css (в HTML они подключены с ?v=...). +app.use(express.static(path.join(__dirname, "public"), { + extensions: ["html"], + maxAge: 0 +})); + +let codexEditInFlight = false; + +class AppError extends Error { + constructor(status, message, details = undefined) { + super(message); + this.name = "AppError"; + this.status = status; + this.details = details; + } +} + +function isHeic(file) { + const mimetype = String(file?.mimetype || "").toLowerCase(); + const extension = path.extname( + String(file?.originalname || "") + ).toLowerCase(); + + return ( + mimetype === "image/heic" || + mimetype === "image/heif" || + extension === ".heic" || + extension === ".heif" + ); +} + +const upload = multer({ + storage: multer.memoryStorage(), + limits: { + fileSize: MAX_UPLOAD_BYTES, + files: 1, + fields: 4 + }, + fileFilter: (_request, file, callback) => { + const supported = new Set([ + "image/jpeg", + "image/jpg", + "image/png", + "image/webp", + "image/heic", + "image/heif" + ]); + + if ( + !supported.has(String(file.mimetype || "").toLowerCase()) && + !isHeic(file) + ) { + callback(new AppError( + 400, + "Поддерживаются фотографии в форматах JPEG, PNG, WebP или HEIC." + )); + return; + } + + callback(null, true); + } +}); + +function asyncRoute(handler) { + return (request, response, next) => { + Promise.resolve(handler(request, response, next)).catch(next); + }; +} + +function delay(milliseconds) { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +} + +function normalizeErrorDetails(value) { + if (value === undefined || value === null) { + return undefined; + } + + try { + return JSON.parse(JSON.stringify(value)); + } catch { + return String(value); + } +} + +async function convertHeicToJpeg(buffer) { + try { + const output = await convert({ + buffer, + format: "JPEG", + quality: 0.92 + }); + + return Buffer.from(output); + } catch (error) { + throw new AppError( + 400, + "Не удалось преобразовать фотографию HEIC/HEIF в JPEG.", + error instanceof Error ? error.message : String(error) + ); + } +} + +function resolveCodexExe() { + const candidates = []; + + if (process.env.CODEX_CLI_PATH) { + candidates.push(process.env.CODEX_CLI_PATH); + } + + try { + const binRoot = path.join( + process.env.LOCALAPPDATA || "", + "OpenAI", + "Codex", + "bin" + ); + + for (const entry of fs.readdirSync(binRoot)) { + const candidate = path.join(binRoot, entry, "codex.exe"); + + if (fs.existsSync(candidate)) { + candidates.push(candidate); + } + } + } catch { + // Папка может отсутствовать — используем fallback. + } + + for (const candidate of candidates) { + if (candidate && fs.existsSync(candidate)) { + return candidate; + } + } + + return "codex"; +} + +function extForMimetype(mimetype) { + const map = { + "image/jpeg": "jpg", + "image/jpg": "jpg", + "image/png": "png", + "image/webp": "webp" + }; + + return map[String(mimetype || "").toLowerCase()] || "jpg"; +} + +function buildCodexPrompt(prompt, dimensions, inputName) { + const size = dimensions && dimensions.width + ? `${dimensions.width}×${dimensions.height}` + : ""; + + return [ + `Перед тобой фотография ${inputName}. Примени к ней следующее редактирование: «${prompt}».`, + "Сохрани отредактированное фото в файл output.jpg в текущей директории.", + "Не перерисовывай фото с нуля и не заменяй его на полностью новое изображение — редактируй исходное фото, сохраняя его сюжет, объекты, лица и пропорции.", + size + ? `Сохрани исходный размер ${size}.` + : "Сохрани исходные пропорции.", + "Файл output.jpg должен быть валидным JPEG. По завершении кратко опиши, что сделал." + ].join(" "); +} + +function runCodexEdit(jobDir, inputName, prompt) { + const lastMessagePath = path.join(jobDir, "last_message.txt"); + const outputPath = path.join(jobDir, "output.jpg"); + + return new Promise((resolve, reject) => { + let child; + + try { + child = spawn( + CODEX_EXE, + [ + "exec", + "-C", jobDir, + "--skip-git-repo-check", + "--ephemeral", + "--dangerously-bypass-approvals-and-sandbox", + "-i", inputName, + "-o", "last_message.txt", + "-" + ], + { + cwd: jobDir, + env: process.env, + stdio: ["pipe", "ignore", "ignore"], + windowsHide: true + } + ); + } catch (error) { + reject(error); + return; + } + + const startedAt = Date.now(); + let exitCode = null; + let processExitedAt = null; + let outputSeenAt = null; + let timedOut = false; + let settled = false; + + const settle = () => { + if (settled) { + return; + } + + settled = true; + clearInterval(deadlineTimer); + + const lastMessage = fs.existsSync(lastMessagePath) + ? fs.readFileSync(lastMessagePath, "utf8").trim().slice(0, 2000) + : ""; + const hasOutput = + fs.existsSync(outputPath) && fs.statSync(outputPath).size > 0; + + resolve({ + exitCode, + timedOut, + outputPath: hasOutput ? outputPath : null, + lastMessage + }); + }; + + const deadlineTimer = setInterval(() => { + if (Date.now() - startedAt > CODEX_EDIT_TIMEOUT_MS) { + timedOut = true; + + try { + child.kill(); + } catch { + // Процесс уже завершён. + } + + settle(); + } + }, 1000); + + child.on("error", (error) => { + if (settled) { + return; + } + + settled = true; + clearInterval(deadlineTimer); + reject(error); + }); + + child.on("exit", (code) => { + exitCode = code; + processExitedAt = Date.now(); + }); + + child.stdin.on("error", () => {}); + child.stdin.end(prompt); + + const poll = () => { + if (settled) { + return; + } + + if (fs.existsSync(outputPath) && fs.statSync(outputPath).size > 0) { + if (outputSeenAt === null) { + outputSeenAt = Date.now(); + } + + // Дожидаемся итогового сообщения Codex, но не дольше 10 секунд. + if ( + !fs.existsSync(lastMessagePath) && + Date.now() - outputSeenAt < 10000 + ) { + setTimeout(poll, 1000); + return; + } + + settle(); + return; + } + + if (Date.now() - startedAt > CODEX_EDIT_TIMEOUT_MS) { + timedOut = true; + + try { + child.kill(); + } catch { + // Процесс уже завершён. + } + + settle(); + return; + } + + if (processExitedAt !== null && Date.now() - processExitedAt > 15000) { + settle(); + return; + } + + setTimeout(poll, 1000); + }; + + poll(); + }); +} + +function contentTypeForExt(ext) { + const map = { + jpg: "image/jpeg", + jpeg: "image/jpeg", + png: "image/png", + webp: "image/webp" + }; + + return map[String(ext || "").toLowerCase()] || "image/jpeg"; +} + +function loadHistory() { + try { + const parsed = JSON.parse(fs.readFileSync(HISTORY_MANIFEST, "utf8")); + + return Array.isArray(parsed) ? parsed : []; + } catch { + return []; + } +} + +function saveHistory(history) { + fs.mkdirSync(HISTORY_DIR, { recursive: true }); + fs.writeFileSync(HISTORY_MANIFEST, JSON.stringify(history, null, 2), "utf8"); +} + +function historyFilePath(version) { + return path.join(HISTORY_DIR, `${version.id}.${version.ext || "jpg"}`); +} + +let historyWriteChain = Promise.resolve(); + +async function appendHistoryVersion(version) { + historyWriteChain = historyWriteChain + .then(() => { + const history = loadHistory(); + history.push(version); + const trimmed = history.slice(-HISTORY_LIMIT); + const keptIds = new Set(trimmed.map((entry) => entry.id)); + + for (const old of history) { + if (!keptIds.has(old.id)) { + try { + fs.rmSync(historyFilePath(old), { force: true }); + } catch { + // Файл мог уже отсутствовать. + } + } + } + + saveHistory(trimmed); + }) + .catch((error) => { + console.error("Ошибка записи истории:", error); + }); + + await historyWriteChain; + return version; +} + +function makeHistoryVersion({ + kind, + label, + prompt, + parentId, + buffer, + ext, + width, + height +}) { + const id = crypto.randomUUID(); + const fileExt = ext || "jpg"; + + fs.mkdirSync(HISTORY_DIR, { recursive: true }); + fs.writeFileSync(path.join(HISTORY_DIR, `${id}.${fileExt}`), buffer); + + return { + id, + kind, + label, + prompt, + parentId: parentId || null, + createdAt: new Date().toISOString(), + url: `/api/history/${id}/image.jpg`, + width: width || null, + height: height || null, + ext: fileExt + }; +} + +async function resolvePhotoInput(request) { + const sourceId = String(request.body?.sourceId || "").trim(); + + if (!sourceId) { + if (!request.file) { + throw new AppError(400, "Выберите фотографию для обработки."); + } + + return null; + } + + const version = loadHistory().find((entry) => entry.id === sourceId); + + if (!version) { + throw new AppError(404, "Исходная версия не найдена в истории."); + } + + const filePath = historyFilePath(version); + + if (!fs.existsSync(filePath)) { + throw new AppError(404, "Файл исходной версии не найден."); + } + + request.file = { + buffer: fs.readFileSync(filePath), + mimetype: contentTypeForExt(version.ext), + originalname: `source-${version.id.slice(0, 8)}.${version.ext || "jpg"}`, + size: fs.statSync(filePath).size + }; + + return version; +} + +async function downloadComfyImage(image) { + const parameters = new URLSearchParams({ + filename: image.filename, + subfolder: image.subfolder || "", + type: image.type || "output" + }); + + const upstream = await comfyRequest( + `/view?${parameters.toString()}`, + {}, + 60000 + ); + + if (!upstream.body) { + throw new AppError(502, "ComfyUI вернул пустое изображение."); + } + + return Buffer.from(await upstream.arrayBuffer()); +} + +async function comfyRequest(route, options = {}, timeoutMs = REQUEST_TIMEOUT_MS) { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + + try { + const response = await fetch(`${COMFY_URL}${route}`, { + ...options, + signal: controller.signal + }); + + if (!response.ok) { + const body = await response.text().catch(() => ""); + throw new AppError( + 502, + `ComfyUI вернул ошибку HTTP ${response.status}.`, + body.slice(0, 2000) || undefined + ); + } + + return response; + } catch (error) { + if (error instanceof AppError) { + throw error; + } + + if (error && error.name === "AbortError") { + throw new AppError( + 504, + "ComfyUI не ответил вовремя. Проверьте сервер обработки и повторите попытку." + ); + } + + throw new AppError( + 503, + "Не удалось подключиться к ComfyUI по адресу 192.168.31.240:8188.", + error instanceof Error ? error.message : String(error) + ); + } finally { + clearTimeout(timer); + } +} + +async function comfyJson(route, options = {}, timeoutMs = REQUEST_TIMEOUT_MS) { + const response = await comfyRequest(route, options, timeoutMs); + + try { + return await response.json(); + } catch { + throw new AppError(502, "ComfyUI вернул некорректный JSON-ответ."); + } +} + +function extractChoiceOptions(specification) { + if (!Array.isArray(specification)) { + return []; + } + + // Старый формат ComfyUI: [["model-a", "model-b"], {...}] + if (Array.isArray(specification[0])) { + return specification[0].filter((item) => typeof item === "string"); + } + + // Новый формат ComfyUI: ["COMBO", { options: ["model-a"] }] + if ( + specification[1] && + typeof specification[1] === "object" && + Array.isArray(specification[1].options) + ) { + return specification[1].options.filter((item) => typeof item === "string"); + } + + if (specification.every((item) => typeof item === "string")) { + return specification; + } + + return []; +} + +function chooseUpscaleModel(models) { + const preferences = [ + /4x[-_ ]?ultrasharp/i, + /realesrgan.*x4plus/i, + /4x.*plus/i, + /4x/i + ]; + + for (const pattern of preferences) { + const match = models.find((model) => pattern.test(model)); + if (match) { + return match; + } + } + + return models[0] || null; +} + +let runtimeCache = null; +let runtimeCacheExpiresAt = 0; + +async function getRuntimeInfo(forceRefresh = false) { + if ( + !forceRefresh && + runtimeCache && + Date.now() < runtimeCacheExpiresAt + ) { + return runtimeCache; + } + + const objectInfo = await comfyJson("/object_info"); + + const nodes = Object.fromEntries( + REQUIRED_NODES.map((nodeName) => [ + nodeName, + Boolean(objectInfo[nodeName]) + ]) + ); + + const upscaleSpec = + objectInfo.UpscaleModelLoader?.input?.required?.model_name; + const checkpointSpec = + objectInfo.CheckpointLoaderSimple?.input?.required?.ckpt_name; + + const upscaleModels = extractChoiceOptions(upscaleSpec); + const checkpoints = extractChoiceOptions(checkpointSpec); + + runtimeCache = { + nodes, + upscaleModels, + selectedUpscaleModel: chooseUpscaleModel(upscaleModels), + checkpoints, + checkpointAvailable: checkpoints.includes(CHECKPOINT) + }; + + runtimeCacheExpiresAt = Date.now() + 30000; + return runtimeCache; +} + +function requireNodes(runtime, nodeNames) { + const missing = nodeNames.filter((nodeName) => !runtime.nodes[nodeName]); + + if (missing.length > 0) { + throw new AppError( + 503, + `На сервере ComfyUI отсутствуют необходимые узлы: ${missing.join(", ")}.` + ); + } +} + +function readUInt24LE(buffer, offset) { + return ( + buffer[offset] | + (buffer[offset + 1] << 8) | + (buffer[offset + 2] << 16) + ); +} + +function getPngDimensions(buffer) { + const pngSignature = "89504e470d0a1a0a"; + + if ( + buffer.length >= 24 && + buffer.subarray(0, 8).toString("hex") === pngSignature + ) { + return { + width: buffer.readUInt32BE(16), + height: buffer.readUInt32BE(20) + }; + } + + return null; +} + +function getJpegDimensions(buffer) { + if ( + buffer.length < 4 || + buffer[0] !== 0xff || + buffer[1] !== 0xd8 + ) { + return null; + } + + const startOfFrameMarkers = new Set([ + 0xc0, 0xc1, 0xc2, 0xc3, + 0xc5, 0xc6, 0xc7, + 0xc9, 0xca, 0xcb, + 0xcd, 0xce, 0xcf + ]); + + let offset = 2; + + while (offset + 9 < buffer.length) { + if (buffer[offset] !== 0xff) { + offset += 1; + continue; + } + + while (offset < buffer.length && buffer[offset] === 0xff) { + offset += 1; + } + + if (offset >= buffer.length) { + break; + } + + const marker = buffer[offset]; + offset += 1; + + if (marker === 0xd8 || marker === 0x01) { + continue; + } + + if (marker === 0xd9 || marker === 0xda) { + break; + } + + if (offset + 1 >= buffer.length) { + break; + } + + const segmentLength = buffer.readUInt16BE(offset); + + if (segmentLength < 2 || offset + segmentLength > buffer.length) { + break; + } + + if (startOfFrameMarkers.has(marker) && segmentLength >= 7) { + return { + height: buffer.readUInt16BE(offset + 3), + width: buffer.readUInt16BE(offset + 5) + }; + } + + offset += segmentLength; + } + + return null; +} + +function getWebpDimensions(buffer) { + if ( + buffer.length < 30 || + buffer.toString("ascii", 0, 4) !== "RIFF" || + buffer.toString("ascii", 8, 12) !== "WEBP" + ) { + return null; + } + + const chunkType = buffer.toString("ascii", 12, 16); + + if (chunkType === "VP8X") { + return { + width: readUInt24LE(buffer, 24) + 1, + height: readUInt24LE(buffer, 27) + 1 + }; + } + + if ( + chunkType === "VP8 " && + buffer.length >= 30 && + buffer[23] === 0x9d && + buffer[24] === 0x01 && + buffer[25] === 0x2a + ) { + return { + width: buffer.readUInt16LE(26) & 0x3fff, + height: buffer.readUInt16LE(28) & 0x3fff + }; + } + + if (chunkType === "VP8L" && buffer.length >= 25 && buffer[20] === 0x2f) { + const byte0 = buffer[21]; + const byte1 = buffer[22]; + const byte2 = buffer[23]; + const byte3 = buffer[24]; + + return { + width: 1 + byte0 + ((byte1 & 0x3f) << 8), + height: 1 + ((byte1 & 0xc0) >> 6) + (byte2 << 2) + ((byte3 & 0x0f) << 10) + }; + } + + return null; +} + +function getImageDimensions(buffer) { + const dimensions = + getPngDimensions(buffer) || + getJpegDimensions(buffer) || + getWebpDimensions(buffer); + + if ( + !dimensions || + !Number.isInteger(dimensions.width) || + !Number.isInteger(dimensions.height) || + dimensions.width <= 0 || + dimensions.height <= 0 + ) { + return null; + } + + return dimensions; +} + +function scaleForLimit(dimensions, maximumDimension) { + const largestDimension = Math.max( + dimensions.width, + dimensions.height + ); + + if (largestDimension <= maximumDimension) { + return null; + } + + const ratio = maximumDimension / largestDimension; + const width = Math.max( + 8, + Math.floor((dimensions.width * ratio) / 8) * 8 + ); + const height = Math.max( + 8, + Math.floor((dimensions.height * ratio) / 8) * 8 + ); + + return { width, height }; +} + +function safeUploadFilename(file) { + const extensionByMime = { + "image/jpeg": ".jpg", + "image/jpg": ".jpg", + "image/png": ".png", + "image/webp": ".webp" + }; + + const extension = + extensionByMime[file.mimetype.toLowerCase()] || + path.extname(file.originalname).toLowerCase() || + ".png"; + + const originalStem = path.parse(file.originalname).name; + const cleanStem = originalStem + .normalize("NFKC") + .replace(/[^\p{L}\p{N}._-]+/gu, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 60) || "photo"; + + return [ + "prompt-editor", + Date.now(), + crypto.randomBytes(4).toString("hex"), + cleanStem + ].join("-") + extension; +} + +async function uploadToComfy(file) { + const form = new FormData(); + + form.append( + "image", + new Blob([file.buffer], { type: file.mimetype }), + safeUploadFilename(file) + ); + form.append("type", "input"); + form.append("overwrite", "true"); + + const uploaded = await comfyJson("/upload/image", { + method: "POST", + body: form + }, 30000); + + if (!uploaded || typeof uploaded.name !== "string") { + throw new AppError( + 502, + "ComfyUI не подтвердил загрузку исходной фотографии.", + uploaded + ); + } + + const subfolder = + typeof uploaded.subfolder === "string" + ? uploaded.subfolder.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "") + : ""; + + return { + name: uploaded.name, + subfolder, + type: uploaded.type || "input", + loadImageName: subfolder + ? `${subfolder}/${uploaded.name}` + : uploaded.name + }; +} + +function makeSeed() { + return crypto.randomBytes(6).readUIntBE(0, 6); +} + +function imageScaleNode(imageSource, size) { + return { + class_type: "ImageScale", + inputs: { + image: imageSource, + upscale_method: "lanczos", + width: size.width, + height: size.height, + crop: "disabled" + } + }; +} + +function buildUpscaleWorkflow(uploaded, modelName, scaledSize) { + const imageSource = scaledSize ? ["2", 0] : ["1", 0]; + + const workflow = { + "1": { + class_type: "LoadImage", + inputs: { + image: uploaded.loadImageName + } + }, + "3": { + class_type: "UpscaleModelLoader", + inputs: { + model_name: modelName + } + }, + "4": { + class_type: "ImageUpscaleWithModel", + inputs: { + upscale_model: ["3", 0], + image: imageSource + } + }, + "5": { + class_type: "SaveImage", + inputs: { + images: ["4", 0], + filename_prefix: "prompt_editor/upscale" + } + } + }; + + if (scaledSize) { + workflow["2"] = imageScaleNode(["1", 0], scaledSize); + } + + return { + workflow, + saveNodeId: "5" + }; +} + +async function submitWorkflow(workflow) { + const response = await comfyJson("/prompt", { + method: "POST", + headers: { + "content-type": "application/json" + }, + body: JSON.stringify({ + prompt: workflow, + client_id: crypto.randomUUID() + }) + }, 30000); + + const nodeErrors = response?.node_errors; + + if ( + nodeErrors && + typeof nodeErrors === "object" && + Object.keys(nodeErrors).length > 0 + ) { + throw new AppError( + 422, + "ComfyUI отклонил схему обработки. Проверьте установленные модели и узлы.", + nodeErrors + ); + } + + if (!response || typeof response.prompt_id !== "string") { + throw new AppError( + 502, + "ComfyUI не вернул идентификатор задачи.", + response + ); + } + + return response.prompt_id; +} + +function executionErrorFromHistory(record) { + const messages = record?.status?.messages; + + if (!Array.isArray(messages)) { + return null; + } + + for (const message of messages) { + if (!Array.isArray(message) || message[0] !== "execution_error") { + continue; + } + + const payload = message[1]; + + if (payload?.exception_message) { + return payload.exception_message; + } + + return "Внутренняя ошибка выполнения workflow."; + } + + return null; +} + +async function waitForResult(promptId, saveNodeId) { + const startedAt = Date.now(); + + while (Date.now() - startedAt < JOB_TIMEOUT_MS) { + const history = await comfyJson( + `/history/${encodeURIComponent(promptId)}` + ); + + const record = history?.[promptId] || null; + const output = record?.outputs?.[saveNodeId]; + const image = output?.images?.[0]; + + if (image && typeof image.filename === "string") { + return { + filename: image.filename, + subfolder: + typeof image.subfolder === "string" ? image.subfolder : "", + type: image.type || "output" + }; + } + + const executionError = executionErrorFromHistory(record); + + if (executionError) { + throw new AppError( + 502, + `ComfyUI не смог обработать изображение: ${executionError}` + ); + } + + if (record?.status?.completed) { + throw new AppError( + 502, + "ComfyUI завершил задачу, но не создал итоговое изображение.", + record.status.messages + ); + } + + await delay(POLL_INTERVAL_MS); + } + + throw new AppError( + 504, + "Обработка заняла больше двух минут и была остановлена по тайм-ауту." + ); +} + +function makePublicResult(image) { + const parameters = new URLSearchParams({ + filename: image.filename, + subfolder: image.subfolder || "", + type: image.type || "output" + }); + + return { + ...image, + url: `/api/result?${parameters.toString()}` + }; +} + +async function requirePhoto(request) { + if (!request.file) { + throw new AppError(400, "Выберите фотографию для обработки."); + } + + let dimensions; + + if (isHeic(request.file)) { + const buffer = await convertHeicToJpeg(request.file.buffer); + const originalStem = + path.parse(String(request.file.originalname || "")).name || "photo"; + + dimensions = getJpegDimensions(buffer); + + request.file = { + ...request.file, + buffer, + size: buffer.length, + mimetype: "image/jpeg", + originalname: `${originalStem}.jpg` + }; + } else { + dimensions = getImageDimensions(request.file.buffer); + } + + if ( + !dimensions || + !Number.isInteger(dimensions.width) || + !Number.isInteger(dimensions.height) || + dimensions.width <= 0 || + dimensions.height <= 0 + ) { + throw new AppError( + 400, + "Не удалось определить размеры фотографии. Используйте корректный JPEG, PNG, WebP или HEIC." + ); + } + + return dimensions; +} + +app.get("/api/health", asyncRoute(async (_request, response) => { + try { + const runtime = await getRuntimeInfo(true); + const missingNodes = REQUIRED_NODES.filter( + (nodeName) => !runtime.nodes[nodeName] + ); + + const ready = + missingNodes.length === 0 && + runtime.checkpointAvailable && + Boolean(runtime.selectedUpscaleModel); + + response.json({ + ok: ready, + comfyAvailable: true, + message: ready + ? "Сервер обработки: доступен" + : "Сервер доступен, но настроен не полностью", + selectedUpscaleModel: runtime.selectedUpscaleModel, + upscaleModels: runtime.upscaleModels, + checkpoint: CHECKPOINT, + checkpointAvailable: runtime.checkpointAvailable, + nodes: runtime.nodes, + missingNodes + }); + } catch (error) { + response.status(200).json({ + ok: false, + comfyAvailable: false, + message: error instanceof Error + ? error.message + : "Сервер обработки недоступен", + selectedUpscaleModel: null, + upscaleModels: [], + checkpoint: CHECKPOINT, + checkpointAvailable: false, + nodes: Object.fromEntries( + REQUIRED_NODES.map((nodeName) => [nodeName, false]) + ) + }); + } +})); + +app.post( + "/api/preview", + upload.single("photo"), + asyncRoute(async (request, response) => { + if (!request.file) { + throw new AppError(400, "Выберите фотографию для предпросмотра."); + } + + let buffer = request.file.buffer; + let contentType = request.file.mimetype; + + if (isHeic(request.file)) { + buffer = await convertHeicToJpeg(request.file.buffer); + contentType = "image/jpeg"; + } + + response.status(200); + response.setHeader("content-type", contentType); + response.setHeader("cache-control", "no-store"); + response.send(buffer); + }) +); + +app.get("/api/history", asyncRoute(async (_request, response) => { + response.json({ ok: true, versions: loadHistory() }); +})); + +app.post( + "/api/history/import", + upload.single("photo"), + asyncRoute(async (request, response) => { + if (!request.file) { + throw new AppError(400, "Выберите фотографию."); + } + + let buffer = request.file.buffer; + let ext = extForMimetype(request.file.mimetype); + + if (isHeic(request.file)) { + buffer = await convertHeicToJpeg(buffer); + ext = "jpg"; + } + + const dimensions = ext === "jpg" + ? getJpegDimensions(buffer) + : getImageDimensions(buffer); + + const version = makeHistoryVersion({ + kind: "original", + label: "Исходник", + prompt: null, + parentId: null, + buffer, + ext, + width: dimensions?.width, + height: dimensions?.height + }); + + await appendHistoryVersion(version); + + response.json({ ok: true, version }); + }) +); + +app.get( + "/api/history/:id/image.jpg", + asyncRoute(async (request, response) => { + const { id } = request.params; + + if (!JOB_ID_PATTERN.test(id)) { + throw new AppError(400, "Некорректный идентификатор версии."); + } + + const version = loadHistory().find((entry) => entry.id === id); + + if (!version) { + throw new AppError(404, "Версия не найдена в истории."); + } + + const filePath = historyFilePath(version); + + if (!fs.existsSync(filePath)) { + throw new AppError(404, "Файл версии не найден."); + } + + response.status(200); + response.setHeader("content-type", contentTypeForExt(version.ext)); + response.setHeader("cache-control", "no-store"); + response.setHeader( + "content-disposition", + `inline; filename*=UTF-8''${encodeURIComponent(`version-${id.slice(0, 8)}.${version.ext || "jpg"}`)}` + ); + + fs.createReadStream(filePath).pipe(response); + }) +); + +app.post( + "/api/edit", + upload.single("photo"), + asyncRoute(async (request, response) => { + const sourceVersion = await resolvePhotoInput(request); + const dimensions = await requirePhoto(request); + const prompt = String(request.body?.prompt || "").trim(); + + if (!prompt) { + throw new AppError(400, "Введите промпт для редактирования фотографии."); + } + + if (prompt.length > 1000) { + throw new AppError(400, "Промпт не должен превышать 1000 символов."); + } + + if (codexEditInFlight) { + throw new AppError( + 429, + "Редактирование уже выполняется. Дождитесь завершения текущего задания." + ); + } + + codexEditInFlight = true; + + try { + const jobId = crypto.randomUUID(); + const jobDir = path.join(CODEX_JOBS_DIR, jobId); + + fs.mkdirSync(jobDir, { recursive: true }); + + const inputName = `input.${extForMimetype(request.file.mimetype)}`; + fs.writeFileSync(path.join(jobDir, inputName), request.file.buffer); + + const promptText = buildCodexPrompt(prompt, dimensions, inputName); + const result = await runCodexEdit(jobDir, inputName, promptText); + + if (!result.outputPath) { + const details = result.lastMessage + ? `Ответ Codex: ${result.lastMessage.slice(0, 500)}` + : undefined; + + throw new AppError( + 504, + "Codex не завершил редактирование. Попробуйте ещё раз или упростите промпт.", + details + ); + } + + const version = makeHistoryVersion({ + kind: "edit", + label: `Редактирование: «${prompt.slice(0, 60)}${prompt.length > 60 ? "…" : ""}»`, + prompt, + parentId: sourceVersion?.id || null, + buffer: fs.readFileSync(result.outputPath), + ext: "jpg", + width: dimensions?.width, + height: dimensions?.height + }); + + await appendHistoryVersion(version); + + response.json({ + ok: true, + job: { + type: "edit", + engine: "codex", + exitCode: result.exitCode, + timedOut: result.timedOut + }, + result: { + filename: "edited-photo.jpg", + url: version.url + }, + input: dimensions, + summary: result.lastMessage, + version + }); + } finally { + codexEditInFlight = false; + } + }) +); + +app.post( + "/api/upscale", + upload.single("photo"), + asyncRoute(async (request, response) => { + const sourceVersion = await resolvePhotoInput(request); + const dimensions = await requirePhoto(request); + const scaledSize = scaleForLimit( + dimensions, + UPSCALE_MAX_DIMENSION + ); + + const runtime = await getRuntimeInfo(); + + requireNodes(runtime, [ + "LoadImage", + "UpscaleModelLoader", + "ImageUpscaleWithModel", + "SaveImage", + ...(scaledSize ? ["ImageScale"] : []) + ]); + + if (!runtime.selectedUpscaleModel) { + throw new AppError( + 503, + "На сервере ComfyUI не установлена модель увеличения разрешения." + ); + } + + const uploaded = await uploadToComfy(request.file); + const built = buildUpscaleWorkflow( + uploaded, + runtime.selectedUpscaleModel, + scaledSize + ); + + const promptId = await submitWorkflow(built.workflow); + const image = await waitForResult(promptId, built.saveNodeId); + const imageBuffer = await downloadComfyImage(image); + + const resultExt = String(image.filename || "") + .toLowerCase() + .endsWith(".png") + ? "png" + : "jpg"; + + const version = makeHistoryVersion({ + kind: "upscale", + label: "4× upscale", + prompt: null, + parentId: sourceVersion?.id || null, + buffer: imageBuffer, + ext: resultExt, + width: null, + height: null + }); + + await appendHistoryVersion(version); + + response.json({ + ok: true, + job: { + type: "upscale", + promptId, + model: runtime.selectedUpscaleModel + }, + result: { + filename: "upscaled-photo.png", + url: version.url + }, + input: dimensions, + processingInput: scaledSize || dimensions, + version + }); + }) +); + +app.get("/api/result", asyncRoute(async (request, response) => { + const filename = String(request.query.filename || ""); + const subfolder = String(request.query.subfolder || ""); + const type = String(request.query.type || "output"); + + if (!filename) { + throw new AppError(400, "Не указано имя итогового изображения."); + } + + if (type !== "output") { + throw new AppError(400, "Разрешена загрузка только итоговых изображений."); + } + + const parameters = new URLSearchParams({ + filename, + subfolder, + type: "output" + }); + + const upstream = await comfyRequest( + `/view?${parameters.toString()}`, + {}, + 30000 + ); + + response.status(200); + response.setHeader( + "content-type", + upstream.headers.get("content-type") || "image/png" + ); + response.setHeader("cache-control", "no-store"); + response.setHeader( + "content-disposition", + `inline; filename*=UTF-8''${encodeURIComponent(path.basename(filename))}` + ); + + if (!upstream.body) { + throw new AppError(502, "ComfyUI вернул пустое изображение."); + } + + await pipeline(Readable.fromWeb(upstream.body), response); +})); + +const JOB_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +app.get("/api/jobs/:id/output.jpg", asyncRoute(async (request, response) => { + const { id } = request.params; + + if (!JOB_ID_PATTERN.test(id)) { + throw new AppError(400, "Некорректный идентификатор задания."); + } + + const filePath = path.join(CODEX_JOBS_DIR, id, "output.jpg"); + + if (!fs.existsSync(filePath)) { + throw new AppError(404, "Результат редактирования не найден."); + } + + response.status(200); + response.setHeader("content-type", "image/jpeg"); + response.setHeader("cache-control", "no-store"); + response.setHeader( + "content-disposition", + `inline; filename*=UTF-8''${encodeURIComponent("edited-photo.jpg")}` + ); + + fs.createReadStream(filePath).pipe(response); +})); + +app.use("/api", (_request, response) => { + response.status(404).json({ + ok: false, + error: "API-метод не найден." + }); +}); + +app.use((error, _request, response, next) => { + if (response.headersSent) { + next(error); + return; + } + + let status = error instanceof AppError ? error.status : 500; + let message = error instanceof Error + ? error.message + : "Неизвестная ошибка сервера."; + + if (error instanceof multer.MulterError) { + status = 400; + + if (error.code === "LIMIT_FILE_SIZE") { + message = "Файл слишком большой. Максимальный размер — 25 МБ."; + } else { + message = `Ошибка загрузки файла: ${error.message}`; + } + } + + if (!(error instanceof AppError) && !(error instanceof multer.MulterError)) { + console.error(error); + message = "Внутренняя ошибка сервера."; + } + + response.status(status).json({ + ok: false, + error: message, + details: normalizeErrorDetails(error.details) + }); +}); + +function listenOnPort(port) { + return new Promise((resolve, reject) => { + const server = app.listen(port, "0.0.0.0"); + + const onError = (error) => { + reject(error); + }; + + server.once("error", onError); + server.once("listening", () => { + server.off("error", onError); + resolve(server); + }); + }); +} + +async function startServer() { + fs.rmSync(CODEX_JOBS_DIR, { recursive: true, force: true }); + fs.mkdirSync(CODEX_JOBS_DIR, { recursive: true }); + fs.mkdirSync(HISTORY_DIR, { recursive: true }); + + for (const port of PORT_CANDIDATES) { + try { + await listenOnPort(port); + + console.log(`Фоторедактор запущен: http://localhost:${port}`); + console.log(`Доступ в локальной сети: http://0.0.0.0:${port}`); + console.log(`ComfyUI: ${COMFY_URL}`); + return; + } catch (error) { + if (error && error.code === "EADDRINUSE") { + console.warn(`Порт ${port} занят, пробую следующий.`); + continue; + } + + throw error; + } + } + + throw new Error( + `Не удалось запустить сервер: порты ${PORT_CANDIDATES.join(", ")} заняты.` + ); +} + +startServer().catch((error) => { + console.error("Ошибка запуска:", error); + process.exitCode = 1; +});