@lehnihon/bit-form 2.0.0 → 2.0.1

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.
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkK3DCDRWBcjs = require('../chunk-K3DCDRWB.cjs');var _core = require('@angular/core');var v=new (0, _core.InjectionToken)("BIT_STORE");function C(t){return{provide:v,useValue:t}}function g(){let t=_core.inject.call(void 0, v,{optional:!0});if(!t)throw new Error('BitForm: N\xE3o foi poss\xEDvel encontrar a BitStore. Certifique-se de que voc\xEA adicionou "provideBitStore(store)" nos providers do seu componente.');return t}function G(){let t=g(),e=_core.inject.call(void 0, _core.DestroyRef),s=_core.signal.call(void 0, t.getState()),r=_core.signal.call(void 0, null),n=_core.signal.call(void 0, null),a=t.subscribe(()=>{s.set(t.getState())});e.onDestroy(()=>a());let S=_core.computed.call(void 0, ()=>s().isValid),o=_core.computed.call(void 0, ()=>s().isSubmitting),i=_core.computed.call(void 0, ()=>s().isDirty),m=()=>s().values,c=()=>s().errors,y=()=>s().touched,x=()=>t.getDirtyValues(),I=P=>B=>(_optionalChain([B, 'optionalAccess', _2 => _2.preventDefault, 'call', _3 => _3()]),_optionalChain([B, 'optionalAccess', _4 => _4.stopPropagation, 'call', _5 => _5()]),t.submit(P)),V=P=>B=>(_optionalChain([B, 'optionalAccess', _6 => _6.preventDefault, 'call', _7 => _7()]),_optionalChain([B, 'optionalAccess', _8 => _8.stopPropagation, 'call', _9 => _9()]),r.set(null),t.submit(async(l,d)=>{try{let u=await P(l,d);n.set(u),r.set(null)}catch(u){_chunkK3DCDRWBcjs.h.call(void 0, u)?t.setServerErrors(_chunkK3DCDRWBcjs.i.call(void 0, u)):r.set(u instanceof Error?u:new Error(String(u)))}})),b=()=>{t.reset(),r.set(null),n.set(null)};return{meta:{isValid:S,isDirty:i,isSubmitting:o,submitError:r.asReadonly(),lastResponse:n.asReadonly()},getValues:m,getErrors:c,getTouched:y,getDirtyValues:x,submit:I,onSubmit:V,reset:b,setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),setField:t.setField.bind(t),blurField:t.blurField.bind(t),validate:t.validate.bind(t),mutations:{pushItem:t.pushItem.bind(t),prependItem:t.prependItem.bind(t),removeItem:t.removeItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t)}}}function X(t,e,s){let r=_core.inject.call(void 0, v),n=_core.signal.call(void 0, r.getState()),a=r.subscribe(()=>{n.set(r.getState())});_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>{a(),r.unregisterField&&r.unregisterField(t)}),e&&r.registerField(t,e);let S=_core.computed.call(void 0, ()=>_chunkK3DCDRWBcjs.e.call(void 0, n().values,t)),o=_core.computed.call(void 0, ()=>n().errors[t]),i=_core.computed.call(void 0, ()=>!!n().touched[t]),m=_core.computed.call(void 0, ()=>i()?o():void 0),c=_core.computed.call(void 0, ()=>(n(),r.isFieldDirty(t))),y=_core.computed.call(void 0, ()=>(n(),r.isFieldValidating(t))),x=_core.computed.call(void 0, ()=>(n(),r.isHidden(t))),I=_core.computed.call(void 0, ()=>(n(),r.isRequired(t))),V=_core.computed.call(void 0, ()=>i()&&!!o()),b=_nullishCoalesce(_optionalChain([s, 'optionalAccess', _10 => _10.mask]), () => (_optionalChain([r, 'access', _11 => _11.config, 'access', _12 => _12.fields, 'optionalAccess', _13 => _13[t], 'optionalAccess', _14 => _14.mask]))),T=b?typeof b=="string"?r.config.masks[b]:b:void 0,P=_core.computed.call(void 0, ()=>{let p=S();return p==null||p===""?"":T?T.format(p):String(p)}),B=p=>{if(!T){r.setField(t,p);return}let K=String(_nullishCoalesce(p, () => ("")));r.setField(t,T.parse(K))},l=()=>r.blurField(t),d=_core.computed.call(void 0, ()=>!!o());return{value:S,displayValue:P,setValue:B,setBlur:l,update:p=>B(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _15 => _15.target, 'optionalAccess', _16 => _16.value]), () => (p))),meta:{error:m,touched:i,invalid:V,isDirty:c,isValidating:y,isHidden:x,isRequired:I,hasError:d}}}var F=()=>Math.random().toString(36).substring(2,9);function N(t){let e=_core.inject.call(void 0, v),s=_core.inject.call(void 0, _core.DestroyRef),r=()=>{let o=_chunkK3DCDRWBcjs.e.call(void 0, e.getState().values,t);return Array.isArray(o)?o:[]},n=_core.signal.call(void 0, r()),a=_core.signal.call(void 0, n().map(F)),S=e.subscribe(()=>{let o=r(),i=_core.untracked.call(void 0, a);n.set(o),o.length!==i.length&&(o.length>i.length?a.set([...i,...Array.from({length:o.length-i.length},F)]):a.set(i.slice(0,o.length)))});return s.onDestroy(()=>{S(),e.unregisterPrefix&&e.unregisterPrefix(`${t}.`)}),{fields:_core.computed.call(void 0, ()=>n().map((o,i)=>({key:a()[i]||`temp-${i}`,value:o,index:i}))),length:_core.computed.call(void 0, ()=>n().length),append:o=>{a.update(i=>[...i,F()]),e.pushItem(t,o)},prepend:o=>{a.update(i=>[F(),...i]),e.prependItem(t,o)},remove:o=>{a.update(i=>i.filter((m,c)=>c!==o)),e.removeItem(t,o)},insert:(o,i)=>{a.update(m=>{let c=[...m];return c.splice(o,0,F()),c}),e.insertItem(t,o,i)},swap:(o,i)=>{a.update(m=>{let c=[...m];return[c[o],c[i]]=[c[i],c[o]],c}),e.swapItems(t,o,i)},move:(o,i)=>{a.update(m=>{let c=[...m],[y]=c.splice(o,1);return c.splice(i,0,y),c}),e.moveItem(t,o,i)},replace:o=>{a.set(o.map(()=>F())),e.setField(t,o)},clear:()=>{a.set([]),e.setField(t,[])}}}function ot(){let t=g(),e=_core.inject.call(void 0, _core.DestroyRef),s=_core.signal.call(void 0, t.getHistoryMetadata()),r=t.subscribe(()=>{s.set(t.getHistoryMetadata())});return e.onDestroy(()=>r()),{canUndo:_core.computed.call(void 0, ()=>s().canUndo),canRedo:_core.computed.call(void 0, ()=>s().canRedo),historyIndex:_core.computed.call(void 0, ()=>s().historyIndex),historySize:_core.computed.call(void 0, ()=>s().historySize),undo:()=>t.undo(),redo:()=>t.redo()}}function at(t,e){let s=Object.keys(t),r=Object.keys(e);return s.length!==r.length?!1:s.every(n=>t[n]===e[n])}function ct(t){let e=g(),s=e.getStepStatus(t),r=_core.signal.call(void 0, s),n=e.subscribe(()=>{let c=e.getStepStatus(t),y=r();(c.hasErrors!==y.hasErrors||c.isDirty!==y.isDirty||!at(c.errors,y.errors))&&r.set(c)});try{_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>n())}catch (e2){}let a=async()=>{let c=await e.validate({scope:t}),y=e.getStepErrors(t);return{valid:c,errors:y}},S=()=>e.getStepErrors(t),o=_core.computed.call(void 0, ()=>!r().hasErrors),i=_core.computed.call(void 0, ()=>r().isDirty),m=_core.computed.call(void 0, ()=>r().errors);return{scopeName:t,status:r,errors:m,validate:a,getErrors:S,isValid:o,isDirty:i,unsubscribe:n}}function dt(t,e){let s=Object.keys(t),r=Object.keys(e);return s.length!==r.length?!1:s.every(n=>t[n]===e[n])}function mt(t){let e=g(),s=_core.signal.call(void 0, 0),r=_core.computed.call(void 0, ()=>_nullishCoalesce(t[s()], () => (""))),n=()=>_nullishCoalesce(t[s()], () => ("")),a=_core.signal.call(void 0, e.getStepStatus(n())),S=()=>{let l=n(),d=e.getStepStatus(l),u=a();(d.hasErrors!==u.hasErrors||d.isDirty!==u.isDirty||!dt(d.errors,u.errors))&&a.set(d)},o=e.subscribe(S);try{_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>o())}catch (e3){}let i=async()=>{let l=n(),d=await e.validate({scope:l}),u=e.getStepErrors(l);return{valid:d,errors:u}},m=()=>e.getStepErrors(n()),c=async()=>{let l=n(),d=await e.validate({scope:l});if(d){let u=Math.min(s()+1,t.length-1);s.set(u),a.set(e.getStepStatus(_nullishCoalesce(t[u], () => (""))))}else{let u=e.getStepErrors(l),p=Object.keys(u);p.length>0&&e.markFieldsTouched(p)}return d},y=()=>{let l=Math.max(s()-1,0);s.set(l),a.set(e.getStepStatus(_nullishCoalesce(t[l], () => (""))))},x=l=>{let d=Math.max(0,Math.min(l-1,t.length-1));s.set(d),a.set(e.getStepStatus(_nullishCoalesce(t[d], () => (""))))},I=_core.computed.call(void 0, ()=>s()+1),V=_core.computed.call(void 0, ()=>s()===0),b=_core.computed.call(void 0, ()=>s()>=t.length-1),T=_core.computed.call(void 0, ()=>!a().hasErrors),P=_core.computed.call(void 0, ()=>a().isDirty),B=_core.computed.call(void 0, ()=>a().errors);return{step:I,stepIndex:s,scope:r,next:c,prev:y,goTo:x,isFirst:V,isLast:b,status:a,errors:B,isValid:T,isDirty:P,validate:i,getErrors:m}}function ft(t){let e=g(),s=_core.inject.call(void 0, _core.DestroyRef),r=_core.signal.call(void 0, _chunkK3DCDRWBcjs.e.call(void 0, e.getState().values,t),{equal:_chunkK3DCDRWBcjs.d}),n=e.watch(t,a=>{r.set(a)});return s.onDestroy(n),r.asReadonly()}exports.injectBitArray = N; exports.injectBitField = X; exports.injectBitForm = G; exports.injectBitHistory = ot; exports.injectBitScope = ct; exports.injectBitSteps = mt; exports.injectBitWatch = ft; exports.provideBitStore = C; exports.useBitStore = g;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk4MPIKMTHcjs = require('../chunk-4MPIKMTH.cjs');var _core = require('@angular/core');var v=new (0, _core.InjectionToken)("BIT_STORE");function C(t){return{provide:v,useValue:t}}function g(){let t=_core.inject.call(void 0, v,{optional:!0});if(!t)throw new Error('BitForm: N\xE3o foi poss\xEDvel encontrar a BitStore. Certifique-se de que voc\xEA adicionou "provideBitStore(store)" nos providers do seu componente.');return t}function G(){let t=g(),e=_core.inject.call(void 0, _core.DestroyRef),s=_core.signal.call(void 0, t.getState()),r=_core.signal.call(void 0, null),n=_core.signal.call(void 0, null),a=t.subscribe(()=>{s.set(t.getState())});e.onDestroy(()=>a());let S=_core.computed.call(void 0, ()=>s().isValid),o=_core.computed.call(void 0, ()=>s().isSubmitting),i=_core.computed.call(void 0, ()=>s().isDirty),m=()=>s().values,c=()=>s().errors,y=()=>s().touched,x=()=>t.getDirtyValues(),I=P=>B=>(_optionalChain([B, 'optionalAccess', _2 => _2.preventDefault, 'call', _3 => _3()]),_optionalChain([B, 'optionalAccess', _4 => _4.stopPropagation, 'call', _5 => _5()]),t.submit(P)),V=P=>B=>(_optionalChain([B, 'optionalAccess', _6 => _6.preventDefault, 'call', _7 => _7()]),_optionalChain([B, 'optionalAccess', _8 => _8.stopPropagation, 'call', _9 => _9()]),r.set(null),t.submit(async(l,d)=>{try{let u=await P(l,d);n.set(u),r.set(null)}catch(u){_chunk4MPIKMTHcjs.h.call(void 0, u)?t.setServerErrors(_chunk4MPIKMTHcjs.i.call(void 0, u)):r.set(u instanceof Error?u:new Error(String(u)))}})),b=()=>{t.reset(),r.set(null),n.set(null)};return{meta:{isValid:S,isDirty:i,isSubmitting:o,submitError:r.asReadonly(),lastResponse:n.asReadonly()},getValues:m,getErrors:c,getTouched:y,getDirtyValues:x,submit:I,onSubmit:V,reset:b,setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),setField:t.setField.bind(t),blurField:t.blurField.bind(t),validate:t.validate.bind(t),mutations:{pushItem:t.pushItem.bind(t),prependItem:t.prependItem.bind(t),removeItem:t.removeItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t)}}}function X(t,e,s){let r=_core.inject.call(void 0, v),n=_core.signal.call(void 0, r.getState()),a=r.subscribe(()=>{n.set(r.getState())});_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>{a(),r.unregisterField&&r.unregisterField(t)}),e&&r.registerField(t,e);let S=_core.computed.call(void 0, ()=>_chunk4MPIKMTHcjs.e.call(void 0, n().values,t)),o=_core.computed.call(void 0, ()=>n().errors[t]),i=_core.computed.call(void 0, ()=>!!n().touched[t]),m=_core.computed.call(void 0, ()=>i()?o():void 0),c=_core.computed.call(void 0, ()=>(n(),r.isFieldDirty(t))),y=_core.computed.call(void 0, ()=>(n(),r.isFieldValidating(t))),x=_core.computed.call(void 0, ()=>(n(),r.isHidden(t))),I=_core.computed.call(void 0, ()=>(n(),r.isRequired(t))),V=_core.computed.call(void 0, ()=>i()&&!!o()),b=_nullishCoalesce(_optionalChain([s, 'optionalAccess', _10 => _10.mask]), () => (_optionalChain([r, 'access', _11 => _11.config, 'access', _12 => _12.fields, 'optionalAccess', _13 => _13[t], 'optionalAccess', _14 => _14.mask]))),T=b?typeof b=="string"?r.config.masks[b]:b:void 0,P=_core.computed.call(void 0, ()=>{let p=S();return p==null||p===""?"":T?T.format(p):String(p)}),B=p=>{if(!T){r.setField(t,p);return}let K=String(_nullishCoalesce(p, () => ("")));r.setField(t,T.parse(K))},l=()=>r.blurField(t),d=_core.computed.call(void 0, ()=>!!o());return{value:S,displayValue:P,setValue:B,setBlur:l,update:p=>B(_nullishCoalesce(_optionalChain([p, 'optionalAccess', _15 => _15.target, 'optionalAccess', _16 => _16.value]), () => (p))),meta:{error:m,touched:i,invalid:V,isDirty:c,isValidating:y,isHidden:x,isRequired:I,hasError:d}}}var F=()=>Math.random().toString(36).substring(2,9);function N(t){let e=_core.inject.call(void 0, v),s=_core.inject.call(void 0, _core.DestroyRef),r=()=>{let o=_chunk4MPIKMTHcjs.e.call(void 0, e.getState().values,t);return Array.isArray(o)?o:[]},n=_core.signal.call(void 0, r()),a=_core.signal.call(void 0, n().map(F)),S=e.subscribe(()=>{let o=r(),i=_core.untracked.call(void 0, a);n.set(o),o.length!==i.length&&(o.length>i.length?a.set([...i,...Array.from({length:o.length-i.length},F)]):a.set(i.slice(0,o.length)))});return s.onDestroy(()=>{S(),e.unregisterPrefix&&e.unregisterPrefix(`${t}.`)}),{fields:_core.computed.call(void 0, ()=>n().map((o,i)=>({key:a()[i]||`temp-${i}`,value:o,index:i}))),length:_core.computed.call(void 0, ()=>n().length),append:o=>{a.update(i=>[...i,F()]),e.pushItem(t,o)},prepend:o=>{a.update(i=>[F(),...i]),e.prependItem(t,o)},remove:o=>{a.update(i=>i.filter((m,c)=>c!==o)),e.removeItem(t,o)},insert:(o,i)=>{a.update(m=>{let c=[...m];return c.splice(o,0,F()),c}),e.insertItem(t,o,i)},swap:(o,i)=>{a.update(m=>{let c=[...m];return[c[o],c[i]]=[c[i],c[o]],c}),e.swapItems(t,o,i)},move:(o,i)=>{a.update(m=>{let c=[...m],[y]=c.splice(o,1);return c.splice(i,0,y),c}),e.moveItem(t,o,i)},replace:o=>{a.set(o.map(()=>F())),e.setField(t,o)},clear:()=>{a.set([]),e.setField(t,[])}}}function ot(){let t=g(),e=_core.inject.call(void 0, _core.DestroyRef),s=_core.signal.call(void 0, t.getHistoryMetadata()),r=t.subscribe(()=>{s.set(t.getHistoryMetadata())});return e.onDestroy(()=>r()),{canUndo:_core.computed.call(void 0, ()=>s().canUndo),canRedo:_core.computed.call(void 0, ()=>s().canRedo),historyIndex:_core.computed.call(void 0, ()=>s().historyIndex),historySize:_core.computed.call(void 0, ()=>s().historySize),undo:()=>t.undo(),redo:()=>t.redo()}}function at(t,e){let s=Object.keys(t),r=Object.keys(e);return s.length!==r.length?!1:s.every(n=>t[n]===e[n])}function ct(t){let e=g(),s=e.getStepStatus(t),r=_core.signal.call(void 0, s),n=e.subscribe(()=>{let c=e.getStepStatus(t),y=r();(c.hasErrors!==y.hasErrors||c.isDirty!==y.isDirty||!at(c.errors,y.errors))&&r.set(c)});try{_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>n())}catch (e2){}let a=async()=>{let c=await e.validate({scope:t}),y=e.getStepErrors(t);return{valid:c,errors:y}},S=()=>e.getStepErrors(t),o=_core.computed.call(void 0, ()=>!r().hasErrors),i=_core.computed.call(void 0, ()=>r().isDirty),m=_core.computed.call(void 0, ()=>r().errors);return{scopeName:t,status:r,errors:m,validate:a,getErrors:S,isValid:o,isDirty:i,unsubscribe:n}}function dt(t,e){let s=Object.keys(t),r=Object.keys(e);return s.length!==r.length?!1:s.every(n=>t[n]===e[n])}function mt(t){let e=g(),s=_core.signal.call(void 0, 0),r=_core.computed.call(void 0, ()=>_nullishCoalesce(t[s()], () => (""))),n=()=>_nullishCoalesce(t[s()], () => ("")),a=_core.signal.call(void 0, e.getStepStatus(n())),S=()=>{let l=n(),d=e.getStepStatus(l),u=a();(d.hasErrors!==u.hasErrors||d.isDirty!==u.isDirty||!dt(d.errors,u.errors))&&a.set(d)},o=e.subscribe(S);try{_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>o())}catch (e3){}let i=async()=>{let l=n(),d=await e.validate({scope:l}),u=e.getStepErrors(l);return{valid:d,errors:u}},m=()=>e.getStepErrors(n()),c=async()=>{let l=n(),d=await e.validate({scope:l});if(d){let u=Math.min(s()+1,t.length-1);s.set(u),a.set(e.getStepStatus(_nullishCoalesce(t[u], () => (""))))}else{let u=e.getStepErrors(l),p=Object.keys(u);p.length>0&&e.markFieldsTouched(p)}return d},y=()=>{let l=Math.max(s()-1,0);s.set(l),a.set(e.getStepStatus(_nullishCoalesce(t[l], () => (""))))},x=l=>{let d=Math.max(0,Math.min(l-1,t.length-1));s.set(d),a.set(e.getStepStatus(_nullishCoalesce(t[d], () => (""))))},I=_core.computed.call(void 0, ()=>s()+1),V=_core.computed.call(void 0, ()=>s()===0),b=_core.computed.call(void 0, ()=>s()>=t.length-1),T=_core.computed.call(void 0, ()=>!a().hasErrors),P=_core.computed.call(void 0, ()=>a().isDirty),B=_core.computed.call(void 0, ()=>a().errors);return{step:I,stepIndex:s,scope:r,next:c,prev:y,goTo:x,isFirst:V,isLast:b,status:a,errors:B,isValid:T,isDirty:P,validate:i,getErrors:m}}function ft(t){let e=g(),s=_core.inject.call(void 0, _core.DestroyRef),r=_core.signal.call(void 0, _chunk4MPIKMTHcjs.e.call(void 0, e.getState().values,t),{equal:_chunk4MPIKMTHcjs.d}),n=e.watch(t,a=>{r.set(a)});return s.onDestroy(n),r.asReadonly()}exports.injectBitArray = N; exports.injectBitField = X; exports.injectBitForm = G; exports.injectBitHistory = ot; exports.injectBitScope = ct; exports.injectBitSteps = mt; exports.injectBitWatch = ft; exports.provideBitStore = C; exports.useBitStore = g;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1,2 +1,2 @@
1
- import{d as k,e as h,h as A,i as O}from"../chunk-4KRTZKIQ.js";import{inject as U,InjectionToken as W}from"@angular/core";var v=new W("BIT_STORE");function C(t){return{provide:v,useValue:t}}function g(){let t=U(v,{optional:!0});if(!t)throw new Error('BitForm: N\xE3o foi poss\xEDvel encontrar a BitStore. Certifique-se de que voc\xEA adicionou "provideBitStore(store)" nos providers do seu componente.');return t}import{signal as E,computed as D,inject as L,DestroyRef as $}from"@angular/core";function G(){let t=g(),e=L($),s=E(t.getState()),r=E(null),n=E(null),a=t.subscribe(()=>{s.set(t.getState())});e.onDestroy(()=>a());let S=D(()=>s().isValid),o=D(()=>s().isSubmitting),i=D(()=>s().isDirty),m=()=>s().values,c=()=>s().errors,y=()=>s().touched,x=()=>t.getDirtyValues(),I=P=>B=>(B?.preventDefault(),B?.stopPropagation(),t.submit(P)),V=P=>B=>(B?.preventDefault(),B?.stopPropagation(),r.set(null),t.submit(async(l,d)=>{try{let u=await P(l,d);n.set(u),r.set(null)}catch(u){A(u)?t.setServerErrors(O(u)):r.set(u instanceof Error?u:new Error(String(u)))}})),b=()=>{t.reset(),r.set(null),n.set(null)};return{meta:{isValid:S,isDirty:i,isSubmitting:o,submitError:r.asReadonly(),lastResponse:n.asReadonly()},getValues:m,getErrors:c,getTouched:y,getDirtyValues:x,submit:I,onSubmit:V,reset:b,setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),setField:t.setField.bind(t),blurField:t.blurField.bind(t),validate:t.validate.bind(t),mutations:{pushItem:t.pushItem.bind(t),prependItem:t.prependItem.bind(t),removeItem:t.removeItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t)}}}import{inject as M,DestroyRef as J,computed as f,signal as Q}from"@angular/core";function X(t,e,s){let r=M(v),n=Q(r.getState()),a=r.subscribe(()=>{n.set(r.getState())});M(J).onDestroy(()=>{a(),r.unregisterField&&r.unregisterField(t)}),e&&r.registerField(t,e);let S=f(()=>h(n().values,t)),o=f(()=>n().errors[t]),i=f(()=>!!n().touched[t]),m=f(()=>i()?o():void 0),c=f(()=>(n(),r.isFieldDirty(t))),y=f(()=>(n(),r.isFieldValidating(t))),x=f(()=>(n(),r.isHidden(t))),I=f(()=>(n(),r.isRequired(t))),V=f(()=>i()&&!!o()),b=s?.mask??r.config.fields?.[t]?.mask,T=b?typeof b=="string"?r.config.masks[b]:b:void 0,P=f(()=>{let p=S();return p==null||p===""?"":T?T.format(p):String(p)}),B=p=>{if(!T){r.setField(t,p);return}let K=String(p??"");r.setField(t,T.parse(K))},l=()=>r.blurField(t),d=f(()=>!!o());return{value:S,displayValue:P,setValue:B,setBlur:l,update:p=>B(p?.target?.value??p),meta:{error:m,touched:i,invalid:V,isDirty:c,isValidating:y,isHidden:x,isRequired:I,hasError:d}}}import{DestroyRef as Y,signal as q,computed as H,inject as _,untracked as Z}from"@angular/core";var F=()=>Math.random().toString(36).substring(2,9);function N(t){let e=_(v),s=_(Y),r=()=>{let o=h(e.getState().values,t);return Array.isArray(o)?o:[]},n=q(r()),a=q(n().map(F)),S=e.subscribe(()=>{let o=r(),i=Z(a);n.set(o),o.length!==i.length&&(o.length>i.length?a.set([...i,...Array.from({length:o.length-i.length},F)]):a.set(i.slice(0,o.length)))});return s.onDestroy(()=>{S(),e.unregisterPrefix&&e.unregisterPrefix(`${t}.`)}),{fields:H(()=>n().map((o,i)=>({key:a()[i]||`temp-${i}`,value:o,index:i}))),length:H(()=>n().length),append:o=>{a.update(i=>[...i,F()]),e.pushItem(t,o)},prepend:o=>{a.update(i=>[F(),...i]),e.prependItem(t,o)},remove:o=>{a.update(i=>i.filter((m,c)=>c!==o)),e.removeItem(t,o)},insert:(o,i)=>{a.update(m=>{let c=[...m];return c.splice(o,0,F()),c}),e.insertItem(t,o,i)},swap:(o,i)=>{a.update(m=>{let c=[...m];return[c[o],c[i]]=[c[i],c[o]],c}),e.swapItems(t,o,i)},move:(o,i)=>{a.update(m=>{let c=[...m],[y]=c.splice(o,1);return c.splice(i,0,y),c}),e.moveItem(t,o,i)},replace:o=>{a.set(o.map(()=>F())),e.setField(t,o)},clear:()=>{a.set([]),e.setField(t,[])}}}import{computed as j,DestroyRef as tt,inject as et,signal as rt}from"@angular/core";function ot(){let t=g(),e=et(tt),s=rt(t.getHistoryMetadata()),r=t.subscribe(()=>{s.set(t.getHistoryMetadata())});return e.onDestroy(()=>r()),{canUndo:j(()=>s().canUndo),canRedo:j(()=>s().canRedo),historyIndex:j(()=>s().historyIndex),historySize:j(()=>s().historySize),undo:()=>t.undo(),redo:()=>t.redo()}}import{signal as st,computed as w,DestroyRef as nt,inject as it}from"@angular/core";function at(t,e){let s=Object.keys(t),r=Object.keys(e);return s.length!==r.length?!1:s.every(n=>t[n]===e[n])}function ct(t){let e=g(),s=e.getStepStatus(t),r=st(s),n=e.subscribe(()=>{let c=e.getStepStatus(t),y=r();(c.hasErrors!==y.hasErrors||c.isDirty!==y.isDirty||!at(c.errors,y.errors))&&r.set(c)});try{it(nt).onDestroy(()=>n())}catch{}let a=async()=>{let c=await e.validate({scope:t}),y=e.getStepErrors(t);return{valid:c,errors:y}},S=()=>e.getStepErrors(t),o=w(()=>!r().hasErrors),i=w(()=>r().isDirty),m=w(()=>r().errors);return{scopeName:t,status:r,errors:m,validate:a,getErrors:S,isValid:o,isDirty:i,unsubscribe:n}}import{signal as z,computed as R,DestroyRef as ut,inject as lt}from"@angular/core";function dt(t,e){let s=Object.keys(t),r=Object.keys(e);return s.length!==r.length?!1:s.every(n=>t[n]===e[n])}function mt(t){let e=g(),s=z(0),r=R(()=>t[s()]??""),n=()=>t[s()]??"",a=z(e.getStepStatus(n())),S=()=>{let l=n(),d=e.getStepStatus(l),u=a();(d.hasErrors!==u.hasErrors||d.isDirty!==u.isDirty||!dt(d.errors,u.errors))&&a.set(d)},o=e.subscribe(S);try{lt(ut).onDestroy(()=>o())}catch{}let i=async()=>{let l=n(),d=await e.validate({scope:l}),u=e.getStepErrors(l);return{valid:d,errors:u}},m=()=>e.getStepErrors(n()),c=async()=>{let l=n(),d=await e.validate({scope:l});if(d){let u=Math.min(s()+1,t.length-1);s.set(u),a.set(e.getStepStatus(t[u]??""))}else{let u=e.getStepErrors(l),p=Object.keys(u);p.length>0&&e.markFieldsTouched(p)}return d},y=()=>{let l=Math.max(s()-1,0);s.set(l),a.set(e.getStepStatus(t[l]??""))},x=l=>{let d=Math.max(0,Math.min(l-1,t.length-1));s.set(d),a.set(e.getStepStatus(t[d]??""))},I=R(()=>s()+1),V=R(()=>s()===0),b=R(()=>s()>=t.length-1),T=R(()=>!a().hasErrors),P=R(()=>a().isDirty),B=R(()=>a().errors);return{step:I,stepIndex:s,scope:r,next:c,prev:y,goTo:x,isFirst:V,isLast:b,status:a,errors:B,isValid:T,isDirty:P,validate:i,getErrors:m}}import{DestroyRef as pt,signal as yt,inject as gt}from"@angular/core";function ft(t){let e=g(),s=gt(pt),r=yt(h(e.getState().values,t),{equal:k}),n=e.watch(t,a=>{r.set(a)});return s.onDestroy(n),r.asReadonly()}export{N as injectBitArray,X as injectBitField,G as injectBitForm,ot as injectBitHistory,ct as injectBitScope,mt as injectBitSteps,ft as injectBitWatch,C as provideBitStore,g as useBitStore};
1
+ import{d as k,e as h,h as A,i as O}from"../chunk-ZWLZ4XDF.js";import{inject as U,InjectionToken as W}from"@angular/core";var v=new W("BIT_STORE");function C(t){return{provide:v,useValue:t}}function g(){let t=U(v,{optional:!0});if(!t)throw new Error('BitForm: N\xE3o foi poss\xEDvel encontrar a BitStore. Certifique-se de que voc\xEA adicionou "provideBitStore(store)" nos providers do seu componente.');return t}import{signal as E,computed as D,inject as L,DestroyRef as $}from"@angular/core";function G(){let t=g(),e=L($),s=E(t.getState()),r=E(null),n=E(null),a=t.subscribe(()=>{s.set(t.getState())});e.onDestroy(()=>a());let S=D(()=>s().isValid),o=D(()=>s().isSubmitting),i=D(()=>s().isDirty),m=()=>s().values,c=()=>s().errors,y=()=>s().touched,x=()=>t.getDirtyValues(),I=P=>B=>(B?.preventDefault(),B?.stopPropagation(),t.submit(P)),V=P=>B=>(B?.preventDefault(),B?.stopPropagation(),r.set(null),t.submit(async(l,d)=>{try{let u=await P(l,d);n.set(u),r.set(null)}catch(u){A(u)?t.setServerErrors(O(u)):r.set(u instanceof Error?u:new Error(String(u)))}})),b=()=>{t.reset(),r.set(null),n.set(null)};return{meta:{isValid:S,isDirty:i,isSubmitting:o,submitError:r.asReadonly(),lastResponse:n.asReadonly()},getValues:m,getErrors:c,getTouched:y,getDirtyValues:x,submit:I,onSubmit:V,reset:b,setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),setField:t.setField.bind(t),blurField:t.blurField.bind(t),validate:t.validate.bind(t),mutations:{pushItem:t.pushItem.bind(t),prependItem:t.prependItem.bind(t),removeItem:t.removeItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t)}}}import{inject as M,DestroyRef as J,computed as f,signal as Q}from"@angular/core";function X(t,e,s){let r=M(v),n=Q(r.getState()),a=r.subscribe(()=>{n.set(r.getState())});M(J).onDestroy(()=>{a(),r.unregisterField&&r.unregisterField(t)}),e&&r.registerField(t,e);let S=f(()=>h(n().values,t)),o=f(()=>n().errors[t]),i=f(()=>!!n().touched[t]),m=f(()=>i()?o():void 0),c=f(()=>(n(),r.isFieldDirty(t))),y=f(()=>(n(),r.isFieldValidating(t))),x=f(()=>(n(),r.isHidden(t))),I=f(()=>(n(),r.isRequired(t))),V=f(()=>i()&&!!o()),b=s?.mask??r.config.fields?.[t]?.mask,T=b?typeof b=="string"?r.config.masks[b]:b:void 0,P=f(()=>{let p=S();return p==null||p===""?"":T?T.format(p):String(p)}),B=p=>{if(!T){r.setField(t,p);return}let K=String(p??"");r.setField(t,T.parse(K))},l=()=>r.blurField(t),d=f(()=>!!o());return{value:S,displayValue:P,setValue:B,setBlur:l,update:p=>B(p?.target?.value??p),meta:{error:m,touched:i,invalid:V,isDirty:c,isValidating:y,isHidden:x,isRequired:I,hasError:d}}}import{DestroyRef as Y,signal as q,computed as H,inject as _,untracked as Z}from"@angular/core";var F=()=>Math.random().toString(36).substring(2,9);function N(t){let e=_(v),s=_(Y),r=()=>{let o=h(e.getState().values,t);return Array.isArray(o)?o:[]},n=q(r()),a=q(n().map(F)),S=e.subscribe(()=>{let o=r(),i=Z(a);n.set(o),o.length!==i.length&&(o.length>i.length?a.set([...i,...Array.from({length:o.length-i.length},F)]):a.set(i.slice(0,o.length)))});return s.onDestroy(()=>{S(),e.unregisterPrefix&&e.unregisterPrefix(`${t}.`)}),{fields:H(()=>n().map((o,i)=>({key:a()[i]||`temp-${i}`,value:o,index:i}))),length:H(()=>n().length),append:o=>{a.update(i=>[...i,F()]),e.pushItem(t,o)},prepend:o=>{a.update(i=>[F(),...i]),e.prependItem(t,o)},remove:o=>{a.update(i=>i.filter((m,c)=>c!==o)),e.removeItem(t,o)},insert:(o,i)=>{a.update(m=>{let c=[...m];return c.splice(o,0,F()),c}),e.insertItem(t,o,i)},swap:(o,i)=>{a.update(m=>{let c=[...m];return[c[o],c[i]]=[c[i],c[o]],c}),e.swapItems(t,o,i)},move:(o,i)=>{a.update(m=>{let c=[...m],[y]=c.splice(o,1);return c.splice(i,0,y),c}),e.moveItem(t,o,i)},replace:o=>{a.set(o.map(()=>F())),e.setField(t,o)},clear:()=>{a.set([]),e.setField(t,[])}}}import{computed as j,DestroyRef as tt,inject as et,signal as rt}from"@angular/core";function ot(){let t=g(),e=et(tt),s=rt(t.getHistoryMetadata()),r=t.subscribe(()=>{s.set(t.getHistoryMetadata())});return e.onDestroy(()=>r()),{canUndo:j(()=>s().canUndo),canRedo:j(()=>s().canRedo),historyIndex:j(()=>s().historyIndex),historySize:j(()=>s().historySize),undo:()=>t.undo(),redo:()=>t.redo()}}import{signal as st,computed as w,DestroyRef as nt,inject as it}from"@angular/core";function at(t,e){let s=Object.keys(t),r=Object.keys(e);return s.length!==r.length?!1:s.every(n=>t[n]===e[n])}function ct(t){let e=g(),s=e.getStepStatus(t),r=st(s),n=e.subscribe(()=>{let c=e.getStepStatus(t),y=r();(c.hasErrors!==y.hasErrors||c.isDirty!==y.isDirty||!at(c.errors,y.errors))&&r.set(c)});try{it(nt).onDestroy(()=>n())}catch{}let a=async()=>{let c=await e.validate({scope:t}),y=e.getStepErrors(t);return{valid:c,errors:y}},S=()=>e.getStepErrors(t),o=w(()=>!r().hasErrors),i=w(()=>r().isDirty),m=w(()=>r().errors);return{scopeName:t,status:r,errors:m,validate:a,getErrors:S,isValid:o,isDirty:i,unsubscribe:n}}import{signal as z,computed as R,DestroyRef as ut,inject as lt}from"@angular/core";function dt(t,e){let s=Object.keys(t),r=Object.keys(e);return s.length!==r.length?!1:s.every(n=>t[n]===e[n])}function mt(t){let e=g(),s=z(0),r=R(()=>t[s()]??""),n=()=>t[s()]??"",a=z(e.getStepStatus(n())),S=()=>{let l=n(),d=e.getStepStatus(l),u=a();(d.hasErrors!==u.hasErrors||d.isDirty!==u.isDirty||!dt(d.errors,u.errors))&&a.set(d)},o=e.subscribe(S);try{lt(ut).onDestroy(()=>o())}catch{}let i=async()=>{let l=n(),d=await e.validate({scope:l}),u=e.getStepErrors(l);return{valid:d,errors:u}},m=()=>e.getStepErrors(n()),c=async()=>{let l=n(),d=await e.validate({scope:l});if(d){let u=Math.min(s()+1,t.length-1);s.set(u),a.set(e.getStepStatus(t[u]??""))}else{let u=e.getStepErrors(l),p=Object.keys(u);p.length>0&&e.markFieldsTouched(p)}return d},y=()=>{let l=Math.max(s()-1,0);s.set(l),a.set(e.getStepStatus(t[l]??""))},x=l=>{let d=Math.max(0,Math.min(l-1,t.length-1));s.set(d),a.set(e.getStepStatus(t[d]??""))},I=R(()=>s()+1),V=R(()=>s()===0),b=R(()=>s()>=t.length-1),T=R(()=>!a().hasErrors),P=R(()=>a().isDirty),B=R(()=>a().errors);return{step:I,stepIndex:s,scope:r,next:c,prev:y,goTo:x,isFirst:V,isLast:b,status:a,errors:B,isValid:T,isDirty:P,validate:i,getErrors:m}}import{DestroyRef as pt,signal as yt,inject as gt}from"@angular/core";function ft(t){let e=g(),s=gt(pt),r=yt(h(e.getState().values,t),{equal:k}),n=e.watch(t,a=>{r.set(a)});return s.onDestroy(n),r.asReadonly()}export{N as injectBitArray,X as injectBitField,G as injectBitForm,ot as injectBitHistory,ct as injectBitScope,mt as injectBitSteps,ft as injectBitWatch,C as provideBitStore,g as useBitStore};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7;var N=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;N.__BIT_FORM__||(N.__BIT_FORM__={stores:{},listeners:new Set,dispatch(n,t){this.listeners.forEach(e=>e(n,t))},subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}});var m=N.__BIT_FORM__;function f(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(Array.isArray(n))return n.map(e=>f(e));let t={};for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=f(n[e]));return t}function x(n,t){return n===t?!0:n===null||typeof n!="object"||t===null||typeof t!="object"?!1:T(n,t)}function T(n,t){if(n===t)return!0;if(n===null||typeof n!="object"||t===null||typeof t!="object")return!1;if(n instanceof Date&&t instanceof Date)return n.getTime()===t.getTime();if(n instanceof RegExp&&t instanceof RegExp)return n.toString()===t.toString();let e=Object.keys(n),s=Object.keys(t);if(e.length!==s.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r)||!T(n[r],t[r]))return!1;return!0}function j(n,t,e="",s=new Set){if(x(n,t))return s;if(n===null||typeof n!="object"||t===null||typeof t!="object")return e&&s.add(e),s;if(Array.isArray(n)||Array.isArray(t))return!x(n,t)&&e&&s.add(e),s;let r=new Set([...Object.keys(n||{}),...Object.keys(t||{})]);for(let i of r){let o=e?`${e}.${i}`:i;j(_optionalChain([n, 'optionalAccess', _2 => _2[i]]),_optionalChain([t, 'optionalAccess', _3 => _3[i]]),o,s)}return s}var k=new Map;function u(n,t){if(!t)return n;let e=k.get(t)||t.split(".");k.has(t)||k.set(t,e);let s=n;for(let r of e){if(s==null)return;s=s[r]}return s}function y(n,t,e){if(!t)return e;let s=k.get(t)||t.split(".");k.has(t)||k.set(t,s);let r=Array.isArray(n)?[...n]:{...n},i=r;for(let o=0;o<s.length-1;o++){let a=s[o],l=s[o+1],c=/^\d+$/.test(l),d=i[a];d==null?i[a]=c?[]:{}:i[a]=Array.isArray(d)?[...d]:{...d},i=i[a]}return i[s[s.length-1]]=e,r}function Pt(n,t){let e={},s=`${t}.`;for(let r in n)r!==t&&!r.startsWith(s)&&(e[r]=n[r]);return e}var q=(n,t,e)=>{let s={},r=`${t}.`;return Object.keys(n).forEach(i=>{if(!i.startsWith(r)){s[i]=n[i];return}let a=i.substring(r.length).split("."),l=parseInt(a[0],10),c=a.slice(1).join(".");if(l!==e)if(l>e){let d=l-1,p=c?`${r}${d}.${c}`:`${r}${d}`;s[p]=n[i]}else s[i]=n[i]}),s},_=(n,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(n).forEach(o=>{if(!o.startsWith(i)){r[o]=n[o];return}let l=o.substring(i.length).split("."),c=parseInt(l[0],10),d=l.slice(1).join(".");if(c===e){let p=d?`${i}${s}.${d}`:`${i}${s}`;r[p]=n[o]}else if(c===s){let p=d?`${i}${e}.${d}`:`${i}${e}`;r[p]=n[o]}else r[o]=n[o]}),r},X=(n,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(n).forEach(o=>{if(!o.startsWith(i)){r[o]=n[o];return}let l=o.substring(i.length).split("."),c=parseInt(l[0],10),d=l.slice(1).join("."),p=c;c===e?p=s:e<s&&c>e&&c<=s?p=c-1:e>s&&c>=s&&c<e&&(p=c+1);let h=d?`${i}${p}.${d}`:`${i}${p}`;r[h]=n[o]}),r};function bt(n){if(typeof n!="object"||n===null||Array.isArray(n))return!1;let t=_nullishCoalesce(n.errors, () => (n));return typeof t!="object"||t===null||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string"||Array.isArray(e)&&e.every(s=>typeof s=="string"))}function Ct(n){return bt(n)?_nullishCoalesce(n.errors, () => (n)):{}}var vt={"#":/\d/,A:/[a-zA-Z]/,X:/[a-zA-Z0-9]/,H:/[0-9a-fA-F]/,U:/[A-Z]/,L:/[a-z]/,"*":/./},M= exports.j =(n,t)=>{if(n==null||n==="")return"";let e=String(n),s=e.startsWith("-"),r=t?t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"",i=new RegExp(`[^a-zA-Z0-9${r}]`,"g"),o=e.replace(i,"");return s&&o&&!o.startsWith("-")?`-${o}`:o},xt= exports.k =(n,t=2)=>{if(typeof n=="number")return n;if(!n)return 0;let e=String(n),s=e.includes("-"),r=e.replace(/\D/g,"");if(!r)return 0;let i=parseInt(r,10)/Math.pow(10,t);return s?-i:i},g= exports.l =(n,t)=>{let e=s=>s.split("").filter(r=>vt[r]).length;return{format:s=>{let r=M(s,_optionalChain([t, 'optionalAccess', _4 => _4.allowChars]));if(!r&&!_optionalChain([t, 'optionalAccess', _5 => _5.guide]))return"";let o=[...Array.isArray(n)?n:[n]].sort((h,v)=>e(h)-e(v)),a=o[o.length-1];for(let h of o)if(r.length<=e(h)){a=h;break}let l="",c=0,d=_optionalChain([t, 'optionalAccess', _6 => _6.guide])||!1,p=_optionalChain([t, 'optionalAccess', _7 => _7.placeholderChar])||"_";for(let h=0;h<a.length;h++){let v=a[h],P=vt[v];if(c<r.length){let S=r[c];if(P)if(v==="U"&&(S=S.toUpperCase()),v==="L"&&(S=S.toLowerCase()),P.test(S))l+=S,c++;else if(d)l+=p;else break;else l+=v,S===v&&c++}else if(d)l+=P?p:v;else break}return l},parse:s=>{if(_optionalChain([t, 'optionalAccess', _8 => _8.customParse]))return t.customParse(s);let i=g(n,t).format(s);if(_optionalChain([t, 'optionalAccess', _9 => _9.saveRaw])){if(_optionalChain([t, 'optionalAccess', _10 => _10.guide])){let a=(t.placeholderChar||"_").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(a,"g");return i.replace(l,"")}return i}return M(i,_optionalChain([t, 'optionalAccess', _11 => _11.allowChars]))}}},b= exports.m =({prefix:n="",suffix:t="",thousand:e,decimal:s,precision:r=2,allowNegative:i=!0,saveRaw:o=!1})=>{let a=l=>{if(l==null||l==="")return"";let c="";if(typeof l=="number"?c=Math.abs(l).toFixed(r).replace(/\D/g,""):c=String(l).replace(/\D/g,""),!c&&String(l).includes("-")&&i)return"-";if(!c)return"";c=c.padStart(r+1,"0");let d=c.slice(0,-r).replace(/^0+(?=\d)/,"")||"0",p=c.slice(-r),h=d.replace(/\B(?=(\d{3})+(?!\d))/g,e);return`${(typeof l=="number"?l<0:String(l).includes("-"))&&i?"-":""}${n}${h}${s}${p}${t}`};return{format:a,parse:l=>{let c=xt(l,r),d=i?c:Math.abs(c);return o?a(d):d}}},z= exports.n =n=>{let t=e=>/^3[47]/.test(e)?"#### ###### #####":/^3(?:0[0-5]|[68])/.test(e)?"#### ###### ####":"#### #### #### ####";return{format:e=>{let s=M(e,_optionalChain([n, 'optionalAccess', _12 => _12.allowChars])),r=t(s);return g(r,n).format(e)},parse:e=>{let s=M(e,_optionalChain([n, 'optionalAccess', _13 => _13.allowChars])),r=t(s);return g(r,n).parse(e)}}},C= exports.o =n=>{let e=(_optionalChain([n, 'optionalAccess', _14 => _14.format])||"DD/MM/YYYY")==="YYYY-MM-DD",s=g(e?"####-##-##":"##/##/####",n);return{format:r=>{let i=M(r);if(!i)return"";let o="",a="",l="";if(e?(l=i.substring(0,4),a=i.substring(4,6),o=i.substring(6,8)):(o=i.substring(0,2),a=i.substring(2,4),l=i.substring(4,8)),o.length===2){let d=parseInt(o,10);d>31&&(o="31"),d===0&&(o="01")}if(a.length===2){let d=parseInt(a,10);d>12&&(a="12"),d===0&&(a="01")}let c=e?`${l}${a}${o}`:`${o}${a}${l}`;return s.format(c)},parse:r=>s.parse(r)}};var W=b({prefix:"R$ ",thousand:".",decimal:",",precision:2}),Y= exports.q =b({prefix:"$",thousand:",",decimal:".",precision:2}),J= exports.r =b({suffix:" \u20AC",thousand:".",decimal:",",precision:2}),K= exports.s =b({prefix:"\xA3",thousand:",",decimal:".",precision:2}),G= exports.t =b({prefix:"\xA5",thousand:",",decimal:".",precision:0}),Z= exports.u =b({suffix:"%",thousand:".",decimal:",",precision:1}),Q= exports.v =b({thousand:".",decimal:",",precision:2}),tt= exports.w =b({thousand:".",decimal:",",precision:0}),et= exports.x =g("###.###.###-##"),st= exports.y =g("##.###.###/####-##"),rt= exports.z =g(["(##) ####-####","(##) #####-####"]),it= exports.A =g("(##) ####-####"),nt= exports.B =g("#####-###"),ot= exports.C =C({format:"DD/MM/YYYY",guide:!0,customParse:n=>{let t=n.replace(/_/g,""),e=t.split("/");return e.length===3&&e[2].length===4?`${e[2]}-${e[1]}-${e[0]}`:t.replace(/\D/g,"")}}),at= exports.D =g("##:##"),lt= exports.E =g("###########"),ct= exports.F =g("##.###.###-X"),Vt= exports.G =g("(###) ###-####"),Dt= exports.H =g("#####-####"),Rt= exports.I =g("##/##/####"),wt= exports.J =g("###-##-####"),dt= exports.K =z(),ut= exports.L =g("####"),It= exports.M =C({format:"YYYY-MM-DD",saveRaw:!0,guide:!0}),gt= exports.N =g("HH:HH:HH:HH:HH:HH"),pt= exports.O =g("#HHHHHH"),ft= exports.P =g("###.###.###.###"),ht= exports.Q =g("HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH"),Ht= exports.R =g("UU## XXXX XXXX XXXX XXXX XXXX XXXX XXXX XX",{allowChars:" "});var mt={brl:W,usd:Y,eur:J,gbp:K,jpy:G,cpf:et,cnpj:st,rg:ct,cep:nt,cnh:lt,phone:rt,landline:it,date:ot,time:at,ip:ft,ipv6:ht,mac:gt,color:pt,cc:dt,cvv:ut,percent:Z,decimal:Q,int:tt};function Ft(n){let t={},e={},s={};if(!n)return{computed:t,transform:e,scopes:s};for(let[r,i]of Object.entries(n))_optionalChain([i, 'optionalAccess', _15 => _15.computed])&&(t[r]=i.computed),_optionalChain([i, 'optionalAccess', _16 => _16.transform])&&(e[r]=i.transform),_optionalChain([i, 'optionalAccess', _17 => _17.scope])&&(s[i.scope]||(s[i.scope]=[]),s[i.scope].push(r));return{computed:Object.keys(t).length?t:void 0,transform:Object.keys(e).length?e:void 0,scopes:Object.keys(s).length?s:void 0}}function Tt(n={}){let t=n.initialValues||{},e=n.validation,s=n.history,{computed:r,transform:i,scopes:o}=Ft(n.fields);return{name:n.name,initialValues:f(t),resolver:_optionalChain([e, 'optionalAccess', _18 => _18.resolver]),validationDelay:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _19 => _19.delay]), () => (300)),enableHistory:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _20 => _20.enabled]), () => (!1)),historyLimit:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _21 => _21.limit]), () => (15)),computed:r,transform:i,scopes:o,masks:mt,fields:n.fields,devTools:n.devTools}}var V= (_class =class{constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this); }__init() {this.fieldConfigs=new Map}__init2() {this.dependencies=new Map}__init3() {this.hiddenFields=new Set}register(t,e,s){this.fieldConfigs.set(t,e);let r=_optionalChain([e, 'access', _22 => _22.conditional, 'optionalAccess', _23 => _23.dependsOn]);r&&r.forEach(i=>{this.dependencies.has(i)||this.dependencies.set(i,new Set),this.dependencies.get(i).add(t)}),this.evaluateFieldCondition(t,s)}isHidden(t){return this.hiddenFields.has(t)}isRequired(t,e){let s=this.fieldConfigs.get(t);return!s||this.isHidden(t)?!1:!!_optionalChain([s, 'access', _24 => _24.conditional, 'optionalAccess', _25 => _25.requiredIf, 'optionalCall', _26 => _26(e)])}getRequiredErrors(t){let e={};return this.fieldConfigs.forEach((s,r)=>{if(this.isRequired(r,t)){let i=u(t,r);this.isEmpty(i)&&(e[r]=_nullishCoalesce(_optionalChain([s, 'access', _27 => _27.conditional, 'optionalAccess', _28 => _28.requiredMessage]), () => ("required field")))}}),e}evaluateAll(t){this.fieldConfigs.forEach((e,s)=>{this.evaluateFieldCondition(s,t)})}updateDependencies(t,e){let s=[],r=this.dependencies.get(t);return r&&r.forEach(i=>{let o=this.isHidden(i);this.evaluateFieldCondition(i,e);let a=this.isHidden(i);o!==a&&s.push(i)}),s}unregister(t){this.fieldConfigs.delete(t),this.hiddenFields.delete(t),this.dependencies.delete(t),this.dependencies.forEach(e=>{e.delete(t)})}unregisterPrefix(t){let e=[];this.fieldConfigs.forEach((s,r)=>{r.startsWith(t)&&e.push(r)}),e.forEach(s=>this.unregister(s))}evaluateFieldCondition(t,e){let r=_optionalChain([this, 'access', _29 => _29.fieldConfigs, 'access', _30 => _30.get, 'call', _31 => _31(t), 'optionalAccess', _32 => _32.conditional, 'optionalAccess', _33 => _33.showIf]);r&&(r(e)?this.hiddenFields.delete(t):this.hiddenFields.add(t))}isEmpty(t){return t==null||typeof t=="string"&&t.trim()===""||Array.isArray(t)&&t.length===0}}, _class);var D= (_class2 =class{constructor(t,e=15){;_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);this.enableHistory=t;this.maxHistory=e}__init4() {this.history=[]}__init5() {this.historyIndex=-1}saveSnapshot(t){if(!this.enableHistory)return;let e=this.history[this.historyIndex];e&&T(e,t)||(this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push(f(t)),this.history.length>this.maxHistory?this.history.shift():this.historyIndex++)}get canUndo(){return this.enableHistory?this.historyIndex>0:!1}get canRedo(){return this.enableHistory?this.historyIndex<this.history.length-1:!1}undo(){return this.canUndo?(this.historyIndex--,f(this.history[this.historyIndex])):null}redo(){return this.canRedo?(this.historyIndex++,f(this.history[this.historyIndex])):null}reset(t){this.history=[],this.historyIndex=-1,this.saveSnapshot(t)}getMetadata(){return{enabled:this.enableHistory,canUndo:this.canUndo,canRedo:this.canRedo,historyIndex:this.historyIndex,historySize:this.history.length}}}, _class2);var R=class{constructor(t){this.store=t}pushItem(t,e){let s=u(this.store.getState().values,t)||[];this.store.setField(t,[...s,e]),this.store.internalSaveSnapshot()}prependItem(t,e){let s=u(this.store.getState().values,t)||[];this.store.setField(t,[e,...s]),this.store.internalSaveSnapshot()}insertItem(t,e,s){let r=[...u(this.store.getState().values,t)||[]];r.splice(e,0,s),this.store.setField(t,r),this.store.internalSaveSnapshot()}removeItem(t,e){let s=this.store.getState(),r=u(s.values,t);if(!Array.isArray(r))return;this.store.unregisterPrefix&&this.store.unregisterPrefix(`${t}.${e}.`);let i=r.filter((l,c)=>c!==e),o=y(s.values,t,i),a=this.store.dirtyMg.updateForPath(t,o,this.store.getConfig().initialValues);this.store.internalUpdateState({values:o,errors:q(s.errors,t,e),touched:q(s.touched,t,e),isDirty:a}),this.store.internalSaveSnapshot(),this.revalidate(t)}swapItems(t,e,s){let r=this.store.getState(),i=[...u(r.values,t)||[]];[i[e],i[s]]=[i[s],i[e]];let o=y(r.values,t,i),a=this.store.dirtyMg.updateForPath(t,o,this.store.getConfig().initialValues);this.store.internalUpdateState({values:o,errors:_(r.errors,t,e,s),touched:_(r.touched,t,e,s),isDirty:a}),this.store.internalSaveSnapshot(),this.revalidate(t)}moveItem(t,e,s){let r=this.store.getState(),i=[...u(r.values,t)||[]],[o]=i.splice(e,1);i.splice(s,0,o);let a=y(r.values,t,i),l=this.store.dirtyMg.updateForPath(t,a,this.store.getConfig().initialValues);this.store.internalUpdateState({values:a,errors:X(r.errors,t,e,s),touched:X(r.touched,t,e,s),isDirty:l}),this.store.internalSaveSnapshot(),this.revalidate(t)}revalidate(t){let e=this.store;typeof e.triggerValidation=="function"?e.triggerValidation([t]):typeof this.store.validate=="function"&&this.store.validate()}};var w=class{constructor(t){this.config=t}apply(t){if(!this.config.computed)return t;let e=t,s=Object.entries(this.config.computed);for(let r=0;r<2;r++){let i=!1;for(let[o,a]of s){let l=a(e),c=u(e,o);T(c,l)||(e=y(e,o,l),i=!0)}if(!i)break}return e}};var I= (_class3 =class{constructor(t){;_class3.prototype.__init6.call(this);_class3.prototype.__init7.call(this);_class3.prototype.__init8.call(this);_class3.prototype.__init9.call(this);this.store=t}__init6() {this.currentValidationId=0}__init7() {this.asyncTimers={}}__init8() {this.asyncRequests={}}__init9() {this.asyncErrors={}}handleAsync(t,e){let s=this.store.depsMg.fieldConfigs.get(t)||_optionalChain([this, 'access', _34 => _34.store, 'access', _35 => _35.config, 'access', _36 => _36.fields, 'optionalAccess', _37 => _37[t]]),r=_optionalChain([s, 'optionalAccess', _38 => _38.validation, 'optionalAccess', _39 => _39.asyncValidate]);if(!r)return;this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]);let i=_nullishCoalesce(_optionalChain([s, 'access', _40 => _40.validation, 'optionalAccess', _41 => _41.asyncValidateDelay]), () => (500));this.asyncTimers[t]=setTimeout(async()=>{let o=(this.asyncRequests[t]||0)+1;this.asyncRequests[t]=o,this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[t]:!0}});try{let a=await r(e,this.store.getState().values);if(this.asyncRequests[t]!==o)return;if(a)this.asyncErrors[t]=a,this.store.setError(t,a);else{delete this.asyncErrors[t];let l=this.store;if(l.validate)await l.validate({scopeFields:[t]});else{let c={...this.store.getState().errors};delete c[t],this.store.internalUpdateState({errors:c,isValid:Object.keys(c).length===0})}}}finally{this.asyncRequests[t]===o&&this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[t]:!1}})}},i)}trigger(t){this.validationTimeout&&clearTimeout(this.validationTimeout);let e=_nullishCoalesce(this.store.config.validationDelay, () => (300));e>0?this.validationTimeout=setTimeout(()=>{this.validate({scopeFields:t})},e):this.validate({scopeFields:t})}async validate(t){let e=++this.currentValidationId,s=this.store.getState(),r=_optionalChain([t, 'optionalAccess', _42 => _42.scopeFields]);_optionalChain([t, 'optionalAccess', _43 => _43.scope])&&_optionalChain([this, 'access', _44 => _44.store, 'access', _45 => _45.config, 'access', _46 => _46.scopes, 'optionalAccess', _47 => _47[t.scope]])&&(r=this.store.config.scopes[t.scope]);let i=this.store.config.resolver?await this.store.config.resolver(s.values,{scopeFields:r}):{},o=this.store.depsMg.getRequiredErrors(s.values);if(i={...i,...o},this.store.depsMg.hiddenFields.forEach(l=>{delete i[l],delete this.asyncErrors[l]}),e!==this.currentValidationId)return s.isValid;if(r){let l={...s.errors};r.forEach(d=>{i[d]?l[d]=i[d]:this.asyncErrors[d]?l[d]=this.asyncErrors[d]:delete l[d]});let c=Object.keys(l).length===0;return this.store.internalUpdateState({errors:l,isValid:c}),r.every(d=>!i[d]&&!this.asyncErrors[d])}i={...this.asyncErrors,...i};let a=Object.keys(i).length===0;return this.store.internalUpdateState({errors:i,isValid:a}),a}clear(t){this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]),delete this.asyncErrors[t]}cancelAll(){this.validationTimeout&&clearTimeout(this.validationTimeout),Object.values(this.asyncTimers).forEach(t=>clearTimeout(t))}}, _class3);var H=class{constructor(t){this.store=t}updateField(t,e){let s=this.store.getState(),r=y(s.values,t,e),i={...s.errors};delete i[t],this.store.validatorMg.clear(t);let o=this.store.depsMg.updateDependencies(t,r);o.forEach(l=>{this.store.depsMg.isHidden(l)&&(delete i[l],this.store.validatorMg.clear(l))});let a=this.store.dirtyMg.updateForPath(t,r,this.store.config.initialValues);return this.store.internalUpdateState({values:r,errors:i,isValid:Object.keys(i).length===0,isDirty:a}),this.store.config.resolver&&this.store.validatorMg.trigger([t]),this.store.validatorMg.handleAsync(t,e),{visibilitiesChanged:o.length>0}}updateAll(t){let e=f(t);this.store.config.initialValues=f(e),this.store.validatorMg.cancelAll(),this.store.depsMg.evaluateAll(e),this.store.dirtyMg.clear(),this.store.internalUpdateState({values:e,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.internalSaveSnapshot(),this.store.validatorMg.validate()}async submit(t){if(this.store.getState().isSubmitting)return;if(this.store.validatorMg.cancelAll(),this.store.internalUpdateState({isSubmitting:!0}),await this.store.validatorMg.validate())try{let r=f(this.store.getState().values);if(this.store.depsMg.hiddenFields.forEach(o=>{r=y(r,o,void 0)}),this.store.config.transform)for(let o in this.store.config.transform){let a=this.store.config.transform[o];if(a){let l=u(r,o);r=y(r,o,a(l,this.store.getState().values))}}let i=this.store.dirtyMg.buildDirtyValues(r);await t(r,i)}catch(r){console.error(r)}else{let r=this.store.getState().errors,i={...this.store.getState().touched};Object.keys(r).forEach(o=>{i[o]=!0}),this.store.internalUpdateState({touched:i})}this.store.internalUpdateState({isSubmitting:!1})}reset(){this.store.validatorMg.cancelAll();let t=f(this.store.config.initialValues);this.store.depsMg.evaluateAll(t),this.store.dirtyMg.clear(),this.store.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.historyMg.reset(t)}};function St(){return`
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7;var N=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;N.__BIT_FORM__||(N.__BIT_FORM__={stores:{},listeners:new Set,dispatch(o,t){this.listeners.forEach(e=>e(o,t))},subscribe(o){return this.listeners.add(o),()=>{this.listeners.delete(o)}}});var m=N.__BIT_FORM__;function f(o){if(o===null||typeof o!="object")return o;if(o instanceof Date)return new Date(o.getTime());if(o instanceof RegExp)return new RegExp(o.source,o.flags);if(Array.isArray(o))return o.map(e=>f(e));let t={};for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&(t[e]=f(o[e]));return t}function x(o,t){return o===t?!0:o===null||typeof o!="object"||t===null||typeof t!="object"?!1:T(o,t)}function T(o,t){if(o===t)return!0;if(o===null||typeof o!="object"||t===null||typeof t!="object")return!1;if(o instanceof Date&&t instanceof Date)return o.getTime()===t.getTime();if(o instanceof RegExp&&t instanceof RegExp)return o.toString()===t.toString();let e=Object.keys(o),s=Object.keys(t);if(e.length!==s.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r)||!T(o[r],t[r]))return!1;return!0}function j(o,t,e="",s=new Set){if(x(o,t))return s;if(o===null||typeof o!="object"||t===null||typeof t!="object")return e&&s.add(e),s;if(Array.isArray(o)||Array.isArray(t))return!x(o,t)&&e&&s.add(e),s;let r=new Set([...Object.keys(o||{}),...Object.keys(t||{})]);for(let i of r){let n=e?`${e}.${i}`:i;j(_optionalChain([o, 'optionalAccess', _2 => _2[i]]),_optionalChain([t, 'optionalAccess', _3 => _3[i]]),n,s)}return s}var k=new Map;function u(o,t){if(!t)return o;let e=k.get(t)||t.split(".");k.has(t)||k.set(t,e);let s=o;for(let r of e){if(s==null)return;s=s[r]}return s}function y(o,t,e){if(!t)return e;let s=k.get(t)||t.split(".");k.has(t)||k.set(t,s);let r=Array.isArray(o)?[...o]:{...o},i=r;for(let n=0;n<s.length-1;n++){let a=s[n],l=s[n+1],c=/^\d+$/.test(l),d=i[a];d==null?i[a]=c?[]:{}:i[a]=Array.isArray(d)?[...d]:{...d},i=i[a]}return i[s[s.length-1]]=e,r}function Pt(o,t){let e={},s=`${t}.`;for(let r in o)r!==t&&!r.startsWith(s)&&(e[r]=o[r]);return e}var q=(o,t,e)=>{let s={},r=`${t}.`;return Object.keys(o).forEach(i=>{if(!i.startsWith(r)){s[i]=o[i];return}let a=i.substring(r.length).split("."),l=parseInt(a[0],10),c=a.slice(1).join(".");if(l!==e)if(l>e){let d=l-1,p=c?`${r}${d}.${c}`:`${r}${d}`;s[p]=o[i]}else s[i]=o[i]}),s},_=(o,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(o).forEach(n=>{if(!n.startsWith(i)){r[n]=o[n];return}let l=n.substring(i.length).split("."),c=parseInt(l[0],10),d=l.slice(1).join(".");if(c===e){let p=d?`${i}${s}.${d}`:`${i}${s}`;r[p]=o[n]}else if(c===s){let p=d?`${i}${e}.${d}`:`${i}${e}`;r[p]=o[n]}else r[n]=o[n]}),r},X=(o,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(o).forEach(n=>{if(!n.startsWith(i)){r[n]=o[n];return}let l=n.substring(i.length).split("."),c=parseInt(l[0],10),d=l.slice(1).join("."),p=c;c===e?p=s:e<s&&c>e&&c<=s?p=c-1:e>s&&c>=s&&c<e&&(p=c+1);let h=d?`${i}${p}.${d}`:`${i}${p}`;r[h]=o[n]}),r};function bt(o){if(typeof o!="object"||o===null||Array.isArray(o))return!1;let t=_nullishCoalesce(o.errors, () => (o));return typeof t!="object"||t===null||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string"||Array.isArray(e)&&e.every(s=>typeof s=="string"))}function Ct(o){return bt(o)?_nullishCoalesce(o.errors, () => (o)):{}}var vt={"#":/\d/,A:/[a-zA-Z]/,X:/[a-zA-Z0-9]/,H:/[0-9a-fA-F]/,U:/[A-Z]/,L:/[a-z]/,"*":/./},M= exports.j =(o,t)=>{if(o==null||o==="")return"";let e=String(o),s=e.startsWith("-"),r=t?t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"",i=new RegExp(`[^a-zA-Z0-9${r}]`,"g"),n=e.replace(i,"");return s&&n&&!n.startsWith("-")?`-${n}`:n},xt= exports.k =(o,t=2)=>{if(typeof o=="number")return o;if(!o)return 0;let e=String(o),s=e.includes("-"),r=e.replace(/\D/g,"");if(!r)return 0;let i=parseInt(r,10)/Math.pow(10,t);return s?-i:i},g= exports.l =(o,t)=>{let e=s=>s.split("").filter(r=>vt[r]).length;return{format:s=>{let r=M(s,_optionalChain([t, 'optionalAccess', _4 => _4.allowChars]));if(!r&&!_optionalChain([t, 'optionalAccess', _5 => _5.guide]))return"";let n=[...Array.isArray(o)?o:[o]].sort((h,v)=>e(h)-e(v)),a=n[n.length-1];for(let h of n)if(r.length<=e(h)){a=h;break}let l="",c=0,d=_optionalChain([t, 'optionalAccess', _6 => _6.guide])||!1,p=_optionalChain([t, 'optionalAccess', _7 => _7.placeholderChar])||"_";for(let h=0;h<a.length;h++){let v=a[h],E=vt[v];if(c<r.length){let S=r[c];if(E)if(v==="U"&&(S=S.toUpperCase()),v==="L"&&(S=S.toLowerCase()),E.test(S))l+=S,c++;else if(d)l+=p;else break;else l+=v,S===v&&c++}else if(d)l+=E?p:v;else break}return l},parse:s=>{if(_optionalChain([t, 'optionalAccess', _8 => _8.customParse]))return t.customParse(s);let i=g(o,t).format(s);if(_optionalChain([t, 'optionalAccess', _9 => _9.saveRaw])){if(_optionalChain([t, 'optionalAccess', _10 => _10.guide])){let a=(t.placeholderChar||"_").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(a,"g");return i.replace(l,"")}return i}return M(i,_optionalChain([t, 'optionalAccess', _11 => _11.allowChars]))}}},b= exports.m =({prefix:o="",suffix:t="",thousand:e,decimal:s,precision:r=2,allowNegative:i=!0,saveRaw:n=!1})=>{let a=l=>{if(l==null||l==="")return"";let c="";if(typeof l=="number"?c=Math.abs(l).toFixed(r).replace(/\D/g,""):c=String(l).replace(/\D/g,""),!c&&String(l).includes("-")&&i)return"-";if(!c)return"";c=c.padStart(r+1,"0");let d=c.slice(0,-r).replace(/^0+(?=\d)/,"")||"0",p=c.slice(-r),h=d.replace(/\B(?=(\d{3})+(?!\d))/g,e);return`${(typeof l=="number"?l<0:String(l).includes("-"))&&i?"-":""}${o}${h}${s}${p}${t}`};return{format:a,parse:l=>{let c=xt(l,r),d=i?c:Math.abs(c);return n?a(d):d}}},z= exports.n =o=>{let t=e=>/^3[47]/.test(e)?"#### ###### #####":/^3(?:0[0-5]|[68])/.test(e)?"#### ###### ####":"#### #### #### ####";return{format:e=>{let s=M(e,_optionalChain([o, 'optionalAccess', _12 => _12.allowChars])),r=t(s);return g(r,o).format(e)},parse:e=>{let s=M(e,_optionalChain([o, 'optionalAccess', _13 => _13.allowChars])),r=t(s);return g(r,o).parse(e)}}},P= exports.o =o=>{let e=(_optionalChain([o, 'optionalAccess', _14 => _14.format])||"DD/MM/YYYY")==="YYYY-MM-DD",s=g(e?"####-##-##":"##/##/####",o);return{format:r=>{let i=M(r);if(!i)return"";let n="",a="",l="";if(e?(l=i.substring(0,4),a=i.substring(4,6),n=i.substring(6,8)):(n=i.substring(0,2),a=i.substring(2,4),l=i.substring(4,8)),n.length===2){let d=parseInt(n,10);d>31&&(n="31"),d===0&&(n="01")}if(a.length===2){let d=parseInt(a,10);d>12&&(a="12"),d===0&&(a="01")}let c=e?`${l}${a}${n}`:`${n}${a}${l}`;return s.format(c)},parse:r=>s.parse(r)}};var W=b({prefix:"R$ ",thousand:".",decimal:",",precision:2}),Y= exports.q =b({prefix:"$",thousand:",",decimal:".",precision:2}),J= exports.r =b({suffix:" \u20AC",thousand:".",decimal:",",precision:2}),K= exports.s =b({prefix:"\xA3",thousand:",",decimal:".",precision:2}),G= exports.t =b({prefix:"\xA5",thousand:",",decimal:".",precision:0}),Z= exports.u =b({suffix:"%",thousand:".",decimal:",",precision:1}),Q= exports.v =b({thousand:".",decimal:",",precision:2}),tt= exports.w =b({thousand:".",decimal:",",precision:0}),et= exports.x =g("###.###.###-##"),st= exports.y =g("##.###.###/####-##"),rt= exports.z =g(["(##) ####-####","(##) #####-####"]),it= exports.A =g("(##) ####-####"),ot= exports.B =g("#####-###"),nt= exports.C =P({format:"DD/MM/YYYY",guide:!0,customParse:o=>{let t=o.replace(/_/g,""),e=t.split("/");return e.length===3&&e[2].length===4?`${e[2]}-${e[1]}-${e[0]}`:t.replace(/\D/g,"")}}),at= exports.D =g("##:##"),lt= exports.E =g("###########"),ct= exports.F =g("##.###.###-X"),Vt= exports.G =g("(###) ###-####"),Dt= exports.H =g("#####-####"),Rt= exports.I =g("##/##/####"),wt= exports.J =g("###-##-####"),dt= exports.K =z(),ut= exports.L =g("####"),It= exports.M =P({format:"YYYY-MM-DD",saveRaw:!0,guide:!0}),gt= exports.N =g("HH:HH:HH:HH:HH:HH"),pt= exports.O =g("#HHHHHH"),ft= exports.P =g("###.###.###.###"),ht= exports.Q =g("HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH"),Ht= exports.R =g("UU## XXXX XXXX XXXX XXXX XXXX XXXX XXXX XX",{allowChars:" "});var mt={brl:W,usd:Y,eur:J,gbp:K,jpy:G,cpf:et,cnpj:st,rg:ct,cep:ot,cnh:lt,phone:rt,landline:it,date:nt,time:at,ip:ft,ipv6:ht,mac:gt,color:pt,cc:dt,cvv:ut,percent:Z,decimal:Q,int:tt};function Ft(o){let t={},e={},s={};if(!o)return{computed:t,transform:e,scopes:s};for(let[r,i]of Object.entries(o))_optionalChain([i, 'optionalAccess', _15 => _15.computed])&&(t[r]=i.computed),_optionalChain([i, 'optionalAccess', _16 => _16.transform])&&(e[r]=i.transform),_optionalChain([i, 'optionalAccess', _17 => _17.scope])&&(s[i.scope]||(s[i.scope]=[]),s[i.scope].push(r));return{computed:Object.keys(t).length?t:void 0,transform:Object.keys(e).length?e:void 0,scopes:Object.keys(s).length?s:void 0}}function Tt(o={}){let t=o.initialValues||{},e=o.validation,s=o.history,{computed:r,transform:i,scopes:n}=Ft(o.fields);return{name:o.name,initialValues:f(t),resolver:_optionalChain([e, 'optionalAccess', _18 => _18.resolver]),validationDelay:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _19 => _19.delay]), () => (300)),enableHistory:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _20 => _20.enabled]), () => (!1)),historyLimit:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _21 => _21.limit]), () => (15)),computed:r,transform:i,scopes:n,masks:mt,fields:o.fields,devTools:o.devTools}}var C= (_class =class{constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this); }__init() {this.fieldConfigs=new Map}__init2() {this.dependencies=new Map}__init3() {this.hiddenFields=new Set}register(t,e,s){this.fieldConfigs.set(t,e);let r=_optionalChain([e, 'access', _22 => _22.conditional, 'optionalAccess', _23 => _23.dependsOn]);r&&r.forEach(i=>{this.dependencies.has(i)||this.dependencies.set(i,new Set),this.dependencies.get(i).add(t)}),this.evaluateFieldCondition(t,s)}isHidden(t){return this.hiddenFields.has(t)}isRequired(t,e){let s=this.fieldConfigs.get(t);return!s||this.isHidden(t)?!1:!!_optionalChain([s, 'access', _24 => _24.conditional, 'optionalAccess', _25 => _25.requiredIf, 'optionalCall', _26 => _26(e)])}getRequiredErrors(t){let e={};return this.fieldConfigs.forEach((s,r)=>{if(this.isRequired(r,t)){let i=u(t,r);this.isEmpty(i)&&(e[r]=_nullishCoalesce(_optionalChain([s, 'access', _27 => _27.conditional, 'optionalAccess', _28 => _28.requiredMessage]), () => ("required field")))}}),e}evaluateAll(t){this.fieldConfigs.forEach((e,s)=>{this.evaluateFieldCondition(s,t)})}updateDependencies(t,e){let s=[],r=this.dependencies.get(t);return r&&r.forEach(i=>{let n=this.isHidden(i);this.evaluateFieldCondition(i,e);let a=this.isHidden(i);n!==a&&s.push(i)}),s}unregister(t){this.fieldConfigs.delete(t),this.hiddenFields.delete(t),this.dependencies.delete(t),this.dependencies.forEach(e=>{e.delete(t)})}unregisterPrefix(t){let e=[];this.fieldConfigs.forEach((s,r)=>{r.startsWith(t)&&e.push(r)}),e.forEach(s=>this.unregister(s))}evaluateFieldCondition(t,e){let r=_optionalChain([this, 'access', _29 => _29.fieldConfigs, 'access', _30 => _30.get, 'call', _31 => _31(t), 'optionalAccess', _32 => _32.conditional, 'optionalAccess', _33 => _33.showIf]);r&&(r(e)?this.hiddenFields.delete(t):this.hiddenFields.add(t))}isEmpty(t){return t==null||typeof t=="string"&&t.trim()===""||Array.isArray(t)&&t.length===0}}, _class);var V= (_class2 =class{constructor(t,e=15){;_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);this.enableHistory=t;this.maxHistory=e}__init4() {this.history=[]}__init5() {this.historyIndex=-1}saveSnapshot(t){if(!this.enableHistory)return;let e=this.history[this.historyIndex];e&&T(e,t)||(this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push(f(t)),this.history.length>this.maxHistory?this.history.shift():this.historyIndex++)}get canUndo(){return this.enableHistory?this.historyIndex>0:!1}get canRedo(){return this.enableHistory?this.historyIndex<this.history.length-1:!1}undo(){return this.canUndo?(this.historyIndex--,f(this.history[this.historyIndex])):null}redo(){return this.canRedo?(this.historyIndex++,f(this.history[this.historyIndex])):null}reset(t){this.history=[],this.historyIndex=-1,this.saveSnapshot(t)}getMetadata(){return{enabled:this.enableHistory,canUndo:this.canUndo,canRedo:this.canRedo,historyIndex:this.historyIndex,historySize:this.history.length}}}, _class2);var D=class{constructor(t){this.store=t}pushItem(t,e){let s=u(this.store.getState().values,t)||[];this.store.setField(t,[...s,e]),this.store.internalSaveSnapshot()}prependItem(t,e){let s=u(this.store.getState().values,t)||[];this.store.setField(t,[e,...s]),this.store.internalSaveSnapshot()}insertItem(t,e,s){let r=[...u(this.store.getState().values,t)||[]];r.splice(e,0,s),this.store.setField(t,r),this.store.internalSaveSnapshot()}removeItem(t,e){let s=this.store.getState(),r=u(s.values,t);if(!Array.isArray(r))return;this.store.unregisterPrefix&&this.store.unregisterPrefix(`${t}.${e}.`);let i=r.filter((l,c)=>c!==e),n=y(s.values,t,i),a=this.store.dirtyMg.updateForPath(t,n,this.store.getConfig().initialValues);this.store.internalUpdateState({values:n,errors:q(s.errors,t,e),touched:q(s.touched,t,e),isDirty:a}),this.store.internalSaveSnapshot(),this.revalidate(t)}swapItems(t,e,s){let r=this.store.getState(),i=[...u(r.values,t)||[]];[i[e],i[s]]=[i[s],i[e]];let n=y(r.values,t,i),a=this.store.dirtyMg.updateForPath(t,n,this.store.getConfig().initialValues);this.store.internalUpdateState({values:n,errors:_(r.errors,t,e,s),touched:_(r.touched,t,e,s),isDirty:a}),this.store.internalSaveSnapshot(),this.revalidate(t)}moveItem(t,e,s){let r=this.store.getState(),i=[...u(r.values,t)||[]],[n]=i.splice(e,1);i.splice(s,0,n);let a=y(r.values,t,i),l=this.store.dirtyMg.updateForPath(t,a,this.store.getConfig().initialValues);this.store.internalUpdateState({values:a,errors:X(r.errors,t,e,s),touched:X(r.touched,t,e,s),isDirty:l}),this.store.internalSaveSnapshot(),this.revalidate(t)}revalidate(t){let e=this.store;typeof e.triggerValidation=="function"?e.triggerValidation([t]):typeof this.store.validate=="function"&&this.store.validate()}};var R=class{constructor(t){this.config=t}apply(t){if(!this.config.computed)return t;let e=t,s=Object.entries(this.config.computed);for(let r=0;r<2;r++){let i=!1;for(let[n,a]of s){let l=a(e),c=u(e,n);T(c,l)||(e=y(e,n,l),i=!0)}if(!i)break}return e}};var w= (_class3 =class{constructor(t){;_class3.prototype.__init6.call(this);_class3.prototype.__init7.call(this);_class3.prototype.__init8.call(this);_class3.prototype.__init9.call(this);this.store=t}__init6() {this.currentValidationId=0}__init7() {this.asyncTimers={}}__init8() {this.asyncRequests={}}__init9() {this.asyncErrors={}}handleAsync(t,e){let s=this.store.depsMg.fieldConfigs.get(t)||_optionalChain([this, 'access', _34 => _34.store, 'access', _35 => _35.config, 'access', _36 => _36.fields, 'optionalAccess', _37 => _37[t]]),r=_optionalChain([s, 'optionalAccess', _38 => _38.validation, 'optionalAccess', _39 => _39.asyncValidate]);if(!r)return;this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]);let i=_nullishCoalesce(_optionalChain([s, 'access', _40 => _40.validation, 'optionalAccess', _41 => _41.asyncValidateDelay]), () => (500));this.asyncTimers[t]=setTimeout(async()=>{let n=(this.asyncRequests[t]||0)+1;this.asyncRequests[t]=n,this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[t]:!0}});try{let a=await r(e,this.store.getState().values);if(this.asyncRequests[t]!==n)return;if(a)this.asyncErrors[t]=a,this.store.setError(t,a);else{delete this.asyncErrors[t];let l=this.store;if(l.validate)await l.validate({scopeFields:[t]});else{let c={...this.store.getState().errors};delete c[t],this.store.internalUpdateState({errors:c,isValid:Object.keys(c).length===0})}}}finally{this.asyncRequests[t]===n&&this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[t]:!1}})}},i)}trigger(t){this.validationTimeout&&clearTimeout(this.validationTimeout);let e=_nullishCoalesce(this.store.config.validationDelay, () => (300));e>0?this.validationTimeout=setTimeout(()=>{this.validate({scopeFields:t})},e):this.validate({scopeFields:t})}async validate(t){let e=++this.currentValidationId,s=this.store.getState(),r=_optionalChain([t, 'optionalAccess', _42 => _42.scopeFields]);_optionalChain([t, 'optionalAccess', _43 => _43.scope])&&_optionalChain([this, 'access', _44 => _44.store, 'access', _45 => _45.config, 'access', _46 => _46.scopes, 'optionalAccess', _47 => _47[t.scope]])&&(r=this.store.config.scopes[t.scope]);let i=this.store.config.resolver?await this.store.config.resolver(s.values,{scopeFields:r}):{},n=this.store.depsMg.getRequiredErrors(s.values);if(i={...i,...n},this.store.depsMg.hiddenFields.forEach(l=>{delete i[l],delete this.asyncErrors[l]}),e!==this.currentValidationId)return s.isValid;if(r){let l={...s.errors};r.forEach(d=>{i[d]?l[d]=i[d]:this.asyncErrors[d]?l[d]=this.asyncErrors[d]:delete l[d]});let c=Object.keys(l).length===0;return this.store.internalUpdateState({errors:l,isValid:c}),r.every(d=>!i[d]&&!this.asyncErrors[d])}i={...this.asyncErrors,...i};let a=Object.keys(i).length===0;return this.store.internalUpdateState({errors:i,isValid:a}),a}clear(t){this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]),delete this.asyncErrors[t]}cancelAll(){this.validationTimeout&&clearTimeout(this.validationTimeout),Object.values(this.asyncTimers).forEach(t=>clearTimeout(t))}}, _class3);var I=class{constructor(t){this.store=t}updateField(t,e){let s=this.store.getState(),r=y(s.values,t,e),i={...s.errors};delete i[t],this.store.validatorMg.clear(t);let n=this.store.depsMg.updateDependencies(t,r);n.forEach(l=>{this.store.depsMg.isHidden(l)&&(delete i[l],this.store.validatorMg.clear(l))});let a=this.store.dirtyMg.updateForPath(t,r,this.store.config.initialValues);return this.store.internalUpdateState({values:r,errors:i,isValid:Object.keys(i).length===0,isDirty:a}),this.store.config.resolver&&this.store.validatorMg.trigger([t]),this.store.validatorMg.handleAsync(t,e),{visibilitiesChanged:n.length>0}}updateAll(t){let e=f(t);this.store.config.initialValues=f(e),this.store.validatorMg.cancelAll(),this.store.depsMg.evaluateAll(e),this.store.dirtyMg.clear(),this.store.internalUpdateState({values:e,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.internalSaveSnapshot(),this.store.validatorMg.validate()}async submit(t){if(this.store.getState().isSubmitting)return;if(this.store.validatorMg.cancelAll(),this.store.internalUpdateState({isSubmitting:!0}),await this.store.validatorMg.validate())try{let r=f(this.store.getState().values);if(this.store.depsMg.hiddenFields.forEach(n=>{r=y(r,n,void 0)}),this.store.config.transform)for(let n in this.store.config.transform){let a=this.store.config.transform[n];if(a){let l=u(r,n);r=y(r,n,a(l,this.store.getState().values))}}let i=this.store.dirtyMg.buildDirtyValues(r);await t(r,i)}catch(r){console.error(r)}else{let r=this.store.getState().errors,i={...this.store.getState().touched};Object.keys(r).forEach(n=>{i[n]=!0}),this.store.internalUpdateState({touched:i})}this.store.internalUpdateState({isSubmitting:!1})}reset(){this.store.validatorMg.cancelAll();let t=f(this.store.config.initialValues);this.store.depsMg.evaluateAll(t),this.store.dirtyMg.clear(),this.store.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.historyMg.reset(t)}};function St(){return`
2
2
  .bit-devtools-container {
3
3
  position: fixed;
4
4
  bottom: 20px;
@@ -86,13 +86,13 @@
86
86
 
87
87
  pre.bit-pre { background: #020617; padding: 10px; border-radius: 4px; font-size: 11px; overflow-x: auto; border: 1px solid #1e293b; margin: 0; color: #e2e8f0; }
88
88
  pre.bit-error-box { background: rgba(239, 68, 68, 0.05); padding: 10px; border-radius: 4px; font-size: 11px; border: 1px dashed #ef4444; color: #fca5a5; margin: 0; overflow-x: auto; }
89
- `}var B= (_class4 =class{__init10() {this.currentStoresState={}}__init11() {this.isOpen=!1}constructor(t,e){;_class4.prototype.__init10.call(this);_class4.prototype.__init11.call(this);if(this.container=t,this.actions=e,!document.getElementById("bit-devtools-styles")){let s=document.createElement("style");s.id="bit-devtools-styles",s.textContent=St(),document.head.appendChild(s)}this.rootElement=document.createElement("div"),this.rootElement.className="bit-devtools-container",this.container.appendChild(this.rootElement),this.rootElement.addEventListener("click",s=>{let r=s.target;if(r.closest(".bit-devtools-trigger")){this.isOpen=!this.isOpen,this.render();return}let i=r.closest(".bit-action-btn");if(i&&!i.hasAttribute("disabled")){let o=i.getAttribute("data-action"),a=i.getAttribute("data-store");o&&a&&(o==="undo"&&this.actions.onUndo(a),o==="redo"&&this.actions.onRedo(a),o==="reset"&&this.actions.onReset(a))}})}updateState(t){this.currentStoresState=t,this.render()}render(){let t=Object.entries(this.currentStoresState);if(t.length===0){this.rootElement.innerHTML="";return}let e="";if(this.isOpen){e=`
89
+ `}var B= (_class4 =class{__init10() {this.currentStoresState={}}__init11() {this.isOpen=!1}constructor(t,e){;_class4.prototype.__init10.call(this);_class4.prototype.__init11.call(this);if(this.container=t,this.actions=e,!document.getElementById("bit-devtools-styles")){let s=document.createElement("style");s.id="bit-devtools-styles",s.textContent=St(),document.head.appendChild(s)}this.rootElement=document.createElement("div"),this.rootElement.className="bit-devtools-container",this.container.appendChild(this.rootElement),this.rootElement.addEventListener("click",s=>{let r=s.target;if(r.closest(".bit-devtools-trigger")){this.isOpen=!this.isOpen,this.render();return}let i=r.closest(".bit-action-btn");if(i&&!i.hasAttribute("disabled")){let n=i.getAttribute("data-action"),a=i.getAttribute("data-store");n&&a&&(n==="undo"&&this.actions.onUndo(a),n==="redo"&&this.actions.onRedo(a),n==="reset"&&this.actions.onReset(a))}})}updateState(t){this.currentStoresState=t,this.render()}render(){let t=Object.entries(this.currentStoresState);if(t.length===0){this.rootElement.innerHTML="";return}let e="";if(this.isOpen){e=`
90
90
  <div class="bit-devtools-panel">
91
91
  <div class="bit-devtools-header">
92
92
  <h2><span style="font-size: 20px;">\u{1F6E0}</span> Bit-Form DevTools</h2>
93
93
  <span style="font-size: 11px; color: #64748b;">v1.0.0</span>
94
94
  </div>
95
- `;for(let[r,i]of t){let o=Object.keys(i.errors||{}).length>0,a=i._meta||{totalSteps:0,currentIndex:-1,canUndo:!1,canRedo:!1},l=a.currentIndex+1,c=a.totalSteps;e+=`
95
+ `;for(let[r,i]of t){let n=Object.keys(i.errors||{}).length>0,a=i._meta||{totalSteps:0,currentIndex:-1,canUndo:!1,canRedo:!1},l=a.currentIndex+1,c=a.totalSteps;e+=`
96
96
  <div class="bit-store-block">
97
97
  <div class="bit-store-header">
98
98
  <h3 class="bit-store-title">${r}</h3>
@@ -118,7 +118,7 @@
118
118
  <span>\u{1F5D1}</span> Reset
119
119
  </button>
120
120
  </div>
121
- `,o&&(e+=`
121
+ `,n&&(e+=`
122
122
  <span class="bit-section-title" style="color: #f87171;">\u26A0\uFE0F Validations Failing</span>
123
123
  <pre class="bit-error-box">${JSON.stringify(i.errors,null,2)}</pre>
124
124
  `),e+=`
@@ -129,5 +129,5 @@
129
129
  <button class="bit-devtools-trigger" style="transform: ${this.isOpen?"scale(0.9)":"scale(1)"};" title="Abrir DevTools">
130
130
  ${this.isOpen?"\u2716":"Bit"}
131
131
  </button>
132
- `;this.rootElement.innerHTML=e+s}}, _class4);function kt(n){let t=new B(n,{onUndo:r=>_optionalChain([m, 'access', _48 => _48.stores, 'access', _49 => _49[r], 'optionalAccess', _50 => _50.undo, 'call', _51 => _51()]),onRedo:r=>_optionalChain([m, 'access', _52 => _52.stores, 'access', _53 => _53[r], 'optionalAccess', _54 => _54.redo, 'call', _55 => _55()]),onReset:r=>_optionalChain([m, 'access', _56 => _56.stores, 'access', _57 => _57[r], 'optionalAccess', _58 => _58.reset, 'call', _59 => _59()])}),e=()=>{let r={};for(let[i,o]of Object.entries(m.stores)){let a=o,l=a.getState(),c=_optionalChain([a, 'optionalAccess', _60 => _60.getHistoryMetadata, 'optionalCall', _61 => _61()])||{enabled:!1,canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};r[i]={...l,_meta:{canUndo:c.canUndo,canRedo:c.canRedo,totalSteps:c.historySize,currentIndex:c.historyIndex}}}return r};t.updateState(e());let s=m.subscribe(()=>{t.updateState(e())});return{ui:t,destroy:()=>{s(),n.innerHTML=""}}}function Mt(n,t="ws://localhost:3000"){let e=new WebSocket(t),s=new B(n,{onUndo:i=>r("ACTION",{storeId:i,action:"undo"}),onRedo:i=>r("ACTION",{storeId:i,action:"redo"}),onReset:i=>r("ACTION",{storeId:i,action:"reset"})}),r=(i,o)=>{e.readyState===WebSocket.OPEN?e.send(JSON.stringify({type:i,payload:o})):console.warn("[bit-form] Tentativa de envio falhou. WebSocket n\xE3o est\xE1 aberto.")};return e.addEventListener("open",()=>{console.log(`[bit-form] Conectado ao DevTools remoto em ${t}`)}),e.addEventListener("message",i=>{try{let o=JSON.parse(i.data);o.type==="STATE_UPDATE"&&s.updateState(o.payload)}catch(o){console.error("[bit-form] Erro ao processar mensagem do WebSocket:",o)}}),e.addEventListener("error",i=>{console.error("[bit-form] Erro na conex\xE3o do DevTools remoto:",i)}),s}function yt(n={}){let{mode:t="local",url:e}=n,s,r=!1;if(typeof n.container=="string"){let o=document.querySelector(n.container);if(!o)throw new Error(`[bit-form] Container '${n.container}' n\xE3o encontrado na p\xE1gina.`);s=o}else n.container instanceof HTMLElement?s=n.container:(s=document.createElement("div"),s.id="bit-form-devtools-root",s.style.position="fixed",s.style.bottom="20px",s.style.right="20px",s.style.zIndex="9999",s.style.maxHeight="80vh",s.style.overflowY="auto",s.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)",document.body.appendChild(s),r=!0);let i;if(t==="local")console.log("[bit-form] DevTools iniciado em modo Local."),i=kt(s);else if(t==="remote")console.log("[bit-form] DevTools iniciado em modo Remote."),i=Mt(s,e);else throw new Error(`[bit-form] Modo DevTools inv\xE1lido: ${t}`);return{...i,destroy:()=>{i&&typeof i.destroy=="function"&&i.destroy(),r&&s.parentNode?s.parentNode.removeChild(s):s.innerHTML=""}}}var A= (_class5 =class{__init12() {this.cleanupFn=null}constructor(t){;_class5.prototype.__init12.call(this);this.store=t,this.setup()}setup(){let t=this.store.config.devTools;if(!t)return;let e=typeof t=="boolean"?{enabled:t,mode:"local"}:{enabled:!0,...t};if(e.enabled)if(e.mode==="remote"){let s=e.url||"ws://localhost:3000";this.cleanupFn=Bt(s)}else{let s=yt();s&&typeof s.destroy=="function"&&(this.cleanupFn=s.destroy)}}destroy(){this.cleanupFn&&this.cleanupFn()}}, _class5);var F= (_class6 =class{constructor() { _class6.prototype.__init13.call(this); }__init13() {this.dirtyPaths=new Set}updateForPath(t,e,s){for(let o of this.dirtyPaths)o.startsWith(t+".")&&this.dirtyPaths.delete(o);let r=u(e,t),i=u(s,t);return x(r,i)?this.dirtyPaths.delete(t):this.dirtyPaths.add(t),this.dirtyPaths.size>0}rebuild(t,e){return this.dirtyPaths=j(t,e),this.dirtyPaths.size>0}clear(){this.dirtyPaths.clear()}get isDirty(){return this.dirtyPaths.size>0}getDirtyPaths(){return this.dirtyPaths}buildDirtyValues(t){if(this.dirtyPaths.size===0)return{};let e={},s=new Set;for(let r of this.dirtyPaths){let i=r.match(/^(.+)\.(\d+)/);if(i){let o=i[1];if(s.has(o))continue;s.add(o),this.setNestedValue(e,o,this.getNestedValue(t,o))}else this.setNestedValue(e,r,this.getNestedValue(t,r))}return e}getNestedValue(t,e){let s=e.split("."),r=t;for(let i of s){if(r==null)return;r=r[i]}return r}setNestedValue(t,e,s){let r=e.split("."),i=t;for(let o=0;o<r.length-1;o++){let a=r[o];a in i||(i[a]={}),i=i[a]}i[r[r.length-1]]=s}}, _class6);var O=class{constructor(t,e){this.getState=t;this.getConfig=e}getStepStatus(t){let e=_optionalChain([this, 'access', _62 => _62.getConfig, 'call', _63 => _63(), 'access', _64 => _64.scopes, 'optionalAccess', _65 => _65[t]])||[],s=this.getState(),r=e.some(a=>!!s.errors[a]),i=e.some(a=>{let l=u(s.values,a),c=u(this.getConfig().initialValues,a);return!x(l,c)}),o=this.getStepErrors(t);return{hasErrors:r,isDirty:i,errors:o}}getStepErrors(t){let e=_optionalChain([this, 'access', _66 => _66.getConfig, 'call', _67 => _67(), 'access', _68 => _68.scopes, 'optionalAccess', _69 => _69[t]])||[],s=this.getState(),r={};for(let i of e){let o=s.errors[i];o&&(r[i]=o)}return r}};var $=class{constructor(t,e,s){this.depsMg=t;this.getState=e;this.getConfig=s}isHidden(t){return this.depsMg.isHidden(t)}isRequired(t){return this.depsMg.isRequired(t,this.getState().values)}isFieldDirty(t){let e=u(this.getState().values,t),s=u(this.getConfig().initialValues,t);return!x(e,s)}isFieldValidating(t){return!!this.getState().isValidating[t]}};var U=class{constructor(t,e){this.getState=t;this.internalUpdateState=e}setError(t,e){let s={...this.getState().errors,[t]:e};e||delete s[t],this.internalUpdateState({errors:s})}setErrors(t){this.internalUpdateState({errors:{...this.getState().errors,...t}})}setServerErrors(t){let e={};for(let[s,r]of Object.entries(t))e[s]=Array.isArray(r)?r[0]:r;this.setErrors(e)}};var E= (_class7 =class{__init14() {this.listeners=new Set}constructor(t={}){;_class7.prototype.__init14.call(this);this.config=Tt(t),this.depsMg=new V,this.computedMg=new w(this.config),this.validatorMg=new I(this),this.dirtyMg=new F,this.lifecycleMg=new H(this),this.historyMg=new D(!!this.config.enableHistory,_nullishCoalesce(this.config.historyLimit, () => (15))),this.arraysMg=new R(this),this.devtoolsMg=new A(this),this.scopeMg=new O(()=>this.state,()=>this.config),this.queryMg=new $(this.depsMg,()=>this.state,()=>this.config),this.errorMg=new U(()=>this.state,r=>this.internalUpdateState(r));let e=f(this.config.initialValues),s=this.computedMg.apply(e);this.state={values:s,errors:{},touched:{},isValidating:{},isValid:!0,isSubmitting:!1,isDirty:!1},this.config.fields&&Object.entries(this.config.fields).forEach(([r,i])=>{this.depsMg.register(r,i,e)}),this.internalSaveSnapshot(),this.storeId=this.config.name||`bit-form-${Math.random().toString(36).substring(2,9)}`,m.stores[this.storeId]=this}getConfig(){return this.config}getState(){return this.state}get isValid(){return this.state.isValid}get isSubmitting(){return this.state.isSubmitting}get isDirty(){return this.state.isDirty}registerField(t,e){this.depsMg.register(t,e,this.state.values),this.depsMg.isHidden(t)&&this.notify()}unregisterField(t){if(_optionalChain([this, 'access', _70 => _70.config, 'access', _71 => _71.fields, 'optionalAccess', _72 => _72[t]]))return;this.depsMg.unregister(t);let e={...this.state.errors},s={...this.state.touched},r=!1;e[t]&&(delete e[t],r=!0),s[t]&&(delete s[t],r=!0),r&&this.internalUpdateState({errors:e,touched:s})}unregisterPrefix(t){this.depsMg.unregisterPrefix(t)}isHidden(t){return this.queryMg.isHidden(t)}isRequired(t){return this.queryMg.isRequired(t)}isFieldDirty(t){return this.queryMg.isFieldDirty(t)}isFieldValidating(t){return this.queryMg.isFieldValidating(t)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}watch(t,e){let s=f(u(this.state.values,t));return this.subscribe(()=>{let r=u(this.state.values,t);T(r,s)||(s=f(r),e(r))})}setField(t,e){let{visibilitiesChanged:s}=this.lifecycleMg.updateField(t,e);(!this.config.resolver||s)&&this.notify()}blurField(t){this.internalSaveSnapshot(),this.state.touched[t]||this.internalUpdateState({touched:{...this.state.touched,[t]:!0}}),this.validatorMg.trigger([t])}markFieldsTouched(t){if(t.length===0)return;let e={...this.state.touched};t.forEach(s=>e[s]=!0),this.internalUpdateState({touched:e})}setValues(t){this.lifecycleMg.updateAll(t)}setError(t,e){this.errorMg.setError(t,e)}setErrors(t){this.errorMg.setErrors(t)}setServerErrors(t){this.errorMg.setServerErrors(t)}reset(){this.lifecycleMg.reset()}async submit(t){return this.lifecycleMg.submit(t)}registerMask(t,e){this.config.masks[t]=e}getDirtyValues(){return this.dirtyMg.buildDirtyValues(this.state.values)}pushItem(t,e){this.arraysMg.pushItem(t,e)}prependItem(t,e){this.arraysMg.prependItem(t,e)}insertItem(t,e,s){this.arraysMg.insertItem(t,e,s)}removeItem(t,e){this.arraysMg.removeItem(t,e)}swapItems(t,e,s){this.arraysMg.swapItems(t,e,s)}moveItem(t,e,s){this.arraysMg.moveItem(t,e,s)}get canUndo(){return this.historyMg.canUndo}get canRedo(){return this.historyMg.canRedo}undo(){let t=this.historyMg.undo();if(t){let e=this.dirtyMg.rebuild(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}redo(){let t=this.historyMg.redo();if(t){let e=this.dirtyMg.rebuild(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}getHistoryMetadata(){return this.historyMg.getMetadata()}validate(t){return this.validatorMg.validate(t)}getStepStatus(t){return this.scopeMg.getStepStatus(t)}getStepErrors(t){return this.scopeMg.getStepErrors(t)}internalUpdateState(t){let e={...this.state,...t};t.values&&(e.values=this.computedMg.apply(t.values)),t.errors&&(e.isValid=Object.keys(e.errors).length===0),this.state=e,this.notify(),m.dispatch(this.storeId,this.state)}internalSaveSnapshot(){this.historyMg.saveSnapshot(this.state.values)}cleanup(){this.listeners.clear(),this.validatorMg.cancelAll(),delete m.stores[this.storeId]}notify(){this.listeners.forEach(t=>t())}}, _class7);function Ot(n={}){let t=new E(n);return{getConfig:()=>t.getConfig(),getState:()=>t.getState(),subscribe:t.subscribe.bind(t),setField:t.setField.bind(t),blurField:t.blurField.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),reset:t.reset.bind(t),submit:t.submit.bind(t),registerMask:t.registerMask.bind(t),getDirtyValues:t.getDirtyValues.bind(t),cleanup:t.cleanup.bind(t)}}function $t(n={}){return new E(n)}var Et=n=>{let t=typeof n.getState=="function"?n.getState():n,e=_optionalChain([n, 'optionalAccess', _73 => _73.getHistoryMetadata, 'optionalCall', _74 => _74()])||{canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};return{...t,_meta:{canUndo:e.canUndo,canRedo:e.canRedo,totalSteps:e.historySize,currentIndex:e.historyIndex}}},L=null;function Bt(n){L&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),L());let t=null,e=null,s,r=!1,i=()=>{r=!1,t=new WebSocket(n),t.onopen=()=>{console.log("[bit-form] \u{1F50C} Conectado ao CLI DevTools via WebSocket.");let a=Object.entries(m.stores);if(a.length>0){let l=a.reduce((c,[d,p])=>(c[d]=Et(p),c),{});_optionalChain([t, 'optionalAccess', _75 => _75.send, 'call', _76 => _76(JSON.stringify({type:"STATE_UPDATE",payload:l}))])}e=m.subscribe((l,c)=>{if(_optionalChain([t, 'optionalAccess', _77 => _77.readyState])===WebSocket.OPEN){let d=m.stores[l];d&&t.send(JSON.stringify({type:"STATE_UPDATE",payload:{[l]:Et(d)}}))}}),s=setInterval(()=>{_optionalChain([t, 'optionalAccess', _78 => _78.readyState])===WebSocket.OPEN&&t.send(JSON.stringify({type:"PING"}))},3e4)},t.onmessage=a=>{try{let{type:l,payload:c}=JSON.parse(a.data);if(l==="ACTION"){let{storeId:d,action:p}=c,h=m.stores[d];h&&typeof h[p]=="function"&&h[p]()}}catch(l){console.warn("[bit-form] Erro ao processar comando do CLI:",l)}},t.onclose=()=>{e&&e(),clearInterval(s),r?console.log("[bit-form] Ponte antiga encerrada com sucesso."):(console.log("[bit-form] Conex\xE3o perdida. Reconectando em 3s..."),setTimeout(i,3e3))}};i();let o=()=>{r=!0,e&&e(),clearInterval(s),t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),L=null};return L=o,o}exports.a = m; exports.b = f; exports.c = x; exports.d = T; exports.e = u; exports.f = y; exports.g = Pt; exports.h = bt; exports.i = Ct; exports.j = M; exports.k = xt; exports.l = g; exports.m = b; exports.n = z; exports.o = C; exports.p = W; exports.q = Y; exports.r = J; exports.s = K; exports.t = G; exports.u = Z; exports.v = Q; exports.w = tt; exports.x = et; exports.y = st; exports.z = rt; exports.A = it; exports.B = nt; exports.C = ot; exports.D = at; exports.E = lt; exports.F = ct; exports.G = Vt; exports.H = Dt; exports.I = Rt; exports.J = wt; exports.K = dt; exports.L = ut; exports.M = It; exports.N = gt; exports.O = pt; exports.P = ft; exports.Q = ht; exports.R = Ht; exports.S = mt; exports.T = Bt; exports.U = yt; exports.V = Ot; exports.W = $t;
133
- //# sourceMappingURL=chunk-K3DCDRWB.cjs.map
132
+ `;this.rootElement.innerHTML=e+s}}, _class4);function kt(o){let t=new B(o,{onUndo:r=>_optionalChain([m, 'access', _48 => _48.stores, 'access', _49 => _49[r], 'optionalAccess', _50 => _50.undo, 'call', _51 => _51()]),onRedo:r=>_optionalChain([m, 'access', _52 => _52.stores, 'access', _53 => _53[r], 'optionalAccess', _54 => _54.redo, 'call', _55 => _55()]),onReset:r=>_optionalChain([m, 'access', _56 => _56.stores, 'access', _57 => _57[r], 'optionalAccess', _58 => _58.reset, 'call', _59 => _59()])}),e=()=>{let r={};for(let[i,n]of Object.entries(m.stores)){let a=n,l=a.getState(),c=_optionalChain([a, 'optionalAccess', _60 => _60.getHistoryMetadata, 'optionalCall', _61 => _61()])||{enabled:!1,canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};r[i]={...l,_meta:{canUndo:c.canUndo,canRedo:c.canRedo,totalSteps:c.historySize,currentIndex:c.historyIndex}}}return r};t.updateState(e());let s=m.subscribe(()=>{t.updateState(e())});return{ui:t,destroy:()=>{s(),o.innerHTML=""}}}function Mt(o,t="ws://localhost:3000"){let e=new WebSocket(t),s=new B(o,{onUndo:i=>r("ACTION",{storeId:i,action:"undo"}),onRedo:i=>r("ACTION",{storeId:i,action:"redo"}),onReset:i=>r("ACTION",{storeId:i,action:"reset"})}),r=(i,n)=>{e.readyState===WebSocket.OPEN?e.send(JSON.stringify({type:i,payload:n})):console.warn("[bit-form] Tentativa de envio falhou. WebSocket n\xE3o est\xE1 aberto.")};return e.addEventListener("open",()=>{console.log(`[bit-form] Conectado ao DevTools remoto em ${t}`)}),e.addEventListener("message",i=>{try{let n=JSON.parse(i.data);n.type==="STATE_UPDATE"&&s.updateState(n.payload)}catch(n){console.error("[bit-form] Erro ao processar mensagem do WebSocket:",n)}}),e.addEventListener("error",i=>{console.error("[bit-form] Erro na conex\xE3o do DevTools remoto:",i)}),s}function yt(o={}){let{mode:t="local",url:e}=o,s,r=!1;if(typeof o.container=="string"){let n=document.querySelector(o.container);if(!n)throw new Error(`[bit-form] Container '${o.container}' n\xE3o encontrado na p\xE1gina.`);s=n}else o.container instanceof HTMLElement?s=o.container:(s=document.createElement("div"),s.id="bit-form-devtools-root",s.style.position="fixed",s.style.bottom="20px",s.style.right="20px",s.style.zIndex="9999",s.style.maxHeight="80vh",s.style.overflowY="auto",s.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)",document.body.appendChild(s),r=!0);let i;if(t==="local")console.log("[bit-form] DevTools iniciado em modo Local."),i=kt(s);else if(t==="remote")console.log("[bit-form] DevTools iniciado em modo Remote."),i=Mt(s,e);else throw new Error(`[bit-form] Modo DevTools inv\xE1lido: ${t}`);return{...i,destroy:()=>{i&&typeof i.destroy=="function"&&i.destroy(),r&&s.parentNode?s.parentNode.removeChild(s):s.innerHTML=""}}}var H= (_class5 =class{__init12() {this.cleanupFn=null}constructor(t){;_class5.prototype.__init12.call(this);this.store=t,this.setup()}setup(){let t=this.store.config.devTools;if(!t)return;let e=typeof t=="boolean"?{enabled:t,mode:"local"}:{enabled:!0,...t};if(e.enabled)if(e.mode==="remote"){let s=e.url||"ws://localhost:3000";this.cleanupFn=Bt(s)}else{let s=yt();s&&typeof s.destroy=="function"&&(this.cleanupFn=s.destroy)}}destroy(){this.cleanupFn&&this.cleanupFn()}}, _class5);var A= (_class6 =class{constructor() { _class6.prototype.__init13.call(this); }__init13() {this.dirtyPaths=new Set}updateForPath(t,e,s){for(let n of this.dirtyPaths)n.startsWith(t+".")&&this.dirtyPaths.delete(n);let r=u(e,t),i=u(s,t);return x(r,i)?this.dirtyPaths.delete(t):this.dirtyPaths.add(t),this.dirtyPaths.size>0}rebuild(t,e){return this.dirtyPaths=j(t,e),this.dirtyPaths.size>0}clear(){this.dirtyPaths.clear()}get isDirty(){return this.dirtyPaths.size>0}getDirtyPaths(){return this.dirtyPaths}buildDirtyValues(t){if(this.dirtyPaths.size===0)return{};let e={},s=new Set;for(let r of this.dirtyPaths){let i=r.match(/^(.+)\.(\d+)/);if(i){let n=i[1];if(s.has(n))continue;s.add(n),this.setNestedValue(e,n,this.getNestedValue(t,n))}else this.setNestedValue(e,r,this.getNestedValue(t,r))}return e}getNestedValue(t,e){let s=e.split("."),r=t;for(let i of s){if(r==null)return;r=r[i]}return r}setNestedValue(t,e,s){let r=e.split("."),i=t;for(let n=0;n<r.length-1;n++){let a=r[n];a in i||(i[a]={}),i=i[a]}i[r[r.length-1]]=s}}, _class6);var F=class{constructor(t,e){this.getState=t;this.getConfig=e}getStepStatus(t){let e=_optionalChain([this, 'access', _62 => _62.getConfig, 'call', _63 => _63(), 'access', _64 => _64.scopes, 'optionalAccess', _65 => _65[t]])||[],s=this.getState(),r=e.some(a=>!!s.errors[a]),i=e.some(a=>{let l=u(s.values,a),c=u(this.getConfig().initialValues,a);return!x(l,c)}),n=this.getStepErrors(t);return{hasErrors:r,isDirty:i,errors:n}}getStepErrors(t){let e=_optionalChain([this, 'access', _66 => _66.getConfig, 'call', _67 => _67(), 'access', _68 => _68.scopes, 'optionalAccess', _69 => _69[t]])||[],s=this.getState(),r={};for(let i of e){let n=s.errors[i];n&&(r[i]=n)}return r}};var O=class{constructor(t,e,s){this.depsMg=t;this.getState=e;this.getConfig=s}isHidden(t){return this.depsMg.isHidden(t)}isRequired(t){return this.depsMg.isRequired(t,this.getState().values)}isFieldDirty(t){let e=u(this.getState().values,t),s=u(this.getConfig().initialValues,t);return!x(e,s)}isFieldValidating(t){return!!this.getState().isValidating[t]}};var $=class{constructor(t,e){this.getState=t;this.internalUpdateState=e}setError(t,e){let s={...this.getState().errors,[t]:e};e||delete s[t],this.internalUpdateState({errors:s})}setErrors(t){this.internalUpdateState({errors:{...this.getState().errors,...t}})}setServerErrors(t){let e={};for(let[s,r]of Object.entries(t))e[s]=Array.isArray(r)?r[0]:r;this.setErrors(e)}};var U= (_class7 =class{__init14() {this.listeners=new Set}constructor(t={}){;_class7.prototype.__init14.call(this);this.config=Tt(t),this.depsMg=new C,this.computedMg=new R(this.config),this.validatorMg=new w(this),this.dirtyMg=new A,this.lifecycleMg=new I(this),this.historyMg=new V(!!this.config.enableHistory,_nullishCoalesce(this.config.historyLimit, () => (15))),this.arraysMg=new D(this),this.devtoolsMg=new H(this),this.scopeMg=new F(()=>this.state,()=>this.config),this.queryMg=new O(this.depsMg,()=>this.state,()=>this.config),this.errorMg=new $(()=>this.state,r=>this.internalUpdateState(r));let e=f(this.config.initialValues),s=this.computedMg.apply(e);this.state={values:s,errors:{},touched:{},isValidating:{},isValid:!0,isSubmitting:!1,isDirty:!1},this.config.fields&&Object.entries(this.config.fields).forEach(([r,i])=>{this.depsMg.register(r,i,e)}),this.internalSaveSnapshot(),this.storeId=this.config.name||`bit-form-${Math.random().toString(36).substring(2,9)}`,m.stores[this.storeId]=this}getConfig(){return this.config}getState(){return this.state}get isValid(){return this.state.isValid}get isSubmitting(){return this.state.isSubmitting}get isDirty(){return this.state.isDirty}registerField(t,e){this.depsMg.register(t,e,this.state.values),this.depsMg.isHidden(t)&&this.notify()}unregisterField(t){if(_optionalChain([this, 'access', _70 => _70.config, 'access', _71 => _71.fields, 'optionalAccess', _72 => _72[t]]))return;this.depsMg.unregister(t);let e={...this.state.errors},s={...this.state.touched},r=!1;e[t]&&(delete e[t],r=!0),s[t]&&(delete s[t],r=!0),r&&this.internalUpdateState({errors:e,touched:s})}unregisterPrefix(t){this.depsMg.unregisterPrefix(t)}isHidden(t){return this.queryMg.isHidden(t)}isRequired(t){return this.queryMg.isRequired(t)}isFieldDirty(t){return this.queryMg.isFieldDirty(t)}isFieldValidating(t){return this.queryMg.isFieldValidating(t)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}watch(t,e){let s=f(u(this.state.values,t));return this.subscribe(()=>{let r=u(this.state.values,t);T(r,s)||(s=f(r),e(r))})}setField(t,e){let{visibilitiesChanged:s}=this.lifecycleMg.updateField(t,e);(!this.config.resolver||s)&&this.notify()}blurField(t){this.internalSaveSnapshot(),this.state.touched[t]||this.internalUpdateState({touched:{...this.state.touched,[t]:!0}}),this.validatorMg.trigger([t])}markFieldsTouched(t){if(t.length===0)return;let e={...this.state.touched};t.forEach(s=>e[s]=!0),this.internalUpdateState({touched:e})}setValues(t){this.lifecycleMg.updateAll(t)}setError(t,e){this.errorMg.setError(t,e)}setErrors(t){this.errorMg.setErrors(t)}setServerErrors(t){this.errorMg.setServerErrors(t)}reset(){this.lifecycleMg.reset()}async submit(t){return this.lifecycleMg.submit(t)}registerMask(t,e){this.config.masks[t]=e}getDirtyValues(){return this.dirtyMg.buildDirtyValues(this.state.values)}pushItem(t,e){this.arraysMg.pushItem(t,e)}prependItem(t,e){this.arraysMg.prependItem(t,e)}insertItem(t,e,s){this.arraysMg.insertItem(t,e,s)}removeItem(t,e){this.arraysMg.removeItem(t,e)}swapItems(t,e,s){this.arraysMg.swapItems(t,e,s)}moveItem(t,e,s){this.arraysMg.moveItem(t,e,s)}get canUndo(){return this.historyMg.canUndo}get canRedo(){return this.historyMg.canRedo}undo(){let t=this.historyMg.undo();if(t){let e=this.dirtyMg.rebuild(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}redo(){let t=this.historyMg.redo();if(t){let e=this.dirtyMg.rebuild(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}getHistoryMetadata(){return this.historyMg.getMetadata()}validate(t){return this.validatorMg.validate(t)}getStepStatus(t){return this.scopeMg.getStepStatus(t)}getStepErrors(t){return this.scopeMg.getStepErrors(t)}internalUpdateState(t){let e={...this.state,...t};t.values&&(e.values=this.computedMg.apply(t.values)),t.errors&&(e.isValid=Object.keys(e.errors).length===0),this.state=e,this.notify(),m.dispatch(this.storeId,this.state)}internalSaveSnapshot(){this.historyMg.saveSnapshot(this.state.values)}cleanup(){this.listeners.clear(),this.validatorMg.cancelAll(),delete m.stores[this.storeId]}notify(){this.listeners.forEach(t=>t())}}, _class7);function Ot(o={}){let t=new U(o);return{getConfig:()=>t.getConfig(),getState:()=>t.getState(),subscribe:t.subscribe.bind(t),setField:t.setField.bind(t),blurField:t.blurField.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),reset:t.reset.bind(t),submit:t.submit.bind(t),registerMask:t.registerMask.bind(t),getDirtyValues:t.getDirtyValues.bind(t),cleanup:t.cleanup.bind(t)}}var Et=o=>{let t=typeof o.getState=="function"?o.getState():o,e=_optionalChain([o, 'optionalAccess', _73 => _73.getHistoryMetadata, 'optionalCall', _74 => _74()])||{canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};return{...t,_meta:{canUndo:e.canUndo,canRedo:e.canRedo,totalSteps:e.historySize,currentIndex:e.historyIndex}}},L=null;function Bt(o){L&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),L());let t=null,e=null,s,r=!1,i=()=>{r=!1,t=new WebSocket(o),t.onopen=()=>{console.log("[bit-form] \u{1F50C} Conectado ao CLI DevTools via WebSocket.");let a=Object.entries(m.stores);if(a.length>0){let l=a.reduce((c,[d,p])=>(c[d]=Et(p),c),{});_optionalChain([t, 'optionalAccess', _75 => _75.send, 'call', _76 => _76(JSON.stringify({type:"STATE_UPDATE",payload:l}))])}e=m.subscribe((l,c)=>{if(_optionalChain([t, 'optionalAccess', _77 => _77.readyState])===WebSocket.OPEN){let d=m.stores[l];d&&t.send(JSON.stringify({type:"STATE_UPDATE",payload:{[l]:Et(d)}}))}}),s=setInterval(()=>{_optionalChain([t, 'optionalAccess', _78 => _78.readyState])===WebSocket.OPEN&&t.send(JSON.stringify({type:"PING"}))},3e4)},t.onmessage=a=>{try{let{type:l,payload:c}=JSON.parse(a.data);if(l==="ACTION"){let{storeId:d,action:p}=c,h=m.stores[d];h&&typeof h[p]=="function"&&h[p]()}}catch(l){console.warn("[bit-form] Erro ao processar comando do CLI:",l)}},t.onclose=()=>{e&&e(),clearInterval(s),r?console.log("[bit-form] Ponte antiga encerrada com sucesso."):(console.log("[bit-form] Conex\xE3o perdida. Reconectando em 3s..."),setTimeout(i,3e3))}};i();let n=()=>{r=!0,e&&e(),clearInterval(s),t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),L=null};return L=n,n}exports.a = m; exports.b = f; exports.c = x; exports.d = T; exports.e = u; exports.f = y; exports.g = Pt; exports.h = bt; exports.i = Ct; exports.j = M; exports.k = xt; exports.l = g; exports.m = b; exports.n = z; exports.o = P; exports.p = W; exports.q = Y; exports.r = J; exports.s = K; exports.t = G; exports.u = Z; exports.v = Q; exports.w = tt; exports.x = et; exports.y = st; exports.z = rt; exports.A = it; exports.B = ot; exports.C = nt; exports.D = at; exports.E = lt; exports.F = ct; exports.G = Vt; exports.H = Dt; exports.I = Rt; exports.J = wt; exports.K = dt; exports.L = ut; exports.M = It; exports.N = gt; exports.O = pt; exports.P = ft; exports.Q = ht; exports.R = Ht; exports.S = mt; exports.T = Bt; exports.U = yt; exports.V = Ot;
133
+ //# sourceMappingURL=chunk-4MPIKMTH.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/store/bus.ts","../src/core/utils.ts","../src/devtools/ui/styles.ts","../src/devtools/ui/index.ts","../src/devtools/init-dev-tools.ts"],"names":["rootGlobal","id","state","fn","bitBus","deepClone","obj","item","clone","key","valueEqual","a","b","deepEqual","keysA","keysB","collectDirtyPaths","initial","prefix","result","allKeys","k","p"],"mappings":"AAaA,+wBAAMA,CAAAA,CACJ,OAAO,UAAA,CAAe,GAAA,CAClB,UAAA,CACE,OAAO,MAAA,CAAW,GAAA,CAAc,MAAA,CAAS,MAAA,CAE5CA,CAAAA,CAAW,YAAA,EAAA,CACdA,CAAAA,CAAW,YAAA,CAAe,CACxB,MAAA,CAAQ,CAAC,CAAA,CACT,SAAA,CAAW,IAAI,GAAA,CAEf,QAAA,CAASC,CAAAA,CAAYC,CAAAA,CAAY,CAC/B,IAAA,CAAK,SAAA,CAAU,OAAA,CAASC,CAAAA,EAAuBA,CAAAA,CAAGF,CAAAA,CAAIC,CAAK,CAAC,CAC9D,CAAA,CAEA,SAAA,CAAUC,CAAAA,CAAoB,CAC5B,OAAA,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIA,CAAE,CAAA,CACd,CAAA,CAAA,EAAM,CACX,IAAA,CAAK,SAAA,CAAU,MAAA,CAAOA,CAAE,CAC1B,CACF,CACF,CAAA,CAAA,CAGK,IAAMC,CAAAA,CAASJ,CAAAA,CAAW,YAAA,CCpC1B,SAASK,CAAAA,CAAaC,CAAAA,CAAW,CACtC,EAAA,CAAIA,CAAAA,GAAQ,IAAA,EAAQ,OAAOA,CAAAA,EAAQ,QAAA,CACjC,OAAOA,CAAAA,CAGT,EAAA,CAAIA,EAAAA,WAAe,IAAA,CACjB,OAAO,IAAI,IAAA,CAAKA,CAAAA,CAAI,OAAA,CAAQ,CAAC,CAAA,CAE/B,EAAA,CAAIA,EAAAA,WAAe,MAAA,CACjB,OAAO,IAAI,MAAA,CAAOA,CAAAA,CAAI,MAAA,CAAQA,CAAAA,CAAI,KAAK,CAAA,CAGzC,EAAA,CAAI,KAAA,CAAM,OAAA,CAAQA,CAAG,CAAA,CACnB,OAAOA,CAAAA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MAAA,CAAO,IAAA,CAAKW,CAAAA,EAAW,CAAC,CAAC,CAC9B,CAAC,CAAA,CACD,GAAA,CAAA,IAAWI,EAAAA,GAAKD,CAAAA,CAAS,CACvB,IAAME,CAAAA,CAAIJ,CAAAA,CAAS,CAAA,EAAA;ACtGd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACkES,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBG,MAAA;AAAA;AAAA;AAGyB,0CAAA;AAAA;AAE0C,uCAAA;AAC7B,kBAAA;AAAA;AAE6B,gBAAA;AACY,gBAAA;AAAA;AAAA;AAAA;AAIhB,yDAAA;AAAA;AAAA;AAG+B,4EAAA;AAAA;AAAA;AAGA,4EAAA;AAAA;AAAA;AAGpB,2FAAA;AAAA;AAAA;AAAA;AAOxE,QAAA;AAAA;AAEuD,uCAAA;AAIzD,UAAA;AAAA;AAEmD,iCAAA;AAAA;AAShD,QAAA;AAC8E,6DAAA;AACnE,QAAA;AAAA;ACjIzB,IAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-K3DCDRWB.cjs","sourcesContent":["export type BitBusListener = (storeId: string, newState: any) => void;\n\ninterface BitFormGlobal {\n stores: Record<string, any>;\n listeners: Set<BitBusListener>;\n dispatch: (storeId: string, state: any) => void;\n subscribe: (fn: BitBusListener) => () => void;\n}\n\ndeclare global {\n var __BIT_FORM__: BitFormGlobal | undefined;\n}\n\nconst rootGlobal =\n typeof globalThis !== \"undefined\"\n ? globalThis\n : ((typeof global !== \"undefined\" ? global : window) as any);\n\nif (!rootGlobal.__BIT_FORM__) {\n rootGlobal.__BIT_FORM__ = {\n stores: {},\n listeners: new Set<BitBusListener>(),\n\n dispatch(id: string, state: any) {\n this.listeners.forEach((fn: BitBusListener) => fn(id, state));\n },\n\n subscribe(fn: BitBusListener) {\n this.listeners.add(fn);\n return () => {\n this.listeners.delete(fn);\n };\n },\n };\n}\n\nexport const bitBus = rootGlobal.__BIT_FORM__ as BitFormGlobal;\n","export function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as any as T;\n }\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags) as any as T;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => deepClone(item)) as any as T;\n }\n\n const clone: any = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone((obj as any)[key]);\n }\n }\n return clone as T;\n}\n\n/**\n * Fast equality for single values. Uses === for primitives, deepEqual for objects/arrays.\n * Prefer over deepEqual when comparing a single field value (e.g. isFieldDirty, getStepStatus).\n */\nexport function valueEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n return deepEqual(a, b);\n}\n\nexport function deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n if (a instanceof RegExp && b instanceof RegExp)\n return a.toString() === b.toString();\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !deepEqual(a[key], b[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Collects all paths where obj differs from initial. Used to rebuild dirtyPaths after full state replacement.\n */\nexport function collectDirtyPaths(\n obj: any,\n initial: any,\n prefix = \"\",\n result: Set<string> = new Set(),\n): Set<string> {\n if (valueEqual(obj, initial)) return result;\n if (\n obj === null ||\n typeof obj !== \"object\" ||\n initial === null ||\n typeof initial !== \"object\"\n ) {\n if (prefix) result.add(prefix);\n return result;\n }\n if (Array.isArray(obj) || Array.isArray(initial)) {\n if (!valueEqual(obj, initial) && prefix) result.add(prefix);\n return result;\n }\n const allKeys = new Set([\n ...Object.keys(obj || {}),\n ...Object.keys(initial || {}),\n ]);\n for (const k of allKeys) {\n const p = prefix ? `${prefix}.${k}` : k;\n collectDirtyPaths((obj as any)?.[k], (initial as any)?.[k], p, result);\n }\n return result;\n}\n\nconst pathCache = new Map<string, string[]>();\n\nexport function getDeepValue(obj: any, path: string): any {\n if (!path) return obj;\n\n const keys = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\n\n let current = obj;\n for (const key of keys) {\n if (current === null || current === undefined) return undefined;\n current = current[key];\n }\n return current;\n}\n\nexport function setDeepValue(obj: any, path: string, value: any): any {\n if (!path) return value;\n\n const keys = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\n\n const result = Array.isArray(obj) ? [...obj] : { ...obj };\n let current = result;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const isNextNumeric = /^\\d+$/.test(nextKey);\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n } else {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n\n return result;\n}\n\nexport function cleanPrefixedKeys(\n obj: Record<string, any>,\n prefix: string,\n): Record<string, any> {\n const newObj: Record<string, any> = {};\n const prefixWithDot = `${prefix}.`;\n\n for (const key in obj) {\n if (key !== prefix && !key.startsWith(prefixWithDot)) {\n newObj[key] = obj[key];\n }\n }\n return newObj;\n}\n\nexport const shiftKeys = (\n obj: Record<string, any>,\n path: string,\n removedIndex: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === removedIndex) return;\n\n if (currentIdx > removedIndex) {\n const newIdx = currentIdx - 1;\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const swapKeys = (\n obj: Record<string, any>,\n path: string,\n indexA: number,\n indexB: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === indexA) {\n const newKey = rest ? `${prefix}${indexB}.${rest}` : `${prefix}${indexB}`;\n newObj[newKey] = obj[key];\n } else if (currentIdx === indexB) {\n const newKey = rest ? `${prefix}${indexA}.${rest}` : `${prefix}${indexA}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const moveKeys = (\n obj: Record<string, any>,\n path: string,\n from: number,\n to: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n let newIdx = currentIdx;\n if (currentIdx === from) {\n newIdx = to;\n } else if (from < to && currentIdx > from && currentIdx <= to) {\n newIdx = currentIdx - 1;\n } else if (from > to && currentIdx >= to && currentIdx < from) {\n newIdx = currentIdx + 1;\n }\n\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n });\n return newObj;\n};\n\n/**\n * Checks if a value looks like a server validation error response.\n * Handles shapes like { email: \"Taken\" }, { errors: { email: [\"Taken\"] } }, etc.\n */\nexport function isValidationErrorShape(\n x: unknown,\n): x is Record<string, string | string[]> {\n if (typeof x !== \"object\" || x === null || Array.isArray(x)) return false;\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return false;\n\n return Object.values(obj as Record<string, unknown>).every(\n (v) =>\n typeof v === \"string\" ||\n (Array.isArray(v) && v.every((i) => typeof i === \"string\")),\n );\n}\n\n/**\n * Extracts server errors in the format expected by setServerErrors.\n */\nexport function extractServerErrors(\n x: unknown,\n): Record<string, string | string[]> {\n if (!isValidationErrorShape(x)) return {};\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n return obj as Record<string, string | string[]>;\n}\n","export function getDevToolsCSS(): string {\n return `\n .bit-devtools-container {\n position: fixed;\n bottom: 20px;\n right: 20px;\n z-index: 9999;\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n }\n\n .bit-devtools-trigger {\n background: #10b981;\n color: #fff;\n border: none;\n border-radius: 50%;\n width: 48px;\n height: 48px;\n cursor: pointer;\n box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);\n font-weight: bold;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n font-size: 16px;\n margin-top: 16px;\n }\n .bit-devtools-trigger:hover { transform: scale(1.05); }\n\n .bit-devtools-panel {\n width: 450px;\n max-height: 80vh;\n background: #0f172a;\n color: #f8fafc;\n border-radius: 8px;\n padding: 16px;\n overflow-y: auto;\n box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5), 0 8px 10px -6px rgba(0,0,0,0.5);\n border: 1px solid #334155;\n display: flex;\n flex-direction: column;\n gap: 16px;\n }\n\n .bit-devtools-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding-bottom: 12px;\n border-bottom: 1px solid #1e293b;\n }\n .bit-devtools-header h2 { margin: 0; font-size: 16px; display: flex; align-items: center; gap: 8px; }\n\n .bit-store-block {\n background: #1e293b;\n border-radius: 6px;\n padding: 12px;\n border: 1px solid #334155;\n }\n\n .bit-store-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 12px;\n }\n .bit-store-title { margin: 0; color: #38bdf8; font-size: 14px; font-weight: bold; }\n\n .bit-badge-group { display: flex; gap: 6px; flex-wrap: wrap; }\n .bit-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: bold; }\n .badge-success { background: rgba(16, 185, 129, 0.2); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.2); }\n .badge-error { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.2); }\n .badge-warn { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.2); }\n .badge-info { background: rgba(56, 189, 248, 0.2); color: #7dd3fc; border: 1px solid rgba(56, 189, 248, 0.2); }\n\n .bit-section-title { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin: 12px 0 4px 0; display: block; }\n\n .bit-controls { display: flex; gap: 6px; margin-bottom: 12px; background: #0f172a; padding: 8px; border-radius: 6px; }\n .bit-action-btn { flex: 1; background: #334155; color: #e2e8f0; border: 1px solid #475569; padding: 6px 0; border-radius: 4px; cursor: pointer; font-size: 11px; display: flex; align-items: center; justify-content: center; gap: 4px; transition: all 0.2s; }\n .bit-action-btn:hover:not(:disabled) { background: #475569; }\n .bit-action-btn:disabled { opacity: 0.5; cursor: not-allowed; }\n .bit-btn-reset { color: #fca5a5; border-color: rgba(239,68,68,0.3); }\n .bit-btn-reset:hover { background: rgba(239,68,68,0.1) !important; }\n\n pre.bit-pre { background: #020617; padding: 10px; border-radius: 4px; font-size: 11px; overflow-x: auto; border: 1px solid #1e293b; margin: 0; color: #e2e8f0; }\n pre.bit-error-box { background: rgba(239, 68, 68, 0.05); padding: 10px; border-radius: 4px; font-size: 11px; border: 1px dashed #ef4444; color: #fca5a5; margin: 0; overflow-x: auto; }\n `;\n}\n","import { getDevToolsCSS } from \"./styles\";\nimport type { DevToolsActions } from \"../types\";\n\nexport type { DevToolsActions };\n\nexport class BitFormDevToolsUI {\n private container: HTMLElement;\n private actions: DevToolsActions;\n private rootElement: HTMLDivElement;\n private currentStoresState: Record<string, any> = {};\n private isOpen: boolean = false;\n\n constructor(container: HTMLElement, actions: DevToolsActions) {\n this.container = container;\n this.actions = actions;\n\n if (!document.getElementById(\"bit-devtools-styles\")) {\n const style = document.createElement(\"style\");\n style.id = \"bit-devtools-styles\";\n style.textContent = getDevToolsCSS();\n document.head.appendChild(style);\n }\n\n this.rootElement = document.createElement(\"div\");\n this.rootElement.className = \"bit-devtools-container\";\n this.container.appendChild(this.rootElement);\n\n this.rootElement.addEventListener(\"click\", (e) => {\n const target = e.target as HTMLElement;\n\n // Evento do botão flutuante\n if (target.closest(\".bit-devtools-trigger\")) {\n this.isOpen = !this.isOpen;\n this.render();\n return;\n }\n\n // Eventos dos botões de ação\n const btn = target.closest(\".bit-action-btn\");\n if (btn && !btn.hasAttribute(\"disabled\")) {\n const action = btn.getAttribute(\"data-action\");\n const storeId = btn.getAttribute(\"data-store\");\n\n if (action && storeId) {\n if (action === \"undo\") this.actions.onUndo(storeId);\n if (action === \"redo\") this.actions.onRedo(storeId);\n if (action === \"reset\") this.actions.onReset(storeId);\n }\n }\n });\n }\n\n public updateState(storesState: Record<string, any>) {\n this.currentStoresState = storesState;\n this.render();\n }\n\n private render() {\n const storeEntries = Object.entries(this.currentStoresState);\n if (storeEntries.length === 0) {\n this.rootElement.innerHTML = \"\";\n return;\n }\n\n let panelHtml = \"\";\n\n if (this.isOpen) {\n panelHtml = `\n <div class=\"bit-devtools-panel\">\n <div class=\"bit-devtools-header\">\n <h2><span style=\"font-size: 20px;\">🛠</span> Bit-Form DevTools</h2>\n <span style=\"font-size: 11px; color: #64748b;\">v1.0.0</span>\n </div>\n `;\n\n for (const [id, state] of storeEntries) {\n const hasErrors = Object.keys(state.errors || {}).length > 0;\n\n // Lemos os metadados do histórico que o adaptador injetou\n const meta = state._meta || {\n totalSteps: 0,\n currentIndex: -1,\n canUndo: false,\n canRedo: false,\n };\n const currentStep = meta.currentIndex + 1;\n const totalSteps = meta.totalSteps;\n\n panelHtml += `\n <div class=\"bit-store-block\">\n <div class=\"bit-store-header\">\n <h3 class=\"bit-store-title\">${id}</h3>\n <div class=\"bit-badge-group\">\n <span class=\"bit-badge ${state.isValid ? \"badge-success\" : \"badge-error\"}\">\n ${state.isValid ? \"✓ Valid\" : \"✕ Invalid\"}\n </span>\n ${state.isDirty ? `<span class=\"bit-badge badge-warn\">Dirty</span>` : \"\"}\n ${state.isSubmitting ? `<span class=\"bit-badge badge-info\">⏳ Submitting</span>` : \"\"}\n </div>\n </div>\n\n <span class=\"bit-section-title\">Time Travel (${currentStep}/${totalSteps})</span>\n \n <div class=\"bit-controls\">\n <button class=\"bit-action-btn\" data-action=\"undo\" data-store=\"${id}\" ${meta.canUndo ? \"\" : \"disabled\"}>\n <span>↺</span> Undo\n </button>\n <button class=\"bit-action-btn\" data-action=\"redo\" data-store=\"${id}\" ${meta.canRedo ? \"\" : \"disabled\"}>\n <span>↻</span> Redo\n </button>\n <button class=\"bit-action-btn bit-btn-reset\" data-action=\"reset\" data-store=\"${id}\">\n <span>🗑</span> Reset\n </button>\n </div>\n `;\n\n if (hasErrors) {\n panelHtml += `\n <span class=\"bit-section-title\" style=\"color: #f87171;\">⚠️ Validations Failing</span>\n <pre class=\"bit-error-box\">${JSON.stringify(state.errors, null, 2)}</pre>\n `;\n }\n\n panelHtml += `\n <span class=\"bit-section-title\">Values</span>\n <pre class=\"bit-pre\">${JSON.stringify(state.values, null, 2)}</pre>\n </div>\n `;\n }\n\n panelHtml += `</div>`;\n }\n\n // Botão Flutuante (sempre renderizado)\n const triggerHtml = `\n <button class=\"bit-devtools-trigger\" style=\"transform: ${this.isOpen ? \"scale(0.9)\" : \"scale(1)\"};\" title=\"Abrir DevTools\">\n ${this.isOpen ? \"✖\" : \"Bit\"}\n </button>\n `;\n\n this.rootElement.innerHTML = panelHtml + triggerHtml;\n }\n}\n","import { setupLocalDevTools } from \"./adapters/local\";\nimport { setupRemoteDevTools } from \"./adapters/remote\";\nimport type { BitDevToolsOptions } from \"./types\";\n\nexport type { BitDevToolsOptions };\n\nexport function initDevTools(options: BitDevToolsOptions = {}) {\n const { mode = \"local\", url } = options;\n let containerEl: HTMLElement;\n\n let isAutoCreated = false;\n\n if (typeof options.container === \"string\") {\n const el = document.querySelector<HTMLElement>(options.container);\n if (!el)\n throw new Error(\n `[bit-form] Container '${options.container}' não encontrado na página.`,\n );\n containerEl = el;\n } else if (options.container instanceof HTMLElement) {\n containerEl = options.container;\n } else {\n containerEl = document.createElement(\"div\");\n containerEl.id = \"bit-form-devtools-root\";\n containerEl.style.position = \"fixed\";\n containerEl.style.bottom = \"20px\";\n containerEl.style.right = \"20px\";\n containerEl.style.zIndex = \"9999\";\n containerEl.style.maxHeight = \"80vh\";\n containerEl.style.overflowY = \"auto\";\n containerEl.style.boxShadow = \"0 10px 25px rgba(0,0,0,0.1)\";\n document.body.appendChild(containerEl);\n isAutoCreated = true;\n }\n\n let adapterInstance: any;\n\n if (mode === \"local\") {\n console.log(\"[bit-form] DevTools iniciado em modo Local.\");\n adapterInstance = setupLocalDevTools(containerEl);\n } else if (mode === \"remote\") {\n console.log(\"[bit-form] DevTools iniciado em modo Remote.\");\n adapterInstance = setupRemoteDevTools(containerEl, url);\n } else {\n throw new Error(`[bit-form] Modo DevTools inválido: ${mode}`);\n }\n\n return {\n ...adapterInstance,\n destroy: () => {\n if (adapterInstance && typeof adapterInstance.destroy === \"function\") {\n adapterInstance.destroy();\n }\n\n if (isAutoCreated && containerEl.parentNode) {\n containerEl.parentNode.removeChild(containerEl);\n } else {\n containerEl.innerHTML = \"\";\n }\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/core/store/bus.ts","../src/core/utils.ts","../src/devtools/ui/styles.ts","../src/devtools/ui/index.ts","../src/devtools/init-dev-tools.ts"],"names":["rootGlobal","id","state","fn","bitBus","deepClone","obj","item","clone","key","valueEqual","a","b","deepEqual","keysA","keysB","collectDirtyPaths","initial","prefix","result","allKeys","k","p"],"mappings":"AAaA,+wBAAMA,CAAAA,CACJ,OAAO,UAAA,CAAe,GAAA,CAClB,UAAA,CACE,OAAO,MAAA,CAAW,GAAA,CAAc,MAAA,CAAS,MAAA,CAE5CA,CAAAA,CAAW,YAAA,EAAA,CACdA,CAAAA,CAAW,YAAA,CAAe,CACxB,MAAA,CAAQ,CAAC,CAAA,CACT,SAAA,CAAW,IAAI,GAAA,CAEf,QAAA,CAASC,CAAAA,CAAYC,CAAAA,CAAY,CAC/B,IAAA,CAAK,SAAA,CAAU,OAAA,CAASC,CAAAA,EAAuBA,CAAAA,CAAGF,CAAAA,CAAIC,CAAK,CAAC,CAC9D,CAAA,CAEA,SAAA,CAAUC,CAAAA,CAAoB,CAC5B,OAAA,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIA,CAAE,CAAA,CACd,CAAA,CAAA,EAAM,CAC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A;AAAA;AAAA;AAAA;AAAA;AAAA;ACkES,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBG,MAAA;AAAA;AAAA;AAGyB,0CAAA;AAAA;AAE0C,uCAAA;AAC7B,kBAAA;AAAA;AAE6B,gBAAA;AACY,gBAAA;AAAA;AAAA;AAAA;AAIhB,yDAAA;AAAA;AAAA;AAG+B,4EAAA;AAAA;AAAA;AAGA,4EAAA;AAAA;AAAA;AAGpB,2FAAA;AAAA;AAAA;AAAA;AAOxE,QAAA;AAAA;AAEuD,uCAAA;AAIzD,UAAA;AAAA;AAEmD,iCAAA;AAAA;AAShD,QAAA;AAC8E,6DAAA;AACnE,QAAA;AAAA;ACjIzB,IAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-4MPIKMTH.cjs","sourcesContent":["export type BitBusListener = (storeId: string, newState: any) => void;\n\ninterface BitFormGlobal {\n stores: Record<string, any>;\n listeners: Set<BitBusListener>;\n dispatch: (storeId: string, state: any) => void;\n subscribe: (fn: BitBusListener) => () => void;\n}\n\ndeclare global {\n var __BIT_FORM__: BitFormGlobal | undefined;\n}\n\nconst rootGlobal =\n typeof globalThis !== \"undefined\"\n ? globalThis\n : ((typeof global !== \"undefined\" ? global : window) as any);\n\nif (!rootGlobal.__BIT_FORM__) {\n rootGlobal.__BIT_FORM__ = {\n stores: {},\n listeners: new Set<BitBusListener>(),\n\n dispatch(id: string, state: any) {\n this.listeners.forEach((fn: BitBusListener) => fn(id, state));\n },\n\n subscribe(fn: BitBusListener) {\n this.listeners.add(fn);\n return () => {\n this.listeners.delete(fn);\n };\n },\n };\n}\n\nexport const bitBus = rootGlobal.__BIT_FORM__ as BitFormGlobal;\n","export function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as any as T;\n }\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags) as any as T;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => deepClone(item)) as any as T;\n }\n\n const clone: any = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone((obj as any)[key]);\n }\n }\n return clone as T;\n}\n\n/**\n * Fast equality for single values. Uses === for primitives, deepEqual for objects/arrays.\n * Prefer over deepEqual when comparing a single field value (e.g. isFieldDirty, getStepStatus).\n */\nexport function valueEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n return deepEqual(a, b);\n}\n\nexport function deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n if (a instanceof RegExp && b instanceof RegExp)\n return a.toString() === b.toString();\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !deepEqual(a[key], b[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Collects all paths where obj differs from initial. Used to rebuild dirtyPaths after full state replacement.\n */\nexport function collectDirtyPaths(\n obj: any,\n initial: any,\n prefix = \"\",\n result: Set<string> = new Set(),\n): Set<string> {\n if (valueEqual(obj, initial)) return result;\n if (\n obj === null ||\n typeof obj !== \"object\" ||\n initial === null ||\n typeof initial !== \"object\"\n ) {\n if (prefix) result.add(prefix);\n return result;\n }\n if (Array.isArray(obj) || Array.isArray(initial)) {\n if (!valueEqual(obj, initial) && prefix) result.add(prefix);\n return result;\n }\n const allKeys = new Set([\n ...Object.keys(obj || {}),\n ...Object.keys(initial || {}),\n ]);\n for (const k of allKeys) {\n const p = prefix ? `${prefix}.${k}` : k;\n collectDirtyPaths((obj as any)?.[k], (initial as any)?.[k], p, result);\n }\n return result;\n}\n\nconst pathCache = new Map<string, string[]>();\n\nexport function getDeepValue(obj: any, path: string): any {\n if (!path) return obj;\n\n const keys = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\n\n let current = obj;\n for (const key of keys) {\n if (current === null || current === undefined) return undefined;\n current = current[key];\n }\n return current;\n}\n\nexport function setDeepValue(obj: any, path: string, value: any): any {\n if (!path) return value;\n\n const keys = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\n\n const result = Array.isArray(obj) ? [...obj] : { ...obj };\n let current = result;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const isNextNumeric = /^\\d+$/.test(nextKey);\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n } else {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n\n return result;\n}\n\nexport function cleanPrefixedKeys(\n obj: Record<string, any>,\n prefix: string,\n): Record<string, any> {\n const newObj: Record<string, any> = {};\n const prefixWithDot = `${prefix}.`;\n\n for (const key in obj) {\n if (key !== prefix && !key.startsWith(prefixWithDot)) {\n newObj[key] = obj[key];\n }\n }\n return newObj;\n}\n\nexport const shiftKeys = (\n obj: Record<string, any>,\n path: string,\n removedIndex: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === removedIndex) return;\n\n if (currentIdx > removedIndex) {\n const newIdx = currentIdx - 1;\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const swapKeys = (\n obj: Record<string, any>,\n path: string,\n indexA: number,\n indexB: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === indexA) {\n const newKey = rest ? `${prefix}${indexB}.${rest}` : `${prefix}${indexB}`;\n newObj[newKey] = obj[key];\n } else if (currentIdx === indexB) {\n const newKey = rest ? `${prefix}${indexA}.${rest}` : `${prefix}${indexA}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const moveKeys = (\n obj: Record<string, any>,\n path: string,\n from: number,\n to: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n let newIdx = currentIdx;\n if (currentIdx === from) {\n newIdx = to;\n } else if (from < to && currentIdx > from && currentIdx <= to) {\n newIdx = currentIdx - 1;\n } else if (from > to && currentIdx >= to && currentIdx < from) {\n newIdx = currentIdx + 1;\n }\n\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n });\n return newObj;\n};\n\n/**\n * Checks if a value looks like a server validation error response.\n * Handles shapes like { email: \"Taken\" }, { errors: { email: [\"Taken\"] } }, etc.\n */\nexport function isValidationErrorShape(\n x: unknown,\n): x is Record<string, string | string[]> {\n if (typeof x !== \"object\" || x === null || Array.isArray(x)) return false;\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return false;\n\n return Object.values(obj as Record<string, unknown>).every(\n (v) =>\n typeof v === \"string\" ||\n (Array.isArray(v) && v.every((i) => typeof i === \"string\")),\n );\n}\n\n/**\n * Extracts server errors in the format expected by setServerErrors.\n */\nexport function extractServerErrors(\n x: unknown,\n): Record<string, string | string[]> {\n if (!isValidationErrorShape(x)) return {};\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n return obj as Record<string, string | string[]>;\n}\n","export function getDevToolsCSS(): string {\n return `\n .bit-devtools-container {\n position: fixed;\n bottom: 20px;\n right: 20px;\n z-index: 9999;\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n }\n\n .bit-devtools-trigger {\n background: #10b981;\n color: #fff;\n border: none;\n border-radius: 50%;\n width: 48px;\n height: 48px;\n cursor: pointer;\n box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);\n font-weight: bold;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n font-size: 16px;\n margin-top: 16px;\n }\n .bit-devtools-trigger:hover { transform: scale(1.05); }\n\n .bit-devtools-panel {\n width: 450px;\n max-height: 80vh;\n background: #0f172a;\n color: #f8fafc;\n border-radius: 8px;\n padding: 16px;\n overflow-y: auto;\n box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5), 0 8px 10px -6px rgba(0,0,0,0.5);\n border: 1px solid #334155;\n display: flex;\n flex-direction: column;\n gap: 16px;\n }\n\n .bit-devtools-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding-bottom: 12px;\n border-bottom: 1px solid #1e293b;\n }\n .bit-devtools-header h2 { margin: 0; font-size: 16px; display: flex; align-items: center; gap: 8px; }\n\n .bit-store-block {\n background: #1e293b;\n border-radius: 6px;\n padding: 12px;\n border: 1px solid #334155;\n }\n\n .bit-store-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 12px;\n }\n .bit-store-title { margin: 0; color: #38bdf8; font-size: 14px; font-weight: bold; }\n\n .bit-badge-group { display: flex; gap: 6px; flex-wrap: wrap; }\n .bit-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: bold; }\n .badge-success { background: rgba(16, 185, 129, 0.2); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.2); }\n .badge-error { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.2); }\n .badge-warn { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.2); }\n .badge-info { background: rgba(56, 189, 248, 0.2); color: #7dd3fc; border: 1px solid rgba(56, 189, 248, 0.2); }\n\n .bit-section-title { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin: 12px 0 4px 0; display: block; }\n\n .bit-controls { display: flex; gap: 6px; margin-bottom: 12px; background: #0f172a; padding: 8px; border-radius: 6px; }\n .bit-action-btn { flex: 1; background: #334155; color: #e2e8f0; border: 1px solid #475569; padding: 6px 0; border-radius: 4px; cursor: pointer; font-size: 11px; display: flex; align-items: center; justify-content: center; gap: 4px; transition: all 0.2s; }\n .bit-action-btn:hover:not(:disabled) { background: #475569; }\n .bit-action-btn:disabled { opacity: 0.5; cursor: not-allowed; }\n .bit-btn-reset { color: #fca5a5; border-color: rgba(239,68,68,0.3); }\n .bit-btn-reset:hover { background: rgba(239,68,68,0.1) !important; }\n\n pre.bit-pre { background: #020617; padding: 10px; border-radius: 4px; font-size: 11px; overflow-x: auto; border: 1px solid #1e293b; margin: 0; color: #e2e8f0; }\n pre.bit-error-box { background: rgba(239, 68, 68, 0.05); padding: 10px; border-radius: 4px; font-size: 11px; border: 1px dashed #ef4444; color: #fca5a5; margin: 0; overflow-x: auto; }\n `;\n}\n","import { getDevToolsCSS } from \"./styles\";\nimport type { DevToolsActions } from \"../types\";\n\nexport type { DevToolsActions };\n\nexport class BitFormDevToolsUI {\n private container: HTMLElement;\n private actions: DevToolsActions;\n private rootElement: HTMLDivElement;\n private currentStoresState: Record<string, any> = {};\n private isOpen: boolean = false;\n\n constructor(container: HTMLElement, actions: DevToolsActions) {\n this.container = container;\n this.actions = actions;\n\n if (!document.getElementById(\"bit-devtools-styles\")) {\n const style = document.createElement(\"style\");\n style.id = \"bit-devtools-styles\";\n style.textContent = getDevToolsCSS();\n document.head.appendChild(style);\n }\n\n this.rootElement = document.createElement(\"div\");\n this.rootElement.className = \"bit-devtools-container\";\n this.container.appendChild(this.rootElement);\n\n this.rootElement.addEventListener(\"click\", (e) => {\n const target = e.target as HTMLElement;\n\n // Evento do botão flutuante\n if (target.closest(\".bit-devtools-trigger\")) {\n this.isOpen = !this.isOpen;\n this.render();\n return;\n }\n\n // Eventos dos botões de ação\n const btn = target.closest(\".bit-action-btn\");\n if (btn && !btn.hasAttribute(\"disabled\")) {\n const action = btn.getAttribute(\"data-action\");\n const storeId = btn.getAttribute(\"data-store\");\n\n if (action && storeId) {\n if (action === \"undo\") this.actions.onUndo(storeId);\n if (action === \"redo\") this.actions.onRedo(storeId);\n if (action === \"reset\") this.actions.onReset(storeId);\n }\n }\n });\n }\n\n public updateState(storesState: Record<string, any>) {\n this.currentStoresState = storesState;\n this.render();\n }\n\n private render() {\n const storeEntries = Object.entries(this.currentStoresState);\n if (storeEntries.length === 0) {\n this.rootElement.innerHTML = \"\";\n return;\n }\n\n let panelHtml = \"\";\n\n if (this.isOpen) {\n panelHtml = `\n <div class=\"bit-devtools-panel\">\n <div class=\"bit-devtools-header\">\n <h2><span style=\"font-size: 20px;\">🛠</span> Bit-Form DevTools</h2>\n <span style=\"font-size: 11px; color: #64748b;\">v1.0.0</span>\n </div>\n `;\n\n for (const [id, state] of storeEntries) {\n const hasErrors = Object.keys(state.errors || {}).length > 0;\n\n // Lemos os metadados do histórico que o adaptador injetou\n const meta = state._meta || {\n totalSteps: 0,\n currentIndex: -1,\n canUndo: false,\n canRedo: false,\n };\n const currentStep = meta.currentIndex + 1;\n const totalSteps = meta.totalSteps;\n\n panelHtml += `\n <div class=\"bit-store-block\">\n <div class=\"bit-store-header\">\n <h3 class=\"bit-store-title\">${id}</h3>\n <div class=\"bit-badge-group\">\n <span class=\"bit-badge ${state.isValid ? \"badge-success\" : \"badge-error\"}\">\n ${state.isValid ? \"✓ Valid\" : \"✕ Invalid\"}\n </span>\n ${state.isDirty ? `<span class=\"bit-badge badge-warn\">Dirty</span>` : \"\"}\n ${state.isSubmitting ? `<span class=\"bit-badge badge-info\">⏳ Submitting</span>` : \"\"}\n </div>\n </div>\n\n <span class=\"bit-section-title\">Time Travel (${currentStep}/${totalSteps})</span>\n \n <div class=\"bit-controls\">\n <button class=\"bit-action-btn\" data-action=\"undo\" data-store=\"${id}\" ${meta.canUndo ? \"\" : \"disabled\"}>\n <span>↺</span> Undo\n </button>\n <button class=\"bit-action-btn\" data-action=\"redo\" data-store=\"${id}\" ${meta.canRedo ? \"\" : \"disabled\"}>\n <span>↻</span> Redo\n </button>\n <button class=\"bit-action-btn bit-btn-reset\" data-action=\"reset\" data-store=\"${id}\">\n <span>🗑</span> Reset\n </button>\n </div>\n `;\n\n if (hasErrors) {\n panelHtml += `\n <span class=\"bit-section-title\" style=\"color: #f87171;\">⚠️ Validations Failing</span>\n <pre class=\"bit-error-box\">${JSON.stringify(state.errors, null, 2)}</pre>\n `;\n }\n\n panelHtml += `\n <span class=\"bit-section-title\">Values</span>\n <pre class=\"bit-pre\">${JSON.stringify(state.values, null, 2)}</pre>\n </div>\n `;\n }\n\n panelHtml += `</div>`;\n }\n\n // Botão Flutuante (sempre renderizado)\n const triggerHtml = `\n <button class=\"bit-devtools-trigger\" style=\"transform: ${this.isOpen ? \"scale(0.9)\" : \"scale(1)\"};\" title=\"Abrir DevTools\">\n ${this.isOpen ? \"✖\" : \"Bit\"}\n </button>\n `;\n\n this.rootElement.innerHTML = panelHtml + triggerHtml;\n }\n}\n","import { setupLocalDevTools } from \"./adapters/local\";\nimport { setupRemoteDevTools } from \"./adapters/remote\";\nimport type { BitDevToolsOptions } from \"./types\";\n\nexport type { BitDevToolsOptions };\n\nexport function initDevTools(options: BitDevToolsOptions = {}) {\n const { mode = \"local\", url } = options;\n let containerEl: HTMLElement;\n\n let isAutoCreated = false;\n\n if (typeof options.container === \"string\") {\n const el = document.querySelector<HTMLElement>(options.container);\n if (!el)\n throw new Error(\n `[bit-form] Container '${options.container}' não encontrado na página.`,\n );\n containerEl = el;\n } else if (options.container instanceof HTMLElement) {\n containerEl = options.container;\n } else {\n containerEl = document.createElement(\"div\");\n containerEl.id = \"bit-form-devtools-root\";\n containerEl.style.position = \"fixed\";\n containerEl.style.bottom = \"20px\";\n containerEl.style.right = \"20px\";\n containerEl.style.zIndex = \"9999\";\n containerEl.style.maxHeight = \"80vh\";\n containerEl.style.overflowY = \"auto\";\n containerEl.style.boxShadow = \"0 10px 25px rgba(0,0,0,0.1)\";\n document.body.appendChild(containerEl);\n isAutoCreated = true;\n }\n\n let adapterInstance: any;\n\n if (mode === \"local\") {\n console.log(\"[bit-form] DevTools iniciado em modo Local.\");\n adapterInstance = setupLocalDevTools(containerEl);\n } else if (mode === \"remote\") {\n console.log(\"[bit-form] DevTools iniciado em modo Remote.\");\n adapterInstance = setupRemoteDevTools(containerEl, url);\n } else {\n throw new Error(`[bit-form] Modo DevTools inválido: ${mode}`);\n }\n\n return {\n ...adapterInstance,\n destroy: () => {\n if (adapterInstance && typeof adapterInstance.destroy === \"function\") {\n adapterInstance.destroy();\n }\n\n if (isAutoCreated && containerEl.parentNode) {\n containerEl.parentNode.removeChild(containerEl);\n } else {\n containerEl.innerHTML = \"\";\n }\n },\n };\n}\n"]}
@@ -1,2 +1,2 @@
1
- import{d as T,e as B,h as I,i as x}from"./chunk-4KRTZKIQ.js";import{createContext as M,useContext as A}from"react";import{jsx as O}from"react/jsx-runtime";var D=M(null),st=({store:t,children:e})=>O(D.Provider,{value:t,children:e}),b=()=>{let t=A(D);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};import{useCallback as y,useSyncExternalStore as q,useMemo as H,useRef as L,useState as R}from"react";function lt(){let t=b(),[e,r]=R(null),[i,a]=R(null),o=L(null),g=y(()=>{let m=t.getState(),d={isValid:m.isValid,isDirty:m.isDirty,isSubmitting:m.isSubmitting};return o.current&&o.current.isValid===d.isValid&&o.current.isDirty===d.isDirty&&o.current.isSubmitting===d.isSubmitting?o.current:(o.current=d,d)},[t]),l=q(t.subscribe.bind(t),g,g),s=y(m=>d=>(d?.preventDefault?.(),t.submit(m)),[t]),n=y(m=>d=>(d?.preventDefault?.(),r(null),t.submit(async(j,C)=>{try{let f=await m(j,C);a(f),r(null)}catch(f){I(f)?t.setServerErrors(x(f)):r(f instanceof Error?f:new Error(String(f)))}})),[t]),S=y(()=>{t.reset(),r(null),a(null)},[t]),u=y(()=>t.getState().values,[t]),p=y(()=>t.getState().errors,[t]),h=y(()=>t.getState().touched,[t]),v=y(()=>t.getDirtyValues(),[t]);return{meta:H(()=>({...l,submitError:e,lastResponse:i}),[l,e,i]),getValues:u,getErrors:p,getTouched:h,getDirtyValues:v,submit:s,onSubmit:n,reset:S,setField:t.setField.bind(t),blurField:t.blurField.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),mutations:{pushItem:t.pushItem.bind(t),removeItem:t.removeItem.bind(t),prependItem:t.prependItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t)}}}import{useCallback as U,useSyncExternalStore as W,useState as _,useMemo as w,useEffect as $}from"react";var P=()=>Math.random().toString(36).substring(2,9);function ft(t){let e=b(),r=U(()=>{let s=e.getState(),n=B(s.values,t);return Array.isArray(n)?n:[]},[e,t]),i=W(e.subscribe.bind(e),r,r),[a,o]=_(()=>i.map(P));$(()=>{i.length!==a.length&&o(s=>{if(i.length>s.length){let n=i.length-s.length;return[...s,...Array(n).fill(null).map(P)]}return s.slice(0,i.length)})},[i.length]);let g=w(()=>({append:s=>{o(n=>[...n,P()]),e.pushItem(t,s)},prepend:s=>{o(n=>[P(),...n]),e.prependItem(t,s)},insert:(s,n)=>{o(S=>{let u=[...S];return u.splice(s,0,P()),u}),e.insertItem(t,s,n)},remove:s=>{o(n=>n.filter((S,u)=>u!==s)),e.removeItem(t,s)},move:(s,n)=>{o(S=>{let u=[...S],[p]=u.splice(s,1);return u.splice(n,0,p),u}),e.moveItem(t,s,n)},swap:(s,n)=>{o(S=>{let u=[...S];return[u[s],u[n]]=[u[n],u[s]],u}),e.swapItems(t,s,n)},replace:s=>{o(s.map(P)),e.setField(t,s)},clear:()=>{o([]),e.setField(t,[])}}),[e,t]);return{fields:w(()=>i.map((s,n)=>({key:a[n]||`temp-${n}`,value:s,index:n})),[i,a]),length:i.length,...g}}import{useCallback as E,useSyncExternalStore as z,useRef as G}from"react";function Pt(t){let e=b(),r=G(null),i=E(()=>{let l=e.getStepStatus(t);return r.current&&r.current.hasErrors===l.hasErrors&&r.current.isDirty===l.isDirty&&Object.keys(r.current.errors).length===Object.keys(l.errors).length&&Object.entries(l.errors).every(([s,n])=>r.current.errors[s]===n)?r.current:(r.current=l,l)},[e,t]),a=z(e.subscribe.bind(e),i,i),o=E(async()=>{let l=await e.validate({scope:t}),s=e.getStepErrors(t);return{valid:l,errors:s}},[e,t]),g=E(()=>e.getStepErrors(t),[e,t]);return{scopeName:t,status:a,errors:a.errors,validate:o,getErrors:g,isValid:!a.hasErrors,isDirty:a.isDirty}}import{useCallback as F,useSyncExternalStore as J,useRef as K,useState as Q}from"react";function Tt(t){let e=b(),[r,i]=Q(0),a=t[r]??"",o=K(null),g=F(()=>{let c=e.getStepStatus(a);return o.current&&o.current.hasErrors===c.hasErrors&&o.current.isDirty===c.isDirty&&Object.keys(o.current.errors).length===Object.keys(c.errors).length&&Object.entries(c.errors).every(([m,d])=>o.current.errors[m]===d)?o.current:(o.current=c,c)},[e,a]),l=J(e.subscribe.bind(e),g,g),s=F(async()=>{let c=await e.validate({scope:a}),m=e.getStepErrors(a);return{valid:c,errors:m}},[e,a]),n=F(()=>e.getStepErrors(a),[e,a]),S=F(async()=>{let c=await e.validate({scope:a});if(c)i(m=>Math.min(m+1,t.length-1));else{let m=e.getStepErrors(a),d=Object.keys(m);d.length>0&&e.markFieldsTouched(d)}return c},[e,a,t.length]),u=F(()=>{i(c=>Math.max(c-1,0))},[]),p=F(c=>{i(Math.max(0,Math.min(c-1,t.length-1)))},[t.length]),h=r===0,v=r>=t.length-1;return{step:r+1,stepIndex:r,scope:a,next:S,prev:u,goTo:p,isFirst:h,isLast:v,status:l,errors:l.errors,isValid:!l.hasErrors,isDirty:l.isDirty,validate:s,getErrors:n}}import{useCallback as k,useSyncExternalStore as X,useRef as Y}from"react";function jt(t){let e=b(),r=Y(null),i=k(()=>{let o=B(e.getState().values,t);return r.current!==null&&T(r.current,o)?r.current:(r.current=o,o)},[e,t]),a=k(o=>e.subscribe(o),[e]);return X(a,i,i)}import{useCallback as V,useSyncExternalStore as Z,useRef as N,useEffect as tt}from"react";function Ut(t,e){let r=b(),i=N(null);tt(()=>(e&&r.registerField(t,e),()=>{r.unregisterField&&r.unregisterField(t)}),[r,t,e]);let a=V(()=>{let n=r.getState(),S=B(n.values,t),u=n.errors[t],p=!!n.touched[t],h=r.isHidden(t),v=r.isRequired(t),c=r.isFieldDirty(t),m=r.isFieldValidating(t);if(i.current&&i.current.value===S&&i.current.error===u&&i.current.touched===p&&i.current.isHidden===h&&i.current.isRequired===v&&i.current.isDirty===c&&i.current.isValidating===m)return i.current;let d={value:S,error:u,touched:p,isHidden:h,isRequired:v,isDirty:c,isValidating:m};return i.current=d,d},[r,t]),o=V(n=>r.subscribe(n),[r]),g=Z(o,a,a),l=V(n=>r.setField(t,n),[r,t]),s=V(()=>r.blurField(t),[r,t]);return{fieldState:g,setValue:l,setBlur:s,store:r}}export{st as a,b,lt as c,Ut as d,ft as e,Pt as f,Tt as g,jt as h};
2
- //# sourceMappingURL=chunk-JEVGTLOM.js.map
1
+ import{d as T,e as B,h as I,i as x}from"./chunk-ZWLZ4XDF.js";import{createContext as M,useContext as A}from"react";import{jsx as O}from"react/jsx-runtime";var D=M(null),st=({store:t,children:e})=>O(D.Provider,{value:t,children:e}),b=()=>{let t=A(D);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};import{useCallback as y,useSyncExternalStore as q,useMemo as H,useRef as L,useState as R}from"react";function lt(){let t=b(),[e,r]=R(null),[i,a]=R(null),o=L(null),g=y(()=>{let m=t.getState(),d={isValid:m.isValid,isDirty:m.isDirty,isSubmitting:m.isSubmitting};return o.current&&o.current.isValid===d.isValid&&o.current.isDirty===d.isDirty&&o.current.isSubmitting===d.isSubmitting?o.current:(o.current=d,d)},[t]),l=q(t.subscribe.bind(t),g,g),s=y(m=>d=>(d?.preventDefault?.(),t.submit(m)),[t]),n=y(m=>d=>(d?.preventDefault?.(),r(null),t.submit(async(j,C)=>{try{let f=await m(j,C);a(f),r(null)}catch(f){I(f)?t.setServerErrors(x(f)):r(f instanceof Error?f:new Error(String(f)))}})),[t]),S=y(()=>{t.reset(),r(null),a(null)},[t]),u=y(()=>t.getState().values,[t]),p=y(()=>t.getState().errors,[t]),h=y(()=>t.getState().touched,[t]),v=y(()=>t.getDirtyValues(),[t]);return{meta:H(()=>({...l,submitError:e,lastResponse:i}),[l,e,i]),getValues:u,getErrors:p,getTouched:h,getDirtyValues:v,submit:s,onSubmit:n,reset:S,setField:t.setField.bind(t),blurField:t.blurField.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),mutations:{pushItem:t.pushItem.bind(t),removeItem:t.removeItem.bind(t),prependItem:t.prependItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t)}}}import{useCallback as U,useSyncExternalStore as W,useState as _,useMemo as w,useEffect as $}from"react";var P=()=>Math.random().toString(36).substring(2,9);function ft(t){let e=b(),r=U(()=>{let s=e.getState(),n=B(s.values,t);return Array.isArray(n)?n:[]},[e,t]),i=W(e.subscribe.bind(e),r,r),[a,o]=_(()=>i.map(P));$(()=>{i.length!==a.length&&o(s=>{if(i.length>s.length){let n=i.length-s.length;return[...s,...Array(n).fill(null).map(P)]}return s.slice(0,i.length)})},[i.length]);let g=w(()=>({append:s=>{o(n=>[...n,P()]),e.pushItem(t,s)},prepend:s=>{o(n=>[P(),...n]),e.prependItem(t,s)},insert:(s,n)=>{o(S=>{let u=[...S];return u.splice(s,0,P()),u}),e.insertItem(t,s,n)},remove:s=>{o(n=>n.filter((S,u)=>u!==s)),e.removeItem(t,s)},move:(s,n)=>{o(S=>{let u=[...S],[p]=u.splice(s,1);return u.splice(n,0,p),u}),e.moveItem(t,s,n)},swap:(s,n)=>{o(S=>{let u=[...S];return[u[s],u[n]]=[u[n],u[s]],u}),e.swapItems(t,s,n)},replace:s=>{o(s.map(P)),e.setField(t,s)},clear:()=>{o([]),e.setField(t,[])}}),[e,t]);return{fields:w(()=>i.map((s,n)=>({key:a[n]||`temp-${n}`,value:s,index:n})),[i,a]),length:i.length,...g}}import{useCallback as E,useSyncExternalStore as z,useRef as G}from"react";function Pt(t){let e=b(),r=G(null),i=E(()=>{let l=e.getStepStatus(t);return r.current&&r.current.hasErrors===l.hasErrors&&r.current.isDirty===l.isDirty&&Object.keys(r.current.errors).length===Object.keys(l.errors).length&&Object.entries(l.errors).every(([s,n])=>r.current.errors[s]===n)?r.current:(r.current=l,l)},[e,t]),a=z(e.subscribe.bind(e),i,i),o=E(async()=>{let l=await e.validate({scope:t}),s=e.getStepErrors(t);return{valid:l,errors:s}},[e,t]),g=E(()=>e.getStepErrors(t),[e,t]);return{scopeName:t,status:a,errors:a.errors,validate:o,getErrors:g,isValid:!a.hasErrors,isDirty:a.isDirty}}import{useCallback as F,useSyncExternalStore as J,useRef as K,useState as Q}from"react";function Tt(t){let e=b(),[r,i]=Q(0),a=t[r]??"",o=K(null),g=F(()=>{let c=e.getStepStatus(a);return o.current&&o.current.hasErrors===c.hasErrors&&o.current.isDirty===c.isDirty&&Object.keys(o.current.errors).length===Object.keys(c.errors).length&&Object.entries(c.errors).every(([m,d])=>o.current.errors[m]===d)?o.current:(o.current=c,c)},[e,a]),l=J(e.subscribe.bind(e),g,g),s=F(async()=>{let c=await e.validate({scope:a}),m=e.getStepErrors(a);return{valid:c,errors:m}},[e,a]),n=F(()=>e.getStepErrors(a),[e,a]),S=F(async()=>{let c=await e.validate({scope:a});if(c)i(m=>Math.min(m+1,t.length-1));else{let m=e.getStepErrors(a),d=Object.keys(m);d.length>0&&e.markFieldsTouched(d)}return c},[e,a,t.length]),u=F(()=>{i(c=>Math.max(c-1,0))},[]),p=F(c=>{i(Math.max(0,Math.min(c-1,t.length-1)))},[t.length]),h=r===0,v=r>=t.length-1;return{step:r+1,stepIndex:r,scope:a,next:S,prev:u,goTo:p,isFirst:h,isLast:v,status:l,errors:l.errors,isValid:!l.hasErrors,isDirty:l.isDirty,validate:s,getErrors:n}}import{useCallback as k,useSyncExternalStore as X,useRef as Y}from"react";function jt(t){let e=b(),r=Y(null),i=k(()=>{let o=B(e.getState().values,t);return r.current!==null&&T(r.current,o)?r.current:(r.current=o,o)},[e,t]),a=k(o=>e.subscribe(o),[e]);return X(a,i,i)}import{useCallback as V,useSyncExternalStore as Z,useRef as N,useEffect as tt}from"react";function Ut(t,e){let r=b(),i=N(null);tt(()=>(e&&r.registerField(t,e),()=>{r.unregisterField&&r.unregisterField(t)}),[r,t,e]);let a=V(()=>{let n=r.getState(),S=B(n.values,t),u=n.errors[t],p=!!n.touched[t],h=r.isHidden(t),v=r.isRequired(t),c=r.isFieldDirty(t),m=r.isFieldValidating(t);if(i.current&&i.current.value===S&&i.current.error===u&&i.current.touched===p&&i.current.isHidden===h&&i.current.isRequired===v&&i.current.isDirty===c&&i.current.isValidating===m)return i.current;let d={value:S,error:u,touched:p,isHidden:h,isRequired:v,isDirty:c,isValidating:m};return i.current=d,d},[r,t]),o=V(n=>r.subscribe(n),[r]),g=Z(o,a,a),l=V(n=>r.setField(t,n),[r,t]),s=V(()=>r.blurField(t),[r,t]);return{fieldState:g,setValue:l,setBlur:s,store:r}}export{st as a,b,lt as c,Ut as d,ft as e,Pt as f,Tt as g,jt as h};
2
+ //# sourceMappingURL=chunk-OZOSKSJA.js.map
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkK3DCDRWBcjs = require('./chunk-K3DCDRWB.cjs');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var D=_react.createContext.call(void 0, null),st= exports.a =({store:t,children:e})=>_jsxruntime.jsx.call(void 0, D.Provider,{value:t,children:e}),b= exports.b =()=>{let t=_react.useContext.call(void 0, D);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};function lt(){let t=b(),[e,r]=_react.useState.call(void 0, null),[i,a]=_react.useState.call(void 0, null),o=_react.useRef.call(void 0, null),g=_react.useCallback.call(void 0, ()=>{let m=t.getState(),d={isValid:m.isValid,isDirty:m.isDirty,isSubmitting:m.isSubmitting};return o.current&&o.current.isValid===d.isValid&&o.current.isDirty===d.isDirty&&o.current.isSubmitting===d.isSubmitting?o.current:(o.current=d,d)},[t]),l=_react.useSyncExternalStore.call(void 0, t.subscribe.bind(t),g,g),s=_react.useCallback.call(void 0, m=>d=>(_optionalChain([d, 'optionalAccess', _2 => _2.preventDefault, 'optionalCall', _3 => _3()]),t.submit(m)),[t]),n=_react.useCallback.call(void 0, m=>d=>(_optionalChain([d, 'optionalAccess', _4 => _4.preventDefault, 'optionalCall', _5 => _5()]),r(null),t.submit(async(j,C)=>{try{let f=await m(j,C);a(f),r(null)}catch(f){_chunkK3DCDRWBcjs.h.call(void 0, f)?t.setServerErrors(_chunkK3DCDRWBcjs.i.call(void 0, f)):r(f instanceof Error?f:new Error(String(f)))}})),[t]),S=_react.useCallback.call(void 0, ()=>{t.reset(),r(null),a(null)},[t]),u=_react.useCallback.call(void 0, ()=>t.getState().values,[t]),p=_react.useCallback.call(void 0, ()=>t.getState().errors,[t]),h=_react.useCallback.call(void 0, ()=>t.getState().touched,[t]),v=_react.useCallback.call(void 0, ()=>t.getDirtyValues(),[t]);return{meta:_react.useMemo.call(void 0, ()=>({...l,submitError:e,lastResponse:i}),[l,e,i]),getValues:u,getErrors:p,getTouched:h,getDirtyValues:v,submit:s,onSubmit:n,reset:S,setField:t.setField.bind(t),blurField:t.blurField.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),mutations:{pushItem:t.pushItem.bind(t),removeItem:t.removeItem.bind(t),prependItem:t.prependItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t)}}}var P=()=>Math.random().toString(36).substring(2,9);function ft(t){let e=b(),r=_react.useCallback.call(void 0, ()=>{let s=e.getState(),n=_chunkK3DCDRWBcjs.e.call(void 0, s.values,t);return Array.isArray(n)?n:[]},[e,t]),i=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),r,r),[a,o]=_react.useState.call(void 0, ()=>i.map(P));_react.useEffect.call(void 0, ()=>{i.length!==a.length&&o(s=>{if(i.length>s.length){let n=i.length-s.length;return[...s,...Array(n).fill(null).map(P)]}return s.slice(0,i.length)})},[i.length]);let g=_react.useMemo.call(void 0, ()=>({append:s=>{o(n=>[...n,P()]),e.pushItem(t,s)},prepend:s=>{o(n=>[P(),...n]),e.prependItem(t,s)},insert:(s,n)=>{o(S=>{let u=[...S];return u.splice(s,0,P()),u}),e.insertItem(t,s,n)},remove:s=>{o(n=>n.filter((S,u)=>u!==s)),e.removeItem(t,s)},move:(s,n)=>{o(S=>{let u=[...S],[p]=u.splice(s,1);return u.splice(n,0,p),u}),e.moveItem(t,s,n)},swap:(s,n)=>{o(S=>{let u=[...S];return[u[s],u[n]]=[u[n],u[s]],u}),e.swapItems(t,s,n)},replace:s=>{o(s.map(P)),e.setField(t,s)},clear:()=>{o([]),e.setField(t,[])}}),[e,t]);return{fields:_react.useMemo.call(void 0, ()=>i.map((s,n)=>({key:a[n]||`temp-${n}`,value:s,index:n})),[i,a]),length:i.length,...g}}function Pt(t){let e=b(),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, ()=>{let l=e.getStepStatus(t);return r.current&&r.current.hasErrors===l.hasErrors&&r.current.isDirty===l.isDirty&&Object.keys(r.current.errors).length===Object.keys(l.errors).length&&Object.entries(l.errors).every(([s,n])=>r.current.errors[s]===n)?r.current:(r.current=l,l)},[e,t]),a=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),i,i),o=_react.useCallback.call(void 0, async()=>{let l=await e.validate({scope:t}),s=e.getStepErrors(t);return{valid:l,errors:s}},[e,t]),g=_react.useCallback.call(void 0, ()=>e.getStepErrors(t),[e,t]);return{scopeName:t,status:a,errors:a.errors,validate:o,getErrors:g,isValid:!a.hasErrors,isDirty:a.isDirty}}function Tt(t){let e=b(),[r,i]=_react.useState.call(void 0, 0),a=_nullishCoalesce(t[r], () => ("")),o=_react.useRef.call(void 0, null),g=_react.useCallback.call(void 0, ()=>{let c=e.getStepStatus(a);return o.current&&o.current.hasErrors===c.hasErrors&&o.current.isDirty===c.isDirty&&Object.keys(o.current.errors).length===Object.keys(c.errors).length&&Object.entries(c.errors).every(([m,d])=>o.current.errors[m]===d)?o.current:(o.current=c,c)},[e,a]),l=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),g,g),s=_react.useCallback.call(void 0, async()=>{let c=await e.validate({scope:a}),m=e.getStepErrors(a);return{valid:c,errors:m}},[e,a]),n=_react.useCallback.call(void 0, ()=>e.getStepErrors(a),[e,a]),S=_react.useCallback.call(void 0, async()=>{let c=await e.validate({scope:a});if(c)i(m=>Math.min(m+1,t.length-1));else{let m=e.getStepErrors(a),d=Object.keys(m);d.length>0&&e.markFieldsTouched(d)}return c},[e,a,t.length]),u=_react.useCallback.call(void 0, ()=>{i(c=>Math.max(c-1,0))},[]),p=_react.useCallback.call(void 0, c=>{i(Math.max(0,Math.min(c-1,t.length-1)))},[t.length]),h=r===0,v=r>=t.length-1;return{step:r+1,stepIndex:r,scope:a,next:S,prev:u,goTo:p,isFirst:h,isLast:v,status:l,errors:l.errors,isValid:!l.hasErrors,isDirty:l.isDirty,validate:s,getErrors:n}}function jt(t){let e=b(),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, ()=>{let o=_chunkK3DCDRWBcjs.e.call(void 0, e.getState().values,t);return r.current!==null&&_chunkK3DCDRWBcjs.d.call(void 0, r.current,o)?r.current:(r.current=o,o)},[e,t]),a=_react.useCallback.call(void 0, o=>e.subscribe(o),[e]);return _react.useSyncExternalStore.call(void 0, a,i,i)}function Ut(t,e){let r=b(),i=_react.useRef.call(void 0, null);_react.useEffect.call(void 0, ()=>(e&&r.registerField(t,e),()=>{r.unregisterField&&r.unregisterField(t)}),[r,t,e]);let a=_react.useCallback.call(void 0, ()=>{let n=r.getState(),S=_chunkK3DCDRWBcjs.e.call(void 0, n.values,t),u=n.errors[t],p=!!n.touched[t],h=r.isHidden(t),v=r.isRequired(t),c=r.isFieldDirty(t),m=r.isFieldValidating(t);if(i.current&&i.current.value===S&&i.current.error===u&&i.current.touched===p&&i.current.isHidden===h&&i.current.isRequired===v&&i.current.isDirty===c&&i.current.isValidating===m)return i.current;let d={value:S,error:u,touched:p,isHidden:h,isRequired:v,isDirty:c,isValidating:m};return i.current=d,d},[r,t]),o=_react.useCallback.call(void 0, n=>r.subscribe(n),[r]),g=_react.useSyncExternalStore.call(void 0, o,a,a),l=_react.useCallback.call(void 0, n=>r.setField(t,n),[r,t]),s=_react.useCallback.call(void 0, ()=>r.blurField(t),[r,t]);return{fieldState:g,setValue:l,setBlur:s,store:r}}exports.a = st; exports.b = b; exports.c = lt; exports.d = Ut; exports.e = ft; exports.f = Pt; exports.g = Tt; exports.h = jt;
2
- //# sourceMappingURL=chunk-P3XTUPHK.cjs.map
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunk4MPIKMTHcjs = require('./chunk-4MPIKMTH.cjs');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var D=_react.createContext.call(void 0, null),st= exports.a =({store:t,children:e})=>_jsxruntime.jsx.call(void 0, D.Provider,{value:t,children:e}),b= exports.b =()=>{let t=_react.useContext.call(void 0, D);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};function lt(){let t=b(),[e,r]=_react.useState.call(void 0, null),[i,a]=_react.useState.call(void 0, null),o=_react.useRef.call(void 0, null),g=_react.useCallback.call(void 0, ()=>{let m=t.getState(),d={isValid:m.isValid,isDirty:m.isDirty,isSubmitting:m.isSubmitting};return o.current&&o.current.isValid===d.isValid&&o.current.isDirty===d.isDirty&&o.current.isSubmitting===d.isSubmitting?o.current:(o.current=d,d)},[t]),l=_react.useSyncExternalStore.call(void 0, t.subscribe.bind(t),g,g),s=_react.useCallback.call(void 0, m=>d=>(_optionalChain([d, 'optionalAccess', _2 => _2.preventDefault, 'optionalCall', _3 => _3()]),t.submit(m)),[t]),n=_react.useCallback.call(void 0, m=>d=>(_optionalChain([d, 'optionalAccess', _4 => _4.preventDefault, 'optionalCall', _5 => _5()]),r(null),t.submit(async(j,C)=>{try{let f=await m(j,C);a(f),r(null)}catch(f){_chunk4MPIKMTHcjs.h.call(void 0, f)?t.setServerErrors(_chunk4MPIKMTHcjs.i.call(void 0, f)):r(f instanceof Error?f:new Error(String(f)))}})),[t]),S=_react.useCallback.call(void 0, ()=>{t.reset(),r(null),a(null)},[t]),u=_react.useCallback.call(void 0, ()=>t.getState().values,[t]),p=_react.useCallback.call(void 0, ()=>t.getState().errors,[t]),h=_react.useCallback.call(void 0, ()=>t.getState().touched,[t]),v=_react.useCallback.call(void 0, ()=>t.getDirtyValues(),[t]);return{meta:_react.useMemo.call(void 0, ()=>({...l,submitError:e,lastResponse:i}),[l,e,i]),getValues:u,getErrors:p,getTouched:h,getDirtyValues:v,submit:s,onSubmit:n,reset:S,setField:t.setField.bind(t),blurField:t.blurField.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),mutations:{pushItem:t.pushItem.bind(t),removeItem:t.removeItem.bind(t),prependItem:t.prependItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t)}}}var P=()=>Math.random().toString(36).substring(2,9);function ft(t){let e=b(),r=_react.useCallback.call(void 0, ()=>{let s=e.getState(),n=_chunk4MPIKMTHcjs.e.call(void 0, s.values,t);return Array.isArray(n)?n:[]},[e,t]),i=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),r,r),[a,o]=_react.useState.call(void 0, ()=>i.map(P));_react.useEffect.call(void 0, ()=>{i.length!==a.length&&o(s=>{if(i.length>s.length){let n=i.length-s.length;return[...s,...Array(n).fill(null).map(P)]}return s.slice(0,i.length)})},[i.length]);let g=_react.useMemo.call(void 0, ()=>({append:s=>{o(n=>[...n,P()]),e.pushItem(t,s)},prepend:s=>{o(n=>[P(),...n]),e.prependItem(t,s)},insert:(s,n)=>{o(S=>{let u=[...S];return u.splice(s,0,P()),u}),e.insertItem(t,s,n)},remove:s=>{o(n=>n.filter((S,u)=>u!==s)),e.removeItem(t,s)},move:(s,n)=>{o(S=>{let u=[...S],[p]=u.splice(s,1);return u.splice(n,0,p),u}),e.moveItem(t,s,n)},swap:(s,n)=>{o(S=>{let u=[...S];return[u[s],u[n]]=[u[n],u[s]],u}),e.swapItems(t,s,n)},replace:s=>{o(s.map(P)),e.setField(t,s)},clear:()=>{o([]),e.setField(t,[])}}),[e,t]);return{fields:_react.useMemo.call(void 0, ()=>i.map((s,n)=>({key:a[n]||`temp-${n}`,value:s,index:n})),[i,a]),length:i.length,...g}}function Pt(t){let e=b(),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, ()=>{let l=e.getStepStatus(t);return r.current&&r.current.hasErrors===l.hasErrors&&r.current.isDirty===l.isDirty&&Object.keys(r.current.errors).length===Object.keys(l.errors).length&&Object.entries(l.errors).every(([s,n])=>r.current.errors[s]===n)?r.current:(r.current=l,l)},[e,t]),a=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),i,i),o=_react.useCallback.call(void 0, async()=>{let l=await e.validate({scope:t}),s=e.getStepErrors(t);return{valid:l,errors:s}},[e,t]),g=_react.useCallback.call(void 0, ()=>e.getStepErrors(t),[e,t]);return{scopeName:t,status:a,errors:a.errors,validate:o,getErrors:g,isValid:!a.hasErrors,isDirty:a.isDirty}}function Tt(t){let e=b(),[r,i]=_react.useState.call(void 0, 0),a=_nullishCoalesce(t[r], () => ("")),o=_react.useRef.call(void 0, null),g=_react.useCallback.call(void 0, ()=>{let c=e.getStepStatus(a);return o.current&&o.current.hasErrors===c.hasErrors&&o.current.isDirty===c.isDirty&&Object.keys(o.current.errors).length===Object.keys(c.errors).length&&Object.entries(c.errors).every(([m,d])=>o.current.errors[m]===d)?o.current:(o.current=c,c)},[e,a]),l=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),g,g),s=_react.useCallback.call(void 0, async()=>{let c=await e.validate({scope:a}),m=e.getStepErrors(a);return{valid:c,errors:m}},[e,a]),n=_react.useCallback.call(void 0, ()=>e.getStepErrors(a),[e,a]),S=_react.useCallback.call(void 0, async()=>{let c=await e.validate({scope:a});if(c)i(m=>Math.min(m+1,t.length-1));else{let m=e.getStepErrors(a),d=Object.keys(m);d.length>0&&e.markFieldsTouched(d)}return c},[e,a,t.length]),u=_react.useCallback.call(void 0, ()=>{i(c=>Math.max(c-1,0))},[]),p=_react.useCallback.call(void 0, c=>{i(Math.max(0,Math.min(c-1,t.length-1)))},[t.length]),h=r===0,v=r>=t.length-1;return{step:r+1,stepIndex:r,scope:a,next:S,prev:u,goTo:p,isFirst:h,isLast:v,status:l,errors:l.errors,isValid:!l.hasErrors,isDirty:l.isDirty,validate:s,getErrors:n}}function jt(t){let e=b(),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, ()=>{let o=_chunk4MPIKMTHcjs.e.call(void 0, e.getState().values,t);return r.current!==null&&_chunk4MPIKMTHcjs.d.call(void 0, r.current,o)?r.current:(r.current=o,o)},[e,t]),a=_react.useCallback.call(void 0, o=>e.subscribe(o),[e]);return _react.useSyncExternalStore.call(void 0, a,i,i)}function Ut(t,e){let r=b(),i=_react.useRef.call(void 0, null);_react.useEffect.call(void 0, ()=>(e&&r.registerField(t,e),()=>{r.unregisterField&&r.unregisterField(t)}),[r,t,e]);let a=_react.useCallback.call(void 0, ()=>{let n=r.getState(),S=_chunk4MPIKMTHcjs.e.call(void 0, n.values,t),u=n.errors[t],p=!!n.touched[t],h=r.isHidden(t),v=r.isRequired(t),c=r.isFieldDirty(t),m=r.isFieldValidating(t);if(i.current&&i.current.value===S&&i.current.error===u&&i.current.touched===p&&i.current.isHidden===h&&i.current.isRequired===v&&i.current.isDirty===c&&i.current.isValidating===m)return i.current;let d={value:S,error:u,touched:p,isHidden:h,isRequired:v,isDirty:c,isValidating:m};return i.current=d,d},[r,t]),o=_react.useCallback.call(void 0, n=>r.subscribe(n),[r]),g=_react.useSyncExternalStore.call(void 0, o,a,a),l=_react.useCallback.call(void 0, n=>r.setField(t,n),[r,t]),s=_react.useCallback.call(void 0, ()=>r.blurField(t),[r,t]);return{fieldState:g,setValue:l,setBlur:s,store:r}}exports.a = st; exports.b = b; exports.c = lt; exports.d = Ut; exports.e = ft; exports.f = Pt; exports.g = Tt; exports.h = jt;
2
+ //# sourceMappingURL=chunk-VCHMCHED.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-P3XTUPHK.cjs","../src/react/context.tsx","../src/react/use-bit-form.ts","../src/react/use-bit-array.ts"],"names":["BitContext","createContext","BitFormProvider","store","children","jsx","useBitStore","useContext","useBitForm","submitError","setSubmitError","useState","lastResponse","setLastResponse","lastMeta","useRef","getMetaSnapshot","useCallback","state","nextMeta","metaState","useSyncExternalStore","submit","onSuccess","e","onSubmit","handler","values","dirtyValues","result","err","isValidationErrorShape","extractServerErrors","reset","getValues","getErrors","getTouched","getDirtyValues","useMemo","generateId","useBitArray","path","getSnapshot","value","getDeepValue","data","ids","setIds","useEffect","prevIds","diff","methods","prev","index","newIds","_","i","from","to","item","indexA","indexB","items"],"mappings":"AAAA,yuBAA6D,8BCAZ,+CAW3C,IARAA,CAAAA,CAAaC,kCAAAA,IAAwC,CAAA,CAE9CC,EAAAA,aAAkB,CAAC,CAC9B,KAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAAA,EAGMC,6BAAAA,CAACL,CAAW,QAAA,CAAX,CAAoB,KAAA,CAAOG,CAAAA,CA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AA,CAAM,QAAA,CAASsC,CAAAA,CAAmCqB,CAAY,CAChE,CAAA,CACA,KAAA,CAAO,CAAA,CAAA,EAAM,CACXf,CAAAA,CAAO,CAAC,CAAC,CAAA,CACT5C,CAAAA,CAAM,QAAA,CAASsC,CAAAA,CAAmC,CAAC,CAAQ,CAC7D,CACF,CAAA,CAAA,CACA,CAACtC,CAAAA,CAAOsC,CAAI,CACd,CAAA,CAYA,MAAO,CACL,MAAA,CAXaH,4BAAAA,CACb,CAAA,EACGO,CAAAA,CAAgB,GAAA,CAAI,CAACc,CAAAA,CAAYN,CAAAA,CAAAA,EAAAA,CAAmB,CACnD,GAAA,CAAKP,CAAAA,CAAIO,CAAK,CAAA,EAAK,CAAA,KAAA,EAAQA,CAAK,CAAA,CAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-P3XTUPHK.cjs","sourcesContent":[null,"import React, { createContext, useContext } from \"react\";\nimport { BitStore } from \"../core/store\";\n\nconst BitContext = createContext<BitStore<any> | null>(null);\n\nexport const BitFormProvider = ({\n store,\n children,\n}: {\n store: BitStore<any>;\n children: React.ReactNode;\n}) => <BitContext.Provider value={store}>{children}</BitContext.Provider>;\n\nexport const useBitStore = <T extends object>() => {\n const store = useContext(BitContext);\n if (!store)\n throw new Error(\n \"BitForm hooks devem ser usados dentro de um BitFormProvider\",\n );\n return store as BitStore<T>;\n};\n","import {\n useCallback,\n useSyncExternalStore,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport { isValidationErrorShape, extractServerErrors } from \"../core/utils\";\n\nexport function useBitForm<T extends object>() {\n const store = useBitStore<T>();\n\n const [submitError, setSubmitError] = useState<Error | null>(null);\n const [lastResponse, setLastResponse] = useState<unknown>(null);\n const lastMeta = useRef<{\n isValid: boolean;\n isDirty: boolean;\n isSubmitting: boolean;\n } | null>(null);\n\n const getMetaSnapshot = useCallback(() => {\n const state = store.getState();\n const nextMeta = {\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n };\n\n if (\n lastMeta.current &&\n lastMeta.current.isValid === nextMeta.isValid &&\n lastMeta.current.isDirty === nextMeta.isDirty &&\n lastMeta.current.isSubmitting === nextMeta.isSubmitting\n ) {\n return lastMeta.current;\n }\n\n lastMeta.current = nextMeta;\n return nextMeta;\n }, [store]);\n\n const metaState = useSyncExternalStore(\n store.subscribe.bind(store),\n getMetaSnapshot,\n getMetaSnapshot,\n );\n\n const submit = useCallback(\n (\n onSuccess: (values: T, dirtyValues?: Partial<T>) => void | Promise<void>,\n ) => {\n return (e?: { preventDefault: () => void }) => {\n e?.preventDefault?.();\n return store.submit(onSuccess);\n };\n },\n [store],\n );\n\n const onSubmit = useCallback(\n (handler: (values: T, dirtyValues?: Partial<T>) => Promise<unknown>) => {\n return (e?: { preventDefault: () => void }) => {\n e?.preventDefault?.();\n setSubmitError(null);\n\n return store.submit(async (values, dirtyValues) => {\n try {\n const result = await handler(values, dirtyValues);\n setLastResponse(result);\n setSubmitError(null);\n } catch (err) {\n if (isValidationErrorShape(err)) {\n store.setServerErrors(extractServerErrors(err));\n } else {\n setSubmitError(\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n }\n });\n };\n },\n [store],\n );\n\n const reset = useCallback(() => {\n store.reset();\n setSubmitError(null);\n setLastResponse(null);\n }, [store]);\n\n const getValues = useCallback(() => store.getState().values, [store]);\n const getErrors = useCallback(() => store.getState().errors, [store]);\n const getTouched = useCallback(() => store.getState().touched, [store]);\n const getDirtyValues = useCallback(() => store.getDirtyValues(), [store]);\n\n const meta = useMemo(\n () => ({\n ...metaState,\n submitError,\n lastResponse,\n }),\n [metaState, submitError, lastResponse],\n );\n\n return {\n // Metadata (grouped)\n meta,\n // Getters\n getValues,\n getErrors,\n getTouched,\n getDirtyValues,\n // Main actions (frequent use - flat)\n submit,\n onSubmit,\n reset,\n setField: store.setField.bind(store),\n blurField: store.blurField.bind(store),\n setValues: store.setValues.bind(store),\n setError: store.setError.bind(store),\n setErrors: store.setErrors.bind(store),\n setServerErrors: store.setServerErrors.bind(store),\n validate: store.validate.bind(store),\n // Array mutations (grouped)\n mutations: {\n pushItem: store.pushItem.bind(store),\n removeItem: store.removeItem.bind(store),\n prependItem: store.prependItem.bind(store),\n insertItem: store.insertItem.bind(store),\n moveItem: store.moveItem.bind(store),\n swapItems: store.swapItems.bind(store),\n },\n };\n}\n","import {\n useCallback,\n useSyncExternalStore,\n useState,\n useMemo,\n useEffect,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n getDeepValue,\n BitArrayPath,\n BitPathValue,\n BitArrayItem,\n BitPath,\n} from \"../core\";\n\nconst generateId = () => Math.random().toString(36).substring(2, 9);\n\nexport function useBitArray<\n TForm extends object = any,\n P extends BitArrayPath<TForm> = BitArrayPath<TForm>,\n>(path: P) {\n const store = useBitStore<TForm>();\n\n type Item = BitArrayItem<BitPathValue<TForm, P>>;\n\n const getSnapshot = useCallback(() => {\n const state = store.getState();\n const value = getDeepValue(state.values, path as string) as\n | BitPathValue<TForm, P>\n | undefined;\n return Array.isArray(value) ? (value as Item[]) : [];\n }, [store, path]);\n\n const data = useSyncExternalStore(\n store.subscribe.bind(store),\n getSnapshot,\n getSnapshot,\n );\n\n const [ids, setIds] = useState<string[]>(() =>\n (data as Item[]).map(generateId),\n );\n\n useEffect(() => {\n if (data.length !== ids.length) {\n setIds((prevIds) => {\n if (data.length > prevIds.length) {\n const diff = data.length - prevIds.length;\n return [...prevIds, ...Array(diff).fill(null).map(generateId)];\n }\n return prevIds.slice(0, data.length);\n });\n }\n }, [data.length]);\n\n const methods = useMemo(\n () => ({\n append: (value: Item) => {\n setIds((prev) => [...prev, generateId()]);\n store.pushItem(path, value);\n },\n prepend: (value: Item) => {\n setIds((prev) => [generateId(), ...prev]);\n store.prependItem(path, value);\n },\n insert: (index: number, value: Item) => {\n setIds((prev) => {\n const newIds = [...prev];\n newIds.splice(index, 0, generateId());\n return newIds;\n });\n store.insertItem(path, index, value);\n },\n remove: (index: number) => {\n setIds((prev) => prev.filter((_, i) => i !== index));\n store.removeItem(path, index);\n },\n move: (from: number, to: number) => {\n setIds((prev) => {\n const newIds = [...prev];\n const [item] = newIds.splice(from, 1);\n newIds.splice(to, 0, item);\n return newIds;\n });\n store.moveItem(path, from, to);\n },\n swap: (indexA: number, indexB: number) => {\n setIds((prev) => {\n const newIds = [...prev];\n [newIds[indexA], newIds[indexB]] = [newIds[indexB], newIds[indexA]];\n return newIds;\n });\n store.swapItems(path, indexA, indexB);\n },\n replace: (items: Item[]) => {\n setIds(items.map(generateId));\n store.setField(path as unknown as BitPath<TForm>, items as any);\n },\n clear: () => {\n setIds([]);\n store.setField(path as unknown as BitPath<TForm>, [] as any);\n },\n }),\n [store, path],\n );\n\n const fields = useMemo(\n () =>\n (data as Item[]).map((item: Item, index: number) => ({\n key: ids[index] || `temp-${index}`,\n value: item,\n index,\n })),\n [data, ids],\n );\n\n return {\n fields,\n length: data.length,\n ...methods,\n };\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-VCHMCHED.cjs","../src/react/context.tsx","../src/react/use-bit-form.ts","../src/react/use-bit-array.ts"],"names":["BitContext","createContext","BitFormProvider","store","children","jsx","useBitStore","useContext","useBitForm","submitError","setSubmitError","useState","lastResponse","setLastResponse","lastMeta","useRef","getMetaSnapshot","useCallback","state","nextMeta","metaState","useSyncExternalStore","submit","onSuccess","e","onSubmit","handler","values","dirtyValues","result","err","isValidationErrorShape","extractServerErrors","reset","getValues","getErrors","getTouched","getDirtyValues","useMemo","generateId","useBitArray","path","getSnapshot","value","getDeepValue","data","ids","setIds","useEffect","prevIds","diff","methods","prev","index","newIds","_","i","from","to","item","indexA","indexB","items"],"mappings":"AAAA,yuBAA6D,8BCAZ,+CAW3C,IARAA,CAAAA,CAAaC,kCAAAA,IAAwC,CAAA,CAE9CC,EAAAA,aAAkB,CAAC,CAC9B,KAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAA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AAAA,CAAOe,CAAAA,CAAM,GAAA,CAAIvB,CAAU,CAAC,CAAA,CAC5BpC,CAAAA,CAAM,QAAA,CAASsC,CAAAA,CAAmCqB,CAAY,CAChE,CAAA,CACA,KAAA,CAAO,CAAA,CAAA,EAAM,CACXf,CAAAA,CAAO,CAAC,CAAC,CAAA,CACT5C,CAAAA,CAAM,QAAA,CAASsC,CAAAA,CAAmC,CAAC,CAAQ,CAC7D,CACF,CAAA,CAAA,CACA,CAACtC,CAAAA,CAAOsC,CAAI,CACd,CAAA,CAYA,MAAO,CACL,MAAA,CAXaH,4BAAAA,CACb,CAAA,EACGO,CAAAA,CAAgB,GAAA,CAAI,CAACc,CAAAA,CAAYN,CAAAA,CAAAA,EAAAA,CAAmB,CACnD,GAAA,CAAKP,CAAAA,CAAIO,CAAK,CAAA,EAAK,CAAA,KAAA,EAAQA,CAAK,CAAA,CAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-VCHMCHED.cjs","sourcesContent":[null,"import React, { createContext, useContext } from \"react\";\nimport { BitStore } from \"../core/store\";\n\nconst BitContext = createContext<BitStore<any> | null>(null);\n\nexport const BitFormProvider = ({\n store,\n children,\n}: {\n store: BitStore<any>;\n children: React.ReactNode;\n}) => <BitContext.Provider value={store}>{children}</BitContext.Provider>;\n\nexport const useBitStore = <T extends object>() => {\n const store = useContext(BitContext);\n if (!store)\n throw new Error(\n \"BitForm hooks devem ser usados dentro de um BitFormProvider\",\n );\n return store as BitStore<T>;\n};\n","import {\n useCallback,\n useSyncExternalStore,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport { isValidationErrorShape, extractServerErrors } from \"../core/utils\";\n\nexport function useBitForm<T extends object>() {\n const store = useBitStore<T>();\n\n const [submitError, setSubmitError] = useState<Error | null>(null);\n const [lastResponse, setLastResponse] = useState<unknown>(null);\n const lastMeta = useRef<{\n isValid: boolean;\n isDirty: boolean;\n isSubmitting: boolean;\n } | null>(null);\n\n const getMetaSnapshot = useCallback(() => {\n const state = store.getState();\n const nextMeta = {\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n };\n\n if (\n lastMeta.current &&\n lastMeta.current.isValid === nextMeta.isValid &&\n lastMeta.current.isDirty === nextMeta.isDirty &&\n lastMeta.current.isSubmitting === nextMeta.isSubmitting\n ) {\n return lastMeta.current;\n }\n\n lastMeta.current = nextMeta;\n return nextMeta;\n }, [store]);\n\n const metaState = useSyncExternalStore(\n store.subscribe.bind(store),\n getMetaSnapshot,\n getMetaSnapshot,\n );\n\n const submit = useCallback(\n (\n onSuccess: (values: T, dirtyValues?: Partial<T>) => void | Promise<void>,\n ) => {\n return (e?: { preventDefault: () => void }) => {\n e?.preventDefault?.();\n return store.submit(onSuccess);\n };\n },\n [store],\n );\n\n const onSubmit = useCallback(\n (handler: (values: T, dirtyValues?: Partial<T>) => Promise<unknown>) => {\n return (e?: { preventDefault: () => void }) => {\n e?.preventDefault?.();\n setSubmitError(null);\n\n return store.submit(async (values, dirtyValues) => {\n try {\n const result = await handler(values, dirtyValues);\n setLastResponse(result);\n setSubmitError(null);\n } catch (err) {\n if (isValidationErrorShape(err)) {\n store.setServerErrors(extractServerErrors(err));\n } else {\n setSubmitError(\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n }\n });\n };\n },\n [store],\n );\n\n const reset = useCallback(() => {\n store.reset();\n setSubmitError(null);\n setLastResponse(null);\n }, [store]);\n\n const getValues = useCallback(() => store.getState().values, [store]);\n const getErrors = useCallback(() => store.getState().errors, [store]);\n const getTouched = useCallback(() => store.getState().touched, [store]);\n const getDirtyValues = useCallback(() => store.getDirtyValues(), [store]);\n\n const meta = useMemo(\n () => ({\n ...metaState,\n submitError,\n lastResponse,\n }),\n [metaState, submitError, lastResponse],\n );\n\n return {\n // Metadata (grouped)\n meta,\n // Getters\n getValues,\n getErrors,\n getTouched,\n getDirtyValues,\n // Main actions (frequent use - flat)\n submit,\n onSubmit,\n reset,\n setField: store.setField.bind(store),\n blurField: store.blurField.bind(store),\n setValues: store.setValues.bind(store),\n setError: store.setError.bind(store),\n setErrors: store.setErrors.bind(store),\n setServerErrors: store.setServerErrors.bind(store),\n validate: store.validate.bind(store),\n // Array mutations (grouped)\n mutations: {\n pushItem: store.pushItem.bind(store),\n removeItem: store.removeItem.bind(store),\n prependItem: store.prependItem.bind(store),\n insertItem: store.insertItem.bind(store),\n moveItem: store.moveItem.bind(store),\n swapItems: store.swapItems.bind(store),\n },\n };\n}\n","import {\n useCallback,\n useSyncExternalStore,\n useState,\n useMemo,\n useEffect,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n getDeepValue,\n BitArrayPath,\n BitPathValue,\n BitArrayItem,\n BitPath,\n} from \"../core\";\n\nconst generateId = () => Math.random().toString(36).substring(2, 9);\n\nexport function useBitArray<\n TForm extends object = any,\n P extends BitArrayPath<TForm> = BitArrayPath<TForm>,\n>(path: P) {\n const store = useBitStore<TForm>();\n\n type Item = BitArrayItem<BitPathValue<TForm, P>>;\n\n const getSnapshot = useCallback(() => {\n const state = store.getState();\n const value = getDeepValue(state.values, path as string) as\n | BitPathValue<TForm, P>\n | undefined;\n return Array.isArray(value) ? (value as Item[]) : [];\n }, [store, path]);\n\n const data = useSyncExternalStore(\n store.subscribe.bind(store),\n getSnapshot,\n getSnapshot,\n );\n\n const [ids, setIds] = useState<string[]>(() =>\n (data as Item[]).map(generateId),\n );\n\n useEffect(() => {\n if (data.length !== ids.length) {\n setIds((prevIds) => {\n if (data.length > prevIds.length) {\n const diff = data.length - prevIds.length;\n return [...prevIds, ...Array(diff).fill(null).map(generateId)];\n }\n return prevIds.slice(0, data.length);\n });\n }\n }, [data.length]);\n\n const methods = useMemo(\n () => ({\n append: (value: Item) => {\n setIds((prev) => [...prev, generateId()]);\n store.pushItem(path, value);\n },\n prepend: (value: Item) => {\n setIds((prev) => [generateId(), ...prev]);\n store.prependItem(path, value);\n },\n insert: (index: number, value: Item) => {\n setIds((prev) => {\n const newIds = [...prev];\n newIds.splice(index, 0, generateId());\n return newIds;\n });\n store.insertItem(path, index, value);\n },\n remove: (index: number) => {\n setIds((prev) => prev.filter((_, i) => i !== index));\n store.removeItem(path, index);\n },\n move: (from: number, to: number) => {\n setIds((prev) => {\n const newIds = [...prev];\n const [item] = newIds.splice(from, 1);\n newIds.splice(to, 0, item);\n return newIds;\n });\n store.moveItem(path, from, to);\n },\n swap: (indexA: number, indexB: number) => {\n setIds((prev) => {\n const newIds = [...prev];\n [newIds[indexA], newIds[indexB]] = [newIds[indexB], newIds[indexA]];\n return newIds;\n });\n store.swapItems(path, indexA, indexB);\n },\n replace: (items: Item[]) => {\n setIds(items.map(generateId));\n store.setField(path as unknown as BitPath<TForm>, items as any);\n },\n clear: () => {\n setIds([]);\n store.setField(path as unknown as BitPath<TForm>, [] as any);\n },\n }),\n [store, path],\n );\n\n const fields = useMemo(\n () =>\n (data as Item[]).map((item: Item, index: number) => ({\n key: ids[index] || `temp-${index}`,\n value: item,\n index,\n })),\n [data, ids],\n );\n\n return {\n fields,\n length: data.length,\n ...methods,\n };\n}\n"]}