i18n-json-react 0.0.0-stage → 0.1.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.
Files changed (157) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +401 -2
  3. package/bundlers/shared.cjs +91 -0
  4. package/dist/cjs/api-types.d.ts +17 -0
  5. package/dist/cjs/api-types.d.ts.map +1 -0
  6. package/dist/cjs/api-types.js +3 -0
  7. package/dist/cjs/api-types.js.map +1 -0
  8. package/dist/cjs/core.d.ts +10 -0
  9. package/dist/cjs/core.d.ts.map +1 -0
  10. package/dist/cjs/core.js +31 -0
  11. package/dist/cjs/core.js.map +1 -0
  12. package/dist/cjs/default-store.d.ts +7 -0
  13. package/dist/cjs/default-store.d.ts.map +1 -0
  14. package/dist/cjs/default-store.js +96 -0
  15. package/dist/cjs/default-store.js.map +1 -0
  16. package/dist/cjs/dictionaries.d.ts +7 -0
  17. package/dist/cjs/dictionaries.d.ts.map +1 -0
  18. package/dist/cjs/dictionaries.js +31 -0
  19. package/dist/cjs/dictionaries.js.map +1 -0
  20. package/dist/cjs/index.d.ts +24 -0
  21. package/dist/cjs/index.d.ts.map +1 -0
  22. package/dist/cjs/index.js +38 -0
  23. package/dist/cjs/index.js.map +1 -0
  24. package/dist/cjs/interpolation.d.ts +6 -0
  25. package/dist/cjs/interpolation.d.ts.map +1 -0
  26. package/dist/cjs/interpolation.js +26 -0
  27. package/dist/cjs/interpolation.js.map +1 -0
  28. package/dist/cjs/languages.d.ts +4 -0
  29. package/dist/cjs/languages.d.ts.map +1 -0
  30. package/dist/cjs/languages.js +61 -0
  31. package/dist/cjs/languages.js.map +1 -0
  32. package/dist/cjs/package.json +1 -0
  33. package/dist/cjs/react.d.ts +15 -0
  34. package/dist/cjs/react.d.ts.map +1 -0
  35. package/dist/cjs/react.js +54 -0
  36. package/dist/cjs/react.js.map +1 -0
  37. package/dist/cjs/resource.d.ts +8 -0
  38. package/dist/cjs/resource.d.ts.map +1 -0
  39. package/dist/cjs/resource.js +34 -0
  40. package/dist/cjs/resource.js.map +1 -0
  41. package/dist/cjs/store-types.d.ts +10 -0
  42. package/dist/cjs/store-types.d.ts.map +1 -0
  43. package/dist/cjs/store-types.js +17 -0
  44. package/dist/cjs/store-types.js.map +1 -0
  45. package/dist/cjs/store.d.ts +24 -0
  46. package/dist/cjs/store.d.ts.map +1 -0
  47. package/dist/cjs/store.js +139 -0
  48. package/dist/cjs/store.js.map +1 -0
  49. package/dist/cjs/typed-react.d.ts +5 -0
  50. package/dist/cjs/typed-react.d.ts.map +1 -0
  51. package/dist/cjs/typed-react.js +23 -0
  52. package/dist/cjs/typed-react.js.map +1 -0
  53. package/dist/cjs/types.d.ts +91 -0
  54. package/dist/cjs/types.d.ts.map +1 -0
  55. package/dist/cjs/types.js +3 -0
  56. package/dist/cjs/types.js.map +1 -0
  57. package/dist/esm/api-types.d.ts +17 -0
  58. package/dist/esm/api-types.d.ts.map +1 -0
  59. package/dist/esm/api-types.js +2 -0
  60. package/dist/esm/api-types.js.map +1 -0
  61. package/dist/esm/core.d.ts +10 -0
  62. package/dist/esm/core.d.ts.map +1 -0
  63. package/dist/esm/core.js +25 -0
  64. package/dist/esm/core.js.map +1 -0
  65. package/dist/esm/default-store.d.ts +7 -0
  66. package/dist/esm/default-store.d.ts.map +1 -0
  67. package/dist/esm/default-store.js +93 -0
  68. package/dist/esm/default-store.js.map +1 -0
  69. package/dist/esm/dictionaries.d.ts +7 -0
  70. package/dist/esm/dictionaries.d.ts.map +1 -0
  71. package/dist/esm/dictionaries.js +26 -0
  72. package/dist/esm/dictionaries.js.map +1 -0
  73. package/dist/esm/index.d.ts +24 -0
  74. package/dist/esm/index.d.ts.map +1 -0
  75. package/dist/esm/index.js +31 -0
  76. package/dist/esm/index.js.map +1 -0
  77. package/dist/esm/interpolation.d.ts +6 -0
  78. package/dist/esm/interpolation.d.ts.map +1 -0
  79. package/dist/esm/interpolation.js +22 -0
  80. package/dist/esm/interpolation.js.map +1 -0
  81. package/dist/esm/languages.d.ts +4 -0
  82. package/dist/esm/languages.d.ts.map +1 -0
  83. package/dist/esm/languages.js +57 -0
  84. package/dist/esm/languages.js.map +1 -0
  85. package/dist/esm/package.json +1 -0
  86. package/dist/esm/react.d.ts +15 -0
  87. package/dist/esm/react.d.ts.map +1 -0
  88. package/dist/esm/react.js +51 -0
  89. package/dist/esm/react.js.map +1 -0
  90. package/dist/esm/resource.d.ts +8 -0
  91. package/dist/esm/resource.d.ts.map +1 -0
  92. package/dist/esm/resource.js +31 -0
  93. package/dist/esm/resource.js.map +1 -0
  94. package/dist/esm/store-types.d.ts +10 -0
  95. package/dist/esm/store-types.d.ts.map +1 -0
  96. package/dist/esm/store-types.js +14 -0
  97. package/dist/esm/store-types.js.map +1 -0
  98. package/dist/esm/store.d.ts +24 -0
  99. package/dist/esm/store.d.ts.map +1 -0
  100. package/dist/esm/store.js +136 -0
  101. package/dist/esm/store.js.map +1 -0
  102. package/dist/esm/typed-react.d.ts +5 -0
  103. package/dist/esm/typed-react.d.ts.map +1 -0
  104. package/dist/esm/typed-react.js +20 -0
  105. package/dist/esm/typed-react.js.map +1 -0
  106. package/dist/esm/types.d.ts +91 -0
  107. package/dist/esm/types.d.ts.map +1 -0
  108. package/dist/esm/types.js +2 -0
  109. package/dist/esm/types.js.map +1 -0
  110. package/dist/types/registry.d.cts +10 -0
  111. package/native/README.md +179 -0
  112. package/native/android/README.md +14 -0
  113. package/native/android/cli.cjs +2 -0
  114. package/native/android/expo.cjs +1 -0
  115. package/native/android/expo.d.cts +1 -0
  116. package/native/android/index.cjs +3 -0
  117. package/native/android/index.d.cts +5 -0
  118. package/native/android/metro.cjs +3 -0
  119. package/native/android/metro.d.cts +7 -0
  120. package/native/android/prepare.cjs +3 -0
  121. package/native/cli.cjs +43 -0
  122. package/native/expo.cjs +17 -0
  123. package/native/expo.d.cts +7 -0
  124. package/native/index.cjs +18 -0
  125. package/native/index.d.cts +14 -0
  126. package/native/ios/README.md +58 -0
  127. package/native/ios/cli.cjs +2 -0
  128. package/native/ios/expo.cjs +1 -0
  129. package/native/ios/expo.d.cts +1 -0
  130. package/native/ios/index.cjs +3 -0
  131. package/native/ios/index.d.cts +5 -0
  132. package/native/ios/metro.cjs +3 -0
  133. package/native/ios/metro.d.cts +7 -0
  134. package/native/ios/prepare.cjs +3 -0
  135. package/native/metro.cjs +45 -0
  136. package/native/metro.d.cts +34 -0
  137. package/native/prepare.cjs +120 -0
  138. package/package.json +165 -4
  139. package/src/api-types.ts +42 -0
  140. package/src/core.ts +29 -0
  141. package/src/default-store.ts +106 -0
  142. package/src/dictionaries.ts +31 -0
  143. package/src/index.ts +46 -0
  144. package/src/interpolation.ts +31 -0
  145. package/src/languages.ts +62 -0
  146. package/src/react.ts +83 -0
  147. package/src/resource.ts +40 -0
  148. package/src/store-types.ts +36 -0
  149. package/src/store.ts +150 -0
  150. package/src/typed-react.ts +33 -0
  151. package/src/types.ts +113 -0
  152. package/types/registry.d.cts +10 -0
  153. package/vite/index.cjs +145 -0
  154. package/vite/index.d.cts +15 -0
  155. package/webpack/index.cjs +46 -0
  156. package/webpack/index.d.cts +22 -0
  157. package/webpack/loader.cjs +21 -0
