@intlayer/use-intl 9.0.0-canary.8 → 9.0.0
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.
- package/dist/esm/client/IntlProvider.mjs.map +1 -1
- package/dist/esm/client/helpers.mjs.map +1 -1
- package/dist/esm/client/index.mjs.map +1 -1
- package/dist/esm/client/useLocale.mjs.map +1 -1
- package/dist/esm/client/useTranslations.mjs +1 -1
- package/dist/esm/client/useTranslations.mjs.map +1 -1
- package/dist/esm/core/createFormatter.mjs.map +1 -1
- package/dist/esm/core/createTranslator.mjs.map +1 -1
- package/dist/esm/core/errors.mjs.map +1 -1
- package/dist/esm/core/hasLocale.mjs.map +1 -1
- package/dist/esm/core/initializeConfig.mjs.map +1 -1
- package/dist/esm/index.mjs +2 -1
- package/dist/esm/plugin/index.mjs +3 -36
- package/dist/esm/plugin/index.mjs.map +1 -1
- package/dist/esm/shared/intlFormatter.mjs.map +1 -1
- package/dist/esm/shared/namespaceTranslator.mjs +56 -35
- package/dist/esm/shared/namespaceTranslator.mjs.map +1 -1
- package/dist/esm/useDictionary.mjs +10 -15
- package/dist/esm/useDictionary.mjs.map +1 -1
- package/dist/esm/useDictionaryDynamic.mjs +7 -15
- package/dist/esm/useDictionaryDynamic.mjs.map +1 -1
- package/dist/types/client/IntlProvider.d.ts +2 -2
- package/dist/types/client/IntlProvider.d.ts.map +1 -1
- package/dist/types/client/helpers.d.ts +0 -1
- package/dist/types/client/helpers.d.ts.map +1 -1
- package/dist/types/client/index.d.ts +0 -1
- package/dist/types/client/index.d.ts.map +1 -1
- package/dist/types/client/useLocale.d.ts +0 -1
- package/dist/types/client/useLocale.d.ts.map +1 -1
- package/dist/types/client/useTranslations.d.ts +4 -4
- package/dist/types/client/useTranslations.d.ts.map +1 -1
- package/dist/types/core/createFormatter.d.ts +0 -1
- package/dist/types/core/createFormatter.d.ts.map +1 -1
- package/dist/types/core/createTranslator.d.ts +9 -7
- package/dist/types/core/createTranslator.d.ts.map +1 -1
- package/dist/types/core/errors.d.ts.map +1 -1
- package/dist/types/core/hasLocale.d.ts +0 -1
- package/dist/types/core/hasLocale.d.ts.map +1 -1
- package/dist/types/core/index.d.ts +1 -1
- package/dist/types/core/initializeConfig.d.ts +0 -1
- package/dist/types/core/initializeConfig.d.ts.map +1 -1
- package/dist/types/core/types.d.ts +1 -1
- package/dist/types/index.d.ts +4 -3
- package/dist/types/plugin/index.d.ts +0 -1
- package/dist/types/plugin/index.d.ts.map +1 -1
- package/dist/types/shared/intlFormatter.d.ts +0 -1
- package/dist/types/shared/intlFormatter.d.ts.map +1 -1
- package/dist/types/shared/namespaceTranslator.d.ts +33 -12
- package/dist/types/shared/namespaceTranslator.d.ts.map +1 -1
- package/dist/types/shared/translateFunctionTypes.d.ts +52 -7
- package/dist/types/shared/translateFunctionTypes.d.ts.map +1 -1
- package/dist/types/useDictionary.d.ts +15 -6
- package/dist/types/useDictionary.d.ts.map +1 -1
- package/dist/types/useDictionaryDynamic.d.ts +12 -7
- package/dist/types/useDictionaryDynamic.d.ts.map +1 -1
- package/package.json +14 -14
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IntlProvider.mjs","names":[],"sources":["../../../src/client/IntlProvider.tsx"],"sourcesContent":["'use client';\n\nimport { log } from '@intlayer/config/built';\nimport { CYAN } from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport type { ComponentProps } from 'react';\nimport { IntlayerProvider } from 'react-intlayer';\nimport type { IntlProvider as _IntlProvider } from 'use-intl';\n\n/**\n * Drop-in for use-intl's `IntlProvider`.\n *\n * Wraps Intlayer's `IntlayerProvider`, seeding the client locale from the\n * `locale` prop. `messages`, `formats`, `now`, `timeZone`, `onError`, and\n * `getMessageFallback` are accepted for API compatibility but have no effect —\n * Intlayer uses its own compiled dictionaries.\n */\nexport const IntlProvider: typeof _IntlProvider = ({\n locale,\n children,\n messages: _messages,\n formats: _formats,\n now: _now,\n timeZone: _timeZone,\n onError: _onError,\n getMessageFallback: _getMessageFallback,\n}) => {\n if (\n process.env.NODE_ENV === 'development' &&\n typeof _messages !== 'undefined'\n ) {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize('IntlProvider', CYAN)} do not pass the messages prop with intlayer. Messages are loaded automatically under the hood for bundle optimization reason`\n );\n }\n\n // `key={locale}` re-seeds the client locale context when the locale changes,\n // so consumers re-render in the new language.\n return (\n <IntlayerProvider key={String(locale)} locale={locale as LocalesValues}>\n {children}\n </IntlayerProvider>\n );\n};\n\n/**\n * Props accepted by {@link IntlProvider}. `messages` is deprecated — Intlayer\n * loads content from compiled dictionaries automatically.\n */\nexport type IntlProviderProps = Omit<\n ComponentProps<typeof _IntlProvider>,\n 'messages' | 'locale'\n> & {\n /**\n * @deprecated has no use case with intlayer. Messages are loaded\n * automatically under the hood for bundle optimization reason.\n */\n messages?: never;\n /** The active locale. */\n locale: LocalesValues;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,MAAa,gBAAsC,EACjD,QACA,UACA,UAAU,WACV,SAAS,UACT,KAAK,MACL,UAAU,WACV,SAAS,UACT,oBAAoB,0BAChB;
|
|
1
|
+
{"version":3,"file":"IntlProvider.mjs","names":[],"sources":["../../../src/client/IntlProvider.tsx"],"sourcesContent":["'use client';\n\nimport { log } from '@intlayer/config/built';\nimport { CYAN } from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\nimport type { ComponentProps } from 'react';\nimport { IntlayerProvider } from 'react-intlayer';\nimport type { IntlProvider as _IntlProvider } from 'use-intl';\n\n/**\n * Drop-in for use-intl's `IntlProvider`.\n *\n * Wraps Intlayer's `IntlayerProvider`, seeding the client locale from the\n * `locale` prop. `messages`, `formats`, `now`, `timeZone`, `onError`, and\n * `getMessageFallback` are accepted for API compatibility but have no effect —\n * Intlayer uses its own compiled dictionaries.\n */\nexport const IntlProvider: typeof _IntlProvider = ({\n locale,\n children,\n messages: _messages,\n formats: _formats,\n now: _now,\n timeZone: _timeZone,\n onError: _onError,\n getMessageFallback: _getMessageFallback,\n}) => {\n if (\n process.env.NODE_ENV === 'development' &&\n typeof _messages !== 'undefined'\n ) {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize('IntlProvider', CYAN)} do not pass the messages prop with intlayer. Messages are loaded automatically under the hood for bundle optimization reason`\n );\n }\n\n // `key={locale}` re-seeds the client locale context when the locale changes,\n // so consumers re-render in the new language.\n return (\n <IntlayerProvider key={String(locale)} locale={locale as LocalesValues}>\n {children}\n </IntlayerProvider>\n );\n};\n\n/**\n * Props accepted by {@link IntlProvider}. `messages` is deprecated — Intlayer\n * loads content from compiled dictionaries automatically.\n */\nexport type IntlProviderProps = Omit<\n ComponentProps<typeof _IntlProvider>,\n 'messages' | 'locale'\n> & {\n /**\n * @deprecated has no use case with intlayer. Messages are loaded\n * automatically under the hood for bundle optimization reason.\n */\n messages?: never;\n /** The active locale. */\n locale: LocalesValues;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,MAAa,gBAAsC,EACjD,QACA,UACA,UAAU,WACV,SAAS,UACT,KAAK,MACL,UAAU,WACV,SAAS,UACT,oBAAoB,0BAChB;CACJ,IAEE,OAAO,cAAc,aAGrB,AADkB,aAAa,EAAE,IAAI,CAC7B,CAAC,CACP,GAAG,SAAS,gBAAgB,IAAI,EAAE,8HACpC;CAKF,OACE,oBAAC,kBAAD;EAA+C;EAC5C;CACe,GAFK,OAAO,MAAM,CAElB;AAEtB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.mjs","names":["useLocaleIntlayer"],"sources":["../../../src/client/helpers.ts"],"sourcesContent":["'use client';\n\nimport { log } from '@intlayer/config/built';\nimport { CYAN } from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { useLocale as useLocaleIntlayer } from 'react-intlayer';\nimport type {\n useFormatter as _useFormatter,\n useMessages as _useMessages,\n useNow as _useNow,\n useTimeZone as _useTimeZone,\n} from 'use-intl';\nimport { buildIntlFormatter } from '../shared/intlFormatter';\n\n/**\n * Drop-in for use-intl's `useNow`.\n * Returns the current `Date`. The `updateInterval` option is ignored.\n */\nexport const useNow: typeof _useNow = () => new Date();\n\n/**\n * Drop-in for use-intl's `useTimeZone`.\n * Returns the system time zone resolved from `Intl.DateTimeFormat`.\n */\nexport const useTimeZone: typeof _useTimeZone = () =>\n Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n/**\n * Drop-in for use-intl's `useMessages`.\n *\n * @deprecated useMessages has no use case with intlayer.\n * Messages are loaded automatically under the hood.\n * @returns An empty object.\n */\nexport const useMessages: typeof _useMessages = () => {\n if (process.env.NODE_ENV === 'development') {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize('useMessages', CYAN)} has no use case with intlayer. Messages are loaded automatically under the hood for bundle optimization reason`\n );\n }\n\n return {} as ReturnType<typeof _useMessages>;\n};\n\n/**\n * Drop-in for use-intl's `useFormatter`.\n * Returns locale-aware formatters backed by the native `Intl.*` APIs:\n * `dateTime`, `number`, `dateTimeRange`, `relativeTime`, `list`, and\n * `displayName`.\n */\nexport const useFormatter: typeof _useFormatter = () => {\n const { locale } = useLocaleIntlayer();\n return buildIntlFormatter((locale as string) ?? 'en');\n};\n"],"mappings":";;;;;;;;;;;;;AAkBA,MAAa,+BAA+B,IAAI,
|
|
1
|
+
{"version":3,"file":"helpers.mjs","names":["useLocaleIntlayer"],"sources":["../../../src/client/helpers.ts"],"sourcesContent":["'use client';\n\nimport { log } from '@intlayer/config/built';\nimport { CYAN } from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { useLocale as useLocaleIntlayer } from 'react-intlayer';\nimport type {\n useFormatter as _useFormatter,\n useMessages as _useMessages,\n useNow as _useNow,\n useTimeZone as _useTimeZone,\n} from 'use-intl';\nimport { buildIntlFormatter } from '../shared/intlFormatter';\n\n/**\n * Drop-in for use-intl's `useNow`.\n * Returns the current `Date`. The `updateInterval` option is ignored.\n */\nexport const useNow: typeof _useNow = () => new Date();\n\n/**\n * Drop-in for use-intl's `useTimeZone`.\n * Returns the system time zone resolved from `Intl.DateTimeFormat`.\n */\nexport const useTimeZone: typeof _useTimeZone = () =>\n Intl.DateTimeFormat().resolvedOptions().timeZone;\n\n/**\n * Drop-in for use-intl's `useMessages`.\n *\n * @deprecated useMessages has no use case with intlayer.\n * Messages are loaded automatically under the hood.\n * @returns An empty object.\n */\nexport const useMessages: typeof _useMessages = () => {\n if (process.env.NODE_ENV === 'development') {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize('useMessages', CYAN)} has no use case with intlayer. Messages are loaded automatically under the hood for bundle optimization reason`\n );\n }\n\n return {} as ReturnType<typeof _useMessages>;\n};\n\n/**\n * Drop-in for use-intl's `useFormatter`.\n * Returns locale-aware formatters backed by the native `Intl.*` APIs:\n * `dateTime`, `number`, `dateTimeRange`, `relativeTime`, `list`, and\n * `displayName`.\n */\nexport const useFormatter: typeof _useFormatter = () => {\n const { locale } = useLocaleIntlayer();\n return buildIntlFormatter((locale as string) ?? 'en');\n};\n"],"mappings":";;;;;;;;;;;;;AAkBA,MAAa,+BAA+B,IAAI,KAAK;;;;;AAMrD,MAAa,oBACX,KAAK,eAAe,CAAC,CAAC,gBAAgB,CAAC,CAAC;;;;;;;;AAS1C,MAAa,oBAAyC;CAGlD,AADkB,aAAa,EAAE,IAAI,CAC7B,CAAC,CACP,GAAG,SAAS,eAAe,IAAI,EAAE,gHACnC;CAGF,OAAO,CAAC;AACV;;;;;;;AAQA,MAAa,qBAA2C;CACtD,MAAM,EAAE,WAAWA,UAAkB;CACrC,OAAO,mBAAoB,UAAqB,IAAI;AACtD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/client/index.ts"],"sourcesContent":["export { useDictionary } from '../useDictionary';\nexport { useDictionaryDynamic } from '../useDictionaryDynamic';\nexport { useFormatter, useMessages, useNow, useTimeZone } from './helpers';\nexport { IntlProvider, type IntlProviderProps } from './IntlProvider';\nexport { useLocale } from './useLocale';\nexport { useTranslations } from './useTranslations';\n\n/**\n * @internal Private use-intl export, kept so aliased `_useExtracted` imports\n * resolve. Not part of the supported public surface.\n */\nexport const _useExtracted = (): Record<string, never> => ({});\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,uBAA8C,
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/client/index.ts"],"sourcesContent":["export { useDictionary } from '../useDictionary';\nexport { useDictionaryDynamic } from '../useDictionaryDynamic';\nexport { useFormatter, useMessages, useNow, useTimeZone } from './helpers';\nexport { IntlProvider, type IntlProviderProps } from './IntlProvider';\nexport { useLocale } from './useLocale';\nexport { useTranslations } from './useTranslations';\n\n/**\n * @internal Private use-intl export, kept so aliased `_useExtracted` imports\n * resolve. Not part of the supported public surface.\n */\nexport const _useExtracted = (): Record<string, never> => ({});\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,uBAA8C,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocale.mjs","names":["useLocaleIntlayer"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport { useLocale as useLocaleIntlayer } from 'react-intlayer';\nimport type { useLocale as _useLocale } from 'use-intl';\n\n/**\n * Drop-in for use-intl's `useLocale`.\n *\n * Returns the active locale string from Intlayer's client context.\n */\nexport const useLocale: typeof _useLocale = () => {\n const { locale } = useLocaleIntlayer();\n return locale as ReturnType<typeof _useLocale>;\n};\n"],"mappings":";;;;;;;;;;AAUA,MAAa,kBAAqC;CAChD,MAAM,EAAE,WAAWA,
|
|
1
|
+
{"version":3,"file":"useLocale.mjs","names":["useLocaleIntlayer"],"sources":["../../../src/client/useLocale.ts"],"sourcesContent":["'use client';\n\nimport { useLocale as useLocaleIntlayer } from 'react-intlayer';\nimport type { useLocale as _useLocale } from 'use-intl';\n\n/**\n * Drop-in for use-intl's `useLocale`.\n *\n * Returns the active locale string from Intlayer's client context.\n */\nexport const useLocale: typeof _useLocale = () => {\n const { locale } = useLocaleIntlayer();\n return locale as ReturnType<typeof _useLocale>;\n};\n"],"mappings":";;;;;;;;;;AAUA,MAAa,kBAAqC;CAChD,MAAM,EAAE,WAAWA,YAAkB;CACrC,OAAO;AACT"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
3
|
import { createNamespaceTranslator } from "../shared/namespaceTranslator.mjs";
|
|
4
|
-
import { IntlayerClientContext } from "react-intlayer";
|
|
5
4
|
import { useContext, useMemo } from "react";
|
|
5
|
+
import { IntlayerClientContext } from "react-intlayer";
|
|
6
6
|
|
|
7
7
|
//#region src/client/useTranslations.ts
|
|
8
8
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useTranslations.mjs","names":[],"sources":["../../../src/client/useTranslations.ts"],"sourcesContent":["'use client';\n\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useContext, useMemo } from 'react';\nimport { IntlayerClientContext } from 'react-intlayer';\nimport { createNamespaceTranslator } from '../shared/namespaceTranslator';\nimport type {\n LooseTranslateFunction,\n TranslateFunction,\n} from '../shared/translateFunctionTypes';\n\n/**\n * Overload set for {@link useTranslations}:\n *\n * 1. A bare dictionary key → fully-typed `t()` (autocompleted dot-paths).\n * 2. A nested namespace `'dictionary.sub.scope'` → `t()` accepts relative\n *
|
|
1
|
+
{"version":3,"file":"useTranslations.mjs","names":[],"sources":["../../../src/client/useTranslations.ts"],"sourcesContent":["'use client';\n\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useContext, useMemo } from 'react';\nimport { IntlayerClientContext } from 'react-intlayer';\nimport { createNamespaceTranslator } from '../shared/namespaceTranslator';\nimport type {\n LooseTranslateFunction,\n TranslateFunction,\n TranslateFunctionForNamespace,\n} from '../shared/translateFunctionTypes';\n\n/**\n * Overload set for {@link useTranslations}:\n *\n * 1. A bare dictionary key → fully-typed `t()` (autocompleted dot-paths).\n * 2. A nested namespace `'dictionary.sub.scope'` → `t()` accepts relative\n * dot-paths under the scope, typed against the dictionary, matching\n * use-intl's scoped-namespace behaviour.\n * 3. No namespace → root scope; the first segment of each key designates\n * the dictionary (`t('about.title')`).\n */\ntype UseTranslations = {\n <N extends DictionaryKeys>(namespace: N): TranslateFunction<N>;\n <N extends `${string}.${string}`>(\n namespace: N\n ): TranslateFunctionForNamespace<N>;\n (): LooseTranslateFunction;\n};\n\n/**\n * Drop-in for use-intl's `useTranslations`.\n *\n * Messages support ICU MessageFormat syntax: simple arguments (`{name}`),\n * plural (`{count, plural, one {…} other {…}}`, `#`), select, and formatted\n * arguments (`{value, number}`). Rich text is available through `t.rich()`\n * and `t.markup()`.\n *\n * @example\n * ```tsx\n * const t = useTranslations('about');\n * t('counter.label'); // ✓ typed\n * t('items', { count: 3 }); // ICU plural\n *\n * // Scoped to a nested object (use-intl idiom)\n * const t = useTranslations('about.counter');\n * t('label'); // resolves about → counter.label\n *\n * // Rich text\n * t.rich('terms', { link: (chunks) => <a href=\"/terms\">{chunks}</a> });\n * ```\n */\nexport const useTranslations = ((namespace?: string) => {\n const { locale: currentLocale } = useContext(IntlayerClientContext) ?? {};\n\n return useMemo(\n () => createNamespaceTranslator(currentLocale as LocalesValues, namespace),\n [currentLocale, namespace]\n );\n}) as UseTranslations;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAa,oBAAoB,cAAuB;CACtD,MAAM,EAAE,QAAQ,kBAAkB,WAAW,qBAAqB,KAAK,CAAC;CAExE,OAAO,cACC,0BAA0B,eAAgC,SAAS,GACzE,CAAC,eAAe,SAAS,CAC3B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createFormatter.mjs","names":[],"sources":["../../../src/core/createFormatter.ts"],"sourcesContent":["import type { createFormatter as _createFormatter } from 'use-intl';\nimport { buildIntlFormatter } from '../shared/intlFormatter';\n\n/**\n * Drop-in for use-intl's `createFormatter`.\n *\n * Returns locale-aware formatters backed by the native `Intl.*` APIs:\n * `dateTime`, `number`, `dateTimeRange`, `relativeTime`, `list`, and\n * `displayName`. `now`, `timeZone`, `formats`, and `onError` are accepted for\n * API compatibility but only `locale` influences the output.\n *\n * @example\n * ```ts\n * const format = createFormatter({ locale: 'en' });\n * format.number(1234.5, { style: 'currency', currency: 'USD' });\n * ```\n */\nexport const createFormatter: typeof _createFormatter = ({ locale }) =>\n buildIntlFormatter(locale);\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAa,mBAA4C,EAAE,aACzD,mBAAmB,
|
|
1
|
+
{"version":3,"file":"createFormatter.mjs","names":[],"sources":["../../../src/core/createFormatter.ts"],"sourcesContent":["import type { createFormatter as _createFormatter } from 'use-intl';\nimport { buildIntlFormatter } from '../shared/intlFormatter';\n\n/**\n * Drop-in for use-intl's `createFormatter`.\n *\n * Returns locale-aware formatters backed by the native `Intl.*` APIs:\n * `dateTime`, `number`, `dateTimeRange`, `relativeTime`, `list`, and\n * `displayName`. `now`, `timeZone`, `formats`, and `onError` are accepted for\n * API compatibility but only `locale` influences the output.\n *\n * @example\n * ```ts\n * const format = createFormatter({ locale: 'en' });\n * format.number(1234.5, { style: 'currency', currency: 'USD' });\n * ```\n */\nexport const createFormatter: typeof _createFormatter = ({ locale }) =>\n buildIntlFormatter(locale);\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAa,mBAA4C,EAAE,aACzD,mBAAmB,MAAM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createTranslator.mjs","names":[],"sources":["../../../src/core/createTranslator.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { CYAN } from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { createNamespaceTranslator } from '../shared/namespaceTranslator';\nimport type {\n LooseTranslateFunction,\n TranslateFunction,\n} from '../shared/translateFunctionTypes';\n\n/**\n * Configuration accepted by {@link createTranslator}.\n *\n * Mirrors use-intl's `IntlConfig`, but `messages`, `formats`, `now`,\n * `timeZone`, `onError`, and `getMessageFallback` have no effect — Intlayer\n * resolves content from its own compiled dictionaries.\n */\nexport type CreateTranslatorConfig<N extends DictionaryKeys> = {\n /** The locale dictionaries are resolved for. */\n locale: LocalesValues;\n /** A bare dictionary key, or a nested `'dictionary.scope'` namespace. */\n namespace?: N | (string & {});\n /**\n * @deprecated has no use case with intlayer. Messages are loaded\n * automatically under the hood for bundle optimization reason.\n */\n messages?: never;\n} & Record<string, unknown>;\n\n/**\n * Overload set for {@link createTranslator}:\n *\n * 1. A bare dictionary key → fully-typed `t()` (autocompleted dot-paths).\n * 2. A nested namespace `'dictionary.sub.scope'` → `t()` accepts relative\n *
|
|
1
|
+
{"version":3,"file":"createTranslator.mjs","names":[],"sources":["../../../src/core/createTranslator.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport { CYAN } from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { createNamespaceTranslator } from '../shared/namespaceTranslator';\nimport type {\n LooseTranslateFunction,\n TranslateFunction,\n TranslateFunctionForNamespace,\n} from '../shared/translateFunctionTypes';\n\n/**\n * Configuration accepted by {@link createTranslator}.\n *\n * Mirrors use-intl's `IntlConfig`, but `messages`, `formats`, `now`,\n * `timeZone`, `onError`, and `getMessageFallback` have no effect — Intlayer\n * resolves content from its own compiled dictionaries.\n */\nexport type CreateTranslatorConfig<N extends DictionaryKeys> = {\n /** The locale dictionaries are resolved for. */\n locale: LocalesValues;\n /** A bare dictionary key, or a nested `'dictionary.scope'` namespace. */\n namespace?: N | (string & {});\n /**\n * @deprecated has no use case with intlayer. Messages are loaded\n * automatically under the hood for bundle optimization reason.\n */\n messages?: never;\n} & Record<string, unknown>;\n\n/**\n * Overload set for {@link createTranslator}:\n *\n * 1. A bare dictionary key → fully-typed `t()` (autocompleted dot-paths).\n * 2. A nested namespace `'dictionary.sub.scope'` → `t()` accepts relative\n * dot-paths under the scope, typed against the dictionary, matching\n * use-intl's scoped-namespace behaviour.\n * 3. No namespace → root scope; the first segment of each key designates\n * the dictionary (`t('about.title')`).\n */\ntype CreateTranslator = {\n <N extends DictionaryKeys>(\n config: CreateTranslatorConfig<N> & { namespace: N }\n ): TranslateFunction<N>;\n <N extends `${string}.${string}`>(\n config: CreateTranslatorConfig<DictionaryKeys> & { namespace: N }\n ): TranslateFunctionForNamespace<N>;\n (config: CreateTranslatorConfig<DictionaryKeys>): LooseTranslateFunction;\n};\n\n/**\n * Drop-in for use-intl's `createTranslator`.\n *\n * Returns a translate function (with `rich`, `markup`, `raw`, `has`) that\n * resolves messages from Intlayer's compiled dictionaries for the given\n * `locale`. Messages support ICU MessageFormat syntax.\n *\n * @example\n * ```ts\n * const t = createTranslator({ locale: 'en', namespace: 'about' });\n * t('counter.label'); // ✓ typed\n * t('items', { count: 3 }); // ICU plural\n * ```\n */\nexport const createTranslator = (({\n locale,\n namespace,\n messages: _messages,\n}: CreateTranslatorConfig<DictionaryKeys>) => {\n if (process.env.NODE_ENV === 'development' && _messages !== undefined) {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize('createTranslator', CYAN)} do not pass the messages option with intlayer. Messages are loaded automatically under the hood for bundle optimization reason`\n );\n }\n\n return createNamespaceTranslator(locale, namespace);\n}) as CreateTranslator;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmEA,MAAa,qBAAqB,EAChC,QACA,WACA,UAAU,gBACkC;CAC5C,IAA8C,cAAc,QAE1D,AADkB,aAAa,EAAE,IAAI,CAC7B,CAAC,CACP,GAAG,SAAS,oBAAoB,IAAI,EAAE,gIACxC;CAGF,OAAO,0BAA0B,QAAQ,SAAS;AACpD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.mjs","names":[],"sources":["../../../src/core/errors.ts"],"sourcesContent":["/**\n * Drop-in for use-intl's `IntlErrorCode` enum.\n *\n * Re-implemented locally (rather than re-exported) because `use-intl` is\n * aliased to this package at build time, so importing its runtime value would\n * be circular.\n */\nexport enum IntlErrorCode {\n MISSING_MESSAGE = 'MISSING_MESSAGE',\n MISSING_FORMAT = 'MISSING_FORMAT',\n ENVIRONMENT_FALLBACK = 'ENVIRONMENT_FALLBACK',\n INSUFFICIENT_PATH = 'INSUFFICIENT_PATH',\n INVALID_MESSAGE = 'INVALID_MESSAGE',\n INVALID_KEY = 'INVALID_KEY',\n FORMATTING_ERROR = 'FORMATTING_ERROR',\n}\n\n/**\n * Drop-in for use-intl's `IntlError`.\n *\n * Carries the {@link IntlErrorCode} and the original message, matching\n * use-intl's error shape so consumer `onError` handlers keep working.\n */\nexport class IntlError extends Error {\n public readonly code: IntlErrorCode;\n public readonly originalMessage: string | undefined;\n\n constructor(code: IntlErrorCode, originalMessage?: string) {\n let message: string = code;\n if (originalMessage) {\n message += `: ${originalMessage}`;\n }\n super(message);\n\n this.code = code;\n if (originalMessage) {\n this.originalMessage = originalMessage;\n }\n }\n}\n"],"mappings":";;;;;;;;AAOA,IAAY,gBAAL;
|
|
1
|
+
{"version":3,"file":"errors.mjs","names":[],"sources":["../../../src/core/errors.ts"],"sourcesContent":["/**\n * Drop-in for use-intl's `IntlErrorCode` enum.\n *\n * Re-implemented locally (rather than re-exported) because `use-intl` is\n * aliased to this package at build time, so importing its runtime value would\n * be circular.\n */\nexport enum IntlErrorCode {\n MISSING_MESSAGE = 'MISSING_MESSAGE',\n MISSING_FORMAT = 'MISSING_FORMAT',\n ENVIRONMENT_FALLBACK = 'ENVIRONMENT_FALLBACK',\n INSUFFICIENT_PATH = 'INSUFFICIENT_PATH',\n INVALID_MESSAGE = 'INVALID_MESSAGE',\n INVALID_KEY = 'INVALID_KEY',\n FORMATTING_ERROR = 'FORMATTING_ERROR',\n}\n\n/**\n * Drop-in for use-intl's `IntlError`.\n *\n * Carries the {@link IntlErrorCode} and the original message, matching\n * use-intl's error shape so consumer `onError` handlers keep working.\n */\nexport class IntlError extends Error {\n public readonly code: IntlErrorCode;\n public readonly originalMessage: string | undefined;\n\n constructor(code: IntlErrorCode, originalMessage?: string) {\n let message: string = code;\n if (originalMessage) {\n message += `: ${originalMessage}`;\n }\n super(message);\n\n this.code = code;\n if (originalMessage) {\n this.originalMessage = originalMessage;\n }\n }\n}\n"],"mappings":";;;;;;;;AAOA,IAAY,gBAAL;CACL;CACA;CACA;CACA;CACA;CACA;CACA;;AACF;;;;;;;AAQA,IAAa,YAAb,cAA+B,MAAM;CACnC,AAAgB;CAChB,AAAgB;CAEhB,YAAY,MAAqB,iBAA0B;EACzD,IAAI,UAAkB;EACtB,IAAI,iBACF,WAAW,KAAK;EAElB,MAAM,OAAO;EAEb,KAAK,OAAO;EACZ,IAAI,iBACF,KAAK,kBAAkB;CAE3B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hasLocale.mjs","names":[],"sources":["../../../src/core/hasLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { hasLocale as _hasLocale } from 'use-intl';\n\n/**\n * Drop-in for use-intl's `hasLocale`.\n *\n * Narrows a locale candidate to the given locales list. When the list is\n * omitted, the locales configured in intlayer are used.\n *\n * @example\n * ```ts\n * if (hasLocale(['en', 'fr'], requested)) { … }\n * ```\n */\nexport const hasLocale: typeof _hasLocale = ((\n locales: readonly string[],\n candidate: unknown\n): boolean => {\n const availableLocales =\n locales ?? internationalization?.locales?.map(String) ?? [];\n return availableLocales.includes(candidate as string);\n}) as typeof _hasLocale;\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,cACX,SACA,cACY;
|
|
1
|
+
{"version":3,"file":"hasLocale.mjs","names":[],"sources":["../../../src/core/hasLocale.ts"],"sourcesContent":["import { internationalization } from '@intlayer/config/built';\nimport type { hasLocale as _hasLocale } from 'use-intl';\n\n/**\n * Drop-in for use-intl's `hasLocale`.\n *\n * Narrows a locale candidate to the given locales list. When the list is\n * omitted, the locales configured in intlayer are used.\n *\n * @example\n * ```ts\n * if (hasLocale(['en', 'fr'], requested)) { … }\n * ```\n */\nexport const hasLocale: typeof _hasLocale = ((\n locales: readonly string[],\n candidate: unknown\n): boolean => {\n const availableLocales =\n locales ?? internationalization?.locales?.map(String) ?? [];\n return availableLocales.includes(candidate as string);\n}) as typeof _hasLocale;\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,cACX,SACA,cACY;CAGZ,QADE,WAAW,sBAAsB,SAAS,IAAI,MAAM,KAAK,CAAC,EACrC,CAAC,SAAS,SAAmB;AACtD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initializeConfig.mjs","names":[],"sources":["../../../src/core/initializeConfig.ts"],"sourcesContent":["import type { initializeConfig as _initializeConfig } from 'use-intl';\n\n/**\n * Drop-in for use-intl's `initializeConfig`.\n *\n * Enhances an incoming config with defaults. With intlayer, `messages` and\n * `formats` are not consumed at runtime (content comes from compiled\n * dictionaries) but the shape is preserved so callers keep type-checking.\n */\nexport const initializeConfig: typeof _initializeConfig = ({\n formats,\n getMessageFallback,\n messages,\n onError,\n ...rest\n}) => {\n const finalOnError = onError ?? ((error) => error);\n const finalGetMessageFallback =\n getMessageFallback ??\n (({ key, namespace }) => [namespace, key].filter(Boolean).join('.'));\n\n return {\n ...rest,\n formats: formats || undefined,\n messages: messages || undefined,\n onError: finalOnError,\n getMessageFallback: finalGetMessageFallback,\n };\n};\n"],"mappings":";;;;;;;;AASA,MAAa,oBAA8C,EACzD,SACA,oBACA,UACA,SACA,GAAG,WACC;CACJ,MAAM,eAAe,aAAa,UAAU;CAC5C,MAAM,0BACJ,wBACE,EAAE,KAAK,gBAAgB,CAAC,WAAW,
|
|
1
|
+
{"version":3,"file":"initializeConfig.mjs","names":[],"sources":["../../../src/core/initializeConfig.ts"],"sourcesContent":["import type { initializeConfig as _initializeConfig } from 'use-intl';\n\n/**\n * Drop-in for use-intl's `initializeConfig`.\n *\n * Enhances an incoming config with defaults. With intlayer, `messages` and\n * `formats` are not consumed at runtime (content comes from compiled\n * dictionaries) but the shape is preserved so callers keep type-checking.\n */\nexport const initializeConfig: typeof _initializeConfig = ({\n formats,\n getMessageFallback,\n messages,\n onError,\n ...rest\n}) => {\n const finalOnError = onError ?? ((error) => error);\n const finalGetMessageFallback =\n getMessageFallback ??\n (({ key, namespace }) => [namespace, key].filter(Boolean).join('.'));\n\n return {\n ...rest,\n formats: formats || undefined,\n messages: messages || undefined,\n onError: finalOnError,\n getMessageFallback: finalGetMessageFallback,\n };\n};\n"],"mappings":";;;;;;;;AASA,MAAa,oBAA8C,EACzD,SACA,oBACA,UACA,SACA,GAAG,WACC;CACJ,MAAM,eAAe,aAAa,UAAU;CAC5C,MAAM,0BACJ,wBACE,EAAE,KAAK,gBAAgB,CAAC,WAAW,GAAG,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,GAAG;CAEpE,OAAO;EACL,GAAG;EACH,SAAS,WAAW;EACpB,UAAU,YAAY;EACtB,SAAS;EACT,oBAAoB;CACtB;AACF"}
|
package/dist/esm/index.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createDictionaryTranslator } from "./shared/namespaceTranslator.mjs";
|
|
1
2
|
import { useDictionaryDynamic } from "./useDictionaryDynamic.mjs";
|
|
2
3
|
import { useDictionary } from "./useDictionary.mjs";
|
|
3
4
|
import { useFormatter, useMessages, useNow, useTimeZone } from "./client/helpers.mjs";
|
|
@@ -11,4 +12,4 @@ import { IntlError, IntlErrorCode } from "./core/errors.mjs";
|
|
|
11
12
|
import { hasLocale } from "./core/hasLocale.mjs";
|
|
12
13
|
import { initializeConfig } from "./core/initializeConfig.mjs";
|
|
13
14
|
|
|
14
|
-
export { IntlError, IntlErrorCode, IntlProvider, _useExtracted, createFormatter, createTranslator, hasLocale, initializeConfig, useDictionary, useDictionaryDynamic, useFormatter, useLocale, useMessages, useNow, useTimeZone, useTranslations };
|
|
15
|
+
export { IntlError, IntlErrorCode, IntlProvider, _useExtracted, createDictionaryTranslator, createFormatter, createTranslator, hasLocale, initializeConfig, useDictionary, useDictionaryDynamic, useFormatter, useLocale, useMessages, useNow, useTimeZone, useTranslations };
|
|
@@ -1,46 +1,13 @@
|
|
|
1
1
|
import * as ANSIColors from "@intlayer/config/colors";
|
|
2
2
|
import { colorize, getAppLogger } from "@intlayer/config/logger";
|
|
3
3
|
import { join } from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { USE_INTL_CALLERS } from "@intlayer/config/callers";
|
|
5
5
|
import { getConfiguration } from "@intlayer/config/node";
|
|
6
|
+
import { runOnce } from "@intlayer/engine/utils";
|
|
6
7
|
import { intlayer } from "vite-intlayer";
|
|
7
8
|
|
|
8
9
|
//#region src/plugin/index.ts
|
|
9
10
|
/**
|
|
10
|
-
* Caller configurations for use-intl's translation entry points.
|
|
11
|
-
*
|
|
12
|
-
* Tells the intlayer field-usage analyser how to extract the dictionary key
|
|
13
|
-
* (namespace) and consumed fields from `useTranslations` / `createTranslator`
|
|
14
|
-
* call sites, enabling accurate dictionary pruning for projects using
|
|
15
|
-
* `@intlayer/use-intl`.
|
|
16
|
-
*/
|
|
17
|
-
const USE_INTL_COMPAT_CALLERS = [{
|
|
18
|
-
callerName: "useTranslations",
|
|
19
|
-
importSources: [
|
|
20
|
-
"use-intl",
|
|
21
|
-
"use-intl/react",
|
|
22
|
-
"@intlayer/use-intl"
|
|
23
|
-
],
|
|
24
|
-
namespace: {
|
|
25
|
-
from: "argument",
|
|
26
|
-
index: 0
|
|
27
|
-
},
|
|
28
|
-
translationFunction: "return-value"
|
|
29
|
-
}, {
|
|
30
|
-
callerName: "createTranslator",
|
|
31
|
-
importSources: [
|
|
32
|
-
"use-intl",
|
|
33
|
-
"use-intl/core",
|
|
34
|
-
"@intlayer/use-intl"
|
|
35
|
-
],
|
|
36
|
-
namespace: {
|
|
37
|
-
from: "option",
|
|
38
|
-
argumentIndex: 0,
|
|
39
|
-
property: "namespace"
|
|
40
|
-
},
|
|
41
|
-
translationFunction: "return-value"
|
|
42
|
-
}];
|
|
43
|
-
/**
|
|
44
11
|
* A Vite plugin for use-intl compat that wraps vite-intlayer and configures
|
|
45
12
|
* resolve aliases so `use-intl` imports are served by `@intlayer/use-intl`.
|
|
46
13
|
*
|
|
@@ -62,7 +29,7 @@ const useIntlVitePlugin = (options) => {
|
|
|
62
29
|
}, { cacheTimeoutMs: 1e3 * 60 * 60 });
|
|
63
30
|
const basePlugins = intlayer({
|
|
64
31
|
...options,
|
|
65
|
-
compatCallers: [...options?.compatCallers ?? [], ...
|
|
32
|
+
compatCallers: [...options?.compatCallers ?? [], ...USE_INTL_CALLERS]
|
|
66
33
|
});
|
|
67
34
|
const compatPlugin = {
|
|
68
35
|
name: "vite-use-intl-compat-plugin",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/plugin/index.ts"],"sourcesContent":["import { join } from 'node:path';\nimport {
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/plugin/index.ts"],"sourcesContent":["import { join } from 'node:path';\nimport { USE_INTL_CALLERS } from '@intlayer/config/callers';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { getConfiguration } from '@intlayer/config/node';\nimport { runOnce } from '@intlayer/engine/utils';\nimport type { PluginOption } from 'vite';\nimport { intlayer } from 'vite-intlayer';\n\n/**\n * A Vite plugin for use-intl compat that wraps vite-intlayer and configures\n * resolve aliases so `use-intl` imports are served by `@intlayer/use-intl`.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import useIntlVitePlugin from '@intlayer/use-intl/plugin';\n *\n * export default defineConfig({\n * plugins: [useIntlVitePlugin()],\n * });\n * ```\n */\nexport const useIntlVitePlugin = (\n options?: Parameters<typeof intlayer>[0]\n): PluginOption[] => {\n const intlayerConfig = getConfiguration();\n const appLogger = getAppLogger(intlayerConfig);\n\n runOnce(\n join(\n intlayerConfig.system.baseDir,\n '.intlayer',\n 'cache',\n 'intlayer-issues-invitation.lock'\n ),\n () => {\n appLogger([\n colorize(\n 'Please report any issues you met on GitHub:',\n ANSIColors.GREY\n ),\n colorize(\n 'https://github.com/aymericzip/intlayer/issues',\n ANSIColors.GREY_LIGHT\n ),\n ]);\n },\n {\n cacheTimeoutMs: 1000 * 60 * 60, // 1 hour\n }\n );\n\n const basePlugins = intlayer({\n ...options,\n compatCallers: [...(options?.compatCallers ?? []), ...USE_INTL_CALLERS],\n });\n\n const compatPlugin: PluginOption = {\n name: 'vite-use-intl-compat-plugin',\n config: () => ({\n resolve: {\n alias: {\n 'use-intl': '@intlayer/use-intl',\n },\n },\n }),\n };\n\n return [\n ...(Array.isArray(basePlugins) ? basePlugins : [basePlugins]),\n compatPlugin,\n ];\n};\n\nexport default useIntlVitePlugin;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,qBACX,YACmB;CACnB,MAAM,iBAAiB,iBAAiB;CACxC,MAAM,YAAY,aAAa,cAAc;CAE7C,QACE,KACE,eAAe,OAAO,SACtB,aACA,SACA,iCACF,SACM;EACJ,UAAU,CACR,SACE,+CACA,WAAW,IACb,GACA,SACE,iDACA,WAAW,UACb,CACF,CAAC;CACH,GACA,EACE,gBAAgB,MAAO,KAAK,GAC9B,CACF;CAEA,MAAM,cAAc,SAAS;EAC3B,GAAG;EACH,eAAe,CAAC,GAAI,SAAS,iBAAiB,CAAC,GAAI,GAAG,gBAAgB;CACxE,CAAC;CAED,MAAM,eAA6B;EACjC,MAAM;EACN,eAAe,EACb,SAAS,EACP,OAAO,EACL,YAAY,qBACd,EACF,EACF;CACF;CAEA,OAAO,CACL,GAAI,MAAM,QAAQ,WAAW,IAAI,cAAc,CAAC,WAAW,GAC3D,YACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlFormatter.mjs","names":[],"sources":["../../../src/shared/intlFormatter.ts"],"sourcesContent":["import type { createFormatter as _createFormatter } from 'use-intl';\n\n/** The formatter object shape exposed by use-intl. */\nexport type Formatter = ReturnType<typeof _createFormatter>;\n\n/** Time units orderable by their duration in seconds. */\nconst RELATIVE_TIME_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [\n ['year', 31536000],\n ['month', 2628000],\n ['week', 604800],\n ['day', 86400],\n ['hour', 3600],\n ['minute', 60],\n ['second', 1],\n];\n\nconst toDate = (value: Date | number | string): Date =>\n value instanceof Date ? value : new Date(value);\n\n/**\n * Builds a use-intl compatible formatter backed by the native `Intl.*` APIs\n * for the given locale.\n *\n * Shared by `useFormatter` (React hook) and `createFormatter` (non-React core).\n *\n * @param locale - The locale used by every `Intl.*` formatter instance.\n * @returns A formatter exposing `dateTime`, `number`, `dateTimeRange`,\n * `relativeTime`, `list`, and `displayName`.\n */\nexport const buildIntlFormatter = (locale: string): Formatter =>\n ({\n dateTime: (value: Date | number, options?: Intl.DateTimeFormatOptions) =>\n new Intl.DateTimeFormat(locale, options).format(value),\n\n number: (value: number | bigint, options?: Intl.NumberFormatOptions) =>\n new Intl.NumberFormat(locale, options).format(value),\n\n /** Formats a date range with `Intl.DateTimeFormat#formatRange`. */\n dateTimeRange: (\n start: Date | number,\n end: Date | number,\n options?: Intl.DateTimeFormatOptions\n ) =>\n new Intl.DateTimeFormat(locale, options).formatRange(\n toDate(start),\n toDate(end)\n ),\n\n /**\n * Formats a date relative to now (or a reference date), automatically\n * selecting the largest fitting unit.\n */\n relativeTime: (\n date: Date | number | string,\n nowOrOptions?:\n | Date\n | number\n | {\n now?: Date | number;\n unit?: Intl.RelativeTimeFormatUnit;\n style?: Intl.RelativeTimeFormatStyle;\n numberingSystem?: string;\n }\n ) => {\n const options =\n nowOrOptions instanceof Date || typeof nowOrOptions === 'number'\n ? { now: nowOrOptions }\n : (nowOrOptions ?? {});\n\n const nowDate =\n options.now !== undefined ? toDate(options.now) : new Date();\n const diffInSeconds = (toDate(date).getTime() - nowDate.getTime()) / 1000;\n\n let unit = options.unit;\n if (!unit) {\n const absoluteDiff = Math.abs(diffInSeconds);\n unit =\n RELATIVE_TIME_UNITS.find(\n ([, unitSeconds]) => absoluteDiff >= unitSeconds\n )?.[0] ?? 'second';\n }\n\n const unitSeconds =\n RELATIVE_TIME_UNITS.find(([unitName]) => unitName === unit)?.[1] ?? 1;\n\n return new Intl.RelativeTimeFormat(locale, {\n numeric: 'auto',\n style: options.style,\n }).format(Math.round(diffInSeconds / unitSeconds), unit);\n },\n\n /** Formats a list with `Intl.ListFormat`. */\n list: (value: Iterable<string>, options?: Intl.ListFormatOptions): string =>\n new Intl.ListFormat(locale, options).format(value),\n\n displayName: (\n value: string,\n optionsOrFormat?: Intl.DisplayNamesOptions | string,\n extraOptions?: Intl.DisplayNamesOptions\n ): string => {\n const resolvedOptions =\n typeof optionsOrFormat === 'string' ? extraOptions : optionsOrFormat;\n try {\n return (\n new Intl.DisplayNames(\n [locale],\n resolvedOptions ?? { type: 'language' }\n ).of(value) ?? value\n );\n } catch {\n return value;\n }\n },\n }) as unknown as Formatter;\n"],"mappings":";;AAMA,MAAM,sBAA+D;CACnE,CAAC,QAAQ,
|
|
1
|
+
{"version":3,"file":"intlFormatter.mjs","names":[],"sources":["../../../src/shared/intlFormatter.ts"],"sourcesContent":["import type { createFormatter as _createFormatter } from 'use-intl';\n\n/** The formatter object shape exposed by use-intl. */\nexport type Formatter = ReturnType<typeof _createFormatter>;\n\n/** Time units orderable by their duration in seconds. */\nconst RELATIVE_TIME_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [\n ['year', 31536000],\n ['month', 2628000],\n ['week', 604800],\n ['day', 86400],\n ['hour', 3600],\n ['minute', 60],\n ['second', 1],\n];\n\nconst toDate = (value: Date | number | string): Date =>\n value instanceof Date ? value : new Date(value);\n\n/**\n * Builds a use-intl compatible formatter backed by the native `Intl.*` APIs\n * for the given locale.\n *\n * Shared by `useFormatter` (React hook) and `createFormatter` (non-React core).\n *\n * @param locale - The locale used by every `Intl.*` formatter instance.\n * @returns A formatter exposing `dateTime`, `number`, `dateTimeRange`,\n * `relativeTime`, `list`, and `displayName`.\n */\nexport const buildIntlFormatter = (locale: string): Formatter =>\n ({\n dateTime: (value: Date | number, options?: Intl.DateTimeFormatOptions) =>\n new Intl.DateTimeFormat(locale, options).format(value),\n\n number: (value: number | bigint, options?: Intl.NumberFormatOptions) =>\n new Intl.NumberFormat(locale, options).format(value),\n\n /** Formats a date range with `Intl.DateTimeFormat#formatRange`. */\n dateTimeRange: (\n start: Date | number,\n end: Date | number,\n options?: Intl.DateTimeFormatOptions\n ) =>\n new Intl.DateTimeFormat(locale, options).formatRange(\n toDate(start),\n toDate(end)\n ),\n\n /**\n * Formats a date relative to now (or a reference date), automatically\n * selecting the largest fitting unit.\n */\n relativeTime: (\n date: Date | number | string,\n nowOrOptions?:\n | Date\n | number\n | {\n now?: Date | number;\n unit?: Intl.RelativeTimeFormatUnit;\n style?: Intl.RelativeTimeFormatStyle;\n numberingSystem?: string;\n }\n ) => {\n const options =\n nowOrOptions instanceof Date || typeof nowOrOptions === 'number'\n ? { now: nowOrOptions }\n : (nowOrOptions ?? {});\n\n const nowDate =\n options.now !== undefined ? toDate(options.now) : new Date();\n const diffInSeconds = (toDate(date).getTime() - nowDate.getTime()) / 1000;\n\n let unit = options.unit;\n if (!unit) {\n const absoluteDiff = Math.abs(diffInSeconds);\n unit =\n RELATIVE_TIME_UNITS.find(\n ([, unitSeconds]) => absoluteDiff >= unitSeconds\n )?.[0] ?? 'second';\n }\n\n const unitSeconds =\n RELATIVE_TIME_UNITS.find(([unitName]) => unitName === unit)?.[1] ?? 1;\n\n return new Intl.RelativeTimeFormat(locale, {\n numeric: 'auto',\n style: options.style,\n }).format(Math.round(diffInSeconds / unitSeconds), unit);\n },\n\n /** Formats a list with `Intl.ListFormat`. */\n list: (value: Iterable<string>, options?: Intl.ListFormatOptions): string =>\n new Intl.ListFormat(locale, options).format(value),\n\n displayName: (\n value: string,\n optionsOrFormat?: Intl.DisplayNamesOptions | string,\n extraOptions?: Intl.DisplayNamesOptions\n ): string => {\n const resolvedOptions =\n typeof optionsOrFormat === 'string' ? extraOptions : optionsOrFormat;\n try {\n return (\n new Intl.DisplayNames(\n [locale],\n resolvedOptions ?? { type: 'language' }\n ).of(value) ?? value\n );\n } catch {\n return value;\n }\n },\n }) as unknown as Formatter;\n"],"mappings":";;AAMA,MAAM,sBAA+D;CACnE,CAAC,QAAQ,OAAQ;CACjB,CAAC,SAAS,MAAO;CACjB,CAAC,QAAQ,MAAM;CACf,CAAC,OAAO,KAAK;CACb,CAAC,QAAQ,IAAI;CACb,CAAC,UAAU,EAAE;CACb,CAAC,UAAU,CAAC;AACd;AAEA,MAAM,UAAU,UACd,iBAAiB,OAAO,QAAQ,IAAI,KAAK,KAAK;;;;;;;;;;;AAYhD,MAAa,sBAAsB,YAChC;CACC,WAAW,OAAsB,YAC/B,IAAI,KAAK,eAAe,QAAQ,OAAO,CAAC,CAAC,OAAO,KAAK;CAEvD,SAAS,OAAwB,YAC/B,IAAI,KAAK,aAAa,QAAQ,OAAO,CAAC,CAAC,OAAO,KAAK;;CAGrD,gBACE,OACA,KACA,YAEA,IAAI,KAAK,eAAe,QAAQ,OAAO,CAAC,CAAC,YACvC,OAAO,KAAK,GACZ,OAAO,GAAG,CACZ;;;;;CAMF,eACE,MACA,iBASG;EACH,MAAM,UACJ,wBAAwB,QAAQ,OAAO,iBAAiB,WACpD,EAAE,KAAK,aAAa,IACnB,gBAAgB,CAAC;EAExB,MAAM,UACJ,QAAQ,QAAQ,SAAY,OAAO,QAAQ,GAAG,oBAAI,IAAI,KAAK;EAC7D,MAAM,iBAAiB,OAAO,IAAI,CAAC,CAAC,QAAQ,IAAI,QAAQ,QAAQ,KAAK;EAErE,IAAI,OAAO,QAAQ;EACnB,IAAI,CAAC,MAAM;GACT,MAAM,eAAe,KAAK,IAAI,aAAa;GAC3C,OACE,oBAAoB,MACjB,GAAG,iBAAiB,gBAAgB,WACvC,CAAC,GAAG,MAAM;EACd;EAEA,MAAM,cACJ,oBAAoB,MAAM,CAAC,cAAc,aAAa,IAAI,CAAC,GAAG,MAAM;EAEtE,OAAO,IAAI,KAAK,mBAAmB,QAAQ;GACzC,SAAS;GACT,OAAO,QAAQ;EACjB,CAAC,CAAC,CAAC,OAAO,KAAK,MAAM,gBAAgB,WAAW,GAAG,IAAI;CACzD;;CAGA,OAAO,OAAyB,YAC9B,IAAI,KAAK,WAAW,QAAQ,OAAO,CAAC,CAAC,OAAO,KAAK;CAEnD,cACE,OACA,iBACA,iBACW;EACX,MAAM,kBACJ,OAAO,oBAAoB,WAAW,eAAe;EACvD,IAAI;GACF,OACE,IAAI,KAAK,aACP,CAAC,MAAM,GACP,mBAAmB,EAAE,MAAM,WAAW,CACxC,CAAC,CAAC,GAAG,KAAK,KAAK;EAEnB,QAAQ;GACN,OAAO;EACT;CACF;AACF"}
|
|
@@ -1,26 +1,10 @@
|
|
|
1
|
-
import { getIntlayer } from "@intlayer/core/interpreter";
|
|
2
|
-
import { parseTaggedMessage, resolveMessage } from "@intlayer/core/messageFormat";
|
|
3
1
|
import { Fragment } from "react";
|
|
2
|
+
import { getIntlayer } from "@intlayer/core/interpreter";
|
|
3
|
+
import { navigatePath, navigatePath as navigatePath$1, parseTaggedMessage, resolveMessage } from "@intlayer/core/messageFormat";
|
|
4
|
+
import { getDictionaries } from "@intlayer/dictionaries-entry";
|
|
4
5
|
import { Fragment as Fragment$1, jsx } from "react/jsx-runtime";
|
|
5
6
|
|
|
6
7
|
//#region src/shared/namespaceTranslator.tsx
|
|
7
|
-
/**
|
|
8
|
-
* Reads a dotted `path` (e.g. `counter.label`) out of a nested object value.
|
|
9
|
-
*
|
|
10
|
-
* @param objectValue - The object to read from.
|
|
11
|
-
* @param path - Dot-separated path. An empty path returns `objectValue`.
|
|
12
|
-
* @returns The value found at `path`, or `undefined` when any segment is absent.
|
|
13
|
-
*/
|
|
14
|
-
const navigatePath = (objectValue, path) => {
|
|
15
|
-
if (!path) return objectValue;
|
|
16
|
-
const parts = path.split(".");
|
|
17
|
-
let current = objectValue;
|
|
18
|
-
for (const part of parts) {
|
|
19
|
-
if (current === null || current === void 0 || typeof current !== "object") return;
|
|
20
|
-
current = current[part];
|
|
21
|
-
}
|
|
22
|
-
return current;
|
|
23
|
-
};
|
|
24
8
|
/** Splits rich values into scalar interpolation values and tag renderers. */
|
|
25
9
|
const splitRichValues = (values = {}) => {
|
|
26
10
|
const scalarValues = {};
|
|
@@ -65,26 +49,63 @@ const renderMarkupTokens = (tokens, renderers) => tokens.map((token) => {
|
|
|
65
49
|
const createNamespaceTranslator = (locale, namespace) => {
|
|
66
50
|
const [dictionaryKey, ...prefixSegments] = (namespace ?? "").split(".");
|
|
67
51
|
const keyPrefix = prefixSegments.join(".");
|
|
68
|
-
const lookup = (
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
52
|
+
const lookup = (lookupKey) => lookupNamespaceKey(locale, dictionaryKey ?? "", keyPrefix, lookupKey);
|
|
53
|
+
return createLookupTranslator(locale, lookup, (key) => namespace ? `${namespace}.${key}` : key);
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Key-based lookup used by {@link createNamespaceTranslator}: resolves the
|
|
57
|
+
* dictionary through the runtime registry (`getIntlayer`).
|
|
58
|
+
*/
|
|
59
|
+
const lookupNamespaceKey = (locale, dictionaryKey, keyPrefix, key) => {
|
|
60
|
+
let targetDictionaryKey = dictionaryKey;
|
|
61
|
+
let path = keyPrefix ? `${keyPrefix}.${key}` : key;
|
|
62
|
+
const dictionaries = getDictionaries();
|
|
63
|
+
if (!targetDictionaryKey) {
|
|
64
|
+
const [firstSegment, ...restSegments] = key.split(".");
|
|
65
|
+
targetDictionaryKey = firstSegment ?? key;
|
|
66
|
+
path = restSegments.join(".");
|
|
67
|
+
if (!dictionaries[targetDictionaryKey]) for (const dictKey of Object.keys(dictionaries)) try {
|
|
68
|
+
const result = navigatePath$1(getIntlayer(dictKey, locale), key);
|
|
69
|
+
if (result !== void 0) return result;
|
|
70
|
+
} catch {}
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
return navigatePath$1(getIntlayer(targetDictionaryKey, locale), path);
|
|
74
|
+
} catch {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Dictionary-bound translator used by the build-optimized `useDictionary` /
|
|
80
|
+
* `getDictionary` variants: instead of resolving the dictionary by key at
|
|
81
|
+
* runtime, the pre-resolved content is supplied directly (the babel/swc
|
|
82
|
+
* optimize pass imports the dictionary JSON at build time).
|
|
83
|
+
*
|
|
84
|
+
* @param locale - The locale messages are resolved for.
|
|
85
|
+
* @param content - The dictionary content, already resolved for `locale`.
|
|
86
|
+
* @param namespacePrefix - Optional key prefix for nested namespaces
|
|
87
|
+
* (`useTranslations('about.counter')` → content of `about`, prefix `counter`).
|
|
88
|
+
* @returns A translate function augmented with `has`, `raw`, `rich`, `markup`.
|
|
89
|
+
*/
|
|
90
|
+
const createDictionaryTranslator = (locale, content, namespacePrefix) => {
|
|
91
|
+
const resolveKey = (key) => namespacePrefix ? `${namespacePrefix}.${key}` : key;
|
|
92
|
+
return createLookupTranslator(locale, (key) => navigatePath$1(content, resolveKey(key)), resolveKey);
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* The untyped runtime translator core shared by every factory above:
|
|
96
|
+
* ICU message resolution plus the `has` / `raw` / `rich` / `markup` helpers.
|
|
97
|
+
*
|
|
98
|
+
* @param locale - The locale messages are resolved for.
|
|
99
|
+
* @param lookup - Reads the raw content value for a message key.
|
|
100
|
+
* @param missingKeyFallback - Builds the echoed key on lookup miss
|
|
101
|
+
* (use-intl convention: `namespace.key`).
|
|
102
|
+
*/
|
|
103
|
+
const createLookupTranslator = (locale, lookup, missingKeyFallback) => {
|
|
82
104
|
const resolveToString = (key, values = {}) => {
|
|
83
105
|
const rawValue = lookup(key);
|
|
84
106
|
if (rawValue === null || rawValue === void 0) return void 0;
|
|
85
107
|
return resolveMessage(rawValue, values, locale, "icu");
|
|
86
108
|
};
|
|
87
|
-
const missingKeyFallback = (key) => namespace ? `${namespace}.${key}` : key;
|
|
88
109
|
const translate = (key, values) => resolveToString(key, values) ?? missingKeyFallback(key);
|
|
89
110
|
return Object.assign(translate, {
|
|
90
111
|
/** Returns `true` if the given key exists in the namespace. */
|
|
@@ -115,5 +136,5 @@ const createNamespaceTranslator = (locale, namespace) => {
|
|
|
115
136
|
};
|
|
116
137
|
|
|
117
138
|
//#endregion
|
|
118
|
-
export { createNamespaceTranslator, navigatePath };
|
|
139
|
+
export { createDictionaryTranslator, createNamespaceTranslator, navigatePath };
|
|
119
140
|
//# sourceMappingURL=namespaceTranslator.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"namespaceTranslator.mjs","names":[],"sources":["../../../src/shared/namespaceTranslator.tsx"],"sourcesContent":["import { getIntlayer } from '@intlayer/core/interpreter';\nimport {\n type MessageValues,\n parseTaggedMessage,\n resolveMessage,\n type TaggedMessageToken,\n} from '@intlayer/core/messageFormat';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { Fragment, type ReactNode } from 'react';\n\n/** Chunk renderer used by `t.rich()` — maps tag children to a React node. */\nexport type RichChunkRenderer = (chunks: ReactNode) => ReactNode;\n\n/** Chunk renderer used by `t.markup()` — maps tag children to a string. */\nexport type MarkupChunkRenderer = (chunks: string) => string;\n\n/**\n * Reads a dotted `path` (e.g. `counter.label`) out of a nested object value.\n *\n * @param objectValue - The object to read from.\n * @param path - Dot-separated path. An empty path returns `objectValue`.\n * @returns The value found at `path`, or `undefined` when any segment is absent.\n */\nexport const navigatePath = (objectValue: unknown, path: string): unknown => {\n if (!path) return objectValue;\n const parts = path.split('.');\n let current: unknown = objectValue;\n for (const part of parts) {\n if (\n current === null ||\n current === undefined ||\n typeof current !== 'object'\n ) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n};\n\n/** Splits rich values into scalar interpolation values and tag renderers. */\nconst splitRichValues = (\n values: Record<string, unknown> = {}\n): { scalarValues: MessageValues; renderers: Record<string, unknown> } => {\n const scalarValues: MessageValues = {};\n const renderers: Record<string, unknown> = {};\n\n for (const [valueKey, value] of Object.entries(values)) {\n if (typeof value === 'function') renderers[valueKey] = value;\n else scalarValues[valueKey] = value;\n }\n\n return { scalarValues, renderers };\n};\n\nconst renderRichTokens = (\n tokens: TaggedMessageToken[],\n renderers: Record<string, unknown>\n): ReactNode[] =>\n tokens.map((token, tokenIndex) => {\n if (typeof token === 'string') return token;\n\n const children = renderRichTokens(token.children, renderers);\n const renderer = renderers[token.tag];\n\n if (typeof renderer === 'function') {\n return (\n <Fragment key={tokenIndex}>\n {(renderer as RichChunkRenderer)(children)}\n </Fragment>\n );\n }\n\n // No renderer provided for the tag — render its children unwrapped\n return <Fragment key={tokenIndex}>{children}</Fragment>;\n });\n\nconst renderMarkupTokens = (\n tokens: TaggedMessageToken[],\n renderers: Record<string, unknown>\n): string =>\n tokens\n .map((token) => {\n if (typeof token === 'string') return token;\n\n const children = renderMarkupTokens(token.children, renderers);\n const renderer = renderers[token.tag];\n\n if (typeof renderer === 'function') {\n return (renderer as MarkupChunkRenderer)(children);\n }\n\n return children;\n })\n .join('');\n\n/**\n * The untyped runtime translator shared by `useTranslations` (React hook) and\n * `createTranslator` (non-React core).\n *\n * Behaviour matches use-intl / next-intl:\n * - namespace `'about'` → keys resolved inside the `about` dictionary\n * - namespace `'about.counter'` → dictionary `about`, key prefix `counter`\n * - no namespace → the first segment of each key is the dictionary key\n * - messages support ICU syntax (plural, select, `#`, formatted arguments)\n * - `t.rich` / `t.markup` map `<tag>chunks</tag>` through the provided\n * renderers; `t.raw` returns the raw value; `t.has` checks existence\n *\n * @param locale - The locale dictionaries are resolved for.\n * @param namespace - Optional dictionary key, optionally with a nested scope.\n * @returns A translate function augmented with `has`, `raw`, `rich`, `markup`.\n */\nexport const createNamespaceTranslator = (\n locale: LocalesValues,\n namespace?: string\n) => {\n const [dictionaryKey, ...prefixSegments] = (namespace ?? '').split('.');\n const keyPrefix = prefixSegments.join('.');\n\n const lookup = (key: string): unknown => {\n let targetDictionaryKey = dictionaryKey;\n let path = keyPrefix ? `${keyPrefix}.${key}` : key;\n\n if (!targetDictionaryKey) {\n // Root scope — the first key segment designates the dictionary\n const [firstSegment, ...restSegments] = key.split('.');\n targetDictionaryKey = firstSegment;\n path = restSegments.join('.');\n }\n\n try {\n const dictionary = getIntlayer(\n targetDictionaryKey as DictionaryKeys,\n locale\n );\n return navigatePath(dictionary, path);\n } catch {\n return undefined;\n }\n };\n\n const resolveToString = (\n key: string,\n values: MessageValues = {}\n ): string | undefined => {\n const rawValue = lookup(key);\n if (rawValue === null || rawValue === undefined) return undefined;\n return resolveMessage(rawValue, values, locale, 'icu');\n };\n\n const missingKeyFallback = (key: string): string =>\n namespace ? `${namespace}.${key}` : key;\n\n const translate = (key: string, values?: MessageValues): string =>\n resolveToString(key, values) ?? missingKeyFallback(key);\n\n return Object.assign(translate, {\n /** Returns `true` if the given key exists in the namespace. */\n has: (key: string): boolean => lookup(key) !== undefined,\n\n /** Returns the raw unprocessed content for the given key. */\n raw: (key: string): unknown => lookup(key),\n\n /**\n * Resolves a message containing `<tag>chunks</tag>` markup, mapping each\n * tag through the matching renderer in `values`.\n */\n rich: (key: string, values?: Record<string, unknown>): ReactNode => {\n const { scalarValues, renderers } = splitRichValues(values);\n const message = resolveToString(key, scalarValues);\n if (message === undefined) return missingKeyFallback(key);\n return <>{renderRichTokens(parseTaggedMessage(message), renderers)}</>;\n },\n\n /**\n * Resolves a message containing `<tag>chunks</tag>` markup into a string,\n * mapping each tag through the matching string renderer in `values`.\n */\n markup: (key: string, values?: Record<string, unknown>): string => {\n const { scalarValues, renderers } = splitRichValues(values);\n const message = resolveToString(key, scalarValues);\n if (message === undefined) return missingKeyFallback(key);\n return renderMarkupTokens(parseTaggedMessage(message), renderers);\n },\n });\n};\n\nexport type CompatTranslator = ReturnType<typeof createNamespaceTranslator>;\n"],"mappings":";;;;;;;;;;;;;AA0BA,MAAa,gBAAgB,aAAsB,SAA0B;AAC3E,KAAI,CAAC,KAAM,QAAO;CAClB,MAAM,QAAQ,KAAK,MAAM,IAAI;CAC7B,IAAI,UAAmB;AACvB,MAAK,MAAM,QAAQ,OAAO;AACxB,MACE,YAAY,QACZ,YAAY,UACZ,OAAO,YAAY,SAEnB;AAEF,YAAW,QAAoC;;AAEjD,QAAO;;;AAIT,MAAM,mBACJ,SAAkC,EAAE,KACoC;CACxE,MAAM,eAA8B,EAAE;CACtC,MAAM,YAAqC,EAAE;AAE7C,MAAK,MAAM,CAAC,UAAU,UAAU,OAAO,QAAQ,OAAO,CACpD,KAAI,OAAO,UAAU,WAAY,WAAU,YAAY;KAClD,cAAa,YAAY;AAGhC,QAAO;EAAE;EAAc;EAAW;;AAGpC,MAAM,oBACJ,QACA,cAEA,OAAO,KAAK,OAAO,eAAe;AAChC,KAAI,OAAO,UAAU,SAAU,QAAO;CAEtC,MAAM,WAAW,iBAAiB,MAAM,UAAU,UAAU;CAC5D,MAAM,WAAW,UAAU,MAAM;AAEjC,KAAI,OAAO,aAAa,WACtB,QACE,oBAAC,UAAD,YACI,SAA+B,SAAS,EACjC,EAFI,WAEJ;AAKf,QAAO,oBAAC,UAAD,EAA4B,UAAoB,EAAjC,WAAiC;EACvD;AAEJ,MAAM,sBACJ,QACA,cAEA,OACG,KAAK,UAAU;AACd,KAAI,OAAO,UAAU,SAAU,QAAO;CAEtC,MAAM,WAAW,mBAAmB,MAAM,UAAU,UAAU;CAC9D,MAAM,WAAW,UAAU,MAAM;AAEjC,KAAI,OAAO,aAAa,WACtB,QAAQ,SAAiC,SAAS;AAGpD,QAAO;EACP,CACD,KAAK,GAAG;;;;;;;;;;;;;;;;;AAkBb,MAAa,6BACX,QACA,cACG;CACH,MAAM,CAAC,eAAe,GAAG,mBAAmB,aAAa,IAAI,MAAM,IAAI;CACvE,MAAM,YAAY,eAAe,KAAK,IAAI;CAE1C,MAAM,UAAU,QAAyB;EACvC,IAAI,sBAAsB;EAC1B,IAAI,OAAO,YAAY,GAAG,UAAU,GAAG,QAAQ;AAE/C,MAAI,CAAC,qBAAqB;GAExB,MAAM,CAAC,cAAc,GAAG,gBAAgB,IAAI,MAAM,IAAI;AACtD,yBAAsB;AACtB,UAAO,aAAa,KAAK,IAAI;;AAG/B,MAAI;AAKF,UAAO,aAJY,YACjB,qBACA,OAE4B,EAAE,KAAK;UAC/B;AACN;;;CAIJ,MAAM,mBACJ,KACA,SAAwB,EAAE,KACH;EACvB,MAAM,WAAW,OAAO,IAAI;AAC5B,MAAI,aAAa,QAAQ,aAAa,OAAW,QAAO;AACxD,SAAO,eAAe,UAAU,QAAQ,QAAQ,MAAM;;CAGxD,MAAM,sBAAsB,QAC1B,YAAY,GAAG,UAAU,GAAG,QAAQ;CAEtC,MAAM,aAAa,KAAa,WAC9B,gBAAgB,KAAK,OAAO,IAAI,mBAAmB,IAAI;AAEzD,QAAO,OAAO,OAAO,WAAW;;EAE9B,MAAM,QAAyB,OAAO,IAAI,KAAK;;EAG/C,MAAM,QAAyB,OAAO,IAAI;;;;;EAM1C,OAAO,KAAa,WAAgD;GAClE,MAAM,EAAE,cAAc,cAAc,gBAAgB,OAAO;GAC3D,MAAM,UAAU,gBAAgB,KAAK,aAAa;AAClD,OAAI,YAAY,OAAW,QAAO,mBAAmB,IAAI;AACzD,UAAO,4CAAG,iBAAiB,mBAAmB,QAAQ,EAAE,UAAU,EAAI;;;;;;EAOxE,SAAS,KAAa,WAA6C;GACjE,MAAM,EAAE,cAAc,cAAc,gBAAgB,OAAO;GAC3D,MAAM,UAAU,gBAAgB,KAAK,aAAa;AAClD,OAAI,YAAY,OAAW,QAAO,mBAAmB,IAAI;AACzD,UAAO,mBAAmB,mBAAmB,QAAQ,EAAE,UAAU;;EAEpE,CAAC"}
|
|
1
|
+
{"version":3,"file":"namespaceTranslator.mjs","names":["navigatePath"],"sources":["../../../src/shared/namespaceTranslator.tsx"],"sourcesContent":["import { getIntlayer } from '@intlayer/core/interpreter';\nimport {\n type MessageValues,\n navigatePath,\n parseTaggedMessage,\n resolveMessage,\n type TaggedMessageToken,\n} from '@intlayer/core/messageFormat';\nimport { getDictionaries } from '@intlayer/dictionaries-entry';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { Fragment, type ReactNode } from 'react';\n\nexport { navigatePath } from '@intlayer/core/messageFormat';\n\n/** Chunk renderer used by `t.rich()` — maps tag children to a React node. */\nexport type RichChunkRenderer = (chunks: ReactNode) => ReactNode;\n\n/** Chunk renderer used by `t.markup()` — maps tag children to a string. */\nexport type MarkupChunkRenderer = (chunks: string) => string;\n\n/** Splits rich values into scalar interpolation values and tag renderers. */\nconst splitRichValues = (\n values: Record<string, unknown> = {}\n): { scalarValues: MessageValues; renderers: Record<string, unknown> } => {\n const scalarValues: MessageValues = {};\n const renderers: Record<string, unknown> = {};\n\n for (const [valueKey, value] of Object.entries(values)) {\n if (typeof value === 'function') renderers[valueKey] = value;\n else scalarValues[valueKey] = value;\n }\n\n return { scalarValues, renderers };\n};\n\nconst renderRichTokens = (\n tokens: TaggedMessageToken[],\n renderers: Record<string, unknown>\n): ReactNode[] =>\n tokens.map((token, tokenIndex) => {\n if (typeof token === 'string') return token;\n\n const children = renderRichTokens(token.children, renderers);\n const renderer = renderers[token.tag];\n\n if (typeof renderer === 'function') {\n return (\n <Fragment key={tokenIndex}>\n {(renderer as RichChunkRenderer)(children)}\n </Fragment>\n );\n }\n\n // No renderer provided for the tag — render its children unwrapped\n return <Fragment key={tokenIndex}>{children}</Fragment>;\n });\n\nconst renderMarkupTokens = (\n tokens: TaggedMessageToken[],\n renderers: Record<string, unknown>\n): string =>\n tokens\n .map((token) => {\n if (typeof token === 'string') return token;\n\n const children = renderMarkupTokens(token.children, renderers);\n const renderer = renderers[token.tag];\n\n if (typeof renderer === 'function') {\n return (renderer as MarkupChunkRenderer)(children);\n }\n\n return children;\n })\n .join('');\n\n/**\n * The untyped runtime translator shared by `useTranslations` (React hook) and\n * `createTranslator` (non-React core).\n *\n * Behaviour matches use-intl / next-intl:\n * - namespace `'about'` → keys resolved inside the `about` dictionary\n * - namespace `'about.counter'` → dictionary `about`, key prefix `counter`\n * - no namespace → the first segment of each key is the dictionary key\n * - messages support ICU syntax (plural, select, `#`, formatted arguments)\n * - `t.rich` / `t.markup` map `<tag>chunks</tag>` through the provided\n * renderers; `t.raw` returns the raw value; `t.has` checks existence\n *\n * @param locale - The locale dictionaries are resolved for.\n * @param namespace - Optional dictionary key, optionally with a nested scope.\n * @returns A translate function augmented with `has`, `raw`, `rich`, `markup`.\n */\nexport const createNamespaceTranslator = (\n locale: LocalesValues,\n namespace?: string\n) => {\n const [dictionaryKey, ...prefixSegments] = (namespace ?? '').split('.');\n const keyPrefix = prefixSegments.join('.');\n\n const lookup = (lookupKey: string): unknown =>\n lookupNamespaceKey(locale, dictionaryKey ?? '', keyPrefix, lookupKey);\n\n return createLookupTranslator(locale, lookup, (key) =>\n namespace ? `${namespace}.${key}` : key\n );\n};\n\n/**\n * Key-based lookup used by {@link createNamespaceTranslator}: resolves the\n * dictionary through the runtime registry (`getIntlayer`).\n */\nconst lookupNamespaceKey = (\n locale: LocalesValues,\n dictionaryKey: string,\n keyPrefix: string,\n key: string\n): unknown => {\n let targetDictionaryKey = dictionaryKey;\n let path = keyPrefix ? `${keyPrefix}.${key}` : key;\n\n const dictionaries = getDictionaries();\n\n if (!targetDictionaryKey) {\n // Root scope — the first key segment usually designates the dictionary\n const [firstSegment, ...restSegments] = key.split('.');\n targetDictionaryKey = firstSegment ?? key;\n path = restSegments.join('.');\n\n // If the assumed dictionary doesn't exist, we must fall back to searching all dictionaries.\n // This supports apps migrating from standard next-intl where all messages were grouped together.\n if (!dictionaries[targetDictionaryKey as DictionaryKeys]) {\n for (const dictKey of Object.keys(dictionaries)) {\n try {\n const dictionary = getIntlayer(dictKey as DictionaryKeys, locale);\n const result = navigatePath(dictionary, key);\n if (result !== undefined) {\n return result;\n }\n } catch {\n // Ignore if getIntlayer throws\n }\n }\n }\n }\n\n try {\n const dictionary = getIntlayer(\n targetDictionaryKey as DictionaryKeys,\n locale\n );\n return navigatePath(dictionary, path);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Dictionary-bound translator used by the build-optimized `useDictionary` /\n * `getDictionary` variants: instead of resolving the dictionary by key at\n * runtime, the pre-resolved content is supplied directly (the babel/swc\n * optimize pass imports the dictionary JSON at build time).\n *\n * @param locale - The locale messages are resolved for.\n * @param content - The dictionary content, already resolved for `locale`.\n * @param namespacePrefix - Optional key prefix for nested namespaces\n * (`useTranslations('about.counter')` → content of `about`, prefix `counter`).\n * @returns A translate function augmented with `has`, `raw`, `rich`, `markup`.\n */\nexport const createDictionaryTranslator = (\n locale: LocalesValues,\n content: unknown,\n namespacePrefix?: string\n) => {\n const resolveKey = (key: string): string =>\n namespacePrefix ? `${namespacePrefix}.${key}` : key;\n\n return createLookupTranslator(\n locale,\n (key) => navigatePath(content, resolveKey(key)),\n resolveKey\n );\n};\n\n/**\n * The untyped runtime translator core shared by every factory above:\n * ICU message resolution plus the `has` / `raw` / `rich` / `markup` helpers.\n *\n * @param locale - The locale messages are resolved for.\n * @param lookup - Reads the raw content value for a message key.\n * @param missingKeyFallback - Builds the echoed key on lookup miss\n * (use-intl convention: `namespace.key`).\n */\nconst createLookupTranslator = (\n locale: LocalesValues,\n lookup: (key: string) => unknown,\n missingKeyFallback: (key: string) => string\n) => {\n const resolveToString = (\n key: string,\n values: MessageValues = {}\n ): string | undefined => {\n const rawValue = lookup(key);\n if (rawValue === null || rawValue === undefined) return undefined;\n return resolveMessage(rawValue, values, locale, 'icu');\n };\n\n const translate = (key: string, values?: MessageValues): string =>\n resolveToString(key, values) ?? missingKeyFallback(key);\n\n return Object.assign(translate, {\n /** Returns `true` if the given key exists in the namespace. */\n has: (key: string): boolean => lookup(key) !== undefined,\n\n /** Returns the raw unprocessed content for the given key. */\n raw: (key: string): unknown => lookup(key),\n\n /**\n * Resolves a message containing `<tag>chunks</tag>` markup, mapping each\n * tag through the matching renderer in `values`.\n */\n rich: (key: string, values?: Record<string, unknown>): ReactNode => {\n const { scalarValues, renderers } = splitRichValues(values);\n const message = resolveToString(key, scalarValues);\n if (message === undefined) return missingKeyFallback(key);\n return <>{renderRichTokens(parseTaggedMessage(message), renderers)}</>;\n },\n\n /**\n * Resolves a message containing `<tag>chunks</tag>` markup into a string,\n * mapping each tag through the matching string renderer in `values`.\n */\n markup: (key: string, values?: Record<string, unknown>): string => {\n const { scalarValues, renderers } = splitRichValues(values);\n const message = resolveToString(key, scalarValues);\n if (message === undefined) return missingKeyFallback(key);\n return renderMarkupTokens(parseTaggedMessage(message), renderers);\n },\n });\n};\n\nexport type CompatTranslator = ReturnType<typeof createNamespaceTranslator>;\n"],"mappings":";;;;;;;;AAwBA,MAAM,mBACJ,SAAkC,CAAC,MACqC;CACxE,MAAM,eAA8B,CAAC;CACrC,MAAM,YAAqC,CAAC;CAE5C,KAAK,MAAM,CAAC,UAAU,UAAU,OAAO,QAAQ,MAAM,GACnD,IAAI,OAAO,UAAU,YAAY,UAAU,YAAY;MAClD,aAAa,YAAY;CAGhC,OAAO;EAAE;EAAc;CAAU;AACnC;AAEA,MAAM,oBACJ,QACA,cAEA,OAAO,KAAK,OAAO,eAAe;CAChC,IAAI,OAAO,UAAU,UAAU,OAAO;CAEtC,MAAM,WAAW,iBAAiB,MAAM,UAAU,SAAS;CAC3D,MAAM,WAAW,UAAU,MAAM;CAEjC,IAAI,OAAO,aAAa,YACtB,OACE,oBAAC,UAAD,YACI,SAA+B,QAAQ,EACjC,GAFK,UAEL;CAKd,OAAO,oBAAC,UAAD,EAA4B,SAAmB,GAAhC,UAAgC;AACxD,CAAC;AAEH,MAAM,sBACJ,QACA,cAEA,OACG,KAAK,UAAU;CACd,IAAI,OAAO,UAAU,UAAU,OAAO;CAEtC,MAAM,WAAW,mBAAmB,MAAM,UAAU,SAAS;CAC7D,MAAM,WAAW,UAAU,MAAM;CAEjC,IAAI,OAAO,aAAa,YACtB,OAAQ,SAAiC,QAAQ;CAGnD,OAAO;AACT,CAAC,CAAC,CACD,KAAK,EAAE;;;;;;;;;;;;;;;;;AAkBZ,MAAa,6BACX,QACA,cACG;CACH,MAAM,CAAC,eAAe,GAAG,mBAAmB,aAAa,GAAE,CAAE,MAAM,GAAG;CACtE,MAAM,YAAY,eAAe,KAAK,GAAG;CAEzC,MAAM,UAAU,cACd,mBAAmB,QAAQ,iBAAiB,IAAI,WAAW,SAAS;CAEtE,OAAO,uBAAuB,QAAQ,SAAS,QAC7C,YAAY,GAAG,UAAU,GAAG,QAAQ,GACtC;AACF;;;;;AAMA,MAAM,sBACJ,QACA,eACA,WACA,QACY;CACZ,IAAI,sBAAsB;CAC1B,IAAI,OAAO,YAAY,GAAG,UAAU,GAAG,QAAQ;CAE/C,MAAM,eAAe,gBAAgB;CAErC,IAAI,CAAC,qBAAqB;EAExB,MAAM,CAAC,cAAc,GAAG,gBAAgB,IAAI,MAAM,GAAG;EACrD,sBAAsB,gBAAgB;EACtC,OAAO,aAAa,KAAK,GAAG;EAI5B,IAAI,CAAC,aAAa,sBAChB,KAAK,MAAM,WAAW,OAAO,KAAK,YAAY,GAC5C,IAAI;GAEF,MAAM,SAASA,eADI,YAAY,SAA2B,MACrB,GAAG,GAAG;GAC3C,IAAI,WAAW,QACb,OAAO;EAEX,QAAQ,CAER;CAGN;CAEA,IAAI;EAKF,OAAOA,eAJY,YACjB,qBACA,MAE2B,GAAG,IAAI;CACtC,QAAQ;EACN;CACF;AACF;;;;;;;;;;;;;AAcA,MAAa,8BACX,QACA,SACA,oBACG;CACH,MAAM,cAAc,QAClB,kBAAkB,GAAG,gBAAgB,GAAG,QAAQ;CAElD,OAAO,uBACL,SACC,QAAQA,eAAa,SAAS,WAAW,GAAG,CAAC,GAC9C,UACF;AACF;;;;;;;;;;AAWA,MAAM,0BACJ,QACA,QACA,uBACG;CACH,MAAM,mBACJ,KACA,SAAwB,CAAC,MACF;EACvB,MAAM,WAAW,OAAO,GAAG;EAC3B,IAAI,aAAa,QAAQ,aAAa,QAAW,OAAO;EACxD,OAAO,eAAe,UAAU,QAAQ,QAAQ,KAAK;CACvD;CAEA,MAAM,aAAa,KAAa,WAC9B,gBAAgB,KAAK,MAAM,KAAK,mBAAmB,GAAG;CAExD,OAAO,OAAO,OAAO,WAAW;;EAE9B,MAAM,QAAyB,OAAO,GAAG,MAAM;;EAG/C,MAAM,QAAyB,OAAO,GAAG;;;;;EAMzC,OAAO,KAAa,WAAgD;GAClE,MAAM,EAAE,cAAc,cAAc,gBAAgB,MAAM;GAC1D,MAAM,UAAU,gBAAgB,KAAK,YAAY;GACjD,IAAI,YAAY,QAAW,OAAO,mBAAmB,GAAG;GACxD,OAAO,4CAAG,iBAAiB,mBAAmB,OAAO,GAAG,SAAS,EAAI;EACvE;;;;;EAMA,SAAS,KAAa,WAA6C;GACjE,MAAM,EAAE,cAAc,cAAc,gBAAgB,MAAM;GAC1D,MAAM,UAAU,gBAAgB,KAAK,YAAY;GACjD,IAAI,YAAY,QAAW,OAAO,mBAAmB,GAAG;GACxD,OAAO,mBAAmB,mBAAmB,OAAO,GAAG,SAAS;EAClE;CACF,CAAC;AACH"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { createDictionaryTranslator } from "./shared/namespaceTranslator.mjs";
|
|
4
|
+
import { useContext } from "react";
|
|
5
|
+
import { IntlayerClientContext, useDictionary as useDictionary$1 } from "react-intlayer";
|
|
5
6
|
|
|
6
7
|
//#region src/useDictionary.ts
|
|
7
8
|
/**
|
|
@@ -12,23 +13,17 @@ import { useDictionary as useDictionary$1 } from "react-intlayer";
|
|
|
12
13
|
* JSON at build time and passes it directly here. This enables tree-shaking of
|
|
13
14
|
* unused locale content.
|
|
14
15
|
*
|
|
16
|
+
* The returned translator matches `useTranslations` exactly (ICU messages,
|
|
17
|
+
* `has`, `raw`, `rich`, `markup`).
|
|
18
|
+
*
|
|
15
19
|
* @example (generated by the plugin, not written manually)
|
|
16
20
|
* import _abc from '.intlayer/dictionaries/about.json' with { type: 'json' };
|
|
17
21
|
* const t = useDictionary(_abc);
|
|
18
22
|
*/
|
|
19
|
-
const useDictionary = (dictionary, namespacePrefix) => {
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const rawValue = navigatePath(content, resolveKey(String(lookup)));
|
|
24
|
-
const text = String(rawValue ?? resolveKey(String(lookup)));
|
|
25
|
-
if (!params) return text;
|
|
26
|
-
return text.replace(/\{(\w+)\}/g, (_match, key) => params[key] != null ? String(params[key]) : `{${key}}`);
|
|
27
|
-
}, {
|
|
28
|
-
has: (lookup) => navigatePath(content, resolveKey(String(lookup))) != null,
|
|
29
|
-
raw: (lookup) => navigatePath(content, resolveKey(String(lookup)))
|
|
30
|
-
});
|
|
31
|
-
};
|
|
23
|
+
const useDictionary = ((dictionary, namespacePrefix) => {
|
|
24
|
+
const { locale } = useContext(IntlayerClientContext) ?? {};
|
|
25
|
+
return createDictionaryTranslator(locale, useDictionary$1(dictionary), namespacePrefix);
|
|
26
|
+
});
|
|
32
27
|
|
|
33
28
|
//#endregion
|
|
34
29
|
export { useDictionary };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDictionary.mjs","names":["useDictionaryBase"],"sources":["../../src/useDictionary.ts"],"sourcesContent":["'use client';\n\nimport type {
|
|
1
|
+
{"version":3,"file":"useDictionary.mjs","names":["useDictionaryBase"],"sources":["../../src/useDictionary.ts"],"sourcesContent":["'use client';\n\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport { useContext } from 'react';\nimport {\n IntlayerClientContext,\n useDictionary as useDictionaryBase,\n} from 'react-intlayer';\nimport { createDictionaryTranslator } from './shared/namespaceTranslator';\nimport type {\n ScopedTranslateFunction,\n TranslateFunction,\n} from './shared/translateFunctionTypes';\n\n/**\n * Overload set for {@link useDictionary}: without a prefix the translator is\n * typed against the dictionary's dot-paths; with a prefix the keys are\n * relative dot-paths under that scope.\n */\ntype UseDictionary = {\n <T extends Dictionary>(\n dictionary: T\n ): TranslateFunction<T['key'] & DictionaryKeys>;\n <T extends Dictionary, Prefix extends string>(\n dictionary: T,\n namespacePrefix: Prefix\n ): ScopedTranslateFunction<T['key'] & DictionaryKeys, Prefix>;\n};\n\n/**\n * Dictionary-accepting variant of `useTranslations`.\n *\n * Used internally by the build-time optimization: instead of looking up the\n * dictionary at runtime by key, the babel/swc plugin pre-imports the dictionary\n * JSON at build time and passes it directly here. This enables tree-shaking of\n * unused locale content.\n *\n * The returned translator matches `useTranslations` exactly (ICU messages,\n * `has`, `raw`, `rich`, `markup`).\n *\n * @example (generated by the plugin, not written manually)\n * import _abc from '.intlayer/dictionaries/about.json' with { type: 'json' };\n * const t = useDictionary(_abc);\n */\nexport const useDictionary = (<T extends Dictionary>(\n dictionary: T,\n namespacePrefix?: string\n) => {\n const { locale } = useContext(IntlayerClientContext) ?? {};\n const content = useDictionaryBase(dictionary);\n\n return createDictionaryTranslator(\n locale as LocalesValues,\n content,\n namespacePrefix\n );\n}) as UseDictionary;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgDA,MAAa,kBACX,YACA,oBACG;CACH,MAAM,EAAE,WAAW,WAAW,qBAAqB,KAAK,CAAC;CAGzD,OAAO,2BACL,QAHcA,gBAAkB,UAI1B,GACN,eACF;AACF"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { createDictionaryTranslator } from "./shared/namespaceTranslator.mjs";
|
|
4
|
+
import { useContext } from "react";
|
|
5
|
+
import { IntlayerClientContext, useDictionaryDynamic as useDictionaryDynamic$1 } from "react-intlayer";
|
|
5
6
|
|
|
6
7
|
//#region src/useDictionaryDynamic.ts
|
|
7
8
|
/**
|
|
@@ -10,19 +11,10 @@ import { useDictionaryDynamic as useDictionaryDynamic$1 } from "react-intlayer";
|
|
|
10
11
|
* Counterpart to {@link useDictionary} for dictionaries imported lazily per
|
|
11
12
|
* locale. Used internally by the build-time optimization.
|
|
12
13
|
*/
|
|
13
|
-
const useDictionaryDynamic = (dictionaryPromise, key, namespacePrefix) => {
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const rawValue = navigatePath(content, resolveKey(String(lookup)));
|
|
18
|
-
const text = String(rawValue ?? resolveKey(String(lookup)));
|
|
19
|
-
if (!params) return text;
|
|
20
|
-
return text.replace(/\{(\w+)\}/g, (_match, key) => params[key] != null ? String(params[key]) : `{${key}}`);
|
|
21
|
-
}, {
|
|
22
|
-
has: (lookup) => navigatePath(content, resolveKey(String(lookup))) != null,
|
|
23
|
-
raw: (lookup) => navigatePath(content, resolveKey(String(lookup)))
|
|
24
|
-
});
|
|
25
|
-
};
|
|
14
|
+
const useDictionaryDynamic = ((dictionaryPromise, key, namespacePrefix) => {
|
|
15
|
+
const { locale } = useContext(IntlayerClientContext) ?? {};
|
|
16
|
+
return createDictionaryTranslator(locale, useDictionaryDynamic$1(dictionaryPromise, key), namespacePrefix);
|
|
17
|
+
});
|
|
26
18
|
|
|
27
19
|
//#endregion
|
|
28
20
|
export { useDictionaryDynamic };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDictionaryDynamic.mjs","names":["useDictionaryDynamicBase"],"sources":["../../src/useDictionaryDynamic.ts"],"sourcesContent":["'use client';\n\nimport type {
|
|
1
|
+
{"version":3,"file":"useDictionaryDynamic.mjs","names":["useDictionaryDynamicBase"],"sources":["../../src/useDictionaryDynamic.ts"],"sourcesContent":["'use client';\n\nimport type { Dictionary } from '@intlayer/types/dictionary';\nimport type {\n DictionaryKeys,\n LocalesValues,\n StrictModeLocaleMap,\n} from '@intlayer/types/module_augmentation';\nimport { useContext } from 'react';\nimport {\n IntlayerClientContext,\n useDictionaryDynamic as useDictionaryDynamicBase,\n} from 'react-intlayer';\nimport { createDictionaryTranslator } from './shared/namespaceTranslator';\nimport type {\n ScopedTranslateFunction,\n TranslateFunction,\n} from './shared/translateFunctionTypes';\n\n/**\n * Overload set for {@link useDictionaryDynamic}: without a prefix the\n * translator is typed against the dictionary's dot-paths; with a prefix the\n * keys are relative dot-paths under that scope.\n */\ntype UseDictionaryDynamic = {\n <T extends Dictionary, K extends DictionaryKeys>(\n dictionaryPromise: StrictModeLocaleMap<() => Promise<T>>,\n key: K\n ): TranslateFunction<K>;\n <T extends Dictionary, K extends DictionaryKeys, Prefix extends string>(\n dictionaryPromise: StrictModeLocaleMap<() => Promise<T>>,\n key: K,\n namespacePrefix: Prefix\n ): ScopedTranslateFunction<K, Prefix>;\n};\n\n/**\n * Dynamic dictionary-accepting variant of `useTranslations`.\n *\n * Counterpart to {@link useDictionary} for dictionaries imported lazily per\n * locale. Used internally by the build-time optimization.\n */\nexport const useDictionaryDynamic = (<\n const T extends Dictionary,\n const K extends DictionaryKeys,\n>(\n dictionaryPromise: StrictModeLocaleMap<() => Promise<T>>,\n key: K,\n namespacePrefix?: string\n) => {\n const { locale } = useContext(IntlayerClientContext) ?? {};\n const content = useDictionaryDynamicBase<T, K>(dictionaryPromise, key);\n\n return createDictionaryTranslator(\n locale as LocalesValues,\n content,\n namespacePrefix\n );\n}) as UseDictionaryDynamic;\n"],"mappings":";;;;;;;;;;;;;AA0CA,MAAa,yBAIX,mBACA,KACA,oBACG;CACH,MAAM,EAAE,WAAW,WAAW,qBAAqB,KAAK,CAAC;CAGzD,OAAO,2BACL,QAHcA,uBAA+B,mBAAmB,GAI1D,GACN,eACF;AACF"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { LocalesValues } from "@intlayer/types/module_augmentation";
|
|
2
2
|
import { ComponentProps } from "react";
|
|
3
3
|
import { IntlProvider as IntlProvider$1 } from "use-intl";
|
|
4
|
-
|
|
5
4
|
//#region src/client/IntlProvider.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* Drop-in for use-intl's `IntlProvider`.
|
|
@@ -21,7 +20,8 @@ type IntlProviderProps = Omit<ComponentProps<typeof IntlProvider$1>, 'messages'
|
|
|
21
20
|
* @deprecated has no use case with intlayer. Messages are loaded
|
|
22
21
|
* automatically under the hood for bundle optimization reason.
|
|
23
22
|
*/
|
|
24
|
-
messages?: never;
|
|
23
|
+
messages?: never;
|
|
24
|
+
/** The active locale. */
|
|
25
25
|
locale: LocalesValues;
|
|
26
26
|
};
|
|
27
27
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IntlProvider.d.ts","names":[],"sources":["../../../src/client/IntlProvider.tsx"],"mappings":"
|
|
1
|
+
{"version":3,"file":"IntlProvider.d.ts","names":[],"sources":["../../../src/client/IntlProvider.tsx"],"mappings":";;;;;;;;;;;;cAkBa,qBAAqB;;;;;KAiCtB,oBAAoB,KAC9B,sBAAsB;;;;;EAOtB;;EAEA,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.ts","names":[],"sources":["../../../src/client/helpers.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","names":[],"sources":["../../../src/client/helpers.ts"],"mappings":";;;;;;cAkBa,eAAe;;;;;cAMf,oBAAoB;;;;;;;;cAUpB,oBAAoB;;;;;;;cAiBpB,qBAAqB"}
|
|
@@ -4,7 +4,6 @@ import { useDictionary } from "../useDictionary.js";
|
|
|
4
4
|
import { useDictionaryDynamic } from "../useDictionaryDynamic.js";
|
|
5
5
|
import { useLocale } from "./useLocale.js";
|
|
6
6
|
import { useTranslations } from "./useTranslations.js";
|
|
7
|
-
|
|
8
7
|
//#region src/client/index.d.ts
|
|
9
8
|
/**
|
|
10
9
|
* @internal Private use-intl export, kept so aliased `_useExtracted` imports
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/client/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/client/index.ts"],"mappings":";;;;;;;;;;;cAWa,qBAAoB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocale.d.ts","names":[],"sources":["../../../src/client/useLocale.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useLocale.d.ts","names":[],"sources":["../../../src/client/useLocale.ts"],"mappings":";;;;;;;cAUa,kBAAkB"}
|
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import { LooseTranslateFunction, TranslateFunction } from "../shared/translateFunctionTypes.js";
|
|
1
|
+
import { LooseTranslateFunction, TranslateFunction, TranslateFunctionForNamespace } from "../shared/translateFunctionTypes.js";
|
|
2
2
|
import { DictionaryKeys } from "@intlayer/types/module_augmentation";
|
|
3
|
-
|
|
4
3
|
//#region src/client/useTranslations.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Overload set for {@link useTranslations}:
|
|
7
6
|
*
|
|
8
7
|
* 1. A bare dictionary key → fully-typed `t()` (autocompleted dot-paths).
|
|
9
8
|
* 2. A nested namespace `'dictionary.sub.scope'` → `t()` accepts relative
|
|
10
|
-
*
|
|
9
|
+
* dot-paths under the scope, typed against the dictionary, matching
|
|
10
|
+
* use-intl's scoped-namespace behaviour.
|
|
11
11
|
* 3. No namespace → root scope; the first segment of each key designates
|
|
12
12
|
* the dictionary (`t('about.title')`).
|
|
13
13
|
*/
|
|
14
14
|
type UseTranslations = {
|
|
15
15
|
<N extends DictionaryKeys>(namespace: N): TranslateFunction<N>;
|
|
16
|
-
|
|
16
|
+
<N extends `${string}.${string}`>(namespace: N): TranslateFunctionForNamespace<N>;
|
|
17
17
|
(): LooseTranslateFunction;
|
|
18
18
|
};
|
|
19
19
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useTranslations.d.ts","names":[],"sources":["../../../src/client/useTranslations.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useTranslations.d.ts","names":[],"sources":["../../../src/client/useTranslations.ts"],"mappings":";;;;;;;;;;;;;KAyBK;GACF,UAAU,gBAAgB,WAAW,IAAI,kBAAkB;GAC3D,iCACC,WAAW,IACV,8BAA8B;MAC7B;;;;;;;;;;;;;;;;;;;;;;;;cAyBO,iBAOP"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createFormatter.d.ts","names":[],"sources":["../../../src/core/createFormatter.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"createFormatter.d.ts","names":[],"sources":["../../../src/core/createFormatter.ts"],"mappings":";;;;;;;;;;;;;;;;cAiBa,wBAAwB"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { LooseTranslateFunction, TranslateFunction } from "../shared/translateFunctionTypes.js";
|
|
1
|
+
import { LooseTranslateFunction, TranslateFunction, TranslateFunctionForNamespace } from "../shared/translateFunctionTypes.js";
|
|
2
2
|
import { DictionaryKeys, LocalesValues } from "@intlayer/types/module_augmentation";
|
|
3
|
-
|
|
4
3
|
//#region src/core/createTranslator.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Configuration accepted by {@link createTranslator}.
|
|
@@ -10,7 +9,9 @@ import { DictionaryKeys, LocalesValues } from "@intlayer/types/module_augmentati
|
|
|
10
9
|
* resolves content from its own compiled dictionaries.
|
|
11
10
|
*/
|
|
12
11
|
type CreateTranslatorConfig<N extends DictionaryKeys> = {
|
|
13
|
-
/** The locale dictionaries are resolved for. */
|
|
12
|
+
/** The locale dictionaries are resolved for. */
|
|
13
|
+
locale: LocalesValues;
|
|
14
|
+
/** A bare dictionary key, or a nested `'dictionary.scope'` namespace. */
|
|
14
15
|
namespace?: N | (string & {});
|
|
15
16
|
/**
|
|
16
17
|
* @deprecated has no use case with intlayer. Messages are loaded
|
|
@@ -23,7 +24,8 @@ type CreateTranslatorConfig<N extends DictionaryKeys> = {
|
|
|
23
24
|
*
|
|
24
25
|
* 1. A bare dictionary key → fully-typed `t()` (autocompleted dot-paths).
|
|
25
26
|
* 2. A nested namespace `'dictionary.sub.scope'` → `t()` accepts relative
|
|
26
|
-
*
|
|
27
|
+
* dot-paths under the scope, typed against the dictionary, matching
|
|
28
|
+
* use-intl's scoped-namespace behaviour.
|
|
27
29
|
* 3. No namespace → root scope; the first segment of each key designates
|
|
28
30
|
* the dictionary (`t('about.title')`).
|
|
29
31
|
*/
|
|
@@ -31,9 +33,9 @@ type CreateTranslator = {
|
|
|
31
33
|
<N extends DictionaryKeys>(config: CreateTranslatorConfig<N> & {
|
|
32
34
|
namespace: N;
|
|
33
35
|
}): TranslateFunction<N>;
|
|
34
|
-
(config: CreateTranslatorConfig<DictionaryKeys> & {
|
|
35
|
-
namespace:
|
|
36
|
-
}):
|
|
36
|
+
<N extends `${string}.${string}`>(config: CreateTranslatorConfig<DictionaryKeys> & {
|
|
37
|
+
namespace: N;
|
|
38
|
+
}): TranslateFunctionForNamespace<N>;
|
|
37
39
|
(config: CreateTranslatorConfig<DictionaryKeys>): LooseTranslateFunction;
|
|
38
40
|
};
|
|
39
41
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createTranslator.d.ts","names":[],"sources":["../../../src/core/createTranslator.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"createTranslator.d.ts","names":[],"sources":["../../../src/core/createTranslator.ts"],"mappings":";;;;;;;;;;KAqBY,uBAAuB,UAAU;;EAE3C,QAAQ;;EAER,YAAY;;;;;EAKZ;IACE;;;;;;;;;;;KAYC;GACF,UAAU,gBACT,QAAQ,uBAAuB;IAAO,WAAW;MAChD,kBAAkB;GACpB,iCACC,QAAQ,uBAAuB;IAAoB,WAAW;MAC7D,8BAA8B;GAChC,QAAQ,uBAAuB,kBAAkB;;;;;;;;;;;;;;;;cAiBvC,kBAaP"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","names":[],"sources":["../../../src/core/errors.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"errors.d.ts","names":[],"sources":["../../../src/core/errors.ts"],"mappings":";;;;;;;;aAOY;EACV;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;cASW,kBAAkB;WACb,MAAM;WACN;EAEhB,YAAY,MAAM,eAAe"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hasLocale.d.ts","names":[],"sources":["../../../src/core/hasLocale.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"hasLocale.d.ts","names":[],"sources":["../../../src/core/hasLocale.ts"],"mappings":";;;;;;;;;;;;;cAca,kBAAkB"}
|
|
@@ -4,4 +4,4 @@ import { IntlError, IntlErrorCode } from "./errors.js";
|
|
|
4
4
|
import { hasLocale } from "./hasLocale.js";
|
|
5
5
|
import { initializeConfig } from "./initializeConfig.js";
|
|
6
6
|
import { AbstractIntlMessages, AppConfig, DateTimeFormatOptions, Formats, ICUArgs, ICUTags, IntlConfig, Locale, MarkupTagsFunction, MarkupTranslationValues, MessageKeys, Messages, NamespaceKeys, NestedKeyOf, NestedValueOf, NumberFormatOptions, RelativeTimeFormatOptions, RichTagsFunction, RichTranslationValues, Timezone, TranslationValues } from "./types.js";
|
|
7
|
-
export { AbstractIntlMessages, AppConfig, type CreateTranslatorConfig, DateTimeFormatOptions, Formats, ICUArgs, ICUTags, IntlConfig, IntlError, IntlErrorCode, Locale, MarkupTagsFunction, MarkupTranslationValues, MessageKeys, Messages, NamespaceKeys, NestedKeyOf, NestedValueOf, NumberFormatOptions, RelativeTimeFormatOptions, RichTagsFunction, RichTranslationValues, Timezone, TranslationValues, createFormatter, createTranslator, hasLocale, initializeConfig };
|
|
7
|
+
export { type AbstractIntlMessages, type AppConfig, type CreateTranslatorConfig, type DateTimeFormatOptions, type Formats, type ICUArgs, type ICUTags, type IntlConfig, IntlError, IntlErrorCode, type Locale, type MarkupTagsFunction, type MarkupTranslationValues, type MessageKeys, type Messages, type NamespaceKeys, type NestedKeyOf, type NestedValueOf, type NumberFormatOptions, type RelativeTimeFormatOptions, type RichTagsFunction, type RichTranslationValues, type Timezone, type TranslationValues, createFormatter, createTranslator, hasLocale, initializeConfig };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initializeConfig.d.ts","names":[],"sources":["../../../src/core/initializeConfig.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"initializeConfig.d.ts","names":[],"sources":["../../../src/core/initializeConfig.ts"],"mappings":";;;;;;;;;cASa,yBAAyB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import { AbstractIntlMessages, AppConfig, DateTimeFormatOptions, Formats, ICUArgs, ICUTags, IntlConfig, Locale, MarkupTagsFunction, MarkupTranslationValues, MessageKeys, Messages, NamespaceKeys, NestedKeyOf, NestedValueOf, NumberFormatOptions, RelativeTimeFormatOptions, RichTagsFunction, RichTranslationValues, Timezone, TranslationValues } from "use-intl";
|
|
2
|
-
export {
|
|
2
|
+
export type { AbstractIntlMessages, AppConfig, DateTimeFormatOptions, Formats, ICUArgs, ICUTags, IntlConfig, Locale, MarkupTagsFunction, MarkupTranslationValues, MessageKeys, Messages, NamespaceKeys, NestedKeyOf, NestedValueOf, NumberFormatOptions, RelativeTimeFormatOptions, RichTagsFunction, RichTranslationValues, Timezone, TranslationValues };
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { IntlProvider, IntlProviderProps } from "./client/IntlProvider.js";
|
|
2
2
|
import { useFormatter, useMessages, useNow, useTimeZone } from "./client/helpers.js";
|
|
3
|
+
import { MarkupChunkRenderer, RichChunkRenderer, createDictionaryTranslator } from "./shared/namespaceTranslator.js";
|
|
4
|
+
import { ContentAtPath, LooseTranslateFunction, ScopedDotPaths, ScopedTranslateFunction, TranslateFunction, TranslateFunctionForNamespace, TranslatedValue } from "./shared/translateFunctionTypes.js";
|
|
3
5
|
import { useDictionary } from "./useDictionary.js";
|
|
4
6
|
import { useDictionaryDynamic } from "./useDictionaryDynamic.js";
|
|
5
7
|
import { useLocale } from "./client/useLocale.js";
|
|
6
|
-
import { MarkupChunkRenderer, RichChunkRenderer } from "./shared/namespaceTranslator.js";
|
|
7
|
-
import { LooseTranslateFunction, TranslateFunction } from "./shared/translateFunctionTypes.js";
|
|
8
8
|
import { useTranslations } from "./client/useTranslations.js";
|
|
9
9
|
import { _useExtracted } from "./client/index.js";
|
|
10
10
|
import { createFormatter } from "./core/createFormatter.js";
|
|
@@ -13,4 +13,5 @@ import { IntlError, IntlErrorCode } from "./core/errors.js";
|
|
|
13
13
|
import { hasLocale } from "./core/hasLocale.js";
|
|
14
14
|
import { initializeConfig } from "./core/initializeConfig.js";
|
|
15
15
|
import { AbstractIntlMessages, AppConfig, DateTimeFormatOptions, Formats, ICUArgs, ICUTags, IntlConfig, Locale, MarkupTagsFunction, MarkupTranslationValues, MessageKeys, Messages, NamespaceKeys, NestedKeyOf, NestedValueOf, NumberFormatOptions, RelativeTimeFormatOptions, RichTagsFunction, RichTranslationValues, Timezone, TranslationValues } from "./core/types.js";
|
|
16
|
-
|
|
16
|
+
import "./core/index.js";
|
|
17
|
+
export { type AbstractIntlMessages, type AppConfig, type ContentAtPath, type CreateTranslatorConfig, type DateTimeFormatOptions, type Formats, type ICUArgs, type ICUTags, type IntlConfig, IntlError, IntlErrorCode, IntlProvider, type IntlProviderProps, type Locale, type LooseTranslateFunction, type MarkupChunkRenderer, type MarkupTagsFunction, type MarkupTranslationValues, type MessageKeys, type Messages, type NamespaceKeys, type NestedKeyOf, type NestedValueOf, type NumberFormatOptions, type RelativeTimeFormatOptions, type RichChunkRenderer, type RichTagsFunction, type RichTranslationValues, type ScopedDotPaths, type ScopedTranslateFunction, type Timezone, type TranslateFunction, type TranslateFunctionForNamespace, type TranslatedValue, type TranslationValues, _useExtracted, createDictionaryTranslator, createFormatter, createTranslator, hasLocale, initializeConfig, useDictionary, useDictionaryDynamic, useFormatter, useLocale, useMessages, useNow, useTimeZone, useTranslations };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/plugin/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/plugin/index.ts"],"mappings":";;;;;;;;;;;;;;;;;cAuBa,oBAAiB,UAClB,kBAAkB,iBAC3B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intlFormatter.d.ts","names":[],"sources":["../../../src/shared/intlFormatter.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"intlFormatter.d.ts","names":[],"sources":["../../../src/shared/intlFormatter.ts"],"mappings":";;;KAGY,YAAY,kBAAkB;;;;;;;;;;;cA0B7B,qBAAkB,mBAAqB"}
|
|
@@ -1,20 +1,11 @@
|
|
|
1
1
|
import { LocalesValues } from "@intlayer/types/module_augmentation";
|
|
2
2
|
import { ReactNode } from "react";
|
|
3
|
-
import { MessageValues } from "@intlayer/core/messageFormat";
|
|
4
|
-
|
|
3
|
+
import { MessageValues, navigatePath } from "@intlayer/core/messageFormat";
|
|
5
4
|
//#region src/shared/namespaceTranslator.d.ts
|
|
6
5
|
/** Chunk renderer used by `t.rich()` — maps tag children to a React node. */
|
|
7
6
|
type RichChunkRenderer = (chunks: ReactNode) => ReactNode;
|
|
8
7
|
/** Chunk renderer used by `t.markup()` — maps tag children to a string. */
|
|
9
8
|
type MarkupChunkRenderer = (chunks: string) => string;
|
|
10
|
-
/**
|
|
11
|
-
* Reads a dotted `path` (e.g. `counter.label`) out of a nested object value.
|
|
12
|
-
*
|
|
13
|
-
* @param objectValue - The object to read from.
|
|
14
|
-
* @param path - Dot-separated path. An empty path returns `objectValue`.
|
|
15
|
-
* @returns The value found at `path`, or `undefined` when any segment is absent.
|
|
16
|
-
*/
|
|
17
|
-
declare const navigatePath: (objectValue: unknown, path: string) => unknown;
|
|
18
9
|
/**
|
|
19
10
|
* The untyped runtime translator shared by `useTranslations` (React hook) and
|
|
20
11
|
* `createTranslator` (non-React core).
|
|
@@ -32,7 +23,37 @@ declare const navigatePath: (objectValue: unknown, path: string) => unknown;
|
|
|
32
23
|
* @returns A translate function augmented with `has`, `raw`, `rich`, `markup`.
|
|
33
24
|
*/
|
|
34
25
|
declare const createNamespaceTranslator: (locale: LocalesValues, namespace?: string) => ((key: string, values?: MessageValues) => string) & {
|
|
35
|
-
/** Returns `true` if the given key exists in the namespace. */
|
|
26
|
+
/** Returns `true` if the given key exists in the namespace. */
|
|
27
|
+
has: (key: string) => boolean;
|
|
28
|
+
/** Returns the raw unprocessed content for the given key. */
|
|
29
|
+
raw: (key: string) => unknown;
|
|
30
|
+
/**
|
|
31
|
+
* Resolves a message containing `<tag>chunks</tag>` markup, mapping each
|
|
32
|
+
* tag through the matching renderer in `values`.
|
|
33
|
+
*/
|
|
34
|
+
rich: (key: string, values?: Record<string, unknown>) => ReactNode;
|
|
35
|
+
/**
|
|
36
|
+
* Resolves a message containing `<tag>chunks</tag>` markup into a string,
|
|
37
|
+
* mapping each tag through the matching string renderer in `values`.
|
|
38
|
+
*/
|
|
39
|
+
markup: (key: string, values?: Record<string, unknown>) => string;
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Dictionary-bound translator used by the build-optimized `useDictionary` /
|
|
43
|
+
* `getDictionary` variants: instead of resolving the dictionary by key at
|
|
44
|
+
* runtime, the pre-resolved content is supplied directly (the babel/swc
|
|
45
|
+
* optimize pass imports the dictionary JSON at build time).
|
|
46
|
+
*
|
|
47
|
+
* @param locale - The locale messages are resolved for.
|
|
48
|
+
* @param content - The dictionary content, already resolved for `locale`.
|
|
49
|
+
* @param namespacePrefix - Optional key prefix for nested namespaces
|
|
50
|
+
* (`useTranslations('about.counter')` → content of `about`, prefix `counter`).
|
|
51
|
+
* @returns A translate function augmented with `has`, `raw`, `rich`, `markup`.
|
|
52
|
+
*/
|
|
53
|
+
declare const createDictionaryTranslator: (locale: LocalesValues, content: unknown, namespacePrefix?: string) => ((key: string, values?: MessageValues) => string) & {
|
|
54
|
+
/** Returns `true` if the given key exists in the namespace. */
|
|
55
|
+
has: (key: string) => boolean;
|
|
56
|
+
/** Returns the raw unprocessed content for the given key. */
|
|
36
57
|
raw: (key: string) => unknown;
|
|
37
58
|
/**
|
|
38
59
|
* Resolves a message containing `<tag>chunks</tag>` markup, mapping each
|
|
@@ -47,5 +68,5 @@ declare const createNamespaceTranslator: (locale: LocalesValues, namespace?: str
|
|
|
47
68
|
};
|
|
48
69
|
type CompatTranslator = ReturnType<typeof createNamespaceTranslator>;
|
|
49
70
|
//#endregion
|
|
50
|
-
export { CompatTranslator, MarkupChunkRenderer, RichChunkRenderer, createNamespaceTranslator, navigatePath };
|
|
71
|
+
export { CompatTranslator, MarkupChunkRenderer, RichChunkRenderer, createDictionaryTranslator, createNamespaceTranslator, navigatePath };
|
|
51
72
|
//# sourceMappingURL=namespaceTranslator.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"namespaceTranslator.d.ts","names":[],"sources":["../../../src/shared/namespaceTranslator.tsx"],"mappings":"
|
|
1
|
+
{"version":3,"file":"namespaceTranslator.d.ts","names":[],"sources":["../../../src/shared/namespaceTranslator.tsx"],"mappings":";;;;;KAkBY,qBAAqB,QAAQ,cAAc;;KAG3C,uBAAuB;;;;;;;;;;;;;;;;;cA0EtB,4BAAyB,QAC5B,eAAa,yBACH,aAgHY,SAAW;;EAK5B,MAAA;;EAGA,MAAA;;;;;EAMC,OAAA,aAAM,SAAW,4BAA0B;;;;;EAWzC,SAAA,aAAM,SAAW;;;;;;;;;;;;;;cA/DtB,6BAA0B,QAC7B,eAAa,kBACL,+BACQ,aAmCM,SAAW;;EAK5B,MAAA;;EAGA,MAAA;;;;;EAMC,OAAA,aAAM,SAAW,4BAA0B;;;;;EAWzC,SAAA,aAAM,SAAW;;KASvB,mBAAmB,kBAAkB"}
|
|
@@ -1,9 +1,25 @@
|
|
|
1
1
|
import { MarkupChunkRenderer, RichChunkRenderer } from "./namespaceTranslator.js";
|
|
2
2
|
import { DictionaryKeys } from "@intlayer/types/module_augmentation";
|
|
3
3
|
import { ReactNode } from "react";
|
|
4
|
+
import { GetNestingResult } from "@intlayer/core/interpreter";
|
|
4
5
|
import { ValidDotPathsFor } from "@intlayer/core/transpiler";
|
|
5
|
-
|
|
6
6
|
//#region src/shared/translateFunctionTypes.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* The interpreter-resolved content type at dot-path `P` of dictionary `N` —
|
|
9
|
+
* the same type strength as the base `useIntlayer` hook.
|
|
10
|
+
*/
|
|
11
|
+
type ContentAtPath<N extends DictionaryKeys, P> = GetNestingResult<N, P>;
|
|
12
|
+
/**
|
|
13
|
+
* The value returned by `t()` for key `P` of dictionary `N`: string literals
|
|
14
|
+
* declared in the dictionary keep their literal type (matching the strength of
|
|
15
|
+
* `useIntlayer`), every other node resolves to `string` at runtime.
|
|
16
|
+
*/
|
|
17
|
+
type TranslatedValue<N extends DictionaryKeys, P> = ContentAtPath<N, P> extends string ? ContentAtPath<N, P> : string;
|
|
18
|
+
/**
|
|
19
|
+
* The dot-paths of dictionary `D` relative to the nested namespace scope
|
|
20
|
+
* `Prefix` (`useTranslations('about.counter')` → paths under `about.counter`).
|
|
21
|
+
*/
|
|
22
|
+
type ScopedDotPaths<D extends DictionaryKeys, Prefix extends string> = ValidDotPathsFor<D> extends (infer AllPaths) ? AllPaths extends `${Prefix}.${infer RelativePath}` ? RelativePath : never : never;
|
|
7
23
|
/**
|
|
8
24
|
* The translation function returned for a bare dictionary key namespace.
|
|
9
25
|
*
|
|
@@ -15,13 +31,42 @@ import { ValidDotPathsFor } from "@intlayer/core/transpiler";
|
|
|
15
31
|
* - `markup(key, values)` — resolves `<tag>chunks</tag>` markup to a string.
|
|
16
32
|
*/
|
|
17
33
|
type TranslateFunction<N extends DictionaryKeys> = {
|
|
18
|
-
/** Translate a key to a string, with optional ICU interpolation params.
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
34
|
+
/** Translate a key to a string, with optional ICU interpolation params. */
|
|
35
|
+
<P extends ValidDotPathsFor<N>>(key: P, params?: Record<string, unknown>): TranslatedValue<N, P>;
|
|
36
|
+
/** Returns `true` if the given key exists in the namespace. */
|
|
37
|
+
has<P extends ValidDotPathsFor<N>>(key: P): boolean;
|
|
38
|
+
/** Returns the raw unprocessed content for the given key. */
|
|
39
|
+
raw<P extends ValidDotPathsFor<N>>(key: P): ContentAtPath<N, P>;
|
|
40
|
+
/** Resolves rich-text markup, mapping tags through React renderers. */
|
|
41
|
+
rich<P extends ValidDotPathsFor<N>>(key: P, values?: Record<string, RichChunkRenderer | ReactNode>): ReactNode;
|
|
42
|
+
/** Resolves rich-text markup, mapping tags through string renderers. */
|
|
22
43
|
markup<P extends ValidDotPathsFor<N>>(key: P, values?: Record<string, MarkupChunkRenderer | string | number>): string;
|
|
23
44
|
};
|
|
24
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
* The translation function returned for a nested `'dictionary.scope'`
|
|
47
|
+
* namespace: keys are relative dot-paths under the scope, and return types are
|
|
48
|
+
* resolved against the absolute path in the dictionary.
|
|
49
|
+
*/
|
|
50
|
+
type ScopedTranslateFunction<D extends DictionaryKeys, Prefix extends string> = {
|
|
51
|
+
/** Translate a scoped key to a string, with optional ICU interpolation params. */
|
|
52
|
+
<P extends ScopedDotPaths<D, Prefix>>(key: P, params?: Record<string, unknown>): TranslatedValue<D, `${Prefix}.${P}`>;
|
|
53
|
+
/** Returns `true` if the given key exists in the scoped namespace. */
|
|
54
|
+
has<P extends ScopedDotPaths<D, Prefix>>(key: P): boolean;
|
|
55
|
+
/** Returns the raw unprocessed content for the given scoped key. */
|
|
56
|
+
raw<P extends ScopedDotPaths<D, Prefix>>(key: P): ContentAtPath<D, `${Prefix}.${P}`>;
|
|
57
|
+
/** Resolves rich-text markup, mapping tags through React renderers. */
|
|
58
|
+
rich<P extends ScopedDotPaths<D, Prefix>>(key: P, values?: Record<string, RichChunkRenderer | ReactNode>): ReactNode;
|
|
59
|
+
/** Resolves rich-text markup, mapping tags through string renderers. */
|
|
60
|
+
markup<P extends ScopedDotPaths<D, Prefix>>(key: P, values?: Record<string, MarkupChunkRenderer | string | number>): string;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Resolves the translation function type for a namespace argument: a bare
|
|
64
|
+
* dictionary key keeps the fully-typed dot-paths, a nested
|
|
65
|
+
* `'dictionary.scope'` namespace is split at the first dot and typed
|
|
66
|
+
* relative to the scope, anything else falls back to loose typing.
|
|
67
|
+
*/
|
|
68
|
+
type TranslateFunctionForNamespace<N extends string> = N extends DictionaryKeys ? TranslateFunction<N> : N extends `${infer D extends DictionaryKeys & string}.${infer Prefix}` ? ScopedTranslateFunction<D, Prefix> : LooseTranslateFunction;
|
|
69
|
+
/** Loosely-typed function returned for untyped namespaces (root scope). */
|
|
25
70
|
type LooseTranslateFunction = {
|
|
26
71
|
(key: string, params?: Record<string, unknown>): string;
|
|
27
72
|
has(key: string): boolean;
|
|
@@ -30,5 +75,5 @@ type LooseTranslateFunction = {
|
|
|
30
75
|
markup(key: string, values?: Record<string, MarkupChunkRenderer | string | number>): string;
|
|
31
76
|
};
|
|
32
77
|
//#endregion
|
|
33
|
-
export { LooseTranslateFunction, TranslateFunction };
|
|
78
|
+
export { ContentAtPath, LooseTranslateFunction, ScopedDotPaths, ScopedTranslateFunction, TranslateFunction, TranslateFunctionForNamespace, TranslatedValue };
|
|
34
79
|
//# sourceMappingURL=translateFunctionTypes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translateFunctionTypes.d.ts","names":[],"sources":["../../../src/shared/translateFunctionTypes.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"translateFunctionTypes.d.ts","names":[],"sources":["../../../src/shared/translateFunctionTypes.ts"],"mappings":";;;;;;;;;;KAaY,cAAc,UAAU,gBAAgB,KAAK,iBAAiB,GAAG;;;;;;KAOjE,gBAAgB,UAAU,gBAAgB,KACpD,cAAc,GAAG,oBAAoB,cAAc,GAAG;;;;;KAM5C,eAAe,UAAU,gBAAgB,yBACnD,iBAAiB,kBAAiB,YAC9B,oBAAoB,gBAAgB,iBAClC;;;;;;;;;;;KAcI,kBAAkB,UAAU;;GAErC,UAAU,iBAAiB,IAC1B,KAAK,GACL,SAAS,0BACR,gBAAgB,GAAG;;EAEtB,IAAI,UAAU,iBAAiB,IAAI,KAAK;;EAExC,IAAI,UAAU,iBAAiB,IAAI,KAAK,IAAI,cAAc,GAAG;;EAE7D,KAAK,UAAU,iBAAiB,IAC9B,KAAK,GACL,SAAS,eAAe,oBAAoB,aAC3C;;EAEH,OAAO,UAAU,iBAAiB,IAChC,KAAK,GACL,SAAS,eAAe;;;;;;;KAShB,wBACV,UAAU,gBACV;;GAGC,UAAU,eAAe,GAAG,SAC3B,KAAK,GACL,SAAS,0BACR,gBAAgB,MAAM,UAAU;;EAEnC,IAAI,UAAU,eAAe,GAAG,SAAS,KAAK;;EAE9C,IAAI,UAAU,eAAe,GAAG,SAC9B,KAAK,IACJ,cAAc,MAAM,UAAU;;EAEjC,KAAK,UAAU,eAAe,GAAG,SAC/B,KAAK,GACL,SAAS,eAAe,oBAAoB,aAC3C;;EAEH,OAAO,UAAU,eAAe,GAAG,SACjC,KAAK,GACL,SAAS,eAAe;;;;;;;;KAUhB,8BAA8B,oBACxC,UAAU,iBACN,kBAAkB,KAClB,mBAAmB,UAAU,iCAAiC,WAC5D,wBAAwB,GAAG,UAC3B;;KAGI;GACT,aAAa,SAAS;EACvB,IAAI;EACJ,IAAI;EACJ,KACE,aACA,SAAS,eAAe,oBAAoB,aAC3C;EACH,OACE,aACA,SAAS,eAAe"}
|
|
@@ -1,7 +1,16 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ScopedTranslateFunction, TranslateFunction } from "./shared/translateFunctionTypes.js";
|
|
2
|
+
import { DictionaryKeys } from "@intlayer/types/module_augmentation";
|
|
2
3
|
import { Dictionary } from "@intlayer/types/dictionary";
|
|
3
|
-
|
|
4
4
|
//#region src/useDictionary.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Overload set for {@link useDictionary}: without a prefix the translator is
|
|
7
|
+
* typed against the dictionary's dot-paths; with a prefix the keys are
|
|
8
|
+
* relative dot-paths under that scope.
|
|
9
|
+
*/
|
|
10
|
+
type UseDictionary = {
|
|
11
|
+
<T extends Dictionary>(dictionary: T): TranslateFunction<T['key'] & DictionaryKeys>;
|
|
12
|
+
<T extends Dictionary, Prefix extends string>(dictionary: T, namespacePrefix: Prefix): ScopedTranslateFunction<T['key'] & DictionaryKeys, Prefix>;
|
|
13
|
+
};
|
|
5
14
|
/**
|
|
6
15
|
* Dictionary-accepting variant of `useTranslations`.
|
|
7
16
|
*
|
|
@@ -10,14 +19,14 @@ import { Dictionary } from "@intlayer/types/dictionary";
|
|
|
10
19
|
* JSON at build time and passes it directly here. This enables tree-shaking of
|
|
11
20
|
* unused locale content.
|
|
12
21
|
*
|
|
22
|
+
* The returned translator matches `useTranslations` exactly (ICU messages,
|
|
23
|
+
* `has`, `raw`, `rich`, `markup`).
|
|
24
|
+
*
|
|
13
25
|
* @example (generated by the plugin, not written manually)
|
|
14
26
|
* import _abc from '.intlayer/dictionaries/about.json' with { type: 'json' };
|
|
15
27
|
* const t = useDictionary(_abc);
|
|
16
28
|
*/
|
|
17
|
-
declare const useDictionary:
|
|
18
|
-
has: <P extends ValidDotPathsFor<string>>(lookup: P) => boolean;
|
|
19
|
-
raw: <P extends ValidDotPathsFor<string>>(lookup: P) => unknown;
|
|
20
|
-
};
|
|
29
|
+
declare const useDictionary: UseDictionary;
|
|
21
30
|
//#endregion
|
|
22
31
|
export { useDictionary };
|
|
23
32
|
//# sourceMappingURL=useDictionary.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDictionary.d.ts","names":[],"sources":["../../src/useDictionary.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useDictionary.d.ts","names":[],"sources":["../../src/useDictionary.ts"],"mappings":";;;;;;;;;KAuBK;GACF,UAAU,YACT,YAAY,IACX,kBAAkB,WAAW;GAC/B,UAAU,YAAY,uBACrB,YAAY,GACZ,iBAAiB,SAChB,wBAAwB,WAAW,gBAAgB;;;;;;;;;;;;;;;;;cAkB3C,eAYP"}
|
|
@@ -1,18 +1,23 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { ScopedTranslateFunction, TranslateFunction } from "./shared/translateFunctionTypes.js";
|
|
2
|
+
import { DictionaryKeys, StrictModeLocaleMap } from "@intlayer/types/module_augmentation";
|
|
3
3
|
import { Dictionary } from "@intlayer/types/dictionary";
|
|
4
|
-
|
|
5
4
|
//#region src/useDictionaryDynamic.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Overload set for {@link useDictionaryDynamic}: without a prefix the
|
|
7
|
+
* translator is typed against the dictionary's dot-paths; with a prefix the
|
|
8
|
+
* keys are relative dot-paths under that scope.
|
|
9
|
+
*/
|
|
10
|
+
type UseDictionaryDynamic = {
|
|
11
|
+
<T extends Dictionary, K extends DictionaryKeys>(dictionaryPromise: StrictModeLocaleMap<() => Promise<T>>, key: K): TranslateFunction<K>;
|
|
12
|
+
<T extends Dictionary, K extends DictionaryKeys, Prefix extends string>(dictionaryPromise: StrictModeLocaleMap<() => Promise<T>>, key: K, namespacePrefix: Prefix): ScopedTranslateFunction<K, Prefix>;
|
|
13
|
+
};
|
|
6
14
|
/**
|
|
7
15
|
* Dynamic dictionary-accepting variant of `useTranslations`.
|
|
8
16
|
*
|
|
9
17
|
* Counterpart to {@link useDictionary} for dictionaries imported lazily per
|
|
10
18
|
* locale. Used internally by the build-time optimization.
|
|
11
19
|
*/
|
|
12
|
-
declare const useDictionaryDynamic:
|
|
13
|
-
has: <P extends ValidDotPathsFor<string>>(lookup: P) => boolean;
|
|
14
|
-
raw: <P extends ValidDotPathsFor<string>>(lookup: P) => unknown;
|
|
15
|
-
};
|
|
20
|
+
declare const useDictionaryDynamic: UseDictionaryDynamic;
|
|
16
21
|
//#endregion
|
|
17
22
|
export { useDictionaryDynamic };
|
|
18
23
|
//# sourceMappingURL=useDictionaryDynamic.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useDictionaryDynamic.d.ts","names":[],"sources":["../../src/useDictionaryDynamic.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useDictionaryDynamic.d.ts","names":[],"sources":["../../src/useDictionaryDynamic.ts"],"mappings":";;;;;;;;;KAwBK;GACF,UAAU,YAAY,UAAU,gBAC/B,mBAAmB,0BAA0B,QAAQ,KACrD,KAAK,IACJ,kBAAkB;GACpB,UAAU,YAAY,UAAU,gBAAgB,uBAC/C,mBAAmB,0BAA0B,QAAQ,KACrD,KAAK,GACL,iBAAiB,SAChB,wBAAwB,GAAG;;;;;;;;cASnB,sBAgBP"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/use-intl",
|
|
3
|
-
"version": "9.0.0
|
|
3
|
+
"version": "9.0.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "use-intl API adapter for intlayer — useTranslations, useLocale, useFormatter, IntlProvider, createTranslator backed by react-intlayer",
|
|
6
6
|
"keywords": [
|
|
@@ -89,26 +89,26 @@
|
|
|
89
89
|
"typecheck": "tsc --noEmit --project tsconfig.types.json"
|
|
90
90
|
},
|
|
91
91
|
"dependencies": {
|
|
92
|
-
"@intlayer/
|
|
93
|
-
"@intlayer/
|
|
94
|
-
"@intlayer/
|
|
95
|
-
"@intlayer/
|
|
96
|
-
"@intlayer/types": "9.0.0
|
|
97
|
-
"react-intlayer": "9.0.0
|
|
98
|
-
"vite-intlayer": "9.0.0
|
|
92
|
+
"@intlayer/config": "9.0.0",
|
|
93
|
+
"@intlayer/core": "9.0.0",
|
|
94
|
+
"@intlayer/dictionaries-entry": "9.0.0",
|
|
95
|
+
"@intlayer/engine": "9.0.0",
|
|
96
|
+
"@intlayer/types": "9.0.0",
|
|
97
|
+
"react-intlayer": "9.0.0",
|
|
98
|
+
"vite-intlayer": "9.0.0"
|
|
99
99
|
},
|
|
100
100
|
"devDependencies": {
|
|
101
|
-
"@types/node": "
|
|
101
|
+
"@types/node": "26.1.1",
|
|
102
102
|
"@types/react": "19.2.17",
|
|
103
103
|
"@utils/ts-config": "1.0.4",
|
|
104
104
|
"@utils/ts-config-types": "1.0.4",
|
|
105
105
|
"@utils/tsdown-config": "1.0.4",
|
|
106
106
|
"rimraf": "6.1.3",
|
|
107
|
-
"tsdown": "0.
|
|
108
|
-
"typescript": "
|
|
109
|
-
"use-intl": "4.13.
|
|
110
|
-
"vite": "8.1.
|
|
111
|
-
"vitest": "4.1.
|
|
107
|
+
"tsdown": "0.22.13",
|
|
108
|
+
"typescript": "7.0.2",
|
|
109
|
+
"use-intl": "4.13.2",
|
|
110
|
+
"vite": "8.1.5",
|
|
111
|
+
"vitest": "4.1.10"
|
|
112
112
|
},
|
|
113
113
|
"peerDependencies": {
|
|
114
114
|
"react": ">=16.0.0",
|