react-lgpd-consent 0.4.1 → 0.4.3

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/dist/index.cjs CHANGED
@@ -1,2207 +1,37 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
-
33
- // src/utils/cookieRegistry.ts
34
- function setCookieCatalogOverrides(overrides) {
35
- COOKIE_CATALOG_OVERRIDES = {
36
- byCategory: { ...COOKIE_CATALOG_OVERRIDES.byCategory || {}, ...overrides.byCategory || {} },
37
- byIntegration: {
38
- ...COOKIE_CATALOG_OVERRIDES.byIntegration || {},
39
- ...overrides.byIntegration || {}
40
- }
41
- };
42
- }
43
- function setCookieCategoryOverrides(map) {
44
- COOKIE_CATEGORY_OVERRIDES = { ...COOKIE_CATEGORY_OVERRIDES, ...map };
45
- }
46
- function matchPattern(name, pattern) {
47
- if (pattern.endsWith("*")) return name.startsWith(pattern.slice(0, -1));
48
- return name === pattern;
49
- }
50
- function getCookiesInfoForCategory(categoryId, usedIntegrations) {
51
- const result = [];
52
- usedIntegrations.forEach((id) => {
53
- const defaultCat = INTEGRATION_DEFAULT_CATEGORY[id];
54
- const defaults = COOKIE_INFO_BY_INTEGRATION[id] || [];
55
- const list = COOKIE_CATALOG_OVERRIDES.byIntegration?.[id] || defaults;
56
- list.forEach((desc) => {
57
- const overrideCat = Object.entries(COOKIE_CATEGORY_OVERRIDES).find(
58
- ([pattern]) => matchPattern(desc.name, pattern)
59
- )?.[1];
60
- const finalCat = overrideCat ?? defaultCat;
61
- if (finalCat === categoryId && !result.find((d) => d.name === desc.name)) result.push(desc);
62
- });
63
- });
64
- const catOverride = COOKIE_CATALOG_OVERRIDES.byCategory?.[categoryId];
65
- if (catOverride) {
66
- catOverride.forEach((d) => {
67
- const idx = result.findIndex((x) => x.name === d.name);
68
- if (idx >= 0) result[idx] = d;
69
- else result.push(d);
70
- });
71
- }
72
- if (categoryId === "necessary") {
73
- if (!result.find((d) => d.name === "cookieConsent")) {
74
- result.push({
75
- name: "cookieConsent",
76
- purpose: "Armazena suas prefer\xEAncias de consentimento",
77
- duration: "365 dias",
78
- provider: "Este site"
79
- });
80
- }
81
- }
82
- return result;
83
- }
84
- var COOKIE_PATTERNS_BY_CATEGORY, COOKIE_INFO_BY_INTEGRATION, INTEGRATION_DEFAULT_CATEGORY, COOKIE_CATALOG_OVERRIDES, COOKIE_CATEGORY_OVERRIDES;
85
- var init_cookieRegistry = __esm({
86
- "src/utils/cookieRegistry.ts"() {
87
- "use strict";
88
- COOKIE_PATTERNS_BY_CATEGORY = {
89
- necessary: ["cookieConsent"],
90
- analytics: ["_ga", "_ga_*", "_gid", "_gcl_au", "_hj*", "mp_*", "_clck", "_clsk"],
91
- functional: ["intercom-*", "__zlcmid", "_zendesk_shared_session", "_userway_*"],
92
- marketing: ["_fbp", "fr"],
93
- social: [],
94
- personalization: []
95
- };
96
- COOKIE_INFO_BY_INTEGRATION = {
97
- "google-analytics": [
98
- {
99
- name: "_ga",
100
- purpose: "Identifica\xE7\xE3o \xFAnica de visitantes para an\xE1lise de tr\xE1fego",
101
- duration: "2 anos",
102
- provider: "Google Analytics"
103
- },
104
- {
105
- name: "_ga_*",
106
- purpose: "Rastreamento de sess\xF5es e eventos espec\xEDficos do stream GA4",
107
- duration: "2 anos",
108
- provider: "Google Analytics"
109
- },
110
- {
111
- name: "_gid",
112
- purpose: "Distin\xE7\xE3o de visitantes \xFAnicos em per\xEDodo de 24h",
113
- duration: "24 horas",
114
- provider: "Google Analytics"
115
- }
116
- ],
117
- "google-tag-manager": [
118
- {
119
- name: "_gcl_au",
120
- purpose: "Rastreamento de convers\xF5es de an\xFAncios",
121
- duration: "90 dias",
122
- provider: "Google"
123
- }
124
- ],
125
- hotjar: [
126
- {
127
- name: "_hjSession_*",
128
- purpose: "Rastreamento de sess\xE3o",
129
- duration: "30 minutos",
130
- provider: "Hotjar"
131
- },
132
- {
133
- name: "_hjSessionUser_*",
134
- purpose: "Persist\xEAncia de usu\xE1rio entre sess\xF5es",
135
- duration: "365 dias",
136
- provider: "Hotjar"
137
- },
138
- {
139
- name: "_hjFirstSeen",
140
- purpose: "Detec\xE7\xE3o da primeira visita do usu\xE1rio",
141
- duration: "Sess\xE3o",
142
- provider: "Hotjar"
143
- }
144
- ],
145
- mixpanel: [
146
- {
147
- name: "mp_*",
148
- purpose: "Rastreamento de eventos e propriedades do usu\xE1rio para analytics",
149
- duration: "1 ano",
150
- provider: "Mixpanel"
151
- }
152
- ],
153
- clarity: [
154
- {
155
- name: "_clck",
156
- purpose: "Identificador de usu\xE1rio",
157
- duration: "365 dias",
158
- provider: "Microsoft"
159
- },
160
- { name: "_clsk", purpose: "Rastreamento de sess\xE3o", duration: "1 dia", provider: "Microsoft" }
161
- ],
162
- intercom: [
163
- {
164
- name: "intercom-id-*",
165
- purpose: "Identificador do usu\xE1rio",
166
- duration: "9 meses",
167
- provider: "Intercom"
168
- },
169
- {
170
- name: "intercom-session-*",
171
- purpose: "Gerenciamento de sess\xE3o",
172
- duration: "1 semana",
173
- provider: "Intercom"
174
- }
175
- ],
176
- "zendesk-chat": [
177
- {
178
- name: "__zlcmid",
179
- purpose: "Identificador de sess\xE3o de chat",
180
- duration: "1 ano",
181
- provider: "Zendesk"
182
- },
183
- {
184
- name: "_zendesk_shared_session",
185
- purpose: "Gerenciamento de sess\xE3o",
186
- duration: "Sess\xE3o",
187
- provider: "Zendesk"
188
- }
189
- ],
190
- userway: [
191
- {
192
- name: "_userway_*",
193
- purpose: "Prefer\xEAncias de acessibilidade",
194
- duration: "1 ano",
195
- provider: "UserWay"
196
- }
197
- ],
198
- "facebook-pixel": [
199
- { name: "_fbp", purpose: "Rastreamento de an\xFAncios", duration: "90 dias", provider: "Meta" },
200
- { name: "fr", purpose: "Direcionamento de an\xFAncios", duration: "90 dias", provider: "Meta" }
201
- ]
202
- };
203
- INTEGRATION_DEFAULT_CATEGORY = {
204
- "google-analytics": "analytics",
205
- "google-tag-manager": "analytics",
206
- hotjar: "analytics",
207
- mixpanel: "analytics",
208
- clarity: "analytics",
209
- intercom: "functional",
210
- "zendesk-chat": "functional",
211
- userway: "functional",
212
- "facebook-pixel": "marketing"
213
- };
214
- COOKIE_CATALOG_OVERRIDES = {};
215
- COOKIE_CATEGORY_OVERRIDES = {};
216
- }
217
- });
1
+ 'use strict';
218
2
 
219
- // src/utils/cookieDiscovery.ts
220
- function discoverRuntimeCookies() {
221
- if (typeof document === "undefined" || !document.cookie) return [];
222
- const names = Array.from(
223
- new Set(
224
- document.cookie.split(";").map((s) => s.trim()).filter(Boolean).map((s) => s.split("=")[0])
225
- )
226
- );
227
- const list = names.map((name) => ({ name }));
228
- try {
229
- ;
230
- globalThis.__LGPD_DISCOVERED_COOKIES__ = list;
231
- } catch {
232
- }
233
- return list;
234
- }
235
- function detectConsentCookieName() {
236
- if (typeof document === "undefined" || !document.cookie) return null;
237
- try {
238
- const pairs = document.cookie.split(";").map((s) => s.trim()).filter(Boolean);
239
- for (const p of pairs) {
240
- const [name, ...rest] = p.split("=");
241
- const raw = rest.join("=");
242
- if (!raw) continue;
243
- let val = raw;
244
- try {
245
- val = decodeURIComponent(raw);
246
- } catch {
247
- }
248
- if (val.startsWith("{")) {
249
- try {
250
- const obj = JSON.parse(val);
251
- if (obj && typeof obj === "object" && "preferences" in obj && "version" in obj) {
252
- return name;
253
- }
254
- } catch {
255
- }
256
- }
257
- }
258
- } catch {
259
- }
260
- return null;
261
- }
262
- function categorizeDiscoveredCookies(discovered, registerOverrides = false) {
263
- const list = discovered || globalThis.__LGPD_DISCOVERED_COOKIES__ || [];
264
- const out = {};
265
- function matchPattern2(name, pattern) {
266
- if (pattern.endsWith("*")) return name.startsWith(pattern.slice(0, -1));
267
- return name === pattern;
268
- }
269
- list.filter((d) => d.name && d.name !== "cookieConsent").forEach((d) => {
270
- let assigned = null;
271
- Object.keys(COOKIE_PATTERNS_BY_CATEGORY).forEach((cat2) => {
272
- if (assigned) return;
273
- const patterns = COOKIE_PATTERNS_BY_CATEGORY[cat2] || [];
274
- if (patterns.some((p) => matchPattern2(d.name, p))) assigned = cat2;
275
- });
276
- const cat = assigned || "analytics";
277
- out[cat] = out[cat] || [];
278
- if (!out[cat].find((x) => x.name === d.name)) out[cat].push(d);
279
- });
280
- if (registerOverrides) {
281
- const byCategory = {};
282
- Object.entries(out).forEach(([cat, cookies]) => {
283
- byCategory[cat] = cookies;
284
- });
285
- setCookieCatalogOverrides({ byCategory });
286
- }
287
- return out;
288
- }
289
- var init_cookieDiscovery = __esm({
290
- "src/utils/cookieDiscovery.ts"() {
291
- "use strict";
292
- init_cookieRegistry();
293
- }
294
- });
3
+ var chunkFJKRAERJ_cjs = require('./chunk-FJKRAERJ.cjs');
4
+ var chunk25XEI2DZ_cjs = require('./chunk-25XEI2DZ.cjs');
5
+ var chunkORI4PLVG_cjs = require('./chunk-ORI4PLVG.cjs');
6
+ var jsxRuntime = require('react/jsx-runtime');
7
+ var styles = require('@mui/material/styles');
8
+ var React = require('react');
295
9
 
