@intlayer/vue-i18n 9.9.3-canary.1 → 9.9.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/components.mjs +161 -0
- package/dist/esm/components.mjs.map +1 -0
- package/dist/esm/composer.mjs +234 -0
- package/dist/esm/composer.mjs.map +1 -0
- package/dist/esm/createI18n.mjs +49 -144
- package/dist/esm/createI18n.mjs.map +1 -1
- package/dist/esm/index.mjs +3 -1
- package/dist/esm/resolveVueMessage.mjs +23 -11
- package/dist/esm/resolveVueMessage.mjs.map +1 -1
- package/dist/esm/vTDirective.mjs +47 -0
- package/dist/esm/vTDirective.mjs.map +1 -0
- package/dist/types/components.d.ts +27 -0
- package/dist/types/components.d.ts.map +1 -0
- package/dist/types/composer.d.ts +97 -0
- package/dist/types/composer.d.ts.map +1 -0
- package/dist/types/createI18n.d.ts +3 -1
- package/dist/types/createI18n.d.ts.map +1 -1
- package/dist/types/index.d.ts +3 -1
- package/dist/types/resolveVueMessage.d.ts +17 -1
- package/dist/types/resolveVueMessage.d.ts.map +1 -1
- package/dist/types/vTDirective.d.ts +13 -0
- package/dist/types/vTDirective.d.ts.map +1 -0
- package/package.json +8 -8
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { useI18n } from "./createI18n.mjs";
|
|
2
|
+
import { Fragment, defineComponent, h } from "vue";
|
|
3
|
+
|
|
4
|
+
// src/components.ts
|
|
5
|
+
/** Props shared by `<i18n-t>`, `<i18n-n>` and `<i18n-d>`. */
|
|
6
|
+
const baseFormatProps = {
|
|
7
|
+
tag: { type: [String, Object] },
|
|
8
|
+
locale: { type: String },
|
|
9
|
+
scope: {
|
|
10
|
+
type: String,
|
|
11
|
+
validator: (value) => value === "parent" || value === "global",
|
|
12
|
+
default: "parent"
|
|
13
|
+
},
|
|
14
|
+
i18n: { type: Object }
|
|
15
|
+
};
|
|
16
|
+
/** The composer a component formats with: the `i18n` prop's, else `useI18n`. */
|
|
17
|
+
const useComponentComposer = (i18n) => i18n?.global ?? useI18n();
|
|
18
|
+
/** Wraps children in `tag`, or in a fragment without one. */
|
|
19
|
+
const renderInTag = ({ tag }, attrs, renderChildren) => {
|
|
20
|
+
if (typeof tag === "object") return h(tag, { ...attrs }, { default: renderChildren });
|
|
21
|
+
if (typeof tag === "string") return h(tag, { ...attrs }, renderChildren());
|
|
22
|
+
return h(Fragment, { ...attrs }, renderChildren());
|
|
23
|
+
};
|
|
24
|
+
/** Marks where a slot goes in a translated string (NUL never occurs in text). */
|
|
25
|
+
const SLOT_MARKER = /\u0000(\d+)\u0000/;
|
|
26
|
+
/**
|
|
27
|
+
* Drop-in for vue-i18n's `<i18n-t>` (`Translation` / `I18nT`): translates
|
|
28
|
+
* `keypath`, rendering named slots (`#terms`) in place of `{terms}`, or the
|
|
29
|
+
* default slot's children in place of `{0}`, `{1}`….
|
|
30
|
+
*/
|
|
31
|
+
const Translation = defineComponent({
|
|
32
|
+
name: "i18n-t",
|
|
33
|
+
props: {
|
|
34
|
+
keypath: {
|
|
35
|
+
type: String,
|
|
36
|
+
required: true
|
|
37
|
+
},
|
|
38
|
+
plural: {
|
|
39
|
+
type: [Number, String],
|
|
40
|
+
validator: (value) => typeof value === "number" || !Number.isNaN(Number(value))
|
|
41
|
+
},
|
|
42
|
+
...baseFormatProps
|
|
43
|
+
},
|
|
44
|
+
setup(props, { slots, attrs }) {
|
|
45
|
+
const composer = useComponentComposer(props.i18n);
|
|
46
|
+
return () => renderInTag(props, attrs, () => {
|
|
47
|
+
const slotNames = Object.keys(slots).filter((name) => name[0] !== "_");
|
|
48
|
+
const slotContents = [];
|
|
49
|
+
const values = {};
|
|
50
|
+
/** Records slot content and returns the marker standing for it. */
|
|
51
|
+
const mark = (content) => {
|
|
52
|
+
slotContents.push(content);
|
|
53
|
+
return `\u0000${slotContents.length - 1}\u0000`;
|
|
54
|
+
};
|
|
55
|
+
if (slotNames.length === 1 && slotNames[0] === "default") (slots.default?.() ?? []).flatMap((child) => child.type === Fragment ? child.children ?? [] : [child]).forEach((child, index) => {
|
|
56
|
+
values[index] = mark([child]);
|
|
57
|
+
});
|
|
58
|
+
else for (const name of slotNames) {
|
|
59
|
+
const content = slots[name]?.();
|
|
60
|
+
if (content) values[name] = mark([h(Fragment, null, content)]);
|
|
61
|
+
}
|
|
62
|
+
const options = {};
|
|
63
|
+
if (props.locale) options.locale = props.locale;
|
|
64
|
+
if (props.plural !== void 0) options.plural = Number(props.plural);
|
|
65
|
+
return composer.t(props.keypath, values, options).split(SLOT_MARKER).flatMap((segment, index) => index % 2 === 1 ? slotContents[Number(segment)] ?? [] : segment ? [segment] : []);
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
/** Resolves the `format` prop to `Intl` options and the named format key. */
|
|
70
|
+
const resolveFormatOptions = (format, namedFormats) => {
|
|
71
|
+
if (typeof format === "string") return {
|
|
72
|
+
key: format,
|
|
73
|
+
options: namedFormats[format]
|
|
74
|
+
};
|
|
75
|
+
if (!format) return { options: void 0 };
|
|
76
|
+
const { key, ...overrides } = format;
|
|
77
|
+
return {
|
|
78
|
+
key,
|
|
79
|
+
options: {
|
|
80
|
+
...key ? namedFormats[key] : void 0,
|
|
81
|
+
...overrides
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Renders each part, as upstream, through the slot named after its type
|
|
87
|
+
* (`#currency`) or as text, each as an array (a fragment).
|
|
88
|
+
*/
|
|
89
|
+
const renderParts = (slots, parts) => parts.map((part, index) => {
|
|
90
|
+
const slot = slots[part.type];
|
|
91
|
+
return slot ? slot({
|
|
92
|
+
[part.type]: part.value,
|
|
93
|
+
index,
|
|
94
|
+
parts
|
|
95
|
+
}) : [part.value];
|
|
96
|
+
});
|
|
97
|
+
/** Base language of a locale (`en` for `en-GB`). */
|
|
98
|
+
const toBaseLanguage = (locale) => locale.split("-")[0] ?? "";
|
|
99
|
+
/**
|
|
100
|
+
* Drop-in for vue-i18n's `<i18n-n>` (`NumberFormat` / `I18nN`): formats
|
|
101
|
+
* `value` with a named or inline `format`, exposing each part as a slot.
|
|
102
|
+
*/
|
|
103
|
+
const NumberFormat = defineComponent({
|
|
104
|
+
name: "i18n-n",
|
|
105
|
+
props: {
|
|
106
|
+
value: {
|
|
107
|
+
type: Number,
|
|
108
|
+
required: true
|
|
109
|
+
},
|
|
110
|
+
format: { type: [String, Object] },
|
|
111
|
+
...baseFormatProps
|
|
112
|
+
},
|
|
113
|
+
setup(props, { slots, attrs }) {
|
|
114
|
+
const composer = useComponentComposer(props.i18n);
|
|
115
|
+
return () => renderInTag(props, attrs, () => {
|
|
116
|
+
const locale = props.locale ?? composer.locale.value;
|
|
117
|
+
const { options } = resolveFormatOptions(props.format, {
|
|
118
|
+
...composer.getNumberFormat(toBaseLanguage(locale)),
|
|
119
|
+
...composer.getNumberFormat(locale)
|
|
120
|
+
});
|
|
121
|
+
return renderParts(slots, new Intl.NumberFormat(locale, options).formatToParts(props.value));
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
/**
|
|
126
|
+
* Drop-in for vue-i18n's `<i18n-d>` (`DatetimeFormat` / `I18nD`): formats
|
|
127
|
+
* `value` with a named or inline `format`, exposing each part as a slot.
|
|
128
|
+
*/
|
|
129
|
+
const DatetimeFormat = defineComponent({
|
|
130
|
+
name: "i18n-d",
|
|
131
|
+
props: {
|
|
132
|
+
value: {
|
|
133
|
+
type: [
|
|
134
|
+
Number,
|
|
135
|
+
Date,
|
|
136
|
+
String
|
|
137
|
+
],
|
|
138
|
+
required: true
|
|
139
|
+
},
|
|
140
|
+
format: { type: [String, Object] },
|
|
141
|
+
...baseFormatProps
|
|
142
|
+
},
|
|
143
|
+
setup(props, { slots, attrs }) {
|
|
144
|
+
const composer = useComponentComposer(props.i18n);
|
|
145
|
+
return () => renderInTag(props, attrs, () => {
|
|
146
|
+
const locale = props.locale ?? composer.locale.value;
|
|
147
|
+
const { options } = resolveFormatOptions(props.format, {
|
|
148
|
+
...composer.getDateTimeFormat(toBaseLanguage(locale)),
|
|
149
|
+
...composer.getDateTimeFormat(locale)
|
|
150
|
+
});
|
|
151
|
+
const date = props.value instanceof Date ? props.value : new Date(props.value);
|
|
152
|
+
return renderParts(slots, new Intl.DateTimeFormat(locale, options).formatToParts(date));
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
const I18nT = Translation;
|
|
157
|
+
const I18nN = NumberFormat;
|
|
158
|
+
const I18nD = DatetimeFormat;
|
|
159
|
+
|
|
160
|
+
export { DatetimeFormat, I18nD, I18nN, I18nT, NumberFormat, Translation };
|
|
161
|
+
//# sourceMappingURL=components.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"components.mjs","names":[],"sources":["../../src/components.ts"],"sourcesContent":["import {\n type Component,\n defineComponent,\n Fragment,\n h,\n type PropType,\n type SetupContext,\n type VNode,\n type VNodeArrayChildren,\n} from 'vue';\nimport type {\n DatetimeFormat as UpstreamDatetimeFormat,\n I18n,\n NumberFormat as UpstreamNumberFormat,\n Translation as UpstreamTranslation,\n} from 'vue-i18n';\nimport type { CompatComposer } from './composer';\nimport { useI18n } from './createI18n';\n\n/** Props shared by `<i18n-t>`, `<i18n-n>` and `<i18n-d>`. */\nconst baseFormatProps = {\n tag: { type: [String, Object] as PropType<string | Component> },\n locale: { type: String },\n scope: {\n type: String as PropType<'parent' | 'global'>,\n validator: (value: string) => value === 'parent' || value === 'global',\n default: 'parent',\n },\n i18n: { type: Object as PropType<I18n> },\n};\n\ntype BaseFormatProps = {\n tag?: string | Component;\n locale?: string;\n i18n?: I18n;\n};\n\n/** The composer a component formats with: the `i18n` prop's, else `useI18n`. */\nconst useComponentComposer = (i18n: I18n | undefined): CompatComposer =>\n (i18n?.global ?? useI18n()) as unknown as CompatComposer;\n\n/** Wraps children in `tag`, or in a fragment without one. */\nconst renderInTag = (\n { tag }: BaseFormatProps,\n attrs: Record<string, unknown>,\n renderChildren: () => VNodeArrayChildren\n): VNode => {\n if (typeof tag === 'object') {\n return h(tag, { ...attrs }, { default: renderChildren });\n }\n if (typeof tag === 'string') return h(tag, { ...attrs }, renderChildren());\n return h(Fragment, { ...attrs }, renderChildren());\n};\n\n/** Marks where a slot goes in a translated string (NUL never occurs in text). */\n// oxlint-disable-next-line no-control-regex -- the NUL delimiter is the point\nconst SLOT_MARKER = /\\u0000(\\d+)\\u0000/;\n\n/**\n * Drop-in for vue-i18n's `<i18n-t>` (`Translation` / `I18nT`): translates\n * `keypath`, rendering named slots (`#terms`) in place of `{terms}`, or the\n * default slot's children in place of `{0}`, `{1}`….\n */\nexport const Translation = defineComponent({\n name: 'i18n-t',\n props: {\n keypath: { type: String, required: true },\n plural: {\n type: [Number, String],\n validator: (value: unknown) =>\n typeof value === 'number' || !Number.isNaN(Number(value)),\n },\n ...baseFormatProps,\n },\n setup(props, { slots, attrs }: SetupContext) {\n const composer = useComponentComposer(props.i18n);\n\n return () =>\n renderInTag(props, attrs, () => {\n const slotNames = Object.keys(slots).filter((name) => name[0] !== '_');\n const slotContents: VNodeArrayChildren[] = [];\n const values: Record<string, string> = {};\n\n /** Records slot content and returns the marker standing for it. */\n const mark = (content: VNodeArrayChildren): string => {\n slotContents.push(content);\n return `\\u0000${slotContents.length - 1}\\u0000`;\n };\n\n if (slotNames.length === 1 && slotNames[0] === 'default') {\n // Default slot: its children fill `{0}`, `{1}`…\n const children = (slots.default?.() ?? []).flatMap((child) =>\n child.type === Fragment\n ? ((child.children as VNodeArrayChildren) ?? [])\n : [child]\n );\n children.forEach((child, index) => {\n values[index] = mark([child]);\n });\n } else {\n for (const name of slotNames) {\n const content = slots[name]?.();\n // A named slot renders as a fragment, as upstream.\n if (content) values[name] = mark([h(Fragment, null, content)]);\n }\n }\n\n const options: Record<string, unknown> = {};\n if (props.locale) options.locale = props.locale;\n if (props.plural !== undefined) options.plural = Number(props.plural);\n\n const translated = composer.t(props.keypath, values, options);\n\n return translated\n .split(SLOT_MARKER)\n .flatMap((segment, index) =>\n index % 2 === 1\n ? (slotContents[Number(segment)] ?? [])\n : segment\n ? [segment]\n : []\n );\n });\n },\n}) as unknown as typeof UpstreamTranslation;\n\n/** Resolves the `format` prop to `Intl` options and the named format key. */\nconst resolveFormatOptions = <FormatOptions extends object>(\n format: string | (FormatOptions & { key?: string }) | undefined,\n namedFormats: Record<string, FormatOptions>\n): { key?: string; options: FormatOptions | undefined } => {\n if (typeof format === 'string') {\n return { key: format, options: namedFormats[format] };\n }\n if (!format) return { options: undefined };\n\n const { key, ...overrides } = format;\n return {\n key,\n options: { ...(key ? namedFormats[key] : undefined), ...overrides } as\n | FormatOptions\n | undefined,\n };\n};\n\n/** One part of `formatToParts()`. */\ntype FormatPart = { type: string; value: string };\n\n/**\n * Renders each part, as upstream, through the slot named after its type\n * (`#currency`) or as text, each as an array (a fragment).\n */\nconst renderParts = (\n slots: SetupContext['slots'],\n parts: FormatPart[]\n): VNodeArrayChildren =>\n parts.map((part, index) => {\n const slot = slots[part.type];\n return slot\n ? slot({ [part.type]: part.value, index, parts })\n : [part.value];\n });\n\n/** Base language of a locale (`en` for `en-GB`). */\nconst toBaseLanguage = (locale: string): string => locale.split('-')[0] ?? '';\n\n/**\n * Drop-in for vue-i18n's `<i18n-n>` (`NumberFormat` / `I18nN`): formats\n * `value` with a named or inline `format`, exposing each part as a slot.\n */\nexport const NumberFormat = defineComponent({\n name: 'i18n-n',\n props: {\n value: { type: Number, required: true },\n format: {\n type: [String, Object] as PropType<\n string | (Intl.NumberFormatOptions & { key?: string })\n >,\n },\n ...baseFormatProps,\n },\n setup(props, { slots, attrs }: SetupContext) {\n const composer = useComponentComposer(props.i18n);\n\n return () =>\n renderInTag(props, attrs, () => {\n const locale = props.locale ?? composer.locale.value;\n const { options } = resolveFormatOptions(props.format, {\n ...composer.getNumberFormat(toBaseLanguage(locale)),\n ...composer.getNumberFormat(locale),\n });\n return renderParts(\n slots,\n new Intl.NumberFormat(locale, options).formatToParts(props.value)\n );\n });\n },\n}) as unknown as typeof UpstreamNumberFormat;\n\n/**\n * Drop-in for vue-i18n's `<i18n-d>` (`DatetimeFormat` / `I18nD`): formats\n * `value` with a named or inline `format`, exposing each part as a slot.\n */\nexport const DatetimeFormat = defineComponent({\n name: 'i18n-d',\n props: {\n value: { type: [Number, Date, String], required: true },\n format: {\n type: [String, Object] as PropType<\n string | (Intl.DateTimeFormatOptions & { key?: string })\n >,\n },\n ...baseFormatProps,\n },\n setup(props, { slots, attrs }: SetupContext) {\n const composer = useComponentComposer(props.i18n);\n\n return () =>\n renderInTag(props, attrs, () => {\n const locale = props.locale ?? composer.locale.value;\n const { options } = resolveFormatOptions(props.format, {\n ...composer.getDateTimeFormat(toBaseLanguage(locale)),\n ...composer.getDateTimeFormat(locale),\n });\n const date =\n props.value instanceof Date ? props.value : new Date(props.value);\n\n return renderParts(\n slots,\n new Intl.DateTimeFormat(locale, options).formatToParts(date)\n );\n });\n },\n}) as unknown as typeof UpstreamDatetimeFormat;\n\nexport const I18nT = Translation;\nexport const I18nN = NumberFormat;\nexport const I18nD = DatetimeFormat;\n"],"mappings":";;;;;AAoBA,MAAM,kBAAkB;CACtB,KAAK,EAAE,MAAM,CAAC,QAAQ,MAAM,EAAkC;CAC9D,QAAQ,EAAE,MAAM,OAAO;CACvB,OAAO;EACL,MAAM;EACN,YAAY,UAAkB,UAAU,YAAY,UAAU;EAC9D,SAAS;CACX;CACA,MAAM,EAAE,MAAM,OAAyB;AACzC;;AASA,MAAM,wBAAwB,SAC3B,MAAM,UAAU,QAAQ;;AAG3B,MAAM,eACJ,EAAE,OACF,OACA,mBACU;CACV,IAAI,OAAO,QAAQ,UACjB,OAAO,EAAE,KAAK,EAAE,GAAG,MAAM,GAAG,EAAE,SAAS,eAAe,CAAC;CAEzD,IAAI,OAAO,QAAQ,UAAU,OAAO,EAAE,KAAK,EAAE,GAAG,MAAM,GAAG,eAAe,CAAC;CACzE,OAAO,EAAE,UAAU,E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AClE;EACF,CAAC;CACL;AACF,CAAC;;;;;AAMD,MAAa,iBAAiB,gBAAgB;CAC5C,MAAM;CACN,OAAO;EACL,OAAO;GAAE,MAAM;IAAC;IAAQ;IAAM;GAAM;GAAG,UAAU;EAAK;EACtD,QAAQ,EACN,MAAM,CAAC,QAAQ,MAAM,EAGvB;EACA,GAAG;CACL;CACA,MAAM,OAAO,EAAE,OAAO,SAAuB;EAC3C,MAAM,WAAW,qBAAqB,MAAM,IAAI;EAEhD,aACE,YAAY,OAAO,aAAa;GAC9B,MAAM,SAAS,MAAM,UAAU,SAAS,OAAO;GAC/C,MAAM,EAAE,YAAY,qBAAqB,MAAM,QAAQ;IACrD,GAAG,SAAS,kBAAkB,eAAe,MAAM,CAAC;IACpD,GAAG,SAAS,kBAAkB,MAAM;GACtC,CAAC;GACD,MAAM,OACJ,MAAM,iBAAiB,OAAO,MAAM,QAAQ,IAAI,KAAK,MAAM,KAAK;GAElE,OAAO,YACL,OACA,IAAI,KAAK,eAAe,QAAQ,OAAO,CAAC,CAAC,cAAc,IAAI,CAC7D;EACF,CAAC;CACL;AACF,CAAC;AAED,MAAa,QAAQ;AACrB,MAAa,QAAQ;AACrB,MAAa,QAAQ"}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { formatDateValue, formatNumberValue } from "./formats.mjs";
|
|
2
|
+
import { getChoiceIndex, parseTranslateArguments, resolveVueMessage } from "./resolveVueMessage.mjs";
|
|
3
|
+
import { navigatePath } from "@intlayer/core/messageFormat";
|
|
4
|
+
import { computed, reactive, ref } from "vue";
|
|
5
|
+
import { internationalization, log } from "@intlayer/config/built";
|
|
6
|
+
import * as ANSIColors from "@intlayer/config/colors";
|
|
7
|
+
import { colorize, getAppLogger } from "@intlayer/config/logger";
|
|
8
|
+
import { getIntlayer } from "@intlayer/core/interpreter";
|
|
9
|
+
|
|
10
|
+
// src/composer.ts
|
|
11
|
+
/**
|
|
12
|
+
* Dictionary key used for keys that carry no explicit namespace and are not
|
|
13
|
+
* dot-namespaced (i18next-style flat keys, e.g. `t('greeting')`).
|
|
14
|
+
*/
|
|
15
|
+
const DEFAULT_NAMESPACE = "translation";
|
|
16
|
+
/** Resolves a single dictionary by key and navigates to the given path. */
|
|
17
|
+
const lookupInDictionary = (locale, dictionaryKey, path) => {
|
|
18
|
+
try {
|
|
19
|
+
const dictionary = getIntlayer(dictionaryKey, locale);
|
|
20
|
+
const value = navigatePath(dictionary, path);
|
|
21
|
+
if (value !== void 0 && value !== null) return value;
|
|
22
|
+
} catch {}
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Looks up a raw value for a vue-i18n key against intlayer dictionaries:
|
|
26
|
+
* 1. `ns:key` prefix or the composer namespace → dictionary `ns`
|
|
27
|
+
* 2. The first key segment as the dictionary key (`'home.title'` →
|
|
28
|
+
* dictionary `home`, path `title`)
|
|
29
|
+
* 3. The default `translation` dictionary for flat keys
|
|
30
|
+
*/
|
|
31
|
+
const lookupRaw = (locale, namespace, key) => {
|
|
32
|
+
let targetNamespace = namespace;
|
|
33
|
+
let path = key;
|
|
34
|
+
if (key.includes(":")) {
|
|
35
|
+
const separatorIndex = key.indexOf(":");
|
|
36
|
+
targetNamespace = key.slice(0, separatorIndex);
|
|
37
|
+
path = key.slice(separatorIndex + 1);
|
|
38
|
+
}
|
|
39
|
+
if (targetNamespace) {
|
|
40
|
+
const value = lookupInDictionary(locale, targetNamespace, path);
|
|
41
|
+
if (value !== void 0) return value;
|
|
42
|
+
}
|
|
43
|
+
if (path.includes(".")) {
|
|
44
|
+
const separatorIndex = path.indexOf(".");
|
|
45
|
+
const value = lookupInDictionary(locale, path.slice(0, separatorIndex), path.slice(separatorIndex + 1));
|
|
46
|
+
if (value !== void 0) return value;
|
|
47
|
+
}
|
|
48
|
+
if (!targetNamespace) {
|
|
49
|
+
const value = lookupInDictionary(locale, DEFAULT_NAMESPACE, path);
|
|
50
|
+
if (value !== void 0) return value;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
/** Locales of the intlayer configuration. */
|
|
54
|
+
const getAvailableLocales = () => internationalization?.locales?.map(String) ?? [];
|
|
55
|
+
const warnRuntimeMessages = (location) => {
|
|
56
|
+
getAppLogger({ log })(`${colorize(location, ANSIColors.CYAN)} has no effect with ${colorize("@intlayer/vue-i18n", ANSIColors.MAGENTA)} — translations are managed by the compiled intlayer dictionaries.`);
|
|
57
|
+
};
|
|
58
|
+
/** Characters vue-i18n escapes in parameters with `escapeParameter`. */
|
|
59
|
+
const HTML_ESCAPES = {
|
|
60
|
+
"&": "&",
|
|
61
|
+
"<": "<",
|
|
62
|
+
">": ">",
|
|
63
|
+
"\"": """,
|
|
64
|
+
"'": "'",
|
|
65
|
+
"/": "/",
|
|
66
|
+
"=": "="
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* HTML-escapes the string values, as vue-i18n's `escapeParameter` does
|
|
70
|
+
* (`&`, `<`, `>`, `"`, `'`, `/` and `=`).
|
|
71
|
+
*/
|
|
72
|
+
const escapeValues = (values) => Object.fromEntries(Object.entries(values).map(([name, value]) => [name, typeof value === "string" ? value.replace(/[&<>"'/=]/g, (character) => HTML_ESCAPES[character]) : value]));
|
|
73
|
+
let composerCount = 0;
|
|
74
|
+
/**
|
|
75
|
+
* Creates a vue-i18n Composition API composer backed by intlayer
|
|
76
|
+
* dictionaries: `t` / `te` / `tm` / `rt` / `d` / `n`, the format and handler
|
|
77
|
+
* accessors, and the option flags, as the global composer and `useI18n`
|
|
78
|
+
* expose them.
|
|
79
|
+
*
|
|
80
|
+
* `messages` passed to the options stay a lookup fallback; runtime message
|
|
81
|
+
* setters only warn, since dictionaries are compiled.
|
|
82
|
+
*/
|
|
83
|
+
const createComposer = ({ locale, availableLocales, namespace, isGlobal, options }) => {
|
|
84
|
+
composerCount += 1;
|
|
85
|
+
const fallbackMessages = options.messages;
|
|
86
|
+
const currentLocale = () => locale.value;
|
|
87
|
+
const fallbackLocaleRef = ref(options.fallbackLocale ?? internationalization?.defaultLocale);
|
|
88
|
+
const fallbackLocale = computed({
|
|
89
|
+
get: () => fallbackLocaleRef.value,
|
|
90
|
+
set: (value) => {
|
|
91
|
+
fallbackLocaleRef.value = value;
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
const datetimeFormatStore = reactive({ ...options.datetimeFormats });
|
|
95
|
+
const numberFormatStore = reactive({ ...options.numberFormats });
|
|
96
|
+
const flags = reactive({
|
|
97
|
+
escapeParameter: options.escapeParameter ?? false,
|
|
98
|
+
fallbackFormat: options.fallbackFormat ?? false,
|
|
99
|
+
fallbackRoot: options.fallbackRoot ?? true,
|
|
100
|
+
fallbackWarn: options.fallbackWarn ?? true,
|
|
101
|
+
missingWarn: options.missingWarn ?? true,
|
|
102
|
+
warnHtmlMessage: options.warnHtmlMessage ?? true,
|
|
103
|
+
inheritLocale: options.inheritLocale ?? true
|
|
104
|
+
});
|
|
105
|
+
let missingHandler = options.missing ?? null;
|
|
106
|
+
let postTranslationHandler = options.postTranslation ?? null;
|
|
107
|
+
const pluralRules = options.pluralRules ?? {};
|
|
108
|
+
/** Translates a key with vue-i18n's polymorphic argument list. */
|
|
109
|
+
const translate = (key, ...args) => {
|
|
110
|
+
const { values, count, defaultMessage, options: callOptions } = parseTranslateArguments(args);
|
|
111
|
+
const targetLocale = callOptions.locale ?? currentLocale();
|
|
112
|
+
const interpolationValues = callOptions.escapeParameter ?? flags.escapeParameter ? escapeValues(values) : values;
|
|
113
|
+
const choiceRule = pluralRules[targetLocale] ?? getChoiceIndex;
|
|
114
|
+
const resolve = (message) => resolveVueMessage(message, interpolationValues, count, targetLocale, choiceRule);
|
|
115
|
+
const applyPostTranslation = (translated) => postTranslationHandler ? postTranslationHandler(translated, key) : translated;
|
|
116
|
+
const rawValue = lookupRaw(targetLocale, namespace, key);
|
|
117
|
+
if (rawValue !== void 0) return applyPostTranslation(resolve(rawValue));
|
|
118
|
+
const fallbackValue = fallbackMessages?.[targetLocale] ? navigatePath(fallbackMessages[targetLocale], namespace ? `${namespace}.${key}` : key) : void 0;
|
|
119
|
+
if (fallbackValue !== void 0) return applyPostTranslation(resolve(fallbackValue));
|
|
120
|
+
const missingResult = missingHandler?.(targetLocale, key, void 0, "translate");
|
|
121
|
+
if (typeof missingResult === "string") return missingResult;
|
|
122
|
+
if (defaultMessage !== void 0) return applyPostTranslation(resolve(defaultMessage));
|
|
123
|
+
if (callOptions.default === true || flags.fallbackFormat) return applyPostTranslation(resolve(key));
|
|
124
|
+
return key;
|
|
125
|
+
};
|
|
126
|
+
const formatDate = (value, formatOrOptions, localeOverride) => formatDateValue(value, formatOrOptions, localeOverride ?? currentLocale(), datetimeFormatStore);
|
|
127
|
+
const formatNumber = (value, formatOrOptions, localeOverride) => formatNumberValue(value, formatOrOptions, localeOverride ?? currentLocale(), numberFormatStore);
|
|
128
|
+
const messages = computed(() => fallbackMessages ?? {});
|
|
129
|
+
return {
|
|
130
|
+
id: composerCount,
|
|
131
|
+
locale,
|
|
132
|
+
fallbackLocale,
|
|
133
|
+
availableLocales,
|
|
134
|
+
isGlobal,
|
|
135
|
+
messages,
|
|
136
|
+
datetimeFormats: computed(() => datetimeFormatStore),
|
|
137
|
+
numberFormats: computed(() => numberFormatStore),
|
|
138
|
+
modifiers: options.modifiers ?? {},
|
|
139
|
+
pluralRules,
|
|
140
|
+
get escapeParameter() {
|
|
141
|
+
return flags.escapeParameter;
|
|
142
|
+
},
|
|
143
|
+
set escapeParameter(value) {
|
|
144
|
+
flags.escapeParameter = value;
|
|
145
|
+
},
|
|
146
|
+
get fallbackFormat() {
|
|
147
|
+
return flags.fallbackFormat;
|
|
148
|
+
},
|
|
149
|
+
set fallbackFormat(value) {
|
|
150
|
+
flags.fallbackFormat = value;
|
|
151
|
+
},
|
|
152
|
+
get fallbackRoot() {
|
|
153
|
+
return flags.fallbackRoot;
|
|
154
|
+
},
|
|
155
|
+
set fallbackRoot(value) {
|
|
156
|
+
flags.fallbackRoot = value;
|
|
157
|
+
},
|
|
158
|
+
get fallbackWarn() {
|
|
159
|
+
return flags.fallbackWarn;
|
|
160
|
+
},
|
|
161
|
+
set fallbackWarn(value) {
|
|
162
|
+
flags.fallbackWarn = value;
|
|
163
|
+
},
|
|
164
|
+
get missingWarn() {
|
|
165
|
+
return flags.missingWarn;
|
|
166
|
+
},
|
|
167
|
+
set missingWarn(value) {
|
|
168
|
+
flags.missingWarn = value;
|
|
169
|
+
},
|
|
170
|
+
get warnHtmlMessage() {
|
|
171
|
+
return flags.warnHtmlMessage;
|
|
172
|
+
},
|
|
173
|
+
set warnHtmlMessage(value) {
|
|
174
|
+
flags.warnHtmlMessage = value;
|
|
175
|
+
},
|
|
176
|
+
get inheritLocale() {
|
|
177
|
+
return flags.inheritLocale;
|
|
178
|
+
},
|
|
179
|
+
set inheritLocale(value) {
|
|
180
|
+
flags.inheritLocale = value;
|
|
181
|
+
},
|
|
182
|
+
t: translate,
|
|
183
|
+
tc: translate,
|
|
184
|
+
te: (key, localeOverride) => lookupRaw(localeOverride ?? currentLocale(), namespace, key) !== void 0,
|
|
185
|
+
tm: (key) => lookupRaw(currentLocale(), namespace, key) ?? {},
|
|
186
|
+
rt: (message, ...args) => {
|
|
187
|
+
const { values, count } = parseTranslateArguments(args);
|
|
188
|
+
return resolveVueMessage(message, values, count, currentLocale(), pluralRules[currentLocale()] ?? getChoiceIndex);
|
|
189
|
+
},
|
|
190
|
+
d: formatDate,
|
|
191
|
+
n: formatNumber,
|
|
192
|
+
getLocaleMessage: (_locale) => {
|
|
193
|
+
warnRuntimeMessages("getLocaleMessage");
|
|
194
|
+
return {};
|
|
195
|
+
},
|
|
196
|
+
setLocaleMessage: (_locale, _messages) => {
|
|
197
|
+
warnRuntimeMessages("setLocaleMessage");
|
|
198
|
+
},
|
|
199
|
+
mergeLocaleMessage: (_locale, _messages) => {
|
|
200
|
+
warnRuntimeMessages("mergeLocaleMessage");
|
|
201
|
+
},
|
|
202
|
+
getDateTimeFormat: (formatLocale) => datetimeFormatStore[formatLocale] ?? {},
|
|
203
|
+
setDateTimeFormat: (formatLocale, format) => {
|
|
204
|
+
datetimeFormatStore[formatLocale] = format;
|
|
205
|
+
},
|
|
206
|
+
mergeDateTimeFormat: (formatLocale, format) => {
|
|
207
|
+
datetimeFormatStore[formatLocale] = {
|
|
208
|
+
...datetimeFormatStore[formatLocale],
|
|
209
|
+
...format
|
|
210
|
+
};
|
|
211
|
+
},
|
|
212
|
+
getNumberFormat: (formatLocale) => numberFormatStore[formatLocale] ?? {},
|
|
213
|
+
setNumberFormat: (formatLocale, format) => {
|
|
214
|
+
numberFormatStore[formatLocale] = format;
|
|
215
|
+
},
|
|
216
|
+
mergeNumberFormat: (formatLocale, format) => {
|
|
217
|
+
numberFormatStore[formatLocale] = {
|
|
218
|
+
...numberFormatStore[formatLocale],
|
|
219
|
+
...format
|
|
220
|
+
};
|
|
221
|
+
},
|
|
222
|
+
getMissingHandler: () => missingHandler,
|
|
223
|
+
setMissingHandler: (handler) => {
|
|
224
|
+
missingHandler = handler;
|
|
225
|
+
},
|
|
226
|
+
getPostTranslationHandler: () => postTranslationHandler,
|
|
227
|
+
setPostTranslationHandler: (handler) => {
|
|
228
|
+
postTranslationHandler = handler;
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
export { createComposer, getAvailableLocales, lookupRaw };
|
|
234
|
+
//# sourceMappingURL=composer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"composer.mjs","names":[],"sources":["../../src/composer.ts"],"sourcesContent":["import { internationalization, log } from '@intlayer/config/built';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { getIntlayer } from '@intlayer/core/interpreter';\nimport { type MessageValues, navigatePath } from '@intlayer/core/messageFormat';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport {\n type ComputedRef,\n computed,\n reactive,\n ref,\n type WritableComputedRef,\n} from 'vue';\nimport {\n type DateTimeFormatsConfig,\n formatDateValue,\n formatNumberValue,\n type NumberFormatsConfig,\n} from './formats';\nimport {\n type ChoiceRule,\n getChoiceIndex,\n parseTranslateArguments,\n resolveVueMessage,\n} from './resolveVueMessage';\n\n/**\n * Dictionary key used for keys that carry no explicit namespace and are not\n * dot-namespaced (i18next-style flat keys, e.g. `t('greeting')`).\n */\nconst DEFAULT_NAMESPACE = 'translation';\n\n/** Resolves a single dictionary by key and navigates to the given path. */\nconst lookupInDictionary = (\n locale: string,\n dictionaryKey: string,\n path: string\n): unknown => {\n try {\n const dictionary = getIntlayer(\n dictionaryKey as DictionaryKeys,\n locale as LocalesValues\n );\n const value = navigatePath(dictionary, path);\n if (value !== undefined && value !== null) return value;\n } catch {}\n return undefined;\n};\n\n/**\n * Looks up a raw value for a vue-i18n key against intlayer dictionaries:\n * 1. `ns:key` prefix or the composer namespace → dictionary `ns`\n * 2. The first key segment as the dictionary key (`'home.title'` →\n * dictionary `home`, path `title`)\n * 3. The default `translation` dictionary for flat keys\n */\nexport const lookupRaw = (\n locale: string,\n namespace: string | undefined,\n key: string\n): unknown => {\n let targetNamespace = namespace;\n let path = key;\n\n if (key.includes(':')) {\n const separatorIndex = key.indexOf(':');\n targetNamespace = key.slice(0, separatorIndex);\n path = key.slice(separatorIndex + 1);\n }\n\n if (targetNamespace) {\n const value = lookupInDictionary(locale, targetNamespace, path);\n if (value !== undefined) return value;\n }\n\n if (path.includes('.')) {\n const separatorIndex = path.indexOf('.');\n const value = lookupInDictionary(\n locale,\n path.slice(0, separatorIndex),\n path.slice(separatorIndex + 1)\n );\n if (value !== undefined) return value;\n }\n\n if (!targetNamespace) {\n const value = lookupInDictionary(locale, DEFAULT_NAMESPACE, path);\n if (value !== undefined) return value;\n }\n\n return undefined;\n};\n\n/** Locales of the intlayer configuration. */\nexport const getAvailableLocales = (): string[] =>\n internationalization?.locales?.map(String) ?? [];\n\nconst warnRuntimeMessages = (location: string) => {\n getAppLogger({ log })(\n `${colorize(location, ANSIColors.CYAN)} has no effect with ${colorize('@intlayer/vue-i18n', ANSIColors.MAGENTA)} — translations are managed by the compiled intlayer dictionaries.`\n );\n};\n\n/** Characters vue-i18n escapes in parameters with `escapeParameter`. */\nconst HTML_ESCAPES: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/',\n '=': '=',\n};\n\n/**\n * HTML-escapes the string values, as vue-i18n's `escapeParameter` does\n * (`&`, `<`, `>`, `\"`, `'`, `/` and `=`).\n */\nconst escapeValues = (values: MessageValues): MessageValues =>\n Object.fromEntries(\n Object.entries(values).map(([name, value]) => [\n name,\n typeof value === 'string'\n ? value.replace(/[&<>\"'/=]/g, (character) => HTML_ESCAPES[character]!)\n : value,\n ])\n ) as MessageValues;\n\n/** Handler called for a missing key; a returned string is used as the result. */\nexport type MissingHandler = (\n locale: string,\n key: string,\n instance?: unknown,\n type?: string,\n ...values: unknown[]\n) => string | void;\n\n/** Handler applied to every translation: `(translated, key) => result`. */\nexport type PostTranslationHandler = (\n translated: unknown,\n key: string\n) => unknown;\n\n/** Options of `createI18n` / `useI18n` the composer reads. */\nexport type ComposerOptions = {\n fallbackLocale?: unknown;\n messages?: Record<string, unknown>;\n datetimeFormats?: DateTimeFormatsConfig;\n numberFormats?: NumberFormatsConfig;\n modifiers?: Record<string, (value: unknown, type: string) => unknown>;\n pluralRules?: Record<string, ChoiceRule>;\n missing?: MissingHandler;\n postTranslation?: PostTranslationHandler;\n escapeParameter?: boolean;\n fallbackFormat?: boolean;\n fallbackRoot?: boolean;\n fallbackWarn?: boolean | RegExp;\n missingWarn?: boolean | RegExp;\n warnHtmlMessage?: boolean;\n inheritLocale?: boolean;\n};\n\n/** What a composer is built from. */\nexport type ComposerContext = {\n /** Writable current locale. */\n locale: WritableComputedRef<string>;\n /** Available locales (the intlayer configuration's). */\n availableLocales: string[];\n /** `useI18n({ namespace })` dictionary, else the root scope. */\n namespace?: string;\n /** The global composer of `createI18n`, or a `useI18n` local one. */\n isGlobal: boolean;\n options: ComposerOptions;\n};\n\nlet composerCount = 0;\n\n/**\n * Creates a vue-i18n Composition API composer backed by intlayer\n * dictionaries: `t` / `te` / `tm` / `rt` / `d` / `n`, the format and handler\n * accessors, and the option flags, as the global composer and `useI18n`\n * expose them.\n *\n * `messages` passed to the options stay a lookup fallback; runtime message\n * setters only warn, since dictionaries are compiled.\n */\nexport const createComposer = ({\n locale,\n availableLocales,\n namespace,\n isGlobal,\n options,\n}: ComposerContext) => {\n composerCount += 1;\n\n const fallbackMessages = options.messages;\n const currentLocale = (): string => locale.value;\n\n const fallbackLocaleRef = ref(\n (options.fallbackLocale ?? internationalization?.defaultLocale) as string\n );\n const fallbackLocale: WritableComputedRef<string> = computed({\n get: () => fallbackLocaleRef.value,\n set: (value: string) => {\n fallbackLocaleRef.value = value;\n },\n });\n\n const datetimeFormatStore = reactive<DateTimeFormatsConfig>({\n ...options.datetimeFormats,\n });\n const numberFormatStore = reactive<NumberFormatsConfig>({\n ...options.numberFormats,\n });\n\n const flags = reactive({\n escapeParameter: options.escapeParameter ?? false,\n fallbackFormat: options.fallbackFormat ?? false,\n fallbackRoot: options.fallbackRoot ?? true,\n fallbackWarn: options.fallbackWarn ?? true,\n missingWarn: options.missingWarn ?? true,\n warnHtmlMessage: options.warnHtmlMessage ?? true,\n inheritLocale: options.inheritLocale ?? true,\n });\n\n let missingHandler: MissingHandler | null = options.missing ?? null;\n let postTranslationHandler: PostTranslationHandler | null =\n options.postTranslation ?? null;\n const pluralRules = options.pluralRules ?? {};\n\n /** Translates a key with vue-i18n's polymorphic argument list. */\n const translate = (key: string, ...args: unknown[]): string => {\n const {\n values,\n count,\n defaultMessage,\n options: callOptions,\n } = parseTranslateArguments(args);\n const targetLocale = callOptions.locale ?? currentLocale();\n const shouldEscape = callOptions.escapeParameter ?? flags.escapeParameter;\n const interpolationValues = shouldEscape ? escapeValues(values) : values;\n const choiceRule = pluralRules[targetLocale] ?? getChoiceIndex;\n\n const resolve = (message: unknown): string =>\n resolveVueMessage(\n message,\n interpolationValues,\n count,\n targetLocale as LocalesValues,\n choiceRule\n );\n\n const applyPostTranslation = (translated: string): string =>\n postTranslationHandler\n ? (postTranslationHandler(translated, key) as string)\n : translated;\n\n const rawValue = lookupRaw(targetLocale, namespace, key);\n if (rawValue !== undefined) return applyPostTranslation(resolve(rawValue));\n\n const fallbackValue = fallbackMessages?.[targetLocale]\n ? navigatePath(\n fallbackMessages[targetLocale],\n namespace ? `${namespace}.${key}` : key\n )\n : undefined;\n if (fallbackValue !== undefined) {\n return applyPostTranslation(resolve(fallbackValue));\n }\n\n const missingResult = missingHandler?.(\n targetLocale,\n key,\n undefined,\n 'translate'\n );\n if (typeof missingResult === 'string') return missingResult;\n\n if (defaultMessage !== undefined) {\n return applyPostTranslation(resolve(defaultMessage));\n }\n if (callOptions.default === true || flags.fallbackFormat) {\n return applyPostTranslation(resolve(key));\n }\n return key;\n };\n\n const formatDate = (\n value: Date | number | string,\n formatOrOptions?: string | Intl.DateTimeFormatOptions,\n localeOverride?: string\n ): string =>\n formatDateValue(\n value,\n formatOrOptions,\n localeOverride ?? currentLocale(),\n datetimeFormatStore\n );\n\n const formatNumber = (\n value: number,\n formatOrOptions?: string | Intl.NumberFormatOptions,\n localeOverride?: string\n ): string =>\n formatNumberValue(\n value,\n formatOrOptions,\n localeOverride ?? currentLocale(),\n numberFormatStore\n );\n\n const messages: ComputedRef<Record<string, unknown>> = computed(\n () => fallbackMessages ?? {}\n );\n\n return {\n id: composerCount,\n locale,\n fallbackLocale,\n availableLocales,\n isGlobal,\n messages,\n datetimeFormats: computed(() => datetimeFormatStore),\n numberFormats: computed(() => numberFormatStore),\n modifiers: options.modifiers ?? {},\n pluralRules,\n\n get escapeParameter() {\n return flags.escapeParameter;\n },\n set escapeParameter(value: boolean) {\n flags.escapeParameter = value;\n },\n get fallbackFormat() {\n return flags.fallbackFormat;\n },\n set fallbackFormat(value: boolean) {\n flags.fallbackFormat = value;\n },\n get fallbackRoot() {\n return flags.fallbackRoot;\n },\n set fallbackRoot(value: boolean) {\n flags.fallbackRoot = value;\n },\n get fallbackWarn() {\n return flags.fallbackWarn;\n },\n set fallbackWarn(value: boolean | RegExp) {\n flags.fallbackWarn = value;\n },\n get missingWarn() {\n return flags.missingWarn;\n },\n set missingWarn(value: boolean | RegExp) {\n flags.missingWarn = value;\n },\n get warnHtmlMessage() {\n return flags.warnHtmlMessage;\n },\n set warnHtmlMessage(value: boolean) {\n flags.warnHtmlMessage = value;\n },\n get inheritLocale() {\n return flags.inheritLocale;\n },\n set inheritLocale(value: boolean) {\n flags.inheritLocale = value;\n },\n\n t: translate,\n tc: translate,\n te: (key: string, localeOverride?: string): boolean =>\n lookupRaw(localeOverride ?? currentLocale(), namespace, key) !==\n undefined,\n tm: (key: string): unknown =>\n lookupRaw(currentLocale(), namespace, key) ?? {},\n rt: (message: unknown, ...args: unknown[]): string => {\n const { values, count } = parseTranslateArguments(args);\n return resolveVueMessage(\n message,\n values,\n count,\n currentLocale() as LocalesValues,\n pluralRules[currentLocale()] ?? getChoiceIndex\n );\n },\n d: formatDate,\n n: formatNumber,\n\n getLocaleMessage: (_locale: string): Record<string, unknown> => {\n warnRuntimeMessages('getLocaleMessage');\n return {};\n },\n setLocaleMessage: (_locale: string, _messages: unknown) => {\n warnRuntimeMessages('setLocaleMessage');\n },\n mergeLocaleMessage: (_locale: string, _messages: unknown) => {\n warnRuntimeMessages('mergeLocaleMessage');\n },\n\n getDateTimeFormat: (\n formatLocale: string\n ): Record<string, Intl.DateTimeFormatOptions> =>\n datetimeFormatStore[formatLocale] ?? {},\n setDateTimeFormat: (\n formatLocale: string,\n format: Record<string, Intl.DateTimeFormatOptions>\n ) => {\n datetimeFormatStore[formatLocale] = format;\n },\n mergeDateTimeFormat: (\n formatLocale: string,\n format: Record<string, Intl.DateTimeFormatOptions>\n ) => {\n datetimeFormatStore[formatLocale] = {\n ...datetimeFormatStore[formatLocale],\n ...format,\n };\n },\n getNumberFormat: (\n formatLocale: string\n ): Record<string, Intl.NumberFormatOptions> =>\n numberFormatStore[formatLocale] ?? {},\n setNumberFormat: (\n formatLocale: string,\n format: Record<string, Intl.NumberFormatOptions>\n ) => {\n numberFormatStore[formatLocale] = format;\n },\n mergeNumberFormat: (\n formatLocale: string,\n format: Record<string, Intl.NumberFormatOptions>\n ) => {\n numberFormatStore[formatLocale] = {\n ...numberFormatStore[formatLocale],\n ...format,\n };\n },\n\n getMissingHandler: (): MissingHandler | null => missingHandler,\n setMissingHandler: (handler: MissingHandler | null) => {\n missingHandler = handler;\n },\n getPostTranslationHandler: (): PostTranslationHandler | null =>\n postTranslationHandler,\n setPostTranslationHandler: (handler: PostTranslationHandler | null) => {\n postTranslationHandler = handler;\n },\n };\n};\n\nexport type CompatComposer = ReturnType<typeof createComposer>;\n"],"mappings":";;;;;;;;;;;;;;AAiCA,MAAM,oBAAoB;;AAG1B,MAAM,sBACJ,QACA,eACA,SACY;CACZ,IAAI;EACF,MAAM,aAAa,YACjB,eACA,MACF;EACA,MAAM,QAAQ,aAAa,YAAY,IAAI;EAC3C,IAAI,UAAU,UAAa,UAAU,MAAM,OAAO;CACpD,QAAQ,CAAC;AAEX;;;;;;;;AASA,MAAa,aACX,QACA,WACA,QACY;CACZ,IAAI,kBAAkB;CACtB,IAAI,OAAO;CAEX,IAAI,IAAI,SAAS,GAAG,GAAG;EACrB,MAAM,iBAAiB,IAAI,QAAQ,GAAG;EACtC,kBAAkB,IAAI,MAAM,GAAG,cAAc;EAC7C,OAAO,IAAI,MAAM,iBAAiB,CAAC;CACrC;CAEA,IAAI,iBAAiB;EACnB,MAAM,QAAQ,mBAAmB,QAAQ,iBAAiB,IAAI;EAC9D,IAAI,UAAU,QAAW,OAAO;CAClC;CAEA,IAAI,KAAK,SAAS,GAAG,GAAG;EACtB,MAAM,iBAAiB,KAAK,QAAQ,GAAG;EACvC,MAAM,QAAQ,mBACZ,QACA,KAAK,MAAM,GAAG,cAAc,GAC5B,KAAK,MAA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C;EACV;EACA,mBAAmB,SAAiB,cAAuB;GACzD,oBAAoB,kBAAkB;EACxC;EACA,qBAAqB,SAAiB,cAAuB;GAC3D,oBAAoB,oBAAoB;EAC1C;EAEA,oBACE,iBAEA,oBAAoB,iBAAiB,CAAC;EACxC,oBACE,cACA,WACG;GACH,oBAAoB,gBAAgB;EACtC;EACA,sBACE,cACA,WACG;GACH,oBAAoB,gBAAgB;IAClC,GAAG,oBAAoB;IACvB,GAAG;GACL;EACF;EACA,kBACE,iBAEA,kBAAkB,iBAAiB,CAAC;EACtC,kBACE,cACA,WACG;GACH,kBAAkB,gBAAgB;EACpC;EACA,oBACE,cACA,WACG;GACH,kBAAkB,gBAAgB;IAChC,GAAG,kBAAkB;IACrB,GAAG;GACL;EACF;EAEA,yBAAgD;EAChD,oBAAoB,YAAmC;GACrD,iBAAiB;EACnB;EACA,iCACE;EACF,4BAA4B,YAA2C;GACrE,yBAAyB;EAC3B;CACF;AACF"}
|
package/dist/esm/createI18n.mjs
CHANGED
|
@@ -1,85 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { DatetimeFormat, NumberFormat, Translation } from "./components.mjs";
|
|
2
|
+
import { createComposer, getAvailableLocales } from "./composer.mjs";
|
|
3
|
+
import { vTDirective } from "./vTDirective.mjs";
|
|
4
4
|
import { computed, inject } from "vue";
|
|
5
5
|
import { INTLAYER_SYMBOL, createIntlayerClient, installIntlayer, useLocale } from "vue-intlayer";
|
|
6
|
-
import {
|
|
6
|
+
import { log } from "@intlayer/config/built";
|
|
7
7
|
import * as ANSIColors from "@intlayer/config/colors";
|
|
8
8
|
import { colorize, getAppLogger } from "@intlayer/config/logger";
|
|
9
|
-
import { getIntlayer } from "@intlayer/core/interpreter";
|
|
10
9
|
|
|
11
10
|
// src/createI18n.ts
|
|
12
11
|
const VERSION = "9.13.1";
|
|
13
12
|
const I18nInjectionKey = Symbol("global-i18n");
|
|
14
|
-
/**
|
|
15
|
-
* Dictionary key used for keys that carry no explicit namespace and are not
|
|
16
|
-
* dot-namespaced (i18next-style flat keys, e.g. `t('greeting')`).
|
|
17
|
-
*/
|
|
18
|
-
const DEFAULT_NAMESPACE = "translation";
|
|
19
|
-
/**
|
|
20
|
-
* Looks up a raw value for a vue-i18n key against intlayer dictionaries.
|
|
21
|
-
*
|
|
22
|
-
* Resolution order:
|
|
23
|
-
* 1. `ns:key` prefix → dictionary `ns`
|
|
24
|
-
* 2. The default namespace dictionary with the full dot-path
|
|
25
|
-
* 3. The first key segment as the dictionary key (`'home.title'` →
|
|
26
|
-
* dictionary `home`, path `title`)
|
|
27
|
-
*/
|
|
28
|
-
/** Resolves a single dictionary by key and navigates to the given path. */
|
|
29
|
-
const lookupInDictionary = (locale, dictionaryKey, path) => {
|
|
30
|
-
try {
|
|
31
|
-
const dictionary = getIntlayer(dictionaryKey, locale);
|
|
32
|
-
const value = navigatePath(dictionary, path);
|
|
33
|
-
if (value !== void 0 && value !== null) return value;
|
|
34
|
-
} catch {}
|
|
35
|
-
};
|
|
36
|
-
const lookupRaw = (locale, namespace, key) => {
|
|
37
|
-
let targetNamespace = namespace;
|
|
38
|
-
let path = key;
|
|
39
|
-
if (key.includes(":")) {
|
|
40
|
-
const separatorIndex = key.indexOf(":");
|
|
41
|
-
targetNamespace = key.slice(0, separatorIndex);
|
|
42
|
-
path = key.slice(separatorIndex + 1);
|
|
43
|
-
}
|
|
44
|
-
if (targetNamespace) {
|
|
45
|
-
const value = lookupInDictionary(locale, targetNamespace, path);
|
|
46
|
-
if (value !== void 0) return value;
|
|
47
|
-
}
|
|
48
|
-
if (path.includes(".")) {
|
|
49
|
-
const separatorIndex = path.indexOf(".");
|
|
50
|
-
const value = lookupInDictionary(locale, path.slice(0, separatorIndex), path.slice(separatorIndex + 1));
|
|
51
|
-
if (value !== void 0) return value;
|
|
52
|
-
}
|
|
53
|
-
if (!targetNamespace) {
|
|
54
|
-
const value = lookupInDictionary(locale, DEFAULT_NAMESPACE, path);
|
|
55
|
-
if (value !== void 0) return value;
|
|
56
|
-
}
|
|
57
|
-
};
|
|
58
|
-
/** Translates a key with vue-i18n's polymorphic argument list. */
|
|
59
|
-
const translateKey = (locale, namespace, key, args, fallbackMessages) => {
|
|
60
|
-
const { values, count, defaultMessage } = parseTranslateArguments(args);
|
|
61
|
-
const rawValue = lookupRaw(locale, namespace, key);
|
|
62
|
-
if (rawValue === void 0) {
|
|
63
|
-
if (fallbackMessages?.[locale]) {
|
|
64
|
-
const targetPath = namespace ? `${namespace}.${key}` : key;
|
|
65
|
-
const fallbackValue = navigatePath(fallbackMessages[locale], targetPath);
|
|
66
|
-
if (fallbackValue !== void 0) return resolveVueMessage(fallbackValue, values, count, locale);
|
|
67
|
-
}
|
|
68
|
-
if (defaultMessage !== void 0) return resolveVueMessage(defaultMessage, values, count, locale);
|
|
69
|
-
return key;
|
|
70
|
-
}
|
|
71
|
-
return resolveVueMessage(rawValue, values, count, locale);
|
|
72
|
-
};
|
|
73
|
-
const getAvailableLocales = () => internationalization?.locales?.map(String) ?? [];
|
|
74
|
-
const warnDeprecatedRuntimeMessages = (location) => {
|
|
75
|
-
getAppLogger({ log })(`${colorize(location, ANSIColors.CYAN)} has no effect with ${colorize("@intlayer/vue-i18n", ANSIColors.MAGENTA)} — translations are managed by the compiled intlayer dictionaries.`);
|
|
76
|
-
};
|
|
77
13
|
const createI18n = ((options = {}) => {
|
|
78
|
-
const fallbackMessages = options.messages;
|
|
79
14
|
if (options.messages !== void 0 && process.env.NODE_ENV === "development") getAppLogger({ log })(`${colorize("createI18n", ANSIColors.CYAN)}: the ${colorize("`messages`", ANSIColors.CYAN)} option is used as a fallback. For optimal bundle size, remove the locale JSON imports and use ${colorize("useDictionary", ANSIColors.CYAN)} or compile your intlayer dictionaries instead:\n ${colorize("Before:", ANSIColors.GREY)} createI18n({ messages: { en, fr, … } })\n ${colorize("After: ", ANSIColors.GREY)} createI18n({})`);
|
|
80
15
|
const client = createIntlayerClient(options.locale);
|
|
81
|
-
const datetimeFormats = options.datetimeFormats;
|
|
82
|
-
const numberFormats = options.numberFormats;
|
|
83
16
|
const currentLocale = () => String(client.locale.value);
|
|
84
17
|
/** Writable ref matching vue-i18n's composition-mode `global.locale`. */
|
|
85
18
|
const localeRef = computed({
|
|
@@ -88,34 +21,12 @@ const createI18n = ((options = {}) => {
|
|
|
88
21
|
client.setLocale(newLocale);
|
|
89
22
|
}
|
|
90
23
|
});
|
|
91
|
-
const
|
|
92
|
-
const globalDate = (value, formatOrOptions) => formatDateValue(value, formatOrOptions, currentLocale(), datetimeFormats);
|
|
93
|
-
const globalNumber = (value, formatOrOptions) => formatNumberValue(value, formatOrOptions, currentLocale(), numberFormats);
|
|
94
|
-
const global = {
|
|
24
|
+
const global = createComposer({
|
|
95
25
|
locale: localeRef,
|
|
96
26
|
availableLocales: getAvailableLocales(),
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
te: (key) => lookupRaw(currentLocale(), void 0, key) !== void 0,
|
|
101
|
-
tm: (key) => lookupRaw(currentLocale(), void 0, key) ?? {},
|
|
102
|
-
rt: (message, ...args) => {
|
|
103
|
-
const { values, count } = parseTranslateArguments(args);
|
|
104
|
-
return resolveVueMessage(message, values, count, currentLocale());
|
|
105
|
-
},
|
|
106
|
-
d: globalDate,
|
|
107
|
-
n: globalNumber,
|
|
108
|
-
setLocaleMessage: (_locale, _messages) => {
|
|
109
|
-
warnDeprecatedRuntimeMessages("setLocaleMessage");
|
|
110
|
-
},
|
|
111
|
-
mergeLocaleMessage: (_locale, _messages) => {
|
|
112
|
-
warnDeprecatedRuntimeMessages("mergeLocaleMessage");
|
|
113
|
-
},
|
|
114
|
-
getLocaleMessage: (_locale) => {
|
|
115
|
-
warnDeprecatedRuntimeMessages("getLocaleMessage");
|
|
116
|
-
return {};
|
|
117
|
-
}
|
|
118
|
-
};
|
|
27
|
+
isGlobal: true,
|
|
28
|
+
options
|
|
29
|
+
});
|
|
119
30
|
/** Legacy Options-API facade (`this.$i18n`) with a string `locale`. */
|
|
120
31
|
const legacyI18n = {
|
|
121
32
|
get locale() {
|
|
@@ -127,44 +38,42 @@ const createI18n = ((options = {}) => {
|
|
|
127
38
|
get availableLocales() {
|
|
128
39
|
return getAvailableLocales();
|
|
129
40
|
},
|
|
130
|
-
t:
|
|
131
|
-
tc:
|
|
41
|
+
t: global.t,
|
|
42
|
+
tc: global.tc,
|
|
132
43
|
te: global.te,
|
|
133
44
|
tm: global.tm,
|
|
134
45
|
rt: global.rt,
|
|
135
|
-
d:
|
|
136
|
-
n:
|
|
137
|
-
};
|
|
138
|
-
const applyTranslateDirective = (element, binding) => {
|
|
139
|
-
const bindingValue = binding.value;
|
|
140
|
-
if (typeof bindingValue === "string") element.textContent = globalTranslate(bindingValue);
|
|
141
|
-
else if (bindingValue && typeof bindingValue === "object") {
|
|
142
|
-
const directiveArgs = [];
|
|
143
|
-
if (bindingValue.args) directiveArgs.push(bindingValue.args);
|
|
144
|
-
if (typeof bindingValue.choice === "number") directiveArgs.push(bindingValue.choice);
|
|
145
|
-
element.textContent = globalTranslate(bindingValue.path, ...directiveArgs);
|
|
146
|
-
}
|
|
46
|
+
d: global.d,
|
|
47
|
+
n: global.n
|
|
147
48
|
};
|
|
148
49
|
const i18nInstance = {
|
|
149
50
|
global,
|
|
150
51
|
mode: options.legacy === true ? "legacy" : "composition",
|
|
151
|
-
__optionsMessages:
|
|
152
|
-
install(app) {
|
|
52
|
+
__optionsMessages: options.messages,
|
|
53
|
+
install(app, installOptions = {}) {
|
|
153
54
|
if (!(INTLAYER_SYMBOL in app._context.provides)) installIntlayer(app, { locale: options.locale });
|
|
154
55
|
app.provide(I18nInjectionKey, i18nInstance);
|
|
155
|
-
app.config.globalProperties
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
56
|
+
const globalProperties = app.config.globalProperties;
|
|
57
|
+
globalProperties.$t = global.t;
|
|
58
|
+
globalProperties.$tc = global.tc;
|
|
59
|
+
globalProperties.$te = global.te;
|
|
60
|
+
globalProperties.$tm = global.tm;
|
|
61
|
+
globalProperties.$rt = global.rt;
|
|
62
|
+
globalProperties.$d = global.d;
|
|
63
|
+
globalProperties.$n = global.n;
|
|
64
|
+
globalProperties.$i18n = legacyI18n;
|
|
65
|
+
if (installOptions.globalInstall ?? true) {
|
|
66
|
+
for (const name of ["i18n-t", "I18nT"]) app.component(name, Translation);
|
|
67
|
+
for (const name of ["i18n-n", "I18nN"]) app.component(name, NumberFormat);
|
|
68
|
+
for (const name of ["i18n-d", "I18nD"]) app.component(name, DatetimeFormat);
|
|
69
|
+
}
|
|
70
|
+
app.directive("t", vTDirective(i18nInstance));
|
|
71
|
+
},
|
|
72
|
+
/**
|
|
73
|
+
* Releases the instance. Its composer holds no effect scope of its own:
|
|
74
|
+
* the locale lives in the intlayer client.
|
|
75
|
+
*/
|
|
76
|
+
dispose() {}
|
|
168
77
|
};
|
|
169
78
|
return i18nInstance;
|
|
170
79
|
});
|
|
@@ -176,7 +85,9 @@ const createI18n = ((options = {}) => {
|
|
|
176
85
|
*
|
|
177
86
|
* Supports vue-i18n's full message syntax: named (`{name}`) and list (`{0}`)
|
|
178
87
|
* interpolation, pipe choice messages (`'car | cars'` with a count argument),
|
|
179
|
-
* plus `te`/`tm`/`rt` and `Intl`-backed `d()`/`n()` formatters.
|
|
88
|
+
* plus `te`/`tm`/`rt` and `Intl`-backed `d()`/`n()` formatters. Formats,
|
|
89
|
+
* missing / post-translation handlers and option flags behave as on the
|
|
90
|
+
* global composer.
|
|
180
91
|
*
|
|
181
92
|
* @example
|
|
182
93
|
* ```ts
|
|
@@ -187,31 +98,25 @@ const createI18n = ((options = {}) => {
|
|
|
187
98
|
*/
|
|
188
99
|
const useI18n = ((options) => {
|
|
189
100
|
const { locale: currentLocale, setLocale, availableLocales } = useLocale();
|
|
190
|
-
const
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
const numberFormats = options?.numberFormats;
|
|
101
|
+
const instance = inject(I18nInjectionKey, void 0);
|
|
102
|
+
const isLocal = options?.useScope === "local" || options?.namespace !== void 0 || options?.messages !== void 0 || options?.datetimeFormats !== void 0 || options?.numberFormats !== void 0;
|
|
103
|
+
if (instance && !isLocal) return instance.global;
|
|
194
104
|
const localeRef = computed({
|
|
195
105
|
get: () => currentLocale.value,
|
|
196
106
|
set: (newLocale) => {
|
|
197
107
|
setLocale(newLocale);
|
|
198
108
|
}
|
|
199
109
|
});
|
|
200
|
-
|
|
201
|
-
return {
|
|
110
|
+
return createComposer({
|
|
202
111
|
locale: localeRef,
|
|
203
112
|
availableLocales,
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
},
|
|
212
|
-
d: (value, formatOrOptions) => formatDateValue(value, formatOrOptions, currentLocale.value, datetimeFormats),
|
|
213
|
-
n: (value, formatOrOptions) => formatNumberValue(value, formatOrOptions, currentLocale.value, numberFormats)
|
|
214
|
-
};
|
|
113
|
+
namespace: options?.namespace,
|
|
114
|
+
isGlobal: false,
|
|
115
|
+
options: {
|
|
116
|
+
messages: instance?.__optionsMessages,
|
|
117
|
+
...options
|
|
118
|
+
}
|
|
119
|
+
});
|
|
215
120
|
});
|
|
216
121
|
|
|
217
122
|
export { I18nInjectionKey, VERSION, createI18n, useI18n };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createI18n.mjs","names":[],"sources":["../../src/createI18n.ts"],"sourcesContent":["import { internationalization, log } from '@intlayer/config/built';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport { getIntlayer } from '@intlayer/core/interpreter';\nimport { navigatePath } from '@intlayer/core/messageFormat';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type {\n App,\n DirectiveBinding,\n InjectionKey,\n WritableComputedRef,\n} from 'vue';\nimport { computed, inject } from 'vue';\nimport type { createI18n as _createI18n, I18n } from 'vue-i18n';\nimport {\n createIntlayerClient,\n INTLAYER_SYMBOL,\n installIntlayer,\n useLocale,\n} from 'vue-intlayer';\nimport {\n type DateTimeFormatsConfig,\n formatDateValue,\n formatNumberValue,\n type NumberFormatsConfig,\n} from './formats';\nimport {\n parseTranslateArguments,\n resolveVueMessage,\n} from './resolveVueMessage';\nimport type { LooseComposer, TypedComposer } from './typedComposer';\n\nexport const VERSION = '9.13.1';\nexport const I18nInjectionKey: InjectionKey<I18n> = Symbol('global-i18n');\n\n/**\n * Dictionary key used for keys that carry no explicit namespace and are not\n * dot-namespaced (i18next-style flat keys, e.g. `t('greeting')`).\n */\nconst DEFAULT_NAMESPACE = 'translation';\n\n/**\n * Looks up a raw value for a vue-i18n key against intlayer dictionaries.\n *\n * Resolution order:\n * 1. `ns:key` prefix → dictionary `ns`\n * 2. The default namespace dictionary with the full dot-path\n * 3. The first key segment as the dictionary key (`'home.title'` →\n * dictionary `home`, path `title`)\n */\n/** Resolves a single dictionary by key and navigates to the given path. */\nconst lookupInDictionary = (\n locale: string,\n dictionaryKey: string,\n path: string\n): unknown => {\n try {\n const dictionary = getIntlayer(\n dictionaryKey as DictionaryKeys,\n locale as LocalesValues\n );\n const value = navigatePath(dictionary, path);\n if (value !== undefined && value !== null) return value;\n } catch {}\n return undefined;\n};\n\nconst lookupRaw = (\n locale: string,\n namespace: string | undefined,\n key: string\n): unknown => {\n let targetNamespace = namespace;\n let path = key;\n\n if (key.includes(':')) {\n const separatorIndex = key.indexOf(':');\n targetNamespace = key.slice(0, separatorIndex);\n path = key.slice(separatorIndex + 1);\n }\n\n // 1. Explicit namespace (from `useI18n({ namespace })` or a `ns:key` prefix)\n if (targetNamespace) {\n const value = lookupInDictionary(locale, targetNamespace, path);\n if (value !== undefined) return value;\n }\n\n // 2. First key segment as the dictionary key (`'home.title'` →\n // dictionary `home`, path `title`). This makes the global `t()` work\n // without a namespace, matching how intlayer splits dictionaries by key.\n if (path.includes('.')) {\n const separatorIndex = path.indexOf('.');\n const value = lookupInDictionary(\n locale,\n path.slice(0, separatorIndex),\n path.slice(separatorIndex + 1)\n );\n if (value !== undefined) return value;\n }\n\n // 3. Default `translation` bucket for flat, namespace-less keys.\n if (!targetNamespace) {\n const value = lookupInDictionary(locale, DEFAULT_NAMESPACE, path);\n if (value !== undefined) return value;\n }\n\n return undefined;\n};\n\n/** Translates a key with vue-i18n's polymorphic argument list. */\nconst translateKey = (\n locale: string,\n namespace: string | undefined,\n key: string,\n args: unknown[],\n fallbackMessages?: Record<string, unknown>\n): string => {\n const { values, count, defaultMessage } = parseTranslateArguments(args);\n\n const rawValue = lookupRaw(locale, namespace, key);\n\n if (rawValue === undefined) {\n if (fallbackMessages?.[locale]) {\n // Defer to the user's provided messages if not found in dictionaries\n const targetPath = namespace ? `${namespace}.${key}` : key;\n const fallbackValue = navigatePath(fallbackMessages[locale], targetPath);\n if (fallbackValue !== undefined) {\n return resolveVueMessage(\n fallbackValue,\n values,\n count,\n locale as LocalesValues\n );\n }\n }\n if (defaultMessage !== undefined) {\n return resolveVueMessage(\n defaultMessage,\n values,\n count,\n locale as LocalesValues\n );\n }\n return key;\n }\n\n return resolveVueMessage(rawValue, values, count, locale as LocalesValues);\n};\n\nconst getAvailableLocales = (): string[] =>\n internationalization?.locales?.map(String) ?? [];\n\nconst warnDeprecatedRuntimeMessages = (location: string) => {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize(location, ANSIColors.CYAN)} has no effect with ${colorize('@intlayer/vue-i18n', ANSIColors.MAGENTA)} — translations are managed by the compiled intlayer dictionaries.`\n );\n};\n\n/** Value accepted by the `v-t` directive. */\ntype TranslateDirectiveValue =\n | string\n | { path: string; args?: Record<string, unknown>; choice?: number };\n\nexport const createI18n: typeof _createI18n = ((\n options: Record<string, unknown> = {}\n) => {\n const fallbackMessages = options.messages as\n | Record<string, unknown>\n | undefined;\n\n if (\n options.messages !== undefined &&\n process.env.NODE_ENV === 'development'\n ) {\n const appLogger = getAppLogger({ log });\n appLogger(\n `${colorize('createI18n', ANSIColors.CYAN)}: the ${colorize('`messages`', ANSIColors.CYAN)} option is used as a fallback. For optimal bundle size, remove the locale JSON imports and use ${colorize('useDictionary', ANSIColors.CYAN)} or compile your intlayer dictionaries instead:\\n ${colorize('Before:', ANSIColors.GREY)} createI18n({ messages: { en, fr, … } })\\n ${colorize('After: ', ANSIColors.GREY)} createI18n({})`\n );\n }\n\n const client = createIntlayerClient(options.locale as LocalesValues);\n\n const datetimeFormats = options.datetimeFormats as\n | DateTimeFormatsConfig\n | undefined;\n const numberFormats = options.numberFormats as\n | NumberFormatsConfig\n | undefined;\n\n const currentLocale = (): string => String(client.locale.value);\n\n /** Writable ref matching vue-i18n's composition-mode `global.locale`. */\n const localeRef: WritableComputedRef<string> = computed({\n get: () => currentLocale(),\n set: (newLocale: string) => {\n client.setLocale(newLocale as LocalesValues);\n },\n });\n\n const globalTranslate = (key: string, ...args: unknown[]): string =>\n translateKey(currentLocale(), undefined, key, args, fallbackMessages);\n\n const globalDate = (\n value: Date | number | string,\n formatOrOptions?: string | Intl.DateTimeFormatOptions\n ): string =>\n formatDateValue(value, formatOrOptions, currentLocale(), datetimeFormats);\n\n const globalNumber = (\n value: number,\n formatOrOptions?: string | Intl.NumberFormatOptions\n ): string =>\n formatNumberValue(value, formatOrOptions, currentLocale(), numberFormats);\n\n const global = {\n locale: localeRef,\n availableLocales: getAvailableLocales(),\n fallbackLocale: (options.fallbackLocale ??\n internationalization?.defaultLocale) as string,\n t: globalTranslate,\n tc: globalTranslate,\n te: (key: string): boolean =>\n lookupRaw(currentLocale(), undefined, key) !== undefined,\n tm: (key: string): unknown =>\n lookupRaw(currentLocale(), undefined, key) ?? {},\n rt: (message: unknown, ...args: unknown[]): string => {\n const { values, count } = parseTranslateArguments(args);\n return resolveVueMessage(\n message,\n values,\n count,\n currentLocale() as LocalesValues\n );\n },\n d: globalDate,\n n: globalNumber,\n setLocaleMessage: (_locale: string, _messages: unknown) => {\n warnDeprecatedRuntimeMessages('setLocaleMessage');\n },\n mergeLocaleMessage: (_locale: string, _messages: unknown) => {\n warnDeprecatedRuntimeMessages('mergeLocaleMessage');\n },\n getLocaleMessage: (_locale: string): Record<string, unknown> => {\n warnDeprecatedRuntimeMessages('getLocaleMessage');\n // We do not load global dictionaries anymore for bundle optimization.\n // The user should use useDictionary or rely on manually provided messages.\n return {};\n },\n };\n\n /** Legacy Options-API facade (`this.$i18n`) with a string `locale`. */\n const legacyI18n = {\n get locale(): string {\n return currentLocale();\n },\n set locale(newLocale: string) {\n client.setLocale(newLocale as LocalesValues);\n },\n get availableLocales(): string[] {\n return getAvailableLocales();\n },\n t: globalTranslate,\n tc: globalTranslate,\n te: global.te,\n tm: global.tm,\n rt: global.rt,\n d: globalDate,\n n: globalNumber,\n };\n\n const applyTranslateDirective = (\n element: HTMLElement,\n binding: DirectiveBinding<TranslateDirectiveValue>\n ) => {\n const bindingValue = binding.value;\n if (typeof bindingValue === 'string') {\n element.textContent = globalTranslate(bindingValue);\n } else if (bindingValue && typeof bindingValue === 'object') {\n const directiveArgs: unknown[] = [];\n if (bindingValue.args) directiveArgs.push(bindingValue.args);\n if (typeof bindingValue.choice === 'number')\n directiveArgs.push(bindingValue.choice);\n element.textContent = globalTranslate(\n bindingValue.path,\n ...directiveArgs\n );\n }\n };\n\n const i18nInstance = {\n global,\n mode: options.legacy === true ? 'legacy' : 'composition',\n __optionsMessages: fallbackMessages,\n install(app: App) {\n // A framework integration (nuxt-intlayer) may have installed it already.\n const isIntlayerInstalled = INTLAYER_SYMBOL in app._context.provides;\n\n if (!isIntlayerInstalled) {\n installIntlayer(app, {\n locale: options.locale as LocalesValues,\n });\n }\n\n // Provide under I18nInjectionKey to satisfy inject(I18nInjectionKey) calls\n app.provide(I18nInjectionKey, i18nInstance as unknown as I18n);\n\n // Legacy API support ($t / $tc / $te / $tm / $rt / $d / $n / $i18n)\n app.config.globalProperties.$t = globalTranslate;\n (app.config.globalProperties as Record<string, unknown>).$tc =\n globalTranslate;\n (app.config.globalProperties as Record<string, unknown>).$te = global.te;\n (app.config.globalProperties as Record<string, unknown>).$tm = global.tm;\n (app.config.globalProperties as Record<string, unknown>).$rt = global.rt;\n (app.config.globalProperties as Record<string, unknown>).$d = globalDate;\n (app.config.globalProperties as Record<string, unknown>).$n =\n globalNumber;\n (app.config.globalProperties as Record<string, unknown>).$i18n =\n legacyI18n;\n\n // `v-t` directive support\n app.directive('t', {\n beforeMount: applyTranslateDirective,\n updated: applyTranslateDirective,\n });\n },\n };\n\n return i18nInstance as unknown as I18n;\n}) as typeof _createI18n;\n\n/**\n * Overload set for {@link useI18n}: with a `namespace` option the composer is\n * fully typed against that dictionary (keys and return values); without one\n * the root scope applies — the first segment of each key designates the\n * dictionary (`t('about.title')`).\n */\ntype UseI18n = {\n <N extends DictionaryKeys>(\n options: Record<string, unknown> & { namespace: N }\n ): TypedComposer<N>;\n (\n options?: Record<string, unknown> & { namespace?: undefined }\n ): LooseComposer;\n};\n\n/**\n * Composable providing a typed `t()` function scoped to a dictionary namespace.\n * Pass `{ namespace: 'myDict' }` to restrict keys to valid dot-notation paths\n * within that intlayer dictionary (autocompleted and validated at compile\n * time) and resolve return types from the content at each path.\n *\n * Supports vue-i18n's full message syntax: named (`{name}`) and list (`{0}`)\n * interpolation, pipe choice messages (`'car | cars'` with a count argument),\n * plus `te`/`tm`/`rt` and `Intl`-backed `d()`/`n()` formatters.\n *\n * @example\n * ```ts\n * const { t } = useI18n({ namespace: 'about' });\n * t('counter.label'); // ✓ typed key and return value\n * t('apples', 5); // pipe plural choice\n * ```\n */\nexport const useI18n = ((\n options?: Record<string, unknown> & { namespace?: string }\n) => {\n const { locale: currentLocale, setLocale, availableLocales } = useLocale();\n const instance = inject(I18nInjectionKey) as unknown as\n | Record<string, unknown>\n | undefined;\n const fallbackMessages = instance?.__optionsMessages as\n | Record<string, unknown>\n | undefined;\n\n const namespace = options?.namespace as string | undefined;\n\n const datetimeFormats = options?.datetimeFormats as\n | DateTimeFormatsConfig\n | undefined;\n const numberFormats = options?.numberFormats as\n | NumberFormatsConfig\n | undefined;\n\n const localeRef = computed({\n get: () => currentLocale.value as string,\n set: (newLocale: string) => {\n setLocale(newLocale as LocalesValues);\n },\n });\n\n const translate = (key: string, ...args: unknown[]): string =>\n translateKey(currentLocale.value, namespace, key, args, fallbackMessages);\n\n return {\n locale: localeRef,\n availableLocales: availableLocales as string[],\n t: translate,\n tc: translate,\n te: (key: string): boolean =>\n lookupRaw(currentLocale.value, namespace, key) !== undefined,\n tm: (key: string): unknown =>\n lookupRaw(currentLocale.value, namespace, key) ?? {},\n rt: (message: unknown, ...args: unknown[]): string => {\n const { values, count } = parseTranslateArguments(args);\n return resolveVueMessage(\n message,\n values,\n count,\n currentLocale.value as LocalesValues\n );\n },\n d: (\n value: Date | number | string,\n formatOrOptions?: string | Intl.DateTimeFormatOptions\n ): string =>\n formatDateValue(\n value,\n formatOrOptions,\n currentLocale.value,\n datetimeFormats\n ),\n n: (\n value: number,\n formatOrOptions?: string | Intl.NumberFormatOptions\n ): string =>\n formatNumberValue(\n value,\n formatOrOptions,\n currentLocale.value,\n numberFormats\n ),\n };\n}) as UseI18n;\n"],"mappings":";;;;;;;;;;;AAmCA,MAAa,UAAU;AACvB,MAAa,mBAAuC,OAAO,aAAa;;;;;AAMxE,MAAM,oBAAoB;;;;;;;;;;;AAY1B,MAAM,sBACJ,QACA,eACA,SACY;CACZ,IAAI;EACF,MAAM,aAAa,YACjB,eACA,MACF;EACA,MAAM,QAAQ,aAAa,YAAY,IAAI;EAC3C,IAAI,UAAU,UAAa,UAAU,MAAM,OAAO;CACpD,QAAQ,CAAC;AAEX;AAEA,MAAM,aACJ,QACA,WACA,QACY;CACZ,IAAI,kBAAkB;CACtB,IAAI,OAAO;CAEX,IAAI,IAAI,SAAS,GAAG,GAAG;EACrB,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O;GACtE,AAAC,IAAI,OAAO,iBAA6C,KAAK;GAC9D,AAAC,IAAI,OAAO,iBAA6C,KACvD;GACF,AAAC,IAAI,OAAO,iBAA6C,QACvD;GAGF,IAAI,UAAU,KAAK;IACjB,aAAa;IACb,SAAS;GACX,CAAC;EACH;CACF;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;AAkCA,MAAa,YACX,YACG;CACH,MAAM,EAAE,QAAQ,eAAe,WAAW,qBAAqB,UAAU;CAIzE,MAAM,mBAHW,OAAO,gBAGQ,CAAC,EAAE;CAInC,MAAM,YAAY,SAAS;CAE3B,MAAM,kBAAkB,SAAS;CAGjC,MAAM,gBAAgB,SAAS;CAI/B,MAAM,YAAY,SAAS;EACzB,WAAW,cAAc;EACzB,MAAM,cAAsB;GAC1B,UAAU,SAA0B;EACtC;CACF,CAAC;CAED,MAAM,aAAa,KAAa,GAAG,SACjC,aAAa,cAAc,OAAO,WAAW,KAAK,MAAM,gBAAgB;CAE1E,OAAO;EACL,QAAQ;EACU;EAClB,GAAG;EACH,IAAI;EACJ,KAAK,QACH,UAAU,cAAc,OAAO,WAAW,GAAG,MAAM;EACrD,KAAK,QACH,UAAU,cAAc,OAAO,WAAW,GAAG,KAAK,CAAC;EACrD,KAAK,SAAkB,GAAG,SAA4B;GACpD,MAAM,EAAE,QAAQ,UAAU,wBAAwB,IAAI;GACtD,OAAO,kBACL,SACA,QACA,OACA,cAAc,KAChB;EACF;EACA,IACE,OACA,oBAEA,gBACE,OACA,iBACA,cAAc,OACd,eACF;EACF,IACE,OACA,oBAEA,kBACE,OACA,iBACA,cAAc,OACd,aACF;CACJ;AACF"}
|
|
1
|
+
{"version":3,"file":"createI18n.mjs","names":[],"sources":["../../src/createI18n.ts"],"sourcesContent":["import { log } from '@intlayer/config/built';\nimport * as ANSIColors from '@intlayer/config/colors';\nimport { colorize, getAppLogger } from '@intlayer/config/logger';\nimport type {\n DictionaryKeys,\n LocalesValues,\n} from '@intlayer/types/module_augmentation';\nimport type { App, InjectionKey, WritableComputedRef } from 'vue';\nimport { computed, inject } from 'vue';\nimport type { createI18n as _createI18n, I18n } from 'vue-i18n';\nimport {\n createIntlayerClient,\n INTLAYER_SYMBOL,\n installIntlayer,\n useLocale,\n} from 'vue-intlayer';\nimport { DatetimeFormat, NumberFormat, Translation } from './components';\nimport {\n type ComposerOptions,\n createComposer,\n getAvailableLocales,\n} from './composer';\nimport type { LooseComposer, TypedComposer } from './typedComposer';\nimport { vTDirective } from './vTDirective';\n\nexport const VERSION = '9.13.1';\nexport const I18nInjectionKey: InjectionKey<I18n> = Symbol('global-i18n');\n\n/** Options of `app.use(i18n, options)`. */\ntype InstallOptions = { globalInstall?: boolean };\n\nexport const createI18n: typeof _createI18n = ((\n options: Record<string, unknown> = {}\n) => {\n if (\n options.messages !== undefined &&\n process.env.NODE_ENV === 'development'\n ) {\n getAppLogger({ log })(\n `${colorize('createI18n', ANSIColors.CYAN)}: the ${colorize('`messages`', ANSIColors.CYAN)} option is used as a fallback. For optimal bundle size, remove the locale JSON imports and use ${colorize('useDictionary', ANSIColors.CYAN)} or compile your intlayer dictionaries instead:\\n ${colorize('Before:', ANSIColors.GREY)} createI18n({ messages: { en, fr, … } })\\n ${colorize('After: ', ANSIColors.GREY)} createI18n({})`\n );\n }\n\n const client = createIntlayerClient(options.locale as LocalesValues);\n const currentLocale = (): string => String(client.locale.value);\n\n /** Writable ref matching vue-i18n's composition-mode `global.locale`. */\n const localeRef: WritableComputedRef<string> = computed({\n get: () => currentLocale(),\n set: (newLocale: string) => {\n client.setLocale(newLocale as LocalesValues);\n },\n });\n\n const global = createComposer({\n locale: localeRef,\n availableLocales: getAvailableLocales(),\n isGlobal: true,\n options: options as ComposerOptions,\n });\n\n /** Legacy Options-API facade (`this.$i18n`) with a string `locale`. */\n const legacyI18n = {\n get locale(): string {\n return currentLocale();\n },\n set locale(newLocale: string) {\n client.setLocale(newLocale as LocalesValues);\n },\n get availableLocales(): string[] {\n return getAvailableLocales();\n },\n t: global.t,\n tc: global.tc,\n te: global.te,\n tm: global.tm,\n rt: global.rt,\n d: global.d,\n n: global.n,\n };\n\n const i18nInstance = {\n global,\n mode: options.legacy === true ? 'legacy' : 'composition',\n __optionsMessages: options.messages,\n install(app: App, installOptions: InstallOptions = {}) {\n // A framework integration (nuxt-intlayer) may have installed it already.\n const isIntlayerInstalled = INTLAYER_SYMBOL in app._context.provides;\n\n if (!isIntlayerInstalled) {\n installIntlayer(app, {\n locale: options.locale as LocalesValues,\n });\n }\n\n app.provide(I18nInjectionKey, i18nInstance as unknown as I18n);\n\n // Legacy API support ($t / $tc / $te / $tm / $rt / $d / $n / $i18n)\n const globalProperties = app.config.globalProperties as Record<\n string,\n unknown\n >;\n globalProperties.$t = global.t;\n globalProperties.$tc = global.tc;\n globalProperties.$te = global.te;\n globalProperties.$tm = global.tm;\n globalProperties.$rt = global.rt;\n globalProperties.$d = global.d;\n globalProperties.$n = global.n;\n globalProperties.$i18n = legacyI18n;\n\n if (installOptions.globalInstall ?? true) {\n for (const name of ['i18n-t', 'I18nT'])\n app.component(name, Translation);\n for (const name of ['i18n-n', 'I18nN']) {\n app.component(name, NumberFormat);\n }\n for (const name of ['i18n-d', 'I18nD']) {\n app.component(name, DatetimeFormat);\n }\n }\n\n app.directive('t', vTDirective(i18nInstance as unknown as I18n));\n },\n /**\n * Releases the instance. Its composer holds no effect scope of its own:\n * the locale lives in the intlayer client.\n */\n dispose() {},\n };\n\n return i18nInstance as unknown as I18n;\n}) as typeof _createI18n;\n\n/**\n * Overload set for {@link useI18n}: with a `namespace` option the composer is\n * fully typed against that dictionary (keys and return values); without one\n * the root scope applies — the first segment of each key designates the\n * dictionary (`t('about.title')`).\n */\ntype UseI18n = {\n <N extends DictionaryKeys>(\n options: Record<string, unknown> & { namespace: N }\n ): TypedComposer<N>;\n (\n options?: Record<string, unknown> & { namespace?: undefined }\n ): LooseComposer;\n};\n\n/**\n * Composable providing a typed `t()` function scoped to a dictionary namespace.\n * Pass `{ namespace: 'myDict' }` to restrict keys to valid dot-notation paths\n * within that intlayer dictionary (autocompleted and validated at compile\n * time) and resolve return types from the content at each path.\n *\n * Supports vue-i18n's full message syntax: named (`{name}`) and list (`{0}`)\n * interpolation, pipe choice messages (`'car | cars'` with a count argument),\n * plus `te`/`tm`/`rt` and `Intl`-backed `d()`/`n()` formatters. Formats,\n * missing / post-translation handlers and option flags behave as on the\n * global composer.\n *\n * @example\n * ```ts\n * const { t } = useI18n({ namespace: 'about' });\n * t('counter.label'); // ✓ typed key and return value\n * t('apples', 5); // pipe plural choice\n * ```\n */\nexport const useI18n = ((\n options?: Record<string, unknown> & { namespace?: string }\n) => {\n const { locale: currentLocale, setLocale, availableLocales } = useLocale();\n const instance = inject(I18nInjectionKey, undefined) as unknown as\n | { global: unknown; __optionsMessages?: Record<string, unknown> }\n | undefined;\n\n // Without local options, upstream returns the global composer.\n const isLocal =\n options?.useScope === 'local' ||\n options?.namespace !== undefined ||\n options?.messages !== undefined ||\n options?.datetimeFormats !== undefined ||\n options?.numberFormats !== undefined;\n if (instance && !isLocal) return instance.global;\n\n const localeRef = computed({\n get: () => currentLocale.value as string,\n set: (newLocale: string) => {\n setLocale(newLocale as LocalesValues);\n },\n });\n\n return createComposer({\n locale: localeRef,\n availableLocales: availableLocales as string[],\n namespace: options?.namespace,\n isGlobal: false,\n options: {\n messages: instance?.__optionsMessages,\n ...(options as ComposerOptions | undefined),\n },\n });\n}) as UseI18n;\n"],"mappings":";;;;;;;;;;AAyBA,MAAa,UAAU;AACvB,MAAa,mBAAuC,OAAO,aAAa;AAKxE,MAAa,eACX,UAAmC,CAAC,MACjC;CACH,IACE,QAAQ,aAAa,mCACI,eAEzB,aAAa,EAAE,IAAI,CAAC,CAAC,CACnB,GAAG,SAAS,cAAc,WAAW,IAAI,EAAE,QAAQ,SAAS,cAAc,WAAW,IAAI,EAAE,iGAAiG,SAAS,iBAAiB,WAAW,IAAI,EAAE,qDAAqD,SAAS,WAAW,WAAW,IAAI,EAAE,8CAA8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KAAK,MAAM,QAAQ,CAAC,UAAU,OAAO,GACnC,IAAI,UAAU,MAAM,YAAY;IAElC,KAAK,MAAM,QAAQ,CAAC,UAAU,OAAO,GACnC,IAAI,UAAU,MAAM,cAAc;GAEtC;GAEA,IAAI,UAAU,KAAK,YAAY,YAA+B,CAAC;EACjE;;;;;EAKA,UAAU,CAAC;CACb;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,YACX,YACG;CACH,MAAM,EAAE,QAAQ,eAAe,WAAW,qBAAqB,UAAU;CACzE,MAAM,WAAW,OAAO,kBAAkB,MAAS;CAKnD,MAAM,UACJ,SAAS,aAAa,WACtB,SAAS,cAAc,UACvB,SAAS,aAAa,UACtB,SAAS,oBAAoB,UAC7B,SAAS,kBAAkB;CAC7B,IAAI,YAAY,CAAC,SAAS,OAAO,SAAS;CAE1C,MAAM,YAAY,SAAS;EACzB,WAAW,cAAc;EACzB,MAAM,cAAsB;GAC1B,UAAU,SAA0B;EACtC;CACF,CAAC;CAED,OAAO,eAAe;EACpB,QAAQ;EACU;EAClB,WAAW,SAAS;EACpB,UAAU;EACV,SAAS;GACP,UAAU,UAAU;GACpB,GAAI;EACN;CACF,CAAC;AACH"}
|
package/dist/esm/index.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { DatetimeFormat, I18nD, I18nN, I18nT, NumberFormat, Translation } from "./components.mjs";
|
|
1
2
|
import { I18nInjectionKey, VERSION, createI18n, useI18n } from "./createI18n.mjs";
|
|
2
3
|
import { useDictionary } from "./useDictionary.mjs";
|
|
3
4
|
import { useDictionaryDynamic } from "./useDictionaryDynamic.mjs";
|
|
5
|
+
import { vTDirective } from "./vTDirective.mjs";
|
|
4
6
|
|
|
5
|
-
export { I18nInjectionKey, VERSION, createI18n, useDictionary, useDictionaryDynamic, useI18n };
|
|
7
|
+
export { DatetimeFormat, I18nD, I18nInjectionKey, I18nN, I18nT, NumberFormat, Translation, VERSION, createI18n, useDictionary, useDictionaryDynamic, useI18n, vTDirective };
|
|
@@ -22,15 +22,27 @@ const getChoiceIndex = (choice, choicesLength) => {
|
|
|
22
22
|
* `t(key, named)`, `t(key, named, count)`, `t(key, list, count)`, …
|
|
23
23
|
*/
|
|
24
24
|
const parseTranslateArguments = (args) => {
|
|
25
|
-
const parsed = {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
parsed.
|
|
32
|
-
if (
|
|
33
|
-
|
|
25
|
+
const parsed = {
|
|
26
|
+
values: {},
|
|
27
|
+
options: {}
|
|
28
|
+
};
|
|
29
|
+
args.forEach((arg, index) => {
|
|
30
|
+
if (typeof arg === "number") parsed.count = arg;
|
|
31
|
+
else if (typeof arg === "string") parsed.defaultMessage = arg;
|
|
32
|
+
else if (Array.isArray(arg)) parsed.values = { ...arg.map(String) };
|
|
33
|
+
else if (typeof arg === "object" && arg !== null) {
|
|
34
|
+
if (index > 0) {
|
|
35
|
+
parsed.options = arg;
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const objectArg = arg;
|
|
39
|
+
parsed.values = objectArg;
|
|
40
|
+
if (typeof objectArg.plural === "number") parsed.count = objectArg.plural;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
const { options } = parsed;
|
|
44
|
+
if (typeof options.plural === "number") parsed.count = options.plural;
|
|
45
|
+
if (typeof options.default === "string") parsed.defaultMessage = options.default;
|
|
34
46
|
return parsed;
|
|
35
47
|
};
|
|
36
48
|
/**
|
|
@@ -39,7 +51,7 @@ const parseTranslateArguments = (args) => {
|
|
|
39
51
|
* interpolation, and intlayer nodes (`insert`, `plural`, `enu`) produced by
|
|
40
52
|
* dictionaries built with `format: 'vue-i18n'`.
|
|
41
53
|
*/
|
|
42
|
-
const resolveVueMessage = (value, values, count, locale) => {
|
|
54
|
+
const resolveVueMessage = (value, values, count, locale, choiceRule = getChoiceIndex) => {
|
|
43
55
|
const interpolationValues = { ...values };
|
|
44
56
|
if (count !== void 0) {
|
|
45
57
|
interpolationValues.count ??= count;
|
|
@@ -49,7 +61,7 @@ const resolveVueMessage = (value, values, count, locale) => {
|
|
|
49
61
|
let message = value;
|
|
50
62
|
if (/(?<!\\)\|/.test(message)) {
|
|
51
63
|
const parts = splitChoices(message);
|
|
52
|
-
message = parts[
|
|
64
|
+
message = parts[choiceRule(count ?? 1, parts.length)] ?? message;
|
|
53
65
|
}
|
|
54
66
|
return interpolateMessage(message, interpolationValues, locale);
|
|
55
67
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveVueMessage.mjs","names":[],"sources":["../../src/resolveVueMessage.ts"],"sourcesContent":["import {\n interpolateMessage,\n type MessageValues,\n resolveMessageNode,\n} from '@intlayer/core/messageFormat';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Splits a vue-i18n choice message (`'no car | one car | {count} cars'`)\n * into its parts, honoring escaped pipes (`\\|`).\n */\nexport const splitChoices = (message: string): string[] =>\n message.split(/(?<!\\\\)\\|/).map((part) => part.replace(/\\\\\\|/g, '|').trim());\n\n/**\n * vue-i18n's default choice rule:\n * - 2 choices: `1 | other` — 0 picks `other`, 1 picks the first part\n * - 3+ choices: `0 | 1 | other`\n */\nexport const getChoiceIndex = (\n choice: number,\n choicesLength: number\n): number => {\n const absoluteChoice = Math.abs(choice);\n\n if (choicesLength === 2) {\n return absoluteChoice ? (absoluteChoice > 1 ? 1 : 0) : 1;\n }\n\n return absoluteChoice ? Math.min(absoluteChoice, 2) : 0;\n};\n\n/** Arguments parsed from vue-i18n's polymorphic `t()` signatures. */\nexport type ParsedTranslateArguments = {\n /** Named (`{name}`) or list (`{0}`) interpolation values. */\n values: MessageValues;\n /** Plural choice count, when a number argument was provided. */\n count?: number;\n /** Default message, when a string argument was provided. */\n defaultMessage?: string;\n};\n\n/**\n * Parses vue-i18n's polymorphic `t()` arguments:\n * `t(key)`, `t(key, count)`, `t(key, defaultMsg)`, `t(key, list)`,\n * `t(key, named)`, `t(key, named, count)`, `t(key, list, count)`, …\n */\nexport const parseTranslateArguments = (\n args: unknown[]\n): ParsedTranslateArguments => {\n const parsed: ParsedTranslateArguments = { values: {} };\n\n
|
|
1
|
+
{"version":3,"file":"resolveVueMessage.mjs","names":[],"sources":["../../src/resolveVueMessage.ts"],"sourcesContent":["import {\n interpolateMessage,\n type MessageValues,\n resolveMessageNode,\n} from '@intlayer/core/messageFormat';\nimport type { LocalesValues } from '@intlayer/types/module_augmentation';\n\n/**\n * Splits a vue-i18n choice message (`'no car | one car | {count} cars'`)\n * into its parts, honoring escaped pipes (`\\|`).\n */\nexport const splitChoices = (message: string): string[] =>\n message.split(/(?<!\\\\)\\|/).map((part) => part.replace(/\\\\\\|/g, '|').trim());\n\n/**\n * vue-i18n's default choice rule:\n * - 2 choices: `1 | other` — 0 picks `other`, 1 picks the first part\n * - 3+ choices: `0 | 1 | other`\n */\nexport const getChoiceIndex = (\n choice: number,\n choicesLength: number\n): number => {\n const absoluteChoice = Math.abs(choice);\n\n if (choicesLength === 2) {\n return absoluteChoice ? (absoluteChoice > 1 ? 1 : 0) : 1;\n }\n\n return absoluteChoice ? Math.min(absoluteChoice, 2) : 0;\n};\n\n/** Picks the choice index of a pipe message: `(choice, choicesLength)`. */\nexport type ChoiceRule = (choice: number, choicesLength: number) => number;\n\n/** vue-i18n's per-call `t()` options (the last object argument). */\nexport type TranslateOptions = {\n /** Locale to translate in, instead of the composer's. */\n locale?: string;\n /** Default message, or `true` to use the key. */\n default?: string | boolean;\n /** Plural choice count. */\n plural?: number;\n /** HTML-escape interpolation values for this call. */\n escapeParameter?: boolean;\n [option: string]: unknown;\n};\n\n/** Arguments parsed from vue-i18n's polymorphic `t()` signatures. */\nexport type ParsedTranslateArguments = {\n /** Named (`{name}`) or list (`{0}`) interpolation values. */\n values: MessageValues;\n /** Plural choice count, when a number argument was provided. */\n count?: number;\n /** Default message, when a string argument was provided. */\n defaultMessage?: string;\n /** Per-call options, when an object follows the values or the count. */\n options: TranslateOptions;\n};\n\n/**\n * Parses vue-i18n's polymorphic `t()` arguments:\n * `t(key)`, `t(key, count)`, `t(key, defaultMsg)`, `t(key, list)`,\n * `t(key, named)`, `t(key, named, count)`, `t(key, list, count)`, …\n */\nexport const parseTranslateArguments = (\n args: unknown[]\n): ParsedTranslateArguments => {\n const parsed: ParsedTranslateArguments = { values: {}, options: {} };\n\n args.forEach((arg, index) => {\n if (typeof arg === 'number') {\n parsed.count = arg;\n } else if (typeof arg === 'string') {\n parsed.defaultMessage = arg;\n } else if (Array.isArray(arg)) {\n // List interpolation: ['a', 'b'] → { 0: 'a', 1: 'b' }\n parsed.values = { ...arg.map(String) } as unknown as MessageValues;\n } else if (typeof arg === 'object' && arg !== null) {\n // The first argument holds values; an object after it holds options.\n if (index > 0) {\n parsed.options = arg as TranslateOptions;\n return;\n }\n const objectArg = arg as MessageValues & { plural?: number };\n parsed.values = objectArg;\n if (typeof objectArg.plural === 'number') {\n parsed.count = objectArg.plural;\n }\n }\n });\n\n const { options } = parsed;\n if (typeof options.plural === 'number') parsed.count = options.plural;\n if (typeof options.default === 'string') {\n parsed.defaultMessage = options.default;\n }\n\n return parsed;\n};\n\n/**\n * Resolves a raw dictionary value the vue-i18n way: pipe-separated choice\n * messages (positional rule, not CLDR), named `{name}` and list `{0}`\n * interpolation, and intlayer nodes (`insert`, `plural`, `enu`) produced by\n * dictionaries built with `format: 'vue-i18n'`.\n */\nexport const resolveVueMessage = (\n value: unknown,\n values: MessageValues,\n count: number | undefined,\n locale: LocalesValues,\n choiceRule: ChoiceRule = getChoiceIndex\n): string => {\n const interpolationValues: MessageValues = { ...values };\n if (count !== undefined) {\n interpolationValues.count ??= count;\n interpolationValues.n ??= count;\n }\n\n if (typeof value === 'string') {\n let message = value;\n\n if (/(?<!\\\\)\\|/.test(message)) {\n const parts = splitChoices(message);\n message = parts[choiceRule(count ?? 1, parts.length)] ?? message;\n }\n\n return interpolateMessage(message, interpolationValues, locale);\n }\n\n const resolved = resolveMessageNode(value, interpolationValues, locale);\n\n return typeof resolved === 'string' ? resolved : String(resolved ?? '');\n};\n"],"mappings":";;;;;;;AAWA,MAAa,gBAAgB,YAC3B,QAAQ,MAAM,WAAW,CAAC,CAAC,KAAK,SAAS,KAAK,QAAQ,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC;;;;;;AAO5E,MAAa,kBACX,QACA,kBACW;CACX,MAAM,iBAAiB,KAAK,IAAI,MAAM;CAEtC,IAAI,kBAAkB,GACpB,OAAO,iBAAkB,iBAAiB,IAAI,IAAI,IAAK;CAGzD,OAAO,iBAAiB,KAAK,IAAI,gBAAgB,CAAC,IAAI;AACxD;;;;;;AAmCA,MAAa,2BACX,SAC6B;CAC7B,MAAM,SAAmC;EAAE,QAAQ,CAAC;EAAG,SAAS,CAAC;CAAE;CAEnE,KAAK,SAAS,KAAK,UAAU;EAC3B,IAAI,OAAO,QAAQ,UACjB,OAAO,QAAQ;OACV,IAAI,OAAO,QAAQ,UACxB,OAAO,iBAAiB;OACnB,IAAI,MAAM,QAAQ,GAAG,GAE1B,OAAO,SAAS,EAAE,GAAG,IAAI,IAAI,MAAM,EAAE;OAChC,IAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;GAElD,IAAI,QAAQ,GAAG;IACb,OAAO,UAAU;IACjB;GACF;GACA,MAAM,YAAY;GAClB,OAAO,SAAS;GAChB,IAAI,OAAO,UAAU,WAAW,UAC9B,OAAO,QAAQ,UAAU;EAE7B;CACF,CAAC;CAED,MAAM,EAAE,YAAY;CACpB,IAAI,OAAO,QAAQ,WAAW,UAAU,OAAO,QAAQ,QAAQ;CAC/D,IAAI,OAAO,QAAQ,YAAY,UAC7B,OAAO,iBAAiB,QAAQ;CAGlC,OAAO;AACT;;;;;;;AAQA,MAAa,qBACX,OACA,QACA,OACA,QACA,aAAyB,mBACd;CACX,MAAM,sBAAqC,EAAE,GAAG,OAAO;CACvD,IAAI,UAAU,QAAW;EACvB,oBAAoB,UAAU;EAC9B,oBAAoB,MAAM;CAC5B;CAEA,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,UAAU;EAEd,IAAI,YAAY,KAAK,OAAO,GAAG;GAC7B,MAAM,QAAQ,aAAa,OAAO;GAClC,UAAU,MAAM,WAAW,SAAS,GAAG,MAAM,MAAM,MAAM;EAC3D;EAEA,OAAO,mBAAmB,SAAS,qBAAqB,MAAM;CAChE;CAEA,MAAM,WAAW,mBAAmB,OAAO,qBAAqB,MAAM;CAEtE,OAAO,OAAO,aAAa,WAAW,WAAW,OAAO,YAAY,EAAE;AACxE"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// src/vTDirective.ts
|
|
2
|
+
/** `t()` arguments for a `v-t` value, as upstream builds them. */
|
|
3
|
+
const toTranslateArguments = (value) => {
|
|
4
|
+
if (typeof value === "string") return [
|
|
5
|
+
value,
|
|
6
|
+
{},
|
|
7
|
+
{}
|
|
8
|
+
];
|
|
9
|
+
if (!value || typeof value !== "object" || !("path" in value)) throw new Error("vue-i18n: v-t requires a key or an object with `path`");
|
|
10
|
+
const options = {};
|
|
11
|
+
if (typeof value.locale === "string") options.locale = value.locale;
|
|
12
|
+
if (typeof value.choice === "number") options.plural = value.choice;
|
|
13
|
+
if (typeof value.plural === "number") options.plural = value.plural;
|
|
14
|
+
return [
|
|
15
|
+
value.path,
|
|
16
|
+
value.args ?? {},
|
|
17
|
+
options
|
|
18
|
+
];
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Drop-in for vue-i18n's `vTDirective`: the `v-t` directive bound to an i18n
|
|
22
|
+
* instance. It writes the translation as the element text, on creation and
|
|
23
|
+
* update, and in server rendering through `getSSRProps`.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* app.directive('t', vTDirective(i18n));
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
const vTDirective = ((i18n) => {
|
|
31
|
+
const translate = (value) => {
|
|
32
|
+
const t = i18n.global.t;
|
|
33
|
+
const [key, ...args] = toTranslateArguments(value);
|
|
34
|
+
return t(key, ...args);
|
|
35
|
+
};
|
|
36
|
+
const applyText = (element, binding) => {
|
|
37
|
+
element.textContent = translate(binding.value);
|
|
38
|
+
};
|
|
39
|
+
return {
|
|
40
|
+
created: applyText,
|
|
41
|
+
beforeUpdate: applyText,
|
|
42
|
+
getSSRProps: (binding) => ({ textContent: translate(binding.value) })
|
|
43
|
+
};
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
export { vTDirective };
|
|
47
|
+
//# sourceMappingURL=vTDirective.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vTDirective.mjs","names":[],"sources":["../../src/vTDirective.ts"],"sourcesContent":["import type { DirectiveBinding, ObjectDirective } from 'vue';\nimport type { I18n, vTDirective as UpstreamVTDirective } from 'vue-i18n';\n\n/** Value of `v-t`: a key, or a key with its arguments. */\ntype TranslateDirectiveValue =\n | string\n | {\n path: string;\n locale?: string;\n args?: Record<string, unknown>;\n choice?: number;\n plural?: number;\n };\n\ntype Translate = (key: string, ...args: unknown[]) => string;\n\n/** `t()` arguments for a `v-t` value, as upstream builds them. */\nconst toTranslateArguments = (value: TranslateDirectiveValue): unknown[] => {\n if (typeof value === 'string') return [value, {}, {}];\n if (!value || typeof value !== 'object' || !('path' in value)) {\n throw new Error('vue-i18n: v-t requires a key or an object with `path`');\n }\n\n const options: Record<string, unknown> = {};\n if (typeof value.locale === 'string') options.locale = value.locale;\n if (typeof value.choice === 'number') options.plural = value.choice;\n if (typeof value.plural === 'number') options.plural = value.plural;\n return [value.path, value.args ?? {}, options];\n};\n\n/**\n * Drop-in for vue-i18n's `vTDirective`: the `v-t` directive bound to an i18n\n * instance. It writes the translation as the element text, on creation and\n * update, and in server rendering through `getSSRProps`.\n *\n * @example\n * ```ts\n * app.directive('t', vTDirective(i18n));\n * ```\n */\nexport const vTDirective = ((i18n: I18n) => {\n const translate = (value: TranslateDirectiveValue): string => {\n const t = (i18n.global as unknown as { t: Translate }).t;\n const [key, ...args] = toTranslateArguments(value);\n return t(key as string, ...args);\n };\n\n const applyText = (\n element: HTMLElement,\n binding: DirectiveBinding<TranslateDirectiveValue>\n ) => {\n element.textContent = translate(binding.value);\n };\n\n const directive: ObjectDirective<HTMLElement, TranslateDirectiveValue> = {\n created: applyText,\n beforeUpdate: applyText,\n getSSRProps: (binding) => ({ textContent: translate(binding.value) }),\n };\n\n return directive;\n}) as unknown as typeof UpstreamVTDirective;\n"],"mappings":";;AAiBA,MAAM,wBAAwB,UAA8C;CAC1E,IAAI,OAAO,UAAU,UAAU,OAAO;EAAC;EAAO,CAAC;EAAG,CAAC;CAAC;CACpD,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,EAAE,UAAU,QACrD,MAAM,IAAI,MAAM,uDAAuD;CAGzE,MAAM,UAAmC,CAAC;CAC1C,IAAI,OAAO,MAAM,WAAW,UAAU,QAAQ,SAAS,MAAM;CAC7D,IAAI,OAAO,MAAM,WAAW,UAAU,QAAQ,SAAS,MAAM;CAC7D,IAAI,OAAO,MAAM,WAAW,UAAU,QAAQ,SAAS,MAAM;CAC7D,OAAO;EAAC,MAAM;EAAM,MAAM,QAAQ,CAAC;EAAG;CAAO;AAC/C;;;;;;;;;;;AAYA,MAAa,gBAAgB,SAAe;CAC1C,MAAM,aAAa,UAA2C;EAC5D,MAAM,IAAK,KAAK,OAAuC;EACvD,MAAM,CAAC,KAAK,GAAG,QAAQ,qBAAqB,KAAK;EACjD,OAAO,EAAE,KAAe,GAAG,IAAI;CACjC;CAEA,MAAM,aACJ,SACA,YACG;EACH,QAAQ,cAAc,UAAU,QAAQ,KAAK;CAC/C;CAQA,OAAO;EALL,SAAS;EACT,cAAc;EACd,cAAc,aAAa,EAAE,aAAa,UAAU,QAAQ,KAAK,EAAE;CAGtD;AACjB"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { DatetimeFormat as DatetimeFormat$1, NumberFormat as NumberFormat$1, Translation as Translation$1 } from "vue-i18n";
|
|
2
|
+
/**
|
|
3
|
+
* Drop-in for vue-i18n's `<i18n-t>` (`Translation` / `I18nT`): translates
|
|
4
|
+
* `keypath`, rendering named slots (`#terms`) in place of `{terms}`, or the
|
|
5
|
+
* default slot's children in place of `{0}`, `{1}`….
|
|
6
|
+
*/
|
|
7
|
+
export declare const Translation: typeof Translation$1;
|
|
8
|
+
/**
|
|
9
|
+
* Drop-in for vue-i18n's `<i18n-n>` (`NumberFormat` / `I18nN`): formats
|
|
10
|
+
* `value` with a named or inline `format`, exposing each part as a slot.
|
|
11
|
+
*/
|
|
12
|
+
export declare const NumberFormat: typeof NumberFormat$1;
|
|
13
|
+
/**
|
|
14
|
+
* Drop-in for vue-i18n's `<i18n-d>` (`DatetimeFormat` / `I18nD`): formats
|
|
15
|
+
* `value` with a named or inline `format`, exposing each part as a slot.
|
|
16
|
+
*/
|
|
17
|
+
export declare const DatetimeFormat: typeof DatetimeFormat$1;
|
|
18
|
+
export declare const I18nT: new () => {
|
|
19
|
+
$props: import("vue").VNodeProps & import("vue-i18n").TranslationProps;
|
|
20
|
+
};
|
|
21
|
+
export declare const I18nN: new () => {
|
|
22
|
+
$props: import("vue").VNodeProps & import("vue-i18n").NumberFormatProps & import("vue-i18n").BaseFormatProps;
|
|
23
|
+
};
|
|
24
|
+
export declare const I18nD: new () => {
|
|
25
|
+
$props: import("vue").VNodeProps & import("vue-i18n").DatetimeFormatProps & import("vue-i18n").BaseFormatProps;
|
|
26
|
+
};
|
|
27
|
+
//# sourceMappingURL=components.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"components.d.ts","names":["UpstreamTranslation","UpstreamNumberFormat","UpstreamDatetimeFormat"],"sources":["../../src/components.ts"],"mappings":";;;;;;qBA+Da,oBA6DWA;;;;;qBA8CX,qBA2BWC;;;;;qBAMX,uBA8BWC;qBAEX;;;qBACA;;;qBACA"}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { DateTimeFormatsConfig, NumberFormatsConfig } from "./formats.js";
|
|
2
|
+
import { ChoiceRule } from "./resolveVueMessage.js";
|
|
3
|
+
import { ComputedRef, WritableComputedRef } from "vue";
|
|
4
|
+
/**
|
|
5
|
+
* Looks up a raw value for a vue-i18n key against intlayer dictionaries:
|
|
6
|
+
* 1. `ns:key` prefix or the composer namespace → dictionary `ns`
|
|
7
|
+
* 2. The first key segment as the dictionary key (`'home.title'` →
|
|
8
|
+
* dictionary `home`, path `title`)
|
|
9
|
+
* 3. The default `translation` dictionary for flat keys
|
|
10
|
+
*/
|
|
11
|
+
export declare const lookupRaw: (locale: string, namespace: string | undefined, key: string) => unknown;
|
|
12
|
+
/** Locales of the intlayer configuration. */
|
|
13
|
+
export declare const getAvailableLocales: () => string[];
|
|
14
|
+
/** Handler called for a missing key; a returned string is used as the result. */
|
|
15
|
+
export type MissingHandler = (locale: string, key: string, instance?: unknown, type?: string, ...values: unknown[]) => string | void;
|
|
16
|
+
/** Handler applied to every translation: `(translated, key) => result`. */
|
|
17
|
+
export type PostTranslationHandler = (translated: unknown, key: string) => unknown;
|
|
18
|
+
/** Options of `createI18n` / `useI18n` the composer reads. */
|
|
19
|
+
export type ComposerOptions = {
|
|
20
|
+
fallbackLocale?: unknown;
|
|
21
|
+
messages?: Record<string, unknown>;
|
|
22
|
+
datetimeFormats?: DateTimeFormatsConfig;
|
|
23
|
+
numberFormats?: NumberFormatsConfig;
|
|
24
|
+
modifiers?: Record<string, (value: unknown, type: string) => unknown>;
|
|
25
|
+
pluralRules?: Record<string, ChoiceRule>;
|
|
26
|
+
missing?: MissingHandler;
|
|
27
|
+
postTranslation?: PostTranslationHandler;
|
|
28
|
+
escapeParameter?: boolean;
|
|
29
|
+
fallbackFormat?: boolean;
|
|
30
|
+
fallbackRoot?: boolean;
|
|
31
|
+
fallbackWarn?: boolean | RegExp;
|
|
32
|
+
missingWarn?: boolean | RegExp;
|
|
33
|
+
warnHtmlMessage?: boolean;
|
|
34
|
+
inheritLocale?: boolean;
|
|
35
|
+
};
|
|
36
|
+
/** What a composer is built from. */
|
|
37
|
+
export type ComposerContext = {
|
|
38
|
+
/** Writable current locale. */
|
|
39
|
+
locale: WritableComputedRef<string>;
|
|
40
|
+
/** Available locales (the intlayer configuration's). */
|
|
41
|
+
availableLocales: string[];
|
|
42
|
+
/** `useI18n({ namespace })` dictionary, else the root scope. */
|
|
43
|
+
namespace?: string;
|
|
44
|
+
/** The global composer of `createI18n`, or a `useI18n` local one. */
|
|
45
|
+
isGlobal: boolean;
|
|
46
|
+
options: ComposerOptions;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Creates a vue-i18n Composition API composer backed by intlayer
|
|
50
|
+
* dictionaries: `t` / `te` / `tm` / `rt` / `d` / `n`, the format and handler
|
|
51
|
+
* accessors, and the option flags, as the global composer and `useI18n`
|
|
52
|
+
* expose them.
|
|
53
|
+
*
|
|
54
|
+
* `messages` passed to the options stay a lookup fallback; runtime message
|
|
55
|
+
* setters only warn, since dictionaries are compiled.
|
|
56
|
+
*/
|
|
57
|
+
export declare const createComposer: ({ locale, availableLocales, namespace, isGlobal, options }: ComposerContext) => {
|
|
58
|
+
id: number;
|
|
59
|
+
locale: WritableComputedRef<string, string>;
|
|
60
|
+
fallbackLocale: WritableComputedRef<string, string>;
|
|
61
|
+
availableLocales: string[];
|
|
62
|
+
isGlobal: boolean;
|
|
63
|
+
messages: ComputedRef<Record<string, unknown>>;
|
|
64
|
+
datetimeFormats: ComputedRef<DateTimeFormatsConfig>;
|
|
65
|
+
numberFormats: ComputedRef<NumberFormatsConfig>;
|
|
66
|
+
modifiers: Record<string, (value: unknown, type: string) => unknown>;
|
|
67
|
+
pluralRules: Record<string, ChoiceRule>;
|
|
68
|
+
escapeParameter: boolean;
|
|
69
|
+
fallbackFormat: boolean;
|
|
70
|
+
fallbackRoot: boolean;
|
|
71
|
+
fallbackWarn: boolean | RegExp;
|
|
72
|
+
missingWarn: boolean | RegExp;
|
|
73
|
+
warnHtmlMessage: boolean;
|
|
74
|
+
inheritLocale: boolean;
|
|
75
|
+
t: (key: string, ...args: unknown[]) => string;
|
|
76
|
+
tc: (key: string, ...args: unknown[]) => string;
|
|
77
|
+
te: (key: string, localeOverride?: string) => boolean;
|
|
78
|
+
tm: (key: string) => unknown;
|
|
79
|
+
rt: (message: unknown, ...args: unknown[]) => string;
|
|
80
|
+
d: (value: Date | number | string, formatOrOptions?: string | Intl.DateTimeFormatOptions, localeOverride?: string) => string;
|
|
81
|
+
n: (value: number, formatOrOptions?: string | Intl.NumberFormatOptions, localeOverride?: string) => string;
|
|
82
|
+
getLocaleMessage: (_locale: string) => Record<string, unknown>;
|
|
83
|
+
setLocaleMessage: (_locale: string, _messages: unknown) => void;
|
|
84
|
+
mergeLocaleMessage: (_locale: string, _messages: unknown) => void;
|
|
85
|
+
getDateTimeFormat: (formatLocale: string) => Record<string, Intl.DateTimeFormatOptions>;
|
|
86
|
+
setDateTimeFormat: (formatLocale: string, format: Record<string, Intl.DateTimeFormatOptions>) => void;
|
|
87
|
+
mergeDateTimeFormat: (formatLocale: string, format: Record<string, Intl.DateTimeFormatOptions>) => void;
|
|
88
|
+
getNumberFormat: (formatLocale: string) => Record<string, Intl.NumberFormatOptions>;
|
|
89
|
+
setNumberFormat: (formatLocale: string, format: Record<string, Intl.NumberFormatOptions>) => void;
|
|
90
|
+
mergeNumberFormat: (formatLocale: string, format: Record<string, Intl.NumberFormatOptions>) => void;
|
|
91
|
+
getMissingHandler: () => MissingHandler | null;
|
|
92
|
+
setMissingHandler: (handler: MissingHandler | null) => void;
|
|
93
|
+
getPostTranslationHandler: () => PostTranslationHandler | null;
|
|
94
|
+
setPostTranslationHandler: (handler: PostTranslationHandler | null) => void;
|
|
95
|
+
};
|
|
96
|
+
export type CompatComposer = ReturnType<typeof createComposer>;
|
|
97
|
+
//# sourceMappingURL=composer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"composer.d.ts","names":[],"sources":["../../src/composer.ts"],"mappings":";;;;;;;;;;qBA2Da,YAAS,gBACN,+BACe;;qBAoClB;;YAmCD,kBACV,gBACA,aACA,oBACA,kBACG;;YAIO,0BACV,qBACA;;YAIU;EACV;EACA,WAAW;EACX,kBAAkB;EAClB,gBAAgB;EAChB,YAAY,gBAAgB,gBAAgB;EAC5C,cAAc,eAAe;EAC7B,UAAU;EACV,kBAAkB;EAClB;EACA;EACA;EACA,yBAAyB;EACzB,wBAAwB;EACxB;EACA;;;YAIU;;EAEV,QAAQ;;EAER;;EAEA;;EAEA;EACA,SAAS;;;;;;;;;;;qBAcE,mBAAc,QAAA,kBAAA,WAAA,UAAA,WAMxB;;;;;;;;;EA3CkC,WAAA,gBAAA,gBAAO;;EAqLb;EAMD;EAMF;EAMA,wBAAU;EAMX,uBAAU;EAMN;EAMF;EAvIH,IAAA,gBAAM;;EA6IlB,KAAA,aAAM;EAGN,KAAA;EAEI,KAAA,qBAAO;EAzFd,IAAA,OAAA,wBAAsB,2BACF,KAAK,uBAAqB;EAW9C,IAAA,eAAM,2BACc,KAAK,qBAAmB;EAyFvB,mBAAA,oBAAS;EAIT,mBAAA,iBAAM;EAGJ,qBAAA,iBAAM;EAKpB,oBAAA,yBACb,eAAe,KAAK;EAGP,oBAAA,sBAAM,QACZ,eAAe,KAAK;EAKd,sBAAA,sBAAM,QACZ,eAAe,KAAK;EAQd,kBAAA,yBACb,eAAe,KAAK;EAGP,kBAAA,sBAAM,QACZ,eAAe,KAAK;EAKd,oBAAA,sBAAM,QACZ,eAAe,KAAK;EAQP,yBAAA;EACM,oBAAA,SAAA;EAGE,iCAAA;EAEM,4BAAA,SAAA;;YAM7B,iBAAiB,kBAAkB"}
|
|
@@ -27,7 +27,9 @@ type UseI18n = {
|
|
|
27
27
|
*
|
|
28
28
|
* Supports vue-i18n's full message syntax: named (`{name}`) and list (`{0}`)
|
|
29
29
|
* interpolation, pipe choice messages (`'car | cars'` with a count argument),
|
|
30
|
-
* plus `te`/`tm`/`rt` and `Intl`-backed `d()`/`n()` formatters.
|
|
30
|
+
* plus `te`/`tm`/`rt` and `Intl`-backed `d()`/`n()` formatters. Formats,
|
|
31
|
+
* missing / post-translation handlers and option flags behave as on the
|
|
32
|
+
* global composer.
|
|
31
33
|
*
|
|
32
34
|
* @example
|
|
33
35
|
* ```ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createI18n.d.ts","names":["_createI18n"],"sources":["../../src/createI18n.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"createI18n.d.ts","names":["_createI18n"],"sources":["../../src/createI18n.ts"],"mappings":";;;;qBAyBa;qBACA,kBAAkB,aAAa;qBAK/B,mBAAmBA;;;;;;;KA6G3B;GACF,UAAU,gBACT,SAAS;IAA4B,WAAW;MAC/C,cAAc;GAEf,UAAU;IAA4B;MACrC;;;;;;;;;;;;;;;;;;;;;qBAsBQ,SAkCP"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { DatetimeFormat, I18nD, I18nN, I18nT, NumberFormat, Translation } from "./components.js";
|
|
1
2
|
import { I18nInjectionKey, VERSION, createI18n, useI18n } from "./createI18n.js";
|
|
2
3
|
import { ContentAtPath, LooseComposer, ScopedComposer, ScopedDotPaths, TranslatedValue, TypedComposer } from "./typedComposer.js";
|
|
3
4
|
import { useDictionary } from "./useDictionary.js";
|
|
4
5
|
import { useDictionaryDynamic } from "./useDictionaryDynamic.js";
|
|
6
|
+
import { vTDirective } from "./vTDirective.js";
|
|
5
7
|
import { Composer, I18n, I18nOptions, UseI18nOptions } from "vue-i18n";
|
|
6
|
-
export { type Composer, type ContentAtPath, type I18n, I18nInjectionKey, type I18nOptions, type LooseComposer, type ScopedComposer, type ScopedDotPaths, type TranslatedValue, type TypedComposer, type UseI18nOptions, VERSION, createI18n, useDictionary, useDictionaryDynamic, useI18n };
|
|
8
|
+
export { type Composer, type ContentAtPath, DatetimeFormat, type I18n, I18nD, I18nInjectionKey, I18nN, type I18nOptions, I18nT, type LooseComposer, NumberFormat, type ScopedComposer, type ScopedDotPaths, type TranslatedValue, Translation, type TypedComposer, type UseI18nOptions, VERSION, createI18n, useDictionary, useDictionaryDynamic, useI18n, vTDirective };
|
|
@@ -11,6 +11,20 @@ export declare const splitChoices: (message: string) => string[];
|
|
|
11
11
|
* - 3+ choices: `0 | 1 | other`
|
|
12
12
|
*/
|
|
13
13
|
export declare const getChoiceIndex: (choice: number, choicesLength: number) => number;
|
|
14
|
+
/** Picks the choice index of a pipe message: `(choice, choicesLength)`. */
|
|
15
|
+
export type ChoiceRule = (choice: number, choicesLength: number) => number;
|
|
16
|
+
/** vue-i18n's per-call `t()` options (the last object argument). */
|
|
17
|
+
export type TranslateOptions = {
|
|
18
|
+
/** Locale to translate in, instead of the composer's. */
|
|
19
|
+
locale?: string;
|
|
20
|
+
/** Default message, or `true` to use the key. */
|
|
21
|
+
default?: string | boolean;
|
|
22
|
+
/** Plural choice count. */
|
|
23
|
+
plural?: number;
|
|
24
|
+
/** HTML-escape interpolation values for this call. */
|
|
25
|
+
escapeParameter?: boolean;
|
|
26
|
+
[option: string]: unknown;
|
|
27
|
+
};
|
|
14
28
|
/** Arguments parsed from vue-i18n's polymorphic `t()` signatures. */
|
|
15
29
|
export type ParsedTranslateArguments = {
|
|
16
30
|
/** Named (`{name}`) or list (`{0}`) interpolation values. */
|
|
@@ -19,6 +33,8 @@ export type ParsedTranslateArguments = {
|
|
|
19
33
|
count?: number;
|
|
20
34
|
/** Default message, when a string argument was provided. */
|
|
21
35
|
defaultMessage?: string;
|
|
36
|
+
/** Per-call options, when an object follows the values or the count. */
|
|
37
|
+
options: TranslateOptions;
|
|
22
38
|
};
|
|
23
39
|
/**
|
|
24
40
|
* Parses vue-i18n's polymorphic `t()` arguments:
|
|
@@ -32,5 +48,5 @@ export declare const parseTranslateArguments: (args: unknown[]) => ParsedTransla
|
|
|
32
48
|
* interpolation, and intlayer nodes (`insert`, `plural`, `enu`) produced by
|
|
33
49
|
* dictionaries built with `format: 'vue-i18n'`.
|
|
34
50
|
*/
|
|
35
|
-
export declare const resolveVueMessage: (value: unknown, values: MessageValues, count: number | undefined, locale: LocalesValues) => string;
|
|
51
|
+
export declare const resolveVueMessage: (value: unknown, values: MessageValues, count: number | undefined, locale: LocalesValues, choiceRule?: ChoiceRule) => string;
|
|
36
52
|
//# sourceMappingURL=resolveVueMessage.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolveVueMessage.d.ts","names":[],"sources":["../../src/resolveVueMessage.ts"],"mappings":";;;;;;qBAWa,eAAY;;;;;;qBAQZ,iBAAc,gBACX;;YAaJ;;EAEV,QAAQ;;EAER;;EAEA;;;;;;;
|
|
1
|
+
{"version":3,"file":"resolveVueMessage.d.ts","names":[],"sources":["../../src/resolveVueMessage.ts"],"mappings":";;;;;;qBAWa,eAAY;;;;;;qBAQZ,iBAAc,gBACX;;YAaJ,cAAc,gBAAgB;;YAG9B;;EAEV;;EAEA;;EAEA;;EAEA;GACC;;;YAIS;;EAEV,QAAQ;;EAER;;EAEA;;EAEA,SAAS;;;;;;;qBAQE,0BAAuB,oBAEjC;;;;;;;qBAwCU,oBAAiB,gBACd,QACN,eAAa,2BACI,QACjB,eAAa,aACT"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { vTDirective as vTDirective$1 } from "vue-i18n";
|
|
2
|
+
/**
|
|
3
|
+
* Drop-in for vue-i18n's `vTDirective`: the `v-t` directive bound to an i18n
|
|
4
|
+
* instance. It writes the translation as the element text, on creation and
|
|
5
|
+
* update, and in server rendering through `getSSRProps`.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* app.directive('t', vTDirective(i18n));
|
|
10
|
+
* ```
|
|
11
|
+
*/
|
|
12
|
+
export declare const vTDirective: typeof vTDirective$1;
|
|
13
|
+
//# sourceMappingURL=vTDirective.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vTDirective.d.ts","names":["UpstreamVTDirective"],"sources":["../../src/vTDirective.ts"],"mappings":";;;;;;;;;;;qBAwCa,oBAqBWA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@intlayer/vue-i18n",
|
|
3
|
-
"version": "9.9.
|
|
3
|
+
"version": "9.9.4",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "vue-i18n API adapter for intlayer — useI18n, createI18n, and installIntlayer backed by vue-intlayer",
|
|
6
6
|
"keywords": [
|
|
@@ -76,13 +76,13 @@
|
|
|
76
76
|
"typecheck": "tsc --noEmit --project tsconfig.types.json"
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
|
-
"@intlayer/config": "9.9.
|
|
80
|
-
"@intlayer/core": "9.9.
|
|
81
|
-
"@intlayer/dictionaries-entry": "9.9.
|
|
82
|
-
"@intlayer/engine": "9.9.
|
|
83
|
-
"@intlayer/types": "9.9.
|
|
84
|
-
"vite-intlayer": "9.9.
|
|
85
|
-
"vue-intlayer": "9.9.
|
|
79
|
+
"@intlayer/config": "9.9.4",
|
|
80
|
+
"@intlayer/core": "9.9.4",
|
|
81
|
+
"@intlayer/dictionaries-entry": "9.9.4",
|
|
82
|
+
"@intlayer/engine": "9.9.4",
|
|
83
|
+
"@intlayer/types": "9.9.4",
|
|
84
|
+
"vite-intlayer": "9.9.4",
|
|
85
|
+
"vue-intlayer": "9.9.4"
|
|
86
86
|
},
|
|
87
87
|
"devDependencies": {
|
|
88
88
|
"@types/node": "^26",
|