@lifefrom/units 0.0.0-stage → 1.0.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.
@@ -0,0 +1,110 @@
1
+ import type { ReferenceCompound, Source } from './types.js';
2
+ export type { Analyte, Bridge, Forbidden, ReferenceCompound, Source, Spec, UnitRecord } from './types.js';
3
+ export { SPEC } from './data.js';
4
+ export declare const VERSION: string;
5
+ export type ErrorCode = 'unknown_unit' | 'unknown_analyte' | 'incompatible_units' | 'forbidden' | 'no_sourced_conversion' | 'invalid_value' | 'qualified_value' | 'ambiguous_value';
6
+ export declare class LifeFromUnitsError extends Error {
7
+ readonly code: ErrorCode;
8
+ readonly details: Record<string, unknown>;
9
+ constructor(code: ErrorCode, message: string, details?: Record<string, unknown>);
10
+ }
11
+ /** Canonical spelling of a unit (µ/u/mcg, superscripts, ×10⁹/L, UI/IU, case, spacing). */
12
+ export declare function normalizeUnit(unit: string): string;
13
+ /** Canonical spelling, dimension, scale to the base unit, and UCUM code of a unit. */
14
+ export declare function unitInfo(unit: string): {
15
+ unit: string;
16
+ dimension: string;
17
+ scale: number;
18
+ ucum: string | null;
19
+ };
20
+ export interface ParsedResult {
21
+ value: number;
22
+ comparator: string | null;
23
+ flag: string | null;
24
+ text: string;
25
+ }
26
+ /** Parse a reported value with an optional comparator ("<5") or flag ("5,4 H"). Never drops the qualifier. */
27
+ export declare function parseResult(value: number | string): ParsedResult;
28
+ /**
29
+ * Parse a number, accepting a decimal comma ("5,4" -> 5.4). "1,234" is ambiguous and throws.
30
+ * Values with a comparator or flag throw qualified_value: use parseResult / convertResult.
31
+ */
32
+ export declare function parseValue(value: number | string): number;
33
+ /** Analytes: id, name, marker slugs, and whether lifefrom-units has conversions for them. */
34
+ export declare function analytes(): Array<{
35
+ id: string;
36
+ name: string;
37
+ marker_slugs: string[];
38
+ has_conversions: boolean;
39
+ }>;
40
+ export interface StepSource extends Source {
41
+ id: string;
42
+ }
43
+ export interface Step {
44
+ kind: string;
45
+ description: string;
46
+ basis?: string;
47
+ factor?: number;
48
+ inverse?: boolean;
49
+ sources: StepSource[];
50
+ reference_compound?: ReferenceCompound | null;
51
+ }
52
+ export interface UserFactorRecord {
53
+ value: number;
54
+ overrides: string | null;
55
+ library_kind: string | null;
56
+ library_factor: number | null;
57
+ }
58
+ export interface Explanation {
59
+ from_unit: string;
60
+ to_unit: string;
61
+ analyte: string | null;
62
+ kind: 'identity' | 'unit_arithmetic' | 'label_equivalence' | 'analyte_factor' | 'equation' | 'user_factor';
63
+ factor: number | null;
64
+ equation: {
65
+ slope: number;
66
+ intercept: number;
67
+ text: string;
68
+ } | null;
69
+ derived: boolean;
70
+ steps: Step[];
71
+ sources: StepSource[];
72
+ reference_compounds: ReferenceCompound[];
73
+ warnings: string[];
74
+ user_factor: UserFactorRecord | null;
75
+ text: string;
76
+ value?: number;
77
+ result?: number;
78
+ }
79
+ /**
80
+ * Convert `value` from `fromUnit` to `toUnit`. `analyte` (lifefrom-units analyte id such as "glucose" or a
81
+ * LifeFrom marker slug such as "glucose-fasting") is needed when the units measure different quantities.
82
+ * `factor` (optional, never a default) is a caller-supplied multiplier recorded by explain().
83
+ * Throws LifeFromUnitsError with code incompatible_units, forbidden, no_sourced_conversion, unknown_unit,
84
+ * unknown_analyte, invalid_value, qualified_value or ambiguous_value.
85
+ */
86
+ export declare function convert(value: number | string, fromUnit: string, toUnit: string, analyte?: string | null, factor?: number | string | null): number;
87
+ export declare const FLAG_NOTE = "The flag is copied unchanged from the original report. It refers to that laboratory's reference interval, not to anything lifefrom-units computed.";
88
+ export interface ConvertedResult {
89
+ value: number;
90
+ comparator: string | null;
91
+ flag: string | null;
92
+ unit: string;
93
+ text: string;
94
+ flag_note?: string;
95
+ }
96
+ /** Convert a reported value that may carry a comparator ("<5") or a flag ("5,4 H"); both are kept. */
97
+ export declare function convertResult(value: number | string, fromUnit: string, toUnit: string, analyte?: string | null, factor?: number | string | null): ConvertedResult;
98
+ /** True if a value in unit `a` equals the same number in unit `b` (e.g. µg/L and ng/mL). */
99
+ export declare function sameUnit(a: string, b: string, analyte?: string | null): boolean;
100
+ /** Format like Python's "{:.6g}". */
101
+ export declare function fmtG(x: number): string;
102
+ /** Explain a conversion: factor or equation, steps, basis, sources, reference compounds and warnings. */
103
+ export declare function explain(fromUnit: string, toUnit: string, analyte?: string | null, value?: number | string, factor?: number | string | null): Explanation;
104
+ /** snake_case aliases matching the Python API names. */
105
+ export declare const normalize_unit: typeof normalizeUnit;
106
+ export declare const same_unit: typeof sameUnit;
107
+ export declare const parse_value: typeof parseValue;
108
+ export declare const parse_result: typeof parseResult;
109
+ export declare const convert_result: typeof convertResult;
110
+ export declare const unit_info: typeof unitInfo;
@@ -0,0 +1,480 @@
1
+ /**
2
+ * @lifefrom/units: normalise clinical lab unit spellings and convert lab values with sourced,
3
+ * analyte-specific factors. Zero runtime dependencies. Same data and API as the Python package.
4
+ */
5
+ import { SPEC } from './data.js';
6
+ export { SPEC } from './data.js';
7
+ export const VERSION = SPEC.version;
8
+ export class LifeFromUnitsError extends Error {
9
+ code;
10
+ details;
11
+ constructor(code, message, details = {}) {
12
+ super(message);
13
+ this.name = 'LifeFromUnitsError';
14
+ this.code = code;
15
+ this.details = details;
16
+ }
17
+ }
18
+ // ---------------------------------------------------------------------------
19
+ // Data
20
+ // ---------------------------------------------------------------------------
21
+ const RULES = SPEC.normalization.rules.map((r) => [new RegExp(r.pattern, 'g'), r.replacement]);
22
+ const UNITS = new Map(SPEC.units.map((u) => [u.unit, u]));
23
+ const ANALYTES = new Map(SPEC.analytes.map((a) => [a.id, a]));
24
+ const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
25
+ function unitKey(text) {
26
+ let s = text.trim();
27
+ for (const [re, repl] of RULES) {
28
+ re.lastIndex = 0;
29
+ s = s.replace(re, repl);
30
+ }
31
+ return s.replace(/\s+/g, '');
32
+ }
33
+ function lookup(unit) {
34
+ if (typeof unit !== 'string' || unit.trim() === '') {
35
+ throw new LifeFromUnitsError('unknown_unit', 'empty unit', { unit });
36
+ }
37
+ const k = unitKey(unit);
38
+ let canon = has(SPEC.lookup.exact, k) ? SPEC.lookup.exact[k] : undefined;
39
+ if (canon === undefined) {
40
+ const kf = unitKey(unit.toLowerCase());
41
+ canon = has(SPEC.lookup.casefold, kf) ? SPEC.lookup.casefold[kf] : undefined;
42
+ }
43
+ if (canon === undefined)
44
+ throw new LifeFromUnitsError('unknown_unit', `unknown unit: '${unit}'`, { unit });
45
+ return UNITS.get(canon);
46
+ }
47
+ // ---------------------------------------------------------------------------
48
+ // Public API
49
+ // ---------------------------------------------------------------------------
50
+ /** Canonical spelling of a unit (µ/u/mcg, superscripts, ×10⁹/L, UI/IU, case, spacing). */
51
+ export function normalizeUnit(unit) {
52
+ return lookup(unit).unit;
53
+ }
54
+ /** Canonical spelling, dimension, scale to the base unit, and UCUM code of a unit. */
55
+ export function unitInfo(unit) {
56
+ const u = lookup(unit);
57
+ return { unit: u.unit, dimension: u.dimension, scale: u.scale, ucum: u.ucum };
58
+ }
59
+ const SEP_SPACES = /(?<=\d)[    '](?=\d)/g;
60
+ const NUM = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
61
+ const isDigits = (s) => /^\d+$/.test(s);
62
+ const stripSign = (s) => s.replace(/^[+-]+/, '');
63
+ const COMPARATOR = /^\s*(<=|>=|=<|=>|≤|≥|<|>)\s*/;
64
+ const FLAG = /\s*(?:\(\s*(HH|LL|H|L|A|AA)\s*\)|\[\s*(HH|LL|H|L|A|AA)\s*\]|(HH|LL|H|L|A|AA|↑|↓|\*|!))\s*$/i;
65
+ const CMP_NORMAL = { '<': '<', '>': '>', '<=': '<=', '>=': '>=', '=<': '<=', '=>': '>=', '≤': '<=', '≥': '>=' };
66
+ function splitQualifiers(text) {
67
+ let comparator = null;
68
+ let flag = null;
69
+ let s = text.trim();
70
+ const m = COMPARATOR.exec(s);
71
+ if (m) {
72
+ comparator = CMP_NORMAL[m[1]];
73
+ s = s.slice(m[0].length);
74
+ }
75
+ const f = FLAG.exec(s);
76
+ if (f && f.index > 0 && /[0-9.]/.test(s.slice(0, f.index))) {
77
+ flag = (f[1] ?? f[2] ?? f[3]).toUpperCase();
78
+ s = s.slice(0, f.index);
79
+ }
80
+ return [comparator, s.trim(), flag];
81
+ }
82
+ /** Parse a reported value with an optional comparator ("<5") or flag ("5,4 H"). Never drops the qualifier. */
83
+ export function parseResult(value) {
84
+ if (typeof value === 'number')
85
+ return { value: parseValue(value), comparator: null, flag: null, text: String(value) };
86
+ if (typeof value !== 'string')
87
+ throw new LifeFromUnitsError('invalid_value', `unsupported value type: ${typeof value}`, { value });
88
+ const [comparator, num, flag] = splitQualifiers(value);
89
+ return { value: parseNumber(num, value), comparator, flag, text: value };
90
+ }
91
+ /**
92
+ * Parse a number, accepting a decimal comma ("5,4" -> 5.4). "1,234" is ambiguous and throws.
93
+ * Values with a comparator or flag throw qualified_value: use parseResult / convertResult.
94
+ */
95
+ export function parseValue(value) {
96
+ if (typeof value === 'number') {
97
+ if (!Number.isFinite(value))
98
+ throw new LifeFromUnitsError('invalid_value', 'value is not finite', { value });
99
+ return value;
100
+ }
101
+ if (typeof value !== 'string')
102
+ throw new LifeFromUnitsError('invalid_value', `unsupported value type: ${typeof value}`, { value });
103
+ const [comparator, num, flag] = splitQualifiers(value);
104
+ if (comparator || flag) {
105
+ parseNumber(num, value); // a malformed number is reported as such
106
+ throw new LifeFromUnitsError('qualified_value', `value '${value}' has a qualifier (${comparator || flag}); use parseResult()/convertResult() so it is kept`, { value, comparator, flag });
107
+ }
108
+ return parseNumber(value, value);
109
+ }
110
+ function parseNumber(text, value) {
111
+ let s = text.trim().replace(/\u2212/g, '-');
112
+ s = s.replace(SEP_SPACES, '');
113
+ if (s.includes(',') && s.includes('.')) {
114
+ const dec = s.lastIndexOf(',') > s.lastIndexOf('.') ? ',' : '.';
115
+ const thou = dec === ',' ? '.' : ',';
116
+ const at = s.lastIndexOf(dec);
117
+ const intPart = s.slice(0, at);
118
+ const frac = s.slice(at + 1);
119
+ const groups = stripSign(intPart).split(thou);
120
+ const ok = groups.length >= 2 && groups.slice(1).every((g) => g.length === 3) && groups[0].length >= 1 && groups[0].length <= 3;
121
+ if (!ok)
122
+ throw new LifeFromUnitsError('ambiguous_value', `cannot read '${value}': mixed separators`, { value });
123
+ s = intPart.split(thou).join('') + '.' + frac;
124
+ }
125
+ else if (s.includes(',')) {
126
+ const parts = s.split(',');
127
+ if (parts.length === 2) {
128
+ const head = stripSign(parts[0]);
129
+ if (parts[1].length === 3 && isDigits(parts[1]) && isDigits(head) && head.length >= 1 && head.length <= 3 && head !== '0') {
130
+ throw new LifeFromUnitsError('ambiguous_value', `cannot read '${value}': the comma may be a decimal or a thousands separator`, { value });
131
+ }
132
+ s = parts[0] + '.' + parts[1];
133
+ }
134
+ else {
135
+ const head = stripSign(parts[0]);
136
+ if (parts.slice(1).every((p) => p.length === 3) && head.length >= 1 && head.length <= 3)
137
+ s = parts.join('');
138
+ else
139
+ throw new LifeFromUnitsError('invalid_value', `cannot read '${value}'`, { value });
140
+ }
141
+ }
142
+ else if ((s.match(/\./g) ?? []).length > 1) {
143
+ const parts = s.split('.');
144
+ const head = stripSign(parts[0]);
145
+ if (parts.slice(1).every((p) => p.length === 3) && head.length >= 1 && head.length <= 3)
146
+ s = parts.join('');
147
+ else
148
+ throw new LifeFromUnitsError('invalid_value', `cannot read '${value}'`, { value });
149
+ }
150
+ if (!NUM.test(s))
151
+ throw new LifeFromUnitsError('invalid_value', `not a number: '${value}'`, { value });
152
+ const v = Number(s);
153
+ if (!Number.isFinite(v))
154
+ throw new LifeFromUnitsError('invalid_value', 'value is not finite', { value });
155
+ return v;
156
+ }
157
+ function resolveAnalyte(analyte) {
158
+ if (analyte === null || analyte === undefined)
159
+ return null;
160
+ if (typeof analyte !== 'string' || analyte.trim() === '')
161
+ throw new LifeFromUnitsError('unknown_analyte', 'empty analyte', { analyte });
162
+ const k = analyte.trim().toLowerCase();
163
+ const id = has(SPEC.lookup.analytes, k) ? SPEC.lookup.analytes[k] : undefined;
164
+ if (id === undefined)
165
+ throw new LifeFromUnitsError('unknown_analyte', `unknown analyte: '${analyte}'`, { analyte });
166
+ return ANALYTES.get(id);
167
+ }
168
+ /** Analytes: id, name, marker slugs, and whether lifefrom-units has conversions for them. */
169
+ export function analytes() {
170
+ return SPEC.analytes.map((a) => ({ id: a.id, name: a.name, marker_slugs: [...a.marker_slugs], has_conversions: a.bridges.length > 0 }));
171
+ }
172
+ function sourceList(ids) {
173
+ return ids.map((i) => ({ ...SPEC.sources[i], id: i }));
174
+ }
175
+ function forbiddenMatch(f, ua, ub) {
176
+ const side = (dim, units, u) => {
177
+ if (dim !== '*' && dim !== u.dimension)
178
+ return false;
179
+ return units === null || units === undefined || units.includes(u.unit);
180
+ };
181
+ return (side(f.a, f.a_units, ua) && side(f.b, f.b_units, ub)) || (side(f.a, f.a_units, ub) && side(f.b, f.b_units, ua));
182
+ }
183
+ function raiseForbidden(f, ua, ub) {
184
+ throw new LifeFromUnitsError('forbidden', `${ua.unit} -> ${ub.unit}: ${f.reason}`, { rule: f.id, reason: f.reason, sources: sourceList(f.sources) });
185
+ }
186
+ function plan(fromUnit, toUnit, analyte) {
187
+ const ua = lookup(fromUnit);
188
+ const ub = lookup(toUnit);
189
+ const an = resolveAnalyte(analyte);
190
+ const base = { from_unit: ua.unit, to_unit: ub.unit, analyte: an ? an.id : null };
191
+ const da = ua.dimension;
192
+ const db = ub.dimension;
193
+ if (an) {
194
+ for (const f of SPEC.forbidden)
195
+ if (f.analyte === an.id && forbiddenMatch(f, ua, ub))
196
+ raiseForbidden(f, ua, ub);
197
+ }
198
+ if (ua.unit === ub.unit) {
199
+ return { ...base, a: 1, b: 0, kind: 'identity', steps: [{ kind: 'identity', description: 'same unit', sources: [] }] };
200
+ }
201
+ if (da.startsWith('arbitrary:') || db.startsWith('arbitrary:')) {
202
+ throw new LifeFromUnitsError('forbidden', `${ua.unit} -> ${ub.unit}: ${SPEC.arbitrary_reason}`, {
203
+ rule: 'arbitrary-units',
204
+ reason: SPEC.arbitrary_reason,
205
+ sources: sourceList(['ucum-2.2']),
206
+ });
207
+ }
208
+ if (da === db) {
209
+ const a = ua.scale / ub.scale;
210
+ return {
211
+ ...base,
212
+ a,
213
+ b: 0,
214
+ kind: 'unit_arithmetic',
215
+ steps: [
216
+ {
217
+ kind: 'unit_arithmetic',
218
+ factor: a,
219
+ description: `same quantity (${SPEC.dimensions[da].name}); factor from unit prefixes`,
220
+ basis: 'derived: unit arithmetic',
221
+ sources: [],
222
+ },
223
+ ],
224
+ };
225
+ }
226
+ const genericForbidden = () => {
227
+ for (const f of SPEC.forbidden)
228
+ if (f.analyte === null && forbiddenMatch(f, ua, ub))
229
+ raiseForbidden(f, ua, ub);
230
+ };
231
+ if (!an) {
232
+ genericForbidden();
233
+ throw new LifeFromUnitsError('incompatible_units', `${ua.unit} (${da}) and ${ub.unit} (${db}) measure different quantities; pass analyte to convert between them`, { from_dimension: da, to_dimension: db });
234
+ }
235
+ // Breadth-first search over the analyte's bridges.
236
+ const edges = new Map();
237
+ const push = (k, v) => {
238
+ if (!edges.has(k))
239
+ edges.set(k, []);
240
+ edges.get(k).push(v);
241
+ };
242
+ for (const br of an.bridges) {
243
+ push(br.from, [br.to, br, false]);
244
+ push(br.to, [br.from, br, true]);
245
+ }
246
+ const prev = new Map();
247
+ const seen = new Set([da]);
248
+ const q = [da];
249
+ while (q.length) {
250
+ const d = q.shift();
251
+ if (d === db)
252
+ break;
253
+ for (const [nd, br, inv] of edges.get(d) ?? []) {
254
+ if (!seen.has(nd)) {
255
+ seen.add(nd);
256
+ prev.set(nd, [d, br, inv]);
257
+ q.push(nd);
258
+ }
259
+ }
260
+ }
261
+ if (!seen.has(db)) {
262
+ genericForbidden();
263
+ throw new LifeFromUnitsError('no_sourced_conversion', `no sourced conversion for ${an.id} between ${ua.unit} (${da}) and ${ub.unit} (${db})`, { analyte: an.id, from_dimension: da, to_dimension: db });
264
+ }
265
+ const path = [];
266
+ let d = db;
267
+ while (d !== da) {
268
+ const [p, br, inv] = prev.get(d);
269
+ path.push([br, inv]);
270
+ d = p;
271
+ }
272
+ path.reverse();
273
+ let a = ua.scale;
274
+ let b = 0;
275
+ const steps = [];
276
+ for (const [br, inv] of path) {
277
+ let ba = br.a;
278
+ let bb = br.b;
279
+ if (inv) {
280
+ const ia = 1 / ba;
281
+ const ib = -bb / ba;
282
+ ba = ia;
283
+ bb = ib;
284
+ }
285
+ a = a * ba;
286
+ b = b * ba + bb;
287
+ steps.push({
288
+ kind: br.kind,
289
+ description: br.description,
290
+ basis: br.basis,
291
+ inverse: inv,
292
+ sources: sourceList(br.sources),
293
+ reference_compound: br.reference_compound ?? null,
294
+ });
295
+ }
296
+ a = a / ub.scale;
297
+ b = b / ub.scale;
298
+ const kinds = new Set(steps.map((s) => s.kind));
299
+ kinds.delete('label_equivalence');
300
+ const kind = b !== 0 ? 'equation' : kinds.size > 0 ? 'analyte_factor' : 'label_equivalence';
301
+ return { ...base, a, b, kind, steps };
302
+ }
303
+ function userFactor(factor) {
304
+ let f;
305
+ try {
306
+ f = parseValue(factor);
307
+ }
308
+ catch {
309
+ throw new LifeFromUnitsError('invalid_value', `factor must be a positive number, got '${factor}'`, { factor });
310
+ }
311
+ if (!(f > 0))
312
+ throw new LifeFromUnitsError('invalid_value', `factor must be a positive number, got '${factor}'`, { factor });
313
+ return f;
314
+ }
315
+ function pct(x) {
316
+ const s = (x * 100).toFixed(2);
317
+ return (s.startsWith('-') ? s : '+' + s) + '%';
318
+ }
319
+ function planWith(fromUnit, toUnit, analyte, factor) {
320
+ if (factor === undefined || factor === null)
321
+ return { ...plan(fromUnit, toUnit, analyte), user_factor: null, warnings: [] };
322
+ const f = userFactor(factor);
323
+ const ua = lookup(fromUnit);
324
+ const ub = lookup(toUnit);
325
+ const an = resolveAnalyte(analyte);
326
+ const warnings = [`Factor ${fmtG(f)} supplied by the caller; lifefrom-units has not checked it.`];
327
+ const record = { value: f, overrides: null, library_kind: null, library_factor: null };
328
+ try {
329
+ const lib = plan(fromUnit, toUnit, analyte);
330
+ record.library_kind = lib.kind;
331
+ if (lib.b !== 0)
332
+ warnings.push('lifefrom-units uses an equation for this pair, not a factor.');
333
+ else {
334
+ record.library_factor = lib.a;
335
+ if (Math.abs(lib.a - f) > 1e-9 * Math.abs(lib.a)) {
336
+ warnings.push(`The library factor is ${fmtG(lib.a)} (${lib.kind}); the supplied factor differs by ${pct((f - lib.a) / lib.a)}.`);
337
+ }
338
+ }
339
+ }
340
+ catch (e) {
341
+ if (e instanceof LifeFromUnitsError && (e.code === 'incompatible_units' || e.code === 'forbidden' || e.code === 'no_sourced_conversion')) {
342
+ record.overrides = e.code;
343
+ const reason = e.details.reason || e.message;
344
+ warnings.push(`Overrides lifefrom-units (${e.code}): ${reason}`);
345
+ }
346
+ else
347
+ throw e;
348
+ }
349
+ return {
350
+ from_unit: ua.unit,
351
+ to_unit: ub.unit,
352
+ analyte: an ? an.id : null,
353
+ a: f,
354
+ b: 0,
355
+ kind: 'user_factor',
356
+ user_factor: record,
357
+ warnings,
358
+ steps: [
359
+ {
360
+ kind: 'user_factor',
361
+ factor: f,
362
+ description: `factor supplied by the caller: 1 ${ua.unit} = ${fmtG(f)} ${ub.unit}`,
363
+ basis: 'caller-supplied; not checked by lifefrom-units',
364
+ sources: [],
365
+ },
366
+ ],
367
+ };
368
+ }
369
+ /**
370
+ * Convert `value` from `fromUnit` to `toUnit`. `analyte` (lifefrom-units analyte id such as "glucose" or a
371
+ * LifeFrom marker slug such as "glucose-fasting") is needed when the units measure different quantities.
372
+ * `factor` (optional, never a default) is a caller-supplied multiplier recorded by explain().
373
+ * Throws LifeFromUnitsError with code incompatible_units, forbidden, no_sourced_conversion, unknown_unit,
374
+ * unknown_analyte, invalid_value, qualified_value or ambiguous_value.
375
+ */
376
+ export function convert(value, fromUnit, toUnit, analyte, factor) {
377
+ const v = parseValue(value);
378
+ const p = planWith(fromUnit, toUnit, analyte, factor);
379
+ return p.a * v + p.b;
380
+ }
381
+ export const FLAG_NOTE = "The flag is copied unchanged from the original report. It refers to that laboratory's reference interval, not to anything lifefrom-units computed.";
382
+ /** Convert a reported value that may carry a comparator ("<5") or a flag ("5,4 H"); both are kept. */
383
+ export function convertResult(value, fromUnit, toUnit, analyte, factor) {
384
+ const r = parseResult(value);
385
+ const p = planWith(fromUnit, toUnit, analyte, factor);
386
+ let comparator = r.comparator;
387
+ if (p.a < 0 && comparator)
388
+ comparator = { '<': '>', '>': '<', '<=': '>=', '>=': '<=' }[comparator];
389
+ const v = p.a * r.value + p.b;
390
+ const out = { value: v, comparator, flag: r.flag, unit: p.to_unit, text: `${comparator ?? ''}${fmtG(v)}${r.flag ? ' ' + r.flag : ''}` };
391
+ if (r.flag)
392
+ out.flag_note = FLAG_NOTE;
393
+ return out;
394
+ }
395
+ /** True if a value in unit `a` equals the same number in unit `b` (e.g. µg/L and ng/mL). */
396
+ export function sameUnit(a, b, analyte) {
397
+ let p;
398
+ try {
399
+ p = plan(a, b, analyte);
400
+ }
401
+ catch (e) {
402
+ if (e instanceof LifeFromUnitsError && (e.code === 'incompatible_units' || e.code === 'forbidden' || e.code === 'no_sourced_conversion'))
403
+ return false;
404
+ throw e;
405
+ }
406
+ return p.b === 0 && Math.abs(p.a - 1) <= 1e-12;
407
+ }
408
+ /** Format like Python's "{:.6g}". */
409
+ export function fmtG(x) {
410
+ if (x === 0)
411
+ return '0';
412
+ if (!Number.isFinite(x))
413
+ return String(x);
414
+ const [, e] = x.toExponential(5).split('e');
415
+ const exp = Number(e);
416
+ if (exp < -4 || exp >= 6) {
417
+ let [m, ex] = x.toExponential(5).split('e');
418
+ if (m.includes('.'))
419
+ m = m.replace(/0+$/, '').replace(/\.$/, '');
420
+ const n = Number(ex);
421
+ return `${m}e${n < 0 ? '-' : '+'}${String(Math.abs(n)).padStart(2, '0')}`;
422
+ }
423
+ let s = x.toFixed(Math.max(0, 5 - exp));
424
+ if (s.includes('.'))
425
+ s = s.replace(/0+$/, '').replace(/\.$/, '');
426
+ return s;
427
+ }
428
+ /** Explain a conversion: factor or equation, steps, basis, sources, reference compounds and warnings. */
429
+ export function explain(fromUnit, toUnit, analyte, value, factor) {
430
+ const p = planWith(fromUnit, toUnit, analyte, factor);
431
+ const out = {
432
+ from_unit: p.from_unit,
433
+ to_unit: p.to_unit,
434
+ analyte: p.analyte,
435
+ kind: p.kind,
436
+ factor: p.b === 0 ? p.a : null,
437
+ equation: null,
438
+ derived: p.kind === 'identity' || p.kind === 'unit_arithmetic',
439
+ steps: p.steps,
440
+ sources: [],
441
+ reference_compounds: [],
442
+ warnings: [...p.warnings],
443
+ user_factor: p.user_factor,
444
+ text: '',
445
+ };
446
+ if (p.b !== 0) {
447
+ const text = `${p.to_unit} = ${fmtG(p.a)} × ${p.from_unit} ${p.b >= 0 ? '+' : '-'} ${fmtG(Math.abs(p.b))}`;
448
+ out.equation = { slope: p.a, intercept: p.b, text };
449
+ out.text = text;
450
+ }
451
+ else {
452
+ out.text = `1 ${p.from_unit} = ${fmtG(p.a)} ${p.to_unit}`;
453
+ }
454
+ const seen = new Set();
455
+ for (const s of p.steps) {
456
+ for (const src of s.sources) {
457
+ if (!seen.has(src.id)) {
458
+ seen.add(src.id);
459
+ out.sources.push(src);
460
+ }
461
+ }
462
+ if (s.reference_compound)
463
+ out.reference_compounds.push(s.reference_compound);
464
+ }
465
+ if (p.analyte && p.kind !== 'identity' && p.kind !== 'unit_arithmetic')
466
+ out.warnings.push(...(ANALYTES.get(p.analyte).caveats ?? []));
467
+ if (value !== undefined && value !== null) {
468
+ const v = parseValue(value);
469
+ out.value = v;
470
+ out.result = p.a * v + p.b;
471
+ }
472
+ return out;
473
+ }
474
+ /** snake_case aliases matching the Python API names. */
475
+ export const normalize_unit = normalizeUnit;
476
+ export const same_unit = sameUnit;
477
+ export const parse_value = parseValue;
478
+ export const parse_result = parseResult;
479
+ export const convert_result = convertResult;
480
+ export const unit_info = unitInfo;
@@ -0,0 +1,104 @@
1
+ /** Shape of units.json (data/units.json), shared with the Python package. */
2
+ export interface Rule {
3
+ pattern: string;
4
+ replacement: string;
5
+ note: string;
6
+ }
7
+ export interface UnitRecord {
8
+ unit: string;
9
+ dimension: string;
10
+ /** Multiply a value in this unit by `scale` to get the dimension's base unit. */
11
+ scale: number;
12
+ aliases: string[];
13
+ case_sensitive_aliases: string[];
14
+ ucum: string | null;
15
+ note: string | null;
16
+ }
17
+ export interface Source {
18
+ id?: string;
19
+ label: string;
20
+ url: string;
21
+ kind: string;
22
+ accessed: string;
23
+ doi?: string;
24
+ location?: string;
25
+ pubchem_cid?: number;
26
+ formula?: string;
27
+ molar_mass?: string;
28
+ element?: string;
29
+ api_url?: string;
30
+ title?: string;
31
+ }
32
+ export interface Bridge {
33
+ from: string;
34
+ to: string;
35
+ /** base_to = a * base_from + b */
36
+ a: number;
37
+ b: number;
38
+ kind: string;
39
+ description: string;
40
+ basis: string;
41
+ sources: string[];
42
+ display: Record<string, string> | null;
43
+ reference_compound?: ReferenceCompound | null;
44
+ }
45
+ export interface ReferenceCompound {
46
+ name: string;
47
+ molar_mass: number;
48
+ molar_mass_text: string;
49
+ unit: string;
50
+ source: string;
51
+ pubchem_cid?: number;
52
+ formula?: string;
53
+ element?: string;
54
+ }
55
+ export interface Analyte {
56
+ id: string;
57
+ name: string;
58
+ marker_slugs: string[];
59
+ molar_mass: {
60
+ value: number;
61
+ unit: string;
62
+ source: string;
63
+ } | null;
64
+ charge: number | null;
65
+ bridges: Bridge[];
66
+ note: string | null;
67
+ caveats: string[];
68
+ caveat_sources: string[];
69
+ }
70
+ export interface Forbidden {
71
+ id: string;
72
+ analyte: string | null;
73
+ a: string;
74
+ b: string;
75
+ a_units: string[] | null;
76
+ b_units: string[] | null;
77
+ example: string[];
78
+ reason: string;
79
+ sources: string[];
80
+ }
81
+ export interface Spec {
82
+ name: string;
83
+ version: string;
84
+ schema_version: number;
85
+ normalization: {
86
+ rules: Rule[];
87
+ procedure: string;
88
+ };
89
+ dimensions: Record<string, {
90
+ name: string;
91
+ base: string;
92
+ convertible: boolean;
93
+ }>;
94
+ units: UnitRecord[];
95
+ lookup: {
96
+ exact: Record<string, string>;
97
+ casefold: Record<string, string>;
98
+ analytes: Record<string, string>;
99
+ };
100
+ analytes: Analyte[];
101
+ forbidden: Forbidden[];
102
+ arbitrary_reason: string;
103
+ sources: Record<string, Source>;
104
+ }
@@ -0,0 +1,2 @@
1
+ /** Shape of units.json (data/units.json), shared with the Python package. */
2
+ export {};