@a-ludi/rjsf-formulas 0.1.3 → 0.3.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.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("react/jsx-runtime"),c=require("react"),W=require("@rjsf/core"),$=Symbol("arrayIndex");function B(e,t){const n=(t==null?void 0:t.formulaKey)??"x-formula",s=(t==null?void 0:t.formulaContextKey)??"x-formula-context",r=[];return P(e,[],r,n,s),r}const Z=["$ref","oneOf","anyOf","allOf"];function L(e,t){return e===void 0||e==="siblings"?"siblings":e==="extended"?"extended":(console.warn(`[rjsf-formulas] Unknown x-formula-context value "${e}" at path [${N(t)}], treating as "siblings"`),"siblings")}function N(e){return e.map(t=>typeof t=="symbol"?"[*]":String(t)).join(", ")}function P(e,t,n,s,r){for(const o of Z)o in e&&console.warn(`[rjsf-formulas] Schema composition operator "${o}" at path [${N(t)}] is not supported and will be skipped. See issue 06.`);if(s in e){const o=e[s];if(typeof o!="string"){console.warn(`[rjsf-formulas] Formula at path [${N(t)}] is not a string (got ${typeof o}), skipping.`);return}n.push({path:t,formula:o,contextMode:L(e[r],t)});return}if(e.type==="object"&&e.properties)for(const[o,u]of Object.entries(e.properties))P(u,[...t,o],n,s,r);if(e.type==="array"){const o=e;Array.isArray(o.prefixItems)&&o.prefixItems.forEach((i,f)=>{P(i,[...t,f],n,s,r)}),e.items&&!Array.isArray(e.items)&&P(e.items,[...t,$],n,s,r)}}function ee(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var T,X;function te(){return X||(X=1,T=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var s,r,o;if(Array.isArray(t)){if(s=t.length,s!=n.length)return!1;for(r=s;r--!==0;)if(!e(t[r],n[r]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(o=Object.keys(t),s=o.length,s!==Object.keys(n).length)return!1;for(r=s;r--!==0;)if(!Object.prototype.hasOwnProperty.call(n,o[r]))return!1;for(r=s;r--!==0;){var u=o[r];if(!e(t[u],n[u]))return!1}return!0}return t!==t&&n!==n}),T}var re=te();const ne=ee(re);function se(e,t,n,s){const o=t.slice(0,-1).reduce((i,f)=>{if(!(i==null||typeof i!="object"))return i[f]},n),u=o!=null&&typeof o=="object"&&!Array.isArray(o)?{...o}:{};return e.contextMode==="extended"?((s.formulaDataKey in u||s.formulaPathKey in u)&&console.warn(`[rjsf-formulas] Extended context key collision: sibling field named "${s.formulaDataKey in u?s.formulaDataKey:s.formulaPathKey}" will be overwritten by the injected context. Use formulaDataKey/formulaPathKey props to choose a different key.`),{...u,[s.formulaDataKey]:n,[s.formulaPathKey]:[...t]}):u}function h(e,t){return t.reduce((n,s)=>{if(!(n==null||typeof n!="object"))return n[s]},e)}function C(e,t,n){if(t.length===0)return;const s=h(e,t.slice(0,-1));s!=null&&typeof s=="object"&&(s[t[t.length-1]]=n)}function O(e,t,n=[]){if(e.length===0)return[n];const[s,...r]=e;if(s===$){const o=h(t,n);if(!Array.isArray(o))return[];const u=[];for(let i=0;i<o.length;i++)u.push(...O(r,t,[...n,i]));return u}return O(r,t,[...n,s])}function z(e,t){return ne(e,t)}async function F(e,t,n,s){const r=structuredClone(e),o=[];for(const f of t)for(const a of O(f.path,r)){const l=se(f,a,r,s);o.push({field:f,concretePath:a,context:l})}const u=await Promise.allSettled(o.map(({field:f,context:a})=>new Promise(l=>l(n(f.formula,a))))),i=[];for(let f=0;f<o.length;f++){const{concretePath:a}=o[f],l=u[f];if(l.status==="fulfilled")C(r,a,l.value);else{const y=l.reason instanceof Error?l.reason:new Error(String(l.reason));i.push({path:a,error:y}),C(r,a,void 0)}}return{data:r,errors:i}}function oe(e,t,n){for(const s of n)for(const r of O(s.path,t))if(!z(h(e,r),h(t,r)))return!1;return!0}async function fe(e,t,n,s,r,o="__formData__",u="__path__"){if(t.length===0)return e;const i={formulaDataKey:o,formulaPathKey:u};let f=e;for(let y=0;y<s;y++){const{data:p,errors:g}=await F(f,t,n,i);if(oe(f,p,t)){for(const{path:d,error:R}of g)r==null||r(d,R);return p}f=p}const{data:a}=await F(f,t,n,i),l=structuredClone(a);for(const y of t)for(const p of O(y.path,a))z(h(f,p),h(a,p))||(r==null||r(p,new Error(`[rjsf-formulas] Formula at [${p.join(", ")}] did not converge after ${s} passes`)),C(l,p,void 0));return l}function ue(e){return JSON.stringify(e)}function ce(e,t,n,s,r,o,u,i){const[f,a]=c.useState(e),l=c.useRef(e),y=c.useRef(e),p=c.useRef(new Map),g=c.useRef(null),d=c.useRef(!1),R=c.useRef(o),m=c.useRef(u),K=c.useRef(n),M=c.useRef(t),x=c.useRef(r),A=c.useRef(i);c.useEffect(()=>{R.current=o},[o]),c.useEffect(()=>{m.current=u},[u]),c.useEffect(()=>{K.current=n},[n]),c.useEffect(()=>{M.current=t},[t]),c.useEffect(()=>{x.current=r},[r]),c.useEffect(()=>{A.current=i},[i]);const b=c.useCallback(()=>{if(d.current)return;(async()=>{var w,k;d.current=!0;try{for(;;){const q=l.current,J=M.current,E=[];for(const I of J)for(const Q of O(I.path,q))E.push(Q);const S=p.current;S.clear();for(const I of E)S.set(ue(I),"running");E.length>0&&((w=m.current)==null||w.call(m,E));const G=await fe(q,J,K.current,x.current,R.current,A.current.formulaDataKey,A.current.formulaPathKey);if(v.current)break;const H=[...S.values()].some(I=>I==="dirty");if(S.clear(),!H){a(G),E.length>0&&((k=m.current)==null||k.call(m,[]));break}}}finally{d.current=!1}})()},[]),_=c.useCallback(Y=>{l.current=Y;const w=p.current;for(const[k,q]of w)q==="running"&&w.set(k,"dirty");d.current||(g.current!==null&&clearTimeout(g.current),g.current=setTimeout(()=>{g.current=null,b()},s))},[s,b]),j=c.useRef(!1),v=c.useRef(!1);return c.useEffect(()=>{j.current?z(e,y.current)||(y.current=e,_(e)):(j.current=!0,y.current=e,_(e))}),c.useEffect(()=>()=>{v.current=!0,g.current!==null&&clearTimeout(g.current)},[]),{enrichedFormData:f,handleInput:_}}function ie(e,t){const n=structuredClone(e??{}),s=ae(t);for(const r of t)D(n,r.path,s);return n}function ae(e){const t=new Set;for(let n=0;n<e.length;n++){const s=e[n].path;for(let r=0;r<s.length;r++){const o=s[r];if(typeof o!="number"&&o!==$)continue;const u=U(s.slice(0,r)),i=typeof o=="number";e.some((a,l)=>{if(l===n||a.path.length<=r||U(a.path.slice(0,r))!==u)return!1;const y=a.path[r];return i?y===$:typeof y=="number"})&&t.add(u)}}return t}function U(e){return JSON.stringify(e.map(t=>typeof t=="symbol"?"__ARRAY_INDEX__":t))}function D(e,t,n,s=[]){if(t.length===0){e["ui:readonly"]=!0;return}const[r,...o]=t;if(typeof r=="string"){(!e[r]||typeof e[r]!="object"||Array.isArray(e[r]))&&(e[r]={}),D(e[r],o,n,[...s,r]);return}if(typeof r=="number"){if(e.items!==void 0&&!Array.isArray(e.items)){console.warn("[rjsf-formulas] mergeReadOnly: cannot inject ui:readonly at tuple index because existing uiSchema has items as an object. Skipping.");return}Array.isArray(e.items)||(e.items=[]);const f=e.items;(!f[r]||typeof f[r]!="object")&&(f[r]={}),D(f[r],o,n,[...s,r]);return}const u=U(s);if(n.has(u))(!e.additionalItems||typeof e.additionalItems!="object")&&(e.additionalItems={}),D(e.additionalItems,o,n,[...s,r]);else{if(Array.isArray(e.items)){console.warn("[rjsf-formulas] mergeReadOnly: cannot inject ui:readonly for uniform array because existing uiSchema has items as an array. Skipping.");return}(!e.items||typeof e.items!="object")&&(e.items={}),D(e.items,o,n,[...s,r])}}function le(e){const{schema:t,formData:n,uiSchema:s,evaluator:r,Form:o=W,formulaKey:u="x-formula",formulaContextKey:i="x-formula-context",formulaDataKey:f="__formData__",formulaPathKey:a="__path__",maxConvergencePasses:l=10,debounceMs:y=300,onFormulaError:p,onLoadingChange:g,onChange:d,...R}=e,m=c.useMemo(()=>B(t,{formulaKey:u,formulaContextKey:i}),[t,u,i]),K=c.useMemo(()=>({formulaDataKey:f,formulaPathKey:a}),[f,a]),M=c.useMemo(()=>ie(s,m),[s,m]),{enrichedFormData:x,handleInput:A}=ce(n,m,r,y,l,p,g,K),b=c.useRef(d);c.useEffect(()=>{b.current=d},[d]),c.useEffect(()=>{var j;m.length!==0&&((j=b.current)==null||j.call(b,{formData:x},void 0))},[x]);const _=(j,v)=>{A(j.formData),d==null||d(j,v)};return V.jsx(o,{...R,schema:t,formData:x,uiSchema:M,onChange:_})}exports.FormulaForm=le;exports.analyzeSchema=B;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const se=require("@rjsf/utils"),oe=require("react/jsx-runtime"),i=require("react"),fe=require("@rjsf/core"),U=Symbol("arrayIndex");function C(e,t){const r=(t==null?void 0:t.formulaKey)??"x-formula",s=(t==null?void 0:t.formulaContextKey)??"x-formula-context",n=(t==null?void 0:t.formulaConflictBehavior)??"warn",o=[];return O(e,[],o,r,s,n,!0,e),o}function J(e,t){if(e===!0)return t;const r=e;return Array.isArray(r.allOf)?{allOf:[...r.allOf,t]}:{allOf:[e,t]}}function ce(e,t){return e===void 0||e==="siblings"?"siblings":e==="extended"?"extended":(console.warn(`[rjsf-formulas] Unknown x-formula-context value "${e}" at path [${z(t)}], treating as "siblings"`),"siblings")}function z(e){return e.map(t=>typeof t=="symbol"?"[*]":String(t)).join(", ")}function Y(e){return e.map(t=>typeof t=="symbol"?"[*]":String(t)).join(".")}function ue(e,t,r){const s=Y(e.path);if(r==="error")throw new TypeError(`[rjsf-formulas] Formula conflict at path [${z(e.path)}]: "${e.formula}" vs "${t.formula}". Resolve the conflict or set formulaConflictBehavior to 'ignore' or 'warn'.`);r==="warn"&&console.warn(`[rjsf-formulas] Formula conflict at path [${s}]: "${e.formula}" (earlier allOf branch) is overridden by "${t.formula}" (later allOf branch).`)}function ie(e,t,r){for(const s of t){const n=Y(s.path),o=e.findIndex(u=>Y(u.path)===n);o!==-1?(ue(e[o],s,r),e[o]=s):e.push(s)}}function O(e,t,r,s,n,o,u,l){const f=e;if(typeof f.$ref=="string"){const c=se.findSchemaDefinition(f.$ref,l);O(c,t,r,s,n,o,u,l);return}if(s in e){const c=f[s];if(typeof c!="string"){console.warn(`[rjsf-formulas] Formula at path [${z(t)}] is not a string (got ${typeof c}), skipping.`);return}r.push({path:t,formula:c,contextMode:ce(f[n],t),condition:u});return}if(e.properties&&e.type!=="array")for(const[c,a]of Object.entries(e.properties))O(a,[...t,c],r,s,n,o,u,l);if(e.type==="array"&&(Array.isArray(f.prefixItems)&&f.prefixItems.forEach((a,y)=>{O(a,[...t,y],r,s,n,o,u,l)}),e.items&&!Array.isArray(e.items)&&O(e.items,[...t,U],r,s,n,o,u,l)),Array.isArray(f.allOf)){const c=f.allOf;for(const a of c){const y=[];O(a,t,y,s,n,o,u,l),ie(r,y,o)}}for(const c of["oneOf","anyOf"])if(Array.isArray(f[c])){const a=f[c];for(const y of a){const m=J(u,y);O(y,t,r,s,n,o,m,l)}}if("if"in f){const c=f.if,a=f.then,y=f.else;if(s in c&&console.warn(`[rjsf-formulas] Formula key "${s}" found inside an "if" schema at path [${z(t)}]. The "if" schema is a validation predicate and is never rendered — the formula will be ignored.`),a!==void 0){const m=J(u,c);O(a,t,r,s,n,o,m,l)}if(y!==void 0){const m=J(u,{not:c});O(y,t,r,s,n,o,m,l)}}}function ae(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var X,Z;function le(){return Z||(Z=1,X=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var s,n,o;if(Array.isArray(t)){if(s=t.length,s!=r.length)return!1;for(n=s;n--!==0;)if(!e(t[n],r[n]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(o=Object.keys(t),s=o.length,s!==Object.keys(r).length)return!1;for(n=s;n--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[n]))return!1;for(n=s;n--!==0;){var u=o[n];if(!e(t[u],r[u]))return!1}return!0}return t!==t&&r!==r}),X}var ye=le();const de=ae(ye);function pe(e,t,r,s){const o=t.slice(0,-1).reduce((l,f)=>{if(!(l==null||typeof l!="object"))return l[f]},r),u=o!=null&&typeof o=="object"&&!Array.isArray(o)?{...o}:{};return e.contextMode==="extended"?((s.formulaDataKey in u||s.formulaPathKey in u)&&console.warn(`[rjsf-formulas] Extended context key collision: sibling field named "${s.formulaDataKey in u?s.formulaDataKey:s.formulaPathKey}" will be overwritten by the injected context. Use formulaDataKey/formulaPathKey props to choose a different key.`),{...u,[s.formulaDataKey]:r,[s.formulaPathKey]:[...t]}):u}function B(e){return e.map(t=>typeof t=="symbol"?"[*]":String(t)).join(", ")}function I(e,t){return t.reduce((r,s)=>{if(!(r==null||typeof r!="object"))return r[s]},e)}function V(e,t,r){if(t.length===0)return;const s=I(e,t.slice(0,-1));s!=null&&typeof s=="object"&&(s[t[t.length-1]]=r)}function k(e,t,r=[]){if(e.length===0)return[r];const[s,...n]=e;if(s===U){const o=I(t,r);if(!Array.isArray(o))return[];const u=[];for(let l=0;l<o.length;l++)u.push(...k(n,t,[...r,l]));return u}return k(n,t,[...r,s])}function H(e,t){return de(e,t)}async function L(e,t,r,s){const n=structuredClone(e),o=[];for(const f of t)for(const c of k(f.path,n)){const a=pe(f,c,n,s);o.push({field:f,concretePath:c,context:a})}const u=await Promise.allSettled(o.map(({field:f,context:c})=>new Promise(a=>a(r(f.formula,c))))),l=[];for(let f=0;f<o.length;f++){const{concretePath:c}=o[f],a=u[f];if(a.status==="fulfilled")V(n,c,a.value);else{const y=a.reason instanceof Error?a.reason:new Error(String(a.reason));l.push({path:c,error:y}),V(n,c,void 0)}}return{data:n,errors:l}}function me(e,t,r){for(const s of r)for(const n of k(s.path,t))if(!H(I(e,n),I(t,n)))return!1;return!0}async function ge(e,t,r,s,n,o,u,l,f){const c=t.filter(p=>p.condition===!0||l(p.condition,e));if(c.length===0)return e;const a=new Map,y=[];for(const p of c){const d=JSON.stringify(p.path);if(a.has(d)){if(f==="error")throw new TypeError(`[rjsf-formulas] Formula conflict: two active fields share path [${B(p.path)}]`);f==="warn"&&console.warn(`[rjsf-formulas] Formula conflict: two active fields share path [${B(p.path)}]; taking last`);const g=y.indexOf(a.get(d));y[g]=p,a.set(d,p)}else a.set(d,p),y.push(p)}const m={formulaDataKey:o,formulaPathKey:u};let h=e;for(let p=0;p<s;p++){const{data:d,errors:g}=await L(h,y,r,m);if(me(h,d,y)){for(const{path:w,error:$}of g)n==null||n(w,$);return d}h=d}const{data:A}=await L(h,y,r,m),j=structuredClone(A);for(const p of y)for(const d of k(p.path,A))H(I(h,d),I(A,d))||(n==null||n(d,new Error(`[rjsf-formulas] Formula at [${d.join(", ")}] did not converge after ${s} passes`)),V(j,d,void 0));return j}function he(e){return JSON.stringify(e)}function je(e,t,r,s,n,o,u,l,f,c){const[a,y]=i.useState(e),m=i.useRef(e),h=i.useRef(e),A=i.useRef(new Map),j=i.useRef(null),p=i.useRef(!1),d=i.useRef(o),g=i.useRef(u),w=i.useRef(r),$=i.useRef(t),S=i.useRef(n),F=i.useRef(l),x=i.useRef(f),T=i.useRef(c);i.useEffect(()=>{d.current=o},[o]),i.useEffect(()=>{g.current=u},[u]),i.useEffect(()=>{w.current=r},[r]),i.useEffect(()=>{$.current=t},[t]),i.useEffect(()=>{S.current=n},[n]),i.useEffect(()=>{F.current=l},[l]),i.useEffect(()=>{x.current=f},[f]),i.useEffect(()=>{T.current=c},[c]);const E=i.useCallback(()=>{if(p.current)return;(async()=>{var _,K;p.current=!0;try{for(;;){const D=m.current,W=$.current,ee=W.filter(b=>b.condition===!0||x.current(b.condition,D)),q=[];for(const b of ee)for(const ne of k(b.path,D))q.push(ne);const N=A.current;N.clear();for(const b of q)N.set(he(b),"running");q.length>0&&((_=g.current)==null||_.call(g,q));const te=await ge(D,W,w.current,S.current,d.current,F.current.formulaDataKey,F.current.formulaPathKey,x.current,T.current);if(v.current)break;const re=[...N.values()].some(b=>b==="dirty");if(N.clear(),!re){y(te),q.length>0&&((K=g.current)==null||K.call(g,[]));break}}}finally{p.current=!1}})()},[]),M=i.useCallback(Q=>{m.current=Q;const _=A.current;for(const[K,D]of _)D==="running"&&_.set(K,"dirty");p.current||(j.current!==null&&clearTimeout(j.current),j.current=setTimeout(()=>{j.current=null,E()},s))},[s,E]),R=i.useRef(!1),v=i.useRef(!1);return i.useEffect(()=>{R.current?H(e,h.current)||(h.current=e,M(e)):(R.current=!0,h.current=e,M(e))}),i.useEffect(()=>(v.current=!1,()=>{v.current=!0,R.current=!1,j.current!==null&&clearTimeout(j.current)}),[]),{enrichedFormData:a,handleInput:M}}function Re(e,t){const r=structuredClone(e??{}),s=we(t);for(const n of t)P(r,n.path,s);return r}function we(e){const t=new Set;for(let r=0;r<e.length;r++){const s=e[r].path;for(let n=0;n<s.length;n++){const o=s[n];if(typeof o!="number"&&o!==U)continue;const u=G(s.slice(0,n)),l=typeof o=="number";e.some((c,a)=>{if(a===r||c.path.length<=n||G(c.path.slice(0,n))!==u)return!1;const y=c.path[n];return l?y===U:typeof y=="number"})&&t.add(u)}}return t}function G(e){return JSON.stringify(e.map(t=>typeof t=="symbol"?"__ARRAY_INDEX__":t))}function P(e,t,r,s=[]){if(t.length===0){e["ui:readonly"]=!0;return}const[n,...o]=t;if(typeof n=="string"){(!e[n]||typeof e[n]!="object"||Array.isArray(e[n]))&&(e[n]={}),P(e[n],o,r,[...s,n]);return}if(typeof n=="number"){if(e.items!==void 0&&!Array.isArray(e.items)){console.warn("[rjsf-formulas] mergeReadOnly: cannot inject ui:readonly at tuple index because existing uiSchema has items as an object. Skipping.");return}Array.isArray(e.items)||(e.items=[]);const f=e.items;(!f[n]||typeof f[n]!="object")&&(f[n]={}),P(f[n],o,r,[...s,n]);return}const u=G(s);if(r.has(u))(!e.additionalItems||typeof e.additionalItems!="object")&&(e.additionalItems={}),P(e.additionalItems,o,r,[...s,n]);else{if(Array.isArray(e.items)){console.warn("[rjsf-formulas] mergeReadOnly: cannot inject ui:readonly for uniform array because existing uiSchema has items as an array. Skipping.");return}(!e.items||typeof e.items!="object")&&(e.items={}),P(e.items,o,r,[...s,n])}}function Oe(e,t){const{schema:r,formData:s,validator:n,uiSchema:o,evaluator:u,Form:l=fe,formulaKey:f="x-formula",formulaContextKey:c="x-formula-context",formulaDataKey:a="__formData__",formulaPathKey:y="__path__",maxConvergencePasses:m=10,debounceMs:h=300,onFormulaError:A,onLoadingChange:j,formulaConflictBehavior:p="warn",onChange:d,...g}=e,w=i.useMemo(()=>C(r,{formulaKey:f,formulaContextKey:c}),[r,f,c]),$=i.useMemo(()=>({formulaDataKey:a,formulaPathKey:y}),[a,y]),S=i.useMemo(()=>Re(o,w),[o,w]),F=i.useCallback((R,v)=>n.isValid(R,v,r),[n,r]),{enrichedFormData:x,handleInput:T}=je(s,w,u,h,m,A,j,$,F,p),E=i.useRef(d);i.useEffect(()=>{E.current=d},[d]),i.useEffect(()=>{var R;w.length!==0&&((R=E.current)==null||R.call(E,{formData:x},void 0))},[x]);const M=(R,v)=>{T(R.formData),d==null||d(R,v)};return oe.jsx(l,{ref:t,...g,schema:r,validator:n,formData:x,uiSchema:S,onChange:M})}const Ae=i.forwardRef(Oe);exports.FormulaForm=Ae;exports.analyzeSchema=C;
package/dist/index.d.cts CHANGED
@@ -8,8 +8,11 @@ import { StrictRJSFSchema } from '@rjsf/utils';
8
8
  * Scans a JSON Schema and returns descriptors for every field that carries a formula key.
9
9
  *
10
10
  * @remarks
11
- * Traversal is depth-first. Schema composition operators (`$ref`, `oneOf`, `anyOf`, `allOf`)
12
- * are not supported and emit a `console.warn` when encountered.
11
+ * Traversal is depth-first. `allOf`, `$ref`, `oneOf`, and `anyOf` are all supported.
12
+ * `allOf` branches are merged with conflict detection. `oneOf`/`anyOf` branches are each
13
+ * recursed and fields are collected with the branch schema as the `condition`. Nested
14
+ * `oneOf`/`anyOf` conditions are composed via `{ allOf: [...] }`. `$ref` is resolved
15
+ * synchronously using `findSchemaDefinition` (external refs will throw).
13
16
  *
14
17
  * @param schema - The root RJSF schema to scan.
15
18
  * @param options - Optional key overrides for locating formulas in the schema.
@@ -40,6 +43,14 @@ export declare type AnalyzeSchemaOptions = {
40
43
  formulaKey?: string;
41
44
  /** Schema key that selects the context mode for a computed field. Defaults to `'x-formula-context'`. */
42
45
  formulaContextKey?: string;
46
+ /**
47
+ * What to do when multiple `allOf` branches define a formula for the same path.
48
+ *
49
+ * - `'ignore'`: silently take the last definition.
50
+ * - `'warn'` (default): emit `console.warn` and take the last definition.
51
+ * - `'error'`: throw a `TypeError` synchronously.
52
+ */
53
+ formulaConflictBehavior?: 'ignore' | 'warn' | 'error';
43
54
  };
44
55
 
45
56
  /* Excluded from this release type: ARRAY_INDEX */
@@ -67,45 +78,17 @@ export declare type FormulaField = {
67
78
  formula: string;
68
79
  /** Which values are available when evaluating this field's formula. */
69
80
  contextMode: ContextMode;
81
+ /**
82
+ * The schema condition under which this formula is active.
83
+ *
84
+ * - `true` — always active (fields from `properties`, `items`, `prefixItems`, or `allOf` branches).
85
+ * - `RJSFSchema` — a conditional schema (a `oneOf`/`anyOf` branch condition, possibly composed
86
+ * via `{ allOf: [...] }` for nested branches).
87
+ */
88
+ condition: RJSFSchema | true;
70
89
  };
71
90
 
72
- /**
73
- * Drop-in replacement for RJSF's `<Form>` with support for computed fields.
74
- *
75
- * @remarks
76
- * Fields marked with a formula key in the JSON schema are evaluated automatically
77
- * on every data change and rendered as read-only. The `evaluator` prop receives
78
- * the formula string and a context object, and returns the computed value.
79
- *
80
- * @example
81
- * ```tsx
82
- * import { FormulaForm } from '@a-ludi/rjsf-formulas'
83
- * import validator from '@rjsf/validator-ajv8'
84
- * import { Parser } from 'expr-eval'
85
- *
86
- * const parser = new Parser()
87
- *
88
- * const schema = {
89
- * type: 'object' as const,
90
- * properties: {
91
- * price: { type: 'number' as const },
92
- * quantity: { type: 'number' as const },
93
- * total: { type: 'number' as const, 'x-formula': 'price * quantity' },
94
- * },
95
- * }
96
- *
97
- * function MyForm() {
98
- * return (
99
- * <FormulaForm
100
- * schema={schema}
101
- * validator={validator}
102
- * evaluator={(formula, ctx) => parser.evaluate(formula, ctx)}
103
- * />
104
- * )
105
- * }
106
- * ```
107
- */
108
- export declare function FormulaForm<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(props: FormulaFormProps<T, S, F>): JSX.Element;
91
+ export declare const FormulaForm: <T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(props: FormulaFormProps<T, S, F>) => JSX.Element;
109
92
 
110
93
  /**
111
94
  * Props accepted by {@link FormulaForm}.
@@ -170,6 +153,15 @@ export declare type FormulaFormProps<T = any, S extends StrictRJSFSchema = RJSFS
170
153
  * @param loadingPaths - Paths of all fields whose evaluations are in progress.
171
154
  */
172
155
  onLoadingChange?: (loadingPaths: (string | number)[][]) => void;
156
+ /**
157
+ * What to do when multiple branches of a composition operator (`allOf` at schema-analysis
158
+ * time, or simultaneously-active `oneOf`/`anyOf` branches at evaluation time) define a
159
+ * formula for the same field path.
160
+ * - `'ignore'` — silently take the last definition.
161
+ * - `'warn'` (default) — emit `console.warn` and take the last definition.
162
+ * - `'error'` — throw a `TypeError` synchronously (useful during development).
163
+ */
164
+ formulaConflictBehavior?: 'ignore' | 'warn' | 'error';
173
165
  };
174
166
 
175
167
  export { }
package/dist/index.d.mts CHANGED
@@ -8,8 +8,11 @@ import { StrictRJSFSchema } from '@rjsf/utils';
8
8
  * Scans a JSON Schema and returns descriptors for every field that carries a formula key.
9
9
  *
10
10
  * @remarks
11
- * Traversal is depth-first. Schema composition operators (`$ref`, `oneOf`, `anyOf`, `allOf`)
12
- * are not supported and emit a `console.warn` when encountered.
11
+ * Traversal is depth-first. `allOf`, `$ref`, `oneOf`, and `anyOf` are all supported.
12
+ * `allOf` branches are merged with conflict detection. `oneOf`/`anyOf` branches are each
13
+ * recursed and fields are collected with the branch schema as the `condition`. Nested
14
+ * `oneOf`/`anyOf` conditions are composed via `{ allOf: [...] }`. `$ref` is resolved
15
+ * synchronously using `findSchemaDefinition` (external refs will throw).
13
16
  *
14
17
  * @param schema - The root RJSF schema to scan.
15
18
  * @param options - Optional key overrides for locating formulas in the schema.
@@ -40,6 +43,14 @@ export declare type AnalyzeSchemaOptions = {
40
43
  formulaKey?: string;
41
44
  /** Schema key that selects the context mode for a computed field. Defaults to `'x-formula-context'`. */
42
45
  formulaContextKey?: string;
46
+ /**
47
+ * What to do when multiple `allOf` branches define a formula for the same path.
48
+ *
49
+ * - `'ignore'`: silently take the last definition.
50
+ * - `'warn'` (default): emit `console.warn` and take the last definition.
51
+ * - `'error'`: throw a `TypeError` synchronously.
52
+ */
53
+ formulaConflictBehavior?: 'ignore' | 'warn' | 'error';
43
54
  };
44
55
 
45
56
  /* Excluded from this release type: ARRAY_INDEX */
@@ -67,45 +78,17 @@ export declare type FormulaField = {
67
78
  formula: string;
68
79
  /** Which values are available when evaluating this field's formula. */
69
80
  contextMode: ContextMode;
81
+ /**
82
+ * The schema condition under which this formula is active.
83
+ *
84
+ * - `true` — always active (fields from `properties`, `items`, `prefixItems`, or `allOf` branches).
85
+ * - `RJSFSchema` — a conditional schema (a `oneOf`/`anyOf` branch condition, possibly composed
86
+ * via `{ allOf: [...] }` for nested branches).
87
+ */
88
+ condition: RJSFSchema | true;
70
89
  };
71
90
 
72
- /**
73
- * Drop-in replacement for RJSF's `<Form>` with support for computed fields.
74
- *
75
- * @remarks
76
- * Fields marked with a formula key in the JSON schema are evaluated automatically
77
- * on every data change and rendered as read-only. The `evaluator` prop receives
78
- * the formula string and a context object, and returns the computed value.
79
- *
80
- * @example
81
- * ```tsx
82
- * import { FormulaForm } from '@a-ludi/rjsf-formulas'
83
- * import validator from '@rjsf/validator-ajv8'
84
- * import { Parser } from 'expr-eval'
85
- *
86
- * const parser = new Parser()
87
- *
88
- * const schema = {
89
- * type: 'object' as const,
90
- * properties: {
91
- * price: { type: 'number' as const },
92
- * quantity: { type: 'number' as const },
93
- * total: { type: 'number' as const, 'x-formula': 'price * quantity' },
94
- * },
95
- * }
96
- *
97
- * function MyForm() {
98
- * return (
99
- * <FormulaForm
100
- * schema={schema}
101
- * validator={validator}
102
- * evaluator={(formula, ctx) => parser.evaluate(formula, ctx)}
103
- * />
104
- * )
105
- * }
106
- * ```
107
- */
108
- export declare function FormulaForm<T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(props: FormulaFormProps<T, S, F>): JSX.Element;
91
+ export declare const FormulaForm: <T = any, S extends StrictRJSFSchema = RJSFSchema, F extends FormContextType = any>(props: FormulaFormProps<T, S, F>) => JSX.Element;
109
92
 
110
93
  /**
111
94
  * Props accepted by {@link FormulaForm}.
@@ -170,6 +153,15 @@ export declare type FormulaFormProps<T = any, S extends StrictRJSFSchema = RJSFS
170
153
  * @param loadingPaths - Paths of all fields whose evaluations are in progress.
171
154
  */
172
155
  onLoadingChange?: (loadingPaths: (string | number)[][]) => void;
156
+ /**
157
+ * What to do when multiple branches of a composition operator (`allOf` at schema-analysis
158
+ * time, or simultaneously-active `oneOf`/`anyOf` branches at evaluation time) define a
159
+ * formula for the same field path.
160
+ * - `'ignore'` — silently take the last definition.
161
+ * - `'warn'` (default) — emit `console.warn` and take the last definition.
162
+ * - `'error'` — throw a `TypeError` synchronously (useful during development).
163
+ */
164
+ formulaConflictBehavior?: 'ignore' | 'warn' | 'error';
173
165
  };
174
166
 
175
167
  export { }
package/dist/index.mjs CHANGED
@@ -1,376 +1,467 @@
1
- import { jsx as F } from "react/jsx-runtime";
2
- import { useState as L, useRef as p, useEffect as j, useCallback as G, useMemo as T } from "react";
3
- import tt from "@rjsf/core";
4
- const N = Symbol("arrayIndex");
5
- function et(t, e) {
6
- const n = (e == null ? void 0 : e.formulaKey) ?? "x-formula", o = (e == null ? void 0 : e.formulaContextKey) ?? "x-formula-context", r = [];
7
- return P(t, [], r, n, o), r;
1
+ import { findSchemaDefinition as ft } from "@rjsf/utils";
2
+ import { jsx as ct } from "react/jsx-runtime";
3
+ import { useState as it, useRef as d, useEffect as h, useCallback as G, forwardRef as ut, useMemo as X } from "react";
4
+ import at from "@rjsf/core";
5
+ const J = Symbol("arrayIndex");
6
+ function lt(t, e) {
7
+ const r = (e == null ? void 0 : e.formulaKey) ?? "x-formula", o = (e == null ? void 0 : e.formulaContextKey) ?? "x-formula-context", n = (e == null ? void 0 : e.formulaConflictBehavior) ?? "warn", s = [];
8
+ return x(t, [], s, r, o, n, !0, t), s;
8
9
  }
9
- const rt = ["$ref", "oneOf", "anyOf", "allOf"];
10
- function nt(t, e) {
10
+ function Y(t, e) {
11
+ if (t === !0) return e;
12
+ const r = t;
13
+ return Array.isArray(r.allOf) ? { allOf: [...r.allOf, e] } : { allOf: [t, e] };
14
+ }
15
+ function pt(t, e) {
11
16
  return t === void 0 || t === "siblings" ? "siblings" : t === "extended" ? "extended" : (console.warn(
12
- `[rjsf-formulas] Unknown x-formula-context value "${t}" at path [${U(e)}], treating as "siblings"`
17
+ `[rjsf-formulas] Unknown x-formula-context value "${t}" at path [${z(e)}], treating as "siblings"`
13
18
  ), "siblings");
14
19
  }
15
- function U(t) {
20
+ function z(t) {
16
21
  return t.map((e) => typeof e == "symbol" ? "[*]" : String(e)).join(", ");
17
22
  }
18
- function P(t, e, n, o, r) {
19
- for (const s of rt)
20
- s in t && console.warn(
21
- `[rjsf-formulas] Schema composition operator "${s}" at path [${U(e)}] is not supported and will be skipped. See issue 06.`
23
+ function H(t) {
24
+ return t.map((e) => typeof e == "symbol" ? "[*]" : String(e)).join(".");
25
+ }
26
+ function yt(t, e, r) {
27
+ const o = H(t.path);
28
+ if (r === "error")
29
+ throw new TypeError(
30
+ `[rjsf-formulas] Formula conflict at path [${z(t.path)}]: "${t.formula}" vs "${e.formula}". Resolve the conflict or set formulaConflictBehavior to 'ignore' or 'warn'.`
22
31
  );
32
+ r === "warn" && console.warn(
33
+ `[rjsf-formulas] Formula conflict at path [${o}]: "${t.formula}" (earlier allOf branch) is overridden by "${e.formula}" (later allOf branch).`
34
+ );
35
+ }
36
+ function dt(t, e, r) {
37
+ for (const o of e) {
38
+ const n = H(o.path), s = t.findIndex((i) => H(i.path) === n);
39
+ s !== -1 ? (yt(t[s], o, r), t[s] = o) : t.push(o);
40
+ }
41
+ }
42
+ function x(t, e, r, o, n, s, i, a) {
43
+ const f = t;
44
+ if (typeof f.$ref == "string") {
45
+ const c = ft(f.$ref, a);
46
+ x(c, e, r, o, n, s, i, a);
47
+ return;
48
+ }
23
49
  if (o in t) {
24
- const s = t[o];
25
- if (typeof s != "string") {
50
+ const c = f[o];
51
+ if (typeof c != "string") {
26
52
  console.warn(
27
- `[rjsf-formulas] Formula at path [${U(e)}] is not a string (got ${typeof s}), skipping.`
53
+ `[rjsf-formulas] Formula at path [${z(e)}] is not a string (got ${typeof c}), skipping.`
28
54
  );
29
55
  return;
30
56
  }
31
- n.push({
57
+ r.push({
32
58
  path: e,
33
- formula: s,
34
- contextMode: nt(
35
- t[r],
36
- e
37
- )
59
+ formula: c,
60
+ contextMode: pt(f[n], e),
61
+ condition: i
38
62
  });
39
63
  return;
40
64
  }
41
- if (t.type === "object" && t.properties)
42
- for (const [s, c] of Object.entries(t.properties))
43
- P(
44
- c,
45
- [...e, s],
46
- n,
65
+ if (t.properties && t.type !== "array")
66
+ for (const [c, u] of Object.entries(t.properties))
67
+ x(
68
+ u,
69
+ [...e, c],
70
+ r,
47
71
  o,
48
- r
72
+ n,
73
+ s,
74
+ i,
75
+ a
49
76
  );
50
- if (t.type === "array") {
51
- const s = t;
52
- Array.isArray(s.prefixItems) && s.prefixItems.forEach((i, f) => {
53
- P(i, [...e, f], n, o, r);
54
- }), t.items && !Array.isArray(t.items) && P(
55
- t.items,
56
- [...e, N],
57
- n,
58
- o,
59
- r
60
- );
77
+ if (t.type === "array" && (Array.isArray(f.prefixItems) && f.prefixItems.forEach((u, l) => {
78
+ x(u, [...e, l], r, o, n, s, i, a);
79
+ }), t.items && !Array.isArray(t.items) && x(
80
+ t.items,
81
+ [...e, J],
82
+ r,
83
+ o,
84
+ n,
85
+ s,
86
+ i,
87
+ a
88
+ )), Array.isArray(f.allOf)) {
89
+ const c = f.allOf;
90
+ for (const u of c) {
91
+ const l = [];
92
+ x(u, e, l, o, n, s, i, a), dt(r, l, s);
93
+ }
94
+ }
95
+ for (const c of ["oneOf", "anyOf"])
96
+ if (Array.isArray(f[c])) {
97
+ const u = f[c];
98
+ for (const l of u) {
99
+ const m = Y(i, l);
100
+ x(l, e, r, o, n, s, m, a);
101
+ }
102
+ }
103
+ if ("if" in f) {
104
+ const c = f.if, u = f.then, l = f.else;
105
+ if (o in c && console.warn(
106
+ `[rjsf-formulas] Formula key "${o}" found inside an "if" schema at path [${z(e)}]. The "if" schema is a validation predicate and is never rendered — the formula will be ignored.`
107
+ ), u !== void 0) {
108
+ const m = Y(i, c);
109
+ x(u, e, r, o, n, s, m, a);
110
+ }
111
+ if (l !== void 0) {
112
+ const m = Y(i, { not: c });
113
+ x(l, e, r, o, n, s, m, a);
114
+ }
61
115
  }
62
116
  }
63
- function ot(t) {
117
+ function mt(t) {
64
118
  return t && t.__esModule && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t;
65
119
  }
66
- var C, H;
67
- function st() {
68
- return H || (H = 1, C = function t(e, n) {
69
- if (e === n) return !0;
70
- if (e && n && typeof e == "object" && typeof n == "object") {
71
- if (e.constructor !== n.constructor) return !1;
72
- var o, r, s;
120
+ var V, C;
121
+ function gt() {
122
+ return C || (C = 1, V = function t(e, r) {
123
+ if (e === r) return !0;
124
+ if (e && r && typeof e == "object" && typeof r == "object") {
125
+ if (e.constructor !== r.constructor) return !1;
126
+ var o, n, s;
73
127
  if (Array.isArray(e)) {
74
- if (o = e.length, o != n.length) return !1;
75
- for (r = o; r-- !== 0; )
76
- if (!t(e[r], n[r])) return !1;
128
+ if (o = e.length, o != r.length) return !1;
129
+ for (n = o; n-- !== 0; )
130
+ if (!t(e[n], r[n])) return !1;
77
131
  return !0;
78
132
  }
79
- if (e.constructor === RegExp) return e.source === n.source && e.flags === n.flags;
80
- if (e.valueOf !== Object.prototype.valueOf) return e.valueOf() === n.valueOf();
81
- if (e.toString !== Object.prototype.toString) return e.toString() === n.toString();
82
- if (s = Object.keys(e), o = s.length, o !== Object.keys(n).length) return !1;
83
- for (r = o; r-- !== 0; )
84
- if (!Object.prototype.hasOwnProperty.call(n, s[r])) return !1;
85
- for (r = o; r-- !== 0; ) {
86
- var c = s[r];
87
- if (!t(e[c], n[c])) return !1;
133
+ if (e.constructor === RegExp) return e.source === r.source && e.flags === r.flags;
134
+ if (e.valueOf !== Object.prototype.valueOf) return e.valueOf() === r.valueOf();
135
+ if (e.toString !== Object.prototype.toString) return e.toString() === r.toString();
136
+ if (s = Object.keys(e), o = s.length, o !== Object.keys(r).length) return !1;
137
+ for (n = o; n-- !== 0; )
138
+ if (!Object.prototype.hasOwnProperty.call(r, s[n])) return !1;
139
+ for (n = o; n-- !== 0; ) {
140
+ var i = s[n];
141
+ if (!t(e[i], r[i])) return !1;
88
142
  }
89
143
  return !0;
90
144
  }
91
- return e !== e && n !== n;
92
- }), C;
145
+ return e !== e && r !== r;
146
+ }), V;
93
147
  }
94
- var ft = st();
95
- const ct = /* @__PURE__ */ ot(ft);
96
- function it(t, e, n, o) {
97
- const s = e.slice(0, -1).reduce((i, f) => {
98
- if (!(i == null || typeof i != "object"))
99
- return i[f];
100
- }, n), c = s != null && typeof s == "object" && !Array.isArray(s) ? { ...s } : {};
101
- return t.contextMode === "extended" ? ((o.formulaDataKey in c || o.formulaPathKey in c) && console.warn(
102
- `[rjsf-formulas] Extended context key collision: sibling field named "${o.formulaDataKey in c ? o.formulaDataKey : o.formulaPathKey}" will be overwritten by the injected context. Use formulaDataKey/formulaPathKey props to choose a different key.`
148
+ var ht = gt();
149
+ const jt = /* @__PURE__ */ mt(ht);
150
+ function wt(t, e, r, o) {
151
+ const s = e.slice(0, -1).reduce((a, f) => {
152
+ if (!(a == null || typeof a != "object"))
153
+ return a[f];
154
+ }, r), i = s != null && typeof s == "object" && !Array.isArray(s) ? { ...s } : {};
155
+ return t.contextMode === "extended" ? ((o.formulaDataKey in i || o.formulaPathKey in i) && console.warn(
156
+ `[rjsf-formulas] Extended context key collision: sibling field named "${o.formulaDataKey in i ? o.formulaDataKey : o.formulaPathKey}" will be overwritten by the injected context. Use formulaDataKey/formulaPathKey props to choose a different key.`
103
157
  ), {
104
- ...c,
105
- [o.formulaDataKey]: n,
158
+ ...i,
159
+ [o.formulaDataKey]: r,
106
160
  [o.formulaPathKey]: [...e]
107
- }) : c;
161
+ }) : i;
162
+ }
163
+ function tt(t) {
164
+ return t.map((e) => typeof e == "symbol" ? "[*]" : String(e)).join(", ");
108
165
  }
109
- function A(t, e) {
110
- return e.reduce((n, o) => {
111
- if (!(n == null || typeof n != "object"))
112
- return n[o];
166
+ function k(t, e) {
167
+ return e.reduce((r, o) => {
168
+ if (!(r == null || typeof r != "object"))
169
+ return r[o];
113
170
  }, t);
114
171
  }
115
- function Y(t, e, n) {
172
+ function Q(t, e, r) {
116
173
  if (e.length === 0) return;
117
- const o = A(t, e.slice(0, -1));
118
- o != null && typeof o == "object" && (o[e[e.length - 1]] = n);
174
+ const o = k(t, e.slice(0, -1));
175
+ o != null && typeof o == "object" && (o[e[e.length - 1]] = r);
119
176
  }
120
- function _(t, e, n = []) {
121
- if (t.length === 0) return [n];
122
- const [o, ...r] = t;
123
- if (o === N) {
124
- const s = A(e, n);
177
+ function D(t, e, r = []) {
178
+ if (t.length === 0) return [r];
179
+ const [o, ...n] = t;
180
+ if (o === J) {
181
+ const s = k(e, r);
125
182
  if (!Array.isArray(s)) return [];
126
- const c = [];
127
- for (let i = 0; i < s.length; i++)
128
- c.push(..._(r, e, [...n, i]));
129
- return c;
183
+ const i = [];
184
+ for (let a = 0; a < s.length; a++)
185
+ i.push(...D(n, e, [...r, a]));
186
+ return i;
130
187
  }
131
- return _(r, e, [...n, o]);
188
+ return D(n, e, [...r, o]);
132
189
  }
133
- function J(t, e) {
134
- return ct(t, e);
190
+ function Z(t, e) {
191
+ return jt(t, e);
135
192
  }
136
- async function Q(t, e, n, o) {
137
- const r = structuredClone(t), s = [];
193
+ async function et(t, e, r, o) {
194
+ const n = structuredClone(t), s = [];
138
195
  for (const f of e)
139
- for (const u of _(f.path, r)) {
140
- const a = it(f, u, r, o);
141
- s.push({ field: f, concretePath: u, context: a });
196
+ for (const c of D(f.path, n)) {
197
+ const u = wt(f, c, n, o);
198
+ s.push({ field: f, concretePath: c, context: u });
142
199
  }
143
- const c = await Promise.allSettled(
144
- s.map(({ field: f, context: u }) => new Promise((a) => a(n(f.formula, u))))
145
- ), i = [];
200
+ const i = await Promise.allSettled(
201
+ s.map(({ field: f, context: c }) => new Promise((u) => u(r(f.formula, c))))
202
+ ), a = [];
146
203
  for (let f = 0; f < s.length; f++) {
147
- const { concretePath: u } = s[f], a = c[f];
148
- if (a.status === "fulfilled")
149
- Y(r, u, a.value);
204
+ const { concretePath: c } = s[f], u = i[f];
205
+ if (u.status === "fulfilled")
206
+ Q(n, c, u.value);
150
207
  else {
151
- const l = a.reason instanceof Error ? a.reason : new Error(String(a.reason));
152
- i.push({ path: u, error: l }), Y(r, u, void 0);
208
+ const l = u.reason instanceof Error ? u.reason : new Error(String(u.reason));
209
+ a.push({ path: c, error: l }), Q(n, c, void 0);
153
210
  }
154
211
  }
155
- return { data: r, errors: i };
212
+ return { data: n, errors: a };
156
213
  }
157
- function ut(t, e, n) {
158
- for (const o of n)
159
- for (const r of _(o.path, e))
160
- if (!J(A(t, r), A(e, r)))
214
+ function Ot(t, e, r) {
215
+ for (const o of r)
216
+ for (const n of D(o.path, e))
217
+ if (!Z(k(t, n), k(e, n)))
161
218
  return !1;
162
219
  return !0;
163
220
  }
164
- async function at(t, e, n, o, r, s = "__formData__", c = "__path__") {
165
- if (e.length === 0) return t;
166
- const i = { formulaDataKey: s, formulaPathKey: c };
167
- let f = t;
168
- for (let l = 0; l < o; l++) {
169
- const { data: y, errors: g } = await Q(f, e, n, i);
170
- if (ut(f, y, e)) {
171
- for (const { path: d, error: x } of g)
172
- r == null || r(d, x);
173
- return y;
221
+ async function At(t, e, r, o, n, s, i, a, f) {
222
+ const c = e.filter(
223
+ (y) => y.condition === !0 || a(y.condition, t)
224
+ );
225
+ if (c.length === 0) return t;
226
+ const u = /* @__PURE__ */ new Map(), l = [];
227
+ for (const y of c) {
228
+ const p = JSON.stringify(y.path);
229
+ if (u.has(p)) {
230
+ if (f === "error")
231
+ throw new TypeError(
232
+ `[rjsf-formulas] Formula conflict: two active fields share path [${tt(y.path)}]`
233
+ );
234
+ f === "warn" && console.warn(
235
+ `[rjsf-formulas] Formula conflict: two active fields share path [${tt(y.path)}]; taking last`
236
+ );
237
+ const g = l.indexOf(u.get(p));
238
+ l[g] = y, u.set(p, y);
239
+ } else
240
+ u.set(p, y), l.push(y);
241
+ }
242
+ const m = { formulaDataKey: s, formulaPathKey: i };
243
+ let j = t;
244
+ for (let y = 0; y < o; y++) {
245
+ const { data: p, errors: g } = await et(j, l, r, m);
246
+ if (Ot(j, p, l)) {
247
+ for (const { path: A, error: _ } of g)
248
+ n == null || n(A, _);
249
+ return p;
174
250
  }
175
- f = y;
251
+ j = p;
176
252
  }
177
- const { data: u } = await Q(f, e, n, i), a = structuredClone(u);
178
- for (const l of e)
179
- for (const y of _(l.path, u))
180
- J(A(f, y), A(u, y)) || (r == null || r(
181
- y,
253
+ const { data: b } = await et(j, l, r, m), w = structuredClone(b);
254
+ for (const y of l)
255
+ for (const p of D(y.path, b))
256
+ Z(k(j, p), k(b, p)) || (n == null || n(
257
+ p,
182
258
  new Error(
183
- `[rjsf-formulas] Formula at [${y.join(", ")}] did not converge after ${o} passes`
259
+ `[rjsf-formulas] Formula at [${p.join(", ")}] did not converge after ${o} passes`
184
260
  )
185
- ), Y(a, y, void 0));
186
- return a;
261
+ ), Q(w, p, void 0));
262
+ return w;
187
263
  }
188
- function lt(t) {
264
+ function xt(t) {
189
265
  return JSON.stringify(t);
190
266
  }
191
- function yt(t, e, n, o, r, s, c, i) {
192
- const [f, u] = L(t), a = p(t), l = p(t), y = p(/* @__PURE__ */ new Map()), g = p(null), d = p(!1), x = p(s), m = p(c), v = p(n), M = p(e), O = p(r), w = p(i);
193
- j(() => {
194
- x.current = s;
195
- }, [s]), j(() => {
196
- m.current = c;
197
- }, [c]), j(() => {
198
- v.current = n;
199
- }, [n]), j(() => {
200
- M.current = e;
201
- }, [e]), j(() => {
202
- O.current = r;
203
- }, [r]), j(() => {
204
- w.current = i;
205
- }, [i]);
206
- const h = G(() => {
207
- if (d.current) return;
267
+ function bt(t, e, r, o, n, s, i, a, f, c) {
268
+ const [u, l] = it(t), m = d(t), j = d(t), b = d(/* @__PURE__ */ new Map()), w = d(null), y = d(!1), p = d(s), g = d(i), A = d(r), _ = d(e), T = d(n), F = d(a), $ = d(f), S = d(c);
269
+ h(() => {
270
+ p.current = s;
271
+ }, [s]), h(() => {
272
+ g.current = i;
273
+ }, [i]), h(() => {
274
+ A.current = r;
275
+ }, [r]), h(() => {
276
+ _.current = e;
277
+ }, [e]), h(() => {
278
+ T.current = n;
279
+ }, [n]), h(() => {
280
+ F.current = a;
281
+ }, [a]), h(() => {
282
+ $.current = f;
283
+ }, [f]), h(() => {
284
+ S.current = c;
285
+ }, [c]);
286
+ const v = G(() => {
287
+ if (y.current) return;
208
288
  (async () => {
209
- var R, E;
210
- d.current = !0;
289
+ var M, N;
290
+ y.current = !0;
211
291
  try {
212
292
  for (; ; ) {
213
- const S = a.current, B = M.current, I = [];
214
- for (const D of B)
215
- for (const Z of _(D.path, S))
216
- I.push(Z);
217
- const $ = y.current;
218
- $.clear();
219
- for (const D of I) $.set(lt(D), "running");
220
- I.length > 0 && ((R = m.current) == null || R.call(m, I));
221
- const V = await at(
222
- S,
223
- B,
224
- v.current,
225
- O.current,
226
- x.current,
227
- w.current.formulaDataKey,
228
- w.current.formulaPathKey
293
+ const E = m.current, L = _.current, rt = L.filter(
294
+ (R) => R.condition === !0 || $.current(R.condition, E)
295
+ ), q = [];
296
+ for (const R of rt)
297
+ for (const st of D(R.path, E))
298
+ q.push(st);
299
+ const U = b.current;
300
+ U.clear();
301
+ for (const R of q) U.set(xt(R), "running");
302
+ q.length > 0 && ((M = g.current) == null || M.call(g, q));
303
+ const nt = await At(
304
+ E,
305
+ L,
306
+ A.current,
307
+ T.current,
308
+ p.current,
309
+ F.current.formulaDataKey,
310
+ F.current.formulaPathKey,
311
+ $.current,
312
+ S.current
229
313
  );
230
- if (q.current) break;
231
- const W = [...$.values()].some((D) => D === "dirty");
232
- if ($.clear(), !W) {
233
- u(V), I.length > 0 && ((E = m.current) == null || E.call(m, []));
314
+ if (I.current) break;
315
+ const ot = [...U.values()].some((R) => R === "dirty");
316
+ if (U.clear(), !ot) {
317
+ l(nt), q.length > 0 && ((N = g.current) == null || N.call(g, []));
234
318
  break;
235
319
  }
236
320
  }
237
321
  } finally {
238
- d.current = !1;
322
+ y.current = !1;
239
323
  }
240
324
  })();
241
- }, []), k = G(
242
- (X) => {
243
- a.current = X;
244
- const R = y.current;
245
- for (const [E, S] of R)
246
- S === "running" && R.set(E, "dirty");
247
- d.current || (g.current !== null && clearTimeout(g.current), g.current = setTimeout(() => {
248
- g.current = null, h();
325
+ }, []), K = G(
326
+ (B) => {
327
+ m.current = B;
328
+ const M = b.current;
329
+ for (const [N, E] of M)
330
+ E === "running" && M.set(N, "dirty");
331
+ y.current || (w.current !== null && clearTimeout(w.current), w.current = setTimeout(() => {
332
+ w.current = null, v();
249
333
  }, o));
250
334
  },
251
- [o, h]
252
- ), b = p(!1), q = p(!1);
253
- return j(() => {
254
- b.current ? J(t, l.current) || (l.current = t, k(t)) : (b.current = !0, l.current = t, k(t));
255
- }), j(
256
- () => () => {
257
- q.current = !0, g.current !== null && clearTimeout(g.current);
258
- },
259
- []
260
- ), { enrichedFormData: f, handleInput: k };
335
+ [o, v]
336
+ ), O = d(!1), I = d(!1);
337
+ return h(() => {
338
+ O.current ? Z(t, j.current) || (j.current = t, K(t)) : (O.current = !0, j.current = t, K(t));
339
+ }), h(() => (I.current = !1, () => {
340
+ I.current = !0, O.current = !1, w.current !== null && clearTimeout(w.current);
341
+ }), []), { enrichedFormData: u, handleInput: K };
261
342
  }
262
- function pt(t, e) {
263
- const n = structuredClone(t ?? {}), o = dt(e);
264
- for (const r of e)
265
- K(n, r.path, o);
266
- return n;
343
+ function Rt(t, e) {
344
+ const r = structuredClone(t ?? {}), o = $t(e);
345
+ for (const n of e)
346
+ P(r, n.path, o);
347
+ return r;
267
348
  }
268
- function dt(t) {
349
+ function $t(t) {
269
350
  const e = /* @__PURE__ */ new Set();
270
- for (let n = 0; n < t.length; n++) {
271
- const o = t[n].path;
272
- for (let r = 0; r < o.length; r++) {
273
- const s = o[r];
274
- if (typeof s != "number" && s !== N) continue;
275
- const c = z(o.slice(0, r)), i = typeof s == "number";
276
- t.some((u, a) => {
277
- if (a === n || u.path.length <= r || z(u.path.slice(0, r)) !== c) return !1;
278
- const l = u.path[r];
279
- return i ? l === N : typeof l == "number";
280
- }) && e.add(c);
351
+ for (let r = 0; r < t.length; r++) {
352
+ const o = t[r].path;
353
+ for (let n = 0; n < o.length; n++) {
354
+ const s = o[n];
355
+ if (typeof s != "number" && s !== J) continue;
356
+ const i = W(o.slice(0, n)), a = typeof s == "number";
357
+ t.some((c, u) => {
358
+ if (u === r || c.path.length <= n || W(c.path.slice(0, n)) !== i) return !1;
359
+ const l = c.path[n];
360
+ return a ? l === J : typeof l == "number";
361
+ }) && e.add(i);
281
362
  }
282
363
  }
283
364
  return e;
284
365
  }
285
- function z(t) {
366
+ function W(t) {
286
367
  return JSON.stringify(t.map((e) => typeof e == "symbol" ? "__ARRAY_INDEX__" : e));
287
368
  }
288
- function K(t, e, n, o = []) {
369
+ function P(t, e, r, o = []) {
289
370
  if (e.length === 0) {
290
371
  t["ui:readonly"] = !0;
291
372
  return;
292
373
  }
293
- const [r, ...s] = e;
294
- if (typeof r == "string") {
295
- (!t[r] || typeof t[r] != "object" || Array.isArray(t[r])) && (t[r] = {}), K(t[r], s, n, [...o, r]);
374
+ const [n, ...s] = e;
375
+ if (typeof n == "string") {
376
+ (!t[n] || typeof t[n] != "object" || Array.isArray(t[n])) && (t[n] = {}), P(t[n], s, r, [...o, n]);
296
377
  return;
297
378
  }
298
- if (typeof r == "number") {
379
+ if (typeof n == "number") {
299
380
  if (t.items !== void 0 && !Array.isArray(t.items)) {
300
381
  console.warn("[rjsf-formulas] mergeReadOnly: cannot inject ui:readonly at tuple index because existing uiSchema has items as an object. Skipping.");
301
382
  return;
302
383
  }
303
384
  Array.isArray(t.items) || (t.items = []);
304
385
  const f = t.items;
305
- (!f[r] || typeof f[r] != "object") && (f[r] = {}), K(f[r], s, n, [...o, r]);
386
+ (!f[n] || typeof f[n] != "object") && (f[n] = {}), P(f[n], s, r, [...o, n]);
306
387
  return;
307
388
  }
308
- const c = z(o);
309
- if (n.has(c))
310
- (!t.additionalItems || typeof t.additionalItems != "object") && (t.additionalItems = {}), K(t.additionalItems, s, n, [...o, r]);
389
+ const i = W(o);
390
+ if (r.has(i))
391
+ (!t.additionalItems || typeof t.additionalItems != "object") && (t.additionalItems = {}), P(t.additionalItems, s, r, [...o, n]);
311
392
  else {
312
393
  if (Array.isArray(t.items)) {
313
394
  console.warn("[rjsf-formulas] mergeReadOnly: cannot inject ui:readonly for uniform array because existing uiSchema has items as an array. Skipping.");
314
395
  return;
315
396
  }
316
- (!t.items || typeof t.items != "object") && (t.items = {}), K(t.items, s, n, [...o, r]);
397
+ (!t.items || typeof t.items != "object") && (t.items = {}), P(t.items, s, r, [...o, n]);
317
398
  }
318
399
  }
319
- function bt(t) {
400
+ function vt(t, e) {
320
401
  const {
321
- schema: e,
322
- formData: n,
323
- uiSchema: o,
324
- evaluator: r,
325
- Form: s = tt,
326
- formulaKey: c = "x-formula",
327
- formulaContextKey: i = "x-formula-context",
328
- formulaDataKey: f = "__formData__",
329
- formulaPathKey: u = "__path__",
330
- maxConvergencePasses: a = 10,
331
- debounceMs: l = 300,
332
- onFormulaError: y,
333
- onLoadingChange: g,
334
- onChange: d,
335
- ...x
336
- } = t, m = T(
337
- () => et(e, { formulaKey: c, formulaContextKey: i }),
338
- [e, c, i]
339
- ), v = T(
340
- () => ({ formulaDataKey: f, formulaPathKey: u }),
341
- [f, u]
342
- ), M = T(
343
- () => pt(o, m),
344
- [o, m]
345
- ), { enrichedFormData: O, handleInput: w } = yt(
346
- n,
402
+ schema: r,
403
+ formData: o,
404
+ validator: n,
405
+ uiSchema: s,
406
+ evaluator: i,
407
+ Form: a = at,
408
+ formulaKey: f = "x-formula",
409
+ formulaContextKey: c = "x-formula-context",
410
+ formulaDataKey: u = "__formData__",
411
+ formulaPathKey: l = "__path__",
412
+ maxConvergencePasses: m = 10,
413
+ debounceMs: j = 300,
414
+ onFormulaError: b,
415
+ onLoadingChange: w,
416
+ formulaConflictBehavior: y = "warn",
417
+ onChange: p,
418
+ ...g
419
+ } = t, A = X(
420
+ () => lt(r, { formulaKey: f, formulaContextKey: c }),
421
+ [r, f, c]
422
+ ), _ = X(
423
+ () => ({ formulaDataKey: u, formulaPathKey: l }),
424
+ [u, l]
425
+ ), T = X(
426
+ () => Rt(s, A),
427
+ [s, A]
428
+ ), F = G(
429
+ (O, I) => n.isValid(O, I, r),
430
+ [n, r]
431
+ ), { enrichedFormData: $, handleInput: S } = bt(
432
+ o,
433
+ A,
434
+ i,
435
+ j,
347
436
  m,
348
- r,
349
- l,
437
+ b,
438
+ w,
439
+ _,
440
+ F,
441
+ y
442
+ ), v = d(p);
443
+ return h(() => {
444
+ v.current = p;
445
+ }, [p]), h(() => {
446
+ var O;
447
+ A.length !== 0 && ((O = v.current) == null || O.call(v, { formData: $ }, void 0));
448
+ }, [$]), /* @__PURE__ */ ct(
350
449
  a,
351
- y,
352
- g,
353
- v
354
- ), h = p(d);
355
- return j(() => {
356
- h.current = d;
357
- }, [d]), j(() => {
358
- var b;
359
- m.length !== 0 && ((b = h.current) == null || b.call(h, { formData: O }, void 0));
360
- }, [O]), /* @__PURE__ */ F(
361
- s,
362
450
  {
363
- ...x,
364
- schema: e,
365
- formData: O,
366
- uiSchema: M,
367
- onChange: (b, q) => {
368
- w(b.formData), d == null || d(b, q);
451
+ ref: e,
452
+ ...g,
453
+ schema: r,
454
+ validator: n,
455
+ formData: $,
456
+ uiSchema: T,
457
+ onChange: (O, I) => {
458
+ S(O.formData), p == null || p(O, I);
369
459
  }
370
460
  }
371
461
  );
372
462
  }
463
+ const Ft = ut(vt);
373
464
  export {
374
- bt as FormulaForm,
375
- et as analyzeSchema
465
+ Ft as FormulaForm,
466
+ lt as analyzeSchema
376
467
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a-ludi/rjsf-formulas",
3
- "version": "0.1.3",
3
+ "version": "0.3.0",
4
4
  "description": "RJSF extension for computed fields driven by formulas",
5
5
  "author": "Arne Ludwig <arne.ludwig@posteo.de>",
6
6
  "license": "MIT",