@fluenti/react 0.3.4 → 0.4.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/trans-core.d.ts.map +1 -1
- package/dist/components-entry.cjs +2 -0
- package/dist/components-entry.cjs.map +1 -0
- package/dist/components-entry.d.ts +12 -0
- package/dist/components-entry.d.ts.map +1 -0
- package/dist/components-entry.js +91 -0
- package/dist/components-entry.js.map +1 -0
- package/dist/context-DVbvrSE8.cjs +2 -0
- package/dist/context-DVbvrSE8.cjs.map +1 -0
- package/dist/context-DVudCV1o.js +7 -0
- package/dist/context-DVudCV1o.js.map +1 -0
- package/dist/create-fluenti.d.ts +12 -8
- package/dist/create-fluenti.d.ts.map +1 -1
- package/dist/{icu-rich-C9wQm3XF.js → icu-rich-ChVWsA7C.js} +7 -2
- package/dist/icu-rich-ChVWsA7C.js.map +1 -0
- package/dist/icu-rich-CotMVC_x.cjs +2 -0
- package/dist/icu-rich-CotMVC_x.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +0 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +137 -296
- package/dist/index.js.map +1 -1
- package/dist/provider.d.ts +41 -0
- package/dist/provider.d.ts.map +1 -1
- package/dist/server.cjs +1 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.ts +18 -3
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +21 -20
- package/dist/server.js.map +1 -1
- package/dist/types.d.ts +5 -0
- package/dist/types.d.ts.map +1 -1
- package/llms-full.txt +2 -1
- package/llms-migration.txt +2 -2
- package/llms.txt +61 -0
- package/package.json +18 -4
- package/dist/icu-rich-C9wQm3XF.js.map +0 -1
- package/dist/icu-rich-DQtv128R.cjs +0 -2
- package/dist/icu-rich-DQtv128R.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trans-core.d.ts","sourceRoot":"","sources":["../../src/components/trans-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,SAAS,EACd,KAAK,YAAY,EAClB,MAAM,OAAO,CAAA;AACd,OAAO,EAAE,WAAW,EAAiB,MAAM,wBAAwB,CAAA;AAEnE,OAAO,EAAE,WAAW,EAAE,CAAA;AAEtB;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS,GAAG;IACnD,OAAO,EAAE,MAAM,CAAA;IACf,UAAU,EAAE,YAAY,EAAE,CAAA;CAC3B,CA4BA;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CACzB,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,YAAY,EAAE,GACzB,SAAS,
|
|
1
|
+
{"version":3,"file":"trans-core.d.ts","sourceRoot":"","sources":["../../src/components/trans-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,SAAS,EACd,KAAK,YAAY,EAClB,MAAM,OAAO,CAAA;AACd,OAAO,EAAE,WAAW,EAAiB,MAAM,wBAAwB,CAAA;AAEnE,OAAO,EAAE,WAAW,EAAE,CAAA;AAEtB;;;;;;;;;;GAUG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,SAAS,GAAG;IACnD,OAAO,EAAE,MAAM,CAAA;IACf,UAAU,EAAE,YAAY,EAAE,CAAA;CAC3B,CA4BA;AAED;;;;;;GAMG;AACH,wBAAgB,WAAW,CACzB,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,YAAY,EAAE,GACzB,SAAS,CAmDX"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./context-DVbvrSE8.cjs`),t=require(`./icu-rich-CotMVC_x.cjs`);let n=require(`react`),r=require(`react/jsx-runtime`),i=require(`@fluenti/core/internal`);var a=(0,n.memo)(function({children:a,id:o,context:s,comment:c,tag:l,render:u,__id:d,__message:f,__components:p}){let m=(0,n.useContext)(e.t);if(!m)throw Error(`[fluenti] <Trans> must be used within an <I18nProvider>`);let h=f!==void 0,{message:g,components:_}=(0,n.useMemo)(()=>h?{message:f,components:p??[]}:t.r(a),[h,f,p,a]),v=(0,n.useMemo)(()=>o??d??(0,i.hashMessage)(g,s),[o,d,g,s]),y=t.i(m.t({id:v,message:g,...s===void 0?{}:{context:s},...c===void 0?{}:{comment:c}}),_);return u?u(y):l?(0,n.createElement)(l,null,y):(0,r.jsx)(r.Fragment,{children:y})}),o=(0,n.memo)(function({value:a,id:o,context:s,comment:c,zero:l,one:u,two:d,few:f,many:p,other:m,offset:h}){let g=(0,n.useContext)(e.t);if(!g)throw Error(`[fluenti] <Plural> must be used within an <I18nProvider>`);let{messages:_,components:v}=t.n(i.PLURAL_CATEGORIES,{zero:l,one:u,two:d,few:f,many:p,other:m}),y=(0,i.buildICUPluralMessage)({..._.zero!==void 0&&{zero:_.zero},..._.one!==void 0&&{one:_.one},..._.two!==void 0&&{two:_.two},..._.few!==void 0&&{few:_.few},..._.many!==void 0&&{many:_.many},other:_.other??``},h);return(0,r.jsx)(r.Fragment,{children:t.t({id:o??(s===void 0?y:(0,i.hashMessage)(y,s)),message:y,...s===void 0?{}:{context:s},...c===void 0?{}:{comment:c}},{count:a},(e,t)=>g.t(e,t),v)})}),s=(0,n.memo)(function(a){let o=(0,n.useContext)(e.t);if(!o)throw Error(`[fluenti] <Select> must be used within an <I18nProvider>`);let{value:s,id:c,context:l,comment:u,other:d,options:f,tag:p,...m}=a,h=f===void 0?{...Object.fromEntries(Object.entries(m).filter(([e])=>![`value`,`id`,`context`,`comment`,`options`,`other`,`tag`].includes(e))),other:d}:{...f,other:d},g=[...Object.keys(h).filter(e=>e!==`other`),`other`],{messages:_,components:v}=t.n(g,h),y=(0,i.normalizeSelectForms)(Object.fromEntries([...g].map(e=>[e,_[e]??``]))),b=(0,i.buildICUSelectMessage)(y.forms),x=t.t({id:c??(l===void 0?b:(0,i.hashMessage)(b,l)),message:b,...l===void 0?{}:{context:l},...u===void 0?{}:{comment:u}},{value:y.valueMap[s]??`other`},(e,t)=>o.t(e,t),v);return p?(0,n.createElement)(p,null,x):(0,r.jsx)(r.Fragment,{children:x})}),c=(0,n.memo)(function({value:t,format:i}){let a=(0,n.useContext)(e.t);if(!a)throw Error(`[fluenti] <DateTime> must be used within an <I18nProvider>`);return(0,r.jsx)(r.Fragment,{children:a.d(t,i)})}),l=(0,n.memo)(function({value:t,format:i}){let a=(0,n.useContext)(e.t);if(!a)throw Error(`[fluenti] <Number> must be used within an <I18nProvider>`);return(0,r.jsx)(r.Fragment,{children:a.n(t,i)})});exports.DateTime=c,exports.NumberFormat=l,exports.Plural=o,exports.Select=s,exports.Trans=a,Object.defineProperty(exports,`interpolate`,{enumerable:!0,get:function(){return i.interpolate}});
|
|
2
|
+
//# sourceMappingURL=components-entry.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"components-entry.cjs","names":[],"sources":["../src/components/Trans.tsx","../src/components/Plural.tsx","../src/components/Select.tsx","../src/components/DateTime.tsx","../src/components/Number.tsx"],"sourcesContent":["import {\n createElement,\n memo,\n useContext,\n useMemo,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport { I18nContext } from '../context'\nimport { hashMessage, extractMessage, reconstruct } from './trans-core'\n\nexport interface FluentiTransProps {\n /** Source text with embedded components */\n children: ReactNode\n /** Override auto-generated hash ID */\n id?: string\n /** Message context used for identity and translator disambiguation */\n context?: string\n /** Context comment for translators */\n comment?: string\n /** Wrapper element tag name (e.g. 'span', 'div'). Defaults to Fragment (no wrapper). */\n tag?: keyof React.JSX.IntrinsicElements\n /** Custom render wrapper */\n render?: (translation: ReactNode) => ReactNode\n /** @internal Pre-computed message ID from build plugin */\n __id?: string\n /** @internal Pre-computed ICU message from build plugin */\n __message?: string\n /** @internal Pre-computed component list from build plugin */\n __components?: ReactElement[]\n}\n\n/**\n * `<Trans>` component for rich-text translations containing nested React elements.\n *\n * @example\n * ```tsx\n * <Trans>Read the <a href=\"/docs\">documentation</a> for more info.</Trans>\n * ```\n */\nexport const Trans = memo(function Trans({\n children,\n id,\n context,\n comment,\n tag,\n render,\n __id,\n __message,\n __components,\n}: FluentiTransProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Trans> must be used within an <I18nProvider>')\n }\n\n // Fast path: build plugin pre-computed message and components\n const hasPrecomputed = __message !== undefined\n\n const { message, components } = useMemo(\n () => hasPrecomputed\n ? { message: __message!, components: __components ?? [] }\n : extractMessage(children),\n [hasPrecomputed, __message, __components, children],\n )\n const messageId = useMemo(\n () => id ?? __id ?? hashMessage(message, context),\n [id, __id, message, context],\n )\n\n const translated = ctx.t(\n {\n id: messageId,\n message,\n ...(context !== undefined ? { context } : {}),\n ...(comment !== undefined ? { comment } : {}),\n },\n )\n\n const result = reconstruct(translated, components)\n if (render) return render(result)\n return tag ? createElement(tag, null, result) : <>{result}</>\n})\n","import { memo, useContext, type ReactNode } from 'react'\nimport { hashMessage } from '@fluenti/core/internal'\nimport { I18nContext } from '../context'\nimport { PLURAL_CATEGORIES, type PluralCategory } from './plural-core'\nimport { buildICUPluralMessage, renderRichTranslation, serializeRichForms } from './icu-rich'\n\nexport interface FluentiPluralProps {\n /** The count value */\n value: number\n /** Override the auto-generated synthetic ICU message id */\n id?: string\n /** Message context used for identity and translator disambiguation */\n context?: string\n /** Translator-facing note preserved in extraction catalogs */\n comment?: string\n /** Text for zero (if language supports) */\n zero?: ReactNode\n /** Singular form. `#` replaced with value */\n one?: ReactNode\n /** Dual form (Arabic, etc.) */\n two?: ReactNode\n /** Few form (Slavic languages, etc.) */\n few?: ReactNode\n /** Many form */\n many?: ReactNode\n /** Default plural form */\n other: ReactNode\n /** Offset from value before selecting form */\n offset?: number\n}\n\n/**\n * `<Plural>` — ICU plural handling as a component.\n *\n * @example\n * ```tsx\n * <Plural value={count} zero=\"No messages\" one=\"# message\" other=\"# messages\" />\n * ```\n */\nexport const Plural = memo(function Plural({\n value,\n id,\n context,\n comment,\n zero,\n one,\n two,\n few,\n many,\n other,\n offset,\n}: FluentiPluralProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Plural> must be used within an <I18nProvider>')\n }\n\n const forms: Record<PluralCategory, ReactNode | undefined> = {\n zero,\n one,\n two,\n few,\n many,\n other,\n }\n const { messages, components } = serializeRichForms(PLURAL_CATEGORIES, forms)\n const icuMessage = buildICUPluralMessage(\n {\n ...(messages.zero !== undefined && { zero: messages.zero }),\n ...(messages.one !== undefined && { one: messages.one }),\n ...(messages.two !== undefined && { two: messages.two }),\n ...(messages.few !== undefined && { few: messages.few }),\n ...(messages.many !== undefined && { many: messages.many }),\n other: messages.other ?? '',\n },\n offset,\n )\n\n const descriptor = {\n id: id ?? (context === undefined ? icuMessage : hashMessage(icuMessage, context)),\n message: icuMessage,\n ...(context !== undefined ? { context } : {}),\n ...(comment !== undefined ? { comment } : {}),\n }\n\n return <>{renderRichTranslation(descriptor, { count: value }, (desc, values) => ctx.t(desc, values), components)}</>\n})\n","import { createElement, memo, useContext, type ReactNode } from 'react'\nimport { hashMessage } from '@fluenti/core/internal'\nimport { I18nContext } from '../context'\nimport { buildICUSelectMessage, normalizeSelectForms, renderRichTranslation, serializeRichForms } from './icu-rich'\n\nexport interface FluentiSelectProps {\n /** The selector value */\n value: string\n /** Override the auto-generated synthetic ICU message id */\n id?: string\n /** Message context used for identity and translator disambiguation */\n context?: string\n /** Translator-facing note preserved in extraction catalogs */\n comment?: string\n /** Default case */\n other: ReactNode\n /** Type-safe named options. Takes precedence over direct case props. */\n options?: Record<string, ReactNode>\n /** Wrapper element tag name (e.g. 'span', 'div'). Defaults to Fragment (no wrapper). */\n tag?: keyof React.JSX.IntrinsicElements\n /** Named cases — any string key maps to a ReactNode */\n [key: string]: ReactNode | Record<string, ReactNode> | keyof React.JSX.IntrinsicElements | undefined\n}\n\n/**\n * `<Select>` — ICU select for gender, role, or other categorical values.\n *\n * @example\n * ```tsx\n * <Select\n * value={gender}\n * male=\"He liked your post\"\n * female=\"She liked your post\"\n * other=\"They liked your post\"\n * />\n * ```\n */\nexport const Select = memo(function Select(props: FluentiSelectProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Select> must be used within an <I18nProvider>')\n }\n\n const { value, id, context, comment, other, options, tag, ...cases } = props\n const forms: Record<string, ReactNode | undefined> = options === undefined\n ? {\n ...Object.fromEntries(\n Object.entries(cases).filter(([key]) => !['value', 'id', 'context', 'comment', 'options', 'other', 'tag'].includes(key)),\n ),\n other,\n }\n : {\n ...options,\n other,\n }\n\n const orderedKeys = [...Object.keys(forms).filter(key => key !== 'other'), 'other'] as const\n const { messages, components } = serializeRichForms(orderedKeys, forms)\n const normalized = normalizeSelectForms(\n Object.fromEntries(\n [...orderedKeys].map((key) => [key, messages[key] ?? '']),\n ),\n )\n const icuMessage = buildICUSelectMessage(normalized.forms)\n\n const descriptor = {\n id: id ?? (context === undefined ? icuMessage : hashMessage(icuMessage, context)),\n message: icuMessage,\n ...(context !== undefined ? { context } : {}),\n ...(comment !== undefined ? { comment } : {}),\n }\n\n const result = renderRichTranslation(\n descriptor,\n { value: normalized.valueMap[value] ?? 'other' },\n (desc, values) => ctx.t(desc, values),\n components,\n )\n return tag ? createElement(tag, null, result) : <>{result}</>\n})\n","import { memo, useContext } from 'react'\nimport { I18nContext } from '../context'\n\nexport interface FluentiDateTimeProps {\n /** Date value to format */\n value: Date | number\n /** Named format key defined in dateFormats config */\n format?: string\n}\n\n/**\n * `<DateTime>` — formatting component using Intl APIs.\n *\n * @example\n * ```tsx\n * <DateTime value={new Date()} format=\"long\" />\n * ```\n */\nexport const DateTime = memo(function DateTime({ value, format }: FluentiDateTimeProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <DateTime> must be used within an <I18nProvider>')\n }\n return <>{ctx.d(value, format)}</>\n})\n","import { memo, useContext } from 'react'\nimport { I18nContext } from '../context'\n\nexport interface NumberFormatProps {\n /** Number value to format */\n value: number\n /** Named format key defined in numberFormats config */\n format?: string\n}\n\n/** @alias NumberFormatProps */\nexport type FluentiNumberFormatProps = NumberFormatProps\n\n/**\n * `<Number>` — number formatting component using Intl APIs.\n *\n * @example\n * ```tsx\n * <Number value={1234.56} format=\"currency\" />\n * ```\n */\nexport const NumberFormat = memo(function NumberFormat({ value, format }: NumberFormatProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Number> must be used within an <I18nProvider>')\n }\n return <>{ctx.n(value, format)}</>\n})\n"],"mappings":"yPAwCA,IAAa,GAAA,EAAA,EAAA,MAAa,SAAe,CACvC,WACA,KACA,UACA,UACA,MACA,SACA,OACA,YACA,gBACoB,CACpB,IAAM,GAAA,EAAA,EAAA,YAAiB,EAAA,EAAY,CACnC,GAAI,CAAC,EACH,MAAU,MAAM,0DAA0D,CAI5E,IAAM,EAAiB,IAAc,IAAA,GAE/B,CAAE,UAAS,eAAA,EAAA,EAAA,aACT,EACF,CAAE,QAAS,EAAY,WAAY,GAAgB,EAAE,CAAE,CACvD,EAAA,EAAe,EAAS,CAC5B,CAAC,EAAgB,EAAW,EAAc,EAAS,CACpD,CACK,GAAA,EAAA,EAAA,aACE,GAAM,IAAA,EAAA,EAAA,aAAoB,EAAS,EAAQ,CACjD,CAAC,EAAI,EAAM,EAAS,EAAQ,CAC7B,CAWK,EAAS,EAAA,EATI,EAAI,EACrB,CACE,GAAI,EACJ,UACA,GAAI,IAAY,IAAA,GAA0B,EAAE,CAAhB,CAAE,UAAS,CACvC,GAAI,IAAY,IAAA,GAA0B,EAAE,CAAhB,CAAE,UAAS,CACxC,CACF,CAEsC,EAAW,CAElD,OADI,EAAe,EAAO,EAAO,CAC1B,GAAA,EAAA,EAAA,eAAoB,EAAK,KAAM,EAAO,EAAG,EAAA,EAAA,KAAA,EAAA,SAAA,CAAA,SAAG,EAAU,CAAA,EAC7D,CC3CW,GAAA,EAAA,EAAA,MAAc,SAAg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B,SAAsB,CAAE,QAAO,UAA6B,CAC3F,IAAM,GAAA,EAAA,EAAA,YAAiB,EAAA,EAAY,CACnC,GAAI,CAAC,EACH,MAAU,MAAM,2DAA2D,CAE7E,OAAO,EAAA,EAAA,KAAA,EAAA,SAAA,CAAA,SAAG,EAAI,EAAE,EAAO,EAAO,CAAI,CAAA,EAClC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { Trans } from './components/Trans';
|
|
2
|
+
export type { FluentiTransProps } from './components/Trans';
|
|
3
|
+
export { Plural } from './components/Plural';
|
|
4
|
+
export type { FluentiPluralProps } from './components/Plural';
|
|
5
|
+
export { Select } from './components/Select';
|
|
6
|
+
export type { FluentiSelectProps } from './components/Select';
|
|
7
|
+
export { DateTime } from './components/DateTime';
|
|
8
|
+
export type { FluentiDateTimeProps } from './components/DateTime';
|
|
9
|
+
export { NumberFormat } from './components/Number';
|
|
10
|
+
export type { NumberFormatProps, FluentiNumberFormatProps } from './components/Number';
|
|
11
|
+
export { interpolate } from '@fluenti/core/internal';
|
|
12
|
+
//# sourceMappingURL=components-entry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"components-entry.d.ts","sourceRoot":"","sources":["../src/components-entry.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC1C,YAAY,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAC5C,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAA;AAC5C,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAA;AAChD,YAAY,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAA;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,YAAY,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAA;AAGtF,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAA"}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { t as e } from "./context-DVudCV1o.js";
|
|
3
|
+
import { a as t, c as n, i as r, l as i, n as a, o, r as s, s as c, t as l } from "./icu-rich-ChVWsA7C.js";
|
|
4
|
+
import { createElement as u, memo as d, useContext as f, useMemo as p } from "react";
|
|
5
|
+
import { Fragment as m, jsx as h } from "react/jsx-runtime";
|
|
6
|
+
import { hashMessage as g, interpolate as _ } from "@fluenti/core/internal";
|
|
7
|
+
//#region src/components/Trans.tsx
|
|
8
|
+
var v = d(function({ children: t, id: r, context: a, comment: o, tag: s, render: l, __id: d, __message: g, __components: _ }) {
|
|
9
|
+
let v = f(e);
|
|
10
|
+
if (!v) throw Error("[fluenti] <Trans> must be used within an <I18nProvider>");
|
|
11
|
+
let y = g !== void 0, { message: b, components: x } = p(() => y ? {
|
|
12
|
+
message: g,
|
|
13
|
+
components: _ ?? []
|
|
14
|
+
} : c(t), [
|
|
15
|
+
y,
|
|
16
|
+
g,
|
|
17
|
+
_,
|
|
18
|
+
t
|
|
19
|
+
]), S = p(() => r ?? d ?? n(b, a), [
|
|
20
|
+
r,
|
|
21
|
+
d,
|
|
22
|
+
b,
|
|
23
|
+
a
|
|
24
|
+
]), C = i(v.t({
|
|
25
|
+
id: S,
|
|
26
|
+
message: b,
|
|
27
|
+
...a === void 0 ? {} : { context: a },
|
|
28
|
+
...o === void 0 ? {} : { comment: o }
|
|
29
|
+
}), x);
|
|
30
|
+
return l ? l(C) : s ? u(s, null, C) : /* @__PURE__ */ h(m, { children: C });
|
|
31
|
+
}), y = d(function({ value: n, id: i, context: a, comment: s, zero: c, one: u, two: d, few: p, many: _, other: v, offset: y }) {
|
|
32
|
+
let b = f(e);
|
|
33
|
+
if (!b) throw Error("[fluenti] <Plural> must be used within an <I18nProvider>");
|
|
34
|
+
let { messages: x, components: S } = t(o, {
|
|
35
|
+
zero: c,
|
|
36
|
+
one: u,
|
|
37
|
+
two: d,
|
|
38
|
+
few: p,
|
|
39
|
+
many: _,
|
|
40
|
+
other: v
|
|
41
|
+
}), C = l({
|
|
42
|
+
...x.zero !== void 0 && { zero: x.zero },
|
|
43
|
+
...x.one !== void 0 && { one: x.one },
|
|
44
|
+
...x.two !== void 0 && { two: x.two },
|
|
45
|
+
...x.few !== void 0 && { few: x.few },
|
|
46
|
+
...x.many !== void 0 && { many: x.many },
|
|
47
|
+
other: x.other ?? ""
|
|
48
|
+
}, y);
|
|
49
|
+
return /* @__PURE__ */ h(m, { children: r({
|
|
50
|
+
id: i ?? (a === void 0 ? C : g(C, a)),
|
|
51
|
+
message: C,
|
|
52
|
+
...a === void 0 ? {} : { context: a },
|
|
53
|
+
...s === void 0 ? {} : { comment: s }
|
|
54
|
+
}, { count: n }, (e, t) => b.t(e, t), S) });
|
|
55
|
+
}), b = d(function(n) {
|
|
56
|
+
let i = f(e);
|
|
57
|
+
if (!i) throw Error("[fluenti] <Select> must be used within an <I18nProvider>");
|
|
58
|
+
let { value: o, id: c, context: l, comment: d, other: p, options: _, tag: v, ...y } = n, b = _ === void 0 ? {
|
|
59
|
+
...Object.fromEntries(Object.entries(y).filter(([e]) => ![
|
|
60
|
+
"value",
|
|
61
|
+
"id",
|
|
62
|
+
"context",
|
|
63
|
+
"comment",
|
|
64
|
+
"options",
|
|
65
|
+
"other",
|
|
66
|
+
"tag"
|
|
67
|
+
].includes(e))),
|
|
68
|
+
other: p
|
|
69
|
+
} : {
|
|
70
|
+
..._,
|
|
71
|
+
other: p
|
|
72
|
+
}, x = [...Object.keys(b).filter((e) => e !== "other"), "other"], { messages: S, components: C } = t(x, b), w = s(Object.fromEntries([...x].map((e) => [e, S[e] ?? ""]))), T = a(w.forms), E = r({
|
|
73
|
+
id: c ?? (l === void 0 ? T : g(T, l)),
|
|
74
|
+
message: T,
|
|
75
|
+
...l === void 0 ? {} : { context: l },
|
|
76
|
+
...d === void 0 ? {} : { comment: d }
|
|
77
|
+
}, { value: w.valueMap[o] ?? "other" }, (e, t) => i.t(e, t), C);
|
|
78
|
+
return v ? u(v, null, E) : /* @__PURE__ */ h(m, { children: E });
|
|
79
|
+
}), x = d(function({ value: t, format: n }) {
|
|
80
|
+
let r = f(e);
|
|
81
|
+
if (!r) throw Error("[fluenti] <DateTime> must be used within an <I18nProvider>");
|
|
82
|
+
return /* @__PURE__ */ h(m, { children: r.d(t, n) });
|
|
83
|
+
}), S = d(function({ value: t, format: n }) {
|
|
84
|
+
let r = f(e);
|
|
85
|
+
if (!r) throw Error("[fluenti] <Number> must be used within an <I18nProvider>");
|
|
86
|
+
return /* @__PURE__ */ h(m, { children: r.n(t, n) });
|
|
87
|
+
});
|
|
88
|
+
//#endregion
|
|
89
|
+
export { x as DateTime, S as NumberFormat, y as Plural, b as Select, v as Trans, _ as interpolate };
|
|
90
|
+
|
|
91
|
+
//# sourceMappingURL=components-entry.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"components-entry.js","names":[],"sources":["../src/components/Trans.tsx","../src/components/Plural.tsx","../src/components/Select.tsx","../src/components/DateTime.tsx","../src/components/Number.tsx"],"sourcesContent":["import {\n createElement,\n memo,\n useContext,\n useMemo,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport { I18nContext } from '../context'\nimport { hashMessage, extractMessage, reconstruct } from './trans-core'\n\nexport interface FluentiTransProps {\n /** Source text with embedded components */\n children: ReactNode\n /** Override auto-generated hash ID */\n id?: string\n /** Message context used for identity and translator disambiguation */\n context?: string\n /** Context comment for translators */\n comment?: string\n /** Wrapper element tag name (e.g. 'span', 'div'). Defaults to Fragment (no wrapper). */\n tag?: keyof React.JSX.IntrinsicElements\n /** Custom render wrapper */\n render?: (translation: ReactNode) => ReactNode\n /** @internal Pre-computed message ID from build plugin */\n __id?: string\n /** @internal Pre-computed ICU message from build plugin */\n __message?: string\n /** @internal Pre-computed component list from build plugin */\n __components?: ReactElement[]\n}\n\n/**\n * `<Trans>` component for rich-text translations containing nested React elements.\n *\n * @example\n * ```tsx\n * <Trans>Read the <a href=\"/docs\">documentation</a> for more info.</Trans>\n * ```\n */\nexport const Trans = memo(function Trans({\n children,\n id,\n context,\n comment,\n tag,\n render,\n __id,\n __message,\n __components,\n}: FluentiTransProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Trans> must be used within an <I18nProvider>')\n }\n\n // Fast path: build plugin pre-computed message and components\n const hasPrecomputed = __message !== undefined\n\n const { message, components } = useMemo(\n () => hasPrecomputed\n ? { message: __message!, components: __components ?? [] }\n : extractMessage(children),\n [hasPrecomputed, __message, __components, children],\n )\n const messageId = useMemo(\n () => id ?? __id ?? hashMessage(message, context),\n [id, __id, message, context],\n )\n\n const translated = ctx.t(\n {\n id: messageId,\n message,\n ...(context !== undefined ? { context } : {}),\n ...(comment !== undefined ? { comment } : {}),\n },\n )\n\n const result = reconstruct(translated, components)\n if (render) return render(result)\n return tag ? createElement(tag, null, result) : <>{result}</>\n})\n","import { memo, useContext, type ReactNode } from 'react'\nimport { hashMessage } from '@fluenti/core/internal'\nimport { I18nContext } from '../context'\nimport { PLURAL_CATEGORIES, type PluralCategory } from './plural-core'\nimport { buildICUPluralMessage, renderRichTranslation, serializeRichForms } from './icu-rich'\n\nexport interface FluentiPluralProps {\n /** The count value */\n value: number\n /** Override the auto-generated synthetic ICU message id */\n id?: string\n /** Message context used for identity and translator disambiguation */\n context?: string\n /** Translator-facing note preserved in extraction catalogs */\n comment?: string\n /** Text for zero (if language supports) */\n zero?: ReactNode\n /** Singular form. `#` replaced with value */\n one?: ReactNode\n /** Dual form (Arabic, etc.) */\n two?: ReactNode\n /** Few form (Slavic languages, etc.) */\n few?: ReactNode\n /** Many form */\n many?: ReactNode\n /** Default plural form */\n other: ReactNode\n /** Offset from value before selecting form */\n offset?: number\n}\n\n/**\n * `<Plural>` — ICU plural handling as a component.\n *\n * @example\n * ```tsx\n * <Plural value={count} zero=\"No messages\" one=\"# message\" other=\"# messages\" />\n * ```\n */\nexport const Plural = memo(function Plural({\n value,\n id,\n context,\n comment,\n zero,\n one,\n two,\n few,\n many,\n other,\n offset,\n}: FluentiPluralProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Plural> must be used within an <I18nProvider>')\n }\n\n const forms: Record<PluralCategory, ReactNode | undefined> = {\n zero,\n one,\n two,\n few,\n many,\n other,\n }\n const { messages, components } = serializeRichForms(PLURAL_CATEGORIES, forms)\n const icuMessage = buildICUPluralMessage(\n {\n ...(messages.zero !== undefined && { zero: messages.zero }),\n ...(messages.one !== undefined && { one: messages.one }),\n ...(messages.two !== undefined && { two: messages.two }),\n ...(messages.few !== undefined && { few: messages.few }),\n ...(messages.many !== undefined && { many: messages.many }),\n other: messages.other ?? '',\n },\n offset,\n )\n\n const descriptor = {\n id: id ?? (context === undefined ? icuMessage : hashMessage(icuMessage, context)),\n message: icuMessage,\n ...(context !== undefined ? { context } : {}),\n ...(comment !== undefined ? { comment } : {}),\n }\n\n return <>{renderRichTranslation(descriptor, { count: value }, (desc, values) => ctx.t(desc, values), components)}</>\n})\n","import { createElement, memo, useContext, type ReactNode } from 'react'\nimport { hashMessage } from '@fluenti/core/internal'\nimport { I18nContext } from '../context'\nimport { buildICUSelectMessage, normalizeSelectForms, renderRichTranslation, serializeRichForms } from './icu-rich'\n\nexport interface FluentiSelectProps {\n /** The selector value */\n value: string\n /** Override the auto-generated synthetic ICU message id */\n id?: string\n /** Message context used for identity and translator disambiguation */\n context?: string\n /** Translator-facing note preserved in extraction catalogs */\n comment?: string\n /** Default case */\n other: ReactNode\n /** Type-safe named options. Takes precedence over direct case props. */\n options?: Record<string, ReactNode>\n /** Wrapper element tag name (e.g. 'span', 'div'). Defaults to Fragment (no wrapper). */\n tag?: keyof React.JSX.IntrinsicElements\n /** Named cases — any string key maps to a ReactNode */\n [key: string]: ReactNode | Record<string, ReactNode> | keyof React.JSX.IntrinsicElements | undefined\n}\n\n/**\n * `<Select>` — ICU select for gender, role, or other categorical values.\n *\n * @example\n * ```tsx\n * <Select\n * value={gender}\n * male=\"He liked your post\"\n * female=\"She liked your post\"\n * other=\"They liked your post\"\n * />\n * ```\n */\nexport const Select = memo(function Select(props: FluentiSelectProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Select> must be used within an <I18nProvider>')\n }\n\n const { value, id, context, comment, other, options, tag, ...cases } = props\n const forms: Record<string, ReactNode | undefined> = options === undefined\n ? {\n ...Object.fromEntries(\n Object.entries(cases).filter(([key]) => !['value', 'id', 'context', 'comment', 'options', 'other', 'tag'].includes(key)),\n ),\n other,\n }\n : {\n ...options,\n other,\n }\n\n const orderedKeys = [...Object.keys(forms).filter(key => key !== 'other'), 'other'] as const\n const { messages, components } = serializeRichForms(orderedKeys, forms)\n const normalized = normalizeSelectForms(\n Object.fromEntries(\n [...orderedKeys].map((key) => [key, messages[key] ?? '']),\n ),\n )\n const icuMessage = buildICUSelectMessage(normalized.forms)\n\n const descriptor = {\n id: id ?? (context === undefined ? icuMessage : hashMessage(icuMessage, context)),\n message: icuMessage,\n ...(context !== undefined ? { context } : {}),\n ...(comment !== undefined ? { comment } : {}),\n }\n\n const result = renderRichTranslation(\n descriptor,\n { value: normalized.valueMap[value] ?? 'other' },\n (desc, values) => ctx.t(desc, values),\n components,\n )\n return tag ? createElement(tag, null, result) : <>{result}</>\n})\n","import { memo, useContext } from 'react'\nimport { I18nContext } from '../context'\n\nexport interface FluentiDateTimeProps {\n /** Date value to format */\n value: Date | number\n /** Named format key defined in dateFormats config */\n format?: string\n}\n\n/**\n * `<DateTime>` — formatting component using Intl APIs.\n *\n * @example\n * ```tsx\n * <DateTime value={new Date()} format=\"long\" />\n * ```\n */\nexport const DateTime = memo(function DateTime({ value, format }: FluentiDateTimeProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <DateTime> must be used within an <I18nProvider>')\n }\n return <>{ctx.d(value, format)}</>\n})\n","import { memo, useContext } from 'react'\nimport { I18nContext } from '../context'\n\nexport interface NumberFormatProps {\n /** Number value to format */\n value: number\n /** Named format key defined in numberFormats config */\n format?: string\n}\n\n/** @alias NumberFormatProps */\nexport type FluentiNumberFormatProps = NumberFormatProps\n\n/**\n * `<Number>` — number formatting component using Intl APIs.\n *\n * @example\n * ```tsx\n * <Number value={1234.56} format=\"currency\" />\n * ```\n */\nexport const NumberFormat = memo(function NumberFormat({ value, format }: NumberFormatProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Number> must be used within an <I18nProvider>')\n }\n return <>{ctx.n(value, format)}</>\n})\n"],"mappings":";;;;;;;AAwCA,IAAa,IAAQ,EAAK,SAAe,EACvC,aACA,OACA,YACA,YACA,QACA,WACA,SACA,cACA,mBACoB;CACpB,IAAM,IAAM,EAAW,EAAY;AACnC,KAAI,CAAC,EACH,OAAU,MAAM,0DAA0D;CAI5E,IAAM,IAAiB,MAAc,KAAA,GAE/B,EAAE,YAAS,kBAAe,QACxB,IACF;EAAE,SAAS;EAAY,YAAY,KAAgB,EAAE;EAAE,GACvD,EAAe,EAAS,EAC5B;EAAC;EAAgB;EAAW;EAAc;EAAS,CACpD,EACK,IAAY,QACV,KAAM,KAAQ,EAAY,GAAS,EAAQ,EACjD;EAAC;EAAI;EAAM;EAAS;EAAQ,CAC7B,EAWK,IAAS,EATI,EAAI,EACrB;EACE,IAAI;EACJ;EACA,GAAI,MAAY,KAAA,IAA0B,EAAE,GAAhB,EAAE,YAAS;EACvC,GAAI,MAAY,KAAA,IAA0B,EAAE,GAAhB,EAAE,YAAS;EACxC,CACF,EAEsC,EAAW;AAElD,QADI,IAAe,EAAO,EAAO,GAC1B,IAAM,EAAc,GAAK,MAAM,EAAO,GAAG,kBAAA,GAAA,EAAA,U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
|
|
|
1
|
+
{"version":3,"file":"context-DVbvrSE8.cjs","names":[],"sources":["../src/context.ts"],"sourcesContent":["import { createContext } from 'react'\nimport type { FluentiContext } from './types'\n\nexport const I18nContext = createContext<FluentiContext | null>(null)\n"],"mappings":"AAGA,IAAa,GAAA,mBAAA,eAAmD,KAAK"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-DVudCV1o.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["import { createContext } from 'react'\nimport type { FluentiContext } from './types'\n\nexport const I18nContext = createContext<FluentiContext | null>(null)\n"],"mappings":";;AAGA,IAAa,IAAc,EAAqC,KAAK"}
|
package/dist/create-fluenti.d.ts
CHANGED
|
@@ -6,21 +6,25 @@ export interface FluentiConfig {
|
|
|
6
6
|
/** Active locale code */
|
|
7
7
|
locale: string;
|
|
8
8
|
/** Static message catalogs keyed by locale */
|
|
9
|
-
messages?: AllMessages;
|
|
9
|
+
messages?: AllMessages | undefined;
|
|
10
10
|
/** Async loader for lazy-loading locale messages */
|
|
11
|
-
loadMessages?: (locale: string) => Promise<Messages | {
|
|
11
|
+
loadMessages?: ((locale: string) => Promise<Messages | {
|
|
12
12
|
default: Messages;
|
|
13
|
-
}
|
|
13
|
+
}>) | undefined;
|
|
14
14
|
/** Fallback locale when a translation is missing */
|
|
15
|
-
fallbackLocale?: string;
|
|
15
|
+
fallbackLocale?: string | undefined;
|
|
16
16
|
/** Custom fallback chains per locale */
|
|
17
|
-
fallbackChain?: Record<string, string[]
|
|
17
|
+
fallbackChain?: Record<string, string[]> | undefined;
|
|
18
18
|
/** Date format styles */
|
|
19
|
-
dateFormats?: DateFormatOptions;
|
|
19
|
+
dateFormats?: DateFormatOptions | undefined;
|
|
20
20
|
/** Number format styles */
|
|
21
|
-
numberFormats?: NumberFormatOptions;
|
|
21
|
+
numberFormats?: NumberFormatOptions | undefined;
|
|
22
22
|
/** Missing message handler */
|
|
23
|
-
missing?: (locale: Locale, id: string) => string | undefined;
|
|
23
|
+
missing?: ((locale: Locale, id: string) => string | undefined) | undefined;
|
|
24
|
+
/** Runtime diagnostics (pre-created instance or config) */
|
|
25
|
+
diagnostics?: unknown | undefined;
|
|
26
|
+
/** Custom interpolation function for full ICU support at runtime */
|
|
27
|
+
interpolate?: ((message: string, values: Record<string, unknown> | undefined, locale: string, formatters?: Record<string, unknown>) => string) | undefined;
|
|
24
28
|
}
|
|
25
29
|
/**
|
|
26
30
|
* The object returned by `createFluenti()`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-fluenti.d.ts","sourceRoot":"","sources":["../src/create-fluenti.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,uBAAuB,IAAI,sBAAsB,EACjD,eAAe,EACf,MAAM,EACN,QAAQ,EACR,WAAW,EACX,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,iBAAiB,EAClB,MAAM,eAAe,CAAA;AAEtB;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,yBAAyB;IACzB,MAAM,EAAE,MAAM,CAAA;IACd,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,WAAW,CAAA;
|
|
1
|
+
{"version":3,"file":"create-fluenti.d.ts","sourceRoot":"","sources":["../src/create-fluenti.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,uBAAuB,IAAI,sBAAsB,EACjD,eAAe,EACf,MAAM,EACN,QAAQ,EACR,WAAW,EACX,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,iBAAiB,EAClB,MAAM,eAAe,CAAA;AAEtB;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,yBAAyB;IACzB,MAAM,EAAE,MAAM,CAAA;IACd,8CAA8C;IAC9C,QAAQ,CAAC,EAAE,WAAW,GAAG,SAAS,CAAA;IAClC,oDAAoD;IACpD,YAAY,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,GAAG;QAAE,OAAO,EAAE,QAAQ,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 0, l = a.exec(e); l !== null;) {
|
|
25
25
|
l.index > s && o.push(e.slice(s, l.index));
|
|
26
|
-
let t = Number(l[1]), r = l[2] === void 0, u = l[3] ?? ""
|
|
26
|
+
let t = Number(l[1]), r = l[2] === void 0, u = l[3] ?? "";
|
|
27
|
+
if (!Number.isInteger(t) || t < 0 || t >= i.length) {
|
|
28
|
+
u && o.push(u), s = a.lastIndex, l = a.exec(e);
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
let d = i[t];
|
|
27
32
|
if (d) {
|
|
28
33
|
let e = `trans-${c++}`;
|
|
29
34
|
if (r) o.push(n(d, { key: e }));
|
|
@@ -70,4 +75,4 @@ function h(e, t, n, r) {
|
|
|
70
75
|
//#endregion
|
|
71
76
|
export { m as a, c, h as i, f as l, s as n, a as o, l as r, d as s, o as t };
|
|
72
77
|
|
|
73
|
-
//# sourceMappingURL=icu-rich-
|
|
78
|
+
//# sourceMappingURL=icu-rich-ChVWsA7C.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"icu-rich-ChVWsA7C.js","names":[],"sources":["../src/components/trans-core.ts","../src/components/icu-rich.tsx"],"sourcesContent":["import {\n Children,\n isValidElement,\n cloneElement,\n createElement,\n Fragment,\n type ReactNode,\n type ReactElement,\n} from 'react'\nimport { hashMessage, offsetIndices } from '@fluenti/core/internal'\n\nexport { hashMessage }\n\n/**\n * Extract a message string and component list from React children.\n *\n * Converts:\n * <Trans>Hello <b>{name}</b>, welcome!</Trans>\n * Into:\n * message: \"Hello <0>{name}</0>, welcome!\"\n * components: [<b>{name}</b>]\n *\n * @internal\n */\nexport function extractMessage(children: ReactNode): {\n message: string\n components: ReactElement[]\n} {\n const components: ReactElement[] = []\n let message = ''\n\n Children.forEach(children, (child) => {\n if (typeof child === 'string' || typeof child === 'number') {\n message += String(child)\n } else if (isValidElement(child)) {\n if (child.type === Fragment) {\n const inner = extractMessage((child.props as { children?: ReactNode }).children)\n message += offsetIndices(inner.message, components.length)\n components.push(...inner.components)\n return\n }\n\n const idx = components.length\n const inner = extractMessage((child.props as { children?: ReactNode }).children)\n components.push(child)\n components.push(...inner.components)\n if (inner.message === '' && inner.components.length === 0) {\n message += `<${idx}/>`\n } else {\n message += `<${idx}>${offsetIndices(inner.message, idx + 1)}</${idx}>`\n }\n }\n })\n\n return { message, components }\n}\n\n/**\n * Reconstruct a translated message string back into React elements.\n *\n * Parses \"<0>content</0>\" tags and replaces them with cloned components.\n *\n * @internal\n */\nexport function reconstruct(\n translated: string,\n components: ReactElement[],\n): ReactNode {\n const COMBINED_RE = /<(\\d+)(?:\\/>|(>)([\\s\\S]*?)<\\/\\1>)/g\n const result: ReactNode[] = []\n let lastIndex = 0\n let keyCounter = 0\n let match: RegExpExecArray | null\n\n COMBINED_RE.lastIndex = 0\n match = COMBINED_RE.exec(translated)\n\n while (match !== null) {\n if (match.index > lastIndex) {\n result.push(translated.slice(lastIndex, match.index))\n }\n\n const idx = Number(match[1])\n const isSelfClosing = match[2] === undefined\n const innerText = match[3] ?? ''\n\n if (!Number.isInteger(idx) || idx < 0 || idx >= components.length) {\n if (innerText) result.push(innerText)\n lastIndex = COMBINED_RE.lastIndex\n match = COMBINED_RE.exec(translated)\n continue\n }\n\n const component = components[idx]\n\n if (component) {\n // Use keyCounter (not idx) so duplicate component indices get unique keys\n const key = `trans-${keyCounter++}`\n if (isSelfClosing) {\n result.push(cloneElement(component, { key }))\n } else {\n const innerContent = reconstruct(innerText, components)\n result.push(cloneElement(component, { key }, innerContent))\n }\n } else {\n // Only push non-empty text to avoid inserting blank DOM nodes\n if (innerText) result.push(innerText)\n }\n\n lastIndex = COMBINED_RE.lastIndex\n match = COMBINED_RE.exec(translated)\n }\n\n if (lastIndex < translated.length) {\n result.push(translated.slice(lastIndex))\n }\n\n return result.length === 1 ? result[0]! : createElement(Fragment, null, ...result)\n}\n","import type { MessageDescriptor } from '@fluenti/core'\nimport {\n buildICUPluralMessage,\n buildICUSelectMessage,\n normalizeSelectForms,\n offsetIndices,\n} from '@fluenti/core/internal'\nimport type { ReactElement, ReactNode } from 'react'\nimport { extractMessage, reconstruct } from './trans-core'\n\nexport { buildICUPluralMessage, buildICUSelectMessage, normalizeSelectForms }\n\nexport interface RichMessagePart {\n message: string\n components: ReactElement[]\n}\n\nexport function serializeRichNode(node: ReactNode): RichMessagePart {\n const extracted = extractMessage(node)\n return {\n message: extracted.message,\n components: extracted.components,\n }\n}\n\nexport function serializeRichForms<T extends string>(\n keys: readonly T[],\n forms: Partial<Record<T, ReactNode>> & Record<string, ReactNode | undefined>,\n): {\n messages: Partial<Record<T, string>> & Record<string, string>\n components: ReactElement[]\n} {\n const components: ReactElement[] = []\n const messages: Record<string, string> = {}\n\n for (const key of keys) {\n const value = forms[key]\n if (value === undefined) continue\n const extracted = serializeRichNode(value)\n messages[key] = offsetIndices(extracted.message, components.length)\n components.push(...extracted.components)\n }\n\n for (const [key, value] of Object.entries(forms)) {\n if (keys.includes(key as T) || value === undefined) continue\n const extracted = serializeRichNode(value)\n messages[key] = offsetIndices(extracted.message, components.length)\n components.push(...extracted.components)\n }\n\n return { messages: messages as Partial<Record<T, string>> & Record<string, string>, components }\n}\n\nexport function renderRichTranslation(\n descriptor: MessageDescriptor,\n values: Record<string, unknown> | undefined,\n translate: (descriptor: MessageDescriptor, values?: Record<string, unknown>) => string,\n components: ReactElement[],\n): ReactNode {\n const translated = translate(descriptor, values)\n return components.length > 0 ? reconstruct(translated, components) : translated\n}\n"],"mappings":";;;AAwBA,SAAgB,EAAe,GAG7B;CACA,IAAM,IAA6B,EAAE,EACjC,IAAU;AAyBd,QAvBA,EAAS,QAAQ,IAAW,MAAU;AACpC,MAAI,OAAO,KAAU,YAAY,OAAO,KAAU,SAChD,MAAW,OAAO,EAAM;WACf,EAAe,EAAM,EAAE;AAChC,OAAI,EAAM,SAAS,GAAU;IAC3B,IAAM,IAAQ,EAAgB,EAAM,MAAmC,SAAS;AAEhF,IADA,KAAW,EAAc,EAAM,SAAS,EA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AAO,KAAK,EAAW,MAAM,EAAU,CAAC,EAGnC,EAAO,WAAW,IAAI,EAAO,KAAM,EAAc,GAAU,MAAM,GAAG,EAAO;;;;ACpGpF,SAAgB,EAAkB,GAAkC;CAClE,IAAM,IAAY,EAAe,EAAK;AACtC,QAAO;EACL,SAAS,EAAU;EACnB,YAAY,EAAU;EACvB;;AAGH,SAAgB,EACd,GACA,GAIA;CACA,IAAM,IAA6B,EAAE,EAC/B,IAAmC,EAAE;AAE3C,MAAK,IAAM,KAAO,GAAM;EACtB,IAAM,IAAQ,EAAM;AACpB,MAAI,MAAU,KAAA,EAAW;EACzB,IAAM,IAAY,EAAkB,EAAM;AAE1C,EADA,EAAS,KAAO,EAAc,EAAU,SAAS,EAAW,OAAO,EACnE,EAAW,KAAK,GAAG,EAAU,WAAW;;AAG1C,MAAK,IAAM,CAAC,GAAK,MAAU,OAAO,QAAQ,EAAM,EAAE;AAChD,MAAI,EAAK,SAAS,EAAS,IAAI,MAAU,KAAA,EAAW;EACpD,IAAM,IAAY,EAAkB,EAAM;AAE1C,EADA,EAAS,KAAO,EAAc,EAAU,SAAS,EAAW,OAAO,EACnE,EAAW,KAAK,GAAG,EAAU,WAAW;;AAG1C,QAAO;EAAY;EAAiE;EAAY;;AAGlG,SAAgB,EACd,GACA,GACA,GACA,GACW;CACX,IAAM,IAAa,EAAU,GAAY,EAAO;AAChD,QAAO,EAAW,SAAS,IAAI,EAAY,GAAY,EAAW,GAAG"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
let e=require(`react`),t=require(`@fluenti/core/internal`);function n(r){let i=[],a=``;return e.Children.forEach(r,r=>{if(typeof r==`string`||typeof r==`number`)a+=String(r);else if((0,e.isValidElement)(r)){if(r.type===e.Fragment){let e=n(r.props.children);a+=(0,t.offsetIndices)(e.message,i.length),i.push(...e.components);return}let o=i.length,s=n(r.props.children);i.push(r),i.push(...s.components),s.message===``&&s.components.length===0?a+=`<${o}/>`:a+=`<${o}>${(0,t.offsetIndices)(s.message,o+1)}</${o}>`}}),{message:a,components:i}}function r(t,n){let i=/<(\d+)(?:\/>|(>)([\s\S]*?)<\/\1>)/g,a=[],o=0,s=0,c;for(i.lastIndex=0,c=i.exec(t);c!==null;){c.index>o&&a.push(t.slice(o,c.index));let l=Number(c[1]),u=c[2]===void 0,d=c[3]??``;if(!Number.isInteger(l)||l<0||l>=n.length){d&&a.push(d),o=i.lastIndex,c=i.exec(t);continue}let f=n[l];if(f){let t=`trans-${s++}`;if(u)a.push((0,e.cloneElement)(f,{key:t}));else{let i=r(d,n);a.push((0,e.cloneElement)(f,{key:t},i))}}else d&&a.push(d);o=i.lastIndex,c=i.exec(t)}return o<t.length&&a.push(t.slice(o)),a.length===1?a[0]:(0,e.createElement)(e.Fragment,null,...a)}function i(e){let t=n(e);return{message:t.message,components:t.components}}function a(e,n){let r=[],a={};for(let o of e){let e=n[o];if(e===void 0)continue;let s=i(e);a[o]=(0,t.offsetIndices)(s.message,r.length),r.push(...s.components)}for(let[o,s]of Object.entries(n)){if(e.includes(o)||s===void 0)continue;let n=i(s);a[o]=(0,t.offsetIndices)(n.message,r.length),r.push(...n.components)}return{messages:a,components:r}}function o(e,t,n,i){let a=n(e,t);return i.length>0?r(a,i):a}Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return o}});
|
|
2
|
+
//# sourceMappingURL=icu-rich-CotMVC_x.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"icu-rich-CotMVC_x.cjs","names":[],"sources":["../src/components/trans-core.ts","../src/components/icu-rich.tsx"],"sourcesContent":["import {\n Children,\n isValidElement,\n cloneElement,\n createElement,\n Fragment,\n type ReactNode,\n type ReactElement,\n} from 'react'\nimport { hashMessage, offsetIndices } from '@fluenti/core/internal'\n\nexport { hashMessage }\n\n/**\n * Extract a message string and component list from React children.\n *\n * Converts:\n * <Trans>Hello <b>{name}</b>, welcome!</Trans>\n * Into:\n * message: \"Hello <0>{name}</0>, welcome!\"\n * components: [<b>{name}</b>]\n *\n * @internal\n */\nexport function extractMessage(children: ReactNode): {\n message: string\n components: ReactElement[]\n} {\n const components: ReactElement[] = []\n let message = ''\n\n Children.forEach(children, (child) => {\n if (typeof child === 'string' || typeof child === 'number') {\n message += String(child)\n } else if (isValidElement(child)) {\n if (child.type === Fragment) {\n const inner = extractMessage((child.props as { children?: ReactNode }).children)\n message += offsetIndices(inner.message, components.length)\n components.push(...inner.components)\n return\n }\n\n const idx = components.length\n const inner = extractMessage((child.props as { children?: ReactNode }).children)\n components.push(child)\n components.push(...inner.components)\n if (inner.message === '' && inner.components.length === 0) {\n message += `<${idx}/>`\n } else {\n message += `<${idx}>${offsetIndices(inner.message, idx + 1)}</${idx}>`\n }\n }\n })\n\n return { message, components }\n}\n\n/**\n * Reconstruct a translated message string back into React elements.\n *\n * Parses \"<0>content</0>\" tags and replaces them with cloned components.\n *\n * @internal\n */\nexport function reconstruct(\n translated: string,\n components: ReactElement[],\n): ReactNode {\n const COMBINED_RE = /<(\\d+)(?:\\/>|(>)([\\s\\S]*?)<\\/\\1>)/g\n const result: ReactNode[] = []\n let lastIndex = 0\n let keyCounter = 0\n let match: RegExpExecArray | null\n\n COMBINED_RE.lastIndex = 0\n match = COMBINED_RE.exec(translated)\n\n while (match !== null) {\n if (match.index > lastIndex) {\n result.push(translated.slice(lastIndex, match.index))\n }\n\n const idx = Number(match[1])\n const isSelfClosing = match[2] === undefined\n const innerText = match[3] ?? ''\n\n if (!Number.isInteger(idx) || idx < 0 || idx >= components.length) {\n if (innerText) result.push(innerText)\n lastIndex = COMBINED_RE.lastIndex\n match = COMBINED_RE.exec(translated)\n continue\n }\n\n const component = components[idx]\n\n if (component) {\n // Use keyCounter (not idx) so duplicate component indices get unique keys\n const key = `trans-${keyCounter++}`\n if (isSelfClosing) {\n result.push(cloneElement(component, { key }))\n } else {\n const innerContent = reconstruct(innerText, components)\n result.push(cloneElement(component, { key }, innerContent))\n }\n } else {\n // Only push non-empty text to avoid inserting blank DOM nodes\n if (innerText) result.push(innerText)\n }\n\n lastIndex = COMBINED_RE.lastIndex\n match = COMBINED_RE.exec(translated)\n }\n\n if (lastIndex < translated.length) {\n result.push(translated.slice(lastIndex))\n }\n\n return result.length === 1 ? result[0]! : createElement(Fragment, null, ...result)\n}\n","import type { MessageDescriptor } from '@fluenti/core'\nimport {\n buildICUPluralMessage,\n buildICUSelectMessage,\n normalizeSelectForms,\n offsetIndices,\n} from '@fluenti/core/internal'\nimport type { ReactElement, ReactNode } from 'react'\nimport { extractMessage, reconstruct } from './trans-core'\n\nexport { buildICUPluralMessage, buildICUSelectMessage, normalizeSelectForms }\n\nexport interface RichMessagePart {\n message: string\n components: ReactElement[]\n}\n\nexport function serializeRichNode(node: ReactNode): RichMessagePart {\n const extracted = extractMessage(node)\n return {\n message: extracted.message,\n components: extracted.components,\n }\n}\n\nexport function serializeRichForms<T extends string>(\n keys: readonly T[],\n forms: Partial<Record<T, ReactNode>> & Record<string, ReactNode | undefined>,\n): {\n messages: Partial<Record<T, string>> & Record<string, string>\n components: ReactElement[]\n} {\n const components: ReactElement[] = []\n const messages: Record<string, string> = {}\n\n for (const key of keys) {\n const value = forms[key]\n if (value === undefined) continue\n const extracted = serializeRichNode(value)\n messages[key] = offsetIndices(extracted.message, components.length)\n components.push(...extracted.components)\n }\n\n for (const [key, value] of Object.entries(forms)) {\n if (keys.includes(key as T) || value === undefined) continue\n const extracted = serializeRichNode(value)\n messages[key] = offsetIndices(extracted.message, components.length)\n components.push(...extracted.components)\n }\n\n return { messages: messages as Partial<Record<T, string>> & Record<string, string>, components }\n}\n\nexport function renderRichTranslation(\n descriptor: MessageDescriptor,\n values: Record<string, unknown> | undefined,\n translate: (descriptor: MessageDescriptor, values?: Record<string, unknown>) => string,\n components: ReactElement[],\n): ReactNode {\n const translated = translate(descriptor, values)\n return components.length > 0 ? reconstruct(translated, components) : translated\n}\n"],"mappings":"2DAwBA,SAAgB,EAAe,EAG7B,CACA,IAAM,EAA6B,EAAE,CACjC,EAAU,GAyBd,OAvBA,EAAA,SAAS,QAAQ,EAAW,GAAU,CACpC,GAAI,OAAO,GAAU,UAAY,OAAO,GAAU,SAChD,GAAW,OAAO,EAAM,8BACA,EAAM,CAAE,CAChC,GAAI,EAAM,OAAS,EAAA,SAAU,CAC3B,IAAM,EAAQ,EAAgB,EAAM,MAAmC,SAAS,CAChF,IAAA,EAAA,EAAA,eAAyB,EAAM,QAAS,EAAW,OAAO,CAC1D,EAAW,KAAK,GAAG,EAAM,WAAW,CACpC,OAGF,IAAM,EAAM,EAAW,OACjB,EAAQ,EAAgB,EAAM,MAAmC,SAAS,CAChF,EAAW,KAAK,EAAM,CACtB,EAAW,KAAK,GAAG,EAAM,WAAW,CAChC,EAAM,UAAY,IAAM,EAAM,WAAW,SAAW,EACtD,GAAW,IAAI,EAAI,IAEnB,GAAW,IAAI,EAAI,IAAA,EAAA,EAAA,eAAiB,EAAM,QAAS,EAAM,EAAE,CAAC,IAAI,EAAI,KAGxE,CAEK,CAAE,UAAS,aAAY,CAUhC,SAAgB,EACd,EACA,EACW,CACX,IAAM,EAAc,qCACd,EAAsB,EAAE,CAC1B,EAAY,EACZ,EAAa,EACb,EAKJ,IAHA,EAAY,UAAY,EACxB,EAAQ,EAAY,KAAK,EAAW,CAE7B,IAAU,MAAM,CACjB,EAAM,MAAQ,GAChB,EAAO,KAAK,EAAW,MAAM,EAAW,EAAM,MAAM,CAAC,CAGvD,IAAM,EAAM,OAAO,EAAM,GAAG,CACtB,EAAgB,EAAM,KAAO,IAAA,GAC7B,EAAY,EAAM,IAAM,GAE9B,GAAI,CAAC,OAAO,UAAU,EAAI,EAAI,EAAM,GAAK,GAAO,EAAW,OAAQ,CAC7D,GAAW,EAAO,KAAK,EAAU,CACrC,EAAY,EAAY,UACxB,EAAQ,EA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,EACW,CACX,IAAM,EAAa,EAAU,EAAY,EAAO,CAChD,OAAO,EAAW,OAAS,EAAI,EAAY,EAAY,EAAW,CAAG"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
"use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./
|
|
2
|
+
"use client";Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./context-DVbvrSE8.cjs`);let t=require(`react`),n=require(`@fluenti/core`),r=require(`react/jsx-runtime`);function i(e){let t={};for(let[n,r]of Object.entries(e))t[n]=typeof r==`object`&&r&&`default`in r?r.default:r;return t}function a(e){let{locale:r,messages:a,loadMessages:o,fallbackLocale:s,fallbackChain:c,dateFormats:l,numberFormats:u,missing:d,diagnostics:f,interpolate:p}=e,[m,h]=(0,t.useState)(r),[g,_]=(0,t.useState)(!1),[v,y]=(0,t.useState)(a?i(a):{}),[b,x]=(0,t.useState)(a?Object.keys(a):[]),S=(0,t.useRef)(v);S.current=v;let C=(0,t.useRef)(0),w=Symbol.for(`fluenti.runtime.react.v1`);function T(){let e=globalThis[w];return typeof e==`object`&&e?e:null}let E=(0,t.useMemo)(()=>{let e={locale:m,messages:v};return s!==void 0&&(e.fallbackLocale=s),c!==void 0&&(e.fallbackChain=c),l!==void 0&&(e.dateFormats=l),u!==void 0&&(e.numberFormats=u),d!==void 0&&(e.missing=d),f!==void 0&&(e.diagnostics=f),p!==void 0&&(e.interpolate=p),(0,n.createFluentiCore)(e)},[m,v,s,c,l,u,d,f,p]);(0,t.useEffect)(()=>{r!==m&&D(r)},[r]);let D=(0,t.useCallback)(async e=>{let t=++C.current,n=o?T():null;if(S.current[e]&&!o){h(e);return}if(S.current[e]){try{n?.__switchLocale&&await n.__switchLocale(e)}catch(t){console.warn(`[fluenti] split runtime switch failed for locale "${e}"`,t)}h(e);return}if(!o){console.warn(`[fluenti] No messages for locale "${e}" and no loadMessages function provided`);return}_(!0);try{let r=await o(e);if(t!==C.current)return;let i=typeof r==`object`&&r&&`default`in r?r.default:r;try{n?.__switchLocale&&await n.__switchLocale(e)}catch(t){console.warn(`[fluenti] split runtime switch failed for locale "${e}"`,t)}if(t!==C.current)return;y(t=>({...t,[e]:i})),x(t=>[...new Set([...t,e])]),h(e)}catch(n){t===C.current&&console.error(`[fluenti] Failed to load locale "${e}"`,n)}finally{t===C.current&&_(!1)}},[o]),O=(0,t.useCallback)(async e=>{if(!(S.current[e]||!o))try{let t=await o(e),n=typeof t==`object`&&t&&`default`in t?t.default:t;y(t=>({...t,[e]:n})),x(t=>[...new Set([...t,e])]);let r=T();r?.__preloadLocale&&await r.__preloadLocale(e)}catch{}},[o]),k=(0,t.useCallback)((e,t)=>{let n=v[t??m];return n!==void 0&&e in n},[v,m]),A=(0,t.useCallback)((e,t)=>{let n=v[t??m];if(n)return n[e]},[v,m]);return(0,t.useMemo)(()=>({t:E.t.bind(E),d:E.d.bind(E),n:E.n.bind(E),locale:m,setLocale:D,isLoading:g,preloadLocale:O,te:k,tm:A,i18n:E,format:E.format.bind(E),loadMessages:E.loadMessages.bind(E),getLocales:E.getLocales.bind(E),loadedLocales:b}),[E,m,D,g,O,k,A,b])}function o(e){globalThis.__fluenti_i18n=e}function s({instance:n,children:i}){let a=(0,t.useMemo)(()=>({t:n.t,d:n.d,n:n.n,format:n.format,loadMessages:n.loadMessages,getLocales:n.getLocales,locale:n.locale,setLocale:n.setLocale,isLoading:n.isLoading,loadedLocales:n.loadedLocales,preloadLocale:n.preloadLocale,te:n.te,tm:n.tm,i18n:n.i18n}),[n]);return(0,r.jsx)(e.t.Provider,{value:a,children:i})}function c(e){return e.instance?(0,r.jsx)(s,{instance:e.instance,children:e.children}):(0,r.jsx)(l,{...e})}function l({locale:e,fallbackLocale:n,messages:i,loadMessages:c,fallbackChain:l,dateFormats:u,numberFormats:d,missing:f,diagnostics:p,interpolate:m,children:h}){let g=a({locale:e??`en`,messages:i,loadMessages:c,fallbackLocale:n,fallbackChain:l,dateFormats:u,numberFormats:d,missing:f,diagnostics:p,interpolate:m});return(0,t.useEffect)(()=>{o(g.i18n)},[g.i18n]),(0,r.jsx)(s,{instance:g,children:h})}function u(){let n=(0,t.useContext)(e.t);if(!n)throw Error(`[fluenti] useI18n() must be used within an <I18nProvider>. Wrap your app with <I18nProvider> to provide i18n context.`);return n}var d=((...e)=>{throw Error("[fluenti] `t` imported from '@fluenti/react' is a compile-time API. Use it only with the Fluenti build transform inside a component or custom hook. For runtime lookups, use useI18n().t(...).")});exports.I18nContext=e.t,exports.I18nProvider=c,exports.createFluenti=a,Object.defineProperty(exports,`msg`,{enumerable:!0,get:function(){return n.msg}}),exports.t=d,exports.useI18n=u;
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../src/create-fluenti.ts","../src/context.ts","../src/global-registry.ts","../src/provider.tsx","../src/hooks/useI18n.ts","../src/compile-time-t.ts","../src/components/Trans.tsx","../src/components/Plural.tsx","../src/components/Select.tsx","../src/components/DateTime.tsx","../src/components/Number.tsx"],"sourcesContent":["import { useState, useCallback, useEffect, useMemo, useRef } from 'react'\nimport { createFluentiCore } from '@fluenti/core'\nimport type {\n FluentiCoreInstanceFull as FluentInstanceExtended,\n CompiledMessage,\n Locale,\n Messages,\n AllMessages,\n DateFormatOptions,\n NumberFormatOptions,\n LocalizedString,\n MessageDescriptor,\n} from '@fluenti/core'\n\n/**\n * Configuration for `createFluenti()`.\n */\nexport interface FluentiConfig {\n /** Active locale code */\n locale: string\n /** Static message catalogs keyed by locale */\n messages?: AllMessages\n /** Async loader for lazy-loading locale messages */\n loadMessages?: (locale: string) => Promise<Messages | { default: Messages }>\n /** Fallback locale when a translation is missing */\n fallbackLocale?: string\n /** Custom fallback chains per locale */\n fallbackChain?: Record<string, string[]>\n /** Date format styles */\n dateFormats?: DateFormatOptions\n /** Number format styles */\n numberFormats?: NumberFormatOptions\n /** Missing message handler */\n missing?: (locale: Locale, id: string) => string | undefined\n}\n\n/**\n * The object returned by `createFluenti()`.\n *\n * Contains all i18n state and methods. Pass to `<I18nProvider instance={...}>`\n * or use directly in tests/non-React contexts.\n */\nexport interface FluentiInstance {\n /** Translate a message by id with optional interpolation values */\n t: {\n (id: string | MessageDescriptor, values?: Record<string, unknown>): LocalizedString\n (strings: TemplateStringsArray, ...exprs: unknown[]): LocalizedString\n }\n /** Format a date value for the current locale */\n d: (value: Date | number, style?: string) => LocalizedString\n /** Format a number value for the current locale */\n n: (value: number, style?: string) => LocalizedString\n /** Current locale */\n locale: string\n /** Change the active locale (async when lazy loading) */\n setLocale: (locale: string) => Promise<void>\n /** Whether a locale is currently being loaded */\n isLoading: boolean\n /** Preload a locale in the background without switching to it */\n preloadLocale: (locale: string) => Promise<void>\n /** Check whether a translation key exists for the given or current locale */\n te: (key: string, locale?: string) => boolean\n /** Get the raw compiled message for a key without interpolation */\n tm: (key: string, locale?: string) => CompiledMessage | undefined\n /** The underlying Fluent instance (escape hatch for advanced use) */\n i18n: FluentInstanceExtended\n /** Format an ICU message string directly (no catalog lookup) */\n format: (message: string, values?: Record<string, unknown>) => LocalizedString\n /** Merge additional messages into a locale catalog at runtime */\n loadMessages: (locale: string, messages: Messages) => void\n /** Return all locale codes that have loaded messages */\n getLocales: () => string[]\n /** Set of locales whose messages have been loaded */\n loadedLocales: string[]\n}\n\nfunction unwrapMessages(allMessages: Record<string, unknown>): Record<string, Messages> {\n const result: Record<string, Messages> = {}\n for (const [locale, msgs] of Object.entries(allMessages)) {\n result[locale] = typeof msgs === 'object' && msgs !== null && 'default' in msgs\n ? (msgs as { default: Messages }).default\n : msgs as Messages\n }\n return result\n}\n\n/**\n * Create a standalone Fluenti i18n instance.\n *\n * This is a React hook that manages locale state, message loading, and\n * provides all i18n methods. The returned instance can be passed to\n * `<I18nProvider instance={...}>` to share it with the component tree.\n *\n * @example\n * ```tsx\n * function App() {\n * const i18n = createFluenti({\n * locale: 'en',\n * messages: { en: enMessages, fr: frMessages },\n * })\n * return (\n * <I18nProvider instance={i18n}>\n * <MyApp />\n * </I18nProvider>\n * )\n * }\n * ```\n */\nexport function createFluenti(config: FluentiConfig): FluentiInstance {\n const {\n locale: initialLocale,\n messages: initialMessages,\n loadMessages: loadMessagesFn,\n fallbackLocale,\n fallbackChain,\n dateFormats,\n numberFormats,\n missing,\n } = config\n\n const [currentLocale, setCurrentLocale] = useState(initialLocale)\n const [isLoading, setIsLoading] = useState(false)\n const [loadedMessages, setLoadedMessages] = useState<Record<string, Messages>>(\n initialMessages ? unwrapMessages(initialMessages) : {},\n )\n const [loadedLocales, setLoadedLocales] = useState<string[]>(\n initialMessages ? Object.keys(initialMessages) : [],\n )\n\n const loadedMessagesRef = useRef(loadedMessages)\n loadedMessagesRef.current = loadedMessages\n\n const localeRequestRef = useRef(0)\n\n const i18n = useMemo(() => {\n const cfg: Parameters<typeof createFluentiCore>[0] = {\n locale: currentLocale,\n messages: loadedMessages,\n }\n if (fallbackLocale !== undefined) cfg.fallbackLocale = fallbackLocale\n if (fallbackChain !== undefined) cfg.fallbackChain = fallbackChain\n if (dateFormats !== undefined) cfg.dateFormats = dateFormats\n if (numberFormats !== undefined) cfg.numberFormats = numberFormats\n if (missing !== undefined) cfg.missing = missing\n return createFluentiCore(cfg)\n }, [currentLocale, loadedMessages, fallbackLocale, fallbackChain, dateFormats, numberFormats, missing])\n\n // Sync external locale changes\n useEffect(() => {\n if (initialLocale !== currentLocale) {\n void handleSetLocale(initialLocale)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [initialLocale])\n\n const handleSetLocale = useCallback(\n async (newLocale: string) => {\n const requestId = ++localeRequestRef.current\n\n if (loadedMessagesRef.current[newLocale] && !loadMessagesFn) {\n setCurrentLocale(newLocale)\n return\n }\n\n if (loadedMessagesRef.current[newLocale]) {\n setCurrentLocale(newLocale)\n return\n }\n\n if (!loadMessagesFn) {\n console.warn(\n `[fluenti] No messages for locale \"${newLocale}\" and no loadMessages function provided`,\n )\n return\n }\n\n setIsLoading(true)\n try {\n const msgs = await loadMessagesFn(newLocale)\n if (requestId !== localeRequestRef.current) return\n\n const resolved: Messages =\n typeof msgs === 'object' && msgs !== null && 'default' in msgs\n ? (msgs as { default: Messages }).default\n : (msgs as Messages)\n setLoadedMessages((prev) => ({ ...prev, [newLocale]: resolved }))\n setLoadedLocales((prev) => [...new Set([...prev, newLocale])])\n setCurrentLocale(newLocale)\n } catch (err) {\n if (requestId === localeRequestRef.current) {\n console.error(`[fluenti] Failed to load locale \"${newLocale}\"`, err)\n }\n } finally {\n if (requestId === localeRequestRef.current) {\n setIsLoading(false)\n }\n }\n },\n [loadMessagesFn],\n )\n\n const preloadLocale = useCallback(\n async (loc: string) => {\n if (loadedMessagesRef.current[loc] || !loadMessagesFn) return\n try {\n const msgs = await loadMessagesFn(loc)\n const resolved: Messages =\n typeof msgs === 'object' && msgs !== null && 'default' in msgs\n ? (msgs as { default: Messages }).default\n : (msgs as Messages)\n setLoadedMessages((prev) => ({ ...prev, [loc]: resolved }))\n setLoadedLocales((prev) => [...new Set([...prev, loc])])\n } catch {\n // Silent fail for preload\n }\n },\n [loadMessagesFn],\n )\n\n const te = useCallback(\n (key: string, loc?: string): boolean => {\n const msgs = loadedMessages[loc ?? currentLocale]\n return msgs !== undefined && key in msgs\n },\n [loadedMessages, currentLocale],\n )\n\n const tm = useCallback(\n (key: string, loc?: string): Messages[string] | undefined => {\n const msgs = loadedMessages[loc ?? currentLocale]\n if (!msgs) return undefined\n return msgs[key]\n },\n [loadedMessages, currentLocale],\n )\n\n return useMemo(\n () => ({\n t: i18n.t.bind(i18n),\n d: i18n.d.bind(i18n),\n n: i18n.n.bind(i18n),\n locale: currentLocale,\n setLocale: handleSetLocale,\n isLoading,\n preloadLocale,\n te,\n tm,\n i18n,\n format: i18n.format.bind(i18n),\n loadMessages: i18n.loadMessages.bind(i18n),\n getLocales: i18n.getLocales.bind(i18n),\n loadedLocales,\n }),\n [i18n, currentLocale, handleSetLocale, isLoading, preloadLocale, te, tm, loadedLocales],\n )\n}\n","import { createContext } from 'react'\nimport type { FluentiContext } from './types'\n\nexport const I18nContext = createContext<FluentiContext | null>(null)\n","import type { FluentiCoreInstanceFull } from '@fluenti/core'\n\n/**\n * Global i18n instance registry.\n *\n * Used by `@fluenti/next` webpack loader and `@fluenti/vite-plugin` to access\n * the i18n instance from module-level code via a Proxy. The instance is set by\n * `<I18nProvider>` on mount.\n */\n\ndeclare global {\n // eslint-disable-next-line no-var\n var __fluenti_i18n: FluentiCoreInstanceFull | undefined\n}\n\n/** Get the global i18n instance (set by `<I18nProvider>`). */\nexport function getGlobalI18n(): FluentiCoreInstanceFull | undefined {\n return globalThis.__fluenti_i18n\n}\n\n/** Set the global i18n instance. Called by `<I18nProvider>` on mount. */\nexport function setGlobalI18n(instance: FluentiCoreInstanceFull): void {\n globalThis.__fluenti_i18n = instance\n}\n\n/** Clear the global i18n instance. Primarily for testing. */\nexport function clearGlobalI18n(): void {\n globalThis.__fluenti_i18n = undefined\n}\n","import { useState, useCallback, useEffect, useMemo, useRef } from 'react'\nimport { createFluentiCore } from '@fluenti/core'\nimport type { Messages } from '@fluenti/core'\nimport { I18nContext } from './context'\nimport type { FluentiProviderProps, FluentiContext } from './types'\nimport type { FluentiInstance } from './create-fluenti'\nimport { setGlobalI18n } from './global-registry'\n\ninterface SplitRuntimeModule {\n __switchLocale?: (locale: string) => Promise<void>\n __preloadLocale?: (locale: string) => Promise<void>\n}\n\nfunction unwrapMessages(allMessages: Record<string, unknown>): Record<string, Messages> {\n const result: Record<string, Messages> = {}\n for (const [locale, msgs] of Object.entries(allMessages)) {\n result[locale] = typeof msgs === 'object' && msgs !== null && 'default' in msgs\n ? (msgs as { default: Messages }).default\n : msgs as Messages\n }\n return result\n}\n\nconst SPLIT_RUNTIME_KEY = Symbol.for('fluenti.runtime.react.v1')\n\nfunction getSplitRuntimeModule(): SplitRuntimeModule | null {\n const runtime = (globalThis as Record<PropertyKey, unknown>)[SPLIT_RUNTIME_KEY]\n return typeof runtime === 'object' && runtime !== null\n ? runtime as SplitRuntimeModule\n : null\n}\n\n/**\n * Internal provider that uses a pre-created `FluentiInstance`.\n */\nfunction InstanceProvider({ instance, children }: { instance: FluentiInstance; children: React.ReactNode }) {\n const ctx: FluentiContext = useMemo(\n () => ({\n t: instance.t,\n d: instance.d,\n n: instance.n,\n format: instance.format,\n loadMessages: instance.loadMessages,\n getLocales: instance.getLocales,\n locale: instance.locale,\n setLocale: instance.setLocale,\n isLoading: instance.isLoading,\n loadedLocales: instance.loadedLocales,\n preloadLocale: instance.preloadLocale,\n te: instance.te,\n tm: instance.tm,\n // Internal: used by __useI18n hook and compiled components — not part of public API\n i18n: instance.i18n,\n }) as FluentiContext,\n [instance],\n )\n\n return <I18nContext.Provider value={ctx}>{children}</I18nContext.Provider>\n}\n\nexport function I18nProvider(props: FluentiProviderProps) {\n if (props.instance) {\n return <InstanceProvider instance={props.instance}>{props.children}</InstanceProvider>\n }\n\n return <InlineProvider {...props} />\n}\n\n/**\n * Original inline provider that manages its own state.\n */\nfunction InlineProvider({\n locale: localeProp,\n fallbackLocale,\n messages,\n loadMessages,\n fallbackChain,\n dateFormats,\n numberFormats,\n missing,\n diagnostics,\n children,\n}: FluentiProviderProps) {\n const locale = localeProp ?? 'en'\n\n const [currentLocale, setCurrentLocale] = useState(locale)\n const [isLoading, setIsLoading] = useState(false)\n const [loadedMessages, setLoadedMessages] = useState<Record<string, Messages>>(\n messages ? unwrapMessages(messages) : {},\n )\n const [loadedLocales, setLoadedLocales] = useState<string[]>(\n messages ? Object.keys(messages) : [],\n )\n\n // Use ref to avoid stale closures in callbacks\n const loadedMessagesRef = useRef(loadedMessages)\n loadedMessagesRef.current = loadedMessages\n\n // Guard against out-of-order async locale loads (race condition protection)\n const localeRequestRef = useRef(0)\n\n // Deduplicates concurrent preloadLocale() calls for the same locale\n const preloadInFlightRef = useRef(new Set<string>())\n\n const i18n = useMemo(() => {\n const config: Parameters<typeof createFluentiCore>[0] = {\n locale: currentLocale,\n messages: loadedMessages,\n }\n if (fallbackLocale !== undefined) config.fallbackLocale = fallbackLocale\n if (fallbackChain !== undefined) config.fallbackChain = fallbackChain\n if (dateFormats !== undefined) config.dateFormats = dateFormats\n if (numberFormats !== undefined) config.numberFormats = numberFormats\n if (missing !== undefined) config.missing = missing\n if (diagnostics !== undefined) config.diagnostics = diagnostics\n return createFluentiCore(config)\n }, [currentLocale, loadedMessages, fallbackLocale, fallbackChain, dateFormats, numberFormats, missing, diagnostics])\n\n // Set global i18n instance for webpack loader / vite plugin access\n useEffect(() => {\n setGlobalI18n(i18n)\n }, [i18n])\n\n // Sync external locale prop changes\n useEffect(() => {\n if (locale !== currentLocale) {\n void handleSetLocale(locale)\n }\n // Intentionally only depend on `locale` — we want to sync when the\n // external prop changes, not when internal state (`currentLocale`,\n // `handleSetLocale`) updates, which would cause infinite re-renders.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [locale])\n\n const handleSetLocale = useCallback(\n async (newLocale: string) => {\n const requestId = ++localeRequestRef.current\n\n if (loadedMessagesRef.current[newLocale] && !loadMessages) {\n setCurrentLocale(newLocale)\n return\n }\n\n const splitRuntime = loadMessages ? getSplitRuntimeModule() : null\n\n if (loadedMessagesRef.current[newLocale]) {\n if (splitRuntime?.__switchLocale) {\n await splitRuntime.__switchLocale(newLocale)\n }\n setCurrentLocale(newLocale)\n return\n }\n\n if (!loadMessages) {\n console.warn(\n `[fluenti] No messages for locale \"${newLocale}\" and no loadMessages function provided`,\n )\n return\n }\n\n setIsLoading(true)\n try {\n const msgs = await loadMessages(newLocale)\n\n // A newer request has superseded this one — discard stale result\n if (requestId !== localeRequestRef.current) return\n\n const resolved: Messages =\n typeof msgs === 'object' && msgs !== null && 'default' in msgs\n ? (msgs as { default: Messages }).default\n : (msgs as Messages)\n // Run __switchLocale before committing state so a failure leaves no partial state.\n // If it throws, loadedMessages stays clean and the next setLocale() retries the full path.\n if (splitRuntime?.__switchLocale) {\n await splitRuntime.__switchLocale(newLocale)\n }\n // Re-check request ID after the async __switchLocale call\n if (requestId !== localeRequestRef.current) return\n setLoadedMessages((prev) => ({ ...prev, [newLocale]: resolved }))\n setLoadedLocales((prev) => [...new Set([...prev, newLocale])])\n setCurrentLocale(newLocale)\n } catch (err) {\n // Only log if this request is still the latest\n if (requestId === localeRequestRef.current) {\n console.error(`[fluenti] Failed to load locale \"${newLocale}\"`, err)\n }\n } finally {\n if (requestId === localeRequestRef.current) {\n setIsLoading(false)\n }\n }\n },\n [loadMessages],\n )\n\n const preloadLocale = useCallback(\n async (loc: string) => {\n const splitRuntime = getSplitRuntimeModule()\n if (loadedMessagesRef.current[loc] || !loadMessages) return\n // Deduplicate concurrent preload calls for the same locale\n if (preloadInFlightRef.current.has(loc)) return\n preloadInFlightRef.current.add(loc)\n try {\n const msgs = await loadMessages(loc)\n const resolved: Messages =\n typeof msgs === 'object' && msgs !== null && 'default' in msgs\n ? (msgs as { default: Messages }).default\n : (msgs as Messages)\n setLoadedMessages((prev) => ({ ...prev, [loc]: resolved }))\n setLoadedLocales((prev) => [...new Set([...prev, loc])])\n if (splitRuntime?.__preloadLocale) {\n await splitRuntime.__preloadLocale(loc)\n }\n } catch (e: unknown) {\n console.warn('[fluenti] preload failed:', loc, e)\n } finally {\n preloadInFlightRef.current.delete(loc)\n }\n },\n [loadMessages],\n )\n\n const te = useCallback(\n (key: string, loc?: string): boolean => {\n const msgs = loadedMessagesRef.current[loc ?? currentLocale]\n return msgs !== undefined && key in msgs\n },\n [currentLocale],\n )\n\n const tm = useCallback(\n (key: string, loc?: string): Messages[string] | undefined => {\n const msgs = loadedMessagesRef.current[loc ?? currentLocale]\n if (!msgs) return undefined\n return msgs[key]\n },\n [currentLocale],\n )\n\n const ctx = useMemo(\n () => ({\n t: i18n.t.bind(i18n),\n d: i18n.d.bind(i18n),\n n: i18n.n.bind(i18n),\n format: i18n.format.bind(i18n),\n loadMessages: i18n.loadMessages.bind(i18n),\n getLocales: i18n.getLocales.bind(i18n),\n locale: currentLocale,\n setLocale: handleSetLocale,\n isLoading,\n loadedLocales,\n preloadLocale,\n te,\n tm,\n // Internal: used by __useI18n hook and compiled components — not part of public API\n i18n,\n }) as FluentiContext,\n [i18n, currentLocale, handleSetLocale, isLoading, loadedLocales, preloadLocale, te, tm],\n )\n\n return <I18nContext.Provider value={ctx}>{children}</I18nContext.Provider>\n}\n","import { useContext } from 'react'\nimport { I18nContext } from '../context'\nimport type { FluentiContext } from '../types'\n\n/**\n * Primary hook for accessing i18n functions.\n *\n * Returns locale, setLocale, isLoading, loadedLocales, preloadLocale,\n * and the underlying i18n instance with t(), d(), n() methods.\n *\n * @throws If used outside of `<I18nProvider>`\n */\nexport function useI18n(): FluentiContext {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error(\n '[fluenti] useI18n() must be used within an <I18nProvider>. ' +\n 'Wrap your app with <I18nProvider> to provide i18n context.',\n )\n }\n return ctx\n}\n","import type { CompileTimeT } from '@fluenti/core'\n\nexport const t: CompileTimeT = ((..._args: unknown[]) => {\n throw new Error(\n \"[fluenti] `t` imported from '@fluenti/react' is a compile-time API. \" +\n 'Use it only with the Fluenti build transform inside a component or custom hook. ' +\n 'For runtime lookups, use useI18n().t(...).',\n )\n}) as CompileTimeT\n","import {\n createElement,\n memo,\n useContext,\n useMemo,\n type ReactElement,\n type ReactNode,\n} from 'react'\nimport { I18nContext } from '../context'\nimport { hashMessage, extractMessage, reconstruct } from './trans-core'\n\nexport interface FluentiTransProps {\n /** Source text with embedded components */\n children: ReactNode\n /** Override auto-generated hash ID */\n id?: string\n /** Message context used for identity and translator disambiguation */\n context?: string\n /** Context comment for translators */\n comment?: string\n /** Wrapper element tag name (e.g. 'span', 'div'). Defaults to Fragment (no wrapper). */\n tag?: keyof React.JSX.IntrinsicElements\n /** Custom render wrapper */\n render?: (translation: ReactNode) => ReactNode\n /** @internal Pre-computed message ID from build plugin */\n __id?: string\n /** @internal Pre-computed ICU message from build plugin */\n __message?: string\n /** @internal Pre-computed component list from build plugin */\n __components?: ReactElement[]\n}\n\n/**\n * `<Trans>` component for rich-text translations containing nested React elements.\n *\n * @example\n * ```tsx\n * <Trans>Read the <a href=\"/docs\">documentation</a> for more info.</Trans>\n * ```\n */\nexport const Trans = memo(function Trans({\n children,\n id,\n context,\n comment,\n tag,\n render,\n __id,\n __message,\n __components,\n}: FluentiTransProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Trans> must be used within an <I18nProvider>')\n }\n\n // Fast path: build plugin pre-computed message and components\n const hasPrecomputed = __message !== undefined\n\n const { message, components } = useMemo(\n () => hasPrecomputed\n ? { message: __message!, components: __components ?? [] }\n : extractMessage(children),\n [hasPrecomputed, __message, __components, children],\n )\n const messageId = useMemo(\n () => id ?? __id ?? hashMessage(message, context),\n [id, __id, message, context],\n )\n\n const translated = ctx.t(\n {\n id: messageId,\n message,\n ...(context !== undefined ? { context } : {}),\n ...(comment !== undefined ? { comment } : {}),\n },\n )\n\n const result = reconstruct(translated, components)\n if (render) return render(result)\n return tag ? createElement(tag, null, result) : <>{result}</>\n})\n","import { memo, useContext, type ReactNode } from 'react'\nimport { hashMessage } from '@fluenti/core/internal'\nimport { I18nContext } from '../context'\nimport { PLURAL_CATEGORIES, type PluralCategory } from './plural-core'\nimport { buildICUPluralMessage, renderRichTranslation, serializeRichForms } from './icu-rich'\n\nexport interface FluentiPluralProps {\n /** The count value */\n value: number\n /** Override the auto-generated synthetic ICU message id */\n id?: string\n /** Message context used for identity and translator disambiguation */\n context?: string\n /** Translator-facing note preserved in extraction catalogs */\n comment?: string\n /** Text for zero (if language supports) */\n zero?: ReactNode\n /** Singular form. `#` replaced with value */\n one?: ReactNode\n /** Dual form (Arabic, etc.) */\n two?: ReactNode\n /** Few form (Slavic languages, etc.) */\n few?: ReactNode\n /** Many form */\n many?: ReactNode\n /** Default plural form */\n other: ReactNode\n /** Offset from value before selecting form */\n offset?: number\n}\n\n/**\n * `<Plural>` — ICU plural handling as a component.\n *\n * @example\n * ```tsx\n * <Plural value={count} zero=\"No messages\" one=\"# message\" other=\"# messages\" />\n * ```\n */\nexport const Plural = memo(function Plural({\n value,\n id,\n context,\n comment,\n zero,\n one,\n two,\n few,\n many,\n other,\n offset,\n}: FluentiPluralProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Plural> must be used within an <I18nProvider>')\n }\n\n const forms: Record<PluralCategory, ReactNode | undefined> = {\n zero,\n one,\n two,\n few,\n many,\n other,\n }\n const { messages, components } = serializeRichForms(PLURAL_CATEGORIES, forms)\n const icuMessage = buildICUPluralMessage(\n {\n ...(messages.zero !== undefined && { zero: messages.zero }),\n ...(messages.one !== undefined && { one: messages.one }),\n ...(messages.two !== undefined && { two: messages.two }),\n ...(messages.few !== undefined && { few: messages.few }),\n ...(messages.many !== undefined && { many: messages.many }),\n other: messages.other ?? '',\n },\n offset,\n )\n\n const descriptor = {\n id: id ?? (context === undefined ? icuMessage : hashMessage(icuMessage, context)),\n message: icuMessage,\n ...(context !== undefined ? { context } : {}),\n ...(comment !== undefined ? { comment } : {}),\n }\n\n return <>{renderRichTranslation(descriptor, { count: value }, (desc, values) => ctx.t(desc, values), components)}</>\n})\n","import { createElement, memo, useContext, type ReactNode } from 'react'\nimport { hashMessage } from '@fluenti/core/internal'\nimport { I18nContext } from '../context'\nimport { buildICUSelectMessage, normalizeSelectForms, renderRichTranslation, serializeRichForms } from './icu-rich'\n\nexport interface FluentiSelectProps {\n /** The selector value */\n value: string\n /** Override the auto-generated synthetic ICU message id */\n id?: string\n /** Message context used for identity and translator disambiguation */\n context?: string\n /** Translator-facing note preserved in extraction catalogs */\n comment?: string\n /** Default case */\n other: ReactNode\n /** Type-safe named options. Takes precedence over direct case props. */\n options?: Record<string, ReactNode>\n /** Wrapper element tag name (e.g. 'span', 'div'). Defaults to Fragment (no wrapper). */\n tag?: keyof React.JSX.IntrinsicElements\n /** Named cases — any string key maps to a ReactNode */\n [key: string]: ReactNode | Record<string, ReactNode> | keyof React.JSX.IntrinsicElements | undefined\n}\n\n/**\n * `<Select>` — ICU select for gender, role, or other categorical values.\n *\n * @example\n * ```tsx\n * <Select\n * value={gender}\n * male=\"He liked your post\"\n * female=\"She liked your post\"\n * other=\"They liked your post\"\n * />\n * ```\n */\nexport const Select = memo(function Select(props: FluentiSelectProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Select> must be used within an <I18nProvider>')\n }\n\n const { value, id, context, comment, other, options, tag, ...cases } = props\n const forms: Record<string, ReactNode | undefined> = options === undefined\n ? {\n ...Object.fromEntries(\n Object.entries(cases).filter(([key]) => !['value', 'id', 'context', 'comment', 'options', 'other', 'tag'].includes(key)),\n ),\n other,\n }\n : {\n ...options,\n other,\n }\n\n const orderedKeys = [...Object.keys(forms).filter(key => key !== 'other'), 'other'] as const\n const { messages, components } = serializeRichForms(orderedKeys, forms)\n const normalized = normalizeSelectForms(\n Object.fromEntries(\n [...orderedKeys].map((key) => [key, messages[key] ?? '']),\n ),\n )\n const icuMessage = buildICUSelectMessage(normalized.forms)\n\n const descriptor = {\n id: id ?? (context === undefined ? icuMessage : hashMessage(icuMessage, context)),\n message: icuMessage,\n ...(context !== undefined ? { context } : {}),\n ...(comment !== undefined ? { comment } : {}),\n }\n\n const result = renderRichTranslation(\n descriptor,\n { value: normalized.valueMap[value] ?? 'other' },\n (desc, values) => ctx.t(desc, values),\n components,\n )\n return tag ? createElement(tag, null, result) : <>{result}</>\n})\n","import { memo, useContext } from 'react'\nimport { I18nContext } from '../context'\n\nexport interface FluentiDateTimeProps {\n /** Date value to format */\n value: Date | number\n /** Named format key defined in dateFormats config */\n format?: string\n}\n\n/**\n * `<DateTime>` — formatting component using Intl APIs.\n *\n * @example\n * ```tsx\n * <DateTime value={new Date()} format=\"long\" />\n * ```\n */\nexport const DateTime = memo(function DateTime({ value, format }: FluentiDateTimeProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <DateTime> must be used within an <I18nProvider>')\n }\n return <>{ctx.d(value, format)}</>\n})\n","import { memo, useContext } from 'react'\nimport { I18nContext } from '../context'\n\nexport interface NumberFormatProps {\n /** Number value to format */\n value: number\n /** Named format key defined in numberFormats config */\n format?: string\n}\n\n/** @alias NumberFormatProps */\nexport type FluentiNumberFormatProps = NumberFormatProps\n\n/**\n * `<Number>` — number formatting component using Intl APIs.\n *\n * @example\n * ```tsx\n * <Number value={1234.56} format=\"currency\" />\n * ```\n */\nexport const NumberFormat = memo(function NumberFormat({ value, format }: NumberFormatProps) {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error('[fluenti] <Number> must be used within an <I18nProvider>')\n }\n return <>{ctx.n(value, format)}</>\n})\n"],"mappings":"gPA4EA,SAAS,EAAe,EAAgE,CACtF,IAAM,EAAmC,EAAE,CAC3C,IAAK,GAAM,CAAC,EAAQ,KAAS,OAAO,QAAQ,EAAY,CACtD,EAAO,GAAU,OAAO,GAAS,UAAY,GAAiB,YAAa,EACtE,EAA+B,QAChC,EAEN,OAAO,EAyBT,SAAgB,EAAc,EAAwC,CACpE,GAAM,CACJ,OAAQ,EACR,SAAU,EACV,aAAc,EACd,iBACA,gBACA,cACA,gBACA,WACE,EAEE,CAAC,EAAe,IAAA,EAAA,EAAA,UAA6B,EAAc,CAC3D,CAAC,EAAW,IAAA,EAAA,EAAA,UAAyB,GAAM,CAC3C,CAAC,EAAgB,IAAA,EAAA,EAAA,UACrB,EAAkB,EAAe,EAAgB,CAAG,EAAE,CACvD,CACK,CAAC,EAAe,IAAA,EAAA,EAAA,UACpB,EAAkB,OAAO,KAAK,EAAgB,CAAG,EAAE,CACpD,CAEK,GAAA,EAAA,EAAA,QAA2B,EAAe,CAChD,EAAkB,QAAU,EAE5B,IAAM,GAAA,EAAA,EAAA,QAA0B,EAAE,CAE5B,GAAA,EAAA,EAAA,aAAqB,CACzB,IAAM,EAA+C,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EAAA,SAAA,CAAA,SAAG,EAAI,EAAE,EAAO,EAAO,CAAI,CAAA,EAClC,CCHW,GAAA,EAAA,EAAA,MAAoB,SAAsB,CAAE,QAAO,UAA6B,CAC3F,IAAM,GAAA,EAAA,EAAA,YAAiB,EAAY,CACnC,GAAI,CAAC,EACH,MAAU,MAAM,2DAA2D,CAE7E,OAAO,EAAA,EAAA,KAAA,EAAA,SAAA,CAAA,SAAG,EAAI,EAAE,EAAO,EAAO,CAAI,CAAA,EAClC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/create-fluenti.ts","../src/global-registry.ts","../src/provider.tsx","../src/hooks/useI18n.ts","../src/compile-time-t.ts"],"sourcesContent":["import { useState, useCallback, useEffect, useMemo, useRef } from 'react'\nimport { createFluentiCore } from '@fluenti/core'\nimport type {\n FluentiCoreInstanceFull as FluentInstanceExtended,\n CompiledMessage,\n Locale,\n Messages,\n AllMessages,\n DateFormatOptions,\n NumberFormatOptions,\n LocalizedString,\n MessageDescriptor,\n} from '@fluenti/core'\n\n/**\n * Configuration for `createFluenti()`.\n */\nexport interface FluentiConfig {\n /** Active locale code */\n locale: string\n /** Static message catalogs keyed by locale */\n messages?: AllMessages | undefined\n /** Async loader for lazy-loading locale messages */\n loadMessages?: ((locale: string) => Promise<Messages | { default: Messages }>) | undefined\n /** Fallback locale when a translation is missing */\n fallbackLocale?: string | undefined\n /** Custom fallback chains per locale */\n fallbackChain?: Record<string, string[]> | undefined\n /** Date format styles */\n dateFormats?: DateFormatOptions | undefined\n /** Number format styles */\n numberFormats?: NumberFormatOptions | undefined\n /** Missing message handler */\n missing?: ((locale: Locale, id: string) => string | undefined) | undefined\n /** Runtime diagnostics (pre-created instance or config) */\n diagnostics?: unknown | undefined\n /** Custom interpolation function for full ICU support at runtime */\n interpolate?: ((message: string, values: Record<string, unknown> | undefined, locale: string, formatters?: Record<string, unknown>) => string) | undefined\n}\n\n/**\n * The object returned by `createFluenti()`.\n *\n * Contains all i18n state and methods. Pass to `<I18nProvider instance={...}>`\n * or use directly in tests/non-React contexts.\n */\nexport interface FluentiInstance {\n /** Translate a message by id with optional interpolation values */\n t: {\n (id: string | MessageDescriptor, values?: Record<string, unknown>): LocalizedString\n (strings: TemplateStringsArray, ...exprs: unknown[]): LocalizedString\n }\n /** Format a date value for the current locale */\n d: (value: Date | number, style?: string) => LocalizedString\n /** Format a number value for the current locale */\n n: (value: number, style?: string) => LocalizedString\n /** Current locale */\n locale: string\n /** Change the active locale (async when lazy loading) */\n setLocale: (locale: string) => Promise<void>\n /** Whether a locale is currently being loaded */\n isLoading: boolean\n /** Preload a locale in the background without switching to it */\n preloadLocale: (locale: string) => Promise<void>\n /** Check whether a translation key exists for the given or current locale */\n te: (key: string, locale?: string) => boolean\n /** Get the raw compiled message for a key without interpolation */\n tm: (key: string, locale?: string) => CompiledMessage | undefined\n /** The underlying Fluent instance (escape hatch for advanced use) */\n i18n: FluentInstanceExtended\n /** Format an ICU message string directly (no catalog lookup) */\n format: (message: string, values?: Record<string, unknown>) => LocalizedString\n /** Merge additional messages into a locale catalog at runtime */\n loadMessages: (locale: string, messages: Messages) => void\n /** Return all locale codes that have loaded messages */\n getLocales: () => string[]\n /** Set of locales whose messages have been loaded */\n loadedLocales: string[]\n}\n\nfunction unwrapMessages(allMessages: Record<string, unknown>): Record<string, Messages> {\n const result: Record<string, Messages> = {}\n for (const [locale, msgs] of Object.entries(allMessages)) {\n result[locale] = typeof msgs === 'object' && msgs !== null && 'default' in msgs\n ? (msgs as { default: Messages }).default\n : msgs as Messages\n }\n return result\n}\n\n/**\n * Create a standalone Fluenti i18n instance.\n *\n * This is a React hook that manages locale state, message loading, and\n * provides all i18n methods. The returned instance can be passed to\n * `<I18nProvider instance={...}>` to share it with the component tree.\n *\n * @example\n * ```tsx\n * function App() {\n * const i18n = createFluenti({\n * locale: 'en',\n * messages: { en: enMessages, fr: frMessages },\n * })\n * return (\n * <I18nProvider instance={i18n}>\n * <MyApp />\n * </I18nProvider>\n * )\n * }\n * ```\n */\nexport function createFluenti(config: FluentiConfig): FluentiInstance {\n const {\n locale: initialLocale,\n messages: initialMessages,\n loadMessages: loadMessagesFn,\n fallbackLocale,\n fallbackChain,\n dateFormats,\n numberFormats,\n missing,\n diagnostics,\n interpolate,\n } = config\n\n const [currentLocale, setCurrentLocale] = useState(initialLocale)\n const [isLoading, setIsLoading] = useState(false)\n const [loadedMessages, setLoadedMessages] = useState<Record<string, Messages>>(\n initialMessages ? unwrapMessages(initialMessages) : {},\n )\n const [loadedLocales, setLoadedLocales] = useState<string[]>(\n initialMessages ? Object.keys(initialMessages) : [],\n )\n\n const loadedMessagesRef = useRef(loadedMessages)\n loadedMessagesRef.current = loadedMessages\n\n const localeRequestRef = useRef(0)\n\n // Split runtime integration (for Vite plugin code splitting)\n const SPLIT_RUNTIME_KEY = Symbol.for('fluenti.runtime.react.v1')\n function getSplitRuntime(): { __switchLocale?: (l: string) => Promise<void>; __preloadLocale?: (l: string) => Promise<void> } | null {\n const rt = (globalThis as Record<PropertyKey, unknown>)[SPLIT_RUNTIME_KEY]\n return typeof rt === 'object' && rt !== null ? rt as any : null\n }\n\n const i18n = useMemo(() => {\n const cfg: Parameters<typeof createFluentiCore>[0] = {\n locale: currentLocale,\n messages: loadedMessages,\n }\n if (fallbackLocale !== undefined) cfg.fallbackLocale = fallbackLocale\n if (fallbackChain !== undefined) cfg.fallbackChain = fallbackChain\n if (dateFormats !== undefined) cfg.dateFormats = dateFormats\n if (numberFormats !== undefined) cfg.numberFormats = numberFormats\n if (missing !== undefined) cfg.missing = missing\n if (diagnostics !== undefined) cfg.diagnostics = diagnostics as Parameters<typeof createFluentiCore>[0]['diagnostics']\n if (interpolate !== undefined) cfg.interpolate = interpolate\n return createFluentiCore(cfg)\n }, [currentLocale, loadedMessages, fallbackLocale, fallbackChain, dateFormats, numberFormats, missing, diagnostics, interpolate])\n\n // Sync external locale changes\n useEffect(() => {\n if (initialLocale !== currentLocale) {\n void handleSetLocale(initialLocale)\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [initialLocale])\n\n const handleSetLocale = useCallback(\n async (newLocale: string) => {\n const requestId = ++localeRequestRef.current\n\n const splitRuntime = loadMessagesFn ? getSplitRuntime() : null\n\n if (loadedMessagesRef.current[newLocale] && !loadMessagesFn) {\n setCurrentLocale(newLocale)\n return\n }\n\n if (loadedMessagesRef.current[newLocale]) {\n try {\n if (splitRuntime?.__switchLocale) {\n await splitRuntime.__switchLocale(newLocale)\n }\n } catch (e) {\n console.warn(`[fluenti] split runtime switch failed for locale \"${newLocale}\"`, e)\n }\n setCurrentLocale(newLocale)\n return\n }\n\n if (!loadMessagesFn) {\n console.warn(\n `[fluenti] No messages for locale \"${newLocale}\" and no loadMessages function provided`,\n )\n return\n }\n\n setIsLoading(true)\n try {\n const msgs = await loadMessagesFn(newLocale)\n if (requestId !== localeRequestRef.current) return\n\n const resolved: Messages =\n typeof msgs === 'object' && msgs !== null && 'default' in msgs\n ? (msgs as { default: Messages }).default\n : (msgs as Messages)\n try {\n if (splitRuntime?.__switchLocale) {\n await splitRuntime.__switchLocale(newLocale)\n }\n } catch (e) {\n console.warn(`[fluenti] split runtime switch failed for locale \"${newLocale}\"`, e)\n }\n if (requestId !== localeRequestRef.current) return\n setLoadedMessages((prev) => ({ ...prev, [newLocale]: resolved }))\n setLoadedLocales((prev) => [...new Set([...prev, newLocale])])\n setCurrentLocale(newLocale)\n } catch (err) {\n if (requestId === localeRequestRef.current) {\n console.error(`[fluenti] Failed to load locale \"${newLocale}\"`, err)\n }\n } finally {\n if (requestId === localeRequestRef.current) {\n setIsLoading(false)\n }\n }\n },\n [loadMessagesFn],\n )\n\n const preloadLocale = useCallback(\n async (loc: string) => {\n if (loadedMessagesRef.current[loc] || !loadMessagesFn) return\n try {\n const msgs = await loadMessagesFn(loc)\n const resolved: Messages =\n typeof msgs === 'object' && msgs !== null && 'default' in msgs\n ? (msgs as { default: Messages }).default\n : (msgs as Messages)\n setLoadedMessages((prev) => ({ ...prev, [loc]: resolved }))\n setLoadedLocales((prev) => [...new Set([...prev, loc])])\n const splitRuntime = getSplitRuntime()\n if (splitRuntime?.__preloadLocale) {\n await splitRuntime.__preloadLocale(loc)\n }\n } catch {\n // Silent fail for preload\n }\n },\n [loadMessagesFn],\n )\n\n const te = useCallback(\n (key: string, loc?: string): boolean => {\n const msgs = loadedMessages[loc ?? currentLocale]\n return msgs !== undefined && key in msgs\n },\n [loadedMessages, currentLocale],\n )\n\n const tm = useCallback(\n (key: string, loc?: string): Messages[string] | undefined => {\n const msgs = loadedMessages[loc ?? currentLocale]\n if (!msgs) return undefined\n return msgs[key]\n },\n [loadedMessages, currentLocale],\n )\n\n return useMemo(\n () => ({\n t: i18n.t.bind(i18n),\n d: i18n.d.bind(i18n),\n n: i18n.n.bind(i18n),\n locale: currentLocale,\n setLocale: handleSetLocale,\n isLoading,\n preloadLocale,\n te,\n tm,\n i18n,\n format: i18n.format.bind(i18n),\n loadMessages: i18n.loadMessages.bind(i18n),\n getLocales: i18n.getLocales.bind(i18n),\n loadedLocales,\n }),\n [i18n, currentLocale, handleSetLocale, isLoading, preloadLocale, te, tm, loadedLocales],\n )\n}\n","import type { FluentiCoreInstanceFull } from '@fluenti/core'\n\n/**\n * Global i18n instance registry.\n *\n * Used by `@fluenti/next` webpack loader and `@fluenti/vite-plugin` to access\n * the i18n instance from module-level code via a Proxy. The instance is set by\n * `<I18nProvider>` on mount.\n */\n\ndeclare global {\n // eslint-disable-next-line no-var\n var __fluenti_i18n: FluentiCoreInstanceFull | undefined\n}\n\n/** Get the global i18n instance (set by `<I18nProvider>`). */\nexport function getGlobalI18n(): FluentiCoreInstanceFull | undefined {\n return globalThis.__fluenti_i18n\n}\n\n/** Set the global i18n instance. Called by `<I18nProvider>` on mount. */\nexport function setGlobalI18n(instance: FluentiCoreInstanceFull): void {\n globalThis.__fluenti_i18n = instance\n}\n\n/** Clear the global i18n instance. Primarily for testing. */\nexport function clearGlobalI18n(): void {\n globalThis.__fluenti_i18n = undefined\n}\n","import { useEffect, useMemo } from 'react'\nimport { I18nContext } from './context'\nimport type { FluentiProviderProps, FluentiContext } from './types'\nimport type { FluentiInstance } from './create-fluenti'\nimport { createFluenti } from './create-fluenti'\nimport { setGlobalI18n } from './global-registry'\n\n/**\n * Internal provider that uses a pre-created `FluentiInstance`.\n */\nfunction InstanceProvider({ instance, children }: { instance: FluentiInstance; children: React.ReactNode }) {\n const ctx: FluentiContext = useMemo(\n () => ({\n t: instance.t,\n d: instance.d,\n n: instance.n,\n format: instance.format,\n loadMessages: instance.loadMessages,\n getLocales: instance.getLocales,\n locale: instance.locale,\n setLocale: instance.setLocale,\n isLoading: instance.isLoading,\n loadedLocales: instance.loadedLocales,\n preloadLocale: instance.preloadLocale,\n te: instance.te,\n tm: instance.tm,\n // Internal: used by __useI18n hook and compiled components — not part of public API\n i18n: instance.i18n,\n }) as FluentiContext,\n [instance],\n )\n\n return <I18nContext.Provider value={ctx}>{children}</I18nContext.Provider>\n}\n\n/**\n * Provides the Fluenti i18n context to the React component tree.\n *\n * Accepts either a `locale` + `messages` pair for inline configuration,\n * or a pre-created `instance` from `createFluenti()`.\n *\n * @example\n * ```tsx\n * import { I18nProvider, useI18n } from '@fluenti/react'\n * import messages from './locales/compiled/en.js'\n *\n * function App() {\n * return (\n * <I18nProvider locale=\"en\" messages={{ en: messages }}>\n * <Content />\n * </I18nProvider>\n * )\n * }\n *\n * function Content() {\n * const { t } = useI18n()\n * return <h1>{t`Welcome to our app`}</h1>\n * }\n * ```\n *\n * @example Using a pre-created instance\n * ```tsx\n * import { I18nProvider, createFluenti } from '@fluenti/react'\n * import messages from './locales/compiled/en.js'\n *\n * const i18n = createFluenti({ locale: 'en', messages: { en: messages } })\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Content />\n * </I18nProvider>\n * )\n * }\n * ```\n */\nexport function I18nProvider(props: FluentiProviderProps) {\n if (props.instance) {\n return <InstanceProvider instance={props.instance}>{props.children}</InstanceProvider>\n }\n\n return <InlineProvider {...props} />\n}\n\n/**\n * Inline provider that delegates to `createFluenti()` for state management.\n */\nfunction InlineProvider({\n locale,\n fallbackLocale,\n messages,\n loadMessages,\n fallbackChain,\n dateFormats,\n numberFormats,\n missing,\n diagnostics,\n interpolate,\n children,\n}: FluentiProviderProps) {\n const instance = createFluenti({\n locale: locale ?? 'en',\n messages,\n loadMessages,\n fallbackLocale,\n fallbackChain,\n dateFormats,\n numberFormats,\n missing,\n diagnostics,\n interpolate,\n })\n\n // Set global i18n instance for webpack loader / vite plugin access\n useEffect(() => {\n setGlobalI18n(instance.i18n)\n }, [instance.i18n])\n\n return <InstanceProvider instance={instance}>{children}</InstanceProvider>\n}\n","import { useContext } from 'react'\nimport { I18nContext } from '../context'\nimport type { FluentiContext } from '../types'\n\n/**\n * Primary hook for accessing i18n functions.\n *\n * Returns locale, setLocale, isLoading, loadedLocales, preloadLocale,\n * and the underlying i18n instance with t(), d(), n() methods.\n *\n * @throws If used outside of `<I18nProvider>`\n */\nexport function useI18n(): FluentiContext {\n const ctx = useContext(I18nContext)\n if (!ctx) {\n throw new Error(\n '[fluenti] useI18n() must be used within an <I18nProvider>. ' +\n 'Wrap your app with <I18nProvider> to provide i18n context.',\n )\n }\n return ctx\n}\n","import type { CompileTimeT } from '@fluenti/core'\n\nexport const t: CompileTimeT = ((..._args: unknown[]) => {\n throw new Error(\n \"[fluenti] `t` imported from '@fluenti/react' is a compile-time API. \" +\n 'Use it only with the Fluenti build transform inside a component or custom hook. ' +\n 'For runtime lookups, use useI18n().t(...).',\n )\n}) as CompileTimeT\n"],"mappings":"2MAgFA,SAAS,EAAe,EAAgE,CACtF,IAAM,EAAmC,EAAE,CAC3C,IAAK,GAAM,CAAC,EAAQ,KAAS,OAAO,QAAQ,EAAY,CACtD,EAAO,GAAU,OAAO,GAAS,UAAY,GAAiB,YAAa,EACtE,EAA+B,QAChC,EAEN,OAAO,EAyBT,SAAgB,EAAc,EAAwC,CACpE,GAAM,CACJ,OAAQ,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AM,WAAgC,CAAA,CA4C5E,SAAgB,EAAa,EAA6B,CAKxD,OAJI,EAAM,UACD,EAAA,EAAA,KAAC,EAAD,CAAkB,SAAU,EAAM,kBAAW,EAAM,SAA4B,CAAA,EAGjF,EAAA,EAAA,KAAC,EAAD,CAAgB,GAAI,EAAS,CAAA,CAMtC,SAAS,EAAe,CACtB,SACA,iBACA,WACA,eACA,gBACA,cACA,gBACA,UACA,cACA,cACA,YACuB,CACvB,IAAM,EAAW,EAAc,CAC7B,OAAQ,GAAU,KAClB,WACA,eACA,iBACA,gBACA,cACA,gBACA,UACA,cACA,cACD,CAAC,CAOF,OAJA,EAAA,EAAA,eAAgB,CACd,EAAc,EAAS,KAAK,EAC3B,CAAC,EAAS,KAAK,CAAC,EAEZ,EAAA,EAAA,KAAC,EAAD,CAA4B,WAAW,WAA4B,CAAA,CC1G5E,SAAgB,GAA0B,CACxC,IAAM,GAAA,EAAA,EAAA,YAAiB,EAAA,EAAY,CACnC,GAAI,CAAC,EACH,MAAU,MACR,wHAED,CAEH,OAAO,EClBT,IAAa,IAAoB,GAAG,IAAqB,CACvD,MAAU,MACR,iMAGD"}
|
package/dist/index.d.ts
CHANGED
|
@@ -4,11 +4,6 @@ export { I18nProvider } from './provider';
|
|
|
4
4
|
export { I18nContext } from './context';
|
|
5
5
|
export { useI18n } from './hooks/useI18n';
|
|
6
6
|
export { t } from './compile-time-t';
|
|
7
|
-
export { Trans } from './components/Trans';
|
|
8
|
-
export { Plural } from './components/Plural';
|
|
9
|
-
export { Select } from './components/Select';
|
|
10
|
-
export { DateTime } from './components/DateTime';
|
|
11
|
-
export { NumberFormat } from './components/Number';
|
|
12
7
|
export { msg } from './msg';
|
|
13
8
|
export type { FluentiContext, I18nProviderProps, Messages, AllMessages, MessageDescriptor, CompileTimeMessageDescriptor, CompileTimeT, Locale, DateFormatOptions, NumberFormatOptions, } from './types';
|
|
14
9
|
export type { FluentiTransProps } from './components/Trans';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAChD,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAGtE,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAGzC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAGvC,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,CAAC,EAAE,MAAM,kBAAkB,CAAA;AAGpC,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAChD,YAAY,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAGtE,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAGzC,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAGvC,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,CAAC,EAAE,MAAM,kBAAkB,CAAA;AAGpC,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAA;AAG3B,YAAY,EACV,cAAc,EACd,iBAAiB,EACjB,QAAQ,EACR,WAAW,EACX,iBAAiB,EACjB,4BAA4B,EAC5B,YAAY,EACZ,MAAM,EACN,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,SAAS,CAAA;AAIhB,YAAY,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAA;AAC3D,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAC7D,YAAY,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AAC7D,YAAY,EAAE,oBAAoB,EAAE,MAAM,uBAAu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