All files / src/helpers oshaChemicalDb.ts

100% Statements 146/146
88.88% Branches 40/45
100% Functions 7/7
100% Lines 146/146

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 3041x 1x 1x 1x 1x   1x                                                                                                                                       1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x                         1x 1x 43x 43x   1x           1x 195x 195x 195x 195x 195x 195x 195x 195x   1x                           1x 1x 4x 4x 1x 1x   3x 4x 9x 9x   6x 6x 9x 9x 9x 9x 9x 9x 180x 180x 21x 180x 180x 180x 6x 6x 3x 3x                         1x   1x         1x 7x 7x 7x 14x 14x 35x 35x 35x 35x 35x 14x 7x 7x   1x                         1x 8x 8x 8x 8x 8x 5x 5x 3x 3x 3x 3x 3x 8x 2x 2x 2x 8x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x   1x                         1x 1x 8x 8x 7x 8x 6x 8x 8x   1x                 1x 1x 10x 10x  
import { chemicalDb } from '@/../config.json';
import { getChemicalDb, putChemicalDb } from '@/utils/idbCache';
import { isCAS } from '@/utils/typeGuards/common';
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
 
const logger = new Logger('oshaChemicalDb');
 
/**
 * A slimmed OSHA OBIS chemical record. Only the fields the chemical-info dialog shows are kept;
 * the ~100 sampling-method / detector-tube fields in the source XML are dropped. Every value is
 * optional because OBIS leaves many fields blank.
 * @category Science Helpers
 * @group Chemical Info
 */
export interface OshaChemical {
  /** Display name, with OBIS's trailing `†`/`‡` markers removed. */
  name: string;
  /** CAS registry number. */
  cas?: string;
  /** Formula, using Unicode subscripts as OBIS publishes it. */
  formula?: string;
  /** Alternate names. */
  synonyms: string[];
  physicalDescription?: string;
  molecularWeight?: string;
  boilingPoint?: string;
  freezingPoint?: string;
  flashPoint?: string;
  vaporPressure?: string;
  specificGravity?: string;
  relativeGasDensity?: string;
  ionizationPotential?: string;
  lowerExplosiveLimit?: string;
  upperExplosiveLimit?: string;
  /** NFPA 704 health rating (0-4). */
  nfpaHealth?: string;
  /** NFPA 704 flammability rating (0-4). */
  nfpaFire?: string;
  /** NFPA 704 instability rating (0-4). */
  nfpaReactivity?: string;
  /** NFPA 704 special notice, e.g. `W` or `OX`. */
  nfpaSpecial?: string;
  pelTwa?: string;
  pelStel?: string;
  pelCeiling?: string;
  relTwa?: string;
  relStel?: string;
  relCeiling?: string;
  tlvTwa?: string;
  tlvStel?: string;
  tlvCeiling?: string;
  idlh?: string;
  carcinogen?: string;
  /** Link to the NIOSH Pocket Guide entry. */
  nioshPocketGuideUrl?: string;
  /** Link to the NOAA CAMEO Chemicals datasheet. */
  cameoUrl?: string;
}
 
/**
 * The single `chemical_db` IndexedDB row.
 * @category Science Helpers
 * @group Chemical Info
 */
export interface ChemicalDbRecord {
  /** Row key; always `"current"`. */
  id: string;
  /** Epoch milliseconds the dataset was downloaded. */
  fetchedAt: number;
  /** Slimmed chemical records. */
  chemicals: OshaChemical[];
}
 
/**
 * Maps each {@link OshaChemical} field (except `name`/`synonyms`) to its OBIS XML element.
 * @source
 */
