Skip to content

@gram-lang/i18n

Shared unit/time normalization and UI-string dictionaries, used internally across the pipeline (the parser doesn’t normalize units — that happens in @gram-lang/kitchen’s scaling engine and @gram-lang/analyzer’s mass standardization) so "càs", "tbsp", and "cuillère à soupe" are all recognized as the same unit regardless of which locale a recipe or a database entry was written in.

normalizeUnit maps any recognized alias (English or French, case-insensitive) to its canonical short form:

CanonicalAliases
tspteaspoon, teaspoons
tbsptablespoon, tablespoons
tadtads
dashdashes
pinchpinches
smidgensmidgen, smidge, smidgens
dropdrops
cupcups
ptpint, pints
qt
galgallon, gallons
fl ozfloz, fl. oz., fluid ounce, fluid ounces
mlmilliliter, milliliters
clcentiliter, centiliters
dldeciliter, deciliters
lliter, liters
mgmilligram, milligrams
ggram, grams
kgkilo, kilos, kilogram, kilograms
ozounce, ounces
lblbs, pound, pounds
function normalizeUnit(rawUnit: string | undefined | null, lang?: string): string
import { normalizeUnit } from '@gram-lang/i18n';

normalizeUnit('càs');              // "tbsp"
normalizeUnit('Tablespoons');      // "tbsp"
normalizeUnit('kilo', 'fr');       // "kg" (language-scoped lookup, falls back to global)

Unrecognized input is returned lowercased and trimmed, unchanged.

Same alias-normalization pattern, scoped to durations:

CanonicalAliases
dday, days
hhr, hrs, hour, hours
mmin, mins, minute, minutes
ssec, secs, second, seconds
function resolveTimeUnit(unit?: string | null, lang?: string): string
import { resolveTimeUnit } from '@gram-lang/i18n';

resolveTimeUnit('minutes'); // "m"
resolveTimeUnit('heures', 'fr'); // "h"
v1.5.0

