@salesforce/ui-bundle-template-feature-cms-toolkit 11.63.0 → 11.66.1

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 (22) hide show
  1. package/dist/CHANGELOG.md +56 -0
  2. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/package.json +3 -3
  3. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/api/cmsContent.ts +35 -8
  4. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/api/cmsPaths.ts +13 -5
  5. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/config/env.ts +21 -0
  6. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/index.ts +13 -1
  7. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/types/cms.ts +2 -1
  8. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/imageUrl.ts +63 -1
  9. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/localiseUrl.ts +128 -0
  10. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/resolveLocale.ts +160 -0
  11. package/dist/force-app/main/default/uiBundles/feature-cms-toolkit/tsconfig.tsbuildinfo +1 -1
  12. package/dist/package-lock.json +2 -2
  13. package/dist/package.json +1 -1
  14. package/package.json +10 -5
  15. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/api/cmsContent.ts +35 -8
  16. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/api/cmsPaths.ts +13 -5
  17. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/config/env.ts +21 -0
  18. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/index.ts +13 -1
  19. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/types/cms.ts +2 -1
  20. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/imageUrl.ts +63 -1
  21. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/localiseUrl.ts +128 -0
  22. package/src/force-app/main/default/uiBundles/feature-cms-toolkit/src/features/cmsToolkit/utils/resolveLocale.ts +160 -0
