angular-intlayer 9.0.0-canary.14 → 9.0.0-canary.16

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 (64) hide show
  1. package/dist/cjs/analytics/exposureSink.cjs +27 -0
  2. package/dist/cjs/analytics/exposureSink.cjs.map +1 -0
  3. package/dist/cjs/analytics/index.cjs +9 -0
  4. package/dist/cjs/analytics/useAnalytics.cjs +85 -0
  5. package/dist/cjs/analytics/useAnalytics.cjs.map +1 -0
  6. package/dist/cjs/analytics/useConversion.cjs +37 -0
  7. package/dist/cjs/analytics/useConversion.cjs.map +1 -0
  8. package/dist/cjs/analytics/useExperiment.cjs +70 -0
  9. package/dist/cjs/analytics/useExperiment.cjs.map +1 -0
  10. package/dist/cjs/client/installIntlayer.cjs +9 -4
  11. package/dist/cjs/client/installIntlayer.cjs.map +1 -1
  12. package/dist/cjs/index.cjs +7 -0
  13. package/dist/cjs/plugins.cjs +21 -12
  14. package/dist/cjs/plugins.cjs.map +1 -1
  15. package/dist/esm/analytics/exposureSink.mjs +24 -0
  16. package/dist/esm/analytics/exposureSink.mjs.map +1 -0
  17. package/dist/esm/analytics/index.mjs +5 -0
  18. package/dist/esm/analytics/useAnalytics.mjs +82 -0
  19. package/dist/esm/analytics/useAnalytics.mjs.map +1 -0
  20. package/dist/esm/analytics/useConversion.mjs +35 -0
  21. package/dist/esm/analytics/useConversion.mjs.map +1 -0
  22. package/dist/esm/analytics/useExperiment.mjs +68 -0
  23. package/dist/esm/analytics/useExperiment.mjs.map +1 -0
  24. package/dist/esm/client/installIntlayer.mjs +9 -4
  25. package/dist/esm/client/installIntlayer.mjs.map +1 -1
  26. package/dist/esm/esbuild/plugin.mjs +2 -2
  27. package/dist/esm/index.mjs +4 -1
  28. package/dist/esm/plugins.mjs +21 -12
  29. package/dist/esm/plugins.mjs.map +1 -1
  30. package/dist/esm/webpack/mergeConfig.mjs +1 -1
  31. package/dist/types/analytics/exposureSink.d.ts +33 -0
  32. package/dist/types/analytics/exposureSink.d.ts.map +1 -0
  33. package/dist/types/analytics/index.d.ts +4 -0
  34. package/dist/types/analytics/useAnalytics.d.ts +38 -0
  35. package/dist/types/analytics/useAnalytics.d.ts.map +1 -0
  36. package/dist/types/analytics/useConversion.d.ts +34 -0
  37. package/dist/types/analytics/useConversion.d.ts.map +1 -0
  38. package/dist/types/analytics/useExperiment.d.ts +48 -0
  39. package/dist/types/analytics/useExperiment.d.ts.map +1 -0
  40. package/dist/types/client/installIntlayer.d.ts.map +1 -1
  41. package/dist/types/client/useLocaleStorage.d.ts +5 -5
  42. package/dist/types/client/useLocaleStorage.d.ts.map +1 -1
  43. package/dist/types/format/useCompact.d.ts +2 -2
  44. package/dist/types/format/useCompact.d.ts.map +1 -1
  45. package/dist/types/format/useCurrency.d.ts +2 -2
  46. package/dist/types/format/useCurrency.d.ts.map +1 -1
  47. package/dist/types/format/useDate.d.ts +2 -2
  48. package/dist/types/format/useDate.d.ts.map +1 -1
  49. package/dist/types/format/useList.d.ts +2 -2
  50. package/dist/types/format/useList.d.ts.map +1 -1
  51. package/dist/types/format/useNumber.d.ts +2 -2
  52. package/dist/types/format/useNumber.d.ts.map +1 -1
  53. package/dist/types/format/usePercentage.d.ts +2 -2
  54. package/dist/types/format/usePercentage.d.ts.map +1 -1
  55. package/dist/types/format/useRelativeTime.d.ts +2 -2
  56. package/dist/types/format/useRelativeTime.d.ts.map +1 -1
  57. package/dist/types/format/useUnit.d.ts +2 -2
  58. package/dist/types/format/useUnit.d.ts.map +1 -1
  59. package/dist/types/index.d.ts +4 -1
  60. package/dist/types/index.d.ts.map +1 -1
  61. package/dist/types/packages/intlayer/dist/types/index.d.ts +4 -0
  62. package/dist/types/plugins.d.ts.map +1 -1
  63. package/dist/types/webpack/mergeConfig.d.ts +1 -1
  64. package/package.json +12 -9
