@lehnihon/bit-form 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/angular/index.cjs +1 -1
  2. package/dist/angular/index.cjs.map +1 -1
  3. package/dist/angular/index.d.cts +19 -19
  4. package/dist/angular/index.d.ts +19 -19
  5. package/dist/angular/index.js +1 -1
  6. package/dist/angular/index.js.map +1 -1
  7. package/dist/{bus-70e4jnBj.d.cts → bus-B3pGaiFZ.d.cts} +14 -5
  8. package/dist/{bus-70e4jnBj.d.ts → bus-B3pGaiFZ.d.ts} +14 -5
  9. package/dist/chunk-442A4FTZ.cjs +2 -0
  10. package/dist/chunk-442A4FTZ.cjs.map +1 -0
  11. package/dist/chunk-6FJEE6O3.js +133 -0
  12. package/dist/chunk-6FJEE6O3.js.map +1 -0
  13. package/dist/chunk-FOV24ACZ.js +2 -0
  14. package/dist/chunk-FOV24ACZ.js.map +1 -0
  15. package/dist/chunk-YWXX6XRV.cjs +133 -0
  16. package/dist/chunk-YWXX6XRV.cjs.map +1 -0
  17. package/dist/devtools/bridge.cjs +1 -1
  18. package/dist/devtools/bridge.js +1 -1
  19. package/dist/devtools/index.cjs +1 -1
  20. package/dist/devtools/index.js +1 -1
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +7 -6
  24. package/dist/index.d.ts +7 -6
  25. package/dist/index.js +1 -1
  26. package/dist/public-types-CtYuIAMP.d.cts +99 -0
  27. package/dist/public-types-Lq3eLstW.d.ts +99 -0
  28. package/dist/react/index.cjs +1 -1
  29. package/dist/react/index.d.cts +5 -5
  30. package/dist/react/index.d.ts +5 -5
  31. package/dist/react/index.js +1 -1
  32. package/dist/react-native/index.cjs +1 -1
  33. package/dist/react-native/index.d.cts +4 -4
  34. package/dist/react-native/index.d.ts +4 -4
  35. package/dist/react-native/index.js +1 -1
  36. package/dist/resolvers/joi.d.cts +1 -1
  37. package/dist/resolvers/joi.d.ts +1 -1
  38. package/dist/resolvers/yup.d.cts +1 -1
  39. package/dist/resolvers/yup.d.ts +1 -1
  40. package/dist/resolvers/zod.d.cts +1 -1
  41. package/dist/resolvers/zod.d.ts +1 -1
  42. package/dist/{use-bit-persist-JshPvwwy.d.cts → use-bit-persist-CWzGfovL.d.cts} +19 -23
  43. package/dist/{use-bit-persist-COdNw_fv.d.ts → use-bit-persist-hxJaKG2S.d.ts} +19 -23
  44. package/dist/vue/index.cjs +1 -1
  45. package/dist/vue/index.cjs.map +1 -1
  46. package/dist/vue/index.d.cts +36 -36
  47. package/dist/vue/index.d.ts +36 -36
  48. package/dist/vue/index.js +1 -1
  49. package/dist/vue/index.js.map +1 -1
  50. package/package.json +1 -1
  51. package/dist/chunk-25Q2XJBV.cjs +0 -133
  52. package/dist/chunk-25Q2XJBV.cjs.map +0 -1
  53. package/dist/chunk-2HAQ3QEQ.js +0 -133
  54. package/dist/chunk-2HAQ3QEQ.js.map +0 -1
  55. package/dist/chunk-HTB6QIUQ.js +0 -2
  56. package/dist/chunk-HTB6QIUQ.js.map +0 -1
  57. package/dist/chunk-W22D7QVJ.cjs +0 -2
  58. package/dist/chunk-W22D7QVJ.cjs.map +0 -1
  59. package/dist/public-types-BVZ16kgZ.d.ts +0 -74
  60. package/dist/public-types-r2aP68Gg.d.cts +0 -74
@@ -42,6 +42,15 @@ interface BitState<T> {
42
42
  isSubmitting: boolean;
43
43
  isDirty: boolean;
44
44
  }
45
+ interface BitFieldState<T extends object = any, TValue = unknown> {
46
+ value: TValue;
47
+ error: string | undefined;
48
+ touched: boolean;
49
+ isHidden: boolean;
50
+ isRequired: boolean;
51
+ isDirty: boolean;
52
+ isValidating: boolean;
53
+ }
45
54
  type ValidatorFn<T> = (values: T, options?: {
46
55
  scopeFields?: string[];
47
56
  }) => Promise<BitErrors<T>> | BitErrors<T>;
@@ -75,7 +84,7 @@ interface DevToolsOptions {
75
84
  url?: string;
76
85
  }
77
86
  type BitPluginHookSource = "beforeValidate" | "afterValidate" | "beforeSubmit" | "afterSubmit" | "onFieldChange" | "setup" | "teardown" | "submit";
78
- type BitFieldChangeOrigin = "setField" | "setValues" | "array";
87
+ type BitFieldChangeOrigin = "setField" | "rebase" | "replaceValues" | "hydrate" | "array";
79
88
  type BitArrayOperation = "push" | "prepend" | "insert" | "remove" | "move" | "swap";