296
- // src/utils/logger.ts
297
- function setDebugLogging(enabled, level = 2 /* INFO */) {
298
- logger.setEnabled(enabled);
299
- logger.setLevel(level);
300
- logger.info(`Debug logging ${enabled ? "enabled" : "disabled"} with level ${LogLevel[level]}`);
301
- }
302
- var LogLevel, _ConsentLogger, ConsentLogger, logger;
303
- var init_logger = __esm({
304
- "src/utils/logger.ts"() {
305
- "use strict";
306
- LogLevel = /* @__PURE__ */ ((LogLevel2) => {
307
- LogLevel2[LogLevel2["ERROR"] = 0] = "ERROR";
308
- LogLevel2[LogLevel2["WARN"] = 1] = "WARN";
309
- LogLevel2[LogLevel2["INFO"] = 2] = "INFO";
310
- LogLevel2[LogLevel2["DEBUG"] = 3] = "DEBUG";
311
- return LogLevel2;
312
- })(LogLevel || {});
313
- _ConsentLogger = class _ConsentLogger {
314
- constructor() {
315
- this.enabled = _ConsentLogger.IS_DEVELOPMENT;
316
- this.level = 2 /* INFO */;
317
- }
318
- /**
319
- * Habilita ou desabilita o sistema de logging.
320
- * @param {boolean} enabled Se `true`, os logs serão exibidos; caso contrário, serão suprimidos.
321
- */
322
- setEnabled(enabled) {
323
- this.enabled = enabled;
324
- }
325
- /**
326
- * Define o nível mínimo de severidade para os logs.
327
- * Mensagens com severidade menor que o nível definido não serão exibidas.
328
- * @param {LogLevel} level O nível mínimo de severidade (ex: `LogLevel.DEBUG` para ver todos os logs).
329
- */
330
- setLevel(level) {
331
- this.level = level;
332
- }
333
- /**
334
- * Registra uma mensagem de erro.
335
- * @param {...unknown[]} args Argumentos a serem logados.
336
- */
337
- error(...args) {
338
- if (this.enabled && this.level >= 0 /* ERROR */) {
339
- console.error(_ConsentLogger.LOG_PREFIX, "[ERROR]", ...args);
340
- }
341
- }
342
- /**
343
- * Registra uma mensagem de aviso.
344
- * @param {...unknown[]} args Argumentos a serem logados.
345
- */
346
- warn(...args) {
347
- if (this.enabled && this.level >= 1 /* WARN */) {
348
- console.warn(_ConsentLogger.LOG_PREFIX, "[WARN]", ...args);
349
- }
350
- }
351
- /**
352
- * Registra uma mensagem informativa.
353
- * @param {...unknown[]} args Argumentos a serem logados.
354
- */
355
- info(...args) {
356
- if (this.enabled && this.level >= 2 /* INFO */) {
357
- console.info(_ConsentLogger.LOG_PREFIX, "[INFO]", ...args);
358
- }
359
- }
360
- /**
361
- * Registra uma mensagem de depuração.
362
- * @param {...unknown[]} args Argumentos a serem logados.
363
- */
364
- debug(...args) {
365
- if (this.enabled && this.level >= 3 /* DEBUG */) {
366
- console.debug(_ConsentLogger.LOG_PREFIX, "[DEBUG]", ...args);
367
- }
368
- }
369
- /**
370
- * Inicia um grupo de logs no console.
371
- * @param {...unknown[]} args Argumentos para o título do grupo.
372
- */
373
- group(...args) {
374
- if (this.enabled && this.level >= 3 /* DEBUG */) {
375
- console.group(_ConsentLogger.LOG_PREFIX, ...args);
376
- }
377
- }
378
- /**
379
- * Finaliza o grupo de logs mais recente no console.
380
- */
381
- groupEnd() {
382
- if (this.enabled && this.level >= 3 /* DEBUG */) {
383
- console.groupEnd();
384
- }
385
- }
386
- /**
387
- * Exibe dados tabulares no console.
388
- * @param {unknown} tabularData Dados a serem exibidos na tabela.
389
- * @param {string[]} [properties] Propriedades opcionais para exibir.
390
- */
391
- table(tabularData, properties) {
392
- if (this.enabled && this.level >= 3 /* DEBUG */) {
393
- console.table(tabularData, properties);
394
- }
395
- }
396
- /**
397
- * Registra informações sobre a compatibilidade do tema Material-UI.
398
- * @param {unknown} themeInfo Objeto potencialmente parcial do tema (inspeção segura).
399
- */
400
- themeCompatibility(themeInfo) {
401
- const isRecord = (v) => typeof v === "object" && v !== null;
402
- const theme = isRecord(themeInfo) ? themeInfo : void 0;
403
- const palette = theme && isRecord(theme["palette"]) ? theme["palette"] : void 0;
404
- const primary = palette && isRecord(palette["primary"]);
405
- const transitions = theme && isRecord(theme["transitions"]) ? theme["transitions"] : void 0;
406
- const duration = transitions && isRecord(transitions["duration"]);
407
- this.debug("Theme compatibility check:", {
408
- hasTheme: !!theme,
409
- hasPalette: !!palette,
410
- hasPrimary: !!primary,
411
- hasTransitions: !!transitions,
412
- hasDuration: !!duration
413
- });
414
- }
415
- /**
416
- * Registra mudanças no estado de consentimento.
417
- * @param {string} action Ação que causou a mudança de estado.
418
- * @param {{ consented?: boolean; isModalOpen?: boolean; preferences?: Record<string, unknown> }} state Estado atual.
419
- */
420
- consentState(action, state) {
421
- this.debug(`Consent state change [${action}]:`, {
422
- consented: state.consented,
423
- isModalOpen: state.isModalOpen,
424
- preferencesCount: Object.keys(state.preferences || {}).length
425
- });
426
- }
427
- /**
428
- * Registra operações de cookie (leitura, escrita, remoção).
429
- * @param {'read' | 'write' | 'delete'} operation Tipo de operação.
430
- * @param {string} cookieName Nome do cookie.
431
- * @param {unknown} [data] Dados associados, se aplicável.
432
- */
433
- cookieOperation(operation, cookieName, data) {
434
- this.debug(`Cookie ${operation}:`, {
435
- name: cookieName,
436
- hasData: !!data,
437
- dataSize: data ? JSON.stringify(data).length : 0
438
- });
439
- }
440
- /**
441
- * Registra a renderização de um componente.
442
- * @param {string} componentName Nome do componente.
443
- * @param {Record<string, unknown>} [props] Propriedades do componente.
444
- */
445
- componentRender(componentName, props) {
446
- this.debug(`Component render [${componentName}]:`, {
447
- hasProps: !!props,
448
- propsKeys: props ? Object.keys(props) : []
10
+ function _interopNamespace(e) {
11
+ if (e && e.__esModule) return e;
12
+ var n = Object.create(null);
13
+ if (e) {
14
+ Object.keys(e).forEach(function (k) {
15
+ if (k !== 'default') {
16
+ var d = Object.getOwnPropertyDescriptor(e, k);
17
+ Object.defineProperty(n, k, d.get ? d : {
18
+ enumerable: true,
19
+ get: function () { return e[k]; }
449
20
  });
450
21
  }
451
- /**
452
- * Registra o status de carregamento de scripts de integração.
453
- * @param {string} scriptName O nome do script.
454
- * @param {'load' | 'remove'} action A ação realizada (carregar ou remover).
455
- * @param {boolean} success Se a operação foi bem-sucedida.
456
- */
457
- scriptIntegration(scriptName, action, success) {
458
- this.info(`Script ${action} [${scriptName}]:`, success ? "SUCCESS" : "FAILED");
459
- }
460
- /**
461
- * Registra chamadas à API interna da biblioteca.
462
- * @param {string} method Nome do método da API chamado.
463
- * @param {unknown} [params] Parâmetros passados para o método.
464
- */
465
- apiUsage(method, params) {
466
- this.debug(`API call [${method}]:`, params);
467
- }
468
- };
469
- _ConsentLogger.IS_DEVELOPMENT = typeof globalThis !== "undefined" && globalThis.process?.env?.NODE_ENV === "development";
470
- _ConsentLogger.LOG_PREFIX = "[react-lgpd-consent]";
471
- ConsentLogger = _ConsentLogger;
472
- logger = new ConsentLogger();
473
- }
474
- });
475
-
476
- // src/utils/cookieUtils.ts
477
- function readConsentCookie(name = DEFAULT_COOKIE_OPTS.name) {
478
- logger.debug("Reading consent cookie", { name });
479
- if (typeof document === "undefined") {
480
- logger.debug("Cookie read skipped: server-side environment");
481
- return null;
482
- }
483
- const raw = import_js_cookie.default.get(name);
484
- if (!raw) {
485
- logger.debug("No consent cookie found");
486
- return null;
487
- }
488
- try {
489
- const data = JSON.parse(raw);
490
- logger.cookieOperation("read", name, data);
491
- if (!data.version) {
492
- logger.debug("Migrating legacy cookie format");
493
- return migrateLegacyCookie(data);
494
- }
495
- if (data.version !== COOKIE_SCHEMA_VERSION) {
496
- logger.warn(`Cookie version mismatch: ${data.version} != ${COOKIE_SCHEMA_VERSION}`);
497
- return null;
498
- }
499
- return data;
500
- } catch (error) {
501
- logger.error("Error parsing consent cookie", error);
502
- return null;
503
- }
504
- }
505
- function migrateLegacyCookie(legacyData) {
506
- try {
507
- const now = (/* @__PURE__ */ new Date()).toISOString();
508
- return {
509
- version: COOKIE_SCHEMA_VERSION,
510
- consented: Boolean(legacyData.consented) || false,
511
- preferences: legacyData.preferences && typeof legacyData.preferences === "object" ? legacyData.preferences : { necessary: true },
512
- consentDate: now,
513
- lastUpdate: now,
514
- source: "banner",
515
- isModalOpen: false
516
- };
517
- } catch {
518
- return null;
519
- }
520
- }
521
- function writeConsentCookie(state, config, opts, source = "banner") {
522
- if (typeof document === "undefined") {
523
- logger.debug("Cookie write skipped: server-side environment");
524
- return;
525
- }
526
- const now = (/* @__PURE__ */ new Date()).toISOString();
527
- const o = { ...DEFAULT_COOKIE_OPTS, ...opts };
528
- const cookieData = {
529
- version: COOKIE_SCHEMA_VERSION,
530
- consented: state.consented,
531
- preferences: state.preferences,
532
- consentDate: state.consentDate || now,
533
- lastUpdate: now,
534
- source,
535
- projectConfig: config
536
- };
537
- logger.cookieOperation("write", o.name, cookieData);
538
- import_js_cookie.default.set(o.name, JSON.stringify(cookieData), {
539
- expires: o.maxAgeDays,
540
- sameSite: o.sameSite,
541
- secure: o.secure,
542
- path: o.path
543
- });
544
- logger.info("Consent cookie saved", {
545
- consented: cookieData.consented,
546
- source: cookieData.source,
547
- preferencesCount: Object.keys(cookieData.preferences).length
548
- });
549
- }
550
- function removeConsentCookie(opts) {
551
- if (typeof document === "undefined") {
552
- logger.debug("Cookie removal skipped: server-side environment");
553
- return;
554
- }
555
- const o = { ...DEFAULT_COOKIE_OPTS, ...opts };
556
- logger.cookieOperation("delete", o.name);
557
- import_js_cookie.default.remove(o.name, { path: o.path });
558
- logger.info("Consent cookie removed");
559
- }
560
- var import_js_cookie, DEFAULT_COOKIE_OPTS, COOKIE_SCHEMA_VERSION;
561
- var init_cookieUtils = __esm({
562
- "src/utils/cookieUtils.ts"() {
563
- "use strict";
564
- import_js_cookie = __toESM(require("js-cookie"), 1);
565
- init_logger();
566
- DEFAULT_COOKIE_OPTS = {
567
- name: "cookieConsent",
568
- maxAgeDays: 365,
569
- sameSite: "Lax",
570
- secure: typeof window !== "undefined" ? window.location.protocol === "https:" : false,
571
- path: "/"
572
- };
573
- COOKIE_SCHEMA_VERSION = "1.0";
574
- }
575
- });
576
-
577
- // src/utils/developerGuidance.ts
578
- function calculateComplianceScore(guidance) {
579
- let score = 0;
580
- const maxScore = 100;
581
- if (!guidance.usingDefaults) score += 30;
582
- const totalCategories = guidance.activeCategoriesInfo.length;
583
- const toggleableCategories = guidance.activeCategoriesInfo.filter((c) => c.uiRequired).length;
584
- if (totalCategories > 1) score += 20;
585
- if (toggleableCategories >= 2 && toggleableCategories <= 4) score += 25;
586
- const criticalWarnings = guidance.messages.filter((m) => m.severity === "error").length;
587
- const warnings = guidance.messages.filter((m) => m.severity === "warning").length;
588
- if (criticalWarnings === 0) score += 15;
589
- if (warnings === 0) score += 10;
590
- return Math.min(score, maxScore);
591
- }
592
- function analyzeDeveloperConfiguration(config) {
593
- const guidance = {
594
- warnings: [],
595
- suggestions: [],
596
- messages: [],
597
- activeCategoriesInfo: [],
598
- usingDefaults: !config,
599
- complianceScore: 0
600
- };
601
- const addMessage = (severity, message, category, actionable = true) => {
602
- const guidanceMessage = { severity, message, category, actionable };
603
- guidance.messages.push(guidanceMessage);
604
- if (severity === "warning" || severity === "error") {
605
- guidance.warnings.push(message);
606
- } else {
607
- guidance.suggestions.push(message);
608
- }
609
- };
610
- const finalConfig = config || DEFAULT_PROJECT_CATEGORIES;
611
- if (!config) {
612
- addMessage(
613
- "warning",
614
- 'LGPD-CONSENT: Nenhuma configura\xE7\xE3o de categorias especificada. Usando padr\xE3o: necessary + analytics. Para produ\xE7\xE3o, especifique explicitamente as categorias via prop "categories".',
615
- "configuration"
616
- );
617
- }
618
- guidance.activeCategoriesInfo.push({
619
- id: "necessary",
620
- name: "Cookies Necess\xE1rios",
621
- description: "Essenciais para funcionamento b\xE1sico do site",
622
- essential: true,
623
- uiRequired: false,
624
- cookies: COOKIE_PATTERNS_BY_CATEGORY["necessary"]
625
- });
626
- const enabled = finalConfig.enabledCategories || [];
627
- const NAMES = {
628
- analytics: { name: "Cookies Anal\xEDticos", description: "Medem uso e performance do site" },
629
- functional: {
630
- name: "Cookies Funcionais",
631
- description: "Melhoram experi\xEAncia e funcionalidades"
632
- },
633
- marketing: { name: "Cookies de Marketing", description: "Publicidade direcionada e campanhas" },
634
- social: { name: "Cookies de Redes Sociais", description: "Integra\xE7\xE3o com plataformas sociais" },
635
- personalization: { name: "Cookies de Personaliza\xE7\xE3o", description: "Adapta\xE7\xE3o de conte\xFAdo" }
636
- };
637
- enabled.forEach((id) => {
638
- const info = NAMES[id];
639
- if (info) {
640
- guidance.activeCategoriesInfo.push({
641
- id,
642
- name: info.name,
643
- description: info.description,
644
- essential: false,
645
- uiRequired: true,
646
- cookies: COOKIE_PATTERNS_BY_CATEGORY[id]
647
- });
648
- }
649
- });
650
- const custom = finalConfig.customCategories || [];
651
- custom.forEach((cat) => {
652
- if (!cat?.id || cat.id === "necessary") return;
653
- guidance.activeCategoriesInfo.push({
654
- id: cat.id,
655
- name: cat.name,
656
- description: cat.description,
657
- essential: !!cat.essential,
658
- uiRequired: !cat.essential,
659
- cookies: cat.cookies
660
- });
661
- });
662
- try {
663
- const gt = globalThis;
664
- const implied = (gt.__LGPD_REQUIRED_CATEGORIES__ || []).filter(Boolean);
665
- implied.forEach((id) => {
666
- if (!guidance.activeCategoriesInfo.find((c) => c.id === id)) {
667
- const info = NAMES[id];
668
- if (info) {
669
- guidance.activeCategoriesInfo.push({
670
- id,
671
- name: info.name,
672
- description: info.description,
673
- essential: false,
674
- uiRequired: true,
675
- cookies: COOKIE_PATTERNS_BY_CATEGORY[id]
676
- });
677
- if (!enabled.includes(id)) {
678
- addMessage(
679
- "info",
680
- `Integra\xE7\xF5es detectadas requerem a categoria '${id}'. Adicione-a em categories.enabledCategories.`,
681
- "integration"
682
- );
683
- }
684
- }
685
- }
686
22
  });
687
- } catch {
688
- }
689
- try {
690
- const gt2 = globalThis;
691
- const used = gt2.__LGPD_USED_INTEGRATIONS__ || [];
692
- guidance.activeCategoriesInfo = guidance.activeCategoriesInfo.map((c) => {
693
- const info = getCookiesInfoForCategory(c.id, used);
694
- const names = Array.from(/* @__PURE__ */ new Set([...c.cookies || [], ...info.map((d) => d.name)]));
695
- return { ...c, cookies: names };
696
- });
697
- } catch {
698
- }
699
- const totalToggleable = guidance.activeCategoriesInfo.filter((c) => c.uiRequired).length;
700
- if (totalToggleable === 0) {
701
- addMessage(
702
- "info",
703
- 'Apenas cookies necess\xE1rios est\xE3o configurados. Para compliance LGPD, considere adicionar categorias como "analytics" ou "functional" conforme uso real.',
704
- "compliance"
705
- );
706
- }
707
- if (totalToggleable > 5) {
708
- addMessage(
709
- "warning",
710
- `${totalToggleable} categorias opcionais detectadas. UI com muitas op\xE7\xF5es pode prejudicar a experi\xEAncia. Considere agrupar categorias similares.`,
711
- "usability"
712
- );
713
- }
714
- guidance.complianceScore = calculateComplianceScore(guidance);
715
- return guidance;
716
- }
717
- function getComplianceScoreColor(score) {
718
- if (score >= 80) return "#4caf50";
719
- if (score >= 60) return "#ff9800";
720
- return "#f44336";
721
- }
722
- function logComplianceScore(prefix, score) {
723
- const color = getComplianceScoreColor(score);
724
- console.log(
725
- `%c${prefix} Score de Conformidade LGPD: ${score}/100`,
726
- `color: ${color}; font-weight: bold; font-size: 14px;`
727
- );
728
- }
729
- function logMessagesByType(prefix, messages, type, config) {
730
- const filteredMessages = messages.filter((m) => m.severity === type);
731
- if (filteredMessages.length === 0) return false;
732
- const typeConfig = {
733
- error: {
734
- show: config.showWarnings,
735
- title: "Erros Cr\xEDticos",
736
- color: "#d32f2f",
737
- method: console.error
738
- },
739
- warning: {
740
- show: config.showWarnings,
741
- title: "Avisos de Configura\xE7\xE3o",
742
- color: "#f57c00",
743
- method: console.warn
744
- },
745
- info: {
746
- show: config.showSuggestions,
747
- title: "Sugest\xF5es",
748
- color: "#2196f3",
749
- method: console.info
750
- }
751
- };
752
- const typeSettings = typeConfig[type];
753
- if (!typeSettings.show) return false;
754
- console.group(
755
- `%c${prefix} ${typeSettings.title}`,
756
- `color: ${typeSettings.color}; font-weight: bold;`
757
- );
758
- filteredMessages.forEach(
759
- (msg) => typeSettings.method(
760
- `%c${prefix}%c ${msg.message}`,
761
- `color: ${typeSettings.color};`,
762
- "color: #333;"
763
- )
764
- );
765
- console.groupEnd();
766
- return true;
767
- }
768
- function getGuidanceHash(guidance) {
769
- const sortedWarnings = [...guidance.warnings].sort((a, b) => a.localeCompare(b));
770
- const sortedSuggestions = [...guidance.suggestions].sort(
771
- (a, b) => a.localeCompare(b)
772
- );
773
- const sortedCategories = guidance.activeCategoriesInfo.map((c) => c.id).sort((a, b) => a.localeCompare(b));
774
- return JSON.stringify({
775
- warnings: sortedWarnings,
776
- suggestions: sortedSuggestions,
777
- categories: sortedCategories,
778
- usingDefaults: guidance.usingDefaults
779
- });
780
- }
781
- function logIntroOnce() {
782
- if (SESSION_LOGGED.intro) return;
783
- SESSION_LOGGED.intro = true;
784
- console.log(
785
- `%c\u{1F36A} LGPD-CONSENT %c- Sistema de Consentimento Ativo`,
786
- "background: #4caf50; color: white; padding: 4px 8px; border-radius: 4px; font-weight: bold;",
787
- "color: #2e7d32; font-weight: 500;"
788
- );
789
- }
790
- function logServerSideIfAvailable(guidance) {
791
- try {
792
- const gt = globalThis;
793
- if (gt.process?.stdout?.write) {
794
- const prefix = "\x1B[36m[LGPD-CONSENT]\x1B[0m";
795
- const warnings = guidance.warnings.length;
796
- const suggestions = guidance.suggestions.length;
797
- const stdout = gt.process.stdout;
798
- if (warnings > 0 || suggestions > 0) {
799
- stdout.write(`${prefix} \u{1F527} Config: ${warnings} avisos, ${suggestions} sugest\xF5es
800
- `);
801
- if (warnings > 0) {
802
- guidance.warnings.forEach((w) => {
803
- stdout.write(`${prefix} \x1B[33m\u26A0\uFE0F ${w}\x1B[0m
804
- `);
805
- });
806
- }
807
- if (suggestions > 0) {
808
- guidance.suggestions.forEach((s) => {
809
- stdout.write(`${prefix} \x1B[36m\u{1F4A1} ${s}\x1B[0m
810
- `);
811
- });
812
- }
813
- }
814
- }
815
- } catch {
816
- }
817
- }
818
- function logDeveloperGuidance(guidance, disableGuidanceProp, config) {
819
- const gt = globalThis;
820
- const nodeEnv = typeof gt.process !== "undefined" ? gt.process?.env?.NODE_ENV : void 0;
821
- const isProd = nodeEnv === "production" || gt.__LGPD_PRODUCTION__ === true;
822
- if (isProd || disableGuidanceProp) return;
823
- const guidanceHash = getGuidanceHash(guidance);
824
- if (GUIDANCE_CACHE.has(guidanceHash)) return;
825
- GUIDANCE_CACHE.add(guidanceHash);
826
- logServerSideIfAvailable(guidance);
827
- const guidanceConfig = {
828
- showWarnings: true,
829
- showSuggestions: true,
830
- showCategoriesTable: true,
831
- showBestPractices: true,
832
- showComplianceScore: true,
833
- minimumSeverity: "info",
834
- ...config
835
- };
836
- if (guidanceConfig.messageProcessor) {
837
- guidanceConfig.messageProcessor(guidance.messages);
838
- return;
839
- }
840
- logIntroOnce();
841
- const PREFIX = "\u{1F36A}";
842
- let hasImportantInfo = false;
843
- const filteredMessages = guidance.messages.filter((msg) => {
844
- const severityLevels = { info: 0, warning: 1, error: 2 };
845
- const minLevel = severityLevels[guidanceConfig.minimumSeverity || "info"];
846
- const msgLevel = severityLevels[msg.severity];
847
- return msgLevel >= minLevel;
848
- });
849
- hasImportantInfo = logMessagesByType(PREFIX, filteredMessages, "error", guidanceConfig) || hasImportantInfo;
850
- hasImportantInfo = logMessagesByType(PREFIX, filteredMessages, "warning", guidanceConfig) || hasImportantInfo;
851
- if (hasImportantInfo || guidance.usingDefaults) {
852
- hasImportantInfo = logMessagesByType(PREFIX, filteredMessages, "info", guidanceConfig) || hasImportantInfo;
853
- }
854
- if (guidanceConfig.showComplianceScore && guidance.complianceScore !== void 0) {
855
- logComplianceScore(PREFIX, guidance.complianceScore);
856
- }
857
- if (guidanceConfig.showCategoriesTable && (hasImportantInfo || guidance.usingDefaults)) {
858
- const rows = guidance.activeCategoriesInfo.map((cat) => ({
859
- "\u{1F4CA} Categoria": cat.id,
860
- "\u{1F3F7}\uFE0F Nome": cat.name,
861
- "\u{1F39B}\uFE0F UI": cat.uiRequired ? "\u2705" : "\u{1F512}",
862
- "\u{1F36A} Cookies": (cat.cookies || []).slice(0, 3).join(", ") + (cat.cookies && cat.cookies.length > 3 ? ` (+${cat.cookies.length - 3})` : "")
863
- }));
864
- if (typeof console.table === "function") {
865
- console.group(`%c${PREFIX} Configura\xE7\xE3o Ativa`, "color: #4caf50; font-weight: bold;");
866
- console.table(rows);
867
- console.groupEnd();
868
- }
869
- }
870
- if (!SESSION_LOGGED.bestPractices && hasImportantInfo) {
871
- SESSION_LOGGED.bestPractices = true;
872
- console.group(`%c${PREFIX} LGPD - Boas Pr\xE1ticas`, "color: #9c27b0; font-weight: bold;");
873
- console.info(
874
- `%c${PREFIX}%c Necessary: sempre ativo \u2022 Demais: opt-out por padr\xE3o`,
875
- "color: #9c27b0;",
876
- "color: #7b1fa2;"
877
- );
878
- console.info(
879
- `%c${PREFIX}%c Documente pol\xEDticas claras por categoria`,
880
- "color: #9c27b0;",
881
- "color: #7b1fa2;"
882
- );
883
- console.info(
884
- `%c${PREFIX}%c Registre consentimento com data/hora/origem`,
885
- "color: #9c27b0;",
886
- "color: #7b1fa2;"
887
- );
888
- console.groupEnd();
889
- }
890
- }
891
- function useDeveloperGuidance(config, disableGuidanceProp, guidanceConfig) {
892
- const guidance = import_react.default.useMemo(() => analyzeDeveloperConfiguration(config), [config]);
893
- import_react.default.useEffect(() => {
894
- if (!disableGuidanceProp) logDeveloperGuidance(guidance, disableGuidanceProp, guidanceConfig);
895
- }, [guidance, disableGuidanceProp, guidanceConfig]);
896
- return guidance;
897
- }
898
- var import_react, DEFAULT_PROJECT_CATEGORIES, GUIDANCE_CACHE, SESSION_LOGGED, GUIDANCE_PRESETS;
899
- var init_developerGuidance = __esm({
900
- "src/utils/developerGuidance.ts"() {
901
- "use strict";
902
- import_react = __toESM(require("react"), 1);
903
- init_cookieRegistry();
904
- DEFAULT_PROJECT_CATEGORIES = {
905
- enabledCategories: ["analytics"]
906
- };
907
- GUIDANCE_CACHE = /* @__PURE__ */ new Set();
908
- SESSION_LOGGED = {
909
- intro: false,
910
- bestPractices: false
911
- };
912
- GUIDANCE_PRESETS = {
913
- /** Configuração completa para desenvolvimento */
914
- development: {
915
- showWarnings: true,
916
- showSuggestions: true,
917
- showCategoriesTable: true,
918
- showBestPractices: true,
919
- showComplianceScore: true,
920
- minimumSeverity: "info"
921
- },
922
- /** Configuração silenciosa para produção */
923
- production: {
924
- showWarnings: false,
925
- showSuggestions: false,
926
- showCategoriesTable: false,
927
- showBestPractices: false,
928
- showComplianceScore: false,
929
- minimumSeverity: "error"
930
- },
931
- /** Apenas erros críticos */
932
- minimal: {
933
- showWarnings: true,
934
- showSuggestions: false,
935
- showCategoriesTable: false,
936
- showBestPractices: false,
937
- showComplianceScore: false,
938
- minimumSeverity: "error"
939
- },
940
- /** Focado em conformidade LGPD */
941
- compliance: {
942
- showWarnings: true,
943
- showSuggestions: true,
944
- showCategoriesTable: true,
945
- showBestPractices: true,
946
- showComplianceScore: true,
947
- minimumSeverity: "warning"
948
- }
949
- };
950
- }
951
- });
952
-
953
- // src/context/CategoriesContext.tsx
954
- function CategoriesProvider({
955
- children,
956
- config,
957
- disableDeveloperGuidance,
958
- disableDiscoveryLog
959
- }) {
960
- const [impliedVersion, setImpliedVersion] = React2.useState(0);
961
- React2.useEffect(() => {
962
- const handler = () => setImpliedVersion((v) => v + 1);
963
- if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
964
- window.addEventListener("lgpd:requiredCategories", handler);
965
- return () => window.removeEventListener("lgpd:requiredCategories", handler);
966
- }
967
- return () => {
968
- };
969
- }, []);
970
- const contextValue = React2.useMemo(() => {
971
- const finalConfig = config || DEFAULT_PROJECT_CATEGORIES;
972
- const guidance = analyzeDeveloperConfiguration(config);
973
- const toggleableCategories = guidance.activeCategoriesInfo.filter((cat) => cat.uiRequired);
974
- return {
975
- config: finalConfig,
976
- guidance,
977
- toggleableCategories,
978
- allCategories: guidance.activeCategoriesInfo
979
- };
980
- }, [config, impliedVersion]);
981
- React2.useEffect(() => {
982
- logDeveloperGuidance(contextValue.guidance, disableDeveloperGuidance);
983
- }, [contextValue.guidance, disableDeveloperGuidance]);
984
- React2.useEffect(() => {
985
- try {
986
- const gt = globalThis;
987
- const env = typeof gt.process !== "undefined" ? gt.process?.env?.NODE_ENV : void 0;
988
- const isDev = env === "development";
989
- if (!isDev || gt.__LGPD_DISCOVERY_LOGGED__ === true || disableDiscoveryLog) return;
990
- const discovered = discoverRuntimeCookies();
991
- const consentName = detectConsentCookieName() || DEFAULT_COOKIE_OPTS.name;
992
- const PREFIX = "[\u{1F36A} LGPD-CONSENT]";
993
- if (typeof console !== "undefined") {
994
- try {
995
- console.group(`${PREFIX} \u{1F50E} Descoberta de cookies (experimental)`);
996
- const names = Array.from(
997
- new Set([consentName, ...discovered.map((d) => d.name)].filter(Boolean))
998
- );
999
- const rows = names.map((n) => ({ Cookie: n }));
1000
- if (typeof console.table === "function") console.table(rows);
1001
- else console.log(rows);
1002
- console.info(
1003
- `${PREFIX} \u2139\uFE0F Estes nomes s\xE3o detectados em tempo de execu\xE7\xE3o. Ajuste ou categorize via APIs de override se necess\xE1rio.`
1004
- );
1005
- console.groupEnd();
1006
- } catch {
1007
- }
1008
- }
1009
- gt.__LGPD_DISCOVERY_LOGGED__ = true;
1010
- } catch {
1011
- }
1012
- }, [disableDiscoveryLog]);
1013
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CategoriesContext.Provider, { value: contextValue, children });
1014
- }
1015
- function useCategories() {
1016
- const context = React2.useContext(CategoriesContext);
1017
- if (!context) {
1018
- throw new Error(
1019
- "useCategories deve ser usado dentro de CategoriesProvider. Certifique-se de que o ConsentProvider est\xE1 envolvendo seu componente."
1020
- );
1021
- }
1022
- return context;
1023
- }
1024
- function useCategoryStatus(categoryId) {
1025
- const { allCategories } = useCategories();
1026
- const category = allCategories.find((cat) => cat.id === categoryId);
1027
- return {
1028
- isActive: !!category,
1029
- isEssential: category?.essential || false,
1030
- needsToggle: category?.uiRequired || false,
1031
- name: category?.name,
1032
- description: category?.description
1033
- };
1034
- }
1035
- var React2, import_jsx_runtime, CategoriesContext;
1036
- var init_CategoriesContext = __esm({
1037
- "src/context/CategoriesContext.tsx"() {
1038
- "use strict";
1039
- React2 = __toESM(require("react"), 1);
1040
- init_cookieDiscovery();
1041
- init_cookieUtils();
1042
- init_developerGuidance();
1043
- import_jsx_runtime = require("react/jsx-runtime");
1044
- CategoriesContext = React2.createContext(null);
1045
- }
1046
- });
1047
-
1048
- // src/context/DesignContext.tsx
1049
- function DesignProvider({
1050
- tokens,
1051
- children
1052
- }) {
1053
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(DesignContext.Provider, { value: tokens, children });
1054
- }
1055
- function useDesignTokens() {
1056
- return React3.useContext(DesignContext);
1057
- }
1058
- var React3, import_jsx_runtime2, DesignContext;
1059
- var init_DesignContext = __esm({
1060
- "src/context/DesignContext.tsx"() {
1061
- "use strict";
1062
- React3 = __toESM(require("react"), 1);
1063
- import_jsx_runtime2 = require("react/jsx-runtime");
1064
- DesignContext = React3.createContext(void 0);
1065
- }
1066
- });
1067
-
1068
- // src/utils/categoryUtils.ts
1069
- function createProjectPreferences(config, defaultValue = false) {
1070
- const preferences = {
1071
- necessary: true
1072
- // Sempre presente e true (essencial)
1073
- };
1074
- const enabledCategories = config?.enabledCategories || [];
1075
- enabledCategories.forEach((category) => {
1076
- if (category !== "necessary") {
1077
- preferences[category] = defaultValue;
1078
- }
1079
- });
1080
- const customCategories = config?.customCategories || [];
1081
- customCategories.forEach((cat) => {
1082
- if (cat.id && cat.id !== "necessary") {
1083
- preferences[cat.id] = defaultValue;
1084
- }
1085
- });
1086
- return preferences;
1087
- }
1088
- function validateProjectPreferences(preferences, config) {
1089
- const validPreferences = {
1090
- necessary: true
1091
- // Sempre válida
1092
- };
1093
- const enabledCategories = config?.enabledCategories || [];
1094
- enabledCategories.forEach((category) => {
1095
- if (category !== "necessary" && preferences[category] !== void 0) {
1096
- validPreferences[category] = preferences[category];
1097
- }
1098
- });
1099
- const customCategories = config?.customCategories || [];
1100
- customCategories.forEach((cat) => {
1101
- const id = cat.id;
1102
- if (id && id !== "necessary" && preferences[id] !== void 0) {
1103
- validPreferences[id] = preferences[id];
1104
- }
1105
- });
1106
- return validPreferences;
1107
- }
1108
- function getAllProjectCategories(config) {
1109
- const allCategories = [
1110
- {
1111
- id: "necessary",
1112
- name: "Necess\xE1rios",
1113
- description: "Cookies essenciais para funcionamento b\xE1sico do site",
1114
- essential: true
1115
- }
1116
- ];
1117
- const enabledCategories = config?.enabledCategories || [];
1118
- enabledCategories.forEach((category) => {
1119
- if (category !== "necessary") {
1120
- allCategories.push(getDefaultCategoryDefinition(category));
1121
- }
1122
- });
1123
- const customCategories = config?.customCategories || [];
1124
- customCategories.forEach((cat) => {
1125
- if (cat.id && cat.id !== "necessary") {
1126
- allCategories.push({ ...cat, essential: !!cat.essential });
1127
- }
1128
- });
1129
- return allCategories;
1130
- }
1131
- function getDefaultCategoryDefinition(category) {
1132
- const definitions = {
1133
- necessary: {
1134
- id: "necessary",
1135
- name: "Necess\xE1rios",
1136
- description: "Cookies essenciais para funcionamento b\xE1sico do site",
1137
- essential: true
1138
- },
1139
- analytics: {
1140
- id: "analytics",
1141
- name: "An\xE1lise e Estat\xEDsticas",
1142
- description: "Cookies para an\xE1lise de uso e estat\xEDsticas do site",
1143
- essential: false
1144
- },
1145
- functional: {
1146
- id: "functional",
1147
- name: "Funcionalidades",
1148
- description: "Cookies para funcionalidades extras como prefer\xEAncias e idioma",
1149
- essential: false
1150
- },
1151
- marketing: {
1152
- id: "marketing",
1153
- name: "Marketing e Publicidade",
1154
- description: "Cookies para publicidade direcionada e marketing",
1155
- essential: false
1156
- },
1157
- social: {
1158
- id: "social",
1159
- name: "Redes Sociais",
1160
- description: "Cookies para integra\xE7\xE3o com redes sociais e compartilhamento",
1161
- essential: false
1162
- },
1163
- personalization: {
1164
- id: "personalization",
1165
- name: "Personaliza\xE7\xE3o",
1166
- description: "Cookies para personaliza\xE7\xE3o de conte\xFAdo e experi\xEAncia",
1167
- essential: false
1168
- }
1169
- };
1170
- return definitions[category];
1171
- }
1172
- var init_categoryUtils = __esm({
1173
- "src/utils/categoryUtils.ts"() {
1174
- "use strict";
1175
- }
1176
- });
1177
-
1178
- // src/components/Branding.tsx
1179
- function Branding({ variant, hidden = false }) {
1180
- const texts = useConsentTexts();
1181
- const designTokens = useDesignTokens();
1182
- if (hidden) return null;
1183
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
1184
- import_Typography.default,
1185
- {
1186
- variant: "caption",
1187
- sx: (theme) => ({
1188
- ...brandingStyles[variant],
1189
- color: designTokens?.colors?.text ?? theme.palette.text.secondary
1190
- }),
1191
- children: [
1192
- texts.brandingPoweredBy || "fornecido por",
1193
- " ",
1194
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
1195
- import_Link.default,
1196
- {
1197
- href: "https://www.ledipo.eti.br",
1198
- target: "_blank",
1199
- rel: "noopener noreferrer",
1200
- sx: (theme) => ({
1201
- ...linkStyles,
1202
- color: designTokens?.colors?.primary ?? theme.palette.primary.main
1203
- }),
1204
- children: "L\xC9dipO.eti.br"
1205
- }
1206
- )
1207
- ]
1208
- }
1209
- );
1210
- }
1211
- var import_Link, import_Typography, import_jsx_runtime3, brandingStyles, linkStyles;
1212
- var init_Branding = __esm({
1213
- "src/components/Branding.tsx"() {
1214
- "use strict";
1215
- init_useConsent();
1216
- init_DesignContext();
1217
- import_Link = __toESM(require("@mui/material/Link"), 1);
1218
- import_Typography = __toESM(require("@mui/material/Typography"), 1);
1219
- import_jsx_runtime3 = require("react/jsx-runtime");
1220
- brandingStyles = {
1221
- banner: {
1222
- fontSize: "0.65rem",
1223
- textAlign: "right",
1224
- mt: 1,
1225
- opacity: 0.7,
1226
- fontStyle: "italic",
1227
- width: "100%"
1228
- },
1229
- modal: {
1230
- fontSize: "0.65rem",
1231
- textAlign: "right",
1232
- px: 3,
1233
- pb: 1,
1234
- opacity: 0.7,
1235
- fontStyle: "italic",
1236
- width: "100%"
1237
- }
1238
- };
1239
- linkStyles = {
1240
- textDecoration: "none",
1241
- fontWeight: 500,
1242
- "&:hover": {
1243
- textDecoration: "underline"
1244
- }
1245
- };
1246
- }
1247
- });
1248
-
1249
- // src/components/CookieBanner.tsx
1250
- function CookieBanner({
1251
- policyLinkUrl,
1252
- termsLinkUrl,
1253
- debug,
1254
- blocking = true,
1255
- hideBranding = false,
1256
- SnackbarProps,
1257
- PaperProps
1258
- }) {
1259
- const { consented, acceptAll, rejectAll, openPreferences } = useConsent();
1260
- const texts = useConsentTexts();
1261
- const isHydrated = useConsentHydration();
1262
- const designTokens = useDesignTokens();
1263
- const open = debug ? true : isHydrated && !consented;
1264
- logger.componentRender("CookieBanner", {
1265
- open,
1266
- consented,
1267
- isHydrated,
1268
- blocking,
1269
- hideBranding
1270
- });
1271
- if (!open) return null;
1272
- const bannerStyle = (theme) => ({
1273
- p: designTokens?.spacing?.padding?.banner ?? 2,
1274
- maxWidth: 720,
1275
- mx: "auto",
1276
- backgroundColor: designTokens?.colors?.background ?? theme.palette.background?.paper,
1277
- color: designTokens?.colors?.text ?? theme.palette.text?.primary,
1278
- borderRadius: designTokens?.spacing?.borderRadius?.banner,
1279
- fontFamily: designTokens?.typography?.fontFamily
1280
- });
1281
- const bannerContent = /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_Paper.default, { elevation: 3, sx: bannerStyle, ...PaperProps, children: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_Stack.default, { spacing: 1, children: [
1282
- /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_Typography2.default, { variant: "body2", sx: { fontSize: designTokens?.typography?.fontSize?.banner }, children: [
1283
- texts.bannerMessage,
1284
- " ",
1285
- policyLinkUrl && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1286
- import_Link2.default,
1287
- {
1288
- href: policyLinkUrl,
1289
- underline: "hover",
1290
- target: "_blank",
1291
- rel: "noopener noreferrer",
1292
- sx: { color: designTokens?.colors?.primary },
1293
- children: texts.policyLink ?? "Saiba mais"
1294
- }
1295
- )
1296
- ] }),
1297
- /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_Stack.default, { direction: { xs: "column", sm: "row" }, spacing: 1, justifyContent: "flex-end", children: [
1298
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1299
- import_Button.default,
1300
- {
1301
- variant: "outlined",
1302
- onClick: () => {
1303
- logger.apiUsage("rejectAll", { source: "banner" });
1304
- rejectAll();
1305
- },
1306
- sx: { color: designTokens?.colors?.secondary },
1307
- children: texts.declineAll
1308
- }
1309
- ),
1310
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1311
- import_Button.default,
1312
- {
1313
- variant: "contained",
1314
- onClick: () => {
1315
- logger.apiUsage("acceptAll", { source: "banner" });
1316
- acceptAll();
1317
- },
1318
- sx: { backgroundColor: designTokens?.colors?.primary },
1319
- children: texts.acceptAll
1320
- }
1321
- ),
1322
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1323
- import_Button.default,
1324
- {
1325
- variant: "text",
1326
- onClick: () => {
1327
- logger.apiUsage("openPreferences", { source: "banner" });
1328
- openPreferences();
1329
- },
1330
- sx: { color: designTokens?.colors?.text },
1331
- children: texts.preferences
1332
- }
1333
- )
1334
- ] }),
1335
- !hideBranding && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(Branding, { variant: "banner" })
1336
- ] }) });
1337
- const positionStyle = {
1338
- position: "fixed",
1339
- zIndex: 1300,
1340
- ...designTokens?.layout?.position === "top" ? { top: 0 } : { bottom: 0 },
1341
- left: 0,
1342
- right: 0,
1343
- width: designTokens?.layout?.width?.desktop ?? "100%",
1344
- p: 2
1345
- };
1346
- const backdropToken = designTokens?.layout?.backdrop;
1347
- const resolveBackdropColor = (theme) => {
1348
- if (backdropToken === false) return "transparent";
1349
- if (typeof backdropToken === "string") {
1350
- if (backdropToken.toLowerCase() === "auto") {
1351
- const isDark2 = theme?.palette?.mode === "dark";
1352
- return isDark2 ? "rgba(255, 255, 255, 0.12)" : "rgba(0, 0, 0, 0.4)";
1353
- }
1354
- return backdropToken;
1355
- }
1356
- const isDark = theme?.palette?.mode === "dark";
1357
- return isDark ? "rgba(255, 255, 255, 0.12)" : "rgba(0, 0, 0, 0.4)";
1358
- };
1359
- const isSafeRoute = (() => {
1360
- try {
1361
- if (typeof window === "undefined") return false;
1362
- const current = new URL(window.location.href);
1363
- const safeUrls = [policyLinkUrl, termsLinkUrl].filter(Boolean);
1364
- return safeUrls.some((u) => {
1365
- try {
1366
- const target = new URL(u, current.origin);
1367
- return target.pathname === current.pathname;
1368
- } catch {
1369
- return false;
1370
- }
1371
- });
1372
- } catch {
1373
- return false;
1374
- }
1375
- })();
1376
- const effectiveBlocking = blocking && !isSafeRoute;
1377
- if (effectiveBlocking) {
1378
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
1379
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1380
- import_Box.default,
1381
- {
1382
- sx: (theme) => ({
1383
- position: "fixed",
1384
- top: 0,
1385
- left: 0,
1386
- right: 0,
1387
- bottom: 0,
1388
- backgroundColor: resolveBackdropColor(theme),
1389
- zIndex: 1299
1390
- })
1391
- }
1392
- ),
1393
- /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_Box.default, { sx: positionStyle, children: bannerContent })
1394
- ] });
1395
- }
1396
- return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
1397
- import_Snackbar.default,
1398
- {
1399
- open,
1400
- anchorOrigin: {
1401
- vertical: designTokens?.layout?.position === "top" ? "top" : "bottom",
1402
- horizontal: "center"
1403
- },
1404
- ...SnackbarProps,
1405
- children: bannerContent
1406
- }
1407
- );
1408
- }
1409
- var import_Button, import_Box, import_Paper, import_Snackbar, import_Stack, import_Typography2, import_Link2, import_jsx_runtime4;
1410
- var init_CookieBanner = __esm({
1411
- "src/components/CookieBanner.tsx"() {
1412
- "use strict";
1413
- import_Button = __toESM(require("@mui/material/Button"), 1);
1414
- import_Box = __toESM(require("@mui/material/Box"), 1);
1415
- import_Paper = __toESM(require("@mui/material/Paper"), 1);
1416
- import_Snackbar = __toESM(require("@mui/material/Snackbar"), 1);
1417
- import_Stack = __toESM(require("@mui/material/Stack"), 1);
1418
- import_Typography2 = __toESM(require("@mui/material/Typography"), 1);
1419
- import_Link2 = __toESM(require("@mui/material/Link"), 1);
1420
- init_useConsent();
1421
- init_DesignContext();
1422
- init_Branding();
1423
- init_logger();
1424
- import_jsx_runtime4 = require("react/jsx-runtime");
1425
- }
1426
- });
1427
-
1428
- // src/components/FloatingPreferencesButton.tsx
1429
- function useThemeWithFallbacks() {
1430
- const theme = (0, import_styles.useTheme)();
1431
- logger.themeCompatibility(theme);
1432
- return {
1433
- palette: {
1434
- primary: {
1435
- main: theme?.palette?.primary?.main || "#1976d2",
1436
- dark: theme?.palette?.primary?.dark || "#1565c0"
1437
- }
1438
- },
1439
- transitions: {
1440
- duration: {
1441
- shortest: theme?.transitions?.duration?.shortest || 150,
1442
- short: theme?.transitions?.duration?.short || 250
1443
- }
1444
- }
1445
- };
1446
- }
1447
- function FloatingPreferencesButton({
1448
- position = "bottom-right",
1449
- offset = 24,
1450
- icon = /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_CookieOutlined.default, {}),
1451
- tooltip,
1452
- FabProps,
1453
- hideWhenConsented = false
1454
- }) {
1455
- const { openPreferences, consented } = useConsent();
1456
- const texts = useConsentTexts();
1457
- const safeTheme = useThemeWithFallbacks();
1458
- const designTokens = useDesignTokens();
1459
- logger.componentRender("FloatingPreferencesButton", {
1460
- position,
1461
- offset,
1462
- hideWhenConsented,
1463
- consented
1464
- });
1465
- if (hideWhenConsented && consented) {
1466
- logger.debug(
1467
- "FloatingPreferencesButton: Hidden due to hideWhenConsented=true and consented=true"
1468
- );
1469
- return null;
1470
- }
1471
- const tooltipText = tooltip ?? texts.preferencesButton ?? "Gerenciar Prefer\xEAncias de Cookies";
1472
- const getPosition = () => {
1473
- const styles = {
1474
- position: "fixed",
1475
- zIndex: 1200
1476
- };
1477
- switch (position) {
1478
- case "bottom-left":
1479
- return { ...styles, bottom: offset, left: offset };
1480
- case "bottom-right":
1481
- return { ...styles, bottom: offset, right: offset };
1482
- case "top-left":
1483
- return { ...styles, top: offset, left: offset };
1484
- case "top-right":
1485
- return { ...styles, top: offset, right: offset };
1486
- default:
1487
- return { ...styles, bottom: offset, right: offset };
1488
- }
1489
- };
1490
- return /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_Tooltip.default, { title: tooltipText, placement: "top", children: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1491
- import_Fab.default,
1492
- {
1493
- size: "medium",
1494
- color: "primary",
1495
- onClick: openPreferences,
1496
- sx: {
1497
- ...getPosition(),
1498
- backgroundColor: designTokens?.colors?.primary ?? safeTheme.palette.primary.main,
1499
- "&:hover": {
1500
- backgroundColor: designTokens?.colors?.primary ? designTokens?.colors?.primary : safeTheme.palette.primary.dark
1501
- },
1502
- transition: `all ${safeTheme.transitions.duration.short}ms`
1503
- },
1504
- "aria-label": tooltipText,
1505
- ...FabProps,
1506
- children: icon
1507
- }
1508
- ) });
1509
- }
1510
- var import_CookieOutlined, import_Fab, import_Tooltip, import_styles, import_jsx_runtime5;
1511
- var init_FloatingPreferencesButton = __esm({
1512
- "src/components/FloatingPreferencesButton.tsx"() {
1513
- "use strict";
1514
- import_CookieOutlined = __toESM(require("@mui/icons-material/CookieOutlined"), 1);
1515
- import_Fab = __toESM(require("@mui/material/Fab"), 1);
1516
- import_Tooltip = __toESM(require("@mui/material/Tooltip"), 1);
1517
- import_styles = require("@mui/material/styles");
1518
- init_DesignContext();
1519
- init_useConsent();
1520
- init_logger();
1521
- import_jsx_runtime5 = require("react/jsx-runtime");
1522
- }
1523
- });
1524
-
1525
- // src/context/ConsentContext.tsx
1526
- function createFullConsentState(consented, preferences, source, projectConfig, isModalOpen = false, existingState) {
1527
- const now = (/* @__PURE__ */ new Date()).toISOString();
1528
- return {
1529
- version: "1.0",
1530
- consented,
1531
- preferences,
1532
- consentDate: existingState?.consentDate || now,
1533
- lastUpdate: now,
1534
- source,
1535
- projectConfig,
1536
- isModalOpen
1537
- };
1538
- }
1539
- function reducer(state, action) {
1540
- logger.consentState(action.type, state);
1541
- switch (action.type) {
1542
- case "ACCEPT_ALL": {
1543
- const prefs = createProjectPreferences(action.config, true);
1544
- const newState = createFullConsentState(true, prefs, "banner", action.config, false, state);
1545
- logger.info("User accepted all cookies", {
1546
- preferences: newState.preferences
1547
- });
1548
- return newState;
1549
- }
1550
- case "REJECT_ALL": {
1551
- const prefs = createProjectPreferences(action.config, false);
1552
- const newState = createFullConsentState(true, prefs, "banner", action.config, false, state);
1553
- logger.info("User rejected all cookies", {
1554
- preferences: newState.preferences
1555
- });
1556
- return newState;
1557
- }
1558
- case "SET_CATEGORY":
1559
- logger.debug("Category preference changed", {
1560
- category: action.category,
1561
- value: action.value
1562
- });
1563
- return {
1564
- ...state,
1565
- preferences: {
1566
- ...state.preferences,
1567
- [action.category]: action.value
1568
- },
1569
- lastUpdate: (/* @__PURE__ */ new Date()).toISOString()
1570
- };
1571
- case "SET_PREFERENCES":
1572
- logger.info("Preferences saved", { preferences: action.preferences });
1573
- return createFullConsentState(true, action.preferences, "modal", action.config, false, state);
1574
- case "OPEN_MODAL":
1575
- return { ...state, isModalOpen: true };
1576
- case "CLOSE_MODAL":
1577
- return createFullConsentState(true, state.preferences, "modal", action.config, false, state);
1578
- case "RESET": {
1579
- return createFullConsentState(
1580
- false,
1581
- createProjectPreferences(action.config),
1582
- "programmatic",
1583
- action.config,
1584
- false
1585
- );
1586
- }
1587
- case "HYDRATE": {
1588
- const validatedPreferences = validateProjectPreferences(
1589
- action.state.preferences,
1590
- action.config
1591
- );
1592
- return {
1593
- ...action.state,
1594
- preferences: validatedPreferences,
1595
- isModalOpen: false
1596
- };
1597
- }
1598
- default:
1599
- return state;
1600
- }
1601
- }
1602
- function ConsentProvider({
1603
- initialState,
1604
- categories,
1605
- texts: textsProp,
1606
- theme,
1607
- designTokens,
1608
- PreferencesModalComponent,
1609
- preferencesModalProps = {},
1610
- CookieBannerComponent,
1611
- cookieBannerProps = {},
1612
- FloatingPreferencesButtonComponent,
1613
- floatingPreferencesButtonProps = {},
1614
- disableFloatingPreferencesButton = false,
1615
- blocking = false,
1616
- blockingStrategy = "auto",
1617
- hideBranding = false,
1618
- onConsentGiven,
1619
- onPreferencesSaved,
1620
- cookie: cookieOpts,
1621
- disableDeveloperGuidance,
1622
- guidanceConfig,
1623
- children,
1624
- disableDiscoveryLog
1625
- }) {
1626
- const texts = React4.useMemo(() => ({ ...DEFAULT_TEXTS, ...textsProp ?? {} }), [textsProp]);
1627
- const cookie = React4.useMemo(
1628
- () => ({ ...DEFAULT_COOKIE_OPTS, ...cookieOpts ?? {} }),
1629
- [cookieOpts]
1630
- );
1631
- const mergedTheme = theme;
1632
- const finalCategoriesConfig = React4.useMemo(() => {
1633
- if (categories) return categories;
1634
- return DEFAULT_PROJECT_CATEGORIES;
1635
- }, [categories]);
1636
- useDeveloperGuidance(finalCategoriesConfig, disableDeveloperGuidance, guidanceConfig);
1637
- React4.useEffect(() => {
1638
- const isProd = typeof process !== "undefined" && process.env?.NODE_ENV === "production";
1639
- if (!isProd && PreferencesModalComponent) {
1640
- console.info(
1641
- "[LGPD-CONSENT] Dica: seu PreferencesModal \xE9 customizado. Garanta exibir os detalhes dos cookies por categoria (nome, finalidade, dura\xE7\xE3o) usando as APIs setCookieCatalogOverrides / setCookieCategoryOverrides e getCookiesInfoForCategory. Consulte QUICKSTART e INTEGRACOES.md."
1642
- );
1643
- }
1644
- }, [PreferencesModalComponent]);
1645
- const boot = React4.useMemo(() => {
1646
- if (initialState) return { ...initialState, isModalOpen: false };
1647
- return createFullConsentState(
1648
- false,
1649
- createProjectPreferences(finalCategoriesConfig),
1650
- "banner",
1651
- finalCategoriesConfig,
1652
- false
1653
- );
1654
- }, [initialState, finalCategoriesConfig]);
1655
- const [state, dispatch] = React4.useReducer(reducer, boot);
1656
- const [isHydrated, setIsHydrated] = React4.useState(false);
1657
- React4.useEffect(() => {
1658
- if (!initialState) {
1659
- const saved = readConsentCookie(cookie.name);
1660
- if (saved?.consented) {
1661
- dispatch({
1662
- type: "HYDRATE",
1663
- state: saved,
1664
- config: finalCategoriesConfig
1665
- });
1666
- }
1667
- }
1668
- setIsHydrated(true);
1669
- }, [cookie.name, initialState, finalCategoriesConfig]);
1670
- React4.useEffect(() => {
1671
- if (state.consented) writeConsentCookie(state, finalCategoriesConfig, cookie);
1672
- }, [state, cookie, finalCategoriesConfig]);
1673
- const prevConsented = React4.useRef(state.consented);
1674
- React4.useEffect(() => {
1675
- if (!prevConsented.current && state.consented && onConsentGiven) {
1676
- setTimeout(() => onConsentGiven(state), 150);
1677
- }
1678
- prevConsented.current = state.consented;
1679
- }, [state, onConsentGiven]);
1680
- const api = React4.useMemo(() => {
1681
- const acceptAll = () => dispatch({ type: "ACCEPT_ALL", config: finalCategoriesConfig });
1682
- const rejectAll = () => dispatch({ type: "REJECT_ALL", config: finalCategoriesConfig });
1683
- const setPreference = (category, value) => dispatch({ type: "SET_CATEGORY", category, value });
1684
- const setPreferences = (preferences) => {
1685
- dispatch({
1686
- type: "SET_PREFERENCES",
1687
- preferences,
1688
- config: finalCategoriesConfig
1689
- });
1690
- if (onPreferencesSaved) {
1691
- setTimeout(() => onPreferencesSaved(preferences), 150);
1692
- }
1693
- };
1694
- const openPreferences = () => dispatch({ type: "OPEN_MODAL" });
1695
- const closePreferences = () => dispatch({ type: "CLOSE_MODAL", config: finalCategoriesConfig });
1696
- const resetConsent = () => {
1697
- removeConsentCookie(cookie);
1698
- dispatch({ type: "RESET", config: finalCategoriesConfig });
1699
- };
1700
- return {
1701
- consented: !!state.consented,
1702
- preferences: state.preferences,
1703
- isModalOpen: state.isModalOpen,
1704
- acceptAll,
1705
- rejectAll,
1706
- setPreference,
1707
- setPreferences,
1708
- openPreferences,
1709
- closePreferences,
1710
- resetConsent
1711
- };
1712
- }, [state, cookie, finalCategoriesConfig, onPreferencesSaved]);
1713
- React4.useEffect(() => {
1714
- _registerGlobalOpenPreferences(api.openPreferences);
1715
- return () => _unregisterGlobalOpenPreferences();
1716
- }, [api.openPreferences]);
1717
- const providerBackdropColor = React4.useMemo(() => {
1718
- const backdrop = designTokens?.layout?.backdrop;
1719
- if (backdrop === false) return "transparent";
1720
- if (typeof backdrop === "string") return backdrop;
1721
- return "rgba(0, 0, 0, 0.4)";
1722
- }, [designTokens]);
1723
- const content = /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(StateCtx.Provider, { value: state, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(ActionsCtx.Provider, { value: api, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(TextsCtx.Provider, { value: texts, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(HydrationCtx.Provider, { value: isHydrated, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(DesignProvider, { tokens: designTokens, children: /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(
1724
- CategoriesProvider,
1725
- {
1726
- config: finalCategoriesConfig,
1727
- disableDeveloperGuidance,
1728
- disableDiscoveryLog,
1729
- children: [
1730
- children,
1731
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(React4.Suspense, { fallback: null, children: PreferencesModalComponent ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1732
- PreferencesModalComponent,
1733
- {
1734
- preferences: api.preferences,
1735
- setPreferences: api.setPreferences,
1736
- closePreferences: api.closePreferences,
1737
- isModalOpen: api.isModalOpen,
1738
- texts,
1739
- ...preferencesModalProps
1740
- }
1741
- ) : /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(PreferencesModal, { hideBranding }) }),
1742
- blocking && isHydrated && !state.consented && blockingStrategy === "provider" && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1743
- "div",
1744
- {
1745
- style: {
1746
- position: "fixed",
1747
- top: 0,
1748
- left: 0,
1749
- right: 0,
1750
- bottom: 0,
1751
- backgroundColor: providerBackdropColor,
1752
- zIndex: 1299
1753
- },
1754
- "data-testid": "lgpd-provider-overlay",
1755
- "aria-hidden": true
1756
- }
1757
- ),
1758
- !state.consented && isHydrated && (CookieBannerComponent ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1759
- CookieBannerComponent,
1760
- {
1761
- consented: api.consented,
1762
- acceptAll: api.acceptAll,
1763
- rejectAll: api.rejectAll,
1764
- openPreferences: api.openPreferences,
1765
- texts,
1766
- blocking,
1767
- ...cookieBannerProps
1768
- }
1769
- ) : /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1770
- CookieBanner,
1771
- {
1772
- blocking,
1773
- hideBranding,
1774
- ...cookieBannerProps
1775
- }
1776
- )),
1777
- state.consented && !disableFloatingPreferencesButton && (FloatingPreferencesButtonComponent ? /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1778
- FloatingPreferencesButtonComponent,
1779
- {
1780
- openPreferences: api.openPreferences,
1781
- consented: api.consented,
1782
- ...floatingPreferencesButtonProps
1783
- }
1784
- ) : (
1785
- // Encaminha `floatingPreferencesButtonProps` para o componente padrão
1786
- /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
1787
- FloatingPreferencesButton,
1788
- {
1789
- ...floatingPreferencesButtonProps ?? {}
1790
- }
1791
- )
1792
- ))
1793
- ]
1794
- }
1795
- ) }) }) }) }) });
1796
- if (mergedTheme) {
1797
- return /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_styles2.ThemeProvider, { theme: mergedTheme, children: content });
1798
- }
1799
- return content;
1800
- }
1801
- function useConsentStateInternal() {
1802
- const ctx = React4.useContext(StateCtx);
1803
- if (!ctx) throw new Error("useConsentState must be used within ConsentProvider");
1804
- return ctx;
1805
- }
1806
- function useConsentActionsInternal() {
1807
- const ctx = React4.useContext(ActionsCtx);
1808
- if (!ctx) throw new Error("useConsentActions must be used within ConsentProvider");
1809
- return ctx;
1810
- }
1811
- function useConsentTextsInternal() {
1812
- const ctx = React4.useContext(TextsCtx);
1813
- return ctx;
1814
- }
1815
- function useConsentHydrationInternal() {
1816
- return React4.useContext(HydrationCtx);
1817
- }
1818
- var import_styles2, React4, import_jsx_runtime6, PreferencesModal, DEFAULT_TEXTS, StateCtx, ActionsCtx, TextsCtx, HydrationCtx, defaultTexts;
1819
- var init_ConsentContext = __esm({
1820
- "src/context/ConsentContext.tsx"() {
1821
- "use strict";
1822
- import_styles2 = require("@mui/material/styles");
1823
- React4 = __toESM(require("react"), 1);
1824
- init_categoryUtils();
1825
- init_cookieUtils();
1826
- init_useConsent();
1827
- init_developerGuidance();
1828
- init_logger();
1829
- init_CategoriesContext();
1830
- init_DesignContext();
1831
- init_CookieBanner();
1832
- init_FloatingPreferencesButton();
1833
- import_jsx_runtime6 = require("react/jsx-runtime");
1834
- PreferencesModal = React4.lazy(
1835
- () => Promise.resolve().then(() => (init_PreferencesModal(), PreferencesModal_exports)).then((m) => ({
1836
- default: m.PreferencesModal
1837
- }))
1838
- );
1839
- DEFAULT_TEXTS = {
1840
- // Textos básicos
1841
- bannerMessage: "Utilizamos cookies para melhorar sua experi\xEAncia.",
1842
- acceptAll: "Aceitar todos",
1843
- declineAll: "Recusar",
1844
- preferences: "Prefer\xEAncias",
1845
- policyLink: "Saiba mais",
1846
- modalTitle: "Prefer\xEAncias de Cookies",
1847
- modalIntro: "Ajuste as categorias de cookies. Cookies necess\xE1rios s\xE3o sempre utilizados para funcionalidades b\xE1sicas.",
1848
- save: "Salvar prefer\xEAncias",
1849
- necessaryAlwaysOn: "Cookies necess\xE1rios (sempre ativos)",
1850
- // Textos adicionais para UI customizada
1851
- preferencesButton: "Configurar Cookies",
1852
- preferencesTitle: "Gerenciar Prefer\xEAncias de Cookies",
1853
- preferencesDescription: "Escolha quais tipos de cookies voc\xEA permite que sejam utilizados.",
1854
- close: "Fechar",
1855
- accept: "Aceitar",
1856
- reject: "Rejeitar",
1857
- // Textos ANPD expandidos (opcionais)
1858
- brandingPoweredBy: "fornecido por",
1859
- controllerInfo: void 0,
1860
- // Exibido se definido
1861
- dataTypes: void 0,
1862
- // Exibido se definido
1863
- thirdPartySharing: void 0,
1864
- // Exibido se definido
1865
- userRights: void 0,
1866
- // Exibido se definido
1867
- contactInfo: void 0,
1868
- // Exibido se definido
1869
- retentionPeriod: void 0,
1870
- // Exibido se definido
1871
- lawfulBasis: void 0,
1872
- // Exibido se definido
1873
- transferCountries: void 0
1874
- // Exibido se definido
1875
- };
1876
- StateCtx = React4.createContext(null);
1877
- ActionsCtx = React4.createContext(null);
1878
- TextsCtx = React4.createContext(DEFAULT_TEXTS);
1879
- HydrationCtx = React4.createContext(false);
1880
- defaultTexts = DEFAULT_TEXTS;
1881
- }
1882
- });
1883
-
1884
- // src/hooks/useConsent.ts
1885
- function useConsent() {
1886
- const state = useConsentStateInternal();
1887
- const actions = useConsentActionsInternal();
1888
- return {
1889
- consented: state.consented,
1890
- preferences: state.preferences,
1891
- isModalOpen: state.isModalOpen,
1892
- acceptAll: actions.acceptAll,
1893
- rejectAll: actions.rejectAll,
1894
- setPreference: actions.setPreference,
1895
- setPreferences: actions.setPreferences,
1896
- openPreferences: actions.openPreferences,
1897
- closePreferences: actions.closePreferences,
1898
- resetConsent: actions.resetConsent
1899
- };
1900
- }
1901
- function useConsentTexts() {
1902
- return useConsentTextsInternal();
1903
- }
1904
- function useConsentHydration() {
1905
- return useConsentHydrationInternal();
1906
- }
1907
- function _registerGlobalOpenPreferences(openPreferences) {
1908
- globalOpenPreferences = openPreferences;
1909
- }
1910
- function _unregisterGlobalOpenPreferences() {
1911
- globalOpenPreferences = null;
1912
- }
1913
- function useOpenPreferencesModal() {
1914
- const actions = useConsentActionsInternal();
1915
- if (!actions) {
1916
- throw new Error(
1917
- "[LGPD-CONSENT] useOpenPreferencesModal deve ser usado dentro do ConsentProvider. Envolva seu componente com <ConsentProvider>."
1918
- );
1919
- }
1920
- return actions.openPreferences;
1921
- }
1922
- function openPreferencesModal() {
1923
- if (globalOpenPreferences) {
1924
- globalOpenPreferences();
1925
- } else {
1926
- logger.warn(
1927
- "openPreferencesModal called but no ConsentProvider is mounted. Make sure ConsentProvider is rendered before calling this function."
1928
- );
1929
- }
1930
- }
1931
- var globalOpenPreferences;
1932
- var init_useConsent = __esm({
1933
- "src/hooks/useConsent.ts"() {
1934
- "use strict";
1935
- init_ConsentContext();
1936
- init_logger();
1937
- globalOpenPreferences = null;
1938
23
  }
1939
- });
1940
-
1941
- // src/components/PreferencesModal.tsx
1942
- var PreferencesModal_exports = {};
1943
- __export(PreferencesModal_exports, {
1944
- PreferencesModal: () => PreferencesModal2
1945
- });
1946
- function PreferencesModal2({
1947
- DialogProps: DialogProps2,
1948
- hideBranding = false
1949
- }) {
1950
- const { preferences, setPreferences, closePreferences, isModalOpen } = useConsent();
1951
- const texts = useConsentTexts();
1952
- const designTokens = useDesignTokens();
1953
- const { toggleableCategories, allCategories } = useCategories();
1954
- const [tempPreferences, setTempPreferences] = (0, import_react2.useState)(() => {
1955
- const initialPrefs = { necessary: true };
1956
- toggleableCategories.forEach((category) => {
1957
- initialPrefs[category.id] = preferences[category.id] ?? false;
1958
- });
1959
- return initialPrefs;
1960
- });
1961
- (0, import_react2.useEffect)(() => {
1962
- if (isModalOpen) {
1963
- const syncedPrefs = { necessary: true };
1964
- toggleableCategories.forEach((category) => {
1965
- syncedPrefs[category.id] = preferences[category.id] ?? false;
1966
- });
1967
- setTempPreferences(syncedPrefs);
1968
- }
1969
- }, [isModalOpen, preferences, toggleableCategories]);
1970
- const open = DialogProps2?.open ?? isModalOpen ?? false;
1971
- const handleSave = () => {
1972
- setPreferences(tempPreferences);
1973
- };
1974
- const handleCancel = () => {
1975
- setTempPreferences(preferences);
1976
- closePreferences();
1977
- };
1978
- const modalTitleSx = (theme) => ({
1979
- fontSize: designTokens?.typography?.fontSize?.modal ?? void 0,
1980
- color: designTokens?.colors?.text ?? theme.palette.text.primary
1981
- });
1982
- const modalContentSx = (theme) => ({
1983
- p: designTokens?.spacing?.padding?.modal ?? void 0,
1984
- backgroundColor: designTokens?.colors?.background ?? theme.palette.background.paper,
1985
- color: designTokens?.colors?.text ?? theme.palette.text.primary
1986
- });
1987
- return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_Dialog.default, { "aria-labelledby": "cookie-pref-title", open, onClose: handleCancel, ...DialogProps2, children: [
1988
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_DialogTitle.default, { id: "cookie-pref-title", sx: modalTitleSx, children: texts.modalTitle }),
1989
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_DialogContent.default, { dividers: true, sx: modalContentSx, children: [
1990
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
1991
- import_Typography3.default,
1992
- {
1993
- variant: "body2",
1994
- sx: (theme) => ({
1995
- mb: 2,
1996
- fontSize: designTokens?.typography?.fontSize?.modal ?? void 0,
1997
- color: designTokens?.colors?.text ?? theme.palette.text.primary
1998
- }),
1999
- children: texts.modalIntro
2000
- }
2001
- ),
2002
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_FormGroup.default, { children: [
2003
- toggleableCategories.map((category) => {
2004
- const full = allCategories.find((c) => c.id === category.id);
2005
- const namesFromGuidance = full?.cookies ?? [];
2006
- const used = globalThis.__LGPD_USED_INTEGRATIONS__ || [];
2007
- const descriptors = getCookiesInfoForCategory(category.id, used);
2008
- const enrichedDescriptors = descriptors.map((desc) => {
2009
- if (desc.purpose && desc.duration && desc.provider) {
2010
- return desc;
2011
- }
2012
- return {
2013
- name: desc.name,
2014
- purpose: desc.purpose || "-",
2015
- duration: desc.duration || "-",
2016
- provider: desc.provider || "-"
2017
- };
2018
- });
2019
- const merged = [
2020
- ...enrichedDescriptors,
2021
- ...namesFromGuidance.filter((n) => !enrichedDescriptors.find((d) => d.name === n)).map((n) => ({ name: n, purpose: "-", duration: "-", provider: "-" }))
2022
- ];
2023
- let mergedFinal = merged;
2024
- try {
2025
- if (merged.length === 0) {
2026
- const gmap = globalThis.__LGPD_INTEGRATIONS_MAP__ || {};
2027
- const scriptRows = Object.entries(gmap).filter(([, cat]) => cat === category.id).map(([id]) => ({
2028
- name: `(script) ${id}`,
2029
- purpose: "Script de integra\xE7\xE3o ativo",
2030
- duration: "-",
2031
- provider: "-"
2032
- }));
2033
- if (scriptRows.length > 0) mergedFinal = scriptRows;
2034
- }
2035
- } catch {
2036
- }
2037
- return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_Box2.default, { sx: { mb: 1 }, children: [
2038
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
2039
- import_FormControlLabel.default,
2040
- {
2041
- control: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(
2042
- import_Switch.default,
2043
- {
2044
- checked: tempPreferences[category.id] ?? false,
2045
- onChange: (e) => setTempPreferences((prev) => ({
2046
- ...prev,
2047
- [category.id]: e.target.checked
2048
- }))
2049
- }
2050
- ),
2051
- label: `${category.name} - ${category.description}`
2052
- }
2053
- ),
2054
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("details", { style: { marginLeft: 48 }, children: [
2055
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("summary", { children: "Ver detalhes" }),
2056
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_Box2.default, { sx: { mt: 1 }, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("table", { style: { width: "100%", borderCollapse: "collapse" }, children: [
2057
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("thead", { children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("tr", { children: [
2058
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { style: { textAlign: "left" }, children: "Cookie" }),
2059
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { style: { textAlign: "left" }, children: "Finalidade" }),
2060
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { style: { textAlign: "left" }, children: "Dura\xE7\xE3o" }),
2061
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { style: { textAlign: "left" }, children: "Fornecedor" })
2062
- ] }) }),
2063
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("tbody", { children: mergedFinal.map((d, idx) => /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("tr", { children: [
2064
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: d.name }),
2065
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: d.purpose }),
2066
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: d.duration }),
2067
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: d.provider })
2068
- ] }, d.name + idx)) })
2069
- ] }) })
2070
- ] })
2071
- ] }, category.id);
2072
- }),
2073
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_FormControlLabel.default, { control: /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_Switch.default, { checked: true, disabled: true }), label: texts.necessaryAlwaysOn }),
2074
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("details", { style: { marginLeft: 48 }, children: [
2075
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("summary", { children: "Ver detalhes" }),
2076
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_Box2.default, { sx: { mt: 1 }, children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("table", { style: { width: "100%", borderCollapse: "collapse" }, children: [
2077
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("thead", { children: /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("tr", { children: [
2078
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { style: { textAlign: "left" }, children: "Cookie" }),
2079
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { style: { textAlign: "left" }, children: "Finalidade" }),
2080
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { style: { textAlign: "left" }, children: "Dura\xE7\xE3o" }),
2081
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("th", { style: { textAlign: "left" }, children: "Fornecedor" })
2082
- ] }) }),
2083
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("tbody", { children: (() => {
2084
- const used = globalThis.__LGPD_USED_INTEGRATIONS__ || [];
2085
- const necessaryCookies = getCookiesInfoForCategory(
2086
- "necessary",
2087
- used
2088
- );
2089
- return necessaryCookies.map((d, idx) => /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("tr", { children: [
2090
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: d.name }),
2091
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: d.purpose || "-" }),
2092
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: d.duration || "-" }),
2093
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("td", { children: d.provider || "-" })
2094
- ] }, d.name + idx));
2095
- })() })
2096
- ] }) })
2097
- ] })
2098
- ] })
2099
- ] }),
2100
- /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_DialogActions.default, { children: [
2101
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_Button2.default, { variant: "outlined", onClick: handleCancel, children: texts.close }),
2102
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_Button2.default, { variant: "contained", onClick: handleSave, children: texts.save })
2103
- ] }),
2104
- !hideBranding && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(Branding, { variant: "modal" })
2105
- ] });
24
+ n.default = e;
25
+ return Object.freeze(n);
2106
26
  }
