@ngx-rock/yandex-smart-captcha 17.0.0 → 17.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +232 -4
  3. package/README_RU.md +235 -0
  4. package/package.json +1 -1
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ngx-rock
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,7 +1,235 @@
1
- # @ngx-rock/yandex-smart-captcha
1
+ # Angular Yandex Smart Captcha
2
2
 
3
- This library was generated with [Nx](https://nx.dev).
3
+ [![npm version](https://badge.fury.io/js/@ngx-rock%2Fyandex-smart-captcha.svg)](https://badge.fury.io/js/@ngx-rock%2Fyandex-smart-captcha) [![GitHub license](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/ngx-rock/memoize-pipe/blob/main/LICENSE)
4
4
 
5
- ## Running unit tests
5
+ An Angular library for integrating Yandex SmartCaptcha into your applications. This package provides Angular components that wrap the Yandex SmartCaptcha JavaScript library, supporting both standard and invisible captchas.
6
+ It leverages Angular’s reactive forms (via `ControlValueAccessor` and `Validator`) and modern features like signals and effects (with `zoneless` support).
6
7
 
7
- Run `nx test @ngx-rock/yandex-smart-captcha` to execute the unit tests.
8
+ > **Note:** This documentation mirrors the concepts from the [Yandex SmartCaptcha React documentation](https://yandex.cloud/en-ru/docs/smartcaptcha/concepts/react?utm_referrer=about%3Ablank) while adapting them to Angular.
9
+
10
+ ## Installation
11
+
12
+ Install the package via npm:
13
+
14
+ ```bash
15
+ npm install @ngx-rock/yandex-smart-captcha
16
+ ```
17
+
18
+ ## Components
19
+
20
+ This library provides two main standalone components:
21
+
22
+ - **SmartCaptchaComponent**: The standard Yandex SmartCaptcha component.
23
+ - **InvisibleSmartCaptchaComponent**: An extension of `SmartCaptchaComponent` configured for invisible captcha behavior.
24
+
25
+ Both components implement Angular’s `ControlValueAccessor` and `Validator`, making them easily integrated into reactive forms.
26
+
27
+ ---
28
+
29
+ ## Usage
30
+
31
+ ### Importing the Component
32
+
33
+ Since the components are standalone, you can directly import them into your Angular module or component:
34
+
35
+ ```typescript
36
+ import { SmartCaptchaComponent } from '@ngx-rock/yandex-smart-captcha';
37
+ // or for invisible captcha
38
+ import { InvisibleSmartCaptchaComponent } from '@ngx-rock/yandex-smart-captcha';
39
+ ```
40
+
41
+ ### Template Example (Standard Captcha)
42
+
43
+ ```html
44
+ <form [formGroup]="form">
45
+ <smart-captcha
46
+ formControlName="captcha"
47
+ [sitekey]="'YOUR_SITE_KEY'"
48
+ [theme]="'light'"
49
+ [language]="'en'"
50
+ (challengeVisible)="onChallengeVisible()"
51
+ (challengeHidden)="onChallengeHidden()"
52
+ (success)="onSuccess($event)"
53
+ (networkError)="onNetworkError()"
54
+ (tokenExpired)="onTokenExpired()"
55
+ (javascriptError)="onJavascriptError($event)"
56
+ ></smart-captcha>
57
+
58
+ <button type="submit" [disabled]="form.invalid">Submit</button>
59
+ </form>
60
+ ```
61
+
62
+ ### Template Example (Invisible Captcha)
63
+
64
+ ```html
65
+ <form [formGroup]="form">
66
+ <invisible-smart-captcha
67
+ formControlName="captcha"
68
+ [sitekey]="'YOUR_SITE_KEY'"
69
+ [theme]="'dark'"
70
+ [language]="'en'"
71
+ (challengeVisible)="onChallengeVisible()"
72
+ (challengeHidden)="onChallengeHidden()"
73
+ (success)="onSuccess($event)"
74
+ (networkError)="onNetworkError()"
75
+ (tokenExpired)="onTokenExpired()"
76
+ (javascriptError)="onJavascriptError($event)"
77
+ ></invisible-smart-captcha>
78
+
79
+ <button type="submit" [disabled]="form.invalid">Submit</button>
80
+ </form>
81
+ ```
82
+
83
+ ---
84
+
85
+ ## Component API
86
+
87
+ ### Inputs
88
+
89
+ #### Common Inputs (for both components)
90
+ - **sitekey** (`string`, **required**): Your Yandex SmartCaptcha site key.
91
+ - **theme** (`'light' | 'dark'`, default: `'light'`): The visual theme of the captcha.
92
+ - **language** (`string`): Locale code for language customization (e.g., `'en'` or `'ru'`).
93
+ - **test** (`boolean`): Enable test mode for development.
94
+ - **webview** (`boolean`): Enable special behavior for webview contexts.
95
+
96
+ #### Specific Inputs
97
+ - **invisible** (`boolean`):
98
+ - **SmartCaptchaComponent**: Determines whether the captcha is invisible.
99
+ - **InvisibleSmartCaptchaComponent**: Always set to `true` (cannot be overridden).
100
+ - **visible** (`boolean`): Triggers the execution for invisible captcha when set.
101
+ - **hideShield** (`boolean`): Option to hide the shield.
102
+ - **shieldPosition** (`'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'`): Position of the shield with data processing notice when visible.
103
+
104
+ ### Outputs (Events)
105
+
106
+ - **challengeVisible**: Emitted when the captcha challenge is displayed.
107
+ - **challengeHidden**: Emitted when the captcha challenge is hidden.
108
+ - **success**: Emitted with the token string when the captcha is successfully solved.
109
+ - **networkError**: Emitted when there is a network error loading the captcha.
110
+ - **tokenExpired**: Emitted when the previously obtained token expires.
111
+ - **javascriptError**: Emitted with an error payload if a JavaScript error occurs in the captcha script.
112
+
113
+ ---
114
+
115
+ ## How It Works
116
+
117
+ 1. **Script Loading & Initialization**:
118
+ The component dynamically creates and appends a `<script>` tag to load the Yandex SmartCaptcha API. A shared callback mechanism ensures that the captcha is rendered as soon as the script is ready.
119
+
120
+ 2. **Rendering the Captcha**:
121
+ Once the API is loaded, the component renders the captcha inside the container element referenced in the template. It passes the configuration parameters (such as sitekey, theme, language, etc.) to the underlying Yandex SmartCaptcha instance.
122
+
123
+ 3. **Event Handling & Subscriptions**:
124
+ The component sets up subscriptions to various captcha events (e.g., challenge visibility, success, network errors) and emits Angular outputs accordingly. This allows you to hook custom logic into the captcha lifecycle.
125
+
126
+ 4. **Validation & Value Access**:
127
+ When the captcha is solved, the token is set internally and propagated to Angular forms via the registered change callback. The validator ensures that a token exists (or defers validation for invisible captcha until user interaction).
128
+
129
+ ---
130
+
131
+ ## Example Component
132
+
133
+ Here is an example of an Angular component using the SmartCaptcha:
134
+
135
+ ```typescript
136
+ import { Component, OnInit } from '@angular/core';
137
+ import { FormBuilder, FormGroup, Validators } from '@angular/forms';
138
+
139
+ @Component({
140
+ selector: 'app-captcha-form',
141
+ templateUrl: './captcha-form.component.html',
142
+ })
143
+ export class CaptchaFormComponent {
144
+ form: FormGroup;
145
+
146
+ constructor(private fb: FormBuilder) {
147
+ this.form = this.fb.group({
148
+ // The captcha control will store the token returned by the captcha
149
+ captcha: [null, Validators.required],
150
+ });
151
+ }
152
+
153
+ onChallengeVisible(): void {
154
+ console.log('Captcha challenge visible');
155
+ }
156
+
157
+ onChallengeHidden(): void {
158
+ console.log('Captcha challenge hidden');
159
+ }
160
+
161
+ onSuccess(token: string): void {
162
+ console.log('Captcha solved, token:', token);
163
+ }
164
+
165
+ onNetworkError(): void {
166
+ console.error('Captcha network error');
167
+ }
168
+
169
+ onTokenExpired(): void {
170
+ console.warn('Captcha token expired');
171
+ }
172
+
173
+ onJavascriptError(error: any): void {
174
+ console.error('Captcha javascript error:', error);
175
+ }
176
+
177
+ onSubmit(): void {
178
+ if (this.form.valid) {
179
+ // Process form submission
180
+ console.log('Form submitted with captcha token:', this.form.value.captcha);
181
+ } else {
182
+ console.error('Form is invalid');
183
+ }
184
+ }
185
+ }
186
+ ```
187
+
188
+ ---
189
+
190
+ ## Customization Options
191
+
192
+ You can customize various aspects of the captcha by passing different inputs:
193
+ - **Theme**: Switch between `'light'` and `'dark'`.
194
+ - **Language**: Adjust the captcha language with the `language` input.
195
+ - **Shield Customization**: Configure shield visibility and position with `hideShield` and `shieldPosition`.
196
+
197
+ ---
198
+
199
+ ## Troubleshooting
200
+
201
+ - **Invalid Host Error**:
202
+ Ensure the host input is in the correct format (e.g., `domain.ru` or `localhost:3000`). An invalid host will log an error and prevent captcha rendering.
203
+
204
+ - **Script Loading Issues**:
205
+ Verify that your network allows access to the Yandex SmartCaptcha API endpoint. Check your browser console for errors if the script fails to load.
206
+
207
+ - **Form Validation**:
208
+ If the captcha control remains invalid, ensure that the user interacts with the captcha (for invisible captcha, make sure the `visible` input is triggered).
209
+
210
+ ---
211
+
212
+ ## Contributing
213
+
214
+ Contributions are welcome! Feel free to fork the repository and submit pull requests. For major changes, please open an issue first to discuss what you would like to change.
215
+
216
+ ---
217
+
218
+ ## License
219
+
220
+ Distributed under the MIT License.
221
+
222
+ ---
223
+
224
+ ## References
225
+
226
+ - [Yandex SmartCaptcha Documentation (React)](https://yandex.cloud/en-ru/docs/smartcaptcha/concepts/react?utm_referrer=about%3Ablank)
227
+
228
+ ---
229
+
230
+ This documentation should provide a complete guide for developers integrating the Yandex SmartCaptcha into their Angular projects using **@ngx-rock/yandex-smart-captcha**.
231
+ Enjoy secure and seamless captcha integration in your Angular apps!
232
+
233
+ ---
234
+
235
+ **[English](README.md)** | [Русский](README_RU.md)
package/README_RU.md ADDED
@@ -0,0 +1,235 @@
1
+ # Angular Yandex Smart Captcha
2
+
3
+ [![npm version](https://badge.fury.io/js/@ngx-rock%2Fyandex-smart-captcha.svg)](https://badge.fury.io/js/@ngx-rock%2Fyandex-smart-captcha) [![GitHub license](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/ngx-rock/memoize-pipe/blob/main/LICENSE)
4
+
5
+ Angular библиотека для интеграции Yandex SmartCaptcha в ваше приложение. Пакет предоставляет Angular-компоненты-обертки для JavaScript библиотеки Yandex SmartCaptcha, поддерживая как стандартный, так и невидимый режим работы.
6
+ Компоненты реализуют интерфейсы `ControlValueAccessor` и `Validator` для интеграции с реактивными формами Angular, а также используют современные возможности Angular (сигналы и эффекты) для работы в `zoneless` режиме.
7
+
8
+ > **Примечание:** Документация основана на концепциях [Yandex SmartCaptcha для React](https://yandex.cloud/en-ru/docs/smartcaptcha/concepts/react?utm_referrer=about%3Ablank) и адаптирована под особенности Angular.
9
+
10
+ ## Установка
11
+
12
+ Установите пакет через npm:
13
+
14
+ ```bash
15
+ npm install @ngx-rock/yandex-smart-captcha
16
+ ```
17
+
18
+ ## Компоненты
19
+
20
+ Библиотека предоставляет два основных standalone-компонента:
21
+
22
+ - **SmartCaptchaComponent**: Стандартный компонент Yandex SmartCaptcha.
23
+ - **InvisibleSmartCaptchaComponent**: Расширение компонента SmartCaptchaComponent, настроенное для невидимого режима (invisible captcha).
24
+
25
+ Оба компонента реализуют интерфейсы `ControlValueAccessor` и `Validator`, что обеспечивает лёгкую интеграцию с реактивными формами Angular.
26
+
27
+ ---
28
+
29
+ ## Использование
30
+
31
+ ### Импорт компонента
32
+
33
+ Так как компоненты являются standalone, вы можете напрямую импортировать их в модуль или компонент вашего приложения:
34
+
35
+ ```typescript
36
+ import { SmartCaptchaComponent } from '@ngx-rock/yandex-smart-captcha';
37
+ // либо для невидимого капчи
38
+ import { InvisibleSmartCaptchaComponent } from '@ngx-rock/yandex-smart-captcha';
39
+ ```
40
+
41
+ ### Пример шаблона (Стандартная капча)
42
+
43
+ ```html
44
+ <form [formGroup]="form">
45
+ <smart-captcha
46
+ formControlName="captcha"
47
+ [sitekey]="'YOUR_SITE_KEY'"
48
+ [theme]="'light'"
49
+ [language]="'ru'"
50
+ (challengeVisible)="onChallengeVisible()"
51
+ (challengeHidden)="onChallengeHidden()"
52
+ (success)="onSuccess($event)"
53
+ (networkError)="onNetworkError()"
54
+ (tokenExpired)="onTokenExpired()"
55
+ (javascriptError)="onJavascriptError($event)"
56
+ ></smart-captcha>
57
+
58
+ <button type="submit" [disabled]="form.invalid">Отправить</button>
59
+ </form>
60
+ ```
61
+
62
+ ### Пример шаблона (Невидимая капча)
63
+
64
+ ```html
65
+ <form [formGroup]="form">
66
+ <invisible-smart-captcha
67
+ formControlName="captcha"
68
+ [sitekey]="'YOUR_SITE_KEY'"
69
+ [theme]="'dark'"
70
+ [language]="'ru'"
71
+ (challengeVisible)="onChallengeVisible()"
72
+ (challengeHidden)="onChallengeHidden()"
73
+ (success)="onSuccess($event)"
74
+ (networkError)="onNetworkError()"
75
+ (tokenExpired)="onTokenExpired()"
76
+ (javascriptError)="onJavascriptError($event)"
77
+ ></invisible-smart-captcha>
78
+
79
+ <button type="submit" [disabled]="form.invalid">Отправить</button>
80
+ </form>
81
+ ```
82
+
83
+ ---
84
+
85
+ ## API Компонента
86
+
87
+ ### Входные параметры (Inputs)
88
+
89
+ #### Общие (для обоих компонентов)
90
+ - **sitekey** (`string`, **обязательный**): Ваш ключ сайта для Yandex SmartCaptcha.
91
+ - **theme** (`'light' | 'dark'`, по умолчанию: `'light'`): Визуальная тема капчи.
92
+ - **language** (`string`): Локаль для отображения капчи (например, `'ru'` или `'en'`).
93
+ - **test** (`boolean`): Включает тестовый режим для разработки.
94
+ - **webview** (`boolean`): Включает специальное поведение для вебвью.
95
+
96
+ #### Специфичные
97
+ - **invisible** (`boolean`):
98
+ - **SmartCaptchaComponent**: Определяет, работает ли капча в невидимом режиме.
99
+ - **InvisibleSmartCaptchaComponent**: Всегда имеет значение `true`.
100
+ - **visible** (`boolean`): Триггер для выполнения невидимой капчи при изменении.
101
+ - **hideShield** (`boolean`): Опция для скрытия блока уведомления об обработке данных.
102
+ - **shieldPosition** (`'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'`): Позиция блока, если он отображается.
103
+
104
+ ### Исходящие события (Outputs)
105
+
106
+ - **challengeVisible**: Событие, возникающее при отображении капчи.
107
+ - **challengeHidden**: Событие, возникающее при скрытии капчи.
108
+ - **success**: Событие, которое передаёт токен капчи при успешном прохождении проверки.
109
+ - **networkError**: Событие, возникающее при ошибке загрузки капчи (сетевая ошибка).
110
+ - **tokenExpired**: Событие, возникающее при истечении срока действия полученного токена.
111
+ - **javascriptError**: Событие, передающее информацию об ошибке, возникшей в JavaScript капчи.
112
+
113
+ ---
114
+
115
+ ## Как это работает
116
+
117
+ 1. **Загрузка скрипта и инициализация**
118
+ Компонент динамически создаёт и добавляет элемент `<script>` для загрузки API Yandex SmartCaptcha. Глобальный колбэк гарантирует, что капча будет отрисована сразу после загрузки скрипта.
119
+
120
+ 2. **Отрисовка капчи**
121
+ После загрузки API компонент отрисовывает капчу в контейнере, указанном в шаблоне. Конфигурационные параметры (например, sitekey, тема, язык) передаются в экземпляр Yandex SmartCaptcha.
122
+
123
+ 3. **Обработка событий и подписки**
124
+ Компонент устанавливает подписки на различные события (например, отображение/скрытие, успешное прохождение проверки, сетевые ошибки) и эмиттирует соответствующие Angular-события. Это позволяет добавлять пользовательскую логику на каждом этапе жизненного цикла.
125
+
126
+ 4. **Валидация и доступ к значению**
127
+ После успешного прохождения капчи токен сохраняется во внутреннем состоянии и передается в Angular форму. Валидатор проверяет наличие токена (или откладывает валидацию для невидимой капчи до взаимодействия пользователя).
128
+
129
+ ---
130
+
131
+ ## Пример компонента
132
+
133
+ Ниже приведён пример использования компонента с реактивной формой:
134
+
135
+ ```typescript
136
+ import { Component, OnInit } from '@angular/core';
137
+ import { FormBuilder, FormGroup, Validators } from '@angular/forms';
138
+
139
+ @Component({
140
+ selector: 'app-captcha-form',
141
+ templateUrl: './captcha-form.component.html',
142
+ })
143
+ export class CaptchaFormComponent {
144
+ form: FormGroup;
145
+
146
+ constructor(private fb: FormBuilder) {
147
+ this.form = this.fb.group({
148
+ // Контрол для капчи будет хранить токен, возвращённый капчей
149
+ captcha: [null, Validators.required],
150
+ });
151
+ }
152
+
153
+ onChallengeVisible(): void {
154
+ console.log('Капча отображена');
155
+ }
156
+
157
+ onChallengeHidden(): void {
158
+ console.log('Капча скрыта');
159
+ }
160
+
161
+ onSuccess(token: string): void {
162
+ console.log('Капча пройдена, токен:', token);
163
+ }
164
+
165
+ onNetworkError(): void {
166
+ console.error('Ошибка сети при загрузке капчи');
167
+ }
168
+
169
+ onTokenExpired(): void {
170
+ console.warn('Срок действия токена капчи истёк');
171
+ }
172
+
173
+ onJavascriptError(error: any): void {
174
+ console.error('Ошибка JavaScript в капче:', error);
175
+ }
176
+
177
+ onSubmit(): void {
178
+ if (this.form.valid) {
179
+ // Обработка отправки формы
180
+ console.log('Форма отправлена с токеном капчи:', this.form.value.captcha);
181
+ } else {
182
+ console.error('Форма невалидна');
183
+ }
184
+ }
185
+ }
186
+ ```
187
+
188
+ ---
189
+
190
+ ## Опции настройки
191
+
192
+ Вы можете настраивать различные параметры капчи, передавая соответствующие входные значения:
193
+ - **Тема (theme)**: Переключайтесь между `'light'` и `'dark'`.
194
+ - **Язык (language)**: Задавайте локаль с помощью параметра `language`.
195
+ - **Настройка уведомления об обработке данных.**: Определяйте видимость и позицию блока с помощью `hideShield` и `shieldPosition`.
196
+
197
+ ---
198
+
199
+ ## Решение проблем
200
+
201
+ - **Ошибка неверного host**
202
+ Убедитесь, что значение параметра host соответствует необходимому формату (например, `domain.ru` или `localhost:3000`). Неверное значение приведёт к логированию ошибки и отмене отрисовки капчи.
203
+
204
+ - **Проблемы с загрузкой скрипта**
205
+ Проверьте, что ваша сеть позволяет доступ к API Yandex SmartCaptcha. Если скрипт не загружается, обратитесь к консоли браузера для получения подробной информации об ошибке.
206
+
207
+ - **Проблемы валидации формы**
208
+ Если контрол капчи остаётся невалидным, убедитесь, что пользователь взаимодействует с капчей (для невидимой капчи необходимо установить параметр `visible`).
209
+
210
+ ---
211
+
212
+ ## Вклад и развитие
213
+
214
+ Мы будем рады принять ваш вклад! Вы можете форкнуть репозиторий, внести изменения и отправить pull request. Если планируется серьёзное изменение, пожалуйста, сначала создайте issue для обсуждения.
215
+
216
+ ---
217
+
218
+ ## Лицензия
219
+
220
+ Распространяется под лицензией MIT.
221
+
222
+ ---
223
+
224
+ ## Ссылки и источники
225
+
226
+ - [Документация Yandex SmartCaptcha (React)](https://yandex.cloud/en-ru/docs/smartcaptcha/concepts/react?utm_referrer=about%3Ablank)
227
+
228
+ ---
229
+
230
+ Эта документация предоставляет полный гайд для разработчиков по интеграции Yandex SmartCaptcha в Angular приложения с использованием **@ngx-rock/yandex-smart-captcha**.
231
+ Наслаждайтесь безопасной и удобной интеграцией капчи в ваши проекты!
232
+
233
+ ---
234
+
235
+ [English](README.md) | **[Русский](README_RU.md)**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngx-rock/yandex-smart-captcha",
3
- "version": "17.0.0",
3
+ "version": "17.0.1",
4
4
  "description": "Yandex smart captcha",
5
5
  "license": "MIT",
6
6
  "repository": {