@truzyx/consent-widget 0.2.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,21 +1,249 @@
1
- var m = Object.defineProperty;
2
- var w = (n, e, t) => e in n ? m(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
- var a = (n, e, t) => w(n, typeof e != "symbol" ? e + "" : e, t);
4
- const c = {
1
+ var $ = Object.defineProperty;
2
+ var B = (n, e, t) => e in n ? $(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var m = (n, e, t) => B(n, typeof e != "symbol" ? e + "" : e, t);
4
+ const W = {
5
5
  live: "https://ui.gateway.nodbook.in",
6
6
  sandbox: "https://sandbox-ui.gateway.nodbook.in"
7
- }, y = "CONSENT_WIDGET_EVENT", h = "GATEWAY_UI_READY", u = "PRINCIPAL_TOKEN";
8
- function b(n) {
9
- return typeof n == "object" && n !== null && n.type === y && typeof n.event == "object";
7
+ }, R = "CONSENT_WIDGET_EVENT", L = "GATEWAY_UI_READY", q = "PRINCIPAL_TOKEN";
8
+ function H(n) {
9
+ return typeof n == "object" && n !== null && n.type === R && typeof n.event == "object";
10
10
  }
11
- function E(n) {
12
- return typeof n == "object" && n !== null && n.type === h;
11
+ function F(n) {
12
+ return typeof n == "object" && n !== null && n.type === L;
13
13
  }
14
- const x = "__consent_widget_overlay__", _ = 600, I = 640;
15
- function v(n, e) {
14
+ const G = ".nodbook-widget";
15
+ function v() {
16
+ const n = globalThis.document;
17
+ if (!n)
18
+ throw new Error("nodbook-widget: `document` is not available in this environment.");
19
+ return n;
20
+ }
21
+ function M(n) {
22
+ var t, o;
23
+ const e = n == null ? void 0 : n.trim();
24
+ if (e) return e;
25
+ try {
26
+ const r = globalThis.navigator, i = (o = (t = r == null ? void 0 : r.language) == null ? void 0 : t.split("-")[0]) == null ? void 0 : o.trim();
27
+ if (i) return i;
28
+ } catch {
29
+ }
30
+ return "en";
31
+ }
32
+ function P(n) {
33
+ var t;
34
+ return (((t = n.apiBaseUrl) == null ? void 0 : t.trim()) || N(n.baseUrl, n.env)).replace(/\/$/, "");
35
+ }
36
+ function S(n, e) {
37
+ var t;
38
+ if (typeof n == "object" && n !== null) {
39
+ const o = (t = n.error_data) == null ? void 0 : t.description;
40
+ if (typeof o == "string" && o.trim()) return o;
41
+ }
42
+ return e;
43
+ }
44
+ async function Y(n, e) {
45
+ const t = await fetch(`${n}/v1/public/direct_consents/purpose`, {
46
+ method: "POST",
47
+ headers: { "Content-Type": "application/json" },
48
+ body: JSON.stringify(e)
49
+ }), o = await t.json().catch(() => null);
50
+ if (!t.ok)
51
+ throw new Error(S(o, `Failed to load purpose (${t.status}).`));
52
+ const r = o == null ? void 0 : o.data;
53
+ if (!r || typeof r != "object" || !("id" in r))
54
+ throw new Error("Failed to load purpose: unexpected response shape.");
55
+ return r;
56
+ }
57
+ async function K(n, e) {
58
+ let t = "";
59
+ try {
60
+ const s = globalThis.navigator;
61
+ typeof (s == null ? void 0 : s.userAgent) == "string" && (t = s.userAgent);
62
+ } catch {
63
+ }
64
+ const o = await fetch(`${n}/v1/public/direct_consents`, {
65
+ method: "POST",
66
+ headers: { "Content-Type": "application/json" },
67
+ body: JSON.stringify({
68
+ ...e,
69
+ device_details: {
70
+ user_agent: t,
71
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
72
+ }
73
+ })
74
+ }), r = await o.json().catch(() => null);
75
+ if (!o.ok)
76
+ throw new Error(S(r, `Failed to record consent (${o.status}).`));
77
+ const i = r == null ? void 0 : r.data;
78
+ if (!i || typeof i != "object" || !Array.isArray(i.consent_ids))
79
+ throw new Error("Failed to record consent: unexpected response shape.");
80
+ return i;
81
+ }
82
+ function V(n, e) {
83
+ var o, r;
84
+ const t = ((o = n.locales) == null ? void 0 : o[e]) ?? ((r = n.locales) == null ? void 0 : r.en) ?? Object.values(n.locales ?? {})[0];
85
+ return {
86
+ name: (t == null ? void 0 : t.name) ?? n.name ?? n.identifier ?? n.id,
87
+ description: (t == null ? void 0 : t.description) ?? n.description ?? ""
88
+ };
89
+ }
90
+ function f(n, e, t) {
91
+ const r = v().createElement(n);
92
+ return r.className = t, r.setAttribute("style", e), r;
93
+ }
94
+ function j(n, e, t) {
95
+ var k, A, z;
96
+ const o = (k = e.organizationId) == null ? void 0 : k.trim(), r = (A = e.purposeId) == null ? void 0 : A.trim(), i = (z = e.principalId) == null ? void 0 : z.trim();
97
+ if (!o || !r || !i)
98
+ throw new Error("embedDirectConsent: `organizationId`, `purposeId` and `principalId` are required.");
99
+ const s = {
100
+ organizationId: o,
101
+ purposeId: r,
102
+ principalId: i,
103
+ locale: M(e.locale),
104
+ apiBaseUrl: P(e)
105
+ }, l = { purposeId: r, principalId: i, organizationId: o };
106
+ let a = !1, c = !1;
107
+ const d = f("div", "display:flex;flex-direction:column;gap:8px;font:inherit;color:inherit;", "nbw-root"), p = (h) => {
108
+ const u = f("span", "font-size:13px;opacity:0.65;", "nbw-loading");
109
+ return u.textContent = h, d.replaceChildren(u), u;
110
+ }, x = (h, u) => {
111
+ if (a) return;
112
+ const w = f("div", "display:flex;flex-direction:column;gap:6px;", "nbw-error-wrap"), b = f("span", "font-size:13px;color:#b91c1c;", "nbw-error");
113
+ if (b.setAttribute("role", "alert"), b.textContent = h, w.appendChild(b), u) {
114
+ const I = f(
115
+ "button",
116
+ "align-self:flex-start;font:inherit;font-size:13px;color:#0b57d0;background:none;border:none;padding:0;cursor:pointer;text-decoration:underline;",
117
+ "nbw-retry"
118
+ );
119
+ I.textContent = "Retry", I.addEventListener("click", u), w.appendChild(I);
120
+ }
121
+ d.replaceChildren(w);
122
+ };
123
+ p("Loading consent…"), n.replaceChildren(d);
124
+ const _ = () => {
125
+ p("Loading consent…"), Y(s.apiBaseUrl, {
126
+ organization_id: s.organizationId,
127
+ purpose_id: s.purposeId
128
+ }).then(
129
+ (h) => {
130
+ a || O(h);
131
+ },
132
+ (h) => {
133
+ if (a) return;
134
+ const u = h instanceof Error ? h.message : "Failed to load purpose.";
135
+ t({ type: "error", message: u, data: l }), x(u, _);
136
+ }
137
+ );
138
+ }, O = (h) => {
139
+ if (a) return;
140
+ const { name: u, description: w } = V(h, s.locale), b = f(
141
+ "label",
142
+ "display:flex;gap:8px;align-items:flex-start;cursor:pointer;font:inherit;",
143
+ "nbw-label"
144
+ ), g = v().createElement("input");
145
+ g.type = "checkbox", g.className = "nbw-checkbox", g.setAttribute(
146
+ "style",
147
+ "margin-top:2px;width:16px;height:16px;accent-color:#0b57d0;cursor:pointer;flex-shrink:0;"
148
+ );
149
+ const C = f("span", "display:flex;flex-direction:column;gap:2px;min-width:0;", "nbw-text"), U = f("span", "font-size:14px;font-weight:600;line-height:1.35;", "nbw-name");
150
+ if (U.textContent = u, C.appendChild(U), w) {
151
+ const y = f("span", "font-size:12px;line-height:1.4;opacity:0.75;", "nbw-description");
152
+ y.textContent = w, C.appendChild(y);
153
+ }
154
+ b.appendChild(g), b.appendChild(C);
155
+ const E = f("span", "font-size:12px;opacity:0.65;", "nbw-status");
156
+ E.setAttribute("aria-live", "polite"), g.addEventListener("change", () => {
157
+ if (c || a) return;
158
+ c = !0;
159
+ const y = g.checked;
160
+ g.disabled = !0, E.textContent = "Saving…", K(s.apiBaseUrl, {
161
+ organization_id: s.organizationId,
162
+ principal_id: s.principalId,
163
+ purpose_id: s.purposeId,
164
+ active: y,
165
+ locale: s.locale
166
+ }).then(
167
+ () => {
168
+ a || (c = !1, g.disabled = !1, E.textContent = "", t({ type: y ? "consent_accepted" : "consent_declined", data: l }));
169
+ },
170
+ (T) => {
171
+ if (a) return;
172
+ c = !1, g.checked = !y, g.disabled = !1;
173
+ const D = T instanceof Error ? T.message : "Failed to record consent.";
174
+ E.textContent = D, t({ type: "error", message: D, data: l });
175
+ }
176
+ );
177
+ }), d.replaceChildren(b, E);
178
+ };
179
+ return _(), () => {
180
+ a = !0, d.remove();
181
+ };
182
+ }
183
+ function J(n) {
184
+ const e = (o) => {
185
+ var i;
186
+ return ((i = n.getAttribute(`data-${o}`)) == null ? void 0 : i.trim()) || void 0;
187
+ }, t = e("env");
188
+ return {
189
+ organizationId: e("organization-id"),
190
+ purposeId: e("purpose-id"),
191
+ principalId: e("principal-id"),
192
+ locale: e("locale"),
193
+ baseUrl: e("base-url"),
194
+ env: t === "live" || t === "sandbox" ? t : void 0,
195
+ apiBaseUrl: e("api-base-url")
196
+ };
197
+ }
198
+ function Q(n = {}, e) {
199
+ const t = n.root ?? v(), o = Array.from(t.querySelectorAll(G)), r = [];
200
+ for (const i of o) {
201
+ if (i.getAttribute("data-nbw-mounted") === "true") continue;
202
+ const s = J(i), l = s.organizationId ?? "", a = s.purposeId ?? "", c = s.principalId ?? "";
203
+ if (!l || !a || !c) {
204
+ const p = `nodbook-widget: missing ${[
205
+ !l && "`data-organization-id`",
206
+ !a && "`data-purpose-id`",
207
+ !c && "`data-principal-id`"
208
+ ].filter(Boolean).join(", ")}.`, x = f("span", "font-size:13px;color:#b91c1c;", "nbw-error");
209
+ x.setAttribute("role", "alert"), x.textContent = p, i.replaceChildren(x), e({ type: "error", message: p, data: { purposeId: a, principalId: c, organizationId: l } });
210
+ continue;
211
+ }
212
+ try {
213
+ const d = j(
214
+ i,
215
+ {
216
+ organizationId: l,
217
+ purposeId: a,
218
+ principalId: c,
219
+ locale: s.locale ?? n.locale,
220
+ baseUrl: s.baseUrl ?? n.baseUrl,
221
+ env: s.env ?? n.env,
222
+ apiBaseUrl: s.apiBaseUrl ?? n.apiBaseUrl
223
+ },
224
+ e
225
+ );
226
+ i.setAttribute("data-nbw-mounted", "true"), r.push(() => {
227
+ i.removeAttribute("data-nbw-mounted"), d();
228
+ });
229
+ } catch (d) {
230
+ const p = d instanceof Error ? d.message : "Failed to embed consent widget.";
231
+ e({ type: "error", message: p, data: { purposeId: a, principalId: c, organizationId: l } });
232
+ }
233
+ }
234
+ return () => {
235
+ for (const i of r)
236
+ try {
237
+ i();
238
+ } catch {
239
+ }
240
+ };
241
+ }
242
+ const X = "__consent_widget_overlay__", Z = 600, ee = 640;
243
+ function N(n, e) {
16
244
  var t;
17
245
  if (n) return n.replace(/\/$/, "");
18
- if (e && c[e]) return c[e];
246
+ if (e && W[e]) return W[e];
19
247
  try {
20
248
  const o = document.getElementsByTagName("script");
21
249
  for (let i = o.length - 1; i >= 0; i--) {
@@ -29,26 +257,25 @@ function v(n, e) {
29
257
  }
30
258
  return window.location.origin;
31
259
  }
32
- function k(n) {
260
+ function te(n) {
33
261
  const e = new URLSearchParams({
34
- auth_token: n.token,
35
262
  embed: "true",
36
263
  origin: window.location.origin
37
264
  });
38
- return n.mode === "preferences" ? `${n.baseUrl}/consent_manager/preferences?${e.toString()}` : n.mode === "direct_consent" ? (n.purposeId && e.set("purpose_id", n.purposeId), n.orgId && e.set("org_id", n.orgId), n.locale && e.set("locale", n.locale), `${n.baseUrl}/consent_manager/direct_consent?${e.toString()}`) : `${n.baseUrl}/consent_manager/consent/${encodeURIComponent(n.requestId ?? "")}?${e.toString()}`;
265
+ return n.token && e.set("auth_token", n.token), n.mode === "preferences" ? `${n.baseUrl}/consent_manager/preferences?${e.toString()}` : n.mode === "direct_consent" ? (n.purposeId && e.set("purpose_id", n.purposeId), n.organizationId && e.set("organization_id", n.organizationId), n.principalId && e.set("principal_id", n.principalId), n.locale && e.set("locale", n.locale), `${n.baseUrl}/consent_manager/direct_consent?${e.toString()}`) : `${n.baseUrl}/consent_manager/consent/${encodeURIComponent(n.requestId ?? "")}?${e.toString()}`;
39
266
  }
40
- class C {
267
+ class ne {
41
268
  constructor() {
42
- a(this, "overlay", null);
43
- a(this, "iframe", null);
44
- a(this, "session", null);
45
- a(this, "callbacks", /* @__PURE__ */ new Set());
46
- a(this, "listening", !1);
47
- a(this, "escHandler", (e) => {
269
+ m(this, "overlay", null);
270
+ m(this, "iframe", null);
271
+ m(this, "session", null);
272
+ m(this, "callbacks", /* @__PURE__ */ new Set());
273
+ m(this, "listening", !1);
274
+ m(this, "escHandler", (e) => {
48
275
  var t;
49
276
  e.key === "Escape" && this.close({ type: "closed", requestId: (t = this.session) == null ? void 0 : t.requestId });
50
277
  });
51
- a(this, "messageHandler", (e) => {
278
+ m(this, "messageHandler", (e) => {
52
279
  var o, r;
53
280
  if (!this.session || !this.iframe) return;
54
281
  let t = "";
@@ -58,32 +285,36 @@ class C {
58
285
  t = "";
59
286
  }
60
287
  if (!(t && e.origin !== t) && e.source === this.iframe.contentWindow) {
61
- if (E(e.data)) {
288
+ if (F(e.data)) {
289
+ if (!this.session.token) return;
62
290
  try {
63
291
  (o = this.iframe.contentWindow) == null || o.postMessage(
64
- { type: u, token: this.session.token },
292
+ { type: q, token: this.session.token },
65
293
  t || "*"
66
294
  );
67
295
  } catch {
68
296
  }
69
297
  return;
70
298
  }
71
- if (typeof e.data == "object" && e.data !== null && e.data.type === h) {
299
+ if (typeof e.data == "object" && e.data !== null && e.data.type === L) {
300
+ if (!this.session.token) return;
72
301
  try {
73
302
  (r = this.iframe.contentWindow) == null || r.postMessage(
74
- { type: u, token: this.session.token },
303
+ { type: q, token: this.session.token },
75
304
  t || "*"
76
305
  );
77
306
  } catch {
78
307
  }
79
308
  return;
80
309
  }
81
- if (b(e.data)) {
310
+ if (H(e.data)) {
82
311
  const i = e.data.event;
83
312
  this.emit(i), this.session.autoClose && (i.type === "consent_accepted" || i.type === "consent_declined" || i.type === "already_resolved" || i.type === "redirecting") && this.teardown();
84
313
  }
85
314
  }
86
315
  });
316
+ // ---- inline embed (no iframe) ----
317
+ m(this, "embeds", /* @__PURE__ */ new Set());
87
318
  }
88
319
  /** Open the consent dialog for a request. */
89
320
  openConsent(e, t, o) {
@@ -93,40 +324,63 @@ class C {
93
324
  openPreferences(e, t) {
94
325
  this.openDialog({ ...t, token: e, mode: "preferences" });
95
326
  }
96
- /** Open the direct-consent (permission-style) dialog for a purpose. */
327
+ /** Open the direct-consent (permission-style) dialog for a purpose (public — no JWT). */
97
328
  openDirectConsent(e, t, o, r, i) {
98
329
  const s = e == null ? void 0 : e.trim();
99
330
  if (!s)
100
331
  throw new Error("ConsentWidget.openDirectConsent: `purposeId` is required.");
101
- this.openDialog({ ...i, purposeId: s, token: t, orgId: o ?? null, locale: r, mode: "direct_consent" });
332
+ const l = t == null ? void 0 : t.trim();
333
+ if (!l)
334
+ throw new Error("ConsentWidget.openDirectConsent: `principalId` is required.");
335
+ const a = o ?? null;
336
+ if (!(a != null && a.trim()))
337
+ throw new Error("ConsentWidget.openDirectConsent: `organizationId` is required.");
338
+ this.openDialog({ ...i, purposeId: s, principalId: l, organizationId: a.trim(), locale: r, mode: "direct_consent" });
102
339
  }
103
340
  /**
104
341
  * Shared opener behind `openConsent` / `openPreferences` / `openDirectConsent`.
342
+ * `token` (JWT) is required for `consent` / `preferences` but NOT for
343
+ * public `direct_consent`, which identifies via principalId + organizationId.
105
344
  */
106
345
  openDialog(e) {
107
- var r;
108
- if (!e || typeof e.token != "string" || e.token.length === 0)
109
- throw new Error("ConsentWidget: `token` is required.");
110
- const t = ((r = e.purposeId) == null ? void 0 : r.trim()) || void 0, o = e.mode ?? (t ? "direct_consent" : e.requestId ? "consent" : "preferences");
111
- if (o === "consent" && !e.requestId)
112
- throw new Error("ConsentWidget: `requestId` is required for the consent dialog.");
346
+ var i, s, l, a, c;
347
+ const t = ((i = e.purposeId) == null ? void 0 : i.trim()) || void 0, o = e.mode ?? (t ? "direct_consent" : e.requestId ? "consent" : "preferences");
348
+ if (o === "consent") {
349
+ if (!e.requestId)
350
+ throw new Error("ConsentWidget: `requestId` is required for the consent dialog.");
351
+ if (!e.token)
352
+ throw new Error("ConsentWidget: `token` is required for the consent dialog.");
353
+ } else if (o === "preferences") {
354
+ if (!e.token)
355
+ throw new Error("ConsentWidget: `token` is required for the preferences dialog.");
356
+ } else {
357
+ const d = ((s = e.principalId) == null ? void 0 : s.trim()) || void 0, p = ((l = e.organizationId) == null ? void 0 : l.trim()) || void 0;
358
+ if (!t)
359
+ throw new Error("ConsentWidget.openDirectConsent: `purposeId` is required.");
360
+ if (!d)
361
+ throw new Error("ConsentWidget.openDirectConsent: `principalId` is required.");
362
+ if (!p)
363
+ throw new Error("ConsentWidget.openDirectConsent: `organizationId` is required.");
364
+ }
365
+ const r = ((a = e.organizationId) == null ? void 0 : a.trim()) || void 0;
113
366
  this.open({
114
367
  requestId: e.requestId,
115
368
  token: e.token,
116
369
  mode: o,
117
370
  purposeId: t,
118
- orgId: e.orgId ?? null,
371
+ principalId: ((c = e.principalId) == null ? void 0 : c.trim()) || void 0,
372
+ organizationId: r ?? null,
119
373
  locale: e.locale,
120
- baseUrl: v(e.baseUrl, e.env),
374
+ baseUrl: N(e.baseUrl, e.env),
121
375
  autoClose: e.autoClose ?? !0
122
376
  }), this.render(
123
377
  e.allowClose ?? !0,
124
- e.width ?? _,
125
- e.height ?? I
378
+ e.width ?? Z,
379
+ e.height ?? ee
126
380
  ), this.emit({
127
381
  type: "opened",
128
382
  requestId: e.requestId,
129
- data: t ? { purposeId: t } : void 0
383
+ data: t ? { purposeId: t, principalId: e.principalId, organizationId: r } : void 0
130
384
  });
131
385
  }
132
386
  /**
@@ -150,11 +404,67 @@ class C {
150
404
  }
151
405
  /** Alias of close() without emitting when already closed. */
152
406
  destroy() {
153
- this.callbacks.clear(), this.teardown();
407
+ this.callbacks.clear(), this.unmountEmbeds(), this.teardown();
154
408
  }
155
409
  isOpen() {
156
410
  return this.overlay !== null;
157
411
  }
412
+ trackEmbed(e) {
413
+ return this.embeds.add(e), () => {
414
+ this.embeds.delete(e), e();
415
+ };
416
+ }
417
+ unmountEmbeds() {
418
+ for (const e of this.embeds)
419
+ try {
420
+ e();
421
+ } catch {
422
+ }
423
+ this.embeds.clear();
424
+ }
425
+ /**
426
+ * Render an inline consent checkbox for a purpose into `target`
427
+ * (element or CSS selector), replacing its contents. Toggling the checkbox
428
+ * captures consent via the public direct-consent APIs (no JWT).
429
+ * Returns an unmount function.
430
+ *
431
+ * ConsentWidget.embedDirectConsent("#newsletter-consent", {
432
+ * organizationId: "org_...",
433
+ * purposeId: "purpose_123",
434
+ * principalId: "principal_123",
435
+ * });
436
+ */
437
+ embedDirectConsent(e, t) {
438
+ const o = typeof e == "string" ? (() => {
439
+ try {
440
+ const r = globalThis.document;
441
+ return (r == null ? void 0 : r.querySelector(e)) ?? null;
442
+ } catch {
443
+ return null;
444
+ }
445
+ })() : e;
446
+ if (!o)
447
+ throw new Error("ConsentWidget.embedDirectConsent: target element not found.");
448
+ return this.trackEmbed(j(o, t, (r) => this.emit(r)));
449
+ }
450
+ /**
451
+ * Embed every `.nodbook-widget` element on the page as an inline consent
452
+ * checkbox. Identifiers come from per-element data attributes
453
+ * (`data-organization-id`, `data-purpose-id`, `data-principal-id`,
454
+ * optional `data-locale`, `data-base-url`, `data-env`, `data-api-base-url`),
455
+ * falling back to `options` for gateway/locale settings.
456
+ * Returns a cleanup that unmounts everything mounted by this call.
457
+ *
458
+ * <div class="nodbook-widget"
459
+ * data-organization-id="org_..."
460
+ * data-purpose-id="purpose_123"
461
+ * data-principal-id="principal_123"></div>
462
+ * <script>ConsentWidget.embedNodbookWidgets();<\/script>
463
+ */
464
+ embedNodbookWidgets(e) {
465
+ const t = Q(e, (o) => this.emit(o));
466
+ return this.trackEmbed(t);
467
+ }
158
468
  // ---- internals ----
159
469
  open(e) {
160
470
  this.teardown(), this.session = e, this.ensureListening();
@@ -164,8 +474,8 @@ class C {
164
474
  }
165
475
  render(e, t, o) {
166
476
  if (!this.session) return;
167
- const r = k(this.session), i = document.createElement("div");
168
- i.id = x, i.setAttribute("role", "dialog"), i.setAttribute("aria-modal", "true"), i.style.cssText = [
477
+ const r = te(this.session), i = document.createElement("div");
478
+ i.id = X, i.setAttribute("role", "dialog"), i.setAttribute("aria-modal", "true"), i.style.cssText = [
169
479
  "position:fixed",
170
480
  "inset:0",
171
481
  "z-index:2147483647",
@@ -177,11 +487,11 @@ class C {
177
487
  "box-sizing:border-box",
178
488
  "pointer-events:auto"
179
489
  ].join(";");
180
- const s = document.createElement("div"), f = Math.min(t, window.innerWidth - 32), g = Math.min(o, window.innerHeight - 32);
490
+ const s = document.createElement("div"), l = Math.min(t, window.innerWidth - 32), a = Math.min(o, window.innerHeight - 32);
181
491
  if (s.style.cssText = [
182
- `width:${f}px`,
492
+ `width:${l}px`,
183
493
  "max-width:100%",
184
- `height:${g}px`,
494
+ `height:${a}px`,
185
495
  "max-height:100%",
186
496
  "background:#fff",
187
497
  "border-radius:16px",
@@ -192,8 +502,8 @@ class C {
192
502
  "flex-direction:column",
193
503
  "pointer-events:auto"
194
504
  ].join(";"), e) {
195
- const l = document.createElement("button");
196
- l.setAttribute("aria-label", "Close"), l.textContent = "×", l.style.cssText = [
505
+ const d = document.createElement("button");
506
+ d.setAttribute("aria-label", "Close"), d.textContent = "×", d.style.cssText = [
197
507
  "position:absolute",
198
508
  "top:16px",
199
509
  "right:16px",
@@ -209,12 +519,12 @@ class C {
209
519
  "cursor:pointer",
210
520
  "box-shadow:0 4px 12px rgba(0,0,0,0.25)",
211
521
  "pointer-events:auto"
212
- ].join(";"), l.onclick = () => this.close(), i.appendChild(l), i.addEventListener("mousedown", (p) => {
522
+ ].join(";"), d.onclick = () => this.close(), i.appendChild(d), i.addEventListener("mousedown", (p) => {
213
523
  p.target === i && this.close();
214
524
  });
215
525
  }
216
- const d = document.createElement("iframe");
217
- d.src = r, d.title = "Consent manager", d.setAttribute("allow", "clipboard-write"), d.style.cssText = [
526
+ const c = document.createElement("iframe");
527
+ c.src = r, c.title = "Consent manager", c.setAttribute("allow", "clipboard-write"), c.style.cssText = [
218
528
  "flex:1",
219
529
  "width:100%",
220
530
  "height:100%",
@@ -223,7 +533,7 @@ class C {
223
533
  "position:relative",
224
534
  "z-index:1",
225
535
  "pointer-events:auto"
226
- ].join(";"), s.appendChild(d), i.appendChild(s), document.body.appendChild(i), document.documentElement.style.overflow = "hidden", this.overlay = i, this.iframe = d;
536
+ ].join(";"), s.appendChild(c), i.appendChild(s), document.body.appendChild(i), document.documentElement.style.overflow = "hidden", this.overlay = i, this.iframe = c;
227
537
  }
228
538
  teardown() {
229
539
  var e;
@@ -242,9 +552,10 @@ class C {
242
552
  });
243
553
  }
244
554
  }
245
- const T = new C();
555
+ const oe = new ne();
246
556
  export {
247
- T as ConsentWidget,
248
- c as GATEWAY_BASE_URLS,
249
- T as default
557
+ oe as ConsentWidget,
558
+ W as GATEWAY_BASE_URLS,
559
+ G as NODBOOK_WIDGET_SELECTOR,
560
+ oe as default
250
561
  };
package/dist/react.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var C=Object.defineProperty;var x=(n,e,t)=>e in n?C(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var h=(n,e,t)=>x(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("react"),w={live:"https://ui.gateway.nodbook.in",sandbox:"https://sandbox-ui.gateway.nodbook.in"},k="CONSENT_WIDGET_EVENT",y="GATEWAY_UI_READY",b="PRINCIPAL_TOKEN";function _(n){return typeof n=="object"&&n!==null&&n.type===k&&typeof n.event=="object"}function I(n){return typeof n=="object"&&n!==null&&n.type===y}const v="__consent_widget_overlay__",A=600,T=640;function W(n,e){var t;if(n)return n.replace(/\/$/,"");if(e&&w[e])return w[e];try{const s=document.getElementsByTagName("script");for(let o=s.length-1;o>=0;o--){const a=((t=s[o])==null?void 0:t.getAttribute("src"))??"";if(a.includes("consent-widget"))return new URL(a,window.location.href).origin}const r=document.currentScript;if(r!=null&&r.src)return new URL(r.src,window.location.href).origin}catch{}return window.location.origin}function U(n){const e=new URLSearchParams({auth_token:n.token,embed:"true",origin:window.location.origin});return n.mode==="preferences"?`${n.baseUrl}/consent_manager/preferences?${e.toString()}`:n.mode==="direct_consent"?(n.purposeId&&e.set("purpose_id",n.purposeId),n.orgId&&e.set("org_id",n.orgId),n.locale&&e.set("locale",n.locale),`${n.baseUrl}/consent_manager/direct_consent?${e.toString()}`):`${n.baseUrl}/consent_manager/consent/${encodeURIComponent(n.requestId??"")}?${e.toString()}`}class q{constructor(){h(this,"overlay",null);h(this,"iframe",null);h(this,"session",null);h(this,"callbacks",new Set);h(this,"listening",!1);h(this,"escHandler",e=>{var t;e.key==="Escape"&&this.close({type:"closed",requestId:(t=this.session)==null?void 0:t.requestId})});h(this,"messageHandler",e=>{var s,r;if(!this.session||!this.iframe)return;let t="";try{t=new URL(this.session.baseUrl).origin}catch{t=""}if(!(t&&e.origin!==t)&&e.source===this.iframe.contentWindow){if(I(e.data)){try{(s=this.iframe.contentWindow)==null||s.postMessage({type:b,token:this.session.token},t||"*")}catch{}return}if(typeof e.data=="object"&&e.data!==null&&e.data.type===y){try{(r=this.iframe.contentWindow)==null||r.postMessage({type:b,token:this.session.token},t||"*")}catch{}return}if(_(e.data)){const o=e.data.event;this.emit(o),this.session.autoClose&&(o.type==="consent_accepted"||o.type==="consent_declined"||o.type==="already_resolved"||o.type==="redirecting")&&this.teardown()}}})}openConsent(e,t,s){this.openDialog({...s,requestId:e,token:t,mode:"consent"})}openPreferences(e,t){this.openDialog({...t,token:e,mode:"preferences"})}openDirectConsent(e,t,s,r,o){const a=e==null?void 0:e.trim();if(!a)throw new Error("ConsentWidget.openDirectConsent: `purposeId` is required.");this.openDialog({...o,purposeId:a,token:t,orgId:s??null,locale:r,mode:"direct_consent"})}openDialog(e){var r;if(!e||typeof e.token!="string"||e.token.length===0)throw new Error("ConsentWidget: `token` is required.");const t=((r=e.purposeId)==null?void 0:r.trim())||void 0,s=e.mode??(t?"direct_consent":e.requestId?"consent":"preferences");if(s==="consent"&&!e.requestId)throw new Error("ConsentWidget: `requestId` is required for the consent dialog.");this.open({requestId:e.requestId,token:e.token,mode:s,purposeId:t,orgId:e.orgId??null,locale:e.locale,baseUrl:W(e.baseUrl,e.env),autoClose:e.autoClose??!0}),this.render(e.allowClose??!0,e.width??A,e.height??T),this.emit({type:"opened",requestId:e.requestId,data:t?{purposeId:t}:void 0})}onCallback(e){return this.callbacks.add(e),()=>{this.callbacks.delete(e)}}close(e){var r;const t=e??{type:"closed",requestId:(r=this.session)==null?void 0:r.requestId},s=this.overlay!==null;this.teardown(),s&&this.emit(t)}destroy(){this.callbacks.clear(),this.teardown()}isOpen(){return this.overlay!==null}open(e){this.teardown(),this.session=e,this.ensureListening()}ensureListening(){this.listening||(window.addEventListener("message",this.messageHandler),window.addEventListener("keydown",this.escHandler),this.listening=!0)}render(e,t,s){if(!this.session)return;const r=U(this.session),o=document.createElement("div");o.id=v,o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.style.cssText=["position:fixed","inset:0","z-index:2147483647","display:flex","align-items:center","justify-content:center","background:rgba(15,23,42,0.55)","padding:16px","box-sizing:border-box","pointer-events:auto"].join(";");const a=document.createElement("div"),g=Math.min(t,window.innerWidth-32),m=Math.min(s,window.innerHeight-32);if(a.style.cssText=[`width:${g}px`,"max-width:100%",`height:${m}px`,"max-height:100%","background:#fff","border-radius:16px","overflow:hidden","position:relative","box-shadow:0 25px 50px -12px rgba(0,0,0,0.35)","display:flex","flex-direction:column","pointer-events:auto"].join(";"),e){const i=document.createElement("button");i.setAttribute("aria-label","Close"),i.textContent="×",i.style.cssText=["position:absolute","top:16px","right:16px","z-index:2","width:32px","height:32px","border-radius:9999px","border:1px solid #e2e8f0","background:#ffffff","color:#475569","font-size:18px","line-height:1","cursor:pointer","box-shadow:0 4px 12px rgba(0,0,0,0.25)","pointer-events:auto"].join(";"),i.onclick=()=>this.close(),o.appendChild(i),o.addEventListener("mousedown",l=>{l.target===o&&this.close()})}const u=document.createElement("iframe");u.src=r,u.title="Consent manager",u.setAttribute("allow","clipboard-write"),u.style.cssText=["flex:1","width:100%","height:100%","border:0","background:#fff","position:relative","z-index:1","pointer-events:auto"].join(";"),a.appendChild(u),o.appendChild(a),document.body.appendChild(o),document.documentElement.style.overflow="hidden",this.overlay=o,this.iframe=u}teardown(){var e;(e=this.overlay)!=null&&e.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.iframe=null,this.session=null,this.listening&&(window.removeEventListener("message",this.messageHandler),window.removeEventListener("keydown",this.escHandler),this.listening=!1);try{document.documentElement.style.overflow=""}catch{}}emit(e){this.callbacks.forEach(t=>{try{t(e)}catch{}})}}const c=new q;function L(n){const{onEvent:e,closeOnUnmount:t=!0}=n??{};d.useEffect(()=>{if(e)return c.onCallback(e)},[e]),d.useEffect(()=>{if(t)return()=>{c.isOpen()&&c.close()}},[t]);const s=d.useCallback((i,l)=>{const{requestId:f,...p}=l??{};f?c.openConsent(f,i,p):c.openPreferences(i,p)},[]),r=d.useCallback((i,l,f)=>{c.openConsent(i,l,f)},[]),o=d.useCallback((i,l)=>{c.openPreferences(i,l)},[]),a=d.useCallback((i,l,f,p,E)=>{c.openDirectConsent(i,l,f,p,E)},[]),g=d.useCallback(i=>{c.close(i)},[]),m=d.useCallback(i=>c.onCallback(i),[]),u=d.useCallback(()=>c.isOpen(),[]);return{open:s,openConsent:r,openPreferences:o,openDirectConsent:a,close:g,onEvent:m,isOpen:u}}exports.useConsentWidget=L;
1
+ "use strict";var R=Object.defineProperty;var P=(n,e,t)=>e in n?R(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var C=(n,e,t)=>P(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("react"),L={live:"https://ui.gateway.nodbook.in",sandbox:"https://sandbox-ui.gateway.nodbook.in"},H="CONSENT_WIDGET_EVENT",N="GATEWAY_UI_READY",O="PRINCIPAL_TOKEN";function M(n){return typeof n=="object"&&n!==null&&n.type===H&&typeof n.event=="object"}function F(n){return typeof n=="object"&&n!==null&&n.type===N}const G=".nodbook-widget";function U(){const n=globalThis.document;if(!n)throw new Error("nodbook-widget: `document` is not available in this environment.");return n}function Y(n){var t,o;const e=n==null?void 0:n.trim();if(e)return e;try{const r=globalThis.navigator,i=(o=(t=r==null?void 0:r.language)==null?void 0:t.split("-")[0])==null?void 0:o.trim();if(i)return i}catch{}return"en"}function K(n){var t;return(((t=n.apiBaseUrl)==null?void 0:t.trim())||B(n.baseUrl,n.env)).replace(/\/$/,"")}function j(n,e){var t;if(typeof n=="object"&&n!==null){const o=(t=n.error_data)==null?void 0:t.description;if(typeof o=="string"&&o.trim())return o}return e}async function V(n,e){const t=await fetch(`${n}/v1/public/direct_consents/purpose`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),o=await t.json().catch(()=>null);if(!t.ok)throw new Error(j(o,`Failed to load purpose (${t.status}).`));const r=o==null?void 0:o.data;if(!r||typeof r!="object"||!("id"in r))throw new Error("Failed to load purpose: unexpected response shape.");return r}async function J(n,e){let t="";try{const s=globalThis.navigator;typeof(s==null?void 0:s.userAgent)=="string"&&(t=s.userAgent)}catch{}const o=await fetch(`${n}/v1/public/direct_consents`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,device_details:{user_agent:t,timestamp:new Date().toISOString()}})}),r=await o.json().catch(()=>null);if(!o.ok)throw new Error(j(r,`Failed to record consent (${o.status}).`));const i=r==null?void 0:r.data;if(!i||typeof i!="object"||!Array.isArray(i.consent_ids))throw new Error("Failed to record consent: unexpected response shape.");return i}function Q(n,e){var o,r;const t=((o=n.locales)==null?void 0:o[e])??((r=n.locales)==null?void 0:r.en)??Object.values(n.locales??{})[0];return{name:(t==null?void 0:t.name)??n.name??n.identifier??n.id,description:(t==null?void 0:t.description)??n.description??""}}function m(n,e,t){const r=U().createElement(n);return r.className=t,r.setAttribute("style",e),r}function $(n,e,t){var x,A,W;const o=(x=e.organizationId)==null?void 0:x.trim(),r=(A=e.purposeId)==null?void 0:A.trim(),i=(W=e.principalId)==null?void 0:W.trim();if(!o||!r||!i)throw new Error("embedDirectConsent: `organizationId`, `purposeId` and `principalId` are required.");const s={organizationId:o,purposeId:r,principalId:i,locale:Y(e.locale),apiBaseUrl:K(e)},u={purposeId:r,principalId:i,organizationId:o};let a=!1,c=!1;const l=m("div","display:flex;flex-direction:column;gap:8px;font:inherit;color:inherit;","nbw-root"),p=w=>{const g=m("span","font-size:13px;opacity:0.65;","nbw-loading");return g.textContent=w,l.replaceChildren(g),g},d=(w,g)=>{if(a)return;const v=m("div","display:flex;flex-direction:column;gap:6px;","nbw-error-wrap"),I=m("span","font-size:13px;color:#b91c1c;","nbw-error");if(I.setAttribute("role","alert"),I.textContent=w,v.appendChild(I),g){const z=m("button","align-self:flex-start;font:inherit;font-size:13px;color:#0b57d0;background:none;border:none;padding:0;cursor:pointer;text-decoration:underline;","nbw-retry");z.textContent="Retry",z.addEventListener("click",g),v.appendChild(z)}l.replaceChildren(v)};p("Loading consent…"),n.replaceChildren(l);const h=()=>{p("Loading consent…"),V(s.apiBaseUrl,{organization_id:s.organizationId,purpose_id:s.purposeId}).then(w=>{a||E(w)},w=>{if(a)return;const g=w instanceof Error?w.message:"Failed to load purpose.";t({type:"error",message:g,data:u}),d(g,h)})},E=w=>{if(a)return;const{name:g,description:v}=Q(w,s.locale),I=m("label","display:flex;gap:8px;align-items:flex-start;cursor:pointer;font:inherit;","nbw-label"),y=U().createElement("input");y.type="checkbox",y.className="nbw-checkbox",y.setAttribute("style","margin-top:2px;width:16px;height:16px;accent-color:#0b57d0;cursor:pointer;flex-shrink:0;");const D=m("span","display:flex;flex-direction:column;gap:2px;min-width:0;","nbw-text"),T=m("span","font-size:14px;font-weight:600;line-height:1.35;","nbw-name");if(T.textContent=g,D.appendChild(T),v){const k=m("span","font-size:12px;line-height:1.4;opacity:0.75;","nbw-description");k.textContent=v,D.appendChild(k)}I.appendChild(y),I.appendChild(D);const _=m("span","font-size:12px;opacity:0.65;","nbw-status");_.setAttribute("aria-live","polite"),y.addEventListener("change",()=>{if(c||a)return;c=!0;const k=y.checked;y.disabled=!0,_.textContent="Saving…",J(s.apiBaseUrl,{organization_id:s.organizationId,principal_id:s.principalId,purpose_id:s.purposeId,active:k,locale:s.locale}).then(()=>{a||(c=!1,y.disabled=!1,_.textContent="",t({type:k?"consent_accepted":"consent_declined",data:u}))},q=>{if(a)return;c=!1,y.checked=!k,y.disabled=!1;const S=q instanceof Error?q.message:"Failed to record consent.";_.textContent=S,t({type:"error",message:S,data:u})})}),l.replaceChildren(I,_)};return h(),()=>{a=!0,l.remove()}}function X(n){const e=o=>{var i;return((i=n.getAttribute(`data-${o}`))==null?void 0:i.trim())||void 0},t=e("env");return{organizationId:e("organization-id"),purposeId:e("purpose-id"),principalId:e("principal-id"),locale:e("locale"),baseUrl:e("base-url"),env:t==="live"||t==="sandbox"?t:void 0,apiBaseUrl:e("api-base-url")}}function Z(n={},e){const t=n.root??U(),o=Array.from(t.querySelectorAll(G)),r=[];for(const i of o){if(i.getAttribute("data-nbw-mounted")==="true")continue;const s=X(i),u=s.organizationId??"",a=s.purposeId??"",c=s.principalId??"";if(!u||!a||!c){const p=`nodbook-widget: missing ${[!u&&"`data-organization-id`",!a&&"`data-purpose-id`",!c&&"`data-principal-id`"].filter(Boolean).join(", ")}.`,d=m("span","font-size:13px;color:#b91c1c;","nbw-error");d.setAttribute("role","alert"),d.textContent=p,i.replaceChildren(d),e({type:"error",message:p,data:{purposeId:a,principalId:c,organizationId:u}});continue}try{const l=$(i,{organizationId:u,purposeId:a,principalId:c,locale:s.locale??n.locale,baseUrl:s.baseUrl??n.baseUrl,env:s.env??n.env,apiBaseUrl:s.apiBaseUrl??n.apiBaseUrl},e);i.setAttribute("data-nbw-mounted","true"),r.push(()=>{i.removeAttribute("data-nbw-mounted"),l()})}catch(l){const p=l instanceof Error?l.message:"Failed to embed consent widget.";e({type:"error",message:p,data:{purposeId:a,principalId:c,organizationId:u}})}}return()=>{for(const i of r)try{i()}catch{}}}const ee="__consent_widget_overlay__",te=600,ne=640;function B(n,e){var t;if(n)return n.replace(/\/$/,"");if(e&&L[e])return L[e];try{const o=document.getElementsByTagName("script");for(let i=o.length-1;i>=0;i--){const s=((t=o[i])==null?void 0:t.getAttribute("src"))??"";if(s.includes("consent-widget"))return new URL(s,window.location.href).origin}const r=document.currentScript;if(r!=null&&r.src)return new URL(r.src,window.location.href).origin}catch{}return window.location.origin}function re(n){const e=new URLSearchParams({embed:"true",origin:window.location.origin});return n.token&&e.set("auth_token",n.token),n.mode==="preferences"?`${n.baseUrl}/consent_manager/preferences?${e.toString()}`:n.mode==="direct_consent"?(n.purposeId&&e.set("purpose_id",n.purposeId),n.organizationId&&e.set("organization_id",n.organizationId),n.principalId&&e.set("principal_id",n.principalId),n.locale&&e.set("locale",n.locale),`${n.baseUrl}/consent_manager/direct_consent?${e.toString()}`):`${n.baseUrl}/consent_manager/consent/${encodeURIComponent(n.requestId??"")}?${e.toString()}`}class oe{constructor(){C(this,"overlay",null);C(this,"iframe",null);C(this,"session",null);C(this,"callbacks",new Set);C(this,"listening",!1);C(this,"escHandler",e=>{var t;e.key==="Escape"&&this.close({type:"closed",requestId:(t=this.session)==null?void 0:t.requestId})});C(this,"messageHandler",e=>{var o,r;if(!this.session||!this.iframe)return;let t="";try{t=new URL(this.session.baseUrl).origin}catch{t=""}if(!(t&&e.origin!==t)&&e.source===this.iframe.contentWindow){if(F(e.data)){if(!this.session.token)return;try{(o=this.iframe.contentWindow)==null||o.postMessage({type:O,token:this.session.token},t||"*")}catch{}return}if(typeof e.data=="object"&&e.data!==null&&e.data.type===N){if(!this.session.token)return;try{(r=this.iframe.contentWindow)==null||r.postMessage({type:O,token:this.session.token},t||"*")}catch{}return}if(M(e.data)){const i=e.data.event;this.emit(i),this.session.autoClose&&(i.type==="consent_accepted"||i.type==="consent_declined"||i.type==="already_resolved"||i.type==="redirecting")&&this.teardown()}}});C(this,"embeds",new Set)}openConsent(e,t,o){this.openDialog({...o,requestId:e,token:t,mode:"consent"})}openPreferences(e,t){this.openDialog({...t,token:e,mode:"preferences"})}openDirectConsent(e,t,o,r,i){const s=e==null?void 0:e.trim();if(!s)throw new Error("ConsentWidget.openDirectConsent: `purposeId` is required.");const u=t==null?void 0:t.trim();if(!u)throw new Error("ConsentWidget.openDirectConsent: `principalId` is required.");const a=o??null;if(!(a!=null&&a.trim()))throw new Error("ConsentWidget.openDirectConsent: `organizationId` is required.");this.openDialog({...i,purposeId:s,principalId:u,organizationId:a.trim(),locale:r,mode:"direct_consent"})}openDialog(e){var i,s,u,a,c;const t=((i=e.purposeId)==null?void 0:i.trim())||void 0,o=e.mode??(t?"direct_consent":e.requestId?"consent":"preferences");if(o==="consent"){if(!e.requestId)throw new Error("ConsentWidget: `requestId` is required for the consent dialog.");if(!e.token)throw new Error("ConsentWidget: `token` is required for the consent dialog.")}else if(o==="preferences"){if(!e.token)throw new Error("ConsentWidget: `token` is required for the preferences dialog.")}else{const l=((s=e.principalId)==null?void 0:s.trim())||void 0,p=((u=e.organizationId)==null?void 0:u.trim())||void 0;if(!t)throw new Error("ConsentWidget.openDirectConsent: `purposeId` is required.");if(!l)throw new Error("ConsentWidget.openDirectConsent: `principalId` is required.");if(!p)throw new Error("ConsentWidget.openDirectConsent: `organizationId` is required.")}const r=((a=e.organizationId)==null?void 0:a.trim())||void 0;this.open({requestId:e.requestId,token:e.token,mode:o,purposeId:t,principalId:((c=e.principalId)==null?void 0:c.trim())||void 0,organizationId:r??null,locale:e.locale,baseUrl:B(e.baseUrl,e.env),autoClose:e.autoClose??!0}),this.render(e.allowClose??!0,e.width??te,e.height??ne),this.emit({type:"opened",requestId:e.requestId,data:t?{purposeId:t,principalId:e.principalId,organizationId:r}:void 0})}onCallback(e){return this.callbacks.add(e),()=>{this.callbacks.delete(e)}}close(e){var r;const t=e??{type:"closed",requestId:(r=this.session)==null?void 0:r.requestId},o=this.overlay!==null;this.teardown(),o&&this.emit(t)}destroy(){this.callbacks.clear(),this.unmountEmbeds(),this.teardown()}isOpen(){return this.overlay!==null}trackEmbed(e){return this.embeds.add(e),()=>{this.embeds.delete(e),e()}}unmountEmbeds(){for(const e of this.embeds)try{e()}catch{}this.embeds.clear()}embedDirectConsent(e,t){const o=typeof e=="string"?(()=>{try{const r=globalThis.document;return(r==null?void 0:r.querySelector(e))??null}catch{return null}})():e;if(!o)throw new Error("ConsentWidget.embedDirectConsent: target element not found.");return this.trackEmbed($(o,t,r=>this.emit(r)))}embedNodbookWidgets(e){const t=Z(e,o=>this.emit(o));return this.trackEmbed(t)}open(e){this.teardown(),this.session=e,this.ensureListening()}ensureListening(){this.listening||(window.addEventListener("message",this.messageHandler),window.addEventListener("keydown",this.escHandler),this.listening=!0)}render(e,t,o){if(!this.session)return;const r=re(this.session),i=document.createElement("div");i.id=ee,i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.style.cssText=["position:fixed","inset:0","z-index:2147483647","display:flex","align-items:center","justify-content:center","background:rgba(15,23,42,0.55)","padding:16px","box-sizing:border-box","pointer-events:auto"].join(";");const s=document.createElement("div"),u=Math.min(t,window.innerWidth-32),a=Math.min(o,window.innerHeight-32);if(s.style.cssText=[`width:${u}px`,"max-width:100%",`height:${a}px`,"max-height:100%","background:#fff","border-radius:16px","overflow:hidden","position:relative","box-shadow:0 25px 50px -12px rgba(0,0,0,0.35)","display:flex","flex-direction:column","pointer-events:auto"].join(";"),e){const l=document.createElement("button");l.setAttribute("aria-label","Close"),l.textContent="×",l.style.cssText=["position:absolute","top:16px","right:16px","z-index:2","width:32px","height:32px","border-radius:9999px","border:1px solid #e2e8f0","background:#ffffff","color:#475569","font-size:18px","line-height:1","cursor:pointer","box-shadow:0 4px 12px rgba(0,0,0,0.25)","pointer-events:auto"].join(";"),l.onclick=()=>this.close(),i.appendChild(l),i.addEventListener("mousedown",p=>{p.target===i&&this.close()})}const c=document.createElement("iframe");c.src=r,c.title="Consent manager",c.setAttribute("allow","clipboard-write"),c.style.cssText=["flex:1","width:100%","height:100%","border:0","background:#fff","position:relative","z-index:1","pointer-events:auto"].join(";"),s.appendChild(c),i.appendChild(s),document.body.appendChild(i),document.documentElement.style.overflow="hidden",this.overlay=i,this.iframe=c}teardown(){var e;(e=this.overlay)!=null&&e.parentNode&&this.overlay.parentNode.removeChild(this.overlay),this.overlay=null,this.iframe=null,this.session=null,this.listening&&(window.removeEventListener("message",this.messageHandler),window.removeEventListener("keydown",this.escHandler),this.listening=!1);try{document.documentElement.style.overflow=""}catch{}}emit(e){this.callbacks.forEach(t=>{try{t(e)}catch{}})}}const f=new oe;function ie(n){const{onEvent:e,closeOnUnmount:t=!0}=n??{};b.useEffect(()=>{if(e)return f.onCallback(e)},[e]),b.useEffect(()=>{if(t)return()=>{f.isOpen()&&f.close()}},[t]);const o=b.useCallback((d,h)=>{const{requestId:E,...x}=h??{};E?f.openConsent(E,d,x):f.openPreferences(d,x)},[]),r=b.useCallback((d,h,E)=>{f.openConsent(d,h,E)},[]),i=b.useCallback((d,h)=>{f.openPreferences(d,h)},[]),s=b.useCallback((d,h,E,x,A)=>{f.openDirectConsent(d,h,E,x,A)},[]),u=b.useCallback(d=>{f.close(d)},[]),a=b.useCallback((d,h)=>f.embedDirectConsent(d,h),[]),c=b.useCallback(d=>f.embedNodbookWidgets(d),[]),l=b.useCallback(d=>f.onCallback(d),[]),p=b.useCallback(()=>f.isOpen(),[]);return{open:o,openConsent:r,openPreferences:i,openDirectConsent:s,embedDirectConsent:a,embedNodbookWidgets:c,close:u,onEvent:l,isOpen:p}}exports.useConsentWidget=ie;
package/dist/react.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { WidgetCallback, WidgetEvent, WidgetOptions } from "./core/types";
2
+ import type { EmbedDirectConsentOptions, EmbedScanOptions } from "./core/widget";
2
3
  export interface UseConsentWidgetOptions {
3
4
  /** Called on every widget event (opened / accepted / declined / ... / closed). */
4
5
  onEvent?: WidgetCallback;
@@ -14,8 +15,12 @@ export interface UseConsentWidgetApi {
14
15
  openConsent: (requestId: string, token: string, options?: WidgetOptions) => void;
15
16
  /** Open the preferences (my consents + grievances) dialog. */
16
17
  openPreferences: (token: string, options?: WidgetOptions) => void;
17
- /** Open the direct-consent (permission-style) dialog for a purpose. */
18
- openDirectConsent: (purposeId: string, token: string, orgId?: string | null, locale?: string, options?: WidgetOptions) => void;
18
+ /** Open the direct-consent (permission-style) dialog for a purpose (public — no JWT). */
19
+ openDirectConsent: (purposeId: string, principalId: string, organizationId?: string | null, locale?: string, options?: WidgetOptions) => void;
20
+ /** Render an inline consent checkbox into `target` (element or selector). Toggling captures via the public APIs. Returns an unmount function. */
21
+ embedDirectConsent: (target: string | Element, options: EmbedDirectConsentOptions) => () => void;
22
+ /** Embed every `.nodbook-widget` element as an inline consent checkbox. Returns a cleanup. */
23
+ embedNodbookWidgets: (options?: EmbedScanOptions) => () => void;
19
24
  /** Programmatically close the dialog (emits a `closed` event). */
20
25
  close: (event?: WidgetEvent) => void;
21
26
  /** Subscribe to flow events. Returns an unsubscribe function. */
@@ -24,4 +29,4 @@ export interface UseConsentWidgetApi {
24
29
  isOpen: () => boolean;
25
30
  }
26
31
  export declare function useConsentWidget(options?: UseConsentWidgetOptions): UseConsentWidgetApi;
27
- export type { WidgetCallback, WidgetEvent, WidgetOptions, };
32
+ export type { WidgetCallback, WidgetEvent, WidgetOptions, EmbedDirectConsentOptions, EmbedScanOptions, };