@lehnihon/bit-form 2.1.2 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/angular/index.cjs +1 -1
- package/dist/angular/index.d.cts +15 -3
- package/dist/angular/index.d.ts +15 -3
- package/dist/angular/index.js +1 -1
- package/dist/angular/index.js.map +1 -1
- package/dist/{bus-vCbulIYH.d.cts → bus-70e4jnBj.d.cts} +106 -1
- package/dist/{bus-vCbulIYH.d.ts → bus-70e4jnBj.d.ts} +106 -1
- package/dist/chunk-25Q2XJBV.cjs +133 -0
- package/dist/{chunk-2QNUW6ZN.cjs.map → chunk-25Q2XJBV.cjs.map} +1 -1
- package/dist/chunk-2HAQ3QEQ.js +133 -0
- package/dist/chunk-2HAQ3QEQ.js.map +1 -0
- package/dist/chunk-HTB6QIUQ.js +2 -0
- package/dist/chunk-HTB6QIUQ.js.map +1 -0
- package/dist/chunk-W22D7QVJ.cjs +2 -0
- package/dist/chunk-W22D7QVJ.cjs.map +1 -0
- package/dist/devtools/bridge.cjs +1 -1
- package/dist/devtools/bridge.js +1 -1
- package/dist/devtools/index.cjs +1 -1
- package/dist/devtools/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/{public-types-ChP5j3xc.d.ts → public-types-BVZ16kgZ.d.ts} +6 -1
- package/dist/{public-types-Nv__uZTR.d.cts → public-types-r2aP68Gg.d.cts} +6 -1
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +5 -5
- package/dist/react/index.d.ts +5 -5
- package/dist/react/index.js +1 -1
- package/dist/react/index.js.map +1 -1
- package/dist/react-native/index.cjs +1 -1
- package/dist/react-native/index.cjs.map +1 -1
- package/dist/react-native/index.d.cts +10 -12
- package/dist/react-native/index.d.ts +10 -12
- package/dist/react-native/index.js +1 -1
- package/dist/react-native/index.js.map +1 -1
- package/dist/resolvers/joi.d.cts +1 -1
- package/dist/resolvers/joi.d.ts +1 -1
- package/dist/resolvers/yup.d.cts +1 -1
- package/dist/resolvers/yup.d.ts +1 -1
- package/dist/resolvers/zod.d.cts +1 -1
- package/dist/resolvers/zod.d.ts +1 -1
- package/dist/{use-bit-watch-hA0AqCkC.d.ts → use-bit-persist-COdNw_fv.d.ts} +15 -3
- package/dist/{use-bit-watch-BRekIj2W.d.cts → use-bit-persist-JshPvwwy.d.cts} +15 -3
- package/dist/vue/index.cjs +1 -1
- package/dist/vue/index.d.cts +16 -4
- package/dist/vue/index.d.ts +16 -4
- package/dist/vue/index.js +1 -1
- package/dist/vue/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-2QNUW6ZN.cjs +0 -133
- package/dist/chunk-F6LJWWEW.js +0 -2
- package/dist/chunk-F6LJWWEW.js.map +0 -1
- package/dist/chunk-LPRLSFPT.cjs +0 -2
- package/dist/chunk-LPRLSFPT.cjs.map +0 -1
- package/dist/chunk-N6IA7HQL.js +0 -133
- package/dist/chunk-N6IA7HQL.js.map +0 -1
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
var j=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;j.__BIT_FORM__||(j.__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=j.__BIT_FORM__;function f(o){if(o===null||typeof o!="object")return o;if(o instanceof Date)return new Date(o.getTime());if(o instanceof RegExp)return new RegExp(o.source,o.flags);if(Array.isArray(o))return o.map(e=>f(e));let t={};for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&(t[e]=f(o[e]));return t}function S(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 z(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;z(o?.[i],t?.[i],n,s)}return s}var B=new Map;function g(o,t){if(!t)return o;let e=B.get(t)||t.split(".");B.has(t)||B.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=B.get(t)||t.split(".");B.has(t)||B.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 Ct(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),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},X=(o,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(o).forEach(n=>{if(!n.startsWith(i)){r[n]=o[n];return}let 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},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("."),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 h=c?`${i}${u}.${c}`:`${i}${u}`;r[h]=o[n]}),r};function St(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 wt(o){return St(o)?o.errors??o:{}}var Tt={"#":/\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},p=(o,t)=>{let e=s=>s.split("").filter(r=>Tt[r]).length;return{format:s=>{let r=E(s,t?.allowChars);if(!r&&!t?.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="",d=0,c=t?.guide||!1,u=t?.placeholderChar||"_";for(let h=0;h<l.length;h++){let v=l[h],k=Tt[v];if(d<r.length){let x=r[d];if(k)if(v==="U"&&(x=x.toUpperCase()),v==="L"&&(x=x.toLowerCase()),k.test(x))a+=x,d++;else if(c)a+=u;else break;else a+=v,x===v&&d++}else if(c)a+=k?u:v;else break}return a},parse:s=>{if(t?.customParse)return t.customParse(s);let i=p(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)}}},b=({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),h=c.replace(/\B(?=(\d{3})+(?!\d))/g,e);return`${(typeof a=="number"?a<0:String(a).includes("-"))&&i?"-":""}${o}${h}${s}${u}${t}`};return{format:l,parse:a=>{let d=xt(a,r),c=i?d:Math.abs(d);return n?l(c):c}}},Y=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 p(r,o).format(e)},parse:e=>{let s=E(e,o?.allowChars),r=t(s);return p(r,o).parse(e)}}},V=o=>{let e=(o?.format||"DD/MM/YYYY")==="YYYY-MM-DD",s=p(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 J=b({prefix:"R$ ",thousand:".",decimal:",",precision:2}),K=b({prefix:"$",thousand:",",decimal:".",precision:2}),G=b({suffix:" \u20AC",thousand:".",decimal:",",precision:2}),Z=b({prefix:"\xA3",thousand:",",decimal:".",precision:2}),Q=b({prefix:"\xA5",thousand:",",decimal:".",precision:0}),tt=b({suffix:"%",thousand:".",decimal:",",precision:1}),et=b({thousand:".",decimal:",",precision:2}),st=b({thousand:".",decimal:",",precision:0}),rt=p("###.###.###-##"),it=p("##.###.###/####-##"),ot=p(["(##) ####-####","(##) #####-####"]),nt=p("(##) ####-####"),at=p("#####-###"),lt=V({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,"")}}),dt=p("##:##"),ct=p("###########"),ut=p("##.###.###-X"),Ft=p("(###) ###-####"),Dt=p("#####-####"),It=p("##/##/####"),At=p("###-##-####"),gt=Y(),pt=p("####"),Rt=V({format:"YYYY-MM-DD",saveRaw:!0,guide:!0}),ft=p("HH:HH:HH:HH:HH:HH"),ht=p("#HHHHHH"),mt=p("###.###.###.###"),yt=p("HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH"),Ht=p("UU## XXXX XXXX XXXX XXXX XXXX XXXX XXXX XX",{allowChars:" "});var bt={brl:J,usd:K,eur:G,gbp:Z,jpy:Q,cpf:rt,cnpj:it,rg:ut,cep:at,cnh:ct,phone:ot,landline:nt,date:lt,time:dt,ip:mt,ipv6:yt,mac:ft,color:ht,cc:gt,cvv:pt,percent:tt,decimal:et,int:st};function Bt(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:f(t),resolver:e?.resolver,validationDelay:e?.delay??300,enableHistory:s?.enabled??!1,historyLimit:s?.limit??15,masks:{...bt},fields:o.fields,devTools:o.devTools,persist:i,plugins:o.plugins??[]}}var P=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=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=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 C=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(f(t)),this.history.length>this.maxHistory?this.history.shift():this.historyIndex++)}get canUndo(){return this.enableHistory?this.historyIndex>0:!1}get canRedo(){return this.enableHistory?this.historyIndex<this.history.length-1:!1}undo(){return this.canUndo?(this.historyIndex--,f(this.history[this.historyIndex])):null}redo(){return this.canRedo?(this.historyIndex++,f(this.history[this.historyIndex])):null}reset(t){this.history=[],this.historyIndex=-1,this.saveSnapshot(t)}getMetadata(){return{enabled:this.enableHistory,canUndo:this.canUndo,canRedo:this.canRedo,historyIndex:this.historyIndex,historySize:this.history.length}}};var w=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=y(s.values,t,n),a=this.store.dirtyMg.updateForPath(t,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:_(s.errors,t,e),touched:_(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=y(r.values,t,i),a=this.store.dirtyMg.updateForPath(t,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:X(r.errors,t,e,s),touched:X(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=y(r.values,t,i),d=this.store.dirtyMg.updateForPath(t,a,this.store.getConfig().initialValues);this.store.internalUpdateState({values:a,errors:W(r.errors,t,e,s),touched:W(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){let e=this.store;typeof e.triggerValidation=="function"?e.triggerValidation([t]):typeof this.store.validate=="function"&&this.store.validate()}};var F=class{constructor(t){this.getComputedEntries=t}apply(t){let e=this.getComputedEntries();if(e.length===0)return t;let s=t;for(let r=0;r<2;r++){let i=!1;for(let[n,l]of e){let a=l(s),d=g(s,n);T(d,a)||(s=y(s,n,a),i=!0)}if(!i)break}return s}};var D=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.depsMg.getRequiredErrors(s.values);if(i={...i,...n},this.store.depsMg.hiddenFields.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 I=class{constructor(t){this.store=t}updateField(t,e,s={origin:"setField"}){let r=this.store.getState(),i=g(r.values,t),n=y(r.values,t,e),l={...r.errors};delete l[t],this.store.validatorMg.clear(t);let a=this.store.depsMg.updateDependencies(t,n);a.forEach(c=>{this.store.depsMg.isHidden(c)&&(delete l[c],this.store.validatorMg.clear(c))});let d=this.store.dirtyMg.updateForPath(t,n,this.store.config.initialValues);return 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.validatorMg.trigger([t]),this.store.validatorMg.handleAsync(t,e),{visibilitiesChanged:a.length>0}}updateAll(t){let e=this.store.getState().values,s=f(t);this.store.config.initialValues=f(s),this.store.validatorMg.cancelAll(),this.store.depsMg.evaluateAll(s),this.store.dirtyMg.clear(),this.store.internalUpdateState({values:s,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.internalSaveSnapshot(),this.store.validatorMg.validate(),this.store.emitFieldChange({path:"*",previousValue:e,nextValue:s,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"setValues"}})}async submit(t){if(this.store.getState().isSubmitting||this.store.validatorMg.hasValidationsInProgress())return;if(this.store.validatorMg.cancelAll(),this.store.internalUpdateState({isSubmitting:!0}),await this.store.validatorMg.validate())try{let r=f(this.store.getState().values);this.store.depsMg.hiddenFields.forEach(n=>{r=y(r,n,void 0)});for(let[n,l]of this.store.getTransformEntries()){let a=g(r,n);r=y(r,n,l(a,this.store.getState().values))}let i=this.store.dirtyMg.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.dirtyMg.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.dirtyMg.buildDirtyValues(this.store.getState().values),state:this.store.getState(),success:!1,invalid:!0})}this.store.internalUpdateState({isSubmitting:!1})}reset(){this.store.validatorMg.cancelAll();let t=f(this.store.config.initialValues);this.store.depsMg.evaluateAll(t),this.store.dirtyMg.clear(),this.store.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.historyMg.reset(t)}};function Et(){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 M=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=Et(),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 Mt(o){let t=new M(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 kt(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 vt(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=Mt(s);else if(t==="remote")console.log("[bit-form] DevTools iniciado em modo Remote."),i=kt(s,e);else throw new Error(`[bit-form] Modo DevTools inv\xE1lido: ${t}`);return{...i,destroy:()=>{i&&typeof i.destroy=="function"&&i.destroy(),r&&s.parentNode?s.parentNode.removeChild(s):s.innerHTML=""}}}var A=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,...t};if(e.enabled)if(e.mode==="remote"){let s=e.url||"ws://localhost:3000";this.cleanupFn=Vt(s)}else{let s=vt();s&&typeof s.destroy=="function"&&(this.cleanupFn=s.destroy)}}destroy(){this.cleanupFn&&this.cleanupFn()}};var R=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 S(r,i)?this.dirtyPaths.delete(t):this.dirtyPaths.add(t),this.dirtyPaths.size>0}rebuild(t,e){return this.dirtyPaths=z(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 H=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!S(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 O=class{constructor(t,e,s){this.depsMg=t;this.getState=e;this.getConfig=s}isHidden(t){return this.depsMg.isHidden(t)}isRequired(t){return this.depsMg.isRequired(t,this.getState().values)}isFieldDirty(t){let e=g(this.getState().values,t),s=g(this.getConfig().initialValues,t);return!S(e,s)}isFieldValidating(t){return!!this.getState().isValidating[t]}};var $=class{constructor(t,e){this.getState=t;this.internalUpdateState=e}setError(t,e){let s={...this.getState().errors,[t]:e};e||delete s[t],this.internalUpdateState({errors:s})}setErrors(t){this.internalUpdateState({errors:{...this.getState().errors,...t}})}setServerErrors(t){let e={};for(let[s,r]of Object.entries(t))e[s]=Array.isArray(r)?r[0]:r;this.setErrors(e)}};function $t(){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 U=class{constructor(t,e,s,r){this.config=t;this.getValues=e;this.getDirtyValues=s;this.applyRestoredValues=r}timer;getStorage(){return this.config.storage||$t()}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(f(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 N=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;persistMg;pluginMg;config;storeId;depsMg;validatorMg;computedMg;dirtyMg;lifecycleMg;historyMg;arraysMg;scopeMg;devtoolsMg;queryMg;errorMg;constructor(t={}){this.config=Bt(t),this.depsMg=new P,this.computedMg=new F(()=>this.getComputedEntries()),this.validatorMg=new D(this),this.dirtyMg=new R,this.lifecycleMg=new I(this),this.historyMg=new C(!!this.config.enableHistory,this.config.historyLimit??15),this.arraysMg=new w(this),this.devtoolsMg=new A(this),this.scopeMg=new H(()=>this.state,()=>this.config.initialValues,r=>this.getScopeFields(r)),this.queryMg=new O(this.depsMg,()=>this.state,()=>this.config),this.errorMg=new $(()=>this.state,r=>this.internalUpdateState(r)),this.persistMg=new U(this.config.persist,()=>this.state.values,()=>this.getDirtyValues(),r=>this.applyPersistedValues(r));let e=f(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 N(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}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)}watch(t,e){let s=f(g(this.state.values,t));return this.subscribe(()=>{let r=g(this.state.values,t);T(r,s)||(s=f(r),e(r))})}setField(t,e){this.setFieldWithMeta(t,e,{origin:"setField"})}setFieldWithMeta(t,e,s={origin:"setField"}){let{visibilitiesChanged:r}=this.lifecycleMg.updateField(t,e,s);(!this.config.resolver||r)&&this.notify()}blurField(t){this.internalSaveSnapshot(),this.state.touched[t]||this.internalUpdateState({touched:{...this.state.touched,[t]:!0}}),this.validatorMg.trigger([t])}markFieldsTouched(t){if(t.length===0)return;let e={...this.state.touched};t.forEach(s=>e[s]=!0),this.internalUpdateState({touched:e})}setValues(t){this.lifecycleMg.updateAll(t)}setError(t,e){this.errorMg.setError(t,e)}setErrors(t){this.errorMg.setErrors(t)}setServerErrors(t){this.errorMg.setServerErrors(t)}reset(){this.lifecycleMg.reset()}async submit(t){return this.lifecycleMg.submit(t)}registerMask(t,e){this.config.masks={...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)}getStepStatus(t){return this.scopeMg.getStepStatus(t)}getStepErrors(t){return this.scopeMg.getStepErrors(t)}internalUpdateState(t){let e={...this.state,...t};t.values&&(e.values=this.computedMg.apply(t.values)),t.errors&&(e.isValid=Object.keys(e.errors).length===0),this.state=e,t.values&&this.persistMg.queueSave(),this.notify(),m.dispatch(this.storeId,this.state)}internalSaveSnapshot(){this.historyMg.saveSnapshot(this.state.values)}applyPersistedValues(t){let e=f({...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.validatorMg.cancelAll(),this.persistMg.destroy(),this.pluginMg.destroy(),delete m.stores[this.storeId]}notify(){this.listeners.forEach(t=>t())}};function Ut(o={}){let t=new L(o);return{getConfig:()=>t.getConfig(),getState:()=>t.getState(),subscribe:t.subscribe.bind(t),setField:t.setField.bind(t),blurField:t.blurField.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),reset:t.reset.bind(t),submit:t.submit.bind(t),registerMask:t.registerMask.bind(t),getDirtyValues:t.getDirtyValues.bind(t),restorePersisted:t.restorePersisted.bind(t),forceSave:t.forceSave.bind(t),clearPersisted:t.clearPersisted.bind(t),cleanup:t.cleanup.bind(t)}}var Pt=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}}},q=null;function Vt(o){q&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),q());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]=Pt(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]:Pt(c)}}))}}),s=setInterval(()=>{t?.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"PING"}))},3e4)},t.onmessage=l=>{try{let{type:a,payload:d}=JSON.parse(l.data);if(a==="ACTION"){let{storeId:c,action:u}=d,h=m.stores[c];h&&typeof h[u]=="function"&&h[u]()}}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(),q=null};return q=n,n}export{m as a,f as b,S as c,T as d,g as e,y as f,Ct as g,St as h,wt as i,E as j,xt as k,p as l,b as m,Y as n,V as o,J 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,Ft as G,Dt as H,It as I,At as J,gt as K,pt as L,Rt as M,ft as N,ht as O,mt as P,yt as Q,Ht as R,bt as S,Vt as T,vt as U,Ut as V};
|
|
133
|
+
//# sourceMappingURL=chunk-2HAQ3QEQ.js.map
|