solid-intlayer 9.9.3 → 9.9.4

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 (125) hide show
  1. package/dist/cjs/IntlayerNode.cjs +11 -1
  2. package/dist/cjs/LoadingBoundary.cjs +26 -1
  3. package/dist/cjs/analytics/AnalyticsProvider.cjs +12 -1
  4. package/dist/cjs/analytics/exposureSink.cjs +23 -1
  5. package/dist/cjs/analytics/index.cjs +9 -1
  6. package/dist/cjs/analytics/useAnalytics.cjs +59 -1
  7. package/dist/cjs/analytics/useConversion.cjs +25 -1
  8. package/dist/cjs/analytics/useExperiment.cjs +59 -1
  9. package/dist/cjs/client/IntlayerProvider.cjs +91 -1
  10. package/dist/cjs/client/contentProxy.cjs +32 -1
  11. package/dist/cjs/client/getBrowserLocale.cjs +115 -1
  12. package/dist/cjs/client/index.cjs +35 -1
  13. package/dist/cjs/client/t.cjs +16 -1
  14. package/dist/cjs/client/useContent.cjs +16 -1
  15. package/dist/cjs/client/useDictionary.cjs +51 -1
  16. package/dist/cjs/client/useDictionaryAsync.cjs +19 -1
  17. package/dist/cjs/client/useDictionaryDynamic.cjs +82 -1
  18. package/dist/cjs/client/useIntlayer.cjs +50 -1
  19. package/dist/cjs/client/useLoadDynamic.cjs +140 -1
  20. package/dist/cjs/client/useLocale.cjs +52 -1
  21. package/dist/cjs/client/useLocaleBase.cjs +19 -1
  22. package/dist/cjs/client/useLocaleStorage.cjs +59 -1
  23. package/dist/cjs/client/usePathname.cjs +41 -1
  24. package/dist/cjs/client/useRewriteURL.cjs +21 -1
  25. package/dist/cjs/client/useTraduction.cjs +32 -1
  26. package/dist/cjs/editor/ContentSelector.cjs +20 -1
  27. package/dist/cjs/editor/EditorProvider.cjs +8 -1
  28. package/dist/cjs/editor/createEditedContentSource.cjs +32 -1
  29. package/dist/cjs/editor/useEditor.cjs +38 -1
  30. package/dist/cjs/format/index.cjs +19 -1
  31. package/dist/cjs/format/useCompact.cjs +15 -1
  32. package/dist/cjs/format/useCurrency.cjs +16 -1
  33. package/dist/cjs/format/useDate.cjs +25 -1
  34. package/dist/cjs/format/useIntl.cjs +31 -1
  35. package/dist/cjs/format/useList.cjs +15 -1
  36. package/dist/cjs/format/useNumber.cjs +19 -1
  37. package/dist/cjs/format/usePercentage.cjs +16 -1
  38. package/dist/cjs/format/useRelativeTime.cjs +16 -1
  39. package/dist/cjs/format/useUnit.cjs +15 -1
  40. package/dist/cjs/getDictionary.cjs +17 -1
  41. package/dist/cjs/getIntlayer.cjs +14 -1
  42. package/dist/cjs/html/HTMLProvider.cjs +24 -1
  43. package/dist/cjs/html/HTMLRenderer.cjs +49 -1
  44. package/dist/cjs/html/index.cjs +8 -1
  45. package/dist/cjs/html/types.cjs +1 -1
  46. package/dist/cjs/index.cjs +48 -1
  47. package/dist/cjs/markdown/MarkdownProvider.cjs +47 -1
  48. package/dist/cjs/markdown/MarkdownRenderer.cjs +56 -1
  49. package/dist/cjs/markdown/compiler.cjs +64 -1
  50. package/dist/cjs/markdown/index.cjs +13 -1
  51. package/dist/cjs/markdown/runtime.cjs +48 -1
  52. package/dist/cjs/plugins.cjs +266 -1
  53. package/dist/cjs/proxyKeys.cjs +14 -1
  54. package/dist/cjs/server/index.cjs +3 -1
  55. package/dist/cjs/server/useDictionary.cjs +30 -1
  56. package/dist/cjs/solidCompat.cjs +167 -1
  57. package/dist/cjs/solidElement/renderSolidElement.cjs +34 -1
  58. package/dist/cjs/solidTypes.cjs +1 -1
  59. package/dist/esm/IntlayerNode.mjs +8 -6
  60. package/dist/esm/LoadingBoundary.mjs +19 -6
  61. package/dist/esm/analytics/AnalyticsProvider.mjs +10 -3
  62. package/dist/esm/analytics/exposureSink.mjs +19 -5
  63. package/dist/esm/analytics/index.mjs +5 -5
  64. package/dist/esm/analytics/useAnalytics.mjs +52 -25
  65. package/dist/esm/analytics/useConversion.mjs +22 -6
  66. package/dist/esm/analytics/useExperiment.mjs +50 -22
  67. package/dist/esm/client/IntlayerProvider.mjs +75 -28
  68. package/dist/esm/client/contentProxy.mjs +26 -12
  69. package/dist/esm/client/getBrowserLocale.mjs +106 -71
  70. package/dist/esm/client/index.mjs +14 -14
  71. package/dist/esm/client/t.mjs +13 -7
  72. package/dist/esm/client/useContent.mjs +11 -8
  73. package/dist/esm/client/useDictionary.mjs +47 -25
  74. package/dist/esm/client/useDictionaryAsync.mjs +16 -9
  75. package/dist/esm/client/useDictionaryDynamic.mjs +72 -43
  76. package/dist/esm/client/useIntlayer.mjs +45 -15
  77. package/dist/esm/client/useLoadDynamic.mjs +128 -49
  78. package/dist/esm/client/useLocale.mjs +47 -16
  79. package/dist/esm/client/useLocaleBase.mjs +14 -10
  80. package/dist/esm/client/useLocaleStorage.mjs +51 -10
  81. package/dist/esm/client/usePathname.mjs +37 -12
  82. package/dist/esm/client/useRewriteURL.mjs +17 -11
  83. package/dist/esm/client/useTraduction.mjs +29 -8
  84. package/dist/esm/editor/ContentSelector.mjs +18 -15
  85. package/dist/esm/editor/EditorProvider.mjs +6 -3
  86. package/dist/esm/editor/createEditedContentSource.mjs +28 -17
  87. package/dist/esm/editor/useEditor.mjs +32 -22
  88. package/dist/esm/format/index.mjs +10 -10
  89. package/dist/esm/format/useCompact.mjs +11 -8
  90. package/dist/esm/format/useCurrency.mjs +12 -9
  91. package/dist/esm/format/useDate.mjs +19 -13
  92. package/dist/esm/format/useIntl.mjs +27 -9
  93. package/dist/esm/format/useList.mjs +11 -8
  94. package/dist/esm/format/useNumber.mjs +15 -9
  95. package/dist/esm/format/usePercentage.mjs +12 -9
  96. package/dist/esm/format/useRelativeTime.mjs +12 -9
  97. package/dist/esm/format/useUnit.mjs +11 -8
  98. package/dist/esm/getDictionary.mjs +14 -6
  99. package/dist/esm/getIntlayer.mjs +11 -6
  100. package/dist/esm/html/HTMLProvider.mjs +21 -12
  101. package/dist/esm/html/HTMLRenderer.mjs +44 -17
  102. package/dist/esm/html/index.mjs +3 -3
  103. package/dist/esm/index.mjs +20 -20
  104. package/dist/esm/markdown/MarkdownProvider.mjs +31 -24
  105. package/dist/esm/markdown/MarkdownRenderer.mjs +48 -37
  106. package/dist/esm/markdown/compiler.mjs +59 -23
  107. package/dist/esm/markdown/index.mjs +4 -4
  108. package/dist/esm/markdown/runtime.mjs +40 -13
  109. package/dist/esm/plugins.mjs +205 -156
  110. package/dist/esm/proxyKeys.mjs +7 -2
  111. package/dist/esm/server/useDictionary.mjs +25 -7
  112. package/dist/esm/solidCompat.mjs +146 -39
  113. package/dist/esm/solidElement/renderSolidElement.mjs +22 -19
  114. package/dist/rolldown-runtime-CmQyd0Gu.js +27 -0
  115. package/dist/solid/analytics/useAnalytics.jsx +3 -3
  116. package/dist/solid/analytics/useConversion.js +2 -2
  117. package/dist/solid/analytics/useExperiment.js +3 -3
  118. package/package.json +7 -7
  119. package/dist/esm-YGODKOLP.js +0 -1
  120. package/dist/esm-bdKnuomJ.mjs +0 -256
  121. package/dist/isEnabled-CuTKz0YA.js +0 -1
  122. package/dist/isEnabled-DVKEZ2He.mjs +0 -18
  123. package/dist/rolldown-runtime-BocRIvOZ.js +0 -1
  124. package/dist/solid/esm-1cHk4dPd.js +0 -644
  125. package/dist/solid/isEnabled-C5NUhdhZ.js +0 -100
