@hagicode/hagilight-core 0.20.1-dev.196.1.d67f4e4 → 0.20.1-dev.199.1.c17b214

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.
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Region decision (`@hagicode/hagilight-core/consent-region`). It answers one question for the visitor: does this
3
+ * visitor need an analytics decision before providers start? The answer is one of `required`, `notRequired` or
4
+ * `unknown`. Every consumer treats `unknown` exactly like `required`, so a visitor whose location cannot be identified
5
+ * gets the consent popup and no provider.
6
+ *
7
+ * Sources are consulted in a fixed order: the site's `countryCode`, the site's `regionHook`, the same-origin
8
+ * `/cdn-cgi/trace` endpoint (only its `loc` line), and a coarse time-zone fallback. The whole resolution is bounded by
9
+ * a deadline that falls back to `required`. No visitor IP address leaves the page, and no location request goes to any
10
+ * host other than the page's own origin. The module never throws and never writes storage.
11
+ */
12
+ export const TRACE_PATH = '/cdn-cgi/trace';
13
+ /** Abandons the trace request early so the time-zone fallback still runs before the deadline. */
14
+ export const TRACE_TIMEOUT_MS = 1200;
15
+ /** The trace body is read only this far. The real body is a few hundred bytes. */
16
+ export const TRACE_MAX_BYTES = 4096;
17
+ /** The whole resolution. A hung source leaves the decision at `required` when this passes. */
18
+ export const RESOLUTION_DEADLINE_MS = 1800;
19
+ /** The default consent-required set: EU27, EEA (IS, LI, NO), GB, CH and BR. A product configuration, not a legal finding. */
20
+ export const DEFAULT_REQUIRED_COUNTRIES = Object.freeze([
21
+ 'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT',
22
+ 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'IS', 'LI', 'NO', 'GB', 'CH', 'BR',
23
+ ]);
24
+ /** Officially assigned ISO 3166-1 alpha-2 codes. User-assigned or reserved codes such as XX, T1 or QQ are not listed. */
25
+ const ASSIGNED_COUNTRY_CODES = new Set(('AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ '
26
+ + 'CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR '
27
+ + 'GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO '
28
+ + 'JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR '
29
+ + 'MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO '
30
+ + 'RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV '
31
+ + 'TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW').split(' '));
32
+ const COUNTRY_CODE = /^[A-Z]{2}$/u;
33
+ /** True only for an upper-case, officially assigned ISO 3166-1 alpha-2 code. */
34
+ export function isAssignedCountryCode(value) {
35
+ return typeof value === 'string' && COUNTRY_CODE.test(value) && ASSIGNED_COUNTRY_CODES.has(value);
36
+ }
37
+ /** The country set a configuration selects. An absent or `default` option uses the built-in set. */
38
+ export function requiredCountrySet(regions) {
39
+ if (regions === undefined || regions === 'default')
40
+ return new Set(DEFAULT_REQUIRED_COUNTRIES);
41
+ return new Set(regions);
42
+ }
43
+ /** Maps a valid country to `required` or `notRequired` under the selected set. */
44
+ export function decisionForCountry(country, set) {
45
+ return set.has(country) ? 'required' : 'notRequired';
46
+ }
47
+ const EUROPE_AND_EXCEPTIONS = new Set([
48
+ 'Atlantic/Reykjavik', 'Atlantic/Canary', 'Atlantic/Madeira', 'Atlantic/Azores', 'Atlantic/Faroe', 'Africa/Ceuta',
49
+ 'Arctic/Longyearbyen', 'Asia/Nicosia', 'Asia/Famagusta', 'Asia/Istanbul',
50
+ // Brazilian zones.
51
+ 'America/Sao_Paulo', 'America/Bahia', 'America/Manaus', 'America/Fortaleza', 'America/Belem', 'America/Recife',
52
+ 'America/Cuiaba', 'America/Campo_Grande', 'America/Noronha', 'America/Porto_Velho', 'America/Rio_Branco',
53
+ 'America/Boa_Vista', 'America/Araguaina', 'America/Maceio', 'America/Santarem', 'America/Eirunepe',
54
+ // French outermost regions.
55
+ 'America/Martinique', 'America/Guadeloupe', 'America/Cayenne', 'America/Marigot', 'America/St_Barthelemy',
56
+ 'Indian/Reunion', 'Indian/Mayotte',
57
+ ]);
58
+ /**
59
+ * The time-zone fallback. Europe and the listed EU/EEA/Brazil/French-territory zones require consent. Other Americas,
60
+ * Asia, Australia and Pacific zones do not. Anything else, including UTC, an empty or missing identifier and an
61
+ * unreadable clock, is `unknown`, which requires consent.
62
+ */
63
+ export function classifyTimeZone(timeZone) {
64
+ if (typeof timeZone !== 'string' || timeZone.length === 0)
65
+ return 'unknown';
66
+ if (timeZone.startsWith('Europe/') || EUROPE_AND_EXCEPTIONS.has(timeZone))
67
+ return 'required';
68
+ if (['America/', 'Asia/', 'Australia/', 'Pacific/'].some((prefix) => timeZone.startsWith(prefix)))
69
+ return 'notRequired';
70
+ return 'unknown';
71
+ }
72
+ /** Reads the `loc` line of a trace body. Only that line is used. The IP line is never returned. */
73
+ export function parseTraceCountry(body) {
74
+ for (const line of body.split(/\r?\n/u)) {
75
+ const trimmed = line.trim();
76
+ if (!trimmed.startsWith('loc='))
77
+ continue;
78
+ const value = trimmed.slice('loc='.length);
79
+ return isAssignedCountryCode(value) ? value : undefined;
80
+ }
81
+ return undefined;
82
+ }
83
+ /** Reads at most `limit` bytes of a response body and then stops the stream. */
84
+ async function readCapped(response, limit) {
85
+ const reader = response.body?.getReader?.();
86
+ if (!reader)
87
+ return (await response.text()).slice(0, limit);
88
+ const decoder = new TextDecoder();
89
+ let text = '';
90
+ let received = 0;
91
+ while (received < limit) {
92
+ const { done, value } = await reader.read();
93
+ if (done)
94
+ break;
95
+ const chunk = value.subarray(0, limit - received);
96
+ received += chunk.byteLength;
97
+ text += decoder.decode(chunk, { stream: true });
98
+ }
99
+ await reader.cancel().catch(() => undefined);
100
+ return text + decoder.decode();
101
+ }
102
+ /** One same-origin trace request with credentials omitted and no cache. Any failure yields no country. */
103
+ async function readTraceCountry(env) {
104
+ if (!env.href || typeof env.fetch !== 'function')
105
+ return undefined;
106
+ const controller = new AbortController();
107
+ const timer = setTimeout(() => controller.abort(), env.traceTimeoutMs ?? TRACE_TIMEOUT_MS);
108
+ try {
109
+ const url = new URL(TRACE_PATH, env.href);
110
+ const response = await env.fetch(url.href, {
111
+ cache: 'no-store',
112
+ credentials: 'omit',
113
+ redirect: 'error',
114
+ signal: controller.signal,
115
+ });
116
+ if (!response.ok)
117
+ return undefined;
118
+ return parseTraceCountry(await readCapped(response, TRACE_MAX_BYTES));
119
+ }
120
+ catch {
121
+ return undefined;
122
+ }
123
+ finally {
124
+ clearTimeout(timer);
125
+ }
126
+ }
127
+ function readTimeZone(env) {
128
+ try {
129
+ if (env.timeZone)
130
+ return env.timeZone();
131
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ }
137
+ /**
138
+ * Adapts a custom hook result. A state is taken as it is, a boolean maps to `notRequired` for `false` and `required`
139
+ * for `true`, and anything else is `unknown`. A throw or a rejected promise is `unknown`.
140
+ */
141
+ export function adaptHookValue(value) {
142
+ if (value === 'required' || value === 'notRequired' || value === 'unknown')
143
+ return value;
144
+ if (value === false)
145
+ return 'notRequired';
146
+ if (value === true)
147
+ return 'required';
148
+ return 'unknown';
149
+ }
150
+ async function hookDecision(hook) {
151
+ try {
152
+ return adaptHookValue(await hook());
153
+ }
154
+ catch {
155
+ return 'unknown';
156
+ }
157
+ }
158
+ async function decideFromSources(config, env) {
159
+ const set = requiredCountrySet(config.regions);
160
+ if (config.countryCode !== undefined) {
161
+ return isAssignedCountryCode(config.countryCode) ? decisionForCountry(config.countryCode, set) : 'unknown';
162
+ }
163
+ if (typeof config.regionHook === 'function')
164
+ return hookDecision(config.regionHook);
165
+ const country = await readTraceCountry(env);
166
+ if (country !== undefined)
167
+ return decisionForCountry(country, set);
168
+ return classifyTimeZone(readTimeZone(env));
169
+ }
170
+ /**
171
+ * Resolves one visitor's decision. Without a regional configuration or a hook the answer is `required` with no request and no time
172
+ * read. Without a page URL or `fetch`, a configured decision is `unknown`. Otherwise the sources run, bounded by the
173
+ * deadline, which resolves to `required`. A late source answer does not change the result. The function never rejects.
174
+ */
175
+ export async function resolveRegionDecision(config, env = pageRegionEnvironment()) {
176
+ try {
177
+ if (config.regions === undefined && config.regionHook === undefined)
178
+ return 'required';
179
+ if (!env.href || typeof env.fetch !== 'function')
180
+ return 'unknown';
181
+ let timer;
182
+ const deadline = new Promise((resolve) => {
183
+ timer = setTimeout(() => resolve('required'), env.deadlineMs ?? RESOLUTION_DEADLINE_MS);
184
+ });
185
+ try {
186
+ return await Promise.race([decideFromSources(config, env).catch(() => 'unknown'), deadline]);
187
+ }
188
+ finally {
189
+ clearTimeout(timer);
190
+ }
191
+ }
192
+ catch {
193
+ return 'unknown';
194
+ }
195
+ }
196
+ /** The page environment: the page URL, `window.fetch` and `window` as the once-per-document holder. Empty without a window. */
197
+ export function pageRegionEnvironment() {
198
+ try {
199
+ if (typeof window === 'undefined' || typeof document === 'undefined')
200
+ return {};
201
+ return {
202
+ href: window.location.href,
203
+ fetch: (input, init) => window.fetch(input, init),
204
+ holder: window,
205
+ };
206
+ }
207
+ catch {
208
+ return {};
209
+ }
210
+ }
211
+ const moduleHolder = {};
212
+ function sharedState(env) {
213
+ const holder = env.holder ?? moduleHolder;
214
+ if (!holder.__hagilightRegion)
215
+ holder.__hagilightRegion = { listeners: new Set() };
216
+ return holder.__hagilightRegion;
217
+ }
218
+ /**
219
+ * Starts the resolution at most once per document and returns its promise. Later calls, including from another bundle
220
+ * on the same page, share the first one. The decision is announced to listeners exactly once.
221
+ */
222
+ export function startRegionResolution(config, env = pageRegionEnvironment()) {
223
+ const state = sharedState(env);
224
+ if (!state.promise) {
225
+ state.promise = resolveRegionDecision(config, env).then((decision) => {
226
+ if (state.decision === undefined) {
227
+ state.decision = decision;
228
+ for (const listener of [...state.listeners]) {
229
+ try {
230
+ listener(decision);
231
+ }
232
+ catch {
233
+ // One failing listener must not stop the others.
234
+ }
235
+ }
236
+ }
237
+ return state.decision;
238
+ });
239
+ }
240
+ return state.promise;
241
+ }
242
+ /** The decision, or `pending` until resolution completes or when it was never started. */
243
+ export function getRegionDecision(env = pageRegionEnvironment()) {
244
+ try {
245
+ return sharedState(env).decision ?? 'pending';
246
+ }
247
+ catch {
248
+ return 'pending';
249
+ }
250
+ }
251
+ /** Calls `listener` with the decision: now when it exists, otherwise once it resolves. Returns an unsubscribe function. */
252
+ export function onRegionDecision(listener, env = pageRegionEnvironment()) {
253
+ try {
254
+ if (typeof listener !== 'function')
255
+ return () => { };
256
+ const state = sharedState(env);
257
+ if (state.decision !== undefined) {
258
+ listener(state.decision);
259
+ return () => { };
260
+ }
261
+ state.listeners.add(listener);
262
+ return () => {
263
+ state.listeners.delete(listener);
264
+ };
265
+ }
266
+ catch {
267
+ return () => { };
268
+ }
269
+ }
270
+ /** The page-backed source the gate and the popup read. It has no state of its own. */
271
+ export function pageRegionSource(env = pageRegionEnvironment()) {
272
+ return {
273
+ current: () => getRegionDecision(env),
274
+ subscribe: (listener) => onRegionDecision(listener, env),
275
+ };
276
+ }
package/dist/consent.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type RegionConfig, type RegionsOption } from './consent-region.js';
1
2
  export declare const CONSENT_STORAGE_KEY = "hagicode:consent";
