react-lgpd-consent 0.7.0 → 0.7.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.
- package/API.md +28 -3
- package/CHANGELOG.md +209 -0
- package/INTEGRACOES.md +61 -15
- package/README.md +1 -1
- package/package.json +4 -4
package/API.md
CHANGED
|
@@ -17,7 +17,9 @@ Este documento é a referência técnica oficial para a API da biblioteca `react
|
|
|
17
17
|
| `useOpenPreferencesModal` | Hook | Retorna uma função para abrir o modal de preferências de forma programática. |
|
|
18
18
|
| `openPreferencesModal` | Função | Versão da função acima para ser usada fora do contexto React. |
|
|
19
19
|
| `ConsentGate` | Componente | Renderiza componentes filhos apenas se uma categoria de cookie for consentida. |
|
|
20
|
-
| `ConsentScriptLoader` | Componente | Carrega scripts de terceiros (como Google Analytics) com base no consentimento. |
|
|
20
|
+
| `ConsentScriptLoader` | Componente | Carrega scripts de terceiros (como Google Analytics) com base no consentimento. Suporta Consent Mode v2 automático. |
|
|
21
|
+
| `registerScript()` | Função | Registra um script na fila global para execução condicional ao consentimento. Retorna função de cleanup. |
|
|
22
|
+
| `RegisteredScript` | Tipo | Interface para scripts registrados programaticamente (id, category, execute, priority, onConsentUpdate). |
|
|
21
23
|
| `buildConsentStorageKey` | Função | (v0.5.2) Gera nomes de cookies `namespace__vX` a partir de namespace/versão. |
|
|
22
24
|
| `createGoogleAnalyticsIntegration` | Função | Factory para integração nativa com o Google Analytics. |
|
|
23
25
|
| `createGoogleTagManagerIntegration` | Função | Factory para integração nativa com o Google Tag Manager. |
|
|
@@ -175,12 +177,35 @@ function MyComponent() {
|
|
|
175
177
|
|
|
176
178
|
Gerencia o carregamento de scripts de terceiros (ex: Google Analytics) com base no consentimento do usuário. Veja o guia `INTEGRACOES.md` para mais detalhes.
|
|
177
179
|
|
|
180
|
+
**Novidades v0.7.1:**
|
|
181
|
+
- ✨ **Google Consent Mode v2 automático**: GA4 e GTM agora enviam `consent('default', 'denied')` no bootstrap e `consent('update', 'granted')` após consentimento
|
|
182
|
+
- 🎯 **Sistema de fila com prioridade**: Scripts são executados ordenadamente (necessary → categoria → prioridade → timestamp)
|
|
183
|
+
- 🔄 **Callbacks de atualização**: `onConsentUpdate` dispara quando preferências mudam
|
|
184
|
+
|
|
178
185
|
```tsx
|
|
179
|
-
import { ConsentScriptLoader, createGoogleAnalyticsIntegration } from 'react-lgpd-consent'
|
|
186
|
+
import { ConsentScriptLoader, createGoogleAnalyticsIntegration, registerScript } from 'react-lgpd-consent'
|
|
180
187
|
|
|
188
|
+
// Uso padrão (Consent Mode v2 automático)
|
|
181
189
|
const integrations = [createGoogleAnalyticsIntegration({ measurementId: 'G-XXXXXXXXXX' })]
|
|
190
|
+
<ConsentScriptLoader integrations={integrations} />
|
|
191
|
+
|
|
192
|
+
// Uso avançado: registro programático com prioridade
|
|
193
|
+
const cleanup = registerScript({
|
|
194
|
+
id: 'custom-analytics',
|
|
195
|
+
category: 'analytics',
|
|
196
|
+
priority: 10, // Maior = executa primeiro
|
|
197
|
+
execute: async () => {
|
|
198
|
+
console.log('Script carregado!')
|
|
199
|
+
},
|
|
200
|
+
onConsentUpdate: ({ consented, preferences }) => {
|
|
201
|
+
if (preferences.analytics) {
|
|
202
|
+
console.log('Analytics habilitado via update!')
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
})
|
|
182
206
|
|
|
183
|
-
|
|
207
|
+
// ℹ️ Estados da fila: pending → running → executed.
|
|
208
|
+
// Scripts só reexecutam se allowReload=true; sempre use o cleanup ao desmontar.
|
|
184
209
|
```
|
|
185
210
|
|
|
186
211
|
---
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,214 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.7.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#133](https://github.com/lucianoedipo/react-lgpd-consent/pull/133) [`33bc0eb`](https://github.com/lucianoedipo/react-lgpd-consent/commit/33bc0ebcb40ce65c70b02668d3c0a97efb1854f1) Thanks [@lucianoedipo](https://github.com/lucianoedipo)! - # 🧩 Fundamento Crítico de Consentimento — SUPER TASK v0.7.1
|
|
8
|
+
|
|
9
|
+
**Persistência + Loader + Consent Mode v2**
|
|
10
|
+
|
|
11
|
+
Esta release estabelece o **núcleo legal, técnico e funcional** da biblioteca react-lgpd-consent, garantindo um contrato sólido, seguro e auditável para uso institucional e governamental.
|
|
12
|
+
|
|
13
|
+
***
|
|
14
|
+
|
|
15
|
+
## 🔹 Bloco A — Persistência de Consentimento por Cookie
|
|
16
|
+
|
|
17
|
+
### ✨ API Consolidada de Persistência
|
|
18
|
+
|
|
19
|
+
Nova API completa no `ConsentProvider`:
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
<ConsentProvider
|
|
23
|
+
cookie={{
|
|
24
|
+
name: 'lgpd-consent',
|
|
25
|
+
domain: '.example.com', // Compartilha entre subdomínios
|
|
26
|
+
path: '/',
|
|
27
|
+
sameSite: 'Lax', // Default seguro
|
|
28
|
+
secure: true, // Auto em HTTPS
|
|
29
|
+
maxAge: 31536000, // Segundos (substitui maxAgeDays)
|
|
30
|
+
}}
|
|
31
|
+
>
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
**Regras Implementadas:**
|
|
35
|
+
- ✅ Defaults seguros: `SameSite=Lax`, `Secure=true` em HTTPS
|
|
36
|
+
- ✅ Categoria `necessary` **sempre forçada como true**
|
|
37
|
+
- ✅ Nenhuma gravação de cookie durante SSR
|
|
38
|
+
- ✅ Suporte completo a subdomínios via `domain`
|
|
39
|
+
- ✅ Nova opção `maxAge` (segundos, padrão moderno)
|
|
40
|
+
- ✅ Opção `maxAgeDays` deprecated mas mantida para compatibilidade
|
|
41
|
+
|
|
42
|
+
**Ambientes Suportados:**
|
|
43
|
+
- ✅ `localhost` (desenvolvimento)
|
|
44
|
+
- ✅ `dev` / `staging` (domínios customizados)
|
|
45
|
+
- ✅ `production` (HTTPS obrigatório)
|
|
46
|
+
- ✅ Comportamento **independente de NODE_ENV**
|
|
47
|
+
|
|
48
|
+
***
|
|
49
|
+
|
|
50
|
+
## 🔹 Bloco B — ConsentScriptLoader com Bloqueio Real
|
|
51
|
+
|
|
52
|
+
### 🚫 Contrato de Bloqueio Garantido
|
|
53
|
+
|
|
54
|
+
> **Nenhum script não necessário executa antes do consentimento correspondente.**
|
|
55
|
+
|
|
56
|
+
### ✨ Sistema de Fila e Priorização
|
|
57
|
+
|
|
58
|
+
Implementado `ConsentScriptLoader` com:
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
registerScript({
|
|
62
|
+
id: 'google-analytics',
|
|
63
|
+
category: 'analytics',
|
|
64
|
+
priority: 1, // Ordem de execução
|
|
65
|
+
execute: () => {
|
|
66
|
+
// Seu script aqui
|
|
67
|
+
},
|
|
68
|
+
onConsentUpdate: (granted) => {
|
|
69
|
+
// Reagir a mudanças de consentimento
|
|
70
|
+
},
|
|
71
|
+
})
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
**Recursos Implementados:**
|
|
75
|
+
- ✅ **Fila interna de execução** com ordenação por:
|
|
76
|
+
- 1. Categoria (`necessary` → `analytics` → `marketing`, etc.)
|
|
77
|
+
- 2. Prioridade (numérica)
|
|
78
|
+
- 3. Timestamp (ordem de registro)
|
|
79
|
+
- ✅ Scripts `necessary` executam **imediatamente**
|
|
80
|
+
- ✅ Scripts de outras categorias aguardam **consentimento explícito**
|
|
81
|
+
- ✅ Suporte a `onConsentUpdate` para reconfiguração dinâmica
|
|
82
|
+
- ✅ Snapshot de consentimento para scripts que precisam do estado atual
|
|
83
|
+
- ✅ **Otimização anti-duplicação**: integrações não são reexecutadas a cada render quando criadas inline (ex.: `integrations={[createGoogleAnalyticsIntegration(...)]}`). Sistema mantém hash estrutural para detectar mudanças reais e prevenir múltiplas inicializações do mesmo script.
|
|
84
|
+
|
|
85
|
+
**Observabilidade em DEV:**
|
|
86
|
+
- ✅ Logs detalhados de ordem de execução
|
|
87
|
+
- ✅ Indicação clara de categoria liberada
|
|
88
|
+
- ✅ Rastreamento de status de cada script
|
|
89
|
+
- ⚠️ **Silencioso em produção** (performance otimizada)
|
|
90
|
+
|
|
91
|
+
***
|
|
92
|
+
|
|
93
|
+
## 🔹 Bloco C — Integração Nativa Google Consent Mode v2
|
|
94
|
+
|
|
95
|
+
### 🎯 Implementação Automática
|
|
96
|
+
|
|
97
|
+
**Zero configuração manual necessária!**
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
import { createGoogleAnalyticsIntegration } from '@react-lgpd-consent/core'
|
|
101
|
+
|
|
102
|
+
const ga4 = createGoogleAnalyticsIntegration({
|
|
103
|
+
measurementId: 'G-XXXXXXXXXX'
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
<ConsentScriptLoader integrations={[ga4]} />
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
**O que a biblioteca faz automaticamente:**
|
|
110
|
+
1. ✅ Inicializa `dataLayer` se não existir
|
|
111
|
+
2. ✅ Define `gtag('consent', 'default', denied)` **antes** de qualquer tag
|
|
112
|
+
3. ✅ Mapeia categorias corretamente:
|
|
113
|
+
- `analytics` → `analytics_storage`
|
|
114
|
+
- `marketing` → `ad_storage`, `ad_user_data`, `ad_personalization`
|
|
115
|
+
4. ✅ Envia `gtag('consent', 'update')` quando usuário escolhe preferências
|
|
116
|
+
5. ✅ Dispara eventos de ciclo de vida:
|
|
117
|
+
```javascript
|
|
118
|
+
{ event: 'consent_initialized' }
|
|
119
|
+
{ event: 'consent_updated', preferences: {...} }
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
**Factories Implementadas:**
|
|
123
|
+
- ✅ `createGoogleAnalyticsIntegration` (GA4)
|
|
124
|
+
- ✅ `createGoogleTagManagerIntegration` (GTM)
|
|
125
|
+
- ✅ Suporte a `bootstrap()` para inicialização pré-consentimento
|
|
126
|
+
- ✅ Suporte a `onConsentUpdate()` para reconfiguração dinâmica
|
|
127
|
+
|
|
128
|
+
### 🔒 Ordem de Inicialização Segura
|
|
129
|
+
|
|
130
|
+
Fluxo garantido pela implementação:
|
|
131
|
+
|
|
132
|
+
```
|
|
133
|
+
1. dataLayer criado
|
|
134
|
+
2. gtag('consent', 'default', denied)
|
|
135
|
+
3. Loader bloqueia tags
|
|
136
|
+
4. Usuário consente
|
|
137
|
+
5. gtag('consent', 'update', granted/denied)
|
|
138
|
+
6. Tags disparam conforme consentimento
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### ⚡ Compatibilidade Next.js (SSR)
|
|
142
|
+
- ✅ Nenhum acesso a `window` fora de `useEffect`
|
|
143
|
+
- ✅ App Router (Next.js 13+)
|
|
144
|
+
- ✅ Pages Router (Next.js 12+)
|
|
145
|
+
- ✅ **Zero hydration mismatch**
|
|
146
|
+
- ✅ Estratégia de renderização: `client-only` quando necessário
|
|
147
|
+
|
|
148
|
+
***
|
|
149
|
+
|
|
150
|
+
## 🆕 Novas APIs Públicas
|
|
151
|
+
|
|
152
|
+
### Core Package (`@react-lgpd-consent/core`):
|
|
153
|
+
|
|
154
|
+
```typescript
|
|
155
|
+
// Registro de scripts
|
|
156
|
+
registerScript(config: RegisteredScript): void
|
|
157
|
+
|
|
158
|
+
// Factories de integrações
|
|
159
|
+
createGoogleAnalyticsIntegration(config): ScriptIntegration
|
|
160
|
+
createGoogleTagManagerIntegration(config): ScriptIntegration
|
|
161
|
+
|
|
162
|
+
// Utilitários de cookie
|
|
163
|
+
readConsentCookie(name?: string): ConsentState | null
|
|
164
|
+
writeConsentCookie(state: ConsentState, options?: CookieOptions): void
|
|
165
|
+
|
|
166
|
+
// Novos tipos
|
|
167
|
+
type RegisteredScript = { ... }
|
|
168
|
+
type ScriptIntegration = { ... }
|
|
169
|
+
interface LoadScriptOptions = { ... }
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
***
|
|
173
|
+
|
|
174
|
+
## 📚 Documentação Atualizada
|
|
175
|
+
- ✅ **API.md** - Novas APIs de `registerScript` e Consent Mode v2
|
|
176
|
+
- ✅ **INTEGRACOES.md** - Guias completos de GA4, GTM, Facebook Pixel
|
|
177
|
+
- ✅ **MIGRATION.md** - Guia de migração v0.7.0 → v0.7.1
|
|
178
|
+
- ✅ **SUPER_TASK_VALIDATION.md** - Relatório técnico de validação completo
|
|
179
|
+
|
|
180
|
+
***
|
|
181
|
+
|
|
182
|
+
## 🔄 Breaking Changes
|
|
183
|
+
|
|
184
|
+
**Nenhum!** Esta release é 100% backward-compatible:
|
|
185
|
+
- ✅ Opção `maxAgeDays` deprecated mas funcional
|
|
186
|
+
- ✅ Comportamento padrão preservado
|
|
187
|
+
- ✅ APIs antigas continuam funcionando
|
|
188
|
+
- ✅ Migração gradual suportada
|
|
189
|
+
|
|
190
|
+
***
|
|
191
|
+
|
|
192
|
+
## 🎯 Melhorias Complementares
|
|
193
|
+
|
|
194
|
+
### Sistema de i18n para Diagnósticos
|
|
195
|
+
|
|
196
|
+
Sistema básico de internacionalização para mensagens de peer dependencies:
|
|
197
|
+
- ✅ Suporte a pt-BR (padrão) e en
|
|
198
|
+
- ✅ API para customização: `setPeerDepsLocale()`, `setPeerDepsMessages()`
|
|
199
|
+
- ✅ Mensagens extraídas para constantes (melhor manutenibilidade)
|
|
200
|
+
|
|
201
|
+
### Refatorações e Otimizações
|
|
202
|
+
- ✅ Strings de mensagens extraídas para constantes
|
|
203
|
+
- ✅ Separação de concerns (lógica vs conteúdo)
|
|
204
|
+
- ✅ Type safety aprimorado em toda API
|
|
205
|
+
- ✅ Performance otimizada (sem logs em produção)
|
|
206
|
+
- ✅ **Fix crítico**: Prevenção de reexecução de integrações a cada render quando `integrations` prop muda referência (inline array). Sistema agora usa hash estrutural para detectar mudanças reais e manter scripts já registrados estáveis.
|
|
207
|
+
|
|
208
|
+
- Updated dependencies [[`33bc0eb`](https://github.com/lucianoedipo/react-lgpd-consent/commit/33bc0ebcb40ce65c70b02668d3c0a97efb1854f1)]:
|
|
209
|
+
- @react-lgpd-consent/core@0.7.1
|
|
210
|
+
- @react-lgpd-consent/mui@0.7.1
|
|
211
|
+
|
|
3
212
|
## 0.7.0
|
|
4
213
|
|
|
5
214
|
### Minor Changes
|
package/INTEGRACOES.md
CHANGED
|
@@ -6,6 +6,36 @@ A biblioteca oferece integrações nativas para as ferramentas mais comuns, elim
|
|
|
6
6
|
|
|
7
7
|
O componente `ConsentScriptLoader` gerencia o carregamento desses scripts automaticamente, disparando-os apenas quando o usuário concede consentimento para a categoria correspondente.
|
|
8
8
|
|
|
9
|
+
### ✨ Novidades v0.7.1
|
|
10
|
+
|
|
11
|
+
- **🎯 Google Consent Mode v2 Automático**: GA4 e GTM agora implementam Consent Mode v2 automaticamente:
|
|
12
|
+
- `bootstrap`: Seta `consent('default', 'denied')` antes de qualquer carregamento
|
|
13
|
+
- `onConsentUpdate`: Envia `consent('update', 'granted')` quando usuário consente
|
|
14
|
+
- Zero configuração manual necessária!
|
|
15
|
+
|
|
16
|
+
- **🔄 Sistema de Fila com Prioridade**: Scripts são executados ordenadamente:
|
|
17
|
+
1. Categoria `necessary` sempre primeiro
|
|
18
|
+
2. Dentro da mesma categoria: maior `priority` primeiro
|
|
19
|
+
3. Mesmo priority: ordem de registro (timestamp)
|
|
20
|
+
|
|
21
|
+
- **📝 API `registerScript()`**: Registre scripts programaticamente fora do JSX:
|
|
22
|
+
|
|
23
|
+
```tsx
|
|
24
|
+
import { registerScript } from 'react-lgpd-consent'
|
|
25
|
+
|
|
26
|
+
const cleanup = registerScript({
|
|
27
|
+
id: 'my-script',
|
|
28
|
+
category: 'analytics',
|
|
29
|
+
priority: 5,
|
|
30
|
+
execute: async () => {
|
|
31
|
+
/* carrega script */
|
|
32
|
+
},
|
|
33
|
+
onConsentUpdate: ({ preferences }) => {
|
|
34
|
+
/* reage a mudanças */
|
|
35
|
+
},
|
|
36
|
+
})
|
|
37
|
+
```
|
|
38
|
+
|
|
9
39
|
> 💡 **Procurando exemplos práticos?** Veja [RECIPES.md](../../RECIPES.md) para receitas passo a passo de Google Consent Mode v2, Next.js App Router e CSP/nonce.
|
|
10
40
|
|
|
11
41
|
## 🎯 Integrações Nativas Disponíveis
|
|
@@ -15,6 +45,7 @@ O componente `ConsentScriptLoader` gerencia o carregamento desses scripts automa
|
|
|
15
45
|
- **Categoria**: `analytics`
|
|
16
46
|
- **Função**: `createGoogleAnalyticsIntegration(config)`
|
|
17
47
|
- **Descrição**: Integração completa com o Google Analytics 4. Suporta `measurementId` e configurações adicionais para o `gtag`.
|
|
48
|
+
- **✨ Novo v0.7.1**: Google Consent Mode v2 automático (sem configuração manual)
|
|
18
49
|
|
|
19
50
|
```tsx
|
|
20
51
|
import { createGoogleAnalyticsIntegration, ConsentScriptLoader } from 'react-lgpd-consent'
|
|
@@ -27,20 +58,28 @@ const integrations = [
|
|
|
27
58
|
]
|
|
28
59
|
|
|
29
60
|
<ConsentScriptLoader integrations={integrations} />
|
|
61
|
+
// ✅ Consent Mode v2 implementado automaticamente:
|
|
62
|
+
// - bootstrap: consent('default', 'denied') antes do script
|
|
63
|
+
// - onConsentUpdate: consent('update', 'granted') após consentimento
|
|
30
64
|
```
|
|
31
65
|
|
|
32
66
|
### 2. Google Tag Manager (GTM)
|
|
33
67
|
|
|
34
68
|
- **Categoria**: `analytics`
|
|
35
69
|
- **Função**: `createGoogleTagManagerIntegration(config)`
|
|
36
|
-
- **Descrição**: Carrega o container do Google Tag Manager. Suporta `gtmId` e `dataLayerName`.
|
|
70
|
+
- **Descrição**: Carrega o container do Google Tag Manager. Suporta `containerId` (ou `gtmId` legado) e `dataLayerName`.
|
|
71
|
+
- **✨ Novo v0.7.1**: Google Consent Mode v2 automático com dataLayer customizado
|
|
37
72
|
|
|
38
73
|
```tsx
|
|
39
74
|
import { createGoogleTagManagerIntegration } from 'react-lgpd-consent'
|
|
40
75
|
|
|
41
76
|
const integrations = [
|
|
42
|
-
createGoogleTagManagerIntegration({
|
|
77
|
+
createGoogleTagManagerIntegration({
|
|
78
|
+
containerId: 'GTM-XXXXXXX',
|
|
79
|
+
dataLayerName: 'dataLayer', // opcional
|
|
80
|
+
}),
|
|
43
81
|
]
|
|
82
|
+
// ✅ Consent Mode v2 no dataLayer customizado automaticamente
|
|
44
83
|
```
|
|
45
84
|
|
|
46
85
|
### 3. Facebook Pixel
|
|
@@ -52,9 +91,7 @@ const integrations = [
|
|
|
52
91
|
```tsx
|
|
53
92
|
import { createFacebookPixelIntegration } from 'react-lgpd-consent'
|
|
54
93
|
|
|
55
|
-
const integrations = [
|
|
56
|
-
createFacebookPixelIntegration({ pixelId: 'YOUR_PIXEL_ID', autoTrack: true })
|
|
57
|
-
]
|
|
94
|
+
const integrations = [createFacebookPixelIntegration({ pixelId: 'YOUR_PIXEL_ID', autoTrack: true })]
|
|
58
95
|
```
|
|
59
96
|
|
|
60
97
|
### 4. Hotjar
|
|
@@ -142,7 +179,11 @@ Para simplificar a configuração de múltiplas integrações, a biblioteca ofer
|
|
|
142
179
|
### Exemplo de Template (E-commerce)
|
|
143
180
|
|
|
144
181
|
```tsx
|
|
145
|
-
import {
|
|
182
|
+
import {
|
|
183
|
+
ConsentProvider,
|
|
184
|
+
ConsentScriptLoader,
|
|
185
|
+
createECommerceIntegrations,
|
|
186
|
+
} from 'react-lgpd-consent'
|
|
146
187
|
|
|
147
188
|
function App() {
|
|
148
189
|
const integrations = createECommerceIntegrations({
|
|
@@ -185,6 +226,7 @@ categorizeDiscoveredCookies(discovered, true)
|
|
|
185
226
|
## 🧱 Nota SSR/Next.js (App Router)
|
|
186
227
|
|
|
187
228
|
Para evitar hydration mismatch e vazamento de scripts:
|
|
229
|
+
|
|
188
230
|
- Coloque o `ConsentProvider` dentro de um Client Component e carregue-o com `dynamic(..., { ssr: false })` a partir do `RootLayout` (Server Component).
|
|
189
231
|
- Use o `ConsentScriptLoader` para carregar GTM/GA4 somente após consentimento e inicialize o Consent Mode v2 com `gtag('consent','default', denied)` antes de qualquer script.
|
|
190
232
|
- Consulte a seção “SSR/Next.js (App Router) — Padrões seguros” em `QUICKSTART.md` para ordem dos provedores/estilos (MUI/Emotion) e checklist SSR.
|
|
@@ -218,6 +260,7 @@ A partir da versão **0.4.5**, a biblioteca dispara automaticamente eventos padr
|
|
|
218
260
|
Disparado quando o sistema de consentimento é inicializado (após hidratação).
|
|
219
261
|
|
|
220
262
|
**Payload:**
|
|
263
|
+
|
|
221
264
|
```typescript
|
|
222
265
|
{
|
|
223
266
|
event: 'consent_initialized',
|
|
@@ -232,6 +275,7 @@ Disparado quando o sistema de consentimento é inicializado (após hidratação)
|
|
|
232
275
|
```
|
|
233
276
|
|
|
234
277
|
**Exemplo de uso no GTM:**
|
|
278
|
+
|
|
235
279
|
- **Tipo de acionador**: Evento personalizado
|
|
236
280
|
- **Nome do evento**: `consent_initialized`
|
|
237
281
|
- **Variáveis**: `{{categories.analytics}}`, `{{categories.marketing}}`, etc.
|
|
@@ -241,6 +285,7 @@ Disparado quando o sistema de consentimento é inicializado (após hidratação)
|
|
|
241
285
|
Disparado sempre que o usuário atualiza suas preferências de consentimento.
|
|
242
286
|
|
|
243
287
|
**Payload:**
|
|
288
|
+
|
|
244
289
|
```typescript
|
|
245
290
|
{
|
|
246
291
|
event: 'consent_updated',
|
|
@@ -257,6 +302,7 @@ Disparado sempre que o usuário atualiza suas preferências de consentimento.
|
|
|
257
302
|
```
|
|
258
303
|
|
|
259
304
|
**Exemplo de uso no GTM:**
|
|
305
|
+
|
|
260
306
|
- **Tipo de acionador**: Evento personalizado
|
|
261
307
|
- **Nome do evento**: `consent_updated`
|
|
262
308
|
- **Condição**: `{{changed_categories}}` contém `analytics`
|
|
@@ -313,7 +359,7 @@ Crie uma tag para registrar mudanças de consentimento em um sistema de auditori
|
|
|
313
359
|
categories: {{DLV - Consent Categories}},
|
|
314
360
|
changed: {{DLV - Changed Categories}}
|
|
315
361
|
};
|
|
316
|
-
|
|
362
|
+
|
|
317
363
|
// Enviar para seu sistema de auditoria
|
|
318
364
|
fetch('/api/consent-audit', {
|
|
319
365
|
method: 'POST',
|
|
@@ -336,9 +382,9 @@ const handleCustomUpdate = () => {
|
|
|
336
382
|
const newPreferences = {
|
|
337
383
|
necessary: true,
|
|
338
384
|
analytics: true,
|
|
339
|
-
marketing: false
|
|
385
|
+
marketing: false,
|
|
340
386
|
}
|
|
341
|
-
|
|
387
|
+
|
|
342
388
|
pushConsentUpdatedEvent(newPreferences, 'programmatic')
|
|
343
389
|
}
|
|
344
390
|
```
|
|
@@ -350,7 +396,7 @@ import type {
|
|
|
350
396
|
ConsentEvent,
|
|
351
397
|
ConsentEventOrigin,
|
|
352
398
|
ConsentInitializedEvent,
|
|
353
|
-
ConsentUpdatedEvent
|
|
399
|
+
ConsentUpdatedEvent,
|
|
354
400
|
} from 'react-lgpd-consent'
|
|
355
401
|
|
|
356
402
|
// Origem da ação
|
|
@@ -389,7 +435,6 @@ interface ConsentUpdatedEvent {
|
|
|
389
435
|
| Live Chat | `functional` | Funcionalidade de suporte |
|
|
390
436
|
| YouTube/Vimeo | `social` | Conteúdo de redes sociais |
|
|
391
437
|
|
|
392
|
-
|
|
393
438
|
---
|
|
394
439
|
|
|
395
440
|
## 🆕 Recursos Avançados v0.7.0
|
|
@@ -402,7 +447,7 @@ Integre sistemas de auditoria monitorando eventos de consentimento:
|
|
|
402
447
|
import { ConsentProvider, ConsentScriptLoader } from 'react-lgpd-consent'
|
|
403
448
|
import { googleAnalytics4Integration } from './integrations'
|
|
404
449
|
|
|
405
|
-
|
|
450
|
+
;<ConsentProvider
|
|
406
451
|
categories={{ enabledCategories: ['analytics', 'marketing'] }}
|
|
407
452
|
onConsentInit={(state) => {
|
|
408
453
|
// Disparado na inicialização (útil para analytics)
|
|
@@ -411,19 +456,19 @@ import { googleAnalytics4Integration } from './integrations'
|
|
|
411
456
|
onConsentChange={(current, previous) => {
|
|
412
457
|
// Disparado em toda mudança de preferências
|
|
413
458
|
console.log('Mudança:', { current, previous })
|
|
414
|
-
|
|
459
|
+
|
|
415
460
|
// Exemplo: disparar evento no dataLayer
|
|
416
461
|
window.dataLayer?.push({
|
|
417
462
|
event: 'consent_preferences_updated',
|
|
418
463
|
consent_analytics: current.preferences.analytics,
|
|
419
|
-
consent_marketing: current.preferences.marketing
|
|
464
|
+
consent_marketing: current.preferences.marketing,
|
|
420
465
|
})
|
|
421
466
|
}}
|
|
422
467
|
onAuditLog={(entry) => {
|
|
423
468
|
// Enviar para backend de compliance
|
|
424
469
|
fetch('/api/consent-audit', {
|
|
425
470
|
method: 'POST',
|
|
426
|
-
body: JSON.stringify(entry)
|
|
471
|
+
body: JSON.stringify(entry),
|
|
427
472
|
})
|
|
428
473
|
}}
|
|
429
474
|
>
|
|
@@ -460,6 +505,7 @@ const customConfig = createAnpdCategories({
|
|
|
460
505
|
```
|
|
461
506
|
|
|
462
507
|
**Vantagens dos presets:**
|
|
508
|
+
|
|
463
509
|
- ✅ Conformidade com diretrizes ANPD
|
|
464
510
|
- ✅ Nomes e descrições em pt-BR revisadas
|
|
465
511
|
- ✅ Tipagem forte para evitar erros
|
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@ Gerenciamento de consentimento de cookies em conformidade com a LGPD — pacote
|
|
|
13
13
|
|
|
14
14
|
## Descrição
|
|
15
15
|
|
|
16
|
-
`react-lgpd-consent` é o pacote agregador compatível com versões anteriores (v0.4.x → v0.5.x). Ele re-exporta os componentes prontos em MUI e facilita a migração. Para projetos mais otimizados, considere importar diretamente `@react-lgpd-consent/core` (headless) ou `@react-lgpd-consent/mui` (
|
|
16
|
+
`react-lgpd-consent` é o pacote agregador compatível com versões anteriores (v0.4.x → v0.5.x). Ele re-exporta os componentes prontos em MUI e facilita a migração. Para projetos mais otimizados, considere importar diretamente `@react-lgpd-consent/core` (headless) ou `@react-lgpd-consent/mui/ui` (apenas UI, sem re-export do core).
|
|
17
17
|
|
|
18
18
|
Principais características:
|
|
19
19
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-lgpd-consent",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "Biblioteca de consentimento LGPD, integrações nativas e sistema extensível para React.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"lgpd",
|
|
@@ -94,8 +94,8 @@
|
|
|
94
94
|
}
|
|
95
95
|
},
|
|
96
96
|
"dependencies": {
|
|
97
|
-
"@react-lgpd-consent/core": "^0.7.
|
|
98
|
-
"@react-lgpd-consent/mui": "^0.7.
|
|
97
|
+
"@react-lgpd-consent/core": "^0.7.1",
|
|
98
|
+
"@react-lgpd-consent/mui": "^0.7.1"
|
|
99
99
|
},
|
|
100
100
|
"size-limit": [
|
|
101
101
|
{
|
|
@@ -117,7 +117,7 @@
|
|
|
117
117
|
"name": "Complete Package Import",
|
|
118
118
|
"path": "dist/index.js",
|
|
119
119
|
"import": "{ ConsentProvider, useConsent, ConsentScriptLoader }",
|
|
120
|
-
"limit": "
|
|
120
|
+
"limit": "80 KB"
|
|
121
121
|
}
|
|
122
122
|
],
|
|
123
123
|
"scripts": {
|