@lehnihon/bit-form 1.0.6 → 1.0.7

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.
Files changed (47) hide show
  1. package/README.md +39 -0
  2. package/dist/angular/index.cjs +1 -1
  3. package/dist/angular/index.d.cts +2 -2
  4. package/dist/angular/index.d.ts +2 -2
  5. package/dist/angular/index.js +1 -1
  6. package/dist/{bus-DAwKIiMY.d.cts → bus-DkMkzOXE.d.cts} +4 -6
  7. package/dist/{bus-DAwKIiMY.d.ts → bus-DkMkzOXE.d.ts} +4 -6
  8. package/dist/{chunk-Z6ITPS2B.cjs → chunk-6ISGLRK2.cjs} +2 -2
  9. package/dist/{chunk-Z6ITPS2B.cjs.map → chunk-6ISGLRK2.cjs.map} +1 -1
  10. package/dist/{chunk-6VDQSKUN.cjs → chunk-J3EGU5ZH.cjs} +6 -6
  11. package/dist/{chunk-6VDQSKUN.cjs.map → chunk-J3EGU5ZH.cjs.map} +1 -1
  12. package/dist/{chunk-UFYHEI6S.js → chunk-OA4FCEV2.js} +2 -2
  13. package/dist/{chunk-KA4FAGIX.js → chunk-QU365SAC.js} +6 -6
  14. package/dist/chunk-QU365SAC.js.map +1 -0
  15. package/dist/devtools/bridge.cjs +1 -1
  16. package/dist/devtools/bridge.js +1 -1
  17. package/dist/devtools/index.cjs +1 -1
  18. package/dist/devtools/index.js +1 -1
  19. package/dist/{index-CPKnWBVv.d.ts → index-BXaNeJBk.d.ts} +1 -1
  20. package/dist/{index-BD_l3aH5.d.cts → index-mzR_3Kbx.d.cts} +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.d.cts +3 -3
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +1 -1
  25. package/dist/react/index.cjs +1 -1
  26. package/dist/react/index.d.cts +4 -4
  27. package/dist/react/index.d.ts +4 -4
  28. package/dist/react/index.js +1 -1
  29. package/dist/react-native/index.cjs +1 -1
  30. package/dist/react-native/index.d.cts +4 -4
  31. package/dist/react-native/index.d.ts +4 -4
  32. package/dist/react-native/index.js +1 -1
  33. package/dist/resolvers/joi.d.cts +1 -1
  34. package/dist/resolvers/joi.d.ts +1 -1
  35. package/dist/resolvers/yup.d.cts +1 -1
  36. package/dist/resolvers/yup.d.ts +1 -1
  37. package/dist/resolvers/zod.d.cts +1 -1
  38. package/dist/resolvers/zod.d.ts +1 -1
  39. package/dist/{use-bit-watch-CoCFwS-F.d.ts → use-bit-watch-DEYCmgNf.d.ts} +2 -2
  40. package/dist/{use-bit-watch-BSWy9rG7.d.cts → use-bit-watch-wjK9PF7w.d.cts} +2 -2
  41. package/dist/vue/index.cjs +1 -1
  42. package/dist/vue/index.d.cts +2 -2
  43. package/dist/vue/index.d.ts +2 -2
  44. package/dist/vue/index.js +1 -1
  45. package/package.json +1 -1
  46. package/dist/chunk-KA4FAGIX.js.map +0 -1
  47. /package/dist/{chunk-UFYHEI6S.js.map → chunk-OA4FCEV2.js.map} +0 -0
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
+ <div align="center">
2
+ <img src="logo.png" alt="Bit-Form" width="280" />
3
+ </div>
4
+
5
+ <p align="center">
6
+ <i>Made with ❤️ by <a href="https://github.com/lehnihon">lehnihon</a> & contributors</i>
7
+ </p>
8
+
9
+ <p align="center">
10
+ <a href="https://github.com/lehnihon/bit-form/actions/workflows/ci.yml">
11
+ <img src="https://img.shields.io/github/actions/workflow/status/lehnihon/bit-form/ci.yml?branch=main&label=tests&style=flat-square" alt="tests" />
12
+ </a>
13
+ <a href="https://github.com/lehnihon/bit-form/actions/workflows/ci.yml">
14
+ <img src="https://img.shields.io/github/actions/workflow/status/lehnihon/bit-form/ci.yml?branch=main&label=build&style=flat-square" alt="build" />
15
+ </a>
16
+ <a href="https://www.npmjs.com/package/@lehnihon/bit-form">
17
+ <img src="https://img.shields.io/npm/v/@lehnihon/bit-form?style=flat-square" alt="npm version" />
18
+ </a>
19
+ <a href="https://www.npmjs.com/package/@lehnihon/bit-form">
20
+ <img src="https://img.shields.io/npm/dm/@lehnihon/bit-form?style=flat-square" alt="npm downloads" />
21
+ </a>
22
+ <a href="https://github.com/lehnihon/bit-form/stargazers">
23
+ <img src="https://img.shields.io/github/stars/lehnihon/bit-form?style=flat-square" alt="stars" />
24
+ </a>
25
+ <a href="https://github.com/lehnihon/bit-form/network/members">
26
+ <img src="https://img.shields.io/github/forks/lehnihon/bit-form?style=flat-square" alt="forks" />
27
+ </a>
28
+ <a href="https://github.com/lehnihon/bit-form/issues">
29
+ <img src="https://img.shields.io/github/issues/lehnihon/bit-form?style=flat-square" alt="issues" />
30
+ </a>
31
+ <a href="https://github.com/lehnihon/bit-form/blob/main/LICENSE">
32
+ <img src="https://img.shields.io/npm/l/@lehnihon/bit-form?style=flat-square" alt="license" />
33
+ </a>
34
+ <img src="https://img.shields.io/badge/TypeScript-007ACC?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript" />
35
+ <img src="https://img.shields.io/badge/Vitest-6E9F18?style=flat-square&logo=vitest&logoColor=white" alt="Vitest" />
36
+ </p>
37
+
38
+ ---
39
+
1
40
  # 🛠 Bit-Form
2
41
 
3
42
  **Agnostic and performant form state management**.
