@gram-lang/i18n 1.4.2 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -21,14 +21,14 @@ function compileDictionary(dictionaries2) {
21
21
  // src/time.ts
22
22
  var en = {
23
23
  d: ["day", "days"],
24
- h: ["hour", "hours"],
24
+ h: ["hr", "hrs", "hour", "hours"],
25
25
  m: ["min", "mins", "minute", "minutes"],
26
26
  s: ["sec", "secs", "second", "seconds"]
27
27
  };
28
28
  var fr = {
29
29
  d: ["j", "jour", "jours"],
30
30
  h: ["heure", "heures"],
31
- m: ["min", "mins", "minute", "minutes"],
31
+ m: ["min", "mn", "mins", "minute", "minutes"],
32
32
  s: ["sec", "secs", "seconde", "secondes"]
33
33
  };
34
34
  var TIME_DICTIONARIES = { en, fr };
@@ -184,6 +184,51 @@ var UNIT_CONVERSIONS = {
184
184
  }
185
185
  }
186
186
  };
187
+ var UNIT_LADDERS = [
188
+ {
189
+ id: "usVolume",
190
+ family: "volume",
191
+ steps: { tsp: 1, tbsp: 3, "fl oz": 6, cup: 48, pt: 96, qt: 192, gal: 768 }
192
+ },
193
+ { id: "imperialMass", family: "mass", steps: { oz: 1, lb: 16 } },
194
+ {
195
+ id: "metricMass",
196
+ family: "mass",
197
+ // The French "livre" is the metric pound: exactly 500 g.
198
+ steps: { mg: 1, g: 1e3, livre: 5e5, kg: 1e6 }
199
+ },
200
+ {
201
+ id: "metricVolume",
202
+ family: "volume",
203
+ // The French "tasse" holds exactly 250 ml.
204
+ steps: { ml: 1, cl: 10, dl: 100, tasse: 250, l: 1e3 }
205
+ }
206
+ ];
207
+ function ladderOf(rawUnit, lang) {
208
+ const unit = normalizeUnit(rawUnit, lang);
209
+ if (!unit) return null;
210
+ for (const ladder of UNIT_LADDERS) {
211
+ const size = ladder.steps[unit];
212
+ if (size !== void 0) return { ladder, unit, size };
213
+ }
214
+ return null;
215
+ }
216
+ function sameLadder(rawUnits, lang) {
217
+ if (rawUnits.length === 0) return false;
218
+ let id;
219
+ for (const raw of rawUnits) {
220
+ const step = ladderOf(raw, lang);
221
+ if (!step) return false;
222
+ if (id !== void 0 && step.ladder.id !== id) return false;
223
+ id = step.ladder.id;
224
+ }
225
+ return true;
226
+ }
227
+ var UNIT_SPELLINGS = { fr: { tsp: "c\xE0c", tbsp: "c\xE0s" } };
228
+ function unitSpelling(canonical, lang) {
229
+ const base = lang?.toLowerCase().split("-")[0];
230
+ return base && UNIT_SPELLINGS[base]?.[canonical] || canonical;
231
+ }
187
232
  function normalizeUnit(rawUnit, lang) {
188
233
  if (!rawUnit) return "";
189
234
  const clean = rawUnit.toLowerCase().trim();
@@ -225,6 +270,44 @@ function toLargerMetricUnit(value, rawUnit, lang) {
225
270
  }
226
271
  return { value, unit };
227
272
  }
