formlab-mcp 0.6.84 → 0.6.86

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "formlab-mcp",
3
- "version": "0.6.84",
3
+ "version": "0.6.86",
4
4
  "mcpName": "io.github.juliu1980/formlab-mcp",
5
5
  "description": "Read-only Model Context Protocol server for FormLab. Lets Claude and other MCP clients read and analyze your FormLab data, from a local export file or your live cloud workspace.",
6
6
  "homepage": "https://formvix.com/mcp",
package/server.json CHANGED
@@ -2,13 +2,13 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.juliu1980/formlab-mcp",
4
4
  "description": "Read-only MCP server for FormLab formulation data: a local export file or your live cloud workspace.",
5
- "version": "0.6.84",
5
+ "version": "0.6.86",
6
6
  "websiteUrl": "https://formvix.com/mcp",
7
7
  "packages": [
8
8
  {
9
9
  "registryType": "npm",
10
10
  "identifier": "formlab-mcp",
11
- "version": "0.6.84",
11
+ "version": "0.6.86",
12
12
  "runtimeHint": "npx",
13
13
  "transport": {
14
14
  "type": "stdio"
package/theoretical.js CHANGED
@@ -47,6 +47,9 @@ const EPILOGUE = `
47
47
  }
48
48
  // The Label tab's numbers (js/views/nutrition-label.js, 0.6.83; the EU ingredient list 0.6.84). The app's allergen roll-up lives in a file that is not
49
49
  // vendored; this is the same walk over the flattened leaves.
50
+ // The viewer's display-currency preference lives in the browser; here there is none, so costs read in USD unless the
51
+ // formula's target price names a currency (0.6.86).
52
+ var localStorage = { getItem: function () { return null; }, setItem: function () {} };
50
53
  // The app's HTML escaper (js/utils.js, not vendored): the EU list builds its bold version with it.
51
54
  function esc(v) { return String(v == null ? '' : v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
52
55
  function rollupFormulaAllergens(f) {
@@ -81,6 +84,16 @@ function __nl(id) {
81
84
  ingredientList: eus.text, allergens: eus.allergens },
82
85
  ingredientStatement: s.text, contains: s.contains,
83
86
  coverage: { ingredients: c.rows, withNutrition: c.withData, noData: c.noData, missing: c.missing, energyFromPartialMacros: c.partial },
87
+ cost: (function () {
88
+ var k = flNlCost(f);
89
+ if (!k.ok) return null;
90
+ var r4 = function (v) { return v == null ? null : +(+v).toPrecision(4); };
91
+ return { currency: k.currency, perServing: r4(k.perServing), packagingPerContainer: r4(k.pack), perServingWithPackaging: r4(k.perServingPacked),
92
+ perContainer: r4(k.perContainer), perKgAsSold: r4(k.perKgSold), perKgAsMixed: r4(k.perKgMixed),
93
+ sellPricePerServing: k.price ? r4(k.price.perServing) : null, sellPricePerContainer: k.price ? r4(k.price.perContainer) : null,
94
+ marginPct: k.price ? +k.price.marginPct.toFixed(1) : null, unpricedRows: k.unpriced,
95
+ basis: k.pack ? 'ingredients and packaging' : 'ingredients only' };
96
+ })(),
84
97
  });
85
98
  }
86
99
  function __theo(kind, id) {
@@ -191,7 +191,7 @@ const get_formulation = {
191
191
  const get_nutrition_label = {
192
192
  definition: {
193
193
  name: 'get_nutrition_label',
194
- description: 'A formulation\'s nutrition label as FormLab\'s Label tab computes it (Pro; live workspace only), from each ingredient\'s per-100 g nutrition fields × the composition (premixes rolled up, units converted). Returns: `serving` (amount in g or mL, its weight in grams, household measure, servings per container, the density used for a mL serving); `cookingYieldPct` when set (numbers are then "as sold" = as mixed ÷ yield); `per100g` unrounded; `nutritionFacts`, the US Nutrition Facts lines per serving with `declared` (FDA rounding, 21 CFR 101.9) and `percentDailyValue`; `perContainer` when servings per container is above 1 (the dual-column second column, rounded from its own total); `simplified` (whether the food qualifies for the simplified format and its "Not a significant source of…" line); `eu`, the EU nutrition declaration per 100 g or 100 ml (kJ and kcal by the EU factors, carbohydrate without fibre, salt = sodium × 2.5) with a per-portion column when a serving is typed, plus `eu.ingredientList`, the EU ingredient list (every ingredient by weight, the 14 EU allergens in CAPITALS, added in brackets where the name does not say it) and `eu.allergens`; `ingredientStatement` (by weight, 2% or less grouped) and `contains` (major US allergens); `coverage` (which ingredients have no nutrition data, which nutrients are missing on which, where calories came from partial macros). `region` / `format` are what the user chose on the tab. A blank field counts as 0: check `coverage` before calling a nutrient absent. Calculated from ingredient data, not a regulatory review.',
194
+ description: 'A formulation\'s nutrition label as FormLab\'s Label tab computes it (Pro; live workspace only), from each ingredient\'s per-100 g nutrition fields × the composition (premixes rolled up, units converted). Returns: `serving` (amount in g or mL, its weight in grams, household measure, servings per container, the density used for a mL serving); `cookingYieldPct` when set (numbers are then "as sold" = as mixed ÷ yield); `per100g` unrounded; `nutritionFacts`, the US Nutrition Facts lines per serving with `declared` (FDA rounding, 21 CFR 101.9) and `percentDailyValue`; `perContainer` when servings per container is above 1 (the dual-column second column, rounded from its own total); `simplified` (whether the food qualifies for the simplified format and its "Not a significant source of…" line); `eu`, the EU nutrition declaration per 100 g or 100 ml (kJ and kcal by the EU factors, carbohydrate without fibre, salt = sodium × 2.5) with a per-portion column when a serving is typed, plus `eu.ingredientList`, the EU ingredient list (every ingredient by weight, the 14 EU allergens in CAPITALS, added in brackets where the name does not say it) and `eu.allergens`; `ingredientStatement` (by weight, 2% or less grouped) and `contains` (major US allergens); `coverage` (which ingredients have no nutrition data, which nutrients are missing on which, where calories came from partial macros). `cost` (null when the ingredients carry no prices): what one serving and one container cost to make, in `currency`, from the ingredient cost per kg, the weight of the serving and the cooking yield, plus `packagingPerContainer` when the user typed one; with a target sell price, `sellPricePerServing` and `marginPct`; `unpricedRows` count as 0; `basis` says what is in the number (never labor or overhead). `region` / `format` are what the user chose on the tab. A blank field counts as 0: check `coverage` before calling a nutrient absent. Calculated from ingredient data, not a regulatory review.',
195
195
  inputSchema: {
196
196
  type: 'object',
197
197
  properties: {
@@ -119,7 +119,9 @@ function flNlCompute(f) {
119
119
  FL_NL_NUTRIENTS.forEach((n, j) => {
120
120
  let sum = 0; const miss = [];
121
121
  rows.forEach((r, i) => { const v = vals[i][j]; if (v == null) { if (vals[i].some(x => x != null)) miss.push(_nlRowName(r)); } else sum += r.amount * v; });
122
- out.per100[n.key] = sum / total;
122
+ // An impossible figure (an amount or a field near 1e308 overflows to Infinity) counts as 0, not "Infinity%" (QA, 17 Nov).
123
+ const v = sum / total;
124
+ out.per100[n.key] = Number.isFinite(v) && v <= 1e9 ? v : 0;
123
125
  if (miss.length) out.missing[n.key] = miss;
124
126
  });
125
127
  out.ok = out.withData > 0;
@@ -144,10 +146,20 @@ function flNlHasFoodData(f) {
144
146
  }
145
147
 
146
148
  const FL_NL_MAX_SERVING = 5000; // g; a larger serving is a typo
149
+ // Typed text only: a stored object or array is not a household measure ("[object Object]"; QA, 17 Nov).
150
+ const _nlStr = (v) => (typeof v === 'string' || typeof v === 'number') ? String(v).trim() : '';
151
+ // Packaging cost per container (1.16.20 11b): { value, currency } as typed, or null. One pack holds servings-per-container
152
+ // servings, so it only counts when that number is set.
153
+ const FL_NL_PACK_MAX = 1e6;
154
+ function _nlPack(p) {
155
+ const v = p && typeof p === 'object' ? parseFloat(p.value) : NaN;
156
+ if (!Number.isFinite(v) || !(v > 0) || v > FL_NL_PACK_MAX) return null;
157
+ return { value: v, currency: typeof p.currency === 'string' && /^[A-Z]{3}$/.test(p.currency) ? p.currency : 'USD' };
158
+ }
147
159
  function _nlSettings(f) {
148
160
  const l = (f && f.label) || {};
149
161
  const s = parseFloat(l.serving), y = parseFloat(l.yield);
150
- return { yield: Number.isFinite(y) && y >= FL_NL_YIELD[0] && y <= FL_NL_YIELD[1] && y !== 100 ? y : null, serving: Number.isFinite(s) && s > 0 && s <= FL_NL_MAX_SERVING ? s : null, unit: l.unit === 'mL' ? 'mL' : 'g', region: l.region === 'eu' ? 'eu' : 'us', format: ['simplified', 'tabular', 'linear', 'dual'].includes(l.format) ? l.format : 'standard', household: String(l.household || '').trim(), servings: String(l.servings || '').trim() };
162
+ return { yield: Number.isFinite(y) && y >= FL_NL_YIELD[0] && y <= FL_NL_YIELD[1] && y !== 100 ? y : null, serving: Number.isFinite(s) && s > 0 && s <= FL_NL_MAX_SERVING ? s : null, unit: l.unit === 'mL' ? 'mL' : 'g', region: l.region === 'eu' ? 'eu' : 'us', format: ['simplified', 'tabular', 'linear', 'dual'].includes(l.format) ? l.format : 'standard', household: _nlStr(l.household), servings: _nlStr(l.servings), pack: _nlPack(l.pack) };
151
163
  }
152
164
  // A serving in grams. A drink's serving is in mL (61r): grams = mL × the formula's density, the finished density
153
165
  // when it has one, else the ideal-mix estimate; with neither, 1 g/mL and `noDensity` so the tab can say so.
@@ -262,6 +274,111 @@ function flNlEuPanelHtml(f, calc) {
262
274
  </table></div>`;
263
275
  }
264
276
 
277
+ // ── Cost per serving (project 20, 1.16.20 11a) ──────────────
278
+ // What one serving and one container cost to make, from the formula's ingredient cost per kg (computeFormulationCost,
279
+ // the number the Composition tab totals), the serving's weight and the cooking yield: a kilogram sold took 1 ÷ yield
280
+ // kilograms of mix. Ingredients only: no packaging, labor or overhead. With a target sell price on the Pricing &
281
+ // Margin panel, the same per serving, and the margin. Money is in the price's currency when one is set, else the
282
+ // viewer's display currency.
283
+ // → { ok, currency, perKgMixed, perKgSold, perServing, perContainer, servings, unpriced: [names],
284
+ // price: { perKg, perServing, perContainer, profitServing, marginPct } | null } ; ok false: why
285
+ function flNlCost(f) {
286
+ const out = { ok: false, why: 'nocost', unpriced: [], price: null };
287
+ if (!f || typeof computeFormulationCost !== 'function') return out;
288
+ const pr = (f.pricing && typeof f.pricing === 'object') ? f.pricing : {};
289
+ const target = parseFloat(pr.targetPrice);
290
+ const hasPrice = Number.isFinite(target) && target > 0;
291
+ let c = null;
292
+ try { c = computeFormulationCost(f, hasPrice && pr.currency ? pr.currency : undefined, 'kg'); } catch (_) { c = null; }
293
+ if (!c || !Number.isFinite(c.perKg) || !(c.perKg > 0)) return out;
294
+ const st = _nlSettings(f), sv = flNlServing(f), y = st.yield || 100, n = flNlServingsCount(f);
295
+ out.ok = true; delete out.why;
296
+ out.currency = c.currency;
297
+ out.perKgMixed = c.perKg;
298
+ out.perKgSold = c.perKg * 100 / y;
299
+ out.perServing = out.perKgSold * sv.g / 1000;
300
+ out.servings = n;
301
+ // Packaging: in the card's currency, added to the container; a serving's share is the container ÷ servings.
302
+ out.pack = null; out.packIdle = false;
303
+ if (st.pack) {
304
+ const conv = st.pack.currency === c.currency ? st.pack.value : (typeof convertCurrencySync === 'function' ? convertCurrencySync(st.pack.value, st.pack.currency, c.currency) : null);
305
+ if (n > 0 && Number.isFinite(conv)) out.pack = conv; else out.packIdle = true; // no servings per container (or no rate): not counted
306
+ }
307
+ out.perContainer = n > 0 ? out.perServing * n + (out.pack || 0) : null;
308
+ out.perServingPacked = out.pack ? out.perContainer / n : null;
309
+ out.unpriced = (c.missing || []).map(m => (m && ((m.ingredient && m.ingredient.name) || (m.subFormula && m.subFormula.name) || m.reason)) || '').filter(Boolean);
310
+ if (hasPrice) {
311
+ const basis = pr.basisUnit || 'kg';
312
+ const perKg = basis === 'kg' ? target : (typeof convertPricePerBasis === 'function' ? convertPricePerBasis(target, basis, 'kg', sv.density || (typeof _rolledUpDensity === 'function' ? _rolledUpDensity(f) : null)) : null);
313
+ if (Number.isFinite(perKg) && perKg > 0) {
314
+ const ps = perKg * sv.g / 1000, cs = out.perServingPacked != null ? out.perServingPacked : out.perServing; // with its share of the pack
315
+ out.price = { perKg, perServing: ps, perContainer: n > 0 ? ps * n : null, profitServing: ps - cs, marginPct: (ps - cs) / ps * 100 };
316
+ }
317
+ }
318
+ return out;
319
+ }
320
+ // Small amounts keep their cents: a serving often costs under a dollar ("$0.2351" reads better than "$0.24" when
321
+ // the next line multiplies it by twelve).
322
+ function _nlMoney(v, ccy) {
323
+ if (!Number.isFinite(v)) return '—';
324
+ if (v < 0) return '−' + _nlMoney(-v, ccy); // the sign before the symbol: −$0.17, not $-0.17
325
+ if (typeof formatMoney !== 'function') return (Math.abs(v) < 1 ? v.toFixed(4) : v.toFixed(2)) + ' ' + (ccy || '');
326
+ if (Math.abs(v) >= 1 || v === 0) return formatMoney(v, ccy);
327
+ const whole = formatMoney(1, ccy), digits = +v.toPrecision(3);
328
+ return whole.replace(/1([.,]0+)?/, String(digits));
329
+ }
330
+ // The cost as lines of text, for the print and for the MCP tool's reader: [[label, value], …]; [] with no cost.
331
+ function flNlCostLines(f) {
332
+ const k = flNlCost(f);
333
+ if (!k.ok) return [];
334
+ const sv = flNlServing(f), st = _nlSettings(f), m = v => _nlMoney(v, k.currency);
335
+ const out = [[`Cost per serving (${_nlNum(sv.amount)} ${sv.unit})${k.pack ? ', ingredients' : ''}`, m(k.perServing)]];
336
+ if (k.pack) out.push(['Packaging per container', m(k.pack)], ['Cost per serving with packaging', m(k.perServingPacked)]);
337
+ if (k.perContainer != null) out.push([`Cost per container (${st.servings} servings${k.pack ? ' + packaging' : ''})`, m(k.perContainer)]);
338
+ out.push([`Cost per kg${st.yield ? ` as sold (${_nlNum(st.yield)}% yield)` : ''}`, m(k.perKgSold)]);
339
+ if (k.price) {
340
+ out.push(['Sell price per serving', m(k.price.perServing)]);
341
+ if (k.price.perContainer != null) out.push(['Sell price per container', m(k.price.perContainer)]);
342
+ out.push(['Margin', `${+k.price.marginPct.toFixed(1)}%`]);
343
+ }
344
+ if (k.unpriced.length) out.push(['Rows with no price (counted as 0)', k.unpriced.slice(0, 12).join(', ')]);
345
+ return out;
346
+ }
347
+ function _nlCostCardHtml(f) {
348
+ const k = flNlCost(f);
349
+ if (!k.ok) return `<div class="card">
350
+ <div class="card-header"><h2>Cost</h2></div>
351
+ <div class="card-body"><div class="nl-dim" data-tip="Set a price on the ingredients (Ingredient › Cost & Pricing), then the cost per serving shows here.">No ingredient prices yet.</div></div>
352
+ </div>`;
353
+ const sv = flNlServing(f), st = _nlSettings(f), m = v => esc(_nlMoney(v, k.currency));
354
+ const row = (label, val, sub, tip) => `<tr${tip ? ` data-tip="${esc(tip)}"` : ''}><td>${label}${sub ? ` <span class="u">${esc(sub)}</span>` : ''}</td><td class="num"><strong>${val}</strong></td></tr>`;
355
+ const id = esc(f.id);
356
+ const packIn = `<tr><td><label for="nl-pack-in">Packaging per container</label> <span class="u">${esc(k.currency)}</span></td><td class="num"><input id="nl-pack-in" type="number" min="0" step="any" value="${st.pack ? esc(String(st.pack.currency === k.currency ? st.pack.value : +(+k.pack || st.pack.value).toFixed(4))) : ''}" placeholder="0" onchange="flNlSet('${id}','pack',this.value)"></td></tr>`;
357
+ const rows = [
358
+ row('Per serving', m(k.perServing), `${_nlNum(sv.amount)} ${sv.unit}${k.pack ? ', ingredients' : ''}`),
359
+ packIn,
360
+ k.perServingPacked != null ? row('Per serving with packaging', m(k.perServingPacked)) : '',
361
+ k.perContainer != null ? row('Per container', m(k.perContainer), `${st.servings} servings${k.pack ? ' + packaging' : ''}`) : '',
362
+ row('Per kg', m(k.perKgSold), st.yield ? `as sold, ${_nlNum(st.yield)}% yield` : '', st.yield ? `As mixed: ${_nlMoney(k.perKgMixed, k.currency)} / kg.` : ''),
363
+ ];
364
+ const p = k.price;
365
+ const priceRows = p ? [
366
+ row('Sell price per serving', m(p.perServing)),
367
+ p.perContainer != null ? row('Sell price per container', m(p.perContainer)) : '',
368
+ row('Margin', `<span style="color:var(${p.marginPct >= 0 ? '--success' : '--danger'})">${esc(String(+p.marginPct.toFixed(1)))}%</span>`, `${_nlMoney(p.profitServing, k.currency)} per serving`),
369
+ ] : [];
370
+ const idle = k.packIdle ? `<div class="nl-note warn">Packaging needs Servings per container. Not counted.</div>` : '';
371
+ const warn = k.unpriced.length ? `<div class="nl-note warn" data-tip="${esc(k.unpriced.slice(0, 12).join(', '))}">${k.unpriced.length} ${k.unpriced.length === 1 ? 'row has' : 'rows have'} no price. Counted as 0.</div>` : '';
372
+ return `<div class="card">
373
+ <div class="card-header"><h2>Cost</h2><span id="nl-cost-saved" class="fl-saved-tick" role="status"></span></div>
374
+ <div class="card-body">
375
+ ${warn}${idle}
376
+ <div class="table-wrapper"><table class="nl-table nl-cost"><tbody>${rows.join('')}${priceRows.length ? `<tr class="nl-cost-gap"><td colspan="2"></td></tr>${priceRows.join('')}` : ''}</tbody></table></div>
377
+ <div class="nl-dim nl-hint" data-tip="From each ingredient’s price and the amounts in the Composition tab${k.pack ? ', plus the packaging you typed' : ''}. Labor and overhead are not in it.${p ? '' : ' Set a target sell price on the Composition tab’s Pricing & Margin panel to see the margin per serving.'}">${k.pack ? 'Ingredients and packaging.' : 'Ingredients only.'}${p ? '' : ' Add a sell price in Pricing &amp; Margin for the margin.'}</div>
378
+ </div>
379
+ </div>`;
380
+ }
381
+
265
382
  // ── Ingredient statement and Contains ───────────────────────
266
383
  // Leaves in descending order by weight; those at 2 % or less may follow "Contains 2% or less of".
267
384
  // The formula's leaves, heaviest first: [{ name (label_name when set), w, allergens }]
@@ -296,7 +413,8 @@ function flNlEuStatement(f) {
296
413
  const one = (it, mark, safe) => {
297
414
  const spans = [], add = [];
298
415
  it.allergens.forEach(k => {
299
- const d = FL_NL_EU_ALLERGENS[k];
416
+ // Own keys only: a stored chip named "constructor" found Object's own and took the tab down (QA, 17 Nov).
417
+ const d = typeof k === 'string' && Object.prototype.hasOwnProperty.call(FL_NL_EU_ALLERGENS, k) ? FL_NL_EU_ALLERGENS[k] : null;
300
418
  if (!d) return;
301
419
  if (!found.includes(d[0])) found.push(d[0]);
302
420
  const m = new RegExp('\\b(?:' + d[1].source + ')\\b', 'i').exec(it.name);
@@ -390,7 +508,11 @@ function flNlPanelHtml(f, calc, tease) {
390
508
  const name = l.italicFirst ? l.label.replace(/^(\S+)/, '<i>$1</i>') : l.label;
391
509
  return `<div class="nl-d-row${l.indent ? ' nl-in' + l.indent : ''}"><span class="nl-d-n">${l.includes ? 'Includes ' + name : l.bold ? `<b>${name}</b>` : name}</span>${cell(l)}${cell(C[l.key])}</div>`;
392
510
  };
393
- return `<div class="nl-panel nl-dual" id="nl-panel" translate="no">
511
+ // The amount columns are as wide as their longest text: "less than 5mg" ran under the % beside it at the fixed
512
+ // 46px (Jun, 17 Nov). The panel grows by what the columns gain, so the names keep their room.
513
+ const colW = (ls, min) => Math.max(min, Math.ceil(Math.max(0, ...ls.filter(l => l.key !== 'energy').map(l => amt(l).length)) * 6.4) + 8);
514
+ const da = colW(lines, 46), dc = colW(Object.values(C), 52);
515
+ return `<div class="nl-panel nl-dual" id="nl-panel" translate="no" style="--da:${da}px;--dc:${dc}px;width:${380 + (da - 46) + (dc - 52)}px">
394
516
  <div class="nl-title">Nutrition Facts</div>
395
517
  <div class="nl-servings">${esc(st.servings)} servings per container</div>
396
518
  <div class="nl-serving${_nlServingText(st).length > 38 ? ' nl-flow' : ''}"><span>Serving size</span> <span>${esc(_nlServingText(st))}</span></div>
@@ -505,6 +627,7 @@ function flNlTabHtml(f) {
505
627
  ${dens}${yld}
506
628
  </div>
507
629
  </div>
630
+ ${_nlCostCardHtml(f)}
508
631
  <div class="card">
509
632
  <div class="card-header"><h2>Ingredient statement</h2>
510
633
  <button class="btn btn-secondary btn-sm" onclick="flNlCopyStatement('${id}')">Copy</button></div>
@@ -545,11 +668,16 @@ function flNlTabHtml(f) {
545
668
  // Save one serving field on the formula, then redraw the tab.
546
669
  function flNlSet(fid, key, value) {
547
670
  const f = (db.formulations || []).find(x => x.id === fid);
548
- if (!f || !['serving', 'unit', 'format', 'region', 'yield', 'household', 'servings'].includes(key)) return;
671
+ if (!f || !['serving', 'unit', 'format', 'region', 'yield', 'pack', 'household', 'servings'].includes(key)) return;
549
672
  const l = { ...(f.label || {}) };
550
673
  if (key === 'serving') { const n = parseFloat(String(value).replace(',', '.')); if (Number.isFinite(n) && n > 0 && n <= FL_NL_MAX_SERVING) l.serving = n; else { delete l.serving; if (String(value).trim() && typeof toast === 'function') toast('Serving size: 0 to ' + FL_NL_MAX_SERVING + '.'); } }
551
674
  else if (key === 'format') { if (['simplified', 'tabular', 'linear', 'dual'].includes(value)) l.format = value; else delete l.format; }
552
675
  else if (key === 'yield') { const n = parseFloat(String(value).replace(',', '.')); if (Number.isFinite(n) && n >= FL_NL_YIELD[0] && n <= FL_NL_YIELD[1] && n !== 100) l.yield = n; else { delete l.yield; if (String(value).trim() && n !== 100 && typeof toast === 'function') toast('Cooking yield: ' + FL_NL_YIELD[0] + ' to ' + FL_NL_YIELD[1] + ' %.'); } }
676
+ else if (key === 'pack') {
677
+ const n = parseFloat(String(value).replace(',', '.'));
678
+ if (Number.isFinite(n) && n > 0 && n <= FL_NL_PACK_MAX) { const k0 = flNlCost(f); l.pack = { value: n, currency: (k0.ok && k0.currency) || (typeof getDisplayCurrency === 'function' && getDisplayCurrency()) || 'USD' }; }
679
+ else { delete l.pack; if (String(value).trim() && n !== 0 && typeof toast === 'function') toast('Packaging: 0 to ' + FL_NL_PACK_MAX.toLocaleString() + '.'); }
680
+ }
553
681
  else if (key === 'region') { if (value === 'eu') l.region = 'eu'; else delete l.region; }
554
682
  else if (key === 'unit') { if (value === 'mL') l.unit = 'mL'; else delete l.unit; }
555
683
  else { const t = String(value || '').trim().slice(0, key === 'household' ? 80 : 40); if (t) l[key] = t; else delete l[key]; }
@@ -557,10 +685,7 @@ function flNlSet(fid, key, value) {
557
685
  const saved = typeof _fmlSyncSave === 'function' && _fmlSyncSave(f, ['label']);
558
686
  const el = document.getElementById('tab-label');
559
687
  if (el) el.innerHTML = flNlTabHtml(f);
560
- // The redraw makes new buttons: grey the ones this person can't use now, not a frame later (Save PNG / Print with
561
- // member exports off flashed enabled on every serving change; Jun, 17 Nov).
562
- try { if (window.__flViewerGate && typeof window.__flViewerGate.refresh === 'function') window.__flViewerGate.refresh(); } catch (_) {}
563
- if (saved && typeof flSavedTick === 'function') flSavedTick(key === 'format' || key === 'region' ? 'nl-fmt-saved' : 'nl-saved');
688
+ if (saved && typeof flSavedTick === 'function') flSavedTick(key === 'format' || key === 'region' ? 'nl-fmt-saved' : key === 'pack' ? 'nl-cost-saved' : 'nl-saved');
564
689
  }
565
690
 
566
691
  function _nlFile(f) { return 'nutrition-facts-' + String(f.uid || f.name || 'formula').replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '').toLowerCase(); }
@@ -629,12 +754,12 @@ const FL_NL_PANEL_CSS = `.nl-panel{box-sizing:border-box;width:280px;padding:4px
629
754
  .nl-panel.nl-lin{width:430px;padding:5px 8px 6px;font-size:11px;line-height:1.3}
630
755
  .nl-l-t{font-weight:900;font-size:19px;line-height:1;letter-spacing:-.3px;margin-right:2px}.nl-l-c{font-weight:900;font-size:13px}
631
756
  .nl-panel.nl-dual{width:380px}
632
- .nl-d-row{display:grid;grid-template-columns:minmax(0,1fr) 46px 40px 52px 40px;align-items:end;padding:2px 0;border-bottom:1px solid #000}
757
+ .nl-d-row{display:grid;grid-template-columns:minmax(0,1fr) var(--da,46px) 40px var(--dc,52px) 40px;align-items:end;padding:2px 0;border-bottom:1px solid #000}
633
758
  .nl-d-row.nl-in1 .nl-d-n{padding-left:12px}.nl-d-row.nl-in2 .nl-d-n{padding-left:24px}
634
759
  .nl-d-a,.nl-d-p{text-align:right;white-space:nowrap}.nl-d-a{border-left:1px solid #000;margin:-2px 0;padding:2px 0}.nl-d-p{padding-right:3px}
635
760
  .nl-d-row .nl-d-p:last-child{padding-right:0}
636
761
  .nl-d-h{font-weight:800;font-size:10px}
637
- .nl-d-cal{grid-template-columns:minmax(0,1fr) 86px 92px;border-bottom:0;padding-bottom:1px}
762
+ .nl-d-cal{grid-template-columns:minmax(0,1fr) calc(var(--da,46px) + 40px) calc(var(--dc,52px) + 40px);border-bottom:0;padding-bottom:1px}
638
763
  .nl-d-cal .nl-d-n b{font-weight:900;font-size:24px;line-height:1}
639
764
  .nl-d-k{display:flex;flex-direction:column;align-items:flex-end;border-left:1px solid #000;padding-right:3px}.nl-d-k:last-child{padding-right:0}
640
765
  .nl-d-k small{font-weight:800;font-size:9.5px}.nl-d-k b{font-weight:900;font-size:30px;line-height:1}
@@ -642,6 +767,7 @@ const FL_NL_PANEL_CSS = `.nl-panel{box-sizing:border-box;width:280px;padding:4px
642
767
  .nl-panel.nl-eu{width:316px;padding:0;border-width:1px}
643
768
  .nl-eu table{width:100%;table-layout:fixed;border-collapse:collapse;margin:0;background:none;font:400 11.5px/1.25 Helvetica,Arial,sans-serif}
644
769
  .nl-eu th,.nl-eu td{padding:3px 5px;border:0;border-bottom:1px solid #000;background:none;color:#000;font:400 11.5px/1.25 Helvetica,Arial,sans-serif;text-align:right;vertical-align:bottom;text-transform:none;letter-spacing:0;white-space:nowrap}
770
+ .nl-panel.nl-eu th,.nl-panel.nl-eu td{background:rgb(255,255,255)!important;color:#000!important}
645
771
  .nl-eu th{font-weight:700;border-bottom-width:1.5px;white-space:normal}.nl-eu th:first-child{width:38%}.nl-eu th:first-child,.nl-eu td:first-child{text-align:left}
646
772
  .nl-eu th + th,.nl-eu td + td{border-left:1px solid #000}
647
773
  .nl-eu tr:last-child td{border-bottom:0}.nl-eu .nl-e-in td:first-child{padding-left:16px}`;
@@ -655,12 +781,14 @@ function flNlPrint(fid) {
655
781
  if (!win) { if (typeof toast === 'function') toast('Couldn’t open the print view. Try again.'); return; }
656
782
  const css = `body{font:12px Helvetica,Arial,sans-serif;color:#000;margin:28px}h1{font-size:15px;margin:0 0 2px}.meta{font-size:11px;opacity:.65;margin-bottom:16px}
657
783
  .stmt{max-width:420px;margin-top:16px;font-size:11.5px;line-height:1.4}.stmt div{margin-bottom:4px}
784
+ .cost{margin-top:14px;border-collapse:collapse;font-size:11.5px}.cost td{padding:2px 14px 2px 0}.cost td + td{text-align:right;font-weight:700}.cost caption{text-align:left;font-weight:700;padding-bottom:3px}
658
785
  ${FL_NL_PANEL_CSS}
659
786
  ${typeof flPrintPageCss === 'function' ? flPrintPageCss() : ''}`;
660
787
  win.document.write(`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${esc(f.name || 'Nutrition Facts')}</title><style>${css}</style></head><body>
661
788
  <h1>${esc(f.name || '')}</h1><div class="meta">${esc([f.uid, 'calculated from ingredient data', 'printed ' + new Date().toLocaleDateString()].filter(Boolean).join(' · '))}</div>
662
789
  ${flNlPanelHtml(f)}
663
790
  <div class="stmt">${_nlSettings(f).region === 'eu' ? (() => { const es = flNlEuStatement(f); return es.html ? `<div><b>INGREDIENTS:</b> ${es.html}</div>` : ''; })() : `${s.text ? `<div><b>INGREDIENTS:</b> ${esc(s.text)}</div>` : ''}${s.contains.length ? `<div><b>CONTAINS:</b> ${esc(s.contains.join(', '))}.</div>` : ''}`}</div>
791
+ ${(() => { const cl = flNlCostLines(f); return cl.length ? `<table class="cost"><caption>Cost to make (${flNlCost(f).pack ? 'ingredients and packaging' : 'ingredients only'})</caption>${cl.map(([a, b]) => `<tr><td>${esc(a)}</td><td>${esc(b)}</td></tr>`).join('')}</table>` : ''; })()}
664
792
  <script>window.onload=()=>setTimeout(()=>window.print(),250)<\/script></body></html>`);
665
793
  win.document.close();
666
794
  if (typeof flPreparePrintWindow === 'function') flPreparePrintWindow(win);