react-lgpd-consent 0.6.1 → 0.7.0

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 CHANGED
@@ -33,6 +33,9 @@ Este documento é a referência técnica oficial para a API da biblioteca `react
33
33
  | `categorizeDiscoveredCookies` | Função | (v0.4.1) Categoriza cookies descobertos usando padrões LGPD. |
34
34
  | `getCookiesInfoForCategory` | Função | Retorna informações detalhadas dos cookies de uma categoria específica. |
35
35
  | `resolveTexts` | Função | (v0.4.1) Resolve textos baseados em templates e contexto. |
36
+ | `createConsentAuditEntry` | Função | **(v0.7.0)** Cria entrada de auditoria de consentimento para logs. |
37
+ | `ANPD_CATEGORY_PRESETS` | Constante | **(v0.7.0)** Presets de categorias conforme diretrizes LGPD/ANPD. |
38
+ | `createAnpdCategories` | Função | **(v0.7.0)** Helper para gerar configurações tipadas com presets ANPD. |
36
39
  | `TEXT_TEMPLATES` | Constante | (v0.4.1) Templates pré-configurados (ecommerce, saas, governo). |
37
40
  | `AdvancedConsentTexts` | Tipo | (v0.4.1) Interface expandida com i18n e contextos. |
38
41
  | `DesignTokens` | Tipo | (v0.4.1) Sistema completo com 200+ pontos de customização. |
@@ -80,6 +83,9 @@ function App() {
80
83
  | `disableFloatingPreferencesButton` | `boolean` | Remove o botão flutuante padrão. |
81
84
  | `onConsentGiven` | `(state: ConsentState) => void` | Dispara na primeira vez que o usuário aceita/rejeita. Útil para inicializar analytics. |
82
85
  | `onPreferencesSaved` | `(prefs: ConsentPreferences) => void` | Executa toda vez que o usuário salva preferências no modal. |
86
+ | `onConsentInit` | `(state: ConsentState) => void` | **(v0.7.0)** Callback executado após hidratação inicial do consentimento. |
87
+ | `onConsentChange` | `(state: ConsentState, previous: ConsentState) => void` | **(v0.7.0)** Callback executado sempre que o estado de consentimento muda. |
88
+ | `onAuditLog` | `(entry: ConsentAuditEntry) => void` | **(v0.7.0)** Callback para registrar eventos de auditoria (init, update, reset). |
83
89
  | `cookie` | `Partial<ConsentCookieOptions>` | Override fino das opções de cookie (nome, expiração, sameSite, secure, path, domain). Se `name` não for informado, o valor deriva de `storage`. |
84
90
  | `storage` | `ConsentStorageConfig` | Define namespace, versão e domínio compartilhado. Gera automaticamente o nome da chave (`namespace__vX`). Alterar `version` força re-consentimento. |
85
91
  | `onConsentVersionChange` | `(context: ConsentVersionChangeContext) => void` | Notificado após mudança da chave de storage. O reset já é automático; use o hook para limpar caches externos ou registrar eventos. |
@@ -574,3 +580,141 @@ Conjunto completo (site com analytics/marketing):
574
580
  <App />
575
581
  </ConsentProvider>
576
582
  ```
