@worldware/msg 0.11.1 → 0.13.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 CHANGED
@@ -33,11 +33,11 @@ A project configuration that defines:
33
33
 
34
34
  ### MsgResource
35
35
 
36
- A collection of messages (extends `Map<string, MsgMessage>`) representing a resource bundle. Each resource has:
36
+ A collection of messages (extends `Map<K, MsgMessage>`, where `K` defaults to `string`) representing a resource bundle. Each resource has:
37
37
  - A title/name
38
38
  - Attributes (language, text direction, do-not-translate flag)
39
39
  - Notes (descriptions, context, etc.)
40
- - Messages indexed by key
40
+ - Messages indexed by key. Dot-separated keys such as `home.cta.label` can be read as a nested tree with `toTree()`, and opting in with `as const` makes the keys type-checked (see [Typed message keys and the message tree](#typed-message-keys-and-the-message-tree)).
41
41
 
42
42
  ### MsgMessage
43
43
 
@@ -64,7 +64,7 @@ const loader = async (project, title, language) => {
64
64
  const module = await import(path, { with: { type: 'json' } });
65
65
  return module.default;
66
66
  } catch (error) {
67
- console.warn(`Translations for locale ${language} could not be loaded.`, error);
67
+ console.warn(`Translations for locale ${language} could not be loaded.`);
68
68
  return {
69
69
  title,
70
70
  attributes: { lang: language, dir: 'auto' },
@@ -149,6 +149,35 @@ const messages = await getMessages();
149
149
  messages.get('sampleKey2')?.format({ name: 'Alice' });
150
150
  ```
151
151
 
152
+ ### Typed message keys and the message tree
153
+
154
+ Define a resource's messages `as const` and TypeScript infers its keys: `get()`, `has()`, and `toTree()` then reject keys the resource doesn't define. `toTree()` returns a nested view of dot-separated keys.
155
+
156
+ ```typescript
157
+ const resource = MsgResource.create({
158
+ title: 'Home',
159
+ attributes: { lang: 'en', dir: 'ltr' },
160
+ messages: [
161
+ { key: 'home.title', value: 'Welcome' },
162
+ { key: 'home.cta.label', value: 'Hi, {name}' },
163
+ { key: 'footer', value: 'Footer' }
164
+ ] as const
165
+ }, project);
166
+
167
+ resource.get('home.titel'); // compile error: unknown key
168
+ const tree = resource.toTree();
169
+ tree.home.cta.label.format({ name: 'Ada' }); // autocompletes; typos are compile errors
170
+ tree.footer.toString(); // "Footer"
171
+ ```
172
+
173
+ - **Opt-in.** Without `as const`, keys are typed as `string`, so a resource can keep growing with `add()`. `add()` always accepts any string and doesn't change the resource's key type.
174
+ - **JavaScript files** (such as msg-cli's `.msg.js` resources) can't use `as const`. Use the JSDoc form instead, `messages: /** @type {const} */ ([ … ])`, and editors and `tsc --checkJs` give the same key checking.
175
+ - **Typed resources are still `MsgResource`s.** You can pass one anywhere a plain `MsgResource` is expected.
176
+ - **Translations keep the key type.** `translate()` and `getTranslation()` return a resource with the same keys as the source (see [Language fallbacks and translation layering](#language-fallbacks-and-translation-layering)).
177
+ - **No key can be both a message and a branch.** Adding `a` when `a.b` exists, or `a.b` when `a` exists, throws a `TypeError`. Replacing an existing key is fine, and `delete()` / `clear()` free the path again.
178
+ - **The tree is built on each call.** It holds the resource's own `MsgMessage` objects and reflects the resource at the time of the call. Keys such as `constructor` or `__proto__` are ordinary tree keys.
179
+ - **Limits.** One `as const` message list can hold up to about 10,000 messages (TypeScript's tuple limit). Resources loaded from JSON at runtime are untyped (`MsgResource<string>`), because their keys aren't known at compile time.
180
+
152
181
  ### Message Formats (MF1, MF2, NONE)
153
182
 
154
183
  Every message is formatted according to its resolved `format` attribute:
@@ -159,6 +188,8 @@ Every message is formatted according to its resolved `format` attribute:
159
188
 
160
189
  The `format` is inheritable: a resource inherits its project's `format` unless it sets its own, and a message inherits its resource's `format` unless it sets its own. The default is `MF2`, so existing code keeps working unchanged. Use a TypeScript union (`'MF1' | 'MF2' | 'NONE'`) — there is no enum.
161
190
 
191
+ `lang`, `dir`, and `dnt` inherit the same way on messages: omitted fields (or omitted `attributes`) take the resource's values, and an explicit per-message value still wins. Compact translation JSON can therefore list only overrides. `create()`, `add()`, `translate()`, and `getTranslation()` all apply this merge.
192
+
162
193
  The following is a **separate illustration** of format inheritance and per-message overrides (not the CLI `Main` / `Messages` scaffold above):
163
194
 
164
195
  ```typescript
@@ -194,7 +225,8 @@ When serializing, an inherited `format` is omitted to keep output compact: a res
194
225
  const zhResource = await resource.getTranslation('zh');
195
226
 
196
227
  // The translated resource will have Chinese messages where available,
197
- // falling back to the source messages for missing translations
228
+ // falling back to the source messages for missing translations.
229
+ // It has exactly the source's keys: keys only the translation has are ignored.
198
230
 
199
231
  // Or use the scaffolded helper (honors setLang() / getLang())
200
232
  const messages = await getMessages();
@@ -208,7 +240,7 @@ When you call `resource.getTranslation(locale)`:
208
240
 
209
241
  1. The **source resource** (the resource you called it on) is the base.
210
242
  2. For each locale in that locale's chain, the project **loader** is called to load that locale's translation data.
211
- 3. Each loaded dataset is **layered** onto the current result: messages in the new data add or override by key; keys missing in the new layer keep the value from the previous layer.
243
+ 3. Each loaded dataset is **layered** onto the current result: messages in the new data override by key; keys missing in the new layer keep the value from the previous layer. Keys that aren't in the source resource are **ignored**, so a translation can't add messages (stale keys left in translation files are dropped).
212
244
  4. The final resource is the result after all layers have been applied.
213
245
 
214
246
  So for `getTranslation('zh-HK')` with chain `['zh', 'zh-Hant', 'zh-HK']`, you get: source → then zh overlay → then zh-Hant overlay → then zh-HK overlay. Later entries in the chain override earlier ones for the same key; missing keys fall back to the previous layer (and ultimately to the source).
@@ -295,15 +327,17 @@ const data = resource.getData();
295
327
  ### MsgResource
296
328
 
297
329
  **Static Methods:**
298
- - `create(data: MsgResourceData, project: MsgProject): MsgResource` - Create a new resource
330
+ - `create(data: MsgResourceData, project: MsgProject): MsgResource<K>` - Create a new resource. When `messages` is `as const`, `K` is the union of its keys; otherwise `string`. Throws a `TypeError` when one key is a dot-separated prefix of another (e.g. `a` and `a.b`)
299
331
 
300
332
  **Methods:**
301
- - `add(key: string, value: string, attributes?: MsgAttributes, notes?: MsgNote[]): MsgResource` - Add a message
333
+ - `add(key: string, value: string, attributes?: MsgAttributes, notes?: MsgNote[]): MsgResource<K>` - Add a message. Accepts any string key; throws a `TypeError` on a leaf/branch collision
334
+ - `set(key: K, message: MsgMessage)` / `delete(key: K)` / `clear()` - `Map` methods; `set()` also throws on a leaf/branch collision
335
+ - `toTree(): MsgTree<K>` - Nested, read-only view of dot-separated keys (`resource.toTree().home.title`). Built on each call from the resource's own messages
302
336
  - `addNote(type: NoteTypes, content: string): MsgResource` - Add a note (returns `this` for chaining)
303
- - `translate(data: MsgResourceData): MsgResource` - Create a translated version
304
- - `getTranslation(lang?: string): Promise<MsgResource>` - Load and apply translations. When `lang` matches the project's `pseudoLocale`, returns a resource with message values pseudo-localized according to each message's resolved `format` (`MF1` / `MF2` / `NONE`) instead of loading from the loader. When `lang` is omitted, returns a clone of the current resource.
337
+ - `translate(data: MsgResourceData): MsgResource<K>` - Create a translated version. Keys that aren't in this resource are ignored
338
+ - `getTranslation(lang?: string): Promise<MsgResource<K>>` - Load and apply translations. When `lang` matches the project's `pseudoLocale`, returns a resource with message values pseudo-localized according to each message's resolved `format` (`MF1` / `MF2` / `NONE`) instead of loading from the loader. When `lang` is omitted, returns a clone of the current resource.
305
339
  - `getProject(): MsgProject` - Returns the project instance associated with the resource
306
- - `getData(stripNotes?: boolean): MsgResourceData` - Get resource data. Message objects in the output omit `attributes` when they match the resource's attributes (to avoid redundancy). The resource's `format` is omitted when it equals the project's, and a message's `format` is omitted when it equals the resource's
340
+ - `getData(stripNotes?: boolean): MsgResourceData<K>` - Get resource data. Message objects in the output omit `attributes` when they match the resource's attributes (to avoid redundancy). The resource's `format` is omitted when it equals the project's, and a message's `format` is omitted when it equals the resource's
307
341
  - `toJSON(stripNotes?: boolean): string` - Serialize to JSON
308
342
 
309
343
  **Properties:**
@@ -333,6 +367,9 @@ const data = resource.getData();
333
367
 
334
368
  - `MsgFormat` - `'MF1' | 'MF2' | 'NONE'`; the formatting syntax for a message.
335
369
  - `MsgAttributes` - `{ lang?: string; dir?: string; dnt?: boolean; format?: MsgFormat }`. Omitted or empty `dir` resolves to `'auto'`.
370
+ - `MsgResourceData<K = string>` / `MsgMessageData<K = string>` - Plain resource and message data; `K` is the message key type.
371
+ - `MsgTree<K>` - Nested view of keys `K`: for `'home.title' | 'footer'`, `{ home: { title: MsgMessage }; footer: MsgMessage }`. `MsgTree<string>` is `MsgTreeNode`.
372
+ - `MsgTreeNode` - `{ readonly [segment: string]: MsgMessage | MsgTreeNode }`; the tree of an untyped resource.
336
373
 
337
374
  ### Pseudo-localization helpers
338
375
 
@@ -12,16 +12,52 @@ import {
12
12
  } from "./chunk-XQVALCKX.mjs";
13
13
 
14
14
  // src/classes/MsgResource/MsgResource.ts
15
+ function branchPrefixes(key) {
16
+ const prefixes = [];
17
+ for (let i = key.indexOf("."); i !== -1; i = key.indexOf(".", i + 1)) {
18
+ prefixes.push(key.slice(0, i));
19
+ }
20
+ return prefixes;
21
+ }
15
22
  var MsgResource = class _MsgResource extends Map {
16
23
  _attributes = {};
17
24
  _notes = [];
18
25
  _title;
19
26
  _project;
27
+ /**
28
+ * For every key prefix that is a branch in the tree (`a` and `a.b` for key
29
+ * `a.b.c`), how many stored keys pass through it. Keeps collision checks
30
+ * proportional to key depth instead of resource size.
31
+ */
32
+ _branches = /* @__PURE__ */ new Map();
20
33
  /**
21
34
  * Builds a resource from {@link MsgResourceData} and an owning project.
22
35
  *
23
36
  * When `messages` is provided, each entry is added to the resource.
24
37
  * When omitted, the resource starts empty.
38
+ *
39
+ * **Typed keys are opt-in with `as const`.** When `messages` (or the whole
40
+ * definition) is `as const`, the resource's key type is the union of its
41
+ * message keys, so `get()`, `has()` and `toTree()` reject unknown keys.
42
+ * Without `as const` the key type is `string`, exactly as before, so a
43
+ * resource can keep growing through `add()`.
44
+ *
45
+ * ```ts
46
+ * const typed = MsgResource.create({
47
+ * title: 'Home',
48
+ * attributes: { lang: 'en' },
49
+ * messages: [{ key: 'home.title', value: 'Welcome' }] as const
50
+ * }, project);
51
+ * typed.get('home.titel'); // compile error
52
+ * ```
53
+ *
54
+ * `as const` data is a tuple, so inference also scales to large resources:
55
+ * up to TypeScript's ~10,000-element tuple limit.
56
+ *
57
+ * @typeParam M - The message list; its `key` types become the resource's
58
+ * key type.
59
+ * @throws {TypeError} When one key is a dot-separated prefix of another
60
+ * (for example `a` and `a.b`).
25
61
  */
26
62
  static create(data, project) {
27
63
  const { title, attributes, notes, messages } = data;
@@ -29,7 +65,7 @@ var MsgResource = class _MsgResource extends Map {
29
65
  if (messages) {
30
66
  messages.forEach((messageData) => {
31
67
  const { key, value, attributes: attributes2, notes: notes2 } = messageData;
32
- res.add(key, value, attributes2, notes2);
68
+ res.add(key, value, attributes2, notes2 && [...notes2]);
33
69
  });
34
70
  } else {
35
71
  res.clear();
@@ -112,7 +148,14 @@ var MsgResource = class _MsgResource extends Map {
112
148
  /**
113
149
  * Adds a message to this resource, merging resource attributes with any overrides.
114
150
  *
151
+ * Unspecified `lang`, `dir`, and `dnt` inherit from this resource; explicit
152
+ * values on the message win.
153
+ *
154
+ * Accepts any string key and does not change the resource's key type.
155
+ *
115
156
  * @returns This resource, for chaining.
157
+ * @throws {TypeError} When `key` and an existing key are dot-separated
158
+ * prefixes of one another (for example `a` and `a.b`).
116
159
  */
117
160
  add(key, value, attributes, notes) {
118
161
  const merged = { ...this.attributes, ...attributes };
@@ -125,11 +168,89 @@ var MsgResource = class _MsgResource extends Map {
125
168
  this.set(key, msg);
126
169
  return this;
127
170
  }
171
+ /**
172
+ * Stores a message under `key`.
173
+ *
174
+ * @throws {TypeError} When `key` and an existing key are dot-separated
175
+ * prefixes of one another (for example `a` and `a.b`), since a tree node
176
+ * cannot be both a message and a branch.
177
+ */
178
+ set(key, value) {
179
+ if (!this.has(key)) {
180
+ this.assertNoCollision(key);
181
+ this.updateBranches(key, 1);
182
+ }
183
+ return super.set(key, value);
184
+ }
185
+ /** Removes the message stored under `key`. */
186
+ delete(key) {
187
+ const deleted = super.delete(key);
188
+ if (deleted) {
189
+ this.updateBranches(key, -1);
190
+ }
191
+ return deleted;
192
+ }
193
+ /** Removes every message from this resource. */
194
+ clear() {
195
+ super.clear();
196
+ this._branches.clear();
197
+ }
198
+ /**
199
+ * Throws when `key` would be both a message and a branch in the tree.
200
+ */
201
+ assertNoCollision(key) {
202
+ if (this._branches.has(key)) {
203
+ const descendant = [...this.keys()].find((existing) => existing.startsWith(`${key}.`));
204
+ throw new TypeError(`Message key "${key}" collides with "${descendant}": a key cannot also be a prefix of another key.`);
205
+ }
206
+ const leaf = branchPrefixes(key).find((prefix) => this.has(prefix));
207
+ if (leaf !== void 0) {
208
+ throw new TypeError(`Message key "${key}" collides with "${leaf}": a key cannot also be a prefix of another key.`);
209
+ }
210
+ }
211
+ /**
212
+ * Adds `delta` to the count of every branch `key` passes through,
213
+ * dropping branches that no key uses any more.
214
+ */
215
+ updateBranches(key, delta) {
216
+ for (const prefix of branchPrefixes(key)) {
217
+ const count = (this._branches.get(prefix) ?? 0) + delta;
218
+ if (count > 0) {
219
+ this._branches.set(prefix, count);
220
+ } else {
221
+ this._branches.delete(prefix);
222
+ }
223
+ }
224
+ }
225
+ /**
226
+ * Returns a nested, read-only view of this resource's messages, splitting
227
+ * keys on `.`: `resource.toTree().home.cta.label` is the message stored
228
+ * under `'home.cta.label'`.
229
+ *
230
+ * The key type comes from `this` rather than the class parameter so that a
231
+ * typed resource stays assignable to a plain `MsgResource`.
232
+ */
233
+ toTree() {
234
+ const root = /* @__PURE__ */ Object.create(null);
235
+ for (const [key, msg] of this) {
236
+ const segments = key.split(".");
237
+ const leaf = segments.pop();
238
+ let node = root;
239
+ for (const segment of segments) {
240
+ node = node[segment] ??= /* @__PURE__ */ Object.create(null);
241
+ }
242
+ node[leaf] = msg;
243
+ }
244
+ return root;
245
+ }
128
246
  /**
129
247
  * Builds a translated copy of this resource from translation data.
130
248
  *
131
249
  * Messages present in the translation replace the source; missing keys keep
132
- * the source message. Notes are carried over from the source.
250
+ * the source message. Keys that are not in this resource are ignored, so the
251
+ * translated resource has the same keys (and key type) as the source. Notes
252
+ * are carried over from the source. Unspecified message `lang`, `dir`, and
253
+ * `dnt` inherit from the translated resource.
133
254
  *
134
255
  * @throws {TypeError} When the translation title does not match this resource.
135
256
  */
@@ -138,29 +259,29 @@ var MsgResource = class _MsgResource extends Map {
138
259
  if (title !== this.title) {
139
260
  throw new TypeError("Title of resource and translations do not match.");
140
261
  }
141
- const translated = _MsgResource.create({
262
+ const translated = new _MsgResource(
142
263
  title,
143
264
  // preserve the source resource's format unless the translation overrides it
144
- attributes: this.preserveFormat(attributes, this.attributes.format),
145
- notes: this.notes
265
+ this.preserveFormat(attributes, this.attributes.format),
266
+ this._project,
267
+ this.notes
146
268
  // transfer the notes
147
- }, this._project);
148
- this.forEach((msg) => {
149
- translated.set(msg.key, msg);
269
+ );
270
+ this.forEach((msg, key) => {
271
+ translated.set(key, msg);
150
272
  });
151
273
  messages?.forEach((messageData) => {
152
274
  const { key, value, attributes: attributes2 } = messageData;
153
- const msg = MsgMessage.create({
275
+ const source = this.get(key);
276
+ if (!source) {
277
+ return;
278
+ }
279
+ translated.add(
154
280
  key,
155
281
  value,
156
- // preserve the source message's format unless the translation overrides it
157
- attributes: this.preserveFormat(attributes2, this.get(key)?.attributes.format)
158
- });
159
- const notes = this.get(key)?.notes || [];
160
- notes.forEach((note) => {
161
- msg.addNote(note.type, note.content);
162
- });
163
- translated.set(key, msg);
282
+ this.preserveFormat(attributes2, source.attributes.format),
283
+ source.notes
284
+ );
164
285
  });
165
286
  return translated;
166
287
  }
@@ -189,8 +310,8 @@ var MsgResource = class _MsgResource extends Map {
189
310
  const project = this._project;
190
311
  const pseudoLocale = project.locales.pseudoLocale;
191
312
  if (lang === pseudoLocale) {
192
- const messages = [...this.values()].map((msg) => ({
193
- key: msg.key,
313
+ const messages = [...this.entries()].map(([key, msg]) => ({
314
+ key,
194
315
  value: pseudoLocalize(msg.value, this.resolveFormat(msg.attributes)),
195
316
  attributes: { ...msg.attributes, lang: pseudoLocale }
196
317
  }));
@@ -230,16 +351,16 @@ var MsgResource = class _MsgResource extends Map {
230
351
  const resourceFormat = this.resolveFormat(this.attributes);
231
352
  const projectFormat = this._project.format;
232
353
  const messages = [];
233
- this.forEach((msg) => {
354
+ this.forEach((msg, key) => {
234
355
  if (this.hasMatchingAttributes(msg)) {
235
356
  const data = {
236
- key: msg.key,
357
+ key,
237
358
  value: msg.value,
238
359
  notes: !stripNotes && msg.notes.length > 0 ? msg.notes : void 0
239
360
  };
240
361
  messages.push(data);
241
362
  } else {
242
- const data = msg.getData(stripNotes);
363
+ const data = { ...msg.getData(stripNotes), key };
243
364
  if (data.attributes && this.resolveFormat(data.attributes) === resourceFormat) {
244
365
  const { format, ...rest } = data.attributes;
245
366
  data.attributes = rest;
@@ -4,10 +4,13 @@ import { MsgInterface, MsgAttributes, MsgNote, NoteTypes } from '../MsgInterface
4
4
 
5
5
  /**
6
6
  * Plain data used to create a {@link MsgMessage}.
7
+ *
8
+ * @typeParam K - The message key. Defaults to `string`; `as const` message
9
+ * data lets `MsgResource.create()` infer a resource's key union.
7
10
  */
8
- type MsgMessageData = {
11
+ type MsgMessageData<K extends string = string> = {
9
12
  /** Unique key that identifies this message within a resource. */
10
- key: string;
13
+ key: K;
11
14
  /** The message string, possibly in MessageFormat syntax. */
12
15
  value: string;
13
16
  /** Optional locale and formatting metadata. */
@@ -4,10 +4,13 @@ import { MsgInterface, MsgAttributes, MsgNote, NoteTypes } from '../MsgInterface
4
4
 
5
5
  /**
6
6
  * Plain data used to create a {@link MsgMessage}.
7
+ *
8
+ * @typeParam K - The message key. Defaults to `string`; `as const` message
9
+ * data lets `MsgResource.create()` infer a resource's key union.
7
10
  */
8
- type MsgMessageData = {
11
+ type MsgMessageData<K extends string = string> = {
9
12
  /** Unique key that identifies this message within a resource. */
10
- key: string;
13
+ key: K;
11
14
  /** The message string, possibly in MessageFormat syntax. */
12
15
  value: string;
13
16
  /** Optional locale and formatting metadata. */
@@ -251,16 +251,52 @@ function pseudoLocalize(source, format, options) {
251
251
  }
252
252
 
253
253
  // src/classes/MsgResource/MsgResource.ts
254
+ function branchPrefixes(key) {
255
+ const prefixes = [];
256
+ for (let i = key.indexOf("."); i !== -1; i = key.indexOf(".", i + 1)) {
257
+ prefixes.push(key.slice(0, i));
258
+ }
259
+ return prefixes;
260
+ }
254
261
  var MsgResource = class _MsgResource extends Map {
255
262
  _attributes = {};
256
263
  _notes = [];
257
264
  _title;
258
265
  _project;
266
+ /**
267
+ * For every key prefix that is a branch in the tree (`a` and `a.b` for key
268
+ * `a.b.c`), how many stored keys pass through it. Keeps collision checks
269
+ * proportional to key depth instead of resource size.
270
+ */
271
+ _branches = /* @__PURE__ */ new Map();
259
272
  /**
260
273
  * Builds a resource from {@link MsgResourceData} and an owning project.
261
274
  *
262
275
  * When `messages` is provided, each entry is added to the resource.
263
276
  * When omitted, the resource starts empty.
277
+ *
278
+ * **Typed keys are opt-in with `as const`.** When `messages` (or the whole
279
+ * definition) is `as const`, the resource's key type is the union of its
280
+ * message keys, so `get()`, `has()` and `toTree()` reject unknown keys.
281
+ * Without `as const` the key type is `string`, exactly as before, so a
282
+ * resource can keep growing through `add()`.
283
+ *
284
+ * ```ts
285
+ * const typed = MsgResource.create({
286
+ * title: 'Home',
287
+ * attributes: { lang: 'en' },
288
+ * messages: [{ key: 'home.title', value: 'Welcome' }] as const
289
+ * }, project);
290
+ * typed.get('home.titel'); // compile error
291
+ * ```
292
+ *
293
+ * `as const` data is a tuple, so inference also scales to large resources:
294
+ * up to TypeScript's ~10,000-element tuple limit.
295
+ *
296
+ * @typeParam M - The message list; its `key` types become the resource's
297
+ * key type.
298
+ * @throws {TypeError} When one key is a dot-separated prefix of another
299
+ * (for example `a` and `a.b`).
264
300
  */
265
301
  static create(data, project) {
266
302
  const { title, attributes, notes, messages } = data;
@@ -268,7 +304,7 @@ var MsgResource = class _MsgResource extends Map {
268
304
  if (messages) {
269
305
  messages.forEach((messageData) => {
270
306
  const { key, value, attributes: attributes2, notes: notes2 } = messageData;
271
- res.add(key, value, attributes2, notes2);
307
+ res.add(key, value, attributes2, notes2 && [...notes2]);
272
308
  });
273
309
  } else {
274
310
  res.clear();
@@ -351,7 +387,14 @@ var MsgResource = class _MsgResource extends Map {
351
387
  /**
352
388
  * Adds a message to this resource, merging resource attributes with any overrides.
353
389
  *
390
+ * Unspecified `lang`, `dir`, and `dnt` inherit from this resource; explicit
391
+ * values on the message win.
392
+ *
393
+ * Accepts any string key and does not change the resource's key type.
394
+ *
354
395
  * @returns This resource, for chaining.
396
+ * @throws {TypeError} When `key` and an existing key are dot-separated
397
+ * prefixes of one another (for example `a` and `a.b`).
355
398
  */
356
399
  add(key, value, attributes, notes) {
357
400
  const merged = { ...this.attributes, ...attributes };
@@ -364,11 +407,89 @@ var MsgResource = class _MsgResource extends Map {
364
407
  this.set(key, msg);
365
408
  return this;
366
409
  }
410
+ /**
411
+ * Stores a message under `key`.
412
+ *
413
+ * @throws {TypeError} When `key` and an existing key are dot-separated
414
+ * prefixes of one another (for example `a` and `a.b`), since a tree node
415
+ * cannot be both a message and a branch.
416
+ */
417
+ set(key, value) {
418
+ if (!this.has(key)) {
419
+ this.assertNoCollision(key);
420
+ this.updateBranches(key, 1);
421
+ }
422
+ return super.set(key, value);
423
+ }
424
+ /** Removes the message stored under `key`. */
425
+ delete(key) {
426
+ const deleted = super.delete(key);
427
+ if (deleted) {
428
+ this.updateBranches(key, -1);
429
+ }
430
+ return deleted;
431
+ }
432
+ /** Removes every message from this resource. */
433
+ clear() {
434
+ super.clear();
435
+ this._branches.clear();
436
+ }
437
+ /**
438
+ * Throws when `key` would be both a message and a branch in the tree.
439
+ */
440
+ assertNoCollision(key) {
441
+ if (this._branches.has(key)) {
442
+ const descendant = [...this.keys()].find((existing) => existing.startsWith(`${key}.`));
443
+ throw new TypeError(`Message key "${key}" collides with "${descendant}": a key cannot also be a prefix of another key.`);
444
+ }
445
+ const leaf = branchPrefixes(key).find((prefix) => this.has(prefix));
446
+ if (leaf !== void 0) {
447
+ throw new TypeError(`Message key "${key}" collides with "${leaf}": a key cannot also be a prefix of another key.`);
448
+ }
449
+ }
450
+ /**
451
+ * Adds `delta` to the count of every branch `key` passes through,
452
+ * dropping branches that no key uses any more.
453
+ */
454
+ updateBranches(key, delta) {
455
+ for (const prefix of branchPrefixes(key)) {
456
+ const count = (this._branches.get(prefix) ?? 0) + delta;
457
+ if (count > 0) {
458
+ this._branches.set(prefix, count);
459
+ } else {
460
+ this._branches.delete(prefix);
461
+ }
462
+ }
463
+ }
464
+ /**
465
+ * Returns a nested, read-only view of this resource's messages, splitting
466
+ * keys on `.`: `resource.toTree().home.cta.label` is the message stored
467
+ * under `'home.cta.label'`.
468
+ *
469
+ * The key type comes from `this` rather than the class parameter so that a
470
+ * typed resource stays assignable to a plain `MsgResource`.
471
+ */
472
+ toTree() {
473
+ const root = /* @__PURE__ */ Object.create(null);
474
+ for (const [key, msg] of this) {
475
+ const segments = key.split(".");
476
+ const leaf = segments.pop();
477
+ let node = root;
478
+ for (const segment of segments) {
479
+ node = node[segment] ??= /* @__PURE__ */ Object.create(null);
480
+ }
481
+ node[leaf] = msg;
482
+ }
483
+ return root;
484
+ }
367
485
  /**
368
486
  * Builds a translated copy of this resource from translation data.
369
487
  *
370
488
  * Messages present in the translation replace the source; missing keys keep
371
- * the source message. Notes are carried over from the source.
489
+ * the source message. Keys that are not in this resource are ignored, so the
490
+ * translated resource has the same keys (and key type) as the source. Notes
491
+ * are carried over from the source. Unspecified message `lang`, `dir`, and
492
+ * `dnt` inherit from the translated resource.
372
493
  *
373
494
  * @throws {TypeError} When the translation title does not match this resource.
374
495
  */
@@ -377,29 +498,29 @@ var MsgResource = class _MsgResource extends Map {
377
498
  if (title !== this.title) {
378
499
  throw new TypeError("Title of resource and translations do not match.");
379
500
  }
380
- const translated = _MsgResource.create({
501
+ const translated = new _MsgResource(
381
502
  title,
382
503
  // preserve the source resource's format unless the translation overrides it
383
- attributes: this.preserveFormat(attributes, this.attributes.format),
384
- notes: this.notes
504
+ this.preserveFormat(attributes, this.attributes.format),
505
+ this._project,
506
+ this.notes
385
507
  // transfer the notes
386
- }, this._project);
387
- this.forEach((msg) => {
388
- translated.set(msg.key, msg);
508
+ );
509
+ this.forEach((msg, key) => {
510
+ translated.set(key, msg);
389
511
  });
390
512
  messages?.forEach((messageData) => {
391
513
  const { key, value, attributes: attributes2 } = messageData;
392
- const msg = MsgMessage.create({
514
+ const source = this.get(key);
515
+ if (!source) {
516
+ return;
517
+ }
518
+ translated.add(
393
519
  key,
394
520
  value,
395
- // preserve the source message's format unless the translation overrides it
396
- attributes: this.preserveFormat(attributes2, this.get(key)?.attributes.format)
397
- });
398
- const notes = this.get(key)?.notes || [];
399
- notes.forEach((note) => {
400
- msg.addNote(note.type, note.content);
401
- });
402
- translated.set(key, msg);
521
+ this.preserveFormat(attributes2, source.attributes.format),
522
+ source.notes
523
+ );
403
524
  });
404
525
  return translated;
405
526
  }
@@ -428,8 +549,8 @@ var MsgResource = class _MsgResource extends Map {
428
549
  const project = this._project;
429
550
  const pseudoLocale = project.locales.pseudoLocale;
430
551
  if (lang === pseudoLocale) {
431
- const messages = [...this.values()].map((msg) => ({
432
- key: msg.key,
552
+ const messages = [...this.entries()].map(([key, msg]) => ({
553
+ key,
433
554
  value: pseudoLocalize(msg.value, this.resolveFormat(msg.attributes)),
434
555
  attributes: { ...msg.attributes, lang: pseudoLocale }
435
556
  }));
@@ -469,16 +590,16 @@ var MsgResource = class _MsgResource extends Map {
469
590
  const resourceFormat = this.resolveFormat(this.attributes);
470
591
  const projectFormat = this._project.format;
471
592
  const messages = [];
472
- this.forEach((msg) => {
593
+ this.forEach((msg, key) => {
473
594
  if (this.hasMatchingAttributes(msg)) {
474
595
  const data = {
475
- key: msg.key,
596
+ key,
476
597
  value: msg.value,
477
598
  notes: !stripNotes && msg.notes.length > 0 ? msg.notes : void 0
478
599
  };
479
600
  messages.push(data);
480
601
  } else {
481
- const data = msg.getData(stripNotes);
602
+ const data = { ...msg.getData(stripNotes), key };
482
603
  if (data.attributes && this.resolveFormat(data.attributes) === resourceFormat) {
483
604
  const { format, ...rest } = data.attributes;
484
605
  data.attributes = rest;
@@ -1,4 +1,4 @@
1
1
  import '../MsgMessage/MsgMessage.cjs';
2
2
  import '../MsgInterface/MsgInterface.cjs';
3
- export { MsgResource, MsgResourceData } from '../index.cjs';
3
+ export { MsgResource, MsgResourceData, MsgTree, MsgTreeNode } from '../index.cjs';
4
4
  import 'messageformat';
@@ -1,4 +1,4 @@
1
1
  import '../MsgMessage/MsgMessage.js';
2
2
  import '../MsgInterface/MsgInterface.js';
3
- export { MsgResource, MsgResourceData } from '../index.js';
3
+ export { MsgResource, MsgResourceData, MsgTree, MsgTreeNode } from '../index.js';
4
4
  import 'messageformat';
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  MsgResource
3
- } from "../../chunk-VDOVMTPF.mjs";
3
+ } from "../../chunk-HQMBNFN5.mjs";
4
4
  import "../../chunk-GHDKBE4P.mjs";
5
5
  import "../../chunk-RMZ42XIY.mjs";
6
6
  import "../../chunk-QU3HGZUN.mjs";