@burojs/i18n-core 0.2.0 → 0.5.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/README.md +38 -6
- package/dist/index.cjs +245 -215
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +215 -150
- package/dist/index.d.ts +215 -150
- package/dist/index.js +221 -209
- package/dist/index.js.map +1 -1
- package/package.json +5 -6
package/dist/index.js
CHANGED
|
@@ -1,229 +1,241 @@
|
|
|
1
|
-
import i18next from
|
|
2
|
-
|
|
3
|
-
// src/lookup.ts
|
|
1
|
+
import i18next from "i18next";
|
|
2
|
+
//#region src/lookup.ts
|
|
4
3
|
function resolveKey(key, resource) {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
candidates.push(`resources._.${key}`);
|
|
14
|
-
candidates.push(`common.${key}`);
|
|
15
|
-
candidates.push(key);
|
|
16
|
-
return candidates;
|
|
4
|
+
if (!key) return [];
|
|
5
|
+
if (key.startsWith("resources.") || key.startsWith("enums.") || key.startsWith("common.") || key.startsWith("blocks.")) return [key];
|
|
6
|
+
const candidates = [];
|
|
7
|
+
if (resource) candidates.push(`resources.${resource}.${key}`);
|
|
8
|
+
candidates.push(`resources._.${key}`);
|
|
9
|
+
candidates.push(`common.${key}`);
|
|
10
|
+
candidates.push(key);
|
|
11
|
+
return candidates;
|
|
17
12
|
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/i18next-adapter.ts
|
|
15
|
+
const MISSING = "\0";
|
|
18
16
|
async function createI18nextAdapter(config) {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
17
|
+
const instance = i18next.createInstance();
|
|
18
|
+
await instance.init({
|
|
19
|
+
lng: config.defaultLocale,
|
|
20
|
+
fallbackLng: config.fallbackLocale ?? config.defaultLocale,
|
|
21
|
+
supportedLngs: config.locales,
|
|
22
|
+
resources: config.resources,
|
|
23
|
+
keySeparator: config.keySeparator ?? ".",
|
|
24
|
+
nsSeparator: config.nsSeparator ?? false,
|
|
25
|
+
defaultNS: "common",
|
|
26
|
+
interpolation: { escapeValue: false },
|
|
27
|
+
returnNull: false,
|
|
28
|
+
returnEmptyString: false
|
|
29
|
+
});
|
|
30
|
+
return {
|
|
31
|
+
t(key, params) {
|
|
32
|
+
const dotIdx = key.indexOf(".");
|
|
33
|
+
if (dotIdx === -1) return instance.t(key, params);
|
|
34
|
+
const ns = key.substring(0, dotIdx);
|
|
35
|
+
const subKey = key.substring(dotIdx + 1);
|
|
36
|
+
const result = instance.t(subKey, {
|
|
37
|
+
ns,
|
|
38
|
+
...params ?? {}
|
|
39
|
+
});
|
|
40
|
+
const count = typeof params?.count === "number" ? params.count : void 0;
|
|
41
|
+
if (result === subKey && !instance.exists(subKey, count === void 0 ? { ns } : {
|
|
42
|
+
ns,
|
|
43
|
+
count
|
|
44
|
+
})) return key;
|
|
45
|
+
return result;
|
|
46
|
+
},
|
|
47
|
+
async changeLocale(locale) {
|
|
48
|
+
await instance.changeLanguage(locale);
|
|
49
|
+
},
|
|
50
|
+
async loadNamespace(namespace, _locale) {
|
|
51
|
+
await instance.loadNamespaces(namespace);
|
|
52
|
+
},
|
|
53
|
+
getCurrentLocale() {
|
|
54
|
+
return instance.language;
|
|
55
|
+
},
|
|
56
|
+
onLocaleChange(cb) {
|
|
57
|
+
instance.on("languageChanged", cb);
|
|
58
|
+
return () => instance.off("languageChanged", cb);
|
|
59
|
+
},
|
|
60
|
+
hasKey(key, options) {
|
|
61
|
+
const dotIdx = key.indexOf(".");
|
|
62
|
+
const ns = dotIdx === -1 ? void 0 : key.substring(0, dotIdx);
|
|
63
|
+
const subKey = dotIdx === -1 ? key : key.substring(dotIdx + 1);
|
|
64
|
+
const lookup = {
|
|
65
|
+
...ns === void 0 ? {} : { ns },
|
|
66
|
+
...options?.count === void 0 ? {} : { count: options.count }
|
|
67
|
+
};
|
|
68
|
+
const value = instance.t(subKey, {
|
|
69
|
+
...lookup,
|
|
70
|
+
returnObjects: true,
|
|
71
|
+
defaultValue: MISSING
|
|
72
|
+
});
|
|
73
|
+
return value !== MISSING && (typeof value !== "object" || value === null);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
72
76
|
}
|
|
73
|
-
|
|
74
|
-
|
|
77
|
+
//#endregion
|
|
78
|
+
//#region src/i18n.ts
|
|
75
79
|
function createI18n(config) {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
adapter
|
|
109
|
-
};
|
|
80
|
+
const { adapter, warnOnMissing = true, locales } = config;
|
|
81
|
+
return {
|
|
82
|
+
t(key, options) {
|
|
83
|
+
const count = options?.count;
|
|
84
|
+
const params = count === void 0 ? options?.params : {
|
|
85
|
+
...options?.params,
|
|
86
|
+
count
|
|
87
|
+
};
|
|
88
|
+
const candidates = resolveKey(key, options?.resource);
|
|
89
|
+
for (const candidate of candidates) if (count === void 0 ? adapter.hasKey(candidate) : adapter.hasKey(candidate, { count })) return adapter.t(candidate, params);
|
|
90
|
+
if (warnOnMissing && typeof console !== "undefined") console.warn(`[@burojs/i18n-core] Missing translation: '${key}'${options?.resource ? ` (resource: ${options.resource})` : ""}`);
|
|
91
|
+
return key;
|
|
92
|
+
},
|
|
93
|
+
has(key, options) {
|
|
94
|
+
const count = options?.count;
|
|
95
|
+
return resolveKey(key, options?.resource).some((candidate) => count === void 0 ? adapter.hasKey(candidate) : adapter.hasKey(candidate, { count }));
|
|
96
|
+
},
|
|
97
|
+
async changeLocale(locale) {
|
|
98
|
+
await adapter.changeLocale(locale);
|
|
99
|
+
},
|
|
100
|
+
getCurrentLocale() {
|
|
101
|
+
return adapter.getCurrentLocale();
|
|
102
|
+
},
|
|
103
|
+
onLocaleChange(cb) {
|
|
104
|
+
return adapter.onLocaleChange?.(cb) ?? (() => {});
|
|
105
|
+
},
|
|
106
|
+
async loadNamespace(namespace, locale) {
|
|
107
|
+
await adapter.loadNamespace(namespace, locale);
|
|
108
|
+
},
|
|
109
|
+
...locales === void 0 ? {} : { locales },
|
|
110
|
+
adapter
|
|
111
|
+
};
|
|
110
112
|
}
|
|
111
|
-
|
|
112
|
-
|
|
113
|
+
//#endregion
|
|
114
|
+
//#region src/resource-context.ts
|
|
113
115
|
function createResourceI18n(i18n, resource) {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
116
|
+
return {
|
|
117
|
+
t(key, options) {
|
|
118
|
+
return i18n.t(key, {
|
|
119
|
+
resource: options?.resource ?? resource,
|
|
120
|
+
params: options?.params,
|
|
121
|
+
...options?.count === void 0 ? {} : { count: options.count }
|
|
122
|
+
});
|
|
123
|
+
},
|
|
124
|
+
changeLocale: i18n.changeLocale,
|
|
125
|
+
getCurrentLocale: i18n.getCurrentLocale,
|
|
126
|
+
resource
|
|
127
|
+
};
|
|
125
128
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
+
//#endregion
|
|
130
|
+
//#region src/locale-registry.ts
|
|
131
|
+
const DEFAULT_NAMESPACE = "common";
|
|
129
132
|
function isPlainObject(value) {
|
|
130
|
-
|
|
133
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
131
134
|
}
|
|
132
135
|
function mergeBundle(base, overlay) {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
136
|
+
const out = { ...base };
|
|
137
|
+
for (const [key, overlayValue] of Object.entries(overlay)) {
|
|
138
|
+
const baseValue = out[key];
|
|
139
|
+
out[key] = isPlainObject(baseValue) && isPlainObject(overlayValue) ? mergeBundle(baseValue, overlayValue) : overlayValue;
|
|
140
|
+
}
|
|
141
|
+
return out;
|
|
139
142
|
}
|
|
140
|
-
function createLocaleRegistry() {
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
143
|
+
function createLocaleRegistry(options) {
|
|
144
|
+
const primary = options?.primary;
|
|
145
|
+
if (typeof primary !== "string" || primary === "") throw new TypeError(`createLocaleRegistry needs { primary }, the locale whose text is the default in code; received ${JSON.stringify(primary)}.`);
|
|
146
|
+
const registered = [];
|
|
147
|
+
return {
|
|
148
|
+
primary() {
|
|
149
|
+
return primary;
|
|
150
|
+
},
|
|
151
|
+
register(contribution) {
|
|
152
|
+
registered.push(contribution);
|
|
153
|
+
},
|
|
154
|
+
locales() {
|
|
155
|
+
return Array.from(new Set(registered.map((c) => c.locale))).sort();
|
|
156
|
+
},
|
|
157
|
+
namespaces() {
|
|
158
|
+
return Array.from(new Set(registered.map((c) => c.namespace ?? DEFAULT_NAMESPACE))).sort();
|
|
159
|
+
},
|
|
160
|
+
contributions() {
|
|
161
|
+
return registered;
|
|
162
|
+
},
|
|
163
|
+
buildResources() {
|
|
164
|
+
if (!registered.some((c) => c.locale === primary)) {
|
|
165
|
+
const known = Array.from(new Set(registered.map((c) => c.locale))).sort();
|
|
166
|
+
throw new Error(`The locale registry's primary locale ${JSON.stringify(primary)} has no contribution (registered: ${known.length === 0 ? "none" : known.join(", ")}). Register its bundle, an empty one if the app has no strings of its own, or declare the primary it does register.`);
|
|
167
|
+
}
|
|
168
|
+
const byLocale = new Map();
|
|
169
|
+
for (const contribution of registered) {
|
|
170
|
+
const namespace = contribution.namespace ?? DEFAULT_NAMESPACE;
|
|
171
|
+
let byNamespace = byLocale.get(contribution.locale);
|
|
172
|
+
if (!byNamespace) {
|
|
173
|
+
byNamespace = new Map();
|
|
174
|
+
byLocale.set(contribution.locale, byNamespace);
|
|
175
|
+
}
|
|
176
|
+
const group = byNamespace.get(namespace);
|
|
177
|
+
if (group) group.push(contribution);
|
|
178
|
+
else byNamespace.set(namespace, [contribution]);
|
|
179
|
+
}
|
|
180
|
+
const resources = {};
|
|
181
|
+
for (const [locale, byNamespace] of byLocale) {
|
|
182
|
+
const namespaces = {};
|
|
183
|
+
for (const [namespace, group] of byNamespace) {
|
|
184
|
+
const ordered = [...group].sort((a, b) => a.priority - b.priority);
|
|
185
|
+
let merged = {};
|
|
186
|
+
for (const contribution of ordered) merged = mergeBundle(merged, contribution.bundle);
|
|
187
|
+
namespaces[namespace] = merged;
|
|
188
|
+
}
|
|
189
|
+
resources[locale] = namespaces;
|
|
190
|
+
}
|
|
191
|
+
return resources;
|
|
192
|
+
}
|
|
193
|
+
};
|
|
187
194
|
}
|
|
188
|
-
|
|
195
|
+
const DEFAULT_LOCALE_PATTERN = /(?:^|\/)([A-Za-z0-9-]+)\.(?:ts|tsx|js|jsx|mjs|cjs)$/;
|
|
189
196
|
function defaultLocaleOf(path) {
|
|
190
|
-
|
|
197
|
+
return DEFAULT_LOCALE_PATTERN.exec(path)?.[1];
|
|
191
198
|
}
|
|
192
199
|
function localeContributionsFromGlob(glob, options) {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
200
|
+
const localeOf = options.localeOf ?? defaultLocaleOf;
|
|
201
|
+
const out = [];
|
|
202
|
+
for (const [path, mod] of Object.entries(glob)) {
|
|
203
|
+
const locale = localeOf(path);
|
|
204
|
+
if (locale === void 0) continue;
|
|
205
|
+
const bundle = isPlainObject(mod.default) ? mod.default : mod;
|
|
206
|
+
out.push({
|
|
207
|
+
locale,
|
|
208
|
+
priority: options.priority,
|
|
209
|
+
source: options.source,
|
|
210
|
+
bundle,
|
|
211
|
+
...options.namespace !== void 0 ? { namespace: options.namespace } : {}
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return out;
|
|
208
215
|
}
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
async function createI18nFromRegistry(registry, config) {
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
216
|
+
//#endregion
|
|
217
|
+
//#region src/create-i18n-from-registry.ts
|
|
218
|
+
async function createI18nFromRegistry(registry, config = {}) {
|
|
219
|
+
const resources = registry.buildResources();
|
|
220
|
+
const primary = registry.primary();
|
|
221
|
+
return createI18n({
|
|
222
|
+
adapter: await createI18nextAdapter({
|
|
223
|
+
defaultLocale: config.defaultLocale ?? primary,
|
|
224
|
+
locales: registry.locales(),
|
|
225
|
+
resources,
|
|
226
|
+
fallbackLocale: config.fallbackLocale ?? primary,
|
|
227
|
+
...config.keySeparator !== void 0 ? { keySeparator: config.keySeparator } : {},
|
|
228
|
+
...config.nsSeparator !== void 0 ? { nsSeparator: config.nsSeparator } : {}
|
|
229
|
+
}),
|
|
230
|
+
warnOnMissing: config.warnOnMissing,
|
|
231
|
+
locales: () => registry.locales()
|
|
232
|
+
});
|
|
221
233
|
}
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
234
|
+
//#endregion
|
|
235
|
+
//#region src/index.ts
|
|
236
|
+
const PACKAGE_NAME = "@burojs/i18n-core";
|
|
237
|
+
const PACKAGE_VERSION = "0.0.0";
|
|
238
|
+
//#endregion
|
|
227
239
|
export { PACKAGE_NAME, PACKAGE_VERSION, createI18n, createI18nFromRegistry, createI18nextAdapter, createLocaleRegistry, createResourceI18n, localeContributionsFromGlob, resolveKey };
|
|
228
|
-
|
|
240
|
+
|
|
229
241
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lookup.ts","../src/i18next-adapter.ts","../src/i18n.ts","../src/resource-context.ts","../src/locale-registry.ts","../src/create-i18n-from-registry.ts","../src/index.ts"],"names":[],"mappings":";;;AAYO,SAAS,UAAA,CAAW,KAAa,QAAA,EAA6B;AACnE,EAAA,IAAI,CAAC,GAAA,EAAK,OAAO,EAAC;AAIlB,EAAA,IAAI,GAAA,CAAI,UAAA,CAAW,YAAY,CAAA,IAAK,GAAA,CAAI,UAAA,CAAW,QAAQ,CAAA,IAAK,GAAA,CAAI,UAAA,CAAW,SAAS,CAAA,EAAG;AACzF,IAAA,OAAO,CAAC,GAAG,CAAA;AAAA,EACb;AAEA,EAAA,MAAM,aAAuB,EAAC;AAC9B,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,UAAA,CAAW,IAAA,CAAK,CAAA,UAAA,EAAa,QAAQ,CAAA,CAAA,EAAI,GAAG,CAAA,CAAE,CAAA;AAAA,EAChD;AACA,EAAA,UAAA,CAAW,IAAA,CAAK,CAAA,YAAA,EAAe,GAAG,CAAA,CAAE,CAAA;AACpC,EAAA,UAAA,CAAW,IAAA,CAAK,CAAA,OAAA,EAAU,GAAG,CAAA,CAAE,CAAA;AAC/B,EAAA,UAAA,CAAW,KAAK,GAAG,CAAA;AACnB,EAAA,OAAO,UAAA;AACT;ACJA,eAAsB,qBAAqB,MAAA,EAAoD;AAC7F,EAAA,MAAM,QAAA,GAAiB,QAAQ,cAAA,EAAe;AAE9C,EAAA,MAAM,SAAS,IAAA,CAAK;AAAA,IAClB,KAAK,MAAA,CAAO,aAAA;AAAA,IACZ,WAAA,EAAa,MAAA,CAAO,cAAA,IAAkB,MAAA,CAAO,aAAA;AAAA,IAC7C,eAAe,MAAA,CAAO,OAAA;AAAA,IACtB,WAAW,MAAA,CAAO,SAAA;AAAA,IAClB,YAAA,EAAc,OAAO,YAAA,IAAgB,GAAA;AAAA;AAAA;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M,OAAA,GAAU,MAAM,oBAAA,CAAqB;AAAA,IACzC,eAAe,MAAA,CAAO,aAAA;AAAA,IACtB,OAAA,EAAS,SAAS,OAAA,EAAQ;AAAA,IAC1B,SAAA,EAAW,SAAS,cAAA,EAAe;AAAA,IACnC,GAAI,OAAO,cAAA,KAAmB,MAAA,GAAY,EAAE,cAAA,EAAgB,MAAA,CAAO,cAAA,EAAe,GAAI,EAAC;AAAA,IACvF,GAAI,OAAO,YAAA,KAAiB,MAAA,GAAY,EAAE,YAAA,EAAc,MAAA,CAAO,YAAA,EAAa,GAAI,EAAC;AAAA,IACjF,GAAI,OAAO,WAAA,KAAgB,MAAA,GAAY,EAAE,WAAA,EAAa,MAAA,CAAO,WAAA,EAAY,GAAI;AAAC,GAC/E,CAAA;AACD,EAAA,OAAO,WAAW,EAAE,OAAA,EAAS,aAAA,EAAe,MAAA,CAAO,eAAe,CAAA;AACpE;;;AC/BO,IAAM,YAAA,GAAe;AACrB,IAAM,eAAA,GAAkB","file":"index.js","sourcesContent":["/**\n * Build candidate keys for fallback lookup.\n *\n * Lookup order (first match wins):\n * 1. resources.<name>.<key> — resource-specific\n * 2. resources._.<key> — base for all resources\n * 3. common.<key> — global common\n * 4. <key> — raw fallback (debug only)\n *\n * If `key` is already namespaced (starts with `resources.`, `enums.` or\n * `common.`), return it as-is without further scoping.\n */\nexport function resolveKey(key: string, resource?: string): string[] {\n if (!key) return [];\n\n // Already namespaced — return as-is. `enums.` is a first-class top-level\n // namespace (global enum labels), like `resources.` and `common.`.\n if (key.startsWith('resources.') || key.startsWith('enums.') || key.startsWith('common.')) {\n return [key];\n }\n\n const candidates: string[] = [];\n if (resource) {\n candidates.push(`resources.${resource}.${key}`);\n }\n candidates.push(`resources._.${key}`);\n candidates.push(`common.${key}`);\n candidates.push(key); // raw fallback for warnings\n return candidates;\n}\n","import i18next, { type FallbackLng, type i18n } from 'i18next';\nimport type { I18nAdapter, TranslationBundle } from './types/index.js';\n\nexport interface I18nextAdapterConfig {\n defaultLocale: string;\n locales: string[];\n resources?: Record<string, Record<string, TranslationBundle>>;\n /**\n * A single fallback locale (`'en'`) applies uniformly to every locale. A\n * `fr → en` fallback for one locale but not another needs i18next's own\n * per-locale chain shape instead — `{ fr: ['en'], default: ['en'] }` — so\n * this accepts i18next's full `FallbackLng` type rather than just `string`.\n * The chain is entirely CONFIG: nothing in this adapter special-cases any\n * particular locale code, here or anywhere else.\n */\n fallbackLocale?: FallbackLng;\n keySeparator?: string | false;\n nsSeparator?: string | false;\n}\n\n/**\n * Default I18nAdapter implementation backed by i18next.\n * Each top-level key in resources becomes a separate i18next namespace\n * (e.g. 'common', 'resources').\n */\nexport async function createI18nextAdapter(config: I18nextAdapterConfig): Promise<I18nAdapter> {\n const instance: i18n = i18next.createInstance();\n\n await instance.init({\n lng: config.defaultLocale,\n fallbackLng: config.fallbackLocale ?? config.defaultLocale,\n supportedLngs: config.locales,\n resources: config.resources,\n keySeparator: config.keySeparator ?? '.',\n // Qualified Buro entity refs use `namespace:id`. Resource keys flow\n // through `resources.<ref>.<key>`, so treating ':' as i18next's namespace\n // separator would split a valid ref before our explicit `ns` routing gets\n // to resolve it.\n nsSeparator: config.nsSeparator ?? false,\n defaultNS: 'common',\n interpolation: { escapeValue: false },\n returnNull: false,\n });\n\n return {\n t(key, params) {\n const dotIdx = key.indexOf('.');\n if (dotIdx === -1) {\n return instance.t(key, params) as string;\n }\n const ns = key.substring(0, dotIdx);\n const subKey = key.substring(dotIdx + 1);\n const result = instance.t(subKey, { ns, ...(params ?? {}) }) as string;\n // i18next returns the bare subKey when missing — restore the full key as fallback\n if (result === subKey && !instance.exists(subKey, { ns })) {\n return key;\n }\n return result;\n },\n async changeLocale(locale) {\n await instance.changeLanguage(locale);\n },\n async loadNamespace(namespace, _locale) {\n await instance.loadNamespaces(namespace);\n },\n getCurrentLocale() {\n return instance.language;\n },\n onLocaleChange(cb) {\n instance.on('languageChanged', cb);\n return () => instance.off('languageChanged', cb);\n },\n hasKey(key) {\n const dotIdx = key.indexOf('.');\n const ns = dotIdx === -1 ? undefined : key.substring(0, dotIdx);\n const subKey = dotIdx === -1 ? key : key.substring(dotIdx + 1);\n const opts = ns === undefined ? undefined : { ns };\n if (!instance.exists(subKey, opts)) return false;\n /*\n `exists()` alone is not enough, and the gap is the root cause of a whole\n family of bugs rather than a curiosity.\n\n i18next answers `exists()` with TRUE for an OBJECT node — `fields.gtin`\n once that entry is promoted from a plain string to `{ label, doc }`,\n `enums.<ns>.<value>` when it carries a `doc` but no `label`, and so on.\n `t()` on such a node neither throws nor returns the key: it returns the\n literal sentence\n\n key '…' returned an object instead of string.\n\n Since `resolveContentSlot` commits to the FIRST key whose `has()` is\n true, every resolver built on it — field labels, enum labels, nav\n labels, tab captions — would render that sentence to the user. No crash,\n no warning, just wrong text on screen. It was found three separate times\n in three separate resolvers before being fixed here, once.\n\n So `has` now means what its callers always assumed: there is a USABLE\n STRING at this key. Non-object primitives stay truthy, leaving plural\n forms and numeric values behaving exactly as before.\n */\n const value = instance.t(subKey, { ...(opts ?? {}), returnObjects: true }) as unknown;\n return typeof value !== 'object' || value === null;\n },\n };\n}\n","import { resolveKey } from './lookup.js';\nimport type { I18nAdapter } from './types/index.js';\n\nexport interface I18nFacade {\n t: (key: string, options?: { resource?: string; params?: Record<string, unknown> }) => string;\n /**\n * True when a translation for `key` EXISTS (through the same candidate chain\n * as {@link I18nFacade.t}). Distinct from `t`, which returns the raw key on a\n * miss — the content model probes presence with `has` to tell \"no bundle\n * entry\" (render nothing) from \"bundle entry === key text\".\n */\n has: (key: string, options?: { resource?: string }) => boolean;\n changeLocale: (locale: string) => Promise<void>;\n getCurrentLocale: () => string;\n /**\n * Subscribe to active-locale changes. Returns an unsubscribe fn. When the\n * adapter can't notify, this is a no-op subscription (returns an unsubscribe\n * that does nothing) — the live language switch then falls back to a static\n * read. Consumed by `useLocale()` via `useSyncExternalStore`.\n */\n onLocaleChange: (cb: () => void) => () => void;\n loadNamespace: (namespace: string, locale: string) => Promise<void>;\n adapter: I18nAdapter;\n}\n\nexport interface CreateI18nConfig {\n adapter: I18nAdapter;\n warnOnMissing?: boolean;\n}\n\nexport function createI18n(config: CreateI18nConfig): I18nFacade {\n const { adapter, warnOnMissing = true } = config;\n\n return {\n t(key, options) {\n const candidates = resolveKey(key, options?.resource);\n for (const candidate of candidates) {\n if (adapter.hasKey(candidate)) {\n return adapter.t(candidate, options?.params);\n }\n }\n if (warnOnMissing && typeof console !== 'undefined') {\n console.warn(\n `[@burojs/i18n-core] Missing translation: '${key}'${options?.resource ? ` (resource: ${options.resource})` : ''}`,\n );\n }\n return key;\n },\n has(key, options) {\n return resolveKey(key, options?.resource).some((candidate) => adapter.hasKey(candidate));\n },\n async changeLocale(locale) {\n await adapter.changeLocale(locale);\n },\n getCurrentLocale() {\n return adapter.getCurrentLocale();\n },\n onLocaleChange(cb) {\n return adapter.onLocaleChange?.(cb) ?? (() => {});\n },\n async loadNamespace(namespace, locale) {\n await adapter.loadNamespace(namespace, locale);\n },\n adapter,\n };\n}\n","import type { I18nFacade } from './i18n.js';\n\nexport interface ResourceI18n {\n t: (key: string, options?: { resource?: string; params?: Record<string, unknown> }) => string;\n changeLocale: (locale: string) => Promise<void>;\n getCurrentLocale: () => string;\n resource: string;\n}\n\n/**\n * Wraps an I18nFacade with a default resource scope.\n * `t('actions.delete')` will lookup `resources.<resource>.actions.delete` first.\n * Pass an explicit `resource` option to override the default scope.\n */\nexport function createResourceI18n(i18n: I18nFacade, resource: string): ResourceI18n {\n return {\n t(key, options) {\n return i18n.t(key, {\n resource: options?.resource ?? resource,\n params: options?.params,\n });\n },\n changeLocale: i18n.changeLocale,\n getCurrentLocale: i18n.getCurrentLocale,\n resource,\n };\n}\n","import type { TranslationBundle } from './types/bundle.js';\n\n/**\n * One package/app/domain module's offering for one locale.\n *\n * A contribution is data, not code: nothing about `createI18nextAdapter`'s\n * `resources` shape is visible here, and nothing here names a fixed set of\n * locale codes or counts them. `locale` is whatever the file/module that\n * produced this contribution says it is — the registry never validates it\n * against a known list, because there is no known list. That is the whole\n * point: a twenty-first language is a twenty-first contribution, not a\n * twenty-first `case`.\n */\nexport interface LocaleContribution {\n /** Locale code this contribution provides strings for (e.g. 'en', 'es', 'fr'). */\n locale: string;\n /**\n * i18next namespace the bundle merges into. Defaults to `'common'` — the\n * same default namespace `createI18nextAdapter` uses.\n */\n namespace?: string;\n /**\n * Declared merge priority. On a key collision within the same\n * (locale, namespace), the contribution with the HIGHER priority wins —\n * not whichever happened to register last. Ties fall back to registration\n * order (last registered wins), which is why two genuinely competing\n * sources must declare distinct priorities rather than relying on the tie\n * break.\n */\n priority: number;\n /**\n * Where this contribution came from — a package name, `'app'`, an enum\n * module name. Diagnostic only (surfaced by {@link LocaleRegistry.contributions}\n * for debugging a collision); never branched on.\n */\n source: string;\n bundle: TranslationBundle;\n}\n\nexport interface LocaleRegistry {\n /** Add one contribution. Order of registration does not matter for the merge result — only `priority` does (see {@link LocaleContribution.priority}). */\n register(contribution: LocaleContribution): void;\n /**\n * Every locale code that has at least one contribution, sorted. Derived\n * purely from what was registered — nothing enumerates or counts locales\n * anywhere else in this module.\n */\n locales(): string[];\n /** Every namespace that has at least one contribution, sorted. */\n namespaces(): string[];\n /** All registered contributions, in registration order. For diagnostics/tests. */\n contributions(): readonly LocaleContribution[];\n /**\n * Assemble `{ [locale]: { [namespace]: TranslationBundle } }`, ready to\n * pass straight as `createI18nextAdapter`'s `resources` config. Within one\n * (locale, namespace) group, contributions are deep-merged in ascending\n * priority order, so a higher-priority contribution's leaves win over a\n * lower-priority one's on any overlapping key while leaving the rest of\n * the lower-priority bundle intact.\n */\n buildResources(): Record<string, Record<string, TranslationBundle>>;\n}\n\nconst DEFAULT_NAMESPACE = 'common';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Recursively merge `overlay` onto `base`. Arrays and primitives are replaced\n * wholesale (a `TranslationBundle` array leaf — see that type's own comment\n * on why arrays are a real leaf shape — is not index-merged: the whole array\n * is the unit an overlay replaces). Plain objects merge key by key.\n */\nfunction mergeBundle(base: TranslationBundle, overlay: TranslationBundle): TranslationBundle {\n const out: Record<string, unknown> = { ...base };\n for (const [key, overlayValue] of Object.entries(overlay)) {\n const baseValue = out[key];\n out[key] =\n isPlainObject(baseValue) && isPlainObject(overlayValue)\n ? mergeBundle(baseValue as TranslationBundle, overlayValue as TranslationBundle)\n : overlayValue;\n }\n return out as TranslationBundle;\n}\n\nexport function createLocaleRegistry(): LocaleRegistry {\n const registered: LocaleContribution[] = [];\n\n return {\n register(contribution) {\n registered.push(contribution);\n },\n locales() {\n return Array.from(new Set(registered.map((c) => c.locale))).sort();\n },\n namespaces() {\n return Array.from(new Set(registered.map((c) => c.namespace ?? DEFAULT_NAMESPACE))).sort();\n },\n contributions() {\n return registered;\n },\n buildResources() {\n // Group by (locale, namespace) via NESTED maps rather than a\n // delimiter-joined composite string key. A locale or namespace code is\n // caller-supplied and unconstrained (see `LocaleContribution.locale`'s\n // own comment), so any single-character delimiter is a value that\n // *could* collide with real content; nested `Map`s need no delimiter\n // at all, so there is nothing to collide with and nothing unusual\n // embedded in this file's source for a diff tool to trip over.\n const byLocale = new Map<string, Map<string, LocaleContribution[]>>();\n for (const contribution of registered) {\n const namespace = contribution.namespace ?? DEFAULT_NAMESPACE;\n let byNamespace = byLocale.get(contribution.locale);\n if (!byNamespace) {\n byNamespace = new Map<string, LocaleContribution[]>();\n byLocale.set(contribution.locale, byNamespace);\n }\n const group = byNamespace.get(namespace);\n if (group) {\n group.push(contribution);\n } else {\n byNamespace.set(namespace, [contribution]);\n }\n }\n\n const resources: Record<string, Record<string, TranslationBundle>> = {};\n for (const [locale, byNamespace] of byLocale) {\n const namespaces: Record<string, TranslationBundle> = {};\n for (const [namespace, group] of byNamespace) {\n // Stable sort ascending by priority: lower priority applied first,\n // higher priority applied last so it wins the overlapping leaves.\n // `Array#sort` is stable per spec (ES2019+), so contributions with\n // equal priority keep their registration order — last-registered\n // wins ONLY within a tie, never across a declared priority gap.\n const ordered = [...group].sort((a, b) => a.priority - b.priority);\n let merged: TranslationBundle = {};\n for (const contribution of ordered) {\n merged = mergeBundle(merged, contribution.bundle);\n }\n namespaces[namespace] = merged;\n }\n resources[locale] = namespaces;\n }\n return resources;\n },\n };\n}\n\n/**\n * A bundler-produced glob module, as `import.meta.glob` (Vite) or an\n * equivalent walk over `require.context` (webpack) would yield it: a flat\n * map of path → either the loaded module itself or `{ default }`.\n *\n * Bundler-agnostic on purpose, same reasoning as `@burojs/core`'s\n * `docsFromGlob`: no bundler-agnostic glob primitive exists, and a published\n * package must not require one — the ADOPTER calls `import.meta.glob` (or\n * whatever their bundler offers) and hands the plain object here.\n */\nexport type LocaleGlobModule = TranslationBundle | { default: TranslationBundle };\n\nexport interface LocaleContributionsFromGlobOptions {\n /** {@link LocaleContribution.source} for every contribution produced. */\n source: string;\n /** {@link LocaleContribution.priority} for every contribution produced. */\n priority: number;\n /** {@link LocaleContribution.namespace}. Defaults to `'common'`. */\n namespace?: string;\n /**\n * Extracts the locale code from a glob path. Default matches a bare\n * `<locale>.ts`/`<locale>.tsx`/`<locale>.js` filename (`'./locales/en.ts'`\n * → `'en'`, `'./locales/fr-CA.ts'` → `'fr-CA'`) — no restriction to a\n * known set of codes; whatever the filename says IS the locale code. Paths\n * that don't match are skipped rather than guessed at (same discipline as\n * `docsFromGlob`).\n */\n localeOf?: (path: string) => string | undefined;\n}\n\nconst DEFAULT_LOCALE_PATTERN = /(?:^|\\/)([A-Za-z0-9-]+)\\.(?:ts|tsx|js|jsx|mjs|cjs)$/;\n\nfunction defaultLocaleOf(path: string): string | undefined {\n return DEFAULT_LOCALE_PATTERN.exec(path)?.[1];\n}\n\n/**\n * Normalize a bundler glob of per-locale files into {@link LocaleContribution}s.\n * One file → one locale → one contribution. Nothing here enumerates or counts\n * locale codes: whatever files are present in the globbed directory at build\n * time ARE the contributions produced — dropping in a new file is the entire\n * mechanism for adding a language.\n */\nexport function localeContributionsFromGlob(\n glob: Record<string, LocaleGlobModule>,\n options: LocaleContributionsFromGlobOptions,\n): LocaleContribution[] {\n const localeOf = options.localeOf ?? defaultLocaleOf;\n const out: LocaleContribution[] = [];\n for (const [path, mod] of Object.entries(glob)) {\n const locale = localeOf(path);\n if (locale === undefined) continue;\n // Eager `import.meta.glob` yields a module namespace object — always\n // `{ default, ...named exports }` for a file that does `export default\n // {...}`. Unwrap it when present; otherwise trust the glob already\n // handed a bare bundle (e.g. a caller that pre-unwrapped, or a\n // require.context-style walk that returns exports directly).\n const bundle = isPlainObject((mod as { default?: unknown }).default)\n ? (mod as { default: TranslationBundle }).default\n : (mod as TranslationBundle);\n out.push({\n locale,\n priority: options.priority,\n source: options.source,\n bundle,\n ...(options.namespace !== undefined ? { namespace: options.namespace } : {}),\n });\n }\n return out;\n}\n","import { type I18nFacade, createI18n } from './i18n.js';\nimport { type I18nextAdapterConfig, createI18nextAdapter } from './i18next-adapter.js';\nimport type { LocaleRegistry } from './locale-registry.js';\n\nexport type CreateI18nFromRegistryConfig = Pick<\n I18nextAdapterConfig,\n 'defaultLocale' | 'fallbackLocale' | 'keySeparator' | 'nsSeparator'\n> & {\n warnOnMissing?: boolean;\n};\n\n/**\n * Wires a {@link LocaleRegistry} straight into `createI18nextAdapter` +\n * `createI18n`: `registry.locales()` becomes the adapter's `locales`,\n * `registry.buildResources()` becomes its `resources`. This is the ONLY\n * place those two need to be threaded together — an app that builds its own\n * registry never re-lists its locale codes to hand them to the adapter, it\n * just calls this.\n */\nexport async function createI18nFromRegistry(\n registry: LocaleRegistry,\n config: CreateI18nFromRegistryConfig,\n): Promise<I18nFacade> {\n const adapter = await createI18nextAdapter({\n defaultLocale: config.defaultLocale,\n locales: registry.locales(),\n resources: registry.buildResources(),\n ...(config.fallbackLocale !== undefined ? { fallbackLocale: config.fallbackLocale } : {}),\n ...(config.keySeparator !== undefined ? { keySeparator: config.keySeparator } : {}),\n ...(config.nsSeparator !== undefined ? { nsSeparator: config.nsSeparator } : {}),\n });\n return createI18n({ adapter, warnOnMissing: config.warnOnMissing });\n}\n","// Constants\nexport const PACKAGE_NAME = '@burojs/i18n-core' as const;\nexport const PACKAGE_VERSION = '0.0.0' as const;\n\n// Types\nexport type * from './types/index.js';\n\n// Lookup\nexport { resolveKey } from './lookup.js';\n\n// i18next adapter\nexport { createI18nextAdapter, type I18nextAdapterConfig } from './i18next-adapter.js';\n\n// I18n facade\nexport { createI18n, type I18nFacade, type CreateI18nConfig } from './i18n.js';\n\n// Resource context\nexport { createResourceI18n, type ResourceI18n } from './resource-context.js';\n\n// Locale registry — assembling locales from what has REGISTERED (framework\n// packages, the app, domain enum modules) instead of a hand-printed literal.\nexport {\n createLocaleRegistry,\n localeContributionsFromGlob,\n type LocaleContribution,\n type LocaleContributionsFromGlobOptions,\n type LocaleGlobModule,\n type LocaleRegistry,\n} from './locale-registry.js';\nexport {\n createI18nFromRegistry,\n type CreateI18nFromRegistryConfig,\n} from './create-i18n-from-registry.js';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/lookup.ts","../src/i18next-adapter.ts","../src/i18n.ts","../src/resource-context.ts","../src/locale-registry.ts","../src/create-i18n-from-registry.ts","../src/index.ts"],"sourcesContent":["/**\n * Build candidate keys for fallback lookup.\n *\n * Lookup order (first match wins):\n * 1. resources.<name>.<key> — resource-specific\n * 2. resources._.<key> — base for all resources\n * 3. common.<key> — global common\n * 4. <key> — raw fallback (debug only)\n *\n * If `key` is already namespaced (starts with `resources.`, `enums.`,\n * `common.` or `blocks.`), return it as-is without further scoping.\n */\nexport function resolveKey(key: string, resource?: string): string[] {\n if (!key) return [];\n\n // Already namespaced — return as-is. `enums.` is a first-class top-level\n // namespace (global enum labels), like `resources.` and `common.`; so is\n // `blocks.` (a block view's `t` reads `blocks.<id>.<key>`).\n if (\n key.startsWith('resources.') ||\n key.startsWith('enums.') ||\n key.startsWith('common.') ||\n key.startsWith('blocks.')\n ) {\n return [key];\n }\n\n const candidates: string[] = [];\n if (resource) {\n candidates.push(`resources.${resource}.${key}`);\n }\n candidates.push(`resources._.${key}`);\n candidates.push(`common.${key}`);\n candidates.push(key); // raw fallback for warnings\n return candidates;\n}\n","import i18next, { type FallbackLng, type i18n } from 'i18next';\nimport type { I18nAdapter, TranslationBundle } from './types/index.js';\n\n/** What a lookup answers when no locale in the chain holds a usable value. */\nconst MISSING = '\\u0000';\n\nexport interface I18nextAdapterConfig {\n defaultLocale: string;\n locales: string[];\n resources?: Record<string, Record<string, TranslationBundle>>;\n /**\n * A single fallback locale (`'en'`) applies uniformly to every locale. A\n * `fr → en` fallback for one locale but not another needs i18next's own\n * per-locale chain shape instead — `{ fr: ['en'], default: ['en'] }` — so\n * this accepts i18next's full `FallbackLng` type rather than just `string`.\n * The chain is entirely CONFIG: nothing in this adapter special-cases any\n * particular locale code, here or anywhere else.\n */\n fallbackLocale?: FallbackLng;\n keySeparator?: string | false;\n nsSeparator?: string | false;\n}\n\n/**\n * Default I18nAdapter implementation backed by i18next.\n * Each top-level key in resources becomes a separate i18next namespace\n * (e.g. 'common', 'resources').\n */\nexport async function createI18nextAdapter(config: I18nextAdapterConfig): Promise<I18nAdapter> {\n const instance: i18n = i18next.createInstance();\n\n await instance.init({\n lng: config.defaultLocale,\n fallbackLng: config.fallbackLocale ?? config.defaultLocale,\n supportedLngs: config.locales,\n resources: config.resources,\n keySeparator: config.keySeparator ?? '.',\n // Qualified Buro entity refs use `namespace:id`. Resource keys flow\n // through `resources.<ref>.<key>`, so treating ':' as i18next's namespace\n // separator would split a valid ref before our explicit `ns` routing gets\n // to resolve it.\n nsSeparator: config.nsSeparator ?? false,\n defaultNS: 'common',\n interpolation: { escapeValue: false },\n returnNull: false,\n // An empty string is an untranslated key (what extraction tools write), not\n // a translation: `exists` and `t` walk on to the fallback locale, then the\n // caller's code default, so a label never renders blank.\n returnEmptyString: false,\n });\n\n return {\n t(key, params) {\n const dotIdx = key.indexOf('.');\n if (dotIdx === -1) {\n return instance.t(key, params) as string;\n }\n const ns = key.substring(0, dotIdx);\n const subKey = key.substring(dotIdx + 1);\n const result = instance.t(subKey, { ns, ...(params ?? {}) }) as string;\n // i18next returns the bare subKey when missing — restore the full key as\n // fallback. The probe carries the count, so a resolved count family is\n // not mistaken for a miss.\n const count = typeof params?.count === 'number' ? params.count : undefined;\n if (\n result === subKey &&\n !instance.exists(subKey, count === undefined ? { ns } : { ns, count })\n ) {\n return key;\n }\n return result;\n },\n async changeLocale(locale) {\n await instance.changeLanguage(locale);\n },\n async loadNamespace(namespace, _locale) {\n await instance.loadNamespaces(namespace);\n },\n getCurrentLocale() {\n return instance.language;\n },\n onLocaleChange(cb) {\n instance.on('languageChanged', cb);\n return () => instance.off('languageChanged', cb);\n },\n hasKey(key, options) {\n const dotIdx = key.indexOf('.');\n const ns = dotIdx === -1 ? undefined : key.substring(0, dotIdx);\n const subKey = dotIdx === -1 ? key : key.substring(dotIdx + 1);\n const lookup = {\n ...(ns === undefined ? {} : { ns }),\n ...(options?.count === undefined ? {} : { count: options.count }),\n };\n /*\n `exists()` is not enough, and the gap is the root cause of a whole\n family of bugs rather than a curiosity.\n\n i18next answers `exists()` with TRUE for an OBJECT node — `fields.gtin`\n once that entry is promoted from a plain string to `{ label, doc }`,\n `enums.<ns>.<value>` when it carries a `doc` but no `label`, and so on.\n `t()` on such a node neither throws nor returns the key: it returns the\n literal sentence\n\n key '…' returned an object instead of string.\n\n Since `resolveContentSlot` commits to the FIRST key whose `has()` is\n true, every resolver built on it — field labels, enum labels, nav\n labels, tab captions — would render that sentence to the user. No crash,\n no warning, just wrong text on screen. It was found three separate times\n in three separate resolvers before being fixed here, once.\n\n `exists()` is also TRUE for an empty string in the last locale of the\n chain, even with `returnEmptyString: false`. So the lookup itself is the\n probe: `t()` walks the whole chain (count forms included) and answers the\n sentinel default only when no locale holds a usable value.\n\n So `has` means what its callers always assumed: there is a USABLE,\n non-empty STRING at this key. Non-object primitives stay truthy, leaving\n plural forms and numeric values behaving exactly as before.\n */\n const value = instance.t(subKey, {\n ...lookup,\n returnObjects: true,\n defaultValue: MISSING,\n }) as unknown;\n return value !== MISSING && (typeof value !== 'object' || value === null);\n },\n };\n}\n","import { resolveKey } from './lookup.js';\nimport type { I18nAdapter } from './types/index.js';\n\nexport interface I18nFacade {\n /**\n * Translate `key` through the candidate chain. `count` selects a count\n * family's form (`<key>_one | _few | _many | _other`, by the locale's CLDR\n * rules) and interpolates `{{count}}`; a family asked without a count is\n * missing. A `count` inside `params` only interpolates.\n */\n t: (\n key: string,\n options?: { resource?: string; params?: Record<string, unknown>; count?: number },\n ) => string;\n /**\n * True when a translation for `key` EXISTS (through the same candidate chain\n * as {@link I18nFacade.t}). Distinct from `t`, which returns the raw key on a\n * miss — the content model probes presence with `has` to tell \"no bundle\n * entry\" (render nothing) from \"bundle entry === key text\". Pass `count` to probe a count family.\n */\n has: (key: string, options?: { resource?: string; count?: number }) => boolean;\n changeLocale: (locale: string) => Promise<void>;\n getCurrentLocale: () => string;\n /**\n * Subscribe to active-locale changes. Returns an unsubscribe fn. When the\n * adapter can't notify, this is a no-op subscription (returns an unsubscribe\n * that does nothing) — the live language switch then falls back to a static\n * read. Consumed by `useLocale()` via `useSyncExternalStore`.\n */\n onLocaleChange: (cb: () => void) => () => void;\n loadNamespace: (namespace: string, locale: string) => Promise<void>;\n /**\n * The locale codes this app can switch to. Optional: a facade built without\n * a list (a hand-rolled one, a test double) simply does not say, and a\n * language control then offers only the active locale. `createI18nFromRegistry`\n * fills it from the registry.\n */\n locales?: () => readonly string[];\n adapter: I18nAdapter;\n}\n\nexport interface CreateI18nConfig {\n adapter: I18nAdapter;\n warnOnMissing?: boolean;\n /** The switchable locale codes, exposed as {@link I18nFacade.locales}. */\n locales?: () => readonly string[];\n}\n\nexport function createI18n(config: CreateI18nConfig): I18nFacade {\n const { adapter, warnOnMissing = true, locales } = config;\n\n return {\n t(key, options) {\n // `count` is the one spelling: a `count` inside `params` only interpolates.\n const count = options?.count;\n const params = count === undefined ? options?.params : { ...options?.params, count };\n const candidates = resolveKey(key, options?.resource);\n for (const candidate of candidates) {\n const present =\n count === undefined ? adapter.hasKey(candidate) : adapter.hasKey(candidate, { count });\n if (present) {\n return adapter.t(candidate, params);\n }\n }\n if (warnOnMissing && typeof console !== 'undefined') {\n console.warn(\n `[@burojs/i18n-core] Missing translation: '${key}'${options?.resource ? ` (resource: ${options.resource})` : ''}`,\n );\n }\n return key;\n },\n has(key, options) {\n const count = options?.count;\n return resolveKey(key, options?.resource).some((candidate) =>\n count === undefined ? adapter.hasKey(candidate) : adapter.hasKey(candidate, { count }),\n );\n },\n async changeLocale(locale) {\n await adapter.changeLocale(locale);\n },\n getCurrentLocale() {\n return adapter.getCurrentLocale();\n },\n onLocaleChange(cb) {\n return adapter.onLocaleChange?.(cb) ?? (() => {});\n },\n async loadNamespace(namespace, locale) {\n await adapter.loadNamespace(namespace, locale);\n },\n ...(locales === undefined ? {} : { locales }),\n adapter,\n };\n}\n","import type { I18nFacade } from './i18n.js';\n\nexport interface ResourceI18n {\n t: (\n key: string,\n options?: { resource?: string; params?: Record<string, unknown>; count?: number },\n ) => string;\n changeLocale: (locale: string) => Promise<void>;\n getCurrentLocale: () => string;\n resource: string;\n}\n\n/**\n * Wraps an I18nFacade with a default resource scope.\n * `t('actions.delete')` will lookup `resources.<resource>.actions.delete` first.\n * Pass an explicit `resource` option to override the default scope.\n */\nexport function createResourceI18n(i18n: I18nFacade, resource: string): ResourceI18n {\n return {\n t(key, options) {\n return i18n.t(key, {\n resource: options?.resource ?? resource,\n params: options?.params,\n ...(options?.count === undefined ? {} : { count: options.count }),\n });\n },\n changeLocale: i18n.changeLocale,\n getCurrentLocale: i18n.getCurrentLocale,\n resource,\n };\n}\n","import type { TranslationBundle } from './types/bundle.js';\n\n/**\n * One package/app/domain module's offering for one locale.\n *\n * A contribution is data, not code: nothing about `createI18nextAdapter`'s\n * `resources` shape is visible here, and nothing here names a fixed set of\n * locale codes or counts them. `locale` is whatever the file/module that\n * produced this contribution says it is — the registry never validates it\n * against a known list, because there is no known list. That is the whole\n * point: a twenty-first language is a twenty-first contribution, not a\n * twenty-first `case`.\n */\nexport interface LocaleContribution {\n /** Locale code this contribution provides strings for (e.g. 'en', 'es', 'fr'). */\n locale: string;\n /**\n * i18next namespace the bundle merges into. Defaults to `'common'` — the\n * same default namespace `createI18nextAdapter` uses.\n */\n namespace?: string;\n /**\n * Declared merge priority. On a key collision within the same\n * (locale, namespace), the contribution with the HIGHER priority wins —\n * not whichever happened to register last. Ties fall back to registration\n * order (last registered wins), which is why two genuinely competing\n * sources must declare distinct priorities rather than relying on the tie\n * break.\n */\n priority: number;\n /**\n * Where this contribution came from — a package name, `'app'`, an enum\n * module name. Diagnostic only (surfaced by {@link LocaleRegistry.contributions}\n * for debugging a collision); never branched on.\n */\n source: string;\n bundle: TranslationBundle;\n}\n\nexport interface LocaleRegistry {\n /**\n * The primary locale, as declared to {@link createLocaleRegistry}: the one\n * whose text is the default in code, and the locale every other one falls\n * back to. The single source of truth for it — `createI18nFromRegistry`\n * defaults both the starting locale and the fallback to it, and\n * `@burojs/testing`'s `checkApp` reads it to know which locale is exempt\n * from `i18n.missing`. Never derived from contributions or their order.\n */\n primary(): string;\n /** Add one contribution. Order of registration does not matter for the merge result — only `priority` does (see {@link LocaleContribution.priority}). */\n register(contribution: LocaleContribution): void;\n /**\n * Every locale code that has at least one contribution, sorted. Derived\n * purely from what was registered — nothing enumerates or counts locales\n * anywhere else in this module.\n */\n locales(): string[];\n /** Every namespace that has at least one contribution, sorted. */\n namespaces(): string[];\n /** All registered contributions, in registration order. For diagnostics/tests. */\n contributions(): readonly LocaleContribution[];\n /**\n * Assemble `{ [locale]: { [namespace]: TranslationBundle } }`, ready to\n * pass straight as `createI18nextAdapter`'s `resources` config. Within one\n * (locale, namespace) group, contributions are deep-merged in ascending\n * priority order, so a higher-priority contribution's leaves win over a\n * lower-priority one's on any overlapping key while leaving the rest of\n * the lower-priority bundle intact.\n *\n * Throws when no contribution is registered for {@link primary}: a\n * fallback chain that ends at a locale with no bundle, and a primary that\n * `locales()` (and so every language switcher built from it) does not\n * list, is a misconfiguration (usually a typo, `'en-US'` for `'en'`, or a\n * glob that missed its file), not a state to render. An app that really\n * has no strings for its primary locale registers an empty bundle for it.\n */\n buildResources(): Record<string, Record<string, TranslationBundle>>;\n}\n\nconst DEFAULT_NAMESPACE = 'common';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Recursively merge `overlay` onto `base`. Arrays and primitives are replaced\n * wholesale (a `TranslationBundle` array leaf — see that type's own comment\n * on why arrays are a real leaf shape — is not index-merged: the whole array\n * is the unit an overlay replaces). Plain objects merge key by key.\n */\nfunction mergeBundle(base: TranslationBundle, overlay: TranslationBundle): TranslationBundle {\n const out: Record<string, unknown> = { ...base };\n for (const [key, overlayValue] of Object.entries(overlay)) {\n const baseValue = out[key];\n out[key] =\n isPlainObject(baseValue) && isPlainObject(overlayValue)\n ? mergeBundle(baseValue as TranslationBundle, overlayValue as TranslationBundle)\n : overlayValue;\n }\n return out as TranslationBundle;\n}\n\nexport interface LocaleRegistryOptions {\n /**\n * The primary locale: the one whose text is the default in code. Required,\n * and declared here rather than inferred, because nothing in the\n * contributions says which locale it is — registration order and the\n * sorted `locales()` both carry no meaning.\n */\n primary: string;\n}\n\nexport function createLocaleRegistry(options: LocaleRegistryOptions): LocaleRegistry {\n const primary = (options as Partial<LocaleRegistryOptions> | undefined)?.primary;\n if (typeof primary !== 'string' || primary === '') {\n throw new TypeError(\n `createLocaleRegistry needs { primary }, the locale whose text is the default in code; received ${JSON.stringify(primary)}.`,\n );\n }\n const registered: LocaleContribution[] = [];\n\n return {\n primary() {\n return primary;\n },\n register(contribution) {\n registered.push(contribution);\n },\n locales() {\n return Array.from(new Set(registered.map((c) => c.locale))).sort();\n },\n namespaces() {\n return Array.from(new Set(registered.map((c) => c.namespace ?? DEFAULT_NAMESPACE))).sort();\n },\n contributions() {\n return registered;\n },\n buildResources() {\n if (!registered.some((c) => c.locale === primary)) {\n const known = Array.from(new Set(registered.map((c) => c.locale))).sort();\n throw new Error(\n `The locale registry's primary locale ${JSON.stringify(primary)} has no contribution` +\n ` (registered: ${known.length === 0 ? 'none' : known.join(', ')}). Register its bundle,` +\n ' an empty one if the app has no strings of its own, or declare the primary it does register.',\n );\n }\n // Group by (locale, namespace) via NESTED maps rather than a\n // delimiter-joined composite string key. A locale or namespace code is\n // caller-supplied and unconstrained (see `LocaleContribution.locale`'s\n // own comment), so any single-character delimiter is a value that\n // *could* collide with real content; nested `Map`s need no delimiter\n // at all, so there is nothing to collide with and nothing unusual\n // embedded in this file's source for a diff tool to trip over.\n const byLocale = new Map<string, Map<string, LocaleContribution[]>>();\n for (const contribution of registered) {\n const namespace = contribution.namespace ?? DEFAULT_NAMESPACE;\n let byNamespace = byLocale.get(contribution.locale);\n if (!byNamespace) {\n byNamespace = new Map<string, LocaleContribution[]>();\n byLocale.set(contribution.locale, byNamespace);\n }\n const group = byNamespace.get(namespace);\n if (group) {\n group.push(contribution);\n } else {\n byNamespace.set(namespace, [contribution]);\n }\n }\n\n const resources: Record<string, Record<string, TranslationBundle>> = {};\n for (const [locale, byNamespace] of byLocale) {\n const namespaces: Record<string, TranslationBundle> = {};\n for (const [namespace, group] of byNamespace) {\n // Stable sort ascending by priority: lower priority applied first,\n // higher priority applied last so it wins the overlapping leaves.\n // `Array#sort` is stable per spec (ES2019+), so contributions with\n // equal priority keep their registration order — last-registered\n // wins ONLY within a tie, never across a declared priority gap.\n const ordered = [...group].sort((a, b) => a.priority - b.priority);\n let merged: TranslationBundle = {};\n for (const contribution of ordered) {\n merged = mergeBundle(merged, contribution.bundle);\n }\n namespaces[namespace] = merged;\n }\n resources[locale] = namespaces;\n }\n return resources;\n },\n };\n}\n\n/**\n * A bundler-produced glob module, as `import.meta.glob` (Vite) or an\n * equivalent walk over `require.context` (webpack) would yield it: a flat\n * map of path → either the loaded module itself or `{ default }`.\n *\n * Bundler-agnostic on purpose, same reasoning as `@burojs/core`'s\n * `docsFromGlob`: no bundler-agnostic glob primitive exists, and a published\n * package must not require one — the ADOPTER calls `import.meta.glob` (or\n * whatever their bundler offers) and hands the plain object here.\n */\nexport type LocaleGlobModule = TranslationBundle | { default: TranslationBundle };\n\nexport interface LocaleContributionsFromGlobOptions {\n /** {@link LocaleContribution.source} for every contribution produced. */\n source: string;\n /** {@link LocaleContribution.priority} for every contribution produced. */\n priority: number;\n /** {@link LocaleContribution.namespace}. Defaults to `'common'`. */\n namespace?: string;\n /**\n * Extracts the locale code from a glob path. Default matches a bare\n * `<locale>.ts`/`<locale>.tsx`/`<locale>.js` filename (`'./locales/en.ts'`\n * → `'en'`, `'./locales/fr-CA.ts'` → `'fr-CA'`) — no restriction to a\n * known set of codes; whatever the filename says IS the locale code. Paths\n * that don't match are skipped rather than guessed at (same discipline as\n * `docsFromGlob`).\n */\n localeOf?: (path: string) => string | undefined;\n}\n\nconst DEFAULT_LOCALE_PATTERN = /(?:^|\\/)([A-Za-z0-9-]+)\\.(?:ts|tsx|js|jsx|mjs|cjs)$/;\n\nfunction defaultLocaleOf(path: string): string | undefined {\n return DEFAULT_LOCALE_PATTERN.exec(path)?.[1];\n}\n\n/**\n * Normalize a bundler glob of per-locale files into {@link LocaleContribution}s.\n * One file → one locale → one contribution. Nothing here enumerates or counts\n * locale codes: whatever files are present in the globbed directory at build\n * time ARE the contributions produced — dropping in a new file is the entire\n * mechanism for adding a language.\n */\nexport function localeContributionsFromGlob(\n glob: Record<string, LocaleGlobModule>,\n options: LocaleContributionsFromGlobOptions,\n): LocaleContribution[] {\n const localeOf = options.localeOf ?? defaultLocaleOf;\n const out: LocaleContribution[] = [];\n for (const [path, mod] of Object.entries(glob)) {\n const locale = localeOf(path);\n if (locale === undefined) continue;\n // Eager `import.meta.glob` yields a module namespace object — always\n // `{ default, ...named exports }` for a file that does `export default\n // {...}`. Unwrap it when present; otherwise trust the glob already\n // handed a bare bundle (e.g. a caller that pre-unwrapped, or a\n // require.context-style walk that returns exports directly).\n const bundle = isPlainObject((mod as { default?: unknown }).default)\n ? (mod as { default: TranslationBundle }).default\n : (mod as TranslationBundle);\n out.push({\n locale,\n priority: options.priority,\n source: options.source,\n bundle,\n ...(options.namespace !== undefined ? { namespace: options.namespace } : {}),\n });\n }\n return out;\n}\n","import { type I18nFacade, createI18n } from './i18n.js';\nimport { type I18nextAdapterConfig, createI18nextAdapter } from './i18next-adapter.js';\nimport type { LocaleRegistry } from './locale-registry.js';\n\nexport type CreateI18nFromRegistryConfig = Partial<\n Pick<I18nextAdapterConfig, 'defaultLocale' | 'fallbackLocale' | 'keySeparator' | 'nsSeparator'>\n> & {\n warnOnMissing?: boolean;\n};\n\n/**\n * Wires a {@link LocaleRegistry} straight into `createI18nextAdapter` +\n * `createI18n`: `registry.locales()` becomes the adapter's `locales`,\n * `registry.buildResources()` becomes its `resources`, and\n * `registry.primary()` is both the starting locale and the fallback unless\n * `defaultLocale` (the starting locale, say a stored choice) or\n * `fallbackLocale` (say a per-locale chain) overrides it. This is the ONLY\n * place those need to be threaded together — an app that builds its own\n * registry never re-lists its locale codes, or restates its primary locale,\n * to hand them to the adapter; it just calls this.\n *\n * Throws when the registry's primary locale has no contribution (see\n * {@link LocaleRegistry.buildResources}).\n */\nexport async function createI18nFromRegistry(\n registry: LocaleRegistry,\n config: CreateI18nFromRegistryConfig = {},\n): Promise<I18nFacade> {\n const resources = registry.buildResources();\n const primary = registry.primary();\n const adapter = await createI18nextAdapter({\n defaultLocale: config.defaultLocale ?? primary,\n locales: registry.locales(),\n resources,\n fallbackLocale: config.fallbackLocale ?? primary,\n ...(config.keySeparator !== undefined ? { keySeparator: config.keySeparator } : {}),\n ...(config.nsSeparator !== undefined ? { nsSeparator: config.nsSeparator } : {}),\n });\n return createI18n({\n adapter,\n warnOnMissing: config.warnOnMissing,\n locales: () => registry.locales(),\n });\n}\n","// Constants\nexport const PACKAGE_NAME = '@burojs/i18n-core' as const;\nexport const PACKAGE_VERSION = '0.0.0' as const;\n\n// Types\nexport type * from './types/index.js';\n\n// Lookup\nexport { resolveKey } from './lookup.js';\n\n// i18next adapter\nexport { createI18nextAdapter, type I18nextAdapterConfig } from './i18next-adapter.js';\n\n// I18n facade\nexport { createI18n, type I18nFacade, type CreateI18nConfig } from './i18n.js';\n\n// Resource context\nexport { createResourceI18n, type ResourceI18n } from './resource-context.js';\n\n// Locale registry — assembling locales from what has REGISTERED (framework\n// packages, the app, domain enum modules) instead of a hand-printed literal.\nexport {\n createLocaleRegistry,\n localeContributionsFromGlob,\n type LocaleContribution,\n type LocaleContributionsFromGlobOptions,\n type LocaleGlobModule,\n type LocaleRegistry,\n type LocaleRegistryOptions,\n} from './locale-registry.js';\nexport {\n createI18nFromRegistry,\n type CreateI18nFromRegistryConfig,\n} from './create-i18n-from-registry.js';\n"],"mappings":";;AAYA,SAAgB,WAAW,KAAa,UAA6B;CACnE,IAAI,CAAC,KAAK,OAAO,CAAC;CAKlB,IACE,IAAI,WAAW,YAAY,KAC3B,IAAI,WAAW,QAAQ,KACvB,IAAI,WAAW,SAAS,KACxB,IAAI,WAAW,SAAS,GAExB,OAAO,CAAC,GAAG;CAGb,MAAM,aAAuB,CAAC;CAC9B,IAAI,UACF,WAAW,KAAK,aAAa,SAAS,GAAG,KAAK;CAEhD,WAAW,KAAK,eAAe,KAAK;CACpC,WAAW,KAAK,UAAU,KAAK;CAC/B,WAAW,KAAK,GAAG;CACnB,OAAO;AACT;;;AC/BA,MAAM,UAAU;AAwBhB,eAAsB,qBAAqB,QAAoD;CAC7F,MAAM,WAAiB,QAAQ,eAAe;CAE9C,MAAM,SAAS,KAAK;EAClB,KAAK,OAAO;EACZ,aAAa,OAAO,kBAAkB,OAAO;EAC7C,eAAe,OAAO;EACtB,WAAW,OAAO;EAClB,cAAc,OAAO,gBAAgB;EAKrC,aAAa,OAAO,eAAe;EACnC,WAAW;EACX,eAAe,EAAE,aAAa,MAAM;EACpC,YAAY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