|
| 1 | +// utils/formulaEvaluator.js |
| 2 | + |
| 3 | +export class FormulaEvaluator { |
| 4 | + /** |
| 5 | + * Eval numeric formula using actor data paths. |
| 6 | + * Supports @paths like: |
| 7 | + * - @characteristics.primaries.power.mod |
| 8 | + * - @system.characteristics.primaries.power.mod |
| 9 | + * No dice allowed here. |
| 10 | + * |
| 11 | + * @param {string} formula |
| 12 | + * @param {Actor|null} actor |
| 13 | + * @returns {number|null} |
| 14 | + */ |
| 15 | + static evaluate(formula, actor = null) { |
| 16 | + const clean = (formula ?? '').trim(); |
| 17 | + if (!clean) return null; |
| 18 | + |
| 19 | + // No dice inside @formula for now |
| 20 | + if (/[dD]\d+/.test(clean)) { |
| 21 | + console.warn('FormulaEvaluator: dice are not allowed inside @formula:', clean); |
| 22 | + return null; |
| 23 | + } |
| 24 | + |
| 25 | + // Local context from actor.system |
| 26 | + /** @type {any} */ |
| 27 | + const ctx = actor?.system ? foundry.utils.duplicate(actor.system) : {}; |
| 28 | + |
| 29 | + // Allow both @foo.bar and @system.foo.bar |
| 30 | + ctx.system = ctx; |
| 31 | + |
| 32 | + try { |
| 33 | + // Replace @path with numeric values from ctx |
| 34 | + const replaced = clean.replace(/@([a-zA-Z0-9_.]+)/g, (match, path) => { |
| 35 | + const value = foundry.utils.getProperty(ctx, path); |
| 36 | + const num = Number(value); |
| 37 | + return Number.isFinite(num) ? String(num) : '0'; |
| 38 | + }); |
| 39 | + |
| 40 | + const compact = replaced.replace(/\s+/g, ''); |
| 41 | + if (!/^[0-9+\-*/().]*$/.test(compact)) { |
| 42 | + console.error('FormulaEvaluator: invalid chars after replace', { |
| 43 | + original: clean, |
| 44 | + replaced |
| 45 | + }); |
| 46 | + return null; |
| 47 | + } |
| 48 | + |
| 49 | + const total = Roll.safeEval(replaced); |
| 50 | + return Number.isFinite(total) ? total : null; |
| 51 | + } catch (err) { |
| 52 | + console.error('FormulaEvaluator error evaluating formula:', { |
| 53 | + formula: clean, |
| 54 | + err |
| 55 | + }); |
| 56 | + return null; |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments