@lehnihon/bit-form 2.2.4 → 2.2.5

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 (121) 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 +3 -2
  4. package/dist/angular/index.d.ts +3 -2
  5. package/dist/angular/index.js +1 -1
  6. package/dist/angular/index.js.map +1 -1
  7. package/dist/{bus-BQI1FIOs.d.ts → bus-B4zZmB9C.d.ts} +4 -1
  8. package/dist/{bus-a_GA51Qw.d.cts → bus-BeAeZwWu.d.cts} +4 -1
  9. package/dist/chunk-2FDEJYA5.js +2 -0
  10. package/dist/chunk-2FDEJYA5.js.map +1 -0
  11. package/dist/chunk-3CARTBEN.cjs +2 -0
  12. package/dist/chunk-3CARTBEN.cjs.map +1 -0
  13. package/dist/chunk-3NUJVIAM.js +2 -0
  14. package/dist/chunk-3NUJVIAM.js.map +1 -0
  15. package/dist/chunk-64KSP4TP.js +2 -0
  16. package/dist/chunk-64KSP4TP.js.map +1 -0
  17. package/dist/{chunk-YEXRRTI3.cjs → chunk-77PK7U73.cjs} +2 -2
  18. package/dist/{chunk-YEXRRTI3.cjs.map → chunk-77PK7U73.cjs.map} +1 -1
  19. package/dist/chunk-CTURHI75.cjs +2 -0
  20. package/dist/{chunk-CFFLDMLG.cjs.map → chunk-CTURHI75.cjs.map} +1 -1
  21. package/dist/{chunk-MQX4YS6D.cjs → chunk-DD6XWUMR.cjs} +2 -2
  22. package/dist/{chunk-MQX4YS6D.cjs.map → chunk-DD6XWUMR.cjs.map} +1 -1
  23. package/dist/{chunk-BMHK77NL.js → chunk-FGJB4DHQ.js} +2 -2
  24. package/dist/{chunk-4XLU5ZCX.js → chunk-GDRNKTHO.js} +2 -2
  25. package/dist/chunk-GUU6EXFN.js +2 -0
  26. package/dist/chunk-GUU6EXFN.js.map +1 -0
  27. package/dist/chunk-JIWR4KSZ.cjs +2 -0
  28. package/dist/chunk-JIWR4KSZ.cjs.map +1 -0
  29. package/dist/{chunk-MBTLLIBM.js → chunk-M2XR4C7T.js} +2 -2
  30. package/dist/chunk-OZKLQRO6.cjs +2 -0
  31. package/dist/chunk-OZKLQRO6.cjs.map +1 -0
  32. package/dist/chunk-PFPGASVZ.cjs +2 -0
  33. package/dist/chunk-PFPGASVZ.cjs.map +1 -0
  34. package/dist/chunk-QWH2NBVB.js +2 -0
  35. package/dist/chunk-QWH2NBVB.js.map +1 -0
  36. package/dist/chunk-UMKOKAPD.js +2 -0
  37. package/dist/chunk-UMKOKAPD.js.map +1 -0
  38. package/dist/{chunk-KYM7JG2G.cjs → chunk-UT63HKR6.cjs} +2 -2
  39. package/dist/{chunk-KYM7JG2G.cjs.map → chunk-UT63HKR6.cjs.map} +1 -1
  40. package/dist/chunk-VQ7MK5VB.cjs +2 -0
  41. package/dist/chunk-VQ7MK5VB.cjs.map +1 -0
  42. package/dist/devtools/bridge.cjs +1 -1
  43. package/dist/devtools/bridge.cjs.map +1 -1
  44. package/dist/devtools/bridge.js +1 -1
  45. package/dist/devtools/bridge.js.map +1 -1
  46. package/dist/devtools/index.cjs +2 -2
  47. package/dist/devtools/index.cjs.map +1 -1
  48. package/dist/devtools/index.js +1 -1
  49. package/dist/devtools/index.js.map +1 -1
  50. package/dist/index.cjs +1 -1
  51. package/dist/index.cjs.map +1 -1
  52. package/dist/index.d.cts +23 -49
  53. package/dist/index.d.ts +23 -49
  54. package/dist/index.js +1 -1
  55. package/dist/mask.cjs +1 -1
  56. package/dist/mask.cjs.map +1 -1
  57. package/dist/mask.js +1 -1
  58. package/dist/mask.js.map +1 -1
  59. package/dist/{public-types-D14VY_4o.d.cts → public-types-BQXaxmAE.d.cts} +7 -2
  60. package/dist/{public-types-D3WIiMGu.d.ts → public-types-CVgFf_qY.d.ts} +7 -2
  61. package/dist/react/index.cjs +1 -1
  62. package/dist/react/index.cjs.map +1 -1
  63. package/dist/react/index.d.cts +5 -5
  64. package/dist/react/index.d.ts +5 -5
  65. package/dist/react/index.js +1 -1
  66. package/dist/react/index.js.map +1 -1
  67. package/dist/react-native/index.cjs +1 -1
  68. package/dist/react-native/index.d.cts +4 -4
  69. package/dist/react-native/index.d.ts +4 -4
  70. package/dist/react-native/index.js +1 -1
  71. package/dist/resolvers/index.cjs +1 -1
  72. package/dist/resolvers/index.d.cts +1 -1
  73. package/dist/resolvers/index.d.ts +1 -1
  74. package/dist/resolvers/index.js +1 -1
  75. package/dist/resolvers/joi.cjs +1 -1
  76. package/dist/resolvers/joi.d.cts +1 -1
  77. package/dist/resolvers/joi.d.ts +1 -1
  78. package/dist/resolvers/joi.js +1 -1
  79. package/dist/resolvers/yup.cjs +1 -1
  80. package/dist/resolvers/yup.d.cts +1 -1
  81. package/dist/resolvers/yup.d.ts +1 -1
  82. package/dist/resolvers/yup.js +1 -1
  83. package/dist/resolvers/zod.cjs +1 -1
  84. package/dist/resolvers/zod.d.cts +1 -1
  85. package/dist/resolvers/zod.d.ts +1 -1
  86. package/dist/resolvers/zod.js +1 -1
  87. package/dist/{use-bit-persist-Dt4zIl2u.d.cts → use-bit-persist-CIVN-oIi.d.cts} +3 -2
  88. package/dist/{use-bit-persist-CNtQ3Gaq.d.ts → use-bit-persist-iPWLbD8l.d.ts} +3 -2
  89. package/dist/vue/index.cjs +1 -1
  90. package/dist/vue/index.cjs.map +1 -1
  91. package/dist/vue/index.d.cts +3 -2
  92. package/dist/vue/index.d.ts +3 -2
  93. package/dist/vue/index.js +1 -1
  94. package/dist/vue/index.js.map +1 -1
  95. package/package.json +20 -1
  96. package/dist/chunk-66DIO2SH.js +0 -2
  97. package/dist/chunk-66DIO2SH.js.map +0 -1
  98. package/dist/chunk-7LMNIQTT.js +0 -2
  99. package/dist/chunk-7LMNIQTT.js.map +0 -1
  100. package/dist/chunk-AE4G32HS.js +0 -2
  101. package/dist/chunk-AE4G32HS.js.map +0 -1
  102. package/dist/chunk-CFFLDMLG.cjs +0 -2
  103. package/dist/chunk-EI5L5L3R.cjs +0 -2
  104. package/dist/chunk-EI5L5L3R.cjs.map +0 -1
  105. package/dist/chunk-IV32WXCF.cjs +0 -2
  106. package/dist/chunk-IV32WXCF.cjs.map +0 -1
  107. package/dist/chunk-K5NZDYAT.js +0 -2
  108. package/dist/chunk-K5NZDYAT.js.map +0 -1
  109. package/dist/chunk-LOYB7TTM.cjs +0 -2
  110. package/dist/chunk-LOYB7TTM.cjs.map +0 -1
  111. package/dist/chunk-O5UPA33R.js +0 -2
  112. package/dist/chunk-O5UPA33R.js.map +0 -1
  113. package/dist/chunk-RFFMBY7M.cjs +0 -2
  114. package/dist/chunk-RFFMBY7M.cjs.map +0 -1
  115. package/dist/chunk-YGAD4ZZW.js +0 -2
  116. package/dist/chunk-YGAD4ZZW.js.map +0 -1
  117. package/dist/chunk-ZO3GXKF3.cjs +0 -2
  118. package/dist/chunk-ZO3GXKF3.cjs.map +0 -1
  119. /package/dist/{chunk-BMHK77NL.js.map → chunk-FGJB4DHQ.js.map} +0 -0
  120. /package/dist/{chunk-4XLU5ZCX.js.map → chunk-GDRNKTHO.js.map} +0 -0
  121. /package/dist/{chunk-MBTLLIBM.js.map → chunk-M2XR4C7T.js.map} +0 -0
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9;var _chunkEI5L5L3Rcjs = require('./chunk-EI5L5L3R.cjs');function h(a){if(a===null||typeof a!="object")return a;if(a instanceof Date)return new Date(a.getTime());if(a instanceof RegExp)return new RegExp(a.source,a.flags);if(Array.isArray(a))return a.map(t=>h(t));let e={};for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&(e[t]=h(a[t]));return e}function B(a,e){if(e===void 0)return h(a);if(e===null||typeof e!="object"||e instanceof Date||e instanceof RegExp||Array.isArray(e))return h(e);let t=a&&typeof a=="object"&&!Array.isArray(a)?h(a):{};for(let i of Object.keys(e)){let r=e[i],s=t[i];if(r!==null&&typeof r=="object"&&!Array.isArray(r)&&!(r instanceof Date)&&!(r instanceof RegExp)){t[i]=B(s,r);continue}t[i]=h(r)}return t}function S(a,e){return a===e?!0:a===null||typeof a!="object"||e===null||typeof e!="object"?!1:f(a,e)}function f(a,e){if(a===e)return!0;if(a===null||typeof a!="object"||e===null||typeof e!="object")return!1;if(a instanceof Date&&e instanceof Date)return a.getTime()===e.getTime();if(a instanceof RegExp&&e instanceof RegExp)return a.toString()===e.toString();let t=Object.keys(a),i=Object.keys(e);if(t.length!==i.length)return!1;for(let r of t)if(!Object.prototype.hasOwnProperty.call(e,r)||!f(a[r],e[r]))return!1;return!0}function U(a,e,t="",i=new Set){if(S(a,e))return i;if(a===null||typeof a!="object"||e===null||typeof e!="object")return t&&i.add(t),i;if(Array.isArray(a)||Array.isArray(e))return!S(a,e)&&t&&i.add(t),i;let r=new Set([...Object.keys(a||{}),...Object.keys(e||{})]);for(let s of r){let n=t?`${t}.${s}`:s;U(_optionalChain([a, 'optionalAccess', _2 => _2[s]]),_optionalChain([e, 'optionalAccess', _3 => _3[s]]),n,i)}return i}var te=1e3,m=new Map;function W(a){let e=m.get(a);if(e)return m.delete(a),m.set(a,e),e;let t=a.split(".");if(m.size>=te){let i=m.keys().next().value;i&&m.delete(i)}return m.set(a,t),t}function g(a,e){if(!e)return a;let t=W(e),i=a;for(let r of t){if(i==null)return;i=i[r]}return i}function p(a,e,t){if(!e)return t;let i=W(e),r=Array.isArray(a)?[...a]:{...a},s=r;for(let n=0;n<i.length-1;n++){let o=i[n],l=i[n+1],d=Number(l),u=Number.isInteger(d)&&String(d)===l,c=s[o];c==null?s[o]=u?[]:{}:s[o]=Array.isArray(c)?[...c]:{...c},s=s[o]}return s[i[i.length-1]]=t,r}function ie(a,e){let t={},i=`${e}.`;for(let r in a)r!==e&&!r.startsWith(i)&&(t[r]=a[r]);return t}var j=(a,e,t)=>{let i={},r=`${e}.`;return Object.keys(a).forEach(s=>{if(!s.startsWith(r)){i[s]=a[s];return}let o=s.substring(r.length).split("."),l=parseInt(o[0],10),d=o.slice(1).join(".");if(l!==t)if(l>t){let u=l-1,c=d?`${r}${u}.${d}`:`${r}${u}`;i[c]=a[s]}else i[s]=a[s]}),i},$=(a,e,t,i)=>{let r={},s=`${e}.`;return Object.keys(a).forEach(n=>{if(!n.startsWith(s)){r[n]=a[n];return}let l=n.substring(s.length).split("."),d=parseInt(l[0],10),u=l.slice(1).join(".");if(d===t){let c=u?`${s}${i}.${u}`:`${s}${i}`;r[c]=a[n]}else if(d===i){let c=u?`${s}${t}.${u}`:`${s}${t}`;r[c]=a[n]}else r[n]=a[n]}),r},_=(a,e,t,i)=>{let r={},s=`${e}.`;return Object.keys(a).forEach(n=>{if(!n.startsWith(s)){r[n]=a[n];return}let l=n.substring(s.length).split("."),d=parseInt(l[0],10),u=l.slice(1).join("."),c=d;d===t?c=i:t<i&&d>t&&d<=i?c=d-1:t>i&&d>=i&&d<t&&(c=d+1);let y=u?`${s}${c}.${u}`:`${s}${c}`;r[y]=a[n]}),r};function G(a){if(typeof a!="object"||a===null||Array.isArray(a))return!1;let e=_nullishCoalesce(a.errors, () => (a));return typeof e!="object"||e===null||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="string"||Array.isArray(t)&&t.every(i=>typeof i=="string"))}function re(a){return G(a)?_nullishCoalesce(a.errors, () => (a)):{}}var z=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;z.__BIT_FORM__||(z.__BIT_FORM__={stores:{},listeners:new Set,dispatch(a,e){this.listeners.forEach(t=>t(a,e))},subscribe(a){return this.listeners.add(a),()=>{this.listeners.delete(a)}}});var T=z.__BIT_FORM__;function se(){return`bit-form-${Math.random().toString(36).slice(2,9)}`}function J(a={}){let e=_nullishCoalesce(a.initialValues, () => ({})),t=a.validation,i=a.history,r=a.name?`bit-form:${a.name}:draft`:"bit-form:draft",s={enabled:_nullishCoalesce(_optionalChain([a, 'access', _4 => _4.persist, 'optionalAccess', _5 => _5.enabled]), () => (!1)),key:_nullishCoalesce(_optionalChain([a, 'access', _6 => _6.persist, 'optionalAccess', _7 => _7.key]), () => (r)),storage:_optionalChain([a, 'access', _8 => _8.persist, 'optionalAccess', _9 => _9.storage]),autoSave:_nullishCoalesce(_optionalChain([a, 'access', _10 => _10.persist, 'optionalAccess', _11 => _11.autoSave]), () => (!0)),debounceMs:_nullishCoalesce(_optionalChain([a, 'access', _12 => _12.persist, 'optionalAccess', _13 => _13.debounceMs]), () => (300)),mode:_nullishCoalesce(_optionalChain([a, 'access', _14 => _14.persist, 'optionalAccess', _15 => _15.mode]), () => ("values")),serialize:_nullishCoalesce(_optionalChain([a, 'access', _16 => _16.persist, 'optionalAccess', _17 => _17.serialize]), () => (JSON.stringify)),deserialize:_nullishCoalesce(_optionalChain([a, 'access', _18 => _18.persist, 'optionalAccess', _19 => _19.deserialize]), () => ((n=>JSON.parse(n)))),onError:_optionalChain([a, 'access', _20 => _20.persist, 'optionalAccess', _21 => _21.onError])};return{name:a.name,initialValues:h(e),resolver:_optionalChain([t, 'optionalAccess', _22 => _22.resolver]),validationDelay:_nullishCoalesce(_optionalChain([t, 'optionalAccess', _23 => _23.delay]), () => (300)),enableHistory:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _24 => _24.enabled]), () => (!1)),historyLimit:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _25 => _25.limit]), () => (15)),masks:_chunkEI5L5L3Rcjs.O,fields:a.fields,devTools:a.devTools,persist:s,idFactory:_nullishCoalesce(a.idFactory, () => (se)),plugins:_nullishCoalesce(a.plugins, () => ([]))}}var E= (_class =class{constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this); }__init() {this.fieldConfigs=new Map}__init2() {this.dependencies=new Map}__init3() {this.hiddenFields=new Set}getFieldConfig(e){return this.fieldConfigs.get(e)}forEachFieldConfig(e){this.fieldConfigs.forEach((t,i)=>e(t,i))}hasFieldConfig(e){return this.fieldConfigs.has(e)}getHiddenFields(){return Array.from(this.hiddenFields)}register(e,t,i){this.fieldConfigs.set(e,t);let r=_optionalChain([t, 'access', _26 => _26.conditional, 'optionalAccess', _27 => _27.dependsOn]);r&&r.forEach(s=>{this.dependencies.has(s)||this.dependencies.set(s,new Set),this.dependencies.get(s).add(e)}),this.evaluateFieldCondition(e,i)}isHidden(e){return this.hiddenFields.has(e)}isRequired(e,t){let i=this.fieldConfigs.get(e);return!i||this.isHidden(e)?!1:!!_optionalChain([i, 'access', _28 => _28.conditional, 'optionalAccess', _29 => _29.requiredIf, 'optionalCall', _30 => _30(t)])}getRequiredErrors(e){let t={};return this.fieldConfigs.forEach((i,r)=>{if(this.isRequired(r,e)){let s=g(e,r);this.isEmpty(s)&&(t[r]=_nullishCoalesce(_optionalChain([i, 'access', _31 => _31.conditional, 'optionalAccess', _32 => _32.requiredMessage]), () => ("required field")))}}),t}evaluateAll(e){this.fieldConfigs.forEach((t,i)=>{this.evaluateFieldCondition(i,e)})}updateDependencies(e,t){let i=[],r=[e],s=new Set;for(;r.length>0;){let n=r.shift();if(s.has(n))continue;s.add(n);let o=this.dependencies.get(n);o&&o.forEach(l=>{let d=this.isHidden(l);this.evaluateFieldCondition(l,t);let u=this.isHidden(l);d!==u&&i.push(l),r.push(l)})}return i}unregister(e){this.fieldConfigs.delete(e),this.hiddenFields.delete(e),this.dependencies.delete(e),this.dependencies.forEach(t=>{t.delete(e)})}unregisterPrefix(e){let t=[];this.fieldConfigs.forEach((i,r)=>{r.startsWith(e)&&t.push(r)}),t.forEach(i=>this.unregister(i))}evaluateFieldCondition(e,t){let r=_optionalChain([this, 'access', _33 => _33.fieldConfigs, 'access', _34 => _34.get, 'call', _35 => _35(e), 'optionalAccess', _36 => _36.conditional, 'optionalAccess', _37 => _37.showIf]);r&&(r(t)?this.hiddenFields.delete(e):this.hiddenFields.add(e))}isEmpty(e){return e==null||typeof e=="string"&&e.trim()===""||Array.isArray(e)&&e.length===0}}, _class);var P= (_class2 =class a{constructor(e){this.getComputedEntries=e}static __initStatic() {this.MIN_PASSES=4}apply(e){let t=this.getComputedEntries();if(t.length===0)return e;let i=e,r=Math.max(a.MIN_PASSES,t.length*2);for(let s=0;s<r;s++){let n=!1;for(let[o,l]of t){let d=l(i),u=g(i,o);f(u,d)||(i=p(i,o,d),n=!0)}if(!n)break;if(s===r-1)throw new Error("BitStore: computed fields did not stabilize. Check for cyclic computed definitions.")}return i}}, _class2.__initStatic(), _class2);var V= (_class3 =class{constructor() { _class3.prototype.__init4.call(this); }__init4() {this.dirtyPaths=new Set}updateForPath(e,t,i){for(let n of this.dirtyPaths)n.startsWith(e+".")&&this.dirtyPaths.delete(n);let r=g(t,e),s=g(i,e);return S(r,s)?this.dirtyPaths.delete(e):this.dirtyPaths.add(e),this.dirtyPaths.size>0}rebuild(e,t){return this.dirtyPaths=U(e,t),this.dirtyPaths.size>0}clear(){this.dirtyPaths.clear()}get isDirty(){return this.dirtyPaths.size>0}getDirtyPaths(){return this.dirtyPaths}isPathDirty(e){if(this.dirtyPaths.has(e))return!0;for(let t of this.dirtyPaths)if(t.startsWith(`${e}.`)||e.startsWith(`${t}.`))return!0;return!1}buildDirtyValues(e){if(this.dirtyPaths.size===0)return{};let t={},i=new Set;for(let r of this.dirtyPaths){let s=r.match(/^(.+)\.\d+/);if(s){let n=s[1];if(i.has(n))continue;i.add(n);let o=g(e,n);t=p(t,n,o)}else{let n=g(e,r);t=p(t,r,n)}}return t}}, _class3);var F= (_class4 =class{constructor(e){;_class4.prototype.__init5.call(this);_class4.prototype.__init6.call(this);_class4.prototype.__init7.call(this);_class4.prototype.__init8.call(this);this.getState=e}__init5() {this.listeners=new Set}__init6() {this.selectorListeners=new Set}__init7() {this.pathScopedSubscriptions=new Map}__init8() {this.pathSelectorIndex=new Map}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}subscribeSelector(e,t,i,r){let s=e(this.getState()),n={notify:d=>{let u=e(d);r(s,u)||(s=u,t(u))}},o=_optionalChain([i, 'optionalAccess', _38 => _38.autoTrackPaths])===!1?[]:this.collectTrackedSelectorPaths(e),l=this.normalizeSubscriptionPaths([..._nullishCoalesce(_optionalChain([i, 'optionalAccess', _39 => _39.paths]), () => ([])),...o]);return l.length>0?(this.pathScopedSubscriptions.set(n,l),l.forEach(d=>{this.expandPathForIndexing(d).forEach(u=>{let c=_nullishCoalesce(this.pathSelectorIndex.get(u), () => (new Set));c.add(n),this.pathSelectorIndex.set(u,c)})})):this.selectorListeners.add(n),_optionalChain([i, 'optionalAccess', _40 => _40.emitImmediately])&&t(s),()=>{this.selectorListeners.delete(n);let d=this.pathScopedSubscriptions.get(n);d&&(d.forEach(u=>{this.expandPathForIndexing(u).forEach(c=>{let y=this.pathSelectorIndex.get(c);y&&(y.delete(n),y.size===0&&this.pathSelectorIndex.delete(c))})}),this.pathScopedSubscriptions.delete(n))}}notify(e,t){if(this.listeners.forEach(r=>r()),this.selectorListeners.forEach(r=>{r.notify(e)}),this.pathScopedSubscriptions.size===0)return;if(!t||t.length===0||t.includes("*")){this.pathScopedSubscriptions.forEach((r,s)=>{s.notify(e)});return}this.collectSubscribersForChangedPaths(t).forEach(r=>{r.notify(e)})}destroy(){this.listeners.clear(),this.selectorListeners.clear(),this.pathScopedSubscriptions.clear(),this.pathSelectorIndex.clear()}normalizeSubscriptionPaths(e){return!e||e.length===0?[]:Array.from(new Set(e.map(t=>t.trim()).filter(t=>t.length>0)))}collectTrackedSelectorPaths(e){let t=new Set,i=(s,n)=>!s||typeof s!="object"?s:new Proxy(s,{get:(o,l)=>{if(typeof l!="string")return Reflect.get(o,l);let d=n?`${n}.${l}`:l;t.add(d);let u=Reflect.get(o,l);return i(u,d)}}),r=new Proxy(this.getState(),{get:(s,n)=>{if(typeof n!="string")return Reflect.get(s,n);let o=Reflect.get(s,n);return n==="values"?i(o,""):o}});try{return e(r),Array.from(t)}catch (e2){return[]}}collectSubscribersForChangedPaths(e){let t=new Set,i=s=>{let n=this.pathSelectorIndex.get(s);n&&n.forEach(o=>t.add(o))};return this.normalizeSubscriptionPaths(e).forEach(s=>{i(s);let n=s.split(".");for(;n.length>1;)n.pop(),i(n.join("."))}),t}expandPathForIndexing(e){let t=e.split("."),i=[];for(let r=1;r<=t.length;r++)i.push(t.slice(0,r).join("."));return i}}, _class4);function ae(a){let e={};return Object.entries(a).forEach(([t,i])=>{i!==void 0&&(e[t]=i)}),e}function X(a){let{currentState:e,partialState:t,changedPaths:i,applyComputedValues:r}=a,s={...e,...t},n=!!t.values;t.values&&(s.values=r(t.values)),t.errors&&(s.errors=ae(t.errors)),s.isValid=Object.keys(s.errors).length===0;let o=i&&i.length>0?i:t.values?["*"]:void 0;return{nextState:s,changedPaths:o,valuesChanged:n}}function ne(a){return typeof a=="boolean"?{enabled:a,mode:"local"}:{enabled:!!a,mode:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _41 => _41.mode]), () => ("local")),url:_optionalChain([a, 'optionalAccess', _42 => _42.url])}}function Q(a){let e=ne(a);return e.enabled?{name:"bit-devtools",setup:()=>{let t=null,i=!1;return(async()=>{try{if(e.mode==="remote"){let{setupRemoteBridge:r}=await Promise.resolve().then(() => _interopRequireWildcard(require("./devtools/bridge.cjs")));t=r(e.url||"ws://localhost:3000")}else{let{initDevTools:r}=await Promise.resolve().then(() => _interopRequireWildcard(require("./devtools/index.cjs"))),s=r();t=s&&typeof s.destroy=="function"?s.destroy:null}i&&t&&(t(),t=null)}catch (e3){}})(),()=>{i=!0,t&&(t(),t=null)}}}:null}function oe(){if(typeof globalThis>"u")return;let a=globalThis.localStorage;if(a)return{getItem:e=>a.getItem(e),setItem:(e,t)=>a.setItem(e,t),removeItem:e=>a.removeItem(e)}}var C=class{constructor(e,t,i,r){this.config=e;this.getValues=t;this.getDirtyValues=i;this.applyRestoredValues=r}getStorage(){return this.config.storage||oe()}canPersist(){return!!(this.config.enabled&&this.config.key&&this.getStorage())}handleError(e){_optionalChain([this, 'access', _43 => _43.config, 'access', _44 => _44.onError, 'optionalCall', _45 => _45(e)])}async saveNow(){if(!this.canPersist())return;let e=this.getStorage();if(e)try{let t=this.config.mode==="dirtyValues"?this.getDirtyValues():this.getValues(),i=this.config.serialize(h(t));await e.setItem(this.config.key,i)}catch(t){this.handleError(t)}}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 e=this.getStorage();if(!e)return!1;try{let t=await e.getItem(this.config.key);if(!t)return!1;let i=this.config.deserialize(t);return!i||typeof i!="object"?!1:(this.applyRestoredValues(i),!0)}catch(t){return this.handleError(t),!1}}async clear(){if(!this.canPersist())return;let e=this.getStorage();if(e)try{await e.removeItem(this.config.key)}catch(t){this.handleError(t)}}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}};var w= (_class5 =class{constructor(e,t){;_class5.prototype.__init9.call(this);_class5.prototype.__init10.call(this);this.plugins=e;this.contextFactory=t}__init9() {this.teardownFns=[]}__init10() {this.notifyingError=!1}setupAll(){this.plugins.forEach(e=>{if(e.setup)try{let t=e.setup(this.contextFactory());typeof t=="function"&&this.teardownFns.push(t)}catch(t){this.reportError("setup",t,void 0,e.name)}})}async beforeValidate(e){await this.emitHook("beforeValidate",e)}async afterValidate(e){await this.emitHook("afterValidate",e)}async beforeSubmit(e){await this.emitHook("beforeSubmit",e)}async afterSubmit(e){await this.emitHook("afterSubmit",e)}onFieldChange(e){this.plugins.forEach(t=>{let i=_optionalChain([t, 'access', _46 => _46.hooks, 'optionalAccess', _47 => _47.onFieldChange]);if(i)try{let r=i(e,this.contextFactory());Promise.resolve(r).catch(s=>{this.reportError("onFieldChange",s,e,t.name)})}catch(r){this.reportError("onFieldChange",r,e,t.name)}})}async reportError(e,t,i,r){if(this.notifyingError)return;this.notifyingError=!0;let s=this.contextFactory(),n={source:e,pluginName:r,error:t,event:i,values:s.getState().values,state:s.getState()};for(let o of this.plugins){let l=_optionalChain([o, 'access', _48 => _48.hooks, 'optionalAccess', _49 => _49.onError]);if(l)try{await l(n,s)}catch (e4){}}this.notifyingError=!1}destroy(){for(let e=this.teardownFns.length-1;e>=0;e-=1){let t=this.teardownFns[e];try{t()}catch(i){this.reportError("teardown",i)}}this.teardownFns=[]}async emitHook(e,t){let i=this.contextFactory();for(let r of this.plugins){let s=_optionalChain([r, 'access', _50 => _50.hooks, 'optionalAccess', _51 => _51[e]]);if(s)try{await s(t,i)}catch(n){await this.reportError(e,n,t,r.name)}}}}, _class5);var x=class{constructor(e,t,i,r){this.storeId=e;this.storeInstance=t;this.persistManager=i;this.pluginManager=r}initialize(){this.pluginManager.setupAll(),T.stores[this.storeId]=this.storeInstance}onStateUpdated(e,t){t&&this.persistManager.queueSave(),T.dispatch(this.storeId,e)}restorePersisted(){return this.persistManager.restore()}savePersistedNow(){return this.persistManager.saveNow()}clearPersisted(){return this.persistManager.clear()}beforeValidate(e){return this.pluginManager.beforeValidate(e)}afterValidate(e){return this.pluginManager.afterValidate(e)}beforeSubmit(e){return this.pluginManager.beforeSubmit(e)}afterSubmit(e){return this.pluginManager.afterSubmit(e)}onFieldChange(e){this.pluginManager.onFieldChange(e)}reportOperationalError(e){return this.pluginManager.reportError(e.source,e.error,e.payload)}destroy(){this.persistManager.destroy(),this.pluginManager.destroy(),delete T.stores[this.storeId]}};var v=class{constructor(e){this.steps=e}async run(e){for(let t of this.steps){if(e.halted)break;await t.run(e)}}},M=class{constructor(e){this.steps=e}run(e){for(let t of this.steps){if(e.halted)break;t.run(e)}}};var D= (_class6 =class{constructor(e){;_class6.prototype.__init11.call(this);_class6.prototype.__init12.call(this);_class6.prototype.__init13.call(this);_class6.prototype.__init14.call(this);_class6.prototype.__init15.call(this);this.store=e}__init11() {this.currentValidationId=0}__init12() {this.asyncEpoch=0}__init13() {this.asyncTimers={}}__init14() {this.asyncRequests={}}__init15() {this.asyncErrors={}}updateFieldValidating(e,t){this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[e]:t}})}cancelFieldAsync(e){this.asyncTimers[e]&&(clearTimeout(this.asyncTimers[e]),delete this.asyncTimers[e]),this.asyncRequests[e]=(this.asyncRequests[e]||0)+1}cleanupField(e){this.cancelFieldAsync(e),delete this.asyncTimers[e],delete this.asyncRequests[e],delete this.asyncErrors[e],this.updateFieldValidating(e,!1)}cleanupPrefix(e){Object.keys(this.asyncTimers).forEach(t=>{(t===e||t.startsWith(`${e}.`))&&this.cleanupField(t)}),Object.keys(this.asyncRequests).forEach(t=>{(t===e||t.startsWith(`${e}.`))&&delete this.asyncRequests[t]}),Object.keys(this.asyncErrors).forEach(t=>{(t===e||t.startsWith(`${e}.`))&&delete this.asyncErrors[t]})}beginExternalValidation(e){this.cancelFieldAsync(e),this.updateFieldValidating(e,!0)}endExternalValidation(e){this.updateFieldValidating(e,!1)}async setExternalError(e,t){if(t){this.asyncErrors[e]=t,this.store.setError(e,t);return}if(delete this.asyncErrors[e],this.store.validate){await this.store.validate({scopeFields:[e]});return}let i={...this.store.getState().errors};delete i[e],this.store.internalUpdateState({errors:i,isValid:Object.keys(i).length===0})}handleAsync(e,t){let i=this.store.getFieldConfig(e),r=_optionalChain([i, 'optionalAccess', _52 => _52.validation, 'optionalAccess', _53 => _53.asyncValidate]);if(!r){this.updateFieldValidating(e,!1);return}this.asyncTimers[e]&&clearTimeout(this.asyncTimers[e]);let s=_nullishCoalesce(_optionalChain([i, 'access', _54 => _54.validation, 'optionalAccess', _55 => _55.asyncValidateDelay]), () => (500));this.updateFieldValidating(e,!0),this.asyncTimers[e]=setTimeout(async()=>{delete this.asyncTimers[e];let n=this.asyncEpoch,o=(this.asyncRequests[e]||0)+1;this.asyncRequests[e]=o;try{let l=await r(t,this.store.getState().values);if(this.asyncRequests[e]!==o||n!==this.asyncEpoch)return;if(l)this.asyncErrors[e]=l,this.store.setError(e,l);else if(delete this.asyncErrors[e],this.store.validate)await this.store.validate({scopeFields:[e]});else{let d={...this.store.getState().errors};delete d[e],this.store.internalUpdateState({errors:d,isValid:Object.keys(d).length===0})}}finally{this.asyncRequests[e]===o&&n===this.asyncEpoch&&this.updateFieldValidating(e,!1)}},s)}hasValidationsInProgress(e){let t=this.store.getState();return e&&e.length>0?e.some(i=>!!t.isValidating[i]):Object.values(t.isValidating).some(Boolean)}trigger(e){this.validationTimeout&&clearTimeout(this.validationTimeout);let t=_nullishCoalesce(this.store.config.validationDelay, () => (300));t>0?this.validationTimeout=setTimeout(()=>{this.validate({scopeFields:e})},t):this.validate({scopeFields:e})}async validate(e){let t={options:e,validationId:++this.currentValidationId,currentState:this.store.getState(),targetFields:_optionalChain([e, 'optionalAccess', _56 => _56.scopeFields]),allErrors:{},isValid:!0,result:!0,aborted:!1};return await new v([{name:"validate:resolve-target-fields",run:r=>{if(_optionalChain([r, 'access', _57 => _57.options, 'optionalAccess', _58 => _58.scope])){let s=this.store.getScopeFields(r.options.scope);s.length>0&&(r.targetFields=s)}}},{name:"validate:before-hooks",run:async r=>{await this.store.emitBeforeValidate({values:r.currentState.values,state:r.currentState,scope:_optionalChain([r, 'access', _59 => _59.options, 'optionalAccess', _60 => _60.scope]),scopeFields:r.targetFields})}},{name:"validate:resolver",run:async r=>{r.allErrors=this.store.config.resolver?await this.store.config.resolver(r.currentState.values,{scopeFields:r.targetFields}):{}}},{name:"validate:required-and-hidden",run:r=>{let s=this.store.getRequiredErrors(r.currentState.values);r.allErrors={...r.allErrors,...s},this.store.getHiddenFields().forEach(n=>{delete r.allErrors[n],delete this.asyncErrors[n]})}},{name:"validate:abort-check",run:async r=>{r.validationId!==this.currentValidationId&&(r.aborted=!0,r.result=r.currentState.isValid,await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:_optionalChain([r, 'access', _61 => _61.options, 'optionalAccess', _62 => _62.scope]),scopeFields:r.targetFields,errors:this.store.getState().errors,result:r.currentState.isValid,aborted:!0}),r.halted=!0)}},{name:"validate:commit-scoped",run:async r=>{if(!r.targetFields)return;let s={...r.currentState.errors};r.targetFields.forEach(n=>{r.allErrors[n]?s[n]=r.allErrors[n]:this.asyncErrors[n]?s[n]=this.asyncErrors[n]:delete s[n]}),r.isValid=Object.keys(s).length===0,r.result=r.targetFields.every(n=>!r.allErrors[n]&&!this.asyncErrors[n]),this.store.internalUpdateState({errors:s,isValid:r.isValid}),await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:_optionalChain([r, 'access', _63 => _63.options, 'optionalAccess', _64 => _64.scope]),scopeFields:r.targetFields,errors:s,result:r.result}),r.halted=!0}},{name:"validate:commit-global",run:async r=>{r.allErrors={...this.asyncErrors,...r.allErrors},r.isValid=Object.keys(r.allErrors).length===0,r.result=r.isValid,this.store.internalUpdateState({errors:r.allErrors,isValid:r.isValid}),await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:_optionalChain([r, 'access', _65 => _65.options, 'optionalAccess', _66 => _66.scope]),scopeFields:r.targetFields,errors:r.allErrors,result:r.isValid})}}]).run(t),t.result}clear(e){this.asyncTimers[e]&&clearTimeout(this.asyncTimers[e]),delete this.asyncTimers[e],this.updateFieldValidating(e,!1),delete this.asyncErrors[e]}cancelAll(){this.asyncEpoch+=1,this.validationTimeout&&clearTimeout(this.validationTimeout),Object.values(this.asyncTimers).forEach(e=>clearTimeout(e)),this.asyncTimers={},this.asyncRequests={},this.asyncErrors={},this.store.internalUpdateState({isValidating:{}})}}, _class6);var k=class{constructor(e){this.store=e}updateField(e,t,i={origin:"setField"}){let r=this.store.getState(),s={path:e,value:t,meta:i,previousValue:g(r.values,e),nextValues:p(r.values,e,t),nextErrors:{...r.errors},toggledFields:[],isDirty:!1};new M([{name:"field:clear-current-error",run:o=>{delete o.nextErrors[o.path],this.store.clearFieldValidation(o.path)}},{name:"field:update-dependencies",run:o=>{o.toggledFields=this.store.updateDependencies(o.path,o.nextValues),o.toggledFields.forEach(l=>{this.store.isFieldHidden(l)&&(delete o.nextErrors[l],this.store.clearFieldValidation(l))})}},{name:"field:update-dirty",run:o=>{o.isDirty=this.store.updateDirtyForPath(o.path,o.nextValues,this.store.config.initialValues)}},{name:"field:commit-state",run:o=>{this.store.internalUpdateState({values:o.nextValues,errors:o.nextErrors,isValid:Object.keys(o.nextErrors).length===0,isDirty:o.isDirty},[o.path,...o.toggledFields])}},{name:"field:emit-change",run:o=>{this.store.emitFieldChange({path:o.path,previousValue:o.previousValue,nextValue:o.value,values:this.store.getState().values,state:this.store.getState(),meta:o.meta})}},{name:"field:trigger-validate",run:o=>{this.store.config.resolver&&this.store.triggerValidation([o.path])}},{name:"field:trigger-async-validate",run:o=>{this.store.handleFieldAsyncValidation(o.path,o.value)}}]).run(s)}replaceValues(e,t="replaceValues"){let i=this.store.getState().values,r=h(e);this.store.cancelAllValidations(),this.store.evaluateAllDependencies(r);let s=this.store.rebuildDirtyState(r,this.store.config.initialValues);this.store.internalUpdateState({values:r,errors:{},isValidating:{},isValid:!0,isDirty:s,isSubmitting:!1},["*"]),this.store.internalSaveSnapshot(),this.store.validateNow(),this.store.emitFieldChange({path:"*",previousValue:i,nextValue:r,values:this.store.getState().values,state:this.store.getState(),meta:{origin:t}})}hydrateValues(e){let t=B(this.store.getState().values,e);this.replaceValues(t,"hydrate")}rebaseValues(e){let t=this.store.getState().values,i=h(e);this.store.config.initialValues=h(i),this.store.cancelAllValidations(),this.store.evaluateAllDependencies(i),this.store.clearDirtyState(),this.store.internalUpdateState({values:i,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1},["*"]),this.store.internalSaveSnapshot(),this.store.validateNow(),this.store.emitFieldChange({path:"*",previousValue:t,nextValue:i,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"rebase"}})}async submit(e){if(this.store.getState().isSubmitting||this.store.hasValidationsInProgress())return;this.store.cancelAllValidations();let i={onSuccess:e,isValid:!1,valuesToSubmit:h(this.store.getState().values),dirtyValues:{}},r=new v([{name:"submit:start",run:async s=>{this.store.internalUpdateState({isSubmitting:!0}),s.isValid=await this.store.validateNow()}},{name:"submit:invalid",run:async s=>{if(s.isValid)return;let n=this.store.getState().errors,o={...this.store.getState().touched};Object.keys(n).forEach(l=>{o[l]=!0}),this.store.internalUpdateState({touched:o}),s.dirtyValues=this.store.buildDirtyValues(this.store.getState().values),s.invalid=!0,await this.store.emitAfterSubmit({values:this.store.getState().values,dirtyValues:s.dirtyValues,state:this.store.getState(),success:!1,invalid:!0}),s.halted=!0}},{name:"submit:prepare",run:s=>{this.store.getHiddenFields().forEach(n=>{s.valuesToSubmit=p(s.valuesToSubmit,n,void 0)});for(let[n,o]of this.store.getTransformEntries()){let l=g(s.valuesToSubmit,n);s.valuesToSubmit=p(s.valuesToSubmit,n,o(l,this.store.getState().values))}s.dirtyValues=this.store.buildDirtyValues(s.valuesToSubmit)}},{name:"submit:before-hooks",run:async s=>{await this.store.emitBeforeSubmit({values:s.valuesToSubmit,dirtyValues:s.dirtyValues,state:this.store.getState()})}},{name:"submit:user-handler",run:async s=>{await s.onSuccess(s.valuesToSubmit,s.dirtyValues)}},{name:"submit:after-hooks",run:async s=>{await this.store.emitAfterSubmit({values:s.valuesToSubmit,dirtyValues:s.dirtyValues,state:this.store.getState(),success:!0})}}]);try{await r.run(i)}catch(s){i.error=s,await this.store.emitOperationalError({source:"submit",error:s}),await this.store.emitAfterSubmit({values:this.store.getState().values,dirtyValues:this.store.buildDirtyValues(this.store.getState().values),state:this.store.getState(),success:!1,error:s}),console.error(s)}finally{this.store.internalUpdateState({isSubmitting:!1})}}reset(){this.store.cancelAllValidations();let e=h(this.store.config.initialValues);this.store.evaluateAllDependencies(e),this.store.clearDirtyState(),this.store.internalUpdateState({values:e,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1},["*"]),this.store.resetHistory(e)}};var I= (_class7 =class{constructor(e,t=15){;_class7.prototype.__init16.call(this);_class7.prototype.__init17.call(this);this.enableHistory=e;this.maxHistory=t}__init16() {this.history=[]}__init17() {this.historyIndex=-1}saveSnapshot(e){if(!this.enableHistory)return;let t=this.history[this.historyIndex];t&&f(t,e)||(this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push(h(e)),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--,h(this.history[this.historyIndex])):null}redo(){return this.canRedo?(this.historyIndex++,h(this.history[this.historyIndex])):null}reset(e){this.history=[],this.historyIndex=-1,this.saveSnapshot(e)}getMetadata(){return{enabled:this.enableHistory,canUndo:this.canUndo,canRedo:this.canRedo,historyIndex:this.historyIndex,historySize:this.history.length}}}, _class7);var A=class{constructor(e){this.store=e}pushItem(e,t){let i=g(this.store.getState().values,e)||[];this.store.setFieldWithMeta(e,[...i,t],{origin:"array",operation:"push"}),this.store.internalSaveSnapshot()}prependItem(e,t){let i=g(this.store.getState().values,e)||[];this.store.setFieldWithMeta(e,[t,...i],{origin:"array",operation:"prepend"}),this.store.internalSaveSnapshot()}insertItem(e,t,i){let r=[...g(this.store.getState().values,e)||[]];r.splice(t,0,i),this.store.setFieldWithMeta(e,r,{origin:"array",operation:"insert",index:t}),this.store.internalSaveSnapshot()}removeItem(e,t){let i=this.store.getState(),r=g(i.values,e);if(!Array.isArray(r))return;let s=[...r];this.store.unregisterPrefix&&this.store.unregisterPrefix(`${e}.${t}.`);let n=r.filter((d,u)=>u!==t),o=p(i.values,e,n),l=this.store.updateDirtyForPath(e,o,this.store.getConfig().initialValues);this.store.internalUpdateState({values:o,errors:j(i.errors,e,t),touched:j(i.touched,e,t),isDirty:l}),this.store.emitFieldChange({path:e,previousValue:s,nextValue:n,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"remove",index:t}}),this.store.internalSaveSnapshot(),this.revalidate(e)}swapItems(e,t,i){let r=this.store.getState(),s=[...g(r.values,e)||[]],n=[...s];[s[t],s[i]]=[s[i],s[t]];let o=p(r.values,e,s),l=this.store.updateDirtyForPath(e,o,this.store.getConfig().initialValues);this.store.internalUpdateState({values:o,errors:$(r.errors,e,t,i),touched:$(r.touched,e,t,i),isDirty:l}),this.store.emitFieldChange({path:e,previousValue:n,nextValue:s,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"swap",from:t,to:i}}),this.store.internalSaveSnapshot(),this.revalidate(e)}moveItem(e,t,i){let r=this.store.getState(),s=[...g(r.values,e)||[]],n=[...s],[o]=s.splice(t,1);s.splice(i,0,o);let l=p(r.values,e,s),d=this.store.updateDirtyForPath(e,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:_(r.errors,e,t,i),touched:_(r.touched,e,t,i),isDirty:d}),this.store.emitFieldChange({path:e,previousValue:n,nextValue:s,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"move",from:t,to:i}}),this.store.internalSaveSnapshot(),this.revalidate(e)}revalidate(e){this.store.triggerValidation([e])}};var R=class{constructor(e,t,i,r){this.getState=e;this.getInitialValues=t;this.getScopeFields=i;this.isPathDirty=r}getStepStatus(e){let t=this.getScopeFields(e),i=this.getState(),r=t.some(o=>!!i.errors[o]),s=t.some(o=>this.isPathDirty(o)),n=this.getStepErrors(e);return{hasErrors:r,isDirty:s,errors:n}}getStepErrors(e){let t=this.getScopeFields(e),i=this.getState(),r={};for(let s of t){let n=i.errors[s];n&&(r[s]=n)}return r}};var O=class{constructor(e,t,i,r){this.dependencyManager=e;this.getState=t;this.getConfig=i;this.isPathDirty=r}isHidden(e){return this.dependencyManager.isHidden(e)}isRequired(e){return this.dependencyManager.isRequired(e,this.getState().values)}isFieldDirty(e){return this.isPathDirty(e)}isFieldValidating(e){return!!this.getState().isValidating[e]}};var q=class{constructor(e,t){this.getState=e;this.internalUpdateState=t}setError(e,t){let i={...this.getState().errors,[e]:t};t||delete i[e],this.internalUpdateState({errors:i})}setErrors(e){this.internalUpdateState({errors:{...this.getState().errors,...e}})}setServerErrors(e){let t={};for(let[i,r]of Object.entries(e))t[i]=Array.isArray(r)?r[0]:r;this.setErrors(t)}};var H= (_class8 =class{constructor() { _class8.prototype.__init18.call(this); }__init18() {this.capabilities=new Map}register(e,t){this.capabilities.set(e,t)}get(e){let t=this.capabilities.get(e);if(!t)throw new Error(`Capability "${String(e)}" is not registered`);return t}has(e){return this.capabilities.has(e)}clear(){this.capabilities.clear()}}, _class8);function Y(a){let{store:e,dependencyManager:t,dirtyManager:i}=a,r=new H;return r.register("validation",new D(e)),r.register("lifecycle",new k(e)),r.register("history",new I(!!e.config.enableHistory,_nullishCoalesce(e.config.historyLimit, () => (15)))),r.register("arrays",new A(e)),r.register("scope",new R(()=>e.getState(),()=>e.config.initialValues,s=>e.getScopeFields(s),s=>i.isPathDirty(s))),r.register("query",new O(t,()=>e.getState(),()=>e.config,s=>i.isPathDirty(s))),r.register("error",new q(()=>e.getState(),s=>e.internalUpdateState(s))),r}function Z(a){let{storeId:e,storeInstance:t,config:i,getState:r,getConfig:s,getValues:n,getDirtyValues:o,applyPersistedValues:l}=a,d=new C(i.persist,n,o,l),u=[...i.plugins],c=Q(i.devTools);c&&u.push(c);let y=new w(u,()=>({storeId:e,getState:()=>r(),getConfig:()=>s()})),N=new x(e,t,d,y);return N.initialize(),N}function ee(a){let{config:e,dependencyManager:t,computedManager:i}=a,r=h(e.initialValues);return e.fields&&Object.entries(e.fields).forEach(([n,o])=>{t.register(n,o,r)}),{values:i.apply(r),errors:{},touched:{},isValidating:{},persist:{isSaving:!1,isRestoring:!1,error:null},isValid:!0,isSubmitting:!1,isDirty:!1}}var b= (_class9 =class{__init19() {this.scopeFieldsIndex=null}__init20() {this.computedEntriesCache=null}__init21() {this.transformEntriesCache=null}invalidateFieldIndexes(){this.scopeFieldsIndex=null,this.computedEntriesCache=null,this.transformEntriesCache=null}getCapability(e){return this.capabilities.get(e)}get validation(){return this.getCapability("validation")}get lifecycle(){return this.getCapability("lifecycle")}get history(){return this.getCapability("history")}get arrays(){return this.getCapability("arrays")}get scope(){return this.getCapability("scope")}get query(){return this.getCapability("query")}get error(){return this.getCapability("error")}constructor(e={}){;_class9.prototype.__init19.call(this);_class9.prototype.__init20.call(this);_class9.prototype.__init21.call(this);this.config=J(e),this.dependencyManager=new E,this.computedManager=new P(()=>this.getComputedEntries()),this.dirtyManager=new V,this.capabilities=Y({store:this,dependencyManager:this.dependencyManager,dirtyManager:this.dirtyManager}),this.state=ee({config:this.config,dependencyManager:this.dependencyManager,computedManager:this.computedManager}),this.subscriptions=new F(()=>this.state),this.internalSaveSnapshot(),this.storeId=e.storeId||this.config.name||this.config.idFactory({scope:"store",storeName:this.config.name}),this.effects=Z({storeId:this.storeId,storeInstance:this,config:this.config,getState:()=>this.getState(),getConfig:()=>this.getConfig(),getValues:()=>this.state.values,getDirtyValues:()=>this.getDirtyValues(),applyPersistedValues:t=>this.applyPersistedValues(t)})}getConfig(){return this.config}getFieldConfig(e){return this.dependencyManager.getFieldConfig(e)||_optionalChain([this, 'access', _67 => _67.config, 'access', _68 => _68.fields, 'optionalAccess', _69 => _69[e]])}getScopeFields(e){if(!this.scopeFieldsIndex){let t=new Map;this.dependencyManager.forEachFieldConfig((i,r)=>{if(!i.scope)return;let s=_nullishCoalesce(t.get(i.scope), () => ([]));s.push(r),t.set(i.scope,s)}),this.scopeFieldsIndex=t}return _nullishCoalesce(this.scopeFieldsIndex.get(e), () => ([]))}getComputedEntries(){if(!this.computedEntriesCache){let e=[];this.dependencyManager.forEachFieldConfig((t,i)=>{t.computed&&e.push([i,t.computed])}),this.computedEntriesCache=e}return this.computedEntriesCache}getTransformEntries(){if(!this.transformEntriesCache){let e=[];this.dependencyManager.forEachFieldConfig((t,i)=>{t.transform&&e.push([i,t.transform])}),this.transformEntriesCache=e}return this.transformEntriesCache}resolveMask(e){let t=_optionalChain([this, 'access', _70 => _70.getFieldConfig, 'call', _71 => _71(e), 'optionalAccess', _72 => _72.mask]);if(t)return typeof t=="string"?_optionalChain([this, 'access', _73 => _73.config, 'access', _74 => _74.masks, 'optionalAccess', _75 => _75[t]]):t}getState(){return this.state}getFieldState(e){return{value:g(this.state.values,e),error:this.state.errors[e],touched:!!this.state.touched[e],isHidden:this.isHidden(e),isRequired:this.isRequired(e),isDirty:this.isFieldDirty(e),isValidating:this.isFieldValidating(e)}}get isValid(){return this.state.isValid}get isSubmitting(){return this.state.isSubmitting}get isDirty(){return this.state.isDirty}registerField(e,t){this.dependencyManager.register(e,t,this.state.values),this.invalidateFieldIndexes(),this.dependencyManager.isHidden(e)&&this.subscriptions.notify(this.state,["*"])}unregisterField(e){if(_optionalChain([this, 'access', _76 => _76.config, 'access', _77 => _77.fields, 'optionalAccess', _78 => _78[e]]))return;this.validation.cleanupField(e),this.dependencyManager.unregister(e),this.invalidateFieldIndexes();let t={...this.state.errors},i={...this.state.touched},r=!1;t[e]&&(delete t[e],r=!0),i[e]&&(delete i[e],r=!0),r&&this.internalUpdateState({errors:t,touched:i})}unregisterPrefix(e){this.validation.cleanupPrefix(e),this.dependencyManager.unregisterPrefix(e),this.invalidateFieldIndexes()}isHidden(e){return this.query.isHidden(e)}isRequired(e){return this.query.isRequired(e)}isFieldDirty(e){return this.query.isFieldDirty(e)}isFieldValidating(e){return this.query.isFieldValidating(e)}subscribe(e){return this.subscriptions.subscribe(e)}subscribeSelector(e,t,i){let r=_nullishCoalesce(_optionalChain([i, 'optionalAccess', _79 => _79.equalityFn]), () => (S));return this.subscriptions.subscribeSelector(e,t,i,r)}subscribePath(e,t,i){let r=[..._nullishCoalesce(_optionalChain([i, 'optionalAccess', _80 => _80.paths]), () => ([])),e];return this.subscribeSelector(s=>g(s.values,e),t,{...i,paths:r})}watch(e,t){return this.subscribePath(e,t,{equalityFn:f})}setField(e,t){this.setFieldWithMeta(e,t,{origin:"setField"})}setFieldWithMeta(e,t,i={origin:"setField"}){this.lifecycle.updateField(e,t,i)}blurField(e){this.internalSaveSnapshot(),this.state.touched[e]||this.internalUpdateState({touched:{...this.state.touched,[e]:!0}}),this.validation.trigger([e])}markFieldsTouched(e){if(e.length===0)return;let t={...this.state.touched};e.forEach(i=>{t[i]=!0}),this.internalUpdateState({touched:t})}replaceValues(e){this.lifecycle.replaceValues(e)}hydrate(e){this.lifecycle.hydrateValues(e)}rebase(e){this.lifecycle.rebaseValues(e)}setError(e,t){this.error.setError(e,t)}setErrors(e){this.error.setErrors(e)}setServerErrors(e){this.error.setServerErrors(e)}reset(){this.lifecycle.reset()}async submit(e){return this.lifecycle.submit(e)}registerMask(e,t){this.config.masks={...this.config.masks||{},[e]:t}}getDirtyValues(){return this.dirtyManager.buildDirtyValues(this.state.values)}getPersistMetadata(){return this.state.persist}async restorePersisted(){this.internalUpdateState({persist:{...this.state.persist,isRestoring:!0,error:null}});try{return await this.effects.restorePersisted()}catch(e){return this.internalUpdateState({persist:{...this.state.persist,isRestoring:!1,error:e instanceof Error?e:new Error(String(e))}}),!1}finally{this.internalUpdateState({persist:{...this.state.persist,isRestoring:!1}})}}async forceSave(){this.internalUpdateState({persist:{...this.state.persist,isSaving:!0,error:null}});try{await this.effects.savePersistedNow()}catch(e){this.internalUpdateState({persist:{...this.state.persist,isSaving:!1,error:e instanceof Error?e:new Error(String(e))}});return}this.internalUpdateState({persist:{...this.state.persist,isSaving:!1}})}async clearPersisted(){this.internalUpdateState({persist:{...this.state.persist,error:null}});try{await this.effects.clearPersisted()}catch(e){this.internalUpdateState({persist:{...this.state.persist,error:e instanceof Error?e:new Error(String(e))}})}}pushItem(e,t){this.arrays.pushItem(e,t)}prependItem(e,t){this.arrays.prependItem(e,t)}insertItem(e,t,i){this.arrays.insertItem(e,t,i)}removeItem(e,t){this.arrays.removeItem(e,t)}swapItems(e,t,i){this.arrays.swapItems(e,t,i)}moveItem(e,t,i){this.arrays.moveItem(e,t,i)}get canUndo(){return this.history.canUndo}get canRedo(){return this.history.canRedo}undo(){let e=this.history.undo();if(e){let t=this.dirtyManager.rebuild(e,this.config.initialValues);this.internalUpdateState({values:e,isDirty:t}),this.validation.validate()}}redo(){let e=this.history.redo();if(e){let t=this.dirtyManager.rebuild(e,this.config.initialValues);this.internalUpdateState({values:e,isDirty:t}),this.validation.validate()}}getHistoryMetadata(){return this.history.getMetadata()}validate(e){return this.validation.validate(e)}emitBeforeValidate(e){return this.effects.beforeValidate(e)}emitAfterValidate(e){return this.effects.afterValidate(e)}emitBeforeSubmit(e){return this.effects.beforeSubmit(e)}emitAfterSubmit(e){return this.effects.afterSubmit(e)}emitFieldChange(e){this.effects.onFieldChange(e)}emitOperationalError(e){return this.effects.reportOperationalError(e)}hasValidationsInProgress(e){return this.validation.hasValidationsInProgress(e)}triggerValidation(e){this.validation.trigger(e)}getStepStatus(e){return this.scope.getStepStatus(e)}getStepErrors(e){return this.scope.getStepErrors(e)}updateDependencies(e,t){return this.dependencyManager.updateDependencies(e,t)}isFieldHidden(e){return this.dependencyManager.isHidden(e)}evaluateAllDependencies(e){this.dependencyManager.evaluateAll(e)}getHiddenFields(){return this.dependencyManager.getHiddenFields()}getRequiredErrors(e){return this.dependencyManager.getRequiredErrors(e)}clearFieldValidation(e){this.validation.clear(e)}handleFieldAsyncValidation(e,t){this.validation.handleAsync(e,t)}cancelAllValidations(){this.validation.cancelAll()}validateNow(e){return this.validation.validate(e)}updateDirtyForPath(e,t,i){return this.dirtyManager.updateForPath(e,t,i)}rebuildDirtyState(e,t){return this.dirtyManager.rebuild(e,t)}clearDirtyState(){this.dirtyManager.clear()}buildDirtyValues(e){return this.dirtyManager.buildDirtyValues(e)}resetHistory(e){this.history.reset(e)}internalUpdateState(e,t){let i=X({currentState:this.state,partialState:e,changedPaths:t,applyComputedValues:r=>this.computedManager.apply(r)});this.state=i.nextState,this.subscriptions.notify(this.state,i.changedPaths),this.effects.onStateUpdated(this.state,i.valuesChanged)}internalSaveSnapshot(){this.history.saveSnapshot(this.state.values)}applyPersistedValues(e){let t=h({...this.config.initialValues,...e});this.validation.cancelAll(),this.dependencyManager.evaluateAll(t);let i=this.dirtyManager.rebuild(t,this.config.initialValues);this.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},persist:{...this.state.persist,error:null},isValid:!0,isDirty:i,isSubmitting:!1}),this.internalSaveSnapshot(),this.validation.validate()}cleanup(){this.subscriptions.destroy(),this.validation.cancelAll(),this.capabilities.clear(),this.effects.destroy()}}, _class9);var K=Symbol.for("bit-form.store.engine");function le(a){if(a instanceof b)return a;let e=a;if(e[K])return e[K];throw new Error("BitStore: store facade without engine reference cannot be resolved for hooks API.")}function de(a={}){let e=new b(a);return{get config(){return e.config},getConfig:()=>e.getConfig(),getState:()=>e.getState(),subscribe:i=>e.subscribe(i),setField:(i,r)=>e.setField(i,r),blurField:i=>e.blurField(i),replaceValues:i=>e.replaceValues(i),hydrate:i=>e.hydrate(i),rebase:i=>e.rebase(i),setError:(i,r)=>e.setError(i,r),setErrors:i=>e.setErrors(i),setServerErrors:i=>e.setServerErrors(i),validate:i=>e.validate(i),reset:()=>e.reset(),submit:i=>e.submit(i),registerMask:(i,r)=>e.registerMask(i,r),getDirtyValues:()=>e.getDirtyValues(),getPersistMetadata:()=>e.getPersistMetadata(),restorePersisted:()=>e.restorePersisted(),forceSave:()=>e.forceSave(),clearPersisted:()=>e.clearPersisted(),cleanup:()=>e.cleanup(),registerField:(i,r)=>e.registerField(i,r),unregisterField:i=>e.unregisterField(i),isHidden:i=>e.isHidden(i),isRequired:i=>e.isRequired(i),isFieldDirty:i=>e.isFieldDirty(i),isFieldValidating:i=>e.isFieldValidating(i),watch:(i,r)=>e.watch(i,r),pushItem:(i,r)=>e.pushItem(i,r),prependItem:(i,r)=>e.prependItem(i,r),insertItem:(i,r,s)=>e.insertItem(i,r,s),removeItem:(i,r)=>e.removeItem(i,r),moveItem:(i,r,s)=>e.moveItem(i,r,s),swapItems:(i,r,s)=>e.swapItems(i,r,s),getHistoryMetadata:()=>e.getHistoryMetadata(),undo:()=>e.undo(),redo:()=>e.redo(),getStepStatus:i=>e.getStepStatus(i),getStepErrors:i=>e.getStepErrors(i),[K]:e}}exports.a = h; exports.b = B; exports.c = S; exports.d = f; exports.e = g; exports.f = p; exports.g = ie; exports.h = G; exports.i = re; exports.j = T; exports.k = le; exports.l = de;
2
- //# sourceMappingURL=chunk-LOYB7TTM.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-LOYB7TTM.cjs","../src/core/utils.ts"],"names":["deepClone","obj","item","clone","key","deepMerge","target","source","base","sourceValue","baseValue","valueEqual","b","deepEqual","keysA","keysB","collectDirtyPaths","initial","prefix","result","allKeys","k","p"],"mappings":"AAAA,+mCAAwC,SCAxBA,CAAAA,CAAaC,CAAAA,CAAW,CACtC,EAAA,CAAIA,CAAAA,GAAQ,IAAA,EAAQ,OAAOA,CAAAA,EAAQ,QAAA,CACjC,OAAOA,CAAAA,CAGT,EAAA,CAAIA,EAAAA,WAAe,IAAA,CACjB,OAAO,IAAI,IAAA,CAAKA,CAAAA,CAAI,OAAA,CAAQ,CAAC,CAAA,CAE/B,EAAA,CAAIA,EAAAA,WAAe,MAAA,CACjB,OAAO,IAAI,MAAA,CAAOA,CAAAA,CAAI,MAAA,CAAQA,CAAAA,CAAI,KAAK,CAAA,CAGzC,EAAA,CAAI,KAAA,CAAM,OAAA,CAAQA,CAAG,CAAA,CACnB,OAAOA,CAAAA,CAAI,GAAA,CA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AA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-LOYB7TTM.cjs","sourcesContent":[null,"export function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as any as T;\n }\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags) as any as T;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => deepClone(item)) as any as T;\n }\n\n const clone: any = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone((obj as any)[key]);\n }\n }\n return clone as T;\n}\n\nexport function deepMerge<T>(target: T, source: any): T {\n if (source === undefined) {\n return deepClone(target);\n }\n\n if (\n source === null ||\n typeof source !== \"object\" ||\n source instanceof Date ||\n source instanceof RegExp ||\n Array.isArray(source)\n ) {\n return deepClone(source as T);\n }\n\n const base =\n target && typeof target === \"object\" && !Array.isArray(target)\n ? deepClone(target as any)\n : ({} as Record<string, unknown>);\n\n for (const key of Object.keys(source)) {\n const sourceValue = source[key];\n const baseValue = (base as Record<string, unknown>)[key];\n\n if (\n sourceValue !== null &&\n typeof sourceValue === \"object\" &&\n !Array.isArray(sourceValue) &&\n !(sourceValue instanceof Date) &&\n !(sourceValue instanceof RegExp)\n ) {\n (base as Record<string, unknown>)[key] = deepMerge(\n baseValue,\n sourceValue,\n );\n continue;\n }\n\n (base as Record<string, unknown>)[key] = deepClone(sourceValue);\n }\n\n return base as T;\n}\n\n/**\n * Fast equality for single values. Uses === for primitives, deepEqual for objects/arrays.\n * Prefer over deepEqual when comparing a single field value (e.g. isFieldDirty, getStepStatus).\n */\nexport function valueEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n return deepEqual(a, b);\n}\n\nexport function deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n if (a instanceof RegExp && b instanceof RegExp)\n return a.toString() === b.toString();\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !deepEqual(a[key], b[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Collects all paths where obj differs from initial. Used to rebuild dirtyPaths after full state replacement.\n */\nexport function collectDirtyPaths(\n obj: any,\n initial: any,\n prefix = \"\",\n result: Set<string> = new Set(),\n): Set<string> {\n if (valueEqual(obj, initial)) return result;\n if (\n obj === null ||\n typeof obj !== \"object\" ||\n initial === null ||\n typeof initial !== \"object\"\n ) {\n if (prefix) result.add(prefix);\n return result;\n }\n if (Array.isArray(obj) || Array.isArray(initial)) {\n if (!valueEqual(obj, initial) && prefix) result.add(prefix);\n return result;\n }\n const allKeys = new Set([\n ...Object.keys(obj || {}),\n ...Object.keys(initial || {}),\n ]);\n for (const k of allKeys) {\n const p = prefix ? `${prefix}.${k}` : k;\n collectDirtyPaths((obj as any)?.[k], (initial as any)?.[k], p, result);\n }\n return result;\n}\n\nconst PATH_CACHE_MAX = 1000;\nconst pathCache = new Map<string, string[]>();\n\nfunction getPathKeys(path: string): string[] {\n const cached = pathCache.get(path);\n if (cached) {\n pathCache.delete(path);\n pathCache.set(path, cached);\n return cached;\n }\n\n const keys = path.split(\".\");\n if (pathCache.size >= PATH_CACHE_MAX) {\n const oldestKey = pathCache.keys().next().value;\n if (oldestKey) {\n pathCache.delete(oldestKey);\n }\n }\n pathCache.set(path, keys);\n return keys;\n}\n\nexport function getDeepValue(obj: any, path: string): any {\n if (!path) return obj;\n\n const keys = getPathKeys(path);\n\n let current = obj;\n for (const key of keys) {\n if (current === null || current === undefined) return undefined;\n current = current[key];\n }\n return current;\n}\n\nexport function setDeepValue(obj: any, path: string, value: any): any {\n if (!path) return value;\n\n const keys = getPathKeys(path);\n\n const result = Array.isArray(obj) ? [...obj] : { ...obj };\n let current = result;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const nextAsNumber = Number(nextKey);\n const isNextNumeric =\n Number.isInteger(nextAsNumber) && String(nextAsNumber) === nextKey;\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n } else {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n\n return result;\n}\n\nexport function cleanPrefixedKeys(\n obj: Record<string, any>,\n prefix: string,\n): Record<string, any> {\n const newObj: Record<string, any> = {};\n const prefixWithDot = `${prefix}.`;\n\n for (const key in obj) {\n if (key !== prefix && !key.startsWith(prefixWithDot)) {\n newObj[key] = obj[key];\n }\n }\n return newObj;\n}\n\nexport const shiftKeys = (\n obj: Record<string, any>,\n path: string,\n removedIndex: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === removedIndex) return;\n\n if (currentIdx > removedIndex) {\n const newIdx = currentIdx - 1;\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const swapKeys = (\n obj: Record<string, any>,\n path: string,\n indexA: number,\n indexB: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === indexA) {\n const newKey = rest ? `${prefix}${indexB}.${rest}` : `${prefix}${indexB}`;\n newObj[newKey] = obj[key];\n } else if (currentIdx === indexB) {\n const newKey = rest ? `${prefix}${indexA}.${rest}` : `${prefix}${indexA}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const moveKeys = (\n obj: Record<string, any>,\n path: string,\n from: number,\n to: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n let newIdx = currentIdx;\n if (currentIdx === from) {\n newIdx = to;\n } else if (from < to && currentIdx > from && currentIdx <= to) {\n newIdx = currentIdx - 1;\n } else if (from > to && currentIdx >= to && currentIdx < from) {\n newIdx = currentIdx + 1;\n }\n\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n });\n return newObj;\n};\n\n/**\n * Checks if a value looks like a server validation error response.\n * Handles shapes like { email: \"Taken\" }, { errors: { email: [\"Taken\"] } }, etc.\n */\nexport function isValidationErrorShape(\n x: unknown,\n): x is Record<string, string | string[]> {\n if (typeof x !== \"object\" || x === null || Array.isArray(x)) return false;\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj))\n return false;\n\n return Object.values(obj as Record<string, unknown>).every(\n (v) =>\n typeof v === \"string\" ||\n (Array.isArray(v) && v.every((i) => typeof i === \"string\")),\n );\n}\n\n/**\n * Extracts server errors in the format expected by setServerErrors.\n */\nexport function extractServerErrors(\n x: unknown,\n): Record<string, string | string[]> {\n if (!isValidationErrorShape(x)) return {};\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n return obj as Record<string, string | string[]>;\n}\n"]}
@@ -1,2 +0,0 @@
1
- function a(n,t,e){return async o=>{if(o){e.setLoading(!0),e.setError(n,void 0);try{let r=await t(o);e.setValue(r.url),e.setUploadKey(r.key),e.setError(n,void 0)}catch(r){let d=r instanceof Error?r.message:"Upload failed";e.setError(n,d)}finally{e.setLoading(!1)}}}}function l(n,t,e){return async()=>{let o=e.getUploadKey();if(o&&t)try{await t(o)}catch(r){let d=r instanceof Error?r.message:"Delete failed";e.setError(n,d);return}e.setValue(null),e.setUploadKey(null),e.setError(n,void 0)}}export{a,l as b};
2
- //# sourceMappingURL=chunk-O5UPA33R.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/adapters/upload-kernel.ts"],"sourcesContent":["/**\n * Framework-agnostic upload kernel.\n *\n * Encapsulates the side-effect logic for uploading/removing files so that\n * React, Vue, and Angular adapters share a single implementation and only\n * differ in how they wire reactive state.\n */\n\nimport type { BitUploadFn, BitDeleteUploadFn } from \"../types/upload\";\n\nexport interface UploadKernelCallbacks {\n /** Called with `true` when upload starts and `false` when it finishes. */\n setLoading: (loading: boolean) => void;\n /** Set or clear a field-level error message. */\n setError: (path: string, message: string | undefined) => void;\n /** Set the stored file URL after a successful upload (or `null` on remove). */\n setValue: (value: string | null) => void;\n /** Return the key of the last uploaded file (used when deleting). */\n getUploadKey: () => string | null;\n /** Persist the upload key returned by the upload function. */\n setUploadKey: (key: string | null) => void;\n}\n\n/**\n * Creates a type-safe `upload` handler for a field.\n *\n * @example\n * ```ts\n * const upload = createUploadHandler(\"avatar\", myUploadFn, {\n * setLoading: (v) => (isUploading.value = v),\n * setError: (p, m) => store.setError(p, m),\n * setValue: (v) => field.setValue(v),\n * getUploadKey: () => uploadKey,\n * setUploadKey: (k) => (uploadKey = k),\n * });\n * ```\n */\nexport function createUploadHandler(\n fieldPath: string,\n uploadFn: BitUploadFn,\n callbacks: UploadKernelCallbacks,\n): (file: File | null | undefined) => Promise<void> {\n return async (file) => {\n if (!file) return;\n\n callbacks.setLoading(true);\n callbacks.setError(fieldPath, undefined);\n\n try {\n const result = await uploadFn(file);\n\n callbacks.setValue(result.url);\n callbacks.setUploadKey(result.key);\n callbacks.setError(fieldPath, undefined);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Upload failed\";\n callbacks.setError(fieldPath, message);\n } finally {\n callbacks.setLoading(false);\n }\n };\n}\n\n/**\n * Creates a type-safe `remove` handler for a field.\n */\nexport function createRemoveHandler(\n fieldPath: string,\n deleteFile: BitDeleteUploadFn | undefined,\n callbacks: UploadKernelCallbacks,\n): () => Promise<void> {\n return async () => {\n const uploadKey = callbacks.getUploadKey();\n\n if (uploadKey && deleteFile) {\n try {\n await deleteFile(uploadKey);\n } catch (error) {\n const message =\n error instanceof Error ? error.message : \"Delete failed\";\n callbacks.setError(fieldPath, message);\n return;\n }\n }\n\n callbacks.setValue(null);\n callbacks.setUploadKey(null);\n callbacks.setError(fieldPath, undefined);\n };\n}\n"],"mappings":"AAqCO,SAASA,EACdC,EACAC,EACAC,EACkD,CAClD,MAAO,OAAOC,GAAS,CACrB,GAAKA,EAEL,CAAAD,EAAU,WAAW,EAAI,EACzBA,EAAU,SAASF,EAAW,MAAS,EAEvC,GAAI,CACF,IAAMI,EAAS,MAAMH,EAASE,CAAI,EAElCD,EAAU,SAASE,EAAO,GAAG,EAC7BF,EAAU,aAAaE,EAAO,GAAG,EACjCF,EAAU,SAASF,EAAW,MAAS,CACzC,OAASK,EAAO,CACd,IAAMC,EAAUD,aAAiB,MAAQA,EAAM,QAAU,gBACzDH,EAAU,SAASF,EAAWM,CAAO,CACvC,QAAE,CACAJ,EAAU,WAAW,EAAK,CAC5B,EACF,CACF,CAKO,SAASK,EACdP,EACAQ,EACAN,EACqB,CACrB,MAAO,UAAY,CACjB,IAAMO,EAAYP,EAAU,aAAa,EAEzC,GAAIO,GAAaD,EACf,GAAI,CACF,MAAMA,EAAWC,CAAS,CAC5B,OAASJ,EAAO,CACd,IAAMC,EACJD,aAAiB,MAAQA,EAAM,QAAU,gBAC3CH,EAAU,SAASF,EAAWM,CAAO,EACrC,MACF,CAGFJ,EAAU,SAAS,IAAI,EACvBA,EAAU,aAAa,IAAI,EAC3BA,EAAU,SAASF,EAAW,MAAS,CACzC,CACF","names":["createUploadHandler","fieldPath","uploadFn","callbacks","file","result","error","message","createRemoveHandler","deleteFile","uploadKey"]}
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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 _chunkLOYB7TTMcjs = require('./chunk-LOYB7TTM.cjs');var _chunkEI5L5L3Rcjs = require('./chunk-EI5L5L3R.cjs');async function d(t,r,e,n){try{let o=await t(r,e);n.onSuccess(o)}catch(o){if(_chunkLOYB7TTMcjs.h.call(void 0, o)){n.onServerErrors(_chunkLOYB7TTMcjs.i.call(void 0, o));return}n.onUnhandledError(o instanceof Error?o:new Error(String(o)))}}function p(t,r){_optionalChain([t, 'optionalAccess', _ => _.preventDefault, 'optionalCall', _2 => _2()]),_optionalChain([r, 'optionalAccess', _3 => _3.stopPropagation])&&_optionalChain([t, 'optionalAccess', _4 => _4.stopPropagation, 'optionalCall', _5 => _5()])}function E(t,r,e){return{submit:i=>a=>(p(a,e),t.submit(i)),onSubmit:i=>a=>(p(a,e),r.setSubmissionError(null),t.submit(async(b,B)=>{await d(i,b,B,{onSuccess:s=>{r.setSubmissionResult(s),r.setSubmissionError(null)},onServerErrors:s=>{t.setServerErrors(s)},onUnhandledError:s=>{r.setSubmissionError(s)}})})),reset:()=>{t.reset(),r.clearSubmissionState()},getValues:()=>t.getState().values,getErrors:()=>t.getState().errors,getTouched:()=>t.getState().touched,getDirtyValues:()=>t.getDirtyValues()}}function y(t,r,e){return t.subscribeSelector(()=>t.getFieldState(r),e,{paths:[r]})}function x(t,r,e){return{setValue:i=>{t.setField(r,_chunkEI5L5L3Rcjs.N.call(void 0, i,e))},setBlur:()=>t.blurField(r),displayValue:i=>_chunkEI5L5L3Rcjs.M.call(void 0, i,e)}}exports.a = E; exports.b = y; exports.c = x;
2
- //# sourceMappingURL=chunk-RFFMBY7M.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-RFFMBY7M.cjs","../src/core/submit-handler.ts","../src/core/form-controller.ts","../src/core/field-controller.ts"],"names":["executeSubmitHandler","handler","values","dirtyValues","handlers","result","error","isValidationErrorShape","extractServerErrors","preventFormEvent","event","options","createFormController","store","runtime","onSuccess","serverErrors","subscribeFieldState","path","listener","createMaskedFieldController","mask","value","parseMaskedInput","formatMaskedValue"],"mappings":"AAAA,qoBAA+C,wDAAgD,MCQ/F,SAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACe,CACf,GAAI,CACF,IAAMC,CAAAA,CAAS,MAAMJ,CAAAA,CAAQC,CAAAA,CAAQC,CAAW,CAAA,CAChDC,CAAAA,CAAS,SAAA,CAAUC,CAAM,CAC3B,CAAA,KAAA,CAASC,CAAAA,CAAO,CACd,EAAA,CAAIC,iCAAAA,CAA4B,CAAA,CAAG,CACjCH,CAAAA,CAAS,cAAA,CAAeI,iCAAAA,CAAyB,CAAC,CAAA,CAClD,MACF,CAEAJ,CAAAA,CAAS,gBAAA,CACPE,EAAAA,WAAiB,KAAA,CAAQA,CAAAA,CAAQ,IAAI,KAAA,CAAM,MAAA,CAAOA,CAAK,CAAC,CAC1D,CACF,C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AA,CAAE,MAAA,CAClC,SAAA,CAAW,CAAA,CAAA,EAAMA,CAAAA,CAAM,QAAA,CAAS,CAAA,CAAE,MAAA,CAClC,UAAA,CAAY,CAAA,CAAA,EAAMA,CAAAA,CAAM,QAAA,CAAS,CAAA,CAAE,OAAA,CACnC,cAAA,CAAgB,CAAA,CAAA,EAAMA,CAAAA,CAAM,cAAA,CAAe,CAC7C,CACF,CCvEO,SAASI,CAAAA,CAIdJ,CAAAA,CACAK,CAAAA,CACAC,CAAAA,CAGA,CACA,OAAON,CAAAA,CAAM,iBAAA,CACX,CAAA,CAAA,EACEA,CAAAA,CAAM,aAAA,CAAcK,CAAI,CAAA,CAG1BC,CAAAA,CACA,CAAE,KAAA,CAAO,CAACD,CAAc,CAAE,CAC5B,CACF,CAEO,SAASE,CAAAA,CAGdP,CAAAA,CAAgCK,CAAAA,CAASG,CAAAA,CAA2B,CAYpE,MAAO,CACL,QAAA,CAZgBC,CAAAA,EAAmB,CACnCT,CAAAA,CAAM,QAAA,CACJK,CAAAA,CACAK,iCAAAA,CAAiBD,CAAOD,CAAI,CAC9B,CACF,CAAA,CAQE,OAAA,CANc,CAAA,CAAA,EAAMR,CAAAA,CAAM,SAAA,CAAUK,CAAI,CAAA,CAOxC,YAAA,CALoBI,CAAAA,EAAmBE,iCAAAA,CAAkBF,CAAOD,CAAI,CAMtE,CACF,CAAA,4CAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-RFFMBY7M.cjs","sourcesContent":[null,"import { extractServerErrors, isValidationErrorShape } from \"./utils\";\n\nexport interface BitSubmitExecutionHandlers {\n onServerErrors: (errors: Record<string, string[] | string>) => void;\n onUnhandledError: (error: Error) => void;\n onSuccess: (result: unknown) => void;\n}\n\nexport async function executeSubmitHandler<T extends object>(\n handler: (values: T, dirtyValues?: Partial<T>) => Promise<unknown>,\n values: T,\n dirtyValues: Partial<T> | undefined,\n handlers: BitSubmitExecutionHandlers,\n): Promise<void> {\n try {\n const result = await handler(values, dirtyValues);\n handlers.onSuccess(result);\n } catch (error) {\n if (isValidationErrorShape(error)) {\n handlers.onServerErrors(extractServerErrors(error));\n return;\n }\n\n handlers.onUnhandledError(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n}\n","import { executeSubmitHandler } from \"./submit-handler\";\nimport type { BitStoreHooksApi } from \"./store/contracts/public-types\";\n\nexport type BitFormDomEvent = {\n preventDefault?: () => void;\n stopPropagation?: () => void;\n};\n\nexport interface BitFormControllerRuntime {\n clearSubmissionState: () => void;\n setSubmissionResult: (result: unknown) => void;\n setSubmissionError: (error: Error | null) => void;\n}\n\nexport interface BitFormControllerOptions {\n stopPropagation?: boolean;\n}\n\nexport function preventFormEvent(\n event?: BitFormDomEvent,\n options?: BitFormControllerOptions,\n) {\n event?.preventDefault?.();\n if (options?.stopPropagation) {\n event?.stopPropagation?.();\n }\n}\n\nexport function createFormController<T extends object>(\n store: BitStoreHooksApi<T>,\n runtime: BitFormControllerRuntime,\n options?: BitFormControllerOptions,\n) {\n const submit = (\n onSuccess: (values: T, dirtyValues?: Partial<T>) => void | Promise<void>,\n ) => {\n return (event?: BitFormDomEvent) => {\n preventFormEvent(event, options);\n return store.submit(onSuccess);\n };\n };\n\n const onSubmit = (\n handler: (values: T, dirtyValues?: Partial<T>) => Promise<unknown>,\n ) => {\n return (event?: BitFormDomEvent) => {\n preventFormEvent(event, options);\n runtime.setSubmissionError(null);\n\n return store.submit(async (values, dirtyValues) => {\n await executeSubmitHandler(handler, values, dirtyValues, {\n onSuccess: (result) => {\n runtime.setSubmissionResult(result);\n runtime.setSubmissionError(null);\n },\n onServerErrors: (serverErrors) => {\n store.setServerErrors(serverErrors);\n },\n onUnhandledError: (error) => {\n runtime.setSubmissionError(error);\n },\n });\n });\n };\n };\n\n const reset = () => {\n store.reset();\n runtime.clearSubmissionState();\n };\n\n return {\n submit,\n onSubmit,\n reset,\n getValues: () => store.getState().values,\n getErrors: () => store.getState().errors,\n getTouched: () => store.getState().touched,\n getDirtyValues: () => store.getDirtyValues(),\n };\n}\n","import { formatMaskedValue, parseMaskedInput } from \"./mask/field-binding\";\nimport type { BitMask } from \"./mask/types\";\nimport type { BitStoreHooksApi } from \"./store/contracts/public-types\";\nimport type {\n BitFieldState,\n BitPath,\n BitPathValue,\n} from \"./store/contracts/types\";\n\nexport function subscribeFieldState<\n TForm extends object,\n P extends BitPath<TForm>,\n>(\n store: BitStoreHooksApi<TForm>,\n path: P,\n listener: (\n value: Readonly<BitFieldState<TForm, BitPathValue<TForm, P>>>,\n ) => void,\n) {\n return store.subscribeSelector(\n () =>\n store.getFieldState(path) as Readonly<\n BitFieldState<TForm, BitPathValue<TForm, P>>\n >,\n listener,\n { paths: [path as string] },\n );\n}\n\nexport function createMaskedFieldController<\n TForm extends object,\n P extends BitPath<TForm>,\n>(store: BitStoreHooksApi<TForm>, path: P, mask: BitMask | undefined) {\n const setValue = (value: unknown) => {\n store.setField(\n path,\n parseMaskedInput(value, mask) as BitPathValue<TForm, P>,\n );\n };\n\n const setBlur = () => store.blurField(path);\n\n const displayValue = (value: unknown) => formatMaskedValue(value, mask);\n\n return {\n setValue,\n setBlur,\n displayValue,\n };\n}\n"]}
@@ -1,2 +0,0 @@
1
- import{h as u,i as l}from"./chunk-AE4G32HS.js";import{M as m,N as c}from"./chunk-7LMNIQTT.js";async function d(t,r,e,n){try{let o=await t(r,e);n.onSuccess(o)}catch(o){if(u(o)){n.onServerErrors(l(o));return}n.onUnhandledError(o instanceof Error?o:new Error(String(o)))}}function p(t,r){t?.preventDefault?.(),r?.stopPropagation&&t?.stopPropagation?.()}function E(t,r,e){return{submit:i=>a=>(p(a,e),t.submit(i)),onSubmit:i=>a=>(p(a,e),r.setSubmissionError(null),t.submit(async(b,B)=>{await d(i,b,B,{onSuccess:s=>{r.setSubmissionResult(s),r.setSubmissionError(null)},onServerErrors:s=>{t.setServerErrors(s)},onUnhandledError:s=>{r.setSubmissionError(s)}})})),reset:()=>{t.reset(),r.clearSubmissionState()},getValues:()=>t.getState().values,getErrors:()=>t.getState().errors,getTouched:()=>t.getState().touched,getDirtyValues:()=>t.getDirtyValues()}}function y(t,r,e){return t.subscribeSelector(()=>t.getFieldState(r),e,{paths:[r]})}function x(t,r,e){return{setValue:i=>{t.setField(r,c(i,e))},setBlur:()=>t.blurField(r),displayValue:i=>m(i,e)}}export{E as a,y as b,x as c};
2
- //# sourceMappingURL=chunk-YGAD4ZZW.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/submit-handler.ts","../src/core/form-controller.ts","../src/core/field-controller.ts"],"sourcesContent":["import { extractServerErrors, isValidationErrorShape } from \"./utils\";\n\nexport interface BitSubmitExecutionHandlers {\n onServerErrors: (errors: Record<string, string[] | string>) => void;\n onUnhandledError: (error: Error) => void;\n onSuccess: (result: unknown) => void;\n}\n\nexport async function executeSubmitHandler<T extends object>(\n handler: (values: T, dirtyValues?: Partial<T>) => Promise<unknown>,\n values: T,\n dirtyValues: Partial<T> | undefined,\n handlers: BitSubmitExecutionHandlers,\n): Promise<void> {\n try {\n const result = await handler(values, dirtyValues);\n handlers.onSuccess(result);\n } catch (error) {\n if (isValidationErrorShape(error)) {\n handlers.onServerErrors(extractServerErrors(error));\n return;\n }\n\n handlers.onUnhandledError(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n}\n","import { executeSubmitHandler } from \"./submit-handler\";\nimport type { BitStoreHooksApi } from \"./store/contracts/public-types\";\n\nexport type BitFormDomEvent = {\n preventDefault?: () => void;\n stopPropagation?: () => void;\n};\n\nexport interface BitFormControllerRuntime {\n clearSubmissionState: () => void;\n setSubmissionResult: (result: unknown) => void;\n setSubmissionError: (error: Error | null) => void;\n}\n\nexport interface BitFormControllerOptions {\n stopPropagation?: boolean;\n}\n\nexport function preventFormEvent(\n event?: BitFormDomEvent,\n options?: BitFormControllerOptions,\n) {\n event?.preventDefault?.();\n if (options?.stopPropagation) {\n event?.stopPropagation?.();\n }\n}\n\nexport function createFormController<T extends object>(\n store: BitStoreHooksApi<T>,\n runtime: BitFormControllerRuntime,\n options?: BitFormControllerOptions,\n) {\n const submit = (\n onSuccess: (values: T, dirtyValues?: Partial<T>) => void | Promise<void>,\n ) => {\n return (event?: BitFormDomEvent) => {\n preventFormEvent(event, options);\n return store.submit(onSuccess);\n };\n };\n\n const onSubmit = (\n handler: (values: T, dirtyValues?: Partial<T>) => Promise<unknown>,\n ) => {\n return (event?: BitFormDomEvent) => {\n preventFormEvent(event, options);\n runtime.setSubmissionError(null);\n\n return store.submit(async (values, dirtyValues) => {\n await executeSubmitHandler(handler, values, dirtyValues, {\n onSuccess: (result) => {\n runtime.setSubmissionResult(result);\n runtime.setSubmissionError(null);\n },\n onServerErrors: (serverErrors) => {\n store.setServerErrors(serverErrors);\n },\n onUnhandledError: (error) => {\n runtime.setSubmissionError(error);\n },\n });\n });\n };\n };\n\n const reset = () => {\n store.reset();\n runtime.clearSubmissionState();\n };\n\n return {\n submit,\n onSubmit,\n reset,\n getValues: () => store.getState().values,\n getErrors: () => store.getState().errors,\n getTouched: () => store.getState().touched,\n getDirtyValues: () => store.getDirtyValues(),\n };\n}\n","import { formatMaskedValue, parseMaskedInput } from \"./mask/field-binding\";\nimport type { BitMask } from \"./mask/types\";\nimport type { BitStoreHooksApi } from \"./store/contracts/public-types\";\nimport type {\n BitFieldState,\n BitPath,\n BitPathValue,\n} from \"./store/contracts/types\";\n\nexport function subscribeFieldState<\n TForm extends object,\n P extends BitPath<TForm>,\n>(\n store: BitStoreHooksApi<TForm>,\n path: P,\n listener: (\n value: Readonly<BitFieldState<TForm, BitPathValue<TForm, P>>>,\n ) => void,\n) {\n return store.subscribeSelector(\n () =>\n store.getFieldState(path) as Readonly<\n BitFieldState<TForm, BitPathValue<TForm, P>>\n >,\n listener,\n { paths: [path as string] },\n );\n}\n\nexport function createMaskedFieldController<\n TForm extends object,\n P extends BitPath<TForm>,\n>(store: BitStoreHooksApi<TForm>, path: P, mask: BitMask | undefined) {\n const setValue = (value: unknown) => {\n store.setField(\n path,\n parseMaskedInput(value, mask) as BitPathValue<TForm, P>,\n );\n };\n\n const setBlur = () => store.blurField(path);\n\n const displayValue = (value: unknown) => formatMaskedValue(value, mask);\n\n return {\n setValue,\n setBlur,\n displayValue,\n };\n}\n"],"mappings":"8FAQA,eAAsBA,EACpBC,EACAC,EACAC,EACAC,EACe,CACf,GAAI,CACF,IAAMC,EAAS,MAAMJ,EAAQC,EAAQC,CAAW,EAChDC,EAAS,UAAUC,CAAM,CAC3B,OAASC,EAAO,CACd,GAAIC,EAAuBD,CAAK,EAAG,CACjCF,EAAS,eAAeI,EAAoBF,CAAK,CAAC,EAClD,MACF,CAEAF,EAAS,iBACPE,aAAiB,MAAQA,EAAQ,IAAI,MAAM,OAAOA,CAAK,CAAC,CAC1D,CACF,CACF,CCTO,SAASG,EACdC,EACAC,EACA,CACAD,GAAO,iBAAiB,EACpBC,GAAS,iBACXD,GAAO,kBAAkB,CAE7B,CAEO,SAASE,EACdC,EACAC,EACAH,EACA,CAuCA,MAAO,CACL,OAtCAI,GAEQL,IACND,EAAiBC,EAAOC,CAAO,EACxBE,EAAM,OAAOE,CAAS,GAmC/B,SA9BAC,GAEQN,IACND,EAAiBC,EAAOC,CAAO,EAC/BG,EAAQ,mBAAmB,IAAI,EAExBD,EAAM,OAAO,MAAOI,EAAQC,IAAgB,CACjD,MAAMC,EAAqBH,EAASC,EAAQC,EAAa,CACvD,UAAYE,GAAW,CACrBN,EAAQ,oBAAoBM,CAAM,EAClCN,EAAQ,mBAAmB,IAAI,CACjC,EACA,eAAiBO,GAAiB,CAChCR,EAAM,gBAAgBQ,CAAY,CACpC,EACA,iBAAmBC,GAAU,CAC3BR,EAAQ,mBAAmBQ,CAAK,CAClC,CACF,CAAC,CACH,CAAC,GAYH,MARY,IAAM,CAClBT,EAAM,MAAM,EACZC,EAAQ,qBAAqB,CAC/B,EAME,UAAW,IAAMD,EAAM,SAAS,EAAE,OAClC,UAAW,IAAMA,EAAM,SAAS,EAAE,OAClC,WAAY,IAAMA,EAAM,SAAS,EAAE,QACnC,eAAgB,IAAMA,EAAM,eAAe,CAC7C,CACF,CCvEO,SAASU,EAIdC,EACAC,EACAC,EAGA,CACA,OAAOF,EAAM,kBACX,IACEA,EAAM,cAAcC,CAAI,EAG1BC,EACA,CAAE,MAAO,CAACD,CAAc,CAAE,CAC5B,CACF,CAEO,SAASE,EAGdH,EAAgCC,EAASG,EAA2B,CAYpE,MAAO,CACL,SAZgBC,GAAmB,CACnCL,EAAM,SACJC,EACAK,EAAiBD,EAAOD,CAAI,CAC9B,CACF,EAQE,QANc,IAAMJ,EAAM,UAAUC,CAAI,EAOxC,aALoBI,GAAmBE,EAAkBF,EAAOD,CAAI,CAMtE,CACF","names":["executeSubmitHandler","handler","values","dirtyValues","handlers","result","error","isValidationErrorShape","extractServerErrors","preventFormEvent","event","options","createFormController","store","runtime","onSuccess","handler","values","dirtyValues","executeSubmitHandler","result","serverErrors","error","subscribeFieldState","store","path","listener","createMaskedFieldController","mask","value","parseMaskedInput","formatMaskedValue"]}
@@ -1,2 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }var _chunkRFFMBY7Mcjs = require('./chunk-RFFMBY7M.cjs');var _chunkLOYB7TTMcjs = require('./chunk-LOYB7TTM.cjs');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var w=_react.createContext.call(void 0, null),nt= exports.a =({store:t,children:e})=>_jsxruntime.jsx.call(void 0, w.Provider,{value:_chunkLOYB7TTMcjs.k.call(void 0, t),children:e}),S= exports.b =()=>{let t=_react.useContext.call(void 0, w);if(!t)throw new Error("BitForm hooks devem ser usados dentro de um BitFormProvider");return t};function mt(){let t=S(),[e,s]=_react.useState.call(void 0, null),[o,u]=_react.useState.call(void 0, null),i=_react.useRef.call(void 0, null),m=_react.useCallback.call(void 0, ()=>{let b=t.getState(),g={isValid:b.isValid,isDirty:b.isDirty,isSubmitting:b.isSubmitting};return i.current&&i.current.isValid===g.isValid&&i.current.isDirty===g.isDirty&&i.current.isSubmitting===g.isSubmitting?i.current:(i.current=g,g)},[t]),d=_react.useCallback.call(void 0, b=>t.subscribeSelector(g=>({isValid:g.isValid,isDirty:g.isDirty,isSubmitting:g.isSubmitting}),()=>b()),[t]),n=_react.useSyncExternalStore.call(void 0, d,m,m),r=_react.useMemo.call(void 0, ()=>_chunkRFFMBY7Mcjs.a.call(void 0, t,{clearSubmissionState:()=>{s(null),u(null)},setSubmissionResult:b=>{u(b)},setSubmissionError:b=>{s(b)}}),[t]),c=_react.useCallback.call(void 0, r.submit,[r]),a=_react.useCallback.call(void 0, r.onSubmit,[r]),f=_react.useCallback.call(void 0, r.reset,[r]),F=_react.useCallback.call(void 0, r.getValues,[r]),P=_react.useCallback.call(void 0, r.getErrors,[r]),l=_react.useCallback.call(void 0, r.getTouched,[r]),y=_react.useCallback.call(void 0, r.getDirtyValues,[r]);return{meta:_react.useMemo.call(void 0, ()=>({...n,submitError:e,lastResponse:o}),[n,e,o]),getValues:F,getErrors:P,getTouched:l,getDirtyValues:y,submit:c,onSubmit:a,reset:f,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),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t)}}function ht(t){let e=S(),s=_react.useCallback.call(void 0, r=>e.config.idFactory({scope:"array",path:t,index:r}),[e,t]),o=_react.useRef.call(void 0, []),u=_react.useCallback.call(void 0, ()=>{let r=e.getState(),c=_chunkLOYB7TTMcjs.e.call(void 0, r.values,t),a=Array.isArray(c)?c:[];if(a.length!==o.current.length)if(a.length>o.current.length){let f=a.length-o.current.length;o.current=[...o.current,...Array(f).fill(null).map((F,P)=>s(o.current.length+P))]}else o.current=o.current.slice(0,a.length);return a},[e,t,s]),i=_react.useCallback.call(void 0, r=>e.subscribePath(t,()=>r()),[e,t]),m=_react.useSyncExternalStore.call(void 0, i,u,u),d=_react.useMemo.call(void 0, ()=>({append:r=>{o.current=[...o.current,s(o.current.length)],e.pushItem(t,r)},prepend:r=>{o.current=[s(0),...o.current],e.prependItem(t,r)},insert:(r,c)=>{let a=[...o.current];a.splice(r,0,s(r)),o.current=a,e.insertItem(t,r,c)},remove:r=>{o.current=o.current.filter((c,a)=>a!==r),e.removeItem(t,r)},move:(r,c)=>{let a=[...o.current],[f]=a.splice(r,1);a.splice(c,0,f),o.current=a,e.moveItem(t,r,c)},swap:(r,c)=>{let a=[...o.current];[a[r],a[c]]=[a[c],a[r]],o.current=a,e.swapItems(t,r,c)},replace:r=>{o.current=r.map((c,a)=>s(a)),e.setField(t,r)},clear:()=>{o.current=[],e.setField(t,[])}}),[e,t,s]);return{fields:_react.useMemo.call(void 0, ()=>m.map((r,c)=>({key:o.current[c]||`temp-${c}`,value:r,index:c})),[m]),length:m.length,...d}}function Vt(t){let e=S(),s=_react.useRef.call(void 0, null),o=_react.useCallback.call(void 0, ()=>{let n=e.getStepStatus(t);return s.current&&s.current.hasErrors===n.hasErrors&&s.current.isDirty===n.isDirty&&Object.keys(s.current.errors).length===Object.keys(n.errors).length&&Object.entries(n.errors).every(([r,c])=>s.current.errors[r]===c)?s.current:(s.current=n,n)},[e,t]),u=_react.useCallback.call(void 0, n=>e.subscribeSelector(r=>({errors:r.errors,isDirty:r.isDirty}),()=>n()),[e]),i=_react.useSyncExternalStore.call(void 0, u,o,o),m=_react.useCallback.call(void 0, async()=>{let n=await e.validate({scope:t}),r=e.getStepErrors(t);return{valid:n,errors:r}},[e,t]),d=_react.useCallback.call(void 0, ()=>e.getStepErrors(t),[e,t]);return{scopeName:t,status:i,errors:i.errors,validate:m,getErrors:d,isValid:!i.hasErrors,isDirty:i.isDirty}}function xt(t){let e=S(),[s,o]=_react.useState.call(void 0, 0),u=_nullishCoalesce(t[s], () => ("")),i=_react.useRef.call(void 0, null),m=_react.useCallback.call(void 0, ()=>{let l=e.getStepStatus(u);return i.current&&i.current.hasErrors===l.hasErrors&&i.current.isDirty===l.isDirty&&Object.keys(i.current.errors).length===Object.keys(l.errors).length&&Object.entries(l.errors).every(([y,B])=>i.current.errors[y]===B)?i.current:(i.current=l,l)},[e,u]),d=_react.useSyncExternalStore.call(void 0, l=>e.subscribeSelector(y=>({errors:y.errors,isDirty:y.isDirty}),()=>l()),m,m),n=_react.useCallback.call(void 0, async()=>{let l=await e.validate({scope:u}),y=e.getStepErrors(u);return{valid:l,errors:y}},[e,u]),r=_react.useCallback.call(void 0, ()=>e.getStepErrors(u),[e,u]),c=_react.useCallback.call(void 0, async()=>{let l=e.getScopeFields(u);if(e.hasValidationsInProgress(l))return!1;let y=await e.validate({scope:u});if(y)o(B=>Math.min(B+1,t.length-1));else{let B=e.getStepErrors(u),b=Object.keys(B);b.length>0&&e.markFieldsTouched(b)}return y},[e,u,t.length]),a=_react.useCallback.call(void 0, ()=>{o(l=>Math.max(l-1,0))},[]),f=_react.useCallback.call(void 0, l=>{o(Math.max(0,Math.min(l-1,t.length-1)))},[t.length]),F=s===0,P=s>=t.length-1;return{step:s+1,stepIndex:s,scope:u,next:c,prev:a,goTo:f,isFirst:F,isLast:P,status:d,errors:d.errors,isValid:!d.hasErrors,isDirty:d.isDirty,validate:n,getErrors:r}}function Ct(t){let e=S(),s=_react.useRef.call(void 0, null),o=_react.useCallback.call(void 0, ()=>{let i=_chunkLOYB7TTMcjs.e.call(void 0, e.getState().values,t);return s.current!==null&&_chunkLOYB7TTMcjs.d.call(void 0, s.current,i)?s.current:(s.current=i,i)},[e,t]),u=_react.useCallback.call(void 0, i=>e.subscribePath(t,()=>i()),[e,t]);return _react.useSyncExternalStore.call(void 0, u,o,o)}function qt(){let t=S(),e=_react.useSyncExternalStore.call(void 0, m=>t.subscribeSelector(d=>d.persist,()=>m()),()=>t.getPersistMetadata(),()=>t.getPersistMetadata()),s=_react.useCallback.call(void 0, async()=>t.restorePersisted(),[t]),o=_react.useCallback.call(void 0, async()=>{await t.forceSave()},[t]),u=_react.useCallback.call(void 0, async()=>{await t.clearPersisted()},[t]),i=_react.useMemo.call(void 0, ()=>({isSaving:e.isSaving,isRestoring:e.isRestoring,error:e.error}),[e]);return{restore:s,save:o,clear:u,meta:i}}function $t(t){let e=S(),s=_react.useRef.call(void 0, null);_react.useEffect.call(void 0, ()=>()=>{e.unregisterField&&e.unregisterField(t)},[e,t]);let o=_react.useCallback.call(void 0, ()=>{let n=e.getFieldState(t);if(s.current&&s.current.value===n.value&&s.current.error===n.error&&s.current.touched===n.touched&&s.current.isHidden===n.isHidden&&s.current.isRequired===n.isRequired&&s.current.isDirty===n.isDirty&&s.current.isValidating===n.isValidating)return s.current;let r={value:n.value,error:n.error,touched:n.touched,isHidden:n.isHidden,isRequired:n.isRequired,isDirty:n.isDirty,isValidating:n.isValidating};return s.current=r,r},[e,t]),u=_react.useCallback.call(void 0, n=>_chunkRFFMBY7Mcjs.b.call(void 0, e,t,()=>n()),[e,t]),i=_react.useSyncExternalStore.call(void 0, u,o,o),m=_react.useCallback.call(void 0, n=>e.setField(t,n),[e,t]),d=_react.useCallback.call(void 0, ()=>e.blurField(t),[e,t]);return{fieldState:i,setValue:m,setBlur:d,store:e}}exports.a = nt; exports.b = S; exports.c = mt; exports.d = $t; exports.e = ht; exports.f = Vt; exports.g = xt; exports.h = Ct; exports.i = qt;
2
- //# sourceMappingURL=chunk-ZO3GXKF3.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/bit-form/bit-form/dist/chunk-ZO3GXKF3.cjs","../src/react/context.tsx","../src/react/use-bit-form.ts","../src/react/use-bit-array.ts"],"names":["BitContext","createContext","BitFormProvider","store","children","jsx","resolveBitStoreForHooks","useBitStore","useContext","useBitForm","submitError","setSubmitError","useState","lastResponse","setLastResponse","lastMeta","useRef","getMetaSnapshot","useCallback","state","nextMeta","subscribeMeta","cb","metaState","useSyncExternalStore","controller","useMemo","createFormController","result","error","submit","onSubmit","reset","getValues","getErrors","getTouched","getDirtyValues","useBitArray","path","createId","index","idsRef","getSnapshot","value","getDeepValue","arrayValue","diff","_","i","subscribeArray","data","methods","newIds","from","to","item","indexA","indexB","items"],"mappings":"AAAA,qOAA+C,wDAAuD,8BCArD,+CAa/C,IATIA,CAAAA,CAAaC,kCAAAA,IAAgD,CAAA,CAEtDC,EAAAA,aAAkB,CAAC,CAC9B,KAAA,CAAAC,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAAA,EAIEC,6BAAAA,CAACL,CAAW,QAAA,CAAX,CAAoB,KAAA,CAAOM,iCAAAA,CAA6B,CAAA,CACtD,QAAA,CAAAF,CAAAA,CACH,CAAA,CAGWG,CAAAA,aAAc,CAAA,CAAA,EAAwB,CACjD,IAAMJ,CAAAA,CAAQK,+BAAAA,CAAqB,CAAA,CACnC,EAAA,CAAI,CAACL,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,6DACF,CAAA,CACF,OAAOA,CACT,CAAA,CCzBA,SAWgBM,EAAAA,CAAAA,CAAoD,CAClE,IAAMN,CAAAA,CAAQI,CAAAA,CAAe,CAAA,CAEvB,CAACG,CAAAA,CAAaC,CAAc,CAAA,CAAIC,6BAAAA,IAA2B,CAAA,CAC3D,CAACC,CAAAA,CAAcC,CAAe,CAAA,CAAIF,6BAAAA,IAAsB,CAAA,CACxDG,CAAAA,CAAWC,2BAAAA,IAIH,CAAA,CAERC,CAAAA,CAAkBC,gCAAAA,CAAY,CAAA,EAAM,CACxC,IAAMC,CAAAA,CAAQhB,CAAAA,CAAM,QAAA,CAAS,CAAA,CACvBiB,CAAAA,CAAW,CACf,OAAA,CAASD,CAAAA,CAAM,OAAA,CACf,OAAA,CAASA,CAAAA,CAAM,OAAA,CACf,YAAA,CAAcA,CAAAA,CAAM,YACtB,CAAA,CAEA,OACEJ,CAAAA,CAAS,OAAA,EACTA,CAAAA,CAAS,OAAA,CAAQ,OAAA,GAAYK,CAAAA,CAAS,OAAA,EACtCL,CAAAA,CAAS,OA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X,CAAAA,CAAGP,CAAAA,CAAAA,EAAUD,CAAAA,CAASC,CAAK,CAAC,CAAA,CACxDrC,CAAAA,CAAM,QAAA,CACJmC,CAAAA,CACAoB,CACF,CACF,CAAA,CACA,KAAA,CAAO,CAAA,CAAA,EAAM,CACXjB,CAAAA,CAAO,OAAA,CAAU,CAAC,CAAA,CAClBtC,CAAAA,CAAM,QAAA,CACJmC,CAAAA,CACA,CAAC,CACH,CACF,CACF,CAAA,CAAA,CACA,CAACnC,CAAAA,CAAOmC,CAAAA,CAAMC,CAAQ,CACxB,CAAA,CAYA,MAAO,CACL,MAAA,CAXab,4BAAAA,CACb,CAAA,EACGwB,CAAAA,CAAgB,GAAA,CAAI,CAACK,CAAAA,CAAYf,CAAAA,CAAAA,EAAAA,CAAmB,CACnD,GAAA,CAAKC,CAAAA,CAAO,OAAA,CAAQD,CAAK,CAAA,EAAK,CAAA,KAAA,EAAQA,CAAK,CAAA,CAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-ZO3GXKF3.cjs","sourcesContent":[null,"import React, { createContext, useContext } from \"react\";\nimport type { BitStoreApi, BitStoreHooksApi } from \"../core\";\nimport { resolveBitStoreForHooks } from \"../core\";\n\nconst BitContext = createContext<BitStoreHooksApi<any> | null>(null);\n\nexport const BitFormProvider = ({\n store,\n children,\n}: {\n store: BitStoreApi<any>;\n children: React.ReactNode;\n}) => (\n <BitContext.Provider value={resolveBitStoreForHooks(store)}>\n {children}\n </BitContext.Provider>\n);\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 BitStoreHooksApi<T>;\n};\n","import {\n useCallback,\n useSyncExternalStore,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { useBitStore } from \"./context\";\nimport { createFormController } from \"../core/form-controller\";\nimport type { UseBitFormResult } from \"./types\";\n\nexport function useBitForm<T extends object>(): UseBitFormResult<T> {\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 controller = useMemo(\n () =>\n createFormController(store, {\n clearSubmissionState: () => {\n setSubmitError(null);\n setLastResponse(null);\n },\n setSubmissionResult: (result) => {\n setLastResponse(result);\n },\n setSubmissionError: (error) => {\n setSubmitError(error);\n },\n }),\n [store],\n );\n\n const submit = useCallback(controller.submit, [controller]);\n const onSubmit = useCallback(controller.onSubmit, [controller]);\n const reset = useCallback(controller.reset, [controller]);\n\n const getValues = useCallback(controller.getValues, [controller]);\n const getErrors = useCallback(controller.getErrors, [controller]);\n const getTouched = useCallback(controller.getTouched, [controller]);\n const getDirtyValues = useCallback(controller.getDirtyValues, [controller]);\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 setError: store.setError.bind(store),\n setErrors: store.setErrors.bind(store),\n setServerErrors: store.setServerErrors.bind(store),\n validate: store.validate.bind(store),\n };\n}\n","import { useCallback, useSyncExternalStore, useRef, useMemo } from \"react\";\nimport { useBitStore } from \"./context\";\nimport {\n getDeepValue,\n BitArrayPath,\n BitPathValue,\n BitArrayItem,\n BitPath,\n} from \"../core\";\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 const createId = useCallback(\n (index?: number) =>\n store.config.idFactory({\n scope: \"array\",\n path: path as string,\n index,\n }),\n [store, path],\n );\n const idsRef = useRef<string[]>([]);\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 const arrayValue = Array.isArray(value) ? (value as Item[]) : [];\n\n if (arrayValue.length !== idsRef.current.length) {\n if (arrayValue.length > idsRef.current.length) {\n const diff = arrayValue.length - idsRef.current.length;\n idsRef.current = [\n ...idsRef.current,\n ...Array(diff)\n .fill(null)\n .map((_, i) => createId(idsRef.current.length + i)),\n ];\n } else {\n idsRef.current = idsRef.current.slice(0, arrayValue.length);\n }\n }\n\n return arrayValue;\n }, [store, path, createId]);\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 methods = useMemo(\n () => ({\n append: (value: Item) => {\n idsRef.current = [...idsRef.current, createId(idsRef.current.length)];\n store.pushItem(path, value);\n },\n prepend: (value: Item) => {\n idsRef.current = [createId(0), ...idsRef.current];\n store.prependItem(path, value);\n },\n insert: (index: number, value: Item) => {\n const newIds = [...idsRef.current];\n newIds.splice(index, 0, createId(index));\n idsRef.current = newIds;\n store.insertItem(path, index, value);\n },\n remove: (index: number) => {\n idsRef.current = idsRef.current.filter((_, i) => i !== index);\n store.removeItem(path, index);\n },\n move: (from: number, to: number) => {\n const newIds = [...idsRef.current];\n const [item] = newIds.splice(from, 1);\n newIds.splice(to, 0, item);\n idsRef.current = newIds;\n store.moveItem(path, from, to);\n },\n swap: (indexA: number, indexB: number) => {\n const newIds = [...idsRef.current];\n [newIds[indexA], newIds[indexB]] = [newIds[indexB], newIds[indexA]];\n idsRef.current = newIds;\n store.swapItems(path, indexA, indexB);\n },\n replace: (items: Item[]) => {\n idsRef.current = items.map((_, index) => createId(index));\n store.setField(\n path as unknown as BitPath<TForm>,\n items as unknown as BitPathValue<TForm, BitPath<TForm>>,\n );\n },\n clear: () => {\n idsRef.current = [];\n store.setField(\n path as unknown as BitPath<TForm>,\n [] as unknown as BitPathValue<TForm, BitPath<TForm>>,\n );\n },\n }),\n [store, path, createId],\n );\n\n const fields = useMemo(\n () =>\n (data as Item[]).map((item: Item, index: number) => ({\n key: idsRef.current[index] || `temp-${index}`,\n value: item,\n index,\n })),\n [data],\n );\n\n return {\n fields,\n length: data.length,\n ...methods,\n };\n}\n"]}