@hagicode/hagilight-core 0.18.0 → 0.19.1-dev.185.1.a85e2a8

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.
Files changed (69) hide show
  1. package/Analytics51LA.astro +19 -3
  2. package/CookieConsent.astro +402 -0
  3. package/Footer.astro +31 -5
  4. package/FooterBrand.astro +23 -3
  5. package/GoogleAnalytics.astro +17 -2
  6. package/PostHog.astro +55 -3
  7. package/PromotoBanner.astro +3 -3
  8. package/README.md +102 -8
  9. package/dist/analytics-events.d.ts +15 -0
  10. package/dist/analytics-events.js +25 -15
  11. package/dist/consent-copy/de-DE.d.ts +2 -0
  12. package/dist/consent-copy/de-DE.js +21 -0
  13. package/dist/consent-copy/en-US.d.ts +2 -0
  14. package/dist/consent-copy/en-US.js +21 -0
  15. package/dist/consent-copy/es-ES.d.ts +2 -0
  16. package/dist/consent-copy/es-ES.js +21 -0
  17. package/dist/consent-copy/fr-FR.d.ts +2 -0
  18. package/dist/consent-copy/fr-FR.js +21 -0
  19. package/dist/consent-copy/index.d.ts +7 -0
  20. package/dist/consent-copy/index.js +31 -0
  21. package/dist/consent-copy/ja-JP.d.ts +2 -0
  22. package/dist/consent-copy/ja-JP.js +21 -0
  23. package/dist/consent-copy/ko-KR.d.ts +2 -0
  24. package/dist/consent-copy/ko-KR.js +21 -0
  25. package/dist/consent-copy/pt-BR.d.ts +2 -0
  26. package/dist/consent-copy/pt-BR.js +21 -0
  27. package/dist/consent-copy/ru-RU.d.ts +2 -0
  28. package/dist/consent-copy/ru-RU.js +21 -0
  29. package/dist/consent-copy/types.d.ts +22 -0
  30. package/dist/consent-copy/types.js +1 -0
  31. package/dist/consent-copy/zh-CN.d.ts +2 -0
  32. package/dist/consent-copy/zh-CN.js +21 -0
  33. package/dist/consent-copy/zh-Hant.d.ts +2 -0
  34. package/dist/consent-copy/zh-Hant.js +21 -0
  35. package/dist/consent-details.d.ts +29 -0
  36. package/dist/consent-details.js +41 -0
  37. package/dist/consent-gate.d.ts +47 -0
  38. package/dist/consent-gate.js +243 -0
  39. package/dist/consent-markup.d.ts +33 -0
  40. package/dist/consent-markup.js +113 -0
  41. package/dist/consent-mount.d.ts +26 -0
  42. package/dist/consent-mount.js +81 -0
  43. package/dist/consent-popup.d.ts +6 -0
  44. package/dist/consent-popup.js +203 -0
  45. package/dist/consent.d.ts +65 -0
  46. package/dist/consent.js +314 -0
  47. package/dist/entity-definition.d.ts +19 -0
  48. package/dist/entity-definition.js +23 -0
  49. package/dist/link-policy.d.ts +7 -2
  50. package/dist/link-policy.js +8 -1
  51. package/dist/links.d.ts +12 -4
  52. package/dist/links.js +16 -10
  53. package/dist/posthog-events.d.ts +95 -0
  54. package/dist/posthog-events.js +263 -0
  55. package/dist/posthog-interactions.d.ts +85 -0
  56. package/dist/posthog-interactions.js +280 -0
  57. package/dist/posthog.d.ts +25 -3
  58. package/dist/posthog.js +64 -6
  59. package/dist/promoto-analytics.d.ts +45 -0
  60. package/dist/promoto-analytics.js +92 -0
  61. package/dist/promoto-banner.js +62 -4
  62. package/dist/related-sites.json +2 -2
  63. package/dist/root-transit.d.ts +7 -1
  64. package/dist/root-transit.js +42 -1
  65. package/dist/seo.d.ts +30 -1
  66. package/dist/seo.js +93 -1
  67. package/dist/site-metadata.d.ts +11 -6
  68. package/dist/site-metadata.js +21 -8
  69. package/package.json +42 -1
