@intlayer/core 8.11.0 → 8.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs +0 -1
  2. package/dist/cjs/dictionaryManipulator/mergeDictionaries.cjs.map +1 -1
  3. package/dist/cjs/dictionaryManipulator/orderDictionaries.cjs +0 -1
  4. package/dist/cjs/dictionaryManipulator/orderDictionaries.cjs.map +1 -1
  5. package/dist/cjs/formatters/compact.cjs +0 -1
  6. package/dist/cjs/formatters/compact.cjs.map +1 -1
  7. package/dist/cjs/formatters/currency.cjs +0 -1
  8. package/dist/cjs/formatters/currency.cjs.map +1 -1
  9. package/dist/cjs/formatters/date.cjs +0 -1
  10. package/dist/cjs/formatters/date.cjs.map +1 -1
  11. package/dist/cjs/formatters/list.cjs +0 -1
  12. package/dist/cjs/formatters/list.cjs.map +1 -1
  13. package/dist/cjs/formatters/number.cjs +0 -1
  14. package/dist/cjs/formatters/number.cjs.map +1 -1
  15. package/dist/cjs/formatters/percentage.cjs +0 -1
  16. package/dist/cjs/formatters/percentage.cjs.map +1 -1
  17. package/dist/cjs/formatters/relativeTime.cjs +0 -1
  18. package/dist/cjs/formatters/relativeTime.cjs.map +1 -1
  19. package/dist/cjs/formatters/units.cjs +0 -1
  20. package/dist/cjs/formatters/units.cjs.map +1 -1
  21. package/dist/cjs/index.cjs +3 -1
  22. package/dist/cjs/interpreter/getCondition.cjs.map +1 -1
  23. package/dist/cjs/interpreter/getContent/getContent.cjs +0 -1
  24. package/dist/cjs/interpreter/getContent/getContent.cjs.map +1 -1
  25. package/dist/cjs/interpreter/getDictionary.cjs.map +1 -1
  26. package/dist/cjs/interpreter/getEnumeration.cjs.map +1 -1
  27. package/dist/cjs/interpreter/getGender.cjs.map +1 -1
  28. package/dist/cjs/interpreter/getIntlayer.cjs +0 -1
  29. package/dist/cjs/interpreter/getIntlayer.cjs.map +1 -1
  30. package/dist/cjs/interpreter/getNesting.cjs.map +1 -1
  31. package/dist/cjs/interpreter/getPlural.cjs.map +1 -1
  32. package/dist/cjs/interpreter/getTranslation.cjs.map +1 -1
  33. package/dist/cjs/localization/getBrowserLocale.cjs +0 -21
  34. package/dist/cjs/localization/getBrowserLocale.cjs.map +1 -1
  35. package/dist/cjs/localization/getLocale.cjs +0 -1
  36. package/dist/cjs/localization/getLocale.cjs.map +1 -1
  37. package/dist/cjs/localization/getLocalizedUrl.cjs +0 -1
  38. package/dist/cjs/localization/getLocalizedUrl.cjs.map +1 -1
  39. package/dist/cjs/localization/getPathWithoutLocale.cjs +0 -1
  40. package/dist/cjs/localization/getPathWithoutLocale.cjs.map +1 -1
  41. package/dist/cjs/localization/getPrefix.cjs +0 -1
  42. package/dist/cjs/localization/getPrefix.cjs.map +1 -1
  43. package/dist/cjs/localization/index.cjs +0 -1
  44. package/dist/cjs/localization/localeMapper.cjs +0 -1
  45. package/dist/cjs/localization/localeMapper.cjs.map +1 -1
  46. package/dist/cjs/localization/localeResolver.cjs +0 -1
  47. package/dist/cjs/localization/localeResolver.cjs.map +1 -1
  48. package/dist/cjs/markdown/compiler.cjs +53 -31
  49. package/dist/cjs/markdown/compiler.cjs.map +1 -1
  50. package/dist/cjs/markdown/index.cjs +2 -0
  51. package/dist/cjs/transpiler/condition/condition.cjs +0 -1
  52. package/dist/cjs/transpiler/condition/condition.cjs.map +1 -1
  53. package/dist/cjs/transpiler/enumeration/enumeration.cjs +0 -1
  54. package/dist/cjs/transpiler/enumeration/enumeration.cjs.map +1 -1
  55. package/dist/cjs/transpiler/file/file.cjs +0 -1
  56. package/dist/cjs/transpiler/file/file.cjs.map +1 -1
  57. package/dist/cjs/transpiler/gender/gender.cjs +0 -1
  58. package/dist/cjs/transpiler/gender/gender.cjs.map +1 -1
  59. package/dist/cjs/transpiler/html/html.cjs +0 -1
  60. package/dist/cjs/transpiler/html/html.cjs.map +1 -1
  61. package/dist/cjs/transpiler/insertion/insertion.cjs +0 -1
  62. package/dist/cjs/transpiler/insertion/insertion.cjs.map +1 -1
  63. package/dist/cjs/transpiler/markdown/markdown.cjs +0 -1
  64. package/dist/cjs/transpiler/markdown/markdown.cjs.map +1 -1
  65. package/dist/cjs/transpiler/nesting/nesting.cjs +0 -1
  66. package/dist/cjs/transpiler/nesting/nesting.cjs.map +1 -1
  67. package/dist/cjs/transpiler/plural/plural.cjs +0 -1
  68. package/dist/cjs/transpiler/plural/plural.cjs.map +1 -1
  69. package/dist/cjs/transpiler/translation/translation.cjs +0 -1
  70. package/dist/cjs/transpiler/translation/translation.cjs.map +1 -1
  71. package/dist/cjs/utils/index.cjs +1 -0
  72. package/dist/cjs/utils/intl.cjs +0 -1
  73. package/dist/cjs/utils/intl.cjs.map +1 -1
  74. package/dist/cjs/utils/localeStorage.cjs +21 -3
  75. package/dist/cjs/utils/localeStorage.cjs.map +1 -1
  76. package/dist/esm/index.mjs +4 -4
  77. package/dist/esm/interpreter/getCondition.mjs.map +1 -1
  78. package/dist/esm/interpreter/getContent/getContent.mjs.map +1 -1
  79. package/dist/esm/interpreter/getDictionary.mjs.map +1 -1
  80. package/dist/esm/interpreter/getEnumeration.mjs.map +1 -1
  81. package/dist/esm/interpreter/getGender.mjs.map +1 -1
  82. package/dist/esm/interpreter/getIntlayer.mjs.map +1 -1
  83. package/dist/esm/interpreter/getNesting.mjs.map +1 -1
  84. package/dist/esm/interpreter/getPlural.mjs.map +1 -1
  85. package/dist/esm/interpreter/getTranslation.mjs.map +1 -1
  86. package/dist/esm/localization/getBrowserLocale.mjs +1 -20
  87. package/dist/esm/localization/getBrowserLocale.mjs.map +1 -1
  88. package/dist/esm/localization/index.mjs +2 -2
  89. package/dist/esm/markdown/compiler.mjs +44 -24
  90. package/dist/esm/markdown/compiler.mjs.map +1 -1
  91. package/dist/esm/markdown/index.mjs +2 -2
  92. package/dist/esm/utils/index.mjs +2 -2
  93. package/dist/esm/utils/localeStorage.mjs +20 -2
  94. package/dist/esm/utils/localeStorage.mjs.map +1 -1
  95. package/dist/types/index.d.ts +4 -4
  96. package/dist/types/interpreter/getCondition.d.ts +1 -1
  97. package/dist/types/interpreter/getCondition.d.ts.map +1 -1
  98. package/dist/types/interpreter/getContent/getContent.d.ts +1 -1
  99. package/dist/types/interpreter/getContent/getContent.d.ts.map +1 -1
  100. package/dist/types/interpreter/getDictionary.d.ts +1 -1
  101. package/dist/types/interpreter/getDictionary.d.ts.map +1 -1
  102. package/dist/types/interpreter/getEnumeration.d.ts +2 -2
  103. package/dist/types/interpreter/getEnumeration.d.ts.map +1 -1
  104. package/dist/types/interpreter/getGender.d.ts +1 -1
  105. package/dist/types/interpreter/getGender.d.ts.map +1 -1
  106. package/dist/types/interpreter/getIntlayer.d.ts +1 -1
  107. package/dist/types/interpreter/getIntlayer.d.ts.map +1 -1
  108. package/dist/types/interpreter/getNesting.d.ts +1 -1
  109. package/dist/types/interpreter/getNesting.d.ts.map +1 -1
  110. package/dist/types/interpreter/getPlural.d.ts +1 -1
  111. package/dist/types/interpreter/getPlural.d.ts.map +1 -1
  112. package/dist/types/interpreter/getTranslation.d.ts +1 -1
  113. package/dist/types/interpreter/getTranslation.d.ts.map +1 -1
  114. package/dist/types/localization/getBrowserLocale.d.ts +1 -3
  115. package/dist/types/localization/getBrowserLocale.d.ts.map +1 -1
  116. package/dist/types/localization/getPrefix.d.ts +5 -5
  117. package/dist/types/localization/getPrefix.d.ts.map +1 -1
  118. package/dist/types/localization/index.d.ts +2 -2
  119. package/dist/types/markdown/compiler.d.ts +12 -1
  120. package/dist/types/markdown/compiler.d.ts.map +1 -1
  121. package/dist/types/markdown/index.d.ts +2 -2
  122. package/dist/types/utils/index.d.ts +2 -2
  123. package/dist/types/utils/localeStorage.d.ts +2 -1
  124. package/dist/types/utils/localeStorage.d.ts.map +1 -1
  125. package/package.json +7 -7
@@ -1,7 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
- const require_runtime = require('../_virtual/_rolldown/runtime.cjs');
3
2
  const require_utils_getCookie = require('./getCookie.cjs');
4
- const require_localization_getBrowserLocale = require('../localization/getBrowserLocale.cjs');
5
3
  let _intlayer_config_built = require("@intlayer/config/built");
6
4
 
7
5
  //#region src/utils/localeStorage.ts
@@ -30,12 +28,31 @@ const buildCookieString = (name, value, attributes) => {
30
28
  if (attributes.sameSite) parts.push(`SameSite=${attributes.sameSite}`);
31
29
  return parts.join("; ");
32
30
  };
31
+ const localeStorageOptions = {
32
+ getCookie: (name) => document.cookie.split(";").find((c) => c.trim().startsWith(`${name}=`))?.split("=")[1],
33
+ getLocaleStorage: (name) => localStorage.getItem(name),
34
+ getSessionStorage: (name) => sessionStorage.getItem(name),
35
+ isCookieEnabled: true,
36
+ setCookieStore: (name, value, attributes) => cookieStore.set({
37
+ name,
38
+ value,
39
+ path: attributes.path,
40
+ domain: attributes.domain,
41
+ expires: attributes.expires,
42
+ sameSite: attributes.sameSite
43
+ }),
44
+ setCookieString: (_name, cookie) => {
45
+ document.cookie = cookie;
46
+ },
47
+ setSessionStorage: (name, value) => sessionStorage.setItem(name, value),
48
+ setLocaleStorage: (name, value) => localStorage.setItem(name, value)
49
+ };
33
50
  /**
34
51
  * Retrieves the locale from browser storage mechanisms
35
52
  * (cookies, localStorage, sessionStorage).
36
53
  * Does not read from headers — use `getLocaleFromStorageServer` for that.
37
54
  */