2107
- var import_Box2, import_Button2, import_Dialog, import_DialogActions, import_DialogContent, import_DialogTitle, import_FormControlLabel, import_FormGroup, import_Switch, import_Typography3, import_react2, import_jsx_runtime7;
2108
- var init_PreferencesModal = __esm({
2109
- "src/components/PreferencesModal.tsx"() {
2110
- "use strict";
2111
- import_Box2 = __toESM(require("@mui/material/Box"), 1);
2112
- import_Button2 = __toESM(require("@mui/material/Button"), 1);
2113
- import_Dialog = __toESM(require("@mui/material/Dialog"), 1);
2114
- import_DialogActions = __toESM(require("@mui/material/DialogActions"), 1);
2115
- import_DialogContent = __toESM(require("@mui/material/DialogContent"), 1);
2116
- import_DialogTitle = __toESM(require("@mui/material/DialogTitle"), 1);
2117
- import_FormControlLabel = __toESM(require("@mui/material/FormControlLabel"), 1);
2118
- import_FormGroup = __toESM(require("@mui/material/FormGroup"), 1);
2119
- import_Switch = __toESM(require("@mui/material/Switch"), 1);
2120
- import_Typography3 = __toESM(require("@mui/material/Typography"), 1);
2121
- import_react2 = require("react");
2122
- init_CategoriesContext();
2123
- init_DesignContext();
2124
- init_useConsent();
2125
- init_cookieRegistry();
2126
- init_Branding();
2127
- import_jsx_runtime7 = require("react/jsx-runtime");
2128
- }
2129
- });
2130
27
 