package/package.json CHANGED
@@ -1,6 +1,167 @@
1
1
  {
2
2
  "name": "i18n-json-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Typed, feature-local JSON translations for React and React Native, with Vite, Webpack and Android/iOS Metro extraction.",
5
+ "type": "module",
6
+ "main": "./dist/cjs/index.js",
7
+ "module": "./dist/esm/index.js",
8
+ "types": "./dist/esm/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/esm/index.d.ts",
13
+ "default": "./dist/esm/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/cjs/index.d.ts",
17
+ "default": "./dist/cjs/index.js"
18
+ }
19
+ },
20
+ "./core": {
21
+ "import": {
22
+ "types": "./dist/esm/core.d.ts",
23
+ "default": "./dist/esm/core.js"
24
+ },
25
+ "require": {
26
+ "types": "./dist/cjs/core.d.ts",
27
+ "default": "./dist/cjs/core.js"
28
+ }
29
+ },
30
+ "./webpack": {
31
+ "types": "./webpack/index.d.cts",
32
+ "default": "./webpack/index.cjs"
33
+ },
34
+ "./vite": {
35
+ "types": "./vite/index.d.cts",
36
+ "default": "./vite/index.cjs"
37
+ },
38
+ "./native/android": {
39
+ "types": "./native/android/index.d.cts",
40
+ "default": "./native/android/index.cjs"
41
+ },
42
+ "./native/android/expo": {
43
+ "types": "./native/android/expo.d.cts",
44
+ "default": "./native/android/expo.cjs"
45
+ },
46
+ "./native/android/metro": {
47
+ "types": "./native/android/metro.d.cts",
48
+ "default": "./native/android/metro.cjs"
49
+ },
50
+ "./package.json": "./package.json",
51
+ "./native": {
52
+ "types": "./native/index.d.cts",
53
+ "default": "./native/index.cjs"
54
+ },
55
+ "./native/expo": {
56
+ "types": "./native/expo.d.cts",
57
+ "default": "./native/expo.cjs"
58
+ },
59
+ "./native/metro": {
60
+ "types": "./native/metro.d.cts",
61
+ "default": "./native/metro.cjs"
62
+ },
63
+ "./native/ios": {
64
+ "types": "./native/ios/index.d.cts",
65
+ "default": "./native/ios/index.cjs"
66
+ },
67
+ "./native/ios/expo": {
68
+ "types": "./native/ios/expo.d.cts",
69
+ "default": "./native/ios/expo.cjs"
70
+ },
71
+ "./native/ios/metro": {
72
+ "types": "./native/ios/metro.d.cts",
73
+ "default": "./native/ios/metro.cjs"
74
+ }
75
+ },
76
+ "files": [
77
+ "dist",
78
+ "src",
79
+ "types",
80
+ "webpack",
81
+ "vite",
82
+ "bundlers",
83
+ "native",
84
+ "README.md"
85
+ ],
86
+ "sideEffects": false,
87
+ "bin": {
88
+ "i18n-json-react-android": "./native/android/cli.cjs",
89
+ "i18n-json-react-native": "./native/cli.cjs",
90
+ "i18n-json-react-ios": "./native/ios/cli.cjs"
91
+ },
92
+ "scripts": {
93
+ "build": "node scripts/build.mjs",
94
+ "typecheck": "npm run build && tsc -p test/tsconfig.json && tsc -p test/tsconfig.registered.json && tsc -p test/tsconfig.languages-only.json && tsc -p test/tsconfig.registration-commonjs.json",
95
+ "test": "npm run build && node --test test/*.test.mjs",
96
+ "check": "npm run typecheck && node --test test/*.test.mjs",
97
+ "prepack": "npm run build"
98
+ },
99
+ "peerDependencies": {
100
+ "react": "^18.3.0 || ^19.0.0",
101
+ "expo-asset": ">=12.0.0",
102
+ "expo-file-system": ">=19.0.0",
103
+ "metro-config": "^0.83.0",
104
+ "vite": "^7.0.0 || ^8.0.0",
105
+ "webpack": "^5.0.0"
106
+ },
107
+ "peerDependenciesMeta": {
108
+ "react": {
109
+ "optional": true
110
+ },
111
+ "expo-asset": {
112
+ "optional": true
113
+ },
114
+ "expo-file-system": {
115
+ "optional": true
116
+ },
117
+ "metro-config": {
118
+ "optional": true
119
+ },
120
+ "vite": {
121
+ "optional": true
122
+ },
123
+ "webpack": {
124
+ "optional": true
125
+ }
126
+ },
127
+ "devDependencies": {
128
+ "@react-native/babel-preset": "0.81.5",
129
+ "@types/node": "^22.0.0",
130
+ "@types/react": "^19.0.0",
131
+ "react": "^19.0.0",
132
+ "react-dom": "^19.0.0",
133
+ "react-test-renderer": "^19.0.0",
134
+ "typescript": "^6.0.3",
135
+ "metro": "^0.83.8",
136
+ "metro-config": "^0.83.8",
137
+ "vite": "^8.3.5",
138
+ "webpack": "^5.0.0"
139
+ },
140
+ "engines": {
141
+ "node": ">=22.13.0"
142
+ },
143
+ "repository": {
144
+ "type": "git",
145
+ "url": "git+https://github.com/alex-tsx/i18n-json-react.git"
146
+ },
147
+ "bugs": {
148
+ "url": "https://github.com/alex-tsx/i18n-json-react/issues"
149
+ },
150
+ "homepage": "https://github.com/alex-tsx/i18n-json-react#readme",
151
+ "keywords": [
152
+ "i18n",
153
+ "react",
154
+ "json",
155
+ "typescript",
156
+ "localization",
157
+ "webpack",
158
+ "vite",
159
+ "vite-plugin",
160
+ "react-native",
161
+ "android",
162
+ "expo",
163
+ "metro",
164
+ "ios"
165
+ ],
166
+ "license": "MIT"
167
+ }
@@ -0,0 +1,42 @@
1
+ import type { NamedExoticComponent } from 'react';
2
+ import type { createReactBindings } from './react.js';
3
+ import type { I18nStore } from './store-types.js';
4
+ import type {
5
+ CheckedDictionary,
6
+ DefaultI18nOptions,
7
+ DictionaryInput,
8
+ DictionaryKeys,
9
+ RegisteredFallbackLanguage,
10
+ RemovePrefix,
11
+ SupportedLanguage,
12
+ TypoHook,
13
+ TypoProps,
14
+ } from './types.js';
15
+
16
+ export interface DictionaryReactBindings<L extends string, F extends string = never> {
17
+ createUseTypo<const D extends DictionaryInput>(info: CheckedDictionary<D, L, F>): TypoHook<DictionaryKeys<D>>;
18
+ createTypo<const D extends DictionaryInput>(
19
+ info: CheckedDictionary<D, L, F>,
20
+ ): NamedExoticComponent<TypoProps<DictionaryKeys<D>>>;
21
+ createTypo<const D extends DictionaryInput, P extends string>(
22
+ info: CheckedDictionary<D, L, F>,
23
+ prefix: P,
24
+ ): NamedExoticComponent<TypoProps<RemovePrefix<DictionaryKeys<D>, P>>>;
25
+ useTypoAsObject<const D extends DictionaryInput>(
26
+ info: CheckedDictionary<D, L, F>,
27
+ ): Record<DictionaryKeys<D>, string | undefined>;
28
+ }
29
+
30
+ export type ReactBindings<L extends string, F extends string = never> = Omit<
31
+ ReturnType<typeof createReactBindings<L>>,
32
+ keyof DictionaryReactBindings<L, F>
33
+ > &
34
+ DictionaryReactBindings<L, F>;
35
+
36
+ export type I18n<L extends string, F extends string = never> = I18nStore<L, F> & ReactBindings<L, F>;
37
+
38
+ export interface DefaultConfiguration {
39
+ configure<const L extends SupportedLanguage>(options: DefaultI18nOptions<L>): void;
40
+ }
41
+
42
+ export type DefaultI18n = I18n<SupportedLanguage, RegisteredFallbackLanguage> & DefaultConfiguration;
package/src/core.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { validateLanguageDictionary } from './dictionaries.js';
2
+ import { createI18nStore as createStore } from './store.js';
3
+ import { withDictionaryTypes } from './store-types.js';
4
+ import type { I18nStore } from './store-types.js';
5
+ import type { FetchDictionaryOptions, I18nOptions, LanguageDictionary } from './types.js';
6
+
7
+ export { interpolateTypo } from './interpolation.js';
8
+ export type { I18nStore } from './store-types.js';
9
+ export type * from './types.js';
10
+
11
+ /** Creates a React-independent store whose dictionary APIs check the configured languages. */
12
+ export function createI18nStore<const L extends string>(options: I18nOptions<L>): I18nStore<L> {
13
+ return withDictionaryTypes(createStore(options));
14
+ }
15
+
16
+ /** HTTP loader for the language files emitted by I18nCollectPlugin. */
17
+ export function createFetchDictionaryLoader(options: FetchDictionaryOptions = {}) {
18
+ const baseUrl = (options.baseUrl ?? 'i18n').replace(/\/+$/, '');
19
+ return async (language: string): Promise<LanguageDictionary> => {
20
+ const fetcher = options.fetch ?? globalThis.fetch;
21
+ if (!fetcher) throw new Error('No fetch implementation available; provide options.fetch');
22
+ const url = `${baseUrl}/${encodeURIComponent(language)}.json`;
23
+ const response = await fetcher(url, options.requestInit);
24
+ if (!response.ok) throw new Error(`Failed to load ${url}: HTTP ${response.status} ${response.statusText}`);
25
+ const dictionary: unknown = await response.json();
26
+ validateLanguageDictionary(dictionary);
27
+ return dictionary;
28
+ };
29
+ }
@@ -0,0 +1,106 @@
1
+ import { createI18nStore } from './store.js';
2
+ import type { I18nStore } from './store.js';
3
+ import type {
4
+ DictionaryInput,
5
+ DictionaryKeys,
6
+ DefaultI18nOptions,
7
+ GetterOptions,
8
+ I18nOptions,
9
+ InterpolationValues,
10
+ LoadOptions,
11
+ SupportedLanguage,
12
+ } from './types.js';
13
+
14
+ /** Stable delegates let module-scope feature factories work before configuration. */
15
+ export function createDefaultI18nStore() {
16
+ let current: I18nStore<SupportedLanguage> | undefined;
17
+ let unsubscribe: (() => void) | undefined;
18
+ let revision = 0;
19
+ let wakePendingReads = () => {};
20
+ let configurationChanged = new Promise<void>(resolve => {
21
+ wakePendingReads = resolve;
22
+ });
23
+ let suspendedReads = new WeakMap<Promise<unknown>, Promise<unknown>>();
24
+ const listeners = new Set<() => void>();
25
+
26
+ const emit = () => {
27
+ revision += 1;
28
+ for (const listener of listeners) listener();
29
+ };
30
+ const getStore = () => {
31
+ if (!current) throw new Error('Call I18N.configure(...) before reading translations or language state');
32
+ return current;
33
+ };
34
+
35
+ const store: I18nStore<SupportedLanguage> = {
36
+ get supportedLanguages() {
37
+ return getStore().supportedLanguages;
38
+ },
39
+ get fallbackLanguage() {
40
+ return getStore().fallbackLanguage;
41
+ },
42
+ interpolateTypo: (template, values) => getStore().interpolateTypo(template, values),
43
+ resolveLanguage: tag => getStore().resolveLanguage(tag),
44
+ getCurrentLang: () => getStore().getCurrentLang(),
45
+ getServerLanguage: () => getStore().getServerLanguage(),
46
+ setCurrentLang: language => getStore().setCurrentLang(language),
47
+ subscribe(listener) {
48
+ listeners.add(listener);
49
+ return () => {
50
+ listeners.delete(listener);
51
+ };
52
+ },
53
+ getSnapshot: () => revision,
54
+ getServerSnapshot: () => 0,
55
+ async loadLanguage(language?: SupportedLanguage, options?: LoadOptions) {
56
+ await getStore().loadLanguage(language, options);
57
+ },
58
+ readLanguage(language) {
59
+ try {
60
+ getStore().readLanguage(language);
61
+ } catch (error) {
62
+ if (!(error instanceof Promise)) throw error;
63
+ let pending = suspendedReads.get(error);
64
+ if (!pending) {
65
+ // Wake suspended roots when configuration changes, even if the old request never finishes.
66
+ pending = Promise.race([error, configurationChanged]);
67
+ suspendedReads.set(error, pending);
68
+ // Keep the thrown promise rejecting for React while handling an unread imperative branch.
69
+ void pending.catch(failure => failure);
70
+ }
71
+ throw pending;
72
+ }
73
+ },
74
+ createTypoGetter<const D extends DictionaryInput>(info: D, options: GetterOptions<SupportedLanguage> = {}) {
75
+ let boundStore: I18nStore<SupportedLanguage> | undefined;
76
+ let getText: ((key: DictionaryKeys<D>, values?: InterpolationValues) => string) | undefined;
77
+ return (key: DictionaryKeys<D>, values?: InterpolationValues) => {
78
+ const configured = getStore();
79
+ if (boundStore !== configured || !getText) {
80
+ getText = configured.createTypoGetter(info, options);
81
+ boundStore = configured;
82
+ }
83
+ return getText(key, values);
84
+ };
85
+ },
86
+ getTypoAsObject: (info, language) => getStore().getTypoAsObject(info, language),
87
+ };
88
+
89
+ /** Replaces the whole configuration atomically; existing helpers follow the new store. */
90
+ function configure<const L extends SupportedLanguage>(options: DefaultI18nOptions<L>): void;
91
+ function configure(options: I18nOptions<SupportedLanguage>) {
92
+ const next = createI18nStore(options);
93
+ // Validate the new store before changing the active configuration or its subscriptions.
94
+ unsubscribe?.();
95
+ current = next;
96
+ unsubscribe = next.subscribe(emit);
97
+ wakePendingReads();
98
+ configurationChanged = new Promise<void>(resolve => {
99
+ wakePendingReads = resolve;
100
+ });
101
+ suspendedReads = new WeakMap();
102
+ emit();
103
+ }
104
+
105
+ return Object.assign(store, { configure });
106
+ }
@@ -0,0 +1,31 @@
1
+ import type { DictionaryInput, LanguageDictionary, Messages } from './types.js';
2
+
3
+ export function getMessages(
4
+ info: DictionaryInput,
5
+ language: string,
6
+ dictionaries: ReadonlyMap<string, LanguageDictionary>,
7
+ ): Messages | undefined {
8
+ if (isReference(info)) {
9
+ const dictionary = dictionaries.get(language);
10
+ return dictionary && Object.hasOwn(dictionary, info.__id) ? dictionary[info.__id] : undefined;
11
+ }
12
+ return Object.hasOwn(info, language) ? info[language] : undefined;
13
+ }
14
+
15
+ export function isReference(info: DictionaryInput): info is { readonly __id: string } {
16
+ return typeof info.__id === 'string';
17
+ }
18
+
19
+ export function validateLanguageDictionary(value: unknown): asserts value is LanguageDictionary {
20
+ if (!isRecord(value)) throw new TypeError('Expected a language dictionary object');
21
+ for (const [id, messages] of Object.entries(value)) {
22
+ if (!isRecord(messages)) throw new TypeError(`Expected a message object for feature "${id}"`);
23
+ for (const [key, message] of Object.entries(messages)) {
24
+ if (typeof message !== 'string') throw new TypeError(`Expected a string for "${id}.${key}"`);
25
+ }
26
+ }
27
+ }
28
+
29
+ function isRecord(value: unknown): value is Record<string, unknown> {
30
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
31
+ }
package/src/index.ts ADDED
@@ -0,0 +1,46 @@
1
+ 'use client';
2
+
3
+ import { createI18nStore } from './store.js';
4
+ import { createDefaultI18nStore } from './default-store.js';
5
+ import { withDictionaryTypes } from './store-types.js';
6
+ import { bindReact } from './typed-react.js';
7
+ import type { I18nOptions, RegisteredFallbackLanguage, SupportedLanguage } from './types.js';
8
+ import type { DefaultI18n, I18n } from './api-types.js';
9
+
10
+ export { createFetchDictionaryLoader, createI18nStore, interpolateTypo } from './core.js';
11
+ export type { I18nStore } from './core.js';
12
+ export type { DefaultI18n, I18n } from './api-types.js';
13
+ export type * from './types.js';
14
+
15
+ /** Creates an isolated language store and its bound React helpers. No provider is needed. */
16
+ export function createI18n<const L extends string>(options: I18nOptions<L>): I18n<L> {
17
+ const store = createI18nStore(options);
18
+ return Object.assign(withDictionaryTypes(store), bindReact(store));
19
+ }
20
+
21
+ const I18N = createSharedI18n();
22
+
23
+ export default I18N;
24
+
25
+ /** These helpers share the default instance configured with I18N.configure(...). */
26
+ export const configure: DefaultI18n['configure'] = I18N.configure;
27
+ export const createTypo: DefaultI18n['createTypo'] = I18N.createTypo;
28
+ export const createUseTypo: DefaultI18n['createUseTypo'] = I18N.createUseTypo;
29
+ export const createTypoGetter: DefaultI18n['createTypoGetter'] = I18N.createTypoGetter;
30
+ export const useTypoAsObject: DefaultI18n['useTypoAsObject'] = I18N.useTypoAsObject;
31
+ export const useI18nLanguage: DefaultI18n['useI18nLanguage'] = I18N.useI18nLanguage;
32
+ export const LoaderForI18N: DefaultI18n['LoaderForI18N'] = I18N.LoaderForI18N;
33
+ export const getCurrentLang: DefaultI18n['getCurrentLang'] = I18N.getCurrentLang;
34
+ export const setCurrentLang: DefaultI18n['setCurrentLang'] = I18N.setCurrentLang;
35
+ export const resolveLanguage: DefaultI18n['resolveLanguage'] = I18N.resolveLanguage;
36
+ export const subscribe: DefaultI18n['subscribe'] = I18N.subscribe;
37
+ export const loadLanguage: DefaultI18n['loadLanguage'] = I18N.loadLanguage;
38
+
39
+ function createSharedI18n(): DefaultI18n {
40
+ const store = createDefaultI18nStore();
41
+ return Object.assign(
42
+ withDictionaryTypes<SupportedLanguage, RegisteredFallbackLanguage>(store),
43
+ bindReact<SupportedLanguage, RegisteredFallbackLanguage>(store),
44
+ { configure: store.configure },
45
+ );
46
+ }
@@ -0,0 +1,31 @@
1
+ import type { InterpolationDelimiters, InterpolationValues } from './types.js';
2
+
3
+ const DEFAULT_DELIMITERS: InterpolationDelimiters = { prefix: '{', suffix: '}' };
4
+ const interpolateDefault = createInterpolator();
5
+
6
+ /** Replaces interpolation parameters using literal delimiters; defaults to {name}. */
7
+ export function interpolateTypo(
8
+ template: string,
9
+ values: InterpolationValues,
10
+ delimiters?: InterpolationDelimiters,
11
+ ): string {
12
+ const interpolate = delimiters === undefined ? interpolateDefault : createInterpolator(delimiters);
13
+ return interpolate(template, values);
14
+ }
15
+
16
+ /** Compiles once per instance so translators do not create regular expressions on each call. */
17
+ export function createInterpolator({ prefix, suffix }: InterpolationDelimiters = DEFAULT_DELIMITERS) {
18
+ if (typeof prefix !== 'string' || !prefix || typeof suffix !== 'string' || !suffix) {
19
+ throw new TypeError('Interpolation prefix and suffix must be nonempty strings');
20
+ }
21
+ const pattern = new RegExp(`${escapeRegExp(prefix)}([\\w.-]+?)${escapeRegExp(suffix)}`, 'g');
22
+ return (template: string, values: InterpolationValues): string =>
23
+ template.replace(pattern, (_, key: string) => {
24
+ const value = Object.hasOwn(values, key) ? values[key] : undefined;
25
+ return value == null ? '' : String(value);
26
+ });
27
+ }
28
+
29
+ function escapeRegExp(value: string) {
30
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
31
+ }
@@ -0,0 +1,62 @@
1
+ import type { I18nOptions, StorageAdapter } from './types.js';
2
+
3
+ export function createLanguageResolver<L extends string>(languages: readonly L[]) {
4
+ const normalized = new Map<string, L>();
5
+ for (const language of languages) {
6
+ if (!/^[a-zA-Z]{2,8}(?:[-_][a-zA-Z0-9]{1,8})*$/.test(language)) {
7
+ throw new Error(`Invalid language identifier: ${language}`);
8
+ }
9
+ const tag = normalize(language);
10
+ if (normalized.has(tag)) throw new Error(`Duplicate language identifier: ${language}`);
11
+ normalized.set(tag, language);
12
+ }
13
+
14
+ return (tag: string): L | undefined => {
15
+ let candidate = normalize(tag);
16
+ // Prefer an exact regional/script match, then progressively less specific tags.
17
+ while (candidate) {
18
+ const match = normalized.get(candidate);
19
+ if (match !== undefined) return match;
20
+ const separator = candidate.lastIndexOf('-');
21
+ if (separator === -1) break;
22
+ candidate = candidate.slice(0, separator);
23
+ }
24
+ return undefined;
25
+ };
26
+ }
27
+
28
+ export function detectLanguage<L extends string>(
29
+ options: I18nOptions<L>,
30
+ resolve: (tag: string) => L | undefined,
31
+ getStorage: () => StorageAdapter | undefined,
32
+ onError: (error: unknown) => void,
33
+ ): L {
34
+ if (options.initialLanguage !== undefined) return options.initialLanguage;
35
+
36
+ try {
37
+ const stored = getStorage()?.getItem(options.storageKey ?? 'i18n-language');
38
+ const language = stored ? resolve(stored) : undefined;
39
+ if (language !== undefined) return language;
40
+ } catch (error) {
41
+ onError(error);
42
+ }
43
+
44
+ const browserLanguages =
45
+ options.getBrowserLanguages?.() ??
46
+ (typeof navigator === 'undefined'
47
+ ? []
48
+ : navigator.languages?.length
49
+ ? navigator.languages
50
+ : navigator.language
51
+ ? [navigator.language]
52
+ : []);
53
+ for (const tag of browserLanguages) {
54
+ const language = resolve(tag);
55
+ if (language !== undefined) return language;
56
+ }
57
+ return options.fallbackLanguage;
58
+ }
59
+
60
+ function normalize(tag: string) {
61
+ return tag.trim().replaceAll('_', '-').toLowerCase();
62
+ }
package/src/react.ts ADDED
@@ -0,0 +1,83 @@
1
+ 'use client';
2
+
3
+ import { memo, useCallback, useMemo, useSyncExternalStore } from 'react';
4
+ import type { NamedExoticComponent } from 'react';
5
+ import type { I18nStore } from './store.js';
6
+ import { isReference } from './dictionaries.js';
7
+ import type {
8
+ DictionaryInput,
9
+ DictionaryKeys,
10
+ InterpolationValues,
11
+ RemovePrefix,
12
+ Typo,
13
+ TypoHook,
14
+ TypoOptions,
15
+ TypoProps,
16
+ } from './types.js';
17
+
18
+ /** Shared bindings for isolated instances and the configurable default instance. */
19
+ export function createReactBindings<L extends string>(store: I18nStore<L>) {
20
+ function useI18nLanguage() {
21
+ return useSyncExternalStore(store.subscribe, store.getCurrentLang, store.getServerLanguage);
22
+ }
23
+
24
+ function useDictionaryLanguage(info: DictionaryInput) {
25
+ const language = useI18nLanguage();
26
+ // A language file can finish loading without the language itself changing.
27
+ const revision = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
28
+ if (isReference(info)) store.readLanguage(language);
29
+ return { language, revision };
30
+ }
31
+
32
+ function useGetText(info: DictionaryInput, placehold = true) {
33
+ const { language, revision } = useDictionaryLanguage(info);
34
+ return useMemo(() => store.createTypoGetter(info, { language, placehold }), [info, language, placehold, revision]);
35
+ }
36
+
37
+ function createUseTypo<const D extends DictionaryInput>(info: D): TypoHook<DictionaryKeys<D>> {
38
+ function useTypo<P extends string>(
39
+ hookOptions: TypoOptions<P> & { keyPrefix: P },
40
+ ): Typo<RemovePrefix<DictionaryKeys<D>, P>>;
41
+ function useTypo(hookOptions?: TypoOptions<never>): Typo<DictionaryKeys<D>>;
42
+ function useTypo<P extends string>(hookOptions?: TypoOptions<P>): Typo<string> {
43
+ const getText = useGetText(info, hookOptions?.placehold ?? true);
44
+ const prefix = hookOptions?.keyPrefix ?? '';
45
+ const translate = useCallback(
46
+ (key: string, values?: InterpolationValues) => {
47
+ return getText(`${prefix}${key}`, values);
48
+ },
49
+ [getText, prefix],
50
+ );
51
+ return useMemo(() => Object.assign(translate, { t: translate }), [translate]);
52
+ }
53
+ return useTypo;
54
+ }
55
+
56
+ function createTypo<const D extends DictionaryInput>(info: D): NamedExoticComponent<TypoProps<DictionaryKeys<D>>>;
57
+ function createTypo<const D extends DictionaryInput, P extends string>(
58
+ info: D,
59
+ prefix: P,
60
+ ): NamedExoticComponent<TypoProps<RemovePrefix<DictionaryKeys<D>, P>>>;
61
+ function createTypo<const D extends DictionaryInput, P extends string>(info: D, prefix?: P) {
62
+ const Component = memo<TypoProps<string>>(({ id, values }) => {
63
+ const getText = useGetText(info);
64
+ return getText(`${prefix ?? ''}${id}`, values);
65
+ });
66
+ Component.displayName = 'Typo';
67
+ return Component;
68
+ }
69
+
70
+ function useTypoAsObject<const D extends DictionaryInput>(info: D): Record<DictionaryKeys<D>, string | undefined>;
71
+ function useTypoAsObject(info: DictionaryInput) {
72
+ const { language, revision } = useDictionaryLanguage(info);
73
+ return useMemo(() => store.getTypoAsObject(info, language), [info, language, revision]);
74
+ }
75
+
76
+ const LoaderForI18N = memo(function LoaderForI18N() {
77
+ useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
78
+ store.readLanguage(useI18nLanguage());
79
+ return null;
80
+ });
81
+
82
+ return { useI18nLanguage, createUseTypo, createTypo, useTypoAsObject, LoaderForI18N };
83
+ }
@@ -0,0 +1,40 @@
1
+ /** A small Suspense resource: deduplicates a request and retains its result or error. */
2
+ export interface AsyncResource<T> {
3
+ promise: Promise<T>;
4
+ read(): T;
5
+ isRejected(): boolean;
6
+ }
7
+
8
+ export function createAsyncResource<T>(load: () => Promise<T>): AsyncResource<T> {
9
+ let status: 'pending' | 'fulfilled' | 'rejected' = 'pending';
10
+ let result: T;
11
+ let failure: unknown;
12
+ const promise = Promise.resolve()
13
+ .then(load)
14
+ .then(
15
+ value => {
16
+ result = value;
17
+ status = 'fulfilled';
18
+ return value;
19
+ },
20
+ error => {
21
+ failure = error;
22
+ status = 'rejected';
23
+ throw error;
24
+ },
25
+ );
26
+
27
+ // React owns suspended promises, but an imperative prefetch may have no reader yet.
28
+ // Handle the rejection on a separate branch; the public promise still rejects.
29
+ void promise.catch(error => error);
30
+
31
+ return {
32
+ promise,
33
+ read() {
34
+ if (status === 'pending') throw promise;
35
+ if (status === 'rejected') throw failure;
36
+ return result;
37
+ },
38
+ isRejected: () => status === 'rejected',
39
+ };
40
+ }