@hagicode/hagilight-core 0.20.1-dev.195.1.06f4ade → 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.
@@ -1,5 +1,5 @@
1
1
  ---
2
- import { CONSENT_DESCRIPTOR_ID, consentDescriptor, renderConsentMarkup, type ConsentPopupOptions } from './dist/consent-markup.js';
2
+ import { CONSENT_DESCRIPTOR_ID, consentDescriptor, renderConsentMarkup, type ConsentPopupOptions, type RegionalPopupOptions } from './dist/consent-markup.js';
3
3
 
4
4
  interface Props {
5
5
  /** The analytics providers this site enables. Mount the popup only when at least one is enabled. */
@@ -10,10 +10,12 @@ interface Props {
10
10
  policyVersion?: string;
11
11
  /** The page locale. Defaults to Astro's current locale, then `en-US`. */
12
12
  locale?: string;
13
+ /** Set only for a regional site. Omitted keeps the global descriptor and markup. */
14
+ regional?: RegionalPopupOptions;
13
15
  }
14
16
 
15
- const { providers, privacyUrl, policyVersion, locale = Astro.currentLocale ?? 'en-US' } = Astro.props;
16
- const options: ConsentPopupOptions = { providers, privacyUrl, policyVersion, locale };
17
+ const { providers, privacyUrl, policyVersion, locale = Astro.currentLocale ?? 'en-US', regional } = Astro.props;
18
+ const options: ConsentPopupOptions = { providers, privacyUrl, policyVersion, locale, ...(regional ? { regional } : {}) };
17
19
  const markup = renderConsentMarkup(options);
18
20
  const descriptor = consentDescriptor(options);
19
21
  ---
package/Footer.astro CHANGED
@@ -17,9 +17,13 @@ interface Props {
17
17
  randomAvatar?: boolean;
18
18
  /** Adds the "Cookie settings" entry. Set only when the site mounts the consent popup. Defaults to `false`. */
19
19
  consent?: boolean;
20
+ /** A regional site: the "Cookie settings" entry is rendered hidden and revealed by the consent popup's decision. */
21
+ regional?: boolean;
22
+ /** A regional site with session replay opt-in: renders the replay entry, hidden until the decision reveals it. */
23
+ replayEntry?: boolean;
20
24
  }
21
25
 
22
- const { locale: propLocale, links, buildInfo: propBuildInfo, avatar, randomAvatar, consent = false } = Astro.props;
26
+ const { locale: propLocale, links, buildInfo: propBuildInfo, avatar, randomAvatar, consent = false, regional = false, replayEntry = false } = Astro.props;
23
27
  const locale = propLocale ?? Astro.currentLocale ?? 'en-US';
24
28
  const footerLinks = resolveRssFooterLinks(Astro.locals, locale, links);
25
29
  const buildItems = buildInfoItems(propBuildInfo ?? buildInfoFromLocals(Astro.locals));
@@ -100,7 +104,23 @@ const resolvedLinks = resolveSiteLinks(locale, {
100
104
  >{link.label}</a>
101
105
  ))}
102
106
  {consent && (
103
- <button type="button" class="hagilight-footer__consent" data-consent-preferences>{consentCopy.footerEntry}</button>
107
+ <button
108
+ type="button"
109
+ class="hagilight-footer__consent"
110
+ data-consent-preferences
111
+ data-consent-entry={regional ? 'settings' : undefined}
112
+ hidden={regional}
113
+ >{consentCopy.footerEntry}</button>
114
+ )}
115
+ {consent && replayEntry && (
116
+ <button
117
+ type="button"
118
+ class="hagilight-footer__consent"
119
+ data-consent-preferences
120
+ data-consent-mode="replay"
121
+ data-consent-entry="replay"
122
+ hidden
123
+ >{consentCopy.replayEntry}</button>
104
124
  )}
105
125
  </nav>
106
126
  </div>
@@ -173,6 +193,10 @@ const resolvedLinks = resolveSiteLinks(locale, {
173
193
  outline-offset: 0.2rem;
174
194
  }
175
195
 
196
+ .hagilight-footer__consent[hidden] {
197
+ display: none;
198
+ }
199
+
176
200
  .hagilight-footer__consent {
177
201
  margin: 0;
178
202
  padding: 0;
package/README.md CHANGED
@@ -367,12 +367,14 @@ The file follows `schemaVersion: 1`. Fields may be added within version 1. Renam
367
367
  "llms": "/llms.txt"
368
368
  },
369
369
  "analytics": { "googleAnalytics": true, "fiftyOneLa": false, "posthog": true },
370
- "features": { "seo": true, "promoto": true, "consent": true }
370
+ "features": { "seo": true, "promoto": true, "consent": true, "consentMode": "globalRequired" }
371
371
  }