2131
- // src/index.ts
2132
- var index_exports = {};
2133
- __export(index_exports, {
2134
- COMMON_INTEGRATIONS: () => COMMON_INTEGRATIONS,
2135
- ConsentGate: () => ConsentGate,
2136
- ConsentProvider: () => ConsentProvider,
2137
- ConsentScriptLoader: () => ConsentScriptLoader,
2138
- CookieBanner: () => CookieBanner,
2139
- DEFAULT_PROJECT_CATEGORIES: () => DEFAULT_PROJECT_CATEGORIES,
2140
- EXPANDED_DEFAULT_TEXTS: () => EXPANDED_DEFAULT_TEXTS,
2141
- FloatingPreferencesButton: () => FloatingPreferencesButton,
2142
- GUIDANCE_PRESETS: () => GUIDANCE_PRESETS,
2143
- INTEGRATION_TEMPLATES: () => INTEGRATION_TEMPLATES,
2144
- LogLevel: () => LogLevel,
2145
- PreferencesModal: () => PreferencesModal2,
2146
- TEXT_TEMPLATES: () => TEXT_TEMPLATES,
2147
- analyzeDeveloperConfiguration: () => analyzeDeveloperConfiguration,
2148
- analyzeIntegrationCategories: () => analyzeIntegrationCategories,
2149
- autoConfigureCategories: () => autoConfigureCategories,
2150
- categorizeDiscoveredCookies: () => categorizeDiscoveredCookies,
2151
- createClarityIntegration: () => createClarityIntegration,
2152
- createCorporateIntegrations: () => createCorporateIntegrations,
2153
- createDefaultConsentTheme: () => createDefaultConsentTheme,
2154
- createECommerceIntegrations: () => createECommerceIntegrations,
2155
- createFacebookPixelIntegration: () => createFacebookPixelIntegration,
2156
- createGoogleAnalyticsIntegration: () => createGoogleAnalyticsIntegration,
2157
- createGoogleTagManagerIntegration: () => createGoogleTagManagerIntegration,
2158
- createHotjarIntegration: () => createHotjarIntegration,
2159
- createIntercomIntegration: () => createIntercomIntegration,
2160
- createMixpanelIntegration: () => createMixpanelIntegration,
2161
- createProjectPreferences: () => createProjectPreferences,
2162
- createSaaSIntegrations: () => createSaaSIntegrations,
2163
- createUserWayIntegration: () => createUserWayIntegration,
2164
- createZendeskChatIntegration: () => createZendeskChatIntegration,
2165
- defaultConsentTheme: () => defaultConsentTheme,
2166
- defaultTexts: () => defaultTexts,
2167
- detectConsentCookieName: () => detectConsentCookieName,
2168
- discoverRuntimeCookies: () => discoverRuntimeCookies,
2169
- extractCategoriesFromIntegrations: () => extractCategoriesFromIntegrations,
2170
- getAllProjectCategories: () => getAllProjectCategories,
2171
- getCookiesInfoForCategory: () => getCookiesInfoForCategory,
2172
- loadScript: () => loadScript,
2173
- logDeveloperGuidance: () => logDeveloperGuidance,
2174
- openPreferencesModal: () => openPreferencesModal,
2175
- resolveTexts: () => resolveTexts,
2176
- setCookieCatalogOverrides: () => setCookieCatalogOverrides,
2177
- setCookieCategoryOverrides: () => setCookieCategoryOverrides,
2178
- setDebugLogging: () => setDebugLogging,
2179
- suggestCategoryForScript: () => suggestCategoryForScript,
2180
- useCategories: () => useCategories,
2181
- useCategoryStatus: () => useCategoryStatus,
2182
- useConsent: () => useConsent,
2183
- useConsentHydration: () => useConsentHydration,
2184
- useConsentScriptLoader: () => useConsentScriptLoader,
2185
- useConsentTexts: () => useConsentTexts,
2186
- useDeveloperGuidance: () => useDeveloperGuidance,
2187
- useOpenPreferencesModal: () => useOpenPreferencesModal,
2188
- validateIntegrationCategories: () => validateIntegrationCategories,
2189
- validateNecessaryClassification: () => validateNecessaryClassification,
2190
- validateProjectPreferences: () => validateProjectPreferences
2191
- });
2192
- module.exports = __toCommonJS(index_exports);
2193
- init_PreferencesModal();
2194
- init_ConsentContext();
2195
- init_useConsent();
2196
- init_CategoriesContext();
28
+ var React__namespace = /*#__PURE__*/_interopNamespace(React);
2197
29
 
