@fluentic/i18n 0.1.0-beta.1 → 0.1.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +9 -1
- package/dist/adapter.d.ts +6 -4
- package/dist/adapter.js +4 -3
- package/dist/compiled.d.ts +26 -24
- package/dist/compiled.js +4 -2
- package/dist/compiled.js.map +1 -1
- package/dist/compiler-support.d.ts +4 -0
- package/dist/compiler-support.js +4 -0
- package/dist/core/format.d.ts +11 -0
- package/dist/core/i18n.d.ts +26 -0
- package/dist/core/index.d.ts +1 -5
- package/dist/core/index.js +3 -2
- package/dist/core/types.d.ts +79 -0
- package/dist/hash-VJlyT31Z.js +90 -0
- package/dist/hash-VJlyT31Z.js.map +1 -0
- package/dist/hydration-store-BK6UxrtJ.js +13 -0
- package/dist/hydration-store-BK6UxrtJ.js.map +1 -0
- package/dist/hydration-store.d.ts +29 -0
- package/dist/hydration.d.ts +7 -0
- package/dist/hydration.js +35 -0
- package/dist/hydration.js.map +1 -0
- package/dist/index.d.ts +6 -6
- package/dist/index.js +3 -2
- package/dist/{interpreter-Dld8QyOI.js → interpreter-BfzvLLrD.js} +4 -3
- package/dist/interpreter-BfzvLLrD.js.map +1 -0
- package/dist/{manager-BW778X1Y.js → manager-BgMJWXWY.js} +21 -31
- package/dist/manager-BgMJWXWY.js.map +1 -0
- package/dist/manager.d.ts +62 -0
- package/dist/message-D4jK2Lzc.js +9 -0
- package/dist/message-D4jK2Lzc.js.map +1 -0
- package/dist/react.d.ts +41 -46
- package/dist/react.js +12 -8
- package/dist/react.js.map +1 -1
- package/dist/registry-manager.d.ts +7 -0
- package/dist/runtime-DXnGeCBw.js +110 -0
- package/dist/runtime-DXnGeCBw.js.map +1 -0
- package/dist/shared/compact.d.ts +5 -0
- package/dist/shared/formatting.d.ts +11 -0
- package/dist/shared/hash.d.ts +7 -0
- package/dist/shared/interpreter.d.ts +2 -0
- package/dist/shared/message.d.ts +2 -0
- package/dist/shared/runtime.d.ts +49 -0
- package/dist/{src-BovRx-mX.js → src-ON68XIog.js} +9 -7
- package/dist/src-ON68XIog.js.map +1 -0
- package/dist/state-manager.d.ts +6 -0
- package/dist/state.d.ts +8 -0
- package/dist/storage-manager.d.ts +14 -0
- package/dist/{translation-manager-C79eKu2K.js → translation-manager-BkmFnlb_.js} +5 -104
- package/dist/translation-manager-BkmFnlb_.js.map +1 -0
- package/dist/translation-manager.d.ts +34 -0
- package/dist/translation.d.ts +20 -0
- package/dist/types-BkDsJfVD.js.map +1 -1
- package/dist/types.d.ts +3 -2
- package/package.json +20 -54
- package/dist/adapter-CWC8rng-.d.ts +0 -178
- package/dist/analyze-CdXCxQDg.d.ts +0 -14
- package/dist/compact-CJ0OWoIv.d.ts +0 -7
- package/dist/compiler-BZtB9WLi.js +0 -365
- package/dist/compiler-BZtB9WLi.js.map +0 -1
- package/dist/compiler.d.ts +0 -35
- package/dist/compiler.js +0 -3
- package/dist/i18n-CfYNwubL.d.ts +0 -25
- package/dist/interpreter-Dld8QyOI.js.map +0 -1
- package/dist/manager-BW778X1Y.js.map +0 -1
- package/dist/options-DE7vYj0e.d.ts +0 -7
- package/dist/options-Dxxx0aOz.js +0 -23
- package/dist/options-Dxxx0aOz.js.map +0 -1
- package/dist/plugin/babel.d.ts +0 -11
- package/dist/plugin/babel.js +0 -31
- package/dist/plugin/babel.js.map +0 -1
- package/dist/plugin/esbuild.d.ts +0 -7
- package/dist/plugin/esbuild.js +0 -37
- package/dist/plugin/esbuild.js.map +0 -1
- package/dist/plugin/rollup.d.ts +0 -30
- package/dist/plugin/rollup.js +0 -34
- package/dist/plugin/rollup.js.map +0 -1
- package/dist/plugin/vite.d.ts +0 -31
- package/dist/plugin/vite.js +0 -11
- package/dist/plugin/vite.js.map +0 -1
- package/dist/plugin/webpack-loader.d.ts +0 -3
- package/dist/plugin/webpack-loader.js +0 -21
- package/dist/plugin/webpack-loader.js.map +0 -1
- package/dist/plugin/webpack.d.ts +0 -8
- package/dist/plugin/webpack.js +0 -22
- package/dist/plugin/webpack.js.map +0 -1
- package/dist/src-BovRx-mX.js.map +0 -1
- package/dist/translation-manager-C79eKu2K.js.map +0 -1
- package/dist/types-BuGoCU3P.d.ts +0 -75
- package/dist-cjs/babel.cjs +0 -379
- package/dist-cjs/babel.cjs.map +0 -1
- package/src/adapter.ts +0 -6
- package/src/compiled.ts +0 -116
- package/src/compiler/analyze.ts +0 -182
- package/src/compiler/index.ts +0 -208
- package/src/compiler/message.ts +0 -74
- package/src/core/format.ts +0 -40
- package/src/core/i18n.ts +0 -124
- package/src/core/index.ts +0 -1
- package/src/core/types.ts +0 -121
- package/src/index.ts +0 -9
- package/src/manager.ts +0 -175
- package/src/plugin/babel.ts +0 -34
- package/src/plugin/esbuild.ts +0 -45
- package/src/plugin/options.ts +0 -24
- package/src/plugin/rollup.ts +0 -29
- package/src/plugin/vite.ts +0 -6
- package/src/plugin/webpack-loader.ts +0 -22
- package/src/plugin/webpack.ts +0 -15
- package/src/react.ts +0 -97
- package/src/registry-manager.ts +0 -3
- package/src/shared/compact.ts +0 -51
- package/src/shared/formatting.ts +0 -121
- package/src/shared/interpreter.ts +0 -128
- package/src/shared/runtime.ts +0 -131
- package/src/state-manager.ts +0 -29
- package/src/state.ts +0 -20
- package/src/storage-manager.ts +0 -47
- package/src/translation-manager.ts +0 -82
- package/src/translation.ts +0 -106
- package/src/types.ts +0 -2
package/src/shared/formatting.ts
DELETED
|
@@ -1,121 +0,0 @@
|
|
|
1
|
-
import { isMessageDescriptor, isMessageSchemaValue, isMessageTagHandler } from '../core/types';
|
|
2
|
-
import type { MessageFormatOptions, MessageParam } from '../core/types';
|
|
3
|
-
import type { CompactMessage } from './compact';
|
|
4
|
-
import { type Formats, getFormats, getRuntime, type Runtime } from './runtime';
|
|
5
|
-
|
|
6
|
-
export type Engine = (
|
|
7
|
-
message: CompactMessage,
|
|
8
|
-
languageId: string,
|
|
9
|
-
formats: Partial<Formats>,
|
|
10
|
-
values: Record<string, unknown>,
|
|
11
|
-
compiled: boolean,
|
|
12
|
-
) => unknown[];
|
|
13
|
-
|
|
14
|
-
export type Formatting = ReturnType<typeof createFormatting>;
|
|
15
|
-
|
|
16
|
-
export function createFormatting(
|
|
17
|
-
engine: Engine,
|
|
18
|
-
compiled = false,
|
|
19
|
-
getCompiledId?: (context: string | null, message: string) => string,
|
|
20
|
-
) {
|
|
21
|
-
const getMessageParts = (options: MessageFormatOptions, runtime = getRuntime(), jsx = false): unknown[] => {
|
|
22
|
-
if (!runtime.ready) throw new Error('[i18n] runtime is not ready; await adapter initialization before rendering');
|
|
23
|
-
|
|
24
|
-
const languageId = options.languageId ?? runtime.languageId;
|
|
25
|
-
|
|
26
|
-
const descriptor = isMessageDescriptor(options.msg)
|
|
27
|
-
? options.msg
|
|
28
|
-
: { text: options.msg, context: null, schema: {}, compiled: undefined };
|
|
29
|
-
|
|
30
|
-
if (compiled && !descriptor.compiled) {
|
|
31
|
-
throw new TypeError('[i18n] compiled runtime requires compiled messages; enable the Fluentic plugin');
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const key = descriptor.compiled?.[0] ?? descriptor.text;
|
|
35
|
-
|
|
36
|
-
const translated = runtime.translationsEnabled
|
|
37
|
-
? runtime.translationGetter?.({
|
|
38
|
-
languageId,
|
|
39
|
-
context: descriptor.compiled ? null : descriptor.context,
|
|
40
|
-
message: key,
|
|
41
|
-
getCompiledId: getCompiledId && !descriptor.compiled
|
|
42
|
-
? () => getCompiledId(descriptor.context, descriptor.text)
|
|
43
|
-
: undefined,
|
|
44
|
-
})
|
|
45
|
-
: null;
|
|
46
|
-
const compiledTranslation = typeof translated === 'object' && translated !== null && !Array.isArray(translated);
|
|
47
|
-
if (compiled && typeof translated === 'string') {
|
|
48
|
-
throw new TypeError('[i18n] compiled runtime requires compiled translations');
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const message = compiledTranslation
|
|
52
|
-
? translated.compiled
|
|
53
|
-
: translated ?? descriptor.compiled?.[1] ?? descriptor.text;
|
|
54
|
-
const isCompiled = compiled || compiledTranslation || Array.isArray(message);
|
|
55
|
-
const values: Record<string, unknown> = {};
|
|
56
|
-
|
|
57
|
-
const resolve = (value: MessageParam): unknown => {
|
|
58
|
-
if (isMessageTagHandler(value)) return value;
|
|
59
|
-
if (isMessageSchemaValue(value)) {
|
|
60
|
-
throw new Error('[i18n] Message parameter schemas are only valid in t.msg(); pass a real value');
|
|
61
|
-
}
|
|
62
|
-
if (typeof value === 'function') return resolve(value({ languageId }) as MessageParam);
|
|
63
|
-
if (isMessageDescriptor(value)) return getText({ msg: value, languageId }, runtime);
|
|
64
|
-
|
|
65
|
-
return value;
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
for (const [key, value] of Object.entries(options.params ?? {})) values[key] = resolve(value);
|
|
69
|
-
values.break = jsx ? runtime.jsxLineBreak : '\n';
|
|
70
|
-
|
|
71
|
-
for (const [key, expected] of Object.entries(descriptor.schema)) {
|
|
72
|
-
if (key !== 'break' && (!options.params || options.params[key] === undefined)) {
|
|
73
|
-
throw new Error('[i18n] Missing required message parameter: ' + key);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const value = values[key];
|
|
77
|
-
|
|
78
|
-
const valid = expected === String
|
|
79
|
-
? typeof value === 'string'
|
|
80
|
-
: expected === Number
|
|
81
|
-
? typeof value === 'number'
|
|
82
|
-
: expected === Boolean
|
|
83
|
-
? typeof value === 'boolean'
|
|
84
|
-
: expected === Date
|
|
85
|
-
? value instanceof Date && !Number.isNaN(value.getTime())
|
|
86
|
-
: true;
|
|
87
|
-
|
|
88
|
-
if (!valid) {
|
|
89
|
-
throw new Error('[i18n] Message parameter "' + key + '" must be a ' + (expected as { name: string; }).name);
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
return engine(message, languageId, getFormats(runtime, languageId), values, isCompiled);
|
|
94
|
-
};
|
|
95
|
-
|
|
96
|
-
const getText = (options: MessageFormatOptions, runtime = getRuntime()): string => {
|
|
97
|
-
const parts = getMessageParts(options, runtime);
|
|
98
|
-
|
|
99
|
-
if (parts.some((part) => typeof part !== 'string')) {
|
|
100
|
-
throw new Error('[i18n] t.text() received a non-text rich value; use t.jsx() instead');
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
return parts.join('');
|
|
104
|
-
};
|
|
105
|
-
|
|
106
|
-
const getJsx = (options: MessageFormatOptions): unknown => {
|
|
107
|
-
const runtime = getRuntime();
|
|
108
|
-
|
|
109
|
-
if (!runtime.jsxHandler) throw new Error('[i18n] JSX renderer is not configured; initialize a platform adapter');
|
|
110
|
-
// Capture notranslate at element creation, not at React's later render.
|
|
111
|
-
const enabled = runtime.translationsEnabled;
|
|
112
|
-
|
|
113
|
-
return runtime.jsxHandler(
|
|
114
|
-
options,
|
|
115
|
-
(current = getRuntime()) =>
|
|
116
|
-
getMessageParts(options, enabled ? current : { ...current, translationsEnabled: false }, true),
|
|
117
|
-
);
|
|
118
|
-
};
|
|
119
|
-
|
|
120
|
-
return { getText, getJsx, getMessageParts, formatMessage: getText };
|
|
121
|
-
}
|
|
@@ -1,128 +0,0 @@
|
|
|
1
|
-
import type { CompactMessage } from './compact';
|
|
2
|
-
import type { Engine } from './formatting';
|
|
3
|
-
|
|
4
|
-
const numberCache = new Map<string, Intl.NumberFormat>();
|
|
5
|
-
const dateCache = new Map<string, Intl.DateTimeFormat>();
|
|
6
|
-
const pluralCache = new Map<string, Intl.PluralRules>();
|
|
7
|
-
|
|
8
|
-
function cached<T>(map: Map<string, T>, key: string, create: () => T): T {
|
|
9
|
-
let value = map.get(key);
|
|
10
|
-
|
|
11
|
-
if (!value) {
|
|
12
|
-
value = create();
|
|
13
|
-
if (map.size >= 100) map.delete(map.keys().next().value!);
|
|
14
|
-
map.set(key, value);
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
return value;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
const numberDefaults = {
|
|
21
|
-
integer: { maximumFractionDigits: 0 },
|
|
22
|
-
currency: { style: 'currency' },
|
|
23
|
-
percent: { style: 'percent' },
|
|
24
|
-
};
|
|
25
|
-
const dateDefaults = {
|
|
26
|
-
short: { month: 'numeric', day: 'numeric', year: '2-digit' },
|
|
27
|
-
medium: { month: 'short', day: 'numeric', year: 'numeric' },
|
|
28
|
-
long: { month: 'long', day: 'numeric', year: 'numeric' },
|
|
29
|
-
full: { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' },
|
|
30
|
-
};
|
|
31
|
-
const timeDefaults = {
|
|
32
|
-
short: { hour: 'numeric', minute: 'numeric' },
|
|
33
|
-
medium: { hour: 'numeric', minute: 'numeric', second: 'numeric' },
|
|
34
|
-
long: { hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' },
|
|
35
|
-
full: { hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'long' },
|
|
36
|
-
};
|
|
37
|
-
export const interpret: Engine = (message, locale, formats, values) => {
|
|
38
|
-
const number = (value: number, options?: Intl.NumberFormatOptions) =>
|
|
39
|
-
cached(numberCache, JSON.stringify([locale, options]), () => new Intl.NumberFormat(locale, options)).format(value);
|
|
40
|
-
|
|
41
|
-
const render = (message: CompactMessage, pound?: number): unknown[] => {
|
|
42
|
-
if (typeof message === 'string') return [message];
|
|
43
|
-
|
|
44
|
-
const output: unknown[] = [];
|
|
45
|
-
|
|
46
|
-
const append = (value: unknown) => {
|
|
47
|
-
if (Array.isArray(value)) {
|
|
48
|
-
for (const part of value) append(part);
|
|
49
|
-
} else if (typeof value === 'string' && typeof output[output.length - 1] === 'string') {
|
|
50
|
-
output[output.length - 1] += value;
|
|
51
|
-
} else output.push(value);
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
for (const part of message) {
|
|
55
|
-
if (typeof part === 'string') {
|
|
56
|
-
append(part);
|
|
57
|
-
continue;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const op = part[0];
|
|
61
|
-
|
|
62
|
-
if (op === 6) {
|
|
63
|
-
if (pound !== undefined) append(number(pound));
|
|
64
|
-
continue;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
const name = part[1];
|
|
68
|
-
|
|
69
|
-
if (!(name in values)) throw new Error('[i18n] Missing required message parameter: ' + name);
|
|
70
|
-
|
|
71
|
-
const value = values[name];
|
|
72
|
-
|
|
73
|
-
if (op === 0) {
|
|
74
|
-
append(typeof value === 'string' || typeof value === 'number' ? String(value) : value || '');
|
|
75
|
-
continue;
|
|
76
|
-
}
|
|
77
|
-
if (op >= 1 && op <= 3) {
|
|
78
|
-
const style = part[2] as string | Record<string, unknown> | null;
|
|
79
|
-
const kind = op === 1 ? 'number' : op === 2 ? 'date' : 'time';
|
|
80
|
-
const defaults = op === 1 ? numberDefaults : op === 2 ? dateDefaults : timeDefaults;
|
|
81
|
-
|
|
82
|
-
const options = (typeof style === 'string'
|
|
83
|
-
? formats[kind]?.[style] ?? (defaults as Record<string, object>)[style]
|
|
84
|
-
: style ?? (op === 3 ? timeDefaults.medium : undefined)) as Record<string, unknown> | undefined;
|
|
85
|
-
|
|
86
|
-
if (op === 1) {
|
|
87
|
-
append(number(Number(value) * (Number(options?.scale ?? 1)), options));
|
|
88
|
-
} else {
|
|
89
|
-
append(
|
|
90
|
-
cached(
|
|
91
|
-
dateCache,
|
|
92
|
-
JSON.stringify([locale, options]),
|
|
93
|
-
() => new Intl.DateTimeFormat(locale, options as Intl.DateTimeFormatOptions),
|
|
94
|
-
).format(value as Date),
|
|
95
|
-
);
|
|
96
|
-
}
|
|
97
|
-
} else if (op === 4) {
|
|
98
|
-
const branches = part[2];
|
|
99
|
-
append(
|
|
100
|
-
render(
|
|
101
|
-
Object.prototype.hasOwnProperty.call(branches, String(value)) ? branches[String(value)] : branches.other,
|
|
102
|
-
),
|
|
103
|
-
);
|
|
104
|
-
} else if (op === 5) {
|
|
105
|
-
const count = Number(value);
|
|
106
|
-
const adjusted = count - part[2];
|
|
107
|
-
const branches = part[4];
|
|
108
|
-
const exact = '=' + count;
|
|
109
|
-
|
|
110
|
-
const key = Object.prototype.hasOwnProperty.call(branches, exact)
|
|
111
|
-
? exact
|
|
112
|
-
: cached(
|
|
113
|
-
pluralCache,
|
|
114
|
-
locale + ':' + part[3],
|
|
115
|
-
() => new Intl.PluralRules(locale, { type: part[3] ? 'ordinal' : 'cardinal' }),
|
|
116
|
-
).select(adjusted);
|
|
117
|
-
append(render(branches[key] ?? branches.other, adjusted));
|
|
118
|
-
} else if (op === 7) {
|
|
119
|
-
if (typeof value !== 'function') throw new TypeError('[i18n] rich tag ' + name + ' requires a handler');
|
|
120
|
-
append(value(render(part[2], pound)));
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
return output;
|
|
125
|
-
};
|
|
126
|
-
|
|
127
|
-
return render(message);
|
|
128
|
-
};
|
package/src/shared/runtime.ts
DELETED
|
@@ -1,131 +0,0 @@
|
|
|
1
|
-
import type { MessageFormatOptions, MessageTagHandler, TranslationGetter } from '../core/types';
|
|
2
|
-
|
|
3
|
-
export type Formats = {
|
|
4
|
-
number: Record<string, Intl.NumberFormatOptions>;
|
|
5
|
-
date: Record<string, Intl.DateTimeFormatOptions>;
|
|
6
|
-
time: Record<string, Intl.DateTimeFormatOptions>;
|
|
7
|
-
};
|
|
8
|
-
|
|
9
|
-
export type FormatContext = { languageId: string; };
|
|
10
|
-
export type FormatFactory<T> = T | ((context: FormatContext) => T);
|
|
11
|
-
export type RegistryConfig = { [K in keyof Formats]: Record<string, FormatFactory<Formats[K][string]>>; };
|
|
12
|
-
export type PartsRenderer = (runtime?: Runtime) => unknown[];
|
|
13
|
-
|
|
14
|
-
export type Runtime = {
|
|
15
|
-
languageId: string;
|
|
16
|
-
ready: boolean;
|
|
17
|
-
translationsEnabled: boolean;
|
|
18
|
-
translationGetter: TranslationGetter | null;
|
|
19
|
-
formats: Partial<Formats>;
|
|
20
|
-
registry: RegistryConfig;
|
|
21
|
-
jsxLineBreak: unknown;
|
|
22
|
-
jsxHandler: ((options: MessageFormatOptions, render: PartsRenderer) => unknown) | null;
|
|
23
|
-
tagElement: ((element: unknown) => (chunks: unknown[]) => unknown) | null;
|
|
24
|
-
subscribe: (listener: () => void) => () => void;
|
|
25
|
-
getSnapshot: () => unknown;
|
|
26
|
-
};
|
|
27
|
-
|
|
28
|
-
export function createRuntime(): Runtime {
|
|
29
|
-
return {
|
|
30
|
-
languageId: 'en',
|
|
31
|
-
ready: false,
|
|
32
|
-
translationsEnabled: true,
|
|
33
|
-
translationGetter: null,
|
|
34
|
-
formats: {},
|
|
35
|
-
registry: { number: {}, date: {}, time: {} },
|
|
36
|
-
jsxLineBreak: '\n',
|
|
37
|
-
jsxHandler: null,
|
|
38
|
-
tagElement: null,
|
|
39
|
-
subscribe: () => () => {},
|
|
40
|
-
getSnapshot: () => null,
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export const defaultRuntime = createRuntime();
|
|
45
|
-
let resolver = () => defaultRuntime;
|
|
46
|
-
|
|
47
|
-
export function setRuntimeResolver(next: () => Runtime): void {
|
|
48
|
-
resolver = next;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export function getRuntime(): Runtime {
|
|
52
|
-
return resolver();
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
export function setTranslationGetter(getter: TranslationGetter | null): void {
|
|
56
|
-
getRuntime().translationGetter = getter;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
export function setLanguageId(languageId: string): void {
|
|
60
|
-
getRuntime().languageId = languageId;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export function setFormats(formats: Partial<Formats>): void {
|
|
64
|
-
getRuntime().formats = formats;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export function setGetJsxHandler(handler: Runtime['jsxHandler']): void {
|
|
68
|
-
getRuntime().jsxHandler = handler;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export const I18nRegistry = {
|
|
72
|
-
addNumberFormat(name: string, format: FormatFactory<Intl.NumberFormatOptions>) {
|
|
73
|
-
getRuntime().registry.number[name] = format;
|
|
74
|
-
},
|
|
75
|
-
addDateFormat(name: string, format: FormatFactory<Intl.DateTimeFormatOptions>) {
|
|
76
|
-
getRuntime().registry.date[name] = format;
|
|
77
|
-
},
|
|
78
|
-
addTimeFormat(name: string, format: FormatFactory<Intl.DateTimeFormatOptions>) {
|
|
79
|
-
getRuntime().registry.time[name] = format;
|
|
80
|
-
},
|
|
81
|
-
setLanguageId,
|
|
82
|
-
getConfig(): RegistryConfig {
|
|
83
|
-
const r = getRuntime().registry;
|
|
84
|
-
|
|
85
|
-
return { number: { ...r.number }, date: { ...r.date }, time: { ...r.time } };
|
|
86
|
-
},
|
|
87
|
-
};
|
|
88
|
-
|
|
89
|
-
export function getFormats(runtime: Runtime, languageId: string): Partial<Formats> {
|
|
90
|
-
const resolve = <T>(entries: Record<string, FormatFactory<T>>) =>
|
|
91
|
-
Object.fromEntries(
|
|
92
|
-
Object.entries(entries).map((
|
|
93
|
-
[key, value],
|
|
94
|
-
) => [key, typeof value === 'function' ? (value as (context: FormatContext) => T)({ languageId }) : value]),
|
|
95
|
-
);
|
|
96
|
-
|
|
97
|
-
return {
|
|
98
|
-
number: { ...runtime.formats.number, ...resolve(runtime.registry.number) },
|
|
99
|
-
date: { ...runtime.formats.date, ...resolve(runtime.registry.date) },
|
|
100
|
-
time: { ...runtime.formats.time, ...resolve(runtime.registry.time) },
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
export function noTranslate<T>(fn: () => T): T {
|
|
105
|
-
const runtime = getRuntime();
|
|
106
|
-
const previous = runtime.translationsEnabled;
|
|
107
|
-
runtime.translationsEnabled = false;
|
|
108
|
-
|
|
109
|
-
try {
|
|
110
|
-
return fn();
|
|
111
|
-
} finally {
|
|
112
|
-
runtime.translationsEnabled = previous;
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
export function createTagHandler<T, R>(handler: (chunks: Array<string | T>) => R): MessageTagHandler<T, R> {
|
|
117
|
-
Object.defineProperty(handler, '__fluenticTagHandler', { value: true });
|
|
118
|
-
|
|
119
|
-
return handler as MessageTagHandler<T, R>;
|
|
120
|
-
}
|
|
121
|
-
/** Synchronous binding only: async callers must keep and use their own instance. */
|
|
122
|
-
export function withRuntime<T>(runtime: Runtime, fn: () => T): T {
|
|
123
|
-
const previous = resolver;
|
|
124
|
-
resolver = () => runtime;
|
|
125
|
-
|
|
126
|
-
try {
|
|
127
|
-
return fn();
|
|
128
|
-
} finally {
|
|
129
|
-
resolver = previous;
|
|
130
|
-
}
|
|
131
|
-
}
|
package/src/state-manager.ts
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
export type StateManager<StateData> = {
|
|
2
|
-
get(): StateData;
|
|
3
|
-
subscribe(listener: () => void): () => void;
|
|
4
|
-
set(partial: Partial<StateData>): void;
|
|
5
|
-
};
|
|
6
|
-
|
|
7
|
-
export function createStateManager<StateData extends object>(initial: StateData): StateManager<StateData> {
|
|
8
|
-
let current = initial;
|
|
9
|
-
|
|
10
|
-
const listeners = new Set<() => void>();
|
|
11
|
-
|
|
12
|
-
return {
|
|
13
|
-
get: () => current,
|
|
14
|
-
subscribe: (listener) => {
|
|
15
|
-
listeners.add(listener);
|
|
16
|
-
|
|
17
|
-
return () => listeners.delete(listener);
|
|
18
|
-
},
|
|
19
|
-
set(partial) {
|
|
20
|
-
const next = { ...current, ...partial };
|
|
21
|
-
const changed = Object.keys(next).some((key) => current[key as keyof StateData] !== next[key as keyof StateData]);
|
|
22
|
-
|
|
23
|
-
if (!changed) return;
|
|
24
|
-
current = next;
|
|
25
|
-
|
|
26
|
-
for (const listener of listeners) listener();
|
|
27
|
-
},
|
|
28
|
-
};
|
|
29
|
-
}
|
package/src/state.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import { useSyncExternalStore } from 'react';
|
|
2
|
-
import { defaultI18nState, type StateData } from './manager';
|
|
3
|
-
|
|
4
|
-
export type { StateData } from './manager';
|
|
5
|
-
|
|
6
|
-
export const I18nState = {
|
|
7
|
-
get(): StateData {
|
|
8
|
-
return defaultI18nState.get();
|
|
9
|
-
},
|
|
10
|
-
subscribe(listener: () => void): () => void {
|
|
11
|
-
return defaultI18nState.subscribe(listener);
|
|
12
|
-
},
|
|
13
|
-
use(): StateData {
|
|
14
|
-
return useSyncExternalStore(I18nState.subscribe, I18nState.get, I18nState.get);
|
|
15
|
-
},
|
|
16
|
-
};
|
|
17
|
-
|
|
18
|
-
export function updateState(next: Partial<StateData>): void {
|
|
19
|
-
defaultI18nState.set(next);
|
|
20
|
-
}
|
package/src/storage-manager.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import type { LanguageId } from './core/types';
|
|
2
|
-
|
|
3
|
-
export type StoredState = { languageId: LanguageId; };
|
|
4
|
-
|
|
5
|
-
export type I18nStorage = {
|
|
6
|
-
read(): StoredState | null | Promise<StoredState | null>;
|
|
7
|
-
write(state: StoredState): void | Promise<void>;
|
|
8
|
-
};
|
|
9
|
-
|
|
10
|
-
export function createStorageManager(initial: I18nStorage | null = null) {
|
|
11
|
-
let storage = initial;
|
|
12
|
-
|
|
13
|
-
return {
|
|
14
|
-
setStorage(next: I18nStorage | null): void {
|
|
15
|
-
storage = next;
|
|
16
|
-
},
|
|
17
|
-
getStorage(): I18nStorage {
|
|
18
|
-
if (!storage) throw new Error('[i18n] storage is not configured');
|
|
19
|
-
|
|
20
|
-
return storage;
|
|
21
|
-
},
|
|
22
|
-
hasStorage(): boolean {
|
|
23
|
-
return storage !== null;
|
|
24
|
-
},
|
|
25
|
-
};
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export function createLocalStorage(): I18nStorage | null {
|
|
29
|
-
if (typeof globalThis.localStorage === 'undefined') return null;
|
|
30
|
-
|
|
31
|
-
return {
|
|
32
|
-
read() {
|
|
33
|
-
const value = globalThis.localStorage.getItem('fluentic:i18n:state');
|
|
34
|
-
|
|
35
|
-
if (!value) return null;
|
|
36
|
-
|
|
37
|
-
try {
|
|
38
|
-
return JSON.parse(value) as StoredState;
|
|
39
|
-
} catch {
|
|
40
|
-
return null;
|
|
41
|
-
}
|
|
42
|
-
},
|
|
43
|
-
write(state) {
|
|
44
|
-
globalThis.localStorage.setItem('fluentic:i18n:state', JSON.stringify(state));
|
|
45
|
-
},
|
|
46
|
-
};
|
|
47
|
-
}
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import type { LanguageId, MessageContext } from './core/types';
|
|
2
|
-
import { type Catalog, parseCatalog, type TranslationData } from './translation';
|
|
3
|
-
|
|
4
|
-
export type * from './translation';
|
|
5
|
-
export { normalizeCatalog } from './translation';
|
|
6
|
-
|
|
7
|
-
export type TranslationLoaderArgs = { languageId: LanguageId; };
|
|
8
|
-
export type TranslationLookupArgs = { languageId: LanguageId; context: MessageContext | null; message: string; };
|
|
9
|
-
export type TranslationLoader = (args: TranslationLoaderArgs) => TranslationData | Promise<TranslationData>;
|
|
10
|
-
export type TranslationModule = { default: TranslationData; };
|
|
11
|
-
export type TranslationSource = TranslationData | TranslationModule;
|
|
12
|
-
|
|
13
|
-
export type TranslationLoaderEntry =
|
|
14
|
-
| TranslationSource
|
|
15
|
-
| Promise<TranslationSource>
|
|
16
|
-
| (() => TranslationSource | Promise<TranslationSource>);
|
|
17
|
-
|
|
18
|
-
export type TranslationLoaderMap = Record<string, TranslationLoaderEntry>;
|
|
19
|
-
|
|
20
|
-
export function defineTranslationLoader(loader: TranslationLoader | TranslationLoaderMap): TranslationLoader {
|
|
21
|
-
if (typeof loader === 'function') return loader;
|
|
22
|
-
|
|
23
|
-
return async ({ languageId }) => {
|
|
24
|
-
if (!Object.prototype.hasOwnProperty.call(loader, languageId)) return [];
|
|
25
|
-
|
|
26
|
-
const entry = loader[languageId];
|
|
27
|
-
const source = await (typeof entry === 'function' ? entry() : entry);
|
|
28
|
-
|
|
29
|
-
return typeof source === 'object' && source !== null && 'default' in source
|
|
30
|
-
? source.default
|
|
31
|
-
: source as TranslationData;
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function createTranslationManager() {
|
|
36
|
-
const catalogs: Record<string, Catalog> = Object.create(null);
|
|
37
|
-
const pending = new Map<string, Promise<void>>();
|
|
38
|
-
const compiledCatalogs: Record<string, boolean> = Object.create(null);
|
|
39
|
-
|
|
40
|
-
let loader: TranslationLoader | null = null;
|
|
41
|
-
let generation = 0;
|
|
42
|
-
|
|
43
|
-
const setTranslationLoader = (next: TranslationLoader | null) => {
|
|
44
|
-
loader = next;
|
|
45
|
-
generation++;
|
|
46
|
-
pending.clear();
|
|
47
|
-
|
|
48
|
-
for (const key of Object.keys(catalogs)) delete catalogs[key];
|
|
49
|
-
for (const key of Object.keys(compiledCatalogs)) delete compiledCatalogs[key];
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
const loadTranslations = async (languageId: string) => {
|
|
53
|
-
if (!loader || Object.prototype.hasOwnProperty.call(catalogs, languageId)) return;
|
|
54
|
-
if (pending.has(languageId)) return pending.get(languageId);
|
|
55
|
-
|
|
56
|
-
const version = generation;
|
|
57
|
-
const currentLoader = loader;
|
|
58
|
-
|
|
59
|
-
const task = Promise.resolve().then(() => currentLoader({ languageId })).then((data) => {
|
|
60
|
-
if (version === generation) {
|
|
61
|
-
const result = parseCatalog(data);
|
|
62
|
-
catalogs[languageId] = result.catalog;
|
|
63
|
-
compiledCatalogs[languageId] = result.compiled;
|
|
64
|
-
}
|
|
65
|
-
}).finally(() => {
|
|
66
|
-
if (version === generation) pending.delete(languageId);
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
pending.set(languageId, task);
|
|
70
|
-
|
|
71
|
-
return task;
|
|
72
|
-
};
|
|
73
|
-
|
|
74
|
-
const getTranslation = (args: TranslationLookupArgs) => {
|
|
75
|
-
const catalog = catalogs[args.languageId];
|
|
76
|
-
const id = args.context ? `${args.context}\0${args.message}` : args.message;
|
|
77
|
-
|
|
78
|
-
return catalog?.[id] ?? catalog?.[args.message] ?? null;
|
|
79
|
-
};
|
|
80
|
-
|
|
81
|
-
return { catalogs, compiledCatalogs, setTranslationLoader, loadTranslations, getTranslation };
|
|
82
|
-
}
|
package/src/translation.ts
DELETED
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
import { type CompactMessage, validateCompact } from './shared/compact';
|
|
2
|
-
|
|
3
|
-
export type TranslationItem = { id: string; translation: string; };
|
|
4
|
-
export type TranslationRow = [id: string, translation: string] | [context: string, id: string, translation: string];
|
|
5
|
-
export type CompiledTranslationItem = [id: string, message: CompactMessage];
|
|
6
|
-
export type CompiledCatalogHeader = { compiled: true; };
|
|
7
|
-
export type TranslationJsonl = string;
|
|
8
|
-
|
|
9
|
-
export type TranslationData =
|
|
10
|
-
| unknown[]
|
|
11
|
-
| TranslationJsonl
|
|
12
|
-
| { jsonl: TranslationJsonl; };
|
|
13
|
-
|
|
14
|
-
export type Catalog = Record<string, CompactMessage>;
|
|
15
|
-
|
|
16
|
-
type TranslationItemRaw = {
|
|
17
|
-
id?: string;
|
|
18
|
-
source?: string;
|
|
19
|
-
context?: string;
|
|
20
|
-
message?: string | [string, string];
|
|
21
|
-
translation?: string;
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
export function normalizeCatalog(data: TranslationData): Catalog {
|
|
25
|
-
return parseCatalog(data).catalog;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export function parseCatalog(data: TranslationData): { catalog: Catalog; compiled: boolean; } {
|
|
29
|
-
const catalog: Catalog = Object.create(null);
|
|
30
|
-
const rows = parseRows(data);
|
|
31
|
-
const header = rows[0];
|
|
32
|
-
const hasHeader = isCompiledHeader(header);
|
|
33
|
-
const compiled = hasHeader ||
|
|
34
|
-
(Array.isArray(data) && rows.some((row) => Array.isArray(row) && row.length === 2 && Array.isArray(row[1])));
|
|
35
|
-
|
|
36
|
-
if (hasHeader) rows.shift();
|
|
37
|
-
if (Array.isArray(data) && rows.at(-1) === null) rows.pop();
|
|
38
|
-
|
|
39
|
-
for (const row of rows) {
|
|
40
|
-
if (Array.isArray(row)) {
|
|
41
|
-
const [id, message] = compiled ? parseCompiledRow(row) : parseTranslationRow(row, Array.isArray(data));
|
|
42
|
-
|
|
43
|
-
if (compiled || message !== '') catalog[id] = message;
|
|
44
|
-
} else {
|
|
45
|
-
if (compiled) throw new TypeError('[i18n] invalid compiled catalog row');
|
|
46
|
-
|
|
47
|
-
const item = parseTranslationItem(row);
|
|
48
|
-
|
|
49
|
-
if (item.translation !== '') catalog[item.id] = item.translation;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
return { catalog, compiled };
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function parseRows(data: TranslationData): unknown[] {
|
|
57
|
-
if (Array.isArray(data)) return [...data];
|
|
58
|
-
|
|
59
|
-
const jsonl = typeof data === 'string' ? data : data.jsonl;
|
|
60
|
-
|
|
61
|
-
return jsonl.split(/\r?\n/).filter((line) => line.trim()).map((line) => JSON.parse(line));
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
function isCompiledHeader(row: unknown): row is CompiledCatalogHeader {
|
|
65
|
-
return typeof row === 'object' && row !== null && !Array.isArray(row) &&
|
|
66
|
-
'compiled' in row && row.compiled === true;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function parseCompiledRow(row: unknown[]): CompiledTranslationItem {
|
|
70
|
-
if (row.length !== 2 || typeof row[0] !== 'string') {
|
|
71
|
-
throw new TypeError('[i18n] invalid compiled catalog row');
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
validateCompact(row[1]);
|
|
75
|
-
|
|
76
|
-
return [row[0], row[1]];
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
function parseTranslationRow(row: unknown[], allowCompact: boolean): [string, CompactMessage] {
|
|
80
|
-
if (row.length === 2 && typeof row[0] === 'string') {
|
|
81
|
-
// Programmatic compileCatalog() results can be passed directly as arrays.
|
|
82
|
-
if (allowCompact) validateCompact(row[1]);
|
|
83
|
-
else if (typeof row[1] !== 'string') throw new TypeError('[i18n] invalid translation row');
|
|
84
|
-
|
|
85
|
-
return [row[0], row[1]];
|
|
86
|
-
}
|
|
87
|
-
if (row.length === 3 && row.every((value) => typeof value === 'string')) {
|
|
88
|
-
return [`${row[0]}\0${row[1]}`, row[2] as string];
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
throw new TypeError('[i18n] invalid translation row');
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function parseTranslationItem(row: unknown): TranslationItem {
|
|
95
|
-
const item = row as TranslationItemRaw;
|
|
96
|
-
|
|
97
|
-
if (!item || typeof item.translation !== 'string') throw new TypeError('[i18n] invalid translation item');
|
|
98
|
-
|
|
99
|
-
const source = item.source ?? (Array.isArray(item.message) ? item.message[1] : item.message);
|
|
100
|
-
const context = Array.isArray(item.message) ? item.message[0] : item.context;
|
|
101
|
-
const id = item.id ?? (source === undefined ? undefined : context ? `${context}\0${source}` : source);
|
|
102
|
-
|
|
103
|
-
if (typeof id !== 'string') throw new TypeError('[i18n] translation id is missing');
|
|
104
|
-
|
|
105
|
-
return { id, translation: item.translation };
|
|
106
|
-
}
|
package/src/types.ts
DELETED