372
372
  ```
373
373
 
374
374
  Rules that every writer applies:
375
375
 
376
+ - `features.consentMode` is `globalRequired` (every visitor requires consent) or `regional` (the site sets `analytics.consent.regions`) when consent is on, and is absent otherwise. It never holds the country list, the hook name or any identifier. See [Regional analytics consent](#regional-analytics-consent).
377
+
376
378
  - `site.name` comes from the `name` option, then the site's own title, then the home page name, then the URL hostname. `site.description` is omitted when no description exists.
377
379
  - `build` holds the same branch, commit, and build time as the footer, with `unknown` for any value that cannot be resolved.
378
380
  - `discovery` holds site-relative paths, relative to `site.base`, for the artifacts that exist in this build. A key is absent when its file is absent.
@@ -624,7 +626,7 @@ The vocabulary, the required properties of each event and the value rules live i
624
626
 
625
627
  Analytics is off until a visitor grants it. With consent on (the default whenever a provider is enabled), Google Analytics, 51LA and PostHog leave only inert `application/json` descriptors in the page. The gate (`@hagicode/hagilight-core/consent-gate`) injects each loader once, after a grant, and nothing from the undecided period is queued or replayed. Consent-off output (`consent` prop `false`, or `analytics.consent.enabled: false` in a framework plugin) keeps the static loaders as before.
626
628
 
627
- - `@hagicode/hagilight-core/consent` (browser-safe): `getConsent()` returns `{ necessary: 'granted', analytics: 'granted' | 'denied' | 'undecided' }`; `setConsent({ analytics })`; `onConsentChange(callback)` returns an unsubscribe function; `openConsentPreferences()` reopens the popup. None of them throw. `configureConsent({ regionHook })` takes an optional region check: returning `false` means consent is not required; any other result or a throw means it is.
629
+ - `@hagicode/hagilight-core/consent` (browser-safe): `getConsent()` returns `{ necessary: 'granted', analytics: 'granted' | 'denied' | 'undecided' }`; `setConsent({ analytics })`; `onConsentChange(callback)` returns an unsubscribe function; `openConsentPreferences()` reopens the popup. None of them throw. `configureConsent({ regionHook })` takes an optional region check: returning `false` means consent is not required; any other result or a throw means it is. The hook may also answer `'required'`, `'notRequired'`, `'unknown'` or a promise of one of these. The regional options are described in [Regional analytics consent](#regional-analytics-consent).
628
630
  - Events: `hagilight:consent-change` on `document`, with the new state as `detail`, after each effective change.
629
631
  - Storage: cookie `hagicode_consent` (`Domain=.hagicode.com`, `Path=/`, `SameSite=Lax`, `Secure`, 180 days) on hagicode.com hosts only, and localStorage `hagicode:consent` everywhere. The record is `1|granted|<epoch seconds>|<policyVersion>`, expires after 180 days, and a changed policy version asks again. With storage blocked the choice holds for the page session only.
630
632
  - `@hagicode/hagilight-core/CookieConsent` (Astro): renders the popup. Pass `providers` (the enabled analytics providers), and optionally `privacyUrl` (an absolute HTTP(S) URL or a `/` path; omitted means no privacy link) and `policyVersion` (1 to 32 letters, digits, dots, underscores or hyphens). Mount it only when a provider is enabled. The popup publishes `--hagilight-consent-clearance` so the banner and footers stay clear of it.
@@ -636,6 +638,89 @@ Storage names that the details list (and that cleanup removes on withdrawal) are
636
638
 
637
639
  Withdrawal stops collection: PostHog opts out and its `ph_` entries are removed; GA sets `ga-disable-<id>` and its cookies are removed; any provider that cannot stop in place (51LA always, GA and PostHog until the consent browser check confirms otherwise) reloads the page after the denial is saved.
638
640
 
641
+ ## Regional analytics consent
642
+
643
+ Regional mode lets a site start Google Analytics, 51LA and PostHog without a click for visitors whose region does not require consent. It is off unless a site sets `analytics.consent.regions`; without it every visitor requires consent and the output is unchanged. The Starlight, Docusaurus and Astro integrations accept the same options under `analytics.consent`, with the same names, defaults and errors.
644
+
645
+ ### Options
646
+
647
+ | Option | Default | Values and errors |
648
+ | --- | --- | --- |
649
+ | `regions` | absent (global consent) | `'default'` for the default country set, or an array of upper-case ISO 3166-1 alpha-2 codes that replaces the whole set. `regions` with `enabled: false` fails configuration with an error naming `regions`. |
650
+ | `countryCode` | none | One upper-case ISO code that overrides detection. Requires `regions`. |
651
+ | `regionHook` | none | Name of a function the site defines on `window` (an identifier or dotted path). It returns `'required'`, `'notRequired'`, `'unknown'`, a boolean (`true` required, `false` not required) or a promise of one of these. Requires `regions`. |
652
+ | `settingsEntry` | `'requiredOnly'` | `requiredOnly` shows the footer "Cookie settings" entry only to required and unknown visitors, and while the decision is pending it stays hidden. `always` shows it to every visitor. Requires `regions`. |
653
+ | `sessionReplay` | `'optIn'` | `optIn`: replay stays off in not-required regions until the visitor allows it in the footer. `projectDefault`: replay follows the PostHog project. `off`: replay never runs in not-required regions and no opt-in entry is rendered. Requires `regions`. |
654
+
655
+ A value of the wrong shape fails configuration with an error naming the option. So does a country code that is not an assigned upper-case ISO code, and a `regionHook` name that is not a valid identifier or dotted path. A regional-only option (`countryCode`, `regionHook`, `settingsEntry`, `sessionReplay`) set without `regions` fails with an error that names the option and says `regions` is required. In the browser an invalid `countryCode` yields `unknown`.
656
+
657
+ ```js
658
+ hagilight({
659
+ analytics: {
660
+ consent: { regions: 'default', settingsEntry: 'requiredOnly', sessionReplay: 'optIn' },
661
+ },
662
+ });
663
+ ```
664
+
665
+ ### Default consent-required countries
666
+
667
+ `regions: 'default'` requires consent for these countries. This is a product configuration, not a legal determination:
668
+
669
+ - EU27: AT BE BG HR CY CZ DK EE FI FR DE GR HU IE IT LV LT LU MT NL PL PT RO SK SI ES SE
670
+ - EEA: IS LI NO
671
+ - GB, CH, BR
672
+
673
+ China, South Korea, India and other regions are not in the set. A site-supplied list replaces the whole set. A visitor from a country outside the set does not require consent.
674
+
675
+ ### Resolution order
676
+
677
+ The decision is resolved at most once per document, and the popup, the footer entries and the gate share the result. Sources are consulted in this order, and a later source never overrides an earlier one that produced a result:
678
+
679
+ 1. The explicit `countryCode`. An invalid value yields `unknown` and no later source is consulted.
680
+ 2. The `regionHook`.
681
+ 3. The same-origin `/cdn-cgi/trace` endpoint, requested without credentials and without caching, with a 1200 ms timeout. Only the `loc` line is read, and it is accepted only when it is an assigned upper-case ISO code. The IP line is never read, stored or sent, and no request goes to a third-party host.
682
+ 4. A coarse fallback from the browser's `Intl` time zone:
683
+ - required: `Europe/*`, `Atlantic/Reykjavik`, `Arctic/Longyearbyen`, the zones of EU and EEA territories outside Europe (for example `Atlantic/Canary`), Cyprus (`Asia/Nicosia`, `Asia/Famagusta`), `Asia/Istanbul`, the Brazilian zones (for example `America/Sao_Paulo`) and the French outermost-region zones (for example `America/Martinique`, `Indian/Reunion`);
684
+ - not required: other `America/*`, `Asia/*`, `Australia/*` and `Pacific/*` zones;
685
+ - unknown: `UTC`, `Etc/*`, other `Africa/*` and `Indian/*` zones, `Antarctica/*`, and empty or unreadable values.
686
+ 5. Otherwise `unknown`.
687
+
688
+ The whole resolution has a 1800 ms deadline. If nothing has answered by then the result is `required`, and a late answer does not change a decision that already resolved. A hook that does not settle before the deadline counts as `unknown`.
689
+
690
+ ### Fail-closed rules
691
+
692
+ `unknown`, a hook that throws or rejects, a hook that returns an unrecognized value, a timeout, an invalid `countryCode` and an uncertain time zone all require consent. For these visitors the popup appears and no provider loads until the visitor accepts. An explicit `granted` or `denied` record is honored in every region, and a visitor with a valid record does not wait for the decision. A record that has expired (180 days) or whose policy version changed makes the visitor undecided again, so the region rule applies.
693
+
694
+ ### Cloudflare trace dependency and the `www` caveat
695
+
696
+ `/cdn-cgi/trace` answers only for hostnames proxied through Cloudflare. It was verified on the docs, design and omniroute `hagicode.com` subdomains. `www.hagicode.com` returned no `loc`, so on `www` the time-zone fallback decides, unless the site sets `countryCode` or `regionHook` for exact behavior. When the trace is unavailable, its failed request costs little and the time-zone fallback runs.
697
+
698
+ ### Consent records and Consent Mode
699
+
700
+ A visitor whose analytics start because of a not-required decision gets no consent record: `getConsent()` still reports `undecided`, and neither the `hagicode_consent` cookie nor the `hagicode:consent` key is written. The record format, the storage names and the 180-day lifetime are unchanged, and an explicit `denied` record blocks analytics in every region. Google Consent Mode and cookieless pings stay off, and no `gtag` consent default is added.
701
+
702
+ ### Session replay opt-in
703
+
704
+ Session replay belongs to PostHog. In a not-required region with `sessionReplay: 'optIn'`, the gate calls `set_config({ disable_session_recording: true })` and `stopSessionRecording()` even when the PostHog project enables replay, so no replay data is sent. The footer then offers "Allow session replay", with "Allow session replay" and "Not now" at equal prominence. Allowing it stores an ordinary `granted` record (the same record a popup acceptance stores), starts replay on the current page, and on later visits replay follows the PostHog project setting. "Not now" stores nothing and leaves replay off. A visitor who allows replay is also treated as having granted analytics in general. `projectDefault` skips the replay calls, and `off` renders no entry. The replay hold was verified with the real PostHog SDK in headless Chromium (`test/fixtures/posthog-replay-facts.json`).
705
+
706
+ ### Settings entry
707
+
708
+ On a regional site the footer "Cookie settings" entry is hidden for not-required visitors by default (`settingsEntry: 'requiredOnly'`). Set `settingsEntry: 'always'` to show it to them. Required and unknown visitors always see it.
709
+
710
+ ### Metadata
711
+
712
+ `features.consentMode` reports `globalRequired` or `regional` (see [Site metadata file](#site-metadata-file)). The file never contains the country list or the hook name.
713
+
714
+ ### Browser-safe region module
715
+
716
+ `@hagicode/hagilight-core/consent-region` exports `resolveRegionDecision()`, `startRegionResolution()`, `getRegionDecision()`, `onRegionDecision()`, `DEFAULT_REQUIRED_COUNTRIES`, `isAssignedCountryCode()` and `classifyTimeZone()`. It does not throw and needs no Node or Astro. Where `window` or `fetch` is unavailable, it resolves to `unknown`.
717
+
718
+ ### Measurement discontinuity
719
+
720
+ For a site that enables regional mode, GA4 and PostHog collection expands again after deployment. Data from then on is a second discontinuity and is not directly comparable with data collected since 2026-10-29. Operators must annotate the deployment date in GA4. In the monorepo, `docs/google-analytics-integration-reference.md` (section 3.2) has the full rules; this package README is published separately and does not link to it.
721
+
722
+ > **Legal notice:** This feature is product configuration and is not legal advice. The default country set, the inclusion of Brazil and the default hiding of "Cookie settings" for not-required visitors need confirmation by legal counsel. Site privacy notices may need matching updates; this project does not provide their wording.
723
+
639
724
  ## Google Analytics click events
640
725
 
641
726
  `GoogleAnalytics` also reports clicks on the key links and download buttons that the shared components render. There is nothing to configure: events follow the same rules as page views, so they are sent only on production pages where Google Analytics is enabled, never on the Starlight 404 page, and silently skipped when `gtag` is missing (development builds, blocked scripts).
@@ -18,4 +18,9 @@ export const copy = {
18
18
  choiceAccepted: "Akzeptiert",
19
19
  choiceRejected: "Abgelehnt",
20
20
  choiceUndecided: "Noch nicht ausgewählt",
21
+ replayEntry: "Sitzungswiederholung erlauben",
22
+ replayTitle: "Sitzungswiederholung",
23
+ replayBody: "Die Analyse läuft auf dieser Seite bereits. Die Sitzungswiederholung zeichnet auf, wie Sie die Seite nutzen, und bleibt aus, bis Sie sie erlauben.",
24
+ replayAllow: "Sitzungswiederholung erlauben",
25
+ replayDecline: "Nicht jetzt",
21
26
  };
@@ -18,4 +18,9 @@ export const copy = {
18
18
  choiceAccepted: "Accepted",
19
19
  choiceRejected: "Rejected",
20
20
  choiceUndecided: "Not chosen yet",
21
+ replayEntry: "Allow session replay",
22
+ replayTitle: "Session replay",
23
+ replayBody: "Analytics is already running here. Session replay records how you use this page and stays off until you allow it.",
24
+ replayAllow: "Allow session replay",
25
+ replayDecline: "Not now",
21
26
  };
@@ -18,4 +18,9 @@ export const copy = {
18
18
  choiceAccepted: "Aceptado",
19
19
  choiceRejected: "Rechazado",
20
20
  choiceUndecided: "Aún sin elegir",
21
+ replayEntry: "Permitir la repetición de sesión",
22
+ replayTitle: "Repetición de sesión",
23
+ replayBody: "El análisis ya se ejecuta en esta página. La repetición de sesión registra cómo usas la página y está desactivada hasta que la permitas.",
24
+ replayAllow: "Permitir la repetición de sesión",
25
+ replayDecline: "Ahora no",
21
26
  };
@@ -18,4 +18,9 @@ export const copy = {
18
18
  choiceAccepted: "Accepté",
19
19
  choiceRejected: "Refusé",
20
20
  choiceUndecided: "Pas encore choisi",
21
+ replayEntry: "Autoriser l'enregistrement de session",
22
+ replayTitle: "Enregistrement de session",
23
+ replayBody: "L'analyse fonctionne déjà sur cette page. L'enregistrement de session retrace votre utilisation de la page et reste désactivé tant que vous ne l'autorisez pas.",
24
+ replayAllow: "Autoriser l'enregistrement de session",
25
+ replayDecline: "Pas maintenant",
21
26
  };
@@ -18,4 +18,9 @@ export const copy = {
18
18
  choiceAccepted: "許可済み",
19
19
  choiceRejected: "拒否済み",
20
20
  choiceUndecided: "未選択",
21
+ replayEntry: "セッションリプレイを許可",
22
+ replayTitle: "セッションリプレイ",
23
+ replayBody: "このページでは分析がすでに動作しています。セッションリプレイはページの操作を記録するため、許可するまでオフのままです。",
24
+ replayAllow: "セッションリプレイを許可",
25
+ replayDecline: "今はしない",
21
26
  };
@@ -18,4 +18,9 @@ export const copy = {
18
18
  choiceAccepted: "허용됨",
19
19
  choiceRejected: "거부됨",
20
20
  choiceUndecided: "아직 선택하지 않음",
21
+ replayEntry: "세션 리플레이 허용",
22
+ replayTitle: "세션 리플레이",
23
+ replayBody: "이 페이지에서는 분석이 이미 실행되고 있습니다. 세션 리플레이는 페이지 사용 방식을 기록하며, 허용하기 전까지 꺼져 있습니다.",
24
+ replayAllow: "세션 리플레이 허용",
25
+ replayDecline: "나중에",
21
26
  };
@@ -18,4 +18,9 @@ export const copy = {
18
18
  choiceAccepted: "Aceita",
19
19
  choiceRejected: "Recusada",
20
20
  choiceUndecided: "Ainda não escolhida",
21
+ replayEntry: "Permitir gravação de sessão",
22
+ replayTitle: "Gravação de sessão",
23
+ replayBody: "A análise já está em execução nesta página. A gravação de sessão registra como você usa a página e fica desativada até você permitir.",
24
+ replayAllow: "Permitir gravação de sessão",
25
+ replayDecline: "Agora não",
21
26
  };
@@ -18,4 +18,9 @@ export const copy = {
18
18
  choiceAccepted: "Принято",
19
19
  choiceRejected: "Отклонено",
20
20
  choiceUndecided: "Пока не выбрано",
21
+ replayEntry: "Разрешить запись сеанса",
22
+ replayTitle: "Запись сеанса",
23
+ replayBody: "Аналитика на этой странице уже работает. Запись сеанса фиксирует, как вы пользуетесь страницей, и выключена, пока вы её не разрешите.",
24
+ replayAllow: "Разрешить запись сеанса",
25
+ replayDecline: "Не сейчас",
21
26
  };
@@ -19,4 +19,9 @@ export interface ConsentCopy {
19
19
  choiceAccepted: string;
20
20
  choiceRejected: string;
21
21
  choiceUndecided: string;
22
+ replayEntry: string;
23
+ replayTitle: string;
24
+ replayBody: string;
25
+ replayAllow: string;
26
+ replayDecline: string;
22
27
  }
@@ -18,4 +18,9 @@ export const copy = {
18
18
  choiceAccepted: "已接受",
19
19
  choiceRejected: "已拒绝",
20
20
  choiceUndecided: "尚未选择",
21
+ replayEntry: "允许会话回放",
22
+ replayTitle: "会话回放",
23
+ replayBody: "分析已在本页运行。会话回放会记录你如何使用本页,在你允许之前保持关闭。",
24
+ replayAllow: "允许会话回放",
25
+ replayDecline: "暂不",
21
26
  };
@@ -18,4 +18,9 @@ export const copy = {
18
18
  choiceAccepted: "已接受",
19
19
  choiceRejected: "已拒絕",
20
20
  choiceUndecided: "尚未選擇",
21
+ replayEntry: "允許工作階段重播",
22
+ replayTitle: "工作階段重播",
23
+ replayBody: "分析已在本頁執行。工作階段重播會記錄你如何使用本頁,在你允許前保持關閉。",
24
+ replayAllow: "允許工作階段重播",
25
+ replayDecline: "暫不",
21
26
  };
@@ -1,9 +1,17 @@
1
1
  import { type ConsentState } from './consent.js';
2
+ import { type RegionSource } from './consent-region.js';
2
3
  export type GateProvider = 'googleAnalytics' | 'fiftyOneLa' | 'posthog';
3
- /** The consent reads and subscriptions the gate uses. The page uses the module functions; tests inject a fake. */
4
+ /** `project` follows the PostHog project's recording setting. `off` keeps session replay disabled until a grant. */
5
+ export type ReplayMode = 'project' | 'off';
6
+ /** What started the providers in this document: an explicit record, or a `notRequired` region decision. */
7
+ export type StartReason = 'consent' | 'region';
8
+ export type SessionReplayOption = 'optIn' | 'projectDefault' | 'off';
9
+ /** The consent reads, subscriptions and region-replay option the gate uses. The page uses the module functions; tests inject a fake. */
4
10
  export interface ConsentApi {
5
11
  getConsent: () => ConsentState;
6
12
  onConsentChange: (listener: (state: ConsentState) => void) => () => void;
13
+ /** The session-replay option for `notRequired` starts. Defaults to `optIn`. */
14
+ sessionReplay?: () => SessionReplayOption;
7
15
  }