const FIELD_MAP: ReadonlyArray<readonly [keyof OshaChemical, string]> = [
  ['cas', 'CASNumber'],
  ['formula', 'Formula'],
  ['physicalDescription', 'PhysicalDescription'],
  ['molecularWeight', 'MolecularWeight'],
  ['boilingPoint', 'BoilingPoint'],
  ['freezingPoint', 'FreezingPoint'],
  ['flashPoint', 'FlashPoint'],
  ['vaporPressure', 'VaporPressure'],
  ['specificGravity', 'SpecificGravity'],
  ['relativeGasDensity', 'RelativeGasDensity'],
  ['ionizationPotential', 'IonizationPotential'],
  ['lowerExplosiveLimit', 'LowerExplosiveLimit'],
  ['upperExplosiveLimit', 'UpperExplosiveLimit'],
  ['nfpaHealth', 'NFPAHealthRating'],
  ['nfpaFire', 'NFPAFireRating'],
  ['nfpaReactivity', 'NFPAReactivityRating'],
  ['nfpaSpecial', 'NFPASpecialInstruction'],
  ['pelTwa', 'PELTWAppm'],
  ['pelStel', 'PELSTELppm'],
  ['pelCeiling', 'PELCppm'],
  ['relTwa', 'RELTWAppm'],
  ['relStel', 'RELSTELppm'],
  ['relCeiling', 'RELCppm'],
  ['tlvTwa', 'TLVTWAppm'],
  ['tlvStel', 'TLVSTELppm'],
  ['tlvCeiling', 'TLVCppm'],
  ['idlh', 'IDLHppm'],
  ['carcinogen', 'Carcinogen'],
  ['nioshPocketGuideUrl', 'NIOSHpgURL'],
  ['cameoUrl', 'ERCameoURL'],
];
 
/**
 * Normalizes a chemical name for matching: lowercase, OBIS dagger markers removed, and runs of
 * whitespace collapsed.
 * @category Science Helpers
 * @group Chemical Info
 * @param name - A chemical name or synonym.
 * @returns The normalized key.
 * @example
 * ```ts
 * normalizeChemicalName('ACETONE†'); // "acetone"
 * normalizeChemicalName('  Sodium   Hydroxide '); // "sodium hydroxide"
 * ```
 * @source
 */
export function normalizeChemicalName(name: string): string {
  return name.replace(/[†‡]/g, '').replace(/\s+/g, ' ').trim().toLowerCase();
}
 
/**
 * Reads one child element's text from an OBIS `<chemical>` node, stripping embedded HTML.
 * @param node - The `<chemical>` element.
 * @param tag - The child element name.
 * @returns The cleaned text, or undefined when blank.
 * @source
 */
function readField(node: Element, tag: string): string | undefined {
  const raw = node.getElementsByTagName(tag)[0]?.textContent ?? '';
  const text = raw
    .replace(/<[^>]*>/g, '')
    .replace(/\s+/g, ' ')
    .trim();
  return text === '' ? undefined : text;
}
 
/**
 * Parses the OBIS `Chemical_DB.xml` document into slimmed records. Records without a name are
 * skipped. Requires `DOMParser` (available on extension pages, not in the service worker).
 * @category Science Helpers
 * @group Chemical Info
 * @param xml - The raw XML text.
 * @returns The slimmed chemical records.
 * @throws When the XML is malformed.
 * @example
 * ```ts
 * parseOshaXml('<chemical_db><chemical><Analyte>ACETONE</Analyte><CASNumber>67-64-1</CASNumber></chemical></chemical_db>');
 * // [{ name: "ACETONE", cas: "67-64-1", synonyms: [] }]
 * ```
 * @source
 */
export function parseOshaXml(xml: string): OshaChemical[] {
  const doc = new DOMParser().parseFromString(xml, 'text/xml');
  if (doc.getElementsByTagName('parsererror').length > 0) {
    throw new Error('Malformed OSHA OBIS XML');
  }
 
  const chemicals: OshaChemical[] = [];
  for (const node of Array.from(doc.getElementsByTagName('chemical'))) {
    const analyte = readField(node, 'Analyte');
    if (analyte === undefined) continue;
 
    const chemical: OshaChemical = {
      name: analyte.replace(/[†‡]/g, '').trim(),
      synonyms: (readField(node, 'Synonyms') ?? '')
        .split(';')
        .map((synonym) => synonym.trim())
        .filter((synonym) => synonym !== ''),
    };
    for (const [field, tag] of FIELD_MAP) {
      const raw = readField(node, tag);
      if (raw === undefined) continue;
      // OBIS publishes links without a scheme.
      const value = tag.endsWith('URL') && !/^https?:\/\//.test(raw) ? `https://${raw}` : raw;
      Object.assign(chemical, { [field]: value });
    }
    chemicals.push(chemical);
  }
  return chemicals;
}
 
/**
 * Lookup indexes over the loaded dataset.
 * @source
 */
