formlab-mcp 0.6.61 → 0.6.63

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.
@@ -230,7 +230,8 @@ function _tpTransformRefs(expr) {
230
230
  // _tpHas(field, 'Binder'), which matches ANY of the pipe-separated labels,
231
231
  // trimmed and case-insensitively (labels are vocabulary, not case-sensitive
232
232
  // data). Single-valued fields keep exact equality (2026-09-13).
233
- const MV = "(r\\.ing\\['(?:function|tags)'\\])";
233
+ // `class` too (28 Oct): classes are stored lowercase ('pigment'), and the PVC preset asked for 'Pigment'.
234
+ const MV = "(r\\.ing\\['(?:function|tags|class)'\\])";
234
235
  const LIT = "('(?:[^'\\\\]|\\\\.)*'|\"(?:[^\"\\\\]|\\\\.)*\")";
235
236
  const OP = "\\s*(===|!==|==|!=)\\s*";
236
237
  const has = (neg, f, l) => (neg ? '!' : '') + '_tpHas(' + f + ',' + l + ')';
@@ -406,8 +407,10 @@ function _tpEvaluateAll(params, rows) {
406
407
  }
407
408
 
408
409
  // Build the row set the evaluator iterates. Sub-formula rows are
409
- // included (so `SUM(row.amount)` is correct) but their `ing` is empty
410
- // (so chemistry-aware aggregations naturally skip them). Custom
410
+ // included (so `SUM(row.amount)` is correct); their `ing` carries what rolls
411
+ // up from their own composition by mass: the reactive groups and the
412
+ // per-mass fields (_tpSubRollup). Density, Tg, HLB and class-based sums
413
+ // (PVC, VOC) don't add by mass, so those still skip a premix and say so. Custom
411
414
  // ingredient fields are flattened into `ing.{name}` alongside the
412
415
  // standard fields, with numeric coercion when the string parses.
413
416
  function _tpBuildRows(composition) {
@@ -436,7 +439,12 @@ function _tpBuildRows(composition) {
436
439
  // — the user can either flatten the recipe or attach the relevant
437
440
  // properties to the sub-formula's parent representation later.
438
441
  const sub = db.formulations.find(g => g.id === c.formulationId);
439
- rows.push({ ...base, ing: { _isSubFormula: true }, _srcSub: c.formulationId, _subName: (sub && sub.name) || 'sub-formula' });
442
+ // Reactive groups pass through (js/reactive.js, step 4): a premix or a kit's Part A / B carries its own
443
+ // composition's ing.epoxy … ing.vinyl, mass-weighted. Every other field stays absent on it.
444
+ const rx = (sub && typeof flRxSubViewFields === 'function') ? flRxSubViewFields(sub) : {};
445
+ // Per-field rules (Jun, 28 Oct): the fields that add up by mass roll up too (_tpSubRollup).
446
+ const roll = sub ? _tpSubRollup(sub) : { fields: {}, units: {} };
447
+ rows.push({ ...base, ing: _tpCiView({ _isSubFormula: true, ...roll.fields, ...rx }), _cfUnits: roll.units, _srcSub: c.formulationId, _subName: (sub && sub.name) || 'sub-formula' });
440
448
  }
441
449
  });
442
450
  // ABSOLUTE rows (a batch's as-prepared composition: 215.9 g water, 6.6 mL
@@ -469,6 +477,58 @@ function _tpBuildRows(composition) {
469
477
  return rows;
470
478
  }
471
479
 
