@hagicode/hagilight-core 0.18.0 → 0.19.1-dev.184.1.830a4c6

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,203 @@
1
+ /**
2
+ * Browser wiring for the consent popup. `mountConsentPopup` reveals the markup from `consent-markup.ts` only for an
3
+ * undecided visitor, connects Accept and Reject to `setConsent`, toggles the details, reflects the current choice when
4
+ * `openConsentPreferences()` is called, and publishes the popup's height as `--hagilight-consent-clearance` on the root.
5
+ * The details slide open and the panel fades out through the Web Animations API, and both snap under reduced motion.
6
+ * It never moves or traps focus.
7
+ */
8
+ import { CONSENT_PREFERENCES_EVENT, getConsent, isConsentRequired, openConsentPreferences, setConsent } from './consent.js';
9
+ export const CONSENT_CLEARANCE_PROPERTY = '--hagilight-consent-clearance';
10
+ /** Space between the popup and the banner or footer it lifts. */
11
+ const CLEARANCE_GAP_PX = 12;
12
+ const noop = () => { };
13
+ /** Durations in ms. The details open slower than they close, and the panel leaves faster than it arrives. */
14
+ const DETAILS_OPEN_MS = 340;
15
+ const DETAILS_CLOSE_MS = 220;
16
+ const PANEL_LEAVE_MS = 200;
17
+ const EASE_OUT = 'cubic-bezier(0.22, 1, 0.36, 1)';
18
+ const EASE_IN = 'cubic-bezier(0.64, 0, 0.78, 0)';
19
+ /** Motion is skipped under reduced motion, and wherever the Web Animations API is missing. */
20
+ function canAnimate(element) {
21
+ try {
22
+ if (typeof element.animate !== 'function')
23
+ return false;
24
+ return !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ }
30
+ function publishClearance(panel) {
31
+ try {
32
+ const root = document.documentElement;
33
+ // A panel that is leaving no longer holds space: the banner and footer settle back while it fades.
34
+ if (panel.hidden || panel.dataset.leaving === 'true') {
35
+ root.style.setProperty(CONSENT_CLEARANCE_PROPERTY, '0px');
36
+ return;
37
+ }
38
+ const height = Math.ceil(panel.getBoundingClientRect().height);
39
+ root.style.setProperty(CONSENT_CLEARANCE_PROPERTY, `${height + CLEARANCE_GAP_PX}px`);
40
+ }
41
+ catch {
42
+ // No layout (for example during static rendering): leave the property unchanged.
43
+ }
44
+ }
45
+ /** Shows the current choice in the panel, using the copy carried on the choice line. */
46
+ function reflectChoice(panel) {
47
+ const decision = getConsent().analytics;
48
+ panel.dataset.state = decision;
49
+ const choice = panel.querySelector('[data-consent-choice]');
50
+ const value = panel.querySelector('[data-consent-choice-value]');
51
+ if (!choice || !value)
52
+ return;
53
+ const text = decision === 'granted'
54
+ ? choice.dataset.choiceGranted
55
+ : decision === 'denied'
56
+ ? choice.dataset.choiceDenied
57
+ : choice.dataset.choiceUndecided;
58
+ value.textContent = text ?? decision;
59
+ }
60
+ /**
61
+ * Mounts the popup inside `root` (the `[data-hagilight-consent]` section). Returns a function that removes the listeners.
62
+ * With no panel, or where the visitor already decided or consent is not required, the panel stays hidden.
63
+ */
64
+ export function mountConsentPopup(root = document) {
65
+ const panel = root.querySelector('[data-hagilight-consent]');
66
+ if (!panel)
67
+ return noop;
68
+ // A page can mount the same panel from both its component and an integration; the second mount does nothing.
69
+ if (panel.dataset.consentMounted === 'true')
70
+ return noop;
71
+ panel.dataset.consentMounted = 'true';
72
+ // Move the popup to the end of the body. Site layouts can isolate their content (Starlight's main pane does), which
73
+ // would trap a z-index of 45 inside that pane, under fixed side panels. In the root stacking context it stays on top.
74
+ const host = panel.closest('.hagilight-consent-host') ?? panel;
75
+ if (host.parentElement !== document.body)
76
+ document.body.appendChild(host);
77
+ const accept = panel.querySelector('[data-consent-accept]');
78
+ const reject = panel.querySelector('[data-consent-reject]');
79
+ const toggle = panel.querySelector('[data-consent-toggle]');
80
+ const details = panel.querySelector('[data-consent-details]');
81
+ let leaving;
82
+ let sliding;
83
+ const hide = () => {
84
+ // The clearance drops at once, so the banner and footer start moving back while the panel is still leaving.
85
+ const wasVisible = !panel.hidden;
86
+ leaving?.cancel();
87
+ leaving = undefined;
88
+ if (!wasVisible || !canAnimate(panel)) {
89
+ panel.hidden = true;
90
+ publishClearance(panel);
91
+ return;
92
+ }
93
+ panel.dataset.leaving = 'true';
94
+ const leave = panel.animate([{ opacity: 1, transform: 'none' }, { opacity: 0, transform: 'translateY(0.75rem) scale(0.98)' }], { duration: PANEL_LEAVE_MS, easing: EASE_IN, fill: 'forwards' });
95
+ leaving = leave;
96
+ publishClearance(panel);
97
+ const finish = () => {
98
+ if (leaving !== leave)
99
+ return;
100
+ leaving = undefined;
101
+ delete panel.dataset.leaving;
102
+ panel.hidden = true;
103
+ leave.cancel();
104
+ publishClearance(panel);
105
+ };
106
+ leave.addEventListener('finish', finish);
107
+ leave.addEventListener('cancel', () => {
108
+ if (leaving === leave)
109
+ leaving = undefined;
110
+ });
111
+ };
112
+ const show = () => {
113
+ if (leaving) {
114
+ leaving.cancel();
115
+ leaving = undefined;
116
+ }
117
+ delete panel.dataset.leaving;
118
+ reflectChoice(panel);
119
+ panel.hidden = false;
120
+ publishClearance(panel);
121
+ };
122
+ const choose = (analytics) => {
123
+ setConsent({ analytics });
124
+ hide();
125
+ };
126
+ const onAccept = () => choose(true);
127
+ const onReject = () => choose(false);
128
+ const onToggle = () => {
129
+ if (!toggle || !details)
130
+ return;
131
+ const expanded = toggle.getAttribute('aria-expanded') !== 'true';
132
+ toggle.setAttribute('aria-expanded', String(expanded));
133
+ slideDetails(details, expanded);
134
+ };
135
+ /** Opens or closes the details with a height slide; the final state is always the plain `hidden` attribute. */
136
+ const slideDetails = (section, open) => {
137
+ const current = sliding;
138
+ // Start from wherever an interrupted slide stopped, so a quick second click reverses instead of jumping.
139
+ const startHeight = current ? section.getBoundingClientRect().height : open ? 0 : section.getBoundingClientRect().height;
140
+ current?.cancel();
141
+ sliding = undefined;
142
+ if (!canAnimate(section)) {
143
+ section.hidden = !open;
144
+ publishClearance(panel);
145
+ return;
146
+ }
147
+ section.hidden = false;
148
+ const endHeight = open ? section.scrollHeight : 0;
149
+ section.style.overflow = 'hidden';
150
+ const slide = section.animate([
151
+ { height: `${startHeight}px`, opacity: open ? 0 : 1 },
152
+ { height: `${endHeight}px`, opacity: open ? 1 : 0 },
153
+ ], { duration: open ? DETAILS_OPEN_MS : DETAILS_CLOSE_MS, easing: open ? EASE_OUT : EASE_IN });
154
+ sliding = slide;
155
+ slide.addEventListener('finish', () => {
156
+ if (sliding !== slide)
157
+ return;
158
+ sliding = undefined;
159
+ section.style.overflow = '';
160
+ section.hidden = !open;
161
+ publishClearance(panel);
162
+ });
163
+ slide.addEventListener('cancel', () => {
164
+ if (sliding === slide)
165
+ sliding = undefined;
166
+ section.style.overflow = '';
167
+ });
168
+ };
169
+ const onPreferences = () => show();
170
+ /** The footer's "Cookie settings" entries call `openConsentPreferences()`; the popup's own listener then shows the panel. */
171
+ const onFooterEntry = (event) => {
172
+ const target = event.target;
173
+ if (target instanceof Element && target.closest('[data-consent-preferences]'))
174
+ openConsentPreferences();
175
+ };
176
+ accept?.addEventListener('click', onAccept);
177
+ reject?.addEventListener('click', onReject);
178
+ toggle?.addEventListener('click', onToggle);
179
+ document.addEventListener(CONSENT_PREFERENCES_EVENT, onPreferences);
180
+ document.addEventListener('click', onFooterEntry);
181
+ let observer;
182
+ try {
183
+ observer = typeof ResizeObserver === 'function' ? new ResizeObserver(() => publishClearance(panel)) : undefined;
184
+ observer?.observe(panel);
185
+ }
186
+ catch {
187
+ observer = undefined;
188
+ }
189
+ if (getConsent().analytics === 'undecided' && isConsentRequired())
190
+ show();
191
+ else
192
+ hide();
193
+ return () => {
194
+ leaving?.cancel();
195
+ sliding?.cancel();
196
+ accept?.removeEventListener('click', onAccept);
197
+ reject?.removeEventListener('click', onReject);
198
+ toggle?.removeEventListener('click', onToggle);
199
+ document.removeEventListener(CONSENT_PREFERENCES_EVENT, onPreferences);
200
+ document.removeEventListener('click', onFooterEntry);
201
+ observer?.disconnect();
202
+ };
203
+ }
@@ -0,0 +1,65 @@
1
+ export declare const CONSENT_STORAGE_KEY = "hagicode:consent";
2
+ export declare const CONSENT_COOKIE = "hagicode_consent";
3
+ export declare const CONSENT_SHARED_DOMAIN = "hagicode.com";
4
+ export declare const CONSENT_MAX_AGE_SECONDS: number;
5
+ /** Dispatched on `document` after every effective analytics change, with the new state as `detail`. */
6
+ export declare const CONSENT_CHANGE_EVENT = "hagilight:consent-change";
7
+ /** Dispatched on `document` by `openConsentPreferences()`; the popup listens for it. */
8
+ export declare const CONSENT_PREFERENCES_EVENT = "hagilight:consent-preferences";
9
+ /** The id of the JSON config descriptor that the popup emits. Its `policyVersion` is read lazily. */
10
+ export declare const CONSENT_CONFIG_ID = "hagilight-consent-config";
11
+ export declare const DEFAULT_POLICY_VERSION = "1";
12
+ export type AnalyticsDecision = 'granted' | 'denied';
13
+ export type AnalyticsConsent = AnalyticsDecision | 'undecided';
14
+ export interface ConsentState {
15
+ /** Strictly necessary storage is always granted. */
16
+ necessary: 'granted';
17
+ analytics: AnalyticsConsent;
18
+ }
19
+ export interface ConsentRecord {
20
+ state: AnalyticsDecision;
21
+ /** Epoch seconds. */
22
+ time: number;
23
+ policyVersion: string;
24
+ }
25
+ export interface ConsentChoice {
26
+ analytics: boolean;
27
+ }
28
+ export type ConsentListener = (state: ConsentState) => void;
29
+ export interface ConsentOptions {
30
+ /**
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.
33
+ */
34
+ regionHook?: () => unknown;
35
+ }
36
+ /** Strict parse: exact field count, a known version and state, a plain epoch time and a bounded policy version. */
37
+ export declare function parseConsentRecord(value: unknown): ConsentRecord | null;
38
+ /** Formats `1|state|time|policyVersion`, or returns null when the result would not parse back. */
39
+ export declare function formatConsentRecord(record: ConsentRecord): string | null;
40
+ /**
41
+ * The decision a record gives at `now` (epoch seconds) under the site's policy version. A record is no decision when
42
+ * it is older than 180 days, dated further ahead than the clock-skew allowance, or written under another policy version.
43
+ */
44
+ export declare function decisionFromRecord(record: ConsentRecord | null, now: number, policyVersion: string): AnalyticsConsent;
45
+ /** Reads the value of one cookie from a `document.cookie` string, or null when it is absent. */
46
+ export declare function readCookieValue(cookies: string, name: string): string | null;
47
+ /** The site's policy version from its JSON config descriptor, read lazily. Anything unusable falls back to `1`. */
48
+ 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. */
52
+ export declare function isConsentRequired(): boolean;
53
+ /** The current consent state. `analytics` is `undecided` when there is no valid record for the site's policy version. */
54
+ export declare function getConsent(): ConsentState;
55
+ /**
56
+ * Stores the analytics choice and notifies subscribers and the DOM event when the decision changes. Invalid arguments
57
+ * are ignored, and the stored decision is left as it was.
58
+ */
59
+ export declare function setConsent(choice: ConsentChoice): void;
60
+ /**
61
+ * Subscribes to analytics changes. Returns an unsubscribe function. A subscriber that throws does not affect the others.
62
+ */
63
+ 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;
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Analytics consent state, browser-safe (`@hagicode/hagilight-core/consent`). One compact record holds the visitor's
3
+ * analytics choice. It is written to cookie `hagicode_consent` on hagicode.com hosts only, and always to localStorage
4
+ * `hagicode:consent`. A choice that cannot be stored lives in memory for the page session. Every exported function
5
+ * is non-throwing: a call that cannot act returns its safe default.
6
+ */
7
+ import { isSharedHost } from './root-transit-marker.js';
8
+ export const CONSENT_STORAGE_KEY = 'hagicode:consent';
9
+ export const CONSENT_COOKIE = 'hagicode_consent';
10
+ export const CONSENT_SHARED_DOMAIN = 'hagicode.com';
11
+ export const CONSENT_MAX_AGE_SECONDS = 180 * 24 * 60 * 60;
12
+ /** Dispatched on `document` after every effective analytics change, with the new state as `detail`. */
13
+ export const CONSENT_CHANGE_EVENT = 'hagilight:consent-change';
14
+ /** Dispatched on `document` by `openConsentPreferences()`; the popup listens for it. */
15
+ export const CONSENT_PREFERENCES_EVENT = 'hagilight:consent-preferences';
16
+ /** The id of the JSON config descriptor that the popup emits. Its `policyVersion` is read lazily. */
17
+ export const CONSENT_CONFIG_ID = 'hagilight-consent-config';
18
+ export const DEFAULT_POLICY_VERSION = '1';
19
+ const RECORD_VERSION = '1';
20
+ /** A normal record is about 25 characters; the cap keeps the cookie and the stored value small. */
21
+ const MAX_RECORD_LENGTH = 64;
22
+ /** A timestamp further ahead of the clock than this is invalid, rather than valid for longer than intended. */
23
+ const CLOCK_SKEW_SECONDS = 300;
24
+ const STATES = ['granted', 'denied'];
25
+ const TIME = /^\d{1,11}$/u;
26
+ const POLICY = /^[A-Za-z0-9._-]{1,32}$/u;
27
+ /** Strict parse: exact field count, a known version and state, a plain epoch time and a bounded policy version. */
28
+ export function parseConsentRecord(value) {
29
+ if (typeof value !== 'string' || value.length === 0 || value.length > MAX_RECORD_LENGTH)
30
+ return null;
31
+ const parts = value.split('|');
32
+ if (parts.length !== 4)
33
+ return null;
34
+ const [version, state, time, policyVersion] = parts;
35
+ if (version !== RECORD_VERSION)
36
+ return null;
37
+ if (!STATES.includes(state))
38
+ return null;
39
+ if (!TIME.test(time) || !POLICY.test(policyVersion))
40
+ return null;
41
+ return { state: state, time: Number(time), policyVersion };
42
+ }
43
+ /** Formats `1|state|time|policyVersion`, or returns null when the result would not parse back. */
44
+ export function formatConsentRecord(record) {
45
+ if (typeof record !== 'object' || record === null)
46
+ return null;
47
+ const text = [RECORD_VERSION, record.state, String(record.time), record.policyVersion].join('|');
48
+ return parseConsentRecord(text) ? text : null;
49
+ }
50
+ /**
51
+ * The decision a record gives at `now` (epoch seconds) under the site's policy version. A record is no decision when
52
+ * it is older than 180 days, dated further ahead than the clock-skew allowance, or written under another policy version.
53
+ */
54
+ export function decisionFromRecord(record, now, policyVersion) {
55
+ if (!record || record.policyVersion !== policyVersion)
56
+ return 'undecided';
57
+ const age = now - record.time;
58
+ if (age > CONSENT_MAX_AGE_SECONDS)
59
+ return 'undecided';
60
+ if (-age > CLOCK_SKEW_SECONDS)
61
+ return 'undecided';
62
+ return record.state;
63
+ }
64
+ /** Reads the value of one cookie from a `document.cookie` string, or null when it is absent. */
65
+ export function readCookieValue(cookies, name) {
66
+ for (const pair of cookies.split(';')) {
67
+ const index = pair.indexOf('=');
68
+ if (index < 0)
69
+ continue;
70
+ if (pair.slice(0, index).trim() === name)
71
+ return pair.slice(index + 1).trim();
72
+ }
73
+ return null;
74
+ }
75
+ function environment() {
76
+ try {
77
+ return {
78
+ window: typeof window === 'undefined' ? undefined : window,
79
+ document: typeof document === 'undefined' ? undefined : document,
80
+ };
81
+ }
82
+ catch {
83
+ return { window: undefined, document: undefined };
84
+ }
85
+ }
86
+ function nowSeconds() {
87
+ return Math.floor(Date.now() / 1000);
88
+ }
89
+ /** The site's policy version from its JSON config descriptor, read lazily. Anything unusable falls back to `1`. */
90
+ export function currentPolicyVersion() {
91
+ try {
92
+ const { document: doc } = environment();
93
+ const element = doc?.getElementById(CONSENT_CONFIG_ID);
94
+ if (!element?.textContent)
95
+ return DEFAULT_POLICY_VERSION;
96
+ const value = JSON.parse(element.textContent)?.policyVersion;
97
+ return typeof value === 'string' && POLICY.test(value) ? value : DEFAULT_POLICY_VERSION;
98
+ }
99
+ catch {
100
+ return DEFAULT_POLICY_VERSION;
101
+ }
102
+ }
103
+ function sharedHostname() {
104
+ try {
105
+ const hostname = environment().window?.location?.hostname;
106
+ return hostname && isSharedHost(hostname, CONSENT_SHARED_DOMAIN) ? hostname : undefined;
107
+ }
108
+ catch {
109
+ return undefined;
110
+ }
111
+ }
112
+ function localStorageOrNull() {
113
+ try {
114
+ return environment().window?.localStorage ?? null;
115
+ }
116
+ catch {
117
+ return null;
118
+ }
119
+ }
120
+ function readStoredRecord() {
121
+ try {
122
+ const storage = localStorageOrNull();
123
+ return storage ? parseConsentRecord(storage.getItem(CONSENT_STORAGE_KEY)) : null;
124
+ }
125
+ catch {
126
+ return null;
127
+ }
128
+ }
129
+ function readSharedCookieRecord() {
130
+ try {
131
+ if (!sharedHostname())
132
+ return null;
133
+ const cookies = environment().document?.cookie ?? '';
134
+ return parseConsentRecord(readCookieValue(cookies, CONSENT_COOKIE));
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ }
140
+ /** The choice made in this page session, kept when storage is unavailable. It is never reported as persisted. */
141
+ let sessionRecord = null;
142
+ /**
143
+ * The newest valid record among the shared cookie, localStorage and the session copy. A tie goes to the stored copy,
144
+ * so another tab's choice written in the same second wins over this page's own memory.
145
+ */
146
+ function currentRecord(now, policyVersion) {
147
+ const candidates = [readSharedCookieRecord(), readStoredRecord(), sessionRecord];
148
+ let best = null;
149
+ for (const candidate of candidates) {
150
+ if (decisionFromRecord(candidate, now, policyVersion) === 'undecided')
151
+ continue;
152
+ if (!best || candidate.time > best.time)
153
+ best = candidate;
154
+ }
155
+ return best;
156
+ }
157
+ function currentDecision() {
158
+ const record = currentRecord(nowSeconds(), currentPolicyVersion());
159
+ return record ? record.state : 'undecided';
160
+ }
161
+ function writeStored(text) {
162
+ try {
163
+ localStorageOrNull()?.setItem(CONSENT_STORAGE_KEY, text);
164
+ }
165
+ catch {
166
+ // Blocked or full storage: the session copy still holds the choice for this page.
167
+ }
168
+ }
169
+ function writeSharedCookie(text) {
170
+ try {
171
+ const hostname = sharedHostname();
172
+ const doc = environment().document;
173
+ if (!hostname || !doc)
174
+ return;
175
+ doc.cookie = `${CONSENT_COOKIE}=${text}; Domain=.${CONSENT_SHARED_DOMAIN}; Path=/; SameSite=Lax; Secure; Max-Age=${CONSENT_MAX_AGE_SECONDS}`;
176
+ }
177
+ catch {
178
+ // Cookies blocked: localStorage and the session copy still hold the choice.
179
+ }
180
+ }
181
+ const listeners = new Set();
182
+ /** The analytics decision last announced to listeners, or undefined until the first observation. */
183
+ let announced;
184
+ let storageListenerInstalled = false;
185
+ function baseline() {
186
+ if (announced === undefined)
187
+ announced = currentDecision();
188
+ return announced;
189
+ }
190
+ function deliver(state) {
191
+ for (const listener of [...listeners]) {
192
+ try {
193
+ listener(state);
194
+ }
195
+ catch {
196
+ // One failing subscriber must not stop the others or the DOM event.
197
+ }
198
+ }
199
+ try {
200
+ const { document: doc } = environment();
201
+ doc?.dispatchEvent(new CustomEvent(CONSENT_CHANGE_EVENT, { detail: state }));
202
+ }
203
+ catch {
204
+ // No DOM event support: subscribers were still notified.
205
+ }
206
+ }
207
+ /** Notifies once for each effective change of the analytics decision. Unchanged decisions are silent. */
208
+ function announceChange() {
209
+ const previous = baseline();
210
+ const next = currentDecision();
211
+ announced = next;
212
+ if (next === previous)
213
+ return;
214
+ deliver({ necessary: 'granted', analytics: next });
215
+ }
216
+ function ensureStorageListener() {
217
+ if (storageListenerInstalled)
218
+ return;
219
+ try {
220
+ const win = environment().window;
221
+ if (!win)
222
+ return;
223
+ win.addEventListener('storage', (event) => {
224
+ if (event.key === null || event.key === CONSENT_STORAGE_KEY)
225
+ announceChange();
226
+ });
227
+ storageListenerInstalled = true;
228
+ }
229
+ catch {
230
+ // Without the storage event, other tabs' choices are seen on the next read.
231
+ }
232
+ }
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) {
236
+ try {
237
+ regionHook = typeof options?.regionHook === 'function' ? options.regionHook : undefined;
238
+ }
239
+ catch {
240
+ regionHook = undefined;
241
+ }
242
+ }
243
+ /** Whether this visitor needs a decision. Without a hook, or when the hook throws or does not answer `false`, it does. */
244
+ export function isConsentRequired() {
245
+ try {
246
+ return regionHook ? regionHook() !== false : true;
247
+ }
248
+ catch {
249
+ return true;
250
+ }
251
+ }
252
+ /** The current consent state. `analytics` is `undecided` when there is no valid record for the site's policy version. */
253
+ export function getConsent() {
254
+ try {
255
+ return { necessary: 'granted', analytics: currentDecision() };
256
+ }
257
+ catch {
258
+ return { necessary: 'granted', analytics: 'undecided' };
259
+ }
260
+ }
261
+ /**
262
+ * Stores the analytics choice and notifies subscribers and the DOM event when the decision changes. Invalid arguments
263
+ * are ignored, and the stored decision is left as it was.
264
+ */
265
+ export function setConsent(choice) {
266
+ try {
267
+ if (typeof choice !== 'object' || choice === null || typeof choice.analytics !== 'boolean')
268
+ return;
269
+ ensureStorageListener();
270
+ baseline();
271
+ const record = {
272
+ state: choice.analytics ? 'granted' : 'denied',
273
+ time: nowSeconds(),
274
+ policyVersion: currentPolicyVersion(),
275
+ };
276
+ sessionRecord = record;
277
+ const text = formatConsentRecord(record);
278
+ if (text) {
279
+ writeSharedCookie(text);
280
+ writeStored(text);
281
+ }
282
+ announceChange();
283
+ }
284
+ catch {
285
+ // Never throw into the page.
286
+ }
287
+ }
288
+ /**
289
+ * Subscribes to analytics changes. Returns an unsubscribe function. A subscriber that throws does not affect the others.
290
+ */
291
+ export function onConsentChange(callback) {
292
+ try {
293
+ if (typeof callback !== 'function')
294
+ return () => { };
295
+ ensureStorageListener();
296
+ baseline();
297
+ listeners.add(callback);
298
+ return () => {
299
+ listeners.delete(callback);
300
+ };
301
+ }
302
+ catch {
303
+ return () => { };
304
+ }
305
+ }
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() {
308
+ try {
309
+ environment().document?.dispatchEvent(new CustomEvent(CONSENT_PREFERENCES_EVENT));
310
+ }
311
+ catch {
312
+ // Nothing to open.
313
+ }
314
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The one citable sentence that defines HagiCode. Every surface that summarizes the product
3
+ * (homepage, desktop page, comparison pages, llms.txt summary, SoftwareApplication description)
4
+ * reads it from here, so the wording cannot drift between them.
5
+ *
6
+ * Each sentence states only facts that the product copy already documents: a proposal-first
7
+ * workflow, execution through agent CLIs (Claude Code, Codex, GitHub Copilot), and team knowledge.
8
+ */
9
+ export declare const ENTITY_DEFINITIONS: {
10
+ readonly 'en-US': "HagiCode is a proposal-driven AI coding workbench that turns a request into a reviewable proposal, runs it through agent CLIs such as Claude Code, Codex and GitHub Copilot, and keeps the outcome as team knowledge.";
11
+ readonly 'zh-CN': "HagiCode 是一款提案驱动的 AI 编码工作台,可将需求转化为可审阅的提案,通过 Claude Code、Codex、GitHub Copilot 等 Agent CLI 执行,并把结果沉淀为团队知识。";
12
+ };
13
+ export type EntityDefinitionLocale = keyof typeof ENTITY_DEFINITIONS;
14
+ export declare const DEFAULT_ENTITY_DEFINITION_LOCALE: EntityDefinitionLocale;
15
+ /**
16
+ * Return the entity definition for a locale. A locale without its own sentence, including an
17
+ * unknown or missing one, receives the `en-US` sentence.
18
+ */
19
+ export declare function getEntityDefinition(locale?: string): string;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The one citable sentence that defines HagiCode. Every surface that summarizes the product
3
+ * (homepage, desktop page, comparison pages, llms.txt summary, SoftwareApplication description)
4
+ * reads it from here, so the wording cannot drift between them.
5
+ *
6
+ * Each sentence states only facts that the product copy already documents: a proposal-first
7
+ * workflow, execution through agent CLIs (Claude Code, Codex, GitHub Copilot), and team knowledge.
8
+ */
9
+ export const ENTITY_DEFINITIONS = {
10
+ 'en-US': 'HagiCode is a proposal-driven AI coding workbench that turns a request into a reviewable proposal, runs it through agent CLIs such as Claude Code, Codex and GitHub Copilot, and keeps the outcome as team knowledge.',
11
+ 'zh-CN': 'HagiCode 是一款提案驱动的 AI 编码工作台,可将需求转化为可审阅的提案,通过 Claude Code、Codex、GitHub Copilot 等 Agent CLI 执行,并把结果沉淀为团队知识。',
12
+ };
13
+ export const DEFAULT_ENTITY_DEFINITION_LOCALE = 'en-US';
14
+ /**
15
+ * Return the entity definition for a locale. A locale without its own sentence, including an
16
+ * unknown or missing one, receives the `en-US` sentence.
17
+ */
18
+ export function getEntityDefinition(locale) {
19
+ if (typeof locale === 'string' && Object.prototype.hasOwnProperty.call(ENTITY_DEFINITIONS, locale)) {
20
+ return ENTITY_DEFINITIONS[locale];
21
+ }
22
+ return ENTITY_DEFINITIONS[DEFAULT_ENTITY_DEFINITION_LOCALE];
23
+ }
@@ -6,7 +6,7 @@
6
6
  */
7
7
  export type LinkClass = 'same-origin' | 'first-party' | 'third-party';
8
8
  export type LinkRel = 'noopener' | 'noopener noreferrer';
9
- export type CampaignMedium = 'footer' | 'promoto';
9
+ export type CampaignMedium = 'article' | 'footer' | 'promoto';
10
10
  export interface ClassifyLinkOptions {
11
11
  /** The hosting site's origin, e.g. `https://docs.hagicode.com`, when known. */
12
12
  origin?: string;
@@ -15,6 +15,10 @@ export interface CampaignTagOptions extends ClassifyLinkOptions {
15
15
  /** The hosting site's identifier. Without it, no tag is added. */
16
16
  siteId?: string | null;
17
17
  medium: CampaignMedium;
18
+ /** The promotion id or stable link id, sent as `utm_campaign`. Omitted leaves the key unset. */
19
+ campaign?: string | null;
20
+ /** Where the link sits, sent as `utm_content`, for example `footer` or `promoto_banner`. */
21
+ content?: string | null;
18
22
  }
19
23
  /**
20
24
  * Classifies a destination from its parsed URL. Relative destinations are
@@ -25,7 +29,8 @@ export declare function classifyLink(href: string, options?: ClassifyLinkOptions
25
29
  /** The relation attribute for a new-tab link of the given class. */
26
30
  export declare function getLinkRel(linkClass: LinkClass): LinkRel;
27
31
  /**
28
- * Adds `utm_source=<siteId>` and `utm_medium=<medium>` to first-party
32
+ * Adds `utm_source=<siteId>`, `utm_medium=<medium>`, and, when given,
33
+ * `utm_campaign=<campaign>` and `utm_content=<content>` to first-party
29
34
  * `hagicode.com` destinations. Existing `utm_*` keys win, other parameters and
30
35
  * the fragment are preserved, and every other class of destination is returned
31
36
  * unchanged.
@@ -56,7 +56,8 @@ export function getLinkRel(linkClass) {
56
56
  return linkClass === 'third-party' ? 'noopener noreferrer' : 'noopener';
57
57
  }
58
58
  /**
59
- * Adds `utm_source=<siteId>` and `utm_medium=<medium>` to first-party
59
+ * Adds `utm_source=<siteId>`, `utm_medium=<medium>`, and, when given,
60
+ * `utm_campaign=<campaign>` and `utm_content=<content>` to first-party
60
61
  * `hagicode.com` destinations. Existing `utm_*` keys win, other parameters and
61
62
  * the fragment are preserved, and every other class of destination is returned
62
63
  * unchanged.
@@ -85,6 +86,12 @@ export function withCampaignUtm(href, options) {
85
86
  additions.push(`utm_source=${encodeURIComponent(siteId)}`);
86
87
  if (!existingKeys.has('utm_medium'))
87
88
  additions.push(`utm_medium=${options.medium}`);
89
+ const campaign = options.campaign?.trim();
90
+ if (campaign && !existingKeys.has('utm_campaign'))
91
+ additions.push(`utm_campaign=${encodeURIComponent(campaign)}`);
92
+ const content = options.content?.trim();
93
+ if (content && !existingKeys.has('utm_content'))
94
+ additions.push(`utm_content=${encodeURIComponent(content)}`);
88
95
  if (additions.length === 0)
89
96
  return href;
90
97
  const current = url.search.replace(/^\?/u, '');