interface OshaIndex {
  byCas: Map<string, OshaChemical>;
  byName: Map<string, OshaChemical>;
  /** Normalized name → sorted-token key, for word-order-insensitive matches. */
  byTokens: Map<string, OshaChemical>;
}
 
let indexPromise: Promise<OshaIndex | undefined> | undefined;
 
/**
 * Builds the in-memory lookup indexes for a dataset.
 * @param chemicals - The chemical records.
 * @returns The indexes.
 * @source
 */
function buildIndex(chemicals: OshaChemical[]): OshaIndex {
  const index: OshaIndex = { byCas: new Map(), byName: new Map(), byTokens: new Map() };
  for (const chemical of chemicals) {
    if (chemical.cas !== undefined) index.byCas.set(chemical.cas, chemical);
    for (const name of [chemical.name, ...chemical.synonyms]) {
      const key = normalizeChemicalName(name);
      if (!index.byName.has(key)) index.byName.set(key, chemical);
      const tokenKey = key.split(' ').sort().join(' ');
      if (!index.byTokens.has(tokenKey)) index.byTokens.set(tokenKey, chemical);
    }
  }
  return index;
}
 
/**
 * Loads the OBIS dataset from IndexedDB, downloading and caching it when missing or older than
 * `chemicalDb.ttlDays`. The download is abandoned after `chemicalDb.fetchTimeoutMs`, and a stale copy is
 * still used when the refresh fails or times out. The result is memoized
 * for the page's lifetime.
 * @category Science Helpers
 * @group Chemical Info
 * @returns The lookup index, or undefined when no copy is cached and the download failed.
 * @example
 * ```ts
 * const index = await loadOshaIndex();
 * ```
 * @source
 */
function loadOshaIndex(): Promise<OshaIndex | undefined> {
  indexPromise ??= (async () => {
    const cached = await getChemicalDb();
    const ttlMs = chemicalDb.ttlDays * 24 * 60 * 60 * 1000;
    if (cached !== undefined && Date.now() - cached.fetchedAt < ttlMs) {
      return buildIndex(cached.chemicals);
    }
    try {
      // The signal also covers reading the body, so a stalled download can't hang the dialog.
      const response = await fetch(chemicalDb.url, {
        signal: AbortSignal.timeout(chemicalDb.fetchTimeoutMs),
      });
      if (!response.ok) throw new Error(`OSHA OBIS responded ${response.status}`);
      const chemicals = parseOshaXml(await response.text());
      await putChemicalDb(chemicals, Date.now());
      return buildIndex(chemicals);
    } catch (error) {
      logger.error(`Failed to download OSHA OBIS chemical DB: ${getErrorMessage(error)}`, {
        error,
      });
      return cached === undefined ? undefined : buildIndex(cached.chemicals);
    }
  })();
  // Don't memoize a failure; let the next open retry.
  void indexPromise.then((index) => {
    if (index === undefined) indexPromise = undefined;
  });
  return indexPromise;
}
 
/**
 * Looks a searched term up in the OSHA OBIS dataset by CAS number, exact name/synonym, or the
 * same words in any order (so "hydroxide sodium" still finds "sodium hydroxide").
 * @category Science Helpers
 * @group Chemical Info
 * @param term - A chemical name or CAS number.
 * @returns The matching record, or undefined when OBIS has none or is unavailable.
 * @example
 * ```ts
 * await lookupOshaChemical('67-64-1'); // { name: "ACETONE", nfpaHealth: "1", ... }
 * await lookupOshaChemical('hydroxide sodium'); // { name: "SODIUM HYDROXIDE", ... }
 * ```
 * @source
 */
export async function lookupOshaChemical(term: string): Promise<OshaChemical | undefined> {
  const index = await loadOshaIndex();
  if (index === undefined) return undefined;
  const trimmed = term.trim();
  if (isCAS(trimmed)) return index.byCas.get(trimmed);
  const key = normalizeChemicalName(trimmed);
  return index.byName.get(key) ?? index.byTokens.get(key.split(' ').sort().join(' '));
}
 
/**
 * Clears the memoized index so the next lookup reloads from storage. Test helper.
 * @category Science Helpers
 * @group Chemical Info
 * @example
 * ```ts
 * resetOshaIndex();
 * ```
 * @source
 */
export function resetOshaIndex(): void {
  indexPromise = undefined;
}