@@ -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 _chunk6VDQSKUNcjs = require('../chunk-6VDQSKUN.cjs');var _core = require('@angular/core');var h=new (0, _core.InjectionToken)("BIT_STORE");function C(t){return{provide:h,useValue:t}}function S(){let t=_core.inject.call(void 0, h,{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 $(){let t=S(),e=_core.inject.call(void 0, _core.DestroyRef),o=_core.signal.call(void 0, t.getState()),r=_core.signal.call(void 0, null),n=_core.signal.call(void 0, null),c=t.subscribe(()=>{o.set(t.getState())});e.onDestroy(()=>c());let g=_core.computed.call(void 0, ()=>o().isValid),s=_core.computed.call(void 0, ()=>o().isSubmitting),i=_core.computed.call(void 0, ()=>o().isDirty),d=_core.computed.call(void 0, ()=>(o(),t.canUndo)),u=_core.computed.call(void 0, ()=>(o(),t.canRedo));return{store:t,isValid:g,isSubmitting:s,isDirty:i,canUndo:d,canRedo:u,getValues:()=>o().values,getErrors:()=>o().errors,getTouched:()=>o().touched,submit:B=>f=>(_optionalChain([f, 'optionalAccess', _2 => _2.preventDefault, 'call', _3 => _3()]),_optionalChain([f, 'optionalAccess', _4 => _4.stopPropagation, 'call', _5 => _5()]),t.submit(B)),onSubmit:B=>f=>(_optionalChain([f, 'optionalAccess', _6 => _6.preventDefault, 'call', _7 => _7()]),_optionalChain([f, 'optionalAccess', _8 => _8.stopPropagation, 'call', _9 => _9()]),r.set(null),t.submit(async l=>{try{let a=await B(l);n.set(a),r.set(null)}catch(a){_chunk6VDQSKUNcjs.h.call(void 0, a)?t.setServerErrors(_chunk6VDQSKUNcjs.i.call(void 0, a)):r.set(a instanceof Error?a:new Error(String(a)))}})),submitError:r,lastResponse:n,reset:()=>{t.reset(),r.set(null),n.set(null)},validate:t.validate.bind(t),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),registerMask:t.registerMask.bind(t),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),undo:t.undo.bind(t),redo:t.redo.bind(t)}}function J(t,e,o){let r=_core.inject.call(void 0, h),n=_core.signal.call(void 0, r.getState()),c=r.subscribe(()=>{n.set(r.getState())});_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>{c(),r.unregisterField&&r.unregisterField(t)}),e&&r.registerField(t,e);let g=_core.computed.call(void 0, ()=>_chunk6VDQSKUNcjs.e.call(void 0, n().values,t)),s=_core.computed.call(void 0, ()=>n().errors[t]),i=_core.computed.call(void 0, ()=>!!n().touched[t]),d=_core.computed.call(void 0, ()=>(n(),r.isFieldDirty(t))),u=_core.computed.call(void 0, ()=>(n(),r.isFieldValidating(t))),m=_core.computed.call(void 0, ()=>(n(),r.isHidden(t))),R=_core.computed.call(void 0, ()=>(n(),r.isRequired(t))),V=_core.computed.call(void 0, ()=>i()&&!!s()),b=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _10 => _10.mask]), () => (_optionalChain([r, 'access', _11 => _11.config, 'access', _12 => _12.fields, 'optionalAccess', _13 => _13[t], 'optionalAccess', _14 => _14.mask]))),P=b?typeof b=="string"?r.config.masks[b]:b:void 0,x=_core.computed.call(void 0, ()=>{let a=g();return a==null||a===""?"":P?P.format(a):String(a)}),B=a=>{if(!P){r.setField(t,a);return}let p=String(_nullishCoalesce(a, () => ("")));r.setField(t,P.parse(p))},f=()=>r.blurField(t),l=_core.computed.call(void 0, ()=>({isDirty:d(),isValidating:u(),isHidden:m(),isRequired:R(),hasError:!!s()}));return{value:g,displayValue:x,error:s,touched:i,invalid:V,isDirty:d,isValidating:u,isHidden:m,isRequired:R,fieldMeta:l,setValue:B,setBlur:f,update:a=>B(_nullishCoalesce(_optionalChain([a, 'optionalAccess', _15 => _15.target, 'optionalAccess', _16 => _16.value]), () => (a)))}}var F=()=>Math.random().toString(36).substring(2,9);function Y(t){let e=_core.inject.call(void 0, h),o=_core.inject.call(void 0, _core.DestroyRef),r=()=>{let s=_chunk6VDQSKUNcjs.e.call(void 0, e.getState().values,t);return Array.isArray(s)?s:[]},n=_core.signal.call(void 0, r()),c=_core.signal.call(void 0, n().map(F)),g=e.subscribe(()=>{let s=r(),i=_core.untracked.call(void 0, c);n.set(s),s.length!==i.length&&(s.length>i.length?c.set([...i,...Array.from({length:s.length-i.length},F)]):c.set(i.slice(0,s.length)))});return o.onDestroy(()=>{g(),e.unregisterPrefix&&e.unregisterPrefix(`${t}.`)}),{fields:_core.computed.call(void 0, ()=>n().map((s,i)=>({key:c()[i]||`temp-${i}`,value:s,index:i}))),length:_core.computed.call(void 0, ()=>n().length),append:s=>{c.update(i=>[...i,F()]),e.pushItem(t,s)},prepend:s=>{c.update(i=>[F(),...i]),e.prependItem(t,s)},remove:s=>{c.update(i=>i.filter((d,u)=>u!==s)),e.removeItem(t,s)},insert:(s,i)=>{c.update(d=>{let u=[...d];return u.splice(s,0,F()),u}),e.insertItem(t,s,i)},swap:(s,i)=>{c.update(d=>{let u=[...d];return[u[s],u[i]]=[u[i],u[s]],u}),e.swapItems(t,s,i)},move:(s,i)=>{c.update(d=>{let u=[...d],[m]=u.splice(s,1);return u.splice(i,0,m),u}),e.moveItem(t,s,i)},replace:s=>{c.set(s.map(()=>F())),e.setField(t,s)},clear:()=>{c.set([]),e.setField(t,[])}}}function et(t,e){let o=Object.keys(t),r=Object.keys(e);return o.length!==r.length?!1:o.every(n=>t[n]===e[n])}function rt(t){let e=S(),o=e.getStepStatus(t),r=_core.signal.call(void 0, o),n=e.subscribe(()=>{let u=e.getStepStatus(t),m=r();(u.hasErrors!==m.hasErrors||u.isDirty!==m.isDirty||!et(u.errors,m.errors))&&r.set(u)});try{_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>n())}catch (e2){}let c=async()=>{let u=await e.validate({scope:t}),m=e.getStepErrors(t);return{valid:u,errors:m}},g=()=>e.getStepErrors(t),s=_core.computed.call(void 0, ()=>!r().hasErrors),i=_core.computed.call(void 0, ()=>r().isDirty),d=_core.computed.call(void 0, ()=>r().errors);return{scopeName:t,status:r,errors:d,validate:c,getErrors:g,isValid:s,isDirty:i,unsubscribe:n}}function nt(t,e){let o=Object.keys(t),r=Object.keys(e);return o.length!==r.length?!1:o.every(n=>t[n]===e[n])}function it(t){let e=S(),o=_core.signal.call(void 0, 0),r=_core.computed.call(void 0, ()=>_nullishCoalesce(t[o()], () => (""))),n=()=>_nullishCoalesce(t[o()], () => ("")),c=_core.signal.call(void 0, e.getStepStatus(n())),g=()=>{let l=n(),a=e.getStepStatus(l),p=c();(a.hasErrors!==p.hasErrors||a.isDirty!==p.isDirty||!nt(a.errors,p.errors))&&c.set(a)},s=e.subscribe(g);try{_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>s())}catch (e3){}let i=async()=>{let l=n(),a=await e.validate({scope:l}),p=e.getStepErrors(l);return{valid:a,errors:p}},d=()=>e.getStepErrors(n()),u=async()=>{let l=n(),a=await e.validate({scope:l});if(a){let p=Math.min(o()+1,t.length-1);o.set(p),c.set(e.getStepStatus(_nullishCoalesce(t[p], () => (""))))}else{let p=e.getStepErrors(l),j=Object.keys(p);j.length>0&&e.markFieldsTouched(j)}return a},m=()=>{let l=Math.max(o()-1,0);o.set(l),c.set(e.getStepStatus(_nullishCoalesce(t[l], () => (""))))},R=l=>{let a=Math.max(0,Math.min(l-1,t.length-1));o.set(a),c.set(e.getStepStatus(_nullishCoalesce(t[a], () => (""))))},V=_core.computed.call(void 0, ()=>o()+1),b=_core.computed.call(void 0, ()=>o()===0),P=_core.computed.call(void 0, ()=>o()>=t.length-1),x=_core.computed.call(void 0, ()=>!c().hasErrors),B=_core.computed.call(void 0, ()=>c().isDirty),f=_core.computed.call(void 0, ()=>c().errors);return{step:V,stepIndex:o,scope:r,next:u,prev:m,goTo:R,isFirst:b,isLast:P,status:c,errors:f,isValid:x,isDirty:B,validate:i,getErrors:d}}function lt(t){let e=S(),o=_core.inject.call(void 0, _core.DestroyRef),r=_core.signal.call(void 0, _chunk6VDQSKUNcjs.e.call(void 0, e.getState().values,t),{equal:_chunk6VDQSKUNcjs.d}),n=e.watch(t,c=>{r.set(c)});return o.onDestroy(n),r.asReadonly()}exports.injectBitArray = Y; exports.injectBitField = J; exports.injectBitForm = $; exports.injectBitScope = rt; exports.injectBitSteps = it; exports.injectBitWatch = lt; exports.provideBitStore = C; exports.useBitStore = S;
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 _chunkJ3EGU5ZHcjs = require('../chunk-J3EGU5ZH.cjs');var _core = require('@angular/core');var h=new (0, _core.InjectionToken)("BIT_STORE");function C(t){return{provide:h,useValue:t}}function S(){let t=_core.inject.call(void 0, h,{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 $(){let t=S(),e=_core.inject.call(void 0, _core.DestroyRef),o=_core.signal.call(void 0, t.getState()),r=_core.signal.call(void 0, null),n=_core.signal.call(void 0, null),c=t.subscribe(()=>{o.set(t.getState())});e.onDestroy(()=>c());let g=_core.computed.call(void 0, ()=>o().isValid),s=_core.computed.call(void 0, ()=>o().isSubmitting),i=_core.computed.call(void 0, ()=>o().isDirty),d=_core.computed.call(void 0, ()=>(o(),t.canUndo)),u=_core.computed.call(void 0, ()=>(o(),t.canRedo));return{store:t,isValid:g,isSubmitting:s,isDirty:i,canUndo:d,canRedo:u,getValues:()=>o().values,getErrors:()=>o().errors,getTouched:()=>o().touched,submit:B=>f=>(_optionalChain([f, 'optionalAccess', _2 => _2.preventDefault, 'call', _3 => _3()]),_optionalChain([f, 'optionalAccess', _4 => _4.stopPropagation, 'call', _5 => _5()]),t.submit(B)),onSubmit:B=>f=>(_optionalChain([f, 'optionalAccess', _6 => _6.preventDefault, 'call', _7 => _7()]),_optionalChain([f, 'optionalAccess', _8 => _8.stopPropagation, 'call', _9 => _9()]),r.set(null),t.submit(async l=>{try{let a=await B(l);n.set(a),r.set(null)}catch(a){_chunkJ3EGU5ZHcjs.h.call(void 0, a)?t.setServerErrors(_chunkJ3EGU5ZHcjs.i.call(void 0, a)):r.set(a instanceof Error?a:new Error(String(a)))}})),submitError:r,lastResponse:n,reset:()=>{t.reset(),r.set(null),n.set(null)},validate:t.validate.bind(t),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),registerMask:t.registerMask.bind(t),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),undo:t.undo.bind(t),redo:t.redo.bind(t)}}function J(t,e,o){let r=_core.inject.call(void 0, h),n=_core.signal.call(void 0, r.getState()),c=r.subscribe(()=>{n.set(r.getState())});_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>{c(),r.unregisterField&&r.unregisterField(t)}),e&&r.registerField(t,e);let g=_core.computed.call(void 0, ()=>_chunkJ3EGU5ZHcjs.e.call(void 0, n().values,t)),s=_core.computed.call(void 0, ()=>n().errors[t]),i=_core.computed.call(void 0, ()=>!!n().touched[t]),d=_core.computed.call(void 0, ()=>(n(),r.isFieldDirty(t))),u=_core.computed.call(void 0, ()=>(n(),r.isFieldValidating(t))),m=_core.computed.call(void 0, ()=>(n(),r.isHidden(t))),R=_core.computed.call(void 0, ()=>(n(),r.isRequired(t))),V=_core.computed.call(void 0, ()=>i()&&!!s()),b=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _10 => _10.mask]), () => (_optionalChain([r, 'access', _11 => _11.config, 'access', _12 => _12.fields, 'optionalAccess', _13 => _13[t], 'optionalAccess', _14 => _14.mask]))),P=b?typeof b=="string"?r.config.masks[b]:b:void 0,x=_core.computed.call(void 0, ()=>{let a=g();return a==null||a===""?"":P?P.format(a):String(a)}),B=a=>{if(!P){r.setField(t,a);return}let p=String(_nullishCoalesce(a, () => ("")));r.setField(t,P.parse(p))},f=()=>r.blurField(t),l=_core.computed.call(void 0, ()=>({isDirty:d(),isValidating:u(),isHidden:m(),isRequired:R(),hasError:!!s()}));return{value:g,displayValue:x,error:s,touched:i,invalid:V,isDirty:d,isValidating:u,isHidden:m,isRequired:R,fieldMeta:l,setValue:B,setBlur:f,update:a=>B(_nullishCoalesce(_optionalChain([a, 'optionalAccess', _15 => _15.target, 'optionalAccess', _16 => _16.value]), () => (a)))}}var F=()=>Math.random().toString(36).substring(2,9);function Y(t){let e=_core.inject.call(void 0, h),o=_core.inject.call(void 0, _core.DestroyRef),r=()=>{let s=_chunkJ3EGU5ZHcjs.e.call(void 0, e.getState().values,t);return Array.isArray(s)?s:[]},n=_core.signal.call(void 0, r()),c=_core.signal.call(void 0, n().map(F)),g=e.subscribe(()=>{let s=r(),i=_core.untracked.call(void 0, c);n.set(s),s.length!==i.length&&(s.length>i.length?c.set([...i,...Array.from({length:s.length-i.length},F)]):c.set(i.slice(0,s.length)))});return o.onDestroy(()=>{g(),e.unregisterPrefix&&e.unregisterPrefix(`${t}.`)}),{fields:_core.computed.call(void 0, ()=>n().map((s,i)=>({key:c()[i]||`temp-${i}`,value:s,index:i}))),length:_core.computed.call(void 0, ()=>n().length),append:s=>{c.update(i=>[...i,F()]),e.pushItem(t,s)},prepend:s=>{c.update(i=>[F(),...i]),e.prependItem(t,s)},remove:s=>{c.update(i=>i.filter((d,u)=>u!==s)),e.removeItem(t,s)},insert:(s,i)=>{c.update(d=>{let u=[...d];return u.splice(s,0,F()),u}),e.insertItem(t,s,i)},swap:(s,i)=>{c.update(d=>{let u=[...d];return[u[s],u[i]]=[u[i],u[s]],u}),e.swapItems(t,s,i)},move:(s,i)=>{c.update(d=>{let u=[...d],[m]=u.splice(s,1);return u.splice(i,0,m),u}),e.moveItem(t,s,i)},replace:s=>{c.set(s.map(()=>F())),e.setField(t,s)},clear:()=>{c.set([]),e.setField(t,[])}}}function et(t,e){let o=Object.keys(t),r=Object.keys(e);return o.length!==r.length?!1:o.every(n=>t[n]===e[n])}function rt(t){let e=S(),o=e.getStepStatus(t),r=_core.signal.call(void 0, o),n=e.subscribe(()=>{let u=e.getStepStatus(t),m=r();(u.hasErrors!==m.hasErrors||u.isDirty!==m.isDirty||!et(u.errors,m.errors))&&r.set(u)});try{_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>n())}catch (e2){}let c=async()=>{let u=await e.validate({scope:t}),m=e.getStepErrors(t);return{valid:u,errors:m}},g=()=>e.getStepErrors(t),s=_core.computed.call(void 0, ()=>!r().hasErrors),i=_core.computed.call(void 0, ()=>r().isDirty),d=_core.computed.call(void 0, ()=>r().errors);return{scopeName:t,status:r,errors:d,validate:c,getErrors:g,isValid:s,isDirty:i,unsubscribe:n}}function nt(t,e){let o=Object.keys(t),r=Object.keys(e);return o.length!==r.length?!1:o.every(n=>t[n]===e[n])}function it(t){let e=S(),o=_core.signal.call(void 0, 0),r=_core.computed.call(void 0, ()=>_nullishCoalesce(t[o()], () => (""))),n=()=>_nullishCoalesce(t[o()], () => ("")),c=_core.signal.call(void 0, e.getStepStatus(n())),g=()=>{let l=n(),a=e.getStepStatus(l),p=c();(a.hasErrors!==p.hasErrors||a.isDirty!==p.isDirty||!nt(a.errors,p.errors))&&c.set(a)},s=e.subscribe(g);try{_core.inject.call(void 0, _core.DestroyRef).onDestroy(()=>s())}catch (e3){}let i=async()=>{let l=n(),a=await e.validate({scope:l}),p=e.getStepErrors(l);return{valid:a,errors:p}},d=()=>e.getStepErrors(n()),u=async()=>{let l=n(),a=await e.validate({scope:l});if(a){let p=Math.min(o()+1,t.length-1);o.set(p),c.set(e.getStepStatus(_nullishCoalesce(t[p], () => (""))))}else{let p=e.getStepErrors(l),j=Object.keys(p);j.length>0&&e.markFieldsTouched(j)}return a},m=()=>{let l=Math.max(o()-1,0);o.set(l),c.set(e.getStepStatus(_nullishCoalesce(t[l], () => (""))))},R=l=>{let a=Math.max(0,Math.min(l-1,t.length-1));o.set(a),c.set(e.getStepStatus(_nullishCoalesce(t[a], () => (""))))},V=_core.computed.call(void 0, ()=>o()+1),b=_core.computed.call(void 0, ()=>o()===0),P=_core.computed.call(void 0, ()=>o()>=t.length-1),x=_core.computed.call(void 0, ()=>!c().hasErrors),B=_core.computed.call(void 0, ()=>c().isDirty),f=_core.computed.call(void 0, ()=>c().errors);return{step:V,stepIndex:o,scope:r,next:u,prev:m,goTo:R,isFirst:b,isLast:P,status:c,errors:f,isValid:x,isDirty:B,validate:i,getErrors:d}}function lt(t){let e=S(),o=_core.inject.call(void 0, _core.DestroyRef),r=_core.signal.call(void 0, _chunkJ3EGU5ZHcjs.e.call(void 0, e.getState().values,t),{equal:_chunkJ3EGU5ZHcjs.d}),n=e.watch(t,c=>{r.set(c)});return o.onDestroy(n),r.asReadonly()}exports.injectBitArray = Y; exports.injectBitField = J; exports.injectBitForm = $; exports.injectBitScope = rt; exports.injectBitSteps = it; exports.injectBitWatch = lt; exports.provideBitStore = C; exports.useBitStore = S;
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1,7 +1,7 @@
1
1
  import * as _angular_core from '@angular/core';
2
2
  import { Provider, computed, signal, Signal } from '@angular/core';
3
- import { B as BitStore } from '../index-BD_l3aH5.cjs';
4
- import { e as BitErrors, n as BitTouched, k as BitPath, l as BitPathValue, B as BitMask, b as BitArrayPath, a as BitArrayItem, g as BitFieldDefinition, h as BitFieldOptions, S as ScopeStatus, V as ValidateScopeResult } from '../bus-DAwKIiMY.cjs';
3
+ import { B as BitStore } from '../index-mzR_3Kbx.cjs';
4
+ import { e as BitErrors, n as BitTouched, k as BitPath, l as BitPathValue, B as BitMask, b as BitArrayPath, a as BitArrayItem, g as BitFieldDefinition, h as BitFieldOptions, S as ScopeStatus, V as ValidateScopeResult } from '../bus-DkMkzOXE.cjs';
5
5
 
6
6
  declare function provideBitStore(store: BitStore<any>): Provider;
7
7
  declare function useBitStore<T extends object>(): BitStore<T>;
@@ -1,7 +1,7 @@
1
1
  import * as _angular_core from '@angular/core';
2
2
  import { Provider, computed, signal, Signal } from '@angular/core';
3
- import { B as BitStore } from '../index-CPKnWBVv.js';
4
- import { e as BitErrors, n as BitTouched, k as BitPath, l as BitPathValue, B as BitMask, b as BitArrayPath, a as BitArrayItem, g as BitFieldDefinition, h as BitFieldOptions, S as ScopeStatus, V as ValidateScopeResult } from '../bus-DAwKIiMY.js';
3
+ import { B as BitStore } from '../index-BXaNeJBk.js';
4
+ import { e as BitErrors, n as BitTouched, k as BitPath, l as BitPathValue, B as BitMask, b as BitArrayPath, a as BitArrayItem, g as BitFieldDefinition, h as BitFieldOptions, S as ScopeStatus, V as ValidateScopeResult } from '../bus-DkMkzOXE.js';
5
5
 
