@magicdoor/magic-localization 0.0.0-stage → 0.1.0
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/LICENSE +202 -0
- package/README.md +186 -2
- package/dist/index.d.ts +66 -0
- package/dist/index.js +26 -0
- package/package.json +61 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 MagicDoor, Inc.
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,187 @@
|
|
|
1
|
-
#
|
|
1
|
+
# magic-localization
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Translations from string enums, checked by the compiler. You write one enum per language, hand them all to a
|
|
4
|
+
single `createDictionary` call, and TypeScript refuses to build if any language:
|
|
5
|
+
|
|
6
|
+
- is missing a key the base language has, or carries one it does not;
|
|
7
|
+
- fills a string with different placeholders than the base language (`{name}` vs `{nombre}`, a dropped or an
|
|
8
|
+
added placeholder — the order may differ);
|
|
9
|
+
- is anything other than a string enum (an `as const` object, a plain record, a numeric enum).
|
|
10
|
+
|
|
11
|
+
The library holds no state and knows no framework. Which language the screen is in belongs to your app: a
|
|
12
|
+
signal, a store, a context, application state. You pass it to `translate` on every call.
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install @magicdoor/magic-localization
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## The dictionary
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import {
|
|
22
|
+
createDictionary,
|
|
23
|
+
type DictionaryKey,
|
|
24
|
+
type DictionaryLanguage,
|
|
25
|
+
type TranslatableText,
|
|
26
|
+
type Translator,
|
|
27
|
+
} from '@magicdoor/magic-localization';
|
|
28
|
+
|
|
29
|
+
// your languages: name and code them however your app does
|
|
30
|
+
export enum Language {
|
|
31
|
+
En = 'en',
|
|
32
|
+
Es = 'es',
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export enum English {
|
|
36
|
+
WELCOME = 'Welcome, {name}',
|
|
37
|
+
LEASE_STATUS = 'Lease {status}',
|
|
38
|
+
ACTIVE = 'active',
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export enum Spanish {
|
|
42
|
+
WELCOME = 'Bienvenido, {name}',
|
|
43
|
+
LEASE_STATUS = 'Contrato {status}',
|
|
44
|
+
ACTIVE = 'activo',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const dictionary = createDictionary({
|
|
48
|
+
base: Language.En,
|
|
49
|
+
translations: { [Language.En]: English, [Language.Es]: Spanish },
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
export type Key = DictionaryKey<typeof dictionary>; // 'WELCOME' | 'LEASE_STATUS' | 'ACTIVE'
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
The library has no languages of its own. A dictionary's languages are exactly the keys of `translations`, coded
|
|
56
|
+
however your app codes them — `'en'`, `'en-GB'`, `'pt-BR'`, `'klingon'` — and `base` is one of them. An app
|
|
57
|
+
without its own enum can name them from the dictionary instead:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const dictionary = createDictionary({ base: 'en-GB', translations: { 'en-GB': English, 'pt-BR': Portuguese } });
|
|
61
|
+
|
|
62
|
+
type Language = DictionaryLanguage<typeof dictionary>; // 'en-GB' | 'pt-BR'
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`createDictionary` returns:
|
|
66
|
+
|
|
67
|
+
| Member | What it is |
|
|
68
|
+
| ----------------------------------- | ------------------------------------------------------------------- |
|
|
69
|
+
| `keys` | every key of the base language, named after itself: `keys.WELCOME` |
|
|
70
|
+
| `base` | the base language |
|
|
71
|
+
| `translate(language, key, params?)` | the key in that language, its `{placeholders}` filled from `params` |
|
|
72
|
+
| `translate(language, text)` | a `TranslatableText` in that language |
|
|
73
|
+
| `isLanguage(code)` | whether `code` is a language the dictionary has, narrowing it if so |
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
dictionary.translate(Language.Es, dictionary.keys.WELCOME, { name: 'Ana' }); // 'Bienvenido, Ana'
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Code that decides what to say — a presenter, a view model — returns a `TranslatableText` instead of a string,
|
|
80
|
+
and only the UI translates it. A placeholder can be a text of its own, translated in the same language:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const label: TranslatableText<Key> = {
|
|
84
|
+
key: dictionary.keys.LEASE_STATUS,
|
|
85
|
+
params: { status: { key: dictionary.keys.ACTIVE } },
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
dictionary.translate(Language.Es, label); // 'Contrato activo'
|
|
89
|
+
dictionary.translate(Language.Es, { params: { text: 'Maple Grove, 4B' } }); // shown as it is, in any language
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Your `t`
|
|
93
|
+
|
|
94
|
+
Each app writes a few lines that read its language and hand it to `translate`. Type `t` as `Translator<Key>`
|
|
95
|
+
and it checks keys and texts as strictly as `translate` does.
|
|
96
|
+
|
|
97
|
+
Build `t` so it reads the language **every time it runs**. A `t` that captured the language once keeps
|
|
98
|
+
translating into that language after it changes.
|
|
99
|
+
|
|
100
|
+
### Solid, with a signal
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { createSignal } from 'solid-js';
|
|
104
|
+
|
|
105
|
+
const [language, setLanguage] = createSignal<Language>(dictionary.base);
|
|
106
|
+
|
|
107
|
+
export const changeLanguage = setLanguage;
|
|
108
|
+
|
|
109
|
+
export const useTranslation = () => {
|
|
110
|
+
const t: Translator<Key> = (keyOrText, params?) => dictionary.translate(language(), keyOrText, params);
|
|
111
|
+
return { t };
|
|
112
|
+
};
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Whatever shows `t(...)` updates when `changeLanguage` is called, because `t` reads the signal.
|
|
116
|
+
|
|
117
|
+
### Solid, with the language in application state
|
|
118
|
+
|
|
119
|
+
When the language already lives in application state that components read through presenters, the hook reads
|
|
120
|
+
it the same way — it never touches the state itself, and changing the language stays with whatever already
|
|
121
|
+
writes that state.
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import { usePresenter } from '@magicdoor/magic-use-case-solid';
|
|
125
|
+
|
|
126
|
+
export const presentSelectedLanguage = (state: AppState) => ({ language: state.selectedLanguage });
|
|
127
|
+
|
|
128
|
+
export const useTranslation = () => {
|
|
129
|
+
const { model } = usePresenter(presentSelectedLanguage);
|
|
130
|
+
const t: Translator<Key> = (keyOrText, params?) =>
|
|
131
|
+
dictionary.translate(model()?.language ?? dictionary.base, keyOrText, params);
|
|
132
|
+
return { t };
|
|
133
|
+
};
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### React, with a context
|
|
137
|
+
|
|
138
|
+
```tsx
|
|
139
|
+
import { createContext, useContext, useMemo, useState, type ReactNode } from 'react';
|
|
140
|
+
|
|
141
|
+
const LanguageContext = createContext<{ language: Language; setLanguage: (language: Language) => void }>({
|
|
142
|
+
language: dictionary.base,
|
|
143
|
+
setLanguage: () => {},
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
export const LanguageProvider = ({ children }: { children: ReactNode }) => {
|
|
147
|
+
const [language, setLanguage] = useState<Language>(dictionary.base);
|
|
148
|
+
const value = useMemo(() => ({ language, setLanguage }), [language]);
|
|
149
|
+
return <LanguageContext.Provider value={value}>{children}</LanguageContext.Provider>;
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
export const useTranslation = () => {
|
|
153
|
+
const { language, setLanguage } = useContext(LanguageContext);
|
|
154
|
+
const t = useMemo<Translator<Key>>(
|
|
155
|
+
() => (keyOrText, params?) => dictionary.translate(language, keyOrText, params),
|
|
156
|
+
[language],
|
|
157
|
+
);
|
|
158
|
+
return { t, changeLanguage: setLanguage };
|
|
159
|
+
};
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
The language can as well come from a store — Redux, Zustand, `useSyncExternalStore` — as long as `t` is rebuilt
|
|
163
|
+
when it changes.
|
|
164
|
+
|
|
165
|
+
### Restoring a language chosen earlier
|
|
166
|
+
|
|
167
|
+
A code read back from storage is a plain string. Check it before it becomes the language:
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
const stored = localStorage.getItem('language') ?? undefined;
|
|
171
|
+
const initial: Language = dictionary.isLanguage(stored) ? stored : dictionary.base;
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
## Development
|
|
175
|
+
|
|
176
|
+
```sh
|
|
177
|
+
npm install
|
|
178
|
+
npm run build
|
|
179
|
+
npm run type-check # includes the tests, whose @ts-expect-error lines are the compile-time checks
|
|
180
|
+
npm run lint
|
|
181
|
+
npm run format-check
|
|
182
|
+
npm run coverage # the suite, failing under 100%
|
|
183
|
+
npm run check-package
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Releases are versioned with [changesets](https://github.com/changesets/changesets): `npm run changeset` to record
|
|
187
|
+
a change, `npm run release` to build and publish.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A key with the values its placeholders take, a value being a text of its own where it is a word too —
|
|
3
|
+
* or, with no key, a text shown as it is.
|
|
4
|
+
*/
|
|
5
|
+
type TranslatableText<Key extends string> = {
|
|
6
|
+
readonly key: Key;
|
|
7
|
+
readonly params?: Readonly<Record<string, string | number | TranslatableText<Key>>>;
|
|
8
|
+
} | {
|
|
9
|
+
readonly params: {
|
|
10
|
+
readonly text: string;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
type Placeholders<Text extends string> = Text extends `${string}{${infer Name}}${infer Rest}` ? Name | Placeholders<Rest> : never;
|
|
14
|
+
type PlaceholdersOf<Value> = Value extends string ? Placeholders<`${Value}`> : never;
|
|
15
|
+
type SameUnion<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
|
|
16
|
+
type Exact<Base, T> = {
|
|
17
|
+
[K in keyof Base]: K extends keyof T ? SameUnion<PlaceholdersOf<Base[K]>, PlaceholdersOf<T[K]>> extends true ? string : {
|
|
18
|
+
placeholdersExpected: PlaceholdersOf<Base[K]>;
|
|
19
|
+
} : string;
|
|
20
|
+
} & {
|
|
21
|
+
[K in Exclude<keyof T, keyof Base>]: never;
|
|
22
|
+
};
|
|
23
|
+
type IsEnumMember<V> = V extends string ? (`${V}` extends V ? false : true) : false;
|
|
24
|
+
type IsStringEnum<T> = false extends {
|
|
25
|
+
[K in keyof T]: IsEnumMember<T[K]>;
|
|
26
|
+
}[keyof T] ? false : true;
|
|
27
|
+
type Dictionaries<T extends Record<string, object>, Base extends keyof T> = {
|
|
28
|
+
[Language in keyof T]: IsStringEnum<T[Language]> extends true ? Exact<T[Base], T[Language]> : 'a translation file must be a string enum';
|
|
29
|
+
} & T;
|
|
30
|
+
/**
|
|
31
|
+
* Every language must carry exactly the keys of `base`, each with the same placeholders, so a string
|
|
32
|
+
* missing from, misspelled in, or filled differently by any language is a compile error naming that
|
|
33
|
+
* language. Only string enums are accepted as translation files.
|
|
34
|
+
*/
|
|
35
|
+
interface LocalizationConfig<T extends Record<string, object>, Base extends LanguageOf<T>> {
|
|
36
|
+
base: Base;
|
|
37
|
+
translations: Dictionaries<T, Base>;
|
|
38
|
+
}
|
|
39
|
+
type KeyOf<T extends Record<string, object>, Base extends keyof T> = Extract<keyof T[Base], string>;
|
|
40
|
+
type LanguageOf<T extends Record<string, object>> = Extract<keyof T, string>;
|
|
41
|
+
interface Translator<Key extends string> {
|
|
42
|
+
(key: Key, params?: Record<string, unknown>): string;
|
|
43
|
+
(text: TranslatableText<Key>, params?: undefined): string;
|
|
44
|
+
}
|
|
45
|
+
/** The keys of a dictionary `createDictionary` made, named from its type: `DictionaryKey<typeof dictionary>`. */
|
|
46
|
+
type DictionaryKey<D extends {
|
|
47
|
+
readonly keys: Readonly<Record<string, string>>;
|
|
48
|
+
}> = Extract<keyof D['keys'], string>;
|
|
49
|
+
/** The languages of a dictionary `createDictionary` made, named from its type: `DictionaryLanguage<typeof dictionary>`. */
|
|
50
|
+
type DictionaryLanguage<D extends {
|
|
51
|
+
readonly isLanguage: (code?: string) => boolean;
|
|
52
|
+
}> = D['isLanguage'] extends ((code?: string) => code is infer Language extends string) ? Language : never;
|
|
53
|
+
|
|
54
|
+
/** The translations themselves, independent of any framework: the language is the caller's to pass. */
|
|
55
|
+
declare function createDictionary<T extends Record<string, object>, Base extends LanguageOf<T>>(config: LocalizationConfig<T, Base>): {
|
|
56
|
+
base: Base;
|
|
57
|
+
keys: Record<KeyOf<T, Base>, KeyOf<T, Base>>;
|
|
58
|
+
isLanguage: (code?: string) => code is LanguageOf<T>;
|
|
59
|
+
translate: {
|
|
60
|
+
(language: LanguageOf<T>, key: KeyOf<T, Base>, params?: Record<string, unknown>): string;
|
|
61
|
+
(language: LanguageOf<T>, text: TranslatableText<KeyOf<T, Base>>): string;
|
|
62
|
+
(language: LanguageOf<T>, keyOrText: KeyOf<T, Base> | TranslatableText<KeyOf<T, Base>>, params?: Record<string, unknown>): string;
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export { type Dictionaries, type DictionaryKey, type DictionaryLanguage, type KeyOf, type LanguageOf, type LocalizationConfig, type TranslatableText, type Translator, createDictionary };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// src/createDictionary.ts
|
|
2
|
+
function createDictionary(config) {
|
|
3
|
+
const dictionaries = config.translations;
|
|
4
|
+
const base = config.base;
|
|
5
|
+
const keys = Object.fromEntries(
|
|
6
|
+
Object.keys(dictionaries[base]).map((key) => [key, key])
|
|
7
|
+
);
|
|
8
|
+
const isText = (value) => value instanceof Object && ("key" in value || "params" in value);
|
|
9
|
+
const textIn = (text, language) => "key" in text ? keyIn(text.key, language, text.params) : text.params.text;
|
|
10
|
+
const keyIn = (key, language, params = {}) => {
|
|
11
|
+
let text = dictionaries[language][key];
|
|
12
|
+
for (const [name, value] of Object.entries(params)) {
|
|
13
|
+
const filling = isText(value) ? textIn(value, language) : String(value);
|
|
14
|
+
text = text.replaceAll(`{${name}}`, filling);
|
|
15
|
+
}
|
|
16
|
+
return text;
|
|
17
|
+
};
|
|
18
|
+
function translate(language, keyOrText, params = {}) {
|
|
19
|
+
return isText(keyOrText) ? textIn(keyOrText, language) : keyIn(keyOrText, language, params);
|
|
20
|
+
}
|
|
21
|
+
const isLanguage = (code) => code !== void 0 && Object.hasOwn(dictionaries, code);
|
|
22
|
+
return { base, keys, isLanguage, translate };
|
|
23
|
+
}
|
|
24
|
+
export {
|
|
25
|
+
createDictionary
|
|
26
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,63 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@magicdoor/magic-localization",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Type-checked translations from string enums, for any framework.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./package.json": "./package.json"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsup",
|
|
22
|
+
"test": "vitest run",
|
|
23
|
+
"coverage": "vitest run --coverage",
|
|
24
|
+
"lint": "eslint src test",
|
|
25
|
+
"check-package": "attw --pack . --ignore-rules cjs-resolves-to-esm && publint --strict",
|
|
26
|
+
"type-check": "tsc --project typecheckconfig.json",
|
|
27
|
+
"changeset": "changeset",
|
|
28
|
+
"release": "npm run build && NPM_CONFIG_PROVENANCE=false changeset publish",
|
|
29
|
+
"format": "prettier --write src test",
|
|
30
|
+
"format-check": "prettier --check src test",
|
|
31
|
+
"prepack": "npm run build"
|
|
32
|
+
},
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=20"
|
|
35
|
+
},
|
|
36
|
+
"keywords": [
|
|
37
|
+
"localization",
|
|
38
|
+
"i18n",
|
|
39
|
+
"translation",
|
|
40
|
+
"typescript"
|
|
41
|
+
],
|
|
42
|
+
"author": "Norbert Nemes",
|
|
43
|
+
"license": "Apache-2.0",
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
49
|
+
"@changesets/cli": "^2.31.1",
|
|
50
|
+
"@eslint/js": "^9.39.5",
|
|
51
|
+
"@vitest/coverage-v8": "^2.1.9",
|
|
52
|
+
"eslint": "^9.39.5",
|
|
53
|
+
"eslint-config-prettier": "^10.1.8",
|
|
54
|
+
"eslint-plugin-prettier": "^5.5.7",
|
|
55
|
+
"eslint-plugin-unused-imports": "^4.4.1",
|
|
56
|
+
"prettier": "^3.9.10",
|
|
57
|
+
"publint": "^0.3.25",
|
|
58
|
+
"tsup": "^8.5.1",
|
|
59
|
+
"typescript": "^5.9.3",
|
|
60
|
+
"typescript-eslint": "^8.72.1",
|
|
61
|
+
"vitest": "^2.1.9"
|
|
62
|
+
}
|
|
63
|
+
}
|