38
- const getLocaleFromStorageClient = (options = require_localization_getBrowserLocale.localeStorageOptions) => {
55
+ const getLocaleFromStorageClient = (options = localeStorageOptions) => {
39
56
  const { locales } = _intlayer_config_built.internationalization;
40
57
  if (options?.isCookieEnabled === false) return void 0;
41
58
  const isValidLocale = (value) => !!value && locales.includes(value);
@@ -266,6 +283,7 @@ exports.LocaleStorageServer = LocaleStorageServer;
266
283
  exports.getLocaleFromStorage = getLocaleFromStorage;
267
284
  exports.getLocaleFromStorageClient = getLocaleFromStorageClient;
268
285
  exports.getLocaleFromStorageServer = getLocaleFromStorageServer;
286
+ exports.localeStorageOptions = localeStorageOptions;
269
287
  exports.setLocaleInStorage = setLocaleInStorage;
270
288
  exports.setLocaleInStorageClient = setLocaleInStorageClient;
271
289
  exports.setLocaleInStorageServer = setLocaleInStorageServer;
@@ -1 +1 @@
1
- {"version":3,"file":"localeStorage.cjs","names":["localeStorageOptions","internationalization","routing","getCookie"],"sources":["../../../src/utils/localeStorage.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { CookiesAttributes } from '@intlayer/types/config';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { localeStorageOptions } from '../localization';\nimport { getCookie } from './getCookie';\n\n// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\n/**\n * True when cookie storage is explicitly disabled at build time.\n */\nconst TREE_SHAKE_STORAGE_COOKIES =\n process.env['INTLAYER_ROUTING_STORAGE_COOKIES'] === 'false';\n\n/**\n * True when localStorage is explicitly disabled at build time.\n */\nconst TREE_SHAKE_STORAGE_LOCAL_STORAGE =\n process.env['INTLAYER_ROUTING_STORAGE_LOCALSTORAGE'] === 'false';\n\n/**\n * True when sessionStorage is explicitly disabled at build time.\n */\nconst TREE_SHAKE_STORAGE_SESSION_STORAGE =\n process.env['INTLAYER_ROUTING_STORAGE_SESSIONSTORAGE'] === 'false';\n\n/**\n * True when header storage is explicitly disabled at build time.\n */\nconst TREE_SHAKE_STORAGE_HEADERS =\n process.env['INTLAYER_ROUTING_STORAGE_HEADERS'] === 'false';\n\n// ============================================================================\n// Shared types\n// ============================================================================\n\nexport type CookieBuildAttributes = {\n domain?: string;\n path?: string;\n secure?: boolean;\n httpOnly?: boolean;\n sameSite?: 'strict' | 'lax' | 'none';\n /** Expiry as milliseconds since epoch (Date.getTime()) or number of days */\n expires?: number | undefined;\n};\n\n// ============================================================================\n// Shared helpers\n// ============================================================================\n\nconst buildCookieString = (\n name: string,\n value: string,\n attributes: Omit<CookiesAttributes, 'name' | 'type'>\n): string => {\n const encodedValue = encodeURIComponent(value);\n const parts: string[] = [`${name}=${encodedValue}`];\n\n if (attributes.path) parts.push(`Path=${attributes.path}`);\n if (attributes.domain) parts.push(`Domain=${attributes.domain}`);\n if (attributes.expires instanceof Date)\n parts.push(`Expires=${attributes.expires.toUTCString()}`);\n if (attributes.secure) parts.push('Secure');\n if (attributes.sameSite) parts.push(`SameSite=${attributes.sameSite}`);\n return parts.join('; ');\n};\n\n// ============================================================================\n// Client-specific types and functions\n// (cookies via browser APIs, localStorage, sessionStorage — no headers)\n// ============================================================================\n\nexport type LocaleStorageClientOptions = {\n overwrite?: boolean;\n isCookieEnabled?: boolean;\n setCookieStore?: (\n name: string,\n value: string,\n cookie: CookieBuildAttributes\n ) => void;\n setCookieString?: (name: string, cookie: string) => void;\n getCookie?: (name: string) => string | undefined | null;\n setSessionStorage?: (name: string, value: string) => void;\n getSessionStorage?: (name: string) => string | undefined | null;\n setLocaleStorage?: (name: string, value: string) => void;\n getLocaleStorage?: (name: string) => string | undefined | null;\n};\n\n/**\n * Retrieves the locale from browser storage mechanisms\n * (cookies, localStorage, sessionStorage).\n * Does not read from headers — use `getLocaleFromStorageServer` for that.\n */\nexport const getLocaleFromStorageClient = (\n options: LocaleStorageClientOptions = localeStorageOptions\n): Locale | undefined => {\n const { locales } = internationalization;\n\n if (options?.isCookieEnabled === false) return undefined;\n\n const isValidLocale = (value: string | null | undefined): value is Locale =>\n !!value && locales.includes(value as Locale);\n\n if (!TREE_SHAKE_STORAGE_COOKIES) {\n for (let i = 0; i < (routing.storage.cookies ?? []).length; i++) {\n try {\n const value = options?.getCookie?.(routing.storage.cookies![i].name);\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n\n if (!TREE_SHAKE_STORAGE_LOCAL_STORAGE) {\n for (let i = 0; i < (routing.storage.localStorage ?? []).length; i++) {\n try {\n const value = options?.getLocaleStorage?.(\n routing.storage.localStorage![i].name\n );\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n\n if (!TREE_SHAKE_STORAGE_SESSION_STORAGE && routing.storage.sessionStorage) {\n for (let i = 0; i < routing.storage.sessionStorage.length; i++) {\n try {\n const value = options?.getSessionStorage?.(\n routing.storage.sessionStorage[i].name\n );\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n};\n\n/**\n * Stores the locale in browser storage mechanisms\n * (cookies, localStorage, sessionStorage).\n * Does not write to headers — use `setLocaleInStorageServer` for that.\n */\nexport const setLocaleInStorageClient = (\n locale: LocalesValues,\n options?: LocaleStorageClientOptions\n): void => {\n if (options?.isCookieEnabled === false) return;\n\n if (!TREE_SHAKE_STORAGE_COOKIES && routing.storage.cookies) {\n for (let i = 0; i < routing.storage.cookies.length; i++) {\n const { name, attributes } = routing.storage.cookies[i];\n try {\n if (options?.setCookieStore) {\n options.setCookieStore(name, locale, {\n ...attributes,\n expires:\n attributes.expires instanceof Date\n ? attributes.expires.getTime()\n : attributes.expires,\n });\n }\n } catch {\n try {\n if (options?.setCookieString) {\n options.setCookieString(\n name,\n buildCookieString(name, locale, attributes)\n );\n }\n } catch {}\n }\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_LOCAL_STORAGE &&\n routing.storage.localStorage &&\n options?.setLocaleStorage\n ) {\n for (let i = 0; i < routing.storage.localStorage.length; i++) {\n const { name } = routing.storage.localStorage[i];\n try {\n if (!(options?.overwrite ?? true) && options?.getLocaleStorage) {\n if (options.getLocaleStorage(name)) continue;\n }\n options.setLocaleStorage(name, locale);\n } catch {}\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_SESSION_STORAGE &&\n routing.storage.sessionStorage &&\n options?.setSessionStorage\n ) {\n for (let i = 0; i < routing.storage.sessionStorage.length; i++) {\n const { name } = routing.storage.sessionStorage[i];\n try {\n if (!(options?.overwrite ?? true) && options?.getSessionStorage) {\n if (options.getSessionStorage(name)) continue;\n }\n options.setSessionStorage(name, locale);\n } catch {}\n }\n }\n};\n\n/**\n * Client-side locale storage utility.\n * Handles cookies (browser), localStorage and sessionStorage.\n * Does not access headers.\n *\n * @example\n * ```ts\n * const storage = LocaleStorageClient(localeStorageOptions);\n * const locale = storage.getLocale();\n * storage.setLocale('fr');\n * ```\n */\nexport const LocaleStorageClient = (options: LocaleStorageClientOptions) => ({\n getLocale: () => getLocaleFromStorageClient(options),\n setLocale: (locale: LocalesValues) =>\n setLocaleInStorageClient(locale, options),\n});\n\n// ============================================================================\n// Server-specific types and functions\n// (cookies via injected getter/setter, headers — no localStorage/sessionStorage)\n// ============================================================================\n\nexport type LocaleStorageServerOptions = {\n overwrite?: boolean;\n isCookieEnabled?: boolean;\n setCookieStore?: (\n name: string,\n value: string,\n cookie: CookieBuildAttributes\n ) => void;\n setCookieString?: (name: string, cookie: string) => void;\n getCookie?: (name: string) => string | undefined | null;\n getHeader?: (name: string) => string | undefined | null;\n setHeader?: (name: string, value: string) => void;\n};\n\n/**\n * Retrieves the locale from server-side storage mechanisms (cookies, headers).\n * Does not access localStorage or sessionStorage.\n * No browser cookie fallback — the caller must provide `getCookie`.\n */\nexport const getLocaleFromStorageServer = (\n options: LocaleStorageServerOptions\n): Locale | undefined => {\n const { locales } = internationalization;\n\n if (options?.isCookieEnabled === false) return undefined;\n\n const isValidLocale = (value: string | null | undefined): value is Locale =>\n !!value && locales.includes(value as Locale);\n\n if (!TREE_SHAKE_STORAGE_COOKIES && routing.storage.cookies) {\n for (let i = 0; i < routing.storage.cookies.length; i++) {\n try {\n const value = options?.getCookie?.(routing.storage.cookies[i].name);\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n\n if (!TREE_SHAKE_STORAGE_HEADERS && routing.storage.headers) {\n for (let i = 0; i < routing.storage.headers.length; i++) {\n try {\n const value = options?.getHeader?.(routing.storage.headers[i].name);\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n};\n\n/**\n * Stores the locale in server-side storage mechanisms (cookies, headers).\n * Does not write to localStorage or sessionStorage.\n */\nexport const setLocaleInStorageServer = (\n locale: LocalesValues,\n options?: LocaleStorageServerOptions\n): void => {\n if (options?.isCookieEnabled === false) return;\n\n if (!TREE_SHAKE_STORAGE_COOKIES && routing.storage.cookies) {\n for (let i = 0; i < routing.storage.cookies.length; i++) {\n const { name, attributes } = routing.storage.cookies[i];\n\n try {\n if (options?.setCookieStore) {\n options.setCookieStore(name, locale, {\n ...attributes,\n expires:\n attributes.expires instanceof Date\n ? attributes.expires.getTime()\n : attributes.expires,\n });\n }\n } catch {\n try {\n if (options?.setCookieString) {\n options.setCookieString(\n name,\n buildCookieString(name, locale, attributes)\n );\n }\n } catch {}\n }\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_HEADERS &&\n routing.storage.headers &&\n options?.setHeader\n ) {\n for (let i = 0; i < routing.storage.headers.length; i++) {\n try {\n options.setHeader(routing.storage.headers[i].name, locale);\n } catch {}\n }\n }\n};\n\n/**\n * Server-side locale storage utility.\n * Handles cookies (via injected getter/setter) and headers.\n * Does not access localStorage or sessionStorage.\n *\n * @example\n * ```ts\n * const storage = LocaleStorageServer({\n * getCookie: (name) => req.cookies[name],\n * setCookieStore: (name, value, attrs) => res.cookie(name, value, attrs),\n * getHeader: (name) => req.headers[name],\n * setHeader: (name, value) => res.setHeader(name, value),\n * });\n * const locale = storage.getLocale();\n * storage.setLocale('fr');\n * ```\n */\nexport const LocaleStorageServer = (options: LocaleStorageServerOptions) => ({\n getLocale: () => getLocaleFromStorageServer(options),\n setLocale: (locale: LocalesValues) =>\n setLocaleInStorageServer(locale, options),\n});\n\n// ============================================================================\n// Deprecated: combined LocaleStorage\n// Use LocaleStorageClient or LocaleStorageServer instead\n// ============================================================================\n\n/**\n * @deprecated Use {@link LocaleStorageClientOptions} or {@link LocaleStorageServerOptions} instead.\n */\nexport type LocaleStorageOptions = LocaleStorageClientOptions &\n LocaleStorageServerOptions;\n\n/**\n * Retrieves the locale from all storage mechanisms\n * (cookies, localStorage, sessionStorage, headers).\n *\n * @deprecated Use {@link getLocaleFromStorageClient} (browser) or\n * {@link getLocaleFromStorageServer} (server) instead.\n */\nexport const getLocaleFromStorage = (\n options: Pick<\n LocaleStorageOptions,\n | 'getCookie'\n | 'getSessionStorage'\n | 'getLocaleStorage'\n | 'getHeader'\n | 'isCookieEnabled'\n >\n): Locale | undefined => {\n const { locales } = internationalization;\n\n if (options?.isCookieEnabled === false) return undefined;\n\n const isValidLocale = (value: string | null | undefined): value is Locale =>\n !!value && locales.includes(value as Locale);\n\n const readCookie = (name: string): string | undefined => {\n try {\n const fromOption = options?.getCookie?.(name);\n if (fromOption !== null && fromOption !== undefined) return fromOption;\n } catch {}\n // Browser fallback kept for backward compatibility\n return getCookie(name);\n };\n\n if (!TREE_SHAKE_STORAGE_COOKIES && routing.storage.cookies) {\n for (let i = 0; i < routing.storage.cookies.length; i++) {\n const value = readCookie(routing.storage.cookies[i].name);\n if (isValidLocale(value)) return value;\n }\n }\n\n if (!TREE_SHAKE_STORAGE_LOCAL_STORAGE && routing.storage.localStorage) {\n for (let i = 0; i < routing.storage.localStorage.length; i++) {\n try {\n const value = options?.getLocaleStorage?.(\n routing.storage.localStorage[i].name\n );\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n\n if (!TREE_SHAKE_STORAGE_SESSION_STORAGE && routing.storage.sessionStorage) {\n for (let i = 0; i < routing.storage.sessionStorage.length; i++) {\n try {\n const value = options?.getSessionStorage?.(\n routing.storage.sessionStorage[i].name\n );\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n\n if (!TREE_SHAKE_STORAGE_HEADERS && routing.storage.headers) {\n for (let i = 0; i < routing.storage.headers.length; i++) {\n try {\n const value = options?.getHeader?.(routing.storage.headers[i].name);\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n};\n\n/**\n * Stores the locale in all configured storage mechanisms\n * (cookies, localStorage, sessionStorage, headers).\n *\n * @deprecated Use {@link setLocaleInStorageClient} (browser) or\n * {@link setLocaleInStorageServer} (server) instead.\n */\nexport const setLocaleInStorage = (\n locale: LocalesValues,\n options?: LocaleStorageOptions\n): void => {\n if (options?.isCookieEnabled === false) return;\n\n if (!TREE_SHAKE_STORAGE_COOKIES && routing.storage.cookies) {\n for (let i = 0; i < routing.storage.cookies.length; i++) {\n const { name, attributes } = routing.storage.cookies[i];\n try {\n if (options?.setCookieStore) {\n options.setCookieStore(name, locale, {\n ...attributes,\n expires:\n attributes.expires instanceof Date\n ? attributes.expires.getTime()\n : attributes.expires,\n });\n }\n } catch {\n try {\n if (options?.setCookieString) {\n options.setCookieString(\n name,\n buildCookieString(name, locale, attributes)\n );\n }\n } catch {}\n }\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_LOCAL_STORAGE &&\n routing.storage.localStorage &&\n options?.setLocaleStorage\n ) {\n for (let i = 0; i < routing.storage.localStorage.length; i++) {\n const { name } = routing.storage.localStorage[i];\n try {\n if (!(options?.overwrite ?? true) && options?.getLocaleStorage) {\n if (options.getLocaleStorage(name)) continue;\n }\n options.setLocaleStorage(name, locale);\n } catch {}\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_SESSION_STORAGE &&\n routing.storage.sessionStorage &&\n options?.setSessionStorage\n ) {\n for (let i = 0; i < routing.storage.sessionStorage.length; i++) {\n const { name } = routing.storage.sessionStorage[i];\n try {\n if (!(options?.overwrite ?? true) && options?.getSessionStorage) {\n if (options.getSessionStorage(name)) continue;\n }\n options.setSessionStorage(name, locale);\n } catch {}\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_HEADERS &&\n routing.storage.headers &&\n options?.setHeader\n ) {\n for (let i = 0; i < routing.storage.headers.length; i++) {\n try {\n options.setHeader(routing.storage.headers[i].name, locale);\n } catch {}\n }\n }\n};\n\n/**\n * Utility object to get and set the locale in storage based on configuration.\n *\n * @deprecated Use {@link LocaleStorageClient} (browser) or\n * {@link LocaleStorageServer} (server) instead.\n */\nexport const LocaleStorage = (options: LocaleStorageOptions) => ({\n getLocale: () => getLocaleFromStorage(options),\n setLocale: (locale: LocalesValues) => setLocaleInStorage(locale, options),\n});\n"],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AQ,QAAQ,gBAChB,SAAS,kBAET,KAAK,IAAI,IAAI,GAAG,IAAIA,+BAAQ,QAAQ,aAAa,QAAQ,KAAK;EAC5D,MAAM,EAAE,SAASA,+BAAQ,QAAQ,aAAa;EAC9C,IAAI;GACF,IAAI,EAAE,SAAS,aAAa,SAAS,SAAS,kBAC5C;QAAI,QAAQ,iBAAiB,IAAI,GAAG;GAAQ;GAE9C,QAAQ,iBAAiB,MAAM,MAAM;EACvC,QAAQ,CAAC;CACX;CAGF,IACE,CAAC,sCACDA,+BAAQ,QAAQ,kBAChB,SAAS,mBAET,KAAK,IAAI,IAAI,GAAG,IAAIA,+BAAQ,QAAQ,eAAe,QAAQ,KAAK;EAC9D,MAAM,EAAE,SAASA,+BAAQ,QAAQ,eAAe;EAChD,IAAI;GACF,IAAI,EAAE,SAAS,aAAa,SAAS,SAAS,mBAC5C;QAAI,QAAQ,kBAAkB,IAAI,GAAG;GAAQ;GAE/C,QAAQ,kBAAkB,MAAM,MAAM;EACxC,QAAQ,CAAC;CACX;CAGF,IACE,CAAC,8BACDA,+BAAQ,QAAQ,WAChB,SAAS,WAET,KAAK,IAAI,IAAI,GAAG,IAAIA,+BAAQ,QAAQ,QAAQ,QAAQ,KAClD,IAAI;EACF,QAAQ,UAAUA,+BAAQ,QAAQ,QAAQ,GAAG,MAAM,MAAM;CAC3D,QAAQ,CAAC;AAGf;;;;;;;AAQA,MAAa,iBAAiB,aAAmC;CAC/D,iBAAiB,qBAAqB,OAAO;CAC7C,YAAY,WAA0B,mBAAmB,QAAQ,OAAO;AAC1E"}
1
+ {"version":3,"file":"localeStorage.cjs","names":["internationalization","routing","getCookie"],"sources":["../../../src/utils/localeStorage.ts"],"sourcesContent":["import { internationalization, routing } from '@intlayer/config/built';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport type { CookiesAttributes } from '@intlayer/types/config';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport { getCookie } from './getCookie';\n\n// ── Tree-shake constants ──────────────────────────────────────────────────────\n// When these env vars are injected at build time, bundlers eliminate the\n// branches guarded by these constants.\n\n/**\n * True when cookie storage is explicitly disabled at build time.\n */\nconst TREE_SHAKE_STORAGE_COOKIES =\n process.env['INTLAYER_ROUTING_STORAGE_COOKIES'] === 'false';\n\n/**\n * True when localStorage is explicitly disabled at build time.\n */\nconst TREE_SHAKE_STORAGE_LOCAL_STORAGE =\n process.env['INTLAYER_ROUTING_STORAGE_LOCALSTORAGE'] === 'false';\n\n/**\n * True when sessionStorage is explicitly disabled at build time.\n */\nconst TREE_SHAKE_STORAGE_SESSION_STORAGE =\n process.env['INTLAYER_ROUTING_STORAGE_SESSIONSTORAGE'] === 'false';\n\n/**\n * True when header storage is explicitly disabled at build time.\n */\nconst TREE_SHAKE_STORAGE_HEADERS =\n process.env['INTLAYER_ROUTING_STORAGE_HEADERS'] === 'false';\n\n// ============================================================================\n// Shared types\n// ============================================================================\n\nexport type CookieBuildAttributes = {\n domain?: string;\n path?: string;\n secure?: boolean;\n httpOnly?: boolean;\n sameSite?: 'strict' | 'lax' | 'none';\n /** Expiry as milliseconds since epoch (Date.getTime()) or number of days */\n expires?: number | undefined;\n};\n\n// ============================================================================\n// Shared helpers\n// ============================================================================\n\nconst buildCookieString = (\n name: string,\n value: string,\n attributes: Omit<CookiesAttributes, 'name' | 'type'>\n): string => {\n const encodedValue = encodeURIComponent(value);\n const parts: string[] = [`${name}=${encodedValue}`];\n\n if (attributes.path) parts.push(`Path=${attributes.path}`);\n if (attributes.domain) parts.push(`Domain=${attributes.domain}`);\n if (attributes.expires instanceof Date)\n parts.push(`Expires=${attributes.expires.toUTCString()}`);\n if (attributes.secure) parts.push('Secure');\n if (attributes.sameSite) parts.push(`SameSite=${attributes.sameSite}`);\n return parts.join('; ');\n};\n\n// ============================================================================\n// Client-specific types and functions\n// (cookies via browser APIs, localStorage, sessionStorage — no headers)\n// ============================================================================\n\nexport type LocaleStorageClientOptions = {\n overwrite?: boolean;\n isCookieEnabled?: boolean;\n setCookieStore?: (\n name: string,\n value: string,\n cookie: CookieBuildAttributes\n ) => void;\n setCookieString?: (name: string, cookie: string) => void;\n getCookie?: (name: string) => string | undefined | null;\n setSessionStorage?: (name: string, value: string) => void;\n getSessionStorage?: (name: string) => string | undefined | null;\n setLocaleStorage?: (name: string, value: string) => void;\n getLocaleStorage?: (name: string) => string | undefined | null;\n};\n\n// cookieStore is part of the experimental Cookie Store API\ndeclare const cookieStore: any;\n\nexport const localeStorageOptions: LocaleStorageClientOptions = {\n getCookie: (name: string) =>\n document.cookie\n .split(';')\n .find((c) => c.trim().startsWith(`${name}=`))\n ?.split('=')[1],\n getLocaleStorage: (name: string) => localStorage.getItem(name),\n getSessionStorage: (name: string) => sessionStorage.getItem(name),\n isCookieEnabled: true,\n setCookieStore: (name, value, attributes) =>\n cookieStore.set({\n name,\n value,\n path: attributes.path,\n domain: attributes.domain,\n expires: attributes.expires,\n sameSite: attributes.sameSite,\n }),\n setCookieString: (_name, cookie) => {\n // biome-ignore lint/suspicious/noDocumentCookie: set cookie fallback\n document.cookie = cookie;\n },\n setSessionStorage: (name, value) => sessionStorage.setItem(name, value),\n setLocaleStorage: (name, value) => localStorage.setItem(name, value),\n};\n\n/**\n * Retrieves the locale from browser storage mechanisms\n * (cookies, localStorage, sessionStorage).\n * Does not read from headers — use `getLocaleFromStorageServer` for that.\n */\nexport const getLocaleFromStorageClient = (\n options: LocaleStorageClientOptions = localeStorageOptions\n): Locale | undefined => {\n const { locales } = internationalization;\n\n if (options?.isCookieEnabled === false) return undefined;\n\n const isValidLocale = (value: string | null | undefined): value is Locale =>\n !!value && locales.includes(value as Locale);\n\n if (!TREE_SHAKE_STORAGE_COOKIES) {\n for (let i = 0; i < (routing.storage.cookies ?? []).length; i++) {\n try {\n const value = options?.getCookie?.(routing.storage.cookies![i].name);\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n\n if (!TREE_SHAKE_STORAGE_LOCAL_STORAGE) {\n for (let i = 0; i < (routing.storage.localStorage ?? []).length; i++) {\n try {\n const value = options?.getLocaleStorage?.(\n routing.storage.localStorage![i].name\n );\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n\n if (!TREE_SHAKE_STORAGE_SESSION_STORAGE && routing.storage.sessionStorage) {\n for (let i = 0; i < routing.storage.sessionStorage.length; i++) {\n try {\n const value = options?.getSessionStorage?.(\n routing.storage.sessionStorage[i].name\n );\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n};\n\n/**\n * Stores the locale in browser storage mechanisms\n * (cookies, localStorage, sessionStorage).\n * Does not write to headers — use `setLocaleInStorageServer` for that.\n */\nexport const setLocaleInStorageClient = (\n locale: LocalesValues,\n options?: LocaleStorageClientOptions\n): void => {\n if (options?.isCookieEnabled === false) return;\n\n if (!TREE_SHAKE_STORAGE_COOKIES && routing.storage.cookies) {\n for (let i = 0; i < routing.storage.cookies.length; i++) {\n const { name, attributes } = routing.storage.cookies[i];\n try {\n if (options?.setCookieStore) {\n options.setCookieStore(name, locale, {\n ...attributes,\n expires:\n attributes.expires instanceof Date\n ? attributes.expires.getTime()\n : attributes.expires,\n });\n }\n } catch {\n try {\n if (options?.setCookieString) {\n options.setCookieString(\n name,\n buildCookieString(name, locale, attributes)\n );\n }\n } catch {}\n }\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_LOCAL_STORAGE &&\n routing.storage.localStorage &&\n options?.setLocaleStorage\n ) {\n for (let i = 0; i < routing.storage.localStorage.length; i++) {\n const { name } = routing.storage.localStorage[i];\n try {\n if (!(options?.overwrite ?? true) && options?.getLocaleStorage) {\n if (options.getLocaleStorage(name)) continue;\n }\n options.setLocaleStorage(name, locale);\n } catch {}\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_SESSION_STORAGE &&\n routing.storage.sessionStorage &&\n options?.setSessionStorage\n ) {\n for (let i = 0; i < routing.storage.sessionStorage.length; i++) {\n const { name } = routing.storage.sessionStorage[i];\n try {\n if (!(options?.overwrite ?? true) && options?.getSessionStorage) {\n if (options.getSessionStorage(name)) continue;\n }\n options.setSessionStorage(name, locale);\n } catch {}\n }\n }\n};\n\n/**\n * Client-side locale storage utility.\n * Handles cookies (browser), localStorage and sessionStorage.\n * Does not access headers.\n *\n * @example\n * ```ts\n * const storage = LocaleStorageClient(localeStorageOptions);\n * const locale = storage.getLocale();\n * storage.setLocale('fr');\n * ```\n */\nexport const LocaleStorageClient = (options: LocaleStorageClientOptions) => ({\n getLocale: () => getLocaleFromStorageClient(options),\n setLocale: (locale: LocalesValues) =>\n setLocaleInStorageClient(locale, options),\n});\n\n// ============================================================================\n// Server-specific types and functions\n// (cookies via injected getter/setter, headers — no localStorage/sessionStorage)\n// ============================================================================\n\nexport type LocaleStorageServerOptions = {\n overwrite?: boolean;\n isCookieEnabled?: boolean;\n setCookieStore?: (\n name: string,\n value: string,\n cookie: CookieBuildAttributes\n ) => void;\n setCookieString?: (name: string, cookie: string) => void;\n getCookie?: (name: string) => string | undefined | null;\n getHeader?: (name: string) => string | undefined | null;\n setHeader?: (name: string, value: string) => void;\n};\n\n/**\n * Retrieves the locale from server-side storage mechanisms (cookies, headers).\n * Does not access localStorage or sessionStorage.\n * No browser cookie fallback — the caller must provide `getCookie`.\n */\nexport const getLocaleFromStorageServer = (\n options: LocaleStorageServerOptions\n): Locale | undefined => {\n const { locales } = internationalization;\n\n if (options?.isCookieEnabled === false) return undefined;\n\n const isValidLocale = (value: string | null | undefined): value is Locale =>\n !!value && locales.includes(value as Locale);\n\n if (!TREE_SHAKE_STORAGE_COOKIES && routing.storage.cookies) {\n for (let i = 0; i < routing.storage.cookies.length; i++) {\n try {\n const value = options?.getCookie?.(routing.storage.cookies[i].name);\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n\n if (!TREE_SHAKE_STORAGE_HEADERS && routing.storage.headers) {\n for (let i = 0; i < routing.storage.headers.length; i++) {\n try {\n const value = options?.getHeader?.(routing.storage.headers[i].name);\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n};\n\n/**\n * Stores the locale in server-side storage mechanisms (cookies, headers).\n * Does not write to localStorage or sessionStorage.\n */\nexport const setLocaleInStorageServer = (\n locale: LocalesValues,\n options?: LocaleStorageServerOptions\n): void => {\n if (options?.isCookieEnabled === false) return;\n\n if (!TREE_SHAKE_STORAGE_COOKIES && routing.storage.cookies) {\n for (let i = 0; i < routing.storage.cookies.length; i++) {\n const { name, attributes } = routing.storage.cookies[i];\n\n try {\n if (options?.setCookieStore) {\n options.setCookieStore(name, locale, {\n ...attributes,\n expires:\n attributes.expires instanceof Date\n ? attributes.expires.getTime()\n : attributes.expires,\n });\n }\n } catch {\n try {\n if (options?.setCookieString) {\n options.setCookieString(\n name,\n buildCookieString(name, locale, attributes)\n );\n }\n } catch {}\n }\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_HEADERS &&\n routing.storage.headers &&\n options?.setHeader\n ) {\n for (let i = 0; i < routing.storage.headers.length; i++) {\n try {\n options.setHeader(routing.storage.headers[i].name, locale);\n } catch {}\n }\n }\n};\n\n/**\n * Server-side locale storage utility.\n * Handles cookies (via injected getter/setter) and headers.\n * Does not access localStorage or sessionStorage.\n *\n * @example\n * ```ts\n * const storage = LocaleStorageServer({\n * getCookie: (name) => req.cookies[name],\n * setCookieStore: (name, value, attrs) => res.cookie(name, value, attrs),\n * getHeader: (name) => req.headers[name],\n * setHeader: (name, value) => res.setHeader(name, value),\n * });\n * const locale = storage.getLocale();\n * storage.setLocale('fr');\n * ```\n */\nexport const LocaleStorageServer = (options: LocaleStorageServerOptions) => ({\n getLocale: () => getLocaleFromStorageServer(options),\n setLocale: (locale: LocalesValues) =>\n setLocaleInStorageServer(locale, options),\n});\n\n// ============================================================================\n// Deprecated: combined LocaleStorage\n// Use LocaleStorageClient or LocaleStorageServer instead\n// ============================================================================\n\n/**\n * @deprecated Use {@link LocaleStorageClientOptions} or {@link LocaleStorageServerOptions} instead.\n */\nexport type LocaleStorageOptions = LocaleStorageClientOptions &\n LocaleStorageServerOptions;\n\n/**\n * Retrieves the locale from all storage mechanisms\n * (cookies, localStorage, sessionStorage, headers).\n *\n * @deprecated Use {@link getLocaleFromStorageClient} (browser) or\n * {@link getLocaleFromStorageServer} (server) instead.\n */\nexport const getLocaleFromStorage = (\n options: Pick<\n LocaleStorageOptions,\n | 'getCookie'\n | 'getSessionStorage'\n | 'getLocaleStorage'\n | 'getHeader'\n | 'isCookieEnabled'\n >\n): Locale | undefined => {\n const { locales } = internationalization;\n\n if (options?.isCookieEnabled === false) return undefined;\n\n const isValidLocale = (value: string | null | undefined): value is Locale =>\n !!value && locales.includes(value as Locale);\n\n const readCookie = (name: string): string | undefined => {\n try {\n const fromOption = options?.getCookie?.(name);\n if (fromOption !== null && fromOption !== undefined) return fromOption;\n } catch {}\n // Browser fallback kept for backward compatibility\n return getCookie(name);\n };\n\n if (!TREE_SHAKE_STORAGE_COOKIES && routing.storage.cookies) {\n for (let i = 0; i < routing.storage.cookies.length; i++) {\n const value = readCookie(routing.storage.cookies[i].name);\n if (isValidLocale(value)) return value;\n }\n }\n\n if (!TREE_SHAKE_STORAGE_LOCAL_STORAGE && routing.storage.localStorage) {\n for (let i = 0; i < routing.storage.localStorage.length; i++) {\n try {\n const value = options?.getLocaleStorage?.(\n routing.storage.localStorage[i].name\n );\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n\n if (!TREE_SHAKE_STORAGE_SESSION_STORAGE && routing.storage.sessionStorage) {\n for (let i = 0; i < routing.storage.sessionStorage.length; i++) {\n try {\n const value = options?.getSessionStorage?.(\n routing.storage.sessionStorage[i].name\n );\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n\n if (!TREE_SHAKE_STORAGE_HEADERS && routing.storage.headers) {\n for (let i = 0; i < routing.storage.headers.length; i++) {\n try {\n const value = options?.getHeader?.(routing.storage.headers[i].name);\n if (isValidLocale(value)) return value;\n } catch {}\n }\n }\n};\n\n/**\n * Stores the locale in all configured storage mechanisms\n * (cookies, localStorage, sessionStorage, headers).\n *\n * @deprecated Use {@link setLocaleInStorageClient} (browser) or\n * {@link setLocaleInStorageServer} (server) instead.\n */\nexport const setLocaleInStorage = (\n locale: LocalesValues,\n options?: LocaleStorageOptions\n): void => {\n if (options?.isCookieEnabled === false) return;\n\n if (!TREE_SHAKE_STORAGE_COOKIES && routing.storage.cookies) {\n for (let i = 0; i < routing.storage.cookies.length; i++) {\n const { name, attributes } = routing.storage.cookies[i];\n try {\n if (options?.setCookieStore) {\n options.setCookieStore(name, locale, {\n ...attributes,\n expires:\n attributes.expires instanceof Date\n ? attributes.expires.getTime()\n : attributes.expires,\n });\n }\n } catch {\n try {\n if (options?.setCookieString) {\n options.setCookieString(\n name,\n buildCookieString(name, locale, attributes)\n );\n }\n } catch {}\n }\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_LOCAL_STORAGE &&\n routing.storage.localStorage &&\n options?.setLocaleStorage\n ) {\n for (let i = 0; i < routing.storage.localStorage.length; i++) {\n const { name } = routing.storage.localStorage[i];\n try {\n if (!(options?.overwrite ?? true) && options?.getLocaleStorage) {\n if (options.getLocaleStorage(name)) continue;\n }\n options.setLocaleStorage(name, locale);\n } catch {}\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_SESSION_STORAGE &&\n routing.storage.sessionStorage &&\n options?.setSessionStorage\n ) {\n for (let i = 0; i < routing.storage.sessionStorage.length; i++) {\n const { name } = routing.storage.sessionStorage[i];\n try {\n if (!(options?.overwrite ?? true) && options?.getSessionStorage) {\n if (options.getSessionStorage(name)) continue;\n }\n options.setSessionStorage(name, locale);\n } catch {}\n }\n }\n\n if (\n !TREE_SHAKE_STORAGE_HEADERS &&\n routing.storage.headers &&\n options?.setHeader\n ) {\n for (let i = 0; i < routing.storage.headers.length; i++) {\n try {\n options.setHeader(routing.storage.headers[i].name, locale);\n } catch {}\n }\n }\n};\n\n/**\n * Utility object to get and set the locale in storage based on configuration.\n *\n * @deprecated Use {@link LocaleStorageClient} (browser) or\n * {@link LocaleStorageServer} (server) instead.\n */\nexport const LocaleStorage = (options: LocaleStor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MAAM,MAAM;EACxC,QAAQ,CAAC;CACX;CAGF,IACE,CAAC,8BACDA,+BAAQ,QAAQ,WAChB,SAAS,WAET,KAAK,IAAI,IAAI,GAAG,IAAIA,+BAAQ,QAAQ,QAAQ,QAAQ,KAClD,IAAI;EACF,QAAQ,UAAUA,+BAAQ,QAAQ,QAAQ,GAAG,MAAM,MAAM;CAC3D,QAAQ,CAAC;AAGf;;;;;;;AAQA,MAAa,iBAAiB,aAAmC;CAC/D,iBAAiB,qBAAqB,OAAO;CAC7C,YAAY,WAA0B,mBAAmB,QAAQ,OAAO;AAC1E"}
@@ -65,10 +65,10 @@ import { getLocalizedUrl } from "./localization/getLocalizedUrl.mjs";
65
65
  import { getMultilingualUrls } from "./localization/getMultilingualUrls.mjs";
66
66
  import { generateSitemap, generateSitemapUrl } from "./localization/generateSitemap.mjs";
67
67
  import { getCookie } from "./utils/getCookie.mjs";
68
- import { LocaleStorage, LocaleStorageClient, LocaleStorageServer, getLocaleFromStorage, getLocaleFromStorageClient, getLocaleFromStorageServer, setLocaleInStorage, setLocaleInStorageClient, setLocaleInStorageServer } from "./utils/localeStorage.mjs";
68
+ import { LocaleStorage, LocaleStorageClient, LocaleStorageServer, getLocaleFromStorage, getLocaleFromStorageClient, getLocaleFromStorageServer, localeStorageOptions, setLocaleInStorage, setLocaleInStorageClient, setLocaleInStorageServer } from "./utils/localeStorage.mjs";
69
69
  import { localeResolver } from "./localization/localeResolver.mjs";
70
70
  import { localeDetector } from "./localization/localeDetector.mjs";
71
- import { getBrowserLocale, localeStorageOptions } from "./localization/getBrowserLocale.mjs";
71
+ import { getBrowserLocale } from "./localization/getBrowserLocale.mjs";
72
72
  import { getHTMLTextDir } from "./localization/getHTMLTextDir.mjs";
73
73
  import { getLocale } from "./localization/getLocale.mjs";
74
74
  import { getLocaleFromPath } from "./localization/getLocaleFromPath.mjs";
@@ -80,7 +80,7 @@ import { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, B
80
80
  import { allowInline, anyScopeRegex, attributeValueToNodePropValue, blockRegex, captureNothing, cx, get, inlineRegex, normalizeAttributeKey, normalizeWhitespace, parseBlock, parseCaptureInline, parseInline, parseSimpleInline, parseStyleAttribute, parseTableAlign, parseTableAlignCapture, parseTableCells, parseTableRow, qualifies, renderNothing, sanitizer, simpleInlineRegex, slugify, some, startsWith, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, unquote } from "./markdown/utils.mjs";
81
81
  import { parserFor } from "./markdown/parser.mjs";
82
82
  import { createRenderer, renderFor } from "./markdown/renderer.mjs";
83
- import { compile, compileWithOptions, createCompiler } from "./markdown/compiler.mjs";
83
+ import { compile, compileWithOptions, createCompiler, parseMarkdown, renderMarkdownAst } from "./markdown/compiler.mjs";
84
84
  import { icuToIntlayerFormatter, intlayerToICUFormatter } from "./messageFormat/ICU.mjs";
85
85
  import { i18nextToIntlayerFormatter, intlayerToI18nextFormatter } from "./messageFormat/i18next.mjs";
86
86
  import { intlayerToPortableObjectFormatter, portableObjectToIntlayerFormatter } from "./messageFormat/po.mjs";
@@ -88,4 +88,4 @@ import { intlayerToVueI18nFormatter, vueI18nToIntlayerFormatter } from "./messag
88
88
  import { isSameKeyPath } from "./utils/isSameKeyPath.mjs";
89
89
  import { stringifyYaml } from "./utils/stringifyYaml.mjs";
90
90
 
91
- export { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, CAPTURE_LETTER_AFTER_HYPHEN, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, CONSECUTIVE_NEWLINE_R, CR_NEWLINE_R, CUSTOM_COMPONENT_R, CachedIntl, CachedIntl as Intl, DO_NOT_PROCESS_HTML_ELEMENTS, DURATION_DELAY_TRIGGER, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FORMFEED_R, FRONT_MATTER_R, GFM_TASK_R, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, HTML_BLOCK_ELEMENT_R, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_CUSTOM_ATTR_R, HTML_LEFT_TRIM_AMOUNT_R, HTML_SELF_CLOSING_ELEMENT_R, HTML_TAGS, INLINE_SKIP_R, INTERPOLATION_R, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, LIST_LOOKBEHIND_R, LOOKAHEAD, LocaleStorage, LocaleStorageClient, LocaleStorageServer, NAMED_CODES_TO_UNICODE, NP_TABLE_R, ORDERED, ORDERED_LIST_BULLET, ORDERED_LIST_ITEM_PREFIX, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, PARAGRAPH_R, Priority, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, RuleType, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, TAB_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_PLAIN_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, UNESCAPE_R, UNORDERED, UNORDERED_LIST_BULLET, UNORDERED_LIST_ITEM_PREFIX, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R, VOID_HTML_ELEMENTS, allowInline, anyScopeRegex, attributeValueToNodePropValue, bindIntl, blockRegex, buildMaskPlugin, captureNothing, checkIsURLAbsolute, checkMissingLocalesPlugin, compact, compile, compileWithOptions, condition as cond, conditionPlugin, createCompiler, createRenderer, currency, cx, date, deepTransformNode, editDictionaryByKeyPath, enumeration as enu, enumerationPlugin, fallbackPlugin, filePlugin, filterMissingTranslationsOnlyPlugin, filterTranslationsOnlyPlugin, findMatchingCondition, gender, genderPlugin, generateListItemPrefix, generateListItemPrefixRegex, generateListItemRegex, generateListRegex, generateSitemap, generateSitemapUrl, get, getBasePlugins, getBrowserLocale, getCachedIntl, getCanonicalPath, getCondition, getContent, getContentNodeByKeyPath, getCookie, getDefaultNode, getDictionary, getEmptyNode, getEnumeration, getFilterMissingTranslationsContent, getFilterMissingTranslationsDictionary, getFilterTranslationsOnlyContent, getFilterTranslationsOnlyDictionary, getFilteredLocalesContent, getFilteredLocalesDictionary, getHTML, getHTMLTextDir, getInsertionValues, getInternalPath, getIntlayer, getLocale, getLocaleFromPath, getLocaleFromStorage, getLocaleFromStorageClient, getLocaleFromStorageServer, getLocaleLang, getLocaleName, getLocalizedContent, getLocalizedPath, getLocalizedUrl, getMarkdownMetadata, getMaskContent, getMissingLocalesContent, getMissingLocalesContentFromDictionary, getMultilingualDictionary, getMultilingualUrls, getNesting, getNodeChildren, getNodeType, getPathWithoutLocale, getPerLocaleDictionary, getPlural, getPrefix, getReplacedValuesContent, getRewritePath, getRewriteRules, getSplittedContent, getSplittedDictionaryContent, getTranslation, html, i18nextToIntlayerFormatter, icuToIntlayerFormatter, inlineRegex, insertion as insert, insertContentInDictionary, insertionPlugin, intlayerToI18nextFormatter, intlayerToICUFormatter, intlayerToPortableObjectFormatter, intlayerToVueI18nFormatter, isSameKeyPath, isValidElement, list, localeDetector, localeFlatMap, localeMap, localeRecord, localeResolver, localeStorageOptions, markdown as md, mergeDictionaries, nesting as nest, nestedPlugin, normalizeAttributeKey, normalizeDictionaries, normalizeDictionary, normalizeWhitespace, number, orderDictionaries, parseBlock, parseCaptureInline, parseInline, parseSimpleInline, parseStyleAttribute, parseTableAlign, parseTableAlignCapture, parseTableCells, parseTableRow, parseYaml, parserFor, percentage, plural, pluralPlugin, portableObjectToIntlayerFormatter, presets, qualifies, relativeTime, removeContentNodeByKeyPath, renameContentNodeByKeyPath, renderFor, renderNothing, sanitizer, setLocaleInStorage, setLocaleInStorageClient, setLocaleInStorageServer, simpleInlineRegex, slugify, some, splitInsertionTemplate, startsWith, stringifyYaml, translation as t, translationPlugin, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, units, unquote, updateNodeChildren, validateHTML, validateMarkdown, validatePrefix, vueI18nToIntlayerFormatter };
91
+ export { ATTRIBUTES_TO_SANITIZE, ATTRIBUTE_TO_NODE_PROP_MAP, ATTR_EXTRACTOR_R, BLOCKQUOTE_ALERT_R, BLOCKQUOTE_R, BLOCKQUOTE_TRIM_LEFT_MULTILINE_R, BLOCK_END_R, BREAK_LINE_R, BREAK_THEMATIC_R, CAPTURE_LETTER_AFTER_HYPHEN, CODE_BLOCK_FENCED_R, CODE_BLOCK_R, CODE_INLINE_R, CONSECUTIVE_NEWLINE_R, CR_NEWLINE_R, CUSTOM_COMPONENT_R, CachedIntl, CachedIntl as Intl, DO_NOT_PROCESS_HTML_ELEMENTS, DURATION_DELAY_TRIGGER, FOOTNOTE_R, FOOTNOTE_REFERENCE_R, FORMFEED_R, FRONT_MATTER_R, GFM_TASK_R, HEADING_ATX_COMPLIANT_R, HEADING_R, HEADING_SETEXT_R, HTML_BLOCK_ELEMENT_R, HTML_CHAR_CODE_R, HTML_COMMENT_R, HTML_CUSTOM_ATTR_R, HTML_LEFT_TRIM_AMOUNT_R, HTML_SELF_CLOSING_ELEMENT_R, HTML_TAGS, INLINE_SKIP_R, INTERPOLATION_R, LINK_AUTOLINK_BARE_URL_R, LINK_AUTOLINK_R, LIST_LOOKBEHIND_R, LOOKAHEAD, LocaleStorage, LocaleStorageClient, LocaleStorageServer, NAMED_CODES_TO_UNICODE, NP_TABLE_R, ORDERED, ORDERED_LIST_BULLET, ORDERED_LIST_ITEM_PREFIX, ORDERED_LIST_ITEM_PREFIX_R, ORDERED_LIST_ITEM_R, ORDERED_LIST_R, PARAGRAPH_R, Priority, REFERENCE_IMAGE_OR_LINK, REFERENCE_IMAGE_R, REFERENCE_LINK_R, RuleType, SHORTCODE_R, SHOULD_RENDER_AS_BLOCK_R, TABLE_CENTER_ALIGN, TABLE_LEFT_ALIGN, TABLE_RIGHT_ALIGN, TABLE_TRIM_PIPES, TAB_R, TEXT_BOLD_R, TEXT_EMPHASIZED_R, TEXT_ESCAPED_R, TEXT_MARKED_R, TEXT_PLAIN_R, TEXT_STRIKETHROUGHED_R, TRIM_STARTING_NEWLINES, UNESCAPE_R, UNORDERED, UNORDERED_LIST_BULLET, UNORDERED_LIST_ITEM_PREFIX, UNORDERED_LIST_ITEM_PREFIX_R, UNORDERED_LIST_ITEM_R, UNORDERED_LIST_R, VOID_HTML_ELEMENTS, allowInline, anyScopeRegex, attributeValueToNodePropValue, bindIntl, blockRegex, buildMaskPlugin, captureNothing, checkIsURLAbsolute, checkMissingLocalesPlugin, compact, compile, compileWithOptions, condition as cond, conditionPlugin, createCompiler, createRenderer, currency, cx, date, deepTransformNode, editDictionaryByKeyPath, enumeration as enu, enumerationPlugin, fallbackPlugin, filePlugin, filterMissingTranslationsOnlyPlugin, filterTranslationsOnlyPlugin, findMatchingCondition, gender, genderPlugin, generateListItemPrefix, generateListItemPrefixRegex, generateListItemRegex, generateListRegex, generateSitemap, generateSitemapUrl, get, getBasePlugins, getBrowserLocale, getCachedIntl, getCanonicalPath, getCondition, getContent, getContentNodeByKeyPath, getCookie, getDefaultNode, getDictionary, getEmptyNode, getEnumeration, getFilterMissingTranslationsContent, getFilterMissingTranslationsDictionary, getFilterTranslationsOnlyContent, getFilterTranslationsOnlyDictionary, getFilteredLocalesContent, getFilteredLocalesDictionary, getHTML, getHTMLTextDir, getInsertionValues, getInternalPath, getIntlayer, getLocale, getLocaleFromPath, getLocaleFromStorage, getLocaleFromStorageClient, getLocaleFromStorageServer, getLocaleLang, getLocaleName, getLocalizedContent, getLocalizedPath, getLocalizedUrl, getMarkdownMetadata, getMaskContent, getMissingLocalesContent, getMissingLocalesContentFromDictionary, getMultilingualDictionary, getMultilingualUrls, getNesting, getNodeChildren, getNodeType, getPathWithoutLocale, getPerLocaleDictionary, getPlural, getPrefix, getReplacedValuesContent, getRewritePath, getRewriteRules, getSplittedContent, getSplittedDictionaryContent, getTranslation, html, i18nextToIntlayerFormatter, icuToIntlayerFormatter, inlineRegex, insertion as insert, insertContentInDictionary, insertionPlugin, intlayerToI18nextFormatter, intlayerToICUFormatter, intlayerToPortableObjectFormatter, intlayerToVueI18nFormatter, isSameKeyPath, isValidElement, list, localeDetector, localeFlatMap, localeMap, localeRecord, localeResolver, localeStorageOptions, markdown as md, mergeDictionaries, nesting as nest, nestedPlugin, normalizeAttributeKey, normalizeDictionaries, normalizeDictionary, normalizeWhitespace, number, orderDictionaries, parseBlock, parseCaptureInline, parseInline, parseMarkdown, parseSimpleInline, parseStyleAttribute, parseTableAlign, parseTableAlignCapture, parseTableCells, parseTableRow, parseYaml, parserFor, percentage, plural, pluralPlugin, portableObjectToIntlayerFormatter, presets, qualifies, relativeTime, removeContentNodeByKeyPath, renameContentNodeByKeyPath, renderFor, renderMarkdownAst, renderNothing, sanitizer, setLocaleInStorage, setLocaleInStorageClient, setLocaleInStorageServer, simpleInlineRegex, slugify, some, splitInsertionTemplate, startsWith, stringifyYaml, translation as t, translationPlugin, trimEnd, trimLeadingWhitespaceOutsideFences, unescapeString, units, unquote, updateNodeChildren, validateHTML, validateMarkdown, validatePrefix, vueI18nToIntlayerFormatter };
@@ -1 +1 @@
1
- {"version":3,"file":"getCondition.mjs","names":[],"sources":["../../../src/interpreter/getCondition.ts"],"sourcesContent":["import type { ConditionContentStates } from '../transpiler';\n\n/**\n * Picks content based on a boolean condition.\n *\n * @param conditionContent - A map with 'true', 'false', and optionally 'fallback' keys.\n * @param state - The boolean state to match.\n * @returns The matching content.\n *\n * @example\n * ```ts\n * const content = getCondition({\n * 'true': 'The condition is validated',\n * 'false': 'The condition is not validated',\n * }, true);\n * // 'The condition is validated'\n * ```\n */\nexport const getCondition = <Content>(\n conditionContent: ConditionContentStates<Content>,\n state?: boolean\n): Content => {\n const stateList = Object.keys(conditionContent);\n const fallbackState = stateList[\n stateList.length - 1\n ] as keyof typeof conditionContent;\n\n // Default or error handling if no keys match\n return (\n conditionContent[`${state}` as keyof typeof conditionContent] ??\n conditionContent.fallback ??\n (conditionContent[fallbackState] as Content)\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,MAAa,gBACX,kBACA,UACY;CACZ,MAAM,YAAY,OAAO,KAAK,gBAAgB;CAC9C,MAAM,gBAAgB,UACpB,UAAU,SAAS;CAIrB,OACE,iBAAiB,GAAG,YACpB,iBAAiB,YAChB,iBAAiB;AAEtB"}
1
+ {"version":3,"file":"getCondition.mjs","names":[],"sources":["../../../src/interpreter/getCondition.ts"],"sourcesContent":["import type { ConditionContentStates } from '../transpiler';\n\n/**\n * Picks content based on a boolean condition.\n *\n * @param conditionContent - A map with 'true', 'false', and optionally 'fallback' keys.\n * @param state - The boolean state to match.\n * @returns The matching content.\n *\n * @example\n * ```ts\n * const content = getCondition({\n * 'true': 'The condition is validated',\n * 'false': 'The condition is not validated',\n * }, true);\n * // 'The condition is validated'\n * ```\n */\nexport const getCondition = <const Content>(\n conditionContent: ConditionContentStates<Content>,\n state?: boolean\n): Content => {\n const stateList = Object.keys(conditionContent);\n const fallbackState = stateList[\n stateList.length - 1\n ] as keyof typeof conditionContent;\n\n // Default or error handling if no keys match\n return (\n conditionContent[`${state}` as keyof typeof conditionContent] ??\n conditionContent.fallback ??\n (conditionContent[fallbackState] as Content)\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,MAAa,gBACX,kBACA,UACY;CACZ,MAAM,YAAY,OAAO,KAAK,gBAAgB;CAC9C,MAAM,gBAAgB,UACpB,UAAU,SAAS;CAIrB,OACE,iBAAiB,GAAG,YACpB,iBAAiB,YAChB,iBAAiB;AAEtB"}
@@ -1 +1 @@
1
- {"version":3,"file":"getContent.mjs","names":[],"sources":["../../../../src/interpreter/getContent/getContent.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { ContentNode } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { deepTransformNode } from './deepTransform';\nimport {\n conditionPlugin,\n type DeepTransformContent,\n enumerationPlugin,\n filePlugin,\n genderPlugin,\n type IInterpreterPluginState,\n insertionPlugin,\n type NodeProps,\n nestedPlugin,\n type Plugins,\n translationPlugin,\n} from './plugins';\n\nexport const getBasePlugins = (\n locale?: LocalesValues,\n fallback: boolean = true\n): Plugins[] =>\n [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n conditionPlugin,\n insertionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n ] as Plugins[];\n\n/**\n * Transforms a node in a single pass, applying each plugin as needed.\n *\n * @param node The node to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n */\nexport const getContent = <\n T extends ContentNode,\n L extends LocalesValues = DeclaredLocales,\n>(\n node: T,\n nodeProps: NodeProps,\n plugins: Plugins[] = []\n) =>\n deepTransformNode(node, {\n ...nodeProps,\n plugins,\n }) as DeepTransformContent<T, IInterpreterPluginState, L>;\n"],"mappings":";;;;;AAqBA,MAAa,kBACX,QACA,WAAoB,SAEpB;CACE,kBACE,UAAU,qBAAqB,eAC/B,WAAW,qBAAqB,gBAAgB,MAClD;CACA;CACA;CACA;CACA,aAAa,UAAU,qBAAqB,aAAa;CACzD;CACA;AACF;;;;;;;AAQF,MAAa,cAIX,MACA,WACA,UAAqB,CAAC,MAEtB,kBAAkB,MAAM;CACtB,GAAG;CACH;AACF,CAAC"}
1
+ {"version":3,"file":"getContent.mjs","names":[],"sources":["../../../../src/interpreter/getContent/getContent.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { ContentNode } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { deepTransformNode } from './deepTransform';\nimport {\n conditionPlugin,\n type DeepTransformContent,\n enumerationPlugin,\n filePlugin,\n genderPlugin,\n type IInterpreterPluginState,\n insertionPlugin,\n type NodeProps,\n nestedPlugin,\n type Plugins,\n translationPlugin,\n} from './plugins';\n\nexport const getBasePlugins = (\n locale?: LocalesValues,\n fallback: boolean = true\n): Plugins[] =>\n [\n translationPlugin(\n locale ?? internationalization.defaultLocale,\n fallback ? internationalization.defaultLocale : undefined\n ),\n enumerationPlugin,\n conditionPlugin,\n insertionPlugin,\n nestedPlugin(locale ?? internationalization.defaultLocale),\n filePlugin,\n genderPlugin,\n ] as Plugins[];\n\n/**\n * Transforms a node in a single pass, applying each plugin as needed.\n *\n * @param node The node to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n */\nexport const getContent = <\n const T extends ContentNode,\n const L extends LocalesValues = DeclaredLocales,\n>(\n node: T,\n nodeProps: NodeProps,\n plugins: Plugins[] = []\n) =>\n deepTransformNode(node, {\n ...nodeProps,\n plugins,\n }) as DeepTransformContent<T, IInterpreterPluginState, L>;\n"],"mappings":";;;;;AAqBA,MAAa,kBACX,QACA,WAAoB,SAEpB;CACE,kBACE,UAAU,qBAAqB,eAC/B,WAAW,qBAAqB,gBAAgB,MAClD;CACA;CACA;CACA;CACA,aAAa,UAAU,qBAAqB,aAAa;CACzD;CACA;AACF;;;;;;;AAQF,MAAa,cAIX,MACA,WACA,UAAqB,CAAC,MAEtB,kBAAkB,MAAM;CACtB,GAAG;CACH;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"getDictionary.mjs","names":[],"sources":["../../../src/interpreter/getDictionary.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n NodeProps,\n Plugins,\n} from './getContent';\nimport { getBasePlugins, getContent } from './getContent/getContent';\n\n/**\n * Transforms a dictionary in a single pass, applying each plugin as needed.\n *\n * @param dictionary The dictionary to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n * @param additionalPlugins An array of NodeTransformer that define how to transform recognized nodes.\n * If omitted, we’ll use a default set of plugins.\n */\nexport const getDictionary = <\n T extends Dictionary,\n L extends LocalesValues = DeclaredLocales,\n>(\n dictionary: T,\n locale?: L,\n plugins: Plugins[] = getBasePlugins(locale)\n): DeepTransformContent<T['content'], IInterpreterPluginState, L> => {\n const props: NodeProps = {\n dictionaryKey: dictionary.key,\n dictionaryPath: dictionary.filePath,\n keyPath: [],\n plugins,\n };\n\n return getContent(dictionary.content, props, plugins);\n};\n"],"mappings":";;;;;;;;;;;AAqBA,MAAa,iBAIX,YACA,QACA,UAAqB,eAAe,MAAM,MACyB;CACnE,MAAM,QAAmB;EACvB,eAAe,WAAW;EAC1B,gBAAgB,WAAW;EAC3B,SAAS,CAAC;EACV;CACF;CAEA,OAAO,WAAW,WAAW,SAAS,OAAO,OAAO;AACtD"}
1
+ {"version":3,"file":"getDictionary.mjs","names":[],"sources":["../../../src/interpreter/getDictionary.ts"],"sourcesContent":["import type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DeclaredLocales,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n NodeProps,\n Plugins,\n} from './getContent';\nimport { getBasePlugins, getContent } from './getContent/getContent';\n\n/**\n * Transforms a dictionary in a single pass, applying each plugin as needed.\n *\n * @param dictionary The dictionary to transform.\n * @param locale The locale to use if your transformers need it (e.g. for translations).\n * @param additionalPlugins An array of NodeTransformer that define how to transform recognized nodes.\n * If omitted, we’ll use a default set of plugins.\n */\nexport const getDictionary = <\n const T extends Dictionary,\n const L extends LocalesValues = DeclaredLocales,\n>(\n dictionary: T,\n locale?: L,\n plugins: Plugins[] = getBasePlugins(locale)\n): DeepTransformContent<T['content'], IInterpreterPluginState, L> => {\n const props: NodeProps = {\n dictionaryKey: dictionary.key,\n dictionaryPath: dictionary.filePath,\n keyPath: [],\n plugins,\n };\n\n return getContent(dictionary.content, props, plugins);\n};\n"],"mappings":";;;;;;;;;;;AAqBA,MAAa,iBAIX,YACA,QACA,UAAqB,eAAe,MAAM,MACyB;CACnE,MAAM,QAAmB;EACvB,eAAe,WAAW;EAC1B,gBAAgB,WAAW;EAC3B,SAAS,CAAC;EACV;CACF;CAEA,OAAO,WAAW,WAAW,SAAS,OAAO,OAAO;AACtD"}
@@ -1 +1 @@
1
- {"version":3,"file":"getEnumeration.mjs","names":[],"sources":["../../../src/interpreter/getEnumeration.ts"],"sourcesContent":["import type { EnterFormat, EnumerationContentState } from '../transpiler';\n\n/**\n * Find the matching condition for a quantity.\n *\n * Usage:\n *\n * ```ts\n * const key = findMatchingCondition({\n * '<=-2.3': 'You have less than -2.3',\n * '<1': 'You have less than one',\n * '2': 'You have two',\n * '>=3': 'You have three or more',\n * }, 2);\n * // '2'\n * ```\n *\n * The order of the keys will define the priority of the content.\n *\n * ```ts\n * const key = findMatchingCondition({\n * '<4': 'You have less than four',\n * '2': 'You have two',\n * }, 2);\n * // '<4'\n * ```\n *\n * If no keys match, the default key is '1'.\n */\nexport const findMatchingCondition = <Content>(\n enumerationContent: EnumerationContentState<Content>,\n quantity: number\n): EnterFormat | undefined => {\n const numericKeys = Object.keys(enumerationContent);\n\n for (const key of numericKeys) {\n const isEqual =\n (!key.startsWith('>') &&\n !key.startsWith('<') &&\n !key.startsWith('=') &&\n parseFloat(key) === quantity) ||\n (key.startsWith('=') && parseFloat(key.slice(1)) === quantity);\n const isSuperior =\n key.startsWith('>') && quantity > parseFloat(key.slice(1));\n const isSuperiorOrEqual =\n key.startsWith('>=') && quantity >= parseFloat(key.slice(2));\n const isInferior =\n key.startsWith('<') && quantity < parseFloat(key.slice(1));\n const isInferiorOrEqual =\n key.startsWith('<=') && quantity <= parseFloat(key.slice(2));\n\n if (\n isEqual ||\n isSuperior ||\n isSuperiorOrEqual ||\n isInferior ||\n isInferiorOrEqual\n ) {\n return key as EnterFormat;\n }\n }\n};\n\n/**\n * Picks content from an enumeration map based on a provided quantity.\n *\n * Supported keys in the enumeration map:\n * - Specific numbers: '0', '1', '2'\n * - Comparison operators: '<5', '>=10', '<=2'\n * - Fallback: 'fallback'\n *\n * The first matching key in the object's iteration order will be selected.\n *\n * @param enumerationContent - A map of conditions/quantities to content.\n * @param quantity - The number to match against the conditions.\n * @returns The matching content.\n *\n * @example\n * ```ts\n * const content = getEnumeration({\n * '0': 'No items',\n * '1': 'One item',\n * '>1': 'Many items',\n * }, 5);\n * // 'Many items'\n * ```\n */\nexport const getEnumeration = <Content>(\n enumerationContent: EnumerationContentState<Content>,\n quantity: number\n): Content => {\n const key =\n findMatchingCondition<Content>(enumerationContent, quantity) ?? 'fallback';\n\n // Default or error handling if no keys match\n return enumerationContent[key] as Content;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,yBACX,oBACA,aAC4B;CAC5B,MAAM,cAAc,OAAO,KAAK,kBAAkB;CAElD,KAAK,MAAM,OAAO,aAAa;EAC7B,MAAM,UACH,CAAC,IAAI,WAAW,GAAG,KAClB,CAAC,IAAI,WAAW,GAAG,KACnB,CAAC,IAAI,WAAW,GAAG,KACnB,WAAW,GAAG,MAAM,YACrB,IAAI,WAAW,GAAG,KAAK,WAAW,IAAI,MAAM,CAAC,CAAC,MAAM;EACvD,MAAM,aACJ,IAAI,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,MAAM,CAAC,CAAC;EAC3D,MAAM,oBACJ,IAAI,WAAW,IAAI,KAAK,YAAY,WAAW,IAAI,MAAM,CAAC,CAAC;EAC7D,MAAM,aACJ,IAAI,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,MAAM,CAAC,CAAC;EAC3D,MAAM,oBACJ,IAAI,WAAW,IAAI,KAAK,YAAY,WAAW,IAAI,MAAM,CAAC,CAAC;EAE7D,IACE,WACA,cACA,qBACA,cACA,mBAEA,OAAO;CAEX;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,kBACX,oBACA,aACY;CAKZ,OAAO,mBAHL,sBAA+B,oBAAoB,QAAQ,KAAK;AAIpE"}
1
+ {"version":3,"file":"getEnumeration.mjs","names":[],"sources":["../../../src/interpreter/getEnumeration.ts"],"sourcesContent":["import type { EnterFormat, EnumerationContentState } from '../transpiler';\n\n/**\n * Find the matching condition for a quantity.\n *\n * Usage:\n *\n * ```ts\n * const key = findMatchingCondition({\n * '<=-2.3': 'You have less than -2.3',\n * '<1': 'You have less than one',\n * '2': 'You have two',\n * '>=3': 'You have three or more',\n * }, 2);\n * // '2'\n * ```\n *\n * The order of the keys will define the priority of the content.\n *\n * ```ts\n * const key = findMatchingCondition({\n * '<4': 'You have less than four',\n * '2': 'You have two',\n * }, 2);\n * // '<4'\n * ```\n *\n * If no keys match, the default key is '1'.\n */\nexport const findMatchingCondition = <const Content>(\n enumerationContent: EnumerationContentState<Content>,\n quantity: number\n): EnterFormat | undefined => {\n const numericKeys = Object.keys(enumerationContent);\n\n for (const key of numericKeys) {\n const isEqual =\n (!key.startsWith('>') &&\n !key.startsWith('<') &&\n !key.startsWith('=') &&\n parseFloat(key) === quantity) ||\n (key.startsWith('=') && parseFloat(key.slice(1)) === quantity);\n const isSuperior =\n key.startsWith('>') && quantity > parseFloat(key.slice(1));\n const isSuperiorOrEqual =\n key.startsWith('>=') && quantity >= parseFloat(key.slice(2));\n const isInferior =\n key.startsWith('<') && quantity < parseFloat(key.slice(1));\n const isInferiorOrEqual =\n key.startsWith('<=') && quantity <= parseFloat(key.slice(2));\n\n if (\n isEqual ||\n isSuperior ||\n isSuperiorOrEqual ||\n isInferior ||\n isInferiorOrEqual\n ) {\n return key as EnterFormat;\n }\n }\n};\n\n/**\n * Picks content from an enumeration map based on a provided quantity.\n *\n * Supported keys in the enumeration map:\n * - Specific numbers: '0', '1', '2'\n * - Comparison operators: '<5', '>=10', '<=2'\n * - Fallback: 'fallback'\n *\n * The first matching key in the object's iteration order will be selected.\n *\n * @param enumerationContent - A map of conditions/quantities to content.\n * @param quantity - The number to match against the conditions.\n * @returns The matching content.\n *\n * @example\n * ```ts\n * const content = getEnumeration({\n * '0': 'No items',\n * '1': 'One item',\n * '>1': 'Many items',\n * }, 5);\n * // 'Many items'\n * ```\n */\nexport const getEnumeration = <const Content>(\n enumerationContent: EnumerationContentState<Content>,\n quantity: number\n): Content => {\n const key =\n findMatchingCondition<Content>(enumerationContent, quantity) ?? 'fallback';\n\n // Default or error handling if no keys match\n return enumerationContent[key] as Content;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,yBACX,oBACA,aAC4B;CAC5B,MAAM,cAAc,OAAO,KAAK,kBAAkB;CAElD,KAAK,MAAM,OAAO,aAAa;EAC7B,MAAM,UACH,CAAC,IAAI,WAAW,GAAG,KAClB,CAAC,IAAI,WAAW,GAAG,KACnB,CAAC,IAAI,WAAW,GAAG,KACnB,WAAW,GAAG,MAAM,YACrB,IAAI,WAAW,GAAG,KAAK,WAAW,IAAI,MAAM,CAAC,CAAC,MAAM;EACvD,MAAM,aACJ,IAAI,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,MAAM,CAAC,CAAC;EAC3D,MAAM,oBACJ,IAAI,WAAW,IAAI,KAAK,YAAY,WAAW,IAAI,MAAM,CAAC,CAAC;EAC7D,MAAM,aACJ,IAAI,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,MAAM,CAAC,CAAC;EAC3D,MAAM,oBACJ,IAAI,WAAW,IAAI,KAAK,YAAY,WAAW,IAAI,MAAM,CAAC,CAAC;EAE7D,IACE,WACA,cACA,qBACA,cACA,mBAEA,OAAO;CAEX;AACF;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,kBACX,oBACA,aACY;CAKZ,OAAO,mBAHL,sBAA+B,oBAAoB,QAAQ,KAAK;AAIpE"}
@@ -1 +1 @@
1
- {"version":3,"file":"getGender.mjs","names":[],"sources":["../../../src/interpreter/getGender.ts"],"sourcesContent":["import type { Gender, GenderContentStates } from '../transpiler';\n\ntype GenderEntry = Gender | 'm' | 'f';\n\nconst getGenderEntry = (gender: GenderEntry): Gender => {\n if (gender === 'm' || gender === 'male') return 'male';\n if (gender === 'f' || gender === 'female') return 'female';\n return 'fallback';\n};\n\n/**\n * Allow to pick a content based on a gender.\n *\n * Usage:\n *\n * ```ts\n * const content = getGender({\n * 'true': 'The gender is validated',\n * 'false': 'The gender is not validated',\n * }, true);\n * // 'The gender is validated'\n * ```\n *\n * The last key provided will be used as the fallback value.\n *\n * ```ts\n * const content = getGender({\n * 'false': 'The gender is not validated',\n * 'true': 'The gender is validated',\n * }, undefined);\n * // 'The gender is validated'\n */\nexport const getGender = <Content>(\n genderContent: GenderContentStates<Content>,\n gender: GenderEntry\n): Content => {\n const stateList = Object.keys(genderContent);\n\n const fallbackState = stateList[\n stateList.length - 1\n ] as keyof typeof genderContent;\n\n const genderEntry = getGenderEntry(gender);\n\n // Default or error handling if no keys match\n return (\n genderContent[genderEntry as keyof typeof genderContent] ??\n genderContent.fallback ??\n (genderContent[fallbackState] as Content)\n );\n};\n"],"mappings":";AAIA,MAAM,kBAAkB,WAAgC;CACtD,IAAI,WAAW,OAAO,WAAW,QAAQ,OAAO;CAChD,IAAI,WAAW,OAAO,WAAW,UAAU,OAAO;CAClD,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,aACX,eACA,WACY;CACZ,MAAM,YAAY,OAAO,KAAK,aAAa;CAE3C,MAAM,gBAAgB,UACpB,UAAU,SAAS;CAMrB,OACE,cAJkB,eAAe,MAIT,MACxB,cAAc,YACb,cAAc;AAEnB"}
1
+ {"version":3,"file":"getGender.mjs","names":[],"sources":["../../../src/interpreter/getGender.ts"],"sourcesContent":["import type { Gender, GenderContentStates } from '../transpiler';\n\ntype GenderEntry = Gender | 'm' | 'f';\n\nconst getGenderEntry = (gender: GenderEntry): Gender => {\n if (gender === 'm' || gender === 'male') return 'male';\n if (gender === 'f' || gender === 'female') return 'female';\n return 'fallback';\n};\n\n/**\n * Allow to pick a content based on a gender.\n *\n * Usage:\n *\n * ```ts\n * const content = getGender({\n * 'true': 'The gender is validated',\n * 'false': 'The gender is not validated',\n * }, true);\n * // 'The gender is validated'\n * ```\n *\n * The last key provided will be used as the fallback value.\n *\n * ```ts\n * const content = getGender({\n * 'false': 'The gender is not validated',\n * 'true': 'The gender is validated',\n * }, undefined);\n * // 'The gender is validated'\n */\nexport const getGender = <const Content>(\n genderContent: GenderContentStates<Content>,\n gender: GenderEntry\n): Content => {\n const stateList = Object.keys(genderContent);\n\n const fallbackState = stateList[\n stateList.length - 1\n ] as keyof typeof genderContent;\n\n const genderEntry = getGenderEntry(gender);\n\n // Default or error handling if no keys match\n return (\n genderContent[genderEntry as keyof typeof genderContent] ??\n genderContent.fallback ??\n (genderContent[fallbackState] as Content)\n );\n};\n"],"mappings":";AAIA,MAAM,kBAAkB,WAAgC;CACtD,IAAI,WAAW,OAAO,WAAW,QAAQ,OAAO;CAChD,IAAI,WAAW,OAAO,WAAW,UAAU,OAAO;CAClD,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,aACX,eACA,WACY;CACZ,MAAM,YAAY,OAAO,KAAK,aAAa;CAE3C,MAAM,gBAAgB,UACpB,UAAU,SAAS;CAMrB,OACE,cAJkB,eAAe,MAIT,MACxB,cAAc,YACb,cAAc;AAEnB"}
@@ -1 +1 @@
1
- {"version":3,"file":"getIntlayer.mjs","names":[],"sources":["../../../src/interpreter/getIntlayer.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryContent,\n DictionaryRegistryElement,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n Plugins,\n} from './getContent';\nimport { getDictionary } from './getDictionary';\n\n/**\n * Creates a Recursive Proxy that returns the path of the accessed key\n * stringified. This prevents the app from crashing on undefined access.\n */\nconst createSafeFallback = (path = ''): any => {\n return new Proxy({} as Record<string | symbol, unknown>, {\n get: (_target, prop) => {\n if (\n prop === 'toJSON' ||\n prop === Symbol.toPrimitive ||\n prop === 'toString' ||\n prop === 'valueOf'\n ) {\n return () => path;\n }\n if (prop === 'then') {\n return undefined; // Prevent it from being treated as a Promise\n }\n if (prop === Symbol.iterator) {\n return function* () {\n yield path;\n };\n }\n\n // Recursively build the path (e.g., \"myDictionary.home.title\")\n const nextPath = path ? `${path}.${String(prop)}` : String(prop);\n return createSafeFallback(nextPath);\n },\n });\n};\n\nconst dictionaryCache = new Map<string, any>();\nconst warnedMissingDictionaries = new Set<string>();\n\nexport const getIntlayer = <\n T extends DictionaryKeys,\n L extends LocalesValues = DeclaredLocales,\n>(\n key: T,\n locale?: L,\n plugins?: Plugins[]\n): DeepTransformContent<\n DictionaryRegistryContent<T>,\n IInterpreterPluginState,\n L\n> => {\n const dictionaries = getDictionaries();\n const dictionary = dictionaries[key as T] as DictionaryRegistryElement<T>;\n\n if (!dictionary && process.env.NODE_ENV === 'development') {\n if (!warnedMissingDictionaries.has(key as string)) {\n // Log a warning instead of throwing (so developers know it's missing)\n const logger = getAppLogger({ log });\n logger(\n typeof window === 'undefined'\n ? `Dictionary ${colorizeKey(key)} was not found. Using fallback proxy.`\n : `Dictionary ${key} was not found. Using fallback proxy.`,\n {\n level: 'warn',\n }\n );\n warnedMissingDictionaries.add(key as string);\n }\n\n return createSafeFallback(key as string);\n }\n\n const cacheKey = `${key}_${locale ?? 'default'}_${plugins ? 'custom_plugins' : 'default_plugins'}`;\n\n if (dictionaryCache.has(cacheKey)) {\n return dictionaryCache.get(cacheKey);\n }\n\n const result = getDictionary<DictionaryRegistryElement<T>, L>(\n dictionary,\n locale,\n plugins\n );\n\n dictionaryCache.set(cacheKey, result);\n\n return result;\n};\n"],"mappings":";;;;;;;;;;AAqBA,MAAM,sBAAsB,OAAO,OAAY;CAC7C,OAAO,IAAI,MAAM,CAAC,GAAuC,EACvD,MAAM,SAAS,SAAS;EACtB,IACE,SAAS,YACT,SAAS,OAAO,eAChB,SAAS,cACT,SAAS,WAET,aAAa;EAEf,IAAI,SAAS,QACX;EAEF,IAAI,SAAS,OAAO,UAClB,OAAO,aAAa;GAClB,MAAM;EACR;EAKF,OAAO,mBADU,OAAO,GAAG,KAAK,GAAG,OAAO,IAAI,MAAM,OAAO,IAAI,CAC7B;CACpC,EACF,CAAC;AACH;AAEA,MAAM,kCAAkB,IAAI,IAAiB;AAC7C,MAAM,4CAA4B,IAAI,IAAY;AAElD,MAAa,eAIX,KACA,QACA,YAKG;CAEH,MAAM,aADe,gBACS,EAAE;CAEhC,IAAI,CAAC,cAAc,MAAwC;EACzD,IAAI,CAAC,0BAA0B,IAAI,GAAa,GAAG;GAGjD,AADe,aAAa,EAAE,IAAI,CAC7B,EACH,OAAO,WAAW,cACd,cAAc,YAAY,GAAG,EAAE,yCAC/B,cAAc,IAAI,wCACtB,EACE,OAAO,OACT,CACF;GACA,0BAA0B,IAAI,GAAa;EAC7C;EAEA,OAAO,mBAAmB,GAAa;CACzC;CAEA,MAAM,WAAW,GAAG,IAAI,GAAG,UAAU,UAAU,GAAG,UAAU,mBAAmB;CAE/E,IAAI,gBAAgB,IAAI,QAAQ,GAC9B,OAAO,gBAAgB,IAAI,QAAQ;CAGrC,MAAM,SAAS,cACb,YACA,QACA,OACF;CAEA,gBAAgB,IAAI,UAAU,MAAM;CAEpC,OAAO;AACT"}
1
+ {"version":3,"file":"getIntlayer.mjs","names":[],"sources":["../../../src/interpreter/getIntlayer.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { colorizeKey, getAppLogger } from '@intlayer/config/logger';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type {\n DeclaredLocales,\n DictionaryKeys,\n DictionaryRegistryContent,\n DictionaryRegistryElement,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n Plugins,\n} from './getContent';\nimport { getDictionary } from './getDictionary';\n\n/**\n * Creates a Recursive Proxy that returns the path of the accessed key\n * stringified. This prevents the app from crashing on undefined access.\n */\nconst createSafeFallback = (path = ''): any => {\n return new Proxy({} as Record<string | symbol, unknown>, {\n get: (_target, prop) => {\n if (\n prop === 'toJSON' ||\n prop === Symbol.toPrimitive ||\n prop === 'toString' ||\n prop === 'valueOf'\n ) {\n return () => path;\n }\n if (prop === 'then') {\n return undefined; // Prevent it from being treated as a Promise\n }\n if (prop === Symbol.iterator) {\n return function* () {\n yield path;\n };\n }\n\n // Recursively build the path (e.g., \"myDictionary.home.title\")\n const nextPath = path ? `${path}.${String(prop)}` : String(prop);\n return createSafeFallback(nextPath);\n },\n });\n};\n\nconst dictionaryCache = new Map<string, any>();\nconst warnedMissingDictionaries = new Set<string>();\n\nexport const getIntlayer = <\n const T extends DictionaryKeys,\n const L extends LocalesValues = DeclaredLocales,\n>(\n key: T,\n locale?: L,\n plugins?: Plugins[]\n): DeepTransformContent<\n DictionaryRegistryContent<T>,\n IInterpreterPluginState,\n L\n> => {\n const dictionaries = getDictionaries();\n const dictionary = dictionaries[key as T] as DictionaryRegistryElement<T>;\n\n if (!dictionary && process.env.NODE_ENV === 'development') {\n if (!warnedMissingDictionaries.has(key as string)) {\n // Log a warning instead of throwing (so developers know it's missing)\n const logger = getAppLogger({ log });\n logger(\n typeof window === 'undefined'\n ? `Dictionary ${colorizeKey(key)} was not found. Using fallback proxy.`\n : `Dictionary ${key} was not found. Using fallback proxy.`,\n {\n level: 'warn',\n }\n );\n warnedMissingDictionaries.add(key as string);\n }\n\n return createSafeFallback(key as string);\n }\n\n const cacheKey = `${key}_${locale ?? 'default'}_${plugins ? 'custom_plugins' : 'default_plugins'}`;\n\n if (dictionaryCache.has(cacheKey)) {\n return dictionaryCache.get(cacheKey);\n }\n\n const result = getDictionary<DictionaryRegistryElement<T>, L>(\n dictionary,\n locale,\n plugins\n );\n\n dictionaryCache.set(cacheKey, result);\n\n return result;\n};\n"],"mappings":";;;;;;;;;;AAqBA,MAAM,sBAAsB,OAAO,OAAY;CAC7C,OAAO,IAAI,MAAM,CAAC,GAAuC,EACvD,MAAM,SAAS,SAAS;EACtB,IACE,SAAS,YACT,SAAS,OAAO,eAChB,SAAS,cACT,SAAS,WAET,aAAa;EAEf,IAAI,SAAS,QACX;EAEF,IAAI,SAAS,OAAO,UAClB,OAAO,aAAa;GAClB,MAAM;EACR;EAKF,OAAO,mBADU,OAAO,GAAG,KAAK,GAAG,OAAO,IAAI,MAAM,OAAO,IAAI,CAC7B;CACpC,EACF,CAAC;AACH;AAEA,MAAM,kCAAkB,IAAI,IAAiB;AAC7C,MAAM,4CAA4B,IAAI,IAAY;AAElD,MAAa,eAIX,KACA,QACA,YAKG;CAEH,MAAM,aADe,gBACS,EAAE;CAEhC,IAAI,CAAC,cAAc,MAAwC;EACzD,IAAI,CAAC,0BAA0B,IAAI,GAAa,GAAG;GAGjD,AADe,aAAa,EAAE,IAAI,CAC7B,EACH,OAAO,WAAW,cACd,cAAc,YAAY,GAAG,EAAE,yCAC/B,cAAc,IAAI,wCACtB,EACE,OAAO,OACT,CACF;GACA,0BAA0B,IAAI,GAAa;EAC7C;EAEA,OAAO,mBAAmB,GAAa;CACzC;CAEA,MAAM,WAAW,GAAG,IAAI,GAAG,UAAU,UAAU,GAAG,UAAU,mBAAmB;CAE/E,IAAI,gBAAgB,IAAI,QAAQ,GAC9B,OAAO,gBAAgB,IAAI,QAAQ;CAGrC,MAAM,SAAS,cACb,YACA,QACA,OACF;CAEA,gBAAgB,IAAI,UAAU,MAAM;CAEpC,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"getNesting.mjs","names":[],"sources":["../../../src/interpreter/getNesting.ts"],"sourcesContent":["import type { GetSubPath } from '@intlayer/types/dictionary';\nimport type {\n DictionaryKeys,\n DictionaryRegistryContent,\n} from '@intlayer/types/module_augmentation';\nimport type { ValidDotPathsFor } from '../transpiler';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n NodeProps,\n} from './getContent';\nimport { getIntlayer } from './getIntlayer';\n\nexport type GetNestingResult<\n K extends DictionaryKeys,\n P = undefined,\n S = IInterpreterPluginState,\n> = GetSubPath<DeepTransformContent<DictionaryRegistryContent<K>, S>, P>;\n\n/**\n * Extracts content from another dictionary by its key and an optional path.\n *\n * This allows for reusing content across different dictionaries.\n *\n * @param dictionaryKey - The key of the dictionary to nest.\n * @param path - Optional dot-separated path to a specific field within the nested dictionary.\n * @param props - Optional properties like locale and plugins.\n * @returns The nested content.\n *\n * @example\n * ```ts\n * const content = getNesting(\"common\", \"buttons.save\");\n * // 'Save'\n * ```\n */\nexport const getNesting = <K extends DictionaryKeys, P>(\n dictionaryKey: K,\n path?: P extends ValidDotPathsFor<K> ? P : never,\n props?: NodeProps\n): GetNestingResult<K, P> => {\n const dictionary = getIntlayer(dictionaryKey, props?.locale, props?.plugins);\n\n if (typeof path === 'string') {\n const pathArray = (path as string).split('.');\n let current: any = dictionary;\n\n for (const key of pathArray) {\n // Safely traverse down the object using the path\n current = current?.[key];\n // If we cannot find the path, return the whole dictionary as a fallback\n if (current === undefined) {\n return dictionary as any;\n }\n }\n\n return current;\n }\n\n // Default or error handling if path is not a string or otherwise undefined\n return dictionary as any;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmCA,MAAa,cACX,eACA,MACA,UAC2B;CAC3B,MAAM,aAAa,YAAY,eAAe,OAAO,QAAQ,OAAO,OAAO;CAE3E,IAAI,OAAO,SAAS,UAAU;EAC5B,MAAM,YAAa,KAAgB,MAAM,GAAG;EAC5C,IAAI,UAAe;EAEnB,KAAK,MAAM,OAAO,WAAW;GAE3B,UAAU,UAAU;GAEpB,IAAI,YAAY,QACd,OAAO;EAEX;EAEA,OAAO;CACT;CAGA,OAAO;AACT"}
1
+ {"version":3,"file":"getNesting.mjs","names":[],"sources":["../../../src/interpreter/getNesting.ts"],"sourcesContent":["import type { GetSubPath } from '@intlayer/types/dictionary';\nimport type {\n DictionaryKeys,\n DictionaryRegistryContent,\n} from '@intlayer/types/module_augmentation';\nimport type { ValidDotPathsFor } from '../transpiler';\nimport type {\n DeepTransformContent,\n IInterpreterPluginState,\n NodeProps,\n} from './getContent';\nimport { getIntlayer } from './getIntlayer';\n\nexport type GetNestingResult<\n K extends DictionaryKeys,\n P = undefined,\n S = IInterpreterPluginState,\n> = GetSubPath<DeepTransformContent<DictionaryRegistryContent<K>, S>, P>;\n\n/**\n * Extracts content from another dictionary by its key and an optional path.\n *\n * This allows for reusing content across different dictionaries.\n *\n * @param dictionaryKey - The key of the dictionary to nest.\n * @param path - Optional dot-separated path to a specific field within the nested dictionary.\n * @param props - Optional properties like locale and plugins.\n * @returns The nested content.\n *\n * @example\n * ```ts\n * const content = getNesting(\"common\", \"buttons.save\");\n * // 'Save'\n * ```\n */\nexport const getNesting = <const K extends DictionaryKeys, const P>(\n dictionaryKey: K,\n path?: P extends ValidDotPathsFor<K> ? P : never,\n props?: NodeProps\n): GetNestingResult<K, P> => {\n const dictionary = getIntlayer(dictionaryKey, props?.locale, props?.plugins);\n\n if (typeof path === 'string') {\n const pathArray = (path as string).split('.');\n let current: any = dictionary;\n\n for (const key of pathArray) {\n // Safely traverse down the object using the path\n current = current?.[key];\n // If we cannot find the path, return the whole dictionary as a fallback\n if (current === undefined) {\n return dictionary as any;\n }\n }\n\n return current;\n }\n\n // Default or error handling if path is not a string or otherwise undefined\n return dictionary as any;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmCA,MAAa,cACX,eACA,MACA,UAC2B;CAC3B,MAAM,aAAa,YAAY,eAAe,OAAO,QAAQ,OAAO,OAAO;CAE3E,IAAI,OAAO,SAAS,UAAU;EAC5B,MAAM,YAAa,KAAgB,MAAM,GAAG;EAC5C,IAAI,UAAe;EAEnB,KAAK,MAAM,OAAO,WAAW;GAE3B,UAAU,UAAU;GAEpB,IAAI,YAAY,QACd,OAAO;EAEX;EAEA,OAAO;CACT;CAGA,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"getPlural.mjs","names":[],"sources":["../../../src/interpreter/getPlural.ts"],"sourcesContent":["import type { DeclaredLocales } from '@intlayer/types';\nimport type { LocalesValues } from 'intlayer';\nimport { getCachedIntl } from '../formatters';\nimport type {\n PluralCategory,\n PluralContentState,\n} from '../transpiler/plural/plural';\n\n/**\n * Picks content from a plural map based on a count and locale, using CLDR\n * pluralization rules (`Intl.PluralRules`).\n *\n * Falls back to the `other` category when no specific category matches.\n *\n * @example\n * ```ts\n * getPlural({\n * one: 'one item',\n * other: '{{count}} items',\n * }, 5, 'en');\n * // '{{count}} items'\n * ```\n */\nexport const getPlural = <L extends LocalesValues = DeclaredLocales>(\n pluralContent: PluralContentState<string>,\n count: number,\n locale: L\n): string => {\n const category = getCachedIntl(Intl.PluralRules, locale).select(\n count\n ) as PluralCategory;\n\n return pluralContent[category] ?? pluralContent.other;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,MAAa,aACX,eACA,OACA,WACW;CAKX,OAAO,cAJU,cAAc,KAAK,aAAa,MAAM,EAAE,OACvD,KAG0B,MAAM,cAAc;AAClD"}
1
+ {"version":3,"file":"getPlural.mjs","names":[],"sources":["../../../src/interpreter/getPlural.ts"],"sourcesContent":["import type { DeclaredLocales } from '@intlayer/types';\nimport type { LocalesValues } from 'intlayer';\nimport { getCachedIntl } from '../formatters';\nimport type {\n PluralCategory,\n PluralContentState,\n} from '../transpiler/plural/plural';\n\n/**\n * Picks content from a plural map based on a count and locale, using CLDR\n * pluralization rules (`Intl.PluralRules`).\n *\n * Falls back to the `other` category when no specific category matches.\n *\n * @example\n * ```ts\n * getPlural({\n * one: 'one item',\n * other: '{{count}} items',\n * }, 5, 'en');\n * // '{{count}} items'\n * ```\n */\nexport const getPlural = <const L extends LocalesValues = DeclaredLocales>(\n pluralContent: PluralContentState<string>,\n count: number,\n locale: L\n): string => {\n const category = getCachedIntl(Intl.PluralRules, locale).select(\n count\n ) as PluralCategory;\n\n return pluralContent[category] ?? pluralContent.other;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,MAAa,aACX,eACA,OACA,WACW;CAKX,OAAO,cAJU,cAAc,KAAK,aAAa,MAAM,EAAE,OACvD,KAG0B,MAAM,cAAc;AAClD"}
@@ -1 +1 @@
1
- {"version":3,"file":"getTranslation.mjs","names":[],"sources":["../../../src/interpreter/getTranslation.ts"],"sourcesContent":["import type {\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\n\n/**\n * Check if a value is a plain object that can be safely merged.\n * Returns false for Promises, React elements, class instances, etc.\n */\nconst isPlainObject = (value: unknown): boolean => {\n if (value === null || typeof value !== 'object') return false;\n if (typeof (value as any).then === 'function') return false;\n if (\n (value as any).$$typeof !== undefined ||\n (value as any).__v_isVNode !== undefined ||\n (value as any)._isVNode !== undefined ||\n (value as any).isJSX !== undefined\n ) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null || Array.isArray(value);\n};\n\n/**\n * Recursively merges two objects, skipping undefined source values.\n * First argument takes precedence. Arrays replace rather than merge.\n */\nconst deepMerge = (target: any, source: any): any => {\n if (target === undefined) return source;\n if (source === undefined) return target;\n if (Array.isArray(target)) return target;\n if (isPlainObject(target) && isPlainObject(source)) {\n const result = { ...target };\n\n for (const key of Object.keys(source)) {\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n source[key] === undefined\n )\n continue;\n result[key] =\n target[key] !== undefined\n ? deepMerge(target[key], source[key])\n : source[key];\n }\n return result;\n }\n return target;\n};\n\n/**\n * Picks the appropriate content from a locale map based on the provided locale.\n *\n * It handles:\n * 1. Exact locale match (e.g., 'en-US').\n * 2. Generic locale fallback (e.g., 'en' if 'en-US' is not found).\n * 3. Explicit fallback locale.\n * 4. Deep merging of objects to ensure partial translations are complemented by fallbacks.\n *\n * @param languageContent - A map of locales to content.\n * @param locale - The target locale to retrieve.\n * @param fallback - Optional fallback locale if the target is not found.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * const content = getTranslation({\n * en: 'Hello',\n * fr: 'Bonjour',\n * }, 'fr');\n * // 'Bonjour'\n * ```\n */\nexport const getTranslation = <Content = string>(\n languageContent: StrictModeLocaleMap<Content>,\n locale: LocalesValues,\n fallback?: LocalesValues\n): Content => {\n const get = (loc: string): Content | undefined =>\n languageContent[loc as keyof typeof languageContent];\n\n // Build priority-ordered locale candidates (most specific first), deduped\n const seen = new Set<string>();\n const locales: string[] = [];\n const addLocale = (loc: string | undefined) => {\n if (loc && !seen.has(loc)) {\n seen.add(loc);\n locales.push(loc);\n }\n };\n\n addLocale(locale);\n if (locale.includes('-')) addLocale(locale.split('-')[0]);\n\n addLocale(fallback);\n if (fallback?.includes('-')) addLocale(fallback.split('-')[0]);\n\n // Collect results: strings exit early (if no higher-priority object was found),\n // objects are accumulated for deep merging.\n const results: Content[] = [];\n\n for (const loc of locales) {\n const val = get(loc);\n\n if (val === undefined) continue;\n if (typeof val === 'string') {\n if (results.length === 0) return val;\n continue; // an object at higher priority takes precedence\n }\n\n results.push(val);\n }\n\n if (results.length === 0) return undefined as Content;\n if (results.length === 1) return results[0];\n if (Array.isArray(results[0])) return results[0];\n\n // Merge objects: first result (most specific) takes precedence\n return (results as object[]).reduce((acc, curr) =>\n deepMerge(acc, curr)\n ) as Content;\n};\n"],"mappings":";;;;;AASA,MAAM,iBAAiB,UAA4B;CACjD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,IAAI,OAAQ,MAAc,SAAS,YAAY,OAAO;CACtD,IACG,MAAc,aAAa,UAC3B,MAAc,gBAAgB,UAC9B,MAAc,aAAa,UAC3B,MAAc,UAAU,QAEzB,OAAO;CAET,MAAM,QAAQ,OAAO,eAAe,KAAK;CACzC,OAAO,UA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jC,IAAI,QAAQ,WAAW,GAAG,OAAO,QAAQ;CACzC,IAAI,MAAM,QAAQ,QAAQ,EAAE,GAAG,OAAO,QAAQ;CAG9C,OAAQ,QAAqB,QAAQ,KAAK,SACxC,UAAU,KAAK,IAAI,CACrB;AACF"}
1
+ {"version":3,"file":"getTranslation.mjs","names":[],"sources":["../../../src/interpreter/getTranslation.ts"],"sourcesContent":["import type {\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\n\n/**\n * Check if a value is a plain object that can be safely merged.\n * Returns false for Promises, React elements, class instances, etc.\n */\nconst isPlainObject = (value: unknown): boolean => {\n if (value === null || typeof value !== 'object') return false;\n if (typeof (value as any).then === 'function') return false;\n if (\n (value as any).$$typeof !== undefined ||\n (value as any).__v_isVNode !== undefined ||\n (value as any)._isVNode !== undefined ||\n (value as any).isJSX !== undefined\n ) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null || Array.isArray(value);\n};\n\n/**\n * Recursively merges two objects, skipping undefined source values.\n * First argument takes precedence. Arrays replace rather than merge.\n */\nconst deepMerge = (target: any, source: any): any => {\n if (target === undefined) return source;\n if (source === undefined) return target;\n if (Array.isArray(target)) return target;\n if (isPlainObject(target) && isPlainObject(source)) {\n const result = { ...target };\n\n for (const key of Object.keys(source)) {\n if (\n key === '__proto__' ||\n key === 'constructor' ||\n source[key] === undefined\n )\n continue;\n result[key] =\n target[key] !== undefined\n ? deepMerge(target[key], source[key])\n : source[key];\n }\n return result;\n }\n return target;\n};\n\n/**\n * Picks the appropriate content from a locale map based on the provided locale.\n *\n * It handles:\n * 1. Exact locale match (e.g., 'en-US').\n * 2. Generic locale fallback (e.g., 'en' if 'en-US' is not found).\n * 3. Explicit fallback locale.\n * 4. Deep merging of objects to ensure partial translations are complemented by fallbacks.\n *\n * @param languageContent - A map of locales to content.\n * @param locale - The target locale to retrieve.\n * @param fallback - Optional fallback locale if the target is not found.\n * @returns The translated content.\n *\n * @example\n * ```ts\n * const content = getTranslation({\n * en: 'Hello',\n * fr: 'Bonjour',\n * }, 'fr');\n * // 'Bonjour'\n * ```\n */\nexport const getTranslation = <const Content = string>(\n languageContent: StrictModeLocaleMap<Content>,\n locale: LocalesValues,\n fallback?: LocalesValues\n): Content => {\n const get = (loc: string): Content | undefined =>\n languageContent[loc as keyof typeof languageContent];\n\n // Build priority-ordered locale candidates (most specific first), deduped\n const seen = new Set<string>();\n const locales: string[] = [];\n const addLocale = (loc: string | undefined) => {\n if (loc && !seen.has(loc)) {\n seen.add(loc);\n locales.push(loc);\n }\n };\n\n addLocale(locale);\n if (locale.includes('-')) addLocale(locale.split('-')[0]);\n\n addLocale(fallback);\n if (fallback?.includes('-')) addLocale(fallback.split('-')[0]);\n\n // Collect results: strings exit early (if no higher-priority object was found),\n // objects are accumulated for deep merging.\n const results: Content[] = [];\n\n for (const loc of locales) {\n const val = get(loc);\n\n if (val === undefined) continue;\n if (typeof val === 'string') {\n if (results.length === 0) return val;\n continue; // an object at higher priority takes precedence\n }\n\n results.push(val);\n }\n\n if (results.length === 0) return undefined as Content;\n if (results.length === 1) return results[0];\n if (Array.isArray(results[0])) return results[0];\n\n // Merge objects: first result (most specific) takes precedence\n return (results as object[]).reduce((acc, curr) =>\n deepMerge(acc, curr)\n ) as Content;\n};\n"],"mappings":";;;;;AASA,MAAM,iBAAiB,UAA4B;CACjD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,IAAI,OAAQ,MAAc,SAAS,YAAY,OAAO;CACtD,IACG,MAAc,aAAa,UAC3B,MAAc,gBAAgB,UAC9B,MAAc,aAAa,UAC3B,MAAc,UAAU,QAEzB,OAAO;CAET,MAAM,QAAQ,OAAO,eAAe,KAAK;CACzC,OAAO,UAAU,OAAO,aAAa,UAAU,QAAQ,MAAM,QAAQ,KAAK;AAC5E;;;;;AAMA,MAAM,aAAa,QAAa,WAAqB;CACnD,IAAI,WAAW,QAAW,OAAO;CACjC,IAAI,WAAW,Q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UAAU,KAAK,IAAI,CACrB;AACF"}
@@ -11,25 +11,6 @@ let LanguageDetector = /* @__PURE__ */ function(LanguageDetector) {
11
11
  LanguageDetector["HtmlTag"] = "htmlTag";
12
12
  return LanguageDetector;
13
13
  }({});
14
- const localeStorageOptions = {
15
- getCookie: (name) => document.cookie.split(";").find((c) => c.trim().startsWith(`${name}=`))?.split("=")[1],
16
- getLocaleStorage: (name) => localStorage.getItem(name),
17
- getSessionStorage: (name) => sessionStorage.getItem(name),
18
- isCookieEnabled: true,
19
- setCookieStore: (name, value, attributes) => cookieStore.set({
20
- name,
21
- value,
22
- path: attributes.path,
23
- domain: attributes.domain,
24
- expires: attributes.expires,
25
- sameSite: attributes.sameSite
26
- }),
27
- setCookieString: (_name, cookie) => {
28
- document.cookie = cookie;
29
- },
30
- setSessionStorage: (name, value) => sessionStorage.setItem(name, value),
31
- setLocaleStorage: (name, value) => localStorage.setItem(name, value)
32
- };
33
14
  const getDefaultsOptions = () => {
34
15
  return {
35
16
  order: [
@@ -128,5 +109,5 @@ const getBrowserLocale = (userOptions = {}) => {
128
109
  };
129
110
 
130
111
  //#endregion
131
- export { LanguageDetector, getBrowserLocale, localeStorageOptions };
112
+ export { LanguageDetector, getBrowserLocale };
132
113
  //# sourceMappingURL=getBrowserLocale.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"getBrowserLocale.mjs","names":[],"sources":["../../../src/localization/getBrowserLocale.tsx"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport {\n getLocaleFromStorageClient,\n type LocaleStorageClientOptions,\n} from '../utils/localeStorage';\nimport { localeDetector } from './localeDetector';\n\nexport enum LanguageDetector {\n Querystring = 'querystring',\n Storage = 'storage',\n Navigator = 'navigator',\n HtmlTag = 'htmlTag',\n}\n\nexport const localeStorageOptions: LocaleStorageClientOptions = {\n getCookie: (name: string) =>\n document.cookie\n .split(';')\n .find((c) => c.trim().startsWith(`${name}=`))\n ?.split('=')[1],\n getLocaleStorage: (name: string) => localStorage.getItem(name),\n getSessionStorage: (name: string) => sessionStorage.getItem(name),\n isCookieEnabled: true,\n setCookieStore: (name, value, attributes) =>\n cookieStore.set({\n name,\n value,\n path: attributes.path,\n domain: attributes.domain,\n expires: attributes.expires,\n sameSite: attributes.sameSite,\n }),\n setCookieString: (_name, cookie) => {\n // biome-ignore lint/suspicious/noDocumentCookie: set cookie fallback\n document.cookie = cookie;\n },\n setSessionStorage: (name, value) => sessionStorage.setItem(name, value),\n setLocaleStorage: (name, value) => localStorage.setItem(name, value),\n};\n\n// Default settings for the language detector\ntype LanguageDetectorOptions = {\n order?: LanguageDetector[];\n lookupQuerystring?: string;\n htmlTag?: HTMLElement | null;\n};\n\nconst getDefaultsOptions = (): LanguageDetectorOptions => {\n return {\n order: [\n LanguageDetector.Querystring,\n LanguageDetector.Storage,\n LanguageDetector.Navigator,\n LanguageDetector.HtmlTag,\n ],\n lookupQuerystring: 'locale',\n htmlTag: typeof document !== 'undefined' ? document.documentElement : null,\n };\n};\n\nconst detectLanguage = (\n order: string[],\n options: LanguageDetectorOptions\n): Record<LanguageDetector, Locale | undefined> => {\n const detected: Record<LanguageDetector, Locale | undefined> = {} as Record<\n LanguageDetector,\n Locale | undefined\n >;\n\n const queryStringDetector = () => {\n if (typeof window === 'undefined') return;\n const search = window.location.search || '';\n const params = new URLSearchParams(search);\n const value = params.get(options.lookupQuerystring ?? '');\n if (value) {\n detected[LanguageDetector.Querystring] = value as Locale;\n }\n };\n\n const storageDetector = () => {\n if (typeof window === 'undefined') return;\n\n const locale = getLocaleFromStorageClient({\n getCookie: (name: string) => {\n try {\n const cookies = document.cookie.split(';');\n const cookieName = `${name}=`;\n\n const cookie = cookies.find((cookie) =>\n cookie.trim().startsWith(cookieName)\n );\n\n if (cookie) {\n return cookie.split('=')[1].trim();\n }\n } catch {}\n return undefined;\n },\n getSessionStorage: (name: string) => {\n try {\n return window.sessionStorage.getItem(name) ?? undefined;\n } catch {}\n return undefined;\n },\n getLocaleStorage: (name: string) => {\n try {\n return window.localStorage.getItem(name) ?? undefined;\n } catch {}\n return undefined;\n },\n });\n\n if (locale) {\n detected[LanguageDetector.Storage] = locale;\n }\n };\n\n const navigatorDetector = () => {\n if (typeof navigator === 'undefined') return;\n\n const languages = navigator.languages ?? [navigator.language];\n\n // Use localeDetector to find the best matching locale\n const locale = localeDetector(\n { 'accept-language': languages.join(',') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n if (locale) {\n detected[LanguageDetector.Navigator] = locale;\n }\n };\n\n const htmlTagDetector = () => {\n const htmlTag = options.htmlTag;\n if (htmlTag && typeof htmlTag.getAttribute === 'function') {\n const lang = htmlTag.getAttribute('lang');\n if (lang) {\n // Validate and resolve the locale\n\n const locale = localeDetector(\n { 'accept-language': lang },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n detected[LanguageDetector.HtmlTag] = locale;\n }\n }\n };\n\n // Map detector names to their corresponding functions\n const detectors: Record<string, () => void> = {\n [LanguageDetector.Querystring]: queryStringDetector,\n [LanguageDetector.Storage]: storageDetector,\n [LanguageDetector.Navigator]: navigatorDetector,\n [LanguageDetector.HtmlTag]: htmlTagDetector,\n };\n\n // Use the provided order to run each detector\n order.forEach((detectorName) => {\n detectors[detectorName]?.();\n });\n\n return detected;\n};\n\nconst getFirstAvailableLocale = (\n locales: Record<LanguageDetector, Locale | undefined>,\n order: LanguageDetector[]\n): Locale => {\n for (const detector of order) {\n const locale = locales[detector];\n\n if (locale && internationalization.locales.includes(locale)) {\n return locale;\n }\n }\n\n return internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n};\n\n/**\n * Core language detector function for browser environments.\n *\n * Detects the user's preferred locale by checking multiple sources in order:\n * 1. Query string parameter\n * 2. Storage (cookies, localStorage, sessionStorage) - uses getLocaleFromStorage\n * 3. Navigator languages - uses localeDetector\n * 4. HTML lang attribute - uses localeDetector\n *\n * @param userOptions - Optional configuration for detection order and lookup keys\n * @returns The detected locale or the default locale\n *\n * @example\n * const locale = getBrowserLocale({ order: [LanguageDetector.Storage, LanguageDetector.Navigator] });\n */\nexport const getBrowserLocale = (\n userOptions: LanguageDetectorOptions | undefined = {}\n): Locale => {\n const options = { ...getDefaultsOptions(), ...userOptions };\n\n const locales = detectLanguage(options.order ?? [], options);\n\n return getFirstAvailableLocale(locales, options.order ?? []);\n};\n"],"mappings":";;;;;;AASA,IAAY,mBAAL;CACL;CACA;CACA;CACA;;AACF;AAEA,MAAa,uBAAmD;CAC9D,YAAY,SACV,SAAS,OACN,MAAM,GAAG,EACT,MAAM,MAAM,EAAE,KAAK,EAAE,WAAW,GAAG,KAAK,EAAE,CAAC,GAC1C,MAAM,GAAG,EAAE;CACjB,mBAAmB,SAAiB,aAAa,QAAQ,IAAI;CAC7D,oBAAoB,SAAiB,eAAe,QAAQ,IAAI;CAChE,iBAAiB;CACjB,iBAAiB,MAAM,OAAO,eAC5B,YAAY,IAAI;EACd;EACA;EACA,MAAM,WAAW;EACjB,QAAQ,WAAW;EACnB,SAAS,WAAW;EACpB,UAAU,WAAW;CACvB,CAAC;CACH,kBAAkB,OAAO,WAAW;EAElC,SAAS,SAAS;CACpB;CACA,oBAAoB,MAAM,UAAU,eAAe,QAAQ,MAAM,KAAK;CACtE,mBAAmB,MAAM,UAAU,aAAa,QAAQ,MAAM,KAAK;AACrE;AASA,MAAM,2BAAoD;CACxD,OAAO;EACL,OAAO;;;;;EAKP;EACA,mBAAmB;EACnB,SAAS,OAAO,aAAa,cAAc,SAAS,kBAAkB;CACxE;AACF;AAEA,MAAM,kBACJ,OACA,YACiD;CACjD,MAAM,WAAyD,CAAC;CAKhE,MAAM,4BAA4B;EAChC,IAAI,OAAO,WAAW,aAAa;EACnC,MAAM,SAAS,OAAO,SAAS,UAAU;EAEzC,MAAM,QAAQ,IADK,gBAAgB,MAChB,EAAE,IAAI,QAAQ,qBAAqB,EAAE;EACxD,IAAI,OACF,0BAAyC;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SAAS,QAAQ;EAEvB,IAAI,UAAU,qBAAqB,QAAQ,SAAS,MAAM,GACxD,OAAO;CAEX;CAEA,OAAO,sBAAsB,iBAAiB;AAChD;;;;;;;;;;;;;;;;AAiBA,MAAa,oBACX,cAAmD,CAAC,MACzC;CACX,MAAM,UAAU;EAAE,GAAG,mBAAmB;EAAG,GAAG;CAAY;CAI1D,OAAO,wBAFS,eAAe,QAAQ,SAAS,CAAC,GAAG,OAEf,GAAG,QAAQ,SAAS,CAAC,CAAC;AAC7D"}
1
+ {"version":3,"file":"getBrowserLocale.mjs","names":[],"sources":["../../../src/localization/getBrowserLocale.tsx"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport { DEFAULT_LOCALE } from '@intlayer/config/defaultValues';\nimport type { Locale } from '@intlayer/types/allLocales';\nimport { getLocaleFromStorageClient } from '../utils/localeStorage';\nimport { localeDetector } from './localeDetector';\n\nexport enum LanguageDetector {\n Querystring = 'querystring',\n Storage = 'storage',\n Navigator = 'navigator',\n HtmlTag = 'htmlTag',\n}\n\n// Default settings for the language detector\ntype LanguageDetectorOptions = {\n order?: LanguageDetector[];\n lookupQuerystring?: string;\n htmlTag?: HTMLElement | null;\n};\n\nconst getDefaultsOptions = (): LanguageDetectorOptions => {\n return {\n order: [\n LanguageDetector.Querystring,\n LanguageDetector.Storage,\n LanguageDetector.Navigator,\n LanguageDetector.HtmlTag,\n ],\n lookupQuerystring: 'locale',\n htmlTag: typeof document !== 'undefined' ? document.documentElement : null,\n };\n};\n\nconst detectLanguage = (\n order: string[],\n options: LanguageDetectorOptions\n): Record<LanguageDetector, Locale | undefined> => {\n const detected: Record<LanguageDetector, Locale | undefined> = {} as Record<\n LanguageDetector,\n Locale | undefined\n >;\n\n const queryStringDetector = () => {\n if (typeof window === 'undefined') return;\n const search = window.location.search || '';\n const params = new URLSearchParams(search);\n const value = params.get(options.lookupQuerystring ?? '');\n if (value) {\n detected[LanguageDetector.Querystring] = value as Locale;\n }\n };\n\n const storageDetector = () => {\n if (typeof window === 'undefined') return;\n\n const locale = getLocaleFromStorageClient({\n getCookie: (name: string) => {\n try {\n const cookies = document.cookie.split(';');\n const cookieName = `${name}=`;\n\n const cookie = cookies.find((cookie) =>\n cookie.trim().startsWith(cookieName)\n );\n\n if (cookie) {\n return cookie.split('=')[1].trim();\n }\n } catch {}\n return undefined;\n },\n getSessionStorage: (name: string) => {\n try {\n return window.sessionStorage.getItem(name) ?? undefined;\n } catch {}\n return undefined;\n },\n getLocaleStorage: (name: string) => {\n try {\n return window.localStorage.getItem(name) ?? undefined;\n } catch {}\n return undefined;\n },\n });\n\n if (locale) {\n detected[LanguageDetector.Storage] = locale;\n }\n };\n\n const navigatorDetector = () => {\n if (typeof navigator === 'undefined') return;\n\n const languages = navigator.languages ?? [navigator.language];\n\n // Use localeDetector to find the best matching locale\n const locale = localeDetector(\n { 'accept-language': languages.join(',') },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n if (locale) {\n detected[LanguageDetector.Navigator] = locale;\n }\n };\n\n const htmlTagDetector = () => {\n const htmlTag = options.htmlTag;\n if (htmlTag && typeof htmlTag.getAttribute === 'function') {\n const lang = htmlTag.getAttribute('lang');\n if (lang) {\n // Validate and resolve the locale\n\n const locale = localeDetector(\n { 'accept-language': lang },\n internationalization.locales,\n internationalization.defaultLocale\n );\n\n detected[LanguageDetector.HtmlTag] = locale;\n }\n }\n };\n\n // Map detector names to their corresponding functions\n const detectors: Record<string, () => void> = {\n [LanguageDetector.Querystring]: queryStringDetector,\n [LanguageDetector.Storage]: storageDetector,\n [LanguageDetector.Navigator]: navigatorDetector,\n [LanguageDetector.HtmlTag]: htmlTagDetector,\n };\n\n // Use the provided order to run each detector\n order.forEach((detectorName) => {\n detectors[detectorName]?.();\n });\n\n return detected;\n};\n\nconst getFirstAvailableLocale = (\n locales: Record<LanguageDetector, Locale | undefined>,\n order: LanguageDetector[]\n): Locale => {\n for (const detector of order) {\n const locale = locales[detector];\n\n if (locale && internationalization.locales.includes(locale)) {\n return locale;\n }\n }\n\n return internationalization?.defaultLocale ?? DEFAULT_LOCALE;\n};\n\n/**\n * Core language detector function for browser environments.\n *\n * Detects the user's preferred locale by checking multiple sources in order:\n * 1. Query string parameter\n * 2. Storage (cookies, localStorage, sessionStorage) - uses getLocaleFromStorage\n * 3. Navigator languages - uses localeDetector\n * 4. HTML lang attribute - uses localeDetector\n *\n * @param userOptions - Optional configuration for detection order and lookup keys\n * @returns The detected locale or the default locale\n *\n * @example\n * const locale = getBrowserLocale({ order: [LanguageDetector.Storage, LanguageDetector.Navigator] });\n */\nexport const getBrowserLocale = (\n userOptions: LanguageDetectorOptions | undefined = {}\n): Locale => {\n const options = { ...getDefaultsOptions(), ...userOptions };\n\n const locales = detectLanguage(options.order ?? [], options);\n\n return getFirstAvailableLocale(locales, options.order ?? []);\n};\n"],"mappings":";;;;;;AAMA,IAAY,mBAAL;CACL;CACA;CACA;CACA;;AACF;AASA,MAAM,2BAAoD;CACxD,OAAO;EACL,OAAO;;;;;EAKP;EACA,mBAAmB;EACnB,SAAS,OAAO,aAAa,cAAc,SAAS,kBAAkB;CACxE;AACF;AAEA,MAAM,kBACJ,OACA,YACiD;CACjD,MAAM,WAAyD,CAAC;CAKhE,MAAM,4BAA4B;EAChC,IAAI,OAAO,WAAW,aAAa;EACnC,MAAM,SAAS,OAAO,SAAS,UAAU;EAEzC,MAAM,QAAQ,IADK,gBAAgB,MAChB,EAAE,IAAI,QAAQ,qBAAqB,EAAE;EACxD,IAAI,OACF,0BAAyC;CAE7C;CAEA,MAAM,wBAAwB;EAC5B,IAAI,OAAO,WAAW,aAAa;EAEnC,MAAM,SAAS,2BAA2B;GACxC,YAAY,SAAiB;IAC3B,IAAI;KACF,MAAM,UAAU,SAAS,OAAO,MAAM,GAAG;KACzC,MAAM,aAAa,GAAG,KAAK;KAE3B,MAAM,SAAS,QAAQ,MAAM,WAC3B,OAAO,KAAK,EAAE,WAAW,UAAU,CACrC;KAEA,IAAI,QACF,OAAO,OAAO,MA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AAS,CAAC,CAAC;AAC7D"}
@@ -6,7 +6,7 @@ import { getMultilingualUrls } from "./getMultilingualUrls.mjs";
6
6
  import { generateSitemap, generateSitemapUrl } from "./generateSitemap.mjs";
7
7
  import { localeResolver } from "./localeResolver.mjs";
8
8
  import { localeDetector } from "./localeDetector.mjs";
9
- import { getBrowserLocale, localeStorageOptions } from "./getBrowserLocale.mjs";
9
+ import { getBrowserLocale } from "./getBrowserLocale.mjs";
10
10
  import { getHTMLTextDir } from "./getHTMLTextDir.mjs";
11
11
  import { getLocale } from "./getLocale.mjs";
12
12
  import { getLocaleFromPath } from "./getLocaleFromPath.mjs";
@@ -15,4 +15,4 @@ import { getLocaleName } from "./getLocaleName.mjs";
15
15
  import { localeFlatMap, localeMap, localeRecord } from "./localeMapper.mjs";
16
16
  import { validatePrefix } from "./validatePrefix.mjs";
17
17
 
18
- export { generateSitemap, generateSitemapUrl, getBrowserLocale, getCanonicalPath, getHTMLTextDir, getInternalPath, getLocale, getLocaleFromPath, getLocaleLang, getLocaleName, getLocalizedPath, getLocalizedUrl, getMultilingualUrls, getPathWithoutLocale, getPrefix, getRewritePath, getRewriteRules, localeDetector, localeFlatMap, localeMap, localeRecord, localeResolver, localeStorageOptions, validatePrefix };
18
+ export { generateSitemap, generateSitemapUrl, getBrowserLocale, getCanonicalPath, getHTMLTextDir, getInternalPath, getLocale, getLocaleFromPath, getLocaleLang, getLocaleName, getLocalizedPath, getLocalizedUrl, getMultilingualUrls, getPathWithoutLocale, getPrefix, getRewritePath, getRewriteRules, localeDetector, localeFlatMap, localeMap, localeRecord, localeResolver, validatePrefix };
@@ -218,7 +218,6 @@ const createRules = (createElement, ctx, options, footnotes, refs, attrStringToM
218
218
  const attrs = { ...node.attrs ?? {} };
219
219
  const langClass = node.lang ? `lang-${node.lang}` : "lang-plaintext";
220
220
  attrs.className = attrs.className ? `${attrs.className} ${langClass}` : langClass;
221
- if (node.lang && !attrs.lang) attrs.lang = node.lang;
222
221
  return createElement("pre", { key: state.key }, createElement("code", attrs, node.text));
223
222
  }
224
223
  },
@@ -683,12 +682,8 @@ const createRules = (createElement, ctx, options, footnotes, refs, attrStringToM
683
682
  }
684
683
  };
685
684
  };
686
- const compile = (markdown = "", ctx, options = {}) => {
687
- const components = ctx.components ?? {};
688
- const slug = (input) => {
689
- return ctx.slugify ? ctx.slugify(input, slugify) : slugify(input);
690
- };
691
- const createElement = createElementFactory(ctx, options);
685
+ const parseMarkdown = (markdown = "", ctx, options = {}) => {
686
+ const dummyCreateElement = () => null;
692
687
  const footnotes = [];
693
688
  const refs = {};
694
689
  const attrStringToMap = (tag, str) => {
@@ -703,7 +698,7 @@ const compile = (markdown = "", ctx, options = {}) => {
703
698
  const mappedKey = ATTRIBUTE_TO_NODE_PROP_MAP[key] ?? key;
704
699
  if (mappedKey === "ref") return map;
705
700
  map[mappedKey] = attributeValueToNodePropValue(tag, key, value, ctx.sanitizer ?? sanitizer);
706
- if (typeof map[mappedKey] === "string" && (HTML_BLOCK_ELEMENT_R.test(map[mappedKey]) || HTML_SELF_CLOSING_ELEMENT_R.test(map[mappedKey]))) map[mappedKey] = compileInner(map[mappedKey].trim());
701
+ if (typeof map[mappedKey] === "string" && (HTML_BLOCK_ELEMENT_R.test(map[mappedKey]) || HTML_SELF_CLOSING_ELEMENT_R.test(map[mappedKey]))) map[mappedKey] = parseMarkdown(map[mappedKey].trim(), ctx, options).ast;
707
702
  } else if (raw !== "style") map[ATTRIBUTE_TO_NODE_PROP_MAP[raw] ?? raw] = true;
708
703
  return map;
709
704
  }, {});
@@ -732,18 +727,40 @@ const compile = (markdown = "", ctx, options = {}) => {
732
727
  CUSTOM_COMPONENT_R
733
728
  ], slice);
734
729
  };
735
- const baseRules = createRules(createElement, ctx, options, footnotes, refs, attrStringToMap, containsBlockSyntax, nonParagraphBlockSyntaxes);
736
- const rules = options.disableParsingRawHTML ? Object.keys(baseRules).reduce((acc, key) => {
730
+ const baseRules = createRules(dummyCreateElement, ctx, options, footnotes, refs, attrStringToMap, containsBlockSyntax, nonParagraphBlockSyntaxes);
731
+ const parser = parserFor(options.disableParsingRawHTML ? Object.keys(baseRules).reduce((acc, key) => {
737
732
  if (key !== RuleType.htmlBlock && key !== RuleType.htmlSelfClosing) acc[key] = baseRules[key];
738
733
  return acc;
739
- }, {}) : baseRules;
740
- const parser = parserFor(rules);
741
- const emitter = renderFor(createRenderer(rules, options.renderRule));
742
- const compileInner = (input) => {
743
- const result = options.preserveFrontmatter ? input : input.replace(FRONT_MATTER_R, "");
744
- const inline = options.forceInline || !options.forceBlock && SHOULD_RENDER_AS_BLOCK_R.test(result.replace(TRIM_STARTING_NEWLINES, "")) === false;
745
- const arr = emitter(parser(inline ? result : `${trimEnd(result).replace(TRIM_STARTING_NEWLINES, "")}\n\n`, { inline }), { inline });
746
- while (typeof arr[arr.length - 1] === "string" && !arr[arr.length - 1].trim()) arr.pop();
734
+ }, {}) : baseRules);
735
+ const result = options.preserveFrontmatter ? markdown : markdown.replace(FRONT_MATTER_R, "");
736
+ const inline = options.forceInline || !options.forceBlock && SHOULD_RENDER_AS_BLOCK_R.test(result.replace(TRIM_STARTING_NEWLINES, "")) === false;
737
+ const ast = parser(inline ? result : `${trimEnd(result).replace(TRIM_STARTING_NEWLINES, "")}\n\n`, { inline });
738
+ if (footnotes.length > 0) for (const def of footnotes) def.parsedAst = parser(def.footnote, { inline: true });
739
+ return {
740
+ ast,
741
+ footnotes,
742
+ inline
743
+ };
744
+ };
745
+ const renderMarkdownAst = (parsed, ctx, options = {}) => {
746
+ const components = ctx.components ?? {};
747
+ const slug = (input) => {
748
+ return ctx.slugify ? ctx.slugify(input, slugify) : slugify(input);
749
+ };
750
+ const createElement = createElementFactory(ctx, options);
751
+ const footnotes = parsed.footnotes || [];
752
+ const refs = {};
753
+ const attrStringToMap = () => null;
754
+ const containsBlockSyntax = () => false;
755
+ const baseRules = createRules(createElement, ctx, options, footnotes, refs, attrStringToMap, containsBlockSyntax, []);
756
+ const emitter = renderFor(createRenderer(options.disableParsingRawHTML ? Object.keys(baseRules).reduce((acc, key) => {
757
+ if (key !== RuleType.htmlBlock && key !== RuleType.htmlSelfClosing) acc[key] = baseRules[key];
758
+ return acc;
759
+ }, {}) : baseRules, options.renderRule));
760
+ const inline = parsed.inline;
761
+ const arr = emitter(parsed.ast, { inline });
762
+ while (typeof arr[arr.length - 1] === "string" && !arr[arr.length - 1].trim()) arr.pop();
763
+ const getOuterNode = () => {
747
764
  if (options.wrapper === null) return arr;
748
765
  const wrapper = options.wrapper ?? (inline ? "span" : "div");
749
766
  if (arr.length > 1 || options.forceWrapper) return createElement(wrapper, { key: "outer" }, arr);
@@ -767,15 +784,18 @@ const compile = (markdown = "", ctx, options = {}) => {
767
784
  }
768
785
  return createElement(wrapper, { key: "outer" }, null);
769
786
  };
787
+ const node = getOuterNode();
788
+ return footnotes.length ? createElement("div", null, node, createElement("footer", { key: "footer" }, ...footnotes.map((def) => createElement("div", {
789
+ id: slug(def.identifier),
790
+ key: def.identifier
791
+ }, def.identifier, emitter(def.parsedAst || def.footnote, { inline: true }))))) : node;
792
+ };
793
+ const compile = (markdown = "", ctx, options = {}) => {
770
794
  if (typeof markdown !== "string") {
771
795
  console.error("intlayer: the first argument must be a string. Received", typeof markdown);
772
796
  throw new Error("intlayer: the first argument must be a string");
773
797
  }
774
- const node = compileInner(markdown);
775
- return footnotes.length ? createElement("div", null, node, createElement("footer", { key: "footer" }, ...footnotes.map((def) => createElement("div", {
776
- id: slug(def.identifier),
777
- key: def.identifier
778
- }, def.identifier, emitter(parser(def.footnote, { inline: true }), { inline: true }))))) : node;
798
+ return renderMarkdownAst(parseMarkdown(markdown, ctx, options), ctx, options);
779
799
  };
780
800
  const createCompiler = (ctx) => (markdown, options) => compile(markdown, ctx, options);
781
801
  const compileWithOptions = (markdown, runtime, options = {}) => {
@@ -790,5 +810,5 @@ const compileWithOptions = (markdown, runtime, options = {}) => {
790
810
  };
791
811
 
792
812
  //#endregion
793
- export { compile, compileWithOptions, createCompiler };
813
+ export { compile, compileWithOptions, createCompiler, parseMarkdown, renderMarkdownAst };
794
814
  //# sourceMappingURL=compiler.mjs.map