6
6
  declare function provideBitStore(store: BitStore<any>): Provider;
7
7
  declare function useBitStore<T extends object>(): BitStore<T>;
@@ -1,2 +1,2 @@
1
- import{d as w,e as v,h as k,i as A}from"../chunk-KA4FAGIX.js";import{inject as K,InjectionToken as W}from"@angular/core";var h=new W("BIT_STORE");function C(t){return{provide:h,useValue:t}}function S(){let t=K(h,{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 I,computed as E,inject as L,DestroyRef as U}from"@angular/core";function $(){let t=S(),e=L(U),o=I(t.getState()),r=I(null),n=I(null),c=t.subscribe(()=>{o.set(t.getState())});e.onDestroy(()=>c());let g=E(()=>o().isValid),s=E(()=>o().isSubmitting),i=E(()=>o().isDirty),d=E(()=>(o(),t.canUndo)),u=E(()=>(o(),t.canRedo));return{store:t,isValid:g,isSubmitting:s,isDirty:i,canUndo:d,canRedo:u,getValues:()=>o().values,getErrors:()=>o().errors,getTouched:()=>o().touched,submit:B=>f=>(f?.preventDefault(),f?.stopPropagation(),t.submit(B)),onSubmit:B=>f=>(f?.preventDefault(),f?.stopPropagation(),r.set(null),t.submit(async l=>{try{let a=await B(l);n.set(a),r.set(null)}catch(a){k(a)?t.setServerErrors(A(a)):r.set(a instanceof Error?a:new Error(String(a)))}})),submitError:r,lastResponse:n,reset:()=>{t.reset(),r.set(null),n.set(null)},validate:t.validate.bind(t),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),registerMask:t.registerMask.bind(t),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),undo:t.undo.bind(t),redo:t.redo.bind(t)}}import{inject as O,DestroyRef as z,computed as y,signal as G}from"@angular/core";function J(t,e,o){let r=O(h),n=G(r.getState()),c=r.subscribe(()=>{n.set(r.getState())});O(z).onDestroy(()=>{c(),r.unregisterField&&r.unregisterField(t)}),e&&r.registerField(t,e);let g=y(()=>v(n().values,t)),s=y(()=>n().errors[t]),i=y(()=>!!n().touched[t]),d=y(()=>(n(),r.isFieldDirty(t))),u=y(()=>(n(),r.isFieldValidating(t))),m=y(()=>(n(),r.isHidden(t))),R=y(()=>(n(),r.isRequired(t))),V=y(()=>i()&&!!s()),b=o?.mask??r.config.fields?.[t]?.mask,P=b?typeof b=="string"?r.config.masks[b]:b:void 0,x=y(()=>{let a=g();return a==null||a===""?"":P?P.format(a):String(a)}),B=a=>{if(!P){r.setField(t,a);return}let p=String(a??"");r.setField(t,P.parse(p))},f=()=>r.blurField(t),l=y(()=>({isDirty:d(),isValidating:u(),isHidden:m(),isRequired:R(),hasError:!!s()}));return{value:g,displayValue:x,error:s,touched:i,invalid:V,isDirty:d,isValidating:u,isHidden:m,isRequired:R,fieldMeta:l,setValue:B,setBlur:f,update:a=>B(a?.target?.value??a)}}import{DestroyRef as Q,signal as q,computed as M,inject as _,untracked as X}from"@angular/core";var F=()=>Math.random().toString(36).substring(2,9);function Y(t){let e=_(h),o=_(Q),r=()=>{let s=v(e.getState().values,t);return Array.isArray(s)?s:[]},n=q(r()),c=q(n().map(F)),g=e.subscribe(()=>{let s=r(),i=X(c);n.set(s),s.length!==i.length&&(s.length>i.length?c.set([...i,...Array.from({length:s.length-i.length},F)]):c.set(i.slice(0,s.length)))});return o.onDestroy(()=>{g(),e.unregisterPrefix&&e.unregisterPrefix(`${t}.`)}),{fields:M(()=>n().map((s,i)=>({key:c()[i]||`temp-${i}`,value:s,index:i}))),length:M(()=>n().length),append:s=>{c.update(i=>[...i,F()]),e.pushItem(t,s)},prepend:s=>{c.update(i=>[F(),...i]),e.prependItem(t,s)},remove:s=>{c.update(i=>i.filter((d,u)=>u!==s)),e.removeItem(t,s)},insert:(s,i)=>{c.update(d=>{let u=[...d];return u.splice(s,0,F()),u}),e.insertItem(t,s,i)},swap:(s,i)=>{c.update(d=>{let u=[...d];return[u[s],u[i]]=[u[i],u[s]],u}),e.swapItems(t,s,i)},move:(s,i)=>{c.update(d=>{let u=[...d],[m]=u.splice(s,1);return u.splice(i,0,m),u}),e.moveItem(t,s,i)},replace:s=>{c.set(s.map(()=>F())),e.setField(t,s)},clear:()=>{c.set([]),e.setField(t,[])}}}import{signal as Z,computed as D,DestroyRef as N,inject as tt}from"@angular/core";function et(t,e){let o=Object.keys(t),r=Object.keys(e);return o.length!==r.length?!1:o.every(n=>t[n]===e[n])}function rt(t){let e=S(),o=e.getStepStatus(t),r=Z(o),n=e.subscribe(()=>{let u=e.getStepStatus(t),m=r();(u.hasErrors!==m.hasErrors||u.isDirty!==m.isDirty||!et(u.errors,m.errors))&&r.set(u)});try{tt(N).onDestroy(()=>n())}catch{}let c=async()=>{let u=await e.validate({scope:t}),m=e.getStepErrors(t);return{valid:u,errors:m}},g=()=>e.getStepErrors(t),s=D(()=>!r().hasErrors),i=D(()=>r().isDirty),d=D(()=>r().errors);return{scopeName:t,status:r,errors:d,validate:c,getErrors:g,isValid:s,isDirty:i,unsubscribe:n}}import{signal as H,computed as T,DestroyRef as st,inject as ot}from"@angular/core";function nt(t,e){let o=Object.keys(t),r=Object.keys(e);return o.length!==r.length?!1:o.every(n=>t[n]===e[n])}function it(t){let e=S(),o=H(0),r=T(()=>t[o()]??""),n=()=>t[o()]??"",c=H(e.getStepStatus(n())),g=()=>{let l=n(),a=e.getStepStatus(l),p=c();(a.hasErrors!==p.hasErrors||a.isDirty!==p.isDirty||!nt(a.errors,p.errors))&&c.set(a)},s=e.subscribe(g);try{ot(st).onDestroy(()=>s())}catch{}let i=async()=>{let l=n(),a=await e.validate({scope:l}),p=e.getStepErrors(l);return{valid:a,errors:p}},d=()=>e.getStepErrors(n()),u=async()=>{let l=n(),a=await e.validate({scope:l});if(a){let p=Math.min(o()+1,t.length-1);o.set(p),c.set(e.getStepStatus(t[p]??""))}else{let p=e.getStepErrors(l),j=Object.keys(p);j.length>0&&e.markFieldsTouched(j)}return a},m=()=>{let l=Math.max(o()-1,0);o.set(l),c.set(e.getStepStatus(t[l]??""))},R=l=>{let a=Math.max(0,Math.min(l-1,t.length-1));o.set(a),c.set(e.getStepStatus(t[a]??""))},V=T(()=>o()+1),b=T(()=>o()===0),P=T(()=>o()>=t.length-1),x=T(()=>!c().hasErrors),B=T(()=>c().isDirty),f=T(()=>c().errors);return{step:V,stepIndex:o,scope:r,next:u,prev:m,goTo:R,isFirst:b,isLast:P,status:c,errors:f,isValid:x,isDirty:B,validate:i,getErrors:d}}import{DestroyRef as at,signal as ct,inject as ut}from"@angular/core";function lt(t){let e=S(),o=ut(at),r=ct(v(e.getState().values,t),{equal:w}),n=e.watch(t,c=>{r.set(c)});return o.onDestroy(n),r.asReadonly()}export{Y as injectBitArray,J as injectBitField,$ as injectBitForm,rt as injectBitScope,it as injectBitSteps,lt as injectBitWatch,C as provideBitStore,S as useBitStore};
1
+ import{d as w,e as v,h as k,i as A}from"../chunk-QU365SAC.js";import{inject as K,InjectionToken as W}from"@angular/core";var h=new W("BIT_STORE");function C(t){return{provide:h,useValue:t}}function S(){let t=K(h,{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 I,computed as E,inject as L,DestroyRef as U}from"@angular/core";function $(){let t=S(),e=L(U),o=I(t.getState()),r=I(null),n=I(null),c=t.subscribe(()=>{o.set(t.getState())});e.onDestroy(()=>c());let g=E(()=>o().isValid),s=E(()=>o().isSubmitting),i=E(()=>o().isDirty),d=E(()=>(o(),t.canUndo)),u=E(()=>(o(),t.canRedo));return{store:t,isValid:g,isSubmitting:s,isDirty:i,canUndo:d,canRedo:u,getValues:()=>o().values,getErrors:()=>o().errors,getTouched:()=>o().touched,submit:B=>f=>(f?.preventDefault(),f?.stopPropagation(),t.submit(B)),onSubmit:B=>f=>(f?.preventDefault(),f?.stopPropagation(),r.set(null),t.submit(async l=>{try{let a=await B(l);n.set(a),r.set(null)}catch(a){k(a)?t.setServerErrors(A(a)):r.set(a instanceof Error?a:new Error(String(a)))}})),submitError:r,lastResponse:n,reset:()=>{t.reset(),r.set(null),n.set(null)},validate:t.validate.bind(t),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),registerMask:t.registerMask.bind(t),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),undo:t.undo.bind(t),redo:t.redo.bind(t)}}import{inject as O,DestroyRef as z,computed as y,signal as G}from"@angular/core";function J(t,e,o){let r=O(h),n=G(r.getState()),c=r.subscribe(()=>{n.set(r.getState())});O(z).onDestroy(()=>{c(),r.unregisterField&&r.unregisterField(t)}),e&&r.registerField(t,e);let g=y(()=>v(n().values,t)),s=y(()=>n().errors[t]),i=y(()=>!!n().touched[t]),d=y(()=>(n(),r.isFieldDirty(t))),u=y(()=>(n(),r.isFieldValidating(t))),m=y(()=>(n(),r.isHidden(t))),R=y(()=>(n(),r.isRequired(t))),V=y(()=>i()&&!!s()),b=o?.mask??r.config.fields?.[t]?.mask,P=b?typeof b=="string"?r.config.masks[b]:b:void 0,x=y(()=>{let a=g();return a==null||a===""?"":P?P.format(a):String(a)}),B=a=>{if(!P){r.setField(t,a);return}let p=String(a??"");r.setField(t,P.parse(p))},f=()=>r.blurField(t),l=y(()=>({isDirty:d(),isValidating:u(),isHidden:m(),isRequired:R(),hasError:!!s()}));return{value:g,displayValue:x,error:s,touched:i,invalid:V,isDirty:d,isValidating:u,isHidden:m,isRequired:R,fieldMeta:l,setValue:B,setBlur:f,update:a=>B(a?.target?.value??a)}}import{DestroyRef as Q,signal as q,computed as M,inject as _,untracked as X}from"@angular/core";var F=()=>Math.random().toString(36).substring(2,9);function Y(t){let e=_(h),o=_(Q),r=()=>{let s=v(e.getState().values,t);return Array.isArray(s)?s:[]},n=q(r()),c=q(n().map(F)),g=e.subscribe(()=>{let s=r(),i=X(c);n.set(s),s.length!==i.length&&(s.length>i.length?c.set([...i,...Array.from({length:s.length-i.length},F)]):c.set(i.slice(0,s.length)))});return o.onDestroy(()=>{g(),e.unregisterPrefix&&e.unregisterPrefix(`${t}.`)}),{fields:M(()=>n().map((s,i)=>({key:c()[i]||`temp-${i}`,value:s,index:i}))),length:M(()=>n().length),append:s=>{c.update(i=>[...i,F()]),e.pushItem(t,s)},prepend:s=>{c.update(i=>[F(),...i]),e.prependItem(t,s)},remove:s=>{c.update(i=>i.filter((d,u)=>u!==s)),e.removeItem(t,s)},insert:(s,i)=>{c.update(d=>{let u=[...d];return u.splice(s,0,F()),u}),e.insertItem(t,s,i)},swap:(s,i)=>{c.update(d=>{let u=[...d];return[u[s],u[i]]=[u[i],u[s]],u}),e.swapItems(t,s,i)},move:(s,i)=>{c.update(d=>{let u=[...d],[m]=u.splice(s,1);return u.splice(i,0,m),u}),e.moveItem(t,s,i)},replace:s=>{c.set(s.map(()=>F())),e.setField(t,s)},clear:()=>{c.set([]),e.setField(t,[])}}}import{signal as Z,computed as D,DestroyRef as N,inject as tt}from"@angular/core";function et(t,e){let o=Object.keys(t),r=Object.keys(e);return o.length!==r.length?!1:o.every(n=>t[n]===e[n])}function rt(t){let e=S(),o=e.getStepStatus(t),r=Z(o),n=e.subscribe(()=>{let u=e.getStepStatus(t),m=r();(u.hasErrors!==m.hasErrors||u.isDirty!==m.isDirty||!et(u.errors,m.errors))&&r.set(u)});try{tt(N).onDestroy(()=>n())}catch{}let c=async()=>{let u=await e.validate({scope:t}),m=e.getStepErrors(t);return{valid:u,errors:m}},g=()=>e.getStepErrors(t),s=D(()=>!r().hasErrors),i=D(()=>r().isDirty),d=D(()=>r().errors);return{scopeName:t,status:r,errors:d,validate:c,getErrors:g,isValid:s,isDirty:i,unsubscribe:n}}import{signal as H,computed as T,DestroyRef as st,inject as ot}from"@angular/core";function nt(t,e){let o=Object.keys(t),r=Object.keys(e);return o.length!==r.length?!1:o.every(n=>t[n]===e[n])}function it(t){let e=S(),o=H(0),r=T(()=>t[o()]??""),n=()=>t[o()]??"",c=H(e.getStepStatus(n())),g=()=>{let l=n(),a=e.getStepStatus(l),p=c();(a.hasErrors!==p.hasErrors||a.isDirty!==p.isDirty||!nt(a.errors,p.errors))&&c.set(a)},s=e.subscribe(g);try{ot(st).onDestroy(()=>s())}catch{}let i=async()=>{let l=n(),a=await e.validate({scope:l}),p=e.getStepErrors(l);return{valid:a,errors:p}},d=()=>e.getStepErrors(n()),u=async()=>{let l=n(),a=await e.validate({scope:l});if(a){let p=Math.min(o()+1,t.length-1);o.set(p),c.set(e.getStepStatus(t[p]??""))}else{let p=e.getStepErrors(l),j=Object.keys(p);j.length>0&&e.markFieldsTouched(j)}return a},m=()=>{let l=Math.max(o()-1,0);o.set(l),c.set(e.getStepStatus(t[l]??""))},R=l=>{let a=Math.max(0,Math.min(l-1,t.length-1));o.set(a),c.set(e.getStepStatus(t[a]??""))},V=T(()=>o()+1),b=T(()=>o()===0),P=T(()=>o()>=t.length-1),x=T(()=>!c().hasErrors),B=T(()=>c().isDirty),f=T(()=>c().errors);return{step:V,stepIndex:o,scope:r,next:u,prev:m,goTo:R,isFirst:b,isLast:P,status:c,errors:f,isValid:x,isDirty:B,validate:i,getErrors:d}}import{DestroyRef as at,signal as ct,inject as ut}from"@angular/core";function lt(t){let e=S(),o=ut(at),r=ct(v(e.getState().values,t),{equal:w}),n=e.watch(t,c=>{r.set(c)});return o.onDestroy(n),r.asReadonly()}export{Y as injectBitArray,J as injectBitField,$ as injectBitForm,rt as injectBitScope,it as injectBitSteps,lt as injectBitWatch,C as provideBitStore,S as useBitStore};
2
2
  //# sourceMappingURL=index.js.map