parseDuration parses timer durations (1h30, 1 hr 30 mins, 1:30 h, 5'30", 45 min - 1 h) into minutes across every language in TIME_DICTIONARIES. Unrecognized inputs return a failure reason—which @gram-lang/kitchen maps to MISSING_UNIT, INVALID_UNIT, or INVALID_DURATION—without guessing. Each side preserves its parsed parts and form (units, clock, or prime), with sign and upper-bound checks left to the caller.

function parseDuration(text: string): DurationResult

type DurationResult =
  | { ok: true; minutes: number; range?: { min: number; max: number }; sides: DurationSide[] }
  | { ok: false; reason: DurationFailure; unit?: string } // `unit`: the word read as a unit, for "unknownUnit"

interface DurationSide { minutes: number; parts: { value: number; unit: "d" | "h" | "m" | "s" }[]; form: "units" | "clock" | "prime" }
import { parseDuration } from '@gram-lang/i18n';

parseDuration('1h30');         // { ok: true, minutes: 90, sides: [{ minutes: 90, parts: [{ value: 1, unit: "h" }, { value: 30, unit: "m" }], form: "units" }] }
parseDuration('45 min - 1 h'); // { ok: true, minutes: 52.5, range: { min: 45, max: 60 }, sides: [...] }
parseDuration('1:30');         // { ok: false, reason: "ambiguousClock" }
parseDuration('3 bananas');    // { ok: false, reason: "unknownUnit", unit: "bananas" }

The reasons (DurationFailure) are listed in the source, each with an example: empty, missingUnit, unknownUnit, words, multiplication, iso8601, unexpected, ambiguousClock, clockFormat, unitOrder, duplicateUnit, overflow60, decimalInCompound, decimalPrime, bareNumber, reversedRange, emptyRange, ambiguousRange. See Writing a duration for the forms themselves.

Used by gram shop and other consumers to group a shopping list by culinary family when an ingredient’s database entry has no explicit category:

Default categories
Vegetables
Fruits
Meat
Seafood
Dairy
Grains
Legumes
Nuts
Oils
Herbs
Spices
Condiments
Sugars
Beverages
Other

CATEGORY_KEYS exports stable, locale-invariant category keys (produce, dairy, meat, pantry, …), and getCategoryLabels(lang) resolves those keys to human-readable localized labels:

function getDefaultCategories(lang?: string): string[] // defaults to 'en'
function getCategoryLabels(lang?: string): Record<CategoryKey, string>
import { getDefaultCategories, getCategoryLabels, CATEGORY_KEYS } from '@gram-lang/i18n';

getDefaultCategories('fr'); // ["Légumes", "Fruits", "Viandes", ...]
getCategoryLabels('fr').produce; // "Légumes"

@gram-lang/i18n acts as the single source of truth for same-family unit conversion factors (UNIT_CONVERSIONS) and time-to-minute duration multipliers (TIME_TO_MINUTES):

import { UNIT_CONVERSIONS, TIME_TO_MINUTES } from '@gram-lang/i18n';

UNIT_CONVERSIONS.mass.map.kg; // 1000 (grams)
UNIT_CONVERSIONS.volume.map.tbsp; // 14.7868 (mL)
TIME_TO_MINUTES.h; // 60 (minutes)

formatNumber writes a number as a reader of the language does (1.5 in English, 1,5 in French), rounded to two decimals by default and with no thousands separator, as a recipe writes 1500 g. localizeDecimals does the same for a quantity already written as text (a range, a timer), and decimalSeparator gives the separator itself. Every view and the CLI write the numbers they show through these; a number read back by a script or a file (a data-* attribute, JSON, .gram source) keeps its point.

import { formatNumber, localizeDecimals, decimalSeparator } from '@gram-lang/i18n';

formatNumber(1.5, 'fr');          // "1,5"
formatNumber(147.46, 'fr', 1);    // "147,5"
formatNumber(1500, 'en');         // "1500"
localizeDecimals('1.5-2', 'fr');  // "1,5-2"
decimalSeparator('fr');           // ","

A quantity is shown with formatAmount, which rounds it to its size rather than to a decimal of its unit: three significant digits, never fewer than its whole part, and two below 1, so a small amount is never shown as 0 (0.15 kg stays 0.15 kg, not 0.2 kg). roundAmount gives the rounded number, amountDecimals the number of decimals kept.

import { formatAmount } from '@gram-lang/i18n';

formatAmount(0.15, 'fr');   // "0,15"
formatAmount(0.0047);       // "0.0047"
formatAmount(15.24);        // "15.2"
formatAmount(152.37);       // "152"

Spoons, cups and imperial measures (tsp, tbsp, cup, tasse, oz, lb, pt…) are read in fractions: toKitchenFraction writes such a quantity as a whole number and a common fraction, as a cook writes it, so 1.75 cup and 1 3/4 cup both show 1 3/4 cup. It returns undefined when no common fraction is near (1.6) and for any other unit: metric units and counts keep decimals. isFractionUnit tells whether a unit is one of them, commonFraction gives the fraction of a value below 1.

import { toKitchenFraction, isFractionUnit, commonFraction } from '@gram-lang/i18n';

toKitchenFraction(1.75, 'cup');   // "1 3/4"
toKitchenFraction(0.5, 'tsp');    // "1/2"
toKitchenFraction(1.6, 'cup');    // undefined
toKitchenFraction(1.5, 'kg');     // undefined
isFractionUnit('tasse', 'fr');    // true
commonFraction(0.25);             // "1/4"

toLargerMetricUnit converts a metric mass (mg, g) or volume (ml, cl, dl) to kg or l once it reaches 1000 g or 1000 ml (rounded to two decimal places), and returns any other amount unchanged. Gram uses it for what is bought or read as a total, never for what is weighed (see Kilograms to buy, grams to weigh). isMetricMassUnit checks whether a unit (including localized aliases) is a metric mass (mg, g, kg).

function toLargerMetricUnit(value: number, rawUnit: string | undefined | null, lang?: string): { value: number; unit: string }
function isMetricMassUnit(rawUnit: string | undefined | null, lang?: string): boolean
import { toLargerMetricUnit, isMetricMassUnit } from '@gram-lang/i18n';

toLargerMetricUnit(3900, 'g');   // { value: 3.9, unit: "kg" }
toLargerMetricUnit(150, 'cl');   // { value: 1.5, unit: "l" }
toLargerMetricUnit(999, 'g');    // { value: 999, unit: "g" }
toLargerMetricUnit(64, 'oz');    // { value: 64, unit: "oz" }
isMetricMassUnit('kilo', 'fr');  // true
isMetricMassUnit('lb');          // false
v1.5.0

Every quantity of the pipeline (a sum like {1 cup + 1 tbsp}, a plain {200 g}, the entries of a shopping list) goes through one model of terms: a value, a unit, and minus for a term taken away. Kitchen, the analyzer and the renderer all add up, scale and write quantities with these functions, so they always agree. The module is pure: it knows nothing about the AST or the compiled recipe.

type TermValue = number | QuantityValue; // a number, or the single / fraction / range shape of the compiled recipe
interface Term { value: TermValue; unit: string | null; minus?: boolean }
interface TermsTotal { qty: TermValue; unit: string | null }

function termsTotal(terms: readonly Term[]): TermsTotal | null
function mergeTerms(terms: readonly Term[], mode: "unit" | "ladder"): Term[]
function scaleTerms(terms: readonly Term[], factor: number): Term[]
function formatTerms(terms: readonly Term[], options?: FormatTermsOptions): string

const UNIT_LADDERS: readonly UnitLadder[]
function ladderOf(rawUnit: string | undefined | null, lang?: string): LadderStep | null
function sameLadder(rawUnits: readonly (string | undefined | null)[], lang?: string): boolean
  • UNIT_LADDERS: the units that convert by a whole ratio, each counted in its ladder’s smallest unit: US volume (tsp 1, tbsp 3, fl oz 6, cup 48, pt 96, qt 192, gal 768), imperial mass (oz 1, lb 16), metric mass (mg, g, livre, kg) and metric volume (ml, cl, dl, tasse, l). They agree with UNIT_CONVERSIONS to 0.01%. pinch, dash and unknown units are on no ladder.
  • termsTotal: one unit keeps its unit (1 tasse + 1 tasse stays in tasse, never converted); units of one ladder add up in the smallest unit written, with exact whole-number arithmetic; one family across systems gives grams or milliliters; anything else (a volume and a weight, unknown units) gives null. Ranges add up bound by bound, and a total with a range stays a range.
  • mergeTerms: "unit" adds up the terms of each unit (a run sheet’s kit), "ladder" the terms of each ladder (the shopping list). An amount never starts with a term taken away: formatTerms keeps the written order (1 cup − 2 tbsp + 30 g, each kind taking away on its own) and only moves the terms added first when it would (1 cup − 2 tbsp, never −2 tbsp + 1 cup).
  • formatTerms: mode: "written" (default) writes the terms as the author did; mode: "computed" writes an amount Gram worked out the way a cook measures it (see scaling sums of quantities). Options: lang, buying (a shopping list: move up to the unit you buy), rounding (round to what a cook can measure, after scaling), plus / minus separators, and number / text to write numbers your own way.
import { termsTotal, mergeTerms, scaleTerms, formatTerms, ladderOf } from '@gram-lang/i18n';

const terms = [{ value: 1, unit: 'cup' }, { value: 1, unit: 'tbsp' }];
termsTotal(terms);                                           // { qty: 17, unit: "tbsp" }
termsTotal([{ value: 1, unit: 'cup' }, { value: 50, unit: 'ml' }]); // { qty: 286.59, unit: "ml" }
termsTotal([{ value: 1, unit: 'cup' }, { value: 20, unit: 'g' }]);  // null
formatTerms(scaleTerms(terms, 2), { mode: 'computed', rounding: true }); // "2 cup + 2 tbsp"
formatTerms([{ value: 34, unit: 'tbsp' }], { mode: 'computed', buying: true }); // "2 cup + 2 tbsp"
ladderOf('cups')?.size;                                      // 48 (teaspoons in a cup)