480
+ // A premix's fields for its row in the parent (Jun, 28 Oct: "yes to per-field rules"). A field rolls up as the
481
+ // mass-weighted mean over the premix's rows when it adds by mass: a custom field in a per-mass unit (%, g/100 g,
482
+ // mg/kg, ppm, mg KOH/g …), or a known per-mass name with no unit (solids, NV %, protein, fat …). Only when every row
483
+ // with an amount has a number for it, in one unit: a premix with a solvent missing its solids is still "not
484
+ // counted", as before. Not rolled: density (by volume), Tg, HLB, purity, cost, text fields. Nested premixes roll up
485
+ // through _tpBuildRows; a cycle rolls up nothing.
486
+ const _TP_MASS_UNIT = /^(%|wt\s*%|%\s*w\/w|w\/w\s*%?|g\s*\/\s*100\s*g|mg\s*\/\s*100\s*g|g\s*\/\s*kg|mg\s*\/\s*kg|ppm|ppb|mg\s*koh\s*\/\s*g|meq\s*\/\s*g|mmol\s*\/\s*g)$/i;
487
+ const _TP_MASS_NAMES = new Set(['solids', 'nv', 'nv %', 'nv%', 'non-volatiles', 'nonvolatiles', 'protein', 'fat', 'carb', 'carbs', 'carbohydrate', 'sugar', 'sugars', 'sodium', 'salt', 'fiber', 'fibre', 'ash', 'moisture',
488
+ 'volume', 'pigmentvolume', 'dryvolume', 'volatileorganic', 'voc %']); // per gram, so they add by mass (PVC, VOC through a premix)
489
+ const _TP_NOT_ROLLED = new Set(['density', 'mw', 'cost', 'purity', 'stock', 'reorder', 'tg', 'hlb', 'taxonid']);
490
+ const _tpSubStack = new Set();
491
+ // Inside _tpWithSubMemo each premix rolls up once: a Solve rebuilds the same rows ~80 times with only the top-level
492
+ // amounts moving, and recomputing every premix took 60–85 ms a keystroke at 3–5 premixes (sweep, 29 Oct).
493
+ let _tpSubMemo = null;
494
+ function _tpWithSubMemo(fn) {
495
+ if (_tpSubMemo) return fn();
496
+ _tpSubMemo = new Map();
497
+ try { return fn(); } finally { _tpSubMemo = null; }
498
+ }
499
+ function _tpSubRollup(sub) {
500
+ if (!_tpSubMemo || !sub || !sub.id || _tpSubStack.has(sub.id)) return _tpSubRollupCalc(sub);
501
+ if (!_tpSubMemo.has(sub.id)) _tpSubMemo.set(sub.id, _tpSubRollupCalc(sub));
502
+ const m = _tpSubMemo.get(sub.id);
503
+ return { fields: { ...m.fields }, units: { ...m.units } };
504
+ }
505
+ function _tpSubRollupCalc(sub) {
506
+ const none = { fields: {}, units: {} };
507
+ if (!sub || !sub.id || _tpSubStack.has(sub.id)) return none;
508
+ _tpSubStack.add(sub.id);
509
+ try {
510
+ const rows = _tpBuildRows(sub.composition || []).filter(r => r && r.amount > 0 && r.ing && !r.ing._missing);
511
+ const total = rows.reduce((t, r) => t + r.amount, 0);
512
+ if (!rows.length || !(total > 0)) return none;
513
+ const keys = new Set();
514
+ rows.forEach(r => Object.keys(r.ing).forEach(k => { if (k[0] !== '_') keys.add(k); }));
515
+ const out = { fields: {}, units: {} };
516
+ keys.forEach(k => {
517
+ const lk = k.toLowerCase();
518
+ if (_TP_NOT_ROLLED.has(lk) || _TP_TEXT_FIELDS.has(lk) || (typeof FL_RX_GROUPS !== 'undefined' && FL_RX_GROUPS[k])) return;
519
+ const units = new Set(rows.map(r => (r._cfUnits && r._cfUnits[lk]) || ''));
520
+ if (units.size > 1) return; // mixed units: not one quantity
521
+ const unit = [...units][0];
522
+ if (!(unit ? _TP_MASS_UNIT.test(unit.trim()) : _TP_MASS_NAMES.has(lk))) return;
523
+ let t = 0;
524
+ for (const r of rows) { const v = r.ing[k]; if (typeof v !== 'number' || !Number.isFinite(v)) return; t += r.amount * v; }
525
+ out.fields[k] = t / total;
526
+ if (unit) out.units[lk] = unit;
527
+ });
528
+ return out;
529
+ } finally { _tpSubStack.delete(sub.id); }
530
+ }
531
+
472
532
  // Project an ingredient onto the flat `ing.X` namespace the formula
473
533
  // language uses. Standard fields are exposed under their canonical
474
534
  // names; custom fields are merged in by name with numeric coercion