@@ -29,7 +29,7 @@ declare class BitDependencyManager<T extends object = any> {
29
29
  register(path: string, config: BitFieldDefinition<T>, currentValues: T): void;
30
30
  isHidden(path: string): boolean;
31
31
  isRequired(path: string, values: T): boolean;
32
- getRequiredErrors(values: T, defaultMessage?: string): Record<string, string>;
32
+ getRequiredErrors(values: T): Record<string, string>;
33
33
  evaluateAll(values: T): void;
34
34
  updateDependencies(changedPath: string, newValues: T): string[];
35
35
  unregister(path: string): void;
@@ -95,11 +95,11 @@ interface BitFieldConditional<T extends object = any> {
95
95
  dependsOn?: string[];
96
96
  showIf?: (values: T) => boolean;
97
97
  requiredIf?: (values: T) => boolean;
98
+ /** Custom message when field is required but empty. Fallback: "required field". */
99
+ requiredMessage?: string;
98
100
  }
99
- /** Field-level validation: async and required message. */
101
+ /** Field-level validation: async validation only. */
100
102
  interface BitFieldValidation<T extends object = any> {
101
- /** Custom message when field is required but empty. Falls back to defaultRequiredMessage or "Este campo é obrigatório". */
102
- requiredMessage?: string;
103
103
  asyncValidate?: (value: any, values: T) => Promise<string | null | undefined>;
104
104
  asyncValidateDelay?: number;
105
105
  }
@@ -123,7 +123,6 @@ interface DevToolsOptions {
123
123
  interface BitValidationConfig<T> {
124
124
  resolver?: ValidatorFn<T>;
125
125
  delay?: number;
126
- defaultRequiredMessage?: string;
127
126
  }
128
127
  /** History config. */
129
128
  interface BitHistoryConfig {
@@ -153,7 +152,6 @@ interface BitResolvedConfig<T extends object> {
153
152
  initialValues: T;
154
153
  resolver?: ValidatorFn<T>;
155
154
  validationDelay: number;
156
- defaultRequiredMessage?: string;
157
155
  enableHistory: boolean;
158
156
  historyLimit: number;
159
157
  /** Derived from fields where field.computed exists. */
@@ -29,7 +29,7 @@ declare class BitDependencyManager<T extends object = any> {
29
29
  register(path: string, config: BitFieldDefinition<T>, currentValues: T): void;
30
30
  isHidden(path: string): boolean;
31
31
  isRequired(path: string, values: T): boolean;
32
- getRequiredErrors(values: T, defaultMessage?: string): Record<string, string>;
32
+ getRequiredErrors(values: T): Record<string, string>;
33
33
  evaluateAll(values: T): void;
34
34
  updateDependencies(changedPath: string, newValues: T): string[];
35
35
  unregister(path: string): void;
@@ -95,11 +95,11 @@ interface BitFieldConditional<T extends object = any> {
95
95
  dependsOn?: string[];
96
96
  showIf?: (values: T) => boolean;
97
97
  requiredIf?: (values: T) => boolean;
98
+ /** Custom message when field is required but empty. Fallback: "required field". */
99
+ requiredMessage?: string;
98
100
  }
99
- /** Field-level validation: async and required message. */
101
+ /** Field-level validation: async validation only. */
100
102
  interface BitFieldValidation<T extends object = any> {
101
- /** Custom message when field is required but empty. Falls back to defaultRequiredMessage or "Este campo é obrigatório". */
102
- requiredMessage?: string;
103
103
  asyncValidate?: (value: any, values: T) => Promise<string | null | undefined>;
104
104
  asyncValidateDelay?: number;
105
105
  }
@@ -123,7 +123,6 @@ interface DevToolsOptions {
123
123
  interface BitValidationConfig<T> {
124
124
  resolver?: ValidatorFn<T>;
125
125
  delay?: number;
126
- defaultRequiredMessage?: string;
127
126
  }
128
127
  /** History config. */
129
128
  interface BitHistoryConfig {
@@ -153,7 +152,6 @@ interface BitResolvedConfig<T extends object> {
153
152
  initialValues: T;
154
153
  resolver?: ValidatorFn<T>;
155
154
  validationDelay: number;
156
- defaultRequiredMessage?: string;
157
155
  enableHistory: boolean;
158
156
  historyLimit: number;
159
157
  /** Derived from fields where field.computed exists. */
@@ -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 _chunk6VDQSKUNcjs = require('./chunk-6VDQSKUN.cjs');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var w=_react.createContext.call(void 0, null),nt= exports.a =({store:t,children:e})=>_jsxruntime.jsx.call(void 0, w.Provider,{value:t,children:e}),S= exports.b =()=>{let t=_react.useContext.call(void 0, w);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};function ct(){let t=S(),[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 u=t.getState(),{isValid:d,isDirty:b,isSubmitting:p}=u,T=t.canUndo,I=t.canRedo;if(o.current&&o.current.isValid===d&&o.current.isDirty===b&&o.current.isSubmitting===p&&o.current.canUndo===T&&o.current.canRedo===I)return o.current;let x={isValid:d,isDirty:b,isSubmitting:p,canUndo:T,canRedo:I};return o.current=x,x},[t]),c=_react.useSyncExternalStore.call(void 0, t.subscribe.bind(t),g,g),s=_react.useCallback.call(void 0, u=>d=>(_optionalChain([d, 'optionalAccess', _2 => _2.preventDefault, 'optionalCall', _3 => _3()]),t.submit(u)),[t]),n=_react.useCallback.call(void 0, u=>d=>(_optionalChain([d, 'optionalAccess', _4 => _4.preventDefault, 'optionalCall', _5 => _5()]),r(null),t.submit(async b=>{try{let p=await u(b);a(p),r(null)}catch(p){_chunk6VDQSKUNcjs.h.call(void 0, p)?t.setServerErrors(_chunk6VDQSKUNcjs.i.call(void 0, p)):r(p instanceof Error?p:new Error(String(p)))}})),[t]),m=_react.useCallback.call(void 0, ()=>{t.reset(),r(null),a(null)},[t]),l=_react.useCallback.call(void 0, ()=>t.getState().values,[t]),f=_react.useCallback.call(void 0, ()=>t.getState().errors,[t]),h=_react.useCallback.call(void 0, ()=>t.getState().touched,[t]),v=_react.useMemo.call(void 0, ()=>({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),reset:m,validate:t.validate.bind(t),registerMask:t.registerMask.bind(t),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),undo:t.undo.bind(t),redo:t.redo.bind(t)}),[t,m]);return{...c,getValues:l,getErrors:f,getTouched:h,submit:s,onSubmit:n,submitError:e,lastResponse:i,...v,reset:m,store:t}}var P=()=>Math.random().toString(36).substring(2,9);function ht(t){let e=S(),r=_react.useCallback.call(void 0, ()=>{let s=e.getState(),n=_chunk6VDQSKUNcjs.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(m=>{let l=[...m];return l.splice(s,0,P()),l}),e.insertItem(t,s,n)},remove:s=>{o(n=>n.filter((m,l)=>l!==s)),e.removeItem(t,s)},move:(s,n)=>{o(m=>{let l=[...m],[f]=l.splice(s,1);return l.splice(n,0,f),l}),e.moveItem(t,s,n)},swap:(s,n)=>{o(m=>{let l=[...m];return[l[s],l[n]]=[l[n],l[s]],l}),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 Ft(t){let e=S(),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, ()=>{let c=e.getStepStatus(t);return r.current&&r.current.hasErrors===c.hasErrors&&r.current.isDirty===c.isDirty&&Object.keys(r.current.errors).length===Object.keys(c.errors).length&&Object.entries(c.errors).every(([s,n])=>r.current.errors[s]===n)?r.current:(r.current=c,c)},[e,t]),a=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),i,i),o=_react.useCallback.call(void 0, async()=>{let c=await e.validate({scope:t}),s=e.getStepErrors(t);return{valid:c,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 It(t){let e=S(),[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 u=e.getStepStatus(a);return o.current&&o.current.hasErrors===u.hasErrors&&o.current.isDirty===u.isDirty&&Object.keys(o.current.errors).length===Object.keys(u.errors).length&&Object.entries(u.errors).every(([d,b])=>o.current.errors[d]===b)?o.current:(o.current=u,u)},[e,a]),c=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),g,g),s=_react.useCallback.call(void 0, async()=>{let u=await e.validate({scope:a}),d=e.getStepErrors(a);return{valid:u,errors:d}},[e,a]),n=_react.useCallback.call(void 0, ()=>e.getStepErrors(a),[e,a]),m=_react.useCallback.call(void 0, async()=>{let u=await e.validate({scope:a});if(u)i(d=>Math.min(d+1,t.length-1));else{let d=e.getStepErrors(a),b=Object.keys(d);b.length>0&&e.markFieldsTouched(b)}return u},[e,a,t.length]),l=_react.useCallback.call(void 0, ()=>{i(u=>Math.max(u-1,0))},[]),f=_react.useCallback.call(void 0, u=>{i(Math.max(0,Math.min(u-1,t.length-1)))},[t.length]),h=r===0,v=r>=t.length-1;return{step:r+1,stepIndex:r,scope:a,next:m,prev:l,goTo:f,isFirst:h,isLast:v,status:c,errors:c.errors,isValid:!c.hasErrors,isDirty:c.isDirty,validate:s,getErrors:n}}function jt(t){let e=S(),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, ()=>{let o=_chunk6VDQSKUNcjs.e.call(void 0, e.getState().values,t);return r.current!==null&&_chunk6VDQSKUNcjs.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 Wt(t,e){let r=S(),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(),m=_chunk6VDQSKUNcjs.e.call(void 0, n.values,t),l=n.errors[t],f=!!n.touched[t],h=r.isHidden(t),v=r.isRequired(t),u=r.isFieldDirty(t),d=r.isFieldValidating(t);if(i.current&&i.current.value===m&&i.current.error===l&&i.current.touched===f&&i.current.isHidden===h&&i.current.isRequired===v&&i.current.isDirty===u&&i.current.isValidating===d)return i.current;let b={value:m,error:l,touched:f,isHidden:h,isRequired:v,isDirty:u,isValidating:d};return i.current=b,b},[r,t]),o=_react.useCallback.call(void 0, n=>r.subscribe(n),[r]),g=_react.useSyncExternalStore.call(void 0, o,a,a),c=_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:c,setBlur:s,store:r}}exports.a = nt; exports.b = S; exports.c = ct; exports.d = Wt; exports.e = ht; exports.f = Ft; exports.g = It; exports.h = jt;
2
- //# sourceMappingURL=chunk-Z6ITPS2B.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 _chunkJ3EGU5ZHcjs = require('./chunk-J3EGU5ZH.cjs');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var w=_react.createContext.call(void 0, null),nt= exports.a =({store:t,children:e})=>_jsxruntime.jsx.call(void 0, w.Provider,{value:t,children:e}),S= exports.b =()=>{let t=_react.useContext.call(void 0, w);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};function ct(){let t=S(),[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 u=t.getState(),{isValid:d,isDirty:b,isSubmitting:p}=u,T=t.canUndo,I=t.canRedo;if(o.current&&o.current.isValid===d&&o.current.isDirty===b&&o.current.isSubmitting===p&&o.current.canUndo===T&&o.current.canRedo===I)return o.current;let x={isValid:d,isDirty:b,isSubmitting:p,canUndo:T,canRedo:I};return o.current=x,x},[t]),c=_react.useSyncExternalStore.call(void 0, t.subscribe.bind(t),g,g),s=_react.useCallback.call(void 0, u=>d=>(_optionalChain([d, 'optionalAccess', _2 => _2.preventDefault, 'optionalCall', _3 => _3()]),t.submit(u)),[t]),n=_react.useCallback.call(void 0, u=>d=>(_optionalChain([d, 'optionalAccess', _4 => _4.preventDefault, 'optionalCall', _5 => _5()]),r(null),t.submit(async b=>{try{let p=await u(b);a(p),r(null)}catch(p){_chunkJ3EGU5ZHcjs.h.call(void 0, p)?t.setServerErrors(_chunkJ3EGU5ZHcjs.i.call(void 0, p)):r(p instanceof Error?p:new Error(String(p)))}})),[t]),m=_react.useCallback.call(void 0, ()=>{t.reset(),r(null),a(null)},[t]),l=_react.useCallback.call(void 0, ()=>t.getState().values,[t]),f=_react.useCallback.call(void 0, ()=>t.getState().errors,[t]),h=_react.useCallback.call(void 0, ()=>t.getState().touched,[t]),v=_react.useMemo.call(void 0, ()=>({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),reset:m,validate:t.validate.bind(t),registerMask:t.registerMask.bind(t),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),undo:t.undo.bind(t),redo:t.redo.bind(t)}),[t,m]);return{...c,getValues:l,getErrors:f,getTouched:h,submit:s,onSubmit:n,submitError:e,lastResponse:i,...v,reset:m,store:t}}var P=()=>Math.random().toString(36).substring(2,9);function ht(t){let e=S(),r=_react.useCallback.call(void 0, ()=>{let s=e.getState(),n=_chunkJ3EGU5ZHcjs.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(m=>{let l=[...m];return l.splice(s,0,P()),l}),e.insertItem(t,s,n)},remove:s=>{o(n=>n.filter((m,l)=>l!==s)),e.removeItem(t,s)},move:(s,n)=>{o(m=>{let l=[...m],[f]=l.splice(s,1);return l.splice(n,0,f),l}),e.moveItem(t,s,n)},swap:(s,n)=>{o(m=>{let l=[...m];return[l[s],l[n]]=[l[n],l[s]],l}),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 Ft(t){let e=S(),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, ()=>{let c=e.getStepStatus(t);return r.current&&r.current.hasErrors===c.hasErrors&&r.current.isDirty===c.isDirty&&Object.keys(r.current.errors).length===Object.keys(c.errors).length&&Object.entries(c.errors).every(([s,n])=>r.current.errors[s]===n)?r.current:(r.current=c,c)},[e,t]),a=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),i,i),o=_react.useCallback.call(void 0, async()=>{let c=await e.validate({scope:t}),s=e.getStepErrors(t);return{valid:c,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 It(t){let e=S(),[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 u=e.getStepStatus(a);return o.current&&o.current.hasErrors===u.hasErrors&&o.current.isDirty===u.isDirty&&Object.keys(o.current.errors).length===Object.keys(u.errors).length&&Object.entries(u.errors).every(([d,b])=>o.current.errors[d]===b)?o.current:(o.current=u,u)},[e,a]),c=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),g,g),s=_react.useCallback.call(void 0, async()=>{let u=await e.validate({scope:a}),d=e.getStepErrors(a);return{valid:u,errors:d}},[e,a]),n=_react.useCallback.call(void 0, ()=>e.getStepErrors(a),[e,a]),m=_react.useCallback.call(void 0, async()=>{let u=await e.validate({scope:a});if(u)i(d=>Math.min(d+1,t.length-1));else{let d=e.getStepErrors(a),b=Object.keys(d);b.length>0&&e.markFieldsTouched(b)}return u},[e,a,t.length]),l=_react.useCallback.call(void 0, ()=>{i(u=>Math.max(u-1,0))},[]),f=_react.useCallback.call(void 0, u=>{i(Math.max(0,Math.min(u-1,t.length-1)))},[t.length]),h=r===0,v=r>=t.length-1;return{step:r+1,stepIndex:r,scope:a,next:m,prev:l,goTo:f,isFirst:h,isLast:v,status:c,errors:c.errors,isValid:!c.hasErrors,isDirty:c.isDirty,validate:s,getErrors:n}}function jt(t){let e=S(),r=_react.useRef.call(void 0, null),i=_react.useCallback.call(void 0, ()=>{let o=_chunkJ3EGU5ZHcjs.e.call(void 0, e.getState().values,t);return r.current!==null&&_chunkJ3EGU5ZHcjs.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 Wt(t,e){let r=S(),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(),m=_chunkJ3EGU5ZHcjs.e.call(void 0, n.values,t),l=n.errors[t],f=!!n.touched[t],h=r.isHidden(t),v=r.isRequired(t),u=r.isFieldDirty(t),d=r.isFieldValidating(t);if(i.current&&i.current.value===m&&i.current.error===l&&i.current.touched===f&&i.current.isHidden===h&&i.current.isRequired===v&&i.current.isDirty===u&&i.current.isValidating===d)return i.current;let b={value:m,error:l,touched:f,isHidden:h,isRequired:v,isDirty:u,isValidating:d};return i.current=b,b},[r,t]),o=_react.useCallback.call(void 0, n=>r.subscribe(n),[r]),g=_react.useSyncExternalStore.call(void 0, o,a,a),c=_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:c,setBlur:s,store:r}}exports.a = nt; exports.b = S; exports.c = ct; exports.d = Wt; exports.e = ht; exports.f = Ft; exports.g = It; exports.h = jt;
2
+ //# sourceMappingURL=chunk-6ISGLRK2.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-Z6ITPS2B.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","isValid","isDirty","isSubmitting","canUndo","canRedo","nextMeta","metaState","useSyncExternalStore","submit","onSuccess","e","onSubmit","handler","values","result","err","isValidationErrorShape","extractServerErrors","reset","getValues","getErrors","getTouched","actions","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,IARA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AMgB,CAAAA,CAAMC,CAAE,CAC/B,CAAA,CACA,IAAA,CAAM,CAACE,CAAAA,CAAgBC,CAAAA,CAAAA,EAAmB,CACxCd,CAAAA,CAAQK,CAAAA,EAAS,CACf,IAAME,CAAAA,CAAS,CAAC,GAAGF,CAAI,CAAA,CACvB,MAAA,CAACE,CAAAA,CAAOM,CAAM,CAAA,CAAGN,CAAAA,CAAOO,CAAM,CAAC,CAAA,CAAI,CAACP,CAAAA,CAAOO,CAAM,CAAA,CAAGP,CAAAA,CAAOM,CAAM,CAAC,CAAA,CAC3DN,CACT,CAAC,CAAA,CACDvD,CAAAA,CAAM,SAAA,CAAU0C,CAAAA,CAAMmB,CAAAA,CAAQC,CAAM,CACtC,CAAA,CACA,OAAA,CAAUC,CAAAA,EAAkB,CAC1Bf,CAAAA,CAAOe,CAAAA,CAAM,GAAA,CAAIvB,CAAU,CAAC,CAAA,CAC5BxC,CAAAA,CAAM,QAAA,CAAS0C,CAAAA,CAAmCqB,CAAY,CAChE,CAAA,CACA,KAAA,CAAO,CAAA,CAAA,EAAM,CACXf,CAAAA,CAAO,CAAC,CAAC,CAAA,CACThD,CAAAA,CAAM,QAAA,CAAS0C,CAAAA,CAAmC,CAAC,CAAQ,CAC7D,CACF,CAAA,CAAA,CACA,CAAC1C,CAAAA,CAAO0C,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-Z6ITPS2B.cjs","sourcesContent":[null,"import React, { createContext, useContext } from \"react\";\nimport { BitStore } from \"../core\";\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 { useCallback, useSyncExternalStore, useMemo, useRef, useState } 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\n const lastMeta = useRef<{\n isValid: boolean;\n isDirty: boolean;\n isSubmitting: boolean;\n canUndo: boolean;\n canRedo: boolean;\n } | null>(null);\n\n const getMetaSnapshot = useCallback(() => {\n const state = store.getState();\n const { isValid, isDirty, isSubmitting } = state;\n const canUndo = store.canUndo;\n const canRedo = store.canRedo;\n\n if (\n lastMeta.current &&\n lastMeta.current.isValid === isValid &&\n lastMeta.current.isDirty === isDirty &&\n lastMeta.current.isSubmitting === isSubmitting &&\n lastMeta.current.canUndo === canUndo &&\n lastMeta.current.canRedo === canRedo\n ) {\n return lastMeta.current;\n }\n\n const nextMeta = { isValid, isDirty, isSubmitting, canUndo, canRedo };\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 (onSuccess: (values: T) => void | Promise<void>) => {\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) => Promise<unknown>) => {\n return (e?: { preventDefault: () => void }) => {\n e?.preventDefault?.();\n setSubmitError(null);\n\n return store.submit(async (values) => {\n try {\n const result = await handler(values);\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\n const actions = useMemo(\n () => ({\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 reset,\n validate: store.validate.bind(store),\n registerMask: store.registerMask.bind(store),\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 undo: store.undo.bind(store),\n redo: store.redo.bind(store),\n }),\n [store, reset],\n );\n\n return {\n ...metaState,\n getValues,\n getErrors,\n getTouched,\n submit,\n onSubmit,\n submitError,\n lastResponse,\n ...actions,\n reset,\n store,\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-6ISGLRK2.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","isValid","isDirty","isSubmitting","canUndo","canRedo","nextMeta","metaState","useSyncExternalStore","submit","onSuccess","e","onSubmit","handler","values","result","err","isValidationErrorShape","extractServerErrors","reset","getValues","getErrors","getTouched","actions","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,CAAQ,QAAA,CAAAC,CAAAA,CAAS,CAAA,CAEtCE,CAAAA,aAAc,CAAA,CAAA,EAAwB,CACjD,IAAMH,CAAAA,CAAQI,+BAAAA,CAAqB,CAAA,CACnC,EAAA,CAAI,CAACJ,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,6DACF,CAAA,CACF,OAAOA,CACT,CAAA,CCpBA,SAIgBK,EAAAA,CAAAA,CAA+B,CAC7C,IAAML,CAAAA,CAAQG,CAAAA,CAAe,CAAA,CAEvB,CAACG,CAAAA,CAAaC,CAAc,CAAA,CAAIC,6BAAAA,IAA2B,CAAA,CAC3D,CAACC,CAAAA,CAAcC,CAAe,CAAA,CAAIF,6BAAAA,IAAsB,CAAA,CAExDG,CAAAA,CAAWC,2BAAAA,IAMH,CAAA,CAERC,CAAAA,CAAkBC,gCAAAA,CAAY,CAAA,EAAM,CACxC,IAAMC,CAAAA,CAAQf,CAAAA,CAAM,QAAA,CAAS,CAAA,CACvB,CAAE,OAA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AAO0C,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-6ISGLRK2.cjs","sourcesContent":[null,"import React, { createContext, useContext } from \"react\";\nimport { BitStore } from \"../core\";\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 { useCallback, useSyncExternalStore, useMemo, useRef, useState } 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\n const lastMeta = useRef<{\n isValid: boolean;\n isDirty: boolean;\n isSubmitting: boolean;\n canUndo: boolean;\n canRedo: boolean;\n } | null>(null);\n\n const getMetaSnapshot = useCallback(() => {\n const state = store.getState();\n const { isValid, isDirty, isSubmitting } = state;\n const canUndo = store.canUndo;\n const canRedo = store.canRedo;\n\n if (\n lastMeta.current &&\n lastMeta.current.isValid === isValid &&\n lastMeta.current.isDirty === isDirty &&\n lastMeta.current.isSubmitting === isSubmitting &&\n lastMeta.current.canUndo === canUndo &&\n lastMeta.current.canRedo === canRedo\n ) {\n return lastMeta.current;\n }\n\n const nextMeta = { isValid, isDirty, isSubmitting, canUndo, canRedo };\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 (onSuccess: (values: T) => void | Promise<void>) => {\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) => Promise<unknown>) => {\n return (e?: { preventDefault: () => void }) => {\n e?.preventDefault?.();\n setSubmitError(null);\n\n return store.submit(async (values) => {\n try {\n const result = await handler(values);\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\n const actions = useMemo(\n () => ({\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 reset,\n validate: store.validate.bind(store),\n registerMask: store.registerMask.bind(store),\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 undo: store.undo.bind(store),\n redo: store.redo.bind(store),\n }),\n [store, reset],\n );\n\n return {\n ...metaState,\n getValues,\n getErrors,\n getTouched,\n submit,\n onSubmit,\n submitError,\n lastResponse,\n ...actions,\n reset,\n store,\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,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 F=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;F.__BIT_FORM__||(F.__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=F.__BIT_FORM__;function g(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=>g(e));let t={};for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&(t[e]=g(o[e]));return t}function S(o,t){return o===t?!0:o===null||typeof o!="object"||t===null||typeof t!="object"?!1:x(o,t)}function x(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)||!x(o[r],t[r]))return!1;return!0}function O(o,t,e="",s=new Set){if(S(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!S(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;O(_optionalChain([o, 'optionalAccess', _2 => _2[i]]),_optionalChain([t, 'optionalAccess', _3 => _3[i]]),n,s)}return s}var k=new Map;function p(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 l=s[n],a=s[n+1],c=/^\d+$/.test(a),d=i[l];d==null?i[l]=c?[]:{}:i[l]=Array.isArray(d)?[...d]:{...d},i=i[l]}return i[s[s.length-1]]=e,r}function kt(o,t){let e={},s=`${t}.`;for(let r in o)r!==t&&!r.startsWith(s)&&(e[r]=o[r]);return e}var $=(o,t,e)=>{let s={},r=`${t}.`;return Object.keys(o).forEach(i=>{if(!i.startsWith(r)){s[i]=o[i];return}let l=i.substring(r.length).split("."),a=parseInt(l[0],10),c=l.slice(1).join(".");if(a!==e)if(a>e){let d=a-1,f=c?`${r}${d}.${c}`:`${r}${d}`;s[f]=o[i]}else s[i]=o[i]}),s},U=(o,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(o).forEach(n=>{if(!n.startsWith(i)){r[n]=o[n];return}let a=n.substring(i.length).split("."),c=parseInt(a[0],10),d=a.slice(1).join(".");if(c===e){let f=d?`${i}${s}.${d}`:`${i}${s}`;r[f]=o[n]}else if(c===s){let f=d?`${i}${e}.${d}`:`${i}${e}`;r[f]=o[n]}else r[n]=o[n]}),r},L=(o,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(o).forEach(n=>{if(!n.startsWith(i)){r[n]=o[n];return}let a=n.substring(i.length).split("."),c=parseInt(a[0],10),d=a.slice(1).join("."),f=c;c===e?f=s:e<s&&c>e&&c<=s?f=c-1:e>s&&c>=s&&c<e&&(f=c+1);let h=d?`${i}${f}.${d}`:`${i}${f}`;r[h]=o[n]}),r};function gt(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 Bt(o){return gt(o)?_nullishCoalesce(o.errors, () => (o)):{}}var ht={"#":/\d/,A:/[a-zA-Z]/,X:/[a-zA-Z0-9]/,H:/[0-9a-fA-F]/,U:/[A-Z]/,L:/[a-z]/,"*":/./},B= 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},mt= 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},u= exports.l =(o,t)=>{let e=s=>s.split("").filter(r=>ht[r]).length;return{format:s=>{let r=B(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)),l=n[n.length-1];for(let h of n)if(r.length<=e(h)){l=h;break}let a="",c=0,d=_optionalChain([t, 'optionalAccess', _6 => _6.guide])||!1,f=_optionalChain([t, 'optionalAccess', _7 => _7.placeholderChar])||"_";for(let h=0;h<l.length;h++){let v=l[h],E=ht[v];if(c<r.length){let T=r[c];if(E)if(v==="U"&&(T=T.toUpperCase()),v==="L"&&(T=T.toLowerCase()),E.test(T))a+=T,c++;else if(d)a+=f;else break;else a+=v,T===v&&c++}else if(d)a+=E?f:v;else break}return a},parse:s=>{if(_optionalChain([t, 'optionalAccess', _8 => _8.customParse]))return t.customParse(s);let i=u(o,t).format(s);if(_optionalChain([t, 'optionalAccess', _9 => _9.saveRaw])){if(_optionalChain([t, 'optionalAccess', _10 => _10.guide])){let l=(t.placeholderChar||"_").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(l,"g");return i.replace(a,"")}return i}return B(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 l=a=>{if(a==null||a==="")return"";let c="";if(typeof a=="number"?c=Math.abs(a).toFixed(r).replace(/\D/g,""):c=String(a).replace(/\D/g,""),!c&&String(a).includes("-")&&i)return"-";if(!c)return"";c=c.padStart(r+1,"0");let d=c.slice(0,-r).replace(/^0+(?=\d)/,"")||"0",f=c.slice(-r),h=d.replace(/\B(?=(\d{3})+(?!\d))/g,e);return`${(typeof a=="number"?a<0:String(a).includes("-"))&&i?"-":""}${o}${h}${s}${f}${t}`};return{format:l,parse:a=>{let c=mt(a,r),d=i?c:Math.abs(c);return n?l(d):d}}},N= exports.n =o=>{let t=e=>/^3[47]/.test(e)?"#### ###### #####":/^3(?:0[0-5]|[68])/.test(e)?"#### ###### ####":"#### #### #### ####";return{format:e=>{let s=B(e,_optionalChain([o, 'optionalAccess', _12 => _12.allowChars])),r=t(s);return u(r,o).format(e)},parse:e=>{let s=B(e,_optionalChain([o, 'optionalAccess', _13 => _13.allowChars])),r=t(s);return u(r,o).parse(e)}}},P= exports.o =o=>{let e=(_optionalChain([o, 'optionalAccess', _14 => _14.format])||"DD/MM/YYYY")==="YYYY-MM-DD",s=u(e?"####-##-##":"##/##/####",o);return{format:r=>{let i=B(r);if(!i)return"";let n="",l="",a="";if(e?(a=i.substring(0,4),l=i.substring(4,6),n=i.substring(6,8)):(n=i.substring(0,2),l=i.substring(2,4),a=i.substring(4,8)),n.length===2){let d=parseInt(n,10);d>31&&(n="31"),d===0&&(n="01")}if(l.length===2){let d=parseInt(l,10);d>12&&(l="12"),d===0&&(l="01")}let c=e?`${a}${l}${n}`:`${n}${l}${a}`;return s.format(c)},parse:r=>s.parse(r)}};var _=b({prefix:"R$ ",thousand:".",decimal:",",precision:2}),j= exports.q =b({prefix:"$",thousand:",",decimal:".",precision:2}),X= exports.r =b({suffix:" \u20AC",thousand:".",decimal:",",precision:2}),q= exports.s =b({prefix:"\xA3",thousand:",",decimal:".",precision:2}),W= exports.t =b({prefix:"\xA5",thousand:",",decimal:".",precision:0}),z= exports.u =b({suffix:"%",thousand:".",decimal:",",precision:1}),Y= exports.v =b({thousand:".",decimal:",",precision:2}),J= exports.w =b({thousand:".",decimal:",",precision:0}),K= exports.x =u("###.###.###-##"),G= exports.y =u("##.###.###/####-##"),Z= exports.z =u(["(##) ####-####","(##) #####-####"]),Q= exports.A =u("(##) ####-####"),tt= exports.B =u("#####-###"),et= 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,"")}}),st= exports.D =u("##:##"),rt= exports.E =u("###########"),it= exports.F =u("##.###.###-X"),Mt= exports.G =u("(###) ###-####"),Et= exports.H =u("#####-####"),Pt= exports.I =u("##/##/####"),Ct= exports.J =u("###-##-####"),ot= exports.K =N(),nt= exports.L =u("####"),Dt= exports.M =P({format:"YYYY-MM-DD",saveRaw:!0,guide:!0}),at= exports.N =u("HH:HH:HH:HH:HH:HH"),lt= exports.O =u("#HHHHHH"),ct= exports.P =u("###.###.###.###"),dt= exports.Q =u("HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH"),wt= exports.R =u("UU## XXXX XXXX XXXX XXXX XXXX XXXX XXXX XX",{allowChars:" "});var ut={brl:_,usd:j,eur:X,gbp:q,jpy:W,cpf:K,cnpj:G,rg:it,cep:tt,cnh:rt,phone:Z,landline:Q,date:et,time:st,ip:ct,ipv6:dt,mac:at,color:lt,cc:ot,cvv:nt,percent:z,decimal:Y,int:J};function Rt(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 yt(o={}){let t=o.initialValues||{},e=o.validation,s=o.history,{computed:r,transform:i,scopes:n}=Rt(o.fields);return{name:o.name,initialValues:g(t),resolver:_optionalChain([e, 'optionalAccess', _18 => _18.resolver]),validationDelay:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _19 => _19.delay]), () => (300)),defaultRequiredMessage:_optionalChain([e, 'optionalAccess', _20 => _20.defaultRequiredMessage]),enableHistory:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _21 => _21.enabled]), () => (!1)),historyLimit:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _22 => _22.limit]), () => (15)),computed:r,transform:i,scopes:n,masks:ut,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', _23 => _23.conditional, 'optionalAccess', _24 => _24.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', _25 => _25.conditional, 'optionalAccess', _26 => _26.requiredIf, 'optionalCall', _27 => _27(e)])}getRequiredErrors(t,e="Este campo \xE9 obrigat\xF3rio"){let s={};return this.fieldConfigs.forEach((r,i)=>{if(this.isRequired(i,t)){let n=p(t,i);this.isEmpty(n)&&(s[i]=_nullishCoalesce(_optionalChain([r, 'access', _28 => _28.validation, 'optionalAccess', _29 => _29.requiredMessage]), () => (e)))}}),s}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 l=this.isHidden(i);n!==l&&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', _30 => _30.fieldConfigs, 'access', _31 => _31.get, 'call', _32 => _32(t), 'optionalAccess', _33 => _33.conditional, 'optionalAccess', _34 => _34.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&&x(e,t)||(this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push(g(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--,g(this.history[this.historyIndex])):null}redo(){return this.canRedo?(this.historyIndex++,g(this.history[this.historyIndex])):null}reset(t){this.history=[],this.historyIndex=-1,this.saveSnapshot(t)}}, _class2);var w=class{constructor(t){this.store=t}pushItem(t,e){let s=p(this.store.getState().values,t)||[];this.store.setField(t,[...s,e]),this.store.internalSaveSnapshot()}prependItem(t,e){let s=p(this.store.getState().values,t)||[];this.store.setField(t,[e,...s]),this.store.internalSaveSnapshot()}insertItem(t,e,s){let r=[...p(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=p(s.values,t);if(!Array.isArray(r))return;this.store.unregisterPrefix&&this.store.unregisterPrefix(`${t}.${e}.`);let i=r.filter((a,c)=>c!==e),n=y(s.values,t,i),l=this.store.updateDirtyForPath(t,n,this.store.getConfig().initialValues);this.store.internalUpdateState({values:n,errors:$(s.errors,t,e),touched:$(s.touched,t,e),isDirty:l}),this.store.internalSaveSnapshot(),this.revalidate(t)}swapItems(t,e,s){let r=this.store.getState(),i=[...p(r.values,t)||[]];[i[e],i[s]]=[i[s],i[e]];let n=y(r.values,t,i),l=this.store.updateDirtyForPath(t,n,this.store.getConfig().initialValues);this.store.internalUpdateState({values:n,errors:U(r.errors,t,e,s),touched:U(r.touched,t,e,s),isDirty:l}),this.store.internalSaveSnapshot(),this.revalidate(t)}moveItem(t,e,s){let r=this.store.getState(),i=[...p(r.values,t)||[]],[n]=i.splice(e,1);i.splice(s,0,n);let l=y(r.values,t,i),a=this.store.updateDirtyForPath(t,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:L(r.errors,t,e,s),touched:L(r.touched,t,e,s),isDirty:a}),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 I=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,l]of s){let a=l(e),c=p(e,n);x(c,a)||(e=y(e,n,a),i=!0)}if(!i)break}return e}};var R= (_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', _35 => _35.store, 'access', _36 => _36.config, 'access', _37 => _37.fields, 'optionalAccess', _38 => _38[t]]),r=_optionalChain([s, 'optionalAccess', _39 => _39.validation, 'optionalAccess', _40 => _40.asyncValidate]);if(!r)return;this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]);let i=_nullishCoalesce(_optionalChain([s, 'access', _41 => _41.validation, 'optionalAccess', _42 => _42.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 l=await r(e,this.store.getState().values);if(this.asyncRequests[t]!==n)return;if(l)this.asyncErrors[t]=l,this.store.setError(t,l);else{delete this.asyncErrors[t];let a=this.store;if(a.validate)await a.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', _43 => _43.scopeFields]);_optionalChain([t, 'optionalAccess', _44 => _44.scope])&&_optionalChain([this, 'access', _45 => _45.store, 'access', _46 => _46.config, 'access', _47 => _47.scopes, 'optionalAccess', _48 => _48[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,this.store.config.defaultRequiredMessage);if(i={...i,...n},this.store.depsMg.hiddenFields.forEach(a=>{delete i[a],delete this.asyncErrors[a]}),e!==this.currentValidationId)return s.isValid;if(r){let a={...s.errors};r.forEach(d=>{i[d]?a[d]=i[d]:this.asyncErrors[d]?a[d]=this.asyncErrors[d]:delete a[d]});let c=Object.keys(a).length===0;return this.store.internalUpdateState({errors:a,isValid:c}),r.every(d=>!i[d]&&!this.asyncErrors[d])}i={...this.asyncErrors,...i};let l=Object.keys(i).length===0;return this.store.internalUpdateState({errors:i,isValid:l}),l}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 V=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(a=>{this.store.depsMg.isHidden(a)&&(delete i[a],this.store.validatorMg.clear(a))});let l=this.store.updateDirtyForPath(t,r,this.store.config.initialValues);return this.store.internalUpdateState({values:r,errors:i,isValid:Object.keys(i).length===0,isDirty:l}),this.store.config.resolver&&this.store.validatorMg.trigger([t]),this.store.validatorMg.handleAsync(t,e),{visibilitiesChanged:n.length>0}}updateAll(t){let e=g(t);this.store.config.initialValues=g(e),this.store.validatorMg.cancelAll(),this.store.depsMg.evaluateAll(e),this.store.clearDirtyPaths(),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=g(this.store.getState().values);if(this.store.depsMg.hiddenFields.forEach(i=>{r=y(r,i,void 0)}),this.store.config.transform)for(let i in this.store.config.transform){let n=this.store.config.transform[i];if(n){let l=p(r,i);r=y(r,i,n(l,this.store.getState().values))}}await t(r)}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=g(this.store.config.initialValues);this.store.depsMg.evaluateAll(t),this.store.clearDirtyPaths(),this.store.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.historyMg.reset(t)}};function bt(){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 F=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;F.__BIT_FORM__||(F.__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=F.__BIT_FORM__;function g(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=>g(e));let t={};for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&(t[e]=g(n[e]));return t}function S(n,t){return n===t?!0:n===null||typeof n!="object"||t===null||typeof t!="object"?!1:x(n,t)}function x(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)||!x(n[r],t[r]))return!1;return!0}function O(n,t,e="",s=new Set){if(S(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!S(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;O(_optionalChain([n, 'optionalAccess', _2 => _2[i]]),_optionalChain([t, 'optionalAccess', _3 => _3[i]]),o,s)}return s}var k=new Map;function p(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 l=s[o],a=s[o+1],c=/^\d+$/.test(a),d=i[l];d==null?i[l]=c?[]:{}:i[l]=Array.isArray(d)?[...d]:{...d},i=i[l]}return i[s[s.length-1]]=e,r}function kt(n,t){let e={},s=`${t}.`;for(let r in n)r!==t&&!r.startsWith(s)&&(e[r]=n[r]);return e}var $=(n,t,e)=>{let s={},r=`${t}.`;return Object.keys(n).forEach(i=>{if(!i.startsWith(r)){s[i]=n[i];return}let l=i.substring(r.length).split("."),a=parseInt(l[0],10),c=l.slice(1).join(".");if(a!==e)if(a>e){let d=a-1,f=c?`${r}${d}.${c}`:`${r}${d}`;s[f]=n[i]}else s[i]=n[i]}),s},U=(n,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(n).forEach(o=>{if(!o.startsWith(i)){r[o]=n[o];return}let a=o.substring(i.length).split("."),c=parseInt(a[0],10),d=a.slice(1).join(".");if(c===e){let f=d?`${i}${s}.${d}`:`${i}${s}`;r[f]=n[o]}else if(c===s){let f=d?`${i}${e}.${d}`:`${i}${e}`;r[f]=n[o]}else r[o]=n[o]}),r},L=(n,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(n).forEach(o=>{if(!o.startsWith(i)){r[o]=n[o];return}let a=o.substring(i.length).split("."),c=parseInt(a[0],10),d=a.slice(1).join("."),f=c;c===e?f=s:e<s&&c>e&&c<=s?f=c-1:e>s&&c>=s&&c<e&&(f=c+1);let h=d?`${i}${f}.${d}`:`${i}${f}`;r[h]=n[o]}),r};function gt(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 Bt(n){return gt(n)?_nullishCoalesce(n.errors, () => (n)):{}}var ht={"#":/\d/,A:/[a-zA-Z]/,X:/[a-zA-Z0-9]/,H:/[0-9a-fA-F]/,U:/[A-Z]/,L:/[a-z]/,"*":/./},B= 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},mt= 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},u= exports.l =(n,t)=>{let e=s=>s.split("").filter(r=>ht[r]).length;return{format:s=>{let r=B(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)),l=o[o.length-1];for(let h of o)if(r.length<=e(h)){l=h;break}let a="",c=0,d=_optionalChain([t, 'optionalAccess', _6 => _6.guide])||!1,f=_optionalChain([t, 'optionalAccess', _7 => _7.placeholderChar])||"_";for(let h=0;h<l.length;h++){let v=l[h],E=ht[v];if(c<r.length){let T=r[c];if(E)if(v==="U"&&(T=T.toUpperCase()),v==="L"&&(T=T.toLowerCase()),E.test(T))a+=T,c++;else if(d)a+=f;else break;else a+=v,T===v&&c++}else if(d)a+=E?f:v;else break}return a},parse:s=>{if(_optionalChain([t, 'optionalAccess', _8 => _8.customParse]))return t.customParse(s);let i=u(n,t).format(s);if(_optionalChain([t, 'optionalAccess', _9 => _9.saveRaw])){if(_optionalChain([t, 'optionalAccess', _10 => _10.guide])){let l=(t.placeholderChar||"_").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(l,"g");return i.replace(a,"")}return i}return B(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 l=a=>{if(a==null||a==="")return"";let c="";if(typeof a=="number"?c=Math.abs(a).toFixed(r).replace(/\D/g,""):c=String(a).replace(/\D/g,""),!c&&String(a).includes("-")&&i)return"-";if(!c)return"";c=c.padStart(r+1,"0");let d=c.slice(0,-r).replace(/^0+(?=\d)/,"")||"0",f=c.slice(-r),h=d.replace(/\B(?=(\d{3})+(?!\d))/g,e);return`${(typeof a=="number"?a<0:String(a).includes("-"))&&i?"-":""}${n}${h}${s}${f}${t}`};return{format:l,parse:a=>{let c=mt(a,r),d=i?c:Math.abs(c);return o?l(d):d}}},N= exports.n =n=>{let t=e=>/^3[47]/.test(e)?"#### ###### #####":/^3(?:0[0-5]|[68])/.test(e)?"#### ###### ####":"#### #### #### ####";return{format:e=>{let s=B(e,_optionalChain([n, 'optionalAccess', _12 => _12.allowChars])),r=t(s);return u(r,n).format(e)},parse:e=>{let s=B(e,_optionalChain([n, 'optionalAccess', _13 => _13.allowChars])),r=t(s);return u(r,n).parse(e)}}},P= exports.o =n=>{let e=(_optionalChain([n, 'optionalAccess', _14 => _14.format])||"DD/MM/YYYY")==="YYYY-MM-DD",s=u(e?"####-##-##":"##/##/####",n);return{format:r=>{let i=B(r);if(!i)return"";let o="",l="",a="";if(e?(a=i.substring(0,4),l=i.substring(4,6),o=i.substring(6,8)):(o=i.substring(0,2),l=i.substring(2,4),a=i.substring(4,8)),o.length===2){let d=parseInt(o,10);d>31&&(o="31"),d===0&&(o="01")}if(l.length===2){let d=parseInt(l,10);d>12&&(l="12"),d===0&&(l="01")}let c=e?`${a}${l}${o}`:`${o}${l}${a}`;return s.format(c)},parse:r=>s.parse(r)}};var _=b({prefix:"R$ ",thousand:".",decimal:",",precision:2}),j= exports.q =b({prefix:"$",thousand:",",decimal:".",precision:2}),X= exports.r =b({suffix:" \u20AC",thousand:".",decimal:",",precision:2}),q= exports.s =b({prefix:"\xA3",thousand:",",decimal:".",precision:2}),W= exports.t =b({prefix:"\xA5",thousand:",",decimal:".",precision:0}),z= exports.u =b({suffix:"%",thousand:".",decimal:",",precision:1}),Y= exports.v =b({thousand:".",decimal:",",precision:2}),J= exports.w =b({thousand:".",decimal:",",precision:0}),K= exports.x =u("###.###.###-##"),G= exports.y =u("##.###.###/####-##"),Z= exports.z =u(["(##) ####-####","(##) #####-####"]),Q= exports.A =u("(##) ####-####"),tt= exports.B =u("#####-###"),et= exports.C =P({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,"")}}),st= exports.D =u("##:##"),rt= exports.E =u("###########"),it= exports.F =u("##.###.###-X"),Mt= exports.G =u("(###) ###-####"),Et= exports.H =u("#####-####"),Pt= exports.I =u("##/##/####"),Ct= exports.J =u("###-##-####"),nt= exports.K =N(),ot= exports.L =u("####"),Dt= exports.M =P({format:"YYYY-MM-DD",saveRaw:!0,guide:!0}),at= exports.N =u("HH:HH:HH:HH:HH:HH"),lt= exports.O =u("#HHHHHH"),ct= exports.P =u("###.###.###.###"),dt= exports.Q =u("HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH"),wt= exports.R =u("UU## XXXX XXXX XXXX XXXX XXXX XXXX XXXX XX",{allowChars:" "});var ut={brl:_,usd:j,eur:X,gbp:q,jpy:W,cpf:K,cnpj:G,rg:it,cep:tt,cnh:rt,phone:Z,landline:Q,date:et,time:st,ip:ct,ipv6:dt,mac:at,color:lt,cc:nt,cvv:ot,percent:z,decimal:Y,int:J};function Vt(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 yt(n={}){let t=n.initialValues||{},e=n.validation,s=n.history,{computed:r,transform:i,scopes:o}=Vt(n.fields);return{name:n.name,initialValues:g(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:ut,fields:n.fields,devTools:n.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=p(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 l=this.isHidden(i);o!==l&&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&&x(e,t)||(this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push(g(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--,g(this.history[this.historyIndex])):null}redo(){return this.canRedo?(this.historyIndex++,g(this.history[this.historyIndex])):null}reset(t){this.history=[],this.historyIndex=-1,this.saveSnapshot(t)}}, _class2);var w=class{constructor(t){this.store=t}pushItem(t,e){let s=p(this.store.getState().values,t)||[];this.store.setField(t,[...s,e]),this.store.internalSaveSnapshot()}prependItem(t,e){let s=p(this.store.getState().values,t)||[];this.store.setField(t,[e,...s]),this.store.internalSaveSnapshot()}insertItem(t,e,s){let r=[...p(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=p(s.values,t);if(!Array.isArray(r))return;this.store.unregisterPrefix&&this.store.unregisterPrefix(`${t}.${e}.`);let i=r.filter((a,c)=>c!==e),o=y(s.values,t,i),l=this.store.updateDirtyForPath(t,o,this.store.getConfig().initialValues);this.store.internalUpdateState({values:o,errors:$(s.errors,t,e),touched:$(s.touched,t,e),isDirty:l}),this.store.internalSaveSnapshot(),this.revalidate(t)}swapItems(t,e,s){let r=this.store.getState(),i=[...p(r.values,t)||[]];[i[e],i[s]]=[i[s],i[e]];let o=y(r.values,t,i),l=this.store.updateDirtyForPath(t,o,this.store.getConfig().initialValues);this.store.internalUpdateState({values:o,errors:U(r.errors,t,e,s),touched:U(r.touched,t,e,s),isDirty:l}),this.store.internalSaveSnapshot(),this.revalidate(t)}moveItem(t,e,s){let r=this.store.getState(),i=[...p(r.values,t)||[]],[o]=i.splice(e,1);i.splice(s,0,o);let l=y(r.values,t,i),a=this.store.updateDirtyForPath(t,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:L(r.errors,t,e,s),touched:L(r.touched,t,e,s),isDirty:a}),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 I=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,l]of s){let a=l(e),c=p(e,o);x(c,a)||(e=y(e,o,a),i=!0)}if(!i)break}return e}};var V= (_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 l=await r(e,this.store.getState().values);if(this.asyncRequests[t]!==o)return;if(l)this.asyncErrors[t]=l,this.store.setError(t,l);else{delete this.asyncErrors[t];let a=this.store;if(a.validate)await a.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(a=>{delete i[a],delete this.asyncErrors[a]}),e!==this.currentValidationId)return s.isValid;if(r){let a={...s.errors};r.forEach(d=>{i[d]?a[d]=i[d]:this.asyncErrors[d]?a[d]=this.asyncErrors[d]:delete a[d]});let c=Object.keys(a).length===0;return this.store.internalUpdateState({errors:a,isValid:c}),r.every(d=>!i[d]&&!this.asyncErrors[d])}i={...this.asyncErrors,...i};let l=Object.keys(i).length===0;return this.store.internalUpdateState({errors:i,isValid:l}),l}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 R=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(a=>{this.store.depsMg.isHidden(a)&&(delete i[a],this.store.validatorMg.clear(a))});let l=this.store.updateDirtyForPath(t,r,this.store.config.initialValues);return this.store.internalUpdateState({values:r,errors:i,isValid:Object.keys(i).length===0,isDirty:l}),this.store.config.resolver&&this.store.validatorMg.trigger([t]),this.store.validatorMg.handleAsync(t,e),{visibilitiesChanged:o.length>0}}updateAll(t){let e=g(t);this.store.config.initialValues=g(e),this.store.validatorMg.cancelAll(),this.store.depsMg.evaluateAll(e),this.store.clearDirtyPaths(),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=g(this.store.getState().values);if(this.store.depsMg.hiddenFields.forEach(i=>{r=y(r,i,void 0)}),this.store.config.transform)for(let i in this.store.config.transform){let o=this.store.config.transform[i];if(o){let l=p(r,i);r=y(r,i,o(l,this.store.getState().values))}}await t(r)}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=g(this.store.config.initialValues);this.store.depsMg.evaluateAll(t),this.store.clearDirtyPaths(),this.store.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.historyMg.reset(t)}};function bt(){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 M= (_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=bt(),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"),l=i.getAttribute("data-store");n&&l&&(n==="undo"&&this.actions.onUndo(l),n==="redo"&&this.actions.onRedo(l),n==="reset"&&this.actions.onReset(l))}})}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 M= (_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=bt(),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"),l=i.getAttribute("data-store");o&&l&&(o==="undo"&&this.actions.onUndo(l),o==="redo"&&this.actions.onRedo(l),o==="reset"&&this.actions.onReset(l))}})}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 n=Object.keys(i.errors||{}).length>0,l=i._meta||{totalSteps:0,currentIndex:-1,canUndo:!1,canRedo:!1},a=l.currentIndex+1,c=l.totalSteps;e+=`
95
+ `;for(let[r,i]of t){let o=Object.keys(i.errors||{}).length>0,l=i._meta||{totalSteps:0,currentIndex:-1,canUndo:!1,canRedo:!1},a=l.currentIndex+1,c=l.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
- `,n&&(e+=`
121
+ `,o&&(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 vt(o){let t=new M(o,{onUndo:r=>_optionalChain([m, 'access', _49 => _49.stores, 'access', _50 => _50[r], 'optionalAccess', _51 => _51.undo, 'call', _52 => _52()]),onRedo:r=>_optionalChain([m, 'access', _53 => _53.stores, 'access', _54 => _54[r], 'optionalAccess', _55 => _55.redo, 'call', _56 => _56()]),onReset:r=>_optionalChain([m, 'access', _57 => _57.stores, 'access', _58 => _58[r], 'optionalAccess', _59 => _59.reset, 'call', _60 => _60()])}),e=()=>{let r={};for(let[i,n]of Object.entries(m.stores)){let l=n,a=l.getState(),c=_optionalChain([l, 'optionalAccess', _61 => _61.historyMg]),d=_optionalChain([c, 'optionalAccess', _62 => _62.history])||[],f=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _63 => _63.historyIndex]), () => (-1));r[i]={...a,_meta:{canUndo:_optionalChain([l, 'optionalAccess', _64 => _64.canUndo]),canRedo:_optionalChain([l, 'optionalAccess', _65 => _65.canRedo]),totalSteps:d.length,currentIndex:f}}}return r};t.updateState(e());let s=m.subscribe(()=>{t.updateState(e())});return{ui:t,destroy:()=>{s(),o.innerHTML=""}}}function xt(o,t="ws://localhost:3000"){let e=new WebSocket(t),s=new M(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 ft(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=vt(s);else if(t==="remote")console.log("[bit-form] DevTools iniciado em modo Remote."),i=xt(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=Tt(s)}else{let s=ft();s&&typeof s.destroy=="function"&&(this.cleanupFn=s.destroy)}}destroy(){this.cleanupFn&&this.cleanupFn()}}, _class5);var pt= (_class6 =class{__init13() {this.listeners=new Set}__init14() {this.dirtyPaths=new Set}__init15() {this.configFields=new Set}constructor(t={}){;_class6.prototype.__init13.call(this);_class6.prototype.__init14.call(this);_class6.prototype.__init15.call(this);this.config=yt(t),this.depsMg=new C,this.historyMg=new D(!!this.config.enableHistory,_nullishCoalesce(this.config.historyLimit, () => (15))),this.computedMg=new I(this.config),this.validatorMg=new R(this),this.arraysMg=new w(this),this.lifecycleMg=new V(this),this.devtoolsMg=new H(this);let e=g(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.configFields.add(r),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}unregisterField(t){if(this.configFields.has(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)}registerField(t,e){this.depsMg.register(t,e,this.state.values),this.depsMg.isHidden(t)&&this.notify()}isHidden(t){return this.depsMg.isHidden(t)}isRequired(t){return this.depsMg.isRequired(t,this.state.values)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}watch(t,e){let s=g(p(this.state.values,t));return this.subscribe(()=>{let r=p(this.state.values,t);x(r,s)||(s=g(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){let s={...this.state.errors,[t]:e};e||delete s[t],this.internalUpdateState({errors:s})}setErrors(t){this.internalUpdateState({errors:{...this.state.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)}reset(){this.lifecycleMg.reset()}registerMask(t,e){this.config.masks[t]=e}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.rebuildDirtyPaths(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}redo(){let t=this.historyMg.redo();if(t){let e=this.rebuildDirtyPaths(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}validate(t){return this.validatorMg.validate(t)}getStepStatus(t){let e=_optionalChain([this, 'access', _66 => _66.config, 'access', _67 => _67.scopes, 'optionalAccess', _68 => _68[t]])||[],s=e.some(n=>!!this.state.errors[n]),r=e.some(n=>{let l=p(this.state.values,n),a=p(this.config.initialValues,n);return!S(l,a)}),i=this.getStepErrors(t);return{hasErrors:s,isDirty:r,errors:i}}getStepErrors(t){let e=_optionalChain([this, 'access', _69 => _69.config, 'access', _70 => _70.scopes, 'optionalAccess', _71 => _71[t]])||[],s={};for(let r of e){let i=this.state.errors[r];i&&(s[r]=i)}return s}isFieldDirty(t){let e=p(this.state.values,t),s=p(this.config.initialValues,t);return!S(e,s)}isFieldValidating(t){return!!this.getState().isValidating[t]}async submit(t){return this.lifecycleMg.submit(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)}updateDirtyForPath(t,e,s){for(let n of this.dirtyPaths)n.startsWith(t+".")&&this.dirtyPaths.delete(n);let r=p(e,t),i=p(s,t);return S(r,i)?this.dirtyPaths.delete(t):this.dirtyPaths.add(t),this.dirtyPaths.size>0}clearDirtyPaths(){this.dirtyPaths.clear()}rebuildDirtyPaths(t,e){return this.dirtyPaths=O(t,e),this.dirtyPaths.size>0}cleanup(){this.listeners.clear(),this.validatorMg.cancelAll(),delete m.stores[this.storeId]}notify(){this.listeners.forEach(t=>t())}}, _class6);var St=o=>({...typeof o.getState=="function"?o.getState():o,_meta:{canUndo:o.canUndo,canRedo:o.canRedo,totalSteps:_optionalChain([o, 'access', _72 => _72.historyMg, 'optionalAccess', _73 => _73.history, 'optionalAccess', _74 => _74.length])||0,currentIndex:_nullishCoalesce(_optionalChain([o, 'access', _75 => _75.historyMg, 'optionalAccess', _76 => _76.historyIndex]), () => (-1))}}),A=null;function Tt(o){A&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),A());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 l=Object.entries(m.stores);if(l.length>0){let a=l.reduce((c,[d,f])=>(c[d]=St(f),c),{});_optionalChain([t, 'optionalAccess', _77 => _77.send, 'call', _78 => _78(JSON.stringify({type:"STATE_UPDATE",payload:a}))])}e=m.subscribe((a,c)=>{if(_optionalChain([t, 'optionalAccess', _79 => _79.readyState])===WebSocket.OPEN){let d=m.stores[a];d&&t.send(JSON.stringify({type:"STATE_UPDATE",payload:{[a]:St(d)}}))}}),s=setInterval(()=>{_optionalChain([t, 'optionalAccess', _80 => _80.readyState])===WebSocket.OPEN&&t.send(JSON.stringify({type:"PING"}))},3e4)},t.onmessage=l=>{try{let{type:a,payload:c}=JSON.parse(l.data);if(a==="ACTION"){let{storeId:d,action:f}=c,h=m.stores[d];h&&typeof h[f]=="function"&&h[f]()}}catch(a){console.warn("[bit-form] Erro ao processar comando do CLI:",a)}},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(),A=null};return A=n,n}exports.a = m; exports.b = g; exports.c = S; exports.d = x; exports.e = p; exports.f = y; exports.g = kt; exports.h = gt; exports.i = Bt; exports.j = B; exports.k = mt; exports.l = u; exports.m = b; exports.n = N; exports.o = P; exports.p = _; exports.q = j; exports.r = X; exports.s = q; exports.t = W; exports.u = z; exports.v = Y; exports.w = J; exports.x = K; exports.y = G; exports.z = Z; exports.A = Q; exports.B = tt; exports.C = et; exports.D = st; exports.E = rt; exports.F = it; exports.G = Mt; exports.H = Et; exports.I = Pt; exports.J = Ct; exports.K = ot; exports.L = nt; exports.M = Dt; exports.N = at; exports.O = lt; exports.P = ct; exports.Q = dt; exports.R = wt; exports.S = ut; exports.T = Tt; exports.U = ft; exports.V = pt;
133
- //# sourceMappingURL=chunk-6VDQSKUN.cjs.map
132
+ `;this.rootElement.innerHTML=e+s}}, _class4);function vt(n){let t=new M(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 l=o,a=l.getState(),c=_optionalChain([l, 'optionalAccess', _60 => _60.historyMg]),d=_optionalChain([c, 'optionalAccess', _61 => _61.history])||[],f=_nullishCoalesce(_optionalChain([c, 'optionalAccess', _62 => _62.historyIndex]), () => (-1));r[i]={...a,_meta:{canUndo:_optionalChain([l, 'optionalAccess', _63 => _63.canUndo]),canRedo:_optionalChain([l, 'optionalAccess', _64 => _64.canRedo]),totalSteps:d.length,currentIndex:f}}}return r};t.updateState(e());let s=m.subscribe(()=>{t.updateState(e())});return{ui:t,destroy:()=>{s(),n.innerHTML=""}}}function xt(n,t="ws://localhost:3000"){let e=new WebSocket(t),s=new M(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 ft(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=vt(s);else if(t==="remote")console.log("[bit-form] DevTools iniciado em modo Remote."),i=xt(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=Tt(s)}else{let s=ft();s&&typeof s.destroy=="function"&&(this.cleanupFn=s.destroy)}}destroy(){this.cleanupFn&&this.cleanupFn()}}, _class5);var pt= (_class6 =class{__init13() {this.listeners=new Set}__init14() {this.dirtyPaths=new Set}__init15() {this.configFields=new Set}constructor(t={}){;_class6.prototype.__init13.call(this);_class6.prototype.__init14.call(this);_class6.prototype.__init15.call(this);this.config=yt(t),this.depsMg=new C,this.historyMg=new D(!!this.config.enableHistory,_nullishCoalesce(this.config.historyLimit, () => (15))),this.computedMg=new I(this.config),this.validatorMg=new V(this),this.arraysMg=new w(this),this.lifecycleMg=new R(this),this.devtoolsMg=new H(this);let e=g(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.configFields.add(r),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}unregisterField(t){if(this.configFields.has(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)}registerField(t,e){this.depsMg.register(t,e,this.state.values),this.depsMg.isHidden(t)&&this.notify()}isHidden(t){return this.depsMg.isHidden(t)}isRequired(t){return this.depsMg.isRequired(t,this.state.values)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}watch(t,e){let s=g(p(this.state.values,t));return this.subscribe(()=>{let r=p(this.state.values,t);x(r,s)||(s=g(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){let s={...this.state.errors,[t]:e};e||delete s[t],this.internalUpdateState({errors:s})}setErrors(t){this.internalUpdateState({errors:{...this.state.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)}reset(){this.lifecycleMg.reset()}registerMask(t,e){this.config.masks[t]=e}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.rebuildDirtyPaths(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}redo(){let t=this.historyMg.redo();if(t){let e=this.rebuildDirtyPaths(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}validate(t){return this.validatorMg.validate(t)}getStepStatus(t){let e=_optionalChain([this, 'access', _65 => _65.config, 'access', _66 => _66.scopes, 'optionalAccess', _67 => _67[t]])||[],s=e.some(o=>!!this.state.errors[o]),r=e.some(o=>{let l=p(this.state.values,o),a=p(this.config.initialValues,o);return!S(l,a)}),i=this.getStepErrors(t);return{hasErrors:s,isDirty:r,errors:i}}getStepErrors(t){let e=_optionalChain([this, 'access', _68 => _68.config, 'access', _69 => _69.scopes, 'optionalAccess', _70 => _70[t]])||[],s={};for(let r of e){let i=this.state.errors[r];i&&(s[r]=i)}return s}isFieldDirty(t){let e=p(this.state.values,t),s=p(this.config.initialValues,t);return!S(e,s)}isFieldValidating(t){return!!this.getState().isValidating[t]}async submit(t){return this.lifecycleMg.submit(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)}updateDirtyForPath(t,e,s){for(let o of this.dirtyPaths)o.startsWith(t+".")&&this.dirtyPaths.delete(o);let r=p(e,t),i=p(s,t);return S(r,i)?this.dirtyPaths.delete(t):this.dirtyPaths.add(t),this.dirtyPaths.size>0}clearDirtyPaths(){this.dirtyPaths.clear()}rebuildDirtyPaths(t,e){return this.dirtyPaths=O(t,e),this.dirtyPaths.size>0}cleanup(){this.listeners.clear(),this.validatorMg.cancelAll(),delete m.stores[this.storeId]}notify(){this.listeners.forEach(t=>t())}}, _class6);var St=n=>({...typeof n.getState=="function"?n.getState():n,_meta:{canUndo:n.canUndo,canRedo:n.canRedo,totalSteps:_optionalChain([n, 'access', _71 => _71.historyMg, 'optionalAccess', _72 => _72.history, 'optionalAccess', _73 => _73.length])||0,currentIndex:_nullishCoalesce(_optionalChain([n, 'access', _74 => _74.historyMg, 'optionalAccess', _75 => _75.historyIndex]), () => (-1))}}),A=null;function Tt(n){A&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),A());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 l=Object.entries(m.stores);if(l.length>0){let a=l.reduce((c,[d,f])=>(c[d]=St(f),c),{});_optionalChain([t, 'optionalAccess', _76 => _76.send, 'call', _77 => _77(JSON.stringify({type:"STATE_UPDATE",payload:a}))])}e=m.subscribe((a,c)=>{if(_optionalChain([t, 'optionalAccess', _78 => _78.readyState])===WebSocket.OPEN){let d=m.stores[a];d&&t.send(JSON.stringify({type:"STATE_UPDATE",payload:{[a]:St(d)}}))}}),s=setInterval(()=>{_optionalChain([t, 'optionalAccess', _79 => _79.readyState])===WebSocket.OPEN&&t.send(JSON.stringify({type:"PING"}))},3e4)},t.onmessage=l=>{try{let{type:a,payload:c}=JSON.parse(l.data);if(a==="ACTION"){let{storeId:d,action:f}=c,h=m.stores[d];h&&typeof h[f]=="function"&&h[f]()}}catch(a){console.warn("[bit-form] Erro ao processar comando do CLI:",a)}},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(),A=null};return A=o,o}exports.a = m; exports.b = g; exports.c = S; exports.d = x; exports.e = p; exports.f = y; exports.g = kt; exports.h = gt; exports.i = Bt; exports.j = B; exports.k = mt; exports.l = u; exports.m = b; exports.n = N; exports.o = P; exports.p = _; exports.q = j; exports.r = X; exports.s = q; exports.t = W; exports.u = z; exports.v = Y; exports.w = J; exports.x = K; exports.y = G; exports.z = Z; exports.A = Q; exports.B = tt; exports.C = et; exports.D = st; exports.E = rt; exports.F = it; exports.G = Mt; exports.H = Et; exports.I = Pt; exports.J = Ct; exports.K = nt; exports.L = ot; exports.M = Dt; exports.N = at; exports.O = lt; exports.P = ct; exports.Q = dt; exports.R = wt; exports.S = ut; exports.T = Tt; exports.U = ft; exports.V = pt;
133
+ //# sourceMappingURL=chunk-J3EGU5ZH.cjs.map