2
3
  export declare const CONSENT_COOKIE = "hagicode_consent";
3
4
  export declare const CONSENT_SHARED_DOMAIN = "hagicode.com";
@@ -28,10 +29,19 @@ export interface ConsentChoice {
28
29
  export type ConsentListener = (state: ConsentState) => void;
29
30
  export interface ConsentOptions {
30
31
  /**
31
- * Optional site-supplied region check. Returning `false` means consent is not required for this visitor. Any other
32
- * result, a throw, or no hook at all means consent is required.
32
+ * Optional site-supplied region check. Without `regions`, returning exactly `false` means consent is not required for
33
+ * this visitor; any other result, a throw, or no hook at all means consent is required. With `regions`, the hook
34
+ * may answer a state, a boolean or a promise (see `consent-region.ts`).
33
35
  */
34
36
  regionHook?: () => unknown;
37
+ /** `default` for the built-in country set, or an array of upper-case ISO country codes. Absent keeps global consent. */
38
+ regions?: RegionsOption;
39
+ /** One upper-case ISO country code. Used only with `regions`. */
40
+ countryCode?: string;
41
+ /** `requiredOnly` (default) or `always`. Used only with `regions`. */
42
+ settingsEntry?: 'requiredOnly' | 'always';
43
+ /** `optIn` (default), `projectDefault` or `off`. Used only with `regions`. */
44
+ sessionReplay?: 'optIn' | 'projectDefault' | 'off';
35
45
  }
36
46
  /** Strict parse: exact field count, a known version and state, a plain epoch time and a bounded policy version. */
37
47
  export declare function parseConsentRecord(value: unknown): ConsentRecord | null;
@@ -46,9 +56,22 @@ export declare function decisionFromRecord(record: ConsentRecord | null, now: nu
46
56
  export declare function readCookieValue(cookies: string, name: string): string | null;
47
57
  /** The site's policy version from its JSON config descriptor, read lazily. Anything unusable falls back to `1`. */
48
58
  export declare function currentPolicyVersion(): string;
49
- /** Sets site options. Only the region hook exists so far; unknown or unusable values are ignored. */
50
- export declare function configureConsent(options: ConsentOptions): void;
51
- /** Whether this visitor needs a decision. Without a hook, or when the hook throws or does not answer `false`, it does. */
59
+ /** Sets site options. Unknown or unusable values are ignored; validation with named errors lives in `consent-markup.ts`. */
60
+ export declare function configureConsent(input: ConsentOptions): void;
61
+ /** The `settingsEntry` and `sessionReplay` behavior in effect. Both default when nothing is configured. */
62
+ export declare function regionalBehavior(): {
63
+ settingsEntry: 'requiredOnly' | 'always';
64
+ sessionReplay: 'optIn' | 'projectDefault' | 'off';
65
+ };
66
+ /**
67
+ * The region configuration the page resolves. With `regions`, it is the regional configuration. Without `regions`, a
68
+ * legacy hook keeps its meaning: exactly `false` is not required, and anything else is required.
69
+ */
70
+ export declare function currentRegionConfig(): RegionConfig;
71
+ /**
72
+ * Whether this visitor needs a decision. With `regions`, it is everything except a resolved `notRequired` decision.
73
+ * Without `regions`, a legacy hook decides: it does unless the hook returns exactly `false`, throws or is absent.
74
+ */
52
75
  export declare function isConsentRequired(): boolean;
53
76
  /** The current consent state. `analytics` is `undecided` when there is no valid record for the site's policy version. */
54
77
  export declare function getConsent(): ConsentState;
@@ -61,5 +84,8 @@ export declare function setConsent(choice: ConsentChoice): void;
61
84
  * Subscribes to analytics changes. Returns an unsubscribe function. A subscriber that throws does not affect the others.
62
85
  */
63
86
  export declare function onConsentChange(callback: ConsentListener): () => void;
64
- /** Asks the page's popup to show its details and choices again. It has no effect when no popup is mounted. */
65
- export declare function openConsentPreferences(): void;
87
+ /**
88
+ * Asks the page's popup to show its details and choices again. `replay` opens the session replay opt-in section instead.
89
+ * It has no effect when no popup is mounted.
90
+ */
91
+ export declare function openConsentPreferences(mode?: 'replay'): void;
package/dist/consent.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * is non-throwing: a call that cannot act returns its safe default.
6
6
  */
7
7
  import { isSharedHost } from './root-transit-marker.js';
8
+ import { getRegionDecision } from './consent-region.js';
8
9
  export const CONSENT_STORAGE_KEY = 'hagicode:consent';
9
10
  export const CONSENT_COOKIE = 'hagicode_consent';
10
11
  export const CONSENT_SHARED_DOMAIN = 'hagicode.com';
@@ -230,20 +231,93 @@ function ensureStorageListener() {
230
231
  // Without the storage event, other tabs' choices are seen on the next read.
231
232
  }
232
233
  }
233
- let regionHook;
234
- /** Sets site options. Only the region hook exists so far; unknown or unusable values are ignored. */
235
- export function configureConsent(options) {
234
+ const GLOBAL_OPTIONS = { settingsEntry: 'requiredOnly', sessionReplay: 'optIn' };
235
+ /** Options set by `configureConsent`. When none were set, the descriptor the integration wrote is read instead. */
236
+ let configured;
237
+ function regionsFrom(value) {
238
+ if (value === 'default')
239
+ return 'default';
240
+ if (Array.isArray(value) && value.every((code) => typeof code === 'string'))
241
+ return [...value];
242
+ return undefined;
243
+ }
244
+ /** Calls a function the site defines on `window` by a dotted name. A missing function returns `undefined`, which is unknown. */
245
+ function callNamedHook(name) {
246
+ let parent = environment().window;
247
+ let target = parent;
248
+ for (const part of name.split('.')) {
249
+ parent = target;
250
+ target = target?.[part];
251
+ }
252
+ return typeof target === 'function' ? target.call(parent) : undefined;
253
+ }
254
+ /** The regional options the integration serialized into the descriptor. Anything unreadable or non-regional is global. */
255
+ function descriptorRegionalOptions() {
256
+ try {
257
+ const text = environment().document?.getElementById(CONSENT_CONFIG_ID)?.textContent;
258
+ if (!text)
259
+ return GLOBAL_OPTIONS;
260
+ const parsed = JSON.parse(text);
261
+ if (parsed?.mode !== 'regional')
262
+ return GLOBAL_OPTIONS;
263
+ const hookName = typeof parsed.regionHook === 'string' ? parsed.regionHook : undefined;
264
+ return {
265
+ regions: regionsFrom(parsed.regions),
266
+ countryCode: typeof parsed.countryCode === 'string' ? parsed.countryCode : undefined,
267
+ regionHook: hookName ? () => callNamedHook(hookName) : undefined,
268
+ settingsEntry: parsed.settingsEntry === 'always' ? 'always' : 'requiredOnly',
269
+ sessionReplay: parsed.sessionReplay === 'projectDefault' || parsed.sessionReplay === 'off' ? parsed.sessionReplay : 'optIn',
270
+ };
271
+ }
272
+ catch {
273
+ return GLOBAL_OPTIONS;
274
+ }
275
+ }
276
+ function effectiveOptions() {
277
+ return configured ?? descriptorRegionalOptions();
278
+ }
279
+ /** Sets site options. Unknown or unusable values are ignored; validation with named errors lives in `consent-markup.ts`. */
280
+ export function configureConsent(input) {
236
281
  try {
237
- regionHook = typeof options?.regionHook === 'function' ? options.regionHook : undefined;
282
+ configured = {
283
+ regionHook: typeof input?.regionHook === 'function' ? input.regionHook : undefined,
284
+ regions: regionsFrom(input?.regions),
285
+ countryCode: typeof input?.countryCode === 'string' ? input.countryCode : undefined,
286
+ settingsEntry: input?.settingsEntry === 'always' ? 'always' : 'requiredOnly',
287
+ sessionReplay: input?.sessionReplay === 'projectDefault' || input?.sessionReplay === 'off' ? input.sessionReplay : 'optIn',
288
+ };
238
289
  }
239
290
  catch {
240
- regionHook = undefined;
291
+ configured = { ...GLOBAL_OPTIONS };
292
+ }
293
+ }
294
+ /** The `settingsEntry` and `sessionReplay` behavior in effect. Both default when nothing is configured. */
295
+ export function regionalBehavior() {
296
+ const options = effectiveOptions();
297
+ return { settingsEntry: options.settingsEntry, sessionReplay: options.sessionReplay };
298
+ }
299
+ /**
300
+ * The region configuration the page resolves. With `regions`, it is the regional configuration. Without `regions`, a
301
+ * legacy hook keeps its meaning: exactly `false` is not required, and anything else is required.
302
+ */
303
+ export function currentRegionConfig() {
304
+ const options = effectiveOptions();
305
+ if (options.regions !== undefined) {
306
+ return { regions: options.regions, countryCode: options.countryCode, regionHook: options.regionHook };
241
307
  }
308
+ const legacy = options.regionHook;
309
+ return legacy ? { regionHook: () => (legacy() === false ? 'notRequired' : 'required') } : {};
242
310
  }
243
- /** Whether this visitor needs a decision. Without a hook, or when the hook throws or does not answer `false`, it does. */
311
+ /**
312
+ * Whether this visitor needs a decision. With `regions`, it is everything except a resolved `notRequired` decision.
313
+ * Without `regions`, a legacy hook decides: it does unless the hook returns exactly `false`, throws or is absent.
314
+ */
244
315
  export function isConsentRequired() {
245
316
  try {
246
- return regionHook ? regionHook() !== false : true;
317
+ const options = effectiveOptions();
318
+ if (options.regions !== undefined)
319
+ return getRegionDecision() !== 'notRequired';
320
+ return options.regionHook ? options.regionHook() !== false : true;
247
321
  }
248
322
  catch {
249
323
  return true;
@@ -303,10 +377,14 @@ export function onConsentChange(callback) {
303
377
  return () => { };
304
378
  }
305
379
  }
306
- /** Asks the page's popup to show its details and choices again. It has no effect when no popup is mounted. */
307
- export function openConsentPreferences() {
380
+ /**
381
+ * Asks the page's popup to show its details and choices again. `replay` opens the session replay opt-in section instead.
382
+ * It has no effect when no popup is mounted.
383
+ */
384
+ export function openConsentPreferences(mode) {
308
385
  try {
309
- environment().document?.dispatchEvent(new CustomEvent(CONSENT_PREFERENCES_EVENT));
386
+ const detail = mode === 'replay' ? { mode: 'replay' } : undefined;
387
+ environment().document?.dispatchEvent(new CustomEvent(CONSENT_PREFERENCES_EVENT, { detail }));
310
388
  }
311
389
  catch {
312
390
  // Nothing to open.
@@ -64,7 +64,17 @@ export interface SiteMetadataFeatures {
64
64
  readonly promoto?: boolean;
65
65
  /** True when the build mounts the consent popup and the analytics gate. */
66
66
  readonly consent?: boolean;
67
+ /** Present only with consent: `globalRequired` for every visitor, or `regional` when the site configured regions. */
68
+ readonly consentMode?: ConsentMode;
67
69
  }
70
+ export declare const CONSENT_MODES: readonly ["globalRequired", "regional"];
71
+ export type ConsentMode = (typeof CONSENT_MODES)[number];
72
+ /**
73
+ * The consent mode of a built site from its HTML: `undefined` when no page mounts consent, `regional` when a consent
74
+ * descriptor carries the regional mode, otherwise `globalRequired`. Only the mode leaves this function, never the
75
+ * country list, the hook name or any identifier.
76
+ */
77
+ export declare function detectConsentMode(pages: Iterable<string>): ConsentMode | undefined;
68
78
  export interface SiteMetadata {
69
79
  readonly schemaVersion: typeof SITE_METADATA_SCHEMA_VERSION;
70
80
  readonly generator: SiteMetadataGenerator;
@@ -6,6 +6,7 @@
6
6
  * never leak into the output. Analytics appears only as on/off booleans.
7
7
  */
8
8
  import { normalizeBuildInfo, UNKNOWN } from './build-info.js';
9
+ import { CONSENT_CONFIG_ID } from './consent.js';
9
10
  export const SITE_METADATA_SCHEMA_VERSION = 1;
10
11
  /** Site-relative output path. This is the only place the path is spelled. */
11
12
  export const SITE_METADATA_PATH = '.well-known/hagilight.metadata.json';
@@ -31,9 +32,27 @@ export const ANALYTICS_LOADER_MARKERS = {
31
32
  ['__hagilightPosthogInitialized'],
32
33
  ],
33
34
  };
35
+ export const CONSENT_MODES = ['globalRequired', 'regional'];
36
+ /**
37
+ * The consent mode of a built site from its HTML: `undefined` when no page mounts consent, `regional` when a consent
38
+ * descriptor carries the regional mode, otherwise `globalRequired`. Only the mode leaves this function, never the
39
+ * country list, the hook name or any identifier.
40
+ */
41
+ export function detectConsentMode(pages) {
42
+ let consent = false;
43
+ for (const html of pages) {
44
+ if (!html.includes(CONSENT_CONFIG_ID))
45
+ continue;
46
+ consent = true;
47
+ if (html.includes('"mode":"regional"'))
48
+ return 'regional';
49
+ }
50
+ return consent ? 'globalRequired' : undefined;
51
+ }
34
52
  const DISCOVERY_KEYS = ['sitemap', 'robots', 'rss', 'llms'];
35
53
  const ANALYTICS_KEYS = ['googleAnalytics', 'fiftyOneLa', 'posthog'];
36
- const FEATURE_KEYS = ['seo', 'promoto', 'consent'];
54
+ const BOOLEAN_FEATURE_KEYS = ['seo', 'promoto', 'consent'];
55
+ const FEATURE_KEYS = ['seo', 'promoto', 'consent', 'consentMode'];
37
56
  const TOP_LEVEL_KEYS = ['schemaVersion', 'generator', 'site', 'languages', 'build', 'discovery', 'analytics', 'features'];
38
57
  function isRecord(value) {
39
58
  return value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -93,10 +112,14 @@ export function buildSiteMetadata(input) {
93
112
  if (typeof value === 'string' && value.startsWith('/'))
94
113
  discovery[key] = value;
95
114
  }
115
+ const consentMode = input.features?.consent === true && CONSENT_MODES.includes(input.features?.consentMode)
116
+ ? input.features?.consentMode
117
+ : undefined;
96
118
  const features = {
97
119
  ...(typeof input.features?.seo === 'boolean' ? { seo: input.features.seo } : {}),
98
120
  ...(typeof input.features?.promoto === 'boolean' ? { promoto: input.features.promoto } : {}),
99
121
  ...(typeof input.features?.consent === 'boolean' ? { consent: input.features.consent } : {}),
122
+ ...(consentMode === undefined ? {} : { consentMode }),
100
123
  };
101
124
  return {
102
125
  schemaVersion: SITE_METADATA_SCHEMA_VERSION,
@@ -182,10 +205,13 @@ export function validateSiteMetadata(value) {
182
205
  problems.push(`analytics.${key} must be a boolean`);
183
206
  }
184
207
  const features = isRecord(value.features) ? value.features : {};
185
- for (const key of FEATURE_KEYS) {
208
+ for (const key of BOOLEAN_FEATURE_KEYS) {
186
209
  if (features[key] !== undefined && typeof features[key] !== 'boolean')
187
210
  problems.push(`features.${key} must be a boolean`);
188
211
  }
212
+ if (features.consentMode !== undefined && !CONSENT_MODES.includes(features.consentMode)) {
213
+ problems.push('features.consentMode must be globalRequired or regional');
214
+ }
189
215
  return problems;
190
216
  }
191
217
  /** Canonical minified JSON: fixed key order, no indentation, trailing newline. Identical input gives identical bytes. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hagicode/hagilight-core",
3
- "version": "0.20.1-dev.196.1.d67f4e4",
3
+ "version": "0.20.1-dev.199.1.c17b214",
4
4
  "type": "module",
5
5
  "description": "Shared TypeScript utilities, components, and assets for HagiCode Astro and Starlight sites",
6
6
  "repository": {
@@ -25,6 +25,10 @@
25
25
  "types": "./dist/consent-copy/index.d.ts",
26
26
  "default": "./dist/consent-copy/index.js"
27
27
  },
28
+ "./consent-region": {
29
+ "types": "./dist/consent-region.d.ts",
30
+ "default": "./dist/consent-region.js"
31
+ },
28
32
  "./consent-markup": {
29
33
  "types": "./dist/consent-markup.d.ts",
30
34
  "default": "./dist/consent-markup.js"