8
16
  /** The minimal document and window surface the gate touches. Tests pass fakes; the page passes the real globals. */
9
17
  export interface GateEnvironment {
@@ -34,14 +42,18 @@ export declare function readDescriptors(doc: Document): ProviderDescriptors;
34
42
  export interface ConsentGate {
35
43
  /** The providers this document has started, in the order they started. */
36
44
  started(): readonly GateProvider[];
37
- /** Removes the subscription. It does not stop providers that are already running. */
45
+ /** Why the providers started, or undefined before any start. */
46
+ startReason(): StartReason | undefined;
47
+ /** Removes the subscriptions. It does not stop providers that are already running. */
38
48
  dispose(): void;
39
49
  }
40
50
  /**
41
- * Starts enabled providers once the visitor grants analytics and stops them on withdrawal. A provider starts at most
42
- * once per document. Nothing is queued while undecided, and the gate never starts a provider while the decision is
43
- * denied or undecided. Withdrawal stops each started provider, then reloads if any of them cannot stop in place.
51
+ * Starts enabled providers and stops them on withdrawal. A provider starts at most once per document, and nothing
52
+ * starts while the decision is denied. An explicit record starts providers without waiting for the region. An
53
+ * undecided visitor starts providers only when the region decision is `notRequired`, and then writes no record. The
54
+ * region decision is awaited only for an undecided visitor. Withdrawal stops each started provider, then reloads if
55
+ * any of them cannot stop in place.
44
56
  */
45
- export declare function installConsentGate(env: GateEnvironment, consent?: ConsentApi): ConsentGate;
57
+ export declare function installConsentGate(env: GateEnvironment, consent?: ConsentApi, region?: RegionSource): ConsentGate;
46
58
  /** Installs the gate once per page, reading the real window and document. A second call returns the first gate. */
47
59
  export declare function mountConsentGate(win?: Window, doc?: Document): ConsentGate;
@@ -10,9 +10,21 @@
10
10
  * | PostHog (`phc_qiVV...PER5`, loader from `posthogInitScript`) | `ph_<key>_posthog` (written after the first `capture` on an opted-in page) | `ph_<key>_posthog`, `__ph_opt_in_out_<key>` (opt-out state) | `ph_<key>_session_registered_properties`, `ph_<key>_primary_window_exists` | `opt_out_capturing()` writes the opt-out state; `opt_in_capturing()` not observed; `clear_opt_in_out_capturing()` removes `__ph_opt_in_out_<key>` only. Opt-out is not a cleanup: `ph_` cookie and storage stay and must be removed by the gate. | Documented: opting out stops all capture, autocapture and session replay on the client. Not observed: the harness never let capture reach the network, so `stopInPlace` stays false until the group-10 browser check (10.2) confirms no request after reject. |
11
11
  * | Google Analytics (`G-EN03FMT2Q4`, `gtag.js`) | `_ga`, `_ga_<id>` where `<id>` is the measurement ID without the `G-` prefix (`_ga_EN03FMT2Q4`), both set on the page host after `config` | none | none | `window['ga-disable-<id>'] = true` set before `gtag.js` runs: no cookie and no `collect` request. Set after `config` (the in-place case): `collect` requests are still attempted, so the flag does not stop an initialized page in place. | false, reload on withdrawal |
12
12
  * | 51LA (`L6b88a5yK4h2Xnci`, `sdk.51.la/js-sdk-pro.min.js`) | not observed: `sdk.51.la` does not resolve from this machine (DNS) | not observed | not observed | task 1.3 is open: the SDK source could not be fetched here, so no stop or consent API is recorded | always reload (hard-coded) |
13
+ *
14
+ * PostHog replay under `notRequired` (verified 2026-11-01, real posthog-js 1.444.0 with the shipped loader; fixture
15
+ * test/fixtures/posthog-replay-facts.json). Queuing `set_config({ disable_session_recording: true })` and
16
+ * `stopSessionRecording()` right after the loader keeps every `/s/` request silent while events still flow, and a
17
+ * remote config that arrives 1500 ms late does not re-enable recording. An opt-in (`set_config` false plus
18
+ * `startSessionRecording()`) starts recording on the same page. So the init-time flag fallback is not used. The probe
19
+ * needed a non-bot user agent and `navigator.webdriver` false, because posthog-js drops events from headless browsers.
13
20
  */
14
- import { getConsent as readConsent, onConsentChange as subscribeConsent } from './consent.js';
15
- const moduleConsentApi = { getConsent: readConsent, onConsentChange: subscribeConsent };
21
+ import { getConsent as readConsent, onConsentChange as subscribeConsent, regionalBehavior, } from './consent.js';
22
+ import { pageRegionSource } from './consent-region.js';
23
+ const moduleConsentApi = {
24
+ getConsent: readConsent,
25
+ onConsentChange: subscribeConsent,
26
+ sessionReplay: () => regionalBehavior().sessionReplay,
27
+ };
16
28
  const DESCRIPTOR_SELECTOR = 'script[type="application/json"][data-hagilight-analytics]';
17
29
  const PROVIDERS = ['googleAnalytics', 'fiftyOneLa', 'posthog'];
18
30
  /** Post-grant hooks run once after PostHog starts, so later listeners install only from the grant. */
@@ -100,6 +112,23 @@ function safeStorage(env, kind) {
100
112
  return undefined;
101
113
  }
102
114
  }