@@ -0,0 +1,128 @@
1
+ /**
2
+ * URL localization for CMS delivery — add/override the `language` query param on a URL.
3
+ *
4
+ * Three entry points, low to high level:
5
+ * - appendLanguageParam(url, language) — PURE + synchronous. Sets `language` on any
6
+ * URL (absolute or root-relative), overriding an existing value. No-op when
7
+ * `language` is falsy. Used by the read/image paths that already know the language.
8
+ * - localiseMediaUrl(url, language?) — SYNCHRONOUS. Reads the active language via
9
+ * {@link getResolvedCmsLanguage} (explicit arg → `SFDC_ENV.language` → warmed i18n
10
+ * cache), then appends it. The render-time sibling of {@link appendLanguageParam} for
11
+ * `<img src>`: it returns a string, not a Promise. On internal apps the i18n language
12
+ * is served only after a one-time `await resolveCmsLanguage()` warms the cache.
13
+ * - localiseCmsUrl(url, options?) — ASYNC convenience for when a content or media
14
+ * URL is passed DIRECTLY: resolves the current language (options → SFDC_ENV → i18n,
15
+ * performing the i18n fetch if needed) and appends it. Used by the async content-read
16
+ * path, where awaiting guarantees resolution without a separate warm-up.
17
+ */
18
+ import { CMS_LANGUAGE_PARAM } from "../config/env";
19
+ import {
20
+ getResolvedCmsLanguage,
21
+ resolveCmsLanguage,
22
+ type ResolveLocaleOptions,
23
+ } from "./resolveLocale";
24
+
25
+ /**
26
+ * Set the `language` query param on `url`, overriding any existing one(s). Preserves the
27
+ * rest of the query and any `#fragment`. Works on absolute URLs and root-relative paths
28
+ * alike (no base needed), so both public CDN links and relative dev paths are handled.
29
+ * Returns `url` unchanged when `language` is falsy.
30
+ *
31
+ * Every segment whose key is EXACTLY `language` is removed — not just the first — so a
32
+ * duplicated key (`?language=de&language=es`) can never leave a stale value for a
33
+ * first-value query parser to pick. The requested value replaces the FIRST such segment in
34
+ * place (keeping its position) and is appended when none existed.
35
+ *
36
+ * The key match is LITERAL and case-sensitive: it is compared byte-for-byte against the
37
+ * canonical `language`, NOT case-folded or percent-decoded. So `Language=`, `LANGUAGE=`, or
38
+ * a percent-encoded `%6canguage=` are treated as DIFFERENT params and left untouched. This
39
+ * is intentional and safe: we only ever emit the canonical lowercase `language` (which the
40
+ * CMS reads), and we always write it here — a variant-cased key is not one the delivery API
41
+ * honours, and case-folding/percent-decoding keys would contradict the byte-for-byte
42
+ * guarantee below (and could clobber a genuinely distinct caller param).
43
+ *
44
+ * The query is spliced BYTE-FOR-BYTE: every other segment is preserved verbatim — it is NOT
45
+ * round-tripped through `URLSearchParams`, which would re-encode other params (e.g.
46
+ * `%20`→`+`) and could invalidate a signed URL.
47
+ */
48
+ export function appendLanguageParam(url: string, language?: string): string {
49
+ if (!language) return url;
50
+
51
+ // Split off a trailing #fragment so it survives at the end untouched.
52
+ const hashIndex = url.indexOf("#");
53
+ const hash = hashIndex === -1 ? "" : url.slice(hashIndex);
54
+ const withoutHash = hashIndex === -1 ? url : url.slice(0, hashIndex);
55
+
56
+ // Split the query from the base without a URL base (keeps relative paths relative).
57
+ const queryIndex = withoutHash.indexOf("?");
58
+ const base = queryIndex === -1 ? withoutHash : withoutHash.slice(0, queryIndex);
59
+ const query = queryIndex === -1 ? "" : withoutHash.slice(queryIndex + 1);
60
+
61
+ const encoded = `${CMS_LANGUAGE_PARAM}=${encodeURIComponent(language)}`;
62
+
63
+ // Walk the existing segments: drop every one whose key is EXACTLY `language` (literal,
64
+ // case-sensitive, not percent-decoded — see docblock), but keep each other segment's
65
+ // bytes untouched. The new value replaces the FIRST `language` occurrence in place;
66
+ // duplicates are discarded; if none existed we append at the end.
67
+ const segments = query ? query.split("&") : [];
68
+ const nextSegments: string[] = [];
69
+ let inserted = false;
70
+ for (const segment of segments) {
71
+ const eq = segment.indexOf("=");
72
+ const key = eq === -1 ? segment : segment.slice(0, eq);
73
+ if (key === CMS_LANGUAGE_PARAM) {
74
+ if (!inserted) {
75
+ nextSegments.push(encoded);
76
+ inserted = true;
77
+ }
78
+ continue;
79
+ }
80
+ nextSegments.push(segment);
81
+ }
82
+ if (!inserted) nextSegments.push(encoded);
83
+
84
+ return `${base}?${nextSegments.join("&")}${hash}`;
85
+ }
86
+
87
+ /**
88
+ * Localize a directly-passed media URL — read the active language via
89
+ * {@link getResolvedCmsLanguage} (explicit `language` arg → `SFDC_ENV.language` on
90
+ * Experience sites → the warmed platform-sdk i18n language on internal apps), then append
91
+ * it as the `language` query param. Returns `url` unchanged when nothing resolves (the API
92
+ * applies its default).
93
+ *
94
+ * SYNCHRONOUS: it returns a ready-to-use string for `<img src>` without an await. Because
95
+ * it only READS the resolved language (it never performs the i18n fetch itself), an
96
+ * internal app must warm the cache once up front so the i18n language is available:
97
+ * ```tsx
98
+ * await resolveCmsLanguage(); // once at init (e.g. in a loader/effect)
99
+ * // ...later, in render:
100
+ * <img src={localiseMediaUrl(mediaUrl)} />
101
+ * ```
102
+ * On Experience sites (`SFDC_ENV.language`) or when you pass an explicit `language`, no
103
+ * warm-up is needed. When you already hold a resolved language, {@link appendLanguageParam}
104
+ * is the pure, dependency-free alternative.
105
+ */
106
+ export function localiseMediaUrl(url: string, language?: string): string {
107
+ return appendLanguageParam(url, getResolvedCmsLanguage({ language }));
108
+ }
109
+
110
+ /**
111
+ * Localize a directly-passed CMS content or media URL: resolve the active language
112
+ * (see {@link resolveCmsLanguage}) and append it as the `language` query param. When no
113
+ * language can be resolved the URL is returned unchanged (the API applies its default).
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * // Fetch language automatically for a pasted delivery URL:
118
+ * const localized = await localiseCmsUrl(deliveryUrl);
119
+ * const article = await getCmsContentByUrl(localized);
120
+ *
121
+ * // Or force a language:
122
+ * const fr = await localiseCmsUrl(mediaUrl, { language: "fr" });
123
+ * ```
124
+ */
125
+ export async function localiseCmsUrl(url: string, options?: ResolveLocaleOptions): Promise<string> {
126
+ const language = await resolveCmsLanguage(options);
127
+ return appendLanguageParam(url, language);
128
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Resolve the active language for CMS delivery reads. The value is returned AS-IS (no
3
+ * normalization — the server/Java layer interprets it; see config/env.ts).
4
+ *
5
+ * Resolution order (first hit wins):
6
+ * 1. `options.language` — explicit caller override. Always wins.
7
+ * 2. `SFDC_ENV.language` — EXTERNAL apps. Experience sites inject it, so its presence
8
+ * is the signal that we're on a site; checked BEFORE the internal path so a site
9
+ * never pays for a wasted i18n GraphQL round-trip. Read fresh (sync), never cached.
10
+ * 3. platform-sdk i18n `fetchI18nContext().lang` — INTERNAL apps (authenticated uiapi).
11
+ * Async; the resolved value is cached module-side so it can be read SYNCHRONOUSLY
12
+ * afterwards (see {@link getResolvedCmsLanguage}) — this is what lets the synchronous
13
+ * {@link resolveCmsImageUrl} localize internal-app media once the language is warmed.
14
+ * 4. `undefined` — nothing resolved; the API applies the channel/site default.
15
+ *
16
+ * Two entry points:
17
+ * - {@link resolveCmsLanguage} — ASYNC. Runs the full chain and WARMS the cache with
18
+ * the resolved internal-app language. Concurrent internal-app calls share ONE in-flight
19
+ * i18n request (memoized), so a burst of media resolutions never fans out into N
20
+ * I18nDetect GraphQL round-trips.
21
+ * - {@link getResolvedCmsLanguage} — SYNC. Reads explicit → `SFDC_ENV.language` → the
22
+ * i18n language warmed by a prior `resolveCmsLanguage()`. Returns `undefined` when the
23
+ * internal-app language has not been warmed yet.
24
+ *
25
+ * Typical use: `await resolveCmsLanguage()` ONCE up front (e.g. in a page loader, before
26
+ * rendering a grid of images), then call the synchronous `resolveCmsImageUrl` per image —
27
+ * each reads the warmed language from cache with no further async work or duplicate fetch.
28
+ *
29
+ * Staleness / in-session locale change: both this module's cache AND platform-sdk's
30
+ * `fetchI18nContext` memoize for the life of the page, so a locale change takes effect on a
31
+ * full reload (the natural flow — `SFDC_ENV.language` is re-injected / the platform locale
32
+ * is re-queried). If the app changes locale WITHOUT reloading, pass the new value explicitly
33
+ * as `options.language` (which bypasses the cache) rather than relying on auto-resolution.
34
+ *
35
+ * Fail-open: the internal i18n path is wrapped so any error (no GraphQL surface, guest
36
+ * context, network failure) resolves to `undefined` instead of throwing — a content read
37
+ * must never fail purely because the locale could not be detected.
38
+ */
39
+ import { createDataSDK } from "@salesforce/platform-sdk";
40
+ import { fetchI18nContext } from "@salesforce/platform-sdk/i18n";
41
+ import { readEnvLanguage } from "../config/env";
42
+
43
+ /** Options controlling language resolution. Shared by every localizing read. */
44
+ export interface ResolveLocaleOptions {
45
+ /**
46
+ * Explicit language (BCP-47 tag like `en-US`, or a Salesforce key like `en_US`).
47
+ * Short-circuits detection — pass this to force a specific language.
48
+ */
49
+ language?: string;
50
+ }
51
+
52
+ /**
53
+ * Cached internal-app i18n language. Populated once by {@link resolveCmsLanguage} so
54
+ * {@link getResolvedCmsLanguage} can serve it synchronously. Only the i18n result is
55
+ * cached — `SFDC_ENV.language` is read fresh each call (sync and cheap), and an explicit
56
+ * `options.language` never touches this cache.
57
+ */
58
+ let cachedI18nLanguage: string | undefined;
59
+ /**
60
+ * Shared in-flight i18n lookup. Concurrent internal-app resolutions await the SAME promise
61
+ * instead of each firing its own I18nDetect GraphQL request. Cleared on settle so a failed
62
+ * (or empty) lookup can be retried later.
63
+ */
64
+ let inflightI18nLanguage: Promise<string | undefined> | null = null;
65
+ /**
66
+ * Whether the internal-app i18n path has EVER been attempted (i.e. `resolveCmsLanguage()`
67
+ * reached the i18n branch at least once). Lets callers distinguish a genuinely cold cache
68
+ * ("warm-up never ran") from a warmed-but-empty one ("ran, but i18n has no language") —
69
+ * used by the dev-mode unwarmed-cache warning in {@link getResolvedCmsLanguage}'s consumers.
70
+ */
71
+ let i18nAttempted = false;
72
+
73
+ /**
74
+ * Fetch the internal-app language via platform-sdk i18n. Fail-open: returns `undefined`
75
+ * on any error (missing GraphQL surface, guest context, network). The underlying
76
+ * `fetchI18nContext` is memoized by platform-sdk, so repeat calls are cheap.
77
+ */
78
+ async function readI18nLanguage(): Promise<string | undefined> {
79
+ try {
80
+ const sdk = await createDataSDK();
81
+ const context = await fetchI18nContext(sdk);
82
+ return context.lang;
83
+ } catch {
84
+ return undefined;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Resolve the internal-app i18n language ONCE: serve a previously-cached value, share a
90
+ * single in-flight request across concurrent callers, and cache a resolved (defined) value
91
+ * for later synchronous reads. A `undefined` result is NOT cached, so a lookup that failed
92
+ * (e.g. a transient network error) can be retried on the next call.
93
+ */
94
+ function resolveI18nLanguageOnce(): Promise<string | undefined> {
95
+ // Mark the i18n path as attempted the moment we enter it — even a call that returns a
96
+ // cached/undefined value counts, so the unwarmed-cache warning fires only before warm-up.
97
+ i18nAttempted = true;
98
+ if (cachedI18nLanguage !== undefined) return Promise.resolve(cachedI18nLanguage);
99
+ if (inflightI18nLanguage) return inflightI18nLanguage;
100
+
101
+ inflightI18nLanguage = readI18nLanguage()
102
+ .then((language) => {
103
+ if (language) cachedI18nLanguage = language;
104
+ return language;
105
+ })
106
+ .finally(() => {
107
+ inflightI18nLanguage = null;
108
+ });
109
+ return inflightI18nLanguage;
110
+ }
111
+
112
+ /**
113
+ * Resolve the CMS `language` value for the current app, or `undefined` when none can be
114
+ * determined (the API then falls back to the channel/site default). ASYNC — runs the full
115
+ * chain (explicit → `SFDC_ENV.language` → platform-sdk i18n) and WARMS the module cache
116
+ * with the resolved internal-app language, so a later {@link getResolvedCmsLanguage} (and
117
+ * therefore the synchronous {@link resolveCmsImageUrl}) can serve it without any await.
118
+ *
119
+ * @param options - Optional explicit `language` override.
120
+ */
121
+ export async function resolveCmsLanguage(
122
+ options?: ResolveLocaleOptions,
123
+ ): Promise<string | undefined> {
124
+ if (options?.language) return options.language;
125
+
126
+ const envLanguage = readEnvLanguage();
127
+ if (envLanguage) return envLanguage;
128
+
129
+ return resolveI18nLanguageOnce();
130
+ }
131
+
132
+ /**
133
+ * SYNCHRONOUS read of the active CMS language: explicit `options.language` →
134
+ * `SFDC_ENV.language` → the internal-app i18n language cached by a prior
135
+ * {@link resolveCmsLanguage} call. Returns `undefined` when an internal-app language has
136
+ * not been warmed yet — callers that need it should `await resolveCmsLanguage()` once up
137
+ * front (e.g. before rendering images) so this can serve the value synchronously.
138
+ *
139
+ * @param options - Optional explicit `language` override.
140
+ */
141
+ export function getResolvedCmsLanguage(options?: ResolveLocaleOptions): string | undefined {
142
+ if (options?.language) return options.language;
143
+
144
+ const envLanguage = readEnvLanguage();
145
+ if (envLanguage) return envLanguage;
146
+
147
+ return cachedI18nLanguage;
148
+ }
149
+
150
+ /**
151
+ * Whether the internal-app i18n language has been WARMED (or at least attempted) via
152
+ * {@link resolveCmsLanguage}. `false` means the cache is genuinely cold — no warm-up has
153
+ * run — so a synchronous read on an internal app would fall through to `undefined`.
154
+ * Internal helper for the dev-mode "did you forget to warm the cache?" warning; not part of
155
+ * the public barrel. Not meaningful on Experience sites (there `SFDC_ENV.language` answers
156
+ * synchronously and the i18n path is never reached).
157
+ */
158
+ export function hasAttemptedCmsLanguage(): boolean {
159
+ return i18nAttempted;
160
+ }