@fluentic/i18n 0.0.0-stage → 0.1.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/LICENSE +21 -0
- package/README.md +21 -2
- package/dist/adapter-CWC8rng-.d.ts +178 -0
- package/dist/adapter.d.ts +4 -0
- package/dist/adapter.js +4 -0
- package/dist/analyze-CdXCxQDg.d.ts +14 -0
- package/dist/compact-CJ0OWoIv.d.ts +7 -0
- package/dist/compact-E3zj3Z8d.js +34 -0
- package/dist/compact-E3zj3Z8d.js.map +1 -0
- package/dist/compiled.d.ts +27 -0
- package/dist/compiled.js +51 -0
- package/dist/compiled.js.map +1 -0
- package/dist/compiler-BZtB9WLi.js +365 -0
- package/dist/compiler-BZtB9WLi.js.map +1 -0
- package/dist/compiler.d.ts +35 -0
- package/dist/compiler.js +3 -0
- package/dist/core/index.d.ts +5 -0
- package/dist/core/index.js +4 -0
- package/dist/i18n-CfYNwubL.d.ts +25 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/interpreter-Dld8QyOI.js +186 -0
- package/dist/interpreter-Dld8QyOI.js.map +1 -0
- package/dist/manager-BW778X1Y.js +193 -0
- package/dist/manager-BW778X1Y.js.map +1 -0
- package/dist/options-DE7vYj0e.d.ts +7 -0
- package/dist/options-Dxxx0aOz.js +23 -0
- package/dist/options-Dxxx0aOz.js.map +1 -0
- package/dist/plugin/babel.d.ts +11 -0
- package/dist/plugin/babel.js +31 -0
- package/dist/plugin/babel.js.map +1 -0
- package/dist/plugin/esbuild.d.ts +7 -0
- package/dist/plugin/esbuild.js +37 -0
- package/dist/plugin/esbuild.js.map +1 -0
- package/dist/plugin/rollup.d.ts +30 -0
- package/dist/plugin/rollup.js +34 -0
- package/dist/plugin/rollup.js.map +1 -0
- package/dist/plugin/vite.d.ts +31 -0
- package/dist/plugin/vite.js +11 -0
- package/dist/plugin/vite.js.map +1 -0
- package/dist/plugin/webpack-loader.d.ts +3 -0
- package/dist/plugin/webpack-loader.js +21 -0
- package/dist/plugin/webpack-loader.js.map +1 -0
- package/dist/plugin/webpack.d.ts +8 -0
- package/dist/plugin/webpack.js +22 -0
- package/dist/plugin/webpack.js.map +1 -0
- package/dist/react.d.ts +53 -0
- package/dist/react.js +60 -0
- package/dist/react.js.map +1 -0
- package/dist/src-BovRx-mX.js +142 -0
- package/dist/src-BovRx-mX.js.map +1 -0
- package/dist/translation-manager-C79eKu2K.js +213 -0
- package/dist/translation-manager-C79eKu2K.js.map +1 -0
- package/dist/types-BkDsJfVD.js +13 -0
- package/dist/types-BkDsJfVD.js.map +1 -0
- package/dist/types-BuGoCU3P.d.ts +75 -0
- package/dist/types.d.ts +2 -0
- package/dist/types.js +1 -0
- package/dist-cjs/babel.cjs +379 -0
- package/dist-cjs/babel.cjs.map +1 -0
- package/package.json +130 -3
- package/src/adapter.ts +6 -0
- package/src/compiled.ts +116 -0
- package/src/compiler/analyze.ts +182 -0
- package/src/compiler/index.ts +208 -0
- package/src/compiler/message.ts +74 -0
- package/src/core/format.ts +40 -0
- package/src/core/i18n.ts +124 -0
- package/src/core/index.ts +1 -0
- package/src/core/types.ts +121 -0
- package/src/index.ts +9 -0
- package/src/manager.ts +175 -0
- package/src/plugin/babel.ts +34 -0
- package/src/plugin/esbuild.ts +45 -0
- package/src/plugin/options.ts +24 -0
- package/src/plugin/rollup.ts +29 -0
- package/src/plugin/vite.ts +6 -0
- package/src/plugin/webpack-loader.ts +22 -0
- package/src/plugin/webpack.ts +15 -0
- package/src/react.ts +97 -0
- package/src/registry-manager.ts +3 -0
- package/src/shared/compact.ts +51 -0
- package/src/shared/formatting.ts +121 -0
- package/src/shared/interpreter.ts +128 -0
- package/src/shared/runtime.ts +131 -0
- package/src/state-manager.ts +29 -0
- package/src/state.ts +20 -0
- package/src/storage-manager.ts +47 -0
- package/src/translation-manager.ts +82 -0
- package/src/translation.ts +106 -0
- package/src/types.ts +2 -0
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { type MessageFormatElement, parse, TYPE } from '@formatjs/icu-messageformat-parser';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import type { CompactMessage, CompactPart } from '../shared/compact';
|
|
4
|
+
|
|
5
|
+
export { COMPACT_VERSION } from '../shared/compact';
|
|
6
|
+
|
|
7
|
+
export function messageIdentity(context: string | null, source: string): string {
|
|
8
|
+
return context ? `${context}\0${source}` : source;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function messageId(context: string | null, source: string): string {
|
|
12
|
+
return createHash('sha256').update(messageIdentity(context, source)).digest('hex').slice(0, 24);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function compileMessage(source: string): CompactMessage {
|
|
16
|
+
const compact = (elements: MessageFormatElement[]): CompactMessage => {
|
|
17
|
+
const result: CompactPart[] = elements.map((element): CompactPart => {
|
|
18
|
+
switch (element.type) {
|
|
19
|
+
case TYPE.literal:
|
|
20
|
+
return element.value;
|
|
21
|
+
case TYPE.argument:
|
|
22
|
+
return [0, element.value];
|
|
23
|
+
case TYPE.number:
|
|
24
|
+
case TYPE.date:
|
|
25
|
+
case TYPE.time:
|
|
26
|
+
return [
|
|
27
|
+
element.type === TYPE.number ? 1 : element.type === TYPE.date ? 2 : 3,
|
|
28
|
+
element.value,
|
|
29
|
+
typeof element.style === 'object' && element.style
|
|
30
|
+
? element.style.parsedOptions as Record<string, unknown>
|
|
31
|
+
: element.style ?? null,
|
|
32
|
+
];
|
|
33
|
+
case TYPE.select:
|
|
34
|
+
return [
|
|
35
|
+
4,
|
|
36
|
+
element.value,
|
|
37
|
+
Object.fromEntries(Object.entries(element.options).map(([key, option]) => [key, compact(option.value)])),
|
|
38
|
+
];
|
|
39
|
+
case TYPE.plural:
|
|
40
|
+
return [
|
|
41
|
+
5,
|
|
42
|
+
element.value,
|
|
43
|
+
element.offset,
|
|
44
|
+
element.pluralType === 'ordinal' ? 1 : 0,
|
|
45
|
+
Object.fromEntries(Object.entries(element.options).map(([key, option]) => [key, compact(option.value)])),
|
|
46
|
+
];
|
|
47
|
+
case TYPE.pound:
|
|
48
|
+
return [6];
|
|
49
|
+
case TYPE.tag:
|
|
50
|
+
return [7, element.value, compact(element.children)];
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
return result.every((part) => typeof part === 'string') ? result.join('') : result;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
return compact(parse(source, { captureLocation: false }));
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function compileCatalog(
|
|
61
|
+
records: Array<{ source: string; context: string | null; translation: string; }>,
|
|
62
|
+
): Array<[string, CompactMessage]> {
|
|
63
|
+
const seen = new Map<string, string>();
|
|
64
|
+
|
|
65
|
+
return records.flatMap((record) => {
|
|
66
|
+
const id = messageId(record.context, record.source);
|
|
67
|
+
const identity = messageIdentity(record.context, record.source);
|
|
68
|
+
|
|
69
|
+
if (seen.has(id) && seen.get(id) !== identity) throw new Error('[i18n] message hash collision: ' + id);
|
|
70
|
+
seen.set(id, identity);
|
|
71
|
+
|
|
72
|
+
return record.translation === '' ? [] : [[id, compileMessage(record.translation)] as [string, CompactMessage]];
|
|
73
|
+
});
|
|
74
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { sha256 } from '@noble/hashes/sha256';
|
|
2
|
+
import { bytesToHex } from '@noble/hashes/utils';
|
|
3
|
+
import { IntlMessageFormat } from 'intl-messageformat';
|
|
4
|
+
import { createFormatting } from '../shared/formatting';
|
|
5
|
+
import { interpret } from '../shared/interpreter';
|
|
6
|
+
|
|
7
|
+
const cache = new Map<string, IntlMessageFormat>();
|
|
8
|
+
const formatting = /* @__PURE__ */ createFormatting(
|
|
9
|
+
(message, languageId, formats, values, compiled) => {
|
|
10
|
+
if (compiled) return interpret(message, languageId, formats, values, true);
|
|
11
|
+
if (typeof message !== 'string') throw new TypeError('[i18n] invalid translation');
|
|
12
|
+
|
|
13
|
+
const key = JSON.stringify([message, languageId, formats]);
|
|
14
|
+
|
|
15
|
+
let formatter = cache.get(key);
|
|
16
|
+
|
|
17
|
+
if (!formatter) {
|
|
18
|
+
formatter = new IntlMessageFormat(
|
|
19
|
+
message,
|
|
20
|
+
languageId,
|
|
21
|
+
formats as ConstructorParameters<typeof IntlMessageFormat>[2],
|
|
22
|
+
);
|
|
23
|
+
if (cache.size >= 500) cache.delete(cache.keys().next().value!);
|
|
24
|
+
cache.set(key, formatter);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return formatter.formatToParts(values as Parameters<IntlMessageFormat['formatToParts']>[0]).map((part) =>
|
|
28
|
+
part.value
|
|
29
|
+
);
|
|
30
|
+
},
|
|
31
|
+
false,
|
|
32
|
+
(context, message) => bytesToHex(sha256(context ? `${context}\0${message}` : message)).slice(0, 24),
|
|
33
|
+
);
|
|
34
|
+
export * from '../shared/runtime';
|
|
35
|
+
|
|
36
|
+
export const getText = (...args: Parameters<typeof formatting.getText>) => formatting.getText(...args);
|
|
37
|
+
export const getJsx = (...args: Parameters<typeof formatting.getJsx>) => formatting.getJsx(...args);
|
|
38
|
+
export const getMessageParts = (...args: Parameters<typeof formatting.getMessageParts>) =>
|
|
39
|
+
formatting.getMessageParts(...args);
|
|
40
|
+
export const formatMessage = getText;
|
package/src/core/i18n.ts
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { Formatting } from '../shared/formatting';
|
|
2
|
+
import { createTagHandler, getRuntime, noTranslate } from '../shared/runtime';
|
|
3
|
+
import type { I18nJsxOutput, I18nTagElement, I18nTagValue } from './types';
|
|
4
|
+
import { isMessageDescriptor } from './types';
|
|
5
|
+
import type {
|
|
6
|
+
JsxRenderer,
|
|
7
|
+
MessageDescriptor,
|
|
8
|
+
MessageInput,
|
|
9
|
+
MessageMeta,
|
|
10
|
+
MessageParams,
|
|
11
|
+
MessageSchema,
|
|
12
|
+
MessageTagHandler,
|
|
13
|
+
TextRenderer,
|
|
14
|
+
TryRenderArgs,
|
|
15
|
+
} from './types';
|
|
16
|
+
|
|
17
|
+
type MessageScope = { context: string | null; notes: string[]; meta?: MessageMeta; };
|
|
18
|
+
|
|
19
|
+
export type MessageApi<JsxOutput = unknown> = {
|
|
20
|
+
context(name: string): MessageApi<JsxOutput>;
|
|
21
|
+
note(note: string): MessageApi<JsxOutput>;
|
|
22
|
+
meta(meta: MessageMeta): MessageApi<JsxOutput>;
|
|
23
|
+
msg<const Text extends string, const Schema extends MessageSchema | undefined = undefined>(
|
|
24
|
+
message: Text,
|
|
25
|
+
schema?: Schema,
|
|
26
|
+
): MessageDescriptor<Text, Schema>;
|
|
27
|
+
text: TextRenderer;
|
|
28
|
+
jsx: JsxRenderer<JsxOutput>;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type TApi<JsxOutput = unknown, TagValue = unknown> = MessageApi<JsxOutput> & {
|
|
32
|
+
clone<const Text extends string, const Schema extends MessageSchema | undefined>(
|
|
33
|
+
message: MessageDescriptor<Text, Schema>,
|
|
34
|
+
): MessageDescriptor<Text, Schema>;
|
|
35
|
+
params<Params extends MessageParams>(params?: Params | null): Params;
|
|
36
|
+
tag(element: I18nTagElement): MessageTagHandler<I18nTagValue, I18nTagElement>;
|
|
37
|
+
tag<T = TagValue, R = TagValue>(handler: (chunks: Array<string | T>) => R): MessageTagHandler<T, R>;
|
|
38
|
+
try<T>(
|
|
39
|
+
renderer: TextRenderer,
|
|
40
|
+
value: T,
|
|
41
|
+
...args: TryRenderArgs<T>
|
|
42
|
+
): T extends { readonly __fluenticMessage: true; } ? string : T;
|
|
43
|
+
try<T>(
|
|
44
|
+
renderer: JsxRenderer<JsxOutput>,
|
|
45
|
+
value: T,
|
|
46
|
+
...args: TryRenderArgs<T>
|
|
47
|
+
): T extends { readonly __fluenticMessage: true; } ? JsxOutput : T;
|
|
48
|
+
notranslate: typeof noTranslate;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export function createT({ getText, getJsx }: Formatting): TApi<I18nJsxOutput, I18nTagValue> {
|
|
52
|
+
const createScope = (scope: MessageScope): MessageApi => {
|
|
53
|
+
return {
|
|
54
|
+
context(name) {
|
|
55
|
+
return createScope({ ...scope, context: scope.context ? `${scope.context}.${name}` : name });
|
|
56
|
+
},
|
|
57
|
+
note(note) {
|
|
58
|
+
return createScope({ ...scope, notes: [...scope.notes, note] });
|
|
59
|
+
},
|
|
60
|
+
meta(meta) {
|
|
61
|
+
return createScope({ ...scope, meta });
|
|
62
|
+
},
|
|
63
|
+
msg(message, schema) {
|
|
64
|
+
return createDescriptor(message, schema, scope);
|
|
65
|
+
},
|
|
66
|
+
text(message: MessageInput, params?: MessageParams) {
|
|
67
|
+
return getText(toFormatOptions(message, params, scope));
|
|
68
|
+
},
|
|
69
|
+
jsx(message: MessageInput, params?: MessageParams) {
|
|
70
|
+
return getJsx(toFormatOptions(message, params, scope));
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const createDescriptor = <const Text extends string, const Schema extends MessageSchema | undefined>(
|
|
76
|
+
message: Text,
|
|
77
|
+
schema: Schema | undefined,
|
|
78
|
+
scope: MessageScope,
|
|
79
|
+
): MessageDescriptor<Text, Schema> => {
|
|
80
|
+
return Object.freeze({
|
|
81
|
+
__fluenticMessage: true,
|
|
82
|
+
text: Array.isArray(message) ? message[0] : message,
|
|
83
|
+
...(Array.isArray(message) ? { compiled: message } : {}),
|
|
84
|
+
context: scope.context,
|
|
85
|
+
schema: schema ?? {},
|
|
86
|
+
notes: scope.notes,
|
|
87
|
+
meta: scope.meta,
|
|
88
|
+
}) as unknown as MessageDescriptor<Text, Schema>;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const toFormatOptions = (message: MessageInput, params: MessageParams | undefined, scope: MessageScope) => {
|
|
92
|
+
if (isMessageDescriptor(message)) return { msg: message, params };
|
|
93
|
+
|
|
94
|
+
return { msg: createDescriptor(message, undefined, scope), params };
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const rootScope = createScope({ context: null, notes: [] });
|
|
98
|
+
|
|
99
|
+
return Object.assign(rootScope, {
|
|
100
|
+
clone(message: MessageDescriptor) {
|
|
101
|
+
return Object.freeze({ ...message });
|
|
102
|
+
},
|
|
103
|
+
params<Params extends MessageParams>(params?: Params | null): Params {
|
|
104
|
+
return (params ?? {}) as Params;
|
|
105
|
+
},
|
|
106
|
+
tag<T = unknown, R = unknown>(handler: (chunks: Array<string | T>) => R) {
|
|
107
|
+
if (typeof handler !== 'function') {
|
|
108
|
+
const adapt = getRuntime().tagElement;
|
|
109
|
+
|
|
110
|
+
if (!adapt) throw new Error('[i18n] element tags require a platform adapter');
|
|
111
|
+
|
|
112
|
+
return createTagHandler(adapt(handler));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return createTagHandler(handler);
|
|
116
|
+
},
|
|
117
|
+
try<T>(renderer: TextRenderer | JsxRenderer, value: T, params?: MessageParams) {
|
|
118
|
+
return isMessageDescriptor(value)
|
|
119
|
+
? (renderer as (message: MessageInput, params?: MessageParams) => unknown)(value, params)
|
|
120
|
+
: value;
|
|
121
|
+
},
|
|
122
|
+
notranslate: noTranslate,
|
|
123
|
+
}) as TApi<I18nJsxOutput, I18nTagValue>;
|
|
124
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from '../index';
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { CompactMessage } from '../shared/compact';
|
|
2
|
+
import type { I18nJsxConfig } from '../types';
|
|
3
|
+
|
|
4
|
+
export type { I18nJsxConfig } from '../types';
|
|
5
|
+
|
|
6
|
+
export type I18nJsxOutput = I18nJsxConfig extends { JSX: infer Output; } ? NonNullable<Output> : unknown;
|
|
7
|
+
export type I18nTagElement = I18nJsxConfig extends { Element: infer Element; } ? Element : never;
|
|
8
|
+
export type I18nTagValue = I18nJsxConfig extends { Value: infer Value; } ? Value : unknown;
|
|
9
|
+
export type PrimitiveType = string | number | boolean | null | undefined;
|
|
10
|
+
|
|
11
|
+
export type LanguageId = string;
|
|
12
|
+
export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue; };
|
|
13
|
+
export type MessageMeta = JsonValue;
|
|
14
|
+
export type MessageContext = string;
|
|
15
|
+
|
|
16
|
+
export type MessageSchemaValue = StringConstructor | NumberConstructor | BooleanConstructor | DateConstructor;
|
|
17
|
+
export type MessageSchema = Partial<Record<string, MessageSchemaValue>>;
|
|
18
|
+
|
|
19
|
+
export type InferMessageSchema<Schema extends MessageSchema> = {
|
|
20
|
+
[Key in keyof Schema]: Schema[Key] extends StringConstructor ? string
|
|
21
|
+
: Schema[Key] extends NumberConstructor ? number
|
|
22
|
+
: Schema[Key] extends BooleanConstructor ? boolean
|
|
23
|
+
: Schema[Key] extends DateConstructor ? Date
|
|
24
|
+
: never;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type MessageDescriptor<Text extends string = string, Schema extends MessageSchema | undefined = MessageSchema> =
|
|
28
|
+
{
|
|
29
|
+
readonly __fluenticMessage: true;
|
|
30
|
+
readonly text: Text;
|
|
31
|
+
readonly compiled?: readonly [string, CompactMessage];
|
|
32
|
+
readonly context: MessageContext | null;
|
|
33
|
+
readonly schema: Schema extends MessageSchema ? Schema : MessageSchema;
|
|
34
|
+
readonly notes: readonly string[];
|
|
35
|
+
readonly meta: MessageMeta | undefined;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export type AnyMessageDescriptor = MessageDescriptor<string, MessageSchema | undefined>;
|
|
39
|
+
|
|
40
|
+
export type MessageValueContext = { languageId: LanguageId; };
|
|
41
|
+
export type MessageValueFactory<T = unknown> = (context: MessageValueContext) => T;
|
|
42
|
+
|
|
43
|
+
export type MessageTagHandler<T = unknown, R = unknown> = ((chunks: Array<string | T>) => R) & {
|
|
44
|
+
readonly __fluenticTagHandler: true;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export type MessageRuntimeValue =
|
|
48
|
+
| PrimitiveType
|
|
49
|
+
| Date
|
|
50
|
+
| AnyMessageDescriptor
|
|
51
|
+
| MessageValueFactory
|
|
52
|
+
| Pick<MessageTagHandler, '__fluenticTagHandler'>;
|
|
53
|
+
|
|
54
|
+
export type MessageParam = MessageRuntimeValue;
|
|
55
|
+
export type MessageParams = Record<string, MessageParam>;
|
|
56
|
+
export type MessageInput = string | AnyMessageDescriptor;
|
|
57
|
+
|
|
58
|
+
export type InferRuntimeParams<Schema extends MessageSchema> = {
|
|
59
|
+
[Key in keyof InferMessageSchema<Schema>]:
|
|
60
|
+
| InferMessageSchema<Schema>[Key]
|
|
61
|
+
| MessageValueFactory<InferMessageSchema<Schema>[Key]>;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export type DescriptorRenderArgs<Schema extends MessageSchema | undefined> = Schema extends undefined
|
|
65
|
+
? [params?: MessageParams]
|
|
66
|
+
: keyof Schema extends never ? []
|
|
67
|
+
: Schema extends MessageSchema ? [params: InferRuntimeParams<Schema>]
|
|
68
|
+
: never;
|
|
69
|
+
|
|
70
|
+
export type TryRenderArgs<Value> = Value extends { readonly __fluenticMessage: true; }
|
|
71
|
+
? Value extends MessageDescriptor<string, infer Schema>
|
|
72
|
+
? Schema extends MessageSchema | undefined ? DescriptorRenderArgs<Schema>
|
|
73
|
+
: [params: MessageParams]
|
|
74
|
+
: [params: MessageParams]
|
|
75
|
+
: [params?: MessageParams];
|
|
76
|
+
|
|
77
|
+
export type TextRenderer = {
|
|
78
|
+
<Text extends string>(message: Text, params?: MessageParams): string;
|
|
79
|
+
<Text extends string, Schema extends MessageSchema | undefined>(
|
|
80
|
+
message: MessageDescriptor<Text, Schema>,
|
|
81
|
+
...args: DescriptorRenderArgs<Schema>
|
|
82
|
+
): string;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
export type JsxRenderer<Output = unknown> = {
|
|
86
|
+
<Text extends string>(message: Text, params?: MessageParams): Output;
|
|
87
|
+
<Text extends string, Schema extends MessageSchema | undefined>(
|
|
88
|
+
message: MessageDescriptor<Text, Schema>,
|
|
89
|
+
...args: DescriptorRenderArgs<Schema>
|
|
90
|
+
): Output;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
export type MessageFormatOptions = {
|
|
94
|
+
msg: MessageInput;
|
|
95
|
+
params?: MessageParams;
|
|
96
|
+
languageId?: LanguageId;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
export type GetJsxHandler<Output = unknown> = (options: MessageFormatOptions) => Output;
|
|
100
|
+
|
|
101
|
+
export type CompiledTranslation = { compiled: CompactMessage; };
|
|
102
|
+
|
|
103
|
+
export type TranslationGetter = (args: {
|
|
104
|
+
languageId: LanguageId;
|
|
105
|
+
context: MessageContext | null;
|
|
106
|
+
message: string;
|
|
107
|
+
getCompiledId?: () => string;
|
|
108
|
+
}) => CompactMessage | CompiledTranslation | null;
|
|
109
|
+
|
|
110
|
+
export function isMessageDescriptor(value: unknown): value is AnyMessageDescriptor {
|
|
111
|
+
return value !== null && typeof value === 'object' && '__fluenticMessage' in value &&
|
|
112
|
+
value.__fluenticMessage === true;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function isMessageTagHandler(value: unknown): value is MessageTagHandler {
|
|
116
|
+
return typeof value === 'function' && '__fluenticTagHandler' in value && value.__fluenticTagHandler === true;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function isMessageSchemaValue(value: unknown): value is MessageSchemaValue {
|
|
120
|
+
return value === String || value === Number || value === Boolean || value === Date;
|
|
121
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import * as formatting from './core/format';
|
|
2
|
+
import { createT } from './core/i18n';
|
|
3
|
+
|
|
4
|
+
export const t = /* @__PURE__ */ createT(formatting);
|
|
5
|
+
export type { MessageApi, TApi } from './core/i18n';
|
|
6
|
+
export * from './core/types';
|
|
7
|
+
export { I18nRegistry, noTranslate, setFormats } from './shared/runtime';
|
|
8
|
+
export { defineTranslationLoader } from './translation-manager';
|
|
9
|
+
export type { TranslationData, TranslationItem, TranslationLoader, TranslationLoaderMap } from './translation-manager';
|
package/src/manager.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { createRuntime, defaultRuntime, type Formats, getFormats, type Runtime } from './shared/runtime';
|
|
2
|
+
import { createStateManager } from './state-manager';
|
|
3
|
+
import { createStorageManager, type I18nStorage } from './storage-manager';
|
|
4
|
+
import { type Catalog, createTranslationManager, type TranslationLoader } from './translation-manager';
|
|
5
|
+
|
|
6
|
+
export type { I18nStorage, StoredState } from './storage-manager';
|
|
7
|
+
export { defineTranslationLoader } from './translation-manager';
|
|
8
|
+
export type * from './translation-manager';
|
|
9
|
+
|
|
10
|
+
export type StateData = { languageId: string; isLoading: boolean; ready: boolean; };
|
|
11
|
+
export type I18nManagerOptions = { languageId: string; fallbackLanguageId?: string; };
|
|
12
|
+
export type CreateI18nManagerOptions = { storage?: I18nStorage | null; runtime?: Runtime; };
|
|
13
|
+
export type GetTranslationArgs = { languageId?: string; context?: string | null; message: string; };
|
|
14
|
+
|
|
15
|
+
export type I18nSnapshot = {
|
|
16
|
+
languageId: string;
|
|
17
|
+
fallbackLanguageId?: string;
|
|
18
|
+
translations: Record<string, Catalog>;
|
|
19
|
+
formats?: Partial<Formats>;
|
|
20
|
+
compiledLanguages?: string[];
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function createI18nManager(options: CreateI18nManagerOptions = {}) {
|
|
24
|
+
const runtime = options.runtime ?? createRuntime();
|
|
25
|
+
|
|
26
|
+
const state = createStateManager<StateData>({
|
|
27
|
+
languageId: runtime.languageId,
|
|
28
|
+
isLoading: false,
|
|
29
|
+
ready: runtime.ready,
|
|
30
|
+
});
|
|
31
|
+
const storage = createStorageManager(options.storage ?? null);
|
|
32
|
+
const translations = createTranslationManager();
|
|
33
|
+
|
|
34
|
+
let fallbackLanguageId: string | undefined;
|
|
35
|
+
let version = 0;
|
|
36
|
+
|
|
37
|
+
runtime.subscribe = state.subscribe;
|
|
38
|
+
runtime.getSnapshot = state.get;
|
|
39
|
+
|
|
40
|
+
/* configure */
|
|
41
|
+
|
|
42
|
+
const configure = (config: I18nManagerOptions) => {
|
|
43
|
+
runtime.languageId = config.languageId;
|
|
44
|
+
runtime.ready = false;
|
|
45
|
+
fallbackLanguageId = config.fallbackLanguageId;
|
|
46
|
+
version++;
|
|
47
|
+
state.set({ languageId: config.languageId, ready: false });
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const setTranslationLoader = (loader: TranslationLoader | null) => {
|
|
51
|
+
translations.setTranslationLoader(loader);
|
|
52
|
+
runtime.ready = false;
|
|
53
|
+
state.set({ ready: false });
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/* language and translations */
|
|
57
|
+
|
|
58
|
+
const init = async () => {
|
|
59
|
+
const saved = storage.hasStorage() ? await storage.getStorage().read() : null;
|
|
60
|
+
|
|
61
|
+
await loadTranslations(saved?.languageId ?? runtime.languageId);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const setLanguageId = async (languageId: string) => {
|
|
65
|
+
const committed = await loadTranslations(languageId);
|
|
66
|
+
|
|
67
|
+
if (committed && storage.hasStorage()) await storage.getStorage().write({ languageId });
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const getLanguageId = () => {
|
|
71
|
+
return runtime.languageId;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const getTranslation = (args: GetTranslationArgs) => {
|
|
75
|
+
for (const languageId of getLanguageIds(args.languageId ?? runtime.languageId)) {
|
|
76
|
+
const value = translations.getTranslation({ ...args, languageId, context: args.context ?? null });
|
|
77
|
+
|
|
78
|
+
if (value !== null) return value;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return null;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/* snapshots */
|
|
85
|
+
|
|
86
|
+
const getSnapshot = (): I18nSnapshot => {
|
|
87
|
+
return {
|
|
88
|
+
languageId: runtime.languageId,
|
|
89
|
+
fallbackLanguageId,
|
|
90
|
+
translations: Object.fromEntries(
|
|
91
|
+
Object.entries(translations.catalogs).map(([id, catalog]) => [id, { ...catalog }]),
|
|
92
|
+
),
|
|
93
|
+
formats: getFormats(runtime, runtime.languageId),
|
|
94
|
+
compiledLanguages: Object.keys(translations.compiledCatalogs).filter((id) => translations.compiledCatalogs[id]),
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const hydrate = (snapshot: I18nSnapshot) => {
|
|
99
|
+
version++;
|
|
100
|
+
|
|
101
|
+
for (const id of Object.keys(translations.catalogs)) delete translations.catalogs[id];
|
|
102
|
+
for (const id of Object.keys(translations.compiledCatalogs)) delete translations.compiledCatalogs[id];
|
|
103
|
+
for (const [id, catalog] of Object.entries(snapshot.translations)) {
|
|
104
|
+
translations.catalogs[id] = Object.assign(Object.create(null), catalog);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
for (const id of snapshot.compiledLanguages ?? []) translations.compiledCatalogs[id] = true;
|
|
108
|
+
|
|
109
|
+
runtime.formats = snapshot.formats ?? {};
|
|
110
|
+
runtime.languageId = snapshot.languageId;
|
|
111
|
+
fallbackLanguageId = snapshot.fallbackLanguageId;
|
|
112
|
+
runtime.ready = true;
|
|
113
|
+
state.set({ languageId: snapshot.languageId, ready: true, isLoading: false });
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/* utils */
|
|
117
|
+
|
|
118
|
+
const getLanguageIds = (languageId: string) => {
|
|
119
|
+
const ids = fallbackLanguageId === undefined
|
|
120
|
+
? [languageId, languageId.split('-')[0]]
|
|
121
|
+
: [languageId, languageId.split('-')[0], fallbackLanguageId];
|
|
122
|
+
|
|
123
|
+
return [...new Set(ids)];
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const loadTranslations = async (languageId: string) => {
|
|
127
|
+
const current = ++version;
|
|
128
|
+
state.set({ isLoading: true });
|
|
129
|
+
|
|
130
|
+
try {
|
|
131
|
+
await Promise.all(getLanguageIds(languageId).map(translations.loadTranslations));
|
|
132
|
+
if (version !== current) return false;
|
|
133
|
+
runtime.languageId = languageId;
|
|
134
|
+
runtime.ready = true;
|
|
135
|
+
state.set({ languageId, ready: true, isLoading: false });
|
|
136
|
+
|
|
137
|
+
return true;
|
|
138
|
+
} finally {
|
|
139
|
+
if (current === version) state.set({ isLoading: false });
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const manager = {
|
|
144
|
+
configure,
|
|
145
|
+
setStorage: storage.setStorage,
|
|
146
|
+
setTranslationLoader,
|
|
147
|
+
init,
|
|
148
|
+
setLanguageId,
|
|
149
|
+
getLanguageId,
|
|
150
|
+
getTranslation,
|
|
151
|
+
getSnapshot,
|
|
152
|
+
hydrate,
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
runtime.translationGetter = (args) => {
|
|
156
|
+
for (const languageId of getLanguageIds(args.languageId)) {
|
|
157
|
+
const compiled = translations.compiledCatalogs[languageId];
|
|
158
|
+
const message = compiled && args.getCompiledId ? args.getCompiledId() : args.message;
|
|
159
|
+
const context = compiled && args.getCompiledId ? null : args.context;
|
|
160
|
+
const value = translations.getTranslation({ languageId, context, message });
|
|
161
|
+
|
|
162
|
+
if (value !== null) return compiled ? { compiled: value } : value;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return null;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
return { manager, state, runtime };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export type ManagedI18n = ReturnType<typeof createI18nManager>;
|
|
172
|
+
export type I18nManager = ManagedI18n['manager'];
|
|
173
|
+
export const defaultManaged = createI18nManager({ runtime: defaultRuntime });
|
|
174
|
+
export const I18nManager = defaultManaged.manager;
|
|
175
|
+
export const defaultI18nState = defaultManaged.state;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { compileProgram } from '../compiler';
|
|
2
|
+
import { traverse } from '../compiler/analyze';
|
|
3
|
+
import { loadOptions, type PluginOptions } from './options';
|
|
4
|
+
/** Owns parsing even when a host (e.g. Metro) passes an already parsed AST. */
|
|
5
|
+
export default function fluenticBabel(_api: unknown, options: PluginOptions = {}) {
|
|
6
|
+
const config = loadOptions(options);
|
|
7
|
+
const handled = new WeakSet<object>();
|
|
8
|
+
const enabled = (code: string) => config.compiled && code.includes('@fluentic/i18n');
|
|
9
|
+
|
|
10
|
+
const compile = (code: string, filename: string) => {
|
|
11
|
+
const { ast } = compileProgram(code, filename, config);
|
|
12
|
+
// Standalone paths have a default Hub. Babel must create its own paths for presets.
|
|
13
|
+
traverse.cache.clear();
|
|
14
|
+
handled.add(ast.program);
|
|
15
|
+
|
|
16
|
+
return ast;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
return {
|
|
20
|
+
name: 'fluentic-i18n',
|
|
21
|
+
parserOverride(code: string, parserOptions: { sourceFilename?: string; }) {
|
|
22
|
+
if (!enabled(code)) return undefined;
|
|
23
|
+
|
|
24
|
+
return compile(code, parserOptions.sourceFilename ?? 'source.tsx');
|
|
25
|
+
},
|
|
26
|
+
pre(file: any) {
|
|
27
|
+
if (!enabled(file.code) || handled.has(file.path.node)) return;
|
|
28
|
+
|
|
29
|
+
const ast = compile(file.code, file.opts.filename ?? 'source.tsx');
|
|
30
|
+
file.path.replaceWith(ast.program);
|
|
31
|
+
file.scope.crawl();
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { transform } from '../compiler';
|
|
3
|
+
import { accepts, loadOptions, type PluginOptions } from './options';
|
|
4
|
+
|
|
5
|
+
export default function fluentic(options: PluginOptions = {}) {
|
|
6
|
+
return {
|
|
7
|
+
name: 'fluentic-i18n',
|
|
8
|
+
setup(build: any) {
|
|
9
|
+
let config = loadOptions(options, build.initialOptions.absWorkingDir);
|
|
10
|
+
build.onStart(() => {
|
|
11
|
+
config = loadOptions(options, build.initialOptions.absWorkingDir);
|
|
12
|
+
});
|
|
13
|
+
build.onLoad(
|
|
14
|
+
{ filter: /\.jsonl$/ },
|
|
15
|
+
async ({ path }: { path: string; }) => ({
|
|
16
|
+
contents: await readFile(path, 'utf8'),
|
|
17
|
+
loader: 'text',
|
|
18
|
+
watchFiles: [path],
|
|
19
|
+
}),
|
|
20
|
+
);
|
|
21
|
+
build.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async ({ path }: { path: string; }) => {
|
|
22
|
+
if (!config.compiled || !accepts(path, config)) return;
|
|
23
|
+
|
|
24
|
+
const result = transform(await readFile(path, 'utf8'), { ...config, filename: path });
|
|
25
|
+
|
|
26
|
+
if (!result) return;
|
|
27
|
+
|
|
28
|
+
const loader = /\.tsx$/.test(path)
|
|
29
|
+
? 'tsx'
|
|
30
|
+
: /\.[cm]?ts$/.test(path)
|
|
31
|
+
? 'ts'
|
|
32
|
+
: /\.jsx$/.test(path)
|
|
33
|
+
? 'jsx'
|
|
34
|
+
: 'js';
|
|
35
|
+
|
|
36
|
+
return {
|
|
37
|
+
contents: result.code + '\n//# sourceMappingURL=data:application/json;base64,' +
|
|
38
|
+
Buffer.from(JSON.stringify(result.map)).toString('base64'),
|
|
39
|
+
loader,
|
|
40
|
+
watchFiles: [path, ...(config.configFile ? [config.configFile] : [])],
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { createJiti } from 'jiti';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
export type PluginOptions = { compiled?: boolean; config?: string; includeDependencies?: boolean; };
|
|
6
|
+
|
|
7
|
+
export function loadOptions(
|
|
8
|
+
options: PluginOptions = {},
|
|
9
|
+
root = process.cwd(),
|
|
10
|
+
): PluginOptions & { configFile?: string; } {
|
|
11
|
+
const file = options.config
|
|
12
|
+
? resolve(root, options.config)
|
|
13
|
+
: ['i18n.config.ts', 'i18n.config.js', 'i18n.config.mjs'].map((name) => resolve(root, name)).find(existsSync);
|
|
14
|
+
|
|
15
|
+
const config = file
|
|
16
|
+
? createJiti(import.meta.url, { moduleCache: false })(file) as { default?: PluginOptions; } & PluginOptions
|
|
17
|
+
: {};
|
|
18
|
+
|
|
19
|
+
return { ...((config.default ?? config) as PluginOptions), ...options, configFile: file };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function accepts(id: string, options: PluginOptions) {
|
|
23
|
+
return /\.[cm]?[jt]sx?$/.test(id.split('?')[0]) && (options.includeDependencies || !id.includes('/node_modules/'));
|
|
24
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { transform } from '../compiler';
|
|
3
|
+
import { accepts, loadOptions, type PluginOptions } from './options';
|
|
4
|
+
|
|
5
|
+
export default function fluentic(options: PluginOptions = {}) {
|
|
6
|
+
let config = loadOptions(options);
|
|
7
|
+
|
|
8
|
+
return {
|
|
9
|
+
name: 'fluentic-i18n',
|
|
10
|
+
buildStart(this: { addWatchFile(file: string): void; }) {
|
|
11
|
+
if (config.configFile) this.addWatchFile(config.configFile);
|
|
12
|
+
},
|
|
13
|
+
watchChange(id: string) {
|
|
14
|
+
if (id === config.configFile) config = loadOptions(options);
|
|
15
|
+
},
|
|
16
|
+
async load(id: string) {
|
|
17
|
+
if (!id.endsWith('.jsonl')) return null;
|
|
18
|
+
|
|
19
|
+
const content = await readFile(id, 'utf8');
|
|
20
|
+
|
|
21
|
+
return { code: 'export default ' + JSON.stringify(content), map: { mappings: '' } };
|
|
22
|
+
},
|
|
23
|
+
transform(code: string, id: string) {
|
|
24
|
+
if (!config.compiled || !accepts(id, config)) return null;
|
|
25
|
+
|
|
26
|
+
return transform(code, { ...config, filename: id.split('?')[0] });
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|