115
+ /** Sets PostHog's session recording through its stub methods. They queue safely before the SDK loads. */
116
+ function setPostHogReplay(env, enabled) {
117
+ try {
118
+ const posthog = env.window.posthog;
119
+ if (enabled) {
120
+ posthog?.set_config?.({ disable_session_recording: false });
121
+ posthog?.startSessionRecording?.();
122
+ }
123
+ else {
124
+ posthog?.set_config?.({ disable_session_recording: true });
125
+ posthog?.stopSessionRecording?.();
126
+ }
127
+ }
128
+ catch {
129
+ // The SDK's stub may be absent in a test page; nothing to change.
130
+ }
131
+ }
103
132
  const TABLE = {
104
133
  googleAnalytics: {
105
134
  stopInPlace: false,
@@ -147,13 +176,16 @@ const TABLE = {
147
176
  },
148
177
  posthog: {
149
178
  stopInPlace: false,
150
- start(env, descriptors) {
179
+ start(env, descriptors, options) {
151
180
  const ph = descriptors.posthog;
152
181
  if (!ph)
153
182
  return;
154
183
  // A previous opt-out would keep capture off after the grant, so the stored opt-out state is cleared first.
155
184
  removeStorageKey(safeStorage(env, 'localStorage'), `__ph_opt_in_out_${ph.apiKey}`);
156
185
  injectInline(env, ph.loader);
186
+ // Replay is switched off right after the loader runs, in the same frame, so the queued calls precede the SDK.
187
+ if (options.replay === 'off')
188
+ setPostHogReplay(env, false);
157
189
  for (const hook of postGrantHooks) {
158
190
  try {
159
191
  hook();
@@ -163,6 +195,9 @@ const TABLE = {
163
195
  }
164
196
  }
165
197
  },
198
+ enableReplay(env) {
199
+ setPostHogReplay(env, true);
200
+ },
166
201
  stop(env) {
167
202
  try {
168
203
  const posthog = env.window.posthog;
@@ -189,23 +224,31 @@ function removeStorageKey(storage, key) {
189
224
  }
190
225
  }
191
226
  /**
192
- * Starts enabled providers once the visitor grants analytics and stops them on withdrawal. A provider starts at most
193
- * once per document. Nothing is queued while undecided, and the gate never starts a provider while the decision is
194
- * denied or undecided. Withdrawal stops each started provider, then reloads if any of them cannot stop in place.
227
+ * Starts enabled providers and stops them on withdrawal. A provider starts at most once per document, and nothing
228
+ * starts while the decision is denied. An explicit record starts providers without waiting for the region. An
229
+ * undecided visitor starts providers only when the region decision is `notRequired`, and then writes no record. The
230
+ * region decision is awaited only for an undecided visitor. Withdrawal stops each started provider, then reloads if
231
+ * any of them cannot stop in place.
195
232
  */
196
- export function installConsentGate(env, consent = moduleConsentApi) {
233
+ export function installConsentGate(env, consent = moduleConsentApi, region = pageRegionSource({ holder: env.window })) {
197
234
  /** Providers running now. Withdrawal empties it. */
198
235
  const startedOrder = [];
199
236
  /** Providers ever started in this document. A provider starts at most once per document, even after a withdrawal. */
200
237
  const everStarted = new Set();
238
+ /** PostHog started with replay off and has not been granted replay yet. */
239
+ let replayHeld = false;
240
+ let reason;
201
241
  let descriptors = readDescriptors(env.document);
202
- const startAll = () => {
242
+ const startAll = (why, replay) => {
203
243
  for (const provider of PROVIDERS) {
204
244
  if (everStarted.has(provider) || !descriptors[provider])
205
245
  continue;
206
246
  everStarted.add(provider);
207
247
  startedOrder.push(provider);
208
- TABLE[provider].start(env, descriptors);
248
+ reason ??= why;
249
+ if (provider === 'posthog' && replay === 'off')
250
+ replayHeld = true;
251
+ TABLE[provider].start(env, descriptors, { replay });
209
252
  }
210
253
  };
211
254
  const stopAll = () => {
@@ -216,20 +259,44 @@ export function installConsentGate(env, consent = moduleConsentApi) {
216
259
  needsReload = true;
217
260
  }
218
261
  startedOrder.length = 0;
262
+ replayHeld = false;
219
263
  if (needsReload)
220
264
  env.reload();
221
265
  };
266
+ /** An explicit grant turns on a replay that was held, unless the site set replay to stay off. */
267
+ const enableHeldReplay = () => {
268
+ if (!replayHeld || !startedOrder.includes('posthog') || consent.sessionReplay?.() === 'off')
269
+ return;
270
+ replayHeld = false;
271
+ TABLE.posthog.enableReplay?.(env);
272
+ };
222
273
  const apply = (state) => {
223
- if (state.analytics === 'granted')
224
- startAll();
225
- else if (state.analytics === 'denied' && startedOrder.length > 0)
274
+ if (state.analytics === 'granted') {
275
+ startAll('consent', 'project');
276
+ enableHeldReplay();
277
+ }
278
+ else if (state.analytics === 'denied' && startedOrder.length > 0) {
226
279
  stopAll();
280
+ }
281
+ };
282
+ /** A `notRequired` decision starts the providers only for a visitor with no record. Other decisions do nothing. */
283
+ const applyRegion = (decision) => {
284
+ if (decision !== 'notRequired')
285
+ return;
286
+ if (consent.getConsent().analytics !== 'undecided')
287
+ return;
288
+ startAll('region', consent.sessionReplay?.() === 'projectDefault' ? 'project' : 'off');
227
289
  };
228
290
  const unsubscribe = consent.onConsentChange(apply);
229
291
  apply(consent.getConsent());
292
+ const unsubscribeRegion = region.subscribe(applyRegion);
230
293
  return {
231
294
  started: () => [...startedOrder],
232
- dispose: unsubscribe,
295
+ startReason: () => reason,
296
+ dispose: () => {
297
+ unsubscribe();
298
+ unsubscribeRegion();
299
+ },
233
300
  };
234
301
  }
235
302
  /** Installs the gate once per page, reading the real window and document. A second call returns the first gate. */
@@ -1,5 +1,14 @@
1
1
  import { type ConsentProvider } from './consent-details.js';
2
2
  export declare const CONSENT_PROVIDERS: readonly ConsentProvider[];
3
+ /** The regional options a regional site passes through to the page. Absent means global consent. */
4
+ export interface RegionalPopupOptions {
5
+ regions: 'default' | readonly string[];
6
+ countryCode?: string;
7
+ /** The name of a function the site defines on `window`. */
8
+ regionHook?: string;
9
+ settingsEntry: 'requiredOnly' | 'always';
10
+ sessionReplay: 'optIn' | 'projectDefault' | 'off';
11
+ }
3
12
  export interface ConsentPopupOptions {
4
13
  /** The page locale. An unsupported value renders `en-US`. */
5
14
  locale?: string;
@@ -9,15 +18,34 @@ export interface ConsentPopupOptions {
9
18
  privacyUrl?: string;
10
19
  /** Defaults to `1`. Changing it asks every visitor again. */
11
20
  policyVersion?: string;
21
+ /** Set only for a regional site. Its absence keeps the global descriptor and markup unchanged. */
22
+ regional?: RegionalPopupOptions;
12
23
  }
13
24
  export interface ResolvedConsentPopupOptions {
14
25
  locale: string;
15
26
  providers: readonly ConsentProvider[];
16
27
  privacyUrl: string | undefined;
17
28
  policyVersion: string;
29
+ regional?: RegionalPopupOptions;
18
30
  }
19
31
  /** Throws a TypeError that names the option when the value is not an absolute HTTP(S) URL or a site-relative path. */
20
32
  export declare function validatePrivacyUrl(value: unknown): string | undefined;
33
+ /** Throws a TypeError that names the option unless it is `default` or a non-empty list of assigned upper-case codes. */
34
+ export declare function validateRegions(value: unknown): 'default' | string[];
35
+ /** Throws a TypeError that names the option unless the value is one assigned upper-case ISO 3166-1 alpha-2 code. */
36
+ export declare function validateCountryCode(value: unknown): string;
37
+ /** Throws a TypeError that names the option unless the value is the name of a function on `window`, not code. */
38
+ export declare function validateHookName(value: unknown): string;
39
+ /** Throws a TypeError that names the option unless it is `requiredOnly` or `always`. */
40
+ export declare function validateSettingsEntry(value: unknown): 'requiredOnly' | 'always';
41
+ /** Throws a TypeError that names the option unless it is `optIn`, `projectDefault` or `off`. */
42
+ export declare function validateSessionReplay(value: unknown): 'optIn' | 'projectDefault' | 'off';
43
+ /**
44
+ * Validates the regional options of `analytics.consent` for every integration. Returns `undefined` when no regional option
45
+ * is set, so a global site stays exactly as it was. A regional-only option without `regions` throws, and so does `regions`
46
+ * with consent disabled, because either would silently widen or hide a compliance setting.
47
+ */
48
+ export declare function resolveRegionalOptions(input: Record<string, unknown> | undefined, enabled?: boolean): RegionalPopupOptions | undefined;
21
49
  /** Throws a TypeError that names the option when the policy version is not 1 to 32 safe characters. */
22
50
  export declare function validatePolicyVersion(value: unknown): string;
23
51
  export declare function resolveConsentPopupOptions(options: ConsentPopupOptions): ResolvedConsentPopupOptions;
@@ -29,5 +57,9 @@ export declare function escapeHtml(value: string): string;
29
57
  export declare function consentDescriptor(options: ConsentPopupOptions): string;
30
58
  /** The ID of the descriptor script, so the popup and the gate can read the same element. */
31
59
  export declare const CONSENT_DESCRIPTOR_ID = "hagilight-consent-config";
32
- /** The popup's HTML: a hidden, labelled, non-modal region with two equal actions and an expandable details section. */
60
+ /**
61
+ * The popup's HTML: a hidden, labelled, non-modal region with two equal actions and an expandable details section. A
62
+ * regional site with session replay opt-in also gets a hidden replay section, with equal Allow and Not now actions. A
63
+ * global site renders exactly the markup it always did.
64
+ */
33
65
  export declare function renderConsentMarkup(options: ConsentPopupOptions): string;