@@ -518,6 +578,10 @@ function _tpIngredientView(ing) {
518
578
  out.reorder = num(ing.reorderThreshold); // reorder point — filterable (stock <= reorder)
519
579
  out.tg = (typeof _ingTg === 'function') ? _ingTg(ing) : num(ing.tg); // glass transition °C (any class) — filterable (tg < 50) + usable in theo formulas (ing.tg)
520
580
  out.hlb = (typeof _ingHlb === 'function') ? _ingHlb(ing) : num(ing.surfactantDetails ? ing.surfactantDetails.hlb : ing.hlb); // HLB (surfactants) — filterable (hlb < 10) + usable in theo formulas (ing.hlb), e.g. Blend HLB preset
581
+ // Reactive groups (js/reactive.js): ing.epoxy … ing.vinyl in meq/g, 0 when absent so a solvent adds nothing to
582
+ // the Reactive presets' sums; the datasheet terms (ing.eew, ing.ohv, ing.ncoPct …) null when absent, so
583
+ // `eew < 200` skips ingredients without one. Custom fields below still win on a name clash.
584
+ if (typeof flRxViewFields === 'function') Object.assign(out, flRxViewFields(ing));
521
585
  (ing.customFields || []).forEach(cf => {
522
586
  if (!cf || !cf.name) return;
523
587
  const raw = cf.value;
@@ -525,11 +589,22 @@ function _tpIngredientView(ing) {
525
589
  if (cf.name === '__proto__') return; // would set the prototype, not a field
526
590
  out[cf.name] = (n !== null && raw !== null && raw !== '') ? n : raw;
527
591
  });
592
+ // Per gram, for PVC and VOC (28 Oct): volume (mL/g), pigment volume, dry volume, volatile organic mass (g/g). They
593
+ // add by mass, so they roll up through a premix (_tpSubRollup) where the old class-filtered sums could not.
594
+ // pigment / filler / extender (class pigment, or that function): all of it is pigment and dry
595
+ // a solvent (function Solvent; water is not a VOC): all of it volatile, none dry
596
+ // anything else: dry by its solids (ing.solids or 'NV %'), volatile organic only by a 'VOC %' field
597
+ Object.assign(out, _tpPerGramFields(ing, out), Object.fromEntries(Object.entries(out).filter(([k]) => _TP_PER_GRAM.has(k))));
528
598
  // Wrap in a Proxy that does case-insensitive property reads. Bracket
529
599
  // form `ing['Solids']` and dotted form `ing.Solids` both flow through
530
600
  // here, so a single hook covers every access path the formula language
531
601
  // emits. Iteration (Object.keys, JSON.stringify) still sees the
532
602
  // original-cased keys — only get/has are normalized.
603
+ return _tpCiView(out);
604
+ }
605
+
606
+ // Case-insensitive, own-fields-only view of a flat field object (ing.Solids = ing.solids; nothing inherited).
607
+ function _tpCiView(out) {
533
608
  const lowerIndex = {};
534
609
  Object.keys(out).forEach(k => { lowerIndex[k.toLowerCase()] = k; });
535
610
  // OWN fields only (17m): `prop in target` also answered for what every object
@@ -551,6 +626,25 @@ function _tpIngredientView(ing) {
551
626
  });
552
627
  }
553
628
 
629
+ const _TP_FIELD_NEEDS = { volume: 'density', pigmentvolume: 'density', dryvolume: 'density or solids' };
630
+ const _TP_PER_GRAM = new Set(['volume', 'pigmentVolume', 'dryVolume', 'volatileOrganic']); // a custom field of the same name wins
631
+ function _tpPerGramFields(ing, view) {
632
+ const d = (typeof _densityToKgPerL === 'function') ? _densityToKgPerL(ing.density, ing.densityUnit) : (parseFloat(ing.density) || null);
633
+ const vol = d > 0 ? 1 / d : null; // kg/L = g/mL, so 1/d is mL per g
634
+ const labels = String(ing.function || '').toLowerCase().split('|').map(x => x.trim());
635
+ const pigment = String(ing.ingredientClass || '').toLowerCase() === 'pigment' || labels.some(x => /^(pigment|filler|extender)\b/.test(x));
636
+ const water = String(ing.cas || '').trim() === '7732-18-5' || /^(water|aqua)\b/i.test(String(ing.name || '').trim());
637
+ const solvent = !pigment && labels.some(x => /\bsolvent\b/.test(x));
638
+ const solids = [view.solids, view['NV %'], view['nv %']].map(v => (typeof v === 'number' && Number.isFinite(v) ? v : null)).find(v => v != null);
639
+ const vocPct = typeof view['VOC %'] === 'number' ? view['VOC %'] : null;
640
+ return {
641
+ volume: vol,
642
+ pigmentVolume: pigment ? vol : 0,
643
+ dryVolume: pigment ? vol : (solvent || water) ? 0 : (solids != null && vol != null ? vol * solids / 100 : null),
644
+ volatileOrganic: vocPct != null ? vocPct / 100 : (solvent && !water) ? 1 : 0,
645
+ };
646
+ }
647
+
554
648
  // Resolve the effective parameter list for a batch. Batches inherit
555
649
  // from formula unless overridden. Mirrors the Procedure pattern
556
650
  // (batch.stepsOverride wins when present).