583
+
584
+ ---
585
+
586
+ ## 🆕 Novidades v0.7.0
587
+
588
+ ### Callbacks de Lifecycle (#68)
589
+
590
+ Monitore eventos de consentimento para integração com sistemas de auditoria:
591
+
592
+ ```tsx
593
+ import { ConsentProvider, createConsentAuditEntry } from 'react-lgpd-consent'
594
+
595
+ function App() {
596
+ return (
597
+ <ConsentProvider
598
+ categories={{ enabledCategories: ['analytics', 'marketing'] }}
599
+ onConsentInit={(state) => {
600
+ console.log('Consentimento inicializado:', state)
601
+ // Útil para analytics iniciais
602
+ }}
603
+ onConsentChange={(current, previous) => {
604
+ console.log('Consentimento alterado:', { current, previous })
605
+ // Dispara em toda mudança de preferências
606
+ }}
607
+ onAuditLog={(entry) => {
608
+ // Registrar no backend para compliance
609
+ fetch('/api/consent-audit', {
610
+ method: 'POST',
611
+ body: JSON.stringify(entry),
612
+ })
613
+ }}
614
+ >
615
+ <YourApp />
616
+ </ConsentProvider>
617
+ )
618
+ }
619
+ ```
620
+
621
+ **Tipos disponíveis:**
622
+
623
+ ```typescript
624
+ interface ConsentAuditEntry {
625
+ timestamp: string // ISO 8601
626
+ action: 'init' | 'update' | 'reset'
627
+ state: ConsentState
628
+ metadata?: {
629
+ storageKey?: string
630
+ consentVersion?: string
631
+ userAgent?: string
632
+ }
633
+ }
634
+ ```
635
+
636
+ ### Presets de Categorias ANPD (#70)
637
+
638
+ Use presets conformes com diretrizes da ANPD:
639
+
640
+ ```tsx
641
+ import { ConsentProvider, createAnpdCategories, ANPD_CATEGORY_PRESETS } from 'react-lgpd-consent'
642
+
643
+ // Preset BÁSICO (necessary + analytics)
644
+ const basicConfig = createAnpdCategories({ include: ['analytics'] })
645
+
646
+ // Preset COMPLETO (todas as categorias)
647
+ const fullConfig = createAnpdCategories({
648
+ include: ['analytics', 'marketing', 'functional', 'social', 'personalization']
649
+ })
650
+
651
+ // Preset MÍNIMO (apenas necessary)
652
+ const minimalConfig = createAnpdCategories({ include: [] })
653
+
654
+ // Com customizações
655
+ const customConfig = createAnpdCategories({
656
+ include: ['analytics', 'marketing'],
657
+ names: { analytics: 'Análises' },
658
+ descriptions: { marketing: 'Anúncios personalizados baseados no seu perfil.' }
659
+ })
660
+
661
+ function App() {
662
+ return (
663
+ <ConsentProvider categories={fullConfig}>
664
+ <YourApp />
665
+ </ConsentProvider>
666
+ )
667
+ }
668
+ ```
669
+
670
+ **Preset disponível:**
671
+
672
+ ```typescript
673
+ export const ANPD_CATEGORY_PRESETS: Record<Category, CategoryDefinition> = {
674
+ necessary: { /* ... */ },
675
+ analytics: { /* ... */ },
676
+ functional: { /* ... */ },
677
+ marketing: { /* ... */ },
678
+ social: { /* ... */ },
679
+ personalization: { /* ... */ }
680
+ }
681
+ ```
682
+
683
+ ### Mensagens de Erro Melhoradas (#71)
684
+
685
+ Hooks agora lançam erros claros em pt-BR quando usados fora do `<ConsentProvider>`:
686
+
687
+ ```tsx
688
+ import { useConsent } from 'react-lgpd-consent'
689
+
690
+ function MyComponent() {
691
+ const consent = useConsent() // ❌ Erro claro!
692
+ // Error: [react-lgpd-consent] useConsent deve ser usado dentro de <ConsentProvider>.
693
+ // Envolva seu componente com o provider ou use o wrapper @react-lgpd-consent/mui.
694
+ }
695
+ ```
696
+
697
+ ### Auditoria e Compliance (#60)
698
+
699
+ Crie entradas de auditoria manualmente:
700
+
701
+ ```typescript
702
+ import { createConsentAuditEntry } from 'react-lgpd-consent'
703
+
704
+ const auditEntry = createConsentAuditEntry(
705
+ { consented: true, preferences: { analytics: true } },
706
+ {
707
+ action: 'update',
708
+ storageKey: 'lgpd-consent__v1',
709
+ consentVersion: '1'
710
+ }
711
+ )
712
+
713
+ // Enviar para backend
714
+ await fetch('/api/audit', {
715
+ method: 'POST',
716
+ body: JSON.stringify(auditEntry)
717
+ })
718
+ ```
719
+
720
+ Consulte [TROUBLESHOOTING.md - Auditoria e log de consentimento](../../TROUBLESHOOTING.md#auditoria-e-log-de-consentimento) para exemplos completos de integração com backend.