@@ -0,0 +1,280 @@
1
+ import { POSTHOG_PAGE_TYPES, capturePostHogEvent, classifyPagePath, } from './posthog-events.js';
2
+ /*
3
+ * Observers for DOM-owned interactions: Pagefind search (Starlight), result clicks, code copy buttons
4
+ * (Expressive Code and Docusaurus) and Docusaurus locale links. Delegated on the document, so lazily
5
+ * created dialogs and client navigation need no rebinding. Observers only read the DOM. They never call
6
+ * preventDefault or stopPropagation, never read copied code or clipboard data, and never throw.
7
+ */
8
+ export const SEARCH_DEBOUNCE_MS = 800;
9
+ export const SEARCH_SETTLE_TIMEOUT_MS = 2000;
10
+ export const SEARCH_POLL_MS = 100;
11
+ const SEARCH_QUERY_MAX_CODE_POINTS = 64;
12
+ const SEARCH_INPUT = '.pagefind-ui__search-input';
13
+ const SEARCH_ROOT = '.pagefind-ui';
14
+ const SEARCH_MESSAGE = '.pagefind-ui__message';
15
+ const SEARCH_RESULT_LINK = 'a.pagefind-ui__result-link';
16
+ // Pagefind renders the results list only once a search has settled; while loading it shows "Searching…" instead.
17
+ const SEARCH_RESULTS = '.pagefind-ui__results';
18
+ const SEARCH_LOADING = '.pagefind-ui__loading';
19
+ const STARLIGHT_COPY_BUTTON = '.expressive-code .copy button';
20
+ const DOCUSAURUS_COPY_BUTTON = '.theme-code-block button[class*="copyButton"]';
21
+ const CODE_BLOCK = '.expressive-code, .theme-code-block';
22
+ // Docusaurus renders each locale dropdown item with `lang` (the locale code); `hreflang` is accepted too.
23
+ const DOCUSAURUS_LOCALE_LINK = '.navbar a[hreflang], .navbar a[lang]';
24
+ const PAGE_TYPE_META = 'meta[name="hagilight:page-type"]';
25
+ const LANGUAGE_PATTERN = /^[a-z0-9+#._-]{1,32}$/u;
26
+ const INSTALLED_KEY = Symbol.for('hagilight.posthog-interactions');
27
+ function defaultEnvironment() {
28
+ const globalWindow = globalThis.window;
29
+ return {
30
+ timers: globalThis,
31
+ posthog: () => globalWindow?.posthog,
32
+ config: () => globalWindow?.__hagilightPosthogConfig,
33
+ pathname: () => globalWindow?.location?.pathname ?? '',
34
+ };
35
+ }
36
+ const HEX_RUN = /[0-9a-f]{16,}/iu;
37
+ const KEY_LIKE_TOKEN = /[A-Za-z0-9+\/_=-]{24,}/u;
38
+ const TOKEN_PREFIXES = ['phc_', 'sk-', 'ghp_', 'gho_', 'xox', 'AKIA', 'eyJ'];
39
+ /**
40
+ * Returns the search text when it is safe to send, or `undefined`. The whole text is checked before it is
41
+ * truncated, so a secret that starts after the 64th character still withholds the text.
42
+ */
43
+ export function sanitizeSearchQuery(value) {
44
+ if (typeof value !== 'string')
45
+ return undefined;
46
+ const text = value.trim();
47
+ if (!text)
48
+ return undefined;
49
+ if (HEX_RUN.test(text) || /[/\\]/u.test(text) || text.startsWith('~') || text.includes('://'))
50
+ return undefined;
51
+ if (/bearer\s/iu.test(text))
52
+ return undefined;
53
+ for (const token of text.split(/\s+/u)) {
54
+ if (KEY_LIKE_TOKEN.test(token) || token.includes('@') || TOKEN_PREFIXES.some((prefix) => token.startsWith(prefix)))
55
+ return undefined;
56
+ }
57
+ return [...text].slice(0, SEARCH_QUERY_MAX_CODE_POINTS).join('');
58
+ }
59
+ /**
60
+ * The result count of a settled Pagefind list. The first number of the message is the total, after the query
61
+ * text is removed so digits typed by the visitor are not counted, and locale grouping (`1,234`) is folded.
62
+ * With no number, an empty list is zero results; anything else is unknown and sends nothing.
63
+ */
64
+ export function readResultsCount(root, query) {
65
+ const raw = root.querySelector(SEARCH_MESSAGE)?.textContent ?? '';
66
+ const message = query ? raw.split(query).join(' ') : raw;
67
+ const match = /\d+(?:[.,\s\u00a0\u202f]\d{3})*/u.exec(message);
68
+ if (match)
69
+ return Number(match[0].replace(/\D/gu, ''));
70
+ return root.querySelectorAll(SEARCH_RESULT_LINK).length === 0 ? 0 : undefined;
71
+ }
72
+ function languageClass(element) {
73
+ const classes = element?.getAttribute('class') ?? '';
74
+ return /(?:^|\s)language-(\S+)/u.exec(classes)?.[1];
75
+ }
76
+ /** A declared language from `data-language` or a `language-*` class, lowercased; `unknown` otherwise. */
77
+ export function normalizeCodeLanguage(value) {
78
+ const text = value?.trim().toLowerCase() ?? '';
79
+ return LANGUAGE_PATTERN.test(text) ? text : 'unknown';
80
+ }
81
+ function pageTypeOf(doc, pathname, lang) {
82
+ const declared = doc.querySelector(PAGE_TYPE_META)?.getAttribute('content');
83
+ if (declared && POSTHOG_PAGE_TYPES.includes(declared))
84
+ return declared;
85
+ return classifyPagePath(pathname, { locales: lang ? [lang] : [] });
86
+ }
87
+ function currentLocale(doc) {
88
+ return doc.documentElement.lang ?? '';
89
+ }
90
+ function reportSearch(doc, env, field, root) {
91
+ const query = (field.value ?? '').trim();
92
+ if (!query)
93
+ return;
94
+ const count = readResultsCount(root, query);
95
+ if (count === undefined)
96
+ return;
97
+ const properties = {
98
+ query_length: [...query].length,
99
+ results_count: count,
100
+ locale: currentLocale(doc),
101
+ };
102
+ if (count === 0 && env.config()?.searchQuery === 'zero-results') {
103
+ const safe = sanitizeSearchQuery(query);
104
+ if (safe !== undefined)
105
+ properties.query = safe;
106
+ }
107
+ capturePostHogEvent('search_used', properties, env.posthog());
108
+ }
109
+ /** Waits until Pagefind has rendered a settled list with no loading placeholder, then reports once. Sends nothing on timeout. */
110
+ function awaitSettledSearch(doc, env, field, root, waitedMs, track) {
111
+ if (root.querySelector(SEARCH_RESULTS) && !root.querySelector(SEARCH_LOADING)) {
112
+ reportSearch(doc, env, field, root);
113
+ return;
114
+ }
115
+ if (waitedMs >= SEARCH_SETTLE_TIMEOUT_MS)
116
+ return;
117
+ track(env.timers.setTimeout(() => awaitSettledSearch(doc, env, field, root, waitedMs + SEARCH_POLL_MS, track), SEARCH_POLL_MS));
118
+ }
119
+ function handleInput(doc, env, state, event) {
120
+ const field = elementOf(event.target)?.closest(SEARCH_INPUT);
121
+ if (!field)
122
+ return;
123
+ for (const handle of state.pending.splice(0))
124
+ env.timers.clearTimeout(handle);
125
+ const root = field.closest(SEARCH_ROOT);
126
+ if (!root)
127
+ return;
128
+ const track = (handle) => state.pending.push(handle);
129
+ state.pending.push(env.timers.setTimeout(() => {
130
+ state.pending.splice(0);
131
+ awaitSettledSearch(doc, env, field, root, 0, track);
132
+ }, SEARCH_DEBOUNCE_MS));
133
+ }
134
+ function handleResultClick(env, link) {
135
+ const root = link.closest(SEARCH_ROOT);
136
+ if (!root)
137
+ return;
138
+ const links = Array.from(root.querySelectorAll(SEARCH_RESULT_LINK));
139
+ const rank = links.indexOf(link) + 1;
140
+ if (rank < 1)
141
+ return;
142
+ const query = root.querySelector(SEARCH_INPUT)?.value?.trim() ?? '';
143
+ const count = readResultsCount(root, query);
144
+ if (count === undefined)
145
+ return;
146
+ capturePostHogEvent('search_result_clicked', { rank, results_count: count }, env.posthog());
147
+ }
148
+ function handleCopy(doc, env, button) {
149
+ const block = button.closest(CODE_BLOCK);
150
+ const pre = block?.querySelector('pre') ?? null;
151
+ const declared = pre?.getAttribute('data-language') ?? languageClass(pre) ?? languageClass(block);
152
+ const pathname = env.pathname();
153
+ capturePostHogEvent('code_copied', {
154
+ language: normalizeCodeLanguage(declared),
155
+ page_type: pageTypeOf(doc, pathname, currentLocale(doc)),
156
+ is_install_page: pathname.includes('/installation/'),
157
+ }, env.posthog());
158
+ }
159
+ function handleLocaleLink(doc, env, link) {
160
+ const to = link.getAttribute('hreflang') ?? link.getAttribute('lang');
161
+ const from = currentLocale(doc);
162
+ if (!to || to === from)
163
+ return;
164
+ capturePostHogEvent('locale_changed', { from, to }, env.posthog());
165
+ }
166
+ function elementOf(target) {
167
+ return typeof target === 'object' && target !== null && typeof target.closest === 'function'
168
+ ? target
169
+ : undefined;
170
+ }
171
+ function handleClick(doc, env, event) {
172
+ const target = elementOf(event.target);
173
+ if (!target)
174
+ return;
175
+ const link = target.closest(SEARCH_RESULT_LINK);
176
+ if (link)
177
+ return handleResultClick(env, link);
178
+ const button = target.closest(STARLIGHT_COPY_BUTTON) ?? target.closest(DOCUSAURUS_COPY_BUTTON);
179
+ if (button)
180
+ return handleCopy(doc, env, button);
181
+ const localeLink = target.closest(DOCUSAURUS_LOCALE_LINK);
182
+ if (localeLink)
183
+ handleLocaleLink(doc, env, localeLink);
184
+ }
185
+ /**
186
+ * Installs the delegated interaction observers once per document. Returns `false` when already installed.
187
+ * Every handler is wrapped so an observer failure never reaches the page.
188
+ */
189
+ export function installPostHogInteractions(doc = document, overrides = {}) {
190
+ const marked = doc;
191
+ if (marked[INSTALLED_KEY])
192
+ return false;
193
+ marked[INSTALLED_KEY] = true;
194
+ const env = { ...defaultEnvironment(), ...overrides };
195
+ const state = { pending: [] };
196
+ doc.addEventListener('input', (event) => {
197
+ try {
198
+ handleInput(doc, env, state, event);
199
+ }
200
+ catch {
201
+ // Analytics must never interfere with search.
202
+ }
203
+ }, { capture: true });
204
+ doc.addEventListener('click', (event) => {
205
+ try {
206
+ handleClick(doc, env, event);
207
+ }
208
+ catch {
209
+ // Analytics must never interfere with clicks.
210
+ }
211
+ }, { capture: true });
212
+ return true;
213
+ }
214
+ /*
215
+ * End-of-article promotion impressions. The card counts as seen once at least half of it is visible for one
216
+ * continuous second. The event fires at most once per page view; click reporting stays with `cta_click`.
217
+ */
218
+ export const PROMOTION_IMPRESSION_THRESHOLD = 0.5;
219
+ export const PROMOTION_IMPRESSION_DWELL_MS = 1000;
220
+ const PROMOTION_CARD = '.hagilight-article-promotion';
221
+ const CENTRE_FAN_CARD = '.hagilight-fan__card[data-slot="1"]';
222
+ const VARIANT_PATTERN = /^[a-z0-9._-]{1,64}$/u;
223
+ /** The pool key of the centre fan card, from its image file name, or `default` when no fan was dealt. */
224
+ export function promotionVariantOf(card) {
225
+ const source = card.querySelector(CENTRE_FAN_CARD)?.getAttribute('src') ?? '';
226
+ const key = (source.split(/[?#]/u, 1)[0] ?? '').split('/').pop()?.replace(/\.avif$/u, '') ?? '';
227
+ return VARIANT_PATTERN.test(key) ? key : 'default';
228
+ }
229
+ /**
230
+ * Observes one promotion card and sends `article_promotion_impression` after sustained visibility. Returns
231
+ * `false` without an IntersectionObserver, so no event is sent there. Never throws.
232
+ */
233
+ export function observePromotionImpression(card, overrides = {}) {
234
+ const defaults = defaultEnvironment();
235
+ const env = {
236
+ timers: defaults.timers,
237
+ posthog: defaults.posthog,
238
+ pathname: defaults.pathname,
239
+ IntersectionObserver: globalThis.IntersectionObserver,
240
+ ...overrides,
241
+ };
242
+ if (typeof env.IntersectionObserver !== 'function')
243
+ return false;
244
+ let timer;
245
+ let sent = false;
246
+ let observer;
247
+ observer = new env.IntersectionObserver((entries) => {
248
+ try {
249
+ for (const entry of entries) {
250
+ if (entry.isIntersecting && entry.intersectionRatio >= PROMOTION_IMPRESSION_THRESHOLD) {
251
+ if (timer === undefined && !sent) {
252
+ timer = env.timers.setTimeout(() => {
253
+ timer = undefined;
254
+ sent = true;
255
+ observer?.disconnect();
256
+ capturePostHogEvent('article_promotion_impression', {
257
+ variant: promotionVariantOf(card),
258
+ path: env.pathname(),
259
+ }, env.posthog());
260
+ }, PROMOTION_IMPRESSION_DWELL_MS);
261
+ }
262
+ }
263
+ else if (timer !== undefined) {
264
+ env.timers.clearTimeout(timer);
265
+ timer = undefined;
266
+ }
267
+ }
268
+ }
269
+ catch {
270
+ // Analytics must never interfere with the page.
271
+ }
272
+ }, { threshold: PROMOTION_IMPRESSION_THRESHOLD });
273
+ observer.observe(card);
274
+ return true;
275
+ }
276
+ /** Observes the page's promotion card, if the page has one. */
277
+ export function installPromotionImpression(doc = document) {
278
+ const card = doc.querySelector(PROMOTION_CARD);
279
+ return card ? observePromotionImpression(card) : false;
280
+ }
package/dist/posthog.d.ts CHANGED
@@ -1,6 +1,28 @@
1
+ import { type PostHogFramework, type PostHogPageType } from './posthog-events.js';
1
2
  export declare const DEFAULT_POSTHOG_API_KEY = "phc_qiVVihsL925ovhPYNdLJWz4k7aoKVMwYCevgZPE6PER5";
2
- export declare const POSTHOG_API_HOST = "https://us.i.posthog.com";
3
+ export declare const POSTHOG_API_HOST = "https://t.hagicode.com";
4
+ export declare const POSTHOG_UI_HOST = "https://us.posthog.com";
3
5
  export declare const POSTHOG_DEFAULTS = "2026-05-30";
6
+ export declare const POSTHOG_PERSON_PROFILES = "identified_only";
4
7
  export declare const POSTHOG_API_KEY_PATTERN: RegExp;
5
- /** Browser-safe, once-per-document initialization using the supplied PostHog loader. */
6
- export declare function posthogInitScript(apiKey?: string): string;
8
+ /** Site facts registered as PostHog super properties right after initialization. */
9
+ export interface PostHogSiteContext {
10
+ /** Omitted to use the document hostname at run time. */
11
+ siteId?: string;
12
+ framework: PostHogFramework;
13
+ /** The integration's package version, sent as `hagilight_version`. */
14
+ version: string;
15
+ /** A build-time page type. Out-of-vocabulary values are treated as absent. */
16
+ pageType?: PostHogPageType;
17
+ }
18
+ /** Options for the interaction layer. Omitted or `off` keeps search text out of every event. */
19
+ export interface PostHogInitOptions {
20
+ searchQuery?: PostHogSearchQueryMode;
21
+ }
22
+ export declare const POSTHOG_SEARCH_QUERY_MODES: readonly ["off", "zero-results"];
23
+ export type PostHogSearchQueryMode = (typeof POSTHOG_SEARCH_QUERY_MODES)[number];
24
+ /**
25
+ * Browser-safe, once-per-document initialization using the supplied PostHog loader. With a site context,
26
+ * the page also registers its super properties once, right after initialization.
27
+ */
28
+ export declare function posthogInitScript(apiKey?: string, context?: PostHogSiteContext, options?: PostHogInitOptions): string;
package/dist/posthog.js CHANGED
@@ -1,17 +1,75 @@
1
+ import { POSTHOG_FRAMEWORKS, POSTHOG_PAGE_TYPES } from './posthog-events.js';
1
2
  export const DEFAULT_POSTHOG_API_KEY = 'phc_qiVVihsL925ovhPYNdLJWz4k7aoKVMwYCevgZPE6PER5';
2
- export const POSTHOG_API_HOST = 'https://us.i.posthog.com';
3
+ export const POSTHOG_API_HOST = 'https://t.hagicode.com';
4
+ export const POSTHOG_UI_HOST = 'https://us.posthog.com';
3
5
  export const POSTHOG_DEFAULTS = '2026-05-30';
6
+ export const POSTHOG_PERSON_PROFILES = 'identified_only';
4
7
  export const POSTHOG_API_KEY_PATTERN = /^phc_[A-Za-z0-9]+$/u;
5
- /** Browser-safe, once-per-document initialization using the supplied PostHog loader. */
6
- export function posthogInitScript(apiKey = DEFAULT_POSTHOG_API_KEY) {
8
+ function serializeLiteral(value) {
9
+ return JSON.stringify(value).replace(/</gu, '\\u003c');
10
+ }
11
+ export const POSTHOG_SEARCH_QUERY_MODES = ['off', 'zero-results'];
12
+ function resolveInteractionConfig(options) {
13
+ if (!POSTHOG_SEARCH_QUERY_MODES.includes(options.searchQuery)) {
14
+ throw new TypeError('PostHog searchQuery must be one of: off, zero-results.');
15
+ }
16
+ return { searchQuery: options.searchQuery };
17
+ }
18
+ function resolveSiteContext(context) {
19
+ if (typeof context !== 'object' || context === null) {
20
+ throw new TypeError('PostHog site context must be an object.');
21
+ }
22
+ if (!POSTHOG_FRAMEWORKS.includes(context.framework)) {
23
+ throw new TypeError(`PostHog site context framework must be one of: ${POSTHOG_FRAMEWORKS.join(', ')}.`);
24
+ }
25
+ if (context.siteId !== undefined && typeof context.siteId !== 'string') {
26
+ throw new TypeError('PostHog site context siteId must be a string.');
27
+ }
28
+ if (typeof context.version !== 'string') {
29
+ throw new TypeError('PostHog site context version must be a string.');
30
+ }
31
+ const siteId = context.siteId?.trim() || undefined;
32
+ const version = context.version.trim() || undefined;
33
+ const pageType = POSTHOG_PAGE_TYPES.includes(context.pageType) ? context.pageType : undefined;
34
+ return { siteId, framework: context.framework, version, pageType };
35
+ }
36
+ /**
37
+ * Browser-safe, once-per-document initialization using the supplied PostHog loader. With a site context,
38
+ * the page also registers its super properties once, right after initialization.
39
+ */
40
+ export function posthogInitScript(apiKey = DEFAULT_POSTHOG_API_KEY, context, options) {
7
41
  if (typeof apiKey !== 'string' || !POSTHOG_API_KEY_PATTERN.test(apiKey)) {
8
42
  throw new TypeError('PostHog apiKey must be phc_ followed by ASCII letters or digits.');
9
43
  }
10
- const key = JSON.stringify(apiKey).replace(/</gu, '\\u003c');
11
- return `(() => {
44
+ const key = serializeLiteral(apiKey);
45
+ const siteContext = serializeLiteral(context === undefined ? {} : resolveSiteContext(context));
46
+ // Only a non-default search option adds a line, so default output stays byte-identical.
47
+ const interactionConfig = options?.searchQuery === undefined || options.searchQuery === 'off'
48
+ ? ''
49
+ : `window.__hagilightPosthogConfig = ${serializeLiteral(resolveInteractionConfig(options))};\n`;
50
+ return `${interactionConfig}(() => {
12
51
  if (window.__hagilightPosthogInitialized) return;
13
52
  !function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],Object.defineProperty(u,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e}}),Object.defineProperty(u.people,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+".people (stub)"}}),o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
14
- posthog.init(${key}, ${JSON.stringify({ api_host: POSTHOG_API_HOST, defaults: POSTHOG_DEFAULTS })});
53
+ posthog.init(${key}, ${JSON.stringify({
54
+ api_host: POSTHOG_API_HOST,
55
+ ui_host: POSTHOG_UI_HOST,
56
+ defaults: POSTHOG_DEFAULTS,
57
+ person_profiles: POSTHOG_PERSON_PROFILES,
58
+ capture_exceptions: true,
59
+ })});
60
+ (() => {
61
+ const context = ${siteContext};
62
+ const pageTypes = ${serializeLiteral(POSTHOG_PAGE_TYPES)};
63
+ const metaPageType = document.querySelector('meta[name="hagilight:page-type"]')?.getAttribute('content');
64
+ const superProperties = {
65
+ site_id: context.siteId || window.location.hostname,
66
+ site_framework: context.framework,
67
+ hagilight_version: context.version,
68
+ locale: document.documentElement.lang,
69
+ page_type: [context.pageType, metaPageType].find((value) => pageTypes.includes(value)) ?? 'other',
70
+ };
71
+ posthog.register(Object.fromEntries(Object.entries(superProperties).filter(([, value]) => typeof value === 'string' && value !== '')));
72
+ })();
15
73
  window.__hagilightPosthogInitialized = true;
16
74
  })();`;
17
75
  }
@@ -0,0 +1,45 @@
1
+ import { type PostHogClient, type PostHogEventName, type PostHogInput } from './posthog-events.js';
2
+ export type PromotoEventName = Extract<PostHogEventName, 'promoto_impression' | 'promoto_dismissed' | 'promoto_paged'>;
3
+ export type PromotoPagingMethod = 'auto' | 'click';
4
+ /** A promotion is an impression only after it stays visible this long. */
5
+ export declare const PROMOTO_IMPRESSION_DELAY_MS = 1000;
6
+ export interface PromotoTimers {
7
+ now(): number;
8
+ setTimeout(callback: () => void, delayMs: number): unknown;
9
+ clearTimeout(handle: unknown): void;
10
+ }
11
+ export interface PromotoPresentation {
12
+ /** The CTA's `data-ga-label`. */
13
+ promoId: string;
14
+ /** The 1-based place in the carousel. */
15
+ position: number;
16
+ }
17
+ export interface PromotoAnalyticsOptions {
18
+ timers?: PromotoTimers;
19
+ /** Read when the impression fires, so `rotating` reflects the state at that moment. */
20
+ rotating?: () => boolean;
21
+ /** Where impressions go. Defaults to the guarded `window.posthog` capture. */
22
+ report?: (event: 'promoto_impression', input: PostHogInput<'promoto_impression'>) => void;
23
+ }
24
+ export interface PromotoAnalytics {
25
+ /** Call with the promotion on screen, or `undefined` when none is visible. Keeps a running timer running. */
26
+ show(presentation: PromotoPresentation | undefined): void;
27
+ /** Forgets the per-page memory. Call when the page key changes. */
28
+ resetPage(): void;
29
+ /** Cancels any pending impression and returns the dismissal properties for `promoId`. */
30
+ dismissed(promoId: string): {
31
+ visible_ms: number;
32
+ seen_count: number;
33
+ };
34
+ }
35
+ /**
36
+ * Sends a promotion event only when `window.posthog` has loaded and the visitor has not opted out.
37
+ * Nothing is queued and nothing throws: while the SDK is still a stub the event is dropped.
38
+ */
39
+ export declare function capturePromoto<E extends PromotoEventName>(event: E, input: PostHogInput<E>, posthog?: PostHogClient | undefined): void;
40
+ /**
41
+ * Impression state for one banner: a promotion reports once per page, after it has been visible for
42
+ * `PROMOTO_IMPRESSION_DELAY_MS` without interruption. Hiding it, rotating away or dismissing it cancels
43
+ * the pending report, and showing it again starts the wait from zero.
44
+ */
45
+ export declare function createPromotoAnalytics(options?: PromotoAnalyticsOptions): PromotoAnalytics;
@@ -0,0 +1,92 @@
1
+ import { capturePostHogEvent } from './posthog-events.js';
2
+ /** A promotion is an impression only after it stays visible this long. */
3
+ export const PROMOTO_IMPRESSION_DELAY_MS = 1000;
4
+ function windowPostHog() {
5
+ return globalThis.window?.posthog;
6
+ }
7
+ /**
8
+ * Sends a promotion event only when `window.posthog` has loaded and the visitor has not opted out.
9
+ * Nothing is queued and nothing throws: while the SDK is still a stub the event is dropped.
10
+ */
11
+ export function capturePromoto(event, input, posthog = windowPostHog()) {
12
+ try {
13
+ if (!posthog || posthog.__loaded !== true)
14
+ return;
15
+ if (typeof posthog.has_opted_out_capturing === 'function' && posthog.has_opted_out_capturing())
16
+ return;
17
+ capturePostHogEvent(event, input, posthog);
18
+ }
19
+ catch {
20
+ // Analytics must never interfere with the banner.
21
+ }
22
+ }
23
+ const defaultTimers = {
24
+ now: () => (typeof performance !== 'undefined' ? performance.now() : Date.now()),
25
+ setTimeout: (callback, delayMs) => globalThis.setTimeout(callback, delayMs),
26
+ clearTimeout: (handle) => globalThis.clearTimeout(handle),
27
+ };
28
+ /**
29
+ * Impression state for one banner: a promotion reports once per page, after it has been visible for
30
+ * `PROMOTO_IMPRESSION_DELAY_MS` without interruption. Hiding it, rotating away or dismissing it cancels
31
+ * the pending report, and showing it again starts the wait from zero.
32
+ */
33
+ export function createPromotoAnalytics(options = {}) {
34
+ const timers = options.timers ?? defaultTimers;
35
+ const rotating = options.rotating ?? (() => false);
36
+ const report = options.report ?? ((event, input) => capturePromoto(event, input));
37
+ const reported = new Set();
38
+ const firstVisibleAt = new Map();
39
+ let current;
40
+ let pending;
41
+ let pendingFor;
42
+ const cancel = () => {
43
+ if (pendingFor === undefined)
44
+ return;
45
+ timers.clearTimeout(pending);
46
+ pending = undefined;
47
+ pendingFor = undefined;
48
+ };
49
+ return {
50
+ show(presentation) {
51
+ if (!presentation) {
52
+ current = undefined;
53
+ cancel();
54
+ return;
55
+ }
56
+ const { promoId } = presentation;
57
+ if (!firstVisibleAt.has(promoId))
58
+ firstVisibleAt.set(promoId, timers.now());
59
+ current = presentation;
60
+ if (reported.has(promoId)) {
61
+ cancel();
62
+ return;
63
+ }
64
+ if (pendingFor === promoId)
65
+ return;
66
+ cancel();
67
+ pendingFor = promoId;
68
+ pending = timers.setTimeout(() => {
69
+ pending = undefined;
70
+ pendingFor = undefined;
71
+ if (!current || current.promoId !== promoId || reported.has(promoId))
72
+ return;
73
+ reported.add(promoId);
74
+ report('promoto_impression', { promo_id: promoId, position: current.position, rotating: rotating() });
75
+ }, PROMOTO_IMPRESSION_DELAY_MS);
76
+ },
77
+ resetPage() {
78
+ cancel();
79
+ current = undefined;
80
+ reported.clear();
81
+ firstVisibleAt.clear();
82
+ },
83
+ dismissed(promoId) {
84
+ cancel();
85
+ const since = firstVisibleAt.get(promoId);
86
+ return {
87
+ visible_ms: since === undefined ? 0 : Math.max(0, Math.round(timers.now() - since)),
88
+ seen_count: firstVisibleAt.size,
89
+ };
90
+ },
91
+ };
92
+ }
@@ -1,7 +1,14 @@
1
1
  import { gaEventAttributes } from './analytics-events.js';
2
2
  import { classifyLink, getLinkRel, withCampaignUtm } from './link-policy.js';
3
+ import { capturePromoto, createPromotoAnalytics, } from './promoto-analytics.js';
3
4
  import { loadActivePromotions, } from './promotions.js';
4
5
  const ELEMENT_NAME = 'hagilight-promoto-banner';
6
+ /*
7
+ * Dismissal is recorded once for the whole card set, not per promotion: `localStorage` holds the
8
+ * signature of every card (id, copy, link and image), with no expiry, scoped per origin. Changing any
9
+ * card shows the banner again. A failed write is not persisted, so the banner returns on the next load.
10
+ * Hiding at page top and while the footer is in view are not dismissals.
11
+ */
5
12
  const DISMISSED_SIGNATURE_KEY = 'hagilight:promoto-banner:dismissed-signature';
6
13
  const VISIT_COUNT_KEY_PREFIX = 'hagilight:promoto-banner:visit-count:';
7
14
  const VISIT_EVENT = 'hagilight:promoto-visit';
@@ -179,8 +186,12 @@ export function definePromotoBannerElement() {
179
186
  resizeObserver;
180
187
  footer = null;
181
188
  loadedLocale = null;
182
- onPrevious = () => this.move(-1);
183
- onNext = () => this.move(1);
189
+ impressions = createPromotoAnalytics({
190
+ rotating: () => this.hasAttribute('data-rotating'),
191
+ });
192
+ impressionPage = null;
193
+ onPrevious = () => this.move(-1, 'click');
194
+ onNext = () => this.move(1, 'click');
184
195
  onPause = () => {
185
196
  if (this.reducedMotion)
186
197
  return;
@@ -193,6 +204,7 @@ export function definePromotoBannerElement() {
193
204
  const signature = getPromotionSetSignature(this.cards);
194
205
  if (!signature || this.dismissing)
195
206
  return;
207
+ this.trackDismissal();
196
208
  this.dismissedSignature = signature;
197
209
  saveDismissedSignature(signature);
198
210
  this.stopRotation();
@@ -221,7 +233,7 @@ export function definePromotoBannerElement() {
221
233
  // The progress line's fill is the rotation clock, so hover, focus and pause hold the card with it.
222
234
  onProgressEnd = (event) => {
223
235
  if (event.target === event.currentTarget)
224
- this.move(1);
236
+ this.move(1, 'auto');
225
237
  };
226
238
  onLayoutChange = () => {
227
239
  const previousState = this.dataset.state;
@@ -238,6 +250,7 @@ export function definePromotoBannerElement() {
238
250
  this.syncRotation(true);
239
251
  this.startRefresh();
240
252
  }
253
+ this.syncImpressions();
241
254
  };
242
255
  onMotionChange = () => {
243
256
  this.reducedMotion = this.motionQuery?.matches ?? false;
@@ -246,6 +259,7 @@ export function definePromotoBannerElement() {
246
259
  };
247
260
  onPageLoad = () => {
248
261
  recordSiteVisit();
262
+ this.syncImpressions();
249
263
  // Re-fetch in the current page locale after a Starlight view-transition
250
264
  // navigation. The element may persist across a soft language switch, so
251
265
  // its previously loaded locale can differ from the new page's data-locale.
@@ -332,6 +346,7 @@ export function definePromotoBannerElement() {
332
346
  this.cards.forEach((card, index) => {
333
347
  const slide = document.createElement('article');
334
348
  slide.className = 'hagilight-promoto__slide';
349
+ slide.dataset.promotoId = card.id;
335
350
  slide.dataset.hasImage = String(Boolean(card.image));
336
351
  slide.setAttribute('aria-hidden', index === this.currentIndex ? 'false' : 'true');
337
352
  if (index !== this.currentIndex)
@@ -352,6 +367,8 @@ export function definePromotoBannerElement() {
352
367
  link.href = withCampaignUtm(card.link, {
353
368
  siteId: this.dataset.siteId,
354
369
  medium: 'promoto',
370
+ campaign: card.id,
371
+ content: 'promoto_banner',
355
372
  origin,
356
373
  });
357
374
  link.target = '_blank';
@@ -438,13 +455,53 @@ export function definePromotoBannerElement() {
438
455
  }
439
456
  this.updateSlides();
440
457
  }
441
- move(direction) {
458
+ move(direction, method) {
442
459
  if (this.cards.length < 2)
443
460
  return;
461
+ const from = this.currentIndex;
444
462
  this.currentIndex = getNextPromotionIndex(this.currentIndex, this.cards.length, direction);
445
463
  this.dataset.dir = direction < 0 ? 'prev' : 'next';
446
464
  this.updateSlides();
465
+ this.trackPaging(from, method);
447
466
  this.syncRotation(true);
467
+ this.syncImpressions();
468
+ }
469
+ /** Reports the carousel page change. Tracking failures are contained and never affect paging. */
470
+ trackPaging(from, method) {
471
+ // Reduced motion never rotates on its own, so an automatic change is not reported.
472
+ if (method === 'auto' && this.reducedMotion)
473
+ return;
474
+ capturePromoto('promoto_paged', { from: from + 1, to: this.currentIndex + 1, method });
475
+ }
476
+ /** Reports the dismissed promotion. Called before the existing dismissal steps, which are unchanged. */
477
+ trackDismissal() {
478
+ try {
479
+ const card = this.cards[this.currentIndex];
480
+ if (!card)
481
+ return;
482
+ capturePromoto('promoto_dismissed', { promo_id: card.id, ...this.impressions.dismissed(card.id) });
483
+ }
484
+ catch {
485
+ // Tracking must not stop the dismissal.
486
+ }
487
+ }
488
+ /** Tells the impression tracker which promotion is visible now. Failures are contained. */
489
+ syncImpressions() {
490
+ try {
491
+ const page = `${window.location.pathname}${window.location.search}`;
492
+ if (page !== this.impressionPage) {
493
+ this.impressionPage = page;
494
+ this.impressions.resetPage();
495
+ }
496
+ const card = this.cards[this.currentIndex];
497
+ const presentation = card && this.dataset.state === 'ready' && document.visibilityState !== 'hidden'
498
+ ? { promoId: card.id, position: this.currentIndex + 1 }
499
+ : undefined;
500
+ this.impressions.show(presentation);
501
+ }
502
+ catch {
503
+ // Tracking must not change what the banner shows.
504
+ }
448
505
  }
449
506
  updateVisibility() {
450
507
  const signature = getPromotionSetSignature(this.cards);
@@ -459,6 +516,7 @@ export function definePromotoBannerElement() {
459
516
  shell.inert = state !== 'ready';
460
517
  }
461
518
  this.dataset.state = state;
519
+ this.syncImpressions();
462
520
  }
463
521
  isFooterVisible() {
464
522
  if (!this.footer)