273
+ function convertUnitInFamily(value, fromUnit, toUnit, lang) {
274
+ const from = normalizeUnit(fromUnit, lang);
275
+ const to = normalizeUnit(toUnit, lang);
276
+ if (from === to) return value;
277
+ for (const family of [UNIT_CONVERSIONS.mass, UNIT_CONVERSIONS.volume]) {
278
+ const fromFactor = family.map[from];
279
+ const toFactor = family.map[to];
280
+ if (fromFactor !== void 0 && toFactor !== void 0) {
281
+ return value * fromFactor / toFactor;
282
+ }
283
+ }
284
+ return null;
285
+ }
286
+ var PIECE_UNITS = /* @__PURE__ */ new Set([
287
+ "pi\xE8ce",
288
+ "pi\xE8ces",
289
+ "piece",
290
+ "pieces",
291
+ "pc",
292
+ "pcs",
293
+ "unit\xE9",
294
+ "unit\xE9s",
295
+ "unit",
296
+ "units"
297
+ ]);
298
+ function sameCountUnit(a, b, lang) {
299
+ if (isMeasureUnit(a, lang) || isMeasureUnit(b, lang)) return false;
300
+ const countForm = (unit) => {
301
+ const form = normalizeUnit(unit, lang);
302
+ return PIECE_UNITS.has(form) ? "" : form;
303
+ };
304
+ const x = countForm(a);
305
+ const y = countForm(b);
306
+ if (x === y) return true;
307
+ const [short, long] = x.length <= y.length ? [x, y] : [y, x];
308
+ if (short.length < 3) return false;
309
+ return ["s", "es", "x"].some((ending) => long === short + ending);
310
+ }
228
311
  function isMeasureUnit(rawUnit, lang) {
229
312
  const canonical = normalizeUnit(rawUnit, lang);
230
313
  return UNIT_CONVERSIONS.mass.map[canonical] !== void 0 || UNIT_CONVERSIONS.volume.map[canonical] !== void 0;
@@ -263,12 +346,27 @@ function formatter(lang, maxDecimals) {
263
346
  function formatNumber(value, lang, maxDecimals = 2) {
264
347
  return formatter(lang, maxDecimals).format(value);
265
348
  }
349
+ function amountDecimals(value) {
350
+ const size = Math.abs(value);
351
+ if (size === 0 || !Number.isFinite(size)) return 0;
352
+ const magnitude = Math.floor(Math.log10(size));
353
+ if (magnitude >= 0) return Math.max(0, 2 - magnitude);
354
+ return Math.min(1 - magnitude, 6);
355
+ }
356
+ function roundAmount(value) {
357
+ return Number(value.toFixed(amountDecimals(value)));
358
+ }
359
+ function formatAmount(value, lang) {
360
+ return formatNumber(value, lang, amountDecimals(value));
361
+ }
266
362
  function decimalSeparator(lang) {
267
363
  return formatter(lang, 1).formatToParts(1.5).find((part) => part.type === "decimal")?.value ?? ".";
268
364
  }
269
365
  function localizeDecimals(text, lang) {
270
- const separator = decimalSeparator(lang);
271
- return separator === "." ? text : text.replace(/(\d)\.(\d)/g, `$1${separator}$2`);
366
+ return text.replace(/(\d)[.,](\d)/g, `$1${decimalSeparator(lang)}$2`);
367
+ }
368
+ function looksLikeThousands(text) {
369
+ return /(?<![\d.,])(?!0+,)\d{1,3},\d{3}(?![\d.,])/.test(text);
272
370
  }
273
371
  var COMMON_FRACTIONS = [
274
372
  { value: 0.5, text: "1/2" },
@@ -541,6 +639,11 @@ var en3 = {
541
639
  runSheetInStock: "in stock",
542
640
  runSheetProgramStep: "step {n}",
543
641
  runSheetProgramSteps: "steps {from} to {to}",
642
+ /**
643
+ * @deprecated Since 1.5.0, will be removed in 2.0.0. (Ref: i18n-run-sheet-range)
644
+ * The run sheet writes a range with `formatDurationRange` (`8–16 h`), as the steps do.
645
+ */
646
+ // @remove-in: 2.0.0 [i18n-run-sheet-range]
544
647
  runSheetRange: "{min} to {max}",
545
648
  runSheetPossibleFrom: "Possible from {time}.",
546
649
  runSheetFixedService: "Can't start earlier: the \u201C{rest}\u201D wait ({section}) can't be longer than {length} and ends when you serve.",
@@ -591,13 +694,17 @@ var en3 = {
591
694
  tooltipBakers: "Baker's %",
592
695
  tooltipTakenFrom: "Taken from",
593
696
  alternatives: "Alternatives",
697
+ // A ratio with units (`1 / 100 g @&flour`): its tooltip row, and either
698
+ // relative form (`70%`, `1 / 100 g`) while it stays unresolved.
699
+ tooltipRatio: "Ratio",
700
+ relativeOf: "{amount} of {target}",
594
701
  // The deprecated portions stepper of the HTML recipe (`interactiveScaling`).
595
702
  // @remove-in: 2.0.0 [renderer-interactive-scaling]
596
703
  decreasePortions: "Decrease portions",
597
704
  editPortions: "Edit portions directly",
598
705
  increasePortions: "Increase portions",
599
706
  returnToStep: "Return to step",
600
- mixedUnitsTooltip: "Couldn't be combined into one total \u2014 add a density to the ingredient database to merge them",
707
+ mixedUnitsTooltip: "Mixed units: couldn't be combined into one total \u2014 add a density to the ingredient database to merge them",
601
708
  mixedUnits: "Mixed units",
602
709
  copyShoppingList: "Copy list",
603
710
  copied: "Copied!",
@@ -775,6 +882,10 @@ var en3 = {
775
882
  stepQuantitiesDesc: "Writes the quantity of each ingredient in the text of the steps, after its name.",
776
883
  nutritionBasis: "Nutrition basis",
777
884
  nutritionBasisAuto: "Automatic (every basis, side by side)",
885
+ clock: "Time format",
886
+ clockAuto: "Automatic (as your region writes it)",
887
+ clock12h: "12 hours (1:00 PM)",
888
+ clock24h: "24 hours (13:00)",
778
889
  rejectedSlots: "Unavailable slots:",
779
890
  forceReference: "Force Reference:",
780
891
  autoDetect: "Auto (detect @*)",
@@ -798,6 +909,7 @@ var en3 = {
798
909
  scaleByIngredient: "Proportionally recalculates the entire recipe to match the exact quantity you have on hand for a specific ingredient (e.g. only 3 eggs or 250g of butter).",
799
910
  bakersMath: "Expresses each ingredient as a percentage of a base ingredient set at 100% (typically flour, or any chosen ingredient), making ratios and formulation easy to evaluate.",
800
911
  comments: "Shows or leaves out the comments written in the recipe with //: the notes alone on a line and the ones at the end of a line. They are set apart discreetly in the run sheet.",
912
+ clock: "How the run sheet and the suggested serving times write the time. Automatic follows your browser's region.",
801
913
  stepQuantities: "Writes each quantity in the step that uses it, with its weight in grams when the masses are standardized. Leave it off for shorter steps: the quantities stay in the ingredient lists.",
802
914
  nutritionBasis: "Which basis the nutrition panel shows, when the nutrition is estimated. Automatic shows per 100 g and per portion side by side, with the whole recipe under them, in every recipe format.",
803
915
  bakersMathOnly: "Hides gram weights to display only relative percentages, turning the recipe into a pure ratio formula.",
@@ -831,7 +943,9 @@ var en3 = {
831
943
  item: "Item",
832
944
  show: "Show",
833
945
  expandConsole: "Expand console",
834
- collapseConsole: "Collapse console"
946
+ collapseConsole: "Collapse console",
947
+ notInDatabase: "Not in the example database.",
948
+ showDatabase: "See the database"
835
949
  },
836
950
  errorState: {
837
951
  title: VIEWS_PAUSED.title,
@@ -839,6 +953,12 @@ var en3 = {
839
953
  jumpToError: "Jump to error",
840
954
  line: "Line"
841
955
  },
956
+ database: {
957
+ tabLabel: "Ingredient database, read-only",
958
+ project: "In a project, this is your own ingredients.yaml, which the CLI fills for you. Here it is read-only.",
959
+ docLink: "How to manage an ingredient database",
960
+ docHref: "/docs/how-to/manage-database"
961
+ },
842
962
  tabs: {
843
963
  addFile: "Add file",
844
964
  removeFile: "Remove file",
@@ -863,6 +983,18 @@ var en3 = {
863
983
  statusValid: "Valid",
864
984
  statusWarnings: "Warnings",
865
985
  copyBtn: "Copy to Clipboard"
986
+ },
987
+ cook: {
988
+ /** Under a step of `gram cook`: the state that ends it (`={ribbon stage}`). */
989
+ targetState: "Target:",
990
+ /** When a timer of a step rings: the target states to check, `{states}`. */
991
+ checkTargetState: "Check: {states}"
992
+ },
993
+ languageServer: {
994
+ /** Hover on a section anchor: `{duration}` is the anticipation. */
995
+ anchorReady: "Ready {duration} before it is used.",
996
+ anchorInDays: "In days: opens a working day of its own.",
997
+ anchorInHours: "In hours or minutes: a deadline within the day, no working day of its own."
866
998
  }
867
999
  };
868
1000
 
@@ -992,6 +1124,7 @@ var fr3 = {
992
1124
  runSheetInStock: "en stock",
993
1125
  runSheetProgramStep: "\xE9tape {n}",
994
1126
  runSheetProgramSteps: "\xE9tapes {from} \xE0 {to}",
1127
+ // @remove-in: 2.0.0 [i18n-run-sheet-range]
995
1128
  runSheetRange: "{min} \xE0 {max}",
996
1129
  runSheetPossibleFrom: "Possible d\xE8s {time}.",
997
1130
  runSheetFixedService: "D\xE9but non avan\xE7able : l'attente \xAB {rest} \xBB ({section}) ne peut pas d\xE9passer {length} et se termine au service.",
@@ -1042,13 +1175,18 @@ var fr3 = {
1042
1175
  tooltipBakers: "% boulanger",
1043
1176
  tooltipTakenFrom: "Pr\xE9lev\xE9 sur",
1044
1177
  alternatives: "Alternatives",
1178
+ // Une proportion avec unités (`1 / 100 g @&farine`) : sa ligne dans la
1179
+ // bulle, et les deux formes relatives (`70 %`, `1 / 100 g`) tant
1180
+ // qu'elles ne sont pas calculées.
1181
+ tooltipRatio: "Proportion",
1182
+ relativeOf: "{amount} de {target}",
1045
1183
  // The deprecated portions stepper of the HTML recipe (`interactiveScaling`).
1046
1184
  // @remove-in: 2.0.0 [renderer-interactive-scaling]
1047
1185
  decreasePortions: "Diminuer les portions",
1048
1186
  editPortions: "Modifier directement les portions",
1049
1187
  increasePortions: "Augmenter les portions",
1050
1188
  returnToStep: "Retour \xE0 l'\xE9tape",
1051
- mixedUnitsTooltip: "Impossible de fusionner en un seul total \u2014 ajoutez une densit\xE9 \xE0 la base de donn\xE9es pour les convertir",
1189
+ mixedUnitsTooltip: "Unit\xE9s mixtes : impossible de fusionner en un seul total \u2014 ajoutez une densit\xE9 \xE0 la base de donn\xE9es pour les convertir",
1052
1190
  mixedUnits: "Unit\xE9s mixtes",
1053
1191
  copyShoppingList: "Copier la liste",
1054
1192
  copied: "Copi\xE9 !",
@@ -1210,6 +1348,10 @@ var fr3 = {
1210
1348
  stepQuantitiesDesc: "\xC9crit la quantit\xE9 de chaque ingr\xE9dient dans le texte des \xE9tapes, juste apr\xE8s son nom.",
1211
1349
  nutritionBasis: "Base nutritionnelle",
1212
1350
  nutritionBasisAuto: "Automatique (toutes les bases c\xF4te \xE0 c\xF4te)",
1351
+ clock: "Format de l'heure",
1352
+ clockAuto: "Automatique (selon votre r\xE9gion)",
1353
+ clock12h: "12 heures (1:00 PM)",
1354
+ clock24h: "24 heures (13:00)",
1213
1355
  rejectedSlots: "Cr\xE9neaux non retenus :",
1214
1356
  forceReference: "Forcer la r\xE9f\xE9rence :",
1215
1357
  autoDetect: "Auto (d\xE9tecte @*)",
@@ -1233,6 +1375,7 @@ var fr3 = {
1233
1375
  scaleByIngredient: "Recalcule proportionnellement toute la recette pour l'ajuster \xE0 la quantit\xE9 exacte dont vous disposez pour un ingr\xE9dient donn\xE9 (ex. seulement 3 \u0153ufs ou 250 g de beurre).",
1234
1376
  bakersMath: "Exprime chaque ingr\xE9dient en pourcentage d'un ingr\xE9dient de base fix\xE9 \xE0 100 % (par d\xE9faut la farine, ou l'ingr\xE9dient de votre choix), facilitant l'\xE9valuation des \xE9quilibres et des ratios.",
1235
1377
  comments: "Affiche ou masque les commentaires \xE9crits dans la recette avec // : les notes seules sur une ligne et celles en fin de ligne. Dans le plan de marche, ils sont mis \xE0 part, discr\xE8tement.",
1378
+ clock: "La fa\xE7on d'\xE9crire l'heure dans le plan de marche et les horaires sugg\xE9r\xE9s. En automatique, elle suit la r\xE9gion de votre navigateur.",
1236
1379
  stepQuantities: "Rappelle chaque quantit\xE9 dans l'\xE9tape qui l'utilise, avec son poids en grammes si les masses sont standardis\xE9es. D\xE9cochez pour des \xE9tapes plus courtes : les quantit\xE9s restent dans les listes d'ingr\xE9dients.",
1237
1380
  nutritionBasis: "La base du panneau nutritionnel, quand la nutrition est estim\xE9e. En automatique, pour 100 g et par portion c\xF4te \xE0 c\xF4te, la recette enti\xE8re en dessous, dans tous les formats de la recette.",
1238
1381
  bakersMathOnly: "Masque les poids en grammes pour n'afficher que les pourcentages relatifs, transformant la recette en une formule de proportions pure.",
@@ -1263,7 +1406,9 @@ var fr3 = {
1263
1406
  item: "\xC9l\xE9ment",
1264
1407
  show: "Afficher",
1265
1408
  expandConsole: "D\xE9velopper la console",
1266
- collapseConsole: "R\xE9duire la console"
1409
+ collapseConsole: "R\xE9duire la console",
1410
+ notInDatabase: "Absent de la base d'exemple.",
1411
+ showDatabase: "Voir la base"
1267
1412
  },
1268
1413
  errorState: {
1269
1414
  title: VIEWS_PAUSED2.title,
@@ -1271,6 +1416,12 @@ var fr3 = {
1271
1416
  jumpToError: "Aller \xE0 l'erreur",
1272
1417
  line: "Ligne"
1273
1418
  },
1419
+ database: {
1420
+ tabLabel: "Base d'ingr\xE9dients, en lecture seule",
1421
+ project: "Base d'exemple en lecture seule. Dans un projet, ce fichier ingredients.yaml est le v\xF4tre (modifiable \xE0 la main ou aid\xE9 par le CLI).",
1422
+ docLink: "G\xE9rer sa base de donn\xE9es d'ingr\xE9dients",
1423
+ docHref: "/fr/docs/how-to/manage-database"
1424
+ },
1274
1425
  tabs: {
1275
1426
  addFile: "Ajouter un fichier",
1276
1427
  removeFile: "Supprimer le fichier",
@@ -1295,6 +1446,15 @@ var fr3 = {
1295
1446
  statusValid: "Valide",
1296
1447
  statusWarnings: "Avertissements",
1297
1448
  copyBtn: "Copier dans le presse-papier"
1449
+ },
1450
+ cook: {
1451
+ targetState: "\xC9tat attendu :",
1452
+ checkTargetState: "V\xE9rifiez : {states}"
1453
+ },
1454
+ languageServer: {
1455
+ anchorReady: "Pr\xEAte {duration} avant d'\xEAtre utilis\xE9e.",
1456
+ anchorInDays: "En jours : ouvre sa propre journ\xE9e de travail.",
1457
+ anchorInHours: "En heures ou en minutes : une \xE9ch\xE9ance dans la journ\xE9e, sans journ\xE9e de travail \xE0 part."
1298
1458
  }
1299
1459
  };
1300
1460
 
@@ -1316,8 +1476,777 @@ function fillTemplate(template, values) {
1316
1476
  (whole, key) => Object.hasOwn(values, key) ? values[key] : whole
1317
1477
  );
1318
1478
  }
1479
+
1480
+ // src/duration.ts
1481
+ var FRACTION_GLYPHS = {
1482
+ "\xBC": 1 / 4,
1483
+ "\xBD": 1 / 2,
1484
+ "\xBE": 3 / 4,
1485
+ "\u2153": 1 / 3,
1486
+ "\u2154": 2 / 3,
1487
+ "\u2155": 1 / 5,
1488
+ "\u2156": 2 / 5,
1489
+ "\u2157": 3 / 5,
1490
+ "\u2158": 4 / 5,
1491
+ "\u2159": 1 / 6,
1492
+ "\u215A": 5 / 6,
1493
+ "\u215B": 1 / 8,
1494
+ "\u215C": 3 / 8,
1495
+ "\u215D": 5 / 8,
1496
+ "\u215E": 7 / 8
1497
+ };
1498
+ var MINUTE_PRIMES = /* @__PURE__ */ new Set(["'", "\u2019", "\u2032"]);
1499
+ var SECOND_PRIMES = /* @__PURE__ */ new Set(['"', "\u201D", "\u2033"]);
1500
+ var DASHES = /* @__PURE__ */ new Set(["-", "\u2013"]);
1501
+ var STARS = /* @__PURE__ */ new Set(["*", "\xD7"]);
1502
+ var isDigit = (c) => c !== void 0 && c >= "0" && c <= "9";
1503
+ var isLetter = (c) => c !== void 0 && /[\p{L}\p{M}]/u.test(c);
1504
+ var ISO_8601 = /^p(?=\d|t\d)(\d+([.,]\d+)?[ymwd])*(t(\d+([.,]\d+)?[hms])+)?$/i;
1505
+ var resolveUnit = (word) => {
1506
+ const unit = TIME_GLOBAL[word];
1507
+ return unit !== void 0 && unit in TIME_TO_MINUTES ? unit : void 0;
1508
+ };
1509
+ function tokenizeDuration(text) {
1510
+ const s = text.normalize("NFC");
1511
+ const tokens = [];
1512
+ let space = false;
1513
+ let i = 0;
1514
+ while (i < s.length) {
1515
+ const c = s[i];
1516
+ if (/\s/u.test(c)) {
1517
+ space = true;
1518
+ i++;
1519
+ continue;
1520
+ }
1521
+ if (isDigit(c) || c in FRACTION_GLYPHS) {
1522
+ let j = i;
1523
+ while (isDigit(s[j])) j++;
1524
+ let num = "int";
1525
+ let value;
1526
+ if ((s[j] === "." || s[j] === ",") && isDigit(s[j + 1])) {
1527
+ j++;
1528
+ while (isDigit(s[j])) j++;
1529
+ num = "decimal";
1530
+ value = Number(s.slice(i, j).replace(",", "."));
1531
+ } else if (s[j] === "/" && j > i && isDigit(s[j + 1])) {
1532
+ const slash = j;
1533
+ j++;
1534
+ while (isDigit(s[j])) j++;
1535
+ const den = Number(s.slice(slash + 1, j));
1536
+ if (den === 0) return { ok: false, reason: "unexpected" };
1537
+ num = "fraction";
1538
+ value = Number(s.slice(i, slash)) / den;
1539
+ } else if (s[j] !== void 0 && s[j] in FRACTION_GLYPHS) {
1540
+ const whole = j > i ? Number(s.slice(i, j)) : 0;
1541
+ value = whole + FRACTION_GLYPHS[s[j]];
1542
+ j++;
1543
+ num = "fraction";
1544
+ } else {
1545
+ value = Number(s.slice(i, j));
1546
+ }
1547
+ tokens.push({ kind: "num", value, text: s.slice(i, j), num, space });
1548
+ i = j;
1549
+ } else if (isLetter(c)) {
1550
+ let j = i;
1551
+ while (isLetter(s[j])) j++;
1552
+ const word = s.slice(i, j).toLowerCase();
1553
+ if (s[j] === ".") j++;
1554
+ tokens.push({ kind: "word", text: word, unit: resolveUnit(word) });
1555
+ i = j;
1556
+ } else if (MINUTE_PRIMES.has(c)) {
1557
+ if (MINUTE_PRIMES.has(s[i + 1])) {
1558
+ tokens.push({ kind: "prime", unit: "s" });
1559
+ i += 2;
1560
+ } else {
1561
+ tokens.push({ kind: "prime", unit: "m" });
1562
+ i++;
1563
+ }
1564
+ } else if (SECOND_PRIMES.has(c)) {
1565
+ tokens.push({ kind: "prime", unit: "s" });
1566
+ i++;
1567
+ } else if (c === ":") {
1568
+ tokens.push({ kind: "colon" });
1569
+ i++;
1570
+ } else if (c === "+") {
1571
+ tokens.push({ kind: "plus" });
1572
+ i++;
1573
+ } else if (DASHES.has(c)) {
1574
+ tokens.push({ kind: "dash" });
1575
+ i++;
1576
+ } else if (STARS.has(c)) {
1577
+ tokens.push({ kind: "star" });
1578
+ i++;
1579
+ } else {
1580
+ return { ok: false, reason: "unexpected" };
1581
+ }
1582
+ space = false;
1583
+ }
1584
+ return { ok: true, tokens: mergeMixedFractions(tokens) };
1585
+ }
1586
+ function mergeMixedFractions(tokens) {
1587
+ const out = [];
1588
+ for (const token of tokens) {
1589
+ const prev = out[out.length - 1];
1590
+ if (token.kind === "num" && token.num === "fraction" && token.space && token.value < 1 && prev?.kind === "num" && prev.num === "int") {
1591
+ out[out.length - 1] = {
1592
+ ...prev,
1593
+ value: prev.value + token.value,
1594
+ text: `${prev.text} ${token.text}`,
1595
+ num: "fraction"
1596
+ };
1597
+ } else {
1598
+ out.push(token);
1599
+ }
1600
+ }
1601
+ return out;
1602
+ }
1603
+ var RANK = { d: 0, h: 1, m: 2, s: 3 };
1604
+ var IMPLIED = { h: "m", m: "s" };
1605
+ var partMinutes = ({ value, unit }) => unit === "s" ? value / 60 : value * TIME_TO_MINUTES[unit];
1606
+ var makeSide = (parts, form) => ({
1607
+ minutes: parts.reduce((sum, part) => sum + partMinutes(part), 0),
1608
+ parts,
1609
+ form
1610
+ });
1611
+ var fail = (reason) => ({ ok: false, reason });
1612
+ function analyzeSide(tokens) {
1613
+ if (tokens.some((t) => t.kind === "colon")) return analyzeClock(tokens);
1614
+ return analyzeTerms(tokens);
1615
+ }
1616
+ function analyzeClock(tokens) {
1617
+ const nums = [];
1618
+ let k = 0;
1619
+ for (; ; ) {
1620
+ const t = tokens[k];
1621
+ if (t?.kind !== "num") return fail("clockFormat");
1622
+ nums.push(t);
1623
+ k++;
1624
+ if (tokens[k]?.kind !== "colon") break;
1625
+ k++;
1626
+ }
1627
+ const rest = tokens.slice(k);
1628
+ const unitToken = rest[0];
1629
+ if (nums.length < 2 || nums.length > 3 || rest.length > 1 || unitToken && unitToken.kind !== "word") {
1630
+ return fail("clockFormat");
1631
+ }
1632
+ const [first, ...others] = nums;
1633
+ if (first.num !== "int") return fail("clockFormat");
1634
+ for (const n of others) {
1635
+ if (n.num !== "int" || n.text.length !== 2) return fail("clockFormat");
1636
+ }
1637
+ if (others.some((n) => n.value >= 60)) return fail("overflow60");
1638
+ const unit = unitToken?.kind === "word" ? unitToken.unit : void 0;
1639
+ const values = nums.map((n) => n.value);
1640
+ if (nums.length === 3) {
1641
+ if (unitToken && unit !== "h") return fail("clockFormat");
1642
+ const [h, m, s] = values;
1643
+ const parts = [
1644
+ { value: h, unit: "h" },
1645
+ { value: m, unit: "m" },
1646
+ { value: s, unit: "s" }
1647
+ ];
1648
+ return { kind: "side", side: makeSide(parts, "clock") };
1649
+ }
1650
+ if (!unitToken)
1651
+ return { kind: "bareClock", nums };
1652
+ if (unit !== "h" && unit !== "m") return fail("clockFormat");
1653
+ return {
1654
+ kind: "side",
1655
+ side: clockSide(values[0], values[1], unit),
1656
+ clockUnit: unit
1657
+ };
1658
+ }
1659
+ var clockSide = (a, b, unit) => makeSide(
1660
+ [
1661
+ { value: a, unit },
1662
+ { value: b, unit: unit === "h" ? "m" : "s" }
1663
+ ],
1664
+ "clock"
1665
+ );
1666
+ function analyzeTerms(tokens) {
1667
+ const parts = [];
1668
+ let primes = 0;
1669
+ let k = 0;
1670
+ while (k < tokens.length) {
1671
+ const num = tokens[k];
1672
+ if (num?.kind !== "num") return fail("unexpected");
1673
+ const next = tokens[k + 1];
1674
+ if (next?.kind !== "word" && next?.kind !== "prime") {
1675
+ if (next !== void 0) return fail("bareNumber");
1676
+ if (parts.length === 0) return { kind: "bare", num };
1677
+ const prev = tokens[k - 1];
1678
+ const last2 = parts[parts.length - 1];
1679
+ const implied = IMPLIED[last2.unit];
1680
+ if (prev?.kind === "plus" || !implied) return fail("bareNumber");
1681
+ if (num.num !== "int") return fail("decimalInCompound");
1682
+ if (num.value >= 60) return fail("overflow60");
1683
+ parts.push({ value: num.value, unit: implied });
1684
+ k++;
1685
+ break;
1686
+ }
1687
+ const unit = next.unit;
1688
+ const last = parts[parts.length - 1];
1689
+ if (next.kind === "prime") {
1690
+ if (num.num !== "int") return fail("decimalPrime");
1691
+ if (last && num.value >= 60) return fail("overflow60");
1692
+ primes++;
1693
+ }
1694
+ if (last) {
1695
+ if (last.unit === unit) return fail("duplicateUnit");
1696
+ if (RANK[last.unit] > RANK[unit]) return fail("unitOrder");
1697
+ }
1698
+ parts.push({ value: num.value, unit });
1699
+ k += 2;
1700
+ if (tokens[k]?.kind === "plus") {
1701
+ if (tokens[k + 1]?.kind !== "num") return fail("unexpected");
1702
+ k++;
1703
+ }
1704
+ }
1705
+ if (parts.length > 1 && tokens.some((t) => t.kind === "num" && t.num !== "int")) {
1706
+ return fail("decimalInCompound");
1707
+ }
1708
+ const terms = tokens.filter((t) => t.kind === "word" || t.kind === "prime");
1709
+ const side = makeSide(parts, primes === terms.length ? "prime" : "units");
1710
+ if (parts.length === 1) {
1711
+ const only = parts[0];
1712
+ return {
1713
+ kind: "side",
1714
+ side,
1715
+ single: { unit: only.unit, prime: primes === 1 }
1716
+ };
1717
+ }
1718
+ return { kind: "side", side };
1719
+ }
1720
+ function parseDuration(text) {
1721
+ const trimmed = text.trim();
1722
+ if (trimmed === "") return fail("empty");
1723
+ if (ISO_8601.test(trimmed.replace(/\s/gu, ""))) return fail("iso8601");
1724
+ const tokenized = tokenizeDuration(trimmed);
1725
+ if (!tokenized.ok) return tokenized;
1726
+ const { tokens } = tokenized;
1727
+ for (let k = 0; k < tokens.length; k++) {
1728
+ const t = tokens[k];
1729
+ const prev = tokens[k - 1];
1730
+ if (t.kind === "star") return fail("multiplication");
1731
+ if (t.kind !== "word") continue;
1732
+ if (t.text === "x" && prev?.kind === "num" && tokens[k + 1]?.kind === "num") {
1733
+ return fail("multiplication");
1734
+ }
1735
+ if (prev?.kind !== "num") return fail("words");
1736
+ if (!t.unit) return { ok: false, reason: "unknownUnit", unit: t.text };
1737
+ }
1738
+ const dashes = tokens.filter((t) => t.kind === "dash").length;
1739
+ if (dashes === 0) {
1740
+ const a = analyzeSide(tokens);
1741
+ if ("ok" in a) return a;
1742
+ if (a.kind === "bare") return fail("missingUnit");
1743
+ if (a.kind === "bareClock") return fail("ambiguousClock");
1744
+ return { ok: true, minutes: a.side.minutes, sides: [a.side] };
1745
+ }
1746
+ const dash = tokens.findIndex((t) => t.kind === "dash");
1747
+ const leftTokens = tokens.slice(0, dash);
1748
+ const rightTokens = tokens.slice(dash + 1);
1749
+ if (dashes > 1 || leftTokens.length === 0 || rightTokens.length === 0) {
1750
+ return fail("unexpected");
1751
+ }
1752
+ return parseRange(analyzeSide(leftTokens), analyzeSide(rightTokens));
1753
+ }
1754
+ function parseRange(left, right) {
1755
+ if ("ok" in left) return left;
1756
+ if ("ok" in right) return right;
1757
+ if (left.kind === "bare" && right.kind === "bare") return fail("missingUnit");
1758
+ if (left.kind === "bareClock" && right.kind === "bareClock") {
1759
+ return fail("ambiguousClock");
1760
+ }
1761
+ if (right.kind !== "side") return fail("ambiguousRange");
1762
+ let min;
1763
+ if (left.kind === "side") {
1764
+ min = left.side;
1765
+ } else if (left.kind === "bare") {
1766
+ const single = right.single;
1767
+ if (!single) return fail("ambiguousRange");
1768
+ if (single.prime && left.num.num !== "int") return fail("decimalPrime");
1769
+ min = makeSide(
1770
+ [{ value: left.num.value, unit: single.unit }],
1771
+ right.side.form
1772
+ );
1773
+ } else {
1774
+ const unit = right.clockUnit;
1775
+ if (unit !== "h" && unit !== "m") return fail("ambiguousRange");
1776
+ min = clockSide(left.nums[0].value, left.nums[1].value, unit);
1777
+ }
1778
+ const max = right.side;
1779
+ if (min.minutes > max.minutes) return fail("reversedRange");
1780
+ if (min.minutes === max.minutes) return fail("emptyRange");
1781
+ return {
1782
+ ok: true,
1783
+ minutes: (min.minutes + max.minutes) / 2,
1784
+ range: { min: min.minutes, max: max.minutes },
1785
+ sides: [min, max]
1786
+ };
1787
+ }
1788
+
1789
+ // src/quantity.ts
1790
+ function localSpelling(unit, lang) {
1791
+ const base = lang?.toLowerCase().split("-")[0];
1792
+ if (!unit || !base || base === "en") return false;
1793
+ const local = UNIT_DICTIONARIES[base];
1794
+ if (!local) return false;
1795
+ const written = unit.toLowerCase().trim();
1796
+ const isIn = (dict) => Object.values(dict).some((aliases) => aliases.includes(written));
1797
+ return isIn(local) && !isIn(UNIT_DICTIONARIES.en);
1798
+ }
1799
+ var QuantityOverflowError = class extends RangeError {
1800
+ constructor(factor) {
1801
+ super(
1802
+ `Scaling by a factor of ${factor} overflowed a quantity to a non-finite value.`
1803
+ );
1804
+ this.factor = factor;
1805
+ this.name = "QuantityOverflowError";
1806
+ }
1807
+ factor;
1808
+ };
1809
+ var round2 = (value) => parseFloat(value.toFixed(2));
1810
+ var roundQuantity = (value) => {
1811
+ const size = Math.abs(value);
1812
+ if (size >= 1 || size === 0 || !Number.isFinite(size)) return round2(value);
1813
+ const decimals = Math.min(1 - Math.floor(Math.log10(size)), 15);
1814
+ return parseFloat(value.toFixed(Math.max(2, decimals)));
1815
+ };
1816
+ function isTermValue(value) {
1817
+ if (typeof value === "number") return true;
1818
+ if (!value || typeof value !== "object") return false;
1819
+ const type = value.type;
1820
+ return type === "single" || type === "fraction" || type === "range";
1821
+ }
1822
+ function termValueNumber(value) {
1823
+ if (typeof value === "number") return value;
1824
+ return value.value ?? null;
1825
+ }
1826
+ function addedFirst(terms) {
1827
+ return [...terms.filter((t) => !t.minus), ...terms.filter((t) => t.minus)];
1828
+ }
1829
+ function termBounds(value) {
1830
+ if (typeof value === "number") return { min: value, max: value };
1831
+ if (value.type === "range" && value.range) {
1832
+ return { min: value.range.min, max: value.range.max };
1833
+ }
1834
+ const n = termValueNumber(value);
1835
+ return n === null ? null : { min: n, max: n };
1836
+ }
1837
+ var exact = (n) => Math.round(n * 1e9) / 1e9;
1838
+ function commonUnit(ordered) {
1839
+ const [first] = ordered;
1840
+ if (!first) return null;
1841
+ const firstKey = normalizeUnit(first.unit);
1842
+ if (ordered.every((t) => normalizeUnit(t.unit) === firstKey)) {
1843
+ return { unit: first.unit, weight: () => 1, divisor: 1, round: exact };
1844
+ }
1845
+ const units = ordered.map((t) => t.unit);
1846
+ if (sameLadder(units)) {
1847
+ const steps = ordered.map((t) => ladderOf(t.unit));
1848
+ let smallest = 0;
1849
+ steps.forEach((step, i) => {
1850
+ if (step.size < steps[smallest].size) smallest = i;
1851
+ });
1852
+ return {
1853
+ unit: ordered[smallest].unit,
1854
+ weight: (t) => ladderOf(t.unit).size,
1855
+ divisor: steps[smallest].size,
1856
+ round: exact
1857
+ };
1858
+ }
1859
+ for (const family of [UNIT_CONVERSIONS.mass, UNIT_CONVERSIONS.volume]) {
1860
+ const factors = units.map((u) => family.map[normalizeUnit(u)]);
1861
+ if (factors.every((f) => f !== void 0)) {
1862
+ return {
1863
+ unit: family.base,
1864
+ weight: (t) => family.map[normalizeUnit(t.unit)],
1865
+ divisor: 1,
1866
+ round: roundQuantity
1867
+ };
1868
+ }
1869
+ }
1870
+ return null;
1871
+ }
1872
+ function termsTotal(terms) {
1873
+ const ordered = addedFirst(terms);
1874
+ const [first] = ordered;
1875
+ if (!first) return null;
1876
+ if (ordered.length === 1 && !first.minus) {
1877
+ return { qty: first.value, unit: first.unit };
1878
+ }
1879
+ const common = commonUnit(ordered);
1880
+ if (!common) return null;
1881
+ let min = 0;
1882
+ let max = 0;
1883
+ let isRange = false;
1884
+ for (const term of ordered) {
1885
+ const bounds = termBounds(term.value);
1886
+ if (!bounds) return null;
1887
+ if (typeof term.value === "object" && term.value.type === "range") {
1888
+ isRange = true;
1889
+ }
1890
+ const weight = common.weight(term);
1891
+ if (term.minus) {
1892
+ min -= bounds.max * weight;
1893
+ max -= bounds.min * weight;
1894
+ } else {
1895
+ min += bounds.min * weight;
1896
+ max += bounds.max * weight;
1897
+ }
1898
+ }
1899
+ min = common.round(min / common.divisor);
1900
+ max = common.round(max / common.divisor);
1901
+ if (!isRange) return { qty: min, unit: common.unit };
1902
+ return {
1903
+ qty: { type: "range", value: exact((min + max) / 2), range: { min, max } },
1904
+ unit: common.unit
1905
+ };
1906
+ }
1907
+ function familyOf(unit) {
1908
+ const key = normalizeUnit(unit);
1909
+ if (UNIT_CONVERSIONS.mass.map[key] !== void 0) return "mass";
1910
+ if (UNIT_CONVERSIONS.volume.map[key] !== void 0) return "volume";
1911
+ return `unit:${key}`;
1912
+ }
1913
+ function totalAsTerm(total) {
1914
+ const { qty, unit } = total;
1915
+ if (typeof qty === "number") {
1916
+ return qty < 0 ? { value: -qty, unit, minus: true } : { value: qty, unit };
1917
+ }
1918
+ if (qty.type === "range" && qty.range.max < 0) {
1919
+ const min = -qty.range.max;
1920
+ const max = -qty.range.min;
1921
+ return {
1922
+ value: {
1923
+ type: "range",
1924
+ value: exact((min + max) / 2),
1925
+ range: { min, max }
1926
+ },
1927
+ unit,
1928
+ minus: true
1929
+ };
1930
+ }
1931
+ return { value: qty, unit };
1932
+ }
1933
+ function mergeKey(unit, mode) {
1934
+ if (mode === "family") return familyOf(unit);
1935
+ const step = mode === "ladder" ? ladderOf(unit) : null;
1936
+ return step ? `ladder:${step.ladder.id}` : `unit:${normalizeUnit(unit)}`;
1937
+ }
1938
+ function groupTerms(terms, mode) {
1939
+ const groups = /* @__PURE__ */ new Map();
1940
+ for (const term of terms) {
1941
+ const key = mergeKey(term.unit, mode);
1942
+ const group = groups.get(key);
1943
+ if (group) group.push(term);
1944
+ else groups.set(key, [term]);
1945
+ }
1946
+ return [...groups.values()];
1947
+ }
1948
+ function isZero(term) {
1949
+ const bounds = termBounds(term.value);
1950
+ return !!bounds && bounds.min === 0 && bounds.max === 0;
1951
+ }
1952
+ function mergeTerms(terms, mode) {
1953
+ const merged = [];
1954
+ for (const group of groupTerms(addedFirst(terms), mode)) {
1955
+ const total = group.length > 1 ? termsTotal(group) : null;
1956
+ if (total) merged.push(totalAsTerm(total));
1957
+ else merged.push(...group);
1958
+ }
1959
+ const kept = merged.filter((term) => !isZero(term));
1960
+ return addedFirst(kept.length > 0 ? kept : merged.slice(0, 1));
1961
+ }
1962
+ function scaleTermValue(value, factor) {
1963
+ if (factor === 1) return value;
1964
+ const scale = (n) => {
1965
+ const scaled = n * factor;
1966
+ if (!Number.isFinite(scaled)) throw new QuantityOverflowError(factor);
1967
+ return roundQuantity(scaled);
1968
+ };
1969
+ if (typeof value === "number") return scale(value);
1970
+ if (!value || typeof value !== "object") return value;
1971
+ if (value.type === "single" && typeof value.value === "number") {
1972
+ return { ...value, value: scale(value.value), text: void 0 };
1973
+ }
1974
+ if (value.type === "range") {
1975
+ return {
1976
+ ...value,
1977
+ value: typeof value.value === "number" ? scale(value.value) : value.value,
1978
+ range: value.range ? { min: scale(value.range.min), max: scale(value.range.max) } : value.range,
1979
+ text: void 0
1980
+ };
1981
+ }
1982
+ if (value.type === "fraction" && typeof value.value === "number") {
1983
+ return { type: "single", value: scale(value.value) };
1984
+ }
1985
+ return value;
1986
+ }
1987
+ function scaleTerms(terms, factor) {
1988
+ return terms.map((term) => ({
1989
+ ...term,
1990
+ value: scaleTermValue(term.value, factor)
1991
+ }));
1992
+ }
1993
+ function writeValue(value, unit, w) {
1994
+ if (typeof value === "number") return w.number(value, unit);
1995
+ if (value.text != null) return w.text(value.text);
1996
+ if (value.type === "range" && value.range) {
1997
+ return `${w.number(value.range.min, unit)}-${w.number(value.range.max, unit)}`;
1998
+ }
1999
+ const n = termValueNumber(value);
2000
+ return n === null ? String(value) : w.number(n, unit);
2001
+ }
2002
+ function writeTerm(term, w) {
2003
+ const text = writeValue(term.value, term.unit, w);
2004
+ if (!term.unit) return text;
2005
+ return term.unit === "%" ? `${text}%` : `${text} ${term.unit}`;
2006
+ }
2007
+ var RAW_WRITER = { number: (n) => String(n), text: (t) => t };
2008
+ function formatTerm(term) {
2009
+ return writeTerm(term, RAW_WRITER);
2010
+ }
2011
+ var MEASURED_FRACTIONS = {
2012
+ cup: [1 / 4, 1 / 3, 1 / 2, 2 / 3, 3 / 4],
2013
+ tbsp: [1 / 2],
2014
+ tsp: [1 / 8, 1 / 4, 1 / 2],
2015
+ "fl oz": [1 / 2],
2016
+ pt: [1 / 2],
2017
+ qt: [1 / 2],
2018
+ gal: [1 / 2],
2019
+ lb: [1 / 4, 1 / 2],
2020
+ oz: [1 / 4, 1 / 2, 3 / 4]
2021
+ };
2022
+ var RECOMPOSE_CHAINS = [
2023
+ ["cup", "tbsp", "tsp"],
2024
+ ["gal", "qt", "pt", "fl oz"],
2025
+ ["lb", "oz"]
2026
+ ];
2027
+ var TOLERANCE = 0.01;
2028
+ function measuredCandidates(value, unit) {
2029
+ const whole = Math.floor(value);
2030
+ const fractions = [0, ...MEASURED_FRACTIONS[unit] ?? [], 1];
2031
+ return fractions.map((f) => whole + f);
2032
+ }
2033
+ function measured(value, unit) {
2034
+ if (value <= 0) return void 0;
2035
+ return measuredCandidates(value, unit).find(
2036
+ (c) => c > 0 && Math.abs(value - c) < TOLERANCE
2037
+ );
2038
+ }
2039
+ function nearestMeasured(value, unit) {
2040
+ const smallest = Math.min(...MEASURED_FRACTIONS[unit] ?? [1]);
2041
+ const whole = Math.floor(value);
2042
+ const multiples = Array.from(
2043
+ { length: Math.round(1 / smallest) + 1 },
2044
+ (_, k) => whole + k * smallest
2045
+ );
2046
+ let best = 0;
2047
+ for (const c of [...measuredCandidates(value, unit), ...multiples]) {
2048
+ if (Math.abs(value - c) < Math.abs(value - best) - 1e-9) best = c;
2049
+ }
2050
+ if (best > 0) return best;
2051
+ return smallest;
2052
+ }
2053
+ function decompose(total, chain, steps) {
2054
+ const out = [];
2055
+ let rest = total;
2056
+ for (let i = 0; i < chain.length; i++) {
2057
+ const unit = chain[i];
2058
+ const size = steps[unit];
2059
+ const value = rest / size;
2060
+ if (i === chain.length - 1 || out.length === 2) {
2061
+ if (value > TOLERANCE / 10 || out.length === 0) {
2062
+ out.push({ value: nearestMeasured(value, unit), unit });
2063
+ }
2064
+ break;
2065
+ }
2066
+ const exactly = measured(value, unit);
2067
+ if (exactly !== void 0) {
2068
+ out.push({ value: exactly, unit });
2069
+ break;
2070
+ }
2071
+ const whole = i === 0 ? Math.max(
2072
+ 0,
2073
+ ...measuredCandidates(value, unit).filter((c) => c <= value + 1e-9)
2074
+ ) : Math.floor(value + 1e-9);
2075
+ if (whole > 0) {
2076
+ out.push({ value: whole, unit });
2077
+ rest -= whole * size;
2078
+ }
2079
+ if (rest <= 1e-9) break;
2080
+ }
2081
+ return out;
2082
+ }
2083
+ function recomposesExactly(parts, total, steps) {
2084
+ const last = parts[parts.length - 1];
2085
+ if (!last) return false;
2086
+ const sum = parts.reduce(
2087
+ (n, p) => n + p.value * steps[p.unit],
2088
+ 0
2089
+ );
2090
+ return Math.abs(sum - total) < TOLERANCE * steps[last.unit];
2091
+ }
2092
+ function ladderBounds(terms, size) {
2093
+ let min = 0;
2094
+ let max = 0;
2095
+ for (const term of terms) {
2096
+ const bounds = termBounds(term.value);
2097
+ if (!bounds) return null;
2098
+ const s = size(term);
2099
+ if (term.minus) {
2100
+ min -= bounds.max * s;
2101
+ max -= bounds.min * s;
2102
+ } else {
2103
+ min += bounds.min * s;
2104
+ max += bounds.max * s;
2105
+ }
2106
+ }
2107
+ return { min: exact(min), max: exact(max) };
2108
+ }
2109
+ function measuredAsTheyAre(terms, canonical, steps) {
2110
+ const units = terms.map(canonical);
2111
+ if (new Set(units).size !== units.length) return false;
2112
+ const sizes = terms.filter((t) => !t.minus).map((t) => steps[canonical(t)]);
2113
+ return terms.every((term) => {
2114
+ const bounds = termBounds(term.value);
2115
+ if (!bounds) return false;
2116
+ const unit = canonical(term);
2117
+ if (measured(bounds.min, unit) === void 0) return false;
2118
+ if (measured(bounds.max, unit) === void 0) return false;
2119
+ if (term.minus) return true;
2120
+ const size = steps[unit];
2121
+ const larger = sizes.filter((s) => s > size);
2122
+ return larger.length === 0 || bounds.max * size < Math.min(...larger);
2123
+ });
2124
+ }
2125
+ function computedGroup(group, w, options) {
2126
+ const { lang, buying } = options;
2127
+ const asWritten = () => addedFirst(group).map((t) => ({ text: writeTerm(t, w), minus: t.minus }));
2128
+ const first = group[0];
2129
+ const step = ladderOf(first.unit, lang);
2130
+ if (!step) {
2131
+ return mergeTerms(group, "unit").map((t) => ({
2132
+ text: writeTerm(t, w),
2133
+ minus: t.minus
2134
+ }));
2135
+ }
2136
+ const { steps } = step.ladder;
2137
+ const canonical = (t) => ladderOf(t.unit, lang).unit;
2138
+ const size = (t) => steps[canonical(t)];
2139
+ const total = ladderBounds(group, size);
2140
+ if (!total || total.min <= 0) return asWritten();
2141
+ let cap = first;
2142
+ for (const t of group) if (size(t) > size(cap)) cap = t;
2143
+ const capUnit = canonical(cap);
2144
+ const spell = (unit) => group.find((t) => canonical(t) === unit)?.unit ?? (group.some((t) => localSpelling(t.unit, lang)) ? unitSpelling(unit, lang) : unit);
2145
+ const write = (value, unit) => `${w.number(value, unit)} ${unit}`;
2146
+ const span = (min, max, unit) => min === max ? `${min} ${unit}` : `${min}-${max} ${unit}`;
2147
+ if (step.ladder.id === "metricMass" || step.ladder.id === "metricVolume") {
2148
+ const written = cap.unit;
2149
+ const capSize2 = steps[capUnit];
2150
+ const larger = buying ? toLargerMetricUnit(total.max / capSize2, written, lang).unit : written;
2151
+ const unit = larger === written ? written : larger;
2152
+ const unitSize = larger === written ? capSize2 : steps[larger];
2153
+ const num = (n) => larger === written ? w.number(n, unit) : formatAmount(n, lang);
2154
+ const lo2 = num(total.min / unitSize);
2155
+ const hi2 = num(total.max / unitSize);
2156
+ return [{ text: span(lo2, hi2, unit) }];
2157
+ }
2158
+ const chain = RECOMPOSE_CHAINS.find((c) => c.includes(capUnit));
2159
+ if (!chain) return asWritten();
2160
+ const capSize = steps[capUnit];
2161
+ const climbed = buying ? chain.find((u) => {
2162
+ const size2 = steps[u];
2163
+ return size2 >= 4 * capSize && (total.min >= size2 || measured(total.min / size2, u) !== void 0);
2164
+ }) : void 0;
2165
+ const from = chain.slice(chain.indexOf(climbed ?? capUnit));
2166
+ const top = from[0];
2167
+ const topSize = steps[top];
2168
+ const lo = measured(total.min / topSize, top);
2169
+ const hi = measured(total.max / topSize, top);
2170
+ if (lo !== void 0 && hi !== void 0) {
2171
+ const unit = spell(top);
2172
+ return [{ text: span(w.number(lo, top), w.number(hi, top), unit) }];
2173
+ }
2174
+ if (!buying && measuredAsTheyAre(group, canonical, steps)) return asWritten();
2175
+ let a = decompose(total.min, from, steps);
2176
+ let b = decompose(total.max, from, steps);
2177
+ if (total.max !== total.min) {
2178
+ for (let cut = a.length - 1; cut >= 0; cut--) {
2179
+ const prefix = a.slice(0, cut);
2180
+ const unit = a[cut].unit;
2181
+ const size2 = steps[unit];
2182
+ const used = prefix.reduce(
2183
+ (n, p) => n + p.value * steps[p.unit],
2184
+ 0
2185
+ );
2186
+ const fit = (value) => options.rounding === false ? measured(value, unit) : value > 0 ? nearestMeasured(value, unit) : void 0;
2187
+ const lo2 = fit((total.min - used) / size2);
2188
+ const hi2 = fit((total.max - used) / size2);
2189
+ const above = cut > 0 ? steps[prefix[cut - 1].unit] : Infinity;
2190
+ if (lo2 === void 0 || hi2 === void 0 || hi2 * size2 >= above) continue;
2191
+ a = [...prefix, { value: lo2, unit }];
2192
+ b = [...prefix, { value: hi2, unit }];
2193
+ break;
2194
+ }
2195
+ }
2196
+ if (options.rounding === false && !(recomposesExactly(a, total.min, steps) && recomposesExactly(b, total.max, steps))) {
2197
+ return asWritten();
2198
+ }
2199
+ const joinParts = (parts) => parts.map((p) => write(p.value, spell(p.unit))).join(options.plus ?? " + ");
2200
+ const same = (i) => a[i]?.unit === b[i]?.unit && a[i]?.value === b[i]?.value;
2201
+ if (a.length === b.length && a.every((_, i) => same(i))) {
2202
+ return a.map((p) => ({ text: write(p.value, spell(p.unit)) }));
2203
+ }
2204
+ const last = a.length - 1;
2205
+ if (a.length === b.length && a[last]?.unit === b[last]?.unit && a.slice(0, last).every((_, i) => same(i))) {
2206
+ const lastA = a[last];
2207
+ const lastB = b[last];
2208
+ return [
2209
+ ...a.slice(0, last).map((p) => ({ text: write(p.value, spell(p.unit)) })),
2210
+ {
2211
+ text: span(
2212
+ w.number(lastA.value, lastA.unit),
2213
+ w.number(lastB.value, lastB.unit),
2214
+ spell(lastA.unit)
2215
+ )
2216
+ }
2217
+ ];
2218
+ }
2219
+ return [{ text: `${joinParts(a)} \u2013 ${joinParts(b)}` }];
2220
+ }
2221
+ function computedNumber(lang) {
2222
+ return (value, unit) => {
2223
+ if (Math.abs(value - Math.round(value)) < TOLERANCE && (Math.round(value) !== 0 || value === 0)) {
2224
+ return String(Math.round(value));
2225
+ }
2226
+ return toKitchenFraction(value, unit, lang) ?? formatAmount(value, lang);
2227
+ };
2228
+ }
2229
+ function formatTerms(terms, options = {}) {
2230
+ const plus = options.plus ?? " + ";
2231
+ const minus = options.minus ?? " \u2212 ";
2232
+ const computed = options.mode === "computed";
2233
+ const w = {
2234
+ number: options.number ?? (computed ? computedNumber(options.lang) : RAW_WRITER.number),
2235
+ text: options.text ?? RAW_WRITER.text
2236
+ };
2237
+ const source = terms[0]?.minus ? addedFirst(terms) : terms;
2238
+ const pieces = computed ? groupTerms(source, "ladder").flatMap(
2239
+ (group) => computedGroup(group, w, options)
2240
+ ) : source.map((term) => ({ text: writeTerm(term, w), minus: term.minus }));
2241
+ return (pieces[0]?.minus ? addedFirst(pieces) : pieces).map((piece, i) => {
2242
+ if (i === 0)
2243
+ return piece.minus ? `${minus.trimStart()}${piece.text}` : piece.text;
2244
+ return `${piece.minus ? minus : plus}${piece.text}`;
2245
+ }).join("");
2246
+ }
1319
2247
  export {
1320
2248
  CATEGORY_KEYS,
2249
+ QuantityOverflowError,
1321
2250
  TIME_BY_LANG,
1322
2251
  TIME_DICTIONARIES,
1323
2252
  TIME_GLOBAL,
@@ -1326,25 +2255,50 @@ export {
1326
2255
  UNIT_CONVERSIONS,
1327
2256
  UNIT_DICTIONARIES,
1328
2257
  UNIT_GLOBAL,
2258
+ UNIT_LADDERS,
2259
+ amountDecimals,
1329
2260
  commonFraction,
1330
2261
  compileDictionary,
2262
+ convertUnitInFamily,
1331
2263
  decimalSeparator,
2264
+ familyOf,
1332
2265
  fillTemplate,
2266
+ formatAmount,
1333
2267
  formatNumber,
2268
+ formatTerm,
2269
+ formatTerms,
1334
2270
  getAiLanguageInstruction,
1335
2271
  getCategoryLabels,
1336
2272
  getDefaultCategories,
1337
2273
  getDictionary,
2274
+ groupTerms,
1338
2275
  isCategoryKey,
1339
2276
  isCoarseUnit,
1340
2277
  isFractionUnit,
1341
2278
  isMeasureUnit,
1342
2279
  isMetricMassUnit,
2280
+ isTermValue,
2281
+ ladderOf,
1343
2282
  localizeDecimals,
2283
+ looksLikeThousands,
2284
+ mergeKey,
2285
+ mergeTerms,
1344
2286
  normalizeUnit,
2287
+ parseDuration,
1345
2288
  resolveTimeUnit,
2289
+ round2,
2290
+ roundAmount,
2291
+ roundQuantity,
2292
+ sameCountUnit,
2293
+ sameLadder,
2294
+ scaleTermValue,
2295
+ scaleTerms,
2296
+ termValueNumber,
2297
+ termsTotal,
1346
2298
  toKitchenFraction,
1347
2299
  toLargerMetricUnit,
2300
+ tokenizeDuration,
1348
2301
  unitContainsQuantity,
1349
- unitKey
2302
+ unitKey,
2303
+ unitSpelling
1350
2304
  };