@@ -794,7 +888,8 @@ function _tpCalcHtml(p, evalRows, valueMap) {
794
888
  if (showEntered) cells.push(td(entered, muted));
795
889
  if (usesAmount) cells.push(td(num(r.amount)));
796
890
  fields.forEach(f => {
797
- const v = isSub ? undefined : (r.ing && r.ing[f]);
891
+ // A sub-formula row shows what it rolls up (reactive groups, per-mass fields: _tpSubRollup); the rest stays "missing".
892
+ const v = r.ing && r.ing[f];
798
893
  cells.push(typeof v === 'number' && Number.isFinite(v) ? td(num(v)) : td('missing', 'color:var(--dk-amber-fg, #b45309);font-style:italic'));
799
894
  });
800
895
  byAgg.forEach((m, k) => {
@@ -854,7 +949,11 @@ function _tpMissingInputs(formula, rows) {
854
949
  const unitsBy = {}; // field → { unit: [ingredient names] }, rows that have a value
855
950
  (rows || []).forEach(r => {
856
951
  if (!r || !r.ing || !(r.amount > 0 || r.amount < 0)) return;
857
- if (r.ing._isSubFormula) { res.subs.push(r._subName || 'sub-formula'); return; }
952
+ if (r.ing._isSubFormula) {
953
+ // Counted when it carries every field the formula reads (reactive groups roll up into it).
954
+ if (!fields.every(f => typeof r.ing[f] === 'number' && Number.isFinite(r.ing[f]))) res.subs.push(r._subName || 'sub-formula');
955
+ return;
956
+ }
858
957
  const nm = r.ing._missing ? '(deleted ingredient)' : (r.ing.name || '(unnamed)');
859
958
  fields.forEach(f => {
860
959
  const v = r.ing._missing ? undefined : r.ing[f];
@@ -883,8 +982,10 @@ function _tpMissingNote(miss) {
883
982
  const parts = [], tips = [];
884
983
  if (miss.ingredients.length) {
885
984
  const n = miss.ingredients.length;
886
- parts.push(`${n} ingredient${n === 1 ? '' : 's'} missing ${miss.fields.map(x => x.field).join(', ')}`);
887
- miss.fields.forEach(x => tips.push(`No ${x.field}: ${x.names.join(', ')}`));
985
+ // The per-gram fields name what they're made from (PVC, VOC): "missing density", not "missing dryvolume".
986
+ const need = f => _TP_FIELD_NEEDS[f] || f;
987
+ parts.push(`${n} ingredient${n === 1 ? '' : 's'} missing ${[...new Set(miss.fields.map(x => need(x.field)))].join(', ')}`);
988
+ miss.fields.forEach(x => tips.push(`No ${need(x.field)}: ${x.names.join(', ')}`));
888
989
  tips.push('Those rows are not counted. Enter 0 where an ingredient truly has none.');
889
990
  }
890
991
  (miss.mixed || []).forEach(m => {
@@ -1393,15 +1494,15 @@ function _tpPresetCatalog() {
1393
1494
  group: 'Coatings',
1394
1495
  name: 'Pigment Volume Concentration (PVC)',
1395
1496
  unit: '%',
1396
- formula: "100 * SUM(row.amount / ing.density WHERE ing.class == 'Pigment') / SUM(row.amount / ing.density WHERE ing.density)",
1397
- description: 'PVC = pigment volume / total non-volatile volume. Needs ing.density and ing.class on each row.',
1497
+ formula: "100 * SUM(row.amount * ing.pigmentVolume) / SUM(row.amount * ing.dryVolume)",
1498
+ description: 'PVC = pigment and filler volume / dry film volume. Needs ing.density on every row, and ing.solids on binders and additives (pigments, fillers and solvents need none). Counts through premixes.',
1398
1499
  },
1399
1500
  {
1400
1501
  group: 'Coatings',
1401
1502
  name: 'VOC (g/L)',
1402
1503
  unit: 'g/L',
1403
- formula: "1000 * SUM(row.amount WHERE ing.class == 'Solvent') / SUM(row.amount / ing.density WHERE ing.density)",
1404
- description: 'Volatile-organic-compound load per liter of paint. Needs ing.class and ing.density.',
1504
+ formula: "1000 * SUM(row.amount * ing.volatileOrganic) / SUM(row.amount * ing.volume)",
1505
+ description: 'Volatile organic grams per liter of paint (water not counted). Solvents count whole; give a resin solution a VOC % field. Needs ing.density on every row. Counts through premixes.',
1405
1506
  },
1406
1507
  {
1407
1508
  group: 'Coatings',
@@ -1410,6 +1511,72 @@ function _tpPresetCatalog() {
1410
1511
  formula: "100 * SUM(row.amount * ing.solids) / (100 * SUM(row.amount))",
1411
1512
  description: 'Same as NV but rescaled to 0–100 if ing.solids is stored as fraction (0–1).',
1412
1513
  },
1514
+ // ---- Reactive (js/reactive.js; Jun 27 Oct: an index everywhere, acid counts toward the NCO demand) ----
1515
+ // ing.epoxy … ing.vinyl are meq/g from each ingredient's Reactive groups (0 when it has none). The formula's
1516
+ // Composition tab shows the same numbers in its balance strip.
1517
+ {
1518
+ group: 'Reactive',
1519
+ name: 'Amine H : epoxy index',
1520
+ unit: '',
1521
+ formula: '100 * SUM(row.amount * ing.amineH) / SUM(row.amount * ing.epoxy)',
1522
+ description: 'Amine H equivalents per 100 epoxy equivalents; 100 = stoichiometric. From each ingredient’s Reactive groups (EEW, AHEW).',
1523
+ },
1524
+ {
1525
+ group: 'Reactive',
1526
+ name: 'Isocyanate index',
1527
+ unit: '',
1528
+ formula: '100 * SUM(row.amount * ing.nco) / SUM(row.amount * (ing.oh + ing.amineH + ing.cooh))',
1529
+ description: 'NCO equivalents per 100 equivalents of OH, amine H and COOH. From NCO %, OH number, AHEW and acid value. Water isn’t counted: see the preset with water.',
1530
+ },
1531
+ {
1532
+ group: 'Reactive',
1533
+ name: 'Isocyanate index (with water)',
1534
+ unit: '',
1535
+ formula: '100 * SUM(row.amount * ing.nco) / SUM(row.amount * (ing.oh + ing.amineH + ing.cooh + ing.h2o))',
1536
+ description: 'As the isocyanate index, with water counted (one H₂O takes two NCO): foams and moisture cure. Water itself counts; give other ingredients a Water group for their moisture.',
1537
+ },
1538
+ {
1539
+ group: 'Reactive',
1540
+ name: 'Si-H : vinyl index',
1541
+ unit: '',
1542
+ formula: '100 * SUM(row.amount * ing.sih) / SUM(row.amount * ing.vinyl)',
1543
+ description: 'Si-H per 100 vinyl equivalents, for addition-cure silicones. From each ingredient’s Si-H and vinyl content.',
1544
+ },
1545
+ {
1546
+ group: 'Reactive',
1547
+ name: 'Degree of neutralization',
1548
+ unit: '%',
1549
+ formula: '100 * SUM(row.amount * ing.amine) / SUM(row.amount * ing.cooh)',
1550
+ description: 'Amine equivalents per 100 acid equivalents, for waterborne resins. From amine value and acid value.',
1551
+ },
1552
+ {
1553
+ group: 'Reactive',
1554
+ name: 'Blend EEW',
1555
+ unit: 'g/eq',
1556
+ formula: '1000 * SUM(row.amount WHERE ing.epoxy > 0) / SUM(row.amount * ing.epoxy)',
1557
+ description: 'Epoxy equivalent weight of the epoxy-bearing part (resins and reactive diluents).',
1558
+ },
1559
+ {
1560
+ group: 'Reactive',
1561
+ name: 'Blend OHV',
1562
+ unit: 'mg KOH/g',
1563
+ formula: '56.1 * SUM(row.amount * ing.oh) / SUM(row.amount)',
1564
+ description: 'OH number of the whole formula, from each ingredient’s OH number.',
1565
+ },
1566
+ {
1567
+ group: 'Reactive',
1568
+ name: 'Blend AV',
1569
+ unit: 'mg KOH/g',
1570
+ formula: '56.1 * SUM(row.amount * ing.cooh) / SUM(row.amount)',
1571
+ description: 'Acid value of the whole formula, from each ingredient’s acid value.',
1572
+ },
1573
+ {
1574
+ group: 'Reactive',
1575
+ name: 'Blend NCO',
1576
+ unit: '%',
1577
+ formula: '4.202 * SUM(row.amount * ing.nco) / SUM(row.amount)',
1578
+ description: 'NCO content of the whole formula (a Part B or a prepolymer), from each ingredient’s NCO %.',
1579
+ },
1413
1580
  // ---- Surfactants / emulsions ----
1414
1581
  {
1415
1582
  group: 'Surfactants',