@@ -0,0 +1,27 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ //#region src/analytics/exposureSink.ts
4
+ let sink = null;
5
+ /**
6
+ * Installs (or clears) the exposure sink. `useAnalytics` sets this once the
7
+ * analytics client has loaded, and clears it on unmount.
8
+ *
9
+ * @param next - The sink to install, or `null` to clear.
10
+ */
11
+ const setExposureSink = (next) => {
12
+ sink = next;
13
+ };
14
+ /**
15
+ * Forwards a content exposure to the installed sink. A cheap null-check when
16
+ * analytics is not running, so it is safe to call from every node resolution.
17
+ *
18
+ * @param input - The node metadata to report.
19
+ */
20
+ const reportExposure = (input) => {
21
+ sink?.(input);
22
+ };
23
+
24
+ //#endregion
25
+ exports.reportExposure = reportExposure;
26
+ exports.setExposureSink = setExposureSink;
27
+ //# sourceMappingURL=exposureSink.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exposureSink.cjs","names":[],"sources":["../../../src/analytics/exposureSink.ts"],"sourcesContent":["import type { KeyPath } from '@intlayer/types/keyPath';\n\n/**\n * Node metadata reported for a content exposure. Kept dependency-free (types\n * only) so the interpreter hot path in `plugins.ts` never statically imports\n * `@intlayer/analytics` — the package stays optional and tree-shakeable.\n */\nexport type ExposureInput = {\n dictionaryKey: string;\n keyPath: KeyPath[];\n locale?: string;\n nodeType?: string;\n};\n\n/** Consumer of exposure reports, installed by `useAnalytics` after init. */\nexport type ExposureSink = (input: ExposureInput) => void;\n\nlet sink: ExposureSink | null = null;\n\n/**\n * Installs (or clears) the exposure sink. `useAnalytics` sets this once the\n * analytics client has loaded, and clears it on unmount.\n *\n * @param next - The sink to install, or `null` to clear.\n */\nexport const setExposureSink = (next: ExposureSink | null): void => {\n sink = next;\n};\n\n/**\n * Forwards a content exposure to the installed sink. A cheap null-check when\n * analytics is not running, so it is safe to call from every node resolution.\n *\n * @param input - The node metadata to report.\n */\nexport const reportExposure = (input: ExposureInput): void => {\n sink?.(input);\n};\n"],"mappings":";;;AAiBA,IAAI,OAA4B;;;;;;;AAQhC,MAAa,mBAAmB,SAAoC;AAClE,QAAO;;;;;;;;AAST,MAAa,kBAAkB,UAA+B;AAC5D,QAAO,MAAM"}
@@ -0,0 +1,9 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_analytics_useAnalytics = require('./useAnalytics.cjs');
3
+ const require_analytics_useConversion = require('./useConversion.cjs');
4
+ const require_analytics_useExperiment = require('./useExperiment.cjs');
5
+
6
+ exports.provideIntlayerAnalytics = require_analytics_useAnalytics.provideIntlayerAnalytics;
7
+ exports.useAnalytics = require_analytics_useAnalytics.useAnalytics;
8
+ exports.useConversion = require_analytics_useConversion.useConversion;
9
+ exports.useExperiment = require_analytics_useExperiment.useExperiment;
@@ -0,0 +1,85 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ const require_analytics_exposureSink = require('./exposureSink.cjs');
4
+ const require_client_intlayerToken = require('../client/intlayerToken.cjs');
5
+ let _angular_core = require("@angular/core");
6
+ let _intlayer_analytics_isEnabled = require("@intlayer/analytics/isEnabled");
7
+
8
+ //#region src/analytics/useAnalytics.ts
9
+ /**
10
+ * Initializes the Intlayer analytics client singleton when analytics is
11
+ * enabled (mirrors {@link useEditor}). Records an initial page view, keeps the
12
+ * client aware of the current locale, and wires node-level content exposures.
13
+ *
14
+ * Must be called inside an Angular injection context (e.g. a component
15
+ * constructor, `provideAppInitializer`, or `runInInjectionContext`).
16
+ *
17
+ * @param client - The IntlayerProvider instance to sync locale from.
18
+ * When omitted the function injects `INTLAYER_TOKEN` from the DI tree,
19
+ * so it still works when called directly from a component.
20
+ */
21
+ const useAnalytics = (client) => {
22
+ if (process.env.INTLAYER_ANALYTICS_ENABLED === "false" || !_intlayer_analytics_isEnabled.isEnabled) return;
23
+ const destroyRef = (0, _angular_core.inject)(_angular_core.DestroyRef, { optional: true });
24
+ const injector = (0, _angular_core.inject)(_angular_core.Injector);
25
+ const resolvedClient = client ?? (0, _angular_core.inject)(require_client_intlayerToken.INTLAYER_TOKEN, { optional: true });
26
+ const analyticsClient = (0, _angular_core.signal)(null);
27
+ let stopped = false;
28
+ let initialized = false;
29
+ import("@intlayer/analytics").then(({ initAnalyticsClient, buildContentExposure }) => {
30
+ if (stopped) return;
31
+ const clientInstance = initAnalyticsClient();
32
+ initialized = true;
33
+ const currentLocale = resolvedClient?.locale();
34
+ if (currentLocale) clientInstance.setLocale(currentLocale);
35
+ clientInstance.trackPageView({ reason: "initial" });
36
+ require_analytics_exposureSink.setExposureSink((input) => clientInstance.trackContentExposure(buildContentExposure(input)));
37
+ analyticsClient.set(clientInstance);
38
+ }).catch(() => {});
39
+ let previousLocale;
40
+ const effectRef = (0, _angular_core.runInInjectionContext)(injector, () => (0, _angular_core.effect)(() => {
41
+ const clientInstance = analyticsClient();
42
+ const locale = resolvedClient?.locale();
43
+ if (!clientInstance || !locale) return;
44
+ if (previousLocale === void 0) {
45
+ previousLocale = locale;
46
+ return;
47
+ }
48
+ if (previousLocale === locale) return;
49
+ previousLocale = locale;
50
+ clientInstance.setLocale(locale);
51
+ clientInstance.trackPageView({ reason: "locale_change" });
52
+ }));
53
+ destroyRef?.onDestroy(() => {
54
+ stopped = true;
55
+ effectRef.destroy();
56
+ analyticsClient.set(null);
57
+ require_analytics_exposureSink.setExposureSink(null);
58
+ import("@intlayer/analytics").then(({ stopAnalyticsClient }) => {
59
+ if (initialized) stopAnalyticsClient();
60
+ }).catch(() => {});
61
+ });
62
+ };
63
+ /**
64
+ * Angular provider that wires `useAnalytics` into the application
65
+ * initialisation phase via `provideAppInitializer`.
66
+ *
67
+ * `provideIntlayer()` already calls this internally, so you only need this
68
+ * function when you want to manage providers individually.
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * // app.config.ts
73
+ * import { provideIntlayer, provideIntlayerAnalytics } from 'angular-intlayer';
74
+ *
75
+ * export const appConfig: ApplicationConfig = {
76
+ * providers: [provideIntlayer(), provideIntlayerAnalytics()],
77
+ * };
78
+ * ```
79
+ */
80
+ const provideIntlayerAnalytics = (client) => (0, _angular_core.provideAppInitializer)(() => useAnalytics(client));
81
+
82
+ //#endregion
83
+ exports.provideIntlayerAnalytics = provideIntlayerAnalytics;
84
+ exports.useAnalytics = useAnalytics;
85
+ //# sourceMappingURL=useAnalytics.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAnalytics.cjs","names":["isEnabled","DestroyRef","Injector","INTLAYER_TOKEN"],"sources":["../../../src/analytics/useAnalytics.ts"],"sourcesContent":["import {\n DestroyRef,\n effect,\n Injector,\n inject,\n provideAppInitializer,\n runInInjectionContext,\n signal,\n} from '@angular/core';\nimport type { AnalyticsClient } from '@intlayer/analytics';\nimport { isEnabled } from '@intlayer/analytics/isEnabled';\n// Import from the standalone token file to avoid a circular dependency:\n// installIntlayer.ts → useAnalytics.ts → ../client → installIntlayer.ts\nimport { INTLAYER_TOKEN, type IntlayerProvider } from '../client/intlayerToken';\nimport { setExposureSink } from './exposureSink';\n\n/**\n * Initializes the Intlayer analytics client singleton when analytics is\n * enabled (mirrors {@link useEditor}). Records an initial page view, keeps the\n * client aware of the current locale, and wires node-level content exposures.\n *\n * Must be called inside an Angular injection context (e.g. a component\n * constructor, `provideAppInitializer`, or `runInInjectionContext`).\n *\n * @param client - The IntlayerProvider instance to sync locale from.\n * When omitted the function injects `INTLAYER_TOKEN` from the DI tree,\n * so it still works when called directly from a component.\n */\nexport const useAnalytics = (client?: IntlayerProvider | null): void => {\n if (process.env.INTLAYER_ANALYTICS_ENABLED === 'false' || !isEnabled) return;\n\n const destroyRef = inject(DestroyRef, { optional: true });\n const injector = inject(Injector);\n\n // Resolve the client: use the passed-in reference or fall back to injection.\n const resolvedClient =\n client ??\n inject<IntlayerProvider>(INTLAYER_TOKEN, { optional: true } as any);\n\n // `analyticsClient` signal is set once the async import resolves.\n // Using a signal lets an `effect()` react to it becoming available.\n const analyticsClient = signal<AnalyticsClient | null>(null);\n\n // Guard: prevents the async callback from acting after the view is destroyed.\n let stopped = false;\n // Tracks whether initAnalyticsClient actually ran, so teardown never calls\n // stopAnalyticsClient for an init that was cancelled — that would decrement\n // the shared reference count once too many.\n let initialized = false;\n\n import('@intlayer/analytics')\n .then(({ initAnalyticsClient, buildContentExposure }) => {\n if (stopped) return;\n\n const clientInstance = initAnalyticsClient();\n initialized = true;\n\n const currentLocale = resolvedClient?.locale();\n if (currentLocale) clientInstance.setLocale(currentLocale);\n clientInstance.trackPageView({ reason: 'initial' });\n\n // Route node-level exposures (from the interpreter plugins) into the\n // client. Serialization happens here, off the hot render path.\n setExposureSink((input) =>\n clientInstance.trackContentExposure(buildContentExposure(input))\n );\n\n analyticsClient.set(clientInstance);\n })\n .catch(() => {\n /* chunk failed to load — analytics stays a no-op */\n });\n\n // Locale switches are a real signal — record them as page views.\n let previousLocale: string | undefined;\n const effectRef = runInInjectionContext(injector, () =>\n effect(() => {\n const clientInstance = analyticsClient();\n const locale = resolvedClient?.locale();\n\n if (!clientInstance || !locale) return;\n\n if (previousLocale === undefined) {\n // First run after init — the initial page view already covered it.\n previousLocale = locale;\n return;\n }\n if (previousLocale === locale) return;\n\n previousLocale = locale;\n clientInstance.setLocale(locale);\n clientInstance.trackPageView({ reason: 'locale_change' });\n })\n );\n\n // Tear down on destroy\n destroyRef?.onDestroy(() => {\n stopped = true;\n effectRef.destroy();\n analyticsClient.set(null);\n setExposureSink(null);\n import('@intlayer/analytics')\n .then(({ stopAnalyticsClient }) => {\n if (initialized) stopAnalyticsClient();\n })\n .catch(() => {});\n });\n};\n\n/**\n * Angular provider that wires `useAnalytics` into the application\n * initialisation phase via `provideAppInitializer`.\n *\n * `provideIntlayer()` already calls this internally, so you only need this\n * function when you want to manage providers individually.\n *\n * @example\n * ```ts\n * // app.config.ts\n * import { provideIntlayer, provideIntlayerAnalytics } from 'angular-intlayer';\n *\n * export const appConfig: ApplicationConfig = {\n * providers: [provideIntlayer(), provideIntlayerAnalytics()],\n * };\n * ```\n */\nexport const provideIntlayerAnalytics = (client?: IntlayerProvider | null) =>\n provideAppInitializer(() => useAnalytics(client));\n"],"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,CAAC"}
@@ -0,0 +1,37 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ let _intlayer_analytics_isEnabled = require("@intlayer/analytics/isEnabled");
4
+
5
+ //#region src/analytics/useConversion.ts
6
+ /**
7
+ * Returns a `trackConversion` callback for content A/B testing. Safe to call
8
+ * from any component: it resolves to a no-op when analytics is disabled or the
9
+ * client has not been initialized yet.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * export class CtaComponent {
14
+ * trackConversion = useConversion();
15
+ *
16
+ * onClick() {
17
+ * this.trackConversion({
18
+ * experimentKey: 'homepage-hero',
19
+ * variant: 'b',
20
+ * goal: 'cta_click',
21
+ * });
22
+ * }
23
+ * }
24
+ * ```
25
+ */
26
+ const useConversion = () => {
27
+ return (params) => {
28
+ if (process.env.INTLAYER_ANALYTICS_ENABLED === "false" || !_intlayer_analytics_isEnabled.isEnabled) return;
29
+ import("@intlayer/analytics").then(({ getGlobalAnalyticsClient }) => {
30
+ getGlobalAnalyticsClient()?.trackConversion(params);
31
+ }).catch(() => {});
32
+ };
33
+ };
34
+
35
+ //#endregion
36
+ exports.useConversion = useConversion;
37
+ //# sourceMappingURL=useConversion.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useConversion.cjs","names":["isEnabled"],"sources":["../../../src/analytics/useConversion.ts"],"sourcesContent":["import { isEnabled } from '@intlayer/analytics/isEnabled';\n\n/**\n * Parameters describing a conversion to record.\n */\nexport type ConversionParams = {\n /** The experiment this conversion is attributed to. */\n experimentKey: string;\n /** The variant the session was assigned. */\n variant: string;\n /** The goal reached (e.g. `\"signup\"`, `\"cta_click\"`). */\n goal: string;\n /** Optional numeric value (e.g. revenue). */\n value?: number;\n};\n\n/**\n * Returns a `trackConversion` callback for content A/B testing. Safe to call\n * from any component: it resolves to a no-op when analytics is disabled or the\n * client has not been initialized yet.\n *\n * @example\n * ```ts\n * export class CtaComponent {\n * trackConversion = useConversion();\n *\n * onClick() {\n * this.trackConversion({\n * experimentKey: 'homepage-hero',\n * variant: 'b',\n * goal: 'cta_click',\n * });\n * }\n * }\n * ```\n */\nexport const useConversion = () => {\n return (params: ConversionParams): void => {\n if (process.env.INTLAYER_ANALYTICS_ENABLED === 'false' || !isEnabled) {\n return;\n }\n\n import('@intlayer/analytics')\n .then(({ getGlobalAnalyticsClient }) => {\n getGlobalAnalyticsClient()?.trackConversion(params);\n })\n .catch(() => {});\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,sBAAsB;AACjC,SAAQ,WAAmC;AACzC,MAAI,QAAQ,IAAI,+BAA+B,WAAW,CAACA,wCACzD;AAGF,SAAO,uBACJ,MAAM,EAAE,+BAA+B;AACtC,6BAA0B,EAAE,gBAAgB,OAAO;IACnD,CACD,YAAY,GAAG"}
@@ -0,0 +1,70 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
+ let _angular_core = require("@angular/core");
4
+ let _intlayer_analytics_isEnabled = require("@intlayer/analytics/isEnabled");
5
+
6
+ //#region src/analytics/useExperiment.ts
7
+ /**
8
+ * Assigns this session to a variant of an A/B experiment and records the
9
+ * exposure, scoped to `experimentKey`, so the backend can compute per-variant
10
+ * conversion rates against `useConversion` events.
11
+ *
12
+ * Assignment is deterministic per session (no server round-trip, stable across
13
+ * re-mounts). The exposure is recorded once per call.
14
+ *
15
+ * Must be called inside an Angular injection context (e.g. a component
16
+ * constructor or field initializer).
17
+ *
18
+ * @param experimentKey - Unique key identifying the experiment.
19
+ * @param variants - The candidate variant names; the first one is the control.
20
+ * @param weights - Optional relative weights, one per variant (e.g. `[9, 1]`).
21
+ * @returns The {@link ExperimentState} for this session.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * export class HeroComponent {
26
+ * experiment = useExperiment('homepage-hero', ['a', 'b']);
27
+ * content = useIntlayer('hero');
28
+ * }
29
+ * ```
30
+ */
31
+ const useExperiment = (experimentKey, variants, weights) => {
32
+ const variant = (0, _angular_core.signal)(variants[0] ?? "");
33
+ const isAssigned = (0, _angular_core.signal)(false);
34
+ if (process.env.INTLAYER_ANALYTICS_ENABLED === "false" || !_intlayer_analytics_isEnabled.isEnabled) return {
35
+ variant: variant.asReadonly(),
36
+ isAssigned: isAssigned.asReadonly()
37
+ };
38
+ const destroyRef = (0, _angular_core.inject)(_angular_core.DestroyRef, { optional: true });
39
+ let cancelled = false;
40
+ let initialized = false;
41
+ import("@intlayer/analytics").then(({ initAnalyticsClient }) => {
42
+ if (cancelled) return;
43
+ const client = initAnalyticsClient();
44
+ initialized = true;
45
+ const assigned = client.getVariant(experimentKey, variants, weights);
46
+ variant.set(assigned);
47
+ isAssigned.set(true);
48
+ client.trackContentExposure({
49
+ dictionaryKey: experimentKey,
50
+ keyPath: "",
51
+ nodeType: "experiment",
52
+ experimentKey,
53
+ variant: assigned
54
+ });
55
+ }).catch(() => {});
56
+ destroyRef?.onDestroy(() => {
57
+ cancelled = true;
58
+ import("@intlayer/analytics").then(({ stopAnalyticsClient }) => {
59
+ if (initialized) stopAnalyticsClient();
60
+ }).catch(() => {});
61
+ });
62
+ return {
63
+ variant: variant.asReadonly(),
64
+ isAssigned: isAssigned.asReadonly()
65
+ };
66
+ };
67
+
68
+ //#endregion
69
+ exports.useExperiment = useExperiment;
70
+ //# sourceMappingURL=useExperiment.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useExperiment.cjs","names":["isEnabled","DestroyRef"],"sources":["../../../src/analytics/useExperiment.ts"],"sourcesContent":["import { DestroyRef, inject, type Signal, signal } from '@angular/core';\nimport { isEnabled } from '@intlayer/analytics/isEnabled';\n\n/**\n * The state of an A/B experiment for the current session.\n */\nexport type ExperimentState = {\n /**\n * The variant assigned to this session. Until assignment resolves (and on\n * the server, or when analytics is disabled), this is the first variant —\n * treat the first variant as the control.\n */\n variant: Signal<string>;\n /**\n * `true` once the variant has been deterministically assigned and its\n * exposure recorded. Useful to defer rendering when a flash of the control\n * variant is not acceptable.\n */\n isAssigned: Signal<boolean>;\n};\n\n/**\n * Assigns this session to a variant of an A/B experiment and records the\n * exposure, scoped to `experimentKey`, so the backend can compute per-variant\n * conversion rates against `useConversion` events.\n *\n * Assignment is deterministic per session (no server round-trip, stable across\n * re-mounts). The exposure is recorded once per call.\n *\n * Must be called inside an Angular injection context (e.g. a component\n * constructor or field initializer).\n *\n * @param experimentKey - Unique key identifying the experiment.\n * @param variants - The candidate variant names; the first one is the control.\n * @param weights - Optional relative weights, one per variant (e.g. `[9, 1]`).\n * @returns The {@link ExperimentState} for this session.\n *\n * @example\n * ```ts\n * export class HeroComponent {\n * experiment = useExperiment('homepage-hero', ['a', 'b']);\n * content = useIntlayer('hero');\n * }\n * ```\n */\nexport const useExperiment = (\n experimentKey: string,\n variants: string[],\n weights?: number[]\n): ExperimentState => {\n const variant = signal(variants[0] ?? '');\n const isAssigned = signal(false);\n\n if (process.env.INTLAYER_ANALYTICS_ENABLED === 'false' || !isEnabled) {\n return {\n variant: variant.asReadonly(),\n isAssigned: isAssigned.asReadonly(),\n };\n }\n\n const destroyRef = inject(DestroyRef, { optional: true });\n\n let cancelled = false;\n let initialized = false;\n\n import('@intlayer/analytics')\n .then(({ initAnalyticsClient }) => {\n if (cancelled) return;\n\n // Ref-counted: guarantees a live client even when this call's import\n // resolves before the provider's. Balanced by stop on destroy.\n const client = initAnalyticsClient();\n initialized = true;\n\n const assigned = client.getVariant(experimentKey, variants, weights);\n variant.set(assigned);\n isAssigned.set(true);\n\n // Experiment-level exposure — the denominator of the conversion rate.\n client.trackContentExposure({\n dictionaryKey: experimentKey,\n keyPath: '',\n nodeType: 'experiment',\n experimentKey,\n variant: assigned,\n });\n })\n .catch(() => {\n /* chunk failed to load — control variant stays in place */\n });\n\n destroyRef?.onDestroy(() => {\n cancelled = true;\n import('@intlayer/analytics')\n .then(({ stopAnalyticsClient }) => {\n if (initialized) stopAnalyticsClient();\n })\n .catch(() => {});\n });\n\n return { variant: variant.asReadonly(), isAssigned: isAssigned.asReadonly() };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAa,iBACX,eACA,UACA,YACoB;CACpB,MAAM,oCAAiB,SAAS,MAAM,GAAG;CACzC,MAAM,uCAAoB,MAAM;AAEhC,KAAI,QAAQ,IAAI,+BAA+B,WAAW,CAACA,wCACzD,QAAO;EACL,SAAS,QAAQ,YAAY;EAC7B,YAAY,WAAW,YAAY;EACpC;CAGH,MAAM,uCAAoBC,0BAAY,EAAE,UAAU,MAAM,CAAC;CAEzD,IAAI,YAAY;CAChB,IAAI,cAAc;AAElB,QAAO,uBACJ,MAAM,EAAE,0BAA0B;AACjC,MAAI,UAAW;EAIf,MAAM,SAAS,qBAAqB;AACpC,gBAAc;EAEd,MAAM,WAAW,OAAO,WAAW,eAAe,UAAU,QAAQ;AACpE,UAAQ,IAAI,SAAS;AACrB,aAAW,IAAI,KAAK;AAGpB,SAAO,qBAAqB;GAC1B,eAAe;GACf,SAAS;GACT,UAAU;GACV;GACA,SAAS;GACV,CAAC;GACF,CACD,YAAY,GAEX;AAEJ,aAAY,gBAAgB;AAC1B,cAAY;AACZ,SAAO,uBACJ,MAAM,EAAE,0BAA0B;AACjC,OAAI,YAAa,sBAAqB;IACtC,CACD,YAAY,GAAG;GAClB;AAEF,QAAO;EAAE,SAAS,QAAQ,YAAY;EAAE,YAAY,WAAW,YAAY;EAAE"}
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_client_intlayerToken = require('./intlayerToken.cjs');
3
+ const require_analytics_useAnalytics = require('../analytics/useAnalytics.cjs');
3
4
  const require_editor_useEditor = require('../editor/useEditor.cjs');
