@truzyx/consent-widget 0.2.4 → 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/README.md +55 -10
- package/dist/core/embed.d.ts +95 -0
- package/dist/core/types.d.ts +1 -1
- package/dist/core/widget.d.ts +43 -6
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +368 -57
- package/dist/react.cjs +1 -1
- package/dist/react.d.ts +8 -3
- package/dist/react.js +404 -94
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -20,8 +20,11 @@ No bundler? Use the script-tag build served from your gateway host instead (glob
|
|
|
20
20
|
|-----------|---------------------|
|
|
21
21
|
| `baseUrl` | Your gateway origin. Optional — precedence is: explicit `baseUrl` → `env` → `<script>` tag origin → current origin. |
|
|
22
22
|
| `env` | `"live"` (`https://ui.gateway.nodbook.in`) or `"sandbox"` (`https://sandbox-ui.gateway.nodbook.in`). Used only when `baseUrl` is omitted. |
|
|
23
|
-
| `token` | Principal JWT for the end user, issued by your backend. Sent to the gateway as `?auth_token=` and via `postMessage`. |
|
|
23
|
+
| `token` | Principal JWT for the end user, issued by your backend. Sent to the gateway as `?auth_token=` and via `postMessage`. Required for consent / preferences only — direct consent is public and takes no JWT. |
|
|
24
24
|
| `requestId` | Consent request id created via the gateway API. Required for the consent dialog only. |
|
|
25
|
+
| `purposeId` | Purpose id for the direct-consent dialog (public). |
|
|
26
|
+
| `principalId` | Principal id the direct consent is recorded against (public). |
|
|
27
|
+
| `organizationId` | Organization id owning the purpose (public). |
|
|
25
28
|
|
|
26
29
|
## Usage
|
|
27
30
|
|
|
@@ -40,9 +43,9 @@ ConsentWidget.openPreferences("<principal-jwt>", {
|
|
|
40
43
|
baseUrl: "https://consent.truzyx.com",
|
|
41
44
|
});
|
|
42
45
|
|
|
43
|
-
// Or direct-consent dialog for a purpose
|
|
44
|
-
ConsentWidget.openDirectConsent("purpose_123", "
|
|
45
|
-
|
|
46
|
+
// Or direct-consent dialog for a purpose (public — no JWT)
|
|
47
|
+
ConsentWidget.openDirectConsent("purpose_123", "principal_123", "org_01K9Z8Q3M5X7T2V4B6N8P0R2S1", undefined, {
|
|
48
|
+
baseUrl: "https://consent.truzyx.com",
|
|
46
49
|
});
|
|
47
50
|
|
|
48
51
|
// React to flow completion
|
|
@@ -82,6 +85,46 @@ function CheckoutButton() {
|
|
|
82
85
|
|
|
83
86
|
The hook subscribes/unsubscribes the callback automatically and closes the dialog if the component unmounts (`closeOnUnmount: true` by default; set `false` to opt out). No JSX component is provided — the dialog is imperative by design so it behaves identically in any tree.
|
|
84
87
|
|
|
88
|
+
### Inline embed — consent checkbox (no iframe)
|
|
89
|
+
|
|
90
|
+
Render a purpose as a checkbox directly inside your page. The widget fetches
|
|
91
|
+
the purpose text and captures accept/revoke on toggle via the public
|
|
92
|
+
direct-consent APIs (no JWT, no iframe):
|
|
93
|
+
|
|
94
|
+
```html
|
|
95
|
+
<div class="nodbook-widget"
|
|
96
|
+
data-organization-id="org_01K9Z8Q3M5X7T2V4B6N8P0R2S1"
|
|
97
|
+
data-purpose-id="01K9Z8Q3M5X7T2V4B6N8P0R2S5"
|
|
98
|
+
data-principal-id="01K9Z8Q3M5X7T2V4B6N8P0R2S4"
|
|
99
|
+
data-locale="en"></div>
|
|
100
|
+
<script src="https://<gateway-host>/consent-widget.js"></script>
|
|
101
|
+
<script>
|
|
102
|
+
const unmount = ConsentWidget.embedNodbookWidgets();
|
|
103
|
+
ConsentWidget.onCallback((e) => console.log(e.type, e.data));
|
|
104
|
+
// unmount(); // detach all inline checkboxes mounted by the scan
|
|
105
|
+
</script>
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Or mount into one element imperatively (selector or `Element`, returns an
|
|
109
|
+
unmount function):
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { ConsentWidget } from "@truzyx/consent-widget";
|
|
113
|
+
|
|
114
|
+
const unmount = ConsentWidget.embedDirectConsent("#newsletter-consent", {
|
|
115
|
+
organizationId: "org_01K9Z8Q3M5X7T2V4B6N8P0R2S1",
|
|
116
|
+
purposeId: "01K9Z8Q3M5X7T2V4B6N8P0R2S5",
|
|
117
|
+
principalId: "01K9Z8Q3M5X7T2V4B6N8P0R2S4",
|
|
118
|
+
locale: "en", // optional, defaults to browser language
|
|
119
|
+
apiBaseUrl: "https://api.your-gateway.com", // optional, defaults to baseUrl
|
|
120
|
+
});
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Checking the box captures `active: true`, unchecking captures `active: false`
|
|
124
|
+
(revoke). Completion flows through the same `onCallback` (`consent_accepted` /
|
|
125
|
+
`consent_declined` / `error` with `data: { purposeId, principalId,
|
|
126
|
+
organizationId }`).
|
|
127
|
+
|
|
85
128
|
### Script tag (no build step)
|
|
86
129
|
|
|
87
130
|
```html
|
|
@@ -103,7 +146,9 @@ Vanilla singleton methods and hook return value are the same, except the hook ad
|
|
|
103
146
|
|--------|-----------|-------------|
|
|
104
147
|
| `openConsent` | `(requestId: string, token: string, options?: WidgetOptions) => void` | Open the consent dialog for a request. Replaces any open dialog. |
|
|
105
148
|
| `openPreferences` | `(token: string, options?: WidgetOptions) => void` | Open the preferences dialog. Replaces any open dialog. |
|
|
106
|
-
| `openDirectConsent` | `(purposeId: string,
|
|
149
|
+
| `openDirectConsent` | `(purposeId: string, principalId: string, organizationId?: string \| null, locale?: string, options?: WidgetOptions) => void` | Open the direct-consent dialog (public, no JWT). |
|
|
150
|
+
| `embedDirectConsent` | `(target: string \| Element, options: EmbedDirectConsentOptions) => () => void` | Render an inline consent checkbox into `target` (replaces contents). Toggle captures via the public APIs. Returns unmount. |
|
|
151
|
+
| `embedNodbookWidgets` | `(options?: EmbedScanOptions) => () => void` | Embed every `.nodbook-widget` element (identifiers from `data-organization-id` / `data-purpose-id` / `data-principal-id`, optional `data-locale`, `data-base-url`, `data-env`, `data-api-base-url`). Returns cleanup. |
|
|
107
152
|
| `onCallback` | `(cb: WidgetCallback) => void` | Subscribe to every flow event. Returns an unsubscribe function. |
|
|
108
153
|
| `close` | `(event?: WidgetEvent) => void` | Close the dialog; emits a `closed` event if one was open. |
|
|
109
154
|
| `destroy` | `() => void` | Clear all callbacks and close without emitting. |
|
|
@@ -111,7 +156,7 @@ Vanilla singleton methods and hook return value are the same, except the hook ad
|
|
|
111
156
|
|
|
112
157
|
### `WidgetOptions`
|
|
113
158
|
|
|
114
|
-
Common options shared by every method. Identifiers (`
|
|
159
|
+
Common options shared by every method. Identifiers travel directly as method arguments — never inside this object (`requestId` + `token` for consent, `token` for preferences, `purposeId` + `principalId` + `organizationId` for direct consent).
|
|
115
160
|
|
|
116
161
|
| Field | Type | Default | Description |
|
|
117
162
|
|-------|------|---------|-------------|
|
|
@@ -135,14 +180,14 @@ Common options shared by every method. Identifiers (`token`, `requestId`, `purpo
|
|
|
135
180
|
|
|
136
181
|
## How it works
|
|
137
182
|
|
|
138
|
-
- The widget renders a modal overlay with an `<iframe>` pointing at `{baseUrl}/consent_manager/consent/{requestId}`, `{baseUrl}/consent_manager/preferences`, or `{baseUrl}/consent_manager/direct_consent`, with `?
|
|
139
|
-
- The token is also delivered via `postMessage` (`PRINCIPAL_TOKEN`) when the iframe signals readiness.
|
|
183
|
+
- The widget renders a modal overlay with an `<iframe>` pointing at `{baseUrl}/consent_manager/consent/{requestId}`, `{baseUrl}/consent_manager/preferences`, or `{baseUrl}/consent_manager/direct_consent`, with `?embed=true&origin=<your-origin>` plus `?auth_token=<token>` (consent / preferences only) or `?purpose_id=&principal_id=&organization_id=` (direct consent, public).
|
|
184
|
+
- The token is also delivered via `postMessage` (`PRINCIPAL_TOKEN`) when the iframe signals readiness (authenticated flows only).
|
|
140
185
|
- Flow completion is reported back as `CONSENT_WIDGET_EVENT` messages, validated against the gateway origin, and fanned out to your callbacks. In embed mode the gateway pages render chromeless (no extra card/background) so only the widget's single card is visible.
|
|
141
186
|
- Because the dialog is an iframe, there is no CSS leakage in either direction.
|
|
142
187
|
|
|
143
188
|
## Trying it locally
|
|
144
189
|
|
|
145
|
-
The gateway repo ships a dev harness at `/consent_manager/check` (query params `requestId`, `token`/`auth_token`, `baseUrl`) that drives this same core and logs every callback event — useful to validate your
|
|
190
|
+
The gateway repo ships a dev harness at `/consent_manager/check` (query params `requestId`, `token`/`auth_token`, `purpose_id`, `principal_id`, `organization_id`, `baseUrl`) that drives this same core and logs every callback event — useful to validate your ids/`token` before integrating.
|
|
146
191
|
|
|
147
192
|
## Package layout
|
|
148
193
|
|
|
@@ -151,4 +196,4 @@ The gateway repo ships a dev harness at `/consent_manager/check` (query params `
|
|
|
151
196
|
| `.` | `dist/index.js` (ESM), `dist/index.cjs` (CJS), `dist/index.d.ts` | Any framework / plain JS. |
|
|
152
197
|
| `./react` | `dist/react.js`, `dist/react.cjs`, `dist/react.d.ts` | `useConsentWidget` hook (`react` stays external). |
|
|
153
198
|
|
|
154
|
-
Source of truth is `src/core/` (`widget.ts`, `types.ts`
|
|
199
|
+
Source of truth is `src/core/` (`widget.ts`, `types.ts`, `embed.ts`).
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { WidgetEnv, WidgetEvent } from "./types";
|
|
2
|
+
/** Selector marking host-page elements as inline-consent slots. */
|
|
3
|
+
export declare const NODBOOK_WIDGET_SELECTOR = ".nodbook-widget";
|
|
4
|
+
export interface EmbeddedPurposeLocale {
|
|
5
|
+
name: string;
|
|
6
|
+
description: string;
|
|
7
|
+
}
|
|
8
|
+
export interface EmbeddedPurposeDataCategory {
|
|
9
|
+
id: string;
|
|
10
|
+
name: string;
|
|
11
|
+
locales?: Record<string, string>;
|
|
12
|
+
status?: string;
|
|
13
|
+
is_parent?: boolean;
|
|
14
|
+
children?: EmbeddedPurposeDataCategory[];
|
|
15
|
+
}
|
|
16
|
+
/** Minimal mirror of the public `POST /v1/public/direct_consents/purpose` response. */
|
|
17
|
+
export interface EmbeddedPurpose {
|
|
18
|
+
id: string;
|
|
19
|
+
organization_id: string;
|
|
20
|
+
identifier?: string;
|
|
21
|
+
name: string;
|
|
22
|
+
description: string;
|
|
23
|
+
status?: string;
|
|
24
|
+
locales: Record<string, EmbeddedPurposeLocale>;
|
|
25
|
+
data_categories: EmbeddedPurposeDataCategory[];
|
|
26
|
+
locale_names: string[];
|
|
27
|
+
locale_count: number;
|
|
28
|
+
}
|
|
29
|
+
export interface EmbedCaptureResult {
|
|
30
|
+
consent_ids: string[];
|
|
31
|
+
redirect_url: string;
|
|
32
|
+
}
|
|
33
|
+
export interface EmbedDirectConsentOptions {
|
|
34
|
+
/** Organization owning the purpose (public identifier). */
|
|
35
|
+
organizationId: string;
|
|
36
|
+
/** Purpose to render and capture consent for. */
|
|
37
|
+
purposeId: string;
|
|
38
|
+
/** Principal the consent is recorded against. */
|
|
39
|
+
principalId: string;
|
|
40
|
+
/** Locale for purpose text + capture. Defaults to the browser language, else `en`. */
|
|
41
|
+
locale?: string;
|
|
42
|
+
/** Gateway origin for API calls. Precedence: `apiBaseUrl` -> `baseUrl` -> `env` -> script-tag origin -> current origin. */
|
|
43
|
+
baseUrl?: string;
|
|
44
|
+
/** Gateway environment used when `baseUrl` is omitted. */
|
|
45
|
+
env?: WidgetEnv;
|
|
46
|
+
/** API origin, when it differs from the gateway `baseUrl`. Defaults to the resolved `baseUrl`. */
|
|
47
|
+
apiBaseUrl?: string;
|
|
48
|
+
}
|
|
49
|
+
export interface EmbedScanOptions {
|
|
50
|
+
/** Gateway origin override applied to every scanned element (per-element `data-base-url` wins). */
|
|
51
|
+
baseUrl?: string;
|
|
52
|
+
/** Gateway environment used when neither `baseUrl` nor per-element `data-base-url` is set. */
|
|
53
|
+
env?: WidgetEnv;
|
|
54
|
+
/** API origin override applied to every scanned element (per-element `data-api-base-url` wins). */
|
|
55
|
+
apiBaseUrl?: string;
|
|
56
|
+
/** Locale fallback for elements without `data-locale`. */
|
|
57
|
+
locale?: string;
|
|
58
|
+
/** Subtree to scan. Defaults to `document`. */
|
|
59
|
+
root?: ParentNode;
|
|
60
|
+
}
|
|
61
|
+
export type EmbedEmit = (event: WidgetEvent) => void;
|
|
62
|
+
/** Public API: fetch the purpose shown next to the checkbox (no auth). */
|
|
63
|
+
export declare function fetchDirectPurpose(apiBaseUrl: string, identifiers: {
|
|
64
|
+
organization_id: string;
|
|
65
|
+
purpose_id: string;
|
|
66
|
+
}): Promise<EmbeddedPurpose>;
|
|
67
|
+
export interface CaptureDirectConsentInput {
|
|
68
|
+
organization_id: string;
|
|
69
|
+
principal_id: string;
|
|
70
|
+
purpose_id: string;
|
|
71
|
+
/** `true` = accept, `false` = revoke. */
|
|
72
|
+
active: boolean;
|
|
73
|
+
locale: string;
|
|
74
|
+
}
|
|
75
|
+
/** Public API: accept (`active: true`) or revoke (`active: false`) direct consent (no auth). */
|
|
76
|
+
export declare function captureDirectConsent(apiBaseUrl: string, input: CaptureDirectConsentInput): Promise<EmbedCaptureResult>;
|
|
77
|
+
/**
|
|
78
|
+
* Render an inline consent checkbox into `root`, replacing its contents.
|
|
79
|
+
* Returns an unmount function that detaches the widget and ignores any
|
|
80
|
+
* in-flight request resolutions.
|
|
81
|
+
*/
|
|
82
|
+
export declare function mountInlineConsent(root: Element, options: EmbedDirectConsentOptions, emit: EmbedEmit): () => void;
|
|
83
|
+
/**
|
|
84
|
+
* Embed every `.nodbook-widget` element under `options.root` (default
|
|
85
|
+
* `document`). Per-element `data-*` attributes override the scan-level
|
|
86
|
+
* options. Elements already mounted (or missing identifiers) are skipped
|
|
87
|
+
* with a visible error. Returns a cleanup that unmounts everything mounted
|
|
88
|
+
* by this call.
|
|
89
|
+
*
|
|
90
|
+
* Recognized attributes per element:
|
|
91
|
+
* data-organization-id (required), data-purpose-id (required),
|
|
92
|
+
* data-principal-id (required), data-locale, data-base-url, data-env,
|
|
93
|
+
* data-api-base-url
|
|
94
|
+
*/
|
|
95
|
+
export declare function scanNodbookWidgets(options: EmbedScanOptions | undefined, emit: EmbedEmit): () => void;
|
package/dist/core/types.d.ts
CHANGED
|
@@ -29,7 +29,7 @@ export type WidgetCallback = (event: WidgetEvent) => void;
|
|
|
29
29
|
* Common options shared by every widget method (`openConsent`,
|
|
30
30
|
* `openPreferences`, `openDirectConsent`, and the hook's `open`).
|
|
31
31
|
* Identifiers travel directly as method arguments (`requestId`, `token`,
|
|
32
|
-
* `purposeId`, `
|
|
32
|
+
* `purposeId`, `principalId`, `organizationId`, `locale`) — never inside this object.
|
|
33
33
|
*/
|
|
34
34
|
export interface WidgetOptions {
|
|
35
35
|
/**
|
package/dist/core/widget.d.ts
CHANGED
|
@@ -14,11 +14,13 @@
|
|
|
14
14
|
*
|
|
15
15
|
* How it works: opens the gateway consent / preferences page in a modal
|
|
16
16
|
* iframe overlay. Auth token travels as `?auth_token=` (already supported by
|
|
17
|
-
* `usePrincipalTokenHandshake`) and via postMessage PRINCIPAL_TOKEN
|
|
18
|
-
*
|
|
19
|
-
*
|
|
17
|
+
* `usePrincipalTokenHandshake`) and via postMessage PRINCIPAL_TOKEN for the
|
|
18
|
+
* authenticated flows. Direct consent is public — purpose / principal /
|
|
19
|
+
* organization identifiers travel as plain query params, no JWT.
|
|
20
20
|
*/
|
|
21
|
-
import { type WidgetCallback, type WidgetEvent, type WidgetOptions } from "./types";
|
|
21
|
+
import { type WidgetCallback, type WidgetEnv, type WidgetEvent, type WidgetOptions } from "./types";
|
|
22
|
+
import { type EmbedDirectConsentOptions, type EmbedScanOptions } from "./embed";
|
|
23
|
+
export declare function inferBaseUrl(explicit?: string, env?: WidgetEnv): string;
|
|
22
24
|
declare class ConsentWidgetImpl {
|
|
23
25
|
private overlay;
|
|
24
26
|
private iframe;
|
|
@@ -31,10 +33,12 @@ declare class ConsentWidgetImpl {
|
|
|
31
33
|
openConsent(requestId: string, token: string, options?: WidgetOptions): void;
|
|
32
34
|
/** Open the preferences (my consents + grievances) dialog. */
|
|
33
35
|
openPreferences(token: string, options?: WidgetOptions): void;
|
|
34
|
-
/** Open the direct-consent (permission-style) dialog for a purpose. */
|
|
35
|
-
openDirectConsent(purposeId: string,
|
|
36
|
+
/** Open the direct-consent (permission-style) dialog for a purpose (public — no JWT). */
|
|
37
|
+
openDirectConsent(purposeId: string, principalId: string, organizationId?: string | null, locale?: string, options?: WidgetOptions): void;
|
|
36
38
|
/**
|
|
37
39
|
* Shared opener behind `openConsent` / `openPreferences` / `openDirectConsent`.
|
|
40
|
+
* `token` (JWT) is required for `consent` / `preferences` but NOT for
|
|
41
|
+
* public `direct_consent`, which identifies via principalId + organizationId.
|
|
38
42
|
*/
|
|
39
43
|
private openDialog;
|
|
40
44
|
/**
|
|
@@ -48,6 +52,37 @@ declare class ConsentWidgetImpl {
|
|
|
48
52
|
/** Alias of close() without emitting when already closed. */
|
|
49
53
|
destroy(): void;
|
|
50
54
|
isOpen(): boolean;
|
|
55
|
+
private embeds;
|
|
56
|
+
private trackEmbed;
|
|
57
|
+
private unmountEmbeds;
|
|
58
|
+
/**
|
|
59
|
+
* Render an inline consent checkbox for a purpose into `target`
|
|
60
|
+
* (element or CSS selector), replacing its contents. Toggling the checkbox
|
|
61
|
+
* captures consent via the public direct-consent APIs (no JWT).
|
|
62
|
+
* Returns an unmount function.
|
|
63
|
+
*
|
|
64
|
+
* ConsentWidget.embedDirectConsent("#newsletter-consent", {
|
|
65
|
+
* organizationId: "org_...",
|
|
66
|
+
* purposeId: "purpose_123",
|
|
67
|
+
* principalId: "principal_123",
|
|
68
|
+
* });
|
|
69
|
+
*/
|
|
70
|
+
embedDirectConsent(target: string | Element, options: EmbedDirectConsentOptions): () => void;
|
|
71
|
+
/**
|
|
72
|
+
* Embed every `.nodbook-widget` element on the page as an inline consent
|
|
73
|
+
* checkbox. Identifiers come from per-element data attributes
|
|
74
|
+
* (`data-organization-id`, `data-purpose-id`, `data-principal-id`,
|
|
75
|
+
* optional `data-locale`, `data-base-url`, `data-env`, `data-api-base-url`),
|
|
76
|
+
* falling back to `options` for gateway/locale settings.
|
|
77
|
+
* Returns a cleanup that unmounts everything mounted by this call.
|
|
78
|
+
*
|
|
79
|
+
* <div class="nodbook-widget"
|
|
80
|
+
* data-organization-id="org_..."
|
|
81
|
+
* data-purpose-id="purpose_123"
|
|
82
|
+
* data-principal-id="principal_123"></div>
|
|
83
|
+
* <script>ConsentWidget.embedNodbookWidgets();</script>
|
|
84
|
+
*/
|
|
85
|
+
embedNodbookWidgets(options?: EmbedScanOptions): () => void;
|
|
51
86
|
private open;
|
|
52
87
|
private ensureListening;
|
|
53
88
|
private render;
|
|
@@ -56,3 +91,5 @@ declare class ConsentWidgetImpl {
|
|
|
56
91
|
}
|
|
57
92
|
export declare const ConsentWidget: ConsentWidgetImpl;
|
|
58
93
|
export type { WidgetOptions, WidgetEvent, WidgetCallback };
|
|
94
|
+
export type { EmbedDirectConsentOptions, EmbedScanOptions, EmbedCaptureResult, EmbeddedPurpose, EmbeddedPurposeDataCategory, EmbeddedPurposeLocale, } from "./embed";
|
|
95
|
+
export { NODBOOK_WIDGET_SELECTOR } from "./embed";
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var w=Object.defineProperty;var y=(n,e,t)=>e in n?w(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var a=(n,e,t)=>y(n,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const c={live:"https://ui.gateway.nodbook.in",sandbox:"https://sandbox-ui.gateway.nodbook.in"},b="CONSENT_WIDGET_EVENT",h="GATEWAY_UI_READY",u="PRINCIPAL_TOKEN";function E(n){return typeof n=="object"&&n!==null&&n.type===b&&typeof n.event=="object"}function _(n){return typeof n=="object"&&n!==null&&n.type===h}const x="__consent_widget_overlay__",I=600,v=640;function k(n,e){var t;if(n)return n.replace(/\/$/,"");if(e&&c[e])return c[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 C(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 A{constructor(){a(this,"overlay",null);a(this,"iframe",null);a(this,"session",null);a(this,"callbacks",new Set);a(this,"listening",!1);a(this,"escHandler",e=>{var t;e.key==="Escape"&&this.close({type:"closed",requestId:(t=this.session)==null?void 0:t.requestId})});a(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(_(e.data)){try{(o=this.iframe.contentWindow)==null||o.postMessage({type:u,token:this.session.token},t||"*")}catch{}return}if(typeof e.data=="object"&&e.data!==null&&e.data.type===h){try{(r=this.iframe.contentWindow)==null||r.postMessage({type:u,token:this.session.token},t||"*")}catch{}return}if(E(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()}}})}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.");this.openDialog({...i,purposeId:s,token:t,orgId:o??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,o=e.mode??(t?"direct_consent":e.requestId?"consent":"preferences");if(o==="consent"&&!e.requestId)throw new Error("ConsentWidget: `requestId` is required for the consent dialog.");this.open({requestId:e.requestId,token:e.token,mode:o,purposeId:t,orgId:e.orgId??null,locale:e.locale,baseUrl:k(e.baseUrl,e.env),autoClose:e.autoClose??!0}),this.render(e.allowClose??!0,e.width??I,e.height??v),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},o=this.overlay!==null;this.teardown(),o&&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,o){if(!this.session)return;const r=C(this.session),i=document.createElement("div");i.id=x,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"),g=Math.min(t,window.innerWidth-32),p=Math.min(o,window.innerHeight-32);if(s.style.cssText=[`width:${g}px`,"max-width:100%",`height:${p}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",m=>{m.target===i&&this.close()})}const d=document.createElement("iframe");d.src=r,d.title="Consent manager",d.setAttribute("allow","clipboard-write"),d.style.cssText=["flex:1","width:100%","height:100%","border:0","background:#fff","position:relative","z-index:1","pointer-events:auto"].join(";"),s.appendChild(d),i.appendChild(s),document.body.appendChild(i),document.documentElement.style.overflow="hidden",this.overlay=i,this.iframe=d}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 A;exports.ConsentWidget=f;exports.GATEWAY_BASE_URLS=c;exports.default=f;
|
|
1
|
+
"use strict";var R=Object.defineProperty;var G=(n,e,t)=>e in n?R(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var m=(n,e,t)=>G(n,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const v={live:"https://ui.gateway.nodbook.in",sandbox:"https://sandbox-ui.gateway.nodbook.in"},M="CONSENT_WIDGET_EVENT",L="GATEWAY_UI_READY",S="PRINCIPAL_TOKEN";function H(n){return typeof n=="object"&&n!==null&&n.type===M&&typeof n.event=="object"}function P(n){return typeof n=="object"&&n!==null&&n.type===L}const q=".nodbook-widget";function _(){const n=globalThis.document;if(!n)throw new Error("nodbook-widget: `document` is not available in this environment.");return n}function F(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 Y(n){var t;return(((t=n.apiBaseUrl)==null?void 0:t.trim())||N(n.baseUrl,n.env)).replace(/\/$/,"")}function O(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 K(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(O(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 V(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(O(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 J(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 f(n,e,t){const r=_().createElement(n);return r.className=t,r.setAttribute("style",e),r}function j(n,e,t){var A,z,T;const o=(A=e.organizationId)==null?void 0:A.trim(),r=(z=e.purposeId)==null?void 0:z.trim(),i=(T=e.principalId)==null?void 0:T.trim();if(!o||!r||!i)throw new Error("embedDirectConsent: `organizationId`, `purposeId` and `principalId` are required.");const s={organizationId:o,purposeId:r,principalId:i,locale:F(e.locale),apiBaseUrl:Y(e)},l={purposeId:r,principalId:i,organizationId:o};let a=!1,c=!1;const d=f("div","display:flex;flex-direction:column;gap:8px;font:inherit;color:inherit;","nbw-root"),u=h=>{const p=f("span","font-size:13px;opacity:0.65;","nbw-loading");return p.textContent=h,d.replaceChildren(p),p},E=(h,p)=>{if(a)return;const w=f("div","display:flex;flex-direction:column;gap:6px;","nbw-error-wrap"),b=f("span","font-size:13px;color:#b91c1c;","nbw-error");if(b.setAttribute("role","alert"),b.textContent=h,w.appendChild(b),p){const I=f("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");I.textContent="Retry",I.addEventListener("click",p),w.appendChild(I)}d.replaceChildren(w)};u("Loading consent…"),n.replaceChildren(d);const k=()=>{u("Loading consent…"),K(s.apiBaseUrl,{organization_id:s.organizationId,purpose_id:s.purposeId}).then(h=>{a||$(h)},h=>{if(a)return;const p=h instanceof Error?h.message:"Failed to load purpose.";t({type:"error",message:p,data:l}),E(p,k)})},$=h=>{if(a)return;const{name:p,description:w}=J(h,s.locale),b=f("label","display:flex;gap:8px;align-items:flex-start;cursor:pointer;font:inherit;","nbw-label"),g=_().createElement("input");g.type="checkbox",g.className="nbw-checkbox",g.setAttribute("style","margin-top:2px;width:16px;height:16px;accent-color:#0b57d0;cursor:pointer;flex-shrink:0;");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");if(U.textContent=p,C.appendChild(U),w){const y=f("span","font-size:12px;line-height:1.4;opacity:0.75;","nbw-description");y.textContent=w,C.appendChild(y)}b.appendChild(g),b.appendChild(C);const x=f("span","font-size:12px;opacity:0.65;","nbw-status");x.setAttribute("aria-live","polite"),g.addEventListener("change",()=>{if(c||a)return;c=!0;const y=g.checked;g.disabled=!0,x.textContent="Saving…",V(s.apiBaseUrl,{organization_id:s.organizationId,principal_id:s.principalId,purpose_id:s.purposeId,active:y,locale:s.locale}).then(()=>{a||(c=!1,g.disabled=!1,x.textContent="",t({type:y?"consent_accepted":"consent_declined",data:l}))},D=>{if(a)return;c=!1,g.checked=!y,g.disabled=!1;const W=D instanceof Error?D.message:"Failed to record consent.";x.textContent=W,t({type:"error",message:W,data:l})})}),d.replaceChildren(b,x)};return k(),()=>{a=!0,d.remove()}}function Q(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 X(n={},e){const t=n.root??_(),o=Array.from(t.querySelectorAll(q)),r=[];for(const i of o){if(i.getAttribute("data-nbw-mounted")==="true")continue;const s=Q(i),l=s.organizationId??"",a=s.purposeId??"",c=s.principalId??"";if(!l||!a||!c){const u=`nodbook-widget: missing ${[!l&&"`data-organization-id`",!a&&"`data-purpose-id`",!c&&"`data-principal-id`"].filter(Boolean).join(", ")}.`,E=f("span","font-size:13px;color:#b91c1c;","nbw-error");E.setAttribute("role","alert"),E.textContent=u,i.replaceChildren(E),e({type:"error",message:u,data:{purposeId:a,principalId:c,organizationId:l}});continue}try{const d=j(i,{organizationId:l,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"),d()})}catch(d){const u=d instanceof Error?d.message:"Failed to embed consent widget.";e({type:"error",message:u,data:{purposeId:a,principalId:c,organizationId:l}})}}return()=>{for(const i of r)try{i()}catch{}}}const Z="__consent_widget_overlay__",ee=600,te=640;function N(n,e){var t;if(n)return n.replace(/\/$/,"");if(e&&v[e])return v[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 ne(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 re{constructor(){m(this,"overlay",null);m(this,"iframe",null);m(this,"session",null);m(this,"callbacks",new Set);m(this,"listening",!1);m(this,"escHandler",e=>{var t;e.key==="Escape"&&this.close({type:"closed",requestId:(t=this.session)==null?void 0:t.requestId})});m(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(P(e.data)){if(!this.session.token)return;try{(o=this.iframe.contentWindow)==null||o.postMessage({type:S,token:this.session.token},t||"*")}catch{}return}if(typeof e.data=="object"&&e.data!==null&&e.data.type===L){if(!this.session.token)return;try{(r=this.iframe.contentWindow)==null||r.postMessage({type:S,token:this.session.token},t||"*")}catch{}return}if(H(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()}}});m(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 l=t==null?void 0:t.trim();if(!l)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:l,organizationId:a.trim(),locale:r,mode:"direct_consent"})}openDialog(e){var i,s,l,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 d=((s=e.principalId)==null?void 0:s.trim())||void 0,u=((l=e.organizationId)==null?void 0:l.trim())||void 0;if(!t)throw new Error("ConsentWidget.openDirectConsent: `purposeId` is required.");if(!d)throw new Error("ConsentWidget.openDirectConsent: `principalId` is required.");if(!u)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:N(e.baseUrl,e.env),autoClose:e.autoClose??!0}),this.render(e.allowClose??!0,e.width??ee,e.height??te),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(j(o,t,r=>this.emit(r)))}embedNodbookWidgets(e){const t=X(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=ne(this.session),i=document.createElement("div");i.id=Z,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"),l=Math.min(t,window.innerWidth-32),a=Math.min(o,window.innerHeight-32);if(s.style.cssText=[`width:${l}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 d=document.createElement("button");d.setAttribute("aria-label","Close"),d.textContent="×",d.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(";"),d.onclick=()=>this.close(),i.appendChild(d),i.addEventListener("mousedown",u=>{u.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 B=new re;exports.ConsentWidget=B;exports.GATEWAY_BASE_URLS=v;exports.NODBOOK_WIDGET_SELECTOR=q;exports.default=B;
|
package/dist/index.d.ts
CHANGED
|
@@ -12,8 +12,9 @@
|
|
|
12
12
|
*
|
|
13
13
|
* Zero runtime dependencies.
|
|
14
14
|
*/
|
|
15
|
-
export { ConsentWidget } from "./core/widget";
|
|
15
|
+
export { ConsentWidget, NODBOOK_WIDGET_SELECTOR } from "./core/widget";
|
|
16
16
|
import { ConsentWidget as ConsentWidgetDefault } from "./core/widget";
|
|
17
17
|
export default ConsentWidgetDefault;
|
|
18
18
|
export { GATEWAY_BASE_URLS } from "./core/types";
|
|
19
19
|
export type { WidgetCallback, WidgetEnv, WidgetEvent, WidgetEventType, WidgetOptions, WidgetMode, } from "./core/types";
|
|
20
|
+
export type { EmbedDirectConsentOptions, EmbedScanOptions, EmbedCaptureResult, EmbeddedPurpose, EmbeddedPurposeDataCategory, EmbeddedPurposeLocale, } from "./core/widget";
|