@@ -1,18 +0,0 @@
1
- import { analytics as e, editor as t } from "@intlayer/config/built";
2
- // ../@intlayer/analytics/dist/esm/utils/isBot.mjs
3
- var n = /cubot/i, r = /bot\b|bot[/\-\s]|crawler|crawling|spider|scraper|slurp|archiver|feedfetcher|validator|curl\/|wget\/|python-requests|python-urllib|okhttp|axios\/|node-fetch|got \(|go-http-client|java\/|libwww|httpunit|http_request|apache-httpclient|headless|phantomjs|puppeteer|playwright|selenium|webdriver|cypress|lighthouse|pagespeed|gtmetrix|prerender|pingdom|uptime|statuscake|site24x7|bingpreview|yandex|baiduspider|sogou|exabot|semrush|ahrefs|mj12|dotbot|petalbot|applebot|amazonbot|bytespider|facebookexternalhit|meta-externalagent|embedly|outbrain|quora link preview|skypeuripreview|vkshare|w3c_validator|apis-google|mediapartners|adsbot|storebot-google|google-inspectiontool|google-read-aloud|google-extended|duplexweb-google|gptbot|oai-searchbot|chatgpt-user|perplexity|claudebot|claude-web|anthropic-ai|cohere-ai|ccbot|diffbot|imagesift|omgili|timpi|youbot/i, i = (e) => !e || !n.test(e) && r.test(e), a = [
4
- "_phantom",
5
- "__nightmare",
6
- "callPhantom",
7
- "__selenium_unwrapped",
8
- "__webdriver_evaluate",
9
- "__driver_evaluate",
10
- "domAutomation",
11
- "Cypress"
12
- ], o = () => {
13
- if (typeof navigator > "u") return !1;
14
- if (navigator.webdriver === !0) return !0;
15
- let e = globalThis;
16
- return a.some((t) => t in e) ? !0 : navigator.userAgent ? i(navigator.userAgent) : !1;
17
- }, s = process.env.INTLAYER_ANALYTICS_ENABLED !== "false" && e?.enabled === !0 && !!t?.clientId && typeof window < "u" && window.self === window.top && !o();
18
- export { i, r as n, o as r, s as t };
@@ -1 +0,0 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
@@ -1,644 +0,0 @@
1
- import { r as isBotEnvironment } from "./isEnabled-C5NUhdhZ.js";
2
- import { analytics, editor } from "@intlayer/config/built";
3
- // ../@intlayer/analytics/dist/esm/events/contentExposure.mjs
4
- /**
5
- * Serializes a `KeyPath[]` into a compact, stable string used both as the
6
- * coalescing key in the buffer and as the stored `keyPath` on the wire.
7
- *
8
- * Only the `key` of each segment is kept (types are implied by the dictionary
9
- * shape), producing paths like `"faq.items.2.answer"`.
10
- *
11
- * @param keyPath - The interpreter key path locating a node.
12
- * @returns A dot-joined, stable path string.
13
- *
14
- * @example
15
- * serializeKeyPath([{ type: 'object', key: 'faq' }, { type: 'array', key: 2 }]);
16
- * // "faq.2"
17
- */
18
- var serializeKeyPath = (keyPath) => keyPath.map((segment) => segment.key === void 0 ? "*" : String(segment.key)).join(".");
19
- /**
20
- * Builds a content-exposure payload from interpreter node metadata. Shared by
21
- * every framework binding's analytics node plugin so the wire shape stays
22
- * identical across React, Vue, Svelte, Angular, etc.
23
- *
24
- * @param params - Node metadata available on `NodeProps`.
25
- * @returns A trackable content-exposure event (minus buffer-stamped fields).
26
- */
27
- var buildContentExposure = (params) => ({
28
- dictionaryKey: params.dictionaryKey,
29
- keyPath: serializeKeyPath(params.keyPath),
30
- locale: params.locale,
31
- nodeType: params.nodeType,
32
- experimentKey: params.experimentKey,
33
- variant: params.variant
34
- });
35
- // ../@intlayer/analytics/dist/esm/utils/hash.mjs
36
- /**
37
- * FNV-1a 32-bit string hash. Small, fast, dependency-free, and stable across
38
- * runtimes — good enough for deterministic A/B bucketing and session seeding
39
- * (not for cryptographic use).
40
- *
41
- * @param input - The string to hash.
42
- * @returns An unsigned 32-bit integer hash.
43
- *
44
- * @example
45
- * hashString('session-1:homepage-hero'); // 3039336720
46
- */
47
- var hashString = (input) => {
48
- let hash = 0x811c9dc5;
49
- for (let index = 0; index < input.length; index++) {
50
- hash ^= input.charCodeAt(index);
51
- hash = Math.imul(hash, 16777619);
52
- }
53
- return hash >>> 0;
54
- };
55
- // ../@intlayer/analytics/dist/esm/core/abTesting.mjs
56
- /**
57
- * Deterministically assigns a variant to a session for a given experiment.
58
- *
59
- * The assignment is a pure function of `sessionId` + `experimentKey`, so it is
60
- * stable for the whole session and requires **no** server round-trip before the
61
- * first render — avoiding layout shift / content flicker. Optional `weights`
62
- * bias the split (e.g. `[0.9, 0.1]` for a 90/10 rollout).
63
- *
64
- * @param sessionId - The current anonymous session id.
65
- * @param experimentKey - Unique key identifying the experiment.
66
- * @param variants - The candidate variant names (at least one).
67
- * @param weights - Optional relative weights, one per variant.
68
- * @returns The variant assigned to this session.
69
- *
70
- * @example
71
- * assignVariant('sid-1', 'homepage-hero', ['a', 'b']); // stable 'a' | 'b'
72
- * assignVariant('sid-1', 'homepage-hero', ['a', 'b'], [9, 1]); // ~90% 'a'
73
- */
74
- var assignVariant = (sessionId, experimentKey, variants, weights) => {
75
- if (variants.length === 0) throw new Error("assignVariant requires at least one variant");
76
- if (variants.length === 1) return variants[0];
77
- const bucket = hashString(`${sessionId}:${experimentKey}`) / 4294967296;
78
- if (!weights || weights.length !== variants.length) {
79
- const index = Math.floor(bucket * variants.length);
80
- return variants[Math.min(index, variants.length - 1)];
81
- }
82
- const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
83
- if (totalWeight <= 0) return variants[Math.floor(bucket * variants.length)];
84
- let cumulative = 0;
85
- const target = bucket * totalWeight;
86
- for (let index = 0; index < variants.length; index++) {
87
- cumulative += weights[index];
88
- if (target < cumulative) return variants[index];
89
- }
90
- return variants[variants.length - 1];
91
- };
92
- // ../@intlayer/analytics/dist/esm/core/eventBuffer.mjs
93
- /** Field separator for coalescing keys — never present in content keys. */
94
- var KEY_SEPARATOR = "";
95
- /**
96
- * Builds the coalescing key for a content-exposure event. Two exposures of the
97
- * same node, page, locale, experiment, and variant collapse into one event with
98
- * an incremented `count`.
99
- */
100
- var exposureKey = (event) => [
101
- event.url,
102
- event.dictionaryKey,
103
- event.keyPath,
104
- event.locale,
105
- event.experimentKey ?? "",
106
- event.variant ?? ""
107
- ].join(KEY_SEPARATOR);
108
- /**
109
- * Creates an {@link EventBuffer}.
110
- *
111
- * @param options - Buffer options.
112
- * @param options.max - Maximum number of distinct events to retain.
113
- * @returns A new buffer instance.
114
- */
115
- var createEventBuffer = ({ max }) => {
116
- let discreteEvents = [];
117
- const exposures = /* @__PURE__ */ new Map();
118
- const size = () => discreteEvents.length + exposures.size;
119
- /** Evicts oldest exposures first, then oldest discrete events. */
120
- const enforceCap = () => {
121
- while (size() > max && exposures.size > 0) {
122
- const oldestKey = exposures.keys().next().value;
123
- exposures.delete(oldestKey);
124
- }
125
- if (size() > max) discreteEvents = discreteEvents.slice(size() - max);
126
- };
127
- const push = (event) => {
128
- if (event.type === "content_exposure") {
129
- const key = exposureKey(event);
130
- const existing = exposures.get(key);
131
- if (existing) {
132
- existing.count = (existing.count ?? 1) + (event.count ?? 1);
133
- existing.t = event.t;
134
- } else exposures.set(key, {
135
- ...event,
136
- count: event.count ?? 1
137
- });
138
- } else discreteEvents.push(event);
139
- enforceCap();
140
- return size();
141
- };
142
- const drain = () => {
143
- const drained = [...discreteEvents, ...exposures.values()];
144
- discreteEvents = [];
145
- exposures.clear();
146
- return drained;
147
- };
148
- return {
149
- push,
150
- drain,
151
- size
152
- };
153
- };
154
- // ../@intlayer/analytics/dist/esm/core/sampling.mjs
155
- /**
156
- * Deterministic per-session sampling gate. Using the session id (rather than a
157
- * fresh random draw per event) means a sampled-in session reports *all* of its
158
- * content exposures, keeping per-session funnels consistent instead of leaving
159
- * holes.
160
- *
161
- * @param sessionId - The current anonymous session id.
162
- * @param sampleRate - Fraction of sessions to keep, from 0 (none) to 1 (all).
163
- * @returns `true` when this session's events should be recorded.
164
- *
165
- * @example
166
- * isSampledIn('abc', 1); // always true
167
- * isSampledIn('abc', 0); // always false
168
- * isSampledIn('abc', 0.5); // stable per session
169
- */
170
- var isSampledIn = (sessionId, sampleRate) => {
171
- if (sampleRate >= 1) return true;
172
- if (sampleRate <= 0) return false;
173
- return hashString(sessionId) / 0xffffffff < sampleRate;
174
- };
175
- // ../@intlayer/analytics/dist/esm/core/session.mjs
176
- /**
177
- * Anonymous, per-tab session identity. Stored in `sessionStorage` so it is
178
- * cleared when the tab closes and is never shared across sites — no durable
179
- * cookie, no cross-site tracking, no PII.
180
- */
181
- var SESSION_STORAGE_KEY = "__intlayer_analytics_sid__";
182
- /**
183
- * Generates a random, opaque session identifier.
184
- *
185
- * @returns A URL-safe random string.
186
- */
187
- var generateSessionId = () => {
188
- const cryptoObj = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
189
- if (cryptoObj?.randomUUID) return cryptoObj.randomUUID();
190
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
191
- };
192
- /**
193
- * Returns the current session id, creating and persisting one on first access.
194
- * Degrades gracefully to an in-memory id when `sessionStorage` is unavailable
195
- * (private mode, native runtimes).
196
- *
197
- * @returns The stable session id for the lifetime of the tab.
198
- */
199
- var getSessionId = () => {
200
- if (typeof window === "undefined" || !window.sessionStorage) return generateSessionId();
201
- try {
202
- const existing = window.sessionStorage.getItem(SESSION_STORAGE_KEY);
203
- if (existing) return existing;
204
- const created = generateSessionId();
205
- window.sessionStorage.setItem(SESSION_STORAGE_KEY, created);
206
- return created;
207
- } catch {
208
- return generateSessionId();
209
- }
210
- };
211
- // ../@intlayer/analytics/dist/esm/core/transport.mjs
212
- /**
213
- * Sends a batch of events to the backend. Every path is non-blocking and
214
- * no-throw — analytics must never break, slow, or delay the host application.
215
- *
216
- * Strategy:
217
- * 1. `navigator.sendBeacon` for the flush-on-hide path — survives page unload
218
- * and never blocks navigation. The payload is sent as `text/plain` (a
219
- * CORS-safelisted content type): a JSON `Blob` would require a CORS
220
- * preflight that browsers handle inconsistently during unload, silently
221
- * dropping the beacon. The backend parses `text/plain` bodies as JSON.
222
- * 2. `fetch(..., { keepalive: true })` for interval flushes — survives short
223
- * navigations without holding the main thread.
224
- * 3. Plain `fetch` fallback for runtimes without `keepalive` (older RN/Lynx).
225
- *
226
- * @param endpoint - Fully-qualified ingestion URL.
227
- * @param body - The batched payload.
228
- * @param options - Transport options.
229
- * @param options.useBeacon - Prefer `sendBeacon` (used when the page is hiding).
230
- * @param options.token - Ingest token, sent as a bearer on the `fetch` path.
231
- * `sendBeacon` cannot set headers, which is why the token is also carried in
232
- * the body.
233
- * @returns `true` when a send was dispatched, `false` otherwise.
234
- */
235
- var sendEvents = (endpoint, body, { useBeacon = false, token } = {}) => {
236
- try {
237
- const payload = JSON.stringify(body);
238
- if (useBeacon && typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function") return navigator.sendBeacon(endpoint, payload);
239
- if (typeof fetch === "function") {
240
- fetch(endpoint, {
241
- method: "POST",
242
- headers: {
243
- "Content-Type": "application/json",
244
- ...token ? { Authorization: `Bearer ${token}` } : {}
245
- },
246
- body: payload,
247
- keepalive: true,
248
- credentials: "omit",
249
- mode: "cors"
250
- }).catch(() => {});
251
- return true;
252
- }
253
- return false;
254
- } catch {
255
- return false;
256
- }
257
- };
258
- // ../@intlayer/analytics/dist/esm/utils/idle.mjs
259
- /**
260
- * Runs a callback when the browser is idle, without blocking first render.
261
- * Falls back to a short `setTimeout` where `requestIdleCallback` is unavailable
262
- * (Safari, React Native, Lynx).
263
- *
264
- * @param callback - Work to run once the main thread is free.
265
- *
266
- * @example
267
- * onIdle(() => attachVisibilityListeners());
268
- */
269
- var onIdle = (callback) => {
270
- if (typeof window === "undefined") return;
271
- const requestIdle = window.requestIdleCallback;
272
- if (typeof requestIdle === "function") {
273
- requestIdle(() => callback());
274
- return;
275
- }
276
- setTimeout(callback, 1);
277
- };
278
- // ../@intlayer/analytics/dist/esm/core/publicToken.mjs
279
- /**
280
- * Short-lived ingest token used to authorise analytics batches.
281
- *
282
- * The SDK runs in the browser, where no confidential credential can be kept, so
283
- * it exchanges the project's **public** `clientId` for a token scoped to
284
- * analytics ingestion and nothing else. The backend authorises the exchange by
285
- * the request's `Origin`, which the page cannot forge.
286
- *
287
- * The token is read synchronously at flush time — the flush-on-hide path runs
288
- * during `pagehide` and cannot await anything — so it is fetched ahead of time
289
- * and cached, both in memory and in `sessionStorage` so a multi-page visit
290
- * exchanges once per tab rather than once per navigation.
291
- */
292
- /** `sessionStorage` key holding the cached token for this tab. */
293
- var TOKEN_STORAGE_KEY = "__intlayer_public_token__";
294
- /**
295
- * Refresh margin: a token within this window of expiry is treated as expired,
296
- * so a batch is never sent with a token that dies in flight.
297
- */
298
- var EXPIRY_MARGIN_MS = 6e4;
299
- /** Reads the cached token for this tab, ignoring an unusable cache. */
300
- var readStoredToken = () => {
301
- try {
302
- const raw = window.sessionStorage?.getItem(TOKEN_STORAGE_KEY);
303
- if (!raw) return null;
304
- const parsed = JSON.parse(raw);
305
- if (typeof parsed?.token !== "string") return null;
306
- if (typeof parsed?.expiresAt !== "number") return null;
307
- return parsed;
308
- } catch {
309
- return null;
310
- }
311
- };
312
- /** Persists the token for this tab. Best-effort: storage may be unavailable. */
313
- var writeStoredToken = (cached) => {
314
- try {
315
- window.sessionStorage?.setItem(TOKEN_STORAGE_KEY, JSON.stringify(cached));
316
- } catch {}
317
- };
318
- /**
319
- * Creates the ingest token manager for a project.
320
- *
321
- * Every failure path is silent: analytics must never break, slow, or log noise
322
- * into the host application. Without a token the client falls back to sending
323
- * its public `clientId`, which the backend still accepts.
324
- *
325
- * @param options - Backend URL and the public project key.
326
- * @returns A manager exposing a synchronous {@link PublicTokenManager.getToken}.
327
- */
328
- var createPublicTokenManager = ({ backendURL, clientId }) => {
329
- const endpoint = `${backendURL.replace(/\/$/, "")}/api/public/token`;
330
- let cached = null;
331
- let pendingExchange = null;
332
- const isUsable = (candidate) => candidate !== null && candidate.expiresAt - EXPIRY_MARGIN_MS > Date.now();
333
- const getToken = () => {
334
- if (isUsable(cached)) return cached.token;
335
- if (typeof window !== "undefined") {
336
- const stored = readStoredToken();
337
- if (isUsable(stored)) {
338
- cached = stored;
339
- return stored.token;
340
- }
341
- }
342
- };
343
- const exchange = async () => {
344
- try {
345
- const response = await fetch(endpoint, {
346
- method: "POST",
347
- headers: { "Content-Type": "application/json" },
348
- body: JSON.stringify({ clientId }),
349
- credentials: "omit",
350
- mode: "cors"
351
- });
352
- if (!response.ok) return;
353
- const payload = await response.json();
354
- const token = payload?.data?.token;
355
- const expiresIn = payload?.data?.expiresIn ?? 0;
356
- if (!token || expiresIn <= 0) return;
357
- cached = {
358
- token,
359
- expiresAt: Date.now() + expiresIn * 1e3
360
- };
361
- if (typeof window !== "undefined") writeStoredToken(cached);
362
- } catch {} finally {
363
- pendingExchange = null;
364
- }
365
- };
366
- const prime = () => {
367
- if (!clientId || typeof fetch !== "function") return;
368
- if (getToken()) return;
369
- if (pendingExchange) return;
370
- pendingExchange = exchange();
371
- };
372
- return {
373
- getToken,
374
- prime
375
- };
376
- };
377
- // ../@intlayer/analytics/dist/esm/core/AnalyticsClient.mjs
378
- /** Identifies the producing SDK in the ingest envelope. */
379
- var SDK_VERSION = "intlayer-analytics/1";
380
- /**
381
- * Reads the current page pathname. Search params are intentionally excluded to
382
- * avoid capturing anything sensitive.
383
- */
384
- var currentUrl = () => {
385
- if (typeof window === "undefined" || !window.location) return "";
386
- return window.location.pathname;
387
- };
388
- /**
389
- * Reduces the referrer to its host — never the full URL — for privacy.
390
- */
391
- var referrerHost = () => {
392
- if (typeof document === "undefined" || !document.referrer) return void 0;
393
- try {
394
- return new URL(document.referrer).host;
395
- } catch {
396
- return;
397
- }
398
- };
399
- /**
400
- * Creates an analytics client. Prefer {@link initAnalyticsClient} in application
401
- * code — it manages a shared singleton so there is only ever one flush timer.
402
- *
403
- * @param config - Resolved client configuration.
404
- * @returns A started-on-demand {@link AnalyticsClient}.
405
- */
406
- var createAnalyticsClient = (config) => {
407
- const sessionId = getSessionId();
408
- const isBotSession = isBotEnvironment();
409
- const sampledIn = !isBotSession && isSampledIn(sessionId, config.sampleRate);
410
- const buffer = createEventBuffer({ max: config.maxBufferSize });
411
- const endpoint = `${config.backendURL.replace(/\/$/, "")}/api/analytics/events`;
412
- const publicToken = createPublicTokenManager({
413
- backendURL: config.backendURL,
414
- clientId: config.clientId
415
- });
416
- let ambientLocale = "";
417
- let flushTimer = null;
418
- let started = false;
419
- let detachListeners = null;
420
- let lastPageViewUrl = null;
421
- let seenExposureKeys = /* @__PURE__ */ new Set();
422
- const flush = (useBeacon = false) => {
423
- const events = buffer.drain();
424
- const token = publicToken.getToken();
425
- for (let start = 0; start < events.length; start += 200) sendEvents(endpoint, {
426
- token,
427
- clientId: token ? void 0 : config.clientId,
428
- sessionId,
429
- sdkVersion: SDK_VERSION,
430
- events: events.slice(start, start + 200)
431
- }, {
432
- useBeacon,
433
- token
434
- });
435
- };
436
- /** Pushes an event and triggers an early flush if the buffer is full. */
437
- const enqueue = (event) => {
438
- if (buffer.push(event) >= config.maxBufferSize) flush();
439
- };
440
- const setLocale = (locale) => {
441
- ambientLocale = locale;
442
- };
443
- const trackPageView = (event = {}) => {
444
- if (!sampledIn) return;
445
- const url = event.url ?? currentUrl();
446
- const reason = event.reason ?? "initial";
447
- if (reason === "route_change" && url === lastPageViewUrl) return;
448
- lastPageViewUrl = url;
449
- seenExposureKeys = /* @__PURE__ */ new Set();
450
- enqueue({
451
- type: "page_view",
452
- t: Date.now(),
453
- url,
454
- locale: event.locale ?? ambientLocale,
455
- ref: event.ref ?? referrerHost(),
456
- vw: event.vw ?? (typeof window !== "undefined" ? window.innerWidth : void 0),
457
- vh: event.vh ?? (typeof window !== "undefined" ? window.innerHeight : void 0),
458
- reason
459
- });
460
- };
461
- const trackContentExposure = (event) => {
462
- if (!sampledIn) return;
463
- const locale = event.locale ?? ambientLocale;
464
- const exposureKey = [
465
- event.dictionaryKey,
466
- event.keyPath,
467
- locale,
468
- event.experimentKey ?? "",
469
- event.variant ?? ""
470
- ].join("");
471
- if (seenExposureKeys.has(exposureKey)) return;
472
- seenExposureKeys.add(exposureKey);
473
- enqueue({
474
- ...event,
475
- type: "content_exposure",
476
- t: Date.now(),
477
- url: currentUrl(),
478
- locale
479
- });
480
- };
481
- const trackConversion = (event) => {
482
- if (isBotSession) return;
483
- enqueue({
484
- ...event,
485
- type: "conversion",
486
- t: Date.now(),
487
- url: currentUrl(),
488
- locale: event.locale ?? ambientLocale
489
- });
490
- flush();
491
- };
492
- const getVariant = (experimentKey, variants, weights) => assignVariant(sessionId, experimentKey, variants, weights);
493
- /** Attaches lifecycle + SPA-navigation listeners without blocking render. */
494
- const attachListeners = () => {
495
- if (typeof window === "undefined") return;
496
- const onHidden = () => {
497
- if (document.visibilityState === "hidden") flush(true);
498
- };
499
- const onPageHide = () => flush(true);
500
- const onPopState = () => trackPageView({ reason: "route_change" });
501
- document.addEventListener("visibilitychange", onHidden);
502
- window.addEventListener("pagehide", onPageHide, { capture: true });
503
- window.addEventListener("popstate", onPopState);
504
- const history = window.history;
505
- const originalPush = history.pushState;
506
- const patchedPushState = function patchedPush(...args) {
507
- const result = originalPush.apply(this, args);
508
- trackPageView({ reason: "route_change" });
509
- return result;
510
- };
511
- history.pushState = patchedPushState;
512
- detachListeners = () => {
513
- document.removeEventListener("visibilitychange", onHidden);
514
- window.removeEventListener("pagehide", onPageHide, { capture: true });
515
- window.removeEventListener("popstate", onPopState);
516
- if (history.pushState === patchedPushState) history.pushState = originalPush;
517
- };
518
- };
519
- const start = () => {
520
- if (started || isBotSession) return;
521
- started = true;
522
- publicToken.prime();
523
- flushTimer = setInterval(flush, config.flushInterval);
524
- flushTimer?.unref?.();
525
- onIdle(attachListeners);
526
- };
527
- const stop = () => {
528
- if (!started) return;
529
- started = false;
530
- if (flushTimer) {
531
- clearInterval(flushTimer);
532
- flushTimer = null;
533
- }
534
- detachListeners?.();
535
- detachListeners = null;
536
- flush(true);
537
- };
538
- return {
539
- setLocale,
540
- trackPageView,
541
- trackContentExposure,
542
- trackConversion,
543
- getVariant,
544
- flush,
545
- start,
546
- stop
547
- };
548
- };
549
- // ../@intlayer/analytics/dist/esm/core/globalManager.mjs
550
- /**
551
- * Key on `window` used to share the client singleton across multiple module
552
- * instances. When bundlers include `@intlayer/analytics` more than once (e.g.
553
- * a framework package plus the app), each copy has its own module-level
554
- * variables; storing the client on `window` ensures they all share one buffer
555
- * and one flush timer.
556
- */
557
- var CLIENT_KEY = "__intlayer_analytics_client__";
558
- /**
559
- * Key on `window` holding the provider reference count. It lives next to the
560
- * client (rather than in module scope) for the same reason the client does:
561
- * duplicated module instances must share one count, otherwise one copy's
562
- * `stopAnalyticsClient` could stop a client another copy still uses.
563
- */
564
- var REF_COUNT_KEY = "__intlayer_analytics_ref_count__";
565
- /**
566
- * Returns the global analytics client, or `null` in SSR or before init.
567
- */
568
- var getGlobalAnalyticsClient = () => {
569
- if (typeof window === "undefined") return null;
570
- return window[CLIENT_KEY] ?? null;
571
- };
572
- /**
573
- * Sets (or clears) the global analytics client singleton.
574
- *
575
- * @param client - The client to store globally, or `null` to clear it.
576
- */
577
- var setGlobalAnalyticsClient = (client) => {
578
- if (typeof window === "undefined") return;
579
- window[CLIENT_KEY] = client;
580
- };
581
- /**
582
- * Increments the shared provider reference count.
583
- *
584
- * @returns The count after incrementing (`0` in SSR, where nothing is stored).
585
- */
586
- var incrementAnalyticsClientRefCount = () => {
587
- if (typeof window === "undefined") return 0;
588
- const globals = window;
589
- globals[REF_COUNT_KEY] = (globals[REF_COUNT_KEY] ?? 0) + 1;
590
- return globals[REF_COUNT_KEY];
591
- };
592
- /**
593
- * Decrements the shared provider reference count, clamping at zero.
594
- *
595
- * @returns The count after decrementing (`0` in SSR, where nothing is stored).
596
- */
597
- var decrementAnalyticsClientRefCount = () => {
598
- if (typeof window === "undefined") return 0;
599
- const globals = window;
600
- globals[REF_COUNT_KEY] = Math.max(0, (globals[REF_COUNT_KEY] ?? 0) - 1);
601
- return globals[REF_COUNT_KEY];
602
- };
603
- // ../@intlayer/analytics/dist/esm/core/initAnalyticsClient.mjs
604
- /**
605
- * Initializes the Intlayer analytics client singleton.
606
- *
607
- * Behavior comes from the `analytics` config block (`flushInterval`,
608
- * `sampleRate`); attribution reuses the existing `editor` config
609
- * (`editor.backendURL` for the endpoint, `editor.clientId` for the project).
610
- *
611
- * Safe to call multiple times: returns the existing client and increments a
612
- * `window`-shared reference count so nested providers (or duplicated module
613
- * instances) don't stop the client prematurely.
614
- *
615
- * @returns The started analytics client singleton.
616
- */
617
- var initAnalyticsClient = () => {
618
- incrementAnalyticsClientRefCount();
619
- const existing = getGlobalAnalyticsClient();
620
- if (existing) return existing;
621
- const client = createAnalyticsClient({
622
- backendURL: editor?.backendURL ?? "",
623
- clientId: editor?.clientId,
624
- flushInterval: analytics?.flushInterval ?? 2e4,
625
- maxBufferSize: 500,
626
- sampleRate: analytics?.sampleRate ?? 1
627
- });
628
- setGlobalAnalyticsClient(client);
629
- client.start();
630
- return client;
631
- };
632
- /**
633
- * Decrements the shared reference count and stops the global analytics client
634
- * only when the last provider unmounts (flushing any remaining events).
635
- *
636
- * Callers must pair each `stopAnalyticsClient` with a prior
637
- * `initAnalyticsClient` — never call it when init was skipped or cancelled.
638
- */
639
- var stopAnalyticsClient = () => {
640
- if (decrementAnalyticsClientRefCount() > 0) return;
641
- getGlobalAnalyticsClient()?.stop();
642
- setGlobalAnalyticsClient(null);
643
- };
644
- export { buildContentExposure, getGlobalAnalyticsClient, initAnalyticsClient, stopAnalyticsClient };