@lehnihon/bit-form 2.2.18 → 2.2.19

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 (136) hide show
  1. package/dist/angular/index.cjs +1 -1
  2. package/dist/angular/index.js +1 -1
  3. package/dist/angular/index.js.map +1 -1
  4. package/dist/chunk-23DHXQOC.js +2 -0
  5. package/dist/chunk-23DHXQOC.js.map +1 -0
  6. package/dist/{chunk-DD6XWUMR.cjs → chunk-27LJCW56.cjs} +2 -2
  7. package/dist/chunk-27LJCW56.cjs.map +1 -0
  8. package/dist/chunk-32RH5MSM.js +2 -0
  9. package/dist/chunk-32RH5MSM.js.map +1 -0
  10. package/dist/{chunk-P5YQ62YN.cjs → chunk-33TGLA5D.cjs} +2 -2
  11. package/dist/{chunk-P5YQ62YN.cjs.map → chunk-33TGLA5D.cjs.map} +1 -1
  12. package/dist/chunk-3CPIJF3Z.cjs +2 -0
  13. package/dist/chunk-3CPIJF3Z.cjs.map +1 -0
  14. package/dist/{chunk-SYEUXL2E.js → chunk-3WNZPBME.js} +2 -2
  15. package/dist/chunk-4WPLTOBT.cjs +2 -0
  16. package/dist/chunk-4WPLTOBT.cjs.map +1 -0
  17. package/dist/chunk-5ILGCBKG.cjs +2 -0
  18. package/dist/chunk-5ILGCBKG.cjs.map +1 -0
  19. package/dist/chunk-725CMNAV.cjs +2 -0
  20. package/dist/chunk-725CMNAV.cjs.map +1 -0
  21. package/dist/{chunk-GKNGJOB3.cjs → chunk-7IO2KLSJ.cjs} +2 -2
  22. package/dist/{chunk-GKNGJOB3.cjs.map → chunk-7IO2KLSJ.cjs.map} +1 -1
  23. package/dist/{chunk-HE6EQZTH.js → chunk-AJUX7LYB.js} +2 -2
  24. package/dist/chunk-B45EMB4Q.js +2 -0
  25. package/dist/chunk-B45EMB4Q.js.map +1 -0
  26. package/dist/chunk-CIS3YZSK.cjs +2 -0
  27. package/dist/chunk-CIS3YZSK.cjs.map +1 -0
  28. package/dist/chunk-DGEGYNQL.js +2 -0
  29. package/dist/{chunk-3NUJVIAM.js.map → chunk-DGEGYNQL.js.map} +1 -1
  30. package/dist/{chunk-AVUK52JW.cjs → chunk-EPBSLPRL.cjs} +2 -2
  31. package/dist/{chunk-AVUK52JW.cjs.map → chunk-EPBSLPRL.cjs.map} +1 -1
  32. package/dist/chunk-HTMNDK6W.js +2 -0
  33. package/dist/chunk-HTMNDK6W.js.map +1 -0
  34. package/dist/chunk-JUDBIEZK.js +2 -0
  35. package/dist/chunk-JUDBIEZK.js.map +1 -0
  36. package/dist/{chunk-77PK7U73.cjs → chunk-K2JSAJAF.cjs} +2 -2
  37. package/dist/chunk-K2JSAJAF.cjs.map +1 -0
  38. package/dist/chunk-K2KCQEER.js +2 -0
  39. package/dist/chunk-K2KCQEER.js.map +1 -0
  40. package/dist/chunk-K65TKDQ2.cjs +2 -0
  41. package/dist/chunk-K65TKDQ2.cjs.map +1 -0
  42. package/dist/chunk-S5A65JVL.cjs +2 -0
  43. package/dist/chunk-S5A65JVL.cjs.map +1 -0
  44. package/dist/chunk-SFVGMVIE.js +2 -0
  45. package/dist/chunk-SFVGMVIE.js.map +1 -0
  46. package/dist/chunk-T7TOEIOH.js +2 -0
  47. package/dist/chunk-T7TOEIOH.js.map +1 -0
  48. package/dist/chunk-TLUCO2ZN.cjs +2 -0
  49. package/dist/chunk-TLUCO2ZN.cjs.map +1 -0
  50. package/dist/chunk-WEZ5Q6YO.js +2 -0
  51. package/dist/chunk-WEZ5Q6YO.js.map +1 -0
  52. package/dist/{chunk-YO4TZ6N6.js → chunk-Y34N5TWV.js} +2 -2
  53. package/dist/cli/index.cjs +5 -5
  54. package/dist/core/bindings.cjs +1 -1
  55. package/dist/core/bindings.js +1 -1
  56. package/dist/core/store.cjs +1 -1
  57. package/dist/core/store.js +1 -1
  58. package/dist/core/utils.cjs +1 -1
  59. package/dist/core/utils.js +1 -1
  60. package/dist/core.cjs +1 -1
  61. package/dist/core.js +1 -1
  62. package/dist/devtools/bridge.cjs +1 -1
  63. package/dist/devtools/bridge.js +1 -1
  64. package/dist/devtools/index.cjs +10 -10
  65. package/dist/devtools/index.cjs.map +1 -1
  66. package/dist/devtools/index.js +10 -10
  67. package/dist/devtools/index.js.map +1 -1
  68. package/dist/index.cjs +1 -1
  69. package/dist/index.js +1 -1
  70. package/dist/mask.cjs +1 -1
  71. package/dist/mask.js +1 -1
  72. package/dist/react/index.cjs +1 -1
  73. package/dist/react/index.cjs.map +1 -1
  74. package/dist/react/index.js +1 -1
  75. package/dist/react/index.js.map +1 -1
  76. package/dist/react-native/index.cjs +1 -1
  77. package/dist/react-native/index.cjs.map +1 -1
  78. package/dist/react-native/index.js +1 -1
  79. package/dist/react-native/index.js.map +1 -1
  80. package/dist/resolvers/index.cjs +1 -1
  81. package/dist/resolvers/index.js +1 -1
  82. package/dist/resolvers/joi.cjs +1 -1
  83. package/dist/resolvers/joi.js +1 -1
  84. package/dist/resolvers/yup.cjs +1 -1
  85. package/dist/resolvers/yup.js +1 -1
  86. package/dist/resolvers/zod.cjs +1 -1
  87. package/dist/resolvers/zod.js +1 -1
  88. package/dist/utils.cjs +1 -1
  89. package/dist/utils.js +1 -1
  90. package/dist/vue/index.cjs +1 -1
  91. package/dist/vue/index.cjs.map +1 -1
  92. package/dist/vue/index.d.cts +18 -17
  93. package/dist/vue/index.d.ts +18 -17
  94. package/dist/vue/index.js +1 -1
  95. package/dist/vue/index.js.map +1 -1
  96. package/package.json +7 -6
  97. package/dist/chunk-3774TIGK.js +0 -2
  98. package/dist/chunk-3774TIGK.js.map +0 -1
  99. package/dist/chunk-3NUJVIAM.js +0 -2
  100. package/dist/chunk-77PK7U73.cjs.map +0 -1
  101. package/dist/chunk-CTURHI75.cjs +0 -2
  102. package/dist/chunk-CTURHI75.cjs.map +0 -1
  103. package/dist/chunk-DD6XWUMR.cjs.map +0 -1
  104. package/dist/chunk-FGJB4DHQ.js +0 -2
  105. package/dist/chunk-FGJB4DHQ.js.map +0 -1
  106. package/dist/chunk-FTXV2NZO.cjs +0 -2
  107. package/dist/chunk-FTXV2NZO.cjs.map +0 -1
  108. package/dist/chunk-G3EHXKOS.js +0 -2
  109. package/dist/chunk-G3EHXKOS.js.map +0 -1
  110. package/dist/chunk-GDRNKTHO.js +0 -2
  111. package/dist/chunk-GDRNKTHO.js.map +0 -1
  112. package/dist/chunk-GSZTHF7Z.js +0 -2
  113. package/dist/chunk-GSZTHF7Z.js.map +0 -1
  114. package/dist/chunk-GUU6EXFN.js +0 -2
  115. package/dist/chunk-GUU6EXFN.js.map +0 -1
  116. package/dist/chunk-L7EAZ6K6.cjs +0 -2
  117. package/dist/chunk-L7EAZ6K6.cjs.map +0 -1
  118. package/dist/chunk-LIHWJJIM.js +0 -2
  119. package/dist/chunk-LIHWJJIM.js.map +0 -1
  120. package/dist/chunk-M2XR4C7T.js +0 -2
  121. package/dist/chunk-M2XR4C7T.js.map +0 -1
  122. package/dist/chunk-PFPGASVZ.cjs +0 -2
  123. package/dist/chunk-PFPGASVZ.cjs.map +0 -1
  124. package/dist/chunk-QCKCONCU.js +0 -2
  125. package/dist/chunk-QCKCONCU.js.map +0 -1
  126. package/dist/chunk-RSH6LQVC.cjs +0 -2
  127. package/dist/chunk-RSH6LQVC.cjs.map +0 -1
  128. package/dist/chunk-U5TBWV74.cjs +0 -2
  129. package/dist/chunk-U5TBWV74.cjs.map +0 -1
  130. package/dist/chunk-UT63HKR6.cjs +0 -2
  131. package/dist/chunk-UT63HKR6.cjs.map +0 -1
  132. package/dist/chunk-WRNR6SXK.cjs +0 -2
  133. package/dist/chunk-WRNR6SXK.cjs.map +0 -1
  134. /package/dist/{chunk-SYEUXL2E.js.map → chunk-3WNZPBME.js.map} +0 -0
  135. /package/dist/{chunk-HE6EQZTH.js.map → chunk-AJUX7LYB.js.map} +0 -0
  136. /package/dist/{chunk-YO4TZ6N6.js.map → chunk-Y34N5TWV.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/store/engines/store-field-query-engine.ts","../src/core/store/orchestration/framework-store-brand.ts","../src/core/store/orchestration/hook-brand.ts","../src/core/store/managers/core/baseline-manager.ts","../src/core/store/managers/core/computed-manager.ts","../src/core/store/managers/core/dirty-manager.ts","../src/core/store/managers/features/mask-manager.ts","../src/core/store/shared/path-prefix.ts","../src/core/utils/path-wildcard.ts","../src/core/store/registry/field-catalog.ts","../src/core/store/registry/field-conditions.ts","../src/core/store/registry/field-registry.ts","../src/core/store/shared/config.ts","../src/core/utils/path-utils.ts","../src/core/store/shared/value-derivation-pipeline.ts","../src/core/store/engines/effect-engine.ts","../src/core/store/engines/effects/bus-effects.ts","../src/core/store/engines/effects/effect-registry.ts","../src/core/store/engines/effects/persist-effects.ts","../src/core/store/engines/effects/plugin-effects.ts","../src/core/store/managers/features/persist-manager.ts","../src/core/store/managers/features/plugin-manager.ts","../src/core/store/shared/bus.ts","../src/core/store/orchestration/store-effects-composition.ts","../src/core/store/engines/operation-engine.ts","../src/core/store/orchestration/store-persist-ops.ts","../src/core/store/engines/store-field-cleanup-engine.ts","../src/core/store/managers/core/computed-dependency-analyzer.ts","../src/core/store/orchestration/store-registration-ops.ts","../src/core/store/engines/subscription-engine.ts","../src/core/store/managers/features/array-manager.ts","../src/core/store/managers/features/error-manager.ts","../src/core/store/managers/features/field-query-manager.ts","../src/core/store/engines/snapshot-diff-engine.ts","../src/core/store/managers/features/history-manager.ts","../src/core/utils/error-utils.ts","../src/core/store/shared/pipeline.ts","../src/core/store/managers/features/lifecycle/field-update-manager.ts","../src/core/store/managers/features/lifecycle/lifecycle-orchestrator.ts","../src/core/store/managers/features/lifecycle/submit-lifecycle-manager.ts","../src/core/store/managers/features/lifecycle/values-lifecycle-manager.ts","../src/core/store/managers/features/lifecycle-manager.ts","../src/core/store/managers/features/scope-manager.ts","../src/core/store/managers/features/validation/async-validation-scheduler.ts","../src/core/store/shared/error-map.ts","../src/core/store/managers/features/validation/scope-validation-commit.ts","../src/core/store/managers/features/validation/validation-coordinator.ts","../src/core/store/managers/features/validation/validation-debouncer.ts","../src/core/store/managers/features/validation/validation-stages.ts","../src/core/store/managers/features/validation/validation-pipeline-stages.ts","../src/core/store/managers/features/validation/validation-pipeline-orchestrator.ts","../src/core/store/managers/features/validation-manager.ts","../src/core/store/orchestration/store-capability-registry.ts","../src/core/store/orchestration/store-bootstrap.ts","../src/core/store/orchestration/capability-ports.ts","../src/core/store/orchestration/store-runtime-feature-composition.ts","../src/core/store/orchestration/store-runtime.ts","../src/core/store/engines/store-batch-engine.ts","../src/core/store/orchestration/store-history-orchestrator.ts","../src/core/store/engines/state-update-engine.ts","../src/core/store/engines/store-commit-engine.ts","../src/core/store/orchestration/store-state-ops.ts","../src/core/store/orchestration/store-runtime-kernel.ts","../src/core/store/orchestration/store-composition-root.ts","../src/core/store/orchestration/store-feature-ops.ts","../src/core/store/orchestration/tracked-selector.ts","../src/core/store/orchestration/store-observe-ops.ts","../src/core/store/orchestration/store-domains.ts","../src/core/store/orchestration/store-slices-factory.ts","../src/core/store/shared/store-state-reader.ts","../src/core/store/bit-store-class.ts","../src/core/store/index.ts","../src/core/store/orchestration/create-store.ts","../src/core/store/orchestration/store-slice-extractors.ts"],"sourcesContent":["import type { BitMask, BitMaskName } from \"../../mask/types\";\nimport type {\n BitErrors,\n BitFieldDefinition,\n BitFieldState,\n BitPath,\n BitPathValue,\n BitState,\n} from \"../contracts/types\";\n\nexport function resolveFieldMask<T extends object>(args: {\n path: string;\n getFieldConfig: (path: string) => BitFieldDefinition<T> | undefined;\n masks: Record<BitMaskName, BitMask> | undefined;\n}): BitMask | undefined {\n const { path, getFieldConfig, masks } = args;\n const maskOption = getFieldConfig(path)?.mask;\n\n if (!maskOption) {\n return undefined;\n }\n\n if (typeof maskOption === \"string\") {\n return masks?.[maskOption as keyof typeof masks];\n }\n\n return maskOption;\n}\n\nexport function createFieldStateSnapshot<\n TForm extends object,\n P extends BitPath<TForm>,\n>(args: {\n state: Readonly<BitState<TForm>>;\n path: P;\n value: BitPathValue<TForm, P>;\n isHidden: boolean;\n isRequired: boolean;\n isDirty: boolean;\n isValidating: boolean;\n}): BitFieldState<TForm, BitPathValue<TForm, P>> {\n const { state, path, value, isHidden, isRequired, isDirty, isValidating } =\n args;\n const pathKey = path as string;\n\n return {\n value,\n error: state.errors[pathKey as keyof BitErrors<TForm>],\n touched: !!state.touched[pathKey as keyof typeof state.touched],\n isHidden,\n isRequired,\n isDirty,\n isValidating,\n };\n}\n","export const BIT_FRAMEWORK_STORE_SYMBOL = Symbol.for(\n \"bit-form.framework-store-api\",\n);\n","export const BIT_HOOKS_API_SYMBOL = Symbol.for(\"bit-form.hooks-api\");\n","import { deepClone } from \"../../../utils\";\n\nexport class BitBaselineManager<T extends object> {\n constructor(baselineValues: T) {\n this.baselineValues = deepClone(baselineValues);\n }\n\n private baselineValues: T;\n private baselineSnapshot?: Readonly<T>;\n\n getValues(): T {\n if (!this.baselineSnapshot) {\n this.baselineSnapshot = Object.freeze(deepClone(this.baselineValues));\n }\n\n return this.baselineSnapshot as T;\n }\n\n setValues(values: T): void {\n this.baselineValues = deepClone(values);\n this.baselineSnapshot = undefined;\n }\n}\n","import { deepEqual, getDeepValue, setDeepValue } from \"../../../utils\";\nimport type { BitComputedFn } from \"../../contracts/types\";\n\nexport interface BitComputedEntry<T extends object> {\n path: string;\n compute: BitComputedFn<T>;\n dependsOn: readonly string[];\n}\n\nexport class BitComputedManager<T extends object> {\n private equalityCache = new Map<\n string,\n { current: unknown; next: unknown; equal: boolean }\n >();\n private reverseDepsCache: Map<string, Set<string>> | null = null;\n private childDepsIndex: Map<string, Set<string>> | null = null;\n private validatedEntriesSignature: string | null = null;\n private validatedEntriesRef: BitComputedEntry<T>[] | null = null;\n private orderedAllEntriesCache: {\n signature: string;\n ordered: BitComputedEntry<T>[];\n } | null = null;\n private orderedIndexByPathCache: {\n signature: string;\n indexByPath: Map<string, number>;\n } | null = null;\n\n constructor(\n private getComputedEntries: (values: T) => BitComputedEntry<T>[],\n private onError?: (error: unknown, path: string) => void,\n ) {}\n\n private isCacheableScalar(value: unknown): boolean {\n return (\n value === null ||\n (typeof value !== \"object\" && typeof value !== \"function\")\n );\n }\n\n invalidateReverseDeps(): void {\n this.reverseDepsCache = null;\n this.childDepsIndex = null;\n this.orderedAllEntriesCache = null;\n this.validatedEntriesSignature = null;\n this.validatedEntriesRef = null;\n this.orderedIndexByPathCache = null;\n this.equalityCache.clear();\n }\n\n apply(values: T, changedPaths?: readonly string[]): T {\n const computedEntries = this.getComputedEntries(values);\n if (computedEntries.length === 0) return values;\n\n this.ensureEntriesAreValid(computedEntries);\n\n const entriesToRun = this.resolveEntriesToRun(\n computedEntries,\n changedPaths,\n );\n\n if (entriesToRun.length === 0) {\n return values;\n }\n\n let nextValues = values;\n const failedPaths = new Set<string>();\n\n for (const entry of entriesToRun) {\n // Skip this entry if any of its declared dependencies failed in this run.\n if (entry.dependsOn.some((dep) => failedPaths.has(dep))) {\n failedPaths.add(entry.path);\n continue;\n }\n\n let newValue: unknown;\n try {\n newValue = entry.compute(nextValues);\n } catch (error) {\n this.onError?.(error, entry.path);\n failedPaths.add(entry.path);\n continue;\n }\n const currentValue = getDeepValue(nextValues, entry.path);\n\n const cached = this.equalityCache.get(entry.path);\n let valuesEqual: boolean;\n const canUseScalarCache =\n this.isCacheableScalar(currentValue) &&\n this.isCacheableScalar(newValue);\n\n if (\n canUseScalarCache &&\n cached &&\n cached.current === currentValue &&\n cached.next === newValue\n ) {\n valuesEqual = cached.equal;\n } else {\n valuesEqual = deepEqual(currentValue, newValue);\n\n if (canUseScalarCache) {\n if (this.equalityCache.size > 1000) {\n this.equalityCache.clear();\n }\n this.equalityCache.set(entry.path, {\n current: currentValue,\n next: newValue,\n equal: valuesEqual,\n });\n } else {\n this.equalityCache.delete(entry.path);\n }\n }\n\n if (!valuesEqual) {\n nextValues = setDeepValue(nextValues, entry.path, newValue);\n }\n }\n return nextValues;\n }\n\n private getReverseDependencies(\n entries: BitComputedEntry<T>[],\n ): Map<string, Set<string>> {\n if (this.reverseDepsCache) return this.reverseDepsCache;\n\n const map = new Map<string, Set<string>>();\n\n for (const entry of entries) {\n for (const dep of entry.dependsOn) {\n let dependents = map.get(dep);\n if (!dependents) {\n dependents = new Set();\n map.set(dep, dependents);\n }\n dependents.add(entry.path);\n }\n }\n\n const childIdx = new Map<string, Set<string>>();\n\n for (const dep of map.keys()) {\n const segments = dep.split(\".\");\n for (let len = 1; len < segments.length; len++) {\n const prefix = segments.slice(0, len).join(\".\");\n let children = childIdx.get(prefix);\n if (!children) {\n children = new Set();\n childIdx.set(prefix, children);\n }\n children.add(dep);\n }\n }\n\n this.reverseDepsCache = map;\n this.childDepsIndex = childIdx;\n return map;\n }\n\n private resolveEntriesToRun(\n entries: BitComputedEntry<T>[],\n changedPaths?: readonly string[],\n ): BitComputedEntry<T>[] {\n if (\n !changedPaths ||\n changedPaths.length === 0 ||\n changedPaths.includes(\"*\")\n ) {\n return this.getOrderedAllEntries(entries);\n }\n\n const reverseDependencies = this.getReverseDependencies(entries);\n const affectedPaths = new Set<string>();\n const queue = [...changedPaths];\n let queueIndex = 0;\n\n while (queueIndex < queue.length) {\n const currentPath = queue[queueIndex++]!;\n const dependents = this.getDependentsForPath(\n reverseDependencies,\n currentPath,\n );\n\n if (!dependents) {\n continue;\n }\n\n for (const dependentPath of dependents) {\n if (affectedPaths.has(dependentPath)) {\n continue;\n }\n\n affectedPaths.add(dependentPath);\n queue.push(dependentPath);\n }\n }\n\n if (affectedPaths.size === 0) {\n return [];\n }\n\n const orderedAllEntries = this.getOrderedAllEntries(entries);\n const indexByPath = this.getOrderedIndexByPath(entries, orderedAllEntries);\n const affectedEntries: Array<{\n index: number;\n entry: BitComputedEntry<T>;\n }> = [];\n\n affectedPaths.forEach((path) => {\n const entryIndex = indexByPath.get(path);\n if (entryIndex === undefined) {\n return;\n }\n\n const entry = orderedAllEntries[entryIndex];\n if (!entry) {\n return;\n }\n\n affectedEntries.push({ index: entryIndex, entry });\n });\n\n affectedEntries.sort((left, right) => left.index - right.index);\n return affectedEntries.map((item) => item.entry);\n }\n\n private orderEntries(entries: BitComputedEntry<T>[]) {\n if (entries.length <= 1) {\n return entries;\n }\n\n const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));\n const inDegree = new Map<string, number>();\n const dependents = new Map<string, Set<string>>();\n\n entries.forEach((entry) => inDegree.set(entry.path, 0));\n\n entries.forEach((entry) => {\n entry.dependsOn.forEach((dependencyPath) => {\n if (!entryByPath.has(dependencyPath)) {\n return;\n }\n\n const nextDependents = dependents.get(dependencyPath) ?? new Set();\n if (!nextDependents.has(entry.path)) {\n nextDependents.add(entry.path);\n dependents.set(dependencyPath, nextDependents);\n inDegree.set(entry.path, (inDegree.get(entry.path) ?? 0) + 1);\n }\n });\n });\n\n const queue = entries\n .filter((entry) => (inDegree.get(entry.path) ?? 0) === 0)\n .map((entry) => entry.path);\n const orderedPaths: string[] = [];\n\n while (queue.length > 0) {\n const currentPath = queue.shift()!;\n orderedPaths.push(currentPath);\n\n const nextDependents = dependents.get(currentPath);\n if (!nextDependents) {\n continue;\n }\n\n nextDependents.forEach((dependentPath) => {\n const nextDegree = (inDegree.get(dependentPath) ?? 0) - 1;\n inDegree.set(dependentPath, nextDegree);\n\n if (nextDegree === 0) {\n queue.push(dependentPath);\n }\n });\n }\n\n if (orderedPaths.length !== entries.length) {\n throw new Error(\n \"BitStore: cyclic computed dependencies detected. Check computedDependsOn definitions.\",\n );\n }\n\n return orderedPaths.map((path) => entryByPath.get(path)!);\n }\n\n private getOrderedAllEntries(entries: BitComputedEntry<T>[]) {\n const signature = this.createEntriesSignature(entries);\n if (\n this.orderedAllEntriesCache &&\n this.orderedAllEntriesCache.signature === signature\n ) {\n return this.orderedAllEntriesCache.ordered;\n }\n\n const ordered = this.orderEntries(entries);\n this.orderedAllEntriesCache = { signature, ordered };\n return ordered;\n }\n\n private getOrderedIndexByPath(\n entries: BitComputedEntry<T>[],\n orderedEntries: BitComputedEntry<T>[],\n ): Map<string, number> {\n const signature = this.createEntriesSignature(entries);\n if (\n this.orderedIndexByPathCache &&\n this.orderedIndexByPathCache.signature === signature\n ) {\n return this.orderedIndexByPathCache.indexByPath;\n }\n\n const indexByPath = new Map<string, number>();\n orderedEntries.forEach((entry, index) => {\n indexByPath.set(entry.path, index);\n });\n\n this.orderedIndexByPathCache = { signature, indexByPath };\n return indexByPath;\n }\n\n private ensureEntriesAreValid(entries: BitComputedEntry<T>[]) {\n if (this.validatedEntriesRef === entries) {\n return;\n }\n\n const signature = this.createEntriesSignature(entries);\n if (this.validatedEntriesSignature === signature) {\n this.validatedEntriesRef = entries;\n return;\n }\n\n entries.forEach((entry) => this.assertDependencies(entry));\n this.invalidateReverseDeps();\n this.validatedEntriesSignature = signature;\n this.validatedEntriesRef = entries;\n }\n\n private createEntriesSignature(entries: BitComputedEntry<T>[]): string {\n return entries\n .map((entry) => `${entry.path}:${entry.dependsOn.join(\",\")}`)\n .join(\"|\");\n }\n\n private getDependentsForPath(\n reverseDependencies: Map<string, Set<string>>,\n changedPath: string,\n ) {\n const dependents = new Set<string>();\n\n const collect = (dependencyPath: string) => {\n const listeners = reverseDependencies.get(dependencyPath);\n if (!listeners) {\n return;\n }\n\n listeners.forEach((path) => dependents.add(path));\n };\n\n collect(changedPath);\n\n const parentSegments = changedPath.split(\".\");\n while (parentSegments.length > 1) {\n parentSegments.pop();\n collect(parentSegments.join(\".\"));\n }\n\n const childKeys = this.childDepsIndex?.get(changedPath);\n if (childKeys) {\n for (const childDep of childKeys) {\n collect(childDep);\n }\n }\n\n return dependents;\n }\n\n private assertDependencies(entry: BitComputedEntry<T>) {\n if (entry.dependsOn.length === 0) {\n throw new Error(\n `BitStore: computed field \\`${entry.path}\\` requires explicit computedDependsOn in v4.`,\n );\n }\n\n if (entry.dependsOn.includes(entry.path)) {\n throw new Error(\n `BitStore: computed field \\`${entry.path}\\` cannot depend on itself.`,\n );\n }\n }\n}\n","import {\n collectDirtyPaths,\n getDeepValue,\n setDeepValues,\n valueEqual,\n} from \"../../../utils\";\n\n/**\n * BitDirtyManager\n *\n * Manages dirty state tracking for form fields.\n * Tracks which fields have been modified from their initial values.\n */\nexport class BitDirtyManager<T extends object = Record<string, unknown>> {\n private dirtyPaths: Set<string> = new Set();\n private dirtyPathIndex: Set<string> = new Set();\n private dirtyPrefixRefCount: Map<string, number> = new Map();\n /** Maps each strict ancestor prefix → set of dirty paths that are its descendants. */\n private childrenByPrefix: Map<string, Set<string>> = new Map();\n\n /**\n * Updates dirty state for a single path change.\n * Automatically removes child paths when parent changes.\n * @returns true if any fields are dirty\n */\n updateForPath(path: string, values: T, initialValues: T): boolean {\n this.removeDirtyChildren(path);\n\n const current = getDeepValue(values, path);\n const initial = getDeepValue(initialValues, path);\n\n if (valueEqual(current, initial)) {\n this.removeDirtyPath(path);\n } else {\n this.addDirtyPath(path);\n }\n\n return this.dirtyPaths.size > 0;\n }\n\n /**\n * Rebuilds dirty paths from full state comparison.\n * Used for undo/redo and bulk updates.\n * @returns true if any fields are dirty\n */\n rebuild(values: T, initialValues: T): boolean {\n this.dirtyPaths = collectDirtyPaths(values, initialValues);\n this.dirtyPrefixRefCount.clear();\n this.rebuildIndex();\n return this.dirtyPaths.size > 0;\n }\n\n /**\n * Clears all dirty tracking.\n * Used when resetting form or updating initial values.\n */\n clear(): void {\n this.dirtyPaths.clear();\n this.dirtyPathIndex.clear();\n this.dirtyPrefixRefCount.clear();\n this.childrenByPrefix.clear();\n }\n\n /**\n * Returns current dirty state.\n */\n get isDirty(): boolean {\n return this.dirtyPaths.size > 0;\n }\n\n /**\n * Returns readonly set of dirty paths (for debugging/devtools).\n */\n getDirtyPaths(): ReadonlySet<string> {\n return this.dirtyPaths;\n }\n\n isPathDirty(path: string): boolean {\n // Check if exact path is dirty\n if (this.dirtyPathIndex.has(path)) {\n return true;\n }\n\n // Check if any ancestor prefix is dirty using refcount (O(1) instead of O(depth))\n let separatorIndex = path.lastIndexOf(\".\");\n while (separatorIndex > -1) {\n const ancestorPath = path.slice(0, separatorIndex);\n if ((this.dirtyPrefixRefCount.get(ancestorPath) ?? 0) > 0) {\n return true;\n }\n separatorIndex = path.lastIndexOf(\".\", separatorIndex - 1);\n }\n\n return false;\n }\n\n /**\n * Builds a partial object containing only dirty values.\n * For arrays, returns the entire array if any index changed.\n * @param values - current form values (already cleaned/transformed)\n */\n buildDirtyValues<T extends object>(values: T): Partial<T> {\n if (this.dirtyPaths.size === 0) return {};\n\n const updates: Array<readonly [string, unknown]> = [];\n const sortedPaths = [...this.dirtyPaths].sort();\n const processedArrays = new Set<string>();\n const includedPaths = new Set<string>();\n\n const isDescendantOfIncludedPath = (path: string) => {\n let separatorIndex = path.lastIndexOf(\".\");\n\n while (separatorIndex > -1) {\n if (includedPaths.has(path.slice(0, separatorIndex))) {\n return true;\n }\n\n separatorIndex = path.lastIndexOf(\".\", separatorIndex - 1);\n }\n\n return false;\n };\n\n for (const path of sortedPaths) {\n if (isDescendantOfIncludedPath(path)) {\n continue;\n }\n\n const arrayMatch = path.match(/^(.+)\\.\\d+/);\n\n if (arrayMatch) {\n const arrayPath = arrayMatch[1];\n if (processedArrays.has(arrayPath)) continue;\n processedArrays.add(arrayPath);\n const arrayVal = getDeepValue(values, arrayPath);\n updates.push([arrayPath, arrayVal]);\n includedPaths.add(arrayPath);\n } else {\n const fieldVal = getDeepValue(values, path);\n updates.push([path, fieldVal]);\n includedPaths.add(path);\n }\n }\n\n if (updates.length === 0) {\n return {};\n }\n\n return setDeepValues({}, updates) as Partial<T>;\n }\n\n private rebuildIndex() {\n const nextIndex = new Set<string>();\n const nextRefCount = new Map<string, number>();\n const nextChildrenByPrefix = new Map<string, Set<string>>();\n\n for (const dirtyPath of this.dirtyPaths) {\n this.forEachPathPrefix(dirtyPath, (prefix) => {\n nextIndex.add(prefix);\n nextRefCount.set(prefix, (nextRefCount.get(prefix) ?? 0) + 1);\n });\n\n this.forEachAncestorPrefix(dirtyPath, (ancestor) => {\n const set = nextChildrenByPrefix.get(ancestor);\n if (set) {\n set.add(dirtyPath);\n } else {\n nextChildrenByPrefix.set(ancestor, new Set([dirtyPath]));\n }\n });\n }\n\n this.dirtyPathIndex = nextIndex;\n this.dirtyPrefixRefCount = nextRefCount;\n this.childrenByPrefix = nextChildrenByPrefix;\n }\n\n private removeDirtyChildren(parentPath: string) {\n const children = this.childrenByPrefix.get(parentPath);\n if (!children || children.size === 0) return;\n\n // Snapshot to avoid mutating the set while iterating\n for (const path of [...children]) {\n this.removeDirtyPath(path);\n }\n }\n\n private addDirtyPath(path: string) {\n if (this.dirtyPaths.has(path)) {\n return;\n }\n\n this.dirtyPaths.add(path);\n this.forEachPathPrefix(path, (prefix) => {\n this.dirtyPathIndex.add(prefix);\n this.dirtyPrefixRefCount.set(\n prefix,\n (this.dirtyPrefixRefCount.get(prefix) ?? 0) + 1,\n );\n });\n\n // Keep childrenByPrefix up to date for O(1) removeDirtyChildren\n this.forEachAncestorPrefix(path, (ancestor) => {\n const set = this.childrenByPrefix.get(ancestor);\n if (set) {\n set.add(path);\n } else {\n this.childrenByPrefix.set(ancestor, new Set([path]));\n }\n });\n }\n\n private removeDirtyPath(path: string) {\n if (!this.dirtyPaths.has(path)) {\n return;\n }\n\n this.dirtyPaths.delete(path);\n\n this.forEachPathPrefix(path, (prefix) => {\n const nextCount = (this.dirtyPrefixRefCount.get(prefix) ?? 0) - 1;\n\n if (nextCount <= 0) {\n this.dirtyPrefixRefCount.delete(prefix);\n this.dirtyPathIndex.delete(prefix);\n return;\n }\n\n this.dirtyPrefixRefCount.set(prefix, nextCount);\n });\n\n // Remove from childrenByPrefix\n this.forEachAncestorPrefix(path, (ancestor) => {\n this.childrenByPrefix.get(ancestor)?.delete(path);\n });\n }\n\n private forEachPathPrefix(path: string, callback: (prefix: string) => void) {\n const segments = path.split(\".\");\n let current = \"\";\n\n for (const segment of segments) {\n current = current ? `${current}.${segment}` : segment;\n callback(current);\n }\n }\n\n /**\n * Iterates over all strict ancestor prefixes of `path` (i.e., excludes the path itself).\n * Used to maintain childrenByPrefix.\n */\n private forEachAncestorPrefix(\n path: string,\n callback: (prefix: string) => void,\n ) {\n const segments = path.split(\".\");\n let current = \"\";\n\n for (let i = 0; i < segments.length - 1; i++) {\n current = current ? `${current}.${segments[i]}` : segments[i];\n callback(current);\n }\n }\n}\n","import { bitMasks } from \"../../../mask/built-ins\";\nimport { BitMask, BitMaskName } from \"../../../mask/types\";\n\n/**\n * BitMaskManager\n *\n * Manages input mask registration and resolution.\n * Decoupled from BitStore to reduce main class complexity.\n *\n * Responsibilities:\n * - Register/unregister masks\n * - Resolve masks by name\n */\nexport class BitMaskManager {\n private masks: Map<string, BitMask> = new Map();\n\n constructor() {\n Object.entries(bitMasks).forEach(([name, mask]) => {\n this.masks.set(name, mask);\n });\n }\n\n /**\n * Register a new input mask\n *\n * @param name - Unique mask identifier\n * @param mask - Mask configuration/pattern\n */\n registerMask(name: BitMaskName, mask: BitMask): void {\n this.masks.set(name, mask);\n }\n\n /**\n * Unregister an existing mask\n *\n * @param name - Mask identifier to remove\n */\n unregisterMask(name: BitMaskName): void {\n if (!this.masks.has(name)) {\n return; // Silently ignore non-existent masks\n }\n\n this.masks.delete(name);\n }\n\n /**\n * Get mask configuration by name\n *\n * @param name - Mask identifier\n * @returns Mask configuration or undefined if not found\n */\n resolveMask(name: BitMaskName): BitMask | undefined {\n return this.masks.get(name);\n }\n\n /**\n * Get all registered masks\n *\n * @returns Object map of all registered masks\n */\n getAllMasks(): Record<string, BitMask> {\n return Object.fromEntries(this.masks.entries());\n }\n\n /**\n * Clear all registered masks\n */\n clear(): void {\n this.masks.clear();\n }\n}\n","function stripTrailingSeparators(path: string): string {\n if (path == null) return \"\";\n return path.replace(/\\.+$/g, \"\");\n}\n\nexport function normalizePathPrefix(prefix: string): string {\n if (prefix == null) return \"\";\n return stripTrailingSeparators(prefix.trim());\n}\n\nexport function isPathWithinPrefix(path: string, prefix: string): boolean {\n if (path == null || prefix == null) return false;\n const normalizedPrefix = normalizePathPrefix(prefix);\n\n if (normalizedPrefix.length === 0) {\n return false;\n }\n\n return path === normalizedPrefix || path.startsWith(`${normalizedPrefix}.`);\n}\n\nexport function toPathPrefix(path: string, index?: number): string {\n if (path == null) return \"\";\n if (index === undefined) {\n return normalizePathPrefix(path);\n }\n\n return normalizePathPrefix(`${path}.${index}`);\n}\n","import { getDeepValue } from \"./path-value\";\n\nexport function isWildcardPath(path: string): boolean {\n return path.includes(\".*.\") || path.endsWith(\".*\");\n}\n\nexport function createWildcardRegex(wildcardPath: string): RegExp {\n const escaped = wildcardPath.replace(/\\./g, \"\\\\.\");\n const regexStr = escaped.replace(/\\*/g, \"\\\\d+\");\n return new RegExp(`^${regexStr}$`);\n}\n\nexport function expandWildcardPaths(\n wildcardPath: string,\n values: unknown,\n): string[] {\n if (!isWildcardPath(wildcardPath)) {\n return [wildcardPath];\n }\n\n const pathSegments = wildcardPath.split(\".\");\n let currentPaths: string[] = [\"\"];\n\n for (let i = 0; i < pathSegments.length; i++) {\n const seg = pathSegments[i];\n const nextPaths: string[] = [];\n\n for (const p of currentPaths) {\n if (seg === \"*\") {\n const arrayPrefix = p.replace(/\\.$/, \"\");\n const arr = arrayPrefix ? getDeepValue(values as object, arrayPrefix) : values;\n\n if (Array.isArray(arr) && arr.length > 0) {\n for (let idx = 0; idx < arr.length; idx++) {\n nextPaths.push(`${p}${idx}.`);\n }\n }\n } else {\n nextPaths.push(`${p}${seg}.`);\n }\n }\n\n currentPaths = nextPaths;\n }\n\n return currentPaths.map((p) => p.replace(/\\.$/, \"\"));\n}\n\nexport function resolveWildcardDependency(\n dependencyPattern: string,\n concretePath: string,\n fieldPattern: string,\n): string {\n if (!isWildcardPath(dependencyPattern) || !isWildcardPath(fieldPattern)) {\n return dependencyPattern;\n }\n\n const fieldRegexStr = fieldPattern\n .replace(/\\./g, \"\\\\.\")\n .replace(/\\*/g, \"(\\\\d+)\");\n const fieldRegex = new RegExp(`^${fieldRegexStr}$`);\n const match = concretePath.match(fieldRegex);\n\n if (!match) {\n return dependencyPattern;\n }\n\n const wildcardValues = match.slice(1);\n let valueIndex = 0;\n const segments = dependencyPattern.split(\"*\");\n let result = segments[0];\n\n for (let i = 1; i < segments.length; i++) {\n const val =\n valueIndex < wildcardValues.length ? wildcardValues[valueIndex++] : \"*\";\n result += val + segments[i];\n }\n\n return result;\n}\n","import type {\n BitFieldDefinition,\n BitNormalizeFn,\n BitTransformFn,\n} from \"../contracts/types\";\nimport type { BitComputedEntry } from \"../managers/core/computed-manager\";\nimport {\n createWildcardRegex,\n expandWildcardPaths,\n isWildcardPath,\n resolveWildcardDependency,\n} from \"../../utils/path-wildcard\";\n\nexport interface BitNormalizerEntry<\n T extends object = Record<string, unknown>,\n> {\n path: string;\n normalize: BitNormalizeFn<T>;\n dependsOn: readonly string[];\n}\n\nexport class BitFieldCatalog<T extends object = Record<string, unknown>> {\n private readonly fieldConfigs: Map<string, BitFieldDefinition<T>> = new Map();\n private readonly wildcardConfigs: Map<string, BitFieldDefinition<T>> = new Map();\n private readonly wildcardRegexes: Map<string, RegExp> = new Map();\n\n private scopeFieldsIndex: Map<string, Set<string>> | null = null;\n private computedEntriesCache: BitComputedEntry<T>[] | null = null;\n private normalizerEntriesCache: BitNormalizerEntry<T>[] | null = null;\n private transformEntriesCache: [string, BitTransformFn<T>][] | null = null;\n\n get(path: string): BitFieldDefinition<T> | undefined {\n const exact = this.fieldConfigs.get(path);\n if (exact) {\n return exact;\n }\n\n for (const [pattern, config] of this.wildcardConfigs.entries()) {\n const regex = this.wildcardRegexes.get(pattern);\n if (regex && regex.test(path)) {\n return config;\n }\n }\n\n return undefined;\n }\n\n set(path: string, config: BitFieldDefinition<T>) {\n if (isWildcardPath(path)) {\n this.wildcardConfigs.set(path, config);\n this.wildcardRegexes.set(path, createWildcardRegex(path));\n } else {\n this.fieldConfigs.set(path, config);\n }\n this.registerCachedIndexes(path, config);\n }\n\n delete(path: string): BitFieldDefinition<T> | undefined {\n let config: BitFieldDefinition<T> | undefined;\n\n if (isWildcardPath(path)) {\n config = this.wildcardConfigs.get(path);\n this.wildcardConfigs.delete(path);\n this.wildcardRegexes.delete(path);\n } else {\n config = this.fieldConfigs.get(path);\n this.fieldConfigs.delete(path);\n }\n\n this.unregisterCachedIndexes(path, config);\n return config;\n }\n\n has(path: string): boolean {\n if (this.fieldConfigs.has(path)) return true;\n if (this.wildcardConfigs.has(path)) return true;\n for (const regex of this.wildcardRegexes.values()) {\n if (regex.test(path)) return true;\n }\n return false;\n }\n\n forEach(callback: (config: BitFieldDefinition<T>, path: string) => void) {\n this.fieldConfigs.forEach((config, path) => callback(config, path));\n this.wildcardConfigs.forEach((config, path) => callback(config, path));\n }\n\n entries(): [string, BitFieldDefinition<T>][] {\n return [\n ...Array.from(this.fieldConfigs.entries()),\n ...Array.from(this.wildcardConfigs.entries()),\n ];\n }\n\n getScopeFields(scopeName: string, values: T): string[] {\n if (!this.scopeFieldsIndex) {\n const index = new Map<string, Set<string>>();\n this.forEach((cfg, path) => {\n if (!cfg.scope) {\n return;\n }\n const list = index.get(cfg.scope) ?? new Set<string>();\n list.add(path);\n index.set(cfg.scope, list);\n });\n this.scopeFieldsIndex = index;\n }\n\n const paths = Array.from(this.scopeFieldsIndex.get(scopeName) ?? []);\n if (paths.length === 0) return [];\n\n const result = new Set<string>();\n for (const path of paths) {\n if (isWildcardPath(path)) {\n const expanded = expandWildcardPaths(path, values);\n expanded.forEach((p) => result.add(p));\n } else {\n result.add(path);\n }\n }\n\n return Array.from(result);\n }\n\n getComputedEntries(values: T): BitComputedEntry<T>[] {\n if (!this.computedEntriesCache) {\n const result: BitComputedEntry<T>[] = [];\n this.forEach((cfg, path) => {\n if (cfg.computed) {\n result.push({\n path,\n compute: cfg.computed,\n dependsOn: cfg.computedDependsOn,\n });\n }\n });\n this.computedEntriesCache = result;\n }\n\n const finalEntries: BitComputedEntry<T>[] = [];\n for (const entry of this.computedEntriesCache) {\n if (isWildcardPath(entry.path)) {\n const expanded = expandWildcardPaths(entry.path, values);\n for (const concretePath of expanded) {\n finalEntries.push({\n path: concretePath,\n compute: (vals) => entry.compute(vals, concretePath),\n dependsOn: entry.dependsOn.map((dep) =>\n resolveWildcardDependency(dep, concretePath, entry.path),\n ),\n });\n }\n } else {\n finalEntries.push({\n path: entry.path,\n compute: (vals) => entry.compute(vals, entry.path),\n dependsOn: entry.dependsOn,\n });\n }\n }\n\n return finalEntries;\n }\n\n getTransformEntries(values: T): [string, BitTransformFn<T>][] {\n if (!this.transformEntriesCache) {\n const result: [string, BitTransformFn<T>][] = [];\n this.forEach((cfg, path) => {\n if (cfg.transform) {\n result.push([path, cfg.transform]);\n }\n });\n this.transformEntriesCache = result;\n }\n\n const finalEntries: [string, BitTransformFn<T>][] = [];\n for (const [path, transformFn] of this.transformEntriesCache) {\n if (isWildcardPath(path)) {\n const expanded = expandWildcardPaths(path, values);\n for (const concretePath of expanded) {\n finalEntries.push([\n concretePath,\n (val, allValues) => transformFn(val, allValues, concretePath) as unknown,\n ]);\n }\n } else {\n finalEntries.push([\n path,\n (val, allValues) => transformFn(val, allValues, path) as unknown,\n ]);\n }\n }\n\n return finalEntries;\n }\n\n getNormalizerEntries(values: T): BitNormalizerEntry<T>[] {\n if (!this.normalizerEntriesCache) {\n const result: BitNormalizerEntry<T>[] = [];\n this.forEach((cfg, path) => {\n if (cfg.normalize) {\n result.push({\n path,\n normalize: cfg.normalize,\n dependsOn: cfg.normalizeDependsOn?.length\n ? cfg.normalizeDependsOn\n : [path],\n });\n }\n });\n this.normalizerEntriesCache = result;\n }\n\n const finalEntries: BitNormalizerEntry<T>[] = [];\n for (const entry of this.normalizerEntriesCache) {\n if (isWildcardPath(entry.path)) {\n const expanded = expandWildcardPaths(entry.path, values);\n for (const concretePath of expanded) {\n finalEntries.push({\n path: concretePath,\n normalize: (val, allValues) =>\n entry.normalize(val, allValues, concretePath) as unknown,\n dependsOn: entry.dependsOn.map((dep) =>\n resolveWildcardDependency(dep, concretePath, entry.path),\n ),\n });\n }\n } else {\n finalEntries.push({\n path: entry.path,\n normalize: (val, allValues) =>\n entry.normalize(val, allValues, entry.path) as unknown,\n dependsOn: entry.dependsOn,\n });\n }\n }\n\n return finalEntries;\n }\n\n invalidateIndexes() {\n this.scopeFieldsIndex = null;\n this.computedEntriesCache = null;\n this.normalizerEntriesCache = null;\n this.transformEntriesCache = null;\n }\n\n private registerCachedIndexes(path: string, config: BitFieldDefinition<T>) {\n if (this.scopeFieldsIndex && config.scope) {\n const scopedPaths =\n this.scopeFieldsIndex.get(config.scope) ?? new Set<string>();\n scopedPaths.add(path);\n this.scopeFieldsIndex.set(config.scope, scopedPaths);\n }\n\n if (this.computedEntriesCache && config.computed) {\n this.computedEntriesCache.push({\n path,\n compute: config.computed,\n dependsOn: config.computedDependsOn,\n });\n }\n\n if (this.normalizerEntriesCache && config.normalize) {\n this.normalizerEntriesCache.push({\n path,\n normalize: config.normalize,\n dependsOn: config.normalizeDependsOn?.length\n ? config.normalizeDependsOn\n : [path],\n });\n }\n\n if (this.transformEntriesCache && config.transform) {\n this.transformEntriesCache.push([path, config.transform]);\n }\n }\n\n private unregisterCachedIndexes(\n path: string,\n config?: BitFieldDefinition<T>,\n ) {\n if (!config) {\n this.invalidateIndexes();\n return;\n }\n\n if (this.scopeFieldsIndex && config.scope) {\n const scopedPaths = this.scopeFieldsIndex.get(config.scope);\n if (scopedPaths) {\n scopedPaths.delete(path);\n\n if (scopedPaths.size > 0) {\n this.scopeFieldsIndex.set(config.scope, scopedPaths);\n } else {\n this.scopeFieldsIndex.delete(config.scope);\n }\n }\n }\n\n if (this.computedEntriesCache && config.computed) {\n this.computedEntriesCache = this.computedEntriesCache.filter(\n (entry) => entry.path !== path,\n );\n }\n\n if (this.normalizerEntriesCache && config.normalize) {\n this.normalizerEntriesCache = this.normalizerEntriesCache.filter(\n (entry) => entry.path !== path,\n );\n }\n\n if (this.transformEntriesCache && config.transform) {\n this.transformEntriesCache = this.transformEntriesCache.filter(\n ([entryPath]) => entryPath !== path,\n );\n }\n }\n}\n","import { deepEqual, getDeepValue } from \"../../utils\";\nimport type { BitDependencyUpdateDiff } from \"../contracts/port-types\";\nimport type { BitErrors, BitFieldDefinition } from \"../contracts/types\";\n\nexport class BitFieldConditions<T extends object = Record<string, unknown>> {\n private readonly dependencies: Map<string, Set<string>> = new Map();\n private readonly hiddenFields: Set<string> = new Set();\n private readonly conditionalVisibilityPaths: Set<string> = new Set();\n private readonly requiredPathsByDependency: Map<string, Set<string>> =\n new Map();\n private readonly requiredConditionalPaths: Set<string> = new Set();\n private requiredEvaluationVersion = 0;\n private readonly requiredEvaluationCache = new Map<\n string,\n {\n version: number;\n valuesRef: T;\n result: boolean;\n }\n >();\n\n constructor(\n private readonly getFieldConfig: (\n path: string,\n ) => BitFieldDefinition<T> | undefined,\n private readonly onConditionError?: (args: {\n path: string;\n kind: \"showIf\" | \"requiredIf\";\n error: unknown;\n }) => void,\n ) {}\n\n getHiddenFields(): ReadonlySet<string> {\n return this.hiddenFields;\n }\n\n onRegister(\n path: string,\n config: BitFieldDefinition<T>,\n currentValues: T,\n ): boolean {\n const hasShowIf = !!config.conditional?.showIf;\n const dependsOn = config.conditional?.dependsOn;\n if (dependsOn) {\n // CRITICAL: Detect circular dependencies early to prevent O(n²) complexity in updateDependencies\n if (this.wouldCreateCycle(path, dependsOn)) {\n const error = new Error(\n `Circular dependency detected: \"${path}\" → [${dependsOn.join(\", \")}]`,\n );\n this.onConditionError?.({ path, kind: \"showIf\", error });\n // Fail-safe for production: only visibility-driven fields become hidden on cycle.\n if (hasShowIf) {\n this.hiddenFields.add(path);\n }\n this.conditionalVisibilityPaths.delete(path);\n this.requiredConditionalPaths.delete(path);\n return false;\n }\n\n dependsOn.forEach((dep) => {\n if (!this.dependencies.has(dep)) {\n this.dependencies.set(dep, new Set());\n }\n this.dependencies.get(dep)!.add(path);\n });\n }\n\n if (hasShowIf) {\n this.conditionalVisibilityPaths.add(path);\n }\n\n if (dependsOn && config.conditional?.requiredIf) {\n this.requiredConditionalPaths.add(path);\n dependsOn.forEach((dep) => {\n if (!this.requiredPathsByDependency.has(dep)) {\n this.requiredPathsByDependency.set(dep, new Set());\n }\n this.requiredPathsByDependency.get(dep)!.add(path);\n });\n }\n\n this.requiredEvaluationVersion += 1;\n this.requiredEvaluationCache.clear();\n this.evaluateFieldCondition(path, currentValues);\n\n return true;\n }\n\n onUnregister(\n path: string,\n config?: BitFieldDefinition<T>,\n options?: { preserveIncomingDependents?: boolean },\n ) {\n this.hiddenFields.delete(path);\n this.conditionalVisibilityPaths.delete(path);\n if (!options?.preserveIncomingDependents) {\n this.dependencies.delete(path);\n }\n this.requiredEvaluationVersion += 1;\n this.requiredEvaluationCache.clear();\n this.requiredConditionalPaths.delete(path);\n\n config?.conditional?.dependsOn?.forEach((dep) => {\n const requiredPaths = this.requiredPathsByDependency.get(dep);\n if (!requiredPaths) {\n return;\n }\n\n requiredPaths.delete(path);\n if (requiredPaths.size === 0) {\n this.requiredPathsByDependency.delete(dep);\n }\n });\n\n this.dependencies.forEach((dependentsSet) => {\n dependentsSet.delete(path);\n });\n }\n\n isHidden(path: string): boolean {\n return this.hiddenFields.has(path);\n }\n\n hasDependents(path: string): boolean {\n return (this.dependencies.get(path)?.size ?? 0) > 0;\n }\n\n isRequired(path: string, values: T): boolean {\n const config = this.getFieldConfig(path);\n if (!config || this.isHidden(path)) return false;\n\n if (!config.conditional?.requiredIf) {\n return false;\n }\n\n const cached = this.requiredEvaluationCache.get(path);\n if (\n cached &&\n cached.version === this.requiredEvaluationVersion &&\n deepEqual(cached.valuesRef, values)\n ) {\n return cached.result;\n }\n\n let result = false;\n\n try {\n result = !!config.conditional.requiredIf(values);\n } catch (error) {\n this.onConditionError?.({ path, kind: \"requiredIf\", error });\n }\n\n this.requiredEvaluationCache.set(path, {\n version: this.requiredEvaluationVersion,\n valuesRef: values,\n result,\n });\n return result;\n }\n\n getRequiredErrors(values: T): BitErrors<T> {\n const errors: BitErrors<T> = {};\n\n this.requiredConditionalPaths.forEach((path) => {\n const config = this.getFieldConfig(path);\n if (!config) {\n return;\n }\n\n // CRITICAL: Do not set error for hidden fields - prevents invisible validation errors\n if (this.isHidden(path)) {\n return;\n }\n\n if (this.isRequired(path, values)) {\n const val = getDeepValue(values, path);\n if (this.isEmpty(val)) {\n errors[path as keyof BitErrors<T>] = (config.conditional\n ?.requiredMessage ??\n \"required field\") as BitErrors<T>[keyof BitErrors<T>];\n }\n }\n });\n\n return errors;\n }\n\n evaluateAll(values: T) {\n this.conditionalVisibilityPaths.forEach((path) => {\n this.evaluateFieldCondition(path, values);\n });\n }\n\n updateDependencies(\n changedPath: string,\n currentValues: T,\n newValues: T,\n ): BitDependencyUpdateDiff {\n const affectedFields = new Set<string>();\n const visibilityChanged = new Set<string>();\n const requiredChanged = new Set<string>();\n\n const queue = [changedPath];\n const visited = new Set<string>();\n\n while (queue.length > 0) {\n const currentPath = queue.shift()!;\n\n if (visited.has(currentPath)) {\n continue;\n }\n\n visited.add(currentPath);\n\n const dependents = this.dependencies.get(currentPath);\n if (!dependents) {\n continue;\n }\n\n dependents.forEach((depPath) => {\n affectedFields.add(depPath);\n\n const wasHidden = this.isHidden(depPath);\n const wasRequired = this.isRequired(depPath, currentValues);\n this.evaluateFieldCondition(depPath, newValues);\n const isHiddenNow = this.isHidden(depPath);\n const isRequiredNow = this.isRequired(depPath, newValues);\n\n if (wasHidden !== isHiddenNow) {\n visibilityChanged.add(depPath);\n }\n\n if (wasRequired !== isRequiredNow) {\n requiredChanged.add(depPath);\n }\n\n queue.push(depPath);\n });\n }\n\n return {\n affectedFields: Array.from(affectedFields),\n visibilityChanged: Array.from(visibilityChanged),\n requiredChanged: Array.from(requiredChanged),\n };\n }\n\n private evaluateFieldCondition(path: string, values: T) {\n const config = this.getFieldConfig(path);\n const showIf = config?.conditional?.showIf;\n if (!showIf) return;\n\n try {\n if (showIf(values)) {\n this.hiddenFields.delete(path);\n } else {\n this.hiddenFields.add(path);\n }\n } catch (error) {\n this.onConditionError?.({ path, kind: \"showIf\", error });\n }\n }\n\n private wouldCreateCycle(newPath: string, dependsOn: string[]): boolean {\n // The dependencies map is reversed (dependency -> dependents).\n // Adding new edges (dep -> newPath) creates a cycle if newPath can already reach dep.\n for (const targetDependency of dependsOn) {\n const queue = [newPath];\n const visited = new Set<string>();\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n if (current === targetDependency) {\n return true;\n }\n\n if (visited.has(current)) {\n continue;\n }\n\n visited.add(current);\n\n const dependents = this.dependencies.get(current);\n if (dependents) {\n queue.push(...dependents);\n }\n }\n }\n\n return false;\n }\n\n private isEmpty(value: unknown): boolean {\n return (\n value === undefined ||\n value === null ||\n (typeof value === \"string\" && value.trim() === \"\") ||\n (Array.isArray(value) && value.length === 0)\n );\n }\n}\n","import type { BitDependencyUpdateDiff } from \"../contracts/port-types\";\nimport type { BitFieldDefinition, BitTransformFn } from \"../contracts/types\";\nimport type { BitComputedEntry } from \"../managers/core/computed-manager\";\nimport { isPathWithinPrefix, normalizePathPrefix } from \"../shared/path-prefix\";\nimport { BitFieldCatalog, type BitNormalizerEntry } from \"./field-catalog\";\nimport { BitFieldConditions } from \"./field-conditions\";\nimport type { BitFieldMetadataProvider } from \"./field-metadata-provider\";\n\nexport class BitFieldRegistry<\n T extends object = Record<string, unknown>,\n> implements BitFieldMetadataProvider<T> {\n private readonly catalog = new BitFieldCatalog<T>();\n private readonly conditions: BitFieldConditions<T>;\n\n constructor(\n onConditionError?: (args: {\n path: string;\n kind: \"showIf\" | \"requiredIf\";\n error: unknown;\n }) => void,\n ) {\n this.conditions = new BitFieldConditions<T>(\n (path) => this.catalog.get(path),\n onConditionError,\n );\n }\n\n getFieldConfig(path: string): BitFieldDefinition<T> | undefined {\n return this.catalog.get(path);\n }\n\n forEachFieldConfig(\n callback: (config: BitFieldDefinition<T>, path: string) => void,\n ) {\n this.catalog.forEach((config, path) => callback(config, path));\n }\n\n hasFieldConfig(path: string): boolean {\n return this.catalog.has(path);\n }\n\n getHiddenFields(): ReadonlySet<string> {\n return this.conditions.getHiddenFields();\n }\n\n register(path: string, config: BitFieldDefinition<T>, currentValues: T) {\n const previousConfig = this.catalog.get(path);\n if (previousConfig) {\n this.conditions.onUnregister(path, previousConfig, {\n preserveIncomingDependents: true,\n });\n }\n\n this.catalog.set(path, config);\n const didRegister = this.conditions.onRegister(path, config, currentValues);\n\n if (didRegister || !previousConfig) {\n return;\n }\n\n // Rollback to previous field config when re-register fails (e.g. cycle).\n this.catalog.set(path, previousConfig);\n this.conditions.onRegister(path, previousConfig, currentValues);\n }\n\n unregister(path: string) {\n const config = this.catalog.delete(path);\n this.conditions.onUnregister(path, config);\n }\n\n unregisterPrefix(prefix: string) {\n const removedEntries: [string, BitFieldDefinition<T>][] = [];\n const normalizedPrefix = normalizePathPrefix(prefix);\n\n if (normalizedPrefix.length === 0) {\n return removedEntries;\n }\n\n this.catalog.forEach((config, path) => {\n if (isPathWithinPrefix(path, normalizedPrefix)) {\n removedEntries.push([path, config]);\n }\n });\n\n // Batch unregister all at once instead of calling unregister N times\n // This avoids N separate invalidations\n removedEntries.forEach(([path, config]) => {\n this.catalog.delete(path);\n this.conditions.onUnregister(path, config);\n });\n\n return removedEntries;\n }\n\n isHidden(path: string): boolean {\n return this.conditions.isHidden(path);\n }\n\n hasDependents(path: string): boolean {\n return this.conditions.hasDependents(path);\n }\n\n isRequired(path: string, values: T): boolean {\n return this.conditions.isRequired(path, values);\n }\n\n getRequiredErrors(values: T): Record<string, string> {\n return this.conditions.getRequiredErrors(values) as Record<string, string>;\n }\n\n evaluateAll(values: T) {\n this.conditions.evaluateAll(values);\n }\n\n updateDependencies(\n changedPath: string,\n currentValues: T,\n newValues: T,\n ): BitDependencyUpdateDiff {\n return this.conditions.updateDependencies(\n changedPath,\n currentValues,\n newValues,\n );\n }\n\n getScopeFields(scopeName: string, values: T): string[] {\n return this.catalog.getScopeFields(scopeName, values);\n }\n\n getComputedEntries(values: T): BitComputedEntry<T>[] {\n return this.catalog.getComputedEntries(values);\n }\n\n getTransformEntries(values: T): [string, BitTransformFn<T>][] {\n return this.catalog.getTransformEntries(values);\n }\n\n getNormalizerEntries(values: T): BitNormalizerEntry<T>[] {\n return this.catalog.getNormalizerEntries(values);\n }\n\n invalidateIndexes() {\n this.catalog.invalidateIndexes();\n }\n}\n","import { deepClone } from \"../../utils\";\nimport type { BitFrameworkConfig } from \"../contracts/public/store-api-types\";\nimport type { BitConfig, BitPersistResolvedConfig } from \"../contracts/types\";\n\nfunction defaultIdFactory() {\n return `bit-form-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction defaultUnhandledErrorReporter(error: unknown) {\n if (typeof console !== \"undefined\" && typeof console.error === \"function\") {\n console.error(error);\n }\n}\n\nexport function normalizeConfig<T extends object>(\n config: BitConfig<T> = {},\n): BitFrameworkConfig<T> {\n const rawInitial = (config.initialValues ?? {}) as T;\n const validation = config.validation;\n const history = config.history;\n\n const defaultPersistKey = config.name\n ? `bit-form:${config.name}:draft`\n : \"bit-form:draft\";\n\n const userUnhandledError =\n config.onUnhandledError ?? defaultUnhandledErrorReporter;\n\n const safeUnhandledErrorReporter = (\n error: unknown,\n source: string,\n ) => {\n try {\n userUnhandledError(error, source);\n } catch (fallbackError) {\n // Isolamento fail-open: se o SDK do Datadog/Sentry der crash (ex: Cycle Object),\n // fazemos um fallback nativo ignorando o crash para não gerar Unhandled Promise Rejections.\n defaultUnhandledErrorReporter(error);\n defaultUnhandledErrorReporter(fallbackError);\n }\n };\n\n const persistErrorHandler = config.persist?.onError;\n\n const persist: BitPersistResolvedConfig<T> = {\n enabled: config.persist?.enabled ?? false,\n key: config.persist?.key ?? defaultPersistKey,\n storage: config.persist?.storage,\n autoSave: config.persist?.autoSave ?? true,\n debounceMs: config.persist?.debounceMs ?? 300,\n mode: config.persist?.mode ?? \"values\",\n serialize: config.persist?.serialize ?? JSON.stringify,\n deserialize:\n config.persist?.deserialize ??\n ((raw: string) => JSON.parse(raw) as Partial<T>),\n onError: (error) => {\n if (persistErrorHandler) {\n persistErrorHandler(error);\n return;\n }\n\n safeUnhandledErrorReporter(error, \"persist\");\n },\n };\n\n return {\n name: config.name,\n initialValues: deepClone(rawInitial),\n resolver: validation?.resolver,\n validationDelay: validation?.delay ?? 300,\n history: {\n enabled: history?.enabled ?? false,\n limit: history?.limit ?? 50,\n debounceMs: history?.debounceMs ?? 300,\n },\n fields: config.fields,\n devTools: config.devTools,\n persist,\n idFactory: config.idFactory ?? defaultIdFactory,\n plugins: config.plugins ?? [],\n scheduler: config.scheduler,\n subscriptionCacheSize: config.subscriptionCacheSize,\n trackedSubscriptions: config.trackedSubscriptions ?? false,\n bus: config.bus,\n onUnhandledError: safeUnhandledErrorReporter,\n } as BitFrameworkConfig<T>;\n}\n","export function mergePaths(\n previous?: readonly string[],\n next?: readonly string[],\n): string[] | undefined {\n if ((!previous || previous.length === 0) && (!next || next.length === 0)) {\n return undefined;\n }\n\n const merged = new Set<string>(previous ?? []);\n next?.forEach((path) => merged.add(path));\n return Array.from(merged);\n}\n","import { getDeepValue, setDeepValue, valueEqual } from \"../../utils\";\nimport { mergePaths } from \"../../utils/path-utils\";\nimport type { BitTransformFn } from \"../contracts/types\";\nimport type { BitNormalizerEntry } from \"../registry/field-catalog\";\n\ninterface BitDependencyAwareEntry {\n path: string;\n dependsOn: readonly string[];\n}\n\nexport function createDependencyImpactChecker(\n changedPaths?: readonly string[],\n) {\n const hasWildcardChange = changedPaths?.includes(\"*\") ?? false;\n const changedPathSet = new Set(changedPaths ?? []);\n const changedAncestorSet = new Set<string>();\n\n for (const changedPath of changedPathSet) {\n changedAncestorSet.add(changedPath);\n\n let separatorIndex = changedPath.lastIndexOf(\".\");\n while (separatorIndex > -1) {\n changedAncestorSet.add(changedPath.slice(0, separatorIndex));\n separatorIndex = changedPath.lastIndexOf(\".\", separatorIndex - 1);\n }\n }\n\n return (dependencyPath: string) => {\n if (!changedPaths || changedPaths.length === 0 || hasWildcardChange) {\n return true;\n }\n\n if (changedPathSet.has(dependencyPath)) {\n return true;\n }\n\n if (changedAncestorSet.has(dependencyPath)) {\n return true;\n }\n\n let separatorIndex = dependencyPath.lastIndexOf(\".\");\n while (separatorIndex > -1) {\n if (changedPathSet.has(dependencyPath.slice(0, separatorIndex))) {\n return true;\n }\n\n separatorIndex = dependencyPath.lastIndexOf(\".\", separatorIndex - 1);\n }\n\n return false;\n };\n}\n\nexport function filterDependencyEntries<TEntry extends BitDependencyAwareEntry>(\n entries: readonly TEntry[],\n changedPaths?: readonly string[],\n): readonly TEntry[] {\n if (\n !changedPaths ||\n changedPaths.length === 0 ||\n changedPaths.includes(\"*\")\n ) {\n return entries;\n }\n\n const isDependencyImpacted = createDependencyImpactChecker(changedPaths);\n return entries.filter((entry) =>\n entry.dependsOn.some((dependencyPath) =>\n isDependencyImpacted(dependencyPath),\n ),\n );\n}\n\nfunction orderDependencyEntries<TEntry extends BitDependencyAwareEntry>(\n entries: readonly TEntry[],\n): {\n orderedEntries: TEntry[];\n cyclePaths: string[];\n} {\n if (entries.length <= 1) {\n return {\n orderedEntries: [...entries],\n cyclePaths: [],\n };\n }\n\n const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));\n const inDegree = new Map<string, number>();\n const dependents = new Map<string, Set<string>>();\n const originalIndex = new Map(\n entries.map((entry, index) => [entry.path, index]),\n );\n\n entries.forEach((entry) => inDegree.set(entry.path, 0));\n\n entries.forEach((entry) => {\n entry.dependsOn.forEach((dependencyPath) => {\n if (dependencyPath === entry.path || !entryByPath.has(dependencyPath)) {\n return;\n }\n\n const nextDependents =\n dependents.get(dependencyPath) ?? new Set<string>();\n if (nextDependents.has(entry.path)) {\n return;\n }\n\n nextDependents.add(entry.path);\n dependents.set(dependencyPath, nextDependents);\n inDegree.set(entry.path, (inDegree.get(entry.path) ?? 0) + 1);\n });\n });\n\n const queue = entries\n .filter((entry) => (inDegree.get(entry.path) ?? 0) === 0)\n .map((entry) => entry.path);\n const orderedPaths: string[] = [];\n\n while (queue.length > 0) {\n queue.sort(\n (left, right) =>\n (originalIndex.get(left) ?? 0) - (originalIndex.get(right) ?? 0),\n );\n\n const currentPath = queue.shift()!;\n orderedPaths.push(currentPath);\n\n const nextDependents = dependents.get(currentPath);\n if (!nextDependents) {\n continue;\n }\n\n nextDependents.forEach((dependentPath) => {\n const nextDegree = (inDegree.get(dependentPath) ?? 0) - 1;\n inDegree.set(dependentPath, nextDegree);\n\n if (nextDegree === 0) {\n queue.push(dependentPath);\n }\n });\n }\n\n if (orderedPaths.length !== entries.length) {\n const cyclePaths = entries\n .filter((entry) => (inDegree.get(entry.path) ?? 0) > 0)\n .map((entry) => entry.path);\n\n return {\n orderedEntries: orderedPaths.map((path) => entryByPath.get(path)!),\n cyclePaths,\n };\n }\n\n return {\n orderedEntries: orderedPaths.map((path) => entryByPath.get(path)!),\n cyclePaths: [],\n };\n}\n\nexport function applyValueDerivations<T extends object>(args: {\n values: T;\n changedPaths?: readonly string[];\n normalizerEntries: readonly BitNormalizerEntry<T>[];\n applyComputed: (values: T, changedPaths?: readonly string[]) => T;\n onError?: (error: unknown, path: string) => void;\n}): T {\n const { values, changedPaths, normalizerEntries, applyComputed, onError } =\n args;\n\n const orderedResult = orderDependencyEntries(\n filterDependencyEntries(normalizerEntries, changedPaths),\n );\n const { orderedEntries: targetedNormalizers, cyclePaths } = orderedResult;\n\n if (cyclePaths.length > 0) {\n onError?.(\n new Error(\n `BitStore: cyclic normalizer dependencies detected. Check normalizeDependsOn definitions for: ${cyclePaths.join(\", \")}.`,\n ),\n cyclePaths[0] ?? \"*\",\n );\n }\n\n if (targetedNormalizers.length === 0) {\n return applyComputed(values, changedPaths);\n }\n\n const normalizerUpdates: Array<[string, unknown]> = [];\n let normalizedValues = values;\n\n for (const entry of targetedNormalizers) {\n const currentValue = getDeepValue(normalizedValues, entry.path);\n let derivedValue: unknown;\n\n try {\n derivedValue = entry.normalize(currentValue, normalizedValues);\n } catch (error) {\n onError?.(error, entry.path);\n continue;\n }\n\n if (valueEqual(currentValue, derivedValue)) {\n continue;\n }\n\n normalizerUpdates.push([entry.path, derivedValue]);\n normalizedValues = setDeepValue(normalizedValues, entry.path, derivedValue);\n }\n\n const nextChangedPaths = mergePaths(\n changedPaths,\n normalizerUpdates.map(([path]) => path),\n );\n\n return applyComputed(normalizedValues, nextChangedPaths);\n}\n\nexport function applyTransformDerivations<T extends object>(args: {\n values: T;\n sourceValues: T;\n transformEntries: readonly [string, BitTransformFn<T>][];\n onError?: (error: unknown, path: string) => void;\n}): T {\n const { values, sourceValues, transformEntries, onError } = args;\n if (transformEntries.length === 0) {\n return values;\n }\n\n let transformedValues = values;\n let transformedAllValues = sourceValues;\n\n for (const [path, transform] of transformEntries) {\n const currentValue = getDeepValue(transformedValues, path);\n let derivedValue: unknown;\n\n try {\n derivedValue = transform(currentValue, transformedAllValues);\n } catch (error) {\n onError?.(error, path);\n continue;\n }\n\n if (valueEqual(currentValue, derivedValue)) {\n continue;\n }\n\n transformedValues = setDeepValue(transformedValues, path, derivedValue);\n transformedAllValues = setDeepValue(\n transformedAllValues,\n path,\n derivedValue,\n );\n }\n\n return transformedValues;\n}\n","import type { BitBusStorePort } from \"../contracts/bus-types\";\nimport type {\n BitAfterSubmitEvent,\n BitAfterValidateEvent,\n BitBeforeSubmitEvent,\n BitBeforeValidateEvent,\n BitFieldChangeEvent,\n BitState,\n} from \"../contracts/types\";\nimport {\n BitEffectRegistry,\n type BitStoreEffect,\n} from \"./effects/effect-registry\";\n\nexport class BitStoreEffectEngine<T extends object> {\n private readonly effects: BitStoreEffect<T>[];\n\n constructor(registry: BitEffectRegistry<T>) {\n this.effects = registry.getAll();\n }\n\n attachStorePort(storeBusPort: BitBusStorePort<T>): void {\n this.effects.forEach((effect) => effect.attachStorePort?.(storeBusPort));\n }\n\n initialize(): void {\n this.effects.forEach((effect) => effect.initialize?.());\n }\n\n onStateUpdated(nextState: BitState<T>, valuesChanged: boolean): void {\n this.effects.forEach((effect) => {\n try {\n effect.onStateUpdated?.(nextState, valuesChanged);\n } catch (error) {\n this.logEffectHookError(effect.name, \"onStateUpdated\", error);\n }\n });\n }\n\n async restorePersisted(): Promise<boolean> {\n let restored = false;\n let firstError: unknown = null;\n\n for (const effect of this.effects) {\n if (!effect.restorePersisted) {\n continue;\n }\n\n try {\n restored = (await effect.restorePersisted()) || restored;\n } catch (error) {\n this.logEffectHookError(effect.name, \"restorePersisted\", error);\n firstError ??= error;\n }\n }\n\n if (firstError) {\n throw firstError;\n }\n\n return restored;\n }\n\n async savePersistedNow(): Promise<void> {\n for (const effect of this.effects) {\n if (!effect.savePersistedNow) {\n continue;\n }\n\n await effect.savePersistedNow();\n }\n }\n\n async clearPersisted(): Promise<void> {\n for (const effect of this.effects) {\n if (!effect.clearPersisted) {\n continue;\n }\n\n await effect.clearPersisted();\n }\n }\n\n async beforeValidate(event: BitBeforeValidateEvent<T>): Promise<void> {\n for (const effect of this.effects) {\n if (!effect.beforeValidate) {\n continue;\n }\n\n try {\n await effect.beforeValidate(event);\n } catch (error) {\n this.logEffectHookError(effect.name, \"beforeValidate\", error);\n }\n }\n }\n\n async afterValidate(event: BitAfterValidateEvent<T>): Promise<void> {\n for (const effect of this.effects) {\n if (!effect.afterValidate) {\n continue;\n }\n\n try {\n await effect.afterValidate(event);\n } catch (error) {\n this.logEffectHookError(effect.name, \"afterValidate\", error);\n }\n }\n }\n\n async beforeSubmit(event: BitBeforeSubmitEvent<T>): Promise<void> {\n for (const effect of this.effects) {\n if (!effect.beforeSubmit) {\n continue;\n }\n\n try {\n await effect.beforeSubmit(event);\n } catch (error) {\n this.logEffectHookError(effect.name, \"beforeSubmit\", error);\n }\n }\n }\n\n async afterSubmit(event: BitAfterSubmitEvent<T>): Promise<void> {\n for (const effect of this.effects) {\n if (!effect.afterSubmit) {\n continue;\n }\n\n try {\n await effect.afterSubmit(event);\n } catch (error) {\n this.logEffectHookError(effect.name, \"afterSubmit\", error);\n }\n }\n }\n\n onFieldChange(event: BitFieldChangeEvent<T>): void {\n this.effects.forEach((effect) => {\n try {\n effect.onFieldChange?.(event);\n } catch (error) {\n this.logEffectHookError(effect.name, \"onFieldChange\", error);\n }\n });\n }\n\n async reportOperationalError(event: {\n source: \"submit\";\n error: unknown;\n payload?: unknown;\n }): Promise<void> {\n for (const effect of this.effects) {\n if (!effect.reportOperationalError) {\n continue;\n }\n\n try {\n await effect.reportOperationalError(event);\n } catch (error) {\n this.logEffectHookError(effect.name, \"reportOperationalError\", error);\n }\n }\n }\n\n private logEffectHookError(\n effectName: string,\n hookName:\n | \"beforeValidate\"\n | \"afterValidate\"\n | \"beforeSubmit\"\n | \"afterSubmit\"\n | \"onFieldChange\"\n | \"onStateUpdated\"\n | \"reportOperationalError\"\n | \"restorePersisted\",\n error: unknown,\n ): void {\n console.error(\n `BitStoreEffectEngine: effect \"${effectName}\" failed in hook \"${hookName}\"`,\n error,\n );\n }\n\n destroy(): void {\n // Tear down in reverse registration order to preserve dependency ordering.\n for (let index = this.effects.length - 1; index >= 0; index -= 1) {\n this.effects[index].destroy?.();\n }\n }\n}\n","import type { BitBusStorePort, BitFormGlobal } from \"../../contracts/bus-types\";\nimport type { BitState } from \"../../contracts/types\";\n\nexport class BitBusEffects<T extends object> {\n private storeBusPort?: BitBusStorePort<T>;\n\n constructor(\n private readonly storeId: string,\n private readonly bus: BitFormGlobal,\n private readonly enableBusDispatch = true,\n storeBusPort?: BitBusStorePort<T>,\n ) {\n this.storeBusPort = storeBusPort;\n }\n\n attachStorePort(storeBusPort: BitBusStorePort<T>): void {\n this.storeBusPort = storeBusPort;\n\n if (!this.enableBusDispatch) {\n return;\n }\n\n this.bus.stores[this.storeId] = storeBusPort as BitBusStorePort<object>;\n }\n\n initialize(): void {\n if (!this.enableBusDispatch || !this.storeBusPort) {\n return;\n }\n\n this.bus.stores[this.storeId] = this\n .storeBusPort as BitBusStorePort<object>;\n }\n\n onStateUpdated(nextState: BitState<T>): void {\n if (!this.enableBusDispatch) {\n return;\n }\n\n this.bus.dispatch(this.storeId, nextState);\n }\n\n destroy(): void {\n if (!this.enableBusDispatch) {\n return;\n }\n\n delete this.bus.stores[this.storeId];\n this.storeBusPort = undefined;\n }\n}\n","import type { BitBusStorePort } from \"../../contracts/bus-types\";\nimport type {\n BitAfterSubmitEvent,\n BitAfterValidateEvent,\n BitBeforeSubmitEvent,\n BitBeforeValidateEvent,\n BitFieldChangeEvent,\n BitState,\n} from \"../../contracts/types\";\n\nexport interface BitStoreEffect<T extends object> {\n name: string;\n attachStorePort?(storeBusPort: BitBusStorePort<T>): void;\n initialize?(): void;\n onStateUpdated?(nextState: BitState<T>, valuesChanged: boolean): void;\n restorePersisted?(): Promise<boolean>;\n savePersistedNow?(): Promise<void>;\n clearPersisted?(): Promise<void>;\n beforeValidate?(event: BitBeforeValidateEvent<T>): Promise<void>;\n afterValidate?(event: BitAfterValidateEvent<T>): Promise<void>;\n beforeSubmit?(event: BitBeforeSubmitEvent<T>): Promise<void>;\n afterSubmit?(event: BitAfterSubmitEvent<T>): Promise<void>;\n onFieldChange?(event: BitFieldChangeEvent<T>): void;\n reportOperationalError?(event: {\n source: \"submit\";\n error: unknown;\n payload?: unknown;\n }): Promise<void>;\n destroy?(): void;\n}\n\nexport class BitEffectRegistry<T extends object> {\n private readonly effects = new Map<string, BitStoreEffect<T>>();\n\n register(effect: BitStoreEffect<T>): void {\n this.effects.set(effect.name, effect);\n }\n\n getAll(): BitStoreEffect<T>[] {\n return Array.from(this.effects.values());\n }\n}\n","import type { BitState } from \"../../contracts/types\";\nimport { BitPersistManager } from \"../../managers/features/persist-manager\";\n\nexport class BitPersistEffects<T extends object> {\n constructor(private readonly persistManager: BitPersistManager<T>) {}\n\n onStateUpdated(_nextState: BitState<T>, valuesChanged: boolean): void {\n if (valuesChanged) {\n this.persistManager.queueSave();\n }\n }\n\n restorePersisted(): Promise<boolean> {\n return this.persistManager.restore();\n }\n\n savePersistedNow(): Promise<void> {\n return this.persistManager.saveNow();\n }\n\n clearPersisted(): Promise<void> {\n return this.persistManager.clear();\n }\n\n destroy(): void {\n this.persistManager.destroy();\n }\n}\n","import type {\n BitAfterSubmitEvent,\n BitAfterValidateEvent,\n BitBeforeSubmitEvent,\n BitBeforeValidateEvent,\n BitFieldChangeEvent,\n} from \"../../contracts/types\";\nimport { BitPluginManager } from \"../../managers/features/plugin-manager\";\n\nexport class BitPluginEffects<T extends object> {\n constructor(private readonly pluginManager: BitPluginManager<T>) {}\n\n initialize(): void {\n this.pluginManager.setupAll();\n }\n\n beforeValidate(event: BitBeforeValidateEvent<T>): Promise<void> {\n return this.pluginManager.beforeValidate(event);\n }\n\n afterValidate(event: BitAfterValidateEvent<T>): Promise<void> {\n return this.pluginManager.afterValidate(event);\n }\n\n beforeSubmit(event: BitBeforeSubmitEvent<T>): Promise<void> {\n return this.pluginManager.beforeSubmit(event);\n }\n\n afterSubmit(event: BitAfterSubmitEvent<T>): Promise<void> {\n return this.pluginManager.afterSubmit(event);\n }\n\n onFieldChange(event: BitFieldChangeEvent<T>): void {\n this.pluginManager.onFieldChange(event);\n }\n\n reportOperationalError(event: {\n source: \"submit\";\n error: unknown;\n payload?: unknown;\n }): Promise<void> {\n return this.pluginManager.reportError(\n event.source,\n event.error,\n event.payload,\n );\n }\n\n destroy(): void {\n this.pluginManager.destroy();\n }\n}\n","import type {\n BitPersistResolvedConfig,\n BitPersistStorageAdapter,\n} from \"../../contracts/types\";\n\ninterface BitPersistManagerCallbacks {\n onWriteStart?: () => void;\n onWriteSuccess?: () => void;\n onWriteError?: (error: unknown) => void;\n onWriteSettled?: () => void;\n onError?: (error: unknown) => void;\n}\n\nfunction getDefaultStorage(): BitPersistStorageAdapter | undefined {\n if (typeof globalThis === \"undefined\") return undefined;\n\n let storageLike: Storage | undefined;\n try {\n storageLike =\n (globalThis as { localStorage?: Storage }).localStorage ?? undefined;\n } catch {\n // Safari Private Mode and some restricted WebViews throw a SecurityError\n // when the localStorage getter is accessed. Treat as unavailable.\n return undefined;\n }\n\n if (!storageLike) return undefined;\n\n return {\n getItem: (key: string) => storageLike!.getItem(key),\n setItem: (key: string, value: string) => storageLike!.setItem(key, value),\n removeItem: (key: string) => storageLike!.removeItem(key),\n };\n}\n\nexport class BitPersistManager<T extends object = Record<string, unknown>> {\n private timer: ReturnType<typeof setTimeout> | undefined;\n private writeQueue: Promise<void> = Promise.resolve();\n private activeWrites = 0;\n private isDestroyed = false;\n\n constructor(\n private config: BitPersistResolvedConfig<T>,\n private getValues: () => T,\n private getDirtyValues: () => Partial<T>,\n private applyRestoredValues: (values: Partial<T>) => void,\n private callbacks: BitPersistManagerCallbacks = {},\n ) {}\n\n private getStorage(): BitPersistStorageAdapter | undefined {\n return this.config.storage || getDefaultStorage();\n }\n\n private canPersist() {\n return !!(this.config.enabled && this.config.key && this.getStorage());\n }\n\n private handleError(error: unknown) {\n this.callbacks.onError?.(error);\n this.config.onError?.(error);\n }\n\n private enqueueWriteOperation(operation: () => Promise<void>): Promise<void> {\n this.activeWrites += 1;\n\n try {\n if (this.activeWrites === 1) {\n this.callbacks.onWriteStart?.();\n }\n } catch (error) {\n this.activeWrites = Math.max(0, this.activeWrites - 1);\n throw error;\n }\n\n const run = this.writeQueue.then(operation, operation);\n this.writeQueue = run.then(\n () => undefined,\n () => undefined,\n );\n\n const observed = run.then(\n () => ({ ok: true as const, error: undefined }),\n (error) => ({ ok: false as const, error }),\n );\n\n return observed.then((result) => {\n this.activeWrites = Math.max(0, this.activeWrites - 1);\n\n if (result.ok) {\n if (this.activeWrites === 0) {\n try {\n this.callbacks.onWriteSuccess?.();\n } finally {\n this.callbacks.onWriteSettled?.();\n }\n }\n return;\n }\n\n try {\n this.callbacks.onWriteError?.(result.error);\n } finally {\n if (this.activeWrites === 0) {\n this.callbacks.onWriteSettled?.();\n }\n }\n\n throw result.error;\n });\n }\n\n private async persistPayload() {\n const storage = this.getStorage();\n if (!storage) return;\n\n const payload =\n this.config.mode === \"dirtyValues\"\n ? this.getDirtyValues()\n : this.getValues();\n const serialized = this.config.serialize(payload);\n await storage.setItem(this.config.key, serialized);\n }\n\n async saveNow() {\n if (!this.canPersist()) return;\n\n await this.enqueueWriteOperation(async () => {\n try {\n await this.persistPayload();\n } catch (error) {\n this.handleError(error);\n throw error;\n }\n });\n }\n\n queueSave() {\n if (!this.canPersist() || !this.config.autoSave) return;\n\n if (this.timer) {\n clearTimeout(this.timer);\n }\n\n this.timer = setTimeout(() => {\n this.timer = undefined;\n if (this.isDestroyed) return;\n void this.saveNow().catch(() => {\n // saveNow already routes persist errors via callbacks and config handlers.\n });\n }, this.config.debounceMs);\n }\n\n async restore() {\n if (this.isDestroyed || !this.canPersist()) return false;\n\n const storage = this.getStorage();\n if (!storage) return false;\n\n try {\n const raw = await storage.getItem(this.config.key);\n if (this.isDestroyed || !raw) return false;\n\n const parsed = this.config.deserialize(raw);\n if (!parsed || typeof parsed !== \"object\") {\n return false;\n }\n\n // Guard against component unmounting during deserialize. In React\n // StrictMode effects run twice; destroy() may be called while we are\n // between the final await and apply. Without this check, stale data\n // from a previous mount would be applied to the freshly-created store.\n if (this.isDestroyed) return false;\n\n this.applyRestoredValues(parsed);\n return true;\n } catch (error) {\n this.handleError(error);\n throw error;\n }\n }\n\n async clear() {\n if (!this.canPersist()) return;\n\n const storage = this.getStorage();\n if (!storage) return;\n\n await this.enqueueWriteOperation(async () => {\n try {\n await storage.removeItem(this.config.key);\n } catch (error) {\n this.handleError(error);\n throw error;\n }\n });\n }\n\n destroy() {\n this.isDestroyed = true;\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = undefined;\n }\n }\n}\n","import type {\n BitAfterSubmitEvent,\n BitAfterValidateEvent,\n BitBeforeSubmitEvent,\n BitBeforeValidateEvent,\n BitFieldChangeEvent,\n BitPlugin,\n BitPluginContext,\n BitPluginErrorEvent,\n} from \"../../contracts/types\";\n\ninterface PendingPluginError<T extends object> {\n source: BitPluginErrorEvent<T>[\"source\"];\n pluginName?: string;\n error: unknown;\n event?: unknown;\n}\n\nexport class BitPluginManager<T extends object = Record<string, unknown>> {\n private teardownFns: Array<() => void> = [];\n private notifyingError = false;\n private pendingErrorQueue: PendingPluginError<T>[] = [];\n private cachedContext: BitPluginContext<T> | null = null;\n\n constructor(\n private plugins: BitPlugin<T>[],\n private contextFactory: () => BitPluginContext<T>,\n ) {}\n\n setupAll() {\n const context = this.getContext();\n this.plugins.forEach((plugin) => {\n if (!plugin.setup) return;\n\n try {\n const maybeTeardown = plugin.setup(context);\n if (typeof maybeTeardown === \"function\") {\n this.teardownFns.push(maybeTeardown);\n }\n } catch (error) {\n void this.reportError(\"setup\", error, undefined, plugin.name);\n }\n });\n }\n\n async beforeValidate(event: BitBeforeValidateEvent<T>) {\n await this.emitHook(\"beforeValidate\", event);\n }\n\n async afterValidate(event: BitAfterValidateEvent<T>) {\n await this.emitHook(\"afterValidate\", event);\n }\n\n async beforeSubmit(event: BitBeforeSubmitEvent<T>) {\n await this.emitHook(\"beforeSubmit\", event);\n }\n\n async afterSubmit(event: BitAfterSubmitEvent<T>) {\n await this.emitHook(\"afterSubmit\", event);\n }\n\n onFieldChange(event: BitFieldChangeEvent<T>) {\n const context = this.getContext();\n this.plugins.forEach((plugin) => {\n const hook = plugin.hooks?.onFieldChange;\n if (!hook) return;\n\n try {\n const result = hook(event, context);\n void Promise.resolve(result).catch((error) => {\n void this.reportError(\"onFieldChange\", error, event, plugin.name);\n });\n } catch (error) {\n void this.reportError(\"onFieldChange\", error, event, plugin.name);\n }\n });\n }\n\n async reportError(\n source: BitPluginErrorEvent<T>[\"source\"],\n error: unknown,\n event?: unknown,\n pluginName?: string,\n ) {\n // Enqueue with minimal data — state snapshot is captured at processing time\n // to ensure plugins receive the freshest state, not a stale copy from the\n // moment the error was enqueued (which may be several ticks earlier).\n this.pendingErrorQueue.push({ source, pluginName, error, event });\n\n if (this.notifyingError) {\n // The active drain loop will pick up this entry in its next iteration.\n // Do NOT return without re-checking: the while-loop below handles the\n // re-entrancy case automatically.\n return;\n }\n\n this.notifyingError = true;\n\n try {\n while (this.pendingErrorQueue.length > 0) {\n const entry = this.pendingErrorQueue.shift();\n if (!entry) {\n break;\n }\n\n // Build the full payload with a fresh state snapshot at dispatch time.\n const stateSnapshot = this.contextFactory().getState();\n const payload: BitPluginErrorEvent<T> = {\n source: entry.source,\n pluginName: entry.pluginName,\n error: entry.error,\n event: entry.event,\n values: stateSnapshot.values,\n state: stateSnapshot,\n };\n\n for (const plugin of this.plugins) {\n const onError = plugin.hooks?.onError;\n if (!onError) continue;\n\n try {\n await onError(payload, this.contextFactory());\n } catch {\n // fail-open: ignore secondary errors from onError handlers\n }\n }\n }\n } finally {\n this.notifyingError = false;\n }\n\n if (this.pendingErrorQueue.length > 0) {\n this.notifyingError = true;\n try {\n while (this.pendingErrorQueue.length > 0) {\n const entry = this.pendingErrorQueue.shift();\n if (!entry) break;\n\n const stateSnapshot = this.contextFactory().getState();\n const payload: BitPluginErrorEvent<T> = {\n source: entry.source,\n pluginName: entry.pluginName,\n error: entry.error,\n event: entry.event,\n values: stateSnapshot.values,\n state: stateSnapshot,\n };\n\n for (const plugin of this.plugins) {\n const onError = plugin.hooks?.onError;\n if (!onError) continue;\n\n try {\n await onError(payload, this.contextFactory());\n } catch {}\n }\n }\n } finally {\n this.notifyingError = false;\n }\n }\n }\n\n destroy() {\n for (let index = this.teardownFns.length - 1; index >= 0; index -= 1) {\n const teardown = this.teardownFns[index];\n try {\n teardown();\n } catch (error) {\n void this.reportError(\"teardown\", error);\n }\n }\n\n this.teardownFns = [];\n this.cachedContext = null;\n }\n\n private async emitHook(\n hookName:\n | \"beforeValidate\"\n | \"afterValidate\"\n | \"beforeSubmit\"\n | \"afterSubmit\",\n event:\n | BitBeforeValidateEvent<T>\n | BitAfterValidateEvent<T>\n | BitBeforeSubmitEvent<T>\n | BitAfterSubmitEvent<T>,\n ) {\n const context = this.getContext();\n\n for (const plugin of this.plugins) {\n const hook = plugin.hooks?.[hookName];\n if (!hook) continue;\n\n try {\n await hook(event as never, context);\n } catch (error) {\n await this.reportError(hookName, error, event, plugin.name);\n }\n }\n }\n\n private getContext(): BitPluginContext<T> {\n if (!this.cachedContext) {\n this.cachedContext = this.contextFactory();\n }\n\n return this.cachedContext;\n }\n}\n","import { BitBusListener, BitFormGlobal } from \"../contracts/bus-types\";\n\ndeclare global {\n var __BIT_FORM__: BitFormGlobal | undefined;\n}\n\nconst rootGlobal =\n typeof globalThis !== \"undefined\"\n ? globalThis\n : typeof global !== \"undefined\"\n ? global\n : window;\n\nif (!rootGlobal.__BIT_FORM__) {\n rootGlobal.__BIT_FORM__ = {\n stores: {},\n listeners: new Set<BitBusListener>(),\n\n dispatch(id: string, state) {\n this.listeners.forEach((fn: BitBusListener) => {\n try {\n fn(id, state);\n } catch {\n // Silently swallow listener errors to prevent breaking the notification chain\n }\n });\n },\n\n subscribe(fn: BitBusListener) {\n this.listeners.add(fn);\n return () => {\n this.listeners.delete(fn);\n };\n },\n };\n}\n\nexport const bitBus = rootGlobal.__BIT_FORM__ as BitFormGlobal;\n\nconst noopBus: BitFormGlobal = {\n stores: {},\n listeners: new Set<BitBusListener>(),\n dispatch: () => {},\n subscribe: () => () => {},\n};\n\nexport function getNoopBitBus(): BitFormGlobal {\n return noopBus;\n}\n\n/**\n * Creates an isolated bus instance — not connected to the browser global.\n * Use this in SSR / Edge Runtime environments (e.g. Next.js Edge) where a\n * shared `globalThis` singleton is unsafe across request contexts.\n *\n * @example\n * // _app.tsx (SSR-safe)\n * const bus = createBitBus();\n * const store = createBitStore({ bus, initialValues: { ... } });\n */\nexport function createBitBus(): BitFormGlobal {\n const listeners = new Set<BitBusListener>();\n return {\n stores: {},\n listeners,\n dispatch(id, state) {\n listeners.forEach((fn) => {\n try {\n fn(id, state);\n } catch {\n // Silently swallow listener errors to prevent breaking the notification chain\n }\n });\n },\n subscribe(fn) {\n listeners.add(fn);\n return () => listeners.delete(fn);\n },\n };\n}\n","import { deepClone } from \"../../utils\";\nimport type { BitBusStorePort } from \"../contracts/bus-types\";\nimport type { BitFrameworkConfig } from \"../contracts/public/store-api-types\";\nimport type { BitPersistMetadata, BitState } from \"../contracts/types\";\nimport { BitStoreEffectEngine } from \"../engines/effect-engine\";\nimport { BitBusEffects } from \"../engines/effects/bus-effects\";\nimport { BitEffectRegistry } from \"../engines/effects/effect-registry\";\nimport { BitPersistEffects } from \"../engines/effects/persist-effects\";\nimport { BitPluginEffects } from \"../engines/effects/plugin-effects\";\nimport { BitPersistManager } from \"../managers/features/persist-manager\";\nimport { BitPluginManager } from \"../managers/features/plugin-manager\";\nimport { bitBus, getNoopBitBus } from \"../shared/bus\";\n\nfunction shouldEnableStoreBus<T extends object>(config: BitFrameworkConfig<T>) {\n if (config.bus) {\n return true;\n }\n\n if (typeof config.devTools === \"boolean\") {\n return config.devTools;\n }\n\n if (config.devTools && typeof config.devTools === \"object\") {\n return config.devTools.enabled !== false;\n }\n\n return false;\n}\n\nexport function createStoreEffects<T extends object>(args: {\n storeId: string;\n storeBusPort?: BitBusStorePort<T>;\n config: BitFrameworkConfig<T>;\n getState: () => BitState<T>;\n getConfig: () => BitFrameworkConfig<T>;\n getValues: () => T;\n getDirtyValues: () => Partial<T>;\n applyPersistedValues: (values: Partial<T>) => void;\n setPersistMetadata?: (patch: Partial<BitPersistMetadata>) => void;\n}): BitStoreEffectEngine<T> {\n const {\n storeId,\n storeBusPort,\n config,\n getState,\n getConfig,\n getValues,\n getDirtyValues,\n applyPersistedValues,\n setPersistMetadata,\n } = args;\n\n const persistManager = new BitPersistManager<T>(\n config.persist,\n getValues,\n getDirtyValues,\n applyPersistedValues,\n {\n onWriteStart: () => setPersistMetadata?.({ isSaving: true, error: null }),\n onWriteSuccess: () =>\n setPersistMetadata?.({ isSaving: false, error: null }),\n onWriteError: (error) =>\n setPersistMetadata?.({\n error: error instanceof Error ? error : new Error(String(error)),\n }),\n onWriteSettled: () => setPersistMetadata?.({ isSaving: false }),\n onError: (error) => config.onUnhandledError(error, \"persist\"),\n },\n );\n\n const pluginManager = new BitPluginManager<T>([...config.plugins], () => ({\n storeId,\n getState: () => deepClone(getState()),\n getConfig: () => deepClone(getConfig()),\n }));\n\n const enableBusDispatch = shouldEnableStoreBus(config);\n const isTestEnv =\n typeof process !== \"undefined\" &&\n typeof process.env !== \"undefined\" &&\n process.env.VITEST === \"true\";\n const resolvedBus = enableBusDispatch\n ? (config.bus ?? (isTestEnv ? getNoopBitBus() : bitBus))\n : getNoopBitBus();\n\n const registry = new BitEffectRegistry<T>();\n let destroyed = false;\n\n const persistEffects = new BitPersistEffects<T>(persistManager);\n registry.register({\n name: \"persist\",\n onStateUpdated: (nextState, valuesChanged) =>\n persistEffects.onStateUpdated(nextState, valuesChanged),\n restorePersisted: async () => {\n if (destroyed) return false;\n const restored = await persistEffects.restorePersisted();\n if (destroyed) return false;\n return restored;\n },\n savePersistedNow: () => persistEffects.savePersistedNow(),\n clearPersisted: () => persistEffects.clearPersisted(),\n destroy: () => {\n destroyed = true;\n persistEffects.destroy();\n },\n });\n\n const pluginEffects = new BitPluginEffects<T>(pluginManager);\n registry.register({\n name: \"plugins\",\n initialize: () => pluginEffects.initialize(),\n beforeValidate: (event) => pluginEffects.beforeValidate(event),\n afterValidate: (event) => pluginEffects.afterValidate(event),\n beforeSubmit: (event) => pluginEffects.beforeSubmit(event),\n afterSubmit: (event) => pluginEffects.afterSubmit(event),\n onFieldChange: (event) => pluginEffects.onFieldChange(event),\n reportOperationalError: (event) =>\n pluginEffects.reportOperationalError(event),\n destroy: () => pluginEffects.destroy(),\n });\n\n const busEffects = new BitBusEffects<T>(\n storeId,\n resolvedBus,\n enableBusDispatch,\n storeBusPort,\n );\n registry.register({\n name: \"bus\",\n attachStorePort: (port) => busEffects.attachStorePort(port),\n initialize: () => busEffects.initialize(),\n onStateUpdated: (nextState) => busEffects.onStateUpdated(nextState),\n destroy: () => busEffects.destroy(),\n });\n\n const effects = new BitStoreEffectEngine<T>(registry);\n\n try {\n effects.initialize();\n } catch (error) {\n console.error(\n \"BitStoreEffects: initialize() failed — store will operate without initialized effects\",\n error,\n );\n }\n\n return effects;\n}\n","import type { BitErrors, BitState } from \"../contracts/types\";\n\nexport interface BitStatePatchOperation<T extends object> {\n kind: \"state.patch\";\n partialState: Partial<BitState<T>>;\n changedPaths?: string[];\n skipComputed?: boolean;\n}\n\nexport interface BitTouchFieldsOperation<_T extends object> {\n kind: \"field.touchMany\";\n paths: string[];\n}\n\nexport interface BitPersistMetaOperation<T extends object> {\n kind: \"form.persistMeta\";\n patch: Partial<BitState<T>[\"persist\"]>;\n}\n\nexport interface BitHistoryApplyOperation<T extends object> {\n kind: \"history.apply\";\n values: T;\n isDirty: boolean;\n}\n\nexport interface BitValidationCommitOperation<T extends object> {\n kind: \"validation.commit\";\n errors: BitErrors<T>;\n isValid: boolean;\n}\n\nexport type BitStoreOperation<T extends object> =\n | BitStatePatchOperation<T>\n | BitTouchFieldsOperation<T>\n | BitPersistMetaOperation<T>\n | BitHistoryApplyOperation<T>\n | BitValidationCommitOperation<T>;\n\nexport function patchStateOperation<T extends object>(\n partialState: Partial<BitState<T>>,\n changedPaths?: string[],\n options?: { skipComputed?: boolean },\n): BitStatePatchOperation<T> {\n return {\n kind: \"state.patch\",\n partialState,\n changedPaths,\n skipComputed: options?.skipComputed,\n };\n}\n\nexport function touchFieldsOperation<T extends object>(\n paths: string[],\n): BitTouchFieldsOperation<T> {\n return {\n kind: \"field.touchMany\",\n paths,\n };\n}\n\nexport function persistMetaOperation<T extends object>(\n patch: Partial<BitState<T>[\"persist\"]>,\n): BitPersistMetaOperation<T> {\n return {\n kind: \"form.persistMeta\",\n patch,\n };\n}\n\nexport function historyApplyOperation<T extends object>(\n values: T,\n isDirty: boolean,\n): BitHistoryApplyOperation<T> {\n return {\n kind: \"history.apply\",\n values,\n isDirty,\n };\n}\n\nexport function validationCommitOperation<T extends object>(\n errors: BitErrors<T>,\n isValid: boolean,\n): BitValidationCommitOperation<T> {\n return {\n kind: \"validation.commit\",\n errors,\n isValid,\n };\n}\n","import { deepClone, deepMerge } from \"../../utils\";\nimport type { BitState } from \"../contracts/types\";\nimport type { BitStoreEffectEngine } from \"../engines/effect-engine\";\nimport {\n patchStateOperation,\n persistMetaOperation,\n type BitStoreOperation,\n} from \"../engines/operation-engine\";\nimport type { BitDirtyManager } from \"../managers/core/dirty-manager\";\nimport type { BitFieldRegistry } from \"../registry/field-registry\";\n\ninterface ValidationAccess {\n cancelAll(): void;\n validate(): Promise<boolean>;\n}\n\n// NOTA: Estes WeakMaps são module-level intencionalmente.\n// A chave `dispatch` é sempre uma closure única por instância de store em produção.\n// Em testes, garanta que cada `createStore()` use um mock de dispatch diferente\n// para evitar vazamento de estado `isRestoring` entre testes.\nconst activeRestoringOpsByDispatch = new WeakMap<Function, number>();\nconst lastRestoringErrorByDispatch = new WeakMap<Function, Error | null>();\n\nfunction beginPersistOperation<T extends object>(args: {\n dispatch: (operation: BitStoreOperation<T>) => void;\n type: \"restoring\";\n}): void {\n const { dispatch } = args;\n const map = activeRestoringOpsByDispatch;\n const errorMap = lastRestoringErrorByDispatch;\n const active = map.get(dispatch) ?? 0;\n\n map.set(dispatch, active + 1);\n\n if (active === 0) {\n errorMap.set(dispatch, null);\n dispatch(\n persistMetaOperation({\n isRestoring: true,\n error: null,\n }),\n );\n }\n}\n\nfunction finalizePersistOperation<T extends object>(args: {\n dispatch: (operation: BitStoreOperation<T>) => void;\n type: \"restoring\";\n error: Error | null;\n}): void {\n const { dispatch, error } = args;\n const map = activeRestoringOpsByDispatch;\n const errorMap = lastRestoringErrorByDispatch;\n const active = map.get(dispatch) ?? 0;\n\n if (active <= 0) {\n return;\n }\n\n const nextActive = active - 1;\n\n if (error) {\n errorMap.set(dispatch, error);\n }\n\n if (nextActive > 0) {\n map.set(dispatch, nextActive);\n const pendingError = errorMap.get(dispatch) ?? null;\n if (pendingError) {\n dispatch(persistMetaOperation({ error: pendingError }));\n }\n return;\n }\n\n map.delete(dispatch);\n\n // If the last active operation succeeded, clear any stale concurrent error.\n if (!error) {\n errorMap.set(dispatch, null);\n }\n\n const finalError = errorMap.get(dispatch) ?? null;\n errorMap.delete(dispatch);\n\n dispatch(\n persistMetaOperation({\n isRestoring: false,\n error: finalError,\n }),\n );\n}\n\nexport async function restoreStorePersisted<T extends object>(args: {\n dispatch: (operation: BitStoreOperation<T>) => void;\n effects: BitStoreEffectEngine<T>;\n onUnhandledError?: (error: unknown, source: string) => void;\n}): Promise<boolean> {\n const { dispatch, effects, onUnhandledError } = args;\n beginPersistOperation({ dispatch, type: \"restoring\" });\n\n let operationError: Error | null = null;\n\n try {\n return await effects.restorePersisted();\n } catch (error) {\n operationError = error instanceof Error ? error : new Error(String(error));\n // Route to global error handler so observability tools (Sentry, Datadog,\n // etc.) capture the failure — the UI metadata update alone is not enough.\n onUnhandledError?.(operationError, \"persist\");\n return false;\n } finally {\n finalizePersistOperation({\n dispatch,\n type: \"restoring\",\n error: operationError,\n });\n }\n}\n\nexport async function forceStorePersistedSave<T extends object>(args: {\n dispatch: (operation: BitStoreOperation<T>) => void;\n effects: BitStoreEffectEngine<T>;\n onUnhandledError?: (error: unknown, source: string) => void;\n}): Promise<void> {\n const { effects, onUnhandledError } = args;\n\n try {\n await effects.savePersistedNow();\n } catch (error) {\n // Route to global error handler so observability tools capture the failure,\n // then re-throw so the caller can react (e.g., show an error message).\n onUnhandledError?.(error, \"persist\");\n throw error;\n }\n}\n\nexport async function clearStorePersisted<T extends object>(args: {\n dispatch: (operation: BitStoreOperation<T>) => void;\n effects: BitStoreEffectEngine<T>;\n onUnhandledError?: (error: unknown, source: string) => void;\n}): Promise<void> {\n const { effects, onUnhandledError } = args;\n\n try {\n await effects.clearPersisted();\n } catch (error) {\n // Route to global error handler so observability tools capture the failure,\n // then re-throw so the caller can react (e.g., show an error message).\n onUnhandledError?.(error, \"persist\");\n throw error;\n }\n}\n\nexport function applyStorePersistedValues<T extends object>(args: {\n values: Partial<T>;\n state: BitState<T>;\n initialValues: T;\n validation: ValidationAccess;\n fieldRegistry: BitFieldRegistry<T>;\n dirtyManager: BitDirtyManager<T>;\n dispatch: (operation: BitStoreOperation<T>) => void;\n saveHistorySnapshot: () => void;\n}): void {\n const {\n values,\n state,\n initialValues,\n validation,\n fieldRegistry,\n dirtyManager,\n dispatch,\n saveHistorySnapshot,\n } = args;\n\n const nextValues = deepClone(deepMerge(initialValues, values));\n\n validation.cancelAll();\n fieldRegistry.evaluateAll(nextValues);\n\n const isDirty = dirtyManager.rebuild(nextValues, initialValues);\n\n dispatch(\n patchStateOperation({\n values: nextValues,\n errors: {},\n touched: {},\n isValidating: {},\n persist: { ...state.persist, error: null },\n isValid: false,\n isDirty,\n }),\n );\n\n saveHistorySnapshot();\n void validation.validate().catch((error: unknown) => {\n console.error(\n \"BitStore: post-persist validation failed — form values persisted but validation error may be stale\",\n error,\n );\n });\n}\n","import type { BitErrors, BitState } from \"../contracts/types\";\n\nexport function buildFieldUnregisterPatch<T extends object>(args: {\n state: Readonly<BitState<T>>;\n path: string;\n}): Pick<BitState<T>, \"errors\" | \"touched\"> | null {\n const { state, path } = args;\n const prefix = `${path}.`;\n\n const nextErrors = { ...state.errors };\n const nextTouched = { ...state.touched };\n let changed = false;\n\n for (const key of Object.keys(nextErrors)) {\n if (key === path || key.startsWith(prefix)) {\n delete nextErrors[key as keyof BitErrors<T>];\n changed = true;\n }\n }\n\n for (const key of Object.keys(nextTouched)) {\n if (key === path || key.startsWith(prefix)) {\n delete nextTouched[key as keyof typeof nextTouched];\n changed = true;\n }\n }\n\n if (!changed) {\n return null;\n }\n\n return {\n errors: nextErrors,\n touched: nextTouched,\n };\n}\n","/**\n * Computed Dependency Analyzer\n *\n * Detects cyclic dependencies in computed fields at initialization time.\n * Prevents runtime errors where computed fields don't stabilize.\n *\n * This replaces the runtime \"did not stabilize\" error with early, clear feedback during setup.\n */\n\nexport interface CyclicDependencyError {\n cycle: string[];\n paths: string[];\n message: string;\n}\n\n/**\n * Analyzes a set of computed field definitions for cyclic dependencies.\n *\n * @param entries - Computed field entries with their dependency information\n * @returns Array of detected cycles, empty if no cycles found\n *\n * @example\n * ```typescript\n * const entries = [\n * { path: 'total', compute: ..., dependsOn: ['price', 'quantity'] },\n * { path: 'price', compute: ..., dependsOn: ['total'] }, // CYCLE!\n * ];\n * const cycles = analyzeCyclicDependencies(entries);\n * if (cycles.length > 0) {\n * throw new Error(`Cyclic dependencies: ${cycles[0].message}`);\n * }\n * ```\n */\nexport function analyzeCyclicDependencies<_T extends object>(\n entries: Array<{\n path: string;\n dependsOn?: readonly string[];\n }>,\n): CyclicDependencyError[] {\n const cycles: CyclicDependencyError[] = [];\n\n // Build adjacency list from dependencies\n const graph = new Map<string, Set<string>>();\n const computedPaths = new Set(entries.map((entry) => entry.path));\n\n for (const entry of entries) {\n if (!graph.has(entry.path)) {\n graph.set(entry.path, new Set());\n }\n\n if (entry.dependsOn) {\n for (const dep of entry.dependsOn) {\n // Only track dependencies between computed fields\n // Ignore dependencies on form values (not computed fields)\n if (computedPaths.has(dep)) {\n graph.get(entry.path)!.add(dep);\n }\n }\n }\n }\n\n // DFS to find cycles\n const visited = new Set<string>();\n const recursionStack = new Set<string>();\n\n const hasCycle = (\n node: string,\n path: string[],\n ): CyclicDependencyError | null => {\n visited.add(node);\n recursionStack.add(node);\n path.push(node);\n\n const neighbors = graph.get(node) || new Set();\n\n for (const neighbor of neighbors) {\n if (!visited.has(neighbor)) {\n const cycle = hasCycle(neighbor, [...path]);\n if (cycle) return cycle;\n } else if (recursionStack.has(neighbor)) {\n // Found a cycle\n const cycleStart = path.indexOf(neighbor);\n const cyclePath = [...path.slice(cycleStart), neighbor];\n\n return {\n cycle: cyclePath,\n paths: Array.from(graph.keys()).filter((p) => cyclePath.includes(p)),\n message: `Circular dependency detected: ${cyclePath.join(\n \" → \",\n )}. Check your computed field definitions.`,\n };\n }\n }\n\n recursionStack.delete(node);\n return null;\n };\n\n // Check each node for cycles\n for (const node of graph.keys()) {\n if (!visited.has(node)) {\n const cycle = hasCycle(node, []);\n if (cycle && !cycles.some((c) => c.message === cycle.message)) {\n cycles.push(cycle);\n }\n }\n }\n\n return cycles;\n}\n\n/**\n * Higher-order function that returns a validator for computed entries.\n * Useful for decorating BitStore initialization.\n *\n * @example\n * ```typescript\n * const validateComputeds = createComputedValidator();\n * const entries = getComputedEntries();\n * const errors = validateComputeds(entries);\n * if (errors.length > 0) {\n * console.error('Cyclic computeds:', errors);\n * throw new Error('Invalid computed field configuration');\n * }\n * ```\n */\nexport function createComputedValidator() {\n return function validate<_T extends object>(\n entries: Array<{\n path: string;\n dependsOn?: readonly string[];\n }>,\n ): CyclicDependencyError[] {\n return analyzeCyclicDependencies(entries);\n };\n}\n","import type { BitFieldDefinition, BitState } from \"../contracts/types\";\nimport {\n patchStateOperation,\n type BitStoreOperation,\n} from \"../engines/operation-engine\";\nimport { buildFieldUnregisterPatch } from \"../engines/store-field-cleanup-engine\";\nimport { BitSubscriptionEngine } from \"../engines/subscription-engine\";\nimport { analyzeCyclicDependencies } from \"../managers/core/computed-dependency-analyzer\";\nimport { BitFieldRegistry } from \"../registry/field-registry\";\nimport { isPathWithinPrefix, normalizePathPrefix } from \"../shared/path-prefix\";\nimport { getScopeRegistrySubscriptionPath } from \"../shared/scope-status\";\nimport type { BitStoreStateReader } from \"../shared/store-state-reader\";\n\nfunction hasValueDerivation<T extends object>(\n config?: BitFieldDefinition<T>,\n): boolean {\n return !!(config?.computed || config?.normalize);\n}\n\nexport function registerStoreField<T extends object>(args: {\n path: string;\n config: BitFieldDefinition<T>;\n state: BitState<T>;\n fieldRegistry: BitFieldRegistry<T>;\n subscriptions: BitSubscriptionEngine<T>;\n validationCleanupField: (path: string) => void;\n stateReader: BitStoreStateReader<T>;\n invalidateFieldIndexes: () => void;\n dispatch: (operation: BitStoreOperation<T>) => void;\n getState: () => BitState<T>;\n onUnhandledError: (error: unknown, source: string) => void;\n}): void {\n const {\n path,\n config,\n state,\n fieldRegistry,\n subscriptions,\n validationCleanupField,\n stateReader,\n invalidateFieldIndexes,\n dispatch,\n getState,\n onUnhandledError,\n } = args;\n\n const previousConfig = fieldRegistry.getFieldConfig(path);\n const previousAsyncValidate = previousConfig?.validation?.asyncValidate;\n const nextAsyncValidate = config.validation?.asyncValidate;\n const previousAsyncValidateOn =\n previousConfig?.validation?.asyncValidateOn ?? \"blur\";\n const nextAsyncValidateOn = config.validation?.asyncValidateOn ?? \"blur\";\n const shouldCleanupAsyncState =\n !!previousConfig &&\n !!previousAsyncValidate &&\n (nextAsyncValidate !== previousAsyncValidate ||\n nextAsyncValidateOn !== previousAsyncValidateOn);\n\n if (shouldCleanupAsyncState) {\n validationCleanupField(path);\n }\n\n const shouldValidateComputedGraph = !!(\n previousConfig?.computed || config.computed\n );\n const shouldRecomputeValues =\n hasValueDerivation(previousConfig) || hasValueDerivation(config);\n\n fieldRegistry.register(path, config, state.values);\n invalidateFieldIndexes();\n\n if (shouldValidateComputedGraph) {\n const cycles = analyzeCyclicDependencies(\n fieldRegistry.getComputedEntries(state.values),\n );\n\n if (cycles.length > 0) {\n if (previousConfig) {\n fieldRegistry.register(path, previousConfig, state.values);\n } else {\n fieldRegistry.unregister(path);\n }\n\n invalidateFieldIndexes();\n subscriptions.invalidatePathExpansionCache(path);\n stateReader.invalidatePath(path);\n onUnhandledError(new Error(cycles[0].message), \"computed\");\n return;\n }\n }\n\n subscriptions.invalidatePathExpansionCache(path);\n stateReader.invalidatePath(path);\n\n if (shouldRecomputeValues) {\n dispatch(\n patchStateOperation(\n {\n values: state.values,\n },\n [\"*\"],\n ),\n );\n }\n\n const currentState = getState();\n\n if (config.scope) {\n subscriptions.notify(currentState, [\n getScopeRegistrySubscriptionPath(config.scope),\n ]);\n }\n\n if (fieldRegistry.isHidden(path)) {\n subscriptions.notify(currentState, [path]);\n }\n}\n\nexport function unregisterStoreField<T extends object>(args: {\n path: string;\n state: BitState<T>;\n hasStaticConfig: boolean;\n fieldRegistry: BitFieldRegistry<T>;\n subscriptions: BitSubscriptionEngine<T>;\n validationCleanupField: (path: string) => void;\n invalidateFieldIndexes: () => void;\n dispatch: (operation: BitStoreOperation<T>) => void;\n}): void {\n const {\n path,\n state,\n hasStaticConfig,\n fieldRegistry,\n subscriptions,\n validationCleanupField,\n invalidateFieldIndexes,\n dispatch,\n } = args;\n\n if (hasStaticConfig) {\n return;\n }\n\n const fieldConfig = fieldRegistry.getFieldConfig(path);\n validationCleanupField(path);\n fieldRegistry.unregister(path);\n invalidateFieldIndexes();\n subscriptions.invalidatePathExpansionCache(path);\n\n if (fieldConfig?.scope) {\n subscriptions.notify(state, [\n getScopeRegistrySubscriptionPath(fieldConfig.scope),\n ]);\n }\n\n const cleanupPatch = buildFieldUnregisterPatch({ state, path });\n\n if (!cleanupPatch) {\n return;\n }\n\n dispatch(\n patchStateOperation({\n errors: cleanupPatch.errors,\n touched: cleanupPatch.touched,\n }),\n );\n}\n\nexport function unregisterStorePrefix<T extends object>(args: {\n prefix: string;\n state: BitState<T>;\n fieldRegistry: BitFieldRegistry<T>;\n subscriptions: BitSubscriptionEngine<T>;\n validationCleanupPrefix: (prefix: string) => void;\n invalidateFieldIndexes: () => void;\n dispatch: (operation: BitStoreOperation<T>) => void;\n hasStaticConfigPath?: (path: string) => boolean;\n}): void {\n const {\n prefix,\n state,\n fieldRegistry,\n subscriptions,\n validationCleanupPrefix,\n invalidateFieldIndexes,\n dispatch,\n hasStaticConfigPath,\n } = args;\n\n validationCleanupPrefix(prefix);\n\n const normalizedPrefix = normalizePathPrefix(prefix);\n const isStaticPath = hasStaticConfigPath ?? (() => false);\n const removablePaths: string[] = [];\n\n fieldRegistry.forEachFieldConfig((_config, path) => {\n if (!isPathWithinPrefix(path, normalizedPrefix)) {\n return;\n }\n\n if (isStaticPath(path)) {\n return;\n }\n\n removablePaths.push(path);\n });\n\n const removedEntries: [string, BitFieldDefinition<T>][] = [];\n removablePaths.forEach((path) => {\n const config = fieldRegistry.getFieldConfig(path);\n if (!config) {\n return;\n }\n\n fieldRegistry.unregister(path);\n removedEntries.push([path, config]);\n });\n\n invalidateFieldIndexes();\n subscriptions.invalidatePathExpansionCache(prefix);\n\n const impactedScopes = new Set(\n removedEntries\n .map(([, config]) => config.scope)\n .filter((scopeName): scopeName is string => !!scopeName),\n );\n\n impactedScopes.forEach((scopeName) => {\n subscriptions.notify(state, [getScopeRegistrySubscriptionPath(scopeName)]);\n });\n\n const nextErrors = { ...state.errors };\n const nextTouched = { ...state.touched };\n let changed = false;\n\n for (const [entryPath] of removedEntries) {\n if (nextErrors[entryPath as keyof typeof nextErrors]) {\n delete nextErrors[entryPath as keyof typeof nextErrors];\n changed = true;\n }\n if (nextTouched[entryPath as keyof typeof nextTouched]) {\n delete nextTouched[entryPath as keyof typeof nextTouched];\n changed = true;\n }\n }\n\n if (changed) {\n dispatch(patchStateOperation({ errors: nextErrors, touched: nextTouched }));\n }\n}\n","import type {\n BitScopedSelectorSubscriptionOptions,\n BitSelector,\n} from \"../contracts/public/subscription-types\";\nimport type { BitState } from \"../contracts/types\";\nimport { isPathWithinPrefix, normalizePathPrefix } from \"../shared/path-prefix\";\n\ninterface SelectorListenerEntry<T extends object> {\n notify(nextState: Readonly<BitState<T>>): void;\n}\n\nconst SUBSCRIPTION_ERROR_SOURCE = \"subscription\";\n\nexport interface BitSubscriptionCacheStats {\n cacheSize: number;\n cacheLimit: number;\n cacheHits: number;\n cacheMisses: number;\n cacheEvictions: number;\n}\n\nexport class BitSubscriptionEngine<T extends object> {\n private listeners: Set<() => void> = new Set();\n private pathScopedSubscriptions: Map<SelectorListenerEntry<T>, string[]> =\n new Map();\n private pathSelectorIndex: Map<string, Set<SelectorListenerEntry<T>>> =\n new Map();\n private readonly pathExpansionCache = new Map<string, string[]>();\n private readonly subscriptionSeenVersion = new Map<\n SelectorListenerEntry<T>,\n number\n >();\n private notifyVersion = 0;\n private readonly MAX_PATH_EXPANSION_CACHE_SIZE: number;\n private cacheHits = 0;\n private cacheMisses = 0;\n private cacheEvictions = 0;\n private readonly onError?: (error: unknown, source: string) => void;\n\n /**\n * Maximum number of entries for path expansion cache.\n * Lower = less memory; higher = fewer cache evictions in large dynamic forms.\n * @default 500\n */\n constructor(\n private readonly getState: () => Readonly<BitState<T>>,\n onErrorOrMaxCache?: ((error: unknown, source: string) => void) | number,\n maxCacheSize = 500,\n ) {\n if (typeof onErrorOrMaxCache === \"function\") {\n this.onError = onErrorOrMaxCache;\n this.MAX_PATH_EXPANSION_CACHE_SIZE = maxCacheSize;\n return;\n }\n\n this.MAX_PATH_EXPANSION_CACHE_SIZE = onErrorOrMaxCache ?? maxCacheSize;\n }\n\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n subscribeSelector<TSlice>(\n selector: BitSelector<T, TSlice>,\n listener: (slice: TSlice) => void,\n options: BitScopedSelectorSubscriptionOptions<TSlice>,\n equalityFn: (previous: TSlice, next: TSlice) => boolean,\n ): () => void {\n let lastSlice = selector(this.getState());\n\n const subscription: SelectorListenerEntry<T> = {\n notify: (nextState) => {\n try {\n const nextSlice = selector(nextState);\n\n if (equalityFn(lastSlice, nextSlice)) {\n return;\n }\n\n lastSlice = nextSlice;\n listener(nextSlice);\n } catch (error) {\n this.reportError(error);\n }\n },\n };\n\n const scopedPaths = this.normalizeSubscriptionPaths(options.paths);\n\n this.pathScopedSubscriptions.set(subscription, scopedPaths);\n scopedPaths.forEach((pathKey) => {\n this.forEachIndexPath(pathKey, (indexPath) => {\n const listeners = this.pathSelectorIndex.get(indexPath) ?? new Set();\n listeners.add(subscription);\n this.pathSelectorIndex.set(indexPath, listeners);\n });\n });\n\n if (options.emitImmediately) {\n try {\n listener(lastSlice);\n } catch (error) {\n this.reportError(error);\n }\n }\n\n return () => {\n this.subscriptionSeenVersion.delete(subscription);\n\n const paths = this.pathScopedSubscriptions.get(subscription);\n if (!paths) return;\n\n paths.forEach((pathKey) => {\n this.forEachIndexPath(pathKey, (indexPath) => {\n const listeners = this.pathSelectorIndex.get(indexPath);\n if (!listeners) return;\n\n listeners.delete(subscription);\n if (listeners.size === 0) {\n this.pathSelectorIndex.delete(indexPath);\n }\n });\n });\n\n this.pathScopedSubscriptions.delete(subscription);\n };\n }\n\n notify(\n nextState: Readonly<BitState<T>>,\n changedPaths?: Iterable<string>,\n ): void {\n this.listeners.forEach((listener) => {\n try {\n listener();\n } catch (error) {\n this.reportError(error);\n }\n });\n\n if (this.pathScopedSubscriptions.size === 0) {\n return;\n }\n\n const normalizedChangedPaths =\n this.normalizeChangedPathIterable(changedPaths);\n\n if (\n normalizedChangedPaths.length === 0 ||\n normalizedChangedPaths.includes(\"*\")\n ) {\n this.notifyScopedSubscribers(\n this.pathScopedSubscriptions.keys(),\n nextState,\n );\n return;\n }\n\n if (\n normalizedChangedPaths.length === 1 &&\n this.isSimplePath(normalizedChangedPaths[0])\n ) {\n const singleScopedSubscribers =\n this.collectSubscribersForSingleChangedPath(normalizedChangedPaths[0]);\n\n this.notifyScopedSubscribers(singleScopedSubscribers, nextState);\n return;\n }\n\n const scopedSubscribers = this.collectSubscribersForChangedPaths(\n normalizedChangedPaths,\n );\n\n this.notifyScopedSubscribers(scopedSubscribers, nextState);\n }\n\n private notifyScopedSubscribers(\n subscriptions: Iterable<SelectorListenerEntry<T>>,\n nextState: Readonly<BitState<T>>,\n ): void {\n for (const subscription of subscriptions) {\n try {\n subscription.notify(nextState);\n } catch (error) {\n this.reportError(error);\n }\n }\n }\n\n private reportError(error: unknown): void {\n try {\n if (this.onError) {\n this.onError(error, SUBSCRIPTION_ERROR_SOURCE);\n return;\n }\n \n console.error(\"Subscription listener error:\", error);\n } catch (e) {\n // Isolamento total contra quebras no laço de inscrição\n }\n }\n\n destroy(): void {\n this.listeners.clear();\n this.pathScopedSubscriptions.clear();\n this.pathSelectorIndex.clear();\n this.pathExpansionCache.clear();\n this.subscriptionSeenVersion.clear();\n }\n\n getPathExpansionCacheStats(): BitSubscriptionCacheStats {\n return {\n cacheSize: this.pathExpansionCache.size,\n cacheLimit: this.MAX_PATH_EXPANSION_CACHE_SIZE,\n cacheHits: this.cacheHits,\n cacheMisses: this.cacheMisses,\n cacheEvictions: this.cacheEvictions,\n };\n }\n\n getActiveSubscribersCount(): number {\n return this.pathScopedSubscriptions.size;\n }\n\n invalidatePathExpansionCache(prefix?: string): void {\n if (!prefix) {\n this.pathExpansionCache.clear();\n return;\n }\n\n const normalizedPrefix = normalizePathPrefix(prefix);\n if (normalizedPrefix.length === 0) {\n this.pathExpansionCache.clear();\n return;\n }\n\n for (const key of this.pathExpansionCache.keys()) {\n if (\n isPathWithinPrefix(key, normalizedPrefix) ||\n isPathWithinPrefix(normalizedPrefix, key)\n ) {\n this.pathExpansionCache.delete(key);\n }\n }\n }\n\n private normalizeSubscriptionPaths(paths?: string[]): string[] {\n if (!paths || paths.length === 0) return [];\n\n const seen = new Set<string>();\n const normalized: string[] = [];\n\n for (const path of paths) {\n if (path == null) continue;\n const trimmed = path.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) {\n continue;\n }\n\n seen.add(trimmed);\n normalized.push(trimmed);\n }\n\n return normalized;\n }\n\n private normalizeChangedPathIterable(paths?: Iterable<string>): string[] {\n if (!paths) {\n return [];\n }\n\n const seen = new Set<string>();\n const normalized: string[] = [];\n\n for (const path of paths) {\n if (path == null) continue;\n const trimmed = path.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) {\n continue;\n }\n\n seen.add(trimmed);\n normalized.push(trimmed);\n }\n\n return normalized;\n }\n\n private collectSubscribersForChangedPaths(\n changedPaths: string[],\n ): SelectorListenerEntry<T>[] {\n const scopedSubscribers: SelectorListenerEntry<T>[] = [];\n // Wrap in 32-bit signed integer to avoid Number.MAX_SAFE_INTEGER stall:\n // ++x at MAX_SAFE_INTEGER returns MAX_SAFE_INTEGER again, making the\n // `seenVersion >= currentVersion` guard fire on every subsequent call and\n // silently stopping all scoped subscribers. Bitwise OR forces 32-bit wrap.\n this.notifyVersion = (this.notifyVersion + 1) | 0;\n const currentVersion = this.notifyVersion;\n\n const addByPath = (path: string) => {\n const listeners = this.pathSelectorIndex.get(path);\n if (!listeners) return;\n\n listeners.forEach((subscription) => {\n const seenVersion = this.subscriptionSeenVersion.get(subscription) ?? Number.NaN;\n if (seenVersion === currentVersion) {\n return;\n }\n\n this.subscriptionSeenVersion.set(subscription, currentVersion);\n scopedSubscribers.push(subscription);\n });\n };\n\n changedPaths.forEach((changedPath) => {\n this.forEachLookupPath(changedPath, addByPath);\n });\n\n return scopedSubscribers;\n }\n\n private collectSubscribersForSingleChangedPath(\n changedPath: string,\n ): SelectorListenerEntry<T>[] {\n const scopedSubscribers: SelectorListenerEntry<T>[] = [];\n this.notifyVersion = (this.notifyVersion + 1) | 0;\n const currentVersion = this.notifyVersion;\n\n const addByPath = (path: string) => {\n const listeners = this.pathSelectorIndex.get(path);\n if (!listeners) return;\n\n listeners.forEach((subscription) => {\n const seenVersion = this.subscriptionSeenVersion.get(subscription) ?? Number.NaN;\n if (seenVersion === currentVersion) {\n return;\n }\n\n this.subscriptionSeenVersion.set(subscription, currentVersion);\n scopedSubscribers.push(subscription);\n });\n };\n\n this.forEachLookupPath(changedPath, addByPath);\n return scopedSubscribers;\n }\n\n private expandChangedPathForLookup(path: string): string[] {\n // Use unified expansion cache\n return this.expandPathGeneric(path);\n }\n\n private expandPathForIndexing(path: string): string[] {\n // Use unified expansion cache\n return this.expandPathGeneric(path);\n }\n\n private forEachIndexPath(\n path: string,\n visitor: (path: string) => void,\n ): void {\n if (!this.isSimplePath(path)) {\n this.expandPathForIndexing(path).forEach(visitor);\n return;\n }\n\n const segments = path.split(\".\");\n let currentPath = \"\";\n\n for (let index = 0; index < segments.length; index += 1) {\n currentPath = currentPath\n ? `${currentPath}.${segments[index]}`\n : segments[index];\n visitor(currentPath);\n }\n }\n\n private forEachLookupPath(\n path: string,\n visitor: (path: string) => void,\n ): void {\n if (!this.isSimplePath(path)) {\n this.expandChangedPathForLookup(path).forEach(visitor);\n return;\n }\n\n visitor(path);\n\n let separatorIndex = path.lastIndexOf(\".\");\n while (separatorIndex > -1) {\n visitor(path.slice(0, separatorIndex));\n separatorIndex = path.lastIndexOf(\".\", separatorIndex - 1);\n }\n }\n\n private isSimplePath(path: string): boolean {\n return !path.includes(\"*\") && !path.includes(\"[\") && !path.includes(\"]\");\n }\n\n private expandPathGeneric(path: string): string[] {\n const cached = this.pathExpansionCache.get(path);\n if (cached) {\n this.cacheHits += 1;\n return cached;\n }\n\n this.cacheMisses += 1;\n\n const segments = path.split(\".\");\n const keys: string[] = [];\n for (let i = 1; i <= segments.length; i++) {\n keys.push(segments.slice(0, i).join(\".\"));\n }\n this.setBoundedCacheEntry(\n this.pathExpansionCache,\n path,\n keys,\n this.MAX_PATH_EXPANSION_CACHE_SIZE,\n );\n return keys;\n }\n\n private setBoundedCacheEntry<K, V>(\n cache: Map<K, V>,\n key: K,\n value: V,\n maxSize: number,\n ) {\n if (cache.size >= maxSize) {\n const oldestKey = cache.keys().next().value;\n if (oldestKey !== undefined) {\n cache.delete(oldestKey);\n this.cacheEvictions += 1;\n }\n }\n\n cache.set(key, value);\n }\n}\n","import { getDeepValue, reindexFieldArrayMeta } from \"../../../utils\";\nimport type { BitFieldChangeMeta, BitState } from \"../../contracts/types\";\nimport {\n BitStoreOperation,\n patchStateOperation,\n} from \"../../engines/operation-engine\";\nimport { toPathPrefix } from \"../../shared/path-prefix\";\n\nexport interface BitArrayStorePort<T extends object> {\n getState: () => BitState<T>;\n setFieldWithMeta: (\n path: string,\n value: unknown,\n meta: BitFieldChangeMeta,\n ) => void;\n dispatch: (operation: BitStoreOperation<T>) => void;\n internalSaveSnapshot: () => void;\n createArrayItemId: (path: string, index?: number) => string;\n unregisterPrefix?: (prefix: string) => void;\n remapValidationPaths?: (\n path: string,\n remapIndex: (currentIdx: number) => number | null,\n ) => void;\n}\n\nexport class BitArrayManager<T extends object = Record<string, unknown>> {\n private readonly pathIds = new Map<string, string[]>();\n\n constructor(private store: BitArrayStorePort<T>) {}\n\n getItemIds(path: string, length?: number): string[] {\n const targetLength =\n typeof length === \"number\"\n ? Math.max(0, length)\n : this.getCurrentArrayLength(path);\n\n return [...this.ensureIds(path, targetLength)];\n }\n\n pushItem(path: string, value: unknown) {\n this.withPathIds(path, (ids) => {\n ids.push(this.store.createArrayItemId(path, ids.length));\n return ids;\n });\n\n this.store.unregisterPrefix?.(toPathPrefix(path));\n\n this.commitArrayMutationWithFieldPipeline({\n path,\n nextArray: [...((getDeepValue(this.store.getState().values, path) as unknown[] | undefined) ?? []), value],\n meta: { origin: \"array\", operation: \"push\" },\n reindex: (currentIdx) => currentIdx,\n });\n }\n\n prependItem(path: string, value: unknown) {\n this.withPathIds(path, (ids) => {\n ids.unshift(this.store.createArrayItemId(path, 0));\n return ids;\n });\n\n this.store.unregisterPrefix?.(toPathPrefix(path));\n\n const current =\n (getDeepValue(this.store.getState().values, path) as\n | unknown[]\n | undefined) ?? [];\n this.commitArrayMutationWithFieldPipeline({\n path,\n nextArray: [value, ...current],\n meta: { origin: \"array\", operation: \"prepend\" },\n reindex: (currentIdx) => currentIdx + 1,\n });\n }\n\n insertItem(path: string, index: number, value: unknown) {\n const currentLength = this.getCurrentArrayLength(path);\n const safeIndex = Math.max(0, Math.min(index, currentLength));\n\n this.withPathIds(path, (ids) => {\n const next = [...ids];\n next.splice(safeIndex, 0, this.store.createArrayItemId(path, safeIndex));\n return next;\n });\n\n if (this.store.unregisterPrefix) {\n for (let i = safeIndex; i < currentLength; i++) {\n this.store.unregisterPrefix(toPathPrefix(path, i));\n }\n }\n\n const current =\n (getDeepValue(this.store.getState().values, path) as\n | unknown[]\n | undefined) ?? [];\n const nextArray = [...current];\n nextArray.splice(safeIndex, 0, value);\n\n this.commitArrayMutationWithFieldPipeline({\n path,\n nextArray,\n meta: { origin: \"array\", operation: \"insert\", index: safeIndex },\n reindex: (currentIdx) =>\n currentIdx < safeIndex ? currentIdx : currentIdx + 1,\n });\n }\n\n removeItem(path: string, index: number) {\n const state = this.store.getState();\n const arr = getDeepValue(state.values, path);\n if (!Array.isArray(arr)) return;\n if (index < 0 || index >= arr.length) return;\n\n this.withPathIds(path, (ids) => {\n const next = [...ids];\n next.splice(index, 1);\n return next;\n });\n\n if (this.store.unregisterPrefix) {\n this.store.unregisterPrefix(toPathPrefix(path, index));\n }\n\n const newArray = arr.filter((_, i) => i !== index);\n\n this.commitArrayMutationWithFieldPipeline({\n path,\n nextArray: newArray,\n meta: { origin: \"array\", operation: \"remove\", index },\n reindex: (currentIdx) => {\n if (currentIdx === index) {\n return null;\n }\n\n return currentIdx > index ? currentIdx - 1 : currentIdx;\n },\n });\n }\n\n swapItems(path: string, indexA: number, indexB: number) {\n const state = this.store.getState();\n const source = getDeepValue(state.values, path);\n if (!Array.isArray(source)) return;\n if (indexA < 0 || indexA >= source.length) return;\n if (indexB < 0 || indexB >= source.length) return;\n\n this.withPathIds(path, (ids) => {\n const next = [...ids];\n [next[indexA], next[indexB]] = [next[indexB], next[indexA]];\n return next;\n });\n\n const arr = [...source];\n [arr[indexA], arr[indexB]] = [arr[indexB], arr[indexA]];\n\n if (this.store.unregisterPrefix) {\n this.store.unregisterPrefix(toPathPrefix(path, indexA));\n this.store.unregisterPrefix(toPathPrefix(path, indexB));\n }\n\n this.commitArrayMutationWithFieldPipeline({\n path,\n nextArray: arr,\n meta: {\n origin: \"array\",\n operation: \"swap\",\n from: indexA,\n to: indexB,\n },\n reindex: (currentIdx) => {\n if (currentIdx === indexA) {\n return indexB;\n }\n\n if (currentIdx === indexB) {\n return indexA;\n }\n\n return currentIdx;\n },\n });\n }\n\n moveItem(path: string, from: number, to: number) {\n const state = this.store.getState();\n const source = getDeepValue(state.values, path);\n if (!Array.isArray(source)) return;\n if (from < 0 || from >= source.length) return;\n if (to < 0 || to >= source.length) return;\n\n this.withPathIds(path, (ids) => {\n const next = [...ids];\n const [id] = next.splice(from, 1);\n next.splice(to, 0, id);\n return next;\n });\n\n const arr = [...source];\n const [item] = arr.splice(from, 1);\n arr.splice(to, 0, item);\n\n if (this.store.unregisterPrefix) {\n const minIndex = Math.min(from, to);\n const maxIndex = Math.max(from, to);\n\n for (let index = minIndex; index <= maxIndex; index += 1) {\n this.store.unregisterPrefix(toPathPrefix(path, index));\n }\n }\n\n this.commitArrayMutationWithFieldPipeline({\n path,\n nextArray: arr,\n meta: {\n origin: \"array\",\n operation: \"move\",\n from,\n to,\n },\n reindex: (currentIdx) => {\n if (currentIdx === from) {\n return to;\n }\n\n if (from < to && currentIdx > from && currentIdx <= to) {\n return currentIdx - 1;\n }\n\n if (from > to && currentIdx >= to && currentIdx < from) {\n return currentIdx + 1;\n }\n\n return currentIdx;\n },\n });\n }\n\n replaceItems(path: string, items: unknown[]) {\n this.store.unregisterPrefix?.(toPathPrefix(path));\n\n if (items.length === 0) {\n this.pathIds.delete(path);\n } else {\n this.pathIds.set(\n path,\n items.map((_, index) => this.store.createArrayItemId(path, index)),\n );\n }\n\n this.commitArrayMutationWithFieldPipeline({\n path,\n nextArray: items,\n meta: { origin: \"array\", operation: \"replace\" },\n reindex: (currentIdx) => (currentIdx < items.length ? currentIdx : null),\n });\n }\n\n clearItems(path: string) {\n this.pathIds.delete(path);\n\n if (this.store.unregisterPrefix) {\n this.store.unregisterPrefix(toPathPrefix(path));\n }\n\n this.commitArrayMutationWithFieldPipeline({\n path,\n nextArray: [],\n meta: { origin: \"array\", operation: \"clear\" },\n reindex: () => null,\n });\n }\n\n private mutateArrayWithSetField(\n path: string,\n mutate: (current: unknown[]) => unknown[],\n meta: BitFieldChangeMeta,\n ) {\n const current = getDeepValue(this.store.getState().values, path) || [];\n this.store.setFieldWithMeta(path, mutate(current), meta);\n this.store.internalSaveSnapshot();\n }\n\n private withPathIds(path: string, updater: (ids: string[]) => string[]) {\n const currentLength = this.getCurrentArrayLength(path);\n const current = this.ensureIds(path, currentLength);\n const next = updater(current);\n\n if (next.length === 0) {\n this.pathIds.delete(path);\n } else {\n this.pathIds.set(path, next);\n }\n }\n\n private ensureIds(path: string, length: number): string[] {\n const current = this.pathIds.get(path) ?? [];\n\n if (current.length === length) {\n return current;\n }\n\n if (current.length < length) {\n const next = [...current];\n for (let index = current.length; index < length; index += 1) {\n next.push(this.store.createArrayItemId(path, index));\n }\n this.pathIds.set(path, next);\n return next;\n }\n\n const next = current.slice(0, length);\n\n if (next.length === 0) {\n this.pathIds.delete(path);\n } else {\n this.pathIds.set(path, next);\n }\n\n return next;\n }\n\n private getCurrentArrayLength(path: string): number {\n const value = getDeepValue(this.store.getState().values, path);\n return Array.isArray(value) ? value.length : 0;\n }\n\n private commitArrayMutationWithFieldPipeline(args: {\n path: string;\n nextArray: unknown[];\n meta: BitFieldChangeMeta;\n reindex: (currentIdx: number) => number | null;\n }) {\n const { path, nextArray, meta, reindex } = args;\n const previousState = this.store.getState();\n\n this.store.setFieldWithMeta(path, nextArray, meta);\n\n const reindexedMeta = reindexFieldArrayMeta(previousState, path, reindex);\n\n this.store.remapValidationPaths?.(path, reindex);\n\n this.store.dispatch(\n patchStateOperation(\n {\n errors: reindexedMeta.errors,\n touched: reindexedMeta.touched,\n isValidating: reindexedMeta.isValidating,\n },\n [path],\n ),\n );\n\n this.store.internalSaveSnapshot();\n }\n}\n","import type { BitServerErrorOptions } from \"../../contracts/public/meta-types\";\nimport { BitErrors, BitState } from \"../../contracts/types\";\nimport {\n BitStoreOperation,\n patchStateOperation,\n} from \"../../engines/operation-engine\";\n\n/**\n * BitErrorManager\n *\n * Manages error state for fields.\n * Handles setting individual errors, batch errors, and server errors.\n */\nexport class BitErrorManager<T extends object = Record<string, unknown>> {\n constructor(\n private getState: () => BitState<T>,\n private dispatch: (operation: BitStoreOperation<T>) => void,\n private reportError?: (error: unknown) => void,\n ) {}\n\n private reportInvalidInput(message: string, details?: unknown) {\n this.reportError?.(\n new Error(\n details === undefined ? message : `${message}: ${String(details)}`,\n ),\n );\n }\n\n /**\n * Set or clear error for a single field.\n * Pass undefined to clear the error.\n */\n setError(path: string, message: string | undefined): void {\n if (!path || typeof path !== \"string\") {\n this.reportInvalidInput(\"setError received an invalid path\", path);\n return;\n }\n\n if (message !== undefined && typeof message !== \"string\") {\n this.reportInvalidInput(\"setError received an invalid message\", message);\n return;\n }\n\n const newErrors = {\n ...this.getState().errors,\n [path]: message,\n } as BitErrors<T>;\n\n if (message === undefined) {\n delete newErrors[path as keyof BitErrors<T>];\n }\n\n this.dispatch(patchStateOperation({ errors: newErrors }));\n }\n\n /**\n * Set multiple field errors at once (merge behavior).\n */\n setErrors(errors: BitErrors<T>): void {\n if (!errors || typeof errors !== \"object\") {\n this.reportInvalidInput(\"setErrors received an invalid payload\");\n return;\n }\n\n const sanitizedErrors: BitErrors<T> = {};\n\n Object.entries(errors).forEach(([path, message]) => {\n if (!path) {\n this.reportInvalidInput(\"setErrors ignored an empty path\");\n return;\n }\n\n if (message !== undefined && typeof message !== \"string\") {\n this.reportInvalidInput(\"setErrors ignored a non-string message\", path);\n return;\n }\n\n sanitizedErrors[path as keyof BitErrors<T>] = message;\n });\n\n this.dispatch(\n patchStateOperation({\n errors: { ...this.getState().errors, ...sanitizedErrors },\n }),\n );\n }\n\n /**\n * Set errors from server response (converts arrays to first element).\n * Useful for handling 422 validation error responses.\n */\n setServerErrors(\n serverErrors: Record<string, string[] | string>,\n options?: BitServerErrorOptions,\n ): void {\n const arrayStrategy = options?.arrayStrategy ?? \"first\";\n const joinSeparator = options?.joinSeparator ?? \"; \";\n const formattedErrors: BitErrors<T> = {};\n\n for (const [key, value] of Object.entries(serverErrors)) {\n if (!key) {\n this.reportInvalidInput(\"setServerErrors ignored an empty path\");\n continue;\n }\n\n if (Array.isArray(value)) {\n const normalizedMessages = value.filter(\n (message): message is string =>\n typeof message === \"string\" && message.length > 0,\n );\n\n if (normalizedMessages.length === 0) {\n continue;\n }\n\n formattedErrors[key as keyof BitErrors<T>] =\n arrayStrategy === \"join\"\n ? normalizedMessages.join(joinSeparator)\n : normalizedMessages[0];\n continue;\n }\n\n formattedErrors[key as keyof BitErrors<T>] = value;\n }\n\n this.setErrors(formattedErrors);\n }\n}\n","import { BitState } from \"../../contracts/types\";\nimport type { BitFieldMetadataProvider } from \"../../registry/field-metadata-provider\";\n\n/**\n * BitFieldQueryManager\n *\n * Provides query methods for field state without mutating.\n * All methods are read-only and delegate to appropriate managers.\n */\nexport class BitFieldQueryManager<T extends object = Record<string, unknown>> {\n private requiredValuesRef: T | null = null;\n\n constructor(\n private fieldMetadataProvider: BitFieldMetadataProvider<T>,\n private getState: () => BitState<T>,\n private isPathDirty: (path: string) => boolean,\n ) {}\n\n /**\n * Check if a field is hidden based on conditional logic.\n */\n isHidden<P extends string>(path: P): boolean {\n return this.fieldMetadataProvider.isHidden(path);\n }\n\n /**\n * Check if a field is required based on conditional logic.\n */\n isRequired<P extends string>(path: P): boolean {\n const values = this.getState().values;\n\n if (this.requiredValuesRef !== values) {\n this.requiredValuesRef = values;\n }\n\n return this.fieldMetadataProvider.isRequired(path, values);\n }\n\n /**\n * Check if a field has been modified from its initial value.\n */\n isFieldDirty(path: string): boolean {\n return this.isPathDirty(path);\n }\n\n /**\n * Check if a field is currently validating (async validation in progress).\n */\n isFieldValidating(path: string): boolean {\n return !!this.getState().isValidating[path];\n }\n\n isTouched(path: string): boolean {\n return !!this.getState().touched[path];\n }\n}\n","import {\n deepClone,\n deepEqual,\n setDeepValues,\n unsetDeepValues,\n} from \"../../utils\";\n\ntype HistoryDirection = \"undo\" | \"redo\";\n\nexport interface BitHistoryPatchOperation {\n path: string;\n previousValue: unknown;\n nextValue: unknown;\n hadPreviousValue: boolean;\n hasNextValue: boolean;\n}\n\nexport interface BitHistoryPatch<T extends object> {\n operations: BitHistoryPatchOperation[];\n _type?: T;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n !(value instanceof RegExp)\n );\n}\n\nexport function createHistoryPatch<T extends object>(\n previousValue: T,\n nextValue: T,\n): BitHistoryPatch<T> {\n const operations: BitHistoryPatchOperation[] = [];\n const activePairs = new Map<object, Set<object>>();\n\n const visit = (\n previousNode: unknown,\n nextNode: unknown,\n path: string,\n hadPreviousValue: boolean,\n hasNextValue: boolean,\n ) => {\n if (hadPreviousValue && hasNextValue && deepEqual(previousNode, nextNode)) {\n return;\n }\n\n if (\n previousNode !== null &&\n typeof previousNode === \"object\" &&\n nextNode !== null &&\n typeof nextNode === \"object\"\n ) {\n const activeNextNodes = activePairs.get(previousNode as object);\n if (activeNextNodes?.has(nextNode as object)) {\n return;\n }\n\n if (activeNextNodes) {\n activeNextNodes.add(nextNode as object);\n } else {\n activePairs.set(previousNode as object, new Set([nextNode as object]));\n }\n }\n\n try {\n if (\n isPlainObject(previousNode) &&\n isPlainObject(nextNode) &&\n hadPreviousValue &&\n hasNextValue\n ) {\n const keys = new Set<string>([\n ...Object.keys(previousNode),\n ...Object.keys(nextNode),\n ]);\n\n for (const key of keys) {\n const childPath = path ? `${path}.${key}` : key;\n const childHasPrevious = Object.prototype.hasOwnProperty.call(\n previousNode,\n key,\n );\n const childHasNext = Object.prototype.hasOwnProperty.call(\n nextNode,\n key,\n );\n\n visit(\n previousNode[key],\n nextNode[key],\n childPath,\n childHasPrevious,\n childHasNext,\n );\n }\n return;\n }\n\n operations.push({\n path,\n previousValue: deepClone(previousNode),\n nextValue: deepClone(nextNode),\n hadPreviousValue,\n hasNextValue,\n });\n } finally {\n if (\n previousNode !== null &&\n typeof previousNode === \"object\" &&\n nextNode !== null &&\n typeof nextNode === \"object\"\n ) {\n const nextActiveNodes = activePairs.get(previousNode as object);\n nextActiveNodes?.delete(nextNode as object);\n\n if (nextActiveNodes && nextActiveNodes.size === 0) {\n activePairs.delete(previousNode as object);\n }\n }\n }\n };\n\n visit(previousValue, nextValue, \"\", true, true);\n\n return {\n operations,\n };\n}\n\nexport function applyHistoryPatch<T extends object>(\n currentValue: T,\n patch: BitHistoryPatch<T>,\n direction: HistoryDirection,\n): T {\n let nextValue: unknown = currentValue;\n const setUpdates: Array<readonly [string, unknown]> = [];\n const unsetPaths: string[] = [];\n\n for (const operation of patch.operations) {\n const shouldSet =\n direction === \"undo\"\n ? operation.hadPreviousValue\n : operation.hasNextValue;\n const value =\n direction === \"undo\" ? operation.previousValue : operation.nextValue;\n\n if (!operation.path) {\n nextValue = shouldSet ? value : {};\n setUpdates.length = 0;\n unsetPaths.length = 0;\n continue;\n }\n\n if (shouldSet) {\n setUpdates.push([operation.path, value]);\n continue;\n }\n\n unsetPaths.push(operation.path);\n }\n\n if (setUpdates.length > 0) {\n nextValue = setDeepValues(nextValue, setUpdates);\n }\n\n if (unsetPaths.length > 0) {\n nextValue = unsetDeepValues(nextValue, unsetPaths);\n }\n\n return nextValue as T;\n}\n","import { deepClone } from \"../../../utils\";\nimport {\n applyHistoryPatch,\n createHistoryPatch,\n type BitHistoryPatch,\n} from \"../../engines/snapshot-diff-engine\";\n\nexport class BitHistoryManager<T extends object = Record<string, unknown>> {\n private baseSnapshot: T | null = null;\n private currentSnapshot: T | null = null;\n private patches: BitHistoryPatch<T>[] = [];\n private historyIndex = -1;\n private historySize = 0;\n\n constructor(\n private enableHistory: boolean,\n private maxHistory: number,\n ) {}\n\n saveSnapshot(values: T) {\n if (!this.enableHistory) return;\n\n if (!this.currentSnapshot || this.baseSnapshot === null) {\n this.reset(values);\n return;\n }\n\n const patch = createHistoryPatch(this.currentSnapshot, values);\n if (patch.operations.length === 0) {\n return;\n }\n\n if (this.historyIndex < this.historySize - 1) {\n this.patches.splice(this.historyIndex);\n this.historySize = this.historyIndex + 1;\n }\n\n this.patches.push(patch);\n this.currentSnapshot = values;\n this.historyIndex += 1;\n this.historySize = this.historyIndex + 1;\n\n while (this.historySize > this.getCapacity()) {\n this.compactOldestSnapshot();\n }\n }\n\n get canUndo(): boolean {\n return this.enableHistory ? this.historyIndex > 0 : false;\n }\n\n get canRedo(): boolean {\n return this.enableHistory\n ? this.historyIndex < this.historySize - 1\n : false;\n }\n\n undo(): T | null {\n if (!this.canUndo || !this.currentSnapshot) {\n return null;\n }\n\n const patch = this.patches[this.historyIndex - 1];\n const previousSnapshot = applyHistoryPatch(\n this.currentSnapshot,\n patch,\n \"undo\",\n );\n\n this.currentSnapshot = previousSnapshot;\n this.historyIndex -= 1;\n return previousSnapshot;\n }\n\n redo(): T | null {\n if (!this.canRedo || !this.currentSnapshot) {\n return null;\n }\n\n const patch = this.patches[this.historyIndex];\n const nextSnapshot = applyHistoryPatch(this.currentSnapshot, patch, \"redo\");\n\n this.currentSnapshot = nextSnapshot;\n this.historyIndex += 1;\n return nextSnapshot;\n }\n\n reset(initialValues: T) {\n if (!this.enableHistory) {\n this.baseSnapshot = null;\n this.currentSnapshot = null;\n this.patches = [];\n this.historyIndex = -1;\n this.historySize = 0;\n return;\n }\n\n this.baseSnapshot = deepClone(initialValues);\n this.currentSnapshot = this.baseSnapshot;\n this.patches = [];\n this.historyIndex = 0;\n this.historySize = 1;\n }\n\n getMetadata(): {\n enabled: boolean;\n canUndo: boolean;\n canRedo: boolean;\n historyIndex: number;\n historySize: number;\n } {\n return {\n enabled: this.enableHistory,\n canUndo: this.canUndo,\n canRedo: this.canRedo,\n historyIndex: this.historyIndex,\n historySize: this.historySize,\n };\n }\n\n private compactOldestSnapshot() {\n const oldestPatch = this.patches.shift();\n if (!oldestPatch || this.baseSnapshot === null) {\n return;\n }\n\n this.baseSnapshot = applyHistoryPatch(\n this.baseSnapshot,\n oldestPatch,\n \"redo\",\n );\n this.historySize = Math.max(1, this.historySize - 1);\n this.historyIndex = Math.max(0, this.historyIndex - 1);\n }\n\n private getCapacity() {\n return Math.max(1, this.maxHistory);\n }\n}\n","import type { BitErrors } from \"../store/contracts/types\";\n\n/**\n * Helper to safely clear an error from an errors object.\n * Returns a tuple of [newErrors, hasMutatedErrors] indicating if the error was cleared\n * and whether a clone was needed.\n */\nexport function clearErrorPath<T extends object>(\n errors: BitErrors<T>,\n path: string,\n alreadyMutated: boolean,\n): [BitErrors<T>, boolean] {\n const hasError = Object.prototype.hasOwnProperty.call(errors, path);\n\n if (!hasError) {\n return [errors, alreadyMutated];\n }\n\n let nextErrors = errors;\n let hasMutated = alreadyMutated;\n\n if (!hasMutated) {\n nextErrors = { ...errors };\n hasMutated = true;\n }\n\n delete nextErrors[path as keyof BitErrors<T>];\n\n return [nextErrors, hasMutated];\n}\n\n/**\n * Check if an error exists for a path.\n */\nexport function hasErrorPath<T extends object>(\n errors: BitErrors<T>,\n path: string,\n): boolean {\n return Object.prototype.hasOwnProperty.call(errors, path);\n}\n","export interface BitPipelineContext {\n halted?: boolean;\n}\n\nexport interface BitPipelineStep<TContext extends BitPipelineContext> {\n name: string;\n run: (context: TContext) => void | Promise<void>;\n}\n\nexport interface BitSyncPipelineStep<TContext extends BitPipelineContext> {\n name: string;\n run: (context: TContext) => void;\n}\n\nexport class BitPipelineRunner<TContext extends BitPipelineContext> {\n constructor(private readonly steps: BitPipelineStep<TContext>[]) {}\n\n async run(context: TContext): Promise<void> {\n for (const step of this.steps) {\n if (context.halted) {\n break;\n }\n\n await step.run(context);\n }\n }\n}\n\nexport class BitSyncPipelineRunner<TContext extends BitPipelineContext> {\n constructor(private readonly steps: BitSyncPipelineStep<TContext>[]) {}\n\n run(context: TContext): void {\n for (const step of this.steps) {\n if (context.halted) {\n break;\n }\n\n const result = step.run(context) as unknown;\n\n if (\n result !== null &&\n result !== undefined &&\n typeof (result as Promise<unknown>).then === \"function\"\n ) {\n throw new Error(\n `BitSyncPipelineRunner: step \"${step.name}\" returned a Promise. Use BitPipelineRunner for async steps.`,\n );\n }\n }\n }\n}\n","import { getDeepValue, setDeepValue } from \"../../../../utils\";\nimport { clearErrorPath } from \"../../../../utils/error-utils\";\nimport type {\n BitDependencyUpdateDiff,\n BitLifecycleFieldUpdatePort,\n} from \"../../../contracts/port-types\";\nimport type { BitErrors, BitFieldChangeMeta } from \"../../../contracts/types\";\nimport { patchStateOperation } from \"../../../engines/operation-engine\";\nimport {\n BitPipelineContext,\n BitSyncPipelineRunner,\n} from \"../../../shared/pipeline\";\n\ninterface FieldUpdatePipelineContext<\n T extends object,\n> extends BitPipelineContext {\n path: string;\n value: unknown;\n meta: BitFieldChangeMeta;\n previousValue: unknown;\n nextValues: T;\n nextErrors: BitErrors<T>;\n hasMutatedErrors: boolean;\n dependencyDiff: BitDependencyUpdateDiff;\n isDirty: boolean;\n}\n\nexport class BitFieldUpdateManager<T extends object> {\n private readonly fieldUpdatePipeline: BitSyncPipelineRunner<\n FieldUpdatePipelineContext<T>\n >;\n\n constructor(private readonly store: BitLifecycleFieldUpdatePort<T>) {\n this.fieldUpdatePipeline = new BitSyncPipelineRunner<\n FieldUpdatePipelineContext<T>\n >([\n {\n name: \"field:clear-current-error\",\n run: (ctx) => this.clearCurrentError(ctx),\n },\n {\n name: \"field:update-dependencies\",\n run: (ctx) => this.updateDependencies(ctx),\n },\n { name: \"field:update-dirty\", run: (ctx) => this.updateDirtyState(ctx) },\n { name: \"field:commit-state\", run: (ctx) => this.commitFieldState(ctx) },\n { name: \"field:emit-change\", run: (ctx) => this.emitFieldChange(ctx) },\n {\n name: \"field:trigger-validate\",\n run: (ctx) => this.triggerResolverValidation(ctx),\n },\n {\n name: \"field:trigger-async-validate\",\n run: (ctx) => this.triggerAsyncValidation(ctx),\n },\n ]);\n }\n\n updateField(\n path: string,\n value: unknown,\n meta: BitFieldChangeMeta = { origin: \"setField\" },\n ): void {\n const state = this.store.getState();\n const previousValue = getDeepValue(state.values, path);\n\n const context: FieldUpdatePipelineContext<T> = {\n path,\n value,\n meta,\n previousValue,\n nextValues: setDeepValue(state.values, path, value),\n nextErrors: state.errors,\n hasMutatedErrors: false,\n dependencyDiff: {\n affectedFields: [],\n visibilityChanged: [],\n requiredChanged: [],\n },\n isDirty: false,\n };\n\n this.fieldUpdatePipeline.run(context);\n }\n\n private clearCurrentError(ctx: FieldUpdatePipelineContext<T>) {\n [ctx.nextErrors, ctx.hasMutatedErrors] = clearErrorPath(\n ctx.nextErrors,\n ctx.path,\n ctx.hasMutatedErrors,\n );\n\n this.store.clearFieldValidation(ctx.path);\n }\n\n private updateDependencies(ctx: FieldUpdatePipelineContext<T>) {\n if (\n typeof this.store.hasDependentFields === \"function\" &&\n !this.store.hasDependentFields(ctx.path)\n ) {\n ctx.dependencyDiff.affectedFields.length = 0;\n ctx.dependencyDiff.visibilityChanged.length = 0;\n ctx.dependencyDiff.requiredChanged.length = 0;\n return;\n }\n\n ctx.dependencyDiff = this.store.updateDependencies(\n ctx.path,\n this.store.getState().values,\n ctx.nextValues,\n );\n\n const fieldsToReset = new Set([\n ...ctx.dependencyDiff.visibilityChanged,\n ...ctx.dependencyDiff.requiredChanged,\n ]);\n\n fieldsToReset.forEach((depPath) => {\n [ctx.nextErrors, ctx.hasMutatedErrors] = clearErrorPath(\n ctx.nextErrors,\n depPath,\n ctx.hasMutatedErrors,\n );\n this.store.clearFieldValidation(depPath);\n });\n }\n\n private updateDirtyState(ctx: FieldUpdatePipelineContext<T>) {\n ctx.isDirty = this.store.updateDirtyForPath(\n ctx.path,\n ctx.nextValues,\n this.store.getBaselineValues(),\n );\n }\n\n private commitFieldState(ctx: FieldUpdatePipelineContext<T>) {\n const changedPaths = Array.from(\n new Set([\n ctx.path,\n ...ctx.dependencyDiff.visibilityChanged,\n ...ctx.dependencyDiff.requiredChanged,\n ]),\n );\n\n this.store.dispatch(\n patchStateOperation(\n {\n values: ctx.nextValues,\n errors: ctx.nextErrors,\n isDirty: ctx.isDirty,\n },\n changedPaths,\n ),\n );\n }\n\n private emitFieldChange(ctx: FieldUpdatePipelineContext<T>) {\n this.store.emitFieldChange({\n path: ctx.path,\n previousValue: ctx.previousValue,\n nextValue: ctx.value,\n values: this.store.getState().values,\n state: this.store.getState(),\n meta: ctx.meta,\n });\n }\n\n private triggerResolverValidation(ctx: FieldUpdatePipelineContext<T>) {\n const validationTargets = Array.from(\n new Set([\n ctx.path,\n ...ctx.dependencyDiff.visibilityChanged,\n ...ctx.dependencyDiff.requiredChanged,\n ]),\n );\n\n if (\n this.store.config.resolver ||\n ctx.dependencyDiff.visibilityChanged.length > 0 ||\n ctx.dependencyDiff.requiredChanged.length > 0\n ) {\n this.store.triggerValidation(validationTargets);\n }\n }\n\n private triggerAsyncValidation(ctx: FieldUpdatePipelineContext<T>) {\n if (this.store.isFieldHidden(ctx.path)) {\n return;\n }\n\n const asyncValidateOn =\n typeof this.store.getFieldConfig === \"function\"\n ? this.store.getFieldConfig(ctx.path)?.validation?.asyncValidateOn\n : undefined;\n\n if (asyncValidateOn !== \"change\") {\n return;\n }\n\n this.store.handleFieldAsyncValidation(ctx.path, ctx.value);\n }\n}\n","import {\n BitLifecyclePhase,\n type BitLifecyclePhaseContext,\n type BitLifecyclePhaseExecutor,\n} from \"./lifecycle-phases\";\n\nexport class BitLifecycleOrchestrator<\n TContext extends BitLifecyclePhaseContext,\n> {\n private readonly executors = new Map<\n TContext[\"kind\"],\n BitLifecyclePhaseExecutor<TContext>[]\n >();\n\n register(\n kind: TContext[\"kind\"],\n executor: BitLifecyclePhaseExecutor<TContext>,\n ) {\n const current = this.executors.get(kind) ?? [];\n current.push(executor);\n this.executors.set(kind, current);\n }\n\n async execute(context: TContext): Promise<void> {\n const ordered = this.getOrderedExecutors(context.kind);\n\n for (const executor of ordered) {\n await executor.execute(context);\n }\n }\n\n executeSync(context: TContext): void {\n const ordered = this.getOrderedExecutors(context.kind);\n\n for (const executor of ordered) {\n const result = executor.execute(context);\n if (result && typeof (result as Promise<unknown>).then === \"function\") {\n throw new Error(\n `BitLifecycleOrchestrator: executor async em modo sync para kind \"${context.kind}\".`,\n );\n }\n }\n }\n\n private getOrderedExecutors(kind: TContext[\"kind\"]) {\n const executors = this.executors.get(kind) ?? [];\n return [...executors].sort((left, right) => left.phase - right.phase);\n }\n}\n\nexport { BitLifecyclePhase };\n","import {\n deepClone,\n extractServerErrors,\n isValidationErrorShape,\n setDeepValues,\n} from \"../../../../utils\";\nimport type { BitLifecycleSubmitPort } from \"../../../contracts/port-types\";\nimport type { BitSubmitResult } from \"../../../contracts/types\";\nimport { patchStateOperation } from \"../../../engines/operation-engine\";\nimport {\n BitPipelineContext,\n BitPipelineRunner,\n} from \"../../../shared/pipeline\";\nimport { applyTransformDerivations } from \"../../../shared/value-derivation-pipeline\";\n\ninterface SubmitPipelineContext<T extends object> extends BitPipelineContext {\n onSuccess: (\n values: T,\n dirtyValues?: Partial<T>,\n ) => unknown | Promise<unknown>;\n isValid: boolean;\n valuesToSubmit: T;\n dirtyValues: Partial<T>;\n error?: unknown;\n invalid?: boolean;\n}\n\nexport class BitSubmitLifecycleManager<T extends object> {\n private readonly submitPipeline: BitPipelineRunner<SubmitPipelineContext<T>>;\n\n constructor(private readonly store: BitLifecycleSubmitPort<T>) {\n this.submitPipeline = new BitPipelineRunner<SubmitPipelineContext<T>>([\n { name: \"submit:start\", run: async (ctx) => this.startSubmit(ctx) },\n {\n name: \"submit:invalid\",\n run: async (ctx) => this.handleInvalidSubmit(ctx),\n },\n { name: \"submit:prepare\", run: (ctx) => this.prepareSubmitValues(ctx) },\n {\n name: \"submit:before-hooks\",\n run: async (ctx) => this.runBeforeSubmitHooks(ctx),\n },\n {\n name: \"submit:user-handler\",\n run: async (ctx) => this.runSubmitHandler(ctx),\n },\n {\n name: \"submit:after-hooks\",\n run: async (ctx) => this.runAfterSubmitHooks(ctx),\n },\n ]);\n }\n\n async submit(\n onSuccess: (\n values: T,\n dirtyValues?: Partial<T>,\n ) => unknown | Promise<unknown>,\n ): Promise<BitSubmitResult> {\n const currentState = this.store.getState();\n\n if (currentState.isSubmitting) {\n return { status: \"blocked\", reason: \"isSubmitting\" };\n }\n\n if (this.store.hasValidationsInProgress()) {\n return { status: \"blocked\", reason: \"validating\" };\n }\n\n this.store.cancelAllValidations();\n\n const context: SubmitPipelineContext<T> = {\n onSuccess,\n isValid: false,\n valuesToSubmit: deepClone(this.store.getState().values),\n dirtyValues: {},\n };\n\n try {\n await this.submitPipeline.run(context);\n\n if (context.invalid) {\n return { status: \"invalid\" };\n }\n\n return { status: \"submitted\" };\n } catch (error) {\n context.error = error;\n\n await this.store.emitOperationalError({\n source: \"submit\",\n error,\n });\n\n await this.store.emitAfterSubmit({\n values: context.valuesToSubmit,\n dirtyValues: context.dirtyValues,\n state: this.store.getState(),\n success: false,\n error,\n });\n\n this.store.config.onUnhandledError(error, \"submit\");\n\n return { status: \"failed\", error };\n } finally {\n this.store.dispatch(patchStateOperation({ isSubmitting: false }));\n }\n }\n\n private async startSubmit(ctx: SubmitPipelineContext<T>) {\n this.store.dispatch(patchStateOperation({ isSubmitting: true }));\n ctx.isValid = await this.store.validateNow();\n }\n\n private async handleInvalidSubmit(ctx: SubmitPipelineContext<T>) {\n if (ctx.isValid) return;\n\n const currentErrors = this.store.getState().errors;\n const newTouched = { ...this.store.getState().touched };\n\n Object.keys(currentErrors).forEach((path) => {\n newTouched[path as keyof typeof newTouched] = true;\n });\n\n this.store.batchStateUpdates(() => {\n this.store.dispatch(patchStateOperation({ touched: newTouched }));\n });\n\n ctx.dirtyValues = this.store.buildDirtyValues(this.store.getState().values);\n ctx.invalid = true;\n\n await this.store.emitAfterSubmit({\n values: this.store.getState().values,\n dirtyValues: ctx.dirtyValues,\n state: this.store.getState(),\n success: false,\n invalid: true,\n });\n\n ctx.halted = true;\n }\n\n private prepareSubmitValues(ctx: SubmitPipelineContext<T>) {\n const updates: Array<[string, unknown]> = [];\n const hiddenFields = this.store.getHiddenFields();\n\n hiddenFields.forEach((hiddenPath) => {\n updates.push([hiddenPath, undefined]);\n });\n\n if (updates.length > 0) {\n ctx.valuesToSubmit = setDeepValues(ctx.valuesToSubmit, updates);\n }\n\n ctx.valuesToSubmit = applyTransformDerivations({\n values: ctx.valuesToSubmit,\n sourceValues: ctx.valuesToSubmit,\n transformEntries: this.store\n .getTransformEntries()\n .filter(([path]) => !hiddenFields.has(path)),\n onError: (error) => {\n throw error;\n },\n });\n\n ctx.dirtyValues = this.store.buildDirtyValues(ctx.valuesToSubmit);\n }\n\n private async runBeforeSubmitHooks(ctx: SubmitPipelineContext<T>) {\n // Hooks recebem um snapshot de submissão imutável por contrato.\n // Mudanças no estado global durante o hook não alteram valuesToSubmit.\n await this.store.emitBeforeSubmit({\n values: ctx.valuesToSubmit,\n dirtyValues: ctx.dirtyValues,\n state: this.store.getState(),\n });\n }\n\n private async runSubmitHandler(ctx: SubmitPipelineContext<T>) {\n try {\n await ctx.onSuccess(ctx.valuesToSubmit, ctx.dirtyValues);\n } catch (error) {\n if (isValidationErrorShape(error)) {\n this.store.setServerErrors(extractServerErrors(error));\n\n await this.store.emitAfterSubmit({\n values: ctx.valuesToSubmit,\n dirtyValues: ctx.dirtyValues,\n state: this.store.getState(),\n success: false,\n invalid: true,\n });\n\n ctx.invalid = true;\n ctx.halted = true;\n return;\n }\n\n throw error;\n }\n }\n\n private async runAfterSubmitHooks(ctx: SubmitPipelineContext<T>) {\n await this.store.emitAfterSubmit({\n values: ctx.valuesToSubmit,\n dirtyValues: ctx.dirtyValues,\n state: this.store.getState(),\n success: true,\n });\n }\n}\n","import { deepClone, setDeepValues } from \"../../../../utils\";\nimport type { BitLifecycleValuesPort } from \"../../../contracts/port-types\";\nimport type { DeepPartial } from \"../../../contracts/types\";\nimport { patchStateOperation } from \"../../../engines/operation-engine\";\n\nexport class BitValuesLifecycleManager<T extends object> {\n constructor(private readonly store: BitLifecycleValuesPort<T>) {}\n\n private collectChangedUpdates(\n values: DeepPartial<T>,\n prefix = \"\",\n updates: Array<readonly [string, unknown]> = [],\n activeBranch: WeakSet<object> = new WeakSet(),\n ): Array<readonly [string, unknown]> {\n if (values && typeof values === \"object\") {\n if (activeBranch.has(values as object)) {\n return updates;\n }\n\n activeBranch.add(values as object);\n }\n\n try {\n Object.entries(values as Record<string, unknown>).forEach(\n ([key, value]) => {\n const nextPath = prefix ? `${prefix}.${key}` : key;\n\n if (\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value as Record<string, unknown>).length > 0\n ) {\n if (activeBranch.has(value as object)) {\n return;\n }\n\n this.collectChangedUpdates(\n value as DeepPartial<T>,\n nextPath,\n updates,\n activeBranch,\n );\n return;\n }\n\n updates.push([nextPath, value]);\n },\n );\n } finally {\n if (values && typeof values === \"object\") {\n activeBranch.delete(values as object);\n }\n }\n\n return updates;\n }\n\n setValues(\n newValues: T | DeepPartial<T>,\n options?: { partial?: boolean; rebase?: boolean },\n ) {\n if (options?.rebase) {\n this.rebaseValues(newValues as T);\n return;\n }\n\n if (options?.partial) {\n this.hydrateValues(newValues as DeepPartial<T>);\n return;\n }\n\n this.replaceValuesInternal(newValues as T, \"replaceValues\");\n }\n\n hydrateValues(values: DeepPartial<T>) {\n const changedUpdates = this.collectChangedUpdates(values);\n const changedPaths = changedUpdates.map(([path]) => path);\n const mergedValues =\n changedUpdates.length > 0\n ? setDeepValues(this.store.getState().values, changedUpdates)\n : this.store.getState().values;\n\n this.replaceValuesInternal(\n mergedValues,\n \"hydrate\",\n changedPaths.length > 0 ? changedPaths : [\"*\"],\n );\n }\n\n rebaseValues(newValues: T) {\n const previousValues = this.store.getState().values;\n const clonedValues = deepClone(newValues);\n\n // Use the clone for the baseline, not the original reference.\n // If the caller mutates `newValues` after calling rebaseValues(), the\n // baseline would be silently corrupted and isDirty comparisons would yield\n // wrong results. The deep clone ensures the baseline is immutable from\n // the outside world's perspective.\n this.store.setBaselineValues(clonedValues);\n\n this.store.cancelAllValidations();\n this.store.evaluateAllDependencies(clonedValues);\n\n this.store.clearDirtyState();\n\n this.store.dispatch(\n patchStateOperation(\n {\n values: clonedValues,\n errors: {},\n touched: {},\n isValidating: {},\n isValid: false,\n isDirty: false,\n },\n [\"*\"],\n ),\n );\n\n this.store.resetHistory(clonedValues);\n void this.store.validateNow().catch((error) => {\n this.store.config?.onUnhandledError(error, \"rebaseValues\");\n });\n\n this.store.emitFieldChange({\n path: \"*\",\n previousValue: previousValues,\n nextValue: clonedValues,\n values: this.store.getState().values,\n state: this.store.getState(),\n meta: { origin: \"rebase\" },\n });\n }\n\n applyHistoryState(snapshot: T) {\n this.store.cancelAllValidations();\n\n const isDirty = this.store.rebuildDirtyState(\n snapshot,\n this.store.getBaselineValues(),\n );\n\n this.store.dispatch(\n patchStateOperation(\n {\n values: snapshot,\n errors: {},\n isValid: false,\n isDirty,\n },\n [\"*\"],\n ),\n );\n void this.store.validateNow().catch((error) => {\n this.store.config?.onUnhandledError(error, \"applyHistoryState\");\n });\n }\n\n reset() {\n this.store.cancelAllValidations();\n\n const initialCloned = deepClone(this.store.getBaselineValues());\n\n this.store.evaluateAllDependencies(initialCloned);\n\n this.store.clearDirtyState();\n\n this.store.dispatch(\n patchStateOperation(\n {\n values: initialCloned,\n errors: {},\n touched: {},\n isValidating: {},\n isValid: false,\n isDirty: false,\n },\n [\"*\"],\n ),\n );\n\n this.store.resetHistory(initialCloned);\n }\n\n private replaceValuesInternal(\n newValues: T,\n origin: \"replaceValues\" | \"hydrate\" = \"replaceValues\",\n changedPaths: string[] = [\"*\"],\n ) {\n const previousValues = this.store.getState().values;\n const clonedValues = deepClone(newValues);\n\n this.store.cancelAllValidations();\n this.store.evaluateAllDependencies(clonedValues);\n\n const isDirty = this.store.rebuildDirtyState(\n clonedValues,\n this.store.getBaselineValues(),\n );\n\n this.store.dispatch(\n patchStateOperation(\n {\n values: clonedValues,\n errors: {},\n isValidating: {},\n isValid: false,\n isDirty,\n },\n changedPaths,\n ),\n );\n\n this.store.internalSaveSnapshot();\n void this.store.validateNow().catch((error) => {\n this.store.config?.onUnhandledError(error, \"replaceValuesInternal\");\n });\n\n this.store.emitFieldChange({\n path: \"*\",\n previousValue: previousValues,\n nextValue: clonedValues,\n values: this.store.getState().values,\n state: this.store.getState(),\n meta: { origin },\n });\n }\n}\n","import type { BitLifecyclePorts } from \"../../contracts/port-types\";\nimport type { BitSubmitResult } from \"../../contracts/types\";\nimport { BitFieldChangeMeta, DeepPartial } from \"../../contracts/types\";\nimport { BitFieldUpdateManager } from \"./lifecycle/field-update-manager\";\nimport {\n BitLifecycleOrchestrator,\n BitLifecyclePhase,\n} from \"./lifecycle/lifecycle-orchestrator\";\nimport { BitSubmitLifecycleManager } from \"./lifecycle/submit-lifecycle-manager\";\nimport { BitValuesLifecycleManager } from \"./lifecycle/values-lifecycle-manager\";\n\ninterface BitLifecycleManagerContext<T extends object> {\n kind:\n | \"updateField\"\n | \"setValues\"\n | \"hydrateValues\"\n | \"rebaseValues\"\n | \"applyHistoryState\"\n | \"submit\"\n | \"reset\";\n path?: string;\n value?: unknown;\n meta?: BitFieldChangeMeta;\n newValues?: T | DeepPartial<T>;\n options?: { partial?: boolean; rebase?: boolean };\n snapshot?: T;\n onSuccess?: (\n values: T,\n dirtyValues?: Partial<T>,\n ) => unknown | Promise<unknown>;\n submitResult?: BitSubmitResult;\n}\n\nexport class BitLifecycleManager<T extends object> {\n private readonly fieldUpdate: BitFieldUpdateManager<T>;\n private readonly values: BitValuesLifecycleManager<T>;\n private readonly submitFlow: BitSubmitLifecycleManager<T>;\n private readonly orchestrator = new BitLifecycleOrchestrator<\n BitLifecycleManagerContext<T>\n >();\n\n constructor(private readonly ports: BitLifecyclePorts<T>) {\n this.fieldUpdate = new BitFieldUpdateManager<T>(ports.fieldUpdate);\n this.values = new BitValuesLifecycleManager<T>(ports.values);\n this.submitFlow = new BitSubmitLifecycleManager<T>(ports.submit);\n\n this.orchestrator.register(\"updateField\", {\n phase: BitLifecyclePhase.UPDATE_FIELD,\n execute: (ctx) =>\n this.fieldUpdate.updateField(\n ctx.path!,\n ctx.value,\n ctx.meta ?? { origin: \"setField\" },\n ),\n });\n\n this.orchestrator.register(\"setValues\", {\n phase: BitLifecyclePhase.UPDATE_VALUES,\n execute: (ctx) => this.values.setValues(ctx.newValues!, ctx.options),\n });\n\n this.orchestrator.register(\"hydrateValues\", {\n phase: BitLifecyclePhase.UPDATE_VALUES,\n execute: (ctx) =>\n this.values.hydrateValues(ctx.newValues as DeepPartial<T>),\n });\n\n this.orchestrator.register(\"rebaseValues\", {\n phase: BitLifecyclePhase.UPDATE_VALUES,\n execute: (ctx) => this.values.rebaseValues(ctx.newValues as T),\n });\n\n this.orchestrator.register(\"applyHistoryState\", {\n phase: BitLifecyclePhase.UPDATE_VALUES,\n execute: (ctx) => this.values.applyHistoryState(ctx.snapshot as T),\n });\n\n this.orchestrator.register(\"submit\", {\n phase: BitLifecyclePhase.SUBMIT,\n execute: async (ctx) => {\n ctx.submitResult = await this.submitFlow.submit(ctx.onSuccess!);\n },\n });\n\n this.orchestrator.register(\"reset\", {\n phase: BitLifecyclePhase.RESET,\n execute: () => this.values.reset(),\n });\n }\n\n updateField(\n path: string,\n value: unknown,\n meta: BitFieldChangeMeta = { origin: \"setField\" },\n ) {\n this.orchestrator.executeSync({\n kind: \"updateField\",\n path,\n value,\n meta,\n });\n }\n\n setValues(\n newValues: T | DeepPartial<T>,\n options?: { partial?: boolean; rebase?: boolean },\n ) {\n this.orchestrator.executeSync({\n kind: \"setValues\",\n newValues,\n options,\n });\n }\n\n hydrateValues(values: DeepPartial<T>) {\n this.orchestrator.executeSync({\n kind: \"hydrateValues\",\n newValues: values,\n });\n }\n\n rebaseValues(newValues: T) {\n this.orchestrator.executeSync({\n kind: \"rebaseValues\",\n newValues,\n });\n }\n\n applyHistoryState(snapshot: T) {\n this.orchestrator.executeSync({\n kind: \"applyHistoryState\",\n snapshot,\n });\n }\n\n async submit(\n onSuccess: (\n values: T,\n dirtyValues?: Partial<T>,\n ) => unknown | Promise<unknown>,\n ): Promise<BitSubmitResult> {\n const context: BitLifecycleManagerContext<T> = {\n kind: \"submit\",\n onSuccess,\n };\n\n await this.orchestrator.execute(context);\n return context.submitResult as BitSubmitResult;\n }\n\n reset() {\n this.orchestrator.executeSync({\n kind: \"reset\",\n });\n }\n}\n","import { BitErrors, BitState } from \"../../contracts/types\";\n\n/**\n * BitScopeManager\n *\n * Manages multi-scope forms and scope-based validation.\n * Scopes are groups of fields that can be validated and tracked independently,\n * useful for wizard-style forms or multi-section forms.\n */\nexport class BitScopeManager<T extends object = Record<string, unknown>> {\n constructor(\n private getState: () => BitState<T>,\n private getInitialValues: () => T,\n private getScopeFields: (scopeName: string) => string[],\n private isPathDirty: (path: string) => boolean,\n ) {}\n\n /**\n * Get validation status of a scope.\n * Returns whether the scope has errors, is dirty, and the error details.\n */\n getScopeStatus(scopeName: string) {\n const fields = this.getScopeFields(scopeName);\n const state = this.getState();\n\n const hasErrors = fields.some(\n (f) => !!state.errors[f as keyof BitErrors<T>],\n );\n\n const isDirty = fields.some((f) => this.isPathDirty(f));\n\n const errors = this.getScopeErrors(scopeName);\n\n return { hasErrors, isDirty, errors };\n }\n\n /**\n * Get all errors for fields in a specific scope.\n */\n getScopeErrors(scopeName: string): Record<string, string> {\n const fields = this.getScopeFields(scopeName);\n const state = this.getState();\n const result: Record<string, string> = {};\n\n for (const field of fields) {\n const error = state.errors[field as keyof BitErrors<T>];\n if (error) {\n result[field] = error;\n }\n }\n\n return result;\n }\n}\n","import { getDeepValue, valueEqual } from \"../../../../utils\";\nimport type { BitFieldDefinition } from \"../../../contracts/types\";\nimport { isPathWithinPrefix } from \"../../../shared/path-prefix\";\n\nexport type BitAsyncValidateFn<T extends object> = NonNullable<\n NonNullable<BitFieldDefinition<T>[\"validation\"]>[\"asyncValidate\"]\n>;\n\ninterface PendingAsyncValidationJob<T extends object> {\n value: unknown;\n dueAt: number;\n validate: BitAsyncValidateFn<T>;\n controller: AbortController;\n timeoutMs?: number;\n}\n\nconst BIT_ASYNC_VALIDATION_TIMEOUT = Symbol(\"bit.async.validation.timeout\");\n\nexport interface BitAsyncValidationSchedulerPort<T extends object> {\n schedule(fn: () => void, delayMs: number): () => void;\n getValues(): T;\n setFieldValidating(path: string, isValidating: boolean): void;\n setAsyncError(path: string, message: string): void;\n clearAsyncError(path: string): void;\n onValidationPassed(path: string): Promise<void>;\n onError(error: unknown): void;\n}\n\nexport class BitAsyncValidationScheduler<T extends object> {\n private _cancellingAll = false;\n private cancelSchedulerTimeout?: () => void;\n private readonly abortControllers = new Map<string, AbortController>();\n private readonly pendingJobs = new Map<\n string,\n PendingAsyncValidationJob<T>\n >();\n\n constructor(private readonly port: BitAsyncValidationSchedulerPort<T>) {}\n\n handle(\n path: string,\n value: unknown,\n validate: BitAsyncValidateFn<T> | undefined,\n delay: number,\n timeoutMs?: number,\n ): void {\n if (!validate) {\n this.cancel(path);\n this.port.setFieldValidating(path, false);\n return;\n }\n\n this.cancel(path);\n this.port.clearAsyncError(path);\n this.port.setFieldValidating(path, true);\n\n const controller = new AbortController();\n this.abortControllers.set(path, controller);\n this.pendingJobs.set(path, {\n value,\n dueAt: Date.now() + delay,\n validate,\n controller,\n timeoutMs,\n });\n this.schedulePendingJobs();\n }\n\n cancel(path: string): void {\n this.cancelInternal(path, true);\n }\n\n private cancelInternal(path: string, shouldReschedule: boolean): void {\n if (this.pendingJobs.has(path)) {\n this.pendingJobs.delete(path);\n if (shouldReschedule) {\n this.schedulePendingJobs();\n }\n }\n\n const controller = this.abortControllers.get(path);\n if (controller) {\n controller.abort();\n this.abortControllers.delete(path);\n }\n }\n\n cleanupPrefix(prefix: string): void {\n let hasPendingChange = false;\n\n const paths = new Set<string>([\n ...this.pendingJobs.keys(),\n ...this.abortControllers.keys(),\n ]);\n\n for (const path of paths) {\n if (isPathWithinPrefix(path, prefix)) {\n this.cancelInternal(path, false);\n hasPendingChange = true;\n this.port.clearAsyncError(path);\n this.port.setFieldValidating(path, false);\n }\n }\n\n if (hasPendingChange) {\n this.schedulePendingJobs();\n }\n }\n\n remapPaths(remapPath: (path: string) => string | null): void {\n let hasPendingChange = false;\n\n const nextPendingJobs = new Map<string, PendingAsyncValidationJob<T>>();\n\n for (const [path, job] of this.pendingJobs.entries()) {\n const nextPath = remapPath(path);\n\n if (!nextPath) {\n job.controller.abort();\n hasPendingChange = true;\n continue;\n }\n\n if (nextPath !== path) {\n hasPendingChange = true;\n }\n\n nextPendingJobs.set(nextPath, job);\n }\n\n const nextAbortControllers = new Map<string, AbortController>();\n\n for (const [path, controller] of this.abortControllers.entries()) {\n const nextPath = remapPath(path);\n\n if (!nextPath) {\n controller.abort();\n continue;\n }\n\n nextAbortControllers.set(nextPath, controller);\n }\n\n this.pendingJobs.clear();\n nextPendingJobs.forEach((job, path) => {\n this.pendingJobs.set(path, job);\n });\n\n this.abortControllers.clear();\n nextAbortControllers.forEach((controller, path) => {\n this.abortControllers.set(path, controller);\n });\n\n if (hasPendingChange) {\n this.schedulePendingJobs();\n }\n }\n\n cancelAll(): void {\n this._cancellingAll = true;\n try {\n if (this.cancelSchedulerTimeout) {\n try {\n this.cancelSchedulerTimeout();\n } catch {\n // Ignore: may fail if cancellation already happened\n } finally {\n this.cancelSchedulerTimeout = undefined;\n }\n }\n\n this.abortControllers.forEach((controller, path) => {\n try {\n controller.abort();\n } catch {\n // Already aborted or invalid\n }\n // Always reset isValidating synchronously so the UI spinner never stays\n // stuck. The runJob finally block is guarded by _cancellingAll so it\n // will not race against this reset.\n this.port.setFieldValidating(path, false);\n });\n\n this.pendingJobs.forEach((_job, path) => {\n // Jobs in the pending queue also had setFieldValidating(true) called in\n // handle(). Clear them so they do not leak on bulk teardown.\n this.port.setFieldValidating(path, false);\n });\n\n this.pendingJobs.clear();\n this.abortControllers.clear();\n } finally {\n this._cancellingAll = false;\n }\n }\n\n private schedulePendingJobs(): void {\n if (this.cancelSchedulerTimeout) {\n this.cancelSchedulerTimeout();\n this.cancelSchedulerTimeout = undefined;\n }\n\n let nextDueAt = Number.POSITIVE_INFINITY;\n\n for (const job of this.pendingJobs.values()) {\n if (job.dueAt < nextDueAt) {\n nextDueAt = job.dueAt;\n }\n }\n\n if (!Number.isFinite(nextDueAt)) {\n return;\n }\n\n this.cancelSchedulerTimeout = this.port.schedule(\n () => {\n this.cancelSchedulerTimeout = undefined;\n void this.flushPendingJobs().catch((error) => {\n this.port.onError(error);\n });\n },\n Math.max(0, nextDueAt - Date.now()),\n );\n }\n\n private async flushPendingJobs(): Promise<void> {\n this.cancelSchedulerTimeout = undefined;\n\n const now = Date.now();\n const dueJobs: Array<[string, PendingAsyncValidationJob<T>]> = [];\n\n for (const [path, job] of this.pendingJobs.entries()) {\n if (job.dueAt <= now) {\n dueJobs.push([path, job]);\n }\n }\n\n if (dueJobs.length === 0) {\n this.schedulePendingJobs();\n return;\n }\n\n dueJobs.forEach(([path]) => {\n this.pendingJobs.delete(path);\n });\n\n const results = await Promise.allSettled(\n dueJobs.map(([path, job]) => this.runJob(path, job)),\n );\n\n for (const result of results) {\n if (result.status === \"rejected\") {\n this.port.onError(result.reason);\n }\n }\n\n this.schedulePendingJobs();\n }\n\n private async runJob(\n path: string,\n job: PendingAsyncValidationJob<T>,\n ): Promise<void> {\n if (job.controller.signal.aborted) {\n return;\n }\n\n try {\n let validationPromise: Promise<\n string | null | undefined | typeof BIT_ASYNC_VALIDATION_TIMEOUT\n > = job.validate(job.value, this.port.getValues());\n\n if (typeof job.timeoutMs === \"number\" && job.timeoutMs > 0) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n validationPromise = Promise.race([\n validationPromise,\n new Promise<typeof BIT_ASYNC_VALIDATION_TIMEOUT>((resolve) => {\n timeoutId = setTimeout(\n () => resolve(BIT_ASYNC_VALIDATION_TIMEOUT),\n job.timeoutMs,\n );\n }),\n ]).finally(() => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n });\n }\n\n const errorMessage = await validationPromise;\n\n if (job.controller.signal.aborted) {\n return;\n }\n\n const currentValue = getDeepValue(this.port.getValues(), path);\n if (!valueEqual(currentValue, job.value)) {\n return;\n }\n\n if (errorMessage === BIT_ASYNC_VALIDATION_TIMEOUT) {\n // Timeout is inconclusive: do not clear/set error and do not report validation success.\n return;\n }\n\n if (errorMessage !== null && errorMessage !== undefined) {\n this.port.setAsyncError(path, errorMessage);\n } else {\n this.port.clearAsyncError(path);\n await this.port.onValidationPassed(path);\n }\n } finally {\n const currentPath = this.findControllerPath(job.controller) ?? path;\n\n // Always clear the validating flag unless cancelAll() is orchestrating\n // a bulk teardown. The !aborted guard was removed intentionally: if\n // asyncValidate throws after being aborted (an uncommon but valid path),\n // the aborted signal would skip this cleanup and leave isValidating=true\n // permanently, blocking submission indefinitely.\n if (!this._cancellingAll) {\n this.port.setFieldValidating(currentPath, false);\n }\n\n if (this.abortControllers.get(currentPath) === job.controller) {\n this.abortControllers.delete(currentPath);\n }\n }\n }\n\n private findControllerPath(controller: AbortController): string | undefined {\n for (const [path, storedController] of this.abortControllers.entries()) {\n if (storedController === controller) {\n return path;\n }\n }\n\n return undefined;\n }\n}\n","export function hasAnyError(errors: Record<string, unknown>): boolean {\n for (const path of Object.keys(errors)) {\n if (errors[path] !== undefined) return true;\n }\n\n return false;\n}\n","import { getDeepValue, valueEqual } from \"../../../../utils\";\nimport type { BitValidationPipelinePort } from \"../../../contracts/port-types\";\nimport type { BitErrors } from \"../../../contracts/types\";\nimport { validationCommitOperation } from \"../../../engines/operation-engine\";\nimport { hasAnyError } from \"../../../shared/error-map\";\n\nexport async function commitSynchronousScopeValidation<T extends object>(args: {\n scopeFields: string[];\n store: BitValidationPipelinePort<T>;\n asyncErrors: Map<string, string>;\n}) {\n const { scopeFields, store, asyncErrors } = args;\n const initialState = store.getState();\n const initialHiddenFields = new Set(store.getHiddenFields());\n const resolverErrors = store.config.resolver\n ? await store.config.resolver(initialState.values, {\n scopeFields,\n })\n : {};\n\n // Capture current state AFTER async operations to avoid stale state\n const currentState = store.getState();\n\n // Guard: if any of the scope fields' values changed, abort to prevent overwriting newer validation.\n // Uses getDeepValue so that nested paths (e.g. \"address.street\", \"items.0.name\") are correctly\n // compared — direct bracket access (`values[field]`) always returns undefined for dot-separated\n // paths, making the guard a no-op and allowing stale errors to overwrite current ones.\n const valuesStale = scopeFields.some(\n (field) =>\n !valueEqual(\n getDeepValue(initialState.values, field),\n getDeepValue(currentState.values, field),\n ),\n );\n const currentHiddenFields = store.getHiddenFields();\n const visibilityStale = scopeFields.some(\n (field) =>\n initialHiddenFields.has(field) !== currentHiddenFields.has(field),\n );\n\n if (valuesStale || visibilityStale) {\n // A scoped field value changed during resolver execution; newer validations may be in flight\n // Skip this commit to avoid race condition\n return;\n }\n\n const dynamicRequiredErrors = store.getRequiredErrors(currentState.values);\n const allErrors = { ...resolverErrors, ...dynamicRequiredErrors };\n\n currentHiddenFields.forEach((hiddenPath) => {\n delete allErrors[hiddenPath];\n // NOTE: Do NOT delete from asyncErrors here — same contract as validation-pipeline-stages.\n // The shared asyncErrors Map must not lose entries for temporarily hidden paths.\n });\n\n const scopedErrors = { ...currentState.errors } as BitErrors<T>;\n\n scopeFields.forEach((field) => {\n if (allErrors[field]) {\n scopedErrors[field as keyof BitErrors<T>] = allErrors[field];\n } else if (asyncErrors.has(field)) {\n scopedErrors[field as keyof BitErrors<T>] = asyncErrors.get(field)!;\n } else {\n delete scopedErrors[field as keyof BitErrors<T>];\n }\n });\n\n store.dispatch(\n validationCommitOperation(\n scopedErrors,\n !hasAnyError(scopedErrors) &&\n !hasAnyError(currentState.errors as Record<string, unknown>),\n ),\n );\n}\n","import { isPathWithinPrefix } from \"../../../shared/path-prefix\";\n\nexport class BitValidationCoordinator {\n private currentValidationId = 0;\n private readonly immediateAbortControllers = new Map<\n string,\n AbortController\n >();\n\n beginValidation(): number {\n this.currentValidationId += 1;\n return this.currentValidationId;\n }\n\n getCurrentValidationId(): number {\n return this.currentValidationId;\n }\n\n isValidationCurrent(validationId: number): boolean {\n return validationId === this.currentValidationId;\n }\n\n setImmediateController(path: string, controller: AbortController): void {\n this.immediateAbortControllers.set(path, controller);\n }\n\n clearImmediateController(path: string, controller: AbortController): boolean {\n if (this.immediateAbortControllers.get(path) === controller) {\n this.immediateAbortControllers.delete(path);\n return true;\n }\n\n return false;\n }\n\n cancelImmediate(path: string): void {\n const controller = this.immediateAbortControllers.get(path);\n if (!controller) {\n return;\n }\n\n controller.abort();\n this.immediateAbortControllers.delete(path);\n }\n\n cancelImmediatePrefix(\n prefix: string,\n onPathCancelled: (path: string) => void,\n ) {\n for (const path of this.immediateAbortControllers.keys()) {\n if (!isPathWithinPrefix(path, prefix)) {\n continue;\n }\n\n this.cancelImmediate(path);\n onPathCancelled(path);\n }\n }\n\n remapImmediateControllers(remapPath: (path: string) => string | null): void {\n const nextControllers = new Map<string, AbortController>();\n\n for (const [path, controller] of this.immediateAbortControllers.entries()) {\n const nextPath = remapPath(path);\n\n if (!nextPath) {\n controller.abort();\n continue;\n }\n\n nextControllers.set(nextPath, controller);\n }\n\n this.immediateAbortControllers.clear();\n nextControllers.forEach((controller, path) => {\n this.immediateAbortControllers.set(path, controller);\n });\n }\n\n cancelAllImmediate(): void {\n this.immediateAbortControllers.forEach((controller) => {\n controller.abort();\n });\n this.immediateAbortControllers.clear();\n }\n}\n","import type { BitValidationTriggerOptions } from \"../../../contracts/port-types\";\nimport type { BitValidationOptions } from \"../../../contracts/public/meta-types\";\n\nexport interface BitValidationDebouncerPort {\n schedule(fn: () => void, delayMs: number): () => void;\n validate(options?: BitValidationOptions): Promise<boolean>;\n readonly validationDelay: number;\n}\n\n/**\n * Responsável exclusivamente pelo debounce do trigger de validação.\n * Acumula campos pendentes dentro da janela de debounce, evitando\n * descartar paths de chamadas anteriores dentro do mesmo intervalo.\n */\nexport class BitValidationDebouncer {\n private cancelTimeout?: () => void;\n private pendingScopeFields: Set<string> | null = null;\n private isGlobalPending = false;\n\n constructor(private readonly port: BitValidationDebouncerPort) {}\n\n trigger(scopeFields?: string[], options?: BitValidationTriggerOptions): void {\n if (this.cancelTimeout) {\n this.cancelTimeout();\n this.cancelTimeout = undefined;\n }\n\n const configuredDelay = this.port.validationDelay ?? 300;\n const delay = options?.forceDebounce\n ? Math.max(1, configuredDelay)\n : configuredDelay;\n\n if (delay > 0) {\n // Se for global ou não tivermos paths, resetamos para global (null)\n if (!scopeFields || scopeFields.length === 0) {\n this.pendingScopeFields = null;\n this.isGlobalPending = true;\n } else if (!this.isGlobalPending) {\n // Apenas acumula paths se não houver uma validação global pendente\n if (!this.pendingScopeFields) {\n this.pendingScopeFields = new Set(scopeFields);\n } else {\n for (const f of scopeFields) this.pendingScopeFields.add(f);\n }\n }\n\n this.cancelTimeout = this.port.schedule(() => {\n // Lê pendingScopeFields aqui — captura todos os campos acumulados\n // dentro da janela de debounce, inclusive os adicionados por trigger()\n // chamados após este agendamento.\n const resolvedScopeFields = this.pendingScopeFields\n ? Array.from(this.pendingScopeFields)\n : undefined;\n this.pendingScopeFields = null;\n this.isGlobalPending = false;\n this.cancelTimeout = undefined;\n void this.validateWithOptionalScopeFields(resolvedScopeFields);\n }, delay);\n } else {\n let mergedScopeFields = scopeFields;\n\n if (this.isGlobalPending) {\n mergedScopeFields = undefined;\n } else if (this.pendingScopeFields) {\n if (scopeFields) {\n for (const f of scopeFields) this.pendingScopeFields.add(f);\n }\n mergedScopeFields = Array.from(this.pendingScopeFields);\n }\n\n this.pendingScopeFields = null;\n this.isGlobalPending = false;\n void this.validateWithOptionalScopeFields(mergedScopeFields);\n }\n }\n\n private validateWithOptionalScopeFields(scopeFields?: string[]) {\n if (scopeFields && scopeFields.length > 0) {\n return this.port.validate({ scopeFields });\n }\n\n return this.port.validate();\n }\n\n cancelPending(): void {\n if (this.cancelTimeout) {\n this.cancelTimeout();\n this.cancelTimeout = undefined;\n }\n this.pendingScopeFields = null;\n this.isGlobalPending = false;\n }\n}\n","import { getDeepValue } from \"../../../../utils\";\nimport type { BitErrors, BitFieldDefinition } from \"../../../contracts/types\";\n\ntype BitAsyncValidateFn<T extends object> = NonNullable<\n NonNullable<BitFieldDefinition<T>[\"validation\"]>[\"asyncValidate\"]\n>;\n\nconst BIT_ASYNC_VALIDATION_TIMEOUT = Symbol(\"bit.async.validation.timeout\");\n\nexport function mergeValidationErrors<T extends object>(args: {\n targetFields?: string[];\n currentErrors: BitErrors<T>;\n allErrors: Record<string, string | undefined>;\n asyncErrors: ReadonlyMap<string, string>;\n hiddenFields?: ReadonlySet<string>;\n}) {\n const { targetFields, currentErrors, allErrors, asyncErrors, hiddenFields } =\n args;\n\n if (targetFields && targetFields.length > 0) {\n let scopedErrors = currentErrors;\n let hasScopedMutation = false;\n\n const ensureScopedMutable = () => {\n if (!hasScopedMutation) {\n scopedErrors = { ...currentErrors } as BitErrors<T>;\n hasScopedMutation = true;\n }\n\n return scopedErrors;\n };\n\n targetFields.forEach((field) => {\n const key = field as keyof BitErrors<T>;\n const currentMessage = currentErrors[key] as string | undefined;\n\n // Hidden fields are excluded from committed errors regardless of asyncErrors state.\n if (hiddenFields?.has(field)) {\n if (currentMessage !== undefined) {\n delete ensureScopedMutable()[key];\n }\n return;\n }\n\n if (allErrors[field] !== undefined) {\n if (currentMessage !== allErrors[field]) {\n ensureScopedMutable()[key] = allErrors[field];\n }\n } else if (asyncErrors.has(field)) {\n const asyncMessage = asyncErrors.get(field)!;\n if (currentMessage !== asyncMessage) {\n ensureScopedMutable()[key] = asyncMessage;\n }\n } else {\n if (currentMessage !== undefined) {\n delete ensureScopedMutable()[key];\n }\n }\n });\n\n const scopedResult = targetFields.every(\n (field) =>\n hiddenFields?.has(field) ||\n (allErrors[field] === undefined && !asyncErrors.has(field)),\n );\n\n return {\n committedErrors: hasScopedMutation ? scopedErrors : currentErrors,\n result: scopedResult,\n mode: \"scoped\" as const,\n };\n }\n\n const globalErrors = {} as BitErrors<T>;\n\n asyncErrors.forEach((message, path) => {\n // Skip async errors for currently hidden fields.\n // We no longer delete them from the shared Map (they survive visibility toggles),\n // so we must exclude them here at commit time instead.\n if (hiddenFields?.has(path)) return;\n globalErrors[path as keyof BitErrors<T>] = message;\n });\n\n Object.entries(allErrors).forEach(([path, message]) => {\n if (message !== undefined) {\n globalErrors[path as keyof BitErrors<T>] = message;\n }\n });\n\n return {\n committedErrors: globalErrors,\n result: undefined,\n mode: \"global\" as const,\n };\n}\n\nexport function resolveAsyncValidationPaths<T extends object>(args: {\n targetFields?: string[];\n hiddenFields: ReadonlySet<string>;\n getFieldConfig: (path: string) => BitFieldDefinition<T> | undefined;\n forEachFieldConfig?: (\n callback: (config: BitFieldDefinition<T>, path: string) => void,\n ) => void;\n}): string[] {\n const { targetFields, hiddenFields, getFieldConfig, forEachFieldConfig } =\n args;\n const paths: string[] = [];\n\n if (targetFields && targetFields.length > 0) {\n for (const path of targetFields) {\n if (hiddenFields.has(path)) {\n continue;\n }\n\n const asyncValidate = getFieldConfig(path)?.validation?.asyncValidate;\n if (asyncValidate) {\n paths.push(path);\n }\n }\n\n return paths;\n }\n\n if (!forEachFieldConfig) {\n return paths;\n }\n\n forEachFieldConfig((config, path) => {\n if (!config.validation?.asyncValidate || hiddenFields.has(path)) {\n return;\n }\n\n paths.push(path);\n });\n\n return paths;\n}\n\nexport async function runImmediateAsyncValidationStage<T extends object>(args: {\n path: string;\n values: T;\n validationId: number;\n getCurrentValidationId: () => number;\n getFieldConfig: (path: string) => BitFieldDefinition<T> | undefined;\n cancelFieldAsync: (path: string) => void;\n createAbortController: () => AbortController;\n setAbortController: (path: string, controller: AbortController) => void;\n clearAbortController: (path: string, controller: AbortController) => boolean;\n setFieldValidating: (path: string, isValidating: boolean) => void;\n setAsyncError: (path: string, message: string) => void;\n clearAsyncError: (path: string) => void;\n}) {\n const {\n path,\n values,\n validationId,\n getCurrentValidationId,\n getFieldConfig,\n cancelFieldAsync,\n createAbortController,\n setAbortController,\n clearAbortController,\n setFieldValidating,\n setAsyncError,\n clearAsyncError,\n } = args;\n\n const asyncValidate = getFieldConfig(path)?.validation?.asyncValidate;\n\n if (!asyncValidate) {\n clearAsyncError(path);\n return;\n }\n\n cancelFieldAsync(path);\n clearAsyncError(path);\n\n const controller = createAbortController();\n setAbortController(path, controller);\n setFieldValidating(path, true);\n\n try {\n const asyncValidateTimeout =\n getFieldConfig(path)?.validation?.asyncValidateTimeout;\n\n let validationPromise: Promise<\n string | null | undefined | typeof BIT_ASYNC_VALIDATION_TIMEOUT\n > = (asyncValidate as BitAsyncValidateFn<T>)(\n getDeepValue(values, path),\n values,\n );\n\n if (typeof asyncValidateTimeout === \"number\" && asyncValidateTimeout > 0) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n validationPromise = Promise.race([\n validationPromise,\n new Promise<typeof BIT_ASYNC_VALIDATION_TIMEOUT>((resolve) => {\n timeoutId = setTimeout(\n () => resolve(BIT_ASYNC_VALIDATION_TIMEOUT),\n asyncValidateTimeout,\n );\n }),\n ]).finally(() => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n });\n }\n\n const errorMessage = await validationPromise;\n\n if (\n controller.signal.aborted ||\n validationId !== getCurrentValidationId()\n ) {\n return;\n }\n\n if (errorMessage === BIT_ASYNC_VALIDATION_TIMEOUT) {\n // Timeout is inconclusive: preserve current async error state.\n } else if (errorMessage !== null && errorMessage !== undefined) {\n setAsyncError(path, errorMessage);\n } else {\n clearAsyncError(path);\n }\n } finally {\n const releasedCurrentController = clearAbortController(path, controller);\n if (releasedCurrentController) {\n setFieldValidating(path, false);\n }\n }\n}\n","import type { BitValidationPipelinePort } from \"../../../contracts/port-types\";\nimport { validationCommitOperation } from \"../../../engines/operation-engine\";\nimport { hasAnyError } from \"../../../shared/error-map\";\nimport type { ValidationPipelineContext } from \"./validation-pipeline-context\";\nimport {\n mergeValidationErrors,\n resolveAsyncValidationPaths,\n} from \"./validation-stages\";\n\nexport interface BitValidationPipelineStageDeps<T extends object> {\n store: BitValidationPipelinePort<T>;\n asyncErrors: Map<string, string>;\n getCurrentValidationId: () => number;\n runImmediateAsyncValidation: (\n path: string,\n values: T,\n validationId: number,\n ) => Promise<void>;\n}\n\nexport function resolveTargetFieldsStage<T extends object>(args: {\n ctx: ValidationPipelineContext<T>;\n deps: BitValidationPipelineStageDeps<T>;\n}) {\n const { ctx, deps } = args;\n const rawOptions = ctx.options as\n | { scope?: string; scopeFields?: string[] }\n | undefined;\n\n if (rawOptions?.scope && rawOptions.scopeFields?.length) {\n deps.store.config.onUnhandledError(\n new Error(\n \"validate received both 'scope' and 'scopeFields'. 'scopeFields' takes precedence.\",\n ),\n \"validation\",\n );\n return;\n }\n\n if (ctx.options?.scopeFields?.length) {\n return;\n }\n\n if (ctx.options?.scope) {\n const scopeFields = deps.store.getScopeFields(ctx.options.scope);\n if (scopeFields.length > 0) {\n ctx.targetFields = scopeFields;\n }\n }\n}\n\nexport async function runBeforeValidateHooksStage<T extends object>(args: {\n ctx: ValidationPipelineContext<T>;\n deps: BitValidationPipelineStageDeps<T>;\n}) {\n const { ctx, deps } = args;\n\n await deps.store.emitBeforeValidate({\n values: ctx.currentState.values,\n state: ctx.currentState,\n scope: ctx.options?.scope,\n scopeFields: ctx.targetFields,\n });\n}\n\nexport async function runSynchronousTrackStage<T extends object>(args: {\n ctx: ValidationPipelineContext<T>;\n deps: BitValidationPipelineStageDeps<T>;\n}) {\n const { ctx, deps } = args;\n\n const resolverErrors = deps.store.config.resolver\n ? await deps.store.config.resolver(ctx.currentState.values, {\n scopeFields: ctx.targetFields,\n })\n : {};\n\n const dynamicRequiredErrors = deps.store.getRequiredErrors(\n ctx.currentState.values,\n );\n\n ctx.allErrors = { ...resolverErrors, ...dynamicRequiredErrors };\n\n deps.store.getHiddenFields().forEach((hiddenPath) => {\n delete ctx.allErrors[hiddenPath];\n // NOTE: Do NOT mutate deps.asyncErrors here. The shared asyncErrors Map\n // must survive field visibility toggles. When the field becomes visible again\n // the async error needs to still be present for the next validation commit.\n // Hidden paths are excluded during mergeValidationErrors via the\n // committedErrors merge path — they simply won't appear in the final errors.\n });\n}\n\nexport async function runAsyncTrackStage<T extends object>(args: {\n ctx: ValidationPipelineContext<T>;\n deps: BitValidationPipelineStageDeps<T>;\n}) {\n const { ctx, deps } = args;\n\n const targetPaths = resolveAsyncValidationPaths<T>({\n targetFields: ctx.targetFields,\n hiddenFields: deps.store.getHiddenFields(),\n getFieldConfig: (path) => deps.store.getFieldConfig(path),\n forEachFieldConfig: deps.store.forEachFieldConfig,\n });\n\n if (targetPaths.length === 0) {\n return;\n }\n\n const results = await Promise.allSettled(\n targetPaths.map((path) =>\n deps.runImmediateAsyncValidation(\n path,\n ctx.currentState.values,\n ctx.validationId,\n ),\n ),\n );\n\n for (const result of results) {\n if (result.status === \"rejected\") {\n deps.store.config.onUnhandledError(result.reason, \"validation\");\n }\n }\n}\n\nexport function mergeAsyncTrackStage<T extends object>(args: {\n ctx: ValidationPipelineContext<T>;\n deps: BitValidationPipelineStageDeps<T>;\n}) {\n const { ctx, deps } = args;\n\n const merged = mergeValidationErrors<T>({\n targetFields: ctx.targetFields,\n currentErrors: ctx.currentState.errors,\n allErrors: ctx.allErrors,\n asyncErrors: deps.asyncErrors,\n hiddenFields: deps.store.getHiddenFields(),\n });\n\n ctx.committedErrors = merged.committedErrors;\n ctx.isValid = !hasAnyError(merged.committedErrors);\n ctx.result = merged.mode === \"scoped\" ? merged.result : ctx.isValid;\n}\n\nexport async function abortIfOutdatedStage<T extends object>(args: {\n ctx: ValidationPipelineContext<T>;\n deps: BitValidationPipelineStageDeps<T>;\n}) {\n const { ctx, deps } = args;\n if (ctx.validationId === deps.getCurrentValidationId()) {\n return;\n }\n\n ctx.aborted = true;\n ctx.result = deps.store.getState().isValid;\n ctx.halted = true;\n}\n\nexport async function commitValidationStage<T extends object>(args: {\n ctx: ValidationPipelineContext<T>;\n deps: BitValidationPipelineStageDeps<T>;\n}) {\n const { ctx, deps } = args;\n\n deps.store.dispatch(\n validationCommitOperation(ctx.committedErrors, ctx.isValid),\n );\n\n await deps.store.emitAfterValidate({\n values: deps.store.getState().values,\n state: deps.store.getState(),\n scope: ctx.options?.scope,\n scopeFields: ctx.targetFields,\n errors: ctx.committedErrors,\n result: ctx.result,\n });\n\n ctx.halted = true;\n}\n","import { BitPipelineRunner } from \"../../../shared/pipeline\";\nimport type { ValidationPipelineContext } from \"./validation-pipeline-context\";\nimport {\n abortIfOutdatedStage,\n commitValidationStage,\n mergeAsyncTrackStage,\n resolveTargetFieldsStage,\n runAsyncTrackStage,\n runBeforeValidateHooksStage,\n runSynchronousTrackStage,\n type BitValidationPipelineStageDeps,\n} from \"./validation-pipeline-stages\";\n\nexport type BitValidationPipelineOrchestratorDeps<T extends object> =\n BitValidationPipelineStageDeps<T>;\n\nexport class BitValidationPipelineOrchestrator<T extends object> {\n private readonly runner: BitPipelineRunner<ValidationPipelineContext<T>>;\n\n constructor(private readonly deps: BitValidationPipelineOrchestratorDeps<T>) {\n this.runner = new BitPipelineRunner<ValidationPipelineContext<T>>([\n {\n name: \"validate:resolve-target-fields\",\n run: (ctx) => resolveTargetFieldsStage({ ctx, deps: this.deps }),\n },\n {\n name: \"validate:before-hooks\",\n run: async (ctx) =>\n runBeforeValidateHooksStage({ ctx, deps: this.deps }),\n },\n {\n name: \"validate:sync-track\",\n run: async (ctx) => runSynchronousTrackStage({ ctx, deps: this.deps }),\n },\n {\n name: \"validate:abort-check-pre-async\",\n run: async (ctx) => abortIfOutdatedStage({ ctx, deps: this.deps }),\n },\n {\n name: \"validate:async-track\",\n run: async (ctx) => runAsyncTrackStage({ ctx, deps: this.deps }),\n },\n {\n name: \"validate:abort-check\",\n run: async (ctx) => abortIfOutdatedStage({ ctx, deps: this.deps }),\n },\n {\n name: \"validate:async-track-merge\",\n run: (ctx) => mergeAsyncTrackStage({ ctx, deps: this.deps }),\n },\n {\n name: \"validate:commit\",\n run: async (ctx) => commitValidationStage({ ctx, deps: this.deps }),\n },\n ]);\n }\n\n async run(context: ValidationPipelineContext<T>): Promise<void> {\n await this.runner.run(context);\n }\n}\n","import { remapIndexedPath } from \"../../../utils\";\nimport type {\n BitValidationManagerPort,\n BitValidationPipelinePort,\n BitValidationTriggerOptions,\n} from \"../../contracts/port-types\";\nimport { BitValidationOptions } from \"../../contracts/public/meta-types\";\nimport { patchStateOperation } from \"../../engines/operation-engine\";\nimport { BitAsyncValidationScheduler } from \"./validation/async-validation-scheduler\";\nimport { commitSynchronousScopeValidation } from \"./validation/scope-validation-commit\";\nimport { BitValidationCoordinator } from \"./validation/validation-coordinator\";\nimport { BitValidationDebouncer } from \"./validation/validation-debouncer\";\nimport type { ValidationPipelineContext } from \"./validation/validation-pipeline-context\";\nimport {\n BitValidationPipelineOrchestrator,\n type BitValidationPipelineOrchestratorDeps,\n} from \"./validation/validation-pipeline-orchestrator\";\nimport { runImmediateAsyncValidationStage } from \"./validation/validation-stages\";\n\nexport class BitValidationManager<T extends object> {\n private validatingCount = 0;\n private readonly asyncErrors = new Map<string, string>();\n private readonly coordinator = new BitValidationCoordinator();\n private readonly validationPipeline: BitValidationPipelineOrchestrator<T>;\n private readonly pipelineStore: BitValidationPipelinePort<T>;\n private readonly schedule: (fn: () => void, delayMs: number) => () => void;\n private readonly asyncScheduler: BitAsyncValidationScheduler<T>;\n private readonly debouncer: BitValidationDebouncer;\n\n constructor(private store: BitValidationManagerPort<T>) {\n this.schedule =\n store.config.scheduler?.schedule ??\n ((fn, delayMs) => {\n const timeoutId = setTimeout(fn, delayMs);\n return () => clearTimeout(timeoutId);\n });\n\n this.debouncer = new BitValidationDebouncer({\n schedule: (fn, delayMs) => this.schedule(fn, delayMs),\n validate: (options) => this.validate(options),\n validationDelay: store.config.validationDelay ?? 300,\n });\n\n this.pipelineStore = {\n getState: () => this.store.getState(),\n dispatch: (operation) => this.store.dispatch(operation),\n config: this.store.config,\n getFieldConfig: (path) => this.store.getFieldConfig(path),\n forEachFieldConfig: (callback) => this.store.forEachFieldConfig(callback),\n getScopeFields: (scopeName) => this.store.getScopeFields(scopeName),\n getRequiredErrors: (values) => this.store.getRequiredErrors(values),\n getHiddenFields: () => this.store.getHiddenFields(),\n emitBeforeValidate: (event) => this.store.emitBeforeValidate(event),\n emitAfterValidate: (event) => this.store.emitAfterValidate(event),\n };\n\n this.asyncScheduler = new BitAsyncValidationScheduler<T>({\n schedule: (fn, delayMs) => this.schedule(fn, delayMs),\n getValues: () => this.store.getState().values,\n setFieldValidating: (path, isValidating) =>\n this.updateFieldValidating(path, isValidating),\n setAsyncError: (path, message) => {\n this.asyncErrors.set(path, message);\n this.store.setError(path, message);\n },\n clearAsyncError: (path) => {\n const previousAsyncMessage = this.asyncErrors.get(path);\n this.asyncErrors.delete(path);\n\n if (previousAsyncMessage && !this.store.config.resolver) {\n const currentMessage = this.store.getState().errors[path];\n if (currentMessage === previousAsyncMessage) {\n this.store.setError(path, undefined);\n }\n }\n\n void commitSynchronousScopeValidation({\n scopeFields: [path],\n store: this.pipelineStore,\n asyncErrors: this.asyncErrors,\n }).catch((error) => {\n this.store.config.onUnhandledError(error, \"validation\");\n });\n },\n onValidationPassed: async (path) => {\n await commitSynchronousScopeValidation({\n scopeFields: [path],\n store: this.pipelineStore,\n asyncErrors: this.asyncErrors,\n });\n },\n onError: (error) => {\n this.store.config.onUnhandledError(error, \"validation\");\n },\n });\n\n const stageDeps: BitValidationPipelineOrchestratorDeps<T> = {\n store: this.pipelineStore,\n asyncErrors: this.asyncErrors,\n getCurrentValidationId: () => this.coordinator.getCurrentValidationId(),\n runImmediateAsyncValidation: (path, values, validationId) =>\n this.runImmediateAsyncValidation(path, values, validationId),\n };\n\n this.validationPipeline = new BitValidationPipelineOrchestrator<T>(\n stageDeps,\n );\n }\n\n private updateFieldValidating(path: string, isValidating: boolean) {\n const currentState = this.store.getState();\n const currentValue = !!currentState.isValidating[path];\n\n if (currentValue === isValidating) {\n return;\n }\n\n const nextValidating = { ...currentState.isValidating };\n\n if (isValidating) {\n nextValidating[path] = true;\n this.validatingCount += 1;\n } else {\n delete nextValidating[path];\n this.validatingCount = Math.max(0, this.validatingCount - 1);\n }\n\n this.store.dispatch(\n patchStateOperation({\n isValidating: nextValidating,\n }),\n );\n }\n\n private cancelFieldAsync(path: string) {\n this.asyncScheduler.cancel(path);\n this.coordinator.cancelImmediate(path);\n }\n\n cleanupField(path: string) {\n this.cancelFieldAsync(path);\n this.asyncErrors.delete(path);\n this.updateFieldValidating(path, false);\n }\n\n cleanupPrefix(prefix: string) {\n this.asyncScheduler.cleanupPrefix(prefix);\n\n this.coordinator.cancelImmediatePrefix(prefix, (path) => {\n this.asyncErrors.delete(path);\n this.updateFieldValidating(path, false);\n });\n }\n\n remapArrayPaths(\n path: string,\n remapIndex: (currentIdx: number) => number | null,\n ) {\n const prefix = `${path}.`;\n\n this.asyncScheduler.remapPaths((currentPath) =>\n remapIndexedPath(currentPath, prefix, remapIndex),\n );\n\n this.coordinator.remapImmediateControllers((currentPath) =>\n remapIndexedPath(currentPath, prefix, remapIndex),\n );\n\n const nextAsyncErrors = new Map<string, string>();\n this.asyncErrors.forEach((message, currentPath) => {\n const nextPath = remapIndexedPath(currentPath, prefix, remapIndex);\n\n if (nextPath !== null) {\n nextAsyncErrors.set(nextPath, message);\n }\n });\n\n this.asyncErrors.clear();\n nextAsyncErrors.forEach((message, nextPath) => {\n this.asyncErrors.set(nextPath, message);\n });\n }\n\n beginExternalValidation(path: string) {\n this.cancelFieldAsync(path);\n this.updateFieldValidating(path, true);\n }\n\n endExternalValidation(path: string) {\n this.updateFieldValidating(path, false);\n }\n\n async setExternalError(path: string, message: string | undefined) {\n if (message) {\n this.asyncErrors.set(path, message);\n this.store.setError(path, message);\n return;\n }\n\n this.cancelFieldAsync(path);\n this.asyncErrors.delete(path);\n this.store.setError(path, undefined);\n\n await this.validate({ scopeFields: [path] });\n return;\n }\n\n handleAsync(path: string, value: unknown) {\n const config = this.store.getFieldConfig(path);\n const asyncValidate = config?.validation?.asyncValidate;\n const asyncValidateOn = config?.validation?.asyncValidateOn ?? \"blur\";\n\n if (!asyncValidate || asyncValidateOn !== \"change\") {\n this.cancelFieldAsync(path);\n this.updateFieldValidating(path, false);\n return;\n }\n\n const delay = config.validation?.asyncValidateDelay ?? 500;\n const timeout = config.validation?.asyncValidateTimeout;\n this.asyncScheduler.handle(path, value, asyncValidate, delay, timeout);\n }\n\n hasValidationsInProgress(scopeFields?: string[]) {\n const state = this.store.getState();\n\n if (scopeFields && scopeFields.length > 0) {\n return scopeFields.some((field) => !!state.isValidating[field]);\n }\n\n return Object.keys(state.isValidating).length > 0;\n }\n\n trigger(scopeFields?: string[], options?: BitValidationTriggerOptions) {\n this.debouncer.trigger(scopeFields, options);\n }\n\n async validate(options?: BitValidationOptions): Promise<boolean> {\n try {\n if (options?.scopeFields?.length) {\n options.scopeFields.forEach((fieldPath) => {\n this.cancelFieldAsync(fieldPath);\n this.updateFieldValidating(fieldPath, false);\n });\n }\n\n const context: ValidationPipelineContext<T> = {\n options,\n validationId: this.coordinator.beginValidation(),\n currentState: this.store.getState(),\n targetFields: options?.scopeFields,\n allErrors: {},\n committedErrors: {},\n isValid: true,\n result: true,\n aborted: false,\n };\n\n await this.validationPipeline.run(context);\n\n if (context.aborted) {\n const liveState = this.store.getState();\n await this.store.emitAfterValidate({\n values: liveState.values,\n state: liveState,\n scope: context.options?.scope,\n scopeFields: context.targetFields,\n errors: liveState.errors,\n result: liveState.isValid,\n aborted: true,\n });\n }\n\n return context.result;\n } catch (error) {\n this.store.config.onUnhandledError(error, \"validation\");\n return false;\n }\n }\n\n clear(path: string) {\n this.cancelFieldAsync(path);\n this.updateFieldValidating(path, false);\n this.asyncErrors.delete(path);\n }\n\n cancelAll() {\n this.validatingCount = 0;\n this.debouncer.cancelPending();\n\n this.asyncScheduler.cancelAll();\n this.asyncErrors.clear();\n this.coordinator.cancelAllImmediate();\n\n // Dispatch clear AFTER aborting async validation, to overwrite any residual state\n // that might have been dispatched synchronously by the cancelAll operations.\n this.store.dispatch(patchStateOperation({ isValidating: {} }));\n }\n\n private async runImmediateAsyncValidation(\n path: string,\n values: T,\n validationId: number,\n ) {\n await runImmediateAsyncValidationStage<T>({\n path,\n values,\n validationId,\n getCurrentValidationId: () => this.coordinator.getCurrentValidationId(),\n getFieldConfig: (fieldPath) => this.store.getFieldConfig(fieldPath),\n cancelFieldAsync: (fieldPath) => this.cancelFieldAsync(fieldPath),\n createAbortController: () => new AbortController(),\n setAbortController: (fieldPath, controller) => {\n this.coordinator.setImmediateController(fieldPath, controller);\n },\n clearAbortController: (fieldPath, ctrl) => {\n return this.coordinator.clearImmediateController(fieldPath, ctrl);\n },\n setFieldValidating: (fieldPath, isValidating) =>\n this.updateFieldValidating(fieldPath, isValidating),\n setAsyncError: (fieldPath, message) => {\n this.asyncErrors.set(fieldPath, message);\n },\n clearAsyncError: (fieldPath) => {\n this.asyncErrors.delete(fieldPath);\n },\n });\n }\n}\n","import type { BitStoreCapabilities } from \"./capabilities\";\n\nexport class BitStoreCapabilityRegistry<T extends object> {\n private readonly entries = new Map<\n keyof BitStoreCapabilities<T>,\n BitStoreCapabilities<T>[keyof BitStoreCapabilities<T>]\n >();\n\n register<K extends keyof BitStoreCapabilities<T>>(\n key: K,\n capability: BitStoreCapabilities<T>[K],\n ): void {\n this.entries.set(key, capability);\n }\n\n resolve<K extends keyof BitStoreCapabilities<T>>(\n key: K,\n ): BitStoreCapabilities<T>[K] {\n const capability = this.entries.get(key);\n\n if (!capability) {\n throw new Error(\n `BitStore capability \"${String(key)}\" não foi registrada.`,\n );\n }\n\n return capability as BitStoreCapabilities<T>[K];\n }\n\n toCapabilities(): BitStoreCapabilities<T> {\n return {\n validation: this.resolve(\"validation\"),\n lifecycle: this.resolve(\"lifecycle\"),\n history: this.resolve(\"history\"),\n arrays: this.resolve(\"arrays\"),\n scope: this.resolve(\"scope\"),\n query: this.resolve(\"query\"),\n error: this.resolve(\"error\"),\n };\n }\n}\n\nexport function createStoreCapabilityRegistry<T extends object>() {\n return new BitStoreCapabilityRegistry<T>();\n}\n","import { deepClone } from \"../../utils\";\nimport type {\n BitLifecyclePorts,\n BitValidationManagerPort,\n} from \"../contracts/port-types\";\nimport type { BitFrameworkConfig } from \"../contracts/public/store-api-types\";\nimport type { BitFieldDefinition, BitState } from \"../contracts/types\";\nimport type { BitStoreOperation } from \"../engines/operation-engine\";\nimport { analyzeCyclicDependencies } from \"../managers/core/computed-dependency-analyzer\";\nimport { BitComputedManager } from \"../managers/core/computed-manager\";\nimport {\n BitArrayManager,\n type BitArrayStorePort,\n} from \"../managers/features/array-manager\";\nimport { BitErrorManager } from \"../managers/features/error-manager\";\nimport { BitFieldQueryManager } from \"../managers/features/field-query-manager\";\nimport { BitHistoryManager } from \"../managers/features/history-manager\";\nimport { BitLifecycleManager } from \"../managers/features/lifecycle-manager\";\nimport { BitScopeManager } from \"../managers/features/scope-manager\";\nimport { BitValidationManager } from \"../managers/features/validation-manager\";\nimport { BitFieldRegistry } from \"../registry/field-registry\";\nimport { applyValueDerivations } from \"../shared/value-derivation-pipeline\";\nimport type { BitStoreCapabilities } from \"./capabilities\";\nimport {\n createStoreCapabilityRegistry,\n type BitStoreCapabilityRegistry,\n} from \"./store-capability-registry\";\n\nexport type BitStoreCapabilityPorts<T extends object> = {\n validationPort: BitValidationManagerPort<T>;\n lifecyclePorts: BitLifecyclePorts<T>;\n arrayPort: BitArrayStorePort<T>;\n config: BitFrameworkConfig<T>;\n getScopeFields(scopeName: string): string[];\n getState(): BitState<T>;\n dispatch(operation: BitStoreOperation<T>): void;\n getBaselineValues(): T;\n isPathDirty(path: string): boolean;\n};\n\nexport interface BitStoreCapabilityComposition<T extends object> {\n registry: BitStoreCapabilityRegistry<T>;\n capabilities: BitStoreCapabilities<T>;\n}\n\nfunction registerStoreCapabilities<T extends object>(args: {\n registry: BitStoreCapabilityRegistry<T>;\n ports: BitStoreCapabilityPorts<T>;\n fieldRegistry: BitFieldRegistry<T>;\n}) {\n const { registry, ports, fieldRegistry } = args;\n\n registry.register(\n \"validation\",\n new BitValidationManager<T>(ports.validationPort),\n );\n registry.register(\n \"lifecycle\",\n new BitLifecycleManager<T>(ports.lifecyclePorts),\n );\n registry.register(\n \"history\",\n new BitHistoryManager<T>(\n !!ports.config.history.enabled,\n ports.config.history.limit ?? 50,\n ),\n );\n registry.register(\"arrays\", new BitArrayManager<T>(ports.arrayPort));\n registry.register(\n \"scope\",\n new BitScopeManager<T>(\n () => ports.getState(),\n () => ports.getBaselineValues(),\n (scopeName) => ports.getScopeFields(scopeName),\n (path) => ports.isPathDirty(path),\n ),\n );\n registry.register(\n \"query\",\n new BitFieldQueryManager<T>(\n fieldRegistry,\n () => ports.getState(),\n (path) => ports.isPathDirty(path),\n ),\n );\n registry.register(\n \"error\",\n new BitErrorManager<T>(\n () => ports.getState(),\n (operation) => ports.dispatch(operation),\n (error) => ports.config.onUnhandledError(error, \"errors\"),\n ),\n );\n}\n\nexport function composeStoreCapabilities<T extends object>(args: {\n ports: BitStoreCapabilityPorts<T>;\n fieldRegistry: BitFieldRegistry<T>;\n}): BitStoreCapabilityComposition<T> {\n const { ports, fieldRegistry } = args;\n const registry = createStoreCapabilityRegistry<T>();\n registerStoreCapabilities({ registry, ports, fieldRegistry });\n\n return {\n registry,\n capabilities: registry.toCapabilities(),\n };\n}\n\nexport function createInitialStoreState<T extends object>(args: {\n config: BitFrameworkConfig<T>;\n fieldRegistry: BitFieldRegistry<T>;\n computedManager: BitComputedManager<T>;\n}): BitState<T> {\n const { config, fieldRegistry, computedManager } = args;\n\n const initialValues = deepClone(config.initialValues);\n\n if (config.fields) {\n Object.entries(config.fields).forEach(([path, fieldConfig]) => {\n fieldRegistry.register(\n path,\n fieldConfig as BitFieldDefinition<T>,\n initialValues,\n );\n });\n }\n\n const computedCycles = analyzeCyclicDependencies(\n fieldRegistry.getComputedEntries(initialValues),\n );\n\n if (computedCycles.length > 0) {\n throw new Error(computedCycles[0].message);\n }\n\n const initialDerivedValues = applyValueDerivations({\n values: initialValues,\n normalizerEntries: fieldRegistry.getNormalizerEntries(initialValues),\n applyComputed: (values, changedPaths) =>\n computedManager.apply(values, changedPaths),\n onError: (error, _path) => {\n config.onUnhandledError(error, \"derivation\");\n },\n });\n\n return {\n values: initialDerivedValues,\n errors: {},\n touched: {},\n isValidating: {},\n persist: {\n isSaving: false,\n isRestoring: false,\n error: null,\n },\n isValid: true,\n isSubmitting: false,\n isDirty: false,\n };\n}\n","import type {\n BitLifecycleFieldUpdatePort,\n BitLifecyclePorts,\n BitLifecycleSubmitPort,\n BitLifecycleValuesPort,\n BitValidationManagerPort,\n BitValidationTriggerOptions,\n} from \"../contracts/port-types\";\nimport type {\n BitServerErrorOptions,\n BitValidationOptions,\n} from \"../contracts/public/meta-types\";\nimport type { BitFrameworkConfig } from \"../contracts/public/store-api-types\";\nimport type {\n BitFieldChangeMeta,\n BitFieldDefinition,\n BitState,\n BitTransformFn,\n} from \"../contracts/types\";\nimport type { BitStoreEffectEngine } from \"../engines/effect-engine\";\nimport type { BitStoreOperation } from \"../engines/operation-engine\";\nimport { BitDirtyManager } from \"../managers/core/dirty-manager\";\nimport type { BitArrayStorePort } from \"../managers/features/array-manager\";\nimport { BitFieldRegistry } from \"../registry/field-registry\";\n\n// Interfaces locais usadas pelas deps do lifecycle port\ninterface BitValidationAccess<_T extends object> {\n clear(path: string): void;\n trigger(scopeFields?: string[], options?: BitValidationTriggerOptions): void;\n handleAsync(path: string, value: unknown): void;\n remapArrayPaths(\n path: string,\n remapIndex: (currentIdx: number) => number | null,\n ): void;\n cancelAll(): void;\n validate(options?: BitValidationOptions): Promise<boolean>;\n hasValidationsInProgress(scopeFields?: string[]): boolean;\n}\n\ninterface BitHistoryAccess<T extends object> {\n reset(initialValues: T): void;\n}\n\n// ---------------------------------------------------------------------------\n// Validation port\n// ---------------------------------------------------------------------------\n\nexport interface BitValidationPortDeps<T extends object> {\n config: BitFrameworkConfig<T>;\n fieldRegistry: BitFieldRegistry<T>;\n getState(): BitState<T>;\n dispatch(operation: BitStoreOperation<T>): void;\n setError(path: string, message: string | undefined): void;\n getFieldConfig(path: string): BitFieldDefinition<T> | undefined;\n getScopeFields(scopeName: string): string[];\n getEffects(): BitStoreEffectEngine<T>;\n}\n\nexport function createValidationPort<T extends object>(\n deps: BitValidationPortDeps<T>,\n): BitValidationManagerPort<T> {\n return {\n getState: deps.getState,\n dispatch: deps.dispatch,\n setError: deps.setError,\n getFieldConfig: deps.getFieldConfig,\n forEachFieldConfig: (callback) =>\n deps.fieldRegistry.forEachFieldConfig((config, path) =>\n callback(config, path),\n ),\n getScopeFields: deps.getScopeFields,\n config: deps.config,\n getRequiredErrors: (values) => deps.fieldRegistry.getRequiredErrors(values),\n getHiddenFields: () => deps.fieldRegistry.getHiddenFields(),\n emitBeforeValidate: (event) => deps.getEffects().beforeValidate(event),\n emitAfterValidate: (event) => deps.getEffects().afterValidate(event),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Lifecycle port\n// ---------------------------------------------------------------------------\n\nexport interface BitLifecyclePortDeps<T extends object> {\n config: BitFrameworkConfig<T>;\n fieldRegistry: BitFieldRegistry<T>;\n dirtyManager: BitDirtyManager<T>;\n getState(): BitState<T>;\n dispatch(operation: BitStoreOperation<T>): void;\n setServerErrors(\n serverErrors: Record<string, string[] | string>,\n options?: BitServerErrorOptions,\n ): void;\n saveHistorySnapshot(): void;\n runStateBatch<TResult>(callback: () => TResult): TResult;\n getTransformEntries(): [string, BitTransformFn<T>][];\n getBaselineValues(): T;\n setBaselineValues(values: T): void;\n getValidation(): BitValidationAccess<T>;\n getHistory(): BitHistoryAccess<T>;\n getEffects(): BitStoreEffectEngine<T>;\n}\n\nexport function createLifecyclePort<T extends object>(\n deps: BitLifecyclePortDeps<T>,\n): BitLifecyclePorts<T> {\n const fieldUpdate: BitLifecycleFieldUpdatePort<T> = {\n getState: deps.getState,\n dispatch: deps.dispatch,\n config: deps.config,\n getFieldConfig: (path) => deps.fieldRegistry.getFieldConfig(path),\n updateDependencies: (changedPath, currentValues, newValues) =>\n deps.fieldRegistry.updateDependencies(\n changedPath,\n currentValues,\n newValues,\n ),\n hasDependentFields: (path) => deps.fieldRegistry.hasDependents(path),\n isFieldHidden: (path) => deps.fieldRegistry.isHidden(path),\n clearFieldValidation: (path) => deps.getValidation().clear(path),\n triggerValidation: (scopeFields, options) =>\n deps.getValidation().trigger(scopeFields, options),\n handleFieldAsyncValidation: (path, value) =>\n deps.getValidation().handleAsync(path, value),\n updateDirtyForPath: (path, nextValues, baselineValues) =>\n deps.dirtyManager.updateForPath(path, nextValues, baselineValues),\n getBaselineValues: deps.getBaselineValues,\n emitFieldChange: (event) => deps.getEffects().onFieldChange(event),\n };\n\n const values: BitLifecycleValuesPort<T> = {\n getState: deps.getState,\n dispatch: deps.dispatch,\n config: deps.config,\n internalSaveSnapshot: deps.saveHistorySnapshot,\n evaluateAllDependencies: (newValues) =>\n deps.fieldRegistry.evaluateAll(newValues),\n cancelAllValidations: () => deps.getValidation().cancelAll(),\n validateNow: (options) => deps.getValidation().validate(options),\n rebuildDirtyState: (nextValues, baselineValues) =>\n deps.dirtyManager.rebuild(nextValues, baselineValues),\n clearDirtyState: deps.dirtyManager.clear.bind(deps.dirtyManager),\n getBaselineValues: deps.getBaselineValues,\n setBaselineValues: deps.setBaselineValues,\n resetHistory: (initialValues) => deps.getHistory().reset(initialValues),\n emitFieldChange: (event) => deps.getEffects().onFieldChange(event),\n triggerValidation: (scopeFields, options) =>\n deps.getValidation().trigger(scopeFields, options),\n };\n\n const submit: BitLifecycleSubmitPort<T> = {\n getState: deps.getState,\n dispatch: deps.dispatch,\n batchStateUpdates: deps.runStateBatch,\n config: deps.config,\n getTransformEntries: deps.getTransformEntries,\n getHiddenFields: () => deps.fieldRegistry.getHiddenFields(),\n cancelAllValidations: () => deps.getValidation().cancelAll(),\n validateNow: (options) => deps.getValidation().validate(options),\n hasValidationsInProgress: (scopeFields) =>\n deps.getValidation().hasValidationsInProgress(scopeFields),\n buildDirtyValues: (values) => deps.dirtyManager.buildDirtyValues(values),\n setServerErrors: (serverErrors, options) =>\n deps.setServerErrors(serverErrors, options),\n emitBeforeSubmit: (event) => deps.getEffects().beforeSubmit(event),\n emitAfterSubmit: (event) => deps.getEffects().afterSubmit(event),\n emitOperationalError: (event) =>\n deps.getEffects().reportOperationalError(event),\n };\n\n return {\n fieldUpdate,\n values,\n submit,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Array port\n// ---------------------------------------------------------------------------\n\nexport interface BitArrayPortDeps<T extends object> {\n getState(): BitState<T>;\n dispatch(operation: BitStoreOperation<T>): void;\n setFieldWithMeta(\n path: string,\n value: unknown,\n meta: BitFieldChangeMeta,\n ): void;\n unregisterPrefix(prefix: string): void;\n remapValidationPaths(\n path: string,\n remapIndex: (currentIdx: number) => number | null,\n ): void;\n saveHistorySnapshot(): void;\n createArrayItemId(path: string, index?: number): string;\n}\n\nexport function createArrayPort<T extends object>(\n deps: BitArrayPortDeps<T>,\n): BitArrayStorePort<T> {\n return {\n getState: deps.getState,\n setFieldWithMeta: deps.setFieldWithMeta,\n dispatch: deps.dispatch,\n internalSaveSnapshot: deps.saveHistorySnapshot,\n unregisterPrefix: deps.unregisterPrefix,\n remapValidationPaths: deps.remapValidationPaths,\n createArrayItemId: deps.createArrayItemId,\n };\n}\n","import type { BitValidationTriggerOptions } from \"../contracts/port-types\";\nimport type { BitFrameworkConfig } from \"../contracts/public/store-api-types\";\nimport type {\n BitFieldChangeMeta,\n BitFieldDefinition,\n BitState,\n BitTransformFn,\n} from \"../contracts/types\";\nimport type { BitStoreEffectEngine } from \"../engines/effect-engine\";\nimport type { BitStoreOperation } from \"../engines/operation-engine\";\nimport type { BitBaselineManager } from \"../managers/core/baseline-manager\";\nimport type { BitDirtyManager } from \"../managers/core/dirty-manager\";\nimport type { BitNormalizerEntry } from \"../registry/field-catalog\";\nimport type { BitFieldRegistry } from \"../registry/field-registry\";\nimport type { BitStoreCapabilities } from \"./capabilities\";\nimport {\n createArrayPort,\n createLifecyclePort,\n createValidationPort,\n} from \"./capability-ports\";\nimport {\n composeStoreCapabilities,\n type BitStoreCapabilityComposition,\n} from \"./store-bootstrap\";\n\ntype BitRuntimeValidationOptions =\n | {\n scope: string;\n scopeFields?: never;\n }\n | {\n scope?: never;\n scopeFields: string[];\n }\n | {\n scope?: undefined;\n scopeFields?: undefined;\n };\n\nexport interface BitStoreRuntimeStateAccess<T extends object> {\n getState(): BitState<T>;\n dispatch(operation: BitStoreOperation<T>): void;\n saveHistorySnapshot(): void;\n runStateBatch<TResult>(callback: () => TResult): TResult;\n}\n\nexport interface BitStoreRuntimeFieldAccess<T extends object> {\n getFieldConfig(path: string): BitFieldDefinition<T> | undefined;\n getScopeFields(scopeName: string): string[];\n getNormalizerEntries(): BitNormalizerEntry<T>[];\n getTransformEntries(): [string, BitTransformFn<T>][];\n}\n\nexport interface BitStoreRuntimeFeatureAccess<T extends object> {\n getEffects(): BitStoreEffectEngine<T>;\n getHistory(): BitStoreCapabilities<T>[\"history\"];\n getValidation(): BitStoreCapabilities<T>[\"validation\"];\n}\n\nexport interface BitStoreRuntimeActions<_T extends object> {\n setError(path: string, message: string | undefined): void;\n setServerErrors(\n serverErrors: Record<string, string[] | string>,\n options?: { arrayStrategy?: \"first\" | \"join\"; joinSeparator?: string },\n ): void;\n validate(options?: BitRuntimeValidationOptions): Promise<boolean>;\n setFieldWithMeta(\n path: string,\n value: unknown,\n meta?: BitFieldChangeMeta,\n ): void;\n unregisterPrefix(prefix: string): void;\n triggerValidation(\n scopeFields?: string[],\n options?: BitValidationTriggerOptions,\n ): void;\n}\n\nexport interface BitStoreRuntimeContext<T extends object> {\n stateAccess: BitStoreRuntimeStateAccess<T>;\n fieldAccess: BitStoreRuntimeFieldAccess<T>;\n featureAccess: BitStoreRuntimeFeatureAccess<T>;\n actions: BitStoreRuntimeActions<T>;\n}\n\nexport interface ComposeRuntimeFeatureCapabilitiesArgs<T extends object> {\n config: BitFrameworkConfig<T>;\n fieldRegistry: BitFieldRegistry<T>;\n dirtyManager: BitDirtyManager<T>;\n baselineManager: BitBaselineManager<T>;\n runtimeContext: BitStoreRuntimeContext<T>;\n}\n\nexport function composeRuntimeFeatureCapabilities<T extends object>(\n args: ComposeRuntimeFeatureCapabilitiesArgs<T>,\n): BitStoreCapabilityComposition<T> {\n const {\n config,\n fieldRegistry,\n dirtyManager,\n baselineManager,\n runtimeContext,\n } = args;\n const { stateAccess, fieldAccess, featureAccess, actions } = runtimeContext;\n\n const validationPort = createValidationPort<T>({\n config,\n fieldRegistry,\n getState: stateAccess.getState,\n dispatch: stateAccess.dispatch,\n setError: actions.setError,\n getFieldConfig: fieldAccess.getFieldConfig,\n getScopeFields: fieldAccess.getScopeFields,\n getEffects: featureAccess.getEffects,\n });\n\n const lifecyclePorts = createLifecyclePort<T>({\n config,\n fieldRegistry,\n dirtyManager,\n getState: stateAccess.getState,\n dispatch: stateAccess.dispatch,\n setServerErrors: actions.setServerErrors,\n saveHistorySnapshot: stateAccess.saveHistorySnapshot,\n runStateBatch: stateAccess.runStateBatch,\n getTransformEntries: fieldAccess.getTransformEntries,\n getBaselineValues: () => baselineManager.getValues(),\n setBaselineValues: (values) => baselineManager.setValues(values),\n getValidation: featureAccess.getValidation,\n getHistory: featureAccess.getHistory,\n getEffects: featureAccess.getEffects,\n });\n\n const arrayPort = createArrayPort<T>({\n getState: stateAccess.getState,\n dispatch: stateAccess.dispatch,\n setFieldWithMeta: (path, value, meta) =>\n actions.setFieldWithMeta(path, value, meta),\n unregisterPrefix: actions.unregisterPrefix,\n remapValidationPaths: (path, remapIndex) =>\n featureAccess.getValidation().remapArrayPaths(path, remapIndex),\n saveHistorySnapshot: stateAccess.saveHistorySnapshot,\n createArrayItemId: (path, index) =>\n config.idFactory({ scope: \"array\", path, index }),\n });\n\n return composeStoreCapabilities<T>({\n ports: {\n validationPort,\n lifecyclePorts,\n arrayPort,\n config,\n getScopeFields: fieldAccess.getScopeFields,\n getState: stateAccess.getState,\n dispatch: stateAccess.dispatch,\n getBaselineValues: () => baselineManager.getValues(),\n isPathDirty: (path) => dirtyManager.isPathDirty(path),\n },\n fieldRegistry,\n });\n}\n","import type { BitFrameworkConfig } from \"../contracts/public/store-api-types\";\nimport type { BitConfig, BitState } from \"../contracts/types\";\nimport { BitSubscriptionEngine } from \"../engines/subscription-engine\";\nimport type { BitBaselineManager } from \"../managers/core/baseline-manager\";\nimport type { BitComputedManager } from \"../managers/core/computed-manager\";\nimport type { BitDirtyManager } from \"../managers/core/dirty-manager\";\nimport type { BitFieldRegistry } from \"../registry/field-registry\";\nimport { createInitialStoreState } from \"./store-bootstrap\";\nimport type { BitStoreCapabilityRegistry } from \"./store-capability-registry\";\nimport {\n composeRuntimeFeatureCapabilities,\n type BitStoreRuntimeContext,\n} from \"./store-runtime-feature-composition\";\n\nexport interface BitStoreRuntimeMembers<T extends object> {\n state: BitState<T>;\n subscriptions: BitSubscriptionEngine<T>;\n capabilityRegistry: BitStoreCapabilityRegistry<T>;\n storeId: string;\n}\n\nexport interface CreateStoreRuntimeArgs<T extends object> {\n rawConfig: BitConfig<T>;\n config: BitFrameworkConfig<T>;\n fieldRegistry: BitFieldRegistry<T>;\n computedManager: BitComputedManager<T>;\n dirtyManager: BitDirtyManager<T>;\n baselineManager: BitBaselineManager<T>;\n runtimeContext: BitStoreRuntimeContext<T>;\n}\n\nexport function createStoreRuntime<T extends object>(\n args: CreateStoreRuntimeArgs<T>,\n): BitStoreRuntimeMembers<T> {\n const {\n config,\n fieldRegistry,\n dirtyManager,\n computedManager,\n rawConfig,\n baselineManager,\n runtimeContext,\n } = args;\n const { stateAccess, fieldAccess, featureAccess, actions } = runtimeContext;\n\n const capabilityComposition = composeRuntimeFeatureCapabilities<T>({\n config,\n fieldRegistry,\n dirtyManager,\n baselineManager,\n runtimeContext: {\n stateAccess,\n fieldAccess,\n featureAccess,\n actions,\n },\n });\n\n const state = createInitialStoreState<T>({\n config,\n fieldRegistry,\n computedManager,\n });\n\n const subscriptions = new BitSubscriptionEngine<T>(\n stateAccess.getState,\n (error, source) => config.onUnhandledError(error, source),\n config.subscriptionCacheSize,\n );\n\n const storeId =\n rawConfig.storeId ||\n config.name ||\n config.idFactory({\n scope: \"store\",\n storeName: config.name,\n });\n\n return {\n state,\n subscriptions,\n capabilityRegistry: capabilityComposition.registry,\n storeId,\n };\n}\n","import type { BitState } from \"../contracts/types\";\nimport type { BitStateUpdateResult } from \"./state-update-engine\";\n\nexport interface BitStoreBatchState<T extends object> {\n depth: number;\n pendingState: BitState<T> | null;\n changedPathSet: Set<string> | null;\n changedPathList: string[] | null;\n valuesChanged: boolean;\n /** When true, a history snapshot should be recorded the moment the top-level\n * batch flushes. This allows multiple mutations inside a `transaction()` –\n * including individual array operations – to produce a single history entry\n * instead of one per mutation. */\n pendingHistorySnapshot: boolean;\n}\n\nexport interface BitStoreBatchFlushResult<T extends object> {\n nextState: BitState<T>;\n changedPaths?: readonly string[];\n valuesChanged: boolean;\n}\n\nexport function createStoreBatchState<\n T extends object,\n>(): BitStoreBatchState<T> {\n return {\n depth: 0,\n pendingState: null,\n changedPathSet: null,\n changedPathList: null,\n valuesChanged: false,\n pendingHistorySnapshot: false,\n };\n}\n\nexport function beginStoreBatch<T extends object>(\n batchState: BitStoreBatchState<T>,\n): void {\n batchState.depth += 1;\n}\n\nexport function endStoreBatch<T extends object>(\n batchState: BitStoreBatchState<T>,\n): boolean {\n batchState.depth -= 1;\n return batchState.depth === 0;\n}\n\nexport function getEffectiveStoreState<T extends object>(\n currentState: BitState<T>,\n batchState: BitStoreBatchState<T>,\n): BitState<T> {\n return batchState.pendingState ?? currentState;\n}\n\nexport function trackBatchedStoreUpdate<T extends object>(\n batchState: BitStoreBatchState<T>,\n updateResult: BitStateUpdateResult<T>,\n): void {\n batchState.pendingState = updateResult.nextState;\n batchState.valuesChanged ||= updateResult.valuesChanged;\n if (updateResult.valuesChanged) {\n batchState.pendingHistorySnapshot = true;\n }\n\n if (updateResult.changedPaths && updateResult.changedPaths.length > 0) {\n const pathSet = batchState.changedPathSet ?? new Set<string>();\n const pathList = batchState.changedPathList ?? [];\n\n updateResult.changedPaths.forEach((path) => {\n if (pathSet.has(\"*\") || pathSet.has(path)) {\n return;\n }\n\n if (path === \"*\") {\n pathSet.clear();\n pathList.length = 0;\n pathSet.add(\"*\");\n pathList.push(\"*\");\n return;\n }\n\n const hasAncestor = pathList.some(\n (existingPath) =>\n existingPath !== \"*\" && path.startsWith(`${existingPath}.`),\n );\n\n if (hasAncestor) {\n return;\n }\n\n for (let index = pathList.length - 1; index >= 0; index -= 1) {\n const existingPath = pathList[index];\n if (existingPath === \"*\" || !existingPath.startsWith(`${path}.`)) {\n continue;\n }\n\n pathSet.delete(existingPath);\n pathList.splice(index, 1);\n }\n\n pathSet.add(path);\n pathList.push(path);\n });\n\n batchState.changedPathSet = pathSet;\n batchState.changedPathList = pathList;\n }\n}\n\nexport function flushStoreBatchState<T extends object>(args: {\n currentState: BitState<T>;\n batchState: BitStoreBatchState<T>;\n applyValueDerivations: (values: T, changedPaths?: readonly string[]) => T;\n onDerivationError?: (error: unknown) => void;\n}): BitStoreBatchFlushResult<T> | null {\n const { currentState, batchState, applyValueDerivations, onDerivationError } =\n args;\n\n if (!batchState.pendingState) {\n return null;\n }\n\n let nextState = { ...batchState.pendingState };\n const changedPaths = batchState.changedPathList ?? undefined;\n const valuesChanged = batchState.valuesChanged;\n\n try {\n if (valuesChanged) {\n try {\n nextState = {\n ...nextState,\n values: applyValueDerivations(nextState.values, changedPaths),\n };\n } catch (error) {\n // Derivation failed: commit the raw accumulated state without derived\n // values so that kernel.state and subscribers stay in sync.\n // The error is surfaced via onDerivationError for observability.\n try {\n onDerivationError?.(error);\n } catch {\n // Prevent observability exceptions from poisoning the entire batch\n // and dropping the state updates.\n }\n // The raw state still advances into the store, so the history snapshot\n // MUST be recorded. Clearing the flag here would cause undo() to skip\n // this user mutation entirely, permanently desynchronising the history\n // stack from the live store state — a silent data-loss bug.\n }\n }\n } finally {\n batchState.pendingState = null;\n batchState.changedPathSet = null;\n batchState.changedPathList = null;\n batchState.valuesChanged = false;\n }\n\n // Note: pendingHistorySnapshot is reset by the caller after it records the snapshot.\n\n return {\n nextState: nextState ?? currentState,\n changedPaths,\n valuesChanged,\n };\n}\n","import type { BitHistoryManager } from \"../managers/features/history-manager\";\n\ntype BitHistoryMetadataSnapshot = {\n canUndo: boolean;\n canRedo: boolean;\n historyIndex: number;\n historySize: number;\n};\n\ninterface BitStoreHistoryOrchestratorArgs<T extends object> {\n debounceMs?: number;\n history: Pick<BitHistoryManager<T>, \"saveSnapshot\" | \"getMetadata\">;\n notifyHistoryChanged: () => void;\n}\n\nexport class BitStoreHistoryOrchestrator<T extends object> {\n private readonly debounceMs: number;\n private timer: ReturnType<typeof setTimeout> | undefined;\n private pendingValues: T | null = null;\n\n constructor(private readonly args: BitStoreHistoryOrchestratorArgs<T>) {\n this.debounceMs = Math.max(0, args.debounceMs ?? 300);\n }\n\n queueSnapshot(values: T): void {\n if (this.debounceMs <= 0) {\n this.recordSnapshot(values);\n return;\n }\n\n this.pendingValues = values;\n\n if (this.timer) {\n clearTimeout(this.timer);\n }\n\n this.timer = setTimeout(() => {\n this.timer = undefined;\n this.flushPendingSnapshot();\n }, this.debounceMs);\n }\n\n flushPendingSnapshot(): void {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n if (!this.pendingValues) {\n return;\n }\n\n const values = this.pendingValues;\n this.pendingValues = null;\n this.recordSnapshot(values);\n }\n\n dispose(): void {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n this.pendingValues = null;\n }\n\n private recordSnapshot(values: T): void {\n const before = this.readMetadata();\n this.args.history.saveSnapshot(values);\n const after = this.readMetadata();\n\n if (\n before.canUndo === after.canUndo &&\n before.canRedo === after.canRedo &&\n before.historyIndex === after.historyIndex &&\n before.historySize === after.historySize\n ) {\n return;\n }\n\n this.args.notifyHistoryChanged();\n }\n\n private readMetadata(): BitHistoryMetadataSnapshot {\n const metadata = this.args.history.getMetadata();\n return {\n canUndo: metadata.canUndo,\n canRedo: metadata.canRedo,\n historyIndex: metadata.historyIndex,\n historySize: metadata.historySize,\n };\n }\n}\n","import { mergePaths } from \"../../utils/path-utils\";\nimport type { BitErrors, BitState } from \"../contracts/types\";\nimport { hasAnyError } from \"../shared/error-map\";\n\nfunction normalizeErrors<T extends object>(errors: BitErrors<T>): BitErrors<T> {\n let hasUndefined = false;\n\n for (const message of Object.values(errors)) {\n if (message === undefined) {\n hasUndefined = true;\n break;\n }\n }\n\n if (!hasUndefined) {\n return errors;\n }\n\n const normalized: BitErrors<T> = {};\n\n Object.entries(errors).forEach(([path, message]) => {\n const typedMessage = message as string | undefined;\n\n if (typedMessage === undefined) {\n return;\n }\n\n normalized[path as keyof BitErrors<T>] = typedMessage;\n });\n\n return normalized;\n}\n\nexport interface BitStateUpdateResult<T extends object> {\n nextState: BitState<T>;\n changedPaths?: string[];\n valuesChanged: boolean;\n}\n\nexport function applyStateUpdate<T extends object>(args: {\n currentState: BitState<T>;\n partialState: Partial<BitState<T>>;\n changedPaths?: string[];\n applyValueDerivations?: (values: T, changedPaths?: readonly string[]) => T;\n applyComputedValues?: (values: T) => T;\n}): BitStateUpdateResult<T> {\n const {\n currentState,\n partialState,\n changedPaths,\n applyValueDerivations,\n applyComputedValues,\n } = args;\n const deriveValues =\n applyValueDerivations ??\n ((values: T) =>\n applyComputedValues ? applyComputedValues(values) : values);\n\n const nextState: BitState<T> = { ...currentState, ...partialState };\n const valuesChanged = !!partialState.values;\n\n if (partialState.values) {\n nextState.values = deriveValues(partialState.values, changedPaths);\n }\n\n if (partialState.errors) {\n nextState.errors = normalizeErrors(partialState.errors as BitErrors<T>);\n const derivedIsValid = !hasAnyError(\n nextState.errors as Record<string, unknown>,\n );\n nextState.isValid =\n \"isValid\" in partialState\n ? Boolean(partialState.isValid)\n : derivedIsValid;\n }\n\n const explicitChangedPaths =\n changedPaths && changedPaths.length > 0 ? changedPaths : undefined;\n const inferredChangedPaths = inferChangedPaths(partialState);\n const effectiveChangedPaths = mergePaths(\n explicitChangedPaths,\n inferredChangedPaths,\n );\n\n return {\n nextState,\n changedPaths: effectiveChangedPaths,\n valuesChanged,\n };\n}\n\nfunction inferChangedPaths<T extends object>(\n partialState: Partial<BitState<T>>,\n): string[] | undefined {\n const changedPaths = new Set<string>();\n\n // Itera os três dicionários de path em único passo para evitar\n // três Object.keys() + três forEach() separados.\n const pathMaps = [\n partialState.errors,\n partialState.touched,\n partialState.isValidating,\n ] as const;\n for (const map of pathMaps) {\n if (map) {\n for (const path in map) {\n changedPaths.add(path);\n }\n }\n }\n\n if (partialState.persist) {\n changedPaths.add(\"persist\");\n }\n\n if (\"isValid\" in partialState) {\n changedPaths.add(\"isValid\");\n }\n\n if (\"isDirty\" in partialState) {\n changedPaths.add(\"isDirty\");\n }\n\n if (\"isSubmitting\" in partialState) {\n changedPaths.add(\"isSubmitting\");\n }\n\n return changedPaths.size > 0 ? Array.from(changedPaths) : undefined;\n}\n","import type { BitState } from \"../contracts/types\";\nimport {\n BitStatePatchOperation,\n BitStoreOperation,\n patchStateOperation,\n} from \"./operation-engine\";\nimport { applyStateUpdate } from \"./state-update-engine\";\nimport {\n flushStoreBatchState,\n getEffectiveStoreState,\n trackBatchedStoreUpdate,\n type BitStoreBatchState,\n} from \"./store-batch-engine\";\n\nfunction assertNever(value: never): never {\n throw new Error(\n `BitStore: unsupported operation kind: ${String((value as { kind?: unknown }).kind)}`,\n );\n}\n\nfunction routeStoreOperation<T extends object>(\n currentState: Readonly<BitState<T>>,\n operation: BitStoreOperation<T>,\n): BitStatePatchOperation<T> | null {\n switch (operation.kind) {\n case \"state.patch\":\n return operation;\n\n case \"field.touchMany\": {\n if (operation.paths.length === 0) {\n return null;\n }\n\n const touched = { ...currentState.touched };\n for (const path of operation.paths) {\n touched[path as keyof typeof touched] = true;\n }\n\n return patchStateOperation({ touched }, operation.paths);\n }\n\n case \"form.persistMeta\":\n return patchStateOperation({\n persist: {\n ...currentState.persist,\n ...operation.patch,\n },\n });\n\n case \"history.apply\":\n return patchStateOperation(\n {\n values: operation.values,\n isDirty: operation.isDirty,\n },\n [\"*\"],\n );\n\n case \"validation.commit\":\n return patchStateOperation({\n errors: operation.errors,\n isValid: operation.isValid,\n });\n\n default:\n return assertNever(operation);\n }\n}\n\nfunction executeStatePatchOperation<T extends object>(args: {\n currentState: BitState<T>;\n operation: BitStatePatchOperation<T>;\n applyValueDerivations: (values: T, changedPaths?: readonly string[]) => T;\n onOperationError?: (error: unknown) => void;\n}) {\n const { currentState, operation, applyValueDerivations, onOperationError } =\n args;\n\n const hasValuesPatch = Object.prototype.hasOwnProperty.call(\n operation.partialState,\n \"values\",\n );\n const effectiveChangedPaths =\n operation.changedPaths ?? (hasValuesPatch ? [\"*\"] : undefined);\n\n let result;\n try {\n result = applyStateUpdate({\n currentState,\n partialState: operation.partialState,\n changedPaths: effectiveChangedPaths,\n applyValueDerivations,\n });\n } catch (error) {\n try {\n onOperationError?.(error);\n } catch {\n // Impede que erros de observabilidade abortem o commit do state update com valores em raw\n }\n try {\n result = applyStateUpdate({\n currentState,\n partialState: operation.partialState,\n changedPaths: effectiveChangedPaths,\n applyValueDerivations: (values) => values, // No derivation fallback\n });\n } catch {\n // If the raw fallback also fails (e.g. immutable proxy, serialisation\n // error), still try to commit the non-values portion of the patch\n // (errors, touched, isValidating, isDirty, isValid, etc.) so the\n // store does not silently diverge from the UI.\n try {\n const { values: _ignored, ...safePartial } = operation.partialState as {\n values?: unknown;\n [key: string]: unknown;\n };\n\n if (Object.keys(safePartial).length > 0) {\n result = applyStateUpdate({\n currentState,\n partialState: safePartial,\n changedPaths: effectiveChangedPaths,\n applyValueDerivations: (values) => values,\n });\n }\n } catch {\n // Completely unrecoverable — abort the mutation gracefully to\n // avoid crashing the component tree. All paths exhausted.\n const unrecoverableError = new Error(\n \"BitStore: all commit fallback strategies failed — operation lost\",\n );\n try {\n onOperationError?.(unrecoverableError);\n } catch {\n // Prevent error-handling errors from crashing the store\n }\n result = undefined;\n }\n }\n }\n return result;\n}\n\nfunction executeStoreOperation<T extends object>(args: {\n currentState: BitState<T>;\n operation: BitStoreOperation<T>;\n applyValueDerivations: (values: T, changedPaths?: readonly string[]) => T;\n onOperationError?: (error: unknown) => void;\n}) {\n const { currentState, operation, applyValueDerivations, onOperationError } =\n args;\n const patchOperation = routeStoreOperation(currentState, operation);\n\n if (!patchOperation) {\n return null;\n }\n\n return executeStatePatchOperation({\n currentState,\n operation: patchOperation,\n applyValueDerivations: (values, changedPaths) =>\n patchOperation.skipComputed\n ? values\n : applyValueDerivations(values, changedPaths),\n onOperationError,\n });\n}\n\nexport function dispatchStoreKernelOperation<T extends object>(args: {\n state: BitState<T>;\n batchState: BitStoreBatchState<T>;\n operation: BitStoreOperation<T>;\n applyValueDerivations: (values: T, changedPaths?: readonly string[]) => T;\n onOperationError?: (error: unknown) => void;\n onStateCommitted: (payload: {\n nextState: BitState<T>;\n changedPaths?: Iterable<string>;\n valuesChanged: boolean;\n }) => void;\n}): BitState<T> {\n const {\n state,\n batchState,\n operation,\n applyValueDerivations,\n onOperationError,\n onStateCommitted,\n } = args;\n\n const currentState = getEffectiveStoreState(state, batchState);\n\n if (batchState.depth > 0) {\n const updateResult = executeStoreOperation({\n currentState,\n operation,\n applyValueDerivations: (values) => values,\n onOperationError,\n });\n\n if (!updateResult) {\n return state;\n }\n\n trackBatchedStoreUpdate(batchState, updateResult);\n return state;\n }\n\n const updateResult = executeStoreOperation({\n currentState: state,\n operation,\n applyValueDerivations,\n onOperationError,\n });\n\n if (!updateResult) {\n return state;\n }\n\n onStateCommitted({\n nextState: updateResult.nextState,\n changedPaths: updateResult.changedPaths,\n valuesChanged: updateResult.valuesChanged,\n });\n\n return updateResult.nextState;\n}\n\nexport function flushStoreKernelBatch<T extends object>(args: {\n state: BitState<T>;\n batchState: BitStoreBatchState<T>;\n applyValueDerivations: (values: T, changedPaths?: readonly string[]) => T;\n onDerivationError?: (error: unknown) => void;\n onStateCommitted: (payload: {\n nextState: BitState<T>;\n changedPaths?: Iterable<string>;\n valuesChanged: boolean;\n }) => void;\n}): BitState<T> {\n const {\n state,\n batchState,\n applyValueDerivations,\n onDerivationError,\n onStateCommitted,\n } = args;\n\n const flushResult = flushStoreBatchState({\n currentState: state,\n batchState,\n applyValueDerivations,\n onDerivationError,\n });\n\n if (!flushResult) {\n return state;\n }\n\n onStateCommitted({\n nextState: flushResult.nextState,\n changedPaths: flushResult.changedPaths,\n valuesChanged: flushResult.valuesChanged,\n });\n\n return flushResult.nextState;\n}\n","import type { BitState } from \"../contracts/types\";\nimport type { BitStoreOperation } from \"../engines/operation-engine\";\nimport {\n beginStoreBatch,\n endStoreBatch,\n type BitStoreBatchState,\n} from \"../engines/store-batch-engine\";\nimport {\n dispatchStoreKernelOperation,\n flushStoreKernelBatch,\n} from \"../engines/store-commit-engine\";\n\nexport function runStoreStateBatch<T extends object, TResult>(args: {\n batchState: BitStoreBatchState<T>;\n callback: () => TResult;\n flushBatchedStateUpdates: () => void;\n}): TResult {\n const { batchState, callback, flushBatchedStateUpdates } = args;\n beginStoreBatch(batchState);\n\n try {\n return callback();\n } finally {\n if (endStoreBatch(batchState)) {\n flushBatchedStateUpdates();\n }\n }\n}\n\nexport function commitStoreStateUpdate<T extends object>(args: {\n payload: {\n nextState: BitState<T>;\n changedPaths?: Iterable<string>;\n valuesChanged: boolean;\n };\n setState: (state: BitState<T>) => void;\n notifySubscriptions: (\n state: BitState<T>,\n changedPaths?: Iterable<string>,\n ) => void;\n notifyEffects: (state: BitState<T>, valuesChanged: boolean) => void;\n}): void {\n const { payload, setState, notifySubscriptions, notifyEffects } = args;\n setState(payload.nextState);\n notifySubscriptions(payload.nextState, payload.changedPaths);\n notifyEffects(payload.nextState, payload.valuesChanged);\n}\n\nexport function dispatchStoreStateOperation<T extends object>(args: {\n state: BitState<T>;\n batchState: BitStoreBatchState<T>;\n operation: BitStoreOperation<T>;\n applyValueDerivations: (values: T, changedPaths?: readonly string[]) => T;\n onOperationError?: (error: unknown) => void;\n onStateCommitted: (payload: {\n nextState: BitState<T>;\n changedPaths?: Iterable<string>;\n valuesChanged: boolean;\n }) => void;\n}): BitState<T> {\n const {\n state,\n batchState,\n operation,\n applyValueDerivations,\n onOperationError,\n onStateCommitted,\n } = args;\n\n return dispatchStoreKernelOperation({\n state,\n batchState,\n operation,\n applyValueDerivations,\n onOperationError,\n onStateCommitted,\n });\n}\n\nexport function saveStoreHistorySnapshot<T extends object>(args: {\n batchState: BitStoreBatchState<T>;\n values: T;\n saveHistory: (values: T) => void;\n}): void {\n const { batchState, values, saveHistory } = args;\n\n if (batchState.depth > 0) {\n batchState.pendingHistorySnapshot = true;\n return;\n }\n\n saveHistory(values);\n}\n\nexport function flushStoreBatchedStateUpdates<T extends object>(args: {\n state: BitState<T>;\n batchState: BitStoreBatchState<T>;\n applyValueDerivations: (values: T, changedPaths?: readonly string[]) => T;\n onDerivationError?: (error: unknown) => void;\n onStateCommitted: (payload: {\n nextState: BitState<T>;\n changedPaths?: Iterable<string>;\n valuesChanged: boolean;\n }) => void;\n saveHistory: (values: T) => void;\n}): BitState<T> {\n const {\n state,\n batchState,\n applyValueDerivations,\n onDerivationError,\n onStateCommitted,\n saveHistory,\n } = args;\n\n const nextState = flushStoreKernelBatch({\n state,\n batchState,\n applyValueDerivations,\n onDerivationError,\n onStateCommitted,\n });\n\n if (batchState.pendingHistorySnapshot) {\n batchState.pendingHistorySnapshot = false;\n if (nextState !== state) {\n saveHistory(nextState.values);\n }\n }\n\n return nextState;\n}\n","import { getHistorySubscriptionPath } from \"../../history-status\";\nimport type { BitState } from \"../contracts/types\";\nimport type { BitStoreEffectEngine } from \"../engines/effect-engine\";\nimport type { BitStoreOperation } from \"../engines/operation-engine\";\nimport {\n createStoreBatchState,\n getEffectiveStoreState,\n type BitStoreBatchState,\n} from \"../engines/store-batch-engine\";\nimport type { BitSubscriptionEngine } from \"../engines/subscription-engine\";\nimport type { BitStoreCapabilities } from \"./capabilities\";\nimport type { BitStoreCapabilityRegistry } from \"./store-capability-registry\";\nimport { BitStoreHistoryOrchestrator } from \"./store-history-orchestrator\";\nimport {\n commitStoreStateUpdate,\n dispatchStoreStateOperation,\n flushStoreBatchedStateUpdates,\n runStoreStateBatch,\n saveStoreHistorySnapshot,\n} from \"./store-state-ops\";\n\nexport interface BitStoreRuntimeKernelArgs<T extends object> {\n state: BitState<T>;\n subscriptions: BitSubscriptionEngine<T>;\n effects: BitStoreEffectEngine<T>;\n capabilityRegistry: BitStoreCapabilityRegistry<T>;\n historyDebounceMs?: number;\n applyValueDerivations?: (values: T, changedPaths?: readonly string[]) => T;\n onUnhandledError?: (error: unknown, source: string) => void;\n}\n\nexport class BitStoreRuntimeKernel<T extends object> {\n private state: BitState<T>;\n private readonly batchState: BitStoreBatchState<T> =\n createStoreBatchState<T>();\n private readonly historyOrchestrator: BitStoreHistoryOrchestrator<T>;\n\n readonly subscriptions: BitSubscriptionEngine<T>;\n readonly effects: BitStoreEffectEngine<T>;\n readonly capabilityRegistry: BitStoreCapabilityRegistry<T>;\n readonly capabilities: BitStoreCapabilities<T>;\n\n constructor(private readonly args: BitStoreRuntimeKernelArgs<T>) {\n this.state = args.state;\n this.subscriptions = args.subscriptions;\n this.effects = args.effects;\n this.capabilityRegistry = args.capabilityRegistry;\n this.capabilities = args.capabilityRegistry.toCapabilities();\n this.historyOrchestrator = new BitStoreHistoryOrchestrator<T>({\n debounceMs: args.historyDebounceMs,\n history: this.capabilities.history,\n notifyHistoryChanged: () => {\n this.subscriptions.notify(this.getState(), [\n getHistorySubscriptionPath(),\n ]);\n },\n });\n }\n\n getCapability<K extends keyof BitStoreCapabilities<T>>(\n name: K,\n ): BitStoreCapabilities<T>[K] {\n return this.capabilityRegistry.resolve(name);\n }\n\n getState(): BitState<T> {\n return getEffectiveStoreState(this.state, this.batchState);\n }\n\n runBatch<TResult>(callback: () => TResult): TResult {\n return runStoreStateBatch({\n batchState: this.batchState,\n callback,\n flushBatchedStateUpdates: () => this.flushBatchedStateUpdates(),\n });\n }\n\n dispatch(operation: BitStoreOperation<T>): void {\n this.state = dispatchStoreStateOperation({\n state: this.state,\n batchState: this.batchState,\n operation,\n applyValueDerivations: (values, changedPaths) =>\n this.applyValueDerivations(values, changedPaths),\n onOperationError: (error) =>\n this.args.onUnhandledError?.(error, \"derivation\"),\n onStateCommitted: (payload) => this.onStateCommitted(payload),\n });\n }\n\n saveHistorySnapshot(): void {\n saveStoreHistorySnapshot({\n batchState: this.batchState,\n values: this.state.values,\n saveHistory: (values) => this.historyOrchestrator.queueSnapshot(values),\n });\n }\n\n flushPendingHistorySnapshot(): void {\n this.historyOrchestrator.flushPendingSnapshot();\n }\n\n cancelPendingHistorySnapshot(): void {\n this.batchState.pendingHistorySnapshot = false;\n }\n\n cleanup(): void {\n this.flushPendingHistorySnapshot();\n this.historyOrchestrator.dispose();\n this.subscriptions.destroy();\n this.capabilities.validation.cancelAll();\n this.effects.destroy();\n }\n\n private onStateCommitted(payload: {\n nextState: BitState<T>;\n changedPaths?: Iterable<string>;\n valuesChanged: boolean;\n }): void {\n commitStoreStateUpdate({\n payload,\n setState: (state) => {\n this.state = state;\n },\n notifySubscriptions: (state, changedPaths) =>\n this.subscriptions.notify(state, changedPaths),\n notifyEffects: (state, valuesChanged) =>\n this.effects.onStateUpdated(state, valuesChanged),\n });\n }\n\n private flushBatchedStateUpdates(): void {\n this.state = flushStoreBatchedStateUpdates({\n state: this.state,\n batchState: this.batchState,\n applyValueDerivations: (values, changedPaths) =>\n this.applyValueDerivations(values, changedPaths),\n onDerivationError: (error) =>\n this.args.onUnhandledError?.(error, \"derivation\"),\n onStateCommitted: (payload) => this.onStateCommitted(payload),\n saveHistory: (values) => this.historyOrchestrator.queueSnapshot(values),\n });\n }\n\n private applyValueDerivations(\n values: T,\n changedPaths?: readonly string[],\n ): T {\n return this.args.applyValueDerivations\n ? this.args.applyValueDerivations(values, changedPaths)\n : values;\n }\n}\n","import type { BitValidationTriggerOptions } from \"../contracts/port-types\";\nimport type { BitFrameworkConfig } from \"../contracts/public/store-api-types\";\nimport type { BitConfig, BitFieldChangeMeta } from \"../contracts/types\";\nimport { BitBaselineManager } from \"../managers/core/baseline-manager\";\nimport { BitComputedManager } from \"../managers/core/computed-manager\";\nimport { BitDirtyManager } from \"../managers/core/dirty-manager\";\nimport { BitMaskManager } from \"../managers/features/mask-manager\";\nimport { BitFieldRegistry } from \"../registry/field-registry\";\nimport { normalizeConfig } from \"../shared/config\";\nimport { applyValueDerivations } from \"../shared/value-derivation-pipeline\";\nimport { createStoreEffects } from \"./store-effects-composition\";\nimport { applyStorePersistedValues } from \"./store-persist-ops\";\nimport { unregisterStorePrefix } from \"./store-registration-ops\";\nimport { createStoreRuntime } from \"./store-runtime\";\nimport { BitStoreRuntimeKernel } from \"./store-runtime-kernel\";\n\nexport interface BitStoreComposition<T extends object> {\n config: BitFrameworkConfig<T>;\n storeId: string;\n runtime: BitStoreRuntimeKernel<T>;\n fieldRegistry: BitFieldRegistry<T>;\n computedManager: BitComputedManager<T>;\n dirtyManager: BitDirtyManager<T>;\n maskManager: BitMaskManager;\n baselineManager: BitBaselineManager<T>;\n}\n\nexport interface BitStoreRuntimeOverrides<T extends object> {\n fieldRegistry?: BitFieldRegistry<T>;\n computedManager?: BitComputedManager<T>;\n dirtyManager?: BitDirtyManager<T>;\n maskManager?: BitMaskManager;\n baselineManager?: BitBaselineManager<T>;\n}\n\nexport function composeBitStoreRuntime<T extends object>(args: {\n rawConfig: BitConfig<T>;\n overrides?: BitStoreRuntimeOverrides<T>;\n}): BitStoreComposition<T> {\n const { rawConfig, overrides } = args;\n const config = normalizeConfig(rawConfig);\n const baselineManager =\n overrides?.baselineManager ??\n new BitBaselineManager<T>(config.initialValues);\n\n const fieldRegistry =\n overrides?.fieldRegistry ??\n new BitFieldRegistry<T>(({ error }) => {\n config.onUnhandledError(error, \"validation\");\n });\n const computedManager =\n overrides?.computedManager ??\n new BitComputedManager<T>(\n (values) => fieldRegistry.getComputedEntries(values),\n (error) => config.onUnhandledError(error, \"computed\"),\n );\n const dirtyManager = overrides?.dirtyManager ?? new BitDirtyManager<T>();\n const maskManager = overrides?.maskManager ?? new BitMaskManager();\n\n const invalidateFieldIndexes = () => {\n fieldRegistry.invalidateIndexes();\n computedManager.invalidateReverseDeps();\n };\n\n let runtimeKernel: BitStoreRuntimeKernel<T> | undefined;\n\n const getRuntimeKernel = () => {\n if (!runtimeKernel) {\n throw new Error(\"BitStore runtime kernel is not initialized yet.\");\n }\n\n return runtimeKernel;\n };\n\n const runtime = createStoreRuntime<T>({\n rawConfig,\n config,\n fieldRegistry,\n computedManager,\n dirtyManager,\n baselineManager,\n runtimeContext: {\n stateAccess: {\n getState: () => getRuntimeKernel().getState(),\n dispatch: (operation) => getRuntimeKernel().dispatch(operation),\n saveHistorySnapshot: () => getRuntimeKernel().saveHistorySnapshot(),\n runStateBatch: (callback) => getRuntimeKernel().runBatch(callback),\n },\n fieldAccess: {\n getFieldConfig: (path) => fieldRegistry.getFieldConfig(path),\n getScopeFields: (scopeName) =>\n fieldRegistry.getScopeFields(\n scopeName,\n getRuntimeKernel().getState().values,\n ),\n getNormalizerEntries: () =>\n fieldRegistry.getNormalizerEntries(\n getRuntimeKernel().getState().values,\n ),\n getTransformEntries: () =>\n fieldRegistry.getTransformEntries(\n getRuntimeKernel().getState().values,\n ),\n },\n featureAccess: {\n getEffects: () => getRuntimeKernel().effects,\n getHistory: () => getRuntimeKernel().getCapability(\"history\"),\n getValidation: () => getRuntimeKernel().getCapability(\"validation\"),\n },\n actions: {\n setError: (path, message) => {\n getRuntimeKernel().getCapability(\"error\").setError(path, message);\n },\n setServerErrors: (serverErrors, options) => {\n getRuntimeKernel()\n .getCapability(\"error\")\n .setServerErrors(serverErrors, options);\n },\n validate: (options) => {\n return getRuntimeKernel()\n .getCapability(\"validation\")\n .validate(options);\n },\n setFieldWithMeta: (\n path,\n value,\n meta: BitFieldChangeMeta = { origin: \"setField\" },\n ) => {\n getRuntimeKernel().runBatch(() => {\n getRuntimeKernel()\n .getCapability(\"lifecycle\")\n .updateField(path, value, meta);\n });\n },\n unregisterPrefix: (prefix) => {\n unregisterStorePrefix({\n prefix,\n state: getRuntimeKernel().getState(),\n fieldRegistry,\n subscriptions: getRuntimeKernel().subscriptions,\n validationCleanupPrefix: (fieldPrefix) =>\n getRuntimeKernel()\n .getCapability(\"validation\")\n .cleanupPrefix(fieldPrefix),\n invalidateFieldIndexes,\n hasStaticConfigPath: (path) =>\n !!config.fields?.[path as keyof typeof config.fields],\n dispatch: (operation) => getRuntimeKernel().dispatch(operation),\n });\n },\n triggerValidation: (\n scopeFields?: string[],\n options?: BitValidationTriggerOptions,\n ) => {\n getRuntimeKernel()\n .getCapability(\"validation\")\n .trigger(scopeFields, options);\n },\n },\n },\n });\n\n const getDirtyValues = () => {\n const effectiveState = getRuntimeKernel().getState();\n return dirtyManager.buildDirtyValues(effectiveState.values);\n };\n\n const applyPersistedValues = (values: Partial<T>) => {\n getRuntimeKernel().flushPendingHistorySnapshot();\n\n applyStorePersistedValues({\n values,\n state: getRuntimeKernel().getState(),\n initialValues: baselineManager.getValues(),\n validation: getRuntimeKernel().getCapability(\"validation\"),\n fieldRegistry,\n dirtyManager,\n dispatch: (operation) => getRuntimeKernel().dispatch(operation),\n saveHistorySnapshot: () => getRuntimeKernel().saveHistorySnapshot(),\n });\n };\n\n const effects = createStoreEffects<T>({\n storeId: runtime.storeId,\n config,\n getState: () => getRuntimeKernel().getState(),\n getConfig: () => config,\n getValues: () => getRuntimeKernel().getState().values,\n getDirtyValues,\n applyPersistedValues,\n setPersistMetadata: (patch) =>\n getRuntimeKernel().dispatch({ kind: \"form.persistMeta\", patch }),\n });\n\n runtimeKernel = new BitStoreRuntimeKernel<T>({\n state: runtime.state,\n subscriptions: runtime.subscriptions,\n effects,\n capabilityRegistry: runtime.capabilityRegistry,\n historyDebounceMs: config.history.debounceMs,\n onUnhandledError: (error, source) => config.onUnhandledError(error, source),\n applyValueDerivations: (values, changedPaths) => {\n try {\n return applyValueDerivations({\n values,\n changedPaths,\n normalizerEntries: fieldRegistry.getNormalizerEntries(values),\n applyComputed: (nextValues, nextChangedPaths) =>\n computedManager.apply(nextValues, nextChangedPaths),\n onError: (error, _path) => {\n config.onUnhandledError(error, \"derivation\");\n },\n });\n } catch (error) {\n config.onUnhandledError(error, \"derivation\");\n return values;\n }\n },\n });\n\n runtimeKernel.saveHistorySnapshot();\n runtimeKernel.flushPendingHistorySnapshot();\n\n return {\n config,\n storeId: runtime.storeId,\n runtime: runtimeKernel,\n fieldRegistry,\n computedManager,\n dirtyManager,\n maskManager,\n baselineManager,\n };\n}\n","import type { BitHistoryMetadata } from \"../contracts/public/meta-types\";\nimport type { BitStoreEffectEngine } from \"../engines/effect-engine\";\nimport type { BitStoreOperation } from \"../engines/operation-engine\";\nimport {\n clearStorePersisted,\n forceStorePersistedSave,\n restoreStorePersisted,\n} from \"./store-persist-ops\";\n\nexport function restorePersistedFeature<T extends object>(args: {\n dispatch: (operation: BitStoreOperation<T>) => void;\n effects: BitStoreEffectEngine<T>;\n onUnhandledError?: (error: unknown, source: string) => void;\n}): Promise<boolean> {\n const { dispatch, effects, onUnhandledError } = args;\n return restoreStorePersisted({ dispatch, effects, onUnhandledError });\n}\n\nexport function forceSavePersistedFeature<T extends object>(args: {\n dispatch: (operation: BitStoreOperation<T>) => void;\n effects: BitStoreEffectEngine<T>;\n onUnhandledError?: (error: unknown, source: string) => void;\n}): Promise<void> {\n const { dispatch, effects, onUnhandledError } = args;\n return forceStorePersistedSave({ dispatch, effects, onUnhandledError });\n}\n\nexport function clearPersistedFeature<T extends object>(args: {\n dispatch: (operation: BitStoreOperation<T>) => void;\n effects: BitStoreEffectEngine<T>;\n onUnhandledError?: (error: unknown, source: string) => void;\n}): Promise<void> {\n const { dispatch, effects, onUnhandledError } = args;\n return clearStorePersisted({ dispatch, effects, onUnhandledError });\n}\n\ntype HistoryFeaturePort<T extends object> = {\n undo: () => T | null;\n redo: () => T | null;\n getMetadata: () => BitHistoryMetadata;\n};\n\nexport function runUndoFeature<T extends object>(args: {\n history: HistoryFeaturePort<T>;\n applyHistoryState: (values: T) => void;\n}): void {\n const { history, applyHistoryState } = args;\n const prevState = history.undo();\n if (prevState) {\n applyHistoryState(prevState);\n }\n}\n\nexport function runRedoFeature<T extends object>(args: {\n history: HistoryFeaturePort<T>;\n applyHistoryState: (values: T) => void;\n}): void {\n const { history, applyHistoryState } = args;\n const nextState = history.redo();\n if (nextState) {\n applyHistoryState(nextState);\n }\n}\n\nexport function readHistoryFeatureMetadata<T extends object>(args: {\n history: HistoryFeaturePort<T>;\n}): BitHistoryMetadata {\n return args.history.getMetadata();\n}\n","import type {\n BitScopedSelectorSubscriptionOptions,\n BitSelector,\n BitTrackedSelectorSubscriptionOptions,\n} from \"../contracts/public/subscription-types\";\nimport type { BitState } from \"../contracts/types\";\n\nexport function collectTrackedSelectorPaths<T extends object, TSlice>(\n state: Readonly<BitState<T>>,\n selector: BitSelector<T, TSlice>,\n): string[] {\n const trackedPaths = new Set<string>();\n\n const createTrackingProxy = <TValue>(\n value: TValue,\n basePath: string,\n visited: WeakSet<object> = new WeakSet(),\n ): TValue => {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n\n if (visited.has(value as object)) {\n return value;\n }\n\n visited.add(value as object);\n\n return new Proxy(value as object, {\n get: (target, key, receiver) => {\n if (typeof key === \"symbol\") {\n return Reflect.get(target, key, receiver);\n }\n\n const keyAsString = String(key);\n const childPath = basePath ? `${basePath}.${keyAsString}` : keyAsString;\n trackedPaths.add(childPath);\n\n const child = Reflect.get(target, key, receiver);\n return createTrackingProxy(child, childPath);\n },\n }) as TValue;\n };\n\n const proxyState = createTrackingProxy(state, \"\");\n selector(proxyState as Readonly<BitState<T>>);\n\n const normalizedPaths = new Set<string>();\n\n trackedPaths.forEach((path) => {\n const normalizedPath = normalizeTrackedPath(path);\n if (normalizedPath) {\n normalizedPaths.add(normalizedPath);\n }\n });\n\n return Array.from(normalizedPaths);\n}\n\nfunction normalizeTrackedPath(path: string): string | undefined {\n if (!path) {\n return undefined;\n }\n\n if (path === \"values\") {\n return \"*\";\n }\n\n if (path.startsWith(\"values.\")) {\n return path.slice(\"values.\".length);\n }\n\n if (path === \"errors\" || path === \"touched\" || path === \"isValidating\") {\n return \"*\";\n }\n\n if (path.startsWith(\"errors.\")) {\n return path.slice(\"errors.\".length);\n }\n\n if (path.startsWith(\"touched.\")) {\n return path.slice(\"touched.\".length);\n }\n\n if (path.startsWith(\"isValidating.\")) {\n return path.slice(\"isValidating.\".length);\n }\n\n if (path === \"persist\" || path.startsWith(\"persist.\")) {\n return \"persist\";\n }\n\n return path;\n}\n\nexport function areTrackedPathSetsEqual(\n previousPaths: readonly string[],\n nextPaths: readonly string[],\n): boolean {\n if (previousPaths.length !== nextPaths.length) {\n return false;\n }\n\n const next = new Set(nextPaths);\n for (const path of previousPaths) {\n if (!next.has(path)) {\n return false;\n }\n }\n\n return true;\n}\n\nexport function withTrackedSelectorPaths<TValue>(\n paths: string[],\n options?: BitTrackedSelectorSubscriptionOptions<TValue>,\n): BitScopedSelectorSubscriptionOptions<TValue> {\n if (paths.length === 0) {\n return {\n emitImmediately: options?.emitImmediately,\n equalityFn: options?.equalityFn,\n mode: \"scoped\",\n paths: [\"*\"],\n };\n }\n\n return {\n emitImmediately: options?.emitImmediately,\n equalityFn: options?.equalityFn,\n mode: \"scoped\",\n paths,\n };\n}\n\nexport function createTrackedSubscription<T extends object, TSlice>(args: {\n getState: () => Readonly<BitState<T>>;\n subscribeSelector: (\n selector: BitSelector<T, TSlice>,\n listener: (slice: TSlice) => void,\n options: BitScopedSelectorSubscriptionOptions<TSlice>,\n ) => () => void;\n selector: BitSelector<T, TSlice>;\n listener: (slice: TSlice) => void;\n options?: BitTrackedSelectorSubscriptionOptions<TSlice>;\n}): () => void {\n const { getState, subscribeSelector, selector, listener, options } = args;\n\n let activeUnsubscribe: (() => void) | null = null;\n let activePaths = collectTrackedSelectorPaths(getState(), selector);\n let isDisposed = false;\n let isResubscribeQueued = false;\n\n const subscribeWithPaths = (paths: string[]) => {\n const previousUnsubscribe = activeUnsubscribe;\n\n activeUnsubscribe = subscribeSelector(\n selector,\n (slice) => {\n listener(slice);\n\n const nextPaths = collectTrackedSelectorPaths(getState(), selector);\n if (areTrackedPathSetsEqual(activePaths, nextPaths)) {\n return;\n }\n\n activePaths = nextPaths;\n\n if (isResubscribeQueued || isDisposed) {\n return;\n }\n\n isResubscribeQueued = true;\n queueMicrotask(() => {\n isResubscribeQueued = false;\n if (isDisposed) {\n return;\n }\n\n activeUnsubscribe?.();\n subscribeWithPaths(activePaths);\n });\n },\n withTrackedSelectorPaths(paths, options),\n );\n\n // Cleanup previous subscription if it exists (CRITICAL: prevents orphaned listeners)\n previousUnsubscribe?.();\n };\n\n subscribeWithPaths(activePaths);\n\n return () => {\n isDisposed = true;\n activeUnsubscribe?.();\n activeUnsubscribe = null;\n };\n}\n","import {\n getHistorySubscriptionPath,\n isHistoryMetaEqual,\n} from \"../../history-status\";\nimport { getDeepValue, valueEqual } from \"../../utils\";\nimport { areFieldStatesEqual } from \"../../utils/field-state-snapshot\";\nimport type {\n BitFormMeta,\n BitHistoryMetadata,\n} from \"../contracts/public/meta-types\";\nimport type {\n BitScopedSelectorSubscriptionOptions,\n BitSelector,\n BitSelectorSubscriptionOptions,\n} from \"../contracts/public/subscription-types\";\nimport type {\n BitFieldState,\n BitPath,\n BitPathValue,\n BitPersistMetadata,\n BitState,\n ScopeStatus,\n} from \"../contracts/types\";\nimport type { BitSubscriptionEngine } from \"../engines/subscription-engine\";\nimport {\n getScopeRegistrySubscriptionPath,\n getScopeSubscriptionPaths,\n isScopeStatusEqual,\n} from \"../shared/scope-status\";\nimport { createTrackedSubscription } from \"./tracked-selector\";\n\nexport function subscribeStoreSelector<T extends object, TSlice>(args: {\n getState: () => Readonly<BitState<T>>;\n subscriptions: Pick<BitSubscriptionEngine<T>, \"subscribeSelector\">;\n selector: BitSelector<T, TSlice>;\n listener: (slice: TSlice) => void;\n options: BitSelectorSubscriptionOptions<TSlice>;\n trackedSubscriptionsEnabled: boolean;\n onUnhandledError?: (error: unknown, source: string) => void;\n}): () => void {\n const {\n getState,\n subscriptions,\n selector,\n listener,\n options,\n trackedSubscriptionsEnabled,\n onUnhandledError,\n } = args;\n const equalityFn = options?.equalityFn ?? valueEqual;\n\n if (options?.mode === \"tracked\") {\n if (!trackedSubscriptionsEnabled) {\n // Do NOT throw — a synchronous throw here would propagate through the\n // framework's rendering cycle and crash the entire component tree.\n // Route via onUnhandledError and return a no-op so the call site stays\n // functional (the subscription simply won't fire).\n onUnhandledError?.(\n new Error(\n 'BitForm: subscribeSelector com mode=\"tracked\" está desabilitado por padrão. Ative config.trackedSubscriptions=true para habilitar o modo avançado.',\n ),\n \"subscription\",\n );\n return () => {};\n }\n\n return createTrackedSubscription({\n getState,\n subscribeSelector: (trackedSelector, trackedListener, trackedOptions) =>\n subscriptions.subscribeSelector(\n trackedSelector,\n trackedListener,\n trackedOptions,\n equalityFn,\n ),\n selector,\n listener,\n options,\n });\n }\n\n return subscriptions.subscribeSelector(\n selector,\n listener,\n options,\n equalityFn,\n );\n}\n\nexport function subscribeStorePath<\n T extends object,\n P extends BitPath<T>,\n>(args: {\n path: P;\n listener: (value: BitPathValue<T, P>) => void;\n options?: BitScopedSelectorSubscriptionOptions<BitPathValue<T, P>>;\n subscribeSelector: (\n selector: BitSelector<T, BitPathValue<T, P>>,\n listener: (slice: BitPathValue<T, P>) => void,\n options: BitSelectorSubscriptionOptions<BitPathValue<T, P>>,\n ) => () => void;\n}): () => void {\n const { path, listener, options, subscribeSelector } = args;\n const mergedPaths = [...(options?.paths ?? []), path as string];\n\n return subscribeSelector(\n (state) => getDeepValue(state.values, path as string) as BitPathValue<T, P>,\n listener,\n {\n ...options,\n paths: mergedPaths,\n },\n );\n}\n\nexport function subscribeStoreFieldState<\n T extends object,\n P extends BitPath<T>,\n>(args: {\n path: P;\n listener: (state: Readonly<BitFieldState<T, BitPathValue<T, P>>>) => void;\n getFieldState: (path: P) => Readonly<BitFieldState<T, BitPathValue<T, P>>>;\n subscribeSelector: (\n selector: BitSelector<T, Readonly<BitFieldState<T, BitPathValue<T, P>>>>,\n listener: (state: Readonly<BitFieldState<T, BitPathValue<T, P>>>) => void,\n options: BitSelectorSubscriptionOptions<\n Readonly<BitFieldState<T, BitPathValue<T, P>>>\n >,\n ) => () => void;\n}): () => void {\n const { path, listener, getFieldState, subscribeSelector } = args;\n\n return subscribeSelector(() => getFieldState(path), listener, {\n paths: [path as string],\n equalityFn: areFieldStatesEqual,\n });\n}\n\nexport function subscribeStoreFormMeta<T extends object>(args: {\n listener: (meta: BitFormMeta) => void;\n subscribeSelector: (\n selector: BitSelector<T, BitFormMeta>,\n listener: (meta: BitFormMeta) => void,\n options: BitSelectorSubscriptionOptions<BitFormMeta>,\n ) => () => void;\n}): () => void {\n const { listener, subscribeSelector } = args;\n\n return subscribeSelector(\n (state) => ({\n isValid: state.isValid,\n isDirty: state.isDirty,\n isSubmitting: state.isSubmitting,\n }),\n listener,\n {\n paths: [\"isValid\", \"isDirty\", \"isSubmitting\"],\n equalityFn: (prev, next) =>\n prev.isValid === next.isValid &&\n prev.isDirty === next.isDirty &&\n prev.isSubmitting === next.isSubmitting,\n },\n );\n}\n\nexport function subscribeStorePersistMeta<T extends object>(args: {\n listener: (meta: BitPersistMetadata) => void;\n subscribeSelector: (\n selector: BitSelector<T, BitPersistMetadata>,\n listener: (meta: BitPersistMetadata) => void,\n options: BitSelectorSubscriptionOptions<BitPersistMetadata>,\n ) => () => void;\n}): () => void {\n const { listener, subscribeSelector } = args;\n\n return subscribeSelector((state) => state.persist, listener, {\n paths: [\"persist\"],\n equalityFn: (prev, next) =>\n prev.isSaving === next.isSaving &&\n prev.isRestoring === next.isRestoring &&\n prev.error === next.error,\n });\n}\n\nexport function subscribeStoreHistoryMeta<T extends object>(args: {\n readHistoryMeta: () => BitHistoryMetadata;\n subscribeSelector: (\n selector: BitSelector<T, BitHistoryMetadata>,\n listener: (meta: BitHistoryMetadata) => void,\n options: BitSelectorSubscriptionOptions<BitHistoryMetadata>,\n ) => () => void;\n listener: (meta: BitHistoryMetadata) => void;\n}): () => void {\n const { readHistoryMeta, subscribeSelector, listener } = args;\n\n return subscribeSelector(() => readHistoryMeta(), listener, {\n paths: [getHistorySubscriptionPath()],\n equalityFn: (prev, next) => isHistoryMetaEqual(prev, next),\n });\n}\n\nexport function subscribeStoreScopeStatus<T extends object>(args: {\n scopeName: string;\n getScopeFields: (scopeName: string) => string[];\n readScopeStatus: (scopeName: string) => ScopeStatus;\n subscribeSelector: <TSlice>(\n selector: BitSelector<T, TSlice>,\n listener: (slice: TSlice) => void,\n options: BitSelectorSubscriptionOptions<TSlice>,\n ) => () => void;\n listener: (status: ScopeStatus) => void;\n}): () => void {\n const {\n scopeName,\n getScopeFields,\n readScopeStatus,\n subscribeSelector,\n listener,\n } = args;\n const registryPath = getScopeRegistrySubscriptionPath(scopeName);\n\n let lastStatus = readScopeStatus(scopeName);\n let unsubscribeScoped = () => {};\n\n const subscribeScoped = () => {\n unsubscribeScoped();\n const scopePaths = getScopeSubscriptionPaths(getScopeFields(scopeName));\n\n unsubscribeScoped = subscribeSelector(\n () => readScopeStatus(scopeName),\n (status) => {\n if (isScopeStatusEqual(lastStatus, status)) {\n return;\n }\n\n lastStatus = status;\n listener(status);\n },\n {\n paths: [...scopePaths, registryPath],\n },\n );\n };\n\n subscribeScoped();\n\n let resubscribeQueued = false;\n // Tracks whether the caller has unsubscribed. The queueMicrotask callback\n // captures this flag so it can bail out if cleanup happens before the\n // microtask fires — preventing orphan subscriptions and setState calls on\n // unmounted components.\n let destroyed = false;\n\n const unsubscribeRegistry = subscribeSelector(\n () => getScopeFields(scopeName).length,\n () => {\n // Coalesce rapid registry changes (e.g. two fields with same scope\n // registered in a single batch) via queueMicrotask to prevent the\n // second re-subscription from orphaning the one just created by the first.\n if (resubscribeQueued) return;\n resubscribeQueued = true;\n\n queueMicrotask(() => {\n resubscribeQueued = false;\n // If the caller unsubscribed while this microtask was queued, do\n // nothing: creating a new scoped subscription here would leak it\n // (no one holds a reference to unsubscribe it), and calling listener\n // would update state on an already-unmounted component.\n if (destroyed) {\n unsubscribeScoped();\n return;\n }\n subscribeScoped();\n const nextStatus = readScopeStatus(scopeName);\n if (isScopeStatusEqual(lastStatus, nextStatus)) {\n return;\n }\n\n lastStatus = nextStatus;\n listener(nextStatus);\n });\n },\n {\n paths: [registryPath],\n },\n );\n\n return () => {\n destroyed = true;\n unsubscribeScoped();\n unsubscribeRegistry();\n };\n}\n","import { deepClone } from \"../../utils\";\nimport type { BitValidationTriggerOptions } from \"../contracts/port-types\";\nimport type {\n BitFormMeta,\n BitHistoryMetadata,\n BitServerErrorOptions,\n BitValidationOptions,\n} from \"../contracts/public/meta-types\";\nimport type { BitFrameworkConfig } from \"../contracts/public/store-api-types\";\nimport type {\n BitScopedSelectorSubscriptionOptions,\n BitSelector,\n BitSelectorSubscriptionOptions,\n} from \"../contracts/public/subscription-types\";\nimport type {\n BitArrayItem,\n BitArrayPath,\n BitErrors,\n BitFieldDefinition,\n BitFieldState,\n BitPath,\n BitPathValue,\n BitPersistMetadata,\n BitSubmitResult,\n DeepPartial,\n ScopeStatus,\n} from \"../contracts/types\";\nimport {\n touchFieldsOperation,\n type BitStoreOperation,\n} from \"../engines/operation-engine\";\nimport type { BitDirtyManager } from \"../managers/core/dirty-manager\";\nimport type { BitFieldRegistry } from \"../registry/field-registry\";\nimport type { BitStoreStateReader } from \"../shared/store-state-reader\";\nimport {\n clearPersistedFeature,\n forceSavePersistedFeature,\n readHistoryFeatureMetadata,\n restorePersistedFeature,\n runRedoFeature,\n runUndoFeature,\n} from \"./store-feature-ops\";\nimport {\n subscribeStoreFieldState,\n subscribeStoreFormMeta,\n subscribeStoreHistoryMeta,\n subscribeStorePath,\n subscribeStorePersistMeta,\n subscribeStoreScopeStatus,\n subscribeStoreSelector,\n} from \"./store-observe-ops\";\nimport {\n registerStoreField,\n unregisterStoreField,\n unregisterStorePrefix,\n} from \"./store-registration-ops\";\nimport type { BitStoreRuntimeKernel } from \"./store-runtime-kernel\";\n\nexport interface BitStoreReadDomain<T extends object> {\n getState(): ReturnType<BitStoreStateReader<T>[\"getState\"]>;\n getFieldState<P extends BitPath<T>>(\n path: P,\n ): BitFieldState<T, BitPathValue<T, P>>;\n getIsValid(): boolean;\n getIsSubmitting(): boolean;\n getIsDirty(): boolean;\n isHidden<P extends BitPath<T>>(path: P): boolean;\n isRequired<P extends BitPath<T>>(path: P): boolean;\n isFieldDirty(path: string): boolean;\n isFieldValidating(path: string): boolean;\n getDirtyValues(): Partial<T>;\n getPersistMetadata(): BitPersistMetadata;\n getHistoryMetadata(): BitHistoryMetadata;\n getScopeStatus(scopeName: string): ScopeStatus;\n getScopeErrors(scopeName: string): Record<string, string>;\n getCanUndo(): boolean;\n getCanRedo(): boolean;\n getScopeFields(scopeName: string): string[];\n}\n\nexport interface BitStoreObserveDomain<T extends object> {\n subscribe(listener: () => void): () => void;\n subscribePersistMeta(\n listener: (meta: BitPersistMetadata) => void,\n ): () => void;\n subscribeHistoryMeta(\n listener: (meta: BitHistoryMetadata) => void,\n ): () => void;\n subscribeScopeStatus(\n scopeName: string,\n listener: (status: ScopeStatus) => void,\n ): () => void;\n subscribeSelector<TSlice>(\n selector: BitSelector<T, TSlice>,\n listener: (slice: TSlice) => void,\n options: BitSelectorSubscriptionOptions<TSlice>,\n ): () => void;\n subscribePath<P extends BitPath<T>>(\n path: P,\n listener: (value: BitPathValue<T, P>) => void,\n options?: BitScopedSelectorSubscriptionOptions<BitPathValue<T, P>>,\n ): () => void;\n subscribeFieldState<P extends BitPath<T>>(\n path: P,\n listener: (state: Readonly<BitFieldState<T, BitPathValue<T, P>>>) => void,\n ): () => void;\n subscribeFormMeta(listener: (meta: BitFormMeta) => void): () => void;\n}\n\nexport interface BitStoreWriteDomain<T extends object> {\n registerField(path: string, config: BitFieldDefinition<T>): void;\n unregisterField(path: string): void;\n unregisterPrefix(prefix: string): void;\n setField<P extends BitPath<T>>(path: P, value: BitPathValue<T, P>): void;\n blurField<P extends BitPath<T>>(path: P): void;\n markFieldsTouched(paths: string[]): void;\n setValues(\n values: T | DeepPartial<T>,\n options?: { partial?: boolean; rebase?: boolean },\n ): void;\n setError(path: string, message: string | undefined): void;\n setErrors(errors: BitErrors<T>): void;\n setServerErrors(\n serverErrors: Record<string, string[] | string>,\n options?: BitServerErrorOptions,\n ): void;\n reset(): void;\n transaction<TResult>(callback: () => TResult): TResult;\n submit(\n onSuccess: (\n values: T,\n dirtyValues?: Partial<T>,\n ) => unknown | Promise<unknown>,\n ): Promise<BitSubmitResult>;\n pushItem<P extends BitArrayPath<T>>(\n path: P,\n value: BitArrayItem<BitPathValue<T, P>>,\n ): void;\n prependItem<P extends BitArrayPath<T>>(\n path: P,\n value: BitArrayItem<BitPathValue<T, P>>,\n ): void;\n insertItem<P extends BitArrayPath<T>>(\n path: P,\n index: number,\n value: BitArrayItem<BitPathValue<T, P>>,\n ): void;\n removeItem<P extends BitArrayPath<T>>(path: P, index: number): void;\n swapItems<P extends BitArrayPath<T>>(\n path: P,\n indexA: number,\n indexB: number,\n ): void;\n moveItem<P extends BitArrayPath<T>>(path: P, from: number, to: number): void;\n replaceItems<P extends BitArrayPath<T>>(\n path: P,\n items: BitArrayItem<BitPathValue<T, P>>[],\n ): void;\n clearItems<P extends BitArrayPath<T>>(path: P): void;\n}\n\nexport interface BitStoreFeatureDomain<_T extends object> {\n undo(): void;\n redo(): void;\n validate(options?: BitValidationOptions): Promise<boolean>;\n hasValidationsInProgress(scopeFields?: string[]): boolean;\n triggerValidation(\n scopeFields?: string[],\n options?: BitValidationTriggerOptions,\n ): void;\n restorePersisted(): Promise<boolean>;\n forceSave(): Promise<void>;\n clearPersisted(): Promise<void>;\n getArrayItemIds(path: string, length?: number): string[];\n cleanup(): void;\n}\n\nexport interface BitStoreDomains<T extends object> {\n read: BitStoreReadDomain<T>;\n observe: BitStoreObserveDomain<T>;\n write: BitStoreWriteDomain<T>;\n feature: BitStoreFeatureDomain<T>;\n}\n\nexport function createBitStoreDomains<T extends object>(args: {\n runtime: BitStoreRuntimeKernel<T>;\n config: BitFrameworkConfig<T>;\n fieldRegistry: BitFieldRegistry<T>;\n dirtyManager: BitDirtyManager<T>;\n stateReader: BitStoreStateReader<T>;\n}): BitStoreDomains<T> {\n const { runtime, config, fieldRegistry, dirtyManager, stateReader } = args;\n\n const readDomain: BitStoreReadDomain<T> = {\n getState: () => deepClone(stateReader.getState()),\n getFieldState: (path) => deepClone(stateReader.getFieldState(path)),\n getIsValid: () => stateReader.getFlag(\"isValid\"),\n getIsSubmitting: () => stateReader.getFlag(\"isSubmitting\"),\n getIsDirty: () => stateReader.getFlag(\"isDirty\"),\n isHidden: (path) => runtime.capabilities.query.isHidden(path),\n isRequired: (path) => runtime.capabilities.query.isRequired(path),\n isFieldDirty: (path) => runtime.capabilities.query.isFieldDirty(path),\n isFieldValidating: (path) =>\n runtime.capabilities.query.isFieldValidating(path),\n getDirtyValues: () =>\n dirtyManager.buildDirtyValues(stateReader.getState().values),\n getPersistMetadata: () => stateReader.getPersistMetadata(),\n getHistoryMetadata: () =>\n readHistoryFeatureMetadata({ history: runtime.capabilities.history }),\n getScopeStatus: (scopeName) =>\n runtime.capabilities.scope.getScopeStatus(scopeName),\n getScopeErrors: (scopeName) =>\n runtime.capabilities.scope.getScopeErrors(scopeName),\n getCanUndo: () => runtime.capabilities.history.canUndo,\n getCanRedo: () => runtime.capabilities.history.canRedo,\n getScopeFields: (scopeName) =>\n fieldRegistry.getScopeFields(scopeName, stateReader.getState().values),\n };\n\n const observeDomain: BitStoreObserveDomain<T> = {\n subscribe: (listener) => runtime.subscriptions.subscribe(listener),\n subscribePersistMeta: (listener) =>\n subscribeStorePersistMeta({\n listener,\n subscribeSelector: (selector, persistListener, options) =>\n observeDomain.subscribeSelector(selector, persistListener, options),\n }),\n subscribeHistoryMeta: (listener) =>\n subscribeStoreHistoryMeta({\n readHistoryMeta: () => readDomain.getHistoryMetadata(),\n subscribeSelector: (selector, historyListener, options) =>\n observeDomain.subscribeSelector(selector, historyListener, options),\n listener,\n }),\n subscribeScopeStatus: (scopeName, listener) =>\n subscribeStoreScopeStatus({\n scopeName,\n getScopeFields: (name) => readDomain.getScopeFields(name),\n readScopeStatus: (name) => readDomain.getScopeStatus(name),\n subscribeSelector: (selector, scopeListener, options) =>\n observeDomain.subscribeSelector(selector, scopeListener, options),\n listener,\n }),\n subscribeSelector: (selector, listener, options) =>\n subscribeStoreSelector({\n getState: () => readDomain.getState(),\n subscriptions: runtime.subscriptions,\n selector,\n listener,\n options,\n trackedSubscriptionsEnabled: !!config.trackedSubscriptions,\n onUnhandledError: (error, source) =>\n config.onUnhandledError(error, source),\n }),\n subscribePath: (path, listener, options) =>\n subscribeStorePath({\n path,\n listener,\n options,\n subscribeSelector: (selector, pathListener, selectorOptions) =>\n observeDomain.subscribeSelector(\n selector,\n pathListener,\n selectorOptions,\n ),\n }),\n subscribeFieldState: (path, listener) =>\n subscribeStoreFieldState({\n path,\n listener,\n getFieldState: (fieldPath) => readDomain.getFieldState(fieldPath),\n subscribeSelector: (selector, fieldListener, options) =>\n observeDomain.subscribeSelector(selector, fieldListener, options),\n }),\n subscribeFormMeta: (listener) =>\n subscribeStoreFormMeta({\n listener,\n subscribeSelector: (selector, metaListener, options) =>\n observeDomain.subscribeSelector(selector, metaListener, options),\n }),\n };\n\n const writeDomain: BitStoreWriteDomain<T> = {\n registerField: (path, fieldConfig) => {\n registerStoreField({\n path,\n config: fieldConfig,\n state: runtime.getState(),\n fieldRegistry,\n subscriptions: runtime.subscriptions,\n validationCleanupField: (fieldPath) =>\n runtime.capabilities.validation.cleanupField(fieldPath),\n stateReader,\n invalidateFieldIndexes: () => {\n fieldRegistry.invalidateIndexes();\n },\n dispatch: (operation) => runtime.dispatch(operation),\n getState: () => runtime.getState(),\n onUnhandledError: (error, source) =>\n config.onUnhandledError(error, source),\n });\n },\n unregisterField: (path) => {\n unregisterStoreField({\n path,\n state: runtime.getState(),\n hasStaticConfig: !!config.fields?.[path as string],\n fieldRegistry,\n subscriptions: runtime.subscriptions,\n validationCleanupField: (fieldPath) =>\n runtime.capabilities.validation.cleanupField(fieldPath),\n invalidateFieldIndexes: () => {\n fieldRegistry.invalidateIndexes();\n },\n dispatch: (operation) => runtime.dispatch(operation),\n });\n },\n unregisterPrefix: (prefix) => {\n unregisterStorePrefix({\n prefix,\n state: runtime.getState(),\n fieldRegistry,\n subscriptions: runtime.subscriptions,\n validationCleanupPrefix: (fieldPrefix) =>\n runtime.capabilities.validation.cleanupPrefix(fieldPrefix),\n invalidateFieldIndexes: () => {\n fieldRegistry.invalidateIndexes();\n },\n hasStaticConfigPath: (path) =>\n !!config.fields?.[path as keyof typeof config.fields],\n dispatch: (operation) => runtime.dispatch(operation),\n });\n },\n setField: (path, value) => {\n runtime.runBatch(() => {\n runtime.capabilities.lifecycle.updateField(path as string, value, {\n origin: \"setField\",\n });\n });\n },\n blurField: (path) => {\n if (!runtime.capabilities.query.isTouched(path as string)) {\n runtime.runBatch(() => {\n runtime.dispatch(touchFieldsOperation([path as string]));\n });\n }\n\n runtime.flushPendingHistorySnapshot();\n runtime.capabilities.validation.trigger([path]);\n },\n markFieldsTouched: (paths) => {\n if (paths.length === 0) return;\n runtime.dispatch(touchFieldsOperation(paths));\n },\n setValues: (values, options) => {\n if (options?.rebase) {\n runtime.flushPendingHistorySnapshot();\n }\n\n runtime.capabilities.lifecycle.setValues(values, options);\n },\n setError: (path, message) => {\n runtime.capabilities.error.setError(path, message);\n },\n setErrors: (errors) => {\n runtime.capabilities.error.setErrors(errors);\n },\n setServerErrors: (serverErrors, options) => {\n runtime.capabilities.error.setServerErrors(serverErrors, options);\n },\n reset: () => {\n runtime.flushPendingHistorySnapshot();\n runtime.runBatch(() => {\n runtime.capabilities.lifecycle.reset();\n runtime.cancelPendingHistorySnapshot();\n });\n },\n transaction: (callback) => runtime.runBatch(callback),\n submit: (onSuccess) => {\n runtime.flushPendingHistorySnapshot();\n return runtime.capabilities.lifecycle.submit(onSuccess);\n },\n pushItem: (path, value) =>\n runtime.capabilities.arrays.pushItem(path, value),\n prependItem: (path, value) =>\n runtime.capabilities.arrays.prependItem(path, value),\n insertItem: (path, index, value) =>\n runtime.capabilities.arrays.insertItem(path, index, value),\n removeItem: (path, index) =>\n runtime.capabilities.arrays.removeItem(path, index),\n swapItems: (path, indexA, indexB) =>\n runtime.capabilities.arrays.swapItems(path, indexA, indexB),\n moveItem: (path, from, to) =>\n runtime.capabilities.arrays.moveItem(path, from, to),\n replaceItems: (path, items) =>\n runtime.capabilities.arrays.replaceItems(path, items),\n clearItems: (path) => runtime.capabilities.arrays.clearItems(path),\n };\n\n const featureDispatch = (operation: BitStoreOperation<T>) =>\n runtime.dispatch(operation);\n\n const featureDomain: BitStoreFeatureDomain<T> = {\n undo: () => {\n runtime.flushPendingHistorySnapshot();\n runUndoFeature({\n history: runtime.capabilities.history,\n applyHistoryState: (values) =>\n runtime.capabilities.lifecycle.applyHistoryState(values),\n });\n },\n redo: () => {\n runtime.flushPendingHistorySnapshot();\n runRedoFeature({\n history: runtime.capabilities.history,\n applyHistoryState: (values) =>\n runtime.capabilities.lifecycle.applyHistoryState(values),\n });\n },\n validate: (options) => runtime.capabilities.validation.validate(options),\n hasValidationsInProgress: (scopeFields) =>\n runtime.capabilities.validation.hasValidationsInProgress(scopeFields),\n triggerValidation: (scopeFields, options) =>\n runtime.capabilities.validation.trigger(scopeFields, options),\n restorePersisted: () =>\n restorePersistedFeature({\n dispatch: featureDispatch,\n effects: runtime.effects,\n onUnhandledError: (error, source) =>\n config.onUnhandledError(error, source),\n }),\n forceSave: () =>\n forceSavePersistedFeature({\n dispatch: featureDispatch,\n effects: runtime.effects,\n onUnhandledError: (error, source) =>\n config.onUnhandledError(error, source),\n }),\n clearPersisted: () =>\n clearPersistedFeature({\n dispatch: featureDispatch,\n effects: runtime.effects,\n onUnhandledError: (error, source) =>\n config.onUnhandledError(error, source),\n }),\n getArrayItemIds: (path, length) =>\n runtime.capabilities.arrays.getItemIds(path, length),\n cleanup: () => runtime.cleanup(),\n };\n\n return {\n read: readDomain,\n observe: observeDomain,\n write: writeDomain,\n feature: featureDomain,\n };\n}\n","import { deepClone } from \"../../utils\";\nimport type { BitFieldDefinition } from \"../contracts/types\";\n\nconst freezeConfig = <T extends object>(config: T): T =>\n Object.freeze(deepClone(config));\n\nimport type { BitMask } from \"../../mask/types\";\nimport type {\n BitStoreFeatureApi,\n BitStoreIdentityApi,\n BitStoreNamespacesApi,\n BitStoreObserveSliceApi,\n BitStoreReadSliceApi,\n BitStoreWriteSliceApi,\n} from \"../contracts/public/store-api-types\";\nimport type {\n BitStoreFeatureDomain,\n BitStoreObserveDomain,\n BitStoreReadDomain,\n BitStoreWriteDomain,\n} from \"./store-domains\";\n\nexport interface BitStoreSlicesFactoryDeps<\n T extends object = Record<string, unknown>,\n> {\n identity: BitStoreIdentityApi<T>;\n read: BitStoreReadDomain<T>;\n observe: BitStoreObserveDomain<T>;\n write: BitStoreWriteDomain<T>;\n feature: BitStoreFeatureDomain<T>;\n getFieldConfig(path: string): BitFieldDefinition<T> | undefined;\n resolveMask(path: string): BitMask | undefined;\n createArrayItemId(path: string, index?: number): string;\n}\n\nexport function buildStoreSlicesApi<T extends object>(\n deps: BitStoreSlicesFactoryDeps<T>,\n): BitStoreNamespacesApi<T> {\n const readState = () => deps.read.getState();\n\n const read: BitStoreReadSliceApi<T> = {\n get storeId() {\n return deps.identity.storeId;\n },\n get config() {\n return freezeConfig(deps.identity.config);\n },\n get isValid() {\n return deps.read.getIsValid();\n },\n get isSubmitting() {\n return deps.read.getIsSubmitting();\n },\n get isDirty() {\n return deps.read.getIsDirty();\n },\n getState: readState,\n getFieldConfig: (path) => {\n const config = deps.getFieldConfig(path);\n return config ? freezeConfig(config) : undefined;\n },\n getFieldState: (path) => deps.read.getFieldState(path),\n isHidden: (path) => deps.read.isHidden(path),\n isRequired: (path) => deps.read.isRequired(path),\n isFieldDirty: (path) => deps.read.isFieldDirty(path),\n isFieldValidating: (path) => deps.read.isFieldValidating(path),\n getDirtyValues: () => deps.read.getDirtyValues(),\n getPersistMetadata: () => deps.read.getPersistMetadata(),\n getHistoryMetadata: () => deps.read.getHistoryMetadata(),\n getScopeStatus: (scopeName) => deps.read.getScopeStatus(scopeName),\n getScopeErrors: (scopeName) => deps.read.getScopeErrors(scopeName),\n getScopeFields: (scopeName) => deps.read.getScopeFields(scopeName),\n };\n\n const observe: BitStoreObserveSliceApi<T> = {\n getState: readState,\n subscribe: (listener) => deps.observe.subscribe(listener),\n subscribePersistMeta: (listener) =>\n deps.observe.subscribePersistMeta(listener),\n subscribeHistoryMeta: (listener) =>\n deps.observe.subscribeHistoryMeta(listener),\n subscribeScopeStatus: (scopeName, listener) =>\n deps.observe.subscribeScopeStatus(scopeName, listener),\n subscribeFormMeta: (listener) => deps.observe.subscribeFormMeta(listener),\n subscribeSelector: (selector, listener, options) =>\n deps.observe.subscribeSelector(selector, listener, options),\n subscribePath: (path, listener, options) =>\n deps.observe.subscribePath(path, listener, options),\n subscribeFieldState: (path, listener) =>\n deps.observe.subscribeFieldState(path, listener),\n };\n\n const write: BitStoreWriteSliceApi<T> = {\n setField: (path, value) => deps.write.setField(path, value),\n blurField: (path) => deps.write.blurField(path),\n markFieldsTouched: (paths) => deps.write.markFieldsTouched(paths),\n setValues: (values, options) => deps.write.setValues(values, options),\n setError: (path, message) => deps.write.setError(path, message),\n setErrors: (errors) => deps.write.setErrors(errors),\n setServerErrors: (serverErrors, options) =>\n deps.write.setServerErrors(serverErrors, options),\n reset: () => deps.write.reset(),\n transaction: (callback) => deps.write.transaction(callback),\n submit: (onSuccess) => deps.write.submit(onSuccess),\n };\n\n const feature: BitStoreFeatureApi<T> = {\n cleanup: () => deps.feature.cleanup(),\n validate: (options) => deps.feature.validate(options),\n triggerValidation: (scopeFields, options) =>\n deps.feature.triggerValidation(scopeFields, options),\n restorePersisted: () => deps.feature.restorePersisted(),\n forceSave: () => deps.feature.forceSave(),\n clearPersisted: () => deps.feature.clearPersisted(),\n registerField: (path, config) => deps.write.registerField(path, config),\n unregisterField: (path) => deps.write.unregisterField(path),\n unregisterPrefix: (prefix) => deps.write.unregisterPrefix(prefix),\n pushItem: (path, value) => deps.write.pushItem(path, value),\n prependItem: (path, value) => deps.write.prependItem(path, value),\n insertItem: (path, index, value) =>\n deps.write.insertItem(path, index, value),\n removeItem: (path, index) => deps.write.removeItem(path, index),\n moveItem: (path, from, to) => deps.write.moveItem(path, from, to),\n swapItems: (path, indexA, indexB) =>\n deps.write.swapItems(path, indexA, indexB),\n replaceItems: (path, items) => deps.write.replaceItems(path, items),\n clearItems: (path) => deps.write.clearItems(path),\n getArrayItemIds: (path, length) =>\n deps.feature.getArrayItemIds(path, length),\n get canUndo() {\n return deps.read.getCanUndo();\n },\n get canRedo() {\n return deps.read.getCanRedo();\n },\n hasValidationsInProgress: (scopeFields) =>\n deps.feature.hasValidationsInProgress(scopeFields),\n resolveMask: (path) => deps.resolveMask(path),\n createArrayItemId: (path, index) => deps.createArrayItemId(path, index),\n undo: () => deps.feature.undo(),\n redo: () => deps.feature.redo(),\n };\n\n return {\n read,\n observe,\n write,\n feature,\n };\n}\n","import { getDeepValue } from \"../../utils\";\nimport type {\n BitFieldState,\n BitPath,\n BitPathValue,\n BitPersistMetadata,\n BitState,\n} from \"../contracts/types\";\nimport { createFieldStateSnapshot } from \"../engines/store-field-query-engine\";\n\ninterface BitStoreStateReaderDeps<T extends object> {\n getState(): Readonly<BitState<T>>;\n isHidden(path: string): boolean;\n isRequired(path: string): boolean;\n isFieldDirty(path: string): boolean;\n isFieldValidating(path: string): boolean;\n}\n\ntype BitStateFlagKey = \"isValid\" | \"isSubmitting\" | \"isDirty\";\n\nexport interface BitUserStateLayer<T extends object> {\n values: T;\n touched: BitState<T>[\"touched\"];\n}\n\nexport interface BitValidationStateLayer<T extends object> {\n errors: BitState<T>[\"errors\"];\n isValidating: BitState<T>[\"isValidating\"];\n isValid: BitState<T>[\"isValid\"];\n}\n\nexport interface BitDerivedStateLayer {\n isDirty: boolean;\n}\n\nexport interface BitFeatureStateLayer<T extends object> {\n persist: BitState<T>[\"persist\"];\n isSubmitting: BitState<T>[\"isSubmitting\"];\n}\n\nexport class BitStoreStateReader<T extends object> {\n private readonly fieldStateCache = new Map<\n string,\n {\n state: Readonly<BitState<T>>;\n snapshot: Readonly<BitFieldState<T, unknown>>;\n }\n >();\n private persistMetaCache:\n | {\n state: Readonly<BitState<T>>;\n snapshot: BitPersistMetadata;\n }\n | undefined;\n\n constructor(private readonly deps: BitStoreStateReaderDeps<T>) {}\n\n getState(): Readonly<BitState<T>> {\n return this.deps.getState();\n }\n\n getUserLayer(): BitUserStateLayer<T> {\n const state = this.deps.getState();\n\n return {\n values: state.values,\n touched: state.touched,\n };\n }\n\n getValidationLayer(): BitValidationStateLayer<T> {\n const state = this.deps.getState();\n\n return {\n errors: state.errors,\n isValidating: state.isValidating,\n isValid: state.isValid,\n };\n }\n\n getDerivedLayer(): BitDerivedStateLayer {\n return {\n isDirty: this.deps.getState().isDirty,\n };\n }\n\n getFeatureLayer(): BitFeatureStateLayer<T> {\n const state = this.deps.getState();\n\n return {\n persist: state.persist,\n isSubmitting: state.isSubmitting,\n };\n }\n\n getFlag<TKey extends BitStateFlagKey>(\n key: TKey,\n ): Readonly<BitState<T>>[TKey] {\n return this.deps.getState()[key];\n }\n\n getPersistMetadata(): BitPersistMetadata {\n const state = this.deps.getState();\n const persist = state.persist;\n const cached = this.persistMetaCache;\n\n if (\n cached &&\n cached.state === state &&\n cached.snapshot.isSaving === persist.isSaving &&\n cached.snapshot.isRestoring === persist.isRestoring &&\n cached.snapshot.error === persist.error\n ) {\n return cached.snapshot;\n }\n\n const snapshot: BitPersistMetadata = {\n isSaving: persist.isSaving,\n isRestoring: persist.isRestoring,\n error: persist.error,\n };\n\n this.persistMetaCache = {\n state,\n snapshot,\n };\n\n return snapshot;\n }\n\n getFieldState<P extends BitPath<T>>(\n path: P,\n ): Readonly<BitFieldState<T, BitPathValue<T, P>>> {\n const pathKey = path as string;\n const state = this.deps.getState();\n const cached = this.fieldStateCache.get(pathKey);\n\n const value = getDeepValue(state.values, pathKey) as BitPathValue<T, P>;\n const error = state.errors[pathKey as keyof typeof state.errors];\n const touched = !!state.touched[pathKey as keyof typeof state.touched];\n const isHidden = this.deps.isHidden(pathKey);\n const isRequired = this.deps.isRequired(pathKey);\n const isDirty = this.deps.isFieldDirty(pathKey);\n const isValidating = this.deps.isFieldValidating(pathKey);\n\n if (cached) {\n const snapshot = cached.snapshot;\n\n if (\n snapshot.value === value &&\n snapshot.error === error &&\n snapshot.touched === touched &&\n snapshot.isHidden === isHidden &&\n snapshot.isRequired === isRequired &&\n snapshot.isDirty === isDirty &&\n snapshot.isValidating === isValidating\n ) {\n return snapshot as Readonly<BitFieldState<T, BitPathValue<T, P>>>;\n }\n }\n\n const snapshot = createFieldStateSnapshot({\n state,\n path,\n value,\n isHidden,\n isRequired,\n isDirty,\n isValidating,\n });\n\n this.fieldStateCache.set(pathKey, {\n state,\n snapshot: snapshot as Readonly<BitFieldState<T, unknown>>,\n });\n\n return snapshot;\n }\n\n invalidatePath(path: string): void {\n this.fieldStateCache.delete(path);\n }\n\n invalidatePathTree(parentPath: string): void {\n const prefix = `${parentPath}.`;\n for (const key of this.fieldStateCache.keys()) {\n if (key === parentPath || key.startsWith(prefix)) {\n this.fieldStateCache.delete(key);\n }\n }\n }\n}\n","import type {\n BitFrameworkConfig,\n BitStoreFeatureApi,\n BitStoreObserveSliceApi,\n BitStoreReadSliceApi,\n BitStoreWriteSliceApi,\n} from \"./contracts/public/store-api-types\";\nimport type { BitConfig } from \"./contracts/types\";\nimport { resolveFieldMask } from \"./engines/store-field-query-engine\";\nimport { BIT_FRAMEWORK_STORE_SYMBOL } from \"./orchestration/framework-store-brand\";\nimport { BIT_HOOKS_API_SYMBOL } from \"./orchestration/hook-brand\";\nimport { composeBitStoreRuntime } from \"./orchestration/store-composition-root\";\nimport { createBitStoreDomains } from \"./orchestration/store-domains\";\nimport { buildStoreSlicesApi } from \"./orchestration/store-slices-factory\";\nimport { BitStoreStateReader } from \"./shared/store-state-reader\";\n\nexport class BitStore<T extends object = Record<string, unknown>> {\n public readonly [BIT_HOOKS_API_SYMBOL] = true;\n public readonly [BIT_FRAMEWORK_STORE_SYMBOL] = true;\n\n public readonly storeId: string;\n\n private readonly _config: BitFrameworkConfig<T>;\n\n public readonly read: BitStoreReadSliceApi<T>;\n public readonly observe: BitStoreObserveSliceApi<T>;\n public readonly write: BitStoreWriteSliceApi<T>;\n public readonly feature: BitStoreFeatureApi<T>;\n\n constructor(config: BitConfig<T> = {}) {\n const composition = composeBitStoreRuntime<T>({\n rawConfig: config,\n });\n\n this._config = composition.config;\n this.storeId = composition.storeId;\n\n const stateReader = new BitStoreStateReader<T>({\n getState: () => composition.runtime.getState(),\n isHidden: (path) => composition.runtime.capabilities.query.isHidden(path),\n isRequired: (path) =>\n composition.runtime.capabilities.query.isRequired(path),\n isFieldDirty: (path) =>\n composition.runtime.capabilities.query.isFieldDirty(path),\n isFieldValidating: (path) =>\n composition.runtime.capabilities.query.isFieldValidating(path),\n });\n\n const domains = createBitStoreDomains<T>({\n runtime: composition.runtime,\n config: this._config,\n fieldRegistry: composition.fieldRegistry,\n dirtyManager: composition.dirtyManager,\n stateReader,\n });\n\n const slices = buildStoreSlicesApi<T>({\n identity: {\n storeId: this.storeId,\n config: this._config,\n },\n read: domains.read,\n observe: domains.observe,\n write: domains.write,\n feature: domains.feature,\n getFieldConfig: (path) => composition.fieldRegistry.getFieldConfig(path),\n resolveMask: (path) =>\n resolveFieldMask<T>({\n path,\n getFieldConfig: (fieldPath) =>\n composition.fieldRegistry.getFieldConfig(fieldPath),\n masks: composition.maskManager.getAllMasks(),\n }),\n createArrayItemId: (path, index) =>\n this._config.idFactory({ scope: \"array\", path, index }),\n });\n\n this.read = slices.read;\n this.observe = slices.observe;\n this.write = slices.write;\n this.feature = slices.feature;\n\n composition.runtime.effects.attachStorePort({\n getState: () => this.read.getState(),\n getHistoryMetadata: () => this.read.getHistoryMetadata(),\n undo: () => this.feature.undo(),\n redo: () => this.feature.redo(),\n reset: () => this.write.reset(),\n });\n }\n}\n","import { BitStore } from \"./bit-store-class\";\nimport type { BitConfig } from \"./contracts/types\";\n\nexport function createInternalBitStore<\n T extends object = Record<string, unknown>,\n>(config: BitConfig<T> = {}): BitStore<T> {\n return new BitStore<T>(config);\n}\n\nexport { BitStore };\n","import { createInternalBitStore } from \"../index\";\nimport { BitConfig } from \"../contracts/types\";\nimport {\n BitStoreApi,\n BitFrameworkStoreApi,\n BitStoreHooksApi,\n} from \"../contracts/public/store-api-types\";\nimport { BIT_FRAMEWORK_STORE_SYMBOL } from \"./framework-store-brand\";\nimport { BIT_HOOKS_API_SYMBOL } from \"./hook-brand\";\n\nfunction isHookCompatibleStore<T extends object>(\n store: unknown,\n): store is BitStoreHooksApi<T> {\n if (!store || typeof store !== \"object\") {\n return false;\n }\n\n const candidate = store as Record<PropertyKey, unknown>;\n return (\n candidate[BIT_HOOKS_API_SYMBOL] === true &&\n !!candidate.read &&\n !!candidate.observe &&\n !!candidate.write &&\n !!candidate.feature\n );\n}\n\nexport function resolveBitStoreForHooks<T extends object>(\n store: unknown,\n): BitStoreHooksApi<T> {\n if (isHookCompatibleStore<T>(store)) {\n return store;\n }\n\n throw new Error(\n \"BitForm: o store informado não expõe a API necessária para hooks/framework bindings.\",\n );\n}\n\nfunction isFrameworkBindingStore<T extends object>(\n store: unknown,\n): store is BitFrameworkStoreApi<T> {\n if (!store || typeof store !== \"object\") {\n return false;\n }\n\n const candidate = store as Record<PropertyKey, unknown>;\n return candidate[BIT_FRAMEWORK_STORE_SYMBOL] === true;\n}\n\nexport function createFrameworkStoreAdapter<T extends object>(\n store: unknown,\n): BitFrameworkStoreApi<T> {\n if (!isHookCompatibleStore<T>(store)) {\n throw new Error(\n \"BitForm: o store informado não possui branding de hooks (BIT_HOOKS_API_SYMBOL).\",\n );\n }\n\n if (!isFrameworkBindingStore<T>(store)) {\n throw new Error(\n \"BitForm: o store informado não possui branding de framework (BIT_FRAMEWORK_STORE_SYMBOL).\",\n );\n }\n\n return store as BitFrameworkStoreApi<T>;\n}\n\nfunction applyStoreBranding<T extends object>(\n store: BitStoreApi<T>,\n): BitStoreApi<T> {\n Object.defineProperty(store as object, BIT_HOOKS_API_SYMBOL, {\n value: true,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n\n Object.defineProperty(store as object, BIT_FRAMEWORK_STORE_SYMBOL, {\n value: true,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n\n return store;\n}\n\nexport function createBitStore<T extends object = Record<string, unknown>>(\n config: BitConfig<T> = {},\n): BitStoreApi<T> {\n const internalStore = createInternalBitStore<T>(config);\n\n const storeApi: BitStoreApi<T> = {\n read: internalStore.read,\n observe: internalStore.observe,\n write: internalStore.write,\n feature: internalStore.feature,\n };\n\n return applyStoreBranding(storeApi);\n}\n","import type {\n BitStoreApi,\n BitStoreReadSliceApi,\n BitStoreObserveSliceApi,\n BitStoreWriteSliceApi,\n BitStoreFeatureApi,\n} from \"../contracts/public/store-api-types\";\n\n/**\n * Extracts the `read` slice from a BitStore instance.\n *\n * Use this to pass a read-only API to utility functions and services.\n *\n * @example\n * ```typescript\n * function useFormValidation(read: BitStoreReadSliceApi<MyForm>) {\n * const isValid = read.getIsValid();\n * // ...\n * }\n *\n * useFormValidation(extractReadSlice(store));\n * ```\n */\nexport function extractReadSlice<T extends object>(\n store: BitStoreApi<T>,\n): BitStoreReadSliceApi<T> {\n return store.read;\n}\n\n/**\n * Extracts the `observe` slice from a BitStore instance.\n *\n * Use this to pass an observation-only API to framework hooks and subscriptions.\n *\n * @example\n * ```typescript\n * function useFormSubscribe(observe: BitStoreObserveSliceApi<MyForm>) {\n * useEffect(() => observe.subscribe(handler), [observe]);\n * }\n *\n * useFormSubscribe(extractObserveSlice(store));\n * ```\n */\nexport function extractObserveSlice<T extends object>(\n store: BitStoreApi<T>,\n): BitStoreObserveSliceApi<T> {\n return store.observe;\n}\n\n/**\n * Extracts the `write` slice from a BitStore instance.\n *\n * Use this to pass a write-only API for form mutations.\n *\n * @example\n * ```typescript\n * function useFormActions(write: BitStoreWriteSliceApi<MyForm>) {\n * const handleChange = (path: string, value: any) => {\n * write.setField(path, value);\n * };\n * }\n *\n * useFormActions(extractWriteSlice(store));\n * ```\n */\nexport function extractWriteSlice<T extends object>(\n store: BitStoreApi<T>,\n): BitStoreWriteSliceApi<T> {\n return store.write;\n}\n\n/**\n * Extracts the `feature` slice from a BitStore instance.\n *\n * Use this to pass feature-specific APIs (validation, history, persistence, etc.)\n *\n * @example\n * ```typescript\n * function useFormValidation(feature: BitStoreFeatureApi<MyForm>) {\n * const isValid = await feature.validate();\n * }\n *\n * useFormValidation(extractFeatureSlice(store));\n * ```\n */\nexport function extractFeatureSlice<T extends object>(\n store: BitStoreApi<T>,\n): BitStoreFeatureApi<T> {\n return store.feature;\n}\n\n/**\n * Extracts multiple slices at once for convenience.\n *\n * @example\n * ```typescript\n * const [readApi, writeApi] = extractSlices(store, [\"read\", \"write\"]);\n * ```\n */\nexport function extractSlices<\n T extends object,\n K extends (keyof BitStoreApi<T>)[],\n>(\n store: BitStoreApi<T>,\n keys: readonly [...K],\n): {\n [P in K[number]]: BitStoreApi<T>[P];\n} {\n const result: Partial<BitStoreApi<T>> = {};\n\n for (const key of keys) {\n result[key] = store[key];\n }\n\n return result as {\n [P in K[number]]: BitStoreApi<T>[P];\n };\n}\n"],"mappings":"2RAUO,SAASA,GAAmCC,EAI3B,CACtB,GAAM,CAAE,KAAAC,EAAM,eAAAC,EAAgB,MAAAC,CAAM,EAAIH,EAClCI,EAAaF,EAAeD,CAAI,GAAG,KAEzC,GAAKG,EAIL,OAAI,OAAOA,GAAe,SACjBD,IAAQC,CAAgC,EAG1CA,CACT,CAEO,SAASC,GAGdL,EAQ+C,CAC/C,GAAM,CAAE,MAAAM,EAAO,KAAAL,EAAM,MAAAM,EAAO,SAAAC,EAAU,WAAAC,EAAY,QAAAC,EAAS,aAAAC,CAAa,EACtEX,EACIY,EAAUX,EAEhB,MAAO,CACL,MAAAM,EACA,MAAOD,EAAM,OAAOM,CAAiC,EACrD,QAAS,CAAC,CAACN,EAAM,QAAQM,CAAqC,EAC9D,SAAAJ,EACA,WAAAC,EACA,QAAAC,EACA,aAAAC,CACF,CACF,CCtDO,IAAME,EAA6B,OAAO,IAC/C,8BACF,ECFO,IAAMC,EAAuB,OAAO,IAAI,oBAAoB,ECE5D,IAAMC,EAAN,KAA2C,CAChD,YAAYC,EAAmB,CAC7B,KAAK,eAAiBC,EAAUD,CAAc,CAChD,CAEQ,eACA,iBAER,WAAe,CACb,OAAK,KAAK,mBACR,KAAK,iBAAmB,OAAO,OAAOC,EAAU,KAAK,cAAc,CAAC,GAG/D,KAAK,gBACd,CAEA,UAAUC,EAAiB,CACzB,KAAK,eAAiBD,EAAUC,CAAM,EACtC,KAAK,iBAAmB,MAC1B,CACF,ECbO,IAAMC,EAAN,KAA2C,CAkBhD,YACUC,E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AChB,IAAMC,EAAgBC,GAA0BF,CAAM,EAEhDG,EAA2B,CAC/B,KAAMF,EAAc,KACpB,QAASA,EAAc,QACvB,MAAOA,EAAc,MACrB,QAASA,EAAc,OACzB,EAEA,OAAOH,GAAmBK,CAAQ,CACpC,CC9EO,SAASC,GACdC,EACyB,CACzB,OAAOA,EAAM,IACf,CAgBO,SAASC,GACdD,EAC4B,CAC5B,OAAOA,EAAM,OACf,CAkBO,SAASE,GACdF,EAC0B,CAC1B,OAAOA,EAAM,KACf,CAgBO,SAASG,GACdH,EACuB,CACvB,OAAOA,EAAM,OACf,CAUO,SAASI,GAIdJ,EACAK,EAGA,CACA,IAAMC,EAAkC,CAAC,EAEzC,QAAWC,KAAOF,EAChBC,EAAOC,CAAG,EAAIP,EAAMO,CAAG,EAGzB,OAAOD,CAGT","names":["resolveFieldMask","args","path","getFieldConfig","masks","maskOption","createFieldStateSnapshot","state","value","isHidden","isRequired","isDirty","isValidating","pathKey","BIT_FRAMEWORK_STORE_SYMBOL","BIT_HOOKS_API_SYMBOL","BitBaselineManager","baselineValues","deepClone","values","BitComputedManager","getComputedEntries","onError","value","values","changedPaths","computedEntries","entriesToRun","nextValues","failedPaths","entry","dep","newValue","error","currentValue","getDeepValue","cached","valuesEqual","canUseScalarCache","deepEqual","setDeepValue","entries","map","dependents","childIdx","segments","len","prefix","children","reverseDependencies","affectedPaths","queue","queueIndex","currentPath","dependentPath","orderedAllEntries","indexByPath","affectedEntries","path","entryIndex","left","right","item","entryByPath","inDegree","dependencyPath","nextDependents","orderedPaths","nextDegree","signature","ordered","orderedEntries","index","changedPath","collect","listeners","parentSegments","childKeys","childDep","BitDirtyManager","path","values","initialValues","current","getDeepValue","initial","valueEqual","collectDirtyPaths","separatorIndex","ancestorPath","updates","sortedPaths","processedArrays","includedPaths","isDescendantOfIncludedPath","arrayMatch","arrayPath","arrayVal","fieldVal","setDeepValues","nextIndex","nextRefCount","nextChildrenByPrefix","dirtyPath","prefix","ancestor","set","parentPath","children","nextCount","callback","segments","segment","i","BitMaskManager","bitMasks","name","mask","stripTrailingSeparators","path","normalizePathPrefix","prefix","isPathWithinPrefix","normalizedPrefix","toPathPrefix","index","isWildcardPath","path","createWildcardRegex","wildcardPath","regexStr","expandWildcardPaths","values","pathSegments","currentPaths","i","seg","nextPaths","p","arrayPrefix","arr","getDeepValue","idx","resolveWildcardDependency","dependencyPattern","concretePath","fieldPattern","fieldRegexStr","fieldRegex","match","wildcardValues","valueIndex","segments","result","val","BitFieldCatalog","path","exact","pattern","config","regex","isWildcardPath","createWildcardRegex","callback","scopeName","values","index","cfg","list","paths","result","expandWildcardPaths","p","finalEntries","entry","expanded","concretePath","vals","dep","resolveWildcardDependency","transformFn","val","allValues","scopedPaths","entryPath","BitFieldConditions","getFieldConfig","onConditionError","path","config","currentValues","hasShowIf","dependsOn","error","dep","options","requiredPaths","dependentsSet","values","cached","deepEqual","result","errors","val","getDeepValue","changedPath","newValues","affectedFields","visibilityChanged","requiredChanged","queue","visited","currentPath","dependents","depPath","wasHidden","wasRequired","isHiddenNow","isRequiredNow","showIf","newPath","targetDependency","current","value","BitFieldRegistry","BitFieldCatalog","onConditionError","BitFieldConditions","path","callback","config","currentValues","previousConfig","prefix","removedEntries","normalizedPrefix","normalizePathPrefix","isPathWithinPrefix","values","changedPath","newValues","scopeName","defaultIdFactory","defaultUnhandledErrorReporter","error","normalizeConfig","config","rawInitial","validation","history","defaultPersistKey","userUnhandledError","safeUnhandledErrorReporter","source","fallbackError","persistErrorHandler","persist","raw","deepClone","mergePaths","previous","next","merged","path","createDependencyImpactChecker","changedPaths","hasWildcardChange","changedPathSet","changedAncestorSet","changedPath","separatorIndex","dependencyPath","filterDependencyEntries","entries","isDependencyImpacted","entry","orderDependencyEntries","entryByPath","inDegree","dependents","originalIndex","index","nextDependents","queue","orderedPaths","left","right","currentPath","dependentPath","nextDegree","cyclePaths","path","applyValueDerivations","args","values","normalizerEntries","applyComputed","onError","orderedResult","targetedNormalizers","normalizerUpdates","normalizedValues","currentValue","getDeepValue","derivedValue","error","valueEqual","setDeepValue","nextChangedPaths","mergePaths","applyTransformDerivations","sourceValues","transformEntries","transformedValues","transformedAllValues","transform","BitStoreEffectEngine","registry","storeBusPort","effect","nextState","valuesChanged","error","restored","firstError","event","effectName","hookName","index","BitBusEffects","storeId","bus","enableBusDispatch","storeBusPort","nextState","BitEffectRegistry","effect","BitPersistEffects","persistManager","_nextState","valuesChanged","BitPluginEffects","pluginManager","event","getDefaultStorage","storageLike","key","value","BitPersistManager","config","getValues","getDirtyValues","applyRestoredValues","callbacks","error","operation","run","result","storage","payload","serialized","raw","parsed","BitPluginManager","plugins","contextFactory","context","plugin","maybeTeardown","error","event","hook","result","source","pluginName","entry","stateSnapshot","payload","onError","index","teardown","hookName","rootGlobal","id","state","fn","bitBus","noopBus","getNoopBitBus","createBitBus","listeners","shouldEnableStoreBus","config","createStoreEffects","args","storeId","storeBusPort","getState","getConfig","getValues","getDirtyValues","applyPersistedValues","setPersistMetadata","persistManager","BitPersistManager","error","pluginManager","BitPluginManager","deepClone","enableBusDispatch","isTestEnv","resolvedBus","getNoopBitBus","bitBus","registry","BitEffectRegistry","destroyed","persistEffects","BitPersistEffects","nextState","valuesChanged","restored","pluginEffects","BitPluginEffects","event","busEffects","BitBusEffects","port","effects","BitStoreEffectEngine","patchStateOperation","partialState","changedPaths","options","touchFieldsOperation","paths","persistMetaOperation","patch","validationCommitOperation","errors","isValid","activeRestoringOpsByDispatch","lastRestoringErrorByDispatch","beginPersistOperation","args","dispatch","map","errorMap","active","persistMetaOperation","finalizePersistOperation","error","nextActive","pendingError","finalError","restoreStorePersisted","effects","onUnhandledError","operationError","forceStorePersistedSave","clearStorePersisted","applyStorePersistedValues","values","state","initialValues","validation","fieldRegistry","dirtyManager","saveHistorySnapshot","nextValues","deepClone","deepMerge","isDirty","patchStateOperation","buildFieldUnregisterPatch","args","state","path","prefix","nextErrors","nextTouched","changed","key","analyzeCyclicDependencies","entries","cycles","graph","computedPaths","entry","dep","visited","recursionStack","hasCycle","node","path","neighbors","neighbor","cycleStart","cyclePath","p","cycle","hasValueDerivation","config","registerStoreField","args","path","state","fieldRegistry","subscriptions","validationCleanupField","stateReader","invalidateFieldIndexes","dispatch","getState","onUnhandledError","previousConfig","previousAsyncValidate","nextAsyncValidate","previousAsyncValidateOn","nextAsyncValidateOn","shouldValidateComputedGraph","shouldRecomputeValues","cycles","analyzeCyclicDependencies","patchStateOperation","currentState","getScopeRegistrySubscriptionPath","unregisterStoreField","hasStaticConfig","fieldConfig","cleanupPatch","buildFieldUnregisterPatch","unregisterStorePrefix","prefix","validationCleanupPrefix","hasStaticConfigPath","normalizedPrefix","normalizePathPrefix","isStaticPath","removablePaths","_config","isPathWithinPrefix","removedEntries","scopeName","nextErrors","nextTouched","changed","entryPath","SUBSCRIPTION_ERROR_SOURCE","BitSubscriptionEngine","getState","onErrorOrMaxCache","maxCacheSize","listener","selector","options","equalityFn","lastSlice","subscription","nextState","nextSlice","error","scopedPaths","pathKey","indexPath","listeners","paths","changedPaths","normalizedChangedPaths","singleScopedSubscribers","scopedSubscribers","subscriptions","prefix","normalizedPrefix","normalizePathPrefix","key","isPathWithinPrefix","seen","normalized","path","trimmed","currentVersion","addByPath","changedPath","visitor","segments","currentPath","index","separatorIndex","cached","keys","i","cache","value","maxSize","oldestKey","BitArrayManager","store","path","length","targetLength","value","ids","toPathPrefix","getDeepValue","currentIdx","current","index","currentLength","safeIndex","next","i","nextArray","state","arr","newArray","_","indexA","indexB","source","from","to","id","item","minIndex","maxIndex","items","mutate","meta","updater","args","reindex","previousState","reindexedMeta","reindexFieldArrayMeta","patchStateOperation","BitErrorManager","getState","dispatch","reportError","message","details","path","newErrors","patchStateOperation","errors","sanitizedErrors","serverErrors","options","arrayStrategy","joinSeparator","formattedErrors","key","value","normalizedMessages","BitFieldQueryManager","fieldMetadataProvider","getState","isPathDirty","path","values","isPlainObject","value","createHistoryPatch","previousValue","nextValue","operations","activePairs","visit","previousNode","nextNode","path","hadPreviousValue","hasNextValue","deepEqual","activeNextNodes","keys","key","childPath","childHasPrevious","childHasNext","deepClone","nextActiveNodes","applyHistoryPatch","currentValue","patch","direction","setUpdates","unsetPaths","operation","shouldSet","setDeepValues","unsetDeepValues","BitHistoryManager","enableHistory","maxHistory","values","patch","createHistoryPatch","previousSnapshot","applyHistoryPatch","nextSnapshot","initialValues","deepClone","oldestPatch","clearErrorPath","errors","path","alreadyMutated","nextErrors","hasMutated","BitPipelineRunner","steps","context","step","BitSyncPipelineRunner","result","BitFieldUpdateManager","store","BitSyncPipelineRunner","ctx","path","value","meta","state","previousValue","getDeepValue","context","setDeepValue","clearErrorPath","depPath","changedPaths","patchStateOperation","validationTargets","BitLifecycleOrchestrator","kind","executor","current","context","ordered","result","left","right","BitSubmitLifecycleManager","store","BitPipelineRunner","ctx","onSuccess","context","deepClone","error","patchStateOperation","currentErrors","newTouched","path","updates","hiddenFields","hiddenPath","setDeepValues","applyTransformDerivations","isValidationErrorShape","extractServerErrors","BitValuesLifecycleManager","store","values","prefix","updates","activeBranch","key","value","nextPath","newValues","options","changedUpdates","changedPaths","path","mergedValues","setDeepValues","previousValues","clonedValues","deepClone","patchStateOperation","error","snapshot","isDirty","initialCloned","origin","BitLifecycleManager","ports","BitFieldUpdateManager","BitValuesLifecycleManager","BitSubmitLifecycleManager","ctx","BitLifecycleOrchestrator","path","value","meta","newValues","options","values","snapshot","onSuccess","context","BitScopeManager","getState","getInitialValues","getScopeFields","isPathDirty","scopeName","fields","state","hasErrors","f","isDirty","errors","result","field","error","BIT_ASYNC_VALIDATION_TIMEOUT","BitAsyncValidationScheduler","port","path","value","validate","delay","timeoutMs","controller","shouldReschedule","prefix","hasPendingChange","paths","isPathWithinPrefix","remapPath","nextPendingJobs","job","nextPath","nextAbortControllers","_job","nextDueAt","error","now","dueJobs","results","result","validationPromise","timeoutId","resolve","errorMessage","currentValue","getDeepValue","valueEqual","currentPath","storedController","hasAnyError","errors","path","commitSynchronousScopeValidation","args","scopeFields","store","asyncErrors","initialState","initialHiddenFields","resolverErrors","currentState","valuesStale","field","valueEqual","getDeepValue","currentHiddenFields","visibilityStale","dynamicRequiredErrors","allErrors","hiddenPath","scopedErrors","validationCommitOperation","hasAnyError","BitValidationCoordinator","validationId","path","controller","prefix","onPathCancelled","isPathWithinPrefix","remapPath","nextControllers","nextPath","BitValidationDebouncer","port","scopeFields","options","configuredDelay","delay","f","resolvedScopeFields","mergedScopeFields","BIT_ASYNC_VALIDATION_TIMEOUT","mergeValidationErrors","args","targetFields","currentErrors","allErrors","asyncErrors","hiddenFields","scopedErrors","hasScopedMutation","ensureScopedMutable","field","key","currentMessage","asyncMessage","scopedResult","globalErrors","message","path","resolveAsyncValidationPaths","getFieldConfig","forEachFieldConfig","paths","config","runImmediateAsyncValidationStage","values","validationId","getCurrentValidationId","cancelFieldAsync","createAbortController","setAbortController","clearAbortController","setFieldValidating","setAsyncError","clearAsyncError","asyncValidate","controller","asyncValidateTimeout","validationPromise","getDeepValue","timeoutId","resolve","errorMessage","resolveTargetFieldsStage","args","ctx","deps","rawOptions","scopeFields","runBeforeValidateHooksStage","runSynchronousTrackStage","resolverErrors","dynamicRequiredErrors","hiddenPath","runAsyncTrackStage","targetPaths","resolveAsyncValidationPaths","path","results","result","mergeAsyncTrackStage","merged","mergeValidationErrors","hasAnyError","abortIfOutdatedStage","commitValidationStage","validationCommitOperation","BitValidationPipelineOrchestrator","deps","BitPipelineRunner","ctx","resolveTargetFieldsStage","runBeforeValidateHooksStage","runSynchronousTrackStage","abortIfOutdatedStage","runAsyncTrackStage","mergeAsyncTrackStage","commitValidationStage","context","BitValidationManager","store","fn","delayMs","timeoutId","BitValidationDebouncer","options","operation","path","callback","scopeName","values","event","BitAsyncValidationScheduler","isValidating","message","previousAsyncMessage","commitSynchronousScopeValidation","error","stageDeps","validationId","BitValidationPipelineOrchestrator","BitValidationCoordinator","currentState","nextValidating","patchStateOperation","prefix","remapIndex","currentPath","remapIndexedPath","nextAsyncErrors","nextPath","value","config","asyncValidate","asyncValidateOn","delay","timeout","scopeFields","state","field","fieldPath","context","liveState","runImmediateAsyncValidationStage","controller","ctrl","BitStoreCapabilityRegistry","key","capability","createStoreCapabilityRegistry","registerStoreCapabilities","args","registry","ports","fieldRegistry","BitValidationManager","BitLifecycleManager","BitHistoryManager","BitArrayManager","BitScopeManager","scopeName","path","BitFieldQueryManager","BitErrorManager","operation","error","composeStoreCapabilities","createStoreCapabilityRegistry","createInitialStoreState","config","computedManager","initialValues","deepClone","fieldConfig","computedCycles","analyzeCyclicDependencies","applyValueDerivations","values","changedPaths","_path","createValidationPort","deps","callback","config","path","values","event","createLifecyclePort","fieldUpdate","changedPath","currentValues","newValues","scopeFields","options","value","nextValues","baselineValues","initialValues","submit","serverErrors","createArrayPort","composeRuntimeFeatureCapabilities","args","config","fieldRegistry","dirtyManager","baselineManager","runtimeContext","stateAccess","fieldAccess","featureAccess","actions","validationPort","createValidationPort","lifecyclePorts","createLifecyclePort","values","arrayPort","createArrayPort","path","value","meta","remapIndex","index","composeStoreCapabilities","createStoreRuntime","args","config","fieldRegistry","dirtyManager","computedManager","rawConfig","baselineManager","runtimeContext","stateAccess","fieldAccess","featureAccess","actions","capabilityComposition","composeRuntimeFeatureCapabilities","state","createInitialStoreState","subscriptions","BitSubscriptionEngine","error","source","storeId","createStoreBatchState","beginStoreBatch","batchState","endStoreBatch","getEffectiveStoreState","currentState","trackBatchedStoreUpdate","updateResult","pathSet","pathList","path","existingPath","index","flushStoreBatchState","args","applyValueDerivations","onDerivationError","nextState","changedPaths","valuesChanged","error","BitStoreHistoryOrchestrator","args","values","before","after","metadata","normalizeErrors","errors","hasUndefined","message","normalized","path","typedMessage","applyStateUpdate","args","currentState","partialState","changedPaths","applyValueDerivations","applyComputedValues","deriveValues","values","nextState","valuesChanged","derivedIsValid","hasAnyError","explicitChangedPaths","inferredChangedPaths","inferChangedPaths","effectiveChangedPaths","mergePaths","pathMaps","map","assertNever","value","routeStoreOperation","currentState","operation","touched","path","patchStateOperation","executeStatePatchOperation","args","applyValueDerivations","onOperationError","hasValuesPatch","effectiveChangedPaths","result","applyStateUpdate","error","values","_ignored","safePartial","unrecoverableError","executeStoreOperation","patchOperation","changedPaths","dispatchStoreKernelOperation","state","batchState","onStateCommitted","getEffectiveStoreState","updateResult","trackBatchedStoreUpdate","flushStoreKernelBatch","onDerivationError","flushResult","flushStoreBatchState","runStoreStateBatch","args","batchState","callback","flushBatchedStateUpdates","beginStoreBatch","endStoreBatch","commitStoreStateUpdate","payload","setState","notifySubscriptions","notifyEffects","dispatchStoreStateOperation","state","operation","applyValueDerivations","onOperationError","onStateCommitted","dispatchStoreKernelOperation","saveStoreHistorySnapshot","values","saveHistory","flushStoreBatchedStateUpdates","onDerivationError","nextState","flushStoreKernelBatch","BitStoreRuntimeKernel","args","BitStoreHistoryOrchestrator","getHistorySubscriptionPath","createStoreBatchState","name","getEffectiveStoreState","callback","runStoreStateBatch","operation","dispatchStoreStateOperation","values","changedPaths","error","payload","saveStoreHistorySnapshot","commitStoreStateUpdate","state","valuesChanged","flushStoreBatchedStateUpdates","composeBitStoreRuntime","args","rawConfig","overrides","config","normalizeConfig","baselineManager","BitBaselineManager","fieldRegistry","BitFieldRegistry","error","computedManager","BitComputedManager","values","dirtyManager","BitDirtyManager","maskManager","BitMaskManager","invalidateFieldIndexes","runtimeKernel","getRuntimeKernel","runtime","createStoreRuntime","operation","callback","path","scopeName","message","serverErrors","options","value","meta","prefix","unregisterStorePrefix","fieldPrefix","scopeFields","getDirtyValues","effectiveState","applyPersistedValues","applyStorePersistedValues","effects","createStoreEffects","patch","BitStoreRuntimeKernel","source","changedPaths","applyValueDerivations","nextValues","nextChangedPaths","_path","restorePersistedFeature","args","dispatch","effects","onUnhandledError","restoreStorePersisted","forceSavePersistedFeature","forceStorePersistedSave","clearPersistedFeature","clearStorePersisted","runUndoFeature","history","applyHistoryState","prevState","runRedoFeature","nextState","readHistoryFeatureMetadata","collectTrackedSelectorPaths","state","selector","trackedPaths","createTrackingProxy","value","basePath","visited","target","key","receiver","keyAsString","childPath","child","proxyState","normalizedPaths","path","normalizedPath","normalizeTrackedPath","areTrackedPathSetsEqual","previousPaths","nextPaths","next","withTrackedSelectorPaths","paths","options","createTrackedSubscription","args","getState","subscribeSelector","listener","activeUnsubscribe","activePaths","isDisposed","isResubscribeQueued","subscribeWithPaths","previousUnsubscribe","slice","subscribeStoreSelector","args","getState","subscriptions","selector","listener","options","trackedSubscriptionsEnabled","onUnhandledError","equalityFn","valueEqual","createTrackedSubscription","trackedSelector","trackedListener","trackedOptions","subscribeStorePath","path","subscribeSelector","mergedPaths","state","getDeepValue","subscribeStoreFieldState","getFieldState","areFieldStatesEqual","subscribeStoreFormMeta","prev","next","subscribeStorePersistMeta","subscribeStoreHistoryMeta","readHistoryMeta","getHistorySubscriptionPath","isHistoryMetaEqual","subscribeStoreScopeStatus","scopeName","getScopeFields","readScopeStatus","registryPath","getScopeRegistrySubscriptionPath","lastStatus","unsubscribeScoped","subscribeScoped","scopePaths","getScopeSubscriptionPaths","status","isScopeStatusEqual","resubscribeQueued","destroyed","unsubscribeRegistry","nextStatus","createBitStoreDomains","args","runtime","config","fieldRegistry","dirtyManager","stateReader","readDomain","deepClone","path","readHistoryFeatureMetadata","scopeName","observeDomain","listener","subscribeStorePersistMeta","selector","persistListener","options","subscribeStoreHistoryMeta","historyListener","subscribeStoreScopeStatus","name","scopeListener","subscribeStoreSelector","error","source","subscribeStorePath","pathListener","selectorOptions","subscribeStoreFieldState","fieldPath","fieldListener","subscribeStoreFormMeta","metaListener","writeDomain","fieldConfig","registerStoreField","operation","unregisterStoreField","prefix","unregisterStorePrefix","fieldPrefix","value","touchFieldsOperation","paths","values","message","errors","serverErrors","callback","onSuccess","index","indexA","indexB","from","to","items","featureDispatch","runUndoFeature","runRedoFeature","scopeFields","restorePersistedFeature","forceSavePersistedFeature","clearPersistedFeature","length","freezeConfig","config","deepClone","buildStoreSlicesApi","deps","readState","path","scopeName","listener","selector","options","value","paths","values","message","errors","serverErrors","callback","onSuccess","scopeFields","prefix","index","from","to","indexA","indexB","items","length","BitStoreStateReader","deps","state","key","persist","cached","snapshot","path","pathKey","value","getDeepValue","error","touched","isHidden","isRequired","isDirty","isValidating","createFieldStateSnapshot","parentPath","prefix","BitStore","BIT_HOOKS_API_SYMBOL","BIT_FRAMEWORK_STORE_SYMBOL","config","composition","composeBitStoreRuntime","stateReader","BitStoreStateReader","path","domains","createBitStoreDomains","slices","buildStoreSlicesApi","resolveFieldMask","fieldPath","index","createInternalBitStore","config","BitStore","isHookCompatibleStore","store","candidate","BIT_HOOKS_API_SYMBOL","resolveBitStoreForHooks","isFrameworkBindingStore","BIT_FRAMEWORK_STORE_SYMBOL","createFrameworkStoreAdapter","applyStoreBranding","createBitStore","config","internalStore","createInternalBitStore","storeApi","extractReadSlice","store","extractObserveSlice","extractWriteSlice","extractFeatureSlice","extractSlices","keys","result","key"]}