@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/dist/index.cjs CHANGED
@@ -261,16 +261,52 @@ function pseudoLocalize(source, format, options) {
261
261
  }
262
262
 
263
263
  // src/classes/MsgResource/MsgResource.ts
264
+ function branchPrefixes(key) {
265
+ const prefixes = [];
266
+ for (let i = key.indexOf("."); i !== -1; i = key.indexOf(".", i + 1)) {
267
+ prefixes.push(key.slice(0, i));
268
+ }
269
+ return prefixes;
270
+ }
264
271
  var MsgResource = class _MsgResource extends Map {
265
272
  _attributes = {};
266
273
  _notes = [];
267
274
  _title;
268
275
  _project;
276
+ /**
277
+ * For every key prefix that is a branch in the tree (`a` and `a.b` for key
278
+ * `a.b.c`), how many stored keys pass through it. Keeps collision checks
279
+ * proportional to key depth instead of resource size.
280
+ */
281
+ _branches = /* @__PURE__ */ new Map();
269
282
  /**
270
283
  * Builds a resource from {@link MsgResourceData} and an owning project.
271
284
  *
272
285
  * When `messages` is provided, each entry is added to the resource.
273
286
  * When omitted, the resource starts empty.
287
+ *
288
+ * **Typed keys are opt-in with `as const`.** When `messages` (or the whole
289
+ * definition) is `as const`, the resource's key type is the union of its
290
+ * message keys, so `get()`, `has()` and `toTree()` reject unknown keys.
291
+ * Without `as const` the key type is `string`, exactly as before, so a
292
+ * resource can keep growing through `add()`.
293
+ *
294
+ * ```ts
295
+ * const typed = MsgResource.create({
296
+ * title: 'Home',
297
+ * attributes: { lang: 'en' },
298
+ * messages: [{ key: 'home.title', value: 'Welcome' }] as const
299
+ * }, project);
300
+ * typed.get('home.titel'); // compile error
301
+ * ```
302
+ *
303
+ * `as const` data is a tuple, so inference also scales to large resources:
304
+ * up to TypeScript's ~10,000-element tuple limit.
305
+ *
306
+ * @typeParam M - The message list; its `key` types become the resource's
307
+ * key type.
308
+ * @throws {TypeError} When one key is a dot-separated prefix of another
309
+ * (for example `a` and `a.b`).
274
310
  */
275
311
  static create(data, project) {
276
312
  const { title, attributes, notes, messages } = data;
@@ -278,7 +314,7 @@ var MsgResource = class _MsgResource extends Map {
278
314
  if (messages) {
279
315
  messages.forEach((messageData) => {
280
316
  const { key, value, attributes: attributes2, notes: notes2 } = messageData;
281
- res.add(key, value, attributes2, notes2);
317
+ res.add(key, value, attributes2, notes2 && [...notes2]);
282
318
  });
283
319
  } else {
284
320
  res.clear();
@@ -361,7 +397,14 @@ var MsgResource = class _MsgResource extends Map {
361
397
  /**
362
398
  * Adds a message to this resource, merging resource attributes with any overrides.
363
399
  *
400
+ * Unspecified `lang`, `dir`, and `dnt` inherit from this resource; explicit
401
+ * values on the message win.
402
+ *
403
+ * Accepts any string key and does not change the resource's key type.
404
+ *
364
405
  * @returns This resource, for chaining.
406
+ * @throws {TypeError} When `key` and an existing key are dot-separated
407
+ * prefixes of one another (for example `a` and `a.b`).
365
408
  */
366
409
  add(key, value, attributes, notes) {
367
410
  const merged = { ...this.attributes, ...attributes };
@@ -374,11 +417,89 @@ var MsgResource = class _MsgResource extends Map {
374
417
  this.set(key, msg);
375
418
  return this;
376
419
  }
420
+ /**
421
+ * Stores a message under `key`.
422
+ *
423
+ * @throws {TypeError} When `key` and an existing key are dot-separated
424
+ * prefixes of one another (for example `a` and `a.b`), since a tree node
425
+ * cannot be both a message and a branch.
426
+ */
427
+ set(key, value) {
428
+ if (!this.has(key)) {
429
+ this.assertNoCollision(key);
430
+ this.updateBranches(key, 1);
431
+ }
432
+ return super.set(key, value);
433
+ }
434
+ /** Removes the message stored under `key`. */
435
+ delete(key) {
436
+ const deleted = super.delete(key);
437
+ if (deleted) {
438
+ this.updateBranches(key, -1);
439
+ }
440
+ return deleted;
441
+ }
442
+ /** Removes every message from this resource. */
443
+ clear() {
444
+ super.clear();
445
+ this._branches.clear();
446
+ }
447
+ /**
448
+ * Throws when `key` would be both a message and a branch in the tree.
449
+ */
450
+ assertNoCollision(key) {
451
+ if (this._branches.has(key)) {
452
+ const descendant = [...this.keys()].find((existing) => existing.startsWith(`${key}.`));
453
+ throw new TypeError(`Message key "${key}" collides with "${descendant}": a key cannot also be a prefix of another key.`);
454
+ }
455
+ const leaf = branchPrefixes(key).find((prefix) => this.has(prefix));
456
+ if (leaf !== void 0) {
457
+ throw new TypeError(`Message key "${key}" collides with "${leaf}": a key cannot also be a prefix of another key.`);
458
+ }
459
+ }
460
+ /**
461
+ * Adds `delta` to the count of every branch `key` passes through,
462
+ * dropping branches that no key uses any more.
463
+ */
464
+ updateBranches(key, delta) {
465
+ for (const prefix of branchPrefixes(key)) {
466
+ const count = (this._branches.get(prefix) ?? 0) + delta;
467
+ if (count > 0) {
468
+ this._branches.set(prefix, count);
469
+ } else {
470
+ this._branches.delete(prefix);
471
+ }
472
+ }
473
+ }
474
+ /**
475
+ * Returns a nested, read-only view of this resource's messages, splitting
476
+ * keys on `.`: `resource.toTree().home.cta.label` is the message stored
477
+ * under `'home.cta.label'`.
478
+ *
479
+ * The key type comes from `this` rather than the class parameter so that a
480
+ * typed resource stays assignable to a plain `MsgResource`.
481
+ */
482
+ toTree() {
483
+ const root = /* @__PURE__ */ Object.create(null);
484
+ for (const [key, msg] of this) {
485
+ const segments = key.split(".");
486
+ const leaf = segments.pop();
487
+ let node = root;
488
+ for (const segment of segments) {
489
+ node = node[segment] ??= /* @__PURE__ */ Object.create(null);
490
+ }
491
+ node[leaf] = msg;
492
+ }
493
+ return root;
494
+ }
377
495
  /**
378
496
  * Builds a translated copy of this resource from translation data.
379
497
  *
380
498
  * Messages present in the translation replace the source; missing keys keep
381
- * the source message. Notes are carried over from the source.
499
+ * the source message. Keys that are not in this resource are ignored, so the
500
+ * translated resource has the same keys (and key type) as the source. Notes
501
+ * are carried over from the source. Unspecified message `lang`, `dir`, and
502
+ * `dnt` inherit from the translated resource.
382
503
  *
383
504
  * @throws {TypeError} When the translation title does not match this resource.
384
505
  */
@@ -387,29 +508,29 @@ var MsgResource = class _MsgResource extends Map {
387
508
  if (title !== this.title) {
388
509
  throw new TypeError("Title of resource and translations do not match.");
389
510
  }
390
- const translated = _MsgResource.create({
511
+ const translated = new _MsgResource(
391
512
  title,
392
513
  // preserve the source resource's format unless the translation overrides it
393
- attributes: this.preserveFormat(attributes, this.attributes.format),
394
- notes: this.notes
514
+ this.preserveFormat(attributes, this.attributes.format),
515
+ this._project,
516
+ this.notes
395
517
  // transfer the notes
396
- }, this._project);
397
- this.forEach((msg) => {
398
- translated.set(msg.key, msg);
518
+ );
519
+ this.forEach((msg, key) => {
520
+ translated.set(key, msg);
399
521
  });
400
522
  messages?.forEach((messageData) => {
401
523
  const { key, value, attributes: attributes2 } = messageData;
402
- const msg = MsgMessage.create({
524
+ const source = this.get(key);
525
+ if (!source) {
526
+ return;
527
+ }
528
+ translated.add(
403
529
  key,
404
530
  value,
405
- // preserve the source message's format unless the translation overrides it
406
- attributes: this.preserveFormat(attributes2, this.get(key)?.attributes.format)
407
- });
408
- const notes = this.get(key)?.notes || [];
409
- notes.forEach((note) => {
410
- msg.addNote(note.type, note.content);
411
- });
412
- translated.set(key, msg);
531
+ this.preserveFormat(attributes2, source.attributes.format),
532
+ source.notes
533
+ );
413
534
  });
414
535
  return translated;
415
536
  }
@@ -438,8 +559,8 @@ var MsgResource = class _MsgResource extends Map {
438
559
  const project = this._project;
439
560
  const pseudoLocale = project.locales.pseudoLocale;
440
561
  if (lang2 === pseudoLocale) {
441
- const messages = [...this.values()].map((msg) => ({
442
- key: msg.key,
562
+ const messages = [...this.entries()].map(([key, msg]) => ({
563
+ key,
443
564
  value: pseudoLocalize(msg.value, this.resolveFormat(msg.attributes)),
444
565
  attributes: { ...msg.attributes, lang: pseudoLocale }
445
566
  }));
@@ -479,16 +600,16 @@ var MsgResource = class _MsgResource extends Map {
479
600
  const resourceFormat = this.resolveFormat(this.attributes);
480
601
  const projectFormat = this._project.format;
481
602
  const messages = [];
482
- this.forEach((msg) => {
603
+ this.forEach((msg, key) => {
483
604
  if (this.hasMatchingAttributes(msg)) {
484
605
  const data = {
485
- key: msg.key,
606
+ key,
486
607
  value: msg.value,
487
608
  notes: !stripNotes && msg.notes.length > 0 ? msg.notes : void 0
488
609
  };
489
610
  messages.push(data);
490
611
  } else {
491
- const data = msg.getData(stripNotes);
612
+ const data = { ...msg.getData(stripNotes), key };
492
613
  if (data.attributes && this.resolveFormat(data.attributes) === resourceFormat) {
493
614
  const { format, ...rest } = data.attributes;
494
615
  data.attributes = rest;
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { DEFAULT_ATTRIBUTES, MSG_DEFAULT_FORMAT, MsgAttributes, MsgFormat, MsgInterface, MsgNote, NoteTypes } from './classes/MsgInterface/MsgInterface.cjs';
2
2
  export { MsgMessage, MsgMessageData } from './classes/MsgMessage/MsgMessage.cjs';
3
- export { MsgLocalesSettings, MsgProject, MsgProjectData, MsgProjectSettings, MsgResource, MsgResourceData, MsgTargetLocalesSettings, MsgTranslationLoader } from './classes/index.cjs';
3
+ export { MsgLocalesSettings, MsgProject, MsgProjectData, MsgProjectSettings, MsgResource, MsgResourceData, MsgTargetLocalesSettings, MsgTranslationLoader, MsgTree, MsgTreeNode } from './classes/index.cjs';
4
4
  export { getLang, setLang } from './lib/lang-utils.cjs';
5
5
  export { PseudoLocalizeOptions, pseudoLocalize, pseudoLocalizeMF1, pseudoLocalizeMF2, pseudoLocalizeNone } from './lib/pseudo-localize.cjs';
6
6
  import 'messageformat';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { DEFAULT_ATTRIBUTES, MSG_DEFAULT_FORMAT, MsgAttributes, MsgFormat, MsgInterface, MsgNote, NoteTypes } from './classes/MsgInterface/MsgInterface.js';
2
2
  export { MsgMessage, MsgMessageData } from './classes/MsgMessage/MsgMessage.js';
3
- export { MsgLocalesSettings, MsgProject, MsgProjectData, MsgProjectSettings, MsgResource, MsgResourceData, MsgTargetLocalesSettings, MsgTranslationLoader } from './classes/index.js';
3
+ export { MsgLocalesSettings, MsgProject, MsgProjectData, MsgProjectSettings, MsgResource, MsgResourceData, MsgTargetLocalesSettings, MsgTranslationLoader, MsgTree, MsgTreeNode } from './classes/index.js';
4
4
  export { getLang, setLang } from './lib/lang-utils.js';
5
5
  export { PseudoLocalizeOptions, pseudoLocalize, pseudoLocalizeMF1, pseudoLocalizeMF2, pseudoLocalizeNone } from './lib/pseudo-localize.js';
6
6
  import 'messageformat';
package/dist/index.mjs CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-DJFPVXQ5.mjs";
5
5
  import {
6
6
  MsgResource
7
- } from "./chunk-VDOVMTPF.mjs";
7
+ } from "./chunk-HQMBNFN5.mjs";
8
8
  import "./chunk-KI3KVHLZ.mjs";
9
9
  import {
10
10
  getLang,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@worldware/msg",
3
- "version": "0.11.1",
3
+ "version": "0.13.0",
4
4
  "description": "Message localization tooling",
5
5
  "license": "MIT",
6
6
  "author": "Joel Sahleen",