diff --git a/docs/html-reporter/static-accepter.mdx b/docs/html-reporter/static-accepter.mdx index 824fc0e7..864bc035 100644 --- a/docs/html-reporter/static-accepter.mdx +++ b/docs/html-reporter/static-accepter.mdx @@ -19,9 +19,9 @@ A typical flow may look as follows: 1. A CI job finishes running tests, generates the html-reporter bundle, and uploads the static report somewhere reviewers can reach it. 2. A reviewer opens that static report, stages the screenshots that should become the new baselines, and presses **Commit**. -3. html-reporter packages the staged screenshots together with repository metadata and sends them to a service that you operate. That service runs persistently (for example on your infrastructure or as a cloud function) and is responsible for updating the pull request with the new baselines. +3. html-reporter sends the staged screenshots through the configured accepter: either the legacy HTTP service that you operate, or a runtime ESM module such as Static Accepter v2. -The static accepter is disabled in GUI mode. To expose it in the static bundle you must configure repository, pull request, and service URLs as shown below. +The static accepter is disabled in GUI mode. To expose it in the static bundle you must configure repository and pull request URLs plus either the legacy service or a v2 module, as shown below. ## Configuration prerequisites @@ -49,11 +49,43 @@ plugins: { } ``` -- The accepter is ignored unless the `enabled` flag is set and the report is opened in static mode. `repositoryUrl`, `pullRequestUrl`, and `serviceUrl` are mandatory; missing values disable the feature inside the bundle. +- The accepter is ignored unless the `enabled` flag is set and the report is opened in static mode. `repositoryUrl` and `pullRequestUrl` are always mandatory. Configure `serviceUrl` for the legacy HTTP flow or `moduleUrl` for Static Accepter v2; when `moduleUrl` is present, it takes precedence and `serviceUrl` is not required. - Images collected for committing always reference the stored baseline path. The accepter throws if the underlying tool cannot provide a `refImg.relativePath`, because the service needs the final repository-relative destination for each file. - `axiosRequestOptions` (optional) are forwarded to the HTTP client used by the report UI so you can tweak timeouts, headers, or authentication parameters required by your service. -## High-level workflow +## Static Accepter v2 + +Static Accepter v2 delegates downloading, batching, authenticated commit creation, and final Submit/Suggest confirmation to a runtime ESM module. To enable the production client, set `moduleUrl` in the existing configuration block: + +```js +plugins: { + 'html-reporter/testplane': { + enabled: true, + staticImageAccepter: { + enabled: true, + repositoryUrl: 'https://github.com/org/project', + pullRequestUrl: 'https://github.com/org/project/pull/42', + moduleUrl: 'https://my-static-accepter-service.com/v2/script.js', + } + } +} +``` + +The module is imported by the report page at runtime and is not included in the html-reporter bundle. Opening the commit dialog starts the import; the final **Commit** button remains disabled until it succeeds. The final click calls the module synchronously so the browser preserves user activation for the static accepter v2 popup. + +The popup owns confirmation and all static accepter API requests. html-reporter does not embed an iframe, open the popup itself, send protocol messages, split commits, or call static accepter `/_api/v2/*` endpoints. While the operation is pending, the report shows download/commit/confirmation/submit progress and keeps the staged set unchanged. `submitted` and `suggested` results mark the staged images as committed; cancellation or an error leaves them staged for retry. + +Before publishing a report with v2, verify the following browser integration requirements: + +- The exact report origin is allowed by static accepter. +- The report CSP permits the `moduleUrl` origin in `script-src` and permits screenshot origins in `connect-src`. +- Screenshot origins return CORS headers that allow the report origin. +- The report does not use `Cross-Origin-Opener-Policy: same-origin`, because static accepter requires `window.opener` for its popup protocol. +- Reviewers are authenticated in static accepter, have access to the pull request, and allow popups for the report origin. + +If `moduleUrl` is omitted, html-reporter preserves the legacy HTTP behavior described below. + +## Legacy HTTP workflow 1. Reviewers browse the static report, stage the screenshots they want to promote, and open the **Commit** dialog. 2. html-reporter gathers the staged entries, fetches the binary data for each actual image, and builds a `multipart/form-data` payload that includes repository metadata, the chosen commit message, and every image file. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/static-accepter.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/static-accepter.mdx index 3d21e8a8..7d01c169 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/static-accepter.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/html-reporter/static-accepter.mdx @@ -19,9 +19,9 @@ import Admonition from "@theme/Admonition"; 1. CI-прогон завершает тесты, генерирует сборку html-reporter и выкладывает статический отчёт в доступное ревьюерам место. 2. Ревьюер открывает этот отчёт, помечает скриншоты, которые должны стать новыми эталонами, и нажимает **Commit**. -3. html-reporter упаковывает выбранные скриншоты вместе с метаданными репозитория и отправляет их на принадлежащий вам сервис. Этот сервис работает постоянно (например, в вашем кластере или как облачная функция) и обновляет pull request новыми эталонами. +3. html-reporter отправляет выбранные скриншоты через настроенный accepter: либо через принадлежащий вам legacy HTTP-сервис, либо через загружаемый во время выполнения ESM-модуль, например Static Accepter v2. -В режиме GUI эта функция выключена, потому что локальный интерфейс уже умеет принимать скриншоты напрямую. Чтобы элементы UI принятия скриншотов появились в статическом отчёте, необходимо задать URL репозитория, pull request'а и сервиса, как показано ниже. +В режиме GUI эта функция выключена, потому что локальный интерфейс уже умеет принимать скриншоты напрямую. Чтобы элементы UI принятия скриншотов появились в статическом отчёте, необходимо задать URL репозитория и pull request'а, а также legacy-сервиса или модуля v2, как показано ниже. ## Предварительная настройка @@ -49,11 +49,43 @@ plugins: { } ``` -- Элементы для принятия скриншотов в статическом отчёте не появятся, если не задан `enabled` или отчёт открыт не в статическом режиме. `repositoryUrl`, `pullRequestUrl` и `serviceUrl` обязательны; без них кнопка «Accept» недоступна. +- Элементы для принятия скриншотов в статическом отчёте не появятся, если не задан `enabled` или отчёт открыт не в статическом режиме. `repositoryUrl` и `pullRequestUrl` обязательны всегда. Для legacy HTTP-сценария настройте `serviceUrl`, а для Static Accepter v2 — `moduleUrl`. Если задан `moduleUrl`, он имеет приоритет, а `serviceUrl` не требуется. - Сохраняемые изображения всегда ссылаются на путь эталона. html-reporter выбросит ошибку, если инструмент не предоставляет `refImg.relativePath`, потому что сервису нужен конечный относительный путь для каждого файла. - Параметр `axiosRequestOptions` (необязательный) прокидывается в HTTP-клиент интерфейса отчёта — так можно настроить таймауты, заголовки или авторизацию, требуемые вашим сервисом. -## Общая схема работы +## Static Accepter v2 + +Static Accepter v2 делегирует загружаемому во время выполнения ESM-модулю скачивание изображений, пакетную обработку, аутентификацию, создание коммита и финальное подтверждение Submit/Suggest. Чтобы включить клиент для production-окружения, задайте `moduleUrl` в существующем блоке конфигурации: + +```js +plugins: { + 'html-reporter/testplane': { + enabled: true, + staticImageAccepter: { + enabled: true, + repositoryUrl: 'https://github.com/org/project', + pullRequestUrl: 'https://github.com/org/project/pull/42', + moduleUrl: 'https://my-static-accepter-service.com/v2/script.js', + } + } +} +``` + +Страница отчёта импортирует модуль во время выполнения, он не включается в сборку html-reporter. Импорт начинается при открытии диалога коммита, а финальная кнопка **Commit** остаётся выключенной, пока импорт не завершится успешно. По финальному клику модуль вызывается синхронно, чтобы браузер сохранил пользовательскую активацию (user activation), необходимую для всплывающего окна Static Accepter v2. + +Всплывающее окно отвечает за подтверждение и все запросы к API Static Accepter. html-reporter не встраивает iframe, не открывает всплывающее окно самостоятельно, не отправляет протокольные сообщения, не разбивает коммиты и не вызывает эндпоинты Static Accepter `/_api/v2/*`. Пока операция выполняется, отчёт показывает прогресс скачивания, создания коммита, подтверждения и отправки, а набор выбранных изображений остаётся неизменным. Результаты `submitted` и `suggested` помечают выбранные изображения как принятые; отмена или ошибка оставляет их выбранными для повторной попытки. + +Перед публикацией отчёта с v2 проверьте следующие требования к интеграции с браузером: + +- В Static Accepter разрешён точный источник (origin) отчёта. +- CSP отчёта разрешает источник `moduleUrl` в `script-src`, а источники скриншотов — в `connect-src`. +- Серверы скриншотов возвращают CORS-заголовки, разрешающие origin отчёта. +- Для отчёта не задан `Cross-Origin-Opener-Policy: same-origin`, потому что протокол всплывающего окна Static Accepter использует `window.opener`. +- Ревьюеры аутентифицированы в Static Accepter, имеют доступ к pull request'у и разрешили всплывающие окна для origin отчёта. + +Если `moduleUrl` не задан, html-reporter сохраняет описанное ниже legacy HTTP-поведение. + +## Legacy HTTP-сценарий 1. Ревьюер просматривает статический отчёт, отмечает скриншоты и открывает диалог **Commit**. 2. html-reporter собирает выбранные элементы, загружает бинарные данные каждого «actual»-скриншота и формирует `multipart/form-data`, содержащий метаданные репозитория, сообщение коммита и файлы изображений.