2198
- // src/utils/ConsentGate.tsx
2199
- init_useConsent();
2200
- var import_jsx_runtime8 = require("react/jsx-runtime");
30
+ // react-lgpd-consent - Tree-shakeable ESM build
2201
31
  function ConsentGate(props) {
2202
- const { preferences } = useConsent();
32
+ const { preferences } = chunkORI4PLVG_cjs.useConsent();
2203
33
  if (!preferences[props.category]) return null;
2204
- return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_jsx_runtime8.Fragment, { children: props.children });
34
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: props.children });
2205
35
  }
2206
36
 
2207
37
  // src/utils/scriptLoader.ts
@@ -2240,14 +70,8 @@ function loadScript(id, src, category = null, attrs = {}) {
2240
70
  checkConsent();
2241
71
  });
2242
72
  }
2243
-
2244
- // src/index.ts
2245
- init_cookieDiscovery();
2246
-
2247
- // src/utils/theme.ts
2248
- var import_styles3 = require("@mui/material/styles");
2249
73
  function createDefaultConsentTheme() {
2250
- return (0, import_styles3.createTheme)({
74
+ return styles.createTheme({
2251
75
  palette: {
2252
76
  primary: {
2253
77
  main: "#1976d2",
@@ -2315,11 +139,6 @@ function createDefaultConsentTheme() {
2315
139
  }
2316
140
  var defaultConsentTheme = () => createDefaultConsentTheme();
2317
141
 
2318
- // src/utils/ConsentScriptLoader.tsx
2319
- var React5 = __toESM(require("react"), 1);
2320
- init_CategoriesContext();
2321
- init_useConsent();
2322
-
2323
142
  // src/utils/autoConfigureCategories.ts
2324
143
  var FORBIDDEN_NECESSARY_SCRIPTS = /* @__PURE__ */ new Set([
2325
144
  // Analytics & Performance
@@ -2476,15 +295,14 @@ function validateNecessaryClassification(integrations, enabledCategories) {
2476
295
  }
2477
296
 
2478
297
  // src/utils/ConsentScriptLoader.tsx
2479
- init_logger();
2480
298
  function ConsentScriptLoader({
2481
299
  integrations,
2482
300
  reloadOnChange = false
2483
301
  }) {
2484
- const { preferences, consented } = useConsent();
2485
- const categories = useCategories();
2486
- const loadedScripts = React5.useRef(/* @__PURE__ */ new Set());
2487
- React5.useEffect(() => {
302
+ const { preferences, consented } = chunkORI4PLVG_cjs.useConsent();
303
+ const categories = chunkORI4PLVG_cjs.useCategories();
304
+ const loadedScripts = React__namespace.useRef(/* @__PURE__ */ new Set());
305
+ React__namespace.useEffect(() => {
2488
306
  try {
2489
307
  const ids = (integrations || []).map((i) => i.id);
2490
308
  const gt = globalThis;
@@ -2503,7 +321,7 @@ function ConsentScriptLoader({
2503
321
  } catch {
2504
322
  }
2505
323
  }, [integrations]);
2506
- React5.useEffect(() => {
324
+ React__namespace.useEffect(() => {
2507
325
  try {
2508
326
  const required = Array.from(new Set((integrations || []).map((i) => i.category))).filter(
2509
327
  Boolean
@@ -2518,7 +336,7 @@ function ConsentScriptLoader({
2518
336
  } catch {
2519
337
  }
2520
338
  }, [integrations]);
2521
- React5.useEffect(() => {
339
+ React__namespace.useEffect(() => {
2522
340
  const isDev = process.env.NODE_ENV !== "production";
2523
341
  if (!isDev || integrations.length === 0) return;
2524
342
  const enabledCategories = categories.allCategories.map((cat) => cat.id);
@@ -2544,7 +362,7 @@ function ConsentScriptLoader({
2544
362
  console.groupEnd();
2545
363
  }
2546
364
  }, [integrations, categories]);
2547
- React5.useEffect(() => {
365
+ React__namespace.useEffect(() => {
2548
366
  if (!consented) return;
2549
367
  integrations.forEach(async (integration) => {
2550
368
  const shouldLoad = preferences[integration.category];
@@ -2557,7 +375,7 @@ function ConsentScriptLoader({
2557
375
  }
2558
376
  loadedScripts.current.add(integration.id);
2559
377
  } catch (error) {
2560
- logger.error(`\u274C Failed to load script: ${integration.id}`, error);
378
+ chunkORI4PLVG_cjs.logger.error(`\u274C Failed to load script: ${integration.id}`, error);
2561
379
  }
2562
380
  }
2563
381
  });
@@ -2565,16 +383,16 @@ function ConsentScriptLoader({
2565
383
  return null;
2566
384
  }
2567
385
  function useConsentScriptLoader() {
2568
- const { preferences, consented } = useConsent();
2569
- return React5.useCallback(
386
+ const { preferences, consented } = chunkORI4PLVG_cjs.useConsent();
387
+ return React__namespace.useCallback(
2570
388
  async (integration) => {
2571
389
  if (!consented) {
2572
- logger.warn(`\u26A0\uFE0F Cannot load script ${integration.id}: No consent given`);
390
+ chunkORI4PLVG_cjs.logger.warn(`\u26A0\uFE0F Cannot load script ${integration.id}: No consent given`);
2573
391
  return false;
2574
392
  }
2575
393
  const shouldLoad = preferences[integration.category];
2576
394
  if (!shouldLoad) {
2577
- logger.warn(
395
+ chunkORI4PLVG_cjs.logger.warn(
2578
396
  `\u26A0\uFE0F Cannot load script ${integration.id}: Category '${integration.category}' not consented`
2579
397
  );
2580
398
  return false;
@@ -2586,7 +404,7 @@ function useConsentScriptLoader() {
2586
404
  }
2587
405
  return true;
2588
406
  } catch (error) {
2589
- logger.error(`\u274C Failed to load script: ${integration.id}`, error);
407
+ chunkORI4PLVG_cjs.logger.error(`\u274C Failed to load script: ${integration.id}`, error);
2590
408
  return false;
2591
409
  }
2592
410
  },
@@ -3130,71 +948,144 @@ var TEXT_TEMPLATES = {
3130
948
  }
3131
949
  };
3132
950
 
3133
- // src/index.ts
3134
- init_developerGuidance();
3135
- init_logger();
3136
- init_cookieRegistry();
3137
- init_CookieBanner();
3138
- init_FloatingPreferencesButton();
3139
- init_ConsentContext();
3140
- init_categoryUtils();
3141
- // Annotate the CommonJS export names for ESM import in node:
3142
- 0 && (module.exports = {
3143
- COMMON_INTEGRATIONS,
3144
- ConsentGate,
3145
- ConsentProvider,
3146
- ConsentScriptLoader,
3147
- CookieBanner,
3148
- DEFAULT_PROJECT_CATEGORIES,
3149
- EXPANDED_DEFAULT_TEXTS,
3150
- FloatingPreferencesButton,
3151
- GUIDANCE_PRESETS,
3152
- INTEGRATION_TEMPLATES,
3153
- LogLevel,
3154
- PreferencesModal,
3155
- TEXT_TEMPLATES,
3156
- analyzeDeveloperConfiguration,
3157
- analyzeIntegrationCategories,
3158
- autoConfigureCategories,
3159
- categorizeDiscoveredCookies,
3160
- createClarityIntegration,
3161
- createCorporateIntegrations,
3162
- createDefaultConsentTheme,
3163
- createECommerceIntegrations,
3164
- createFacebookPixelIntegration,
3165
- createGoogleAnalyticsIntegration,
3166
- createGoogleTagManagerIntegration,
3167
- createHotjarIntegration,
3168
- createIntercomIntegration,
3169
- createMixpanelIntegration,
3170
- createProjectPreferences,
3171
- createSaaSIntegrations,
3172
- createUserWayIntegration,
3173
- createZendeskChatIntegration,
3174
- defaultConsentTheme,
3175
- defaultTexts,
3176
- detectConsentCookieName,
3177
- discoverRuntimeCookies,
3178
- extractCategoriesFromIntegrations,
3179
- getAllProjectCategories,
3180
- getCookiesInfoForCategory,
3181
- loadScript,
3182
- logDeveloperGuidance,
3183
- openPreferencesModal,
3184
- resolveTexts,
3185
- setCookieCatalogOverrides,
3186
- setCookieCategoryOverrides,
3187
- setDebugLogging,
3188
- suggestCategoryForScript,
3189
- useCategories,
3190
- useCategoryStatus,
3191
- useConsent,
3192
- useConsentHydration,
3193
- useConsentScriptLoader,
3194
- useConsentTexts,
3195
- useDeveloperGuidance,
3196
- useOpenPreferencesModal,
3197
- validateIntegrationCategories,
3198
- validateNecessaryClassification,
3199
- validateProjectPreferences
951
+ Object.defineProperty(exports, "FloatingPreferencesButton", {
952
+ enumerable: true,
953
+ get: function () { return chunkFJKRAERJ_cjs.FloatingPreferencesButton; }
954
+ });
955
+ Object.defineProperty(exports, "PreferencesModal", {
956
+ enumerable: true,
957
+ get: function () { return chunk25XEI2DZ_cjs.PreferencesModal; }
958
+ });
959
+ Object.defineProperty(exports, "ConsentProvider", {
960
+ enumerable: true,
961
+ get: function () { return chunkORI4PLVG_cjs.ConsentProvider; }
962
+ });
963
+ Object.defineProperty(exports, "CookieBanner", {
964
+ enumerable: true,
965
+ get: function () { return chunkORI4PLVG_cjs.CookieBanner; }
966
+ });
967
+ Object.defineProperty(exports, "DEFAULT_PROJECT_CATEGORIES", {
968
+ enumerable: true,
969
+ get: function () { return chunkORI4PLVG_cjs.DEFAULT_PROJECT_CATEGORIES; }
970
+ });
971
+ Object.defineProperty(exports, "GUIDANCE_PRESETS", {
972
+ enumerable: true,
973
+ get: function () { return chunkORI4PLVG_cjs.GUIDANCE_PRESETS; }
974
+ });
975
+ Object.defineProperty(exports, "LogLevel", {
976
+ enumerable: true,
977
+ get: function () { return chunkORI4PLVG_cjs.LogLevel; }
978
+ });
979
+ Object.defineProperty(exports, "analyzeDeveloperConfiguration", {
980
+ enumerable: true,
981
+ get: function () { return chunkORI4PLVG_cjs.analyzeDeveloperConfiguration; }
982
+ });
983
+ Object.defineProperty(exports, "categorizeDiscoveredCookies", {
984
+ enumerable: true,
985
+ get: function () { return chunkORI4PLVG_cjs.categorizeDiscoveredCookies; }
986
+ });
987
+ Object.defineProperty(exports, "createProjectPreferences", {
988
+ enumerable: true,
989
+ get: function () { return chunkORI4PLVG_cjs.createProjectPreferences; }
990
+ });
991
+ Object.defineProperty(exports, "defaultTexts", {
992
+ enumerable: true,
993
+ get: function () { return chunkORI4PLVG_cjs.defaultTexts; }
994
+ });
995
+ Object.defineProperty(exports, "detectConsentCookieName", {
996
+ enumerable: true,
997
+ get: function () { return chunkORI4PLVG_cjs.detectConsentCookieName; }
998
+ });
999
+ Object.defineProperty(exports, "discoverRuntimeCookies", {
1000
+ enumerable: true,
1001
+ get: function () { return chunkORI4PLVG_cjs.discoverRuntimeCookies; }
1002
+ });
1003
+ Object.defineProperty(exports, "getAllProjectCategories", {
1004
+ enumerable: true,
1005
+ get: function () { return chunkORI4PLVG_cjs.getAllProjectCategories; }
1006
+ });
1007
+ Object.defineProperty(exports, "getCookiesInfoForCategory", {
1008
+ enumerable: true,
1009
+ get: function () { return chunkORI4PLVG_cjs.getCookiesInfoForCategory; }
1010
+ });
1011
+ Object.defineProperty(exports, "logDeveloperGuidance", {
1012
+ enumerable: true,
1013
+ get: function () { return chunkORI4PLVG_cjs.logDeveloperGuidance; }
1014
+ });
1015
+ Object.defineProperty(exports, "openPreferencesModal", {
1016
+ enumerable: true,
1017
+ get: function () { return chunkORI4PLVG_cjs.openPreferencesModal; }
1018
+ });
1019
+ Object.defineProperty(exports, "setCookieCatalogOverrides", {
1020
+ enumerable: true,
1021
+ get: function () { return chunkORI4PLVG_cjs.setCookieCatalogOverrides; }
1022
+ });
1023
+ Object.defineProperty(exports, "setCookieCategoryOverrides", {
1024
+ enumerable: true,
1025
+ get: function () { return chunkORI4PLVG_cjs.setCookieCategoryOverrides; }
1026
+ });
1027
+ Object.defineProperty(exports, "setDebugLogging", {
1028
+ enumerable: true,
1029
+ get: function () { return chunkORI4PLVG_cjs.setDebugLogging; }
1030
+ });
1031
+ Object.defineProperty(exports, "useCategories", {
1032
+ enumerable: true,
1033
+ get: function () { return chunkORI4PLVG_cjs.useCategories; }
1034
+ });
1035
+ Object.defineProperty(exports, "useCategoryStatus", {
1036
+ enumerable: true,
1037
+ get: function () { return chunkORI4PLVG_cjs.useCategoryStatus; }
1038
+ });
1039
+ Object.defineProperty(exports, "useConsent", {
1040
+ enumerable: true,
1041
+ get: function () { return chunkORI4PLVG_cjs.useConsent; }
1042
+ });
1043
+ Object.defineProperty(exports, "useConsentHydration", {
1044
+ enumerable: true,
1045
+ get: function () { return chunkORI4PLVG_cjs.useConsentHydration; }
1046
+ });
1047
+ Object.defineProperty(exports, "useConsentTexts", {
1048
+ enumerable: true,
1049
+ get: function () { return chunkORI4PLVG_cjs.useConsentTexts; }
1050
+ });
1051
+ Object.defineProperty(exports, "useDeveloperGuidance", {
1052
+ enumerable: true,
1053
+ get: function () { return chunkORI4PLVG_cjs.useDeveloperGuidance; }
1054
+ });
1055
+ Object.defineProperty(exports, "useOpenPreferencesModal", {
1056
+ enumerable: true,
1057
+ get: function () { return chunkORI4PLVG_cjs.useOpenPreferencesModal; }
1058
+ });
1059
+ Object.defineProperty(exports, "validateProjectPreferences", {
1060
+ enumerable: true,
1061
+ get: function () { return chunkORI4PLVG_cjs.validateProjectPreferences; }
3200
1062
  });
1063
+ exports.COMMON_INTEGRATIONS = COMMON_INTEGRATIONS;
1064
+ exports.ConsentGate = ConsentGate;
1065
+ exports.ConsentScriptLoader = ConsentScriptLoader;
1066
+ exports.EXPANDED_DEFAULT_TEXTS = EXPANDED_DEFAULT_TEXTS;
1067
+ exports.INTEGRATION_TEMPLATES = INTEGRATION_TEMPLATES;
1068
+ exports.TEXT_TEMPLATES = TEXT_TEMPLATES;
1069
+ exports.analyzeIntegrationCategories = analyzeIntegrationCategories;
1070
+ exports.autoConfigureCategories = autoConfigureCategories;
1071
+ exports.createClarityIntegration = createClarityIntegration;
1072
+ exports.createCorporateIntegrations = createCorporateIntegrations;
1073
+ exports.createDefaultConsentTheme = createDefaultConsentTheme;
1074
+ exports.createECommerceIntegrations = createECommerceIntegrations;
1075
+ exports.createFacebookPixelIntegration = createFacebookPixelIntegration;
1076
+ exports.createGoogleAnalyticsIntegration = createGoogleAnalyticsIntegration;
1077
+ exports.createGoogleTagManagerIntegration = createGoogleTagManagerIntegration;
1078
+ exports.createHotjarIntegration = createHotjarIntegration;
1079
+ exports.createIntercomIntegration = createIntercomIntegration;
1080
+ exports.createMixpanelIntegration = createMixpanelIntegration;
1081
+ exports.createSaaSIntegrations = createSaaSIntegrations;
1082
+ exports.createUserWayIntegration = createUserWayIntegration;
1083
+ exports.createZendeskChatIntegration = createZendeskChatIntegration;
1084
+ exports.defaultConsentTheme = defaultConsentTheme;
1085
+ exports.extractCategoriesFromIntegrations = extractCategoriesFromIntegrations;
1086
+ exports.loadScript = loadScript;
1087
+ exports.resolveTexts = resolveTexts;
1088
+ exports.suggestCategoryForScript = suggestCategoryForScript;
1089
+ exports.useConsentScriptLoader = useConsentScriptLoader;
1090
+ exports.validateIntegrationCategories = validateIntegrationCategories;
1091
+ exports.validateNecessaryClassification = validateNecessaryClassification;