80
89
  interface BitFieldChangeMeta {
81
90
  origin: BitFieldChangeOrigin;
@@ -230,11 +239,11 @@ type BitPathValue<T, P extends string> = P extends `${infer K}.${infer Rest}` ?
230
239
  type BitArrayPath<T> = BitPath<T> extends infer P ? P extends string ? BitPathValue<T, P> extends readonly any[] ? P : never : never : never;
231
240
  type BitArrayItem<A> = A extends readonly (infer U)[] ? U : A extends (infer U)[] ? U : never;
232
241
 
233
- type BitBusListener = (storeId: string, newState: any) => void;
242
+ type BitBusListener<T extends object = any> = (storeId: string, newState: BitState<T>) => void;
234
243
  interface BitFormGlobal {
235
- stores: Record<string, any>;
244
+ stores: Record<string, unknown>;
236
245
  listeners: Set<BitBusListener>;
237
- dispatch: (storeId: string, state: any) => void;
246
+ dispatch: (storeId: string, state: BitState<any>) => void;
238
247
  subscribe: (fn: BitBusListener) => () => void;
239
248
  }
240
249
 
@@ -243,4 +252,4 @@ declare global {
243
252
  }
244
253
  declare const bitBus: BitFormGlobal;
245
254
 
246
- export { type BitTransformFn as A, type BitConfig as B, type CurrencyMaskConfig as C, type DateMaskConfig as D, type BitValidationConfig as E, type DeepPartial as F, type ValidatorFn as G, bitBus as H, type DevToolsOptions as I, type BitPersistResolvedConfig as J, type PatternMaskOptions as P, type ScopeStatus as S, type ValidateScopeResult as V, type BitMask as a, type BitAfterSubmitEvent as b, type BitAfterValidateEvent as c, type BitArrayItem as d, type BitArrayPath as e, type BitBeforeSubmitEvent as f, type BitBeforeValidateEvent as g, type BitComputedFn as h, type BitErrors as i, type BitFieldChangeEvent as j, type BitFieldChangeMeta as k, type BitFieldConditional as l, type BitFieldDefinition as m, type BitFieldValidation as n, type BitHistoryConfig as o, type BitPath as p, type BitPathValue as q, type BitPersistConfig as r, type BitPersistMode as s, type BitPersistStorageAdapter as t, type BitPlugin as u, type BitPluginContext as v, type BitPluginErrorEvent as w, type BitPluginHooks as x, type BitState as y, type BitTouched as z };
255
+ export { type BitTouched as A, type BitConfig as B, type CurrencyMaskConfig as C, type DateMaskConfig as D, type BitTransformFn as E, type BitValidationConfig as F, type DeepPartial as G, type ValidatorFn as H, bitBus as I, type DevToolsOptions as J, type BitPersistResolvedConfig as K, type PatternMaskOptions as P, type ScopeStatus as S, type ValidateScopeResult as V, type BitMask as a, type BitAfterSubmitEvent as b, type BitAfterValidateEvent as c, type BitArrayItem as d, type BitArrayPath as e, type BitBeforeSubmitEvent as f, type BitBeforeValidateEvent as g, type BitComputedFn as h, type BitErrors as i, type BitFieldChangeEvent as j, type BitFieldChangeMeta as k, type BitFieldConditional as l, type BitFieldDefinition as m, type BitFieldState as n, type BitFieldValidation as o, type BitHistoryConfig as p, type BitPath as q, type BitPathValue as r, type BitPersistConfig as s, type BitPersistMode as t, type BitPersistStorageAdapter as u, type BitPlugin as v, type BitPluginContext as w, type BitPluginErrorEvent as x, type BitPluginHooks as y, type BitState as z };
@@ -0,0 +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 _chunkYWXX6XRVcjs = require('./chunk-YWXX6XRV.cjs');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var k=_react.createContext.call(void 0, null),at= exports.a =({store:t,children:e})=>_jsxruntime.jsx.call(void 0, k.Provider,{value:t,children:e}),g= exports.b =()=>{let t=_react.useContext.call(void 0, k);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};function St(){let t=g(),[e,s]=_react.useState.call(void 0, null),[m,n]=_react.useState.call(void 0, null),o=_react.useRef.call(void 0, null),u=_react.useCallback.call(void 0, ()=>{let p=t.getState(),b={isValid:p.isValid,isDirty:p.isDirty,isSubmitting:p.isSubmitting};return o.current&&o.current.isValid===b.isValid&&o.current.isDirty===b.isDirty&&o.current.isSubmitting===b.isSubmitting?o.current:(o.current=b,b)},[t]),c=_react.useCallback.call(void 0, p=>t.subscribeSelector(b=>({isValid:b.isValid,isDirty:b.isDirty,isSubmitting:b.isSubmitting}),()=>p()),[t]),i=_react.useSyncExternalStore.call(void 0, c,u,u),r=_react.useCallback.call(void 0, p=>b=>(_optionalChain([b, 'optionalAccess', _2 => _2.preventDefault, 'optionalCall', _3 => _3()]),t.submit(p)),[t]),a=_react.useCallback.call(void 0, p=>b=>(_optionalChain([b, 'optionalAccess', _4 => _4.preventDefault, 'optionalCall', _5 => _5()]),s(null),t.submit(async(O,q)=>{try{let h=await p(O,q);n(h),s(null)}catch(h){_chunkYWXX6XRVcjs.i.call(void 0, h)?t.setServerErrors(_chunkYWXX6XRVcjs.j.call(void 0, h)):s(h instanceof Error?h:new Error(String(h)))}})),[t]),l=_react.useCallback.call(void 0, ()=>{t.reset(),s(null),n(null)},[t]),d=_react.useCallback.call(void 0, ()=>t.getState().values,[t]),B=_react.useCallback.call(void 0, ()=>t.getState().errors,[t]),F=_react.useCallback.call(void 0, ()=>t.getState().touched,[t]),S=_react.useCallback.call(void 0, ()=>t.getDirtyValues(),[t]);return{meta:_react.useMemo.call(void 0, ()=>({...i,submitError:e,lastResponse:m}),[i,e,m]),getValues:d,getErrors:B,getTouched:F,getDirtyValues:S,submit:r,onSubmit:a,reset:l,setField:t.setField.bind(t),blurField:t.blurField.bind(t),replaceValues:t.replaceValues.bind(t),hydrate:t.hydrate.bind(t),rebase:t.rebase.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),mutations:{pushItem:t.pushItem.bind(t),removeItem:t.removeItem.bind(t),prependItem:t.prependItem.bind(t),insertItem:t.insertItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t)}}}var P=()=>Math.random().toString(36).substring(2,9);function Bt(t){let e=g(),s=_react.useCallback.call(void 0, ()=>{let r=e.getState(),a=_chunkYWXX6XRVcjs.f.call(void 0, r.values,t);return Array.isArray(a)?a:[]},[e,t]),m=_react.useCallback.call(void 0, r=>e.subscribePath(t,()=>r()),[e,t]),n=_react.useSyncExternalStore.call(void 0, m,s,s),[o,u]=_react.useState.call(void 0, ()=>n.map(P));_react.useEffect.call(void 0, ()=>{n.length!==o.length&&u(r=>{if(n.length>r.length){let a=n.length-r.length;return[...r,...Array(a).fill(null).map(P)]}return r.slice(0,n.length)})},[n.length]);let c=_react.useMemo.call(void 0, ()=>({append:r=>{u(a=>[...a,P()]),e.pushItem(t,r)},prepend:r=>{u(a=>[P(),...a]),e.prependItem(t,r)},insert:(r,a)=>{u(l=>{let d=[...l];return d.splice(r,0,P()),d}),e.insertItem(t,r,a)},remove:r=>{u(a=>a.filter((l,d)=>d!==r)),e.removeItem(t,r)},move:(r,a)=>{u(l=>{let d=[...l],[B]=d.splice(r,1);return d.splice(a,0,B),d}),e.moveItem(t,r,a)},swap:(r,a)=>{u(l=>{let d=[...l];return[d[r],d[a]]=[d[a],d[r]],d}),e.swapItems(t,r,a)},replace:r=>{u(r.map(P)),e.setField(t,r)},clear:()=>{u([]),e.setField(t,[])}}),[e,t]);return{fields:_react.useMemo.call(void 0, ()=>n.map((r,a)=>({key:o[a]||`temp-${a}`,value:r,index:a})),[n,o]),length:n.length,...c}}function Tt(t){let e=g(),s=_react.useRef.call(void 0, null),m=_react.useCallback.call(void 0, ()=>{let c=e.getStepStatus(t);return s.current&&s.current.hasErrors===c.hasErrors&&s.current.isDirty===c.isDirty&&Object.keys(s.current.errors).length===Object.keys(c.errors).length&&Object.entries(c.errors).every(([i,r])=>s.current.errors[i]===r)?s.current:(s.current=c,c)},[e,t]),n=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),m,m),o=_react.useCallback.call(void 0, async()=>{let c=await e.validate({scope:t}),i=e.getStepErrors(t);return{valid:c,errors:i}},[e,t]),u=_react.useCallback.call(void 0, ()=>e.getStepErrors(t),[e,t]);return{scopeName:t,status:n,errors:n.errors,validate:o,getErrors:u,isValid:!n.hasErrors,isDirty:n.isDirty}}function wt(t){let e=g(),[s,m]=_react.useState.call(void 0, 0),n=_nullishCoalesce(t[s], () => ("")),o=_react.useRef.call(void 0, null),u=_react.useCallback.call(void 0, ()=>{let S=e.getStepStatus(n);return o.current&&o.current.hasErrors===S.hasErrors&&o.current.isDirty===S.isDirty&&Object.keys(o.current.errors).length===Object.keys(S.errors).length&&Object.entries(S.errors).every(([f,p])=>o.current.errors[f]===p)?o.current:(o.current=S,S)},[e,n]),c=_react.useSyncExternalStore.call(void 0, e.subscribe.bind(e),u,u),i=_react.useCallback.call(void 0, async()=>{let S=await e.validate({scope:n}),f=e.getStepErrors(n);return{valid:S,errors:f}},[e,n]),r=_react.useCallback.call(void 0, ()=>e.getStepErrors(n),[e,n]),a=_react.useCallback.call(void 0, async()=>{let S=e.getScopeFields(n);if(e.hasValidationsInProgress(S))return!1;let f=await e.validate({scope:n});if(f)m(p=>Math.min(p+1,t.length-1));else{let p=e.getStepErrors(n),b=Object.keys(p);b.length>0&&e.markFieldsTouched(b)}return f},[e,n,t.length]),l=_react.useCallback.call(void 0, ()=>{m(S=>Math.max(S-1,0))},[]),d=_react.useCallback.call(void 0, S=>{m(Math.max(0,Math.min(S-1,t.length-1)))},[t.length]),B=s===0,F=s>=t.length-1;return{step:s+1,stepIndex:s,scope:n,next:a,prev:l,goTo:d,isFirst:B,isLast:F,status:c,errors:c.errors,isValid:!c.hasErrors,isDirty:c.isDirty,validate:i,getErrors:r}}function Ot(t){let e=g(),s=_react.useRef.call(void 0, null),m=_react.useCallback.call(void 0, ()=>{let o=_chunkYWXX6XRVcjs.f.call(void 0, e.getState().values,t);return s.current!==null&&_chunkYWXX6XRVcjs.e.call(void 0, s.current,o)?s.current:(s.current=o,o)},[e,t]),n=_react.useCallback.call(void 0, o=>e.subscribe(o),[e]);return _react.useSyncExternalStore.call(void 0, n,m,m)}function Lt(){let t=g(),[e,s]=_react.useState.call(void 0, !1),[m,n]=_react.useState.call(void 0, !1),[o,u]=_react.useState.call(void 0, null),c=_react.useCallback.call(void 0, async()=>{n(!0),u(null);try{return await t.restorePersisted()}catch(l){return u(l instanceof Error?l:new Error(String(l))),!1}finally{n(!1)}},[t]),i=_react.useCallback.call(void 0, async()=>{s(!0),u(null);try{await t.forceSave()}catch(l){u(l instanceof Error?l:new Error(String(l)))}finally{s(!1)}},[t]),r=_react.useCallback.call(void 0, async()=>{u(null);try{await t.clearPersisted()}catch(l){u(l instanceof Error?l:new Error(String(l)))}},[t]),a=_react.useMemo.call(void 0, ()=>({isSaving:e,isRestoring:m,error:o}),[e,m,o]);return{restore:c,save:i,clear:r,meta:a}}function zt(t){let e=g(),s=_react.useRef.call(void 0, null);_react.useEffect.call(void 0, ()=>()=>{e.unregisterField&&e.unregisterField(t)},[e,t]);let m=_react.useCallback.call(void 0, ()=>{let i=e.getFieldState(t);if(s.current&&s.current.value===i.value&&s.current.error===i.error&&s.current.touched===i.touched&&s.current.isHidden===i.isHidden&&s.current.isRequired===i.isRequired&&s.current.isDirty===i.isDirty&&s.current.isValidating===i.isValidating)return s.current;let r={value:i.value,error:i.error,touched:i.touched,isHidden:i.isHidden,isRequired:i.isRequired,isDirty:i.isDirty,isValidating:i.isValidating};return s.current=r,r},[e,t]),n=_react.useCallback.call(void 0, i=>e.subscribeSelector(()=>e.getFieldState(t),()=>i()),[e,t]),o=_react.useSyncExternalStore.call(void 0, n,m,m),u=_react.useCallback.call(void 0, i=>e.setField(t,i),[e,t]),c=_react.useCallback.call(void 0, ()=>e.blurField(t),[e,t]);return{fieldState:o,setValue:u,setBlur:c,store:e}}exports.a = at; exports.b = g; exports.c = St; exports.d = zt; exports.e = Bt; exports.f = Tt; exports.g = wt; exports.h = Ot; exports.i = Lt;
2
+ //# sourceMappingURL=chunk-442A4FTZ.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-442A4FTZ.cjs","../src/react/context.tsx","../src/react/use-bit-form.ts","../src/react/use-bit-array.ts"],"names":["BitContext","createContext","BitFormProvider","store","children","jsx","useBitStore","useContext","useBitForm","submitError","setSubmitError","useState","lastResponse","setLastResponse","lastMeta","useRef","getMetaSnapshot","useCallback","state","nextMeta","subscribeMeta","cb","metaState","useSyncExternalStore","submit","onSuccess","e","onSubmit","handler","values","dirtyValues","result","err","isValidationErrorShape","extractServerErrors","reset","getValues","getErrors","getTouched","getDirtyValues","useMemo","generateId","useBitArray","path","getSnapshot","value","getDeepValue","subscribeArray","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,IAA2C,CAAA,CAEjDC,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,6D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AAS,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,CACDtD,CAAAA,CAAM,SAAA,CAAUwC,CAAAA,CAAMoB,CAAAA,CAAQC,CAAM,CACtC,CAAA,CACA,OAAA,CAAUC,CAAAA,EAAkB,CAC1Bf,CAAAA,CAAOe,CAAAA,CAAM,GAAA,CAAIxB,CAAU,CAAC,CAAA,CAC5BtC,CAAAA,CAAM,QAAA,CACJwC,CAAAA,CACAsB,CACF,CACF,CAAA,CACA,KAAA,CAAO,CAAA,CAAA,EAAM,CACXf,CAAAA,CAAO,CAAC,CAAC,CAAA,CACT/C,CAAAA,CAAM,QAAA,CACJwC,CAAAA,CACA,CAAC,CACH,CACF,CACF,CAAA,CAAA,CACA,CAACxC,CAAAA,CAAOwC,CAAI,CACd,CAAA,CAYA,MAAO,CACL,MAAA,CAXaH,4BAAAA,CACb,CAAA,EACGQ,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-442A4FTZ.cjs","sourcesContent":[null,"import React, { createContext, useContext } from \"react\";\nimport type { BitStoreApi } from \"../core\";\n\nconst BitContext = createContext<BitStoreApi<any> | null>(null);\n\nexport const BitFormProvider = ({\n store,\n children,\n}: {\n store: BitStoreApi<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 BitStoreApi<T>;\n};\n","import {\n useCallback,\n useSyncExternalStore,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport { isValidationErrorShape, extractServerErrors } from \"../core/utils\";\n\nexport function useBitForm<T extends object>() {\n const store = useBitStore<T>();\n\n const [submitError, setSubmitError] = useState<Error | null>(null);\n const [lastResponse, setLastResponse] = useState<unknown>(null);\n const lastMeta = useRef<{\n isValid: boolean;\n isDirty: boolean;\n isSubmitting: boolean;\n } | null>(null);\n\n const getMetaSnapshot = useCallback(() => {\n const state = store.getState();\n const nextMeta = {\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n };\n\n if (\n lastMeta.current &&\n lastMeta.current.isValid === nextMeta.isValid &&\n lastMeta.current.isDirty === nextMeta.isDirty &&\n lastMeta.current.isSubmitting === nextMeta.isSubmitting\n ) {\n return lastMeta.current;\n }\n\n lastMeta.current = nextMeta;\n return nextMeta;\n }, [store]);\n\n const subscribeMeta = useCallback(\n (cb: () => void) =>\n store.subscribeSelector(\n (state) => ({\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n }),\n () => cb(),\n ),\n [store],\n );\n\n const metaState = useSyncExternalStore(\n subscribeMeta,\n getMetaSnapshot,\n getMetaSnapshot,\n );\n\n const submit = useCallback(\n (\n onSuccess: (values: T, dirtyValues?: Partial<T>) => void | Promise<void>,\n ) => {\n return (e?: { preventDefault: () => void }) => {\n e?.preventDefault?.();\n return store.submit(onSuccess);\n };\n },\n [store],\n );\n\n const onSubmit = useCallback(\n (handler: (values: T, dirtyValues?: Partial<T>) => Promise<unknown>) => {\n return (e?: { preventDefault: () => void }) => {\n e?.preventDefault?.();\n setSubmitError(null);\n\n return store.submit(async (values, dirtyValues) => {\n try {\n const result = await handler(values, dirtyValues);\n setLastResponse(result);\n setSubmitError(null);\n } catch (err) {\n if (isValidationErrorShape(err)) {\n store.setServerErrors(extractServerErrors(err));\n } else {\n setSubmitError(\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n }\n });\n };\n },\n [store],\n );\n\n const reset = useCallback(() => {\n store.reset();\n setSubmitError(null);\n setLastResponse(null);\n }, [store]);\n\n const getValues = useCallback(() => store.getState().values, [store]);\n const getErrors = useCallback(() => store.getState().errors, [store]);\n const getTouched = useCallback(() => store.getState().touched, [store]);\n const getDirtyValues = useCallback(() => store.getDirtyValues(), [store]);\n\n const meta = useMemo(\n () => ({\n ...metaState,\n submitError,\n lastResponse,\n }),\n [metaState, submitError, lastResponse],\n );\n\n return {\n // Metadata (grouped)\n meta,\n // Getters\n getValues,\n getErrors,\n getTouched,\n getDirtyValues,\n // Main actions (frequent use - flat)\n submit,\n onSubmit,\n reset,\n setField: store.setField.bind(store),\n blurField: store.blurField.bind(store),\n replaceValues: store.replaceValues.bind(store),\n hydrate: store.hydrate.bind(store),\n rebase: store.rebase.bind(store),\n setValues: store.setValues.bind(store),\n setError: store.setError.bind(store),\n setErrors: store.setErrors.bind(store),\n setServerErrors: store.setServerErrors.bind(store),\n validate: store.validate.bind(store),\n // Array mutations (grouped)\n mutations: {\n pushItem: store.pushItem.bind(store),\n removeItem: store.removeItem.bind(store),\n prependItem: store.prependItem.bind(store),\n insertItem: store.insertItem.bind(store),\n moveItem: store.moveItem.bind(store),\n swapItems: store.swapItems.bind(store),\n },\n };\n}\n","import {\n useCallback,\n useSyncExternalStore,\n useState,\n useMemo,\n useEffect,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n getDeepValue,\n BitArrayPath,\n BitPathValue,\n BitArrayItem,\n BitPath,\n} from \"../core\";\n\nconst generateId = () => Math.random().toString(36).substring(2, 9);\n\nexport function useBitArray<\n TForm extends object = any,\n P extends BitArrayPath<TForm> = BitArrayPath<TForm>,\n>(path: P) {\n const store = useBitStore<TForm>();\n\n type Item = BitArrayItem<BitPathValue<TForm, P>>;\n\n const getSnapshot = useCallback(() => {\n const state = store.getState();\n const value = getDeepValue(state.values, path as string) as\n | BitPathValue<TForm, P>\n | undefined;\n return Array.isArray(value) ? (value as Item[]) : [];\n }, [store, path]);\n\n const subscribeArray = useCallback(\n (cb: () => void) => store.subscribePath(path, () => cb()),\n [store, path],\n );\n\n const data = useSyncExternalStore(subscribeArray, getSnapshot, getSnapshot);\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(\n path as unknown as BitPath<TForm>,\n items as unknown as BitPathValue<TForm, BitPath<TForm>>,\n );\n },\n clear: () => {\n setIds([]);\n store.setField(\n path as unknown as BitPath<TForm>,\n [] as unknown as BitPathValue<TForm, BitPath<TForm>>,\n );\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"]}
@@ -0,0 +1,133 @@
1
+ var z=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;z.__BIT_FORM__||(z.__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=z.__BIT_FORM__;function p(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=>p(e));let t={};for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&(t[e]=p(o[e]));return t}function M(o,t){if(t===void 0)return p(o);if(t===null||typeof t!="object"||t instanceof Date||t instanceof RegExp||Array.isArray(t))return p(t);let e=o&&typeof o=="object"&&!Array.isArray(o)?p(o):{};for(let s of Object.keys(t)){let r=t[s],i=e[s];if(r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp)){e[s]=M(i,r);continue}e[s]=p(r)}return e}function b(o,t){return o===t?!0:o===null||typeof o!="object"||t===null||typeof t!="object"?!1:T(o,t)}function T(o,t){if(o===t)return!0;if(o===null||typeof o!="object"||t===null||typeof t!="object")return!1;if(o instanceof Date&&t instanceof Date)return o.getTime()===t.getTime();if(o instanceof RegExp&&t instanceof RegExp)return o.toString()===t.toString();let e=Object.keys(o),s=Object.keys(t);if(e.length!==s.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r)||!T(o[r],t[r]))return!1;return!0}function _(o,t,e="",s=new Set){if(b(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!b(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?.[i],t?.[i],n,s)}return s}var x=new Map;function g(o,t){if(!t)return o;let e=x.get(t)||t.split(".");x.has(t)||x.set(t,e);let s=o;for(let r of e){if(s==null)return;s=s[r]}return s}function v(o,t,e){if(!t)return e;let s=x.get(t)||t.split(".");x.has(t)||x.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],d=/^\d+$/.test(a),c=i[l];c==null?i[l]=d?[]:{}:i[l]=Array.isArray(c)?[...c]:{...c},i=i[l]}return i[s[s.length-1]]=e,r}function wt(o,t){let e={},s=`${t}.`;for(let r in o)r!==t&&!r.startsWith(s)&&(e[r]=o[r]);return e}var X=(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),d=l.slice(1).join(".");if(a!==e)if(a>e){let c=a-1,u=d?`${r}${c}.${d}`:`${r}${c}`;s[u]=o[i]}else s[i]=o[i]}),s},W=(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("."),d=parseInt(a[0],10),c=a.slice(1).join(".");if(d===e){let u=c?`${i}${s}.${c}`:`${i}${s}`;r[u]=o[n]}else if(d===s){let u=c?`${i}${e}.${c}`:`${i}${e}`;r[u]=o[n]}else r[n]=o[n]}),r},Y=(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("."),d=parseInt(a[0],10),c=a.slice(1).join("."),u=d;d===e?u=s:e<s&&d>e&&d<=s?u=d-1:e>s&&d>=s&&d<e&&(u=d+1);let f=c?`${i}${u}.${c}`:`${i}${u}`;r[f]=o[n]}),r};function Tt(o){if(typeof o!="object"||o===null||Array.isArray(o))return!1;let t=o.errors??o;return typeof t!="object"||t===null||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string"||Array.isArray(e)&&e.every(s=>typeof s=="string"))}function Ct(o){return Tt(o)?o.errors??o:{}}var Bt={"#":/\d/,A:/[a-zA-Z]/,X:/[a-zA-Z0-9]/,H:/[0-9a-fA-F]/,U:/[A-Z]/,L:/[a-z]/,"*":/./},E=(o,t)=>{if(o==null||o==="")return"";let e=String(o),s=e.startsWith("-"),r=t?t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"",i=new RegExp(`[^a-zA-Z0-9${r}]`,"g"),n=e.replace(i,"");return s&&n&&!n.startsWith("-")?`-${n}`:n},xt=(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},h=(o,t)=>{let e=s=>s.split("").filter(r=>Bt[r]).length;return{format:s=>{let r=E(s,t?.allowChars);if(!r&&!t?.guide)return"";let n=[...Array.isArray(o)?o:[o]].sort((f,y)=>e(f)-e(y)),l=n[n.length-1];for(let f of n)if(r.length<=e(f)){l=f;break}let a="",d=0,c=t?.guide||!1,u=t?.placeholderChar||"_";for(let f=0;f<l.length;f++){let y=l[f],k=Bt[y];if(d<r.length){let B=r[d];if(k)if(y==="U"&&(B=B.toUpperCase()),y==="L"&&(B=B.toLowerCase()),k.test(B))a+=B,d++;else if(c)a+=u;else break;else a+=y,B===y&&d++}else if(c)a+=k?u:y;else break}return a},parse:s=>{if(t?.customParse)return t.customParse(s);let i=h(o,t).format(s);if(t?.saveRaw){if(t?.guide){let l=(t.placeholderChar||"_").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(l,"g");return i.replace(a,"")}return i}return E(i,t?.allowChars)}}},S=({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 d="";if(typeof a=="number"?d=Math.abs(a).toFixed(r).replace(/\D/g,""):d=String(a).replace(/\D/g,""),!d&&String(a).includes("-")&&i)return"-";if(!d)return"";d=d.padStart(r+1,"0");let c=d.slice(0,-r).replace(/^0+(?=\d)/,"")||"0",u=d.slice(-r),f=c.replace(/\B(?=(\d{3})+(?!\d))/g,e);return`${(typeof a=="number"?a<0:String(a).includes("-"))&&i?"-":""}${o}${f}${s}${u}${t}`};return{format:l,parse:a=>{let d=xt(a,r),c=i?d:Math.abs(d);return n?l(c):c}}},J=o=>{let t=e=>/^3[47]/.test(e)?"#### ###### #####":/^3(?:0[0-5]|[68])/.test(e)?"#### ###### ####":"#### #### #### ####";return{format:e=>{let s=E(e,o?.allowChars),r=t(s);return h(r,o).format(e)},parse:e=>{let s=E(e,o?.allowChars),r=t(s);return h(r,o).parse(e)}}},P=o=>{let e=(o?.format||"DD/MM/YYYY")==="YYYY-MM-DD",s=h(e?"####-##-##":"##/##/####",o);return{format:r=>{let i=E(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 c=parseInt(n,10);c>31&&(n="31"),c===0&&(n="01")}if(l.length===2){let c=parseInt(l,10);c>12&&(l="12"),c===0&&(l="01")}let d=e?`${a}${l}${n}`:`${n}${l}${a}`;return s.format(d)},parse:r=>s.parse(r)}};var K=S({prefix:"R$ ",thousand:".",decimal:",",precision:2}),G=S({prefix:"$",thousand:",",decimal:".",precision:2}),Z=S({suffix:" \u20AC",thousand:".",decimal:",",precision:2}),Q=S({prefix:"\xA3",thousand:",",decimal:".",precision:2}),tt=S({prefix:"\xA5",thousand:",",decimal:".",precision:0}),et=S({suffix:"%",thousand:".",decimal:",",precision:1}),st=S({thousand:".",decimal:",",precision:2}),rt=S({thousand:".",decimal:",",precision:0}),it=h("###.###.###-##"),ot=h("##.###.###/####-##"),nt=h(["(##) ####-####","(##) #####-####"]),at=h("(##) ####-####"),lt=h("#####-###"),dt=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,"")}}),ct=h("##:##"),ut=h("###########"),gt=h("##.###.###-X"),Dt=h("(###) ###-####"),It=h("#####-####"),At=h("##/##/####"),Rt=h("###-##-####"),pt=J(),ht=h("####"),Ht=P({format:"YYYY-MM-DD",saveRaw:!0,guide:!0}),ft=h("HH:HH:HH:HH:HH:HH"),mt=h("#HHHHHH"),yt=h("###.###.###.###"),bt=h("HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH"),Ot=h("UU## XXXX XXXX XXXX XXXX XXXX XXXX XXXX XX",{allowChars:" "});var vt={brl:K,usd:G,eur:Z,gbp:Q,jpy:tt,cpf:it,cnpj:ot,rg:gt,cep:lt,cnh:ut,phone:nt,landline:at,date:dt,time:ct,ip:yt,ipv6:bt,mac:ft,color:mt,cc:pt,cvv:ht,percent:et,decimal:st,int:rt};function Et(o={}){let t=o.initialValues??{},e=o.validation,s=o.history,r=o.name?`bit-form:${o.name}:draft`:"bit-form:draft",i={enabled:o.persist?.enabled??!1,key:o.persist?.key??r,storage:o.persist?.storage,autoSave:o.persist?.autoSave??!0,debounceMs:o.persist?.debounceMs??300,mode:o.persist?.mode??"values",serialize:o.persist?.serialize??JSON.stringify,deserialize:o.persist?.deserialize??(n=>JSON.parse(n)),onError:o.persist?.onError};return{name:o.name,initialValues:p(t),resolver:e?.resolver,validationDelay:e?.delay??300,enableHistory:s?.enabled??!1,historyLimit:s?.limit??15,masks:{...vt},fields:o.fields,devTools:o.devTools,persist:i,plugins:o.plugins??[]}}var F=class{fieldConfigs=new Map;dependencies=new Map;hiddenFields=new Set;register(t,e,s){this.fieldConfigs.set(t,e);let r=e.conditional?.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:!!s.conditional?.requiredIf?.(e)}getRequiredErrors(t){let e={};return this.fieldConfigs.forEach((s,r)=>{if(this.isRequired(r,t)){let i=g(t,r);this.isEmpty(i)&&(e[r]=s.conditional?.requiredMessage??"required field")}}),e}evaluateAll(t){this.fieldConfigs.forEach((e,s)=>{this.evaluateFieldCondition(s,t)})}updateDependencies(t,e){let s=[],r=[t],i=new Set;for(;r.length>0;){let n=r.shift();if(i.has(n))continue;i.add(n);let l=this.dependencies.get(n);l&&l.forEach(a=>{let d=this.isHidden(a);this.evaluateFieldCondition(a,e);let c=this.isHidden(a);d!==c&&s.push(a),r.push(a)})}return 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=this.fieldConfigs.get(t)?.conditional?.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}};var w=class{constructor(t,e=15){this.enableHistory=t;this.maxHistory=e}history=[];historyIndex=-1;saveSnapshot(t){if(!this.enableHistory)return;let e=this.history[this.historyIndex];e&&T(e,t)||(this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push(p(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--,p(this.history[this.historyIndex])):null}redo(){return this.canRedo?(this.historyIndex++,p(this.history[this.historyIndex])):null}reset(t){this.history=[],this.historyIndex=-1,this.saveSnapshot(t)}getMetadata(){return{enabled:this.enableHistory,canUndo:this.canUndo,canRedo:this.canRedo,historyIndex:this.historyIndex,historySize:this.history.length}}};var C=class{constructor(t){this.store=t}pushItem(t,e){let s=g(this.store.getState().values,t)||[];this.store.setFieldWithMeta(t,[...s,e],{origin:"array",operation:"push"}),this.store.internalSaveSnapshot()}prependItem(t,e){let s=g(this.store.getState().values,t)||[];this.store.setFieldWithMeta(t,[e,...s],{origin:"array",operation:"prepend"}),this.store.internalSaveSnapshot()}insertItem(t,e,s){let r=[...g(this.store.getState().values,t)||[]];r.splice(e,0,s),this.store.setFieldWithMeta(t,r,{origin:"array",operation:"insert",index:e}),this.store.internalSaveSnapshot()}removeItem(t,e){let s=this.store.getState(),r=g(s.values,t);if(!Array.isArray(r))return;let i=[...r];this.store.unregisterPrefix&&this.store.unregisterPrefix(`${t}.${e}.`);let n=r.filter((d,c)=>c!==e),l=v(s.values,t,n),a=this.store.updateDirtyForPath(t,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:X(s.errors,t,e),touched:X(s.touched,t,e),isDirty:a}),this.store.emitFieldChange({path:t,previousValue:i,nextValue:n,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"remove",index:e}}),this.store.internalSaveSnapshot(),this.revalidate(t)}swapItems(t,e,s){let r=this.store.getState(),i=[...g(r.values,t)||[]],n=[...i];[i[e],i[s]]=[i[s],i[e]];let l=v(r.values,t,i),a=this.store.updateDirtyForPath(t,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:W(r.errors,t,e,s),touched:W(r.touched,t,e,s),isDirty:a}),this.store.emitFieldChange({path:t,previousValue:n,nextValue:i,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"swap",from:e,to:s}}),this.store.internalSaveSnapshot(),this.revalidate(t)}moveItem(t,e,s){let r=this.store.getState(),i=[...g(r.values,t)||[]],n=[...i],[l]=i.splice(e,1);i.splice(s,0,l);let a=v(r.values,t,i),d=this.store.updateDirtyForPath(t,a,this.store.getConfig().initialValues);this.store.internalUpdateState({values:a,errors:Y(r.errors,t,e,s),touched:Y(r.touched,t,e,s),isDirty:d}),this.store.emitFieldChange({path:t,previousValue:n,nextValue:i,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"move",from:e,to:s}}),this.store.internalSaveSnapshot(),this.revalidate(t)}revalidate(t){this.store.triggerValidation([t])}};var D=class o{constructor(t){this.getComputedEntries=t}static MIN_PASSES=4;apply(t){let e=this.getComputedEntries();if(e.length===0)return t;let s=t,r=Math.max(o.MIN_PASSES,e.length*2);for(let i=0;i<r;i++){let n=!1;for(let[l,a]of e){let d=a(s),c=g(s,l);T(c,d)||(s=v(s,l,d),n=!0)}if(!n)break;if(i===r-1)throw new Error("BitStore: computed fields did not stabilize. Check for cyclic computed definitions.")}return s}};var I=class{constructor(t){this.store=t}validationTimeout;currentValidationId=0;asyncTimers={};asyncRequests={};asyncErrors={};updateFieldValidating(t,e){this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[t]:e}})}cancelFieldAsync(t){this.asyncTimers[t]&&(clearTimeout(this.asyncTimers[t]),delete this.asyncTimers[t]),this.asyncRequests[t]=(this.asyncRequests[t]||0)+1}beginExternalValidation(t){this.cancelFieldAsync(t),this.updateFieldValidating(t,!0)}endExternalValidation(t){this.updateFieldValidating(t,!1)}async setExternalError(t,e){if(e){this.asyncErrors[t]=e,this.store.setError(t,e);return}if(delete this.asyncErrors[t],this.store.validate){await this.store.validate({scopeFields:[t]});return}let s={...this.store.getState().errors};delete s[t],this.store.internalUpdateState({errors:s,isValid:Object.keys(s).length===0})}handleAsync(t,e){let s=this.store.getFieldConfig(t),r=s?.validation?.asyncValidate;if(!r){this.updateFieldValidating(t,!1);return}this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]);let i=s.validation?.asyncValidateDelay??500;this.updateFieldValidating(t,!0),this.asyncTimers[t]=setTimeout(async()=>{delete this.asyncTimers[t];let n=(this.asyncRequests[t]||0)+1;this.asyncRequests[t]=n;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 if(delete this.asyncErrors[t],this.store.validate)await this.store.validate({scopeFields:[t]});else{let a={...this.store.getState().errors};delete a[t],this.store.internalUpdateState({errors:a,isValid:Object.keys(a).length===0})}}finally{this.asyncRequests[t]===n&&this.updateFieldValidating(t,!1)}},i)}hasValidationsInProgress(t){let e=this.store.getState();return t&&t.length>0?t.some(s=>!!e.isValidating[s]):Object.values(e.isValidating).some(Boolean)}trigger(t){this.validationTimeout&&clearTimeout(this.validationTimeout);let e=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=t?.scopeFields;if(t?.scope){let a=this.store.getScopeFields(t.scope);a.length>0&&(r=a)}await this.store.emitBeforeValidate({values:s.values,state:s,scope:t?.scope,scopeFields:r});let i=this.store.config.resolver?await this.store.config.resolver(s.values,{scopeFields:r}):{},n=this.store.getRequiredErrors(s.values);if(i={...i,...n},this.store.getHiddenFields().forEach(a=>{delete i[a],delete this.asyncErrors[a]}),e!==this.currentValidationId)return await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:t?.scope,scopeFields:r,errors:this.store.getState().errors,result:s.isValid,aborted:!0}),s.isValid;if(r){let a={...s.errors};r.forEach(u=>{i[u]?a[u]=i[u]:this.asyncErrors[u]?a[u]=this.asyncErrors[u]:delete a[u]});let d=Object.keys(a).length===0;this.store.internalUpdateState({errors:a,isValid:d});let c=r.every(u=>!i[u]&&!this.asyncErrors[u]);return await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:t?.scope,scopeFields:r,errors:a,result:c}),c}i={...this.asyncErrors,...i};let l=Object.keys(i).length===0;return this.store.internalUpdateState({errors:i,isValid:l}),await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:t?.scope,scopeFields:r,errors:i,result:l}),l}clear(t){this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]),delete this.asyncTimers[t],this.updateFieldValidating(t,!1),delete this.asyncErrors[t]}cancelAll(){this.validationTimeout&&clearTimeout(this.validationTimeout),Object.values(this.asyncTimers).forEach(t=>clearTimeout(t)),this.asyncTimers={},this.store.internalUpdateState({isValidating:{}})}};var A=class{constructor(t){this.store=t}updateField(t,e,s={origin:"setField"}){let r=this.store.getState(),i=g(r.values,t),n=v(r.values,t,e),l={...r.errors};delete l[t],this.store.clearFieldValidation(t),this.store.updateDependencies(t,n).forEach(c=>{this.store.isFieldHidden(c)&&(delete l[c],this.store.clearFieldValidation(c))});let d=this.store.updateDirtyForPath(t,n,this.store.config.initialValues);this.store.internalUpdateState({values:n,errors:l,isValid:Object.keys(l).length===0,isDirty:d}),this.store.emitFieldChange({path:t,previousValue:i,nextValue:e,values:this.store.getState().values,state:this.store.getState(),meta:s}),this.store.config.resolver&&this.store.triggerValidation([t]),this.store.handleFieldAsyncValidation(t,e)}replaceValues(t,e="replaceValues"){let s=this.store.getState().values,r=p(t);this.store.cancelAllValidations(),this.store.evaluateAllDependencies(r);let i=this.store.rebuildDirtyState(r,this.store.config.initialValues);this.store.internalUpdateState({values:r,errors:{},isValidating:{},isValid:!0,isDirty:i,isSubmitting:!1}),this.store.internalSaveSnapshot(),this.store.validateNow(),this.store.emitFieldChange({path:"*",previousValue:s,nextValue:r,values:this.store.getState().values,state:this.store.getState(),meta:{origin:e}})}hydrateValues(t){let e=M(this.store.getState().values,t);this.replaceValues(e,"hydrate")}rebaseValues(t){let e=this.store.getState().values,s=p(t);this.store.config.initialValues=p(s),this.store.cancelAllValidations(),this.store.evaluateAllDependencies(s),this.store.clearDirtyState(),this.store.internalUpdateState({values:s,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.internalSaveSnapshot(),this.store.validateNow(),this.store.emitFieldChange({path:"*",previousValue:e,nextValue:s,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"rebase"}})}async submit(t){if(this.store.getState().isSubmitting||this.store.hasValidationsInProgress())return;if(this.store.cancelAllValidations(),this.store.internalUpdateState({isSubmitting:!0}),await this.store.validateNow())try{let r=p(this.store.getState().values);this.store.getHiddenFields().forEach(n=>{r=v(r,n,void 0)});for(let[n,l]of this.store.getTransformEntries()){let a=g(r,n);r=v(r,n,l(a,this.store.getState().values))}let i=this.store.buildDirtyValues(r);await this.store.emitBeforeSubmit({values:r,dirtyValues:i,state:this.store.getState()}),await t(r,i),await this.store.emitAfterSubmit({values:r,dirtyValues:i,state:this.store.getState(),success:!0})}catch(r){await this.store.emitOperationalError({source:"submit",error:r}),await this.store.emitAfterSubmit({values:this.store.getState().values,dirtyValues:this.store.buildDirtyValues(this.store.getState().values),state:this.store.getState(),success:!1,error: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}),await this.store.emitAfterSubmit({values:this.store.getState().values,dirtyValues:this.store.buildDirtyValues(this.store.getState().values),state:this.store.getState(),success:!1,invalid:!0})}this.store.internalUpdateState({isSubmitting:!1})}reset(){this.store.cancelAllValidations();let t=p(this.store.config.initialValues);this.store.evaluateAllDependencies(t),this.store.clearDirtyState(),this.store.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.resetHistory(t)}};function Vt(){return`
2
+ .bit-devtools-container {
3
+ position: fixed;
4
+ bottom: 20px;
5
+ right: 20px;
6
+ z-index: 9999;
7
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
8
+ display: flex;
9
+ flex-direction: column;
10
+ align-items: flex-end;
11
+ }
12
+
13
+ .bit-devtools-trigger {
14
+ background: #10b981;
15
+ color: #fff;
16
+ border: none;
17
+ border-radius: 50%;
18
+ width: 48px;
19
+ height: 48px;
20
+ cursor: pointer;
21
+ box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
22
+ font-weight: bold;
23
+ display: flex;
24
+ align-items: center;
25
+ justify-content: center;
26
+ transition: transform 0.2s;
27
+ font-size: 16px;
28
+ margin-top: 16px;
29
+ }
30
+ .bit-devtools-trigger:hover { transform: scale(1.05); }
31
+
32
+ .bit-devtools-panel {
33
+ width: 450px;
34
+ max-height: 80vh;
35
+ background: #0f172a;
36
+ color: #f8fafc;
37
+ border-radius: 8px;
38
+ padding: 16px;
39
+ overflow-y: auto;
40
+ box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5), 0 8px 10px -6px rgba(0,0,0,0.5);
41
+ border: 1px solid #334155;
42
+ display: flex;
43
+ flex-direction: column;
44
+ gap: 16px;
45
+ }
46
+
47
+ .bit-devtools-header {
48
+ display: flex;
49
+ justify-content: space-between;
50
+ align-items: center;
51
+ padding-bottom: 12px;
52
+ border-bottom: 1px solid #1e293b;
53
+ }
54
+ .bit-devtools-header h2 { margin: 0; font-size: 16px; display: flex; align-items: center; gap: 8px; }
55
+
56
+ .bit-store-block {
57
+ background: #1e293b;
58
+ border-radius: 6px;
59
+ padding: 12px;
60
+ border: 1px solid #334155;
61
+ }
62
+
63
+ .bit-store-header {
64
+ display: flex;
65
+ justify-content: space-between;
66
+ align-items: center;
67
+ margin-bottom: 12px;
68
+ }
69
+ .bit-store-title { margin: 0; color: #38bdf8; font-size: 14px; font-weight: bold; }
70
+
71
+ .bit-badge-group { display: flex; gap: 6px; flex-wrap: wrap; }
72
+ .bit-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: bold; }
73
+ .badge-success { background: rgba(16, 185, 129, 0.2); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.2); }
74
+ .badge-error { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.2); }
75
+ .badge-warn { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.2); }
76
+ .badge-info { background: rgba(56, 189, 248, 0.2); color: #7dd3fc; border: 1px solid rgba(56, 189, 248, 0.2); }
77
+
78
+ .bit-section-title { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin: 12px 0 4px 0; display: block; }
79
+
80
+ .bit-controls { display: flex; gap: 6px; margin-bottom: 12px; background: #0f172a; padding: 8px; border-radius: 6px; }
81
+ .bit-action-btn { flex: 1; background: #334155; color: #e2e8f0; border: 1px solid #475569; padding: 6px 0; border-radius: 4px; cursor: pointer; font-size: 11px; display: flex; align-items: center; justify-content: center; gap: 4px; transition: all 0.2s; }
82
+ .bit-action-btn:hover:not(:disabled) { background: #475569; }
83
+ .bit-action-btn:disabled { opacity: 0.5; cursor: not-allowed; }
84
+ .bit-btn-reset { color: #fca5a5; border-color: rgba(239,68,68,0.3); }
85
+ .bit-btn-reset:hover { background: rgba(239,68,68,0.1) !important; }
86
+
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
+ 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 V=class{container;actions;rootElement;currentStoresState={};isOpen=!1;constructor(t,e){if(this.container=t,this.actions=e,!document.getElementById("bit-devtools-styles")){let s=document.createElement("style");s.id="bit-devtools-styles",s.textContent=Vt(),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=`
90
+ <div class="bit-devtools-panel">
91
+ <div class="bit-devtools-header">
92
+ <h2><span style="font-size: 20px;">\u{1F6E0}</span> Bit-Form DevTools</h2>
93
+ <span style="font-size: 11px; color: #64748b;">v1.0.0</span>
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,d=l.totalSteps;e+=`
96
+ <div class="bit-store-block">
97
+ <div class="bit-store-header">
98
+ <h3 class="bit-store-title">${r}</h3>
99
+ <div class="bit-badge-group">
100
+ <span class="bit-badge ${i.isValid?"badge-success":"badge-error"}">
101
+ ${i.isValid?"\u2713 Valid":"\u2715 Invalid"}
102
+ </span>
103
+ ${i.isDirty?'<span class="bit-badge badge-warn">Dirty</span>':""}
104
+ ${i.isSubmitting?'<span class="bit-badge badge-info">\u23F3 Submitting</span>':""}
105
+ </div>
106
+ </div>
107
+
108
+ <span class="bit-section-title">Time Travel (${a}/${d})</span>
109
+
110
+ <div class="bit-controls">
111
+ <button class="bit-action-btn" data-action="undo" data-store="${r}" ${l.canUndo?"":"disabled"}>
112
+ <span>\u21BA</span> Undo
113
+ </button>
114
+ <button class="bit-action-btn" data-action="redo" data-store="${r}" ${l.canRedo?"":"disabled"}>
115
+ <span>\u21BB</span> Redo
116
+ </button>
117
+ <button class="bit-action-btn bit-btn-reset" data-action="reset" data-store="${r}">
118
+ <span>\u{1F5D1}</span> Reset
119
+ </button>
120
+ </div>
121
+ `,n&&(e+=`
122
+ <span class="bit-section-title" style="color: #f87171;">\u26A0\uFE0F Validations Failing</span>
123
+ <pre class="bit-error-box">${JSON.stringify(i.errors,null,2)}</pre>
124
+ `),e+=`
125
+ <span class="bit-section-title">Values</span>
126
+ <pre class="bit-pre">${JSON.stringify(i.values,null,2)}</pre>
127
+ </div>
128
+ `}e+="</div>"}let s=`
129
+ <button class="bit-devtools-trigger" style="transform: ${this.isOpen?"scale(0.9)":"scale(1)"};" title="Abrir DevTools">
130
+ ${this.isOpen?"\u2716":"Bit"}
131
+ </button>
132
+ `;this.rootElement.innerHTML=e+s}};function kt(o){let t=new V(o,{onUndo:r=>m.stores[r]?.undo(),onRedo:r=>m.stores[r]?.redo(),onReset:r=>m.stores[r]?.reset()}),e=()=>{let r={};for(let[i,n]of Object.entries(m.stores)){let l=n,a=l.getState(),d=l?.getHistoryMetadata?.()||{enabled:!1,canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};r[i]={...a,_meta:{canUndo:d.canUndo,canRedo:d.canRedo,totalSteps:d.historySize,currentIndex:d.historyIndex}}}return r};t.updateState(e());let s=m.subscribe(()=>{t.updateState(e())});return{ui:t,destroy:()=>{s(),o.innerHTML=""}}}function Mt(o,t="ws://localhost:3000"){let e=new WebSocket(t),s=new V(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 St(o={}){let{mode:t="local",url:e}=o,s,r=!1;if(typeof o.container=="string"){let n=document.querySelector(o.container);if(!n)throw new Error(`[bit-form] Container '${o.container}' n\xE3o encontrado na p\xE1gina.`);s=n}else o.container instanceof HTMLElement?s=o.container:(s=document.createElement("div"),s.id="bit-form-devtools-root",s.style.position="fixed",s.style.bottom="20px",s.style.right="20px",s.style.zIndex="9999",s.style.maxHeight="80vh",s.style.overflowY="auto",s.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)",document.body.appendChild(s),r=!0);let i;if(t==="local")console.log("[bit-form] DevTools iniciado em modo Local."),i=kt(s);else if(t==="remote")console.log("[bit-form] DevTools iniciado em modo Remote."),i=Mt(s,e);else throw new Error(`[bit-form] Modo DevTools inv\xE1lido: ${t}`);return{...i,destroy:()=>{i&&typeof i.destroy=="function"&&i.destroy(),r&&s.parentNode?s.parentNode.removeChild(s):s.innerHTML=""}}}var R=class{store;cleanupFn=null;constructor(t){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,mode:t.mode??"local",...t};if(e.enabled)if(e.mode==="remote"){let s=e.url||"ws://localhost:3000";this.cleanupFn=Pt(s)}else{let s=St();s&&typeof s.destroy=="function"&&(this.cleanupFn=s.destroy)}}destroy(){this.cleanupFn&&this.cleanupFn()}};var H=class{dirtyPaths=new Set;updateForPath(t,e,s){for(let n of this.dirtyPaths)n.startsWith(t+".")&&this.dirtyPaths.delete(n);let r=g(e,t),i=g(s,t);return b(r,i)?this.dirtyPaths.delete(t):this.dirtyPaths.add(t),this.dirtyPaths.size>0}rebuild(t,e){return this.dirtyPaths=_(t,e),this.dirtyPaths.size>0}clear(){this.dirtyPaths.clear()}get isDirty(){return this.dirtyPaths.size>0}getDirtyPaths(){return this.dirtyPaths}buildDirtyValues(t){if(this.dirtyPaths.size===0)return{};let e={},s=new Set;for(let r of this.dirtyPaths){let i=r.match(/^(.+)\.(\d+)/);if(i){let n=i[1];if(s.has(n))continue;s.add(n),this.setNestedValue(e,n,this.getNestedValue(t,n))}else this.setNestedValue(e,r,this.getNestedValue(t,r))}return e}getNestedValue(t,e){let s=e.split("."),r=t;for(let i of s){if(r==null)return;r=r[i]}return r}setNestedValue(t,e,s){let r=e.split("."),i=t;for(let n=0;n<r.length-1;n++){let l=r[n];l in i||(i[l]={}),i=i[l]}i[r[r.length-1]]=s}};var O=class{constructor(t,e,s){this.getState=t;this.getInitialValues=e;this.getScopeFields=s}getStepStatus(t){let e=this.getScopeFields(t),s=this.getState(),r=e.some(l=>!!s.errors[l]),i=e.some(l=>{let a=g(s.values,l),d=g(this.getInitialValues(),l);return!b(a,d)}),n=this.getStepErrors(t);return{hasErrors:r,isDirty:i,errors:n}}getStepErrors(t){let e=this.getScopeFields(t),s=this.getState(),r={};for(let i of e){let n=s.errors[i];n&&(r[i]=n)}return r}};var $=class{constructor(t,e,s){this.depsMg=t;this.getState=e;this.getConfig=s}isHidden(t){return this.depsMg.isHidden(t)}isRequired(t){return this.depsMg.isRequired(t,this.getState().values)}isFieldDirty(t){let e=g(this.getState().values,t),s=g(this.getConfig().initialValues,t);return!b(e,s)}isFieldValidating(t){return!!this.getState().isValidating[t]}};var U=class{constructor(t,e){this.getState=t;this.internalUpdateState=e}setError(t,e){let s={...this.getState().errors,[t]:e};e||delete s[t],this.internalUpdateState({errors:s})}setErrors(t){this.internalUpdateState({errors:{...this.getState().errors,...t}})}setServerErrors(t){let e={};for(let[s,r]of Object.entries(t))e[s]=Array.isArray(r)?r[0]:r;this.setErrors(e)}};function Ut(){if(typeof globalThis>"u")return;let o=globalThis.localStorage;if(o)return{getItem:t=>o.getItem(t),setItem:(t,e)=>o.setItem(t,e),removeItem:t=>o.removeItem(t)}}var N=class{constructor(t,e,s,r){this.config=t;this.getValues=e;this.getDirtyValues=s;this.applyRestoredValues=r}timer;getStorage(){return this.config.storage||Ut()}canPersist(){return!!(this.config.enabled&&this.config.key&&this.getStorage())}handleError(t){this.config.onError?.(t)}async saveNow(){if(!this.canPersist())return;let t=this.getStorage();if(t)try{let e=this.config.mode==="dirtyValues"?this.getDirtyValues():this.getValues(),s=this.config.serialize(p(e));await t.setItem(this.config.key,s)}catch(e){this.handleError(e)}}queueSave(){!this.canPersist()||!this.config.autoSave||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.saveNow()},this.config.debounceMs))}async restore(){if(!this.canPersist())return!1;let t=this.getStorage();if(!t)return!1;try{let e=await t.getItem(this.config.key);if(!e)return!1;let s=this.config.deserialize(e);return!s||typeof s!="object"?!1:(this.applyRestoredValues(s),!0)}catch(e){return this.handleError(e),!1}}async clear(){if(!this.canPersist())return;let t=this.getStorage();if(t)try{await t.removeItem(this.config.key)}catch(e){this.handleError(e)}}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}};var q=class{constructor(t,e){this.plugins=t;this.contextFactory=e}teardownFns=[];notifyingError=!1;setupAll(){this.plugins.forEach(t=>{if(t.setup)try{let e=t.setup(this.contextFactory());typeof e=="function"&&this.teardownFns.push(e)}catch(e){this.reportError("setup",e,void 0,t.name)}})}async beforeValidate(t){await this.emitHook("beforeValidate",t)}async afterValidate(t){await this.emitHook("afterValidate",t)}async beforeSubmit(t){await this.emitHook("beforeSubmit",t)}async afterSubmit(t){await this.emitHook("afterSubmit",t)}onFieldChange(t){this.plugins.forEach(e=>{let s=e.hooks?.onFieldChange;if(s)try{let r=s(t,this.contextFactory());Promise.resolve(r).catch(i=>{this.reportError("onFieldChange",i,t,e.name)})}catch(r){this.reportError("onFieldChange",r,t,e.name)}})}async reportError(t,e,s,r){if(this.notifyingError)return;this.notifyingError=!0;let i=this.contextFactory(),n={source:t,pluginName:r,error:e,event:s,values:i.getState().values,state:i.getState()};for(let l of this.plugins){let a=l.hooks?.onError;if(a)try{await a(n,i)}catch{}}this.notifyingError=!1}destroy(){for(let t=this.teardownFns.length-1;t>=0;t-=1){let e=this.teardownFns[t];try{e()}catch(s){this.reportError("teardown",s)}}this.teardownFns=[]}async emitHook(t,e){let s=this.contextFactory();for(let r of this.plugins){let i=r.hooks?.[t];if(i)try{await i(e,s)}catch(n){await this.reportError(t,n,e,r.name)}}}};var L=class{state;listeners=new Set;selectorListeners=new Set;persistMg;pluginMg;config;storeId;depsMg;validatorMg;computedMg;dirtyMg;lifecycleMg;historyMg;arraysMg;scopeMg;devtoolsMg;queryMg;errorMg;constructor(t={}){this.config=Et(t),this.depsMg=new F,this.computedMg=new D(()=>this.getComputedEntries()),this.validatorMg=new I(this),this.dirtyMg=new H,this.lifecycleMg=new A(this),this.historyMg=new w(!!this.config.enableHistory,this.config.historyLimit??15),this.arraysMg=new C(this),this.devtoolsMg=new R(this),this.scopeMg=new O(()=>this.state,()=>this.config.initialValues,r=>this.getScopeFields(r)),this.queryMg=new $(this.depsMg,()=>this.state,()=>this.config),this.errorMg=new U(()=>this.state,r=>this.internalUpdateState(r)),this.persistMg=new N(this.config.persist,()=>this.state.values,()=>this.getDirtyValues(),r=>this.applyPersistedValues(r));let e=p(this.config.initialValues);this.config.fields&&Object.entries(this.config.fields).forEach(([r,i])=>{this.depsMg.register(r,i,e)});let s=this.computedMg.apply(e);this.state={values:s,errors:{},touched:{},isValidating:{},isValid:!0,isSubmitting:!1,isDirty:!1},this.internalSaveSnapshot(),this.storeId=this.config.name||`bit-form-${Math.random().toString(36).substring(2,9)}`,this.pluginMg=new q(this.config.plugins,()=>({storeId:this.storeId,getState:()=>this.getState(),getConfig:()=>this.getConfig()})),this.pluginMg.setupAll(),m.stores[this.storeId]=this}getConfig(){return this.config}getFieldConfig(t){return this.depsMg.fieldConfigs.get(t)||this.config.fields?.[t]}getScopeFields(t){let e=[];return this.depsMg.fieldConfigs.forEach((s,r)=>{s.scope===t&&e.push(r)}),e}getComputedEntries(){let t=[];return this.depsMg.fieldConfigs.forEach((e,s)=>{e.computed&&t.push([s,e.computed])}),t}getTransformEntries(){let t=[];return this.depsMg.fieldConfigs.forEach((e,s)=>{e.transform&&t.push([s,e.transform])}),t}resolveMask(t){let e=this.getFieldConfig(t)?.mask;if(e)return typeof e=="string"?this.config.masks?.[e]:e}getState(){return this.state}getFieldState(t){return{value:g(this.state.values,t),error:this.state.errors[t],touched:!!this.state.touched[t],isHidden:this.isHidden(t),isRequired:this.isRequired(t),isDirty:this.isFieldDirty(t),isValidating:this.isFieldValidating(t)}}get isValid(){return this.state.isValid}get isSubmitting(){return this.state.isSubmitting}get isDirty(){return this.state.isDirty}registerField(t,e){this.depsMg.register(t,e,this.state.values),this.depsMg.isHidden(t)&&this.notify()}unregisterField(t){if(this.config.fields?.[t])return;this.depsMg.unregister(t);let e={...this.state.errors},s={...this.state.touched},r=!1;e[t]&&(delete e[t],r=!0),s[t]&&(delete s[t],r=!0),r&&this.internalUpdateState({errors:e,touched:s})}unregisterPrefix(t){this.depsMg.unregisterPrefix(t)}isHidden(t){return this.queryMg.isHidden(t)}isRequired(t){return this.queryMg.isRequired(t)}isFieldDirty(t){return this.queryMg.isFieldDirty(t)}isFieldValidating(t){return this.queryMg.isFieldValidating(t)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}subscribeSelector(t,e,s){let r=s?.equalityFn??b,i=t(this.state),n={notify:l=>{let a=t(l);r(i,a)||(i=a,e(a))}};return this.selectorListeners.add(n),s?.emitImmediately&&e(i),()=>this.selectorListeners.delete(n)}subscribePath(t,e,s){return this.subscribeSelector(r=>g(r.values,t),e,s)}watch(t,e){return this.subscribePath(t,e,{equalityFn:T})}setField(t,e){this.setFieldWithMeta(t,e,{origin:"setField"})}setFieldWithMeta(t,e,s={origin:"setField"}){this.lifecycleMg.updateField(t,e,s)}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.rebase(t)}replaceValues(t){this.lifecycleMg.replaceValues(t)}hydrate(t){this.lifecycleMg.hydrateValues(t)}rebase(t){this.lifecycleMg.rebaseValues(t)}setError(t,e){this.errorMg.setError(t,e)}setErrors(t){this.errorMg.setErrors(t)}setServerErrors(t){this.errorMg.setServerErrors(t)}reset(){this.lifecycleMg.reset()}async submit(t){return this.lifecycleMg.submit(t)}registerMask(t,e){this.config.masks={...this.config.masks||{},[t]:e}}getDirtyValues(){return this.dirtyMg.buildDirtyValues(this.state.values)}async restorePersisted(){return this.persistMg.restore()}async forceSave(){await this.persistMg.saveNow()}async clearPersisted(){await this.persistMg.clear()}pushItem(t,e){this.arraysMg.pushItem(t,e)}prependItem(t,e){this.arraysMg.prependItem(t,e)}insertItem(t,e,s){this.arraysMg.insertItem(t,e,s)}removeItem(t,e){this.arraysMg.removeItem(t,e)}swapItems(t,e,s){this.arraysMg.swapItems(t,e,s)}moveItem(t,e,s){this.arraysMg.moveItem(t,e,s)}get canUndo(){return this.historyMg.canUndo}get canRedo(){return this.historyMg.canRedo}undo(){let t=this.historyMg.undo();if(t){let e=this.dirtyMg.rebuild(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}redo(){let t=this.historyMg.redo();if(t){let e=this.dirtyMg.rebuild(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}getHistoryMetadata(){return this.historyMg.getMetadata()}validate(t){return this.validatorMg.validate(t)}emitBeforeValidate(t){return this.pluginMg.beforeValidate(t)}emitAfterValidate(t){return this.pluginMg.afterValidate(t)}emitBeforeSubmit(t){return this.pluginMg.beforeSubmit(t)}emitAfterSubmit(t){return this.pluginMg.afterSubmit(t)}emitFieldChange(t){this.pluginMg.onFieldChange(t)}emitOperationalError(t){return this.pluginMg.reportError(t.source,t.error,t.payload)}hasValidationsInProgress(t){return this.validatorMg.hasValidationsInProgress(t)}beginFieldValidation(t){this.validatorMg.beginExternalValidation(t)}endFieldValidation(t){this.validatorMg.endExternalValidation(t)}setFieldAsyncError(t,e){return this.validatorMg.setExternalError(t,e)}clearFieldAsyncError(t){return this.validatorMg.setExternalError(t,void 0)}triggerValidation(t){this.validatorMg.trigger(t)}getStepStatus(t){return this.scopeMg.getStepStatus(t)}getStepErrors(t){return this.scopeMg.getStepErrors(t)}updateDependencies(t,e){return this.depsMg.updateDependencies(t,e)}isFieldHidden(t){return this.depsMg.isHidden(t)}evaluateAllDependencies(t){this.depsMg.evaluateAll(t)}getHiddenFields(){return Array.from(this.depsMg.hiddenFields)}getRequiredErrors(t){return this.depsMg.getRequiredErrors(t)}clearFieldValidation(t){this.validatorMg.clear(t)}handleFieldAsyncValidation(t,e){this.validatorMg.handleAsync(t,e)}cancelAllValidations(){this.validatorMg.cancelAll()}validateNow(t){return this.validatorMg.validate(t)}updateDirtyForPath(t,e,s){return this.dirtyMg.updateForPath(t,e,s)}rebuildDirtyState(t,e){return this.dirtyMg.rebuild(t,e)}clearDirtyState(){this.dirtyMg.clear()}buildDirtyValues(t){return this.dirtyMg.buildDirtyValues(t)}resetHistory(t){this.historyMg.reset(t)}internalUpdateState(t){let e=this.state,s={...this.state,...t};t.values&&(s.values=this.computedMg.apply(t.values)),t.errors&&(s.isValid=Object.keys(s.errors).length===0),this.state=s,t.values&&this.persistMg.queueSave(),this.notify(e,s),m.dispatch(this.storeId,this.state)}internalSaveSnapshot(){this.historyMg.saveSnapshot(this.state.values)}applyPersistedValues(t){let e=p({...this.config.initialValues,...t});this.validatorMg.cancelAll(),this.depsMg.evaluateAll(e);let s=this.dirtyMg.rebuild(e,this.config.initialValues);this.internalUpdateState({values:e,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:s,isSubmitting:!1}),this.internalSaveSnapshot(),this.validatorMg.validate()}cleanup(){this.listeners.clear(),this.selectorListeners.clear(),this.validatorMg.cancelAll(),this.devtoolsMg.destroy(),this.persistMg.destroy(),this.pluginMg.destroy(),delete m.stores[this.storeId]}notify(t=this.state,e=this.state){this.listeners.forEach(s=>s()),this.selectorListeners.forEach(s=>{s.notify(e)})}};function Nt(o={}){let t=new L(o);return{get config(){return t.config},getConfig:()=>t.getConfig(),getState:()=>t.getState(),getFieldState:t.getFieldState.bind(t),subscribe:t.subscribe.bind(t),subscribePath:t.subscribePath.bind(t),subscribeSelector:t.subscribeSelector.bind(t),setField:t.setField.bind(t),blurField:t.blurField.bind(t),replaceValues:t.replaceValues.bind(t),hydrate:t.hydrate.bind(t),rebase:t.rebase.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),reset:t.reset.bind(t),submit:t.submit.bind(t),registerMask:t.registerMask.bind(t),getDirtyValues:t.getDirtyValues.bind(t),restorePersisted:t.restorePersisted.bind(t),forceSave:t.forceSave.bind(t),clearPersisted:t.clearPersisted.bind(t),registerField:t.registerField.bind(t),unregisterField:t.unregisterField.bind(t),unregisterPrefix:t.unregisterPrefix.bind(t),isHidden:t.isHidden.bind(t),isRequired:t.isRequired.bind(t),isFieldDirty:t.isFieldDirty.bind(t),isFieldValidating:t.isFieldValidating.bind(t),watch:t.watch.bind(t),pushItem:t.pushItem.bind(t),prependItem:t.prependItem.bind(t),insertItem:t.insertItem.bind(t),removeItem:t.removeItem.bind(t),moveItem:t.moveItem.bind(t),swapItems:t.swapItems.bind(t),getHistoryMetadata:t.getHistoryMetadata.bind(t),undo:t.undo.bind(t),redo:t.redo.bind(t),getStepStatus:t.getStepStatus.bind(t),getStepErrors:t.getStepErrors.bind(t),markFieldsTouched:t.markFieldsTouched.bind(t),hasValidationsInProgress:t.hasValidationsInProgress.bind(t),beginFieldValidation:t.beginFieldValidation.bind(t),endFieldValidation:t.endFieldValidation.bind(t),setFieldAsyncError:t.setFieldAsyncError.bind(t),clearFieldAsyncError:t.clearFieldAsyncError.bind(t),resolveMask:t.resolveMask.bind(t),getScopeFields:t.getScopeFields.bind(t),cleanup:t.cleanup.bind(t)}}var Ft=o=>{let t=typeof o.getState=="function"?o.getState():o,e=o?.getHistoryMetadata?.()||{canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};return{...t,_meta:{canUndo:e.canUndo,canRedo:e.canRedo,totalSteps:e.historySize,currentIndex:e.historyIndex}}},j=null;function Pt(o){j&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),j());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((d,[c,u])=>(d[c]=Ft(u),d),{});t?.send(JSON.stringify({type:"STATE_UPDATE",payload:a}))}e=m.subscribe((a,d)=>{if(t?.readyState===WebSocket.OPEN){let c=m.stores[a];c&&t.send(JSON.stringify({type:"STATE_UPDATE",payload:{[a]:Ft(c)}}))}}),s=setInterval(()=>{t?.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"PING"}))},3e4)},t.onmessage=l=>{try{let a=JSON.parse(l.data);if(a.type==="ACTION"){let d=a.payload,c=d.storeId,u=d.action;if(typeof c!="string"||typeof u!="string")return;let f=m.stores[c];if(!f||typeof f!="object")return;let y=f[u];typeof y=="function"&&y.call(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(),j=null};return j=n,n}export{m as a,p as b,M as c,b as d,T as e,g as f,v as g,wt as h,Tt as i,Ct as j,E as k,xt as l,h as m,S as n,J as o,P as p,K as q,G as r,Z as s,Q as t,tt as u,et as v,st as w,rt as x,it as y,ot as z,nt as A,at as B,lt as C,dt as D,ct as E,ut as F,gt as G,Dt as H,It as I,At as J,Rt as K,pt as L,ht as M,Ht as N,ft as O,mt as P,yt as Q,bt as R,Ot as S,vt as T,Pt as U,St as V,Nt as W};
133
+ //# sourceMappingURL=chunk-6FJEE6O3.js.map