4
5
 
5
6
  //#region src/client/installIntlayer.ts
@@ -28,10 +29,14 @@ const require_editor_useEditor = require('../editor/useEditor.cjs');
28
29
  */
29
30
  const provideIntlayer = (locale, isCookieEnabled = true) => {
30
31
  const client = installIntlayer(locale, isCookieEnabled);
31
- return [{
32
- provide: require_client_intlayerToken.INTLAYER_TOKEN,
33
- useValue: client
34
- }, require_editor_useEditor.provideIntlayerEditor(client)];
32
+ return [
33
+ {
34
+ provide: require_client_intlayerToken.INTLAYER_TOKEN,
35
+ useValue: client
36
+ },
37
+ require_editor_useEditor.provideIntlayerEditor(client),
38
+ require_analytics_useAnalytics.provideIntlayerAnalytics(client)
39
+ ];
35
40
  };
36
41
  /**
37
42
  * Helper to install the Intlayer provider.
@@ -1 +1 @@
1
- {"version":3,"file":"installIntlayer.cjs","names":["INTLAYER_TOKEN","provideIntlayerEditor","createIntlayerClient"],"sources":["../../../src/client/installIntlayer.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { provideIntlayerEditor } from '../editor/useEditor';\nimport {\n createIntlayerClient,\n INTLAYER_TOKEN,\n IntlayerProvider,\n} from './intlayerToken';\n\nexport { createIntlayerClient, INTLAYER_TOKEN, IntlayerProvider };\n\n/**\n * Provides Intlayer to your Angular application.\n *\n * Registers the Intlayer locale token **and** automatically starts the Intlayer\n * editor client (when the editor is enabled) via `provideAppInitializer`.\n *\n * This is the recommended way to set up Intlayer in `app.config.ts`.\n *\n * @param locale - Initial locale to use.\n * @param isCookieEnabled - Whether to store the locale in cookies.\n * @returns An array of Angular providers for Intlayer.\n *\n * @example\n * ```ts\n * // app.config.ts\n * import { ApplicationConfig } from '@angular/core';\n * import { provideIntlayer } from 'angular-intlayer';\n *\n * export const appConfig: ApplicationConfig = {\n * providers: [provideIntlayer()],\n * };\n * ```\n */\nexport const provideIntlayer = (\n locale?: LocalesValues,\n isCookieEnabled = true\n) => {\n const client = installIntlayer(locale, isCookieEnabled);\n\n return [\n { provide: INTLAYER_TOKEN, useValue: client },\n provideIntlayerEditor(client),\n ];\n};\n\n/**\n * Helper to install the Intlayer provider.\n */\nexport const installIntlayer = (\n locale?: LocalesValues,\n isCookieEnabled = true\n) => {\n return createIntlayerClient(locale, isCookieEnabled);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,mBACX,QACA,kBAAkB,SACf;CACH,MAAM,SAAS,gBAAgB,QAAQ,gBAAgB;AAEvD,QAAO,CACL;EAAE,SAASA;EAAgB,UAAU;EAAQ,EAC7CC,+CAAsB,OAAO,CAC9B;;;;;AAMH,MAAa,mBACX,QACA,kBAAkB,SACf;AACH,QAAOC,kDAAqB,QAAQ,gBAAgB"}
1
+ {"version":3,"file":"installIntlayer.cjs","names":["INTLAYER_TOKEN","provideIntlayerEditor","provideIntlayerAnalytics","createIntlayerClient"],"sources":["../../../src/client/installIntlayer.ts"],"sourcesContent":["import type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { provideIntlayerAnalytics } from '../analytics/useAnalytics';\nimport { provideIntlayerEditor } from '../editor/useEditor';\nimport {\n createIntlayerClient,\n INTLAYER_TOKEN,\n IntlayerProvider,\n} from './intlayerToken';\n\nexport { createIntlayerClient, INTLAYER_TOKEN, IntlayerProvider };\n\n/**\n * Provides Intlayer to your Angular application.\n *\n * Registers the Intlayer locale token **and** automatically starts the Intlayer\n * editor client (when the editor is enabled) via `provideAppInitializer`.\n *\n * This is the recommended way to set up Intlayer in `app.config.ts`.\n *\n * @param locale - Initial locale to use.\n * @param isCookieEnabled - Whether to store the locale in cookies.\n * @returns An array of Angular providers for Intlayer.\n *\n * @example\n * ```ts\n * // app.config.ts\n * import { ApplicationConfig } from '@angular/core';\n * import { provideIntlayer } from 'angular-intlayer';\n *\n * export const appConfig: ApplicationConfig = {\n * providers: [provideIntlayer()],\n * };\n * ```\n */\nexport const provideIntlayer = (\n locale?: LocalesValues,\n isCookieEnabled = true\n) => {\n const client = installIntlayer(locale, isCookieEnabled);\n\n return [\n { provide: INTLAYER_TOKEN, useValue: client },\n provideIntlayerEditor(client),\n provideIntlayerAnalytics(client),\n ];\n};\n\n/**\n * Helper to install the Intlayer provider.\n */\nexport const installIntlayer = (\n locale?: LocalesValues,\n isCookieEnabled = true\n) => {\n return createIntlayerClient(locale, isCookieEnabled);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAa,mBACX,QACA,kBAAkB,SACf;CACH,MAAM,SAAS,gBAAgB,QAAQ,gBAAgB;AAEvD,QAAO;EACL;GAAE,SAASA;GAAgB,UAAU;GAAQ;EAC7CC,+CAAsB,OAAO;EAC7BC,wDAAyB,OAAO;EACjC;;;;;AAMH,MAAa,mBACX,QACA,kBAAkB,SACf;AACH,QAAOC,kDAAqB,QAAQ,gBAAgB"}
@@ -3,6 +3,9 @@ const require_plugins = require('./plugins.cjs');
3
3
  const require_getIntlayer = require('./getIntlayer.cjs');
4
4
  const require_getDictionary = require('./getDictionary.cjs');
5
5
  const require_client_intlayerToken = require('./client/intlayerToken.cjs');
6
+ const require_analytics_useAnalytics = require('./analytics/useAnalytics.cjs');
7
+ const require_analytics_useConversion = require('./analytics/useConversion.cjs');
8
+ const require_analytics_useExperiment = require('./analytics/useExperiment.cjs');
6
9
  const require_client_installIntlayer = require('./client/installIntlayer.cjs');
7
10
  const require_client_useDictionary = require('./client/useDictionary.cjs');
8
11
  const require_client_useDictionaryAsync = require('./client/useDictionaryAsync.cjs');
@@ -33,9 +36,13 @@ exports.isUpdatableNode = require_client_useIntlayer.isUpdatableNode;
33
36
  exports.markdownPlugin = require_plugins.markdownPlugin;
34
37
  exports.markdownStringPlugin = require_plugins.markdownStringPlugin;
35
38
  exports.provideIntlayer = require_client_installIntlayer.provideIntlayer;
39
+ exports.provideIntlayerAnalytics = require_analytics_useAnalytics.provideIntlayerAnalytics;
40
+ exports.useAnalytics = require_analytics_useAnalytics.useAnalytics;
41
+ exports.useConversion = require_analytics_useConversion.useConversion;
36
42
  exports.useDictionary = require_client_useDictionary.useDictionary;
37
43
  exports.useDictionaryAsync = require_client_useDictionaryAsync.useDictionaryAsync;
38
44
  exports.useDictionaryDynamic = require_client_useDictionaryDynamic.useDictionaryDynamic;
45
+ exports.useExperiment = require_analytics_useExperiment.useExperiment;
39
46
  exports.useIntlayer = require_client_useIntlayer.useIntlayer;
40
47
  exports.useLoadDynamic = require_client_useLoadDynamic.useLoadDynamic;
41
48
  exports.useLocale = require_client_useLocale.useLocale;
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
3
  const require_renderIntlayerNode = require('./renderIntlayerNode.cjs');
4
+ const require_analytics_exposureSink = require('./analytics/exposureSink.cjs');
4
5
  const require_editor_ContentSelector_component = require('./editor/ContentSelector.component.cjs');
5
6
  let _intlayer_core_interpreter = require("@intlayer/core/interpreter");
6
7
  let _intlayer_config_built = require("@intlayer/config/built");
@@ -40,18 +41,26 @@ const createRuntimeWithOverides = (baseRuntime, overrides) => ({
40
41
  const intlayerNodePlugins = {
41
42
  id: "intlayer-node-plugin",
42
43
  canHandle: (node) => typeof node === "bigint" || typeof node === "string" || typeof node === "number",
43
- transform: (_node, { children, ...rest }) => require_renderIntlayerNode.renderIntlayerNode({
44
- ...rest,
45
- value: children,
46
- children: () => ({
47
- component: process.env.INTLAYER_EDITOR_ENABLED === "false" || !_intlayer_config_built.editor.enabled ? children : require_editor_ContentSelector_component.ContentSelectorWrapperComponent,
48
- props: {
49
- dictionaryKey: rest.dictionaryKey,
50
- keyPath: rest.keyPath
51
- },
52
- children
53
- })
54
- })
44
+ transform: (_node, { children, ...rest }) => {
45
+ if (process.env.INTLAYER_ANALYTICS_ENABLED !== "false") require_analytics_exposureSink.reportExposure({
46
+ dictionaryKey: rest.dictionaryKey,
47
+ keyPath: rest.keyPath,
48
+ locale: rest.locale,
49
+ nodeType: "text"
50
+ });
51
+ return require_renderIntlayerNode.renderIntlayerNode({
52
+ ...rest,
53
+ value: children,
54
+ children: () => ({
55
+ component: process.env.INTLAYER_EDITOR_ENABLED === "false" || !_intlayer_config_built.editor.enabled ? children : require_editor_ContentSelector_component.ContentSelectorWrapperComponent,
56
+ props: {
57
+ dictionaryKey: rest.dictionaryKey,
58
+ keyPath: rest.keyPath
59
+ },
60
+ children
61
+ })
62
+ });
63
+ }
55
64
  };
56
65
  /** Markdown string plugin. Replaces string node with a component that render the markdown. */
57
66
  const markdownStringPlugin = process.env.INTLAYER_NODE_TYPE_MARKDOWN === "false" ? _intlayer_core_interpreter.fallbackPlugin : {
@@ -1 +1 @@
1
- {"version":3,"file":"plugins.cjs","names":["renderIntlayerNode","editor","ContentSelectorWrapperComponent","fallbackPlugin","compile","NodeTypes","internationalization","enumerationPlugin","conditionPlugin","filePlugin","genderPlugin"],"sources":["../../src/plugins.ts"],"sourcesContent":["import { editor, internationalization } from '@intlayer/config/built';\nimport {\n conditionPlugin,\n type DeepTransformContent as DeepTransformContentCore,\n enumerationPlugin,\n fallbackPlugin,\n filePlugin,\n genderPlugin,\n type IInterpreterPluginState as IInterpreterPluginStateCore,\n nestedPlugin,\n type Plugins,\n pluralPlugin,\n translationPlugin,\n} from '@intlayer/core/interpreter';\nimport type { MarkdownContent } from '@intlayer/core/markdown';\nimport { compile, getMarkdownMetadata } from '@intlayer/core/markdown';\nimport type { HTMLContent, InsertionContent } from '@intlayer/core/transpiler';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { NodeType } from '@intlayer/types/nodeType';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { ContentSelectorWrapperComponent } from './editor/ContentSelector.component';\nimport { renderIntlayerNode } from './renderIntlayerNode';\n\nlet _markdownInstall: {\n htmlRuntime: any;\n useMarkdown: () => { renderMarkdown: (s: string, components?: any) => any };\n} | null = null;\nif (\n process.env.INTLAYER_NODE_TYPE_MARKDOWN !== 'false' ||\n process.env.INTLAYER_NODE_TYPE_HTML !== 'false'\n) {\n void import('./markdown/installIntlayerMarkdown').then((m) => {\n _markdownInstall = m as any;\n });\n}\n\n/** ---------------------------------------------\n * UTILS\n * --------------------------------------------- */\n\nconst createRuntimeWithOverides = (baseRuntime: any, overrides: any) => ({\n ...baseRuntime,\n createElement: (tag: string, props: any, ...children: any[]) => {\n const override = overrides?.[tag];\n\n if (override) {\n const newProps = { ...props, ...override };\n\n // Merge class attributes intelligently\n const originalClass = props?.class || props?.className;\n const overrideClass = override.class || override.className;\n\n if (originalClass && overrideClass) {\n newProps.class = `${originalClass} ${overrideClass}`;\n newProps.className = undefined;\n }\n\n return baseRuntime.createElement(tag, newProps, ...children);\n }\n\n return baseRuntime.createElement(tag, props, ...children);\n },\n});\n\n/** ---------------------------------------------\n * INTLAYER NODE PLUGIN\n * --------------------------------------------- */\n\nexport type IntlayerNodeCond<T> = T extends number | string\n ? IntlayerNode<T>\n : never;\n\nexport interface IntlayerNode<T, P = {}> {\n value: T;\n children?: any;\n additionalProps?: P;\n}\n\n/** Translation plugin. Replaces node with a locale string if nodeType = Translation. */\nexport const intlayerNodePlugins: Plugins = {\n id: 'intlayer-node-plugin',\n canHandle: (node) =>\n typeof node === 'bigint' ||\n typeof node === 'string' ||\n typeof node === 'number',\n transform: (_node, { children, ...rest }) =>\n renderIntlayerNode({\n ...rest,\n value: children,\n children: () => ({\n component:\n process.env.INTLAYER_EDITOR_ENABLED === 'false' || !editor.enabled\n ? children\n : ContentSelectorWrapperComponent,\n props: {\n dictionaryKey: rest.dictionaryKey,\n keyPath: rest.keyPath,\n },\n children: children,\n }),\n }),\n};\n\n/**\n * MARKDOWN PLUGIN\n */\n\nexport type MarkdownStringCond<T> = T extends string\n ? IntlayerNode<string, { metadata: DeepTransformContent<string> }>\n : never;\n\n/** Markdown string plugin. Replaces string node with a component that render the markdown. */\nexport const markdownStringPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_MARKDOWN === 'false'\n ? fallbackPlugin\n : {\n id: 'markdown-string-plugin',\n canHandle: (node) => typeof node === 'string',\n transform: (node: string, props, deepTransformNode) => {\n const {\n plugins, // Removed to avoid next error - Functions cannot be passed directly to Client Components\n ...rest\n } = props;\n\n const metadata = getMarkdownMetadata(node) ?? {};\n\n const metadataPlugins: Plugins = {\n id: 'markdown-metadata-plugin',\n canHandle: (metadataNode) =>\n typeof metadataNode === 'string' ||\n typeof metadataNode === 'number' ||\n typeof metadataNode === 'boolean' ||\n !metadataNode,\n transform: (metadataNode, props) =>\n renderIntlayerNode({\n ...props,\n value: metadataNode,\n children: node,\n }),\n };\n\n // Transform metadata while keeping the same structure\n const metadataNodes = deepTransformNode(metadata, {\n plugins: [metadataPlugins],\n dictionaryKey: rest.dictionaryKey,\n keyPath: [],\n });\n\n const render = (components?: any) =>\n renderIntlayerNode({\n ...rest,\n value: node,\n children:\n process.env.INTLAYER_EDITOR_ENABLED === 'false' ||\n !editor.enabled\n ? () => {\n const { renderMarkdown } =\n _markdownInstall?.useMarkdown() ?? {\n renderMarkdown: () => node,\n };\n return renderMarkdown(node, components);\n }\n : () => ({\n component: ContentSelectorWrapperComponent,\n props: {\n dictionaryKey: rest.dictionaryKey,\n keyPath: rest.keyPath,\n ...components,\n },\n children: () => {\n const { renderMarkdown } =\n _markdownInstall?.useMarkdown() ?? {\n renderMarkdown: () => node,\n };\n return renderMarkdown(node, components);\n },\n }),\n additionalProps: {\n metadata: metadataNodes,\n },\n });\n\n const createProxy = (element: any, components?: any) =>\n new Proxy(element, {\n get(target, prop, receiver) {\n if (prop === 'value') {\n return node;\n }\n if (prop === 'metadata') {\n return metadataNodes;\n }\n\n if (prop === 'toString') {\n return () => {\n const htmlRuntime = _markdownInstall?.htmlRuntime;\n if (!htmlRuntime || !compile) return node;\n const runtime = components\n ? createRuntimeWithOverides(htmlRuntime, components)\n : htmlRuntime;\n return compile(node, { runtime }) as string;\n };\n }\n\n if (prop === Symbol.toPrimitive) {\n return () => {\n const htmlRuntime = _markdownInstall?.htmlRuntime;\n if (!htmlRuntime || !compile) return node;\n const runtime = components\n ? createRuntimeWithOverides(htmlRuntime, components)\n : htmlRuntime;\n return compile(node, { runtime }) as string;\n };\n }\n\n if (prop === 'use') {\n return (newComponents?: any) => {\n const mergedComponents = {\n ...components,\n ...newComponents,\n };\n return createProxy(\n render(mergedComponents),\n mergedComponents\n );\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n }) as any;\n\n return createProxy(render() as any);\n },\n };\n\nexport type MarkdownCond<T, _S, _L extends LocalesValues> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.MARKDOWN]: infer M;\n tags?: infer U;\n metadata?: infer V;\n}\n ? IntlayerNode<\n M,\n {\n use: (components?: Record<keyof U, any>) => any;\n metadata: DeepTransformContent<V>;\n }\n >\n : never;\n\nexport const markdownPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_MARKDOWN === 'false'\n ? fallbackPlugin\n : {\n id: 'markdown-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.MARKDOWN,\n transform: (node: MarkdownContent, props, deepTransformNode) => {\n const newKeyPath: KeyPath[] = [\n ...props.keyPath,\n {\n type: NodeTypes.MARKDOWN,\n },\n ];\n\n const children = node[NodeTypes.MARKDOWN];\n\n return deepTransformNode(children, {\n ...props,\n children,\n keyPath: newKeyPath,\n plugins: [markdownStringPlugin, ...(props.plugins ?? [])],\n });\n },\n };\n\n/** ---------------------------------------------\n * HTML PLUGIN\n * --------------------------------------------- */\n\n/**\n * HTML conditional type.\n *\n * This ensures type safety:\n * - `html('<div>Hello <CustomComponent /></div>').use({ CustomComponent: ... })` - optional but typed\n */\nexport type HTMLPluginCond<T, _S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.HTML]: infer I;\n tags?: infer U;\n}\n ? IntlayerNode<\n I,\n {\n use: (components?: Record<keyof U, any>) => any;\n }\n >\n : never;\n\n/** HTML plugin. Replaces node with a function that takes components => IntlayerNode. */\nexport const htmlPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_HTML === 'false'\n ? fallbackPlugin\n : {\n id: 'html-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.HTML,\n\n transform: (node: HTMLContent<string>, props) => {\n const html = node[NodeTypes.HTML];\n const { plugins, ...rest } = props;\n\n // Type-safe render function that accepts properly typed components\n const render = (userComponents?: any) =>\n renderIntlayerNode({\n ...rest,\n value: html,\n children:\n process.env.INTLAYER_EDITOR_ENABLED === 'false' ||\n !editor.enabled\n ? html\n : () => ({\n component: ContentSelectorWrapperComponent,\n props: {\n dictionaryKey: rest.dictionaryKey,\n keyPath: rest.keyPath,\n ...userComponents,\n },\n children: html,\n }),\n });\n\n const createProxy = (element: any, components?: any) =>\n new Proxy(element, {\n get(target, prop, receiver) {\n if (prop === 'value') {\n return html;\n }\n\n if (prop === 'toString') {\n return () => {\n if (\n !components ||\n (typeof components === 'object' &&\n Object.keys(components).length === 0)\n ) {\n return String(html);\n }\n const htmlRuntime = _markdownInstall?.htmlRuntime;\n if (!htmlRuntime || !compile) return String(html);\n const runtime = createRuntimeWithOverides(\n htmlRuntime,\n components\n );\n return compile(html, { runtime }) as string;\n };\n }\n\n if (prop === Symbol.toPrimitive) {\n return () => {\n if (\n !components ||\n (typeof components === 'object' &&\n Object.keys(components).length === 0)\n ) {\n return String(html);\n }\n const htmlRuntime = _markdownInstall?.htmlRuntime;\n if (!htmlRuntime || !compile) return String(html);\n const runtime = createRuntimeWithOverides(\n htmlRuntime,\n components\n );\n return compile(html, { runtime }) as string;\n };\n }\n\n if (prop === 'use') {\n // Return a properly typed function based on custom components\n return (userComponents?: any) => {\n const mergedComponents = {\n ...components,\n ...userComponents,\n };\n return createProxy(\n render(mergedComponents),\n mergedComponents\n );\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n }) as any;\n\n return createProxy(render() as any);\n },\n };\n\n/** ---------------------------------------------\n * INSERTION PLUGIN\n * --------------------------------------------- */\n\n/**\n * Insertion conditional type.\n */\nexport type InsertionPluginCond<T> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.INSERTION]: infer _I;\n}\n ? (args: Record<string, string | number>) => string\n : never;\n\nexport const insertionPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_INSERTION === 'false'\n ? fallbackPlugin\n : {\n id: 'insertion-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.INSERTION,\n transform: (node: InsertionContent, props) => {\n const { plugins, ...rest } = props;\n\n // Return a function that performs the interpolation\n const render = (args: Record<string, string | number> = {}) => {\n let text = node[NodeTypes.INSERTION] as string;\n if (args) {\n Object.entries(args).forEach(([key, value]) => {\n text = text.replace(\n new RegExp(`{{\\\\s*${key}\\\\s*}}`, 'g'),\n String(value)\n );\n });\n }\n return text;\n };\n\n return renderIntlayerNode({\n ...rest,\n value: render as any,\n children: render,\n });\n },\n };\n\nexport interface IInterpreterPluginAngular<T, S, L extends LocalesValues> {\n angularIntlayerNode: IntlayerNodeCond<T>;\n angularMarkdown: MarkdownCond<T, S, L>;\n angularHtml: HTMLPluginCond<T, S, L>;\n angularInsertion: InsertionPluginCond<T>;\n}\n\n/**\n * Insert this type as param of `DeepTransformContent` to avoid `intlayer` package pollution.\n *\n * Otherwise the the `angular-intlayer` plugins will override the types of `intlayer` functions.\n */\nexport type IInterpreterPluginState = Omit<\n IInterpreterPluginStateCore,\n 'insertion' // Remove insertion type from core package\n> & {\n angularIntlayerNode: true;\n angularMarkdown: true;\n angularHtml: true;\n angularInsertion: true;\n};\n\nexport type DeepTransformContent<\n T,\n L extends LocalesValues = DeclaredLocales,\n> = DeepTransformContentCore<T, IInterpreterPluginState, L>;\n\nconst pluginsCache = new Map<string, Plugins[]>();\n\n/**\n * Get the plugins array for Angular content transformation.\n * This function is used by both getIntlayer and getDictionary to ensure consistent plugin configuration.\n */\nexport const getPlugins = (\n locale?: LocalesValues,\n fallback: boolean = true\n): Plugins[] => {\n const currentLocale = locale ?? internationalization.defaultLocale;\n const cacheKey = `${currentLocale}_${fallback}`;\n\n if (pluginsCache.has(cacheKey)) {\n return pluginsCache.get(cacheKey)!;\n }\n\n const plugins = [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n pluralPlugin(locale ?? internationalization.defaultLocale),\n conditionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n intlayerNodePlugins,\n markdownPlugin,\n htmlPlugin,\n insertionPlugin,\n ] as Plugins[];\n\n pluginsCache.set(cacheKey, plugins);\n\n return plugins;\n};\n"],"mappings":";;;;;;;;;;;AA2BA,IAAI,mBAGO;AACX,IACE,QAAQ,IAAI,gCAAgC,WAC5C,QAAQ,IAAI,4BAA4B,QAExC,sCAAK,2CAA6C,MAAM,MAAM;AAC5D,oBAAmB;EACnB;;;;AAOJ,MAAM,6BAA6B,aAAkB,eAAoB;CACvE,GAAG;CACH,gBAAgB,KAAa,OAAY,GAAG,aAAoB;EAC9D,MAAM,WAAW,YAAY;AAE7B,MAAI,UAAU;GACZ,MAAM,WAAW;IAAE,GAAG;IAAO,GAAG;IAAU;GAG1C,MAAM,gBAAgB,OAAO,SAAS,OAAO;GAC7C,MAAM,gBAAgB,SAAS,SAAS,SAAS;AAEjD,OAAI,iBAAiB,eAAe;AAClC,aAAS,QAAQ,GAAG,cAAc,GAAG;AACrC,aAAS,YAAY;;AAGvB,UAAO,YAAY,cAAc,KAAK,UAAU,GAAG,SAAS;;AAG9D,SAAO,YAAY,cAAc,KAAK,OAAO,GAAG,SAAS;;CAE5D;;AAiBD,MAAa,sBAA+B;CAC1C,IAAI;CACJ,YAAY,SACV,OAAO,SAAS,YAChB,OAAO,SAAS,YAChB,OAAO,SAAS;CAClB,YAAY,OAAO,EAAE,UAAU,GAAG,WAChCA,8CAAmB;EACjB,GAAG;EACH,OAAO;EACP,iBAAiB;GACf,WACE,QAAQ,IAAI,4BAA4B,WAAW,CAACC,8BAAO,UACvD,WACAC;GACN,OAAO;IACL,eAAe,KAAK;IACpB,SAAS,KAAK;IACf;GACS;GACX;EACF,CAA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;AAC7C,WAAO,KAAK,QACV,IAAI,OAAO,SAAS,IAAI,SAAS,IAAI,EACrC,OAAO,MAAM,CACd;KACD;AAEJ,UAAO;;AAGT,SAAOL,8CAAmB;GACxB,GAAG;GACH,OAAO;GACP,UAAU;GACX,CAAC;;CAEL;AA6BP,MAAM,+BAAe,IAAI,KAAwB;;;;;AAMjD,MAAa,cACX,QACA,WAAoB,SACN;CAEd,MAAM,WAAW,GADK,UAAUM,4CAAqB,cACnB,GAAG;AAErC,KAAI,aAAa,IAAI,SAAS,CAC5B,QAAO,aAAa,IAAI,SAAS;CAGnC,MAAM,UAAU;oDAEZ,UAAUA,4CAAqB,eAC/B,WAAWA,4CAAqB,gBAAgB,OACjD;EACDC;+CACa,UAAUD,4CAAqB,cAAc;EAC1DE;+CACa,UAAUF,4CAAqB,cAAc;EAC1DG;EACAC;EACA;EACA;EACA;EACA;EACD;AAED,cAAa,IAAI,UAAU,QAAQ;AAEnC,QAAO"}
1
+ {"version":3,"file":"plugins.cjs","names":["renderIntlayerNode","editor","ContentSelectorWrapperComponent","fallbackPlugin","compile","NodeTypes","internationalization","enumerationPlugin","conditionPlugin","filePlugin","genderPlugin"],"sources":["../../src/plugins.ts"],"sourcesContent":["import { editor, internationalization } from '@intlayer/config/built';\nimport {\n conditionPlugin,\n type DeepTransformContent as DeepTransformContentCore,\n enumerationPlugin,\n fallbackPlugin,\n filePlugin,\n genderPlugin,\n type IInterpreterPluginState as IInterpreterPluginStateCore,\n nestedPlugin,\n type Plugins,\n pluralPlugin,\n translationPlugin,\n} from '@intlayer/core/interpreter';\nimport type { MarkdownContent } from '@intlayer/core/markdown';\nimport { compile, getMarkdownMetadata } from '@intlayer/core/markdown';\nimport type { HTMLContent, InsertionContent } from '@intlayer/core/transpiler';\nimport type { KeyPath } from '@intlayer/types/keyPath';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { NodeType } from '@intlayer/types/nodeType';\nimport * as NodeTypes from '@intlayer/types/nodeType';\nimport { reportExposure } from './analytics/exposureSink';\nimport { ContentSelectorWrapperComponent } from './editor/ContentSelector.component';\nimport { renderIntlayerNode } from './renderIntlayerNode';\n\nlet _markdownInstall: {\n htmlRuntime: any;\n useMarkdown: () => { renderMarkdown: (s: string, components?: any) => any };\n} | null = null;\nif (\n process.env.INTLAYER_NODE_TYPE_MARKDOWN !== 'false' ||\n process.env.INTLAYER_NODE_TYPE_HTML !== 'false'\n) {\n void import('./markdown/installIntlayerMarkdown').then((m) => {\n _markdownInstall = m as any;\n });\n}\n\n/** ---------------------------------------------\n * UTILS\n * --------------------------------------------- */\n\nconst createRuntimeWithOverides = (baseRuntime: any, overrides: any) => ({\n ...baseRuntime,\n createElement: (tag: string, props: any, ...children: any[]) => {\n const override = overrides?.[tag];\n\n if (override) {\n const newProps = { ...props, ...override };\n\n // Merge class attributes intelligently\n const originalClass = props?.class || props?.className;\n const overrideClass = override.class || override.className;\n\n if (originalClass && overrideClass) {\n newProps.class = `${originalClass} ${overrideClass}`;\n newProps.className = undefined;\n }\n\n return baseRuntime.createElement(tag, newProps, ...children);\n }\n\n return baseRuntime.createElement(tag, props, ...children);\n },\n});\n\n/** ---------------------------------------------\n * INTLAYER NODE PLUGIN\n * --------------------------------------------- */\n\nexport type IntlayerNodeCond<T> = T extends number | string\n ? IntlayerNode<T>\n : never;\n\nexport interface IntlayerNode<T, P = {}> {\n value: T;\n children?: any;\n additionalProps?: P;\n}\n\n/** Translation plugin. Replaces node with a locale string if nodeType = Translation. */\nexport const intlayerNodePlugins: Plugins = {\n id: 'intlayer-node-plugin',\n canHandle: (node) =>\n typeof node === 'bigint' ||\n typeof node === 'string' ||\n typeof node === 'number',\n transform: (_node, { children, ...rest }) => {\n // Node-level analytics: record which content is resolved for display.\n // No-op (and dead-code-eliminated) when analytics is disabled.\n if (process.env.INTLAYER_ANALYTICS_ENABLED !== 'false') {\n reportExposure({\n dictionaryKey: rest.dictionaryKey,\n keyPath: rest.keyPath,\n locale: rest.locale,\n nodeType: 'text',\n });\n }\n\n return renderIntlayerNode({\n ...rest,\n value: children,\n children: () => ({\n component:\n process.env.INTLAYER_EDITOR_ENABLED === 'false' || !editor.enabled\n ? children\n : ContentSelectorWrapperComponent,\n props: {\n dictionaryKey: rest.dictionaryKey,\n keyPath: rest.keyPath,\n },\n children: children,\n }),\n });\n },\n};\n\n/**\n * MARKDOWN PLUGIN\n */\n\nexport type MarkdownStringCond<T> = T extends string\n ? IntlayerNode<string, { metadata: DeepTransformContent<string> }>\n : never;\n\n/** Markdown string plugin. Replaces string node with a component that render the markdown. */\nexport const markdownStringPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_MARKDOWN === 'false'\n ? fallbackPlugin\n : {\n id: 'markdown-string-plugin',\n canHandle: (node) => typeof node === 'string',\n transform: (node: string, props, deepTransformNode) => {\n const {\n plugins, // Removed to avoid next error - Functions cannot be passed directly to Client Components\n ...rest\n } = props;\n\n const metadata = getMarkdownMetadata(node) ?? {};\n\n const metadataPlugins: Plugins = {\n id: 'markdown-metadata-plugin',\n canHandle: (metadataNode) =>\n typeof metadataNode === 'string' ||\n typeof metadataNode === 'number' ||\n typeof metadataNode === 'boolean' ||\n !metadataNode,\n transform: (metadataNode, props) =>\n renderIntlayerNode({\n ...props,\n value: metadataNode,\n children: node,\n }),\n };\n\n // Transform metadata while keeping the same structure\n const metadataNodes = deepTransformNode(metadata, {\n plugins: [metadataPlugins],\n dictionaryKey: rest.dictionaryKey,\n keyPath: [],\n });\n\n const render = (components?: any) =>\n renderIntlayerNode({\n ...rest,\n value: node,\n children:\n process.env.INTLAYER_EDITOR_ENABLED === 'false' ||\n !editor.enabled\n ? () => {\n const { renderMarkdown } =\n _markdownInstall?.useMarkdown() ?? {\n renderMarkdown: () => node,\n };\n return renderMarkdown(node, components);\n }\n : () => ({\n component: ContentSelectorWrapperComponent,\n props: {\n dictionaryKey: rest.dictionaryKey,\n keyPath: rest.keyPath,\n ...components,\n },\n children: () => {\n const { renderMarkdown } =\n _markdownInstall?.useMarkdown() ?? {\n renderMarkdown: () => node,\n };\n return renderMarkdown(node, components);\n },\n }),\n additionalProps: {\n metadata: metadataNodes,\n },\n });\n\n const createProxy = (element: any, components?: any) =>\n new Proxy(element, {\n get(target, prop, receiver) {\n if (prop === 'value') {\n return node;\n }\n if (prop === 'metadata') {\n return metadataNodes;\n }\n\n if (prop === 'toString') {\n return () => {\n const htmlRuntime = _markdownInstall?.htmlRuntime;\n if (!htmlRuntime || !compile) return node;\n const runtime = components\n ? createRuntimeWithOverides(htmlRuntime, components)\n : htmlRuntime;\n return compile(node, { runtime }) as string;\n };\n }\n\n if (prop === Symbol.toPrimitive) {\n return () => {\n const htmlRuntime = _markdownInstall?.htmlRuntime;\n if (!htmlRuntime || !compile) return node;\n const runtime = components\n ? createRuntimeWithOverides(htmlRuntime, components)\n : htmlRuntime;\n return compile(node, { runtime }) as string;\n };\n }\n\n if (prop === 'use') {\n return (newComponents?: any) => {\n const mergedComponents = {\n ...components,\n ...newComponents,\n };\n return createProxy(\n render(mergedComponents),\n mergedComponents\n );\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n }) as any;\n\n return createProxy(render() as any);\n },\n };\n\nexport type MarkdownCond<T, _S, _L extends LocalesValues> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.MARKDOWN]: infer M;\n tags?: infer U;\n metadata?: infer V;\n}\n ? IntlayerNode<\n M,\n {\n use: (components?: Record<keyof U, any>) => any;\n metadata: DeepTransformContent<V>;\n }\n >\n : never;\n\nexport const markdownPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_MARKDOWN === 'false'\n ? fallbackPlugin\n : {\n id: 'markdown-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.MARKDOWN,\n transform: (node: MarkdownContent, props, deepTransformNode) => {\n const newKeyPath: KeyPath[] = [\n ...props.keyPath,\n {\n type: NodeTypes.MARKDOWN,\n },\n ];\n\n const children = node[NodeTypes.MARKDOWN];\n\n return deepTransformNode(children, {\n ...props,\n children,\n keyPath: newKeyPath,\n plugins: [markdownStringPlugin, ...(props.plugins ?? [])],\n });\n },\n };\n\n/** ---------------------------------------------\n * HTML PLUGIN\n * --------------------------------------------- */\n\n/**\n * HTML conditional type.\n *\n * This ensures type safety:\n * - `html('<div>Hello <CustomComponent /></div>').use({ CustomComponent: ... })` - optional but typed\n */\nexport type HTMLPluginCond<T, _S, _L> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.HTML]: infer I;\n tags?: infer U;\n}\n ? IntlayerNode<\n I,\n {\n use: (components?: Record<keyof U, any>) => any;\n }\n >\n : never;\n\n/** HTML plugin. Replaces node with a function that takes components => IntlayerNode. */\nexport const htmlPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_HTML === 'false'\n ? fallbackPlugin\n : {\n id: 'html-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.HTML,\n\n transform: (node: HTMLContent<string>, props) => {\n const html = node[NodeTypes.HTML];\n const { plugins, ...rest } = props;\n\n // Type-safe render function that accepts properly typed components\n const render = (userComponents?: any) =>\n renderIntlayerNode({\n ...rest,\n value: html,\n children:\n process.env.INTLAYER_EDITOR_ENABLED === 'false' ||\n !editor.enabled\n ? html\n : () => ({\n component: ContentSelectorWrapperComponent,\n props: {\n dictionaryKey: rest.dictionaryKey,\n keyPath: rest.keyPath,\n ...userComponents,\n },\n children: html,\n }),\n });\n\n const createProxy = (element: any, components?: any) =>\n new Proxy(element, {\n get(target, prop, receiver) {\n if (prop === 'value') {\n return html;\n }\n\n if (prop === 'toString') {\n return () => {\n if (\n !components ||\n (typeof components === 'object' &&\n Object.keys(components).length === 0)\n ) {\n return String(html);\n }\n const htmlRuntime = _markdownInstall?.htmlRuntime;\n if (!htmlRuntime || !compile) return String(html);\n const runtime = createRuntimeWithOverides(\n htmlRuntime,\n components\n );\n return compile(html, { runtime }) as string;\n };\n }\n\n if (prop === Symbol.toPrimitive) {\n return () => {\n if (\n !components ||\n (typeof components === 'object' &&\n Object.keys(components).length === 0)\n ) {\n return String(html);\n }\n const htmlRuntime = _markdownInstall?.htmlRuntime;\n if (!htmlRuntime || !compile) return String(html);\n const runtime = createRuntimeWithOverides(\n htmlRuntime,\n components\n );\n return compile(html, { runtime }) as string;\n };\n }\n\n if (prop === 'use') {\n // Return a properly typed function based on custom components\n return (userComponents?: any) => {\n const mergedComponents = {\n ...components,\n ...userComponents,\n };\n return createProxy(\n render(mergedComponents),\n mergedComponents\n );\n };\n }\n\n return Reflect.get(target, prop, receiver);\n },\n }) as any;\n\n return createProxy(render() as any);\n },\n };\n\n/** ---------------------------------------------\n * INSERTION PLUGIN\n * --------------------------------------------- */\n\n/**\n * Insertion conditional type.\n */\nexport type InsertionPluginCond<T> = T extends {\n nodeType: NodeType | string;\n [NodeTypes.INSERTION]: infer _I;\n}\n ? (args: Record<string, string | number>) => string\n : never;\n\nexport const insertionPlugin: Plugins =\n process.env.INTLAYER_NODE_TYPE_INSERTION === 'false'\n ? fallbackPlugin\n : {\n id: 'insertion-plugin',\n canHandle: (node) =>\n typeof node === 'object' && node?.nodeType === NodeTypes.INSERTION,\n transform: (node: InsertionContent, props) => {\n const { plugins, ...rest } = props;\n\n // Return a function that performs the interpolation\n const render = (args: Record<string, string | number> = {}) => {\n let text = node[NodeTypes.INSERTION] as string;\n if (args) {\n Object.entries(args).forEach(([key, value]) => {\n text = text.replace(\n new RegExp(`{{\\\\s*${key}\\\\s*}}`, 'g'),\n String(value)\n );\n });\n }\n return text;\n };\n\n return renderIntlayerNode({\n ...rest,\n value: render as any,\n children: render,\n });\n },\n };\n\nexport interface IInterpreterPluginAngular<T, S, L extends LocalesValues> {\n angularIntlayerNode: IntlayerNodeCond<T>;\n angularMarkdown: MarkdownCond<T, S, L>;\n angularHtml: HTMLPluginCond<T, S, L>;\n angularInsertion: InsertionPluginCond<T>;\n}\n\n/**\n * Insert this type as param of `DeepTransformContent` to avoid `intlayer` package pollution.\n *\n * Otherwise the the `angular-intlayer` plugins will override the types of `intlayer` functions.\n */\nexport type IInterpreterPluginState = Omit<\n IInterpreterPluginStateCore,\n 'insertion' // Remove insertion type from core package\n> & {\n angularIntlayerNode: true;\n angularMarkdown: true;\n angularHtml: true;\n angularInsertion: true;\n};\n\nexport type DeepTransformContent<\n T,\n L extends LocalesValues = DeclaredLocales,\n> = DeepTransformContentCore<T, IInterpreterPluginState, L>;\n\nconst pluginsCache = new Map<string, Plugins[]>();\n\n/**\n * Get the plugins array for Angular content transformation.\n * This function is used by both getIntlayer and getDictionary to ensure consistent plugin configuration.\n */\nexport const getPlugins = (\n locale?: LocalesValues,\n fallback: boolean = true\n): Plugins[] => {\n const currentLocale = locale ?? internationalization.defaultLocale;\n const cacheKey = `${currentLocale}_${fallback}`;\n\n if (pluginsCache.has(cacheKey)) {\n return pluginsCache.get(cacheKey)!;\n }\n\n const plugins = [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n pluralPlugin(locale ?? internationalization.defaultLocale),\n conditionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n intlayerNodePlugins,\n markdownPlugin,\n htmlPlugin,\n insertionPlugin,\n ] as Plugins[];\n\n pluginsCache.set(cacheKey, plugins);\n\n return plugins;\n};\n"],"mappings":";;;;;;;;;;;;AA4BA,IAAI,mBAGO;AACX,IACE,QAAQ,IAAI,gCAAgC,WAC5C,QAAQ,IAAI,4BAA4B,QAExC,sCAAK,2CAA6C,MAAM,MAAM;AAC5D,oBAAmB;EACnB;;;;AAOJ,MAAM,6BAA6B,aAAkB,eAAoB;CACvE,GAAG;CACH,gBAAgB,KAAa,OAAY,GAAG,aAAoB;EAC9D,MAAM,WAAW,YAAY;AAE7B,MAAI,UAAU;GACZ,MAAM,WAAW;IAAE,GAAG;IAAO,GAAG;IAAU;GAG1C,MAAM,gBAAgB,OAAO,SAAS,OAAO;GAC7C,MAAM,gBAAgB,SA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AI,UAAU,QAAQ;AAEnC,QAAO"}
@@ -0,0 +1,24 @@
1
+ //#region src/analytics/exposureSink.ts
2
+ let sink = null;
3
+ /**
4
+ * Installs (or clears) the exposure sink. `useAnalytics` sets this once the
5
+ * analytics client has loaded, and clears it on unmount.
6
+ *
7
+ * @param next - The sink to install, or `null` to clear.
8
+ */
9
+ const setExposureSink = (next) => {
10
+ sink = next;
11
+ };
12
+ /**
13
+ * Forwards a content exposure to the installed sink. A cheap null-check when
14
+ * analytics is not running, so it is safe to call from every node resolution.
15
+ *
16
+ * @param input - The node metadata to report.
17
+ */
18
+ const reportExposure = (input) => {
19
+ sink?.(input);
20
+ };
21
+
22
+ //#endregion
23
+ export { reportExposure, setExposureSink };
24
+ //# sourceMappingURL=exposureSink.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exposureSink.mjs","names":[],"sources":["../../../src/analytics/exposureSink.ts"],"sourcesContent":["import type { KeyPath } from '@intlayer/types/keyPath';\n\n/**\n * Node metadata reported for a content exposure. Kept dependency-free (types\n * only) so the interpreter hot path in `plugins.ts` never statically imports\n * `@intlayer/analytics` — the package stays optional and tree-shakeable.\n */\nexport type ExposureInput = {\n dictionaryKey: string;\n keyPath: KeyPath[];\n locale?: string;\n nodeType?: string;\n};\n\n/** Consumer of exposure reports, installed by `useAnalytics` after init. */\nexport type ExposureSink = (input: ExposureInput) => void;\n\nlet sink: ExposureSink | null = null;\n\n/**\n * Installs (or clears) the exposure sink. `useAnalytics` sets this once the\n * analytics client has loaded, and clears it on unmount.\n *\n * @param next - The sink to install, or `null` to clear.\n */\nexport const setExposureSink = (next: ExposureSink | null): void => {\n sink = next;\n};\n\n/**\n * Forwards a content exposure to the installed sink. A cheap null-check when\n * analytics is not running, so it is safe to call from every node resolution.\n *\n * @param input - The node metadata to report.\n */\nexport const reportExposure = (input: ExposureInput): void => {\n sink?.(input);\n};\n"],"mappings":";AAiBA,IAAI,OAA4B;;;;;;;AAQhC,MAAa,mBAAmB,SAAoC;AAClE,QAAO;;;;;;;;AAST,MAAa,kBAAkB,UAA+B;AAC5D,QAAO,MAAM"}
@@ -0,0 +1,5 @@
1
+ import { provideIntlayerAnalytics, useAnalytics } from "./useAnalytics.mjs";
2
+ import { useConversion } from "./useConversion.mjs";
3
+ import { useExperiment } from "./useExperiment.mjs";
4
+
5
+ export { provideIntlayerAnalytics, useAnalytics, useConversion, useExperiment };
@@ -0,0 +1,82 @@
1
+ import { setExposureSink } from "./exposureSink.mjs";
2
+ import { INTLAYER_TOKEN } from "../client/intlayerToken.mjs";
3
+ import { DestroyRef, Injector, effect, inject, provideAppInitializer, runInInjectionContext, signal } from "@angular/core";
4
+ import { isEnabled } from "@intlayer/analytics/isEnabled";
5
+
6
+ //#region src/analytics/useAnalytics.ts
7
+ /**
8
+ * Initializes the Intlayer analytics client singleton when analytics is
9
+ * enabled (mirrors {@link useEditor}). Records an initial page view, keeps the
10
+ * client aware of the current locale, and wires node-level content exposures.
11
+ *
12
+ * Must be called inside an Angular injection context (e.g. a component
13
+ * constructor, `provideAppInitializer`, or `runInInjectionContext`).
14
+ *
15
+ * @param client - The IntlayerProvider instance to sync locale from.
16
+ * When omitted the function injects `INTLAYER_TOKEN` from the DI tree,
17
+ * so it still works when called directly from a component.
18
+ */
19
+ const useAnalytics = (client) => {
20
+ if (process.env.INTLAYER_ANALYTICS_ENABLED === "false" || !isEnabled) return;
21
+ const destroyRef = inject(DestroyRef, { optional: true });
22
+ const injector = inject(Injector);
23
+ const resolvedClient = client ?? inject(INTLAYER_TOKEN, { optional: true });
24
+ const analyticsClient = signal(null);
25
+ let stopped = false;
26
+ let initialized = false;
27
+ import("@intlayer/analytics").then(({ initAnalyticsClient, buildContentExposure }) => {
28
+ if (stopped) return;
29
+ const clientInstance = initAnalyticsClient();
30
+ initialized = true;
31
+ const currentLocale = resolvedClient?.locale();
32
+ if (currentLocale) clientInstance.setLocale(currentLocale);
33
+ clientInstance.trackPageView({ reason: "initial" });
34
+ setExposureSink((input) => clientInstance.trackContentExposure(buildContentExposure(input)));
35
+ analyticsClient.set(clientInstance);
36
+ }).catch(() => {});
37
+ let previousLocale;
38
+ const effectRef = runInInjectionContext(injector, () => effect(() => {
39
+ const clientInstance = analyticsClient();
40
+ const locale = resolvedClient?.locale();
41
+ if (!clientInstance || !locale) return;
42
+ if (previousLocale === void 0) {
43
+ previousLocale = locale;
44
+ return;
45
+ }
46
+ if (previousLocale === locale) return;
47
+ previousLocale = locale;
48
+ clientInstance.setLocale(locale);
49
+ clientInstance.trackPageView({ reason: "locale_change" });
50
+ }));
51
+ destroyRef?.onDestroy(() => {
52
+ stopped = true;
53
+ effectRef.destroy();
54
+ analyticsClient.set(null);
55
+ setExposureSink(null);
56
+ import("@intlayer/analytics").then(({ stopAnalyticsClient }) => {
57
+ if (initialized) stopAnalyticsClient();
58
+ }).catch(() => {});
59
+ });
60
+ };
61
+ /**
62
+ * Angular provider that wires `useAnalytics` into the application
63
+ * initialisation phase via `provideAppInitializer`.
64
+ *
65
+ * `provideIntlayer()` already calls this internally, so you only need this
66
+ * function when you want to manage providers individually.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * // app.config.ts
71
+ * import { provideIntlayer, provideIntlayerAnalytics } from 'angular-intlayer';
72
+ *
73
+ * export const appConfig: ApplicationConfig = {
74
+ * providers: [provideIntlayer(), provideIntlayerAnalytics()],
75
+ * };
76
+ * ```
77
+ */
78
+ const provideIntlayerAnalytics = (client) => provideAppInitializer(() => useAnalytics(client));
79
+
80
+ //#endregion
81
+ export { provideIntlayerAnalytics, useAnalytics };
82
+ //# sourceMappingURL=useAnalytics.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAnalytics.mjs","names":[],"sources":["../../../src/analytics/useAnalytics.ts"],"sourcesContent":["import {\n DestroyRef,\n effect,\n Injector,\n inject,\n provideAppInitializer,\n runInInjectionContext,\n signal,\n} from '@angular/core';\nimport type { AnalyticsClient } from '@intlayer/analytics';\nimport { isEnabled } from '@intlayer/analytics/isEnabled';\n// Import from the standalone token file to avoid a circular dependency:\n// installIntlayer.ts → useAnalytics.ts → ../client → installIntlayer.ts\nimport { INTLAYER_TOKEN, type IntlayerProvider } from '../client/intlayerToken';\nimport { setExposureSink } from './exposureSink';\n\n/**\n * Initializes the Intlayer analytics client singleton when analytics is\n * enabled (mirrors {@link useEditor}). Records an initial page view, keeps the\n * client aware of the current locale, and wires node-level content exposures.\n *\n * Must be called inside an Angular injection context (e.g. a component\n * constructor, `provideAppInitializer`, or `runInInjectionContext`).\n *\n * @param client - The IntlayerProvider instance to sync locale from.\n * When omitted the function injects `INTLAYER_TOKEN` from the DI tree,\n * so it still works when called directly from a component.\n */\nexport const useAnalytics = (client?: IntlayerProvider | null): void => {\n if (process.env.INTLAYER_ANALYTICS_ENABLED === 'false' || !isEnabled) return;\n\n const destroyRef = inject(DestroyRef, { optional: true });\n const injector = inject(Injector);\n\n // Resolve the client: use the passed-in reference or fall back to injection.\n const resolvedClient =\n client ??\n inject<IntlayerProvider>(INTLAYER_TOKEN, { optional: true } as any);\n\n // `analyticsClient` signal is set once the async import resolves.\n // Using a signal lets an `effect()` react to it becoming available.\n const analyticsClient = signal<AnalyticsClient | null>(null);\n\n // Guard: prevents the async callback from acting after the view is destroyed.\n let stopped = false;\n // Tracks whether initAnalyticsClient actually ran, so teardown never calls\n // stopAnalyticsClient for an init that was cancelled — that would decrement\n // the shared reference count once too many.\n let initialized = false;\n\n import('@intlayer/analytics')\n .then(({ initAnalyticsClient, buildContentExposure }) => {\n if (stopped) return;\n\n const clientInstance = initAnalyticsClient();\n initialized = true;\n\n const currentLocale = resolvedClient?.locale();\n if (currentLocale) clientInstance.setLocale(currentLocale);\n clientInstance.trackPageView({ reason: 'initial' });\n\n // Route node-level exposures (from the interpreter plugins) into the\n // client. Serialization happens here, off the hot render path.\n setExposureSink((input) =>\n clientInstance.trackContentExposure(buildContentExposure(input))\n );\n\n analyticsClient.set(clientInstance);\n })\n .catch(() => {\n /* chunk failed to load — analytics stays a no-op */\n });\n\n // Locale switches are a real signal — record them as page views.\n let previousLocale: string | undefined;\n const effectRef = runInInjectionContext(injector, () =>\n effect(() => {\n const clientInstance = analyticsClient();\n const locale = resolvedClient?.locale();\n\n if (!clientInstance || !locale) return;\n\n if (previousLocale === undefined) {\n // First run after init — the initial page view already covered it.\n previousLocale = locale;\n return;\n }\n if (previousLocale === locale) return;\n\n previousLocale = locale;\n clientInstance.setLocale(locale);\n clientInstance.trackPageView({ reason: 'locale_change' });\n })\n );\n\n // Tear down on destroy\n destroyRef?.onDestroy(() => {\n stopped = true;\n effectRef.destroy();\n analyticsClient.set(null);\n setExposureSink(null);\n import('@intlayer/analytics')\n .then(({ stopAnalyticsClient }) => {\n if (initialized) stopAnalyticsClient();\n })\n .catch(() => {});\n });\n};\n\n/**\n * Angular provider that wires `useAnalytics` into the application\n * initialisation phase via `provideAppInitializer`.\n *\n * `provideIntlayer()` already calls this internally, so you only need this\n * function when you want to manage providers individually.\n *\n * @example\n * ```ts\n * // app.config.ts\n * import { provideIntlayer, provideIntlayerAnalytics } from 'angular-intlayer';\n *\n * export const appConfig: ApplicationConfig = {\n * providers: [provideIntlayer(), provideIntlayerAnalytics()],\n * };\n * ```\n */\nexport const provideIntlayerAnalytics = (client?: IntlayerProvider | null) =>\n provideAppInitializer(() => useAnalytics(client));\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4BA,MAAa,gBAAgB,WAA2C;AACtE,KAAI,QAAQ,IAAI,+BAA+B,WAAW,CAAC,UAAW;CAEtE,MAAM,aAAa,OAAO,YAAY,EAAE,UAAU,MAAM,CAAC;CACzD,MAAM,WAAW,OAAO,SAAS;CAGjC,MAAM,iBACJ,UACA,OAAyB,gBAAgB,EAAE,UAAU,MAAM,CAAQ;CAIrE,MAAM,kBAAkB,OAA+B,KAAK;CAG5D,IAAI,UAAU;CAId,IAAI,cAAc;AAElB,QAAO,uBACJ,MAAM,EAAE,qBAAqB,2BAA2B;AACvD,MAAI,QAAS;EAEb,MAAM,iBAAiB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