@lehnihon/bit-form 2.1.1 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/angular/index.cjs +1 -1
- package/dist/angular/index.cjs.map +1 -1
- package/dist/angular/index.d.cts +16 -4
- package/dist/angular/index.d.ts +16 -4
- package/dist/angular/index.js +1 -1
- package/dist/angular/index.js.map +1 -1
- package/dist/{bus-C1xKmQdw.d.cts → bus-70e4jnBj.d.cts} +106 -4
- package/dist/{bus-C1xKmQdw.d.ts → bus-70e4jnBj.d.ts} +106 -4
- package/dist/chunk-25Q2XJBV.cjs +133 -0
- package/dist/{chunk-SIM4YIOW.cjs.map → chunk-25Q2XJBV.cjs.map} +1 -1
- package/dist/chunk-2HAQ3QEQ.js +133 -0
- package/dist/chunk-2HAQ3QEQ.js.map +1 -0
- package/dist/chunk-HTB6QIUQ.js +2 -0
- package/dist/chunk-HTB6QIUQ.js.map +1 -0
- package/dist/chunk-W22D7QVJ.cjs +2 -0
- package/dist/chunk-W22D7QVJ.cjs.map +1 -0
- package/dist/devtools/bridge.cjs +1 -1
- package/dist/devtools/bridge.js +1 -1
- package/dist/devtools/index.cjs +1 -1
- package/dist/devtools/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +1 -1
- package/dist/{public-types-B3jU1R2E.d.cts → public-types-BVZ16kgZ.d.ts} +8 -4
- package/dist/{public-types-By_9Weno.d.ts → public-types-r2aP68Gg.d.cts} +8 -4
- package/dist/react/index.cjs +1 -1
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +6 -6
- package/dist/react/index.d.ts +6 -6
- package/dist/react/index.js +1 -1
- package/dist/react/index.js.map +1 -1
- package/dist/react-native/index.cjs +1 -1
- package/dist/react-native/index.cjs.map +1 -1
- package/dist/react-native/index.d.cts +11 -13
- package/dist/react-native/index.d.ts +11 -13
- package/dist/react-native/index.js +1 -1
- package/dist/react-native/index.js.map +1 -1
- package/dist/resolvers/joi.d.cts +1 -1
- package/dist/resolvers/joi.d.ts +1 -1
- package/dist/resolvers/yup.d.cts +1 -1
- package/dist/resolvers/yup.d.ts +1 -1
- package/dist/resolvers/zod.d.cts +1 -1
- package/dist/resolvers/zod.d.ts +1 -1
- package/dist/{use-bit-watch-DVxSlp2A.d.ts → use-bit-persist-COdNw_fv.d.ts} +15 -3
- package/dist/{use-bit-watch-v4eamRCT.d.cts → use-bit-persist-JshPvwwy.d.cts} +15 -3
- package/dist/vue/index.cjs +1 -1
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.d.cts +17 -5
- package/dist/vue/index.d.ts +17 -5
- package/dist/vue/index.js +1 -1
- package/dist/vue/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-5JV3QKOT.js +0 -2
- package/dist/chunk-5JV3QKOT.js.map +0 -1
- package/dist/chunk-CPFHKRLU.cjs +0 -2
- package/dist/chunk-CPFHKRLU.cjs.map +0 -1
- package/dist/chunk-SIM4YIOW.cjs +0 -133
- package/dist/chunk-XHZAMKSZ.js +0 -133
- package/dist/chunk-XHZAMKSZ.js.map +0 -1
|
@@ -74,6 +74,107 @@ interface DevToolsOptions {
|
|
|
74
74
|
mode?: "local" | "remote";
|
|
75
75
|
url?: string;
|
|
76
76
|
}
|
|
77
|
+
type BitPluginHookSource = "beforeValidate" | "afterValidate" | "beforeSubmit" | "afterSubmit" | "onFieldChange" | "setup" | "teardown" | "submit";
|
|
78
|
+
type BitFieldChangeOrigin = "setField" | "setValues" | "array";
|
|
79
|
+
type BitArrayOperation = "push" | "prepend" | "insert" | "remove" | "move" | "swap";
|
|
80
|
+
interface BitFieldChangeMeta {
|
|
81
|
+
origin: BitFieldChangeOrigin;
|
|
82
|
+
operation?: BitArrayOperation;
|
|
83
|
+
index?: number;
|
|
84
|
+
from?: number;
|
|
85
|
+
to?: number;
|
|
86
|
+
}
|
|
87
|
+
interface BitFieldChangeEvent<T extends object = any> {
|
|
88
|
+
path: string;
|
|
89
|
+
previousValue: unknown;
|
|
90
|
+
nextValue: unknown;
|
|
91
|
+
values: Readonly<T>;
|
|
92
|
+
state: Readonly<BitState<T>>;
|
|
93
|
+
meta: BitFieldChangeMeta;
|
|
94
|
+
}
|
|
95
|
+
interface BitBeforeValidateEvent<T extends object = any> {
|
|
96
|
+
values: Readonly<T>;
|
|
97
|
+
state: Readonly<BitState<T>>;
|
|
98
|
+
scope?: string;
|
|
99
|
+
scopeFields?: string[];
|
|
100
|
+
}
|
|
101
|
+
interface BitAfterValidateEvent<T extends object = any> {
|
|
102
|
+
values: Readonly<T>;
|
|
103
|
+
state: Readonly<BitState<T>>;
|
|
104
|
+
scope?: string;
|
|
105
|
+
scopeFields?: string[];
|
|
106
|
+
errors: BitErrors<T>;
|
|
107
|
+
result: boolean;
|
|
108
|
+
aborted?: boolean;
|
|
109
|
+
}
|
|
110
|
+
interface BitBeforeSubmitEvent<T extends object = any> {
|
|
111
|
+
values: Readonly<T>;
|
|
112
|
+
dirtyValues: Readonly<Partial<T>>;
|
|
113
|
+
state: Readonly<BitState<T>>;
|
|
114
|
+
}
|
|
115
|
+
interface BitAfterSubmitEvent<T extends object = any> {
|
|
116
|
+
values: Readonly<T>;
|
|
117
|
+
dirtyValues: Readonly<Partial<T>>;
|
|
118
|
+
state: Readonly<BitState<T>>;
|
|
119
|
+
success: boolean;
|
|
120
|
+
error?: unknown;
|
|
121
|
+
invalid?: boolean;
|
|
122
|
+
}
|
|
123
|
+
interface BitPluginErrorEvent<T extends object = any> {
|
|
124
|
+
source: BitPluginHookSource;
|
|
125
|
+
pluginName?: string;
|
|
126
|
+
error: unknown;
|
|
127
|
+
event?: unknown;
|
|
128
|
+
values: Readonly<T>;
|
|
129
|
+
state: Readonly<BitState<T>>;
|
|
130
|
+
}
|
|
131
|
+
interface BitPluginContext<T extends object = any> {
|
|
132
|
+
storeId: string;
|
|
133
|
+
getState: () => Readonly<BitState<T>>;
|
|
134
|
+
getConfig: () => Readonly<BitConfig<T>>;
|
|
135
|
+
}
|
|
136
|
+
interface BitPluginHooks<T extends object = any> {
|
|
137
|
+
beforeValidate?: (event: BitBeforeValidateEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
138
|
+
afterValidate?: (event: BitAfterValidateEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
139
|
+
beforeSubmit?: (event: BitBeforeSubmitEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
140
|
+
afterSubmit?: (event: BitAfterSubmitEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
141
|
+
onFieldChange?: (event: BitFieldChangeEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
142
|
+
onError?: (event: BitPluginErrorEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
143
|
+
}
|
|
144
|
+
interface BitPlugin<T extends object = any> {
|
|
145
|
+
name: string;
|
|
146
|
+
setup?: (context: BitPluginContext<T>) => void | (() => void);
|
|
147
|
+
hooks?: BitPluginHooks<T>;
|
|
148
|
+
}
|
|
149
|
+
type BitMaybePromise<T> = T | Promise<T>;
|
|
150
|
+
interface BitPersistStorageAdapter {
|
|
151
|
+
getItem(key: string): BitMaybePromise<string | null>;
|
|
152
|
+
setItem(key: string, value: string): BitMaybePromise<void>;
|
|
153
|
+
removeItem(key: string): BitMaybePromise<void>;
|
|
154
|
+
}
|
|
155
|
+
type BitPersistMode = "values" | "dirtyValues";
|
|
156
|
+
interface BitPersistConfig<T extends object = any> {
|
|
157
|
+
enabled?: boolean;
|
|
158
|
+
key?: string;
|
|
159
|
+
storage?: BitPersistStorageAdapter;
|
|
160
|
+
autoSave?: boolean;
|
|
161
|
+
debounceMs?: number;
|
|
162
|
+
mode?: BitPersistMode;
|
|
163
|
+
serialize?: (payload: unknown) => string;
|
|
164
|
+
deserialize?: (raw: string) => Partial<T>;
|
|
165
|
+
onError?: (error: unknown) => void;
|
|
166
|
+
}
|
|
167
|
+
interface BitPersistResolvedConfig<T extends object = any> {
|
|
168
|
+
enabled: boolean;
|
|
169
|
+
key: string;
|
|
170
|
+
storage?: BitPersistStorageAdapter;
|
|
171
|
+
autoSave: boolean;
|
|
172
|
+
debounceMs: number;
|
|
173
|
+
mode: BitPersistMode;
|
|
174
|
+
serialize: (payload: unknown) => string;
|
|
175
|
+
deserialize: (raw: string) => Partial<T>;
|
|
176
|
+
onError?: (error: unknown) => void;
|
|
177
|
+
}
|
|
77
178
|
/** Validation config. */
|
|
78
179
|
interface BitValidationConfig<T> {
|
|
79
180
|
resolver?: ValidatorFn<T>;
|
|
@@ -100,9 +201,10 @@ interface BitConfig<T extends object = any> {
|
|
|
100
201
|
history?: BitHistoryConfig;
|
|
101
202
|
/** DevTools */
|
|
102
203
|
devTools?: boolean | DevToolsOptions;
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
204
|
+
/** Persistência local de rascunho */
|
|
205
|
+
persist?: BitPersistConfig<T>;
|
|
206
|
+
/** Plugins de lifecycle (observabilidade) */
|
|
207
|
+
plugins?: BitPlugin<T>[];
|
|
106
208
|
}
|
|
107
209
|
/** Return type of BitStore.getStepStatus, used by useBitScope/injectBitScope. */
|
|
108
210
|
interface ScopeStatus {
|
|
@@ -141,4 +243,4 @@ declare global {
|
|
|
141
243
|
}
|
|
142
244
|
declare const bitBus: BitFormGlobal;
|
|
143
245
|
|
|
144
|
-
export { type BitConfig as B, type CurrencyMaskConfig as C, type DateMaskConfig as D, type PatternMaskOptions as P, type ScopeStatus as S, type ValidateScopeResult as V, type BitMask as a, type
|
|
246
|
+
export { type BitTransformFn as A, type BitConfig as B, type CurrencyMaskConfig as C, type DateMaskConfig as D, type BitValidationConfig as E, type DeepPartial as F, type ValidatorFn as G, bitBus as H, type DevToolsOptions as I, type BitPersistResolvedConfig as J, type PatternMaskOptions as P, type ScopeStatus as S, type ValidateScopeResult as V, type BitMask as a, type BitAfterSubmitEvent as b, type BitAfterValidateEvent as c, type BitArrayItem as d, type BitArrayPath as e, type BitBeforeSubmitEvent as f, type BitBeforeValidateEvent as g, type BitComputedFn as h, type BitErrors as i, type BitFieldChangeEvent as j, type BitFieldChangeMeta as k, type BitFieldConditional as l, type BitFieldDefinition as m, type BitFieldValidation as n, type BitHistoryConfig as o, type BitPath as p, type BitPathValue as q, type BitPersistConfig as r, type BitPersistMode as s, type BitPersistStorageAdapter as t, type BitPlugin as u, type BitPluginContext as v, type BitPluginErrorEvent as w, type BitPluginHooks as x, type BitState as y, type BitTouched as z };
|
|
@@ -74,6 +74,107 @@ interface DevToolsOptions {
|
|
|
74
74
|
mode?: "local" | "remote";
|
|
75
75
|
url?: string;
|
|
76
76
|
}
|
|
77
|
+
type BitPluginHookSource = "beforeValidate" | "afterValidate" | "beforeSubmit" | "afterSubmit" | "onFieldChange" | "setup" | "teardown" | "submit";
|
|
78
|
+
type BitFieldChangeOrigin = "setField" | "setValues" | "array";
|
|
79
|
+
type BitArrayOperation = "push" | "prepend" | "insert" | "remove" | "move" | "swap";
|
|
80
|
+
interface BitFieldChangeMeta {
|
|
81
|
+
origin: BitFieldChangeOrigin;
|
|
82
|
+
operation?: BitArrayOperation;
|
|
83
|
+
index?: number;
|
|
84
|
+
from?: number;
|
|
85
|
+
to?: number;
|
|
86
|
+
}
|
|
87
|
+
interface BitFieldChangeEvent<T extends object = any> {
|
|
88
|
+
path: string;
|
|
89
|
+
previousValue: unknown;
|
|
90
|
+
nextValue: unknown;
|
|
91
|
+
values: Readonly<T>;
|
|
92
|
+
state: Readonly<BitState<T>>;
|
|
93
|
+
meta: BitFieldChangeMeta;
|
|
94
|
+
}
|
|
95
|
+
interface BitBeforeValidateEvent<T extends object = any> {
|
|
96
|
+
values: Readonly<T>;
|
|
97
|
+
state: Readonly<BitState<T>>;
|
|
98
|
+
scope?: string;
|
|
99
|
+
scopeFields?: string[];
|
|
100
|
+
}
|
|
101
|
+
interface BitAfterValidateEvent<T extends object = any> {
|
|
102
|
+
values: Readonly<T>;
|
|
103
|
+
state: Readonly<BitState<T>>;
|
|
104
|
+
scope?: string;
|
|
105
|
+
scopeFields?: string[];
|
|
106
|
+
errors: BitErrors<T>;
|
|
107
|
+
result: boolean;
|
|
108
|
+
aborted?: boolean;
|
|
109
|
+
}
|
|
110
|
+
interface BitBeforeSubmitEvent<T extends object = any> {
|
|
111
|
+
values: Readonly<T>;
|
|
112
|
+
dirtyValues: Readonly<Partial<T>>;
|
|
113
|
+
state: Readonly<BitState<T>>;
|
|
114
|
+
}
|
|
115
|
+
interface BitAfterSubmitEvent<T extends object = any> {
|
|
116
|
+
values: Readonly<T>;
|
|
117
|
+
dirtyValues: Readonly<Partial<T>>;
|
|
118
|
+
state: Readonly<BitState<T>>;
|
|
119
|
+
success: boolean;
|
|
120
|
+
error?: unknown;
|
|
121
|
+
invalid?: boolean;
|
|
122
|
+
}
|
|
123
|
+
interface BitPluginErrorEvent<T extends object = any> {
|
|
124
|
+
source: BitPluginHookSource;
|
|
125
|
+
pluginName?: string;
|
|
126
|
+
error: unknown;
|
|
127
|
+
event?: unknown;
|
|
128
|
+
values: Readonly<T>;
|
|
129
|
+
state: Readonly<BitState<T>>;
|
|
130
|
+
}
|
|
131
|
+
interface BitPluginContext<T extends object = any> {
|
|
132
|
+
storeId: string;
|
|
133
|
+
getState: () => Readonly<BitState<T>>;
|
|
134
|
+
getConfig: () => Readonly<BitConfig<T>>;
|
|
135
|
+
}
|
|
136
|
+
interface BitPluginHooks<T extends object = any> {
|
|
137
|
+
beforeValidate?: (event: BitBeforeValidateEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
138
|
+
afterValidate?: (event: BitAfterValidateEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
139
|
+
beforeSubmit?: (event: BitBeforeSubmitEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
140
|
+
afterSubmit?: (event: BitAfterSubmitEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
141
|
+
onFieldChange?: (event: BitFieldChangeEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
142
|
+
onError?: (event: BitPluginErrorEvent<T>, context: BitPluginContext<T>) => BitMaybePromise<void>;
|
|
143
|
+
}
|
|
144
|
+
interface BitPlugin<T extends object = any> {
|
|
145
|
+
name: string;
|
|
146
|
+
setup?: (context: BitPluginContext<T>) => void | (() => void);
|
|
147
|
+
hooks?: BitPluginHooks<T>;
|
|
148
|
+
}
|
|
149
|
+
type BitMaybePromise<T> = T | Promise<T>;
|
|
150
|
+
interface BitPersistStorageAdapter {
|
|
151
|
+
getItem(key: string): BitMaybePromise<string | null>;
|
|
152
|
+
setItem(key: string, value: string): BitMaybePromise<void>;
|
|
153
|
+
removeItem(key: string): BitMaybePromise<void>;
|
|
154
|
+
}
|
|
155
|
+
type BitPersistMode = "values" | "dirtyValues";
|
|
156
|
+
interface BitPersistConfig<T extends object = any> {
|
|
157
|
+
enabled?: boolean;
|
|
158
|
+
key?: string;
|
|
159
|
+
storage?: BitPersistStorageAdapter;
|
|
160
|
+
autoSave?: boolean;
|
|
161
|
+
debounceMs?: number;
|
|
162
|
+
mode?: BitPersistMode;
|
|
163
|
+
serialize?: (payload: unknown) => string;
|
|
164
|
+
deserialize?: (raw: string) => Partial<T>;
|
|
165
|
+
onError?: (error: unknown) => void;
|
|
166
|
+
}
|
|
167
|
+
interface BitPersistResolvedConfig<T extends object = any> {
|
|
168
|
+
enabled: boolean;
|
|
169
|
+
key: string;
|
|
170
|
+
storage?: BitPersistStorageAdapter;
|
|
171
|
+
autoSave: boolean;
|
|
172
|
+
debounceMs: number;
|
|
173
|
+
mode: BitPersistMode;
|
|
174
|
+
serialize: (payload: unknown) => string;
|
|
175
|
+
deserialize: (raw: string) => Partial<T>;
|
|
176
|
+
onError?: (error: unknown) => void;
|
|
177
|
+
}
|
|
77
178
|
/** Validation config. */
|
|
78
179
|
interface BitValidationConfig<T> {
|
|
79
180
|
resolver?: ValidatorFn<T>;
|
|
@@ -100,9 +201,10 @@ interface BitConfig<T extends object = any> {
|
|
|
100
201
|
history?: BitHistoryConfig;
|
|
101
202
|
/** DevTools */
|
|
102
203
|
devTools?: boolean | DevToolsOptions;
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
204
|
+
/** Persistência local de rascunho */
|
|
205
|
+
persist?: BitPersistConfig<T>;
|
|
206
|
+
/** Plugins de lifecycle (observabilidade) */
|
|
207
|
+
plugins?: BitPlugin<T>[];
|
|
106
208
|
}
|
|
107
209
|
/** Return type of BitStore.getStepStatus, used by useBitScope/injectBitScope. */
|
|
108
210
|
interface ScopeStatus {
|
|
@@ -141,4 +243,4 @@ declare global {
|
|
|
141
243
|
}
|
|
142
244
|
declare const bitBus: BitFormGlobal;
|
|
143
245
|
|
|
144
|
-
export { type BitConfig as B, type CurrencyMaskConfig as C, type DateMaskConfig as D, type PatternMaskOptions as P, type ScopeStatus as S, type ValidateScopeResult as V, type BitMask as a, type
|
|
246
|
+
export { type BitTransformFn as A, type BitConfig as B, type CurrencyMaskConfig as C, type DateMaskConfig as D, type BitValidationConfig as E, type DeepPartial as F, type ValidatorFn as G, bitBus as H, type DevToolsOptions as I, type BitPersistResolvedConfig as J, type PatternMaskOptions as P, type ScopeStatus as S, type ValidateScopeResult as V, type BitMask as a, type BitAfterSubmitEvent as b, type BitAfterValidateEvent as c, type BitArrayItem as d, type BitArrayPath as e, type BitBeforeSubmitEvent as f, type BitBeforeValidateEvent as g, type BitComputedFn as h, type BitErrors as i, type BitFieldChangeEvent as j, type BitFieldChangeMeta as k, type BitFieldConditional as l, type BitFieldDefinition as m, type BitFieldValidation as n, type BitHistoryConfig as o, type BitPath as p, type BitPathValue as q, type BitPersistConfig as r, type BitPersistMode as s, type BitPersistStorageAdapter as t, type BitPlugin as u, type BitPluginContext as v, type BitPluginErrorEvent as w, type BitPluginHooks as x, type BitState as y, type BitTouched as z };
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8;var j=typeof globalThis<"u"?globalThis:typeof global<"u"?global:window;j.__BIT_FORM__||(j.__BIT_FORM__={stores:{},listeners:new Set,dispatch(o,t){this.listeners.forEach(e=>e(o,t))},subscribe(o){return this.listeners.add(o),()=>{this.listeners.delete(o)}}});var m=j.__BIT_FORM__;function f(o){if(o===null||typeof o!="object")return o;if(o instanceof Date)return new Date(o.getTime());if(o instanceof RegExp)return new RegExp(o.source,o.flags);if(Array.isArray(o))return o.map(e=>f(e));let t={};for(let e in o)Object.prototype.hasOwnProperty.call(o,e)&&(t[e]=f(o[e]));return t}function S(o,t){return o===t?!0:o===null||typeof o!="object"||t===null||typeof t!="object"?!1:T(o,t)}function T(o,t){if(o===t)return!0;if(o===null||typeof o!="object"||t===null||typeof t!="object")return!1;if(o instanceof Date&&t instanceof Date)return o.getTime()===t.getTime();if(o instanceof RegExp&&t instanceof RegExp)return o.toString()===t.toString();let e=Object.keys(o),s=Object.keys(t);if(e.length!==s.length)return!1;for(let r of e)if(!Object.prototype.hasOwnProperty.call(t,r)||!T(o[r],t[r]))return!1;return!0}function z(o,t,e="",s=new Set){if(S(o,t))return s;if(o===null||typeof o!="object"||t===null||typeof t!="object")return e&&s.add(e),s;if(Array.isArray(o)||Array.isArray(t))return!S(o,t)&&e&&s.add(e),s;let r=new Set([...Object.keys(o||{}),...Object.keys(t||{})]);for(let i of r){let n=e?`${e}.${i}`:i;z(_optionalChain([o, 'optionalAccess', _2 => _2[i]]),_optionalChain([t, 'optionalAccess', _3 => _3[i]]),n,s)}return s}var B=new Map;function g(o,t){if(!t)return o;let e=B.get(t)||t.split(".");B.has(t)||B.set(t,e);let s=o;for(let r of e){if(s==null)return;s=s[r]}return s}function y(o,t,e){if(!t)return e;let s=B.get(t)||t.split(".");B.has(t)||B.set(t,s);let r=Array.isArray(o)?[...o]:{...o},i=r;for(let n=0;n<s.length-1;n++){let l=s[n],a=s[n+1],d=/^\d+$/.test(a),c=i[l];c==null?i[l]=d?[]:{}:i[l]=Array.isArray(c)?[...c]:{...c},i=i[l]}return i[s[s.length-1]]=e,r}function Ct(o,t){let e={},s=`${t}.`;for(let r in o)r!==t&&!r.startsWith(s)&&(e[r]=o[r]);return e}var _=(o,t,e)=>{let s={},r=`${t}.`;return Object.keys(o).forEach(i=>{if(!i.startsWith(r)){s[i]=o[i];return}let l=i.substring(r.length).split("."),a=parseInt(l[0],10),d=l.slice(1).join(".");if(a!==e)if(a>e){let c=a-1,u=d?`${r}${c}.${d}`:`${r}${c}`;s[u]=o[i]}else s[i]=o[i]}),s},X=(o,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(o).forEach(n=>{if(!n.startsWith(i)){r[n]=o[n];return}let a=n.substring(i.length).split("."),d=parseInt(a[0],10),c=a.slice(1).join(".");if(d===e){let u=c?`${i}${s}.${c}`:`${i}${s}`;r[u]=o[n]}else if(d===s){let u=c?`${i}${e}.${c}`:`${i}${e}`;r[u]=o[n]}else r[n]=o[n]}),r},W=(o,t,e,s)=>{let r={},i=`${t}.`;return Object.keys(o).forEach(n=>{if(!n.startsWith(i)){r[n]=o[n];return}let a=n.substring(i.length).split("."),d=parseInt(a[0],10),c=a.slice(1).join("."),u=d;d===e?u=s:e<s&&d>e&&d<=s?u=d-1:e>s&&d>=s&&d<e&&(u=d+1);let h=c?`${i}${u}.${c}`:`${i}${u}`;r[h]=o[n]}),r};function St(o){if(typeof o!="object"||o===null||Array.isArray(o))return!1;let t=_nullishCoalesce(o.errors, () => (o));return typeof t!="object"||t===null||Array.isArray(t)?!1:Object.values(t).every(e=>typeof e=="string"||Array.isArray(e)&&e.every(s=>typeof s=="string"))}function wt(o){return St(o)?_nullishCoalesce(o.errors, () => (o)):{}}var Tt={"#":/\d/,A:/[a-zA-Z]/,X:/[a-zA-Z0-9]/,H:/[0-9a-fA-F]/,U:/[A-Z]/,L:/[a-z]/,"*":/./},E= exports.j =(o,t)=>{if(o==null||o==="")return"";let e=String(o),s=e.startsWith("-"),r=t?t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):"",i=new RegExp(`[^a-zA-Z0-9${r}]`,"g"),n=e.replace(i,"");return s&&n&&!n.startsWith("-")?`-${n}`:n},xt= exports.k =(o,t=2)=>{if(typeof o=="number")return o;if(!o)return 0;let e=String(o),s=e.includes("-"),r=e.replace(/\D/g,"");if(!r)return 0;let i=parseInt(r,10)/Math.pow(10,t);return s?-i:i},p= exports.l =(o,t)=>{let e=s=>s.split("").filter(r=>Tt[r]).length;return{format:s=>{let r=E(s,_optionalChain([t, 'optionalAccess', _4 => _4.allowChars]));if(!r&&!_optionalChain([t, 'optionalAccess', _5 => _5.guide]))return"";let n=[...Array.isArray(o)?o:[o]].sort((h,v)=>e(h)-e(v)),l=n[n.length-1];for(let h of n)if(r.length<=e(h)){l=h;break}let a="",d=0,c=_optionalChain([t, 'optionalAccess', _6 => _6.guide])||!1,u=_optionalChain([t, 'optionalAccess', _7 => _7.placeholderChar])||"_";for(let h=0;h<l.length;h++){let v=l[h],k=Tt[v];if(d<r.length){let x=r[d];if(k)if(v==="U"&&(x=x.toUpperCase()),v==="L"&&(x=x.toLowerCase()),k.test(x))a+=x,d++;else if(c)a+=u;else break;else a+=v,x===v&&d++}else if(c)a+=k?u:v;else break}return a},parse:s=>{if(_optionalChain([t, 'optionalAccess', _8 => _8.customParse]))return t.customParse(s);let i=p(o,t).format(s);if(_optionalChain([t, 'optionalAccess', _9 => _9.saveRaw])){if(_optionalChain([t, 'optionalAccess', _10 => _10.guide])){let l=(t.placeholderChar||"_").replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(l,"g");return i.replace(a,"")}return i}return E(i,_optionalChain([t, 'optionalAccess', _11 => _11.allowChars]))}}},b= exports.m =({prefix:o="",suffix:t="",thousand:e,decimal:s,precision:r=2,allowNegative:i=!0,saveRaw:n=!1})=>{let l=a=>{if(a==null||a==="")return"";let d="";if(typeof a=="number"?d=Math.abs(a).toFixed(r).replace(/\D/g,""):d=String(a).replace(/\D/g,""),!d&&String(a).includes("-")&&i)return"-";if(!d)return"";d=d.padStart(r+1,"0");let c=d.slice(0,-r).replace(/^0+(?=\d)/,"")||"0",u=d.slice(-r),h=c.replace(/\B(?=(\d{3})+(?!\d))/g,e);return`${(typeof a=="number"?a<0:String(a).includes("-"))&&i?"-":""}${o}${h}${s}${u}${t}`};return{format:l,parse:a=>{let d=xt(a,r),c=i?d:Math.abs(d);return n?l(c):c}}},Y= exports.n =o=>{let t=e=>/^3[47]/.test(e)?"#### ###### #####":/^3(?:0[0-5]|[68])/.test(e)?"#### ###### ####":"#### #### #### ####";return{format:e=>{let s=E(e,_optionalChain([o, 'optionalAccess', _12 => _12.allowChars])),r=t(s);return p(r,o).format(e)},parse:e=>{let s=E(e,_optionalChain([o, 'optionalAccess', _13 => _13.allowChars])),r=t(s);return p(r,o).parse(e)}}},V= exports.o =o=>{let e=(_optionalChain([o, 'optionalAccess', _14 => _14.format])||"DD/MM/YYYY")==="YYYY-MM-DD",s=p(e?"####-##-##":"##/##/####",o);return{format:r=>{let i=E(r);if(!i)return"";let n="",l="",a="";if(e?(a=i.substring(0,4),l=i.substring(4,6),n=i.substring(6,8)):(n=i.substring(0,2),l=i.substring(2,4),a=i.substring(4,8)),n.length===2){let c=parseInt(n,10);c>31&&(n="31"),c===0&&(n="01")}if(l.length===2){let c=parseInt(l,10);c>12&&(l="12"),c===0&&(l="01")}let d=e?`${a}${l}${n}`:`${n}${l}${a}`;return s.format(d)},parse:r=>s.parse(r)}};var J=b({prefix:"R$ ",thousand:".",decimal:",",precision:2}),K= exports.q =b({prefix:"$",thousand:",",decimal:".",precision:2}),G= exports.r =b({suffix:" \u20AC",thousand:".",decimal:",",precision:2}),Z= exports.s =b({prefix:"\xA3",thousand:",",decimal:".",precision:2}),Q= exports.t =b({prefix:"\xA5",thousand:",",decimal:".",precision:0}),tt= exports.u =b({suffix:"%",thousand:".",decimal:",",precision:1}),et= exports.v =b({thousand:".",decimal:",",precision:2}),st= exports.w =b({thousand:".",decimal:",",precision:0}),rt= exports.x =p("###.###.###-##"),it= exports.y =p("##.###.###/####-##"),ot= exports.z =p(["(##) ####-####","(##) #####-####"]),nt= exports.A =p("(##) ####-####"),at= exports.B =p("#####-###"),lt= exports.C =V({format:"DD/MM/YYYY",guide:!0,customParse:o=>{let t=o.replace(/_/g,""),e=t.split("/");return e.length===3&&e[2].length===4?`${e[2]}-${e[1]}-${e[0]}`:t.replace(/\D/g,"")}}),dt= exports.D =p("##:##"),ct= exports.E =p("###########"),ut= exports.F =p("##.###.###-X"),Ft= exports.G =p("(###) ###-####"),Dt= exports.H =p("#####-####"),It= exports.I =p("##/##/####"),At= exports.J =p("###-##-####"),gt= exports.K =Y(),pt= exports.L =p("####"),Rt= exports.M =V({format:"YYYY-MM-DD",saveRaw:!0,guide:!0}),ft= exports.N =p("HH:HH:HH:HH:HH:HH"),ht= exports.O =p("#HHHHHH"),mt= exports.P =p("###.###.###.###"),yt= exports.Q =p("HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH:HHHH"),Ht= exports.R =p("UU## XXXX XXXX XXXX XXXX XXXX XXXX XXXX XX",{allowChars:" "});var bt={brl:J,usd:K,eur:G,gbp:Z,jpy:Q,cpf:rt,cnpj:it,rg:ut,cep:at,cnh:ct,phone:ot,landline:nt,date:lt,time:dt,ip:mt,ipv6:yt,mac:ft,color:ht,cc:gt,cvv:pt,percent:tt,decimal:et,int:st};function Bt(o={}){let t=_nullishCoalesce(o.initialValues, () => ({})),e=o.validation,s=o.history,r=o.name?`bit-form:${o.name}:draft`:"bit-form:draft",i={enabled:_nullishCoalesce(_optionalChain([o, 'access', _15 => _15.persist, 'optionalAccess', _16 => _16.enabled]), () => (!1)),key:_nullishCoalesce(_optionalChain([o, 'access', _17 => _17.persist, 'optionalAccess', _18 => _18.key]), () => (r)),storage:_optionalChain([o, 'access', _19 => _19.persist, 'optionalAccess', _20 => _20.storage]),autoSave:_nullishCoalesce(_optionalChain([o, 'access', _21 => _21.persist, 'optionalAccess', _22 => _22.autoSave]), () => (!0)),debounceMs:_nullishCoalesce(_optionalChain([o, 'access', _23 => _23.persist, 'optionalAccess', _24 => _24.debounceMs]), () => (300)),mode:_nullishCoalesce(_optionalChain([o, 'access', _25 => _25.persist, 'optionalAccess', _26 => _26.mode]), () => ("values")),serialize:_nullishCoalesce(_optionalChain([o, 'access', _27 => _27.persist, 'optionalAccess', _28 => _28.serialize]), () => (JSON.stringify)),deserialize:_nullishCoalesce(_optionalChain([o, 'access', _29 => _29.persist, 'optionalAccess', _30 => _30.deserialize]), () => ((n=>JSON.parse(n)))),onError:_optionalChain([o, 'access', _31 => _31.persist, 'optionalAccess', _32 => _32.onError])};return{name:o.name,initialValues:f(t),resolver:_optionalChain([e, 'optionalAccess', _33 => _33.resolver]),validationDelay:_nullishCoalesce(_optionalChain([e, 'optionalAccess', _34 => _34.delay]), () => (300)),enableHistory:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _35 => _35.enabled]), () => (!1)),historyLimit:_nullishCoalesce(_optionalChain([s, 'optionalAccess', _36 => _36.limit]), () => (15)),masks:{...bt},fields:o.fields,devTools:o.devTools,persist:i,plugins:_nullishCoalesce(o.plugins, () => ([]))}}var P= (_class =class{constructor() { _class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this); }__init() {this.fieldConfigs=new Map}__init2() {this.dependencies=new Map}__init3() {this.hiddenFields=new Set}register(t,e,s){this.fieldConfigs.set(t,e);let r=_optionalChain([e, 'access', _37 => _37.conditional, 'optionalAccess', _38 => _38.dependsOn]);r&&r.forEach(i=>{this.dependencies.has(i)||this.dependencies.set(i,new Set),this.dependencies.get(i).add(t)}),this.evaluateFieldCondition(t,s)}isHidden(t){return this.hiddenFields.has(t)}isRequired(t,e){let s=this.fieldConfigs.get(t);return!s||this.isHidden(t)?!1:!!_optionalChain([s, 'access', _39 => _39.conditional, 'optionalAccess', _40 => _40.requiredIf, 'optionalCall', _41 => _41(e)])}getRequiredErrors(t){let e={};return this.fieldConfigs.forEach((s,r)=>{if(this.isRequired(r,t)){let i=g(t,r);this.isEmpty(i)&&(e[r]=_nullishCoalesce(_optionalChain([s, 'access', _42 => _42.conditional, 'optionalAccess', _43 => _43.requiredMessage]), () => ("required field")))}}),e}evaluateAll(t){this.fieldConfigs.forEach((e,s)=>{this.evaluateFieldCondition(s,t)})}updateDependencies(t,e){let s=[],r=this.dependencies.get(t);return r&&r.forEach(i=>{let n=this.isHidden(i);this.evaluateFieldCondition(i,e);let l=this.isHidden(i);n!==l&&s.push(i)}),s}unregister(t){this.fieldConfigs.delete(t),this.hiddenFields.delete(t),this.dependencies.delete(t),this.dependencies.forEach(e=>{e.delete(t)})}unregisterPrefix(t){let e=[];this.fieldConfigs.forEach((s,r)=>{r.startsWith(t)&&e.push(r)}),e.forEach(s=>this.unregister(s))}evaluateFieldCondition(t,e){let r=_optionalChain([this, 'access', _44 => _44.fieldConfigs, 'access', _45 => _45.get, 'call', _46 => _46(t), 'optionalAccess', _47 => _47.conditional, 'optionalAccess', _48 => _48.showIf]);r&&(r(e)?this.hiddenFields.delete(t):this.hiddenFields.add(t))}isEmpty(t){return t==null||typeof t=="string"&&t.trim()===""||Array.isArray(t)&&t.length===0}}, _class);var C= (_class2 =class{constructor(t,e=15){;_class2.prototype.__init4.call(this);_class2.prototype.__init5.call(this);this.enableHistory=t;this.maxHistory=e}__init4() {this.history=[]}__init5() {this.historyIndex=-1}saveSnapshot(t){if(!this.enableHistory)return;let e=this.history[this.historyIndex];e&&T(e,t)||(this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push(f(t)),this.history.length>this.maxHistory?this.history.shift():this.historyIndex++)}get canUndo(){return this.enableHistory?this.historyIndex>0:!1}get canRedo(){return this.enableHistory?this.historyIndex<this.history.length-1:!1}undo(){return this.canUndo?(this.historyIndex--,f(this.history[this.historyIndex])):null}redo(){return this.canRedo?(this.historyIndex++,f(this.history[this.historyIndex])):null}reset(t){this.history=[],this.historyIndex=-1,this.saveSnapshot(t)}getMetadata(){return{enabled:this.enableHistory,canUndo:this.canUndo,canRedo:this.canRedo,historyIndex:this.historyIndex,historySize:this.history.length}}}, _class2);var w=class{constructor(t){this.store=t}pushItem(t,e){let s=g(this.store.getState().values,t)||[];this.store.setFieldWithMeta(t,[...s,e],{origin:"array",operation:"push"}),this.store.internalSaveSnapshot()}prependItem(t,e){let s=g(this.store.getState().values,t)||[];this.store.setFieldWithMeta(t,[e,...s],{origin:"array",operation:"prepend"}),this.store.internalSaveSnapshot()}insertItem(t,e,s){let r=[...g(this.store.getState().values,t)||[]];r.splice(e,0,s),this.store.setFieldWithMeta(t,r,{origin:"array",operation:"insert",index:e}),this.store.internalSaveSnapshot()}removeItem(t,e){let s=this.store.getState(),r=g(s.values,t);if(!Array.isArray(r))return;let i=[...r];this.store.unregisterPrefix&&this.store.unregisterPrefix(`${t}.${e}.`);let n=r.filter((d,c)=>c!==e),l=y(s.values,t,n),a=this.store.dirtyMg.updateForPath(t,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:_(s.errors,t,e),touched:_(s.touched,t,e),isDirty:a}),this.store.emitFieldChange({path:t,previousValue:i,nextValue:n,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"remove",index:e}}),this.store.internalSaveSnapshot(),this.revalidate(t)}swapItems(t,e,s){let r=this.store.getState(),i=[...g(r.values,t)||[]],n=[...i];[i[e],i[s]]=[i[s],i[e]];let l=y(r.values,t,i),a=this.store.dirtyMg.updateForPath(t,l,this.store.getConfig().initialValues);this.store.internalUpdateState({values:l,errors:X(r.errors,t,e,s),touched:X(r.touched,t,e,s),isDirty:a}),this.store.emitFieldChange({path:t,previousValue:n,nextValue:i,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"swap",from:e,to:s}}),this.store.internalSaveSnapshot(),this.revalidate(t)}moveItem(t,e,s){let r=this.store.getState(),i=[...g(r.values,t)||[]],n=[...i],[l]=i.splice(e,1);i.splice(s,0,l);let a=y(r.values,t,i),d=this.store.dirtyMg.updateForPath(t,a,this.store.getConfig().initialValues);this.store.internalUpdateState({values:a,errors:W(r.errors,t,e,s),touched:W(r.touched,t,e,s),isDirty:d}),this.store.emitFieldChange({path:t,previousValue:n,nextValue:i,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"array",operation:"move",from:e,to:s}}),this.store.internalSaveSnapshot(),this.revalidate(t)}revalidate(t){let e=this.store;typeof e.triggerValidation=="function"?e.triggerValidation([t]):typeof this.store.validate=="function"&&this.store.validate()}};var F=class{constructor(t){this.getComputedEntries=t}apply(t){let e=this.getComputedEntries();if(e.length===0)return t;let s=t;for(let r=0;r<2;r++){let i=!1;for(let[n,l]of e){let a=l(s),d=g(s,n);T(d,a)||(s=y(s,n,a),i=!0)}if(!i)break}return s}};var D= (_class3 =class{constructor(t){;_class3.prototype.__init6.call(this);_class3.prototype.__init7.call(this);_class3.prototype.__init8.call(this);_class3.prototype.__init9.call(this);this.store=t}__init6() {this.currentValidationId=0}__init7() {this.asyncTimers={}}__init8() {this.asyncRequests={}}__init9() {this.asyncErrors={}}updateFieldValidating(t,e){this.store.internalUpdateState({isValidating:{...this.store.getState().isValidating,[t]:e}})}cancelFieldAsync(t){this.asyncTimers[t]&&(clearTimeout(this.asyncTimers[t]),delete this.asyncTimers[t]),this.asyncRequests[t]=(this.asyncRequests[t]||0)+1}beginExternalValidation(t){this.cancelFieldAsync(t),this.updateFieldValidating(t,!0)}endExternalValidation(t){this.updateFieldValidating(t,!1)}async setExternalError(t,e){if(e){this.asyncErrors[t]=e,this.store.setError(t,e);return}if(delete this.asyncErrors[t],this.store.validate){await this.store.validate({scopeFields:[t]});return}let s={...this.store.getState().errors};delete s[t],this.store.internalUpdateState({errors:s,isValid:Object.keys(s).length===0})}handleAsync(t,e){let s=this.store.getFieldConfig(t),r=_optionalChain([s, 'optionalAccess', _49 => _49.validation, 'optionalAccess', _50 => _50.asyncValidate]);if(!r){this.updateFieldValidating(t,!1);return}this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]);let i=_nullishCoalesce(_optionalChain([s, 'access', _51 => _51.validation, 'optionalAccess', _52 => _52.asyncValidateDelay]), () => (500));this.updateFieldValidating(t,!0),this.asyncTimers[t]=setTimeout(async()=>{delete this.asyncTimers[t];let n=(this.asyncRequests[t]||0)+1;this.asyncRequests[t]=n;try{let l=await r(e,this.store.getState().values);if(this.asyncRequests[t]!==n)return;if(l)this.asyncErrors[t]=l,this.store.setError(t,l);else if(delete this.asyncErrors[t],this.store.validate)await this.store.validate({scopeFields:[t]});else{let a={...this.store.getState().errors};delete a[t],this.store.internalUpdateState({errors:a,isValid:Object.keys(a).length===0})}}finally{this.asyncRequests[t]===n&&this.updateFieldValidating(t,!1)}},i)}hasValidationsInProgress(t){let e=this.store.getState();return t&&t.length>0?t.some(s=>!!e.isValidating[s]):Object.values(e.isValidating).some(Boolean)}trigger(t){this.validationTimeout&&clearTimeout(this.validationTimeout);let e=_nullishCoalesce(this.store.config.validationDelay, () => (300));e>0?this.validationTimeout=setTimeout(()=>{this.validate({scopeFields:t})},e):this.validate({scopeFields:t})}async validate(t){let e=++this.currentValidationId,s=this.store.getState(),r=_optionalChain([t, 'optionalAccess', _53 => _53.scopeFields]);if(_optionalChain([t, 'optionalAccess', _54 => _54.scope])){let a=this.store.getScopeFields(t.scope);a.length>0&&(r=a)}await this.store.emitBeforeValidate({values:s.values,state:s,scope:_optionalChain([t, 'optionalAccess', _55 => _55.scope]),scopeFields:r});let i=this.store.config.resolver?await this.store.config.resolver(s.values,{scopeFields:r}):{},n=this.store.depsMg.getRequiredErrors(s.values);if(i={...i,...n},this.store.depsMg.hiddenFields.forEach(a=>{delete i[a],delete this.asyncErrors[a]}),e!==this.currentValidationId)return await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:_optionalChain([t, 'optionalAccess', _56 => _56.scope]),scopeFields:r,errors:this.store.getState().errors,result:s.isValid,aborted:!0}),s.isValid;if(r){let a={...s.errors};r.forEach(u=>{i[u]?a[u]=i[u]:this.asyncErrors[u]?a[u]=this.asyncErrors[u]:delete a[u]});let d=Object.keys(a).length===0;this.store.internalUpdateState({errors:a,isValid:d});let c=r.every(u=>!i[u]&&!this.asyncErrors[u]);return await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:_optionalChain([t, 'optionalAccess', _57 => _57.scope]),scopeFields:r,errors:a,result:c}),c}i={...this.asyncErrors,...i};let l=Object.keys(i).length===0;return this.store.internalUpdateState({errors:i,isValid:l}),await this.store.emitAfterValidate({values:this.store.getState().values,state:this.store.getState(),scope:_optionalChain([t, 'optionalAccess', _58 => _58.scope]),scopeFields:r,errors:i,result:l}),l}clear(t){this.asyncTimers[t]&&clearTimeout(this.asyncTimers[t]),delete this.asyncTimers[t],this.updateFieldValidating(t,!1),delete this.asyncErrors[t]}cancelAll(){this.validationTimeout&&clearTimeout(this.validationTimeout),Object.values(this.asyncTimers).forEach(t=>clearTimeout(t)),this.asyncTimers={},this.store.internalUpdateState({isValidating:{}})}}, _class3);var I=class{constructor(t){this.store=t}updateField(t,e,s={origin:"setField"}){let r=this.store.getState(),i=g(r.values,t),n=y(r.values,t,e),l={...r.errors};delete l[t],this.store.validatorMg.clear(t);let a=this.store.depsMg.updateDependencies(t,n);a.forEach(c=>{this.store.depsMg.isHidden(c)&&(delete l[c],this.store.validatorMg.clear(c))});let d=this.store.dirtyMg.updateForPath(t,n,this.store.config.initialValues);return this.store.internalUpdateState({values:n,errors:l,isValid:Object.keys(l).length===0,isDirty:d}),this.store.emitFieldChange({path:t,previousValue:i,nextValue:e,values:this.store.getState().values,state:this.store.getState(),meta:s}),this.store.config.resolver&&this.store.validatorMg.trigger([t]),this.store.validatorMg.handleAsync(t,e),{visibilitiesChanged:a.length>0}}updateAll(t){let e=this.store.getState().values,s=f(t);this.store.config.initialValues=f(s),this.store.validatorMg.cancelAll(),this.store.depsMg.evaluateAll(s),this.store.dirtyMg.clear(),this.store.internalUpdateState({values:s,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.internalSaveSnapshot(),this.store.validatorMg.validate(),this.store.emitFieldChange({path:"*",previousValue:e,nextValue:s,values:this.store.getState().values,state:this.store.getState(),meta:{origin:"setValues"}})}async submit(t){if(this.store.getState().isSubmitting||this.store.validatorMg.hasValidationsInProgress())return;if(this.store.validatorMg.cancelAll(),this.store.internalUpdateState({isSubmitting:!0}),await this.store.validatorMg.validate())try{let r=f(this.store.getState().values);this.store.depsMg.hiddenFields.forEach(n=>{r=y(r,n,void 0)});for(let[n,l]of this.store.getTransformEntries()){let a=g(r,n);r=y(r,n,l(a,this.store.getState().values))}let i=this.store.dirtyMg.buildDirtyValues(r);await this.store.emitBeforeSubmit({values:r,dirtyValues:i,state:this.store.getState()}),await t(r,i),await this.store.emitAfterSubmit({values:r,dirtyValues:i,state:this.store.getState(),success:!0})}catch(r){await this.store.emitOperationalError({source:"submit",error:r}),await this.store.emitAfterSubmit({values:this.store.getState().values,dirtyValues:this.store.dirtyMg.buildDirtyValues(this.store.getState().values),state:this.store.getState(),success:!1,error:r}),console.error(r)}else{let r=this.store.getState().errors,i={...this.store.getState().touched};Object.keys(r).forEach(n=>{i[n]=!0}),this.store.internalUpdateState({touched:i}),await this.store.emitAfterSubmit({values:this.store.getState().values,dirtyValues:this.store.dirtyMg.buildDirtyValues(this.store.getState().values),state:this.store.getState(),success:!1,invalid:!0})}this.store.internalUpdateState({isSubmitting:!1})}reset(){this.store.validatorMg.cancelAll();let t=f(this.store.config.initialValues);this.store.depsMg.evaluateAll(t),this.store.dirtyMg.clear(),this.store.internalUpdateState({values:t,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:!1,isSubmitting:!1}),this.store.historyMg.reset(t)}};function Et(){return`
|
|
2
|
+
.bit-devtools-container {
|
|
3
|
+
position: fixed;
|
|
4
|
+
bottom: 20px;
|
|
5
|
+
right: 20px;
|
|
6
|
+
z-index: 9999;
|
|
7
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
8
|
+
display: flex;
|
|
9
|
+
flex-direction: column;
|
|
10
|
+
align-items: flex-end;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
.bit-devtools-trigger {
|
|
14
|
+
background: #10b981;
|
|
15
|
+
color: #fff;
|
|
16
|
+
border: none;
|
|
17
|
+
border-radius: 50%;
|
|
18
|
+
width: 48px;
|
|
19
|
+
height: 48px;
|
|
20
|
+
cursor: pointer;
|
|
21
|
+
box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
|
|
22
|
+
font-weight: bold;
|
|
23
|
+
display: flex;
|
|
24
|
+
align-items: center;
|
|
25
|
+
justify-content: center;
|
|
26
|
+
transition: transform 0.2s;
|
|
27
|
+
font-size: 16px;
|
|
28
|
+
margin-top: 16px;
|
|
29
|
+
}
|
|
30
|
+
.bit-devtools-trigger:hover { transform: scale(1.05); }
|
|
31
|
+
|
|
32
|
+
.bit-devtools-panel {
|
|
33
|
+
width: 450px;
|
|
34
|
+
max-height: 80vh;
|
|
35
|
+
background: #0f172a;
|
|
36
|
+
color: #f8fafc;
|
|
37
|
+
border-radius: 8px;
|
|
38
|
+
padding: 16px;
|
|
39
|
+
overflow-y: auto;
|
|
40
|
+
box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5), 0 8px 10px -6px rgba(0,0,0,0.5);
|
|
41
|
+
border: 1px solid #334155;
|
|
42
|
+
display: flex;
|
|
43
|
+
flex-direction: column;
|
|
44
|
+
gap: 16px;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
.bit-devtools-header {
|
|
48
|
+
display: flex;
|
|
49
|
+
justify-content: space-between;
|
|
50
|
+
align-items: center;
|
|
51
|
+
padding-bottom: 12px;
|
|
52
|
+
border-bottom: 1px solid #1e293b;
|
|
53
|
+
}
|
|
54
|
+
.bit-devtools-header h2 { margin: 0; font-size: 16px; display: flex; align-items: center; gap: 8px; }
|
|
55
|
+
|
|
56
|
+
.bit-store-block {
|
|
57
|
+
background: #1e293b;
|
|
58
|
+
border-radius: 6px;
|
|
59
|
+
padding: 12px;
|
|
60
|
+
border: 1px solid #334155;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
.bit-store-header {
|
|
64
|
+
display: flex;
|
|
65
|
+
justify-content: space-between;
|
|
66
|
+
align-items: center;
|
|
67
|
+
margin-bottom: 12px;
|
|
68
|
+
}
|
|
69
|
+
.bit-store-title { margin: 0; color: #38bdf8; font-size: 14px; font-weight: bold; }
|
|
70
|
+
|
|
71
|
+
.bit-badge-group { display: flex; gap: 6px; flex-wrap: wrap; }
|
|
72
|
+
.bit-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: bold; }
|
|
73
|
+
.badge-success { background: rgba(16, 185, 129, 0.2); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.2); }
|
|
74
|
+
.badge-error { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.2); }
|
|
75
|
+
.badge-warn { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.2); }
|
|
76
|
+
.badge-info { background: rgba(56, 189, 248, 0.2); color: #7dd3fc; border: 1px solid rgba(56, 189, 248, 0.2); }
|
|
77
|
+
|
|
78
|
+
.bit-section-title { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin: 12px 0 4px 0; display: block; }
|
|
79
|
+
|
|
80
|
+
.bit-controls { display: flex; gap: 6px; margin-bottom: 12px; background: #0f172a; padding: 8px; border-radius: 6px; }
|
|
81
|
+
.bit-action-btn { flex: 1; background: #334155; color: #e2e8f0; border: 1px solid #475569; padding: 6px 0; border-radius: 4px; cursor: pointer; font-size: 11px; display: flex; align-items: center; justify-content: center; gap: 4px; transition: all 0.2s; }
|
|
82
|
+
.bit-action-btn:hover:not(:disabled) { background: #475569; }
|
|
83
|
+
.bit-action-btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
84
|
+
.bit-btn-reset { color: #fca5a5; border-color: rgba(239,68,68,0.3); }
|
|
85
|
+
.bit-btn-reset:hover { background: rgba(239,68,68,0.1) !important; }
|
|
86
|
+
|
|
87
|
+
pre.bit-pre { background: #020617; padding: 10px; border-radius: 4px; font-size: 11px; overflow-x: auto; border: 1px solid #1e293b; margin: 0; color: #e2e8f0; }
|
|
88
|
+
pre.bit-error-box { background: rgba(239, 68, 68, 0.05); padding: 10px; border-radius: 4px; font-size: 11px; border: 1px dashed #ef4444; color: #fca5a5; margin: 0; overflow-x: auto; }
|
|
89
|
+
`}var M= (_class4 =class{__init10() {this.currentStoresState={}}__init11() {this.isOpen=!1}constructor(t,e){;_class4.prototype.__init10.call(this);_class4.prototype.__init11.call(this);if(this.container=t,this.actions=e,!document.getElementById("bit-devtools-styles")){let s=document.createElement("style");s.id="bit-devtools-styles",s.textContent=Et(),document.head.appendChild(s)}this.rootElement=document.createElement("div"),this.rootElement.className="bit-devtools-container",this.container.appendChild(this.rootElement),this.rootElement.addEventListener("click",s=>{let r=s.target;if(r.closest(".bit-devtools-trigger")){this.isOpen=!this.isOpen,this.render();return}let i=r.closest(".bit-action-btn");if(i&&!i.hasAttribute("disabled")){let n=i.getAttribute("data-action"),l=i.getAttribute("data-store");n&&l&&(n==="undo"&&this.actions.onUndo(l),n==="redo"&&this.actions.onRedo(l),n==="reset"&&this.actions.onReset(l))}})}updateState(t){this.currentStoresState=t,this.render()}render(){let t=Object.entries(this.currentStoresState);if(t.length===0){this.rootElement.innerHTML="";return}let e="";if(this.isOpen){e=`
|
|
90
|
+
<div class="bit-devtools-panel">
|
|
91
|
+
<div class="bit-devtools-header">
|
|
92
|
+
<h2><span style="font-size: 20px;">\u{1F6E0}</span> Bit-Form DevTools</h2>
|
|
93
|
+
<span style="font-size: 11px; color: #64748b;">v1.0.0</span>
|
|
94
|
+
</div>
|
|
95
|
+
`;for(let[r,i]of t){let n=Object.keys(i.errors||{}).length>0,l=i._meta||{totalSteps:0,currentIndex:-1,canUndo:!1,canRedo:!1},a=l.currentIndex+1,d=l.totalSteps;e+=`
|
|
96
|
+
<div class="bit-store-block">
|
|
97
|
+
<div class="bit-store-header">
|
|
98
|
+
<h3 class="bit-store-title">${r}</h3>
|
|
99
|
+
<div class="bit-badge-group">
|
|
100
|
+
<span class="bit-badge ${i.isValid?"badge-success":"badge-error"}">
|
|
101
|
+
${i.isValid?"\u2713 Valid":"\u2715 Invalid"}
|
|
102
|
+
</span>
|
|
103
|
+
${i.isDirty?'<span class="bit-badge badge-warn">Dirty</span>':""}
|
|
104
|
+
${i.isSubmitting?'<span class="bit-badge badge-info">\u23F3 Submitting</span>':""}
|
|
105
|
+
</div>
|
|
106
|
+
</div>
|
|
107
|
+
|
|
108
|
+
<span class="bit-section-title">Time Travel (${a}/${d})</span>
|
|
109
|
+
|
|
110
|
+
<div class="bit-controls">
|
|
111
|
+
<button class="bit-action-btn" data-action="undo" data-store="${r}" ${l.canUndo?"":"disabled"}>
|
|
112
|
+
<span>\u21BA</span> Undo
|
|
113
|
+
</button>
|
|
114
|
+
<button class="bit-action-btn" data-action="redo" data-store="${r}" ${l.canRedo?"":"disabled"}>
|
|
115
|
+
<span>\u21BB</span> Redo
|
|
116
|
+
</button>
|
|
117
|
+
<button class="bit-action-btn bit-btn-reset" data-action="reset" data-store="${r}">
|
|
118
|
+
<span>\u{1F5D1}</span> Reset
|
|
119
|
+
</button>
|
|
120
|
+
</div>
|
|
121
|
+
`,n&&(e+=`
|
|
122
|
+
<span class="bit-section-title" style="color: #f87171;">\u26A0\uFE0F Validations Failing</span>
|
|
123
|
+
<pre class="bit-error-box">${JSON.stringify(i.errors,null,2)}</pre>
|
|
124
|
+
`),e+=`
|
|
125
|
+
<span class="bit-section-title">Values</span>
|
|
126
|
+
<pre class="bit-pre">${JSON.stringify(i.values,null,2)}</pre>
|
|
127
|
+
</div>
|
|
128
|
+
`}e+="</div>"}let s=`
|
|
129
|
+
<button class="bit-devtools-trigger" style="transform: ${this.isOpen?"scale(0.9)":"scale(1)"};" title="Abrir DevTools">
|
|
130
|
+
${this.isOpen?"\u2716":"Bit"}
|
|
131
|
+
</button>
|
|
132
|
+
`;this.rootElement.innerHTML=e+s}}, _class4);function Mt(o){let t=new M(o,{onUndo:r=>_optionalChain([m, 'access', _59 => _59.stores, 'access', _60 => _60[r], 'optionalAccess', _61 => _61.undo, 'call', _62 => _62()]),onRedo:r=>_optionalChain([m, 'access', _63 => _63.stores, 'access', _64 => _64[r], 'optionalAccess', _65 => _65.redo, 'call', _66 => _66()]),onReset:r=>_optionalChain([m, 'access', _67 => _67.stores, 'access', _68 => _68[r], 'optionalAccess', _69 => _69.reset, 'call', _70 => _70()])}),e=()=>{let r={};for(let[i,n]of Object.entries(m.stores)){let l=n,a=l.getState(),d=_optionalChain([l, 'optionalAccess', _71 => _71.getHistoryMetadata, 'optionalCall', _72 => _72()])||{enabled:!1,canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};r[i]={...a,_meta:{canUndo:d.canUndo,canRedo:d.canRedo,totalSteps:d.historySize,currentIndex:d.historyIndex}}}return r};t.updateState(e());let s=m.subscribe(()=>{t.updateState(e())});return{ui:t,destroy:()=>{s(),o.innerHTML=""}}}function kt(o,t="ws://localhost:3000"){let e=new WebSocket(t),s=new M(o,{onUndo:i=>r("ACTION",{storeId:i,action:"undo"}),onRedo:i=>r("ACTION",{storeId:i,action:"redo"}),onReset:i=>r("ACTION",{storeId:i,action:"reset"})}),r=(i,n)=>{e.readyState===WebSocket.OPEN?e.send(JSON.stringify({type:i,payload:n})):console.warn("[bit-form] Tentativa de envio falhou. WebSocket n\xE3o est\xE1 aberto.")};return e.addEventListener("open",()=>{console.log(`[bit-form] Conectado ao DevTools remoto em ${t}`)}),e.addEventListener("message",i=>{try{let n=JSON.parse(i.data);n.type==="STATE_UPDATE"&&s.updateState(n.payload)}catch(n){console.error("[bit-form] Erro ao processar mensagem do WebSocket:",n)}}),e.addEventListener("error",i=>{console.error("[bit-form] Erro na conex\xE3o do DevTools remoto:",i)}),s}function vt(o={}){let{mode:t="local",url:e}=o,s,r=!1;if(typeof o.container=="string"){let n=document.querySelector(o.container);if(!n)throw new Error(`[bit-form] Container '${o.container}' n\xE3o encontrado na p\xE1gina.`);s=n}else o.container instanceof HTMLElement?s=o.container:(s=document.createElement("div"),s.id="bit-form-devtools-root",s.style.position="fixed",s.style.bottom="20px",s.style.right="20px",s.style.zIndex="9999",s.style.maxHeight="80vh",s.style.overflowY="auto",s.style.boxShadow="0 10px 25px rgba(0,0,0,0.1)",document.body.appendChild(s),r=!0);let i;if(t==="local")console.log("[bit-form] DevTools iniciado em modo Local."),i=Mt(s);else if(t==="remote")console.log("[bit-form] DevTools iniciado em modo Remote."),i=kt(s,e);else throw new Error(`[bit-form] Modo DevTools inv\xE1lido: ${t}`);return{...i,destroy:()=>{i&&typeof i.destroy=="function"&&i.destroy(),r&&s.parentNode?s.parentNode.removeChild(s):s.innerHTML=""}}}var A= (_class5 =class{__init12() {this.cleanupFn=null}constructor(t){;_class5.prototype.__init12.call(this);this.store=t,this.setup()}setup(){let t=this.store.config.devTools;if(!t)return;let e=typeof t=="boolean"?{enabled:t,mode:"local"}:{enabled:!0,...t};if(e.enabled)if(e.mode==="remote"){let s=e.url||"ws://localhost:3000";this.cleanupFn=Vt(s)}else{let s=vt();s&&typeof s.destroy=="function"&&(this.cleanupFn=s.destroy)}}destroy(){this.cleanupFn&&this.cleanupFn()}}, _class5);var R= (_class6 =class{constructor() { _class6.prototype.__init13.call(this); }__init13() {this.dirtyPaths=new Set}updateForPath(t,e,s){for(let n of this.dirtyPaths)n.startsWith(t+".")&&this.dirtyPaths.delete(n);let r=g(e,t),i=g(s,t);return S(r,i)?this.dirtyPaths.delete(t):this.dirtyPaths.add(t),this.dirtyPaths.size>0}rebuild(t,e){return this.dirtyPaths=z(t,e),this.dirtyPaths.size>0}clear(){this.dirtyPaths.clear()}get isDirty(){return this.dirtyPaths.size>0}getDirtyPaths(){return this.dirtyPaths}buildDirtyValues(t){if(this.dirtyPaths.size===0)return{};let e={},s=new Set;for(let r of this.dirtyPaths){let i=r.match(/^(.+)\.(\d+)/);if(i){let n=i[1];if(s.has(n))continue;s.add(n),this.setNestedValue(e,n,this.getNestedValue(t,n))}else this.setNestedValue(e,r,this.getNestedValue(t,r))}return e}getNestedValue(t,e){let s=e.split("."),r=t;for(let i of s){if(r==null)return;r=r[i]}return r}setNestedValue(t,e,s){let r=e.split("."),i=t;for(let n=0;n<r.length-1;n++){let l=r[n];l in i||(i[l]={}),i=i[l]}i[r[r.length-1]]=s}}, _class6);var H=class{constructor(t,e,s){this.getState=t;this.getInitialValues=e;this.getScopeFields=s}getStepStatus(t){let e=this.getScopeFields(t),s=this.getState(),r=e.some(l=>!!s.errors[l]),i=e.some(l=>{let a=g(s.values,l),d=g(this.getInitialValues(),l);return!S(a,d)}),n=this.getStepErrors(t);return{hasErrors:r,isDirty:i,errors:n}}getStepErrors(t){let e=this.getScopeFields(t),s=this.getState(),r={};for(let i of e){let n=s.errors[i];n&&(r[i]=n)}return r}};var O=class{constructor(t,e,s){this.depsMg=t;this.getState=e;this.getConfig=s}isHidden(t){return this.depsMg.isHidden(t)}isRequired(t){return this.depsMg.isRequired(t,this.getState().values)}isFieldDirty(t){let e=g(this.getState().values,t),s=g(this.getConfig().initialValues,t);return!S(e,s)}isFieldValidating(t){return!!this.getState().isValidating[t]}};var $=class{constructor(t,e){this.getState=t;this.internalUpdateState=e}setError(t,e){let s={...this.getState().errors,[t]:e};e||delete s[t],this.internalUpdateState({errors:s})}setErrors(t){this.internalUpdateState({errors:{...this.getState().errors,...t}})}setServerErrors(t){let e={};for(let[s,r]of Object.entries(t))e[s]=Array.isArray(r)?r[0]:r;this.setErrors(e)}};function $t(){if(typeof globalThis>"u")return;let o=globalThis.localStorage;if(o)return{getItem:t=>o.getItem(t),setItem:(t,e)=>o.setItem(t,e),removeItem:t=>o.removeItem(t)}}var U=class{constructor(t,e,s,r){this.config=t;this.getValues=e;this.getDirtyValues=s;this.applyRestoredValues=r}getStorage(){return this.config.storage||$t()}canPersist(){return!!(this.config.enabled&&this.config.key&&this.getStorage())}handleError(t){_optionalChain([this, 'access', _73 => _73.config, 'access', _74 => _74.onError, 'optionalCall', _75 => _75(t)])}async saveNow(){if(!this.canPersist())return;let t=this.getStorage();if(t)try{let e=this.config.mode==="dirtyValues"?this.getDirtyValues():this.getValues(),s=this.config.serialize(f(e));await t.setItem(this.config.key,s)}catch(e){this.handleError(e)}}queueSave(){!this.canPersist()||!this.config.autoSave||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.saveNow()},this.config.debounceMs))}async restore(){if(!this.canPersist())return!1;let t=this.getStorage();if(!t)return!1;try{let e=await t.getItem(this.config.key);if(!e)return!1;let s=this.config.deserialize(e);return!s||typeof s!="object"?!1:(this.applyRestoredValues(s),!0)}catch(e){return this.handleError(e),!1}}async clear(){if(!this.canPersist())return;let t=this.getStorage();if(t)try{await t.removeItem(this.config.key)}catch(e){this.handleError(e)}}destroy(){this.timer&&(clearTimeout(this.timer),this.timer=void 0)}};var N= (_class7 =class{constructor(t,e){;_class7.prototype.__init14.call(this);_class7.prototype.__init15.call(this);this.plugins=t;this.contextFactory=e}__init14() {this.teardownFns=[]}__init15() {this.notifyingError=!1}setupAll(){this.plugins.forEach(t=>{if(t.setup)try{let e=t.setup(this.contextFactory());typeof e=="function"&&this.teardownFns.push(e)}catch(e){this.reportError("setup",e,void 0,t.name)}})}async beforeValidate(t){await this.emitHook("beforeValidate",t)}async afterValidate(t){await this.emitHook("afterValidate",t)}async beforeSubmit(t){await this.emitHook("beforeSubmit",t)}async afterSubmit(t){await this.emitHook("afterSubmit",t)}onFieldChange(t){this.plugins.forEach(e=>{let s=_optionalChain([e, 'access', _76 => _76.hooks, 'optionalAccess', _77 => _77.onFieldChange]);if(s)try{let r=s(t,this.contextFactory());Promise.resolve(r).catch(i=>{this.reportError("onFieldChange",i,t,e.name)})}catch(r){this.reportError("onFieldChange",r,t,e.name)}})}async reportError(t,e,s,r){if(this.notifyingError)return;this.notifyingError=!0;let i=this.contextFactory(),n={source:t,pluginName:r,error:e,event:s,values:i.getState().values,state:i.getState()};for(let l of this.plugins){let a=_optionalChain([l, 'access', _78 => _78.hooks, 'optionalAccess', _79 => _79.onError]);if(a)try{await a(n,i)}catch (e2){}}this.notifyingError=!1}destroy(){for(let t=this.teardownFns.length-1;t>=0;t-=1){let e=this.teardownFns[t];try{e()}catch(s){this.reportError("teardown",s)}}this.teardownFns=[]}async emitHook(t,e){let s=this.contextFactory();for(let r of this.plugins){let i=_optionalChain([r, 'access', _80 => _80.hooks, 'optionalAccess', _81 => _81[t]]);if(i)try{await i(e,s)}catch(n){await this.reportError(t,n,e,r.name)}}}}, _class7);var L= (_class8 =class{__init16() {this.listeners=new Set}constructor(t={}){;_class8.prototype.__init16.call(this);this.config=Bt(t),this.depsMg=new P,this.computedMg=new F(()=>this.getComputedEntries()),this.validatorMg=new D(this),this.dirtyMg=new R,this.lifecycleMg=new I(this),this.historyMg=new C(!!this.config.enableHistory,_nullishCoalesce(this.config.historyLimit, () => (15))),this.arraysMg=new w(this),this.devtoolsMg=new A(this),this.scopeMg=new H(()=>this.state,()=>this.config.initialValues,r=>this.getScopeFields(r)),this.queryMg=new O(this.depsMg,()=>this.state,()=>this.config),this.errorMg=new $(()=>this.state,r=>this.internalUpdateState(r)),this.persistMg=new U(this.config.persist,()=>this.state.values,()=>this.getDirtyValues(),r=>this.applyPersistedValues(r));let e=f(this.config.initialValues);this.config.fields&&Object.entries(this.config.fields).forEach(([r,i])=>{this.depsMg.register(r,i,e)});let s=this.computedMg.apply(e);this.state={values:s,errors:{},touched:{},isValidating:{},isValid:!0,isSubmitting:!1,isDirty:!1},this.internalSaveSnapshot(),this.storeId=this.config.name||`bit-form-${Math.random().toString(36).substring(2,9)}`,this.pluginMg=new N(this.config.plugins,()=>({storeId:this.storeId,getState:()=>this.getState(),getConfig:()=>this.getConfig()})),this.pluginMg.setupAll(),m.stores[this.storeId]=this}getConfig(){return this.config}getFieldConfig(t){return this.depsMg.fieldConfigs.get(t)||_optionalChain([this, 'access', _82 => _82.config, 'access', _83 => _83.fields, 'optionalAccess', _84 => _84[t]])}getScopeFields(t){let e=[];return this.depsMg.fieldConfigs.forEach((s,r)=>{s.scope===t&&e.push(r)}),e}getComputedEntries(){let t=[];return this.depsMg.fieldConfigs.forEach((e,s)=>{e.computed&&t.push([s,e.computed])}),t}getTransformEntries(){let t=[];return this.depsMg.fieldConfigs.forEach((e,s)=>{e.transform&&t.push([s,e.transform])}),t}resolveMask(t){let e=_optionalChain([this, 'access', _85 => _85.getFieldConfig, 'call', _86 => _86(t), 'optionalAccess', _87 => _87.mask]);if(e)return typeof e=="string"?_optionalChain([this, 'access', _88 => _88.config, 'access', _89 => _89.masks, 'optionalAccess', _90 => _90[e]]):e}getState(){return this.state}get isValid(){return this.state.isValid}get isSubmitting(){return this.state.isSubmitting}get isDirty(){return this.state.isDirty}registerField(t,e){this.depsMg.register(t,e,this.state.values),this.depsMg.isHidden(t)&&this.notify()}unregisterField(t){if(_optionalChain([this, 'access', _91 => _91.config, 'access', _92 => _92.fields, 'optionalAccess', _93 => _93[t]]))return;this.depsMg.unregister(t);let e={...this.state.errors},s={...this.state.touched},r=!1;e[t]&&(delete e[t],r=!0),s[t]&&(delete s[t],r=!0),r&&this.internalUpdateState({errors:e,touched:s})}unregisterPrefix(t){this.depsMg.unregisterPrefix(t)}isHidden(t){return this.queryMg.isHidden(t)}isRequired(t){return this.queryMg.isRequired(t)}isFieldDirty(t){return this.queryMg.isFieldDirty(t)}isFieldValidating(t){return this.queryMg.isFieldValidating(t)}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}watch(t,e){let s=f(g(this.state.values,t));return this.subscribe(()=>{let r=g(this.state.values,t);T(r,s)||(s=f(r),e(r))})}setField(t,e){this.setFieldWithMeta(t,e,{origin:"setField"})}setFieldWithMeta(t,e,s={origin:"setField"}){let{visibilitiesChanged:r}=this.lifecycleMg.updateField(t,e,s);(!this.config.resolver||r)&&this.notify()}blurField(t){this.internalSaveSnapshot(),this.state.touched[t]||this.internalUpdateState({touched:{...this.state.touched,[t]:!0}}),this.validatorMg.trigger([t])}markFieldsTouched(t){if(t.length===0)return;let e={...this.state.touched};t.forEach(s=>e[s]=!0),this.internalUpdateState({touched:e})}setValues(t){this.lifecycleMg.updateAll(t)}setError(t,e){this.errorMg.setError(t,e)}setErrors(t){this.errorMg.setErrors(t)}setServerErrors(t){this.errorMg.setServerErrors(t)}reset(){this.lifecycleMg.reset()}async submit(t){return this.lifecycleMg.submit(t)}registerMask(t,e){this.config.masks={...this.config.masks||{},[t]:e}}getDirtyValues(){return this.dirtyMg.buildDirtyValues(this.state.values)}async restorePersisted(){return this.persistMg.restore()}async forceSave(){await this.persistMg.saveNow()}async clearPersisted(){await this.persistMg.clear()}pushItem(t,e){this.arraysMg.pushItem(t,e)}prependItem(t,e){this.arraysMg.prependItem(t,e)}insertItem(t,e,s){this.arraysMg.insertItem(t,e,s)}removeItem(t,e){this.arraysMg.removeItem(t,e)}swapItems(t,e,s){this.arraysMg.swapItems(t,e,s)}moveItem(t,e,s){this.arraysMg.moveItem(t,e,s)}get canUndo(){return this.historyMg.canUndo}get canRedo(){return this.historyMg.canRedo}undo(){let t=this.historyMg.undo();if(t){let e=this.dirtyMg.rebuild(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}redo(){let t=this.historyMg.redo();if(t){let e=this.dirtyMg.rebuild(t,this.config.initialValues);this.internalUpdateState({values:t,isDirty:e}),this.validatorMg.validate()}}getHistoryMetadata(){return this.historyMg.getMetadata()}validate(t){return this.validatorMg.validate(t)}emitBeforeValidate(t){return this.pluginMg.beforeValidate(t)}emitAfterValidate(t){return this.pluginMg.afterValidate(t)}emitBeforeSubmit(t){return this.pluginMg.beforeSubmit(t)}emitAfterSubmit(t){return this.pluginMg.afterSubmit(t)}emitFieldChange(t){this.pluginMg.onFieldChange(t)}emitOperationalError(t){return this.pluginMg.reportError(t.source,t.error,t.payload)}hasValidationsInProgress(t){return this.validatorMg.hasValidationsInProgress(t)}beginFieldValidation(t){this.validatorMg.beginExternalValidation(t)}endFieldValidation(t){this.validatorMg.endExternalValidation(t)}setFieldAsyncError(t,e){return this.validatorMg.setExternalError(t,e)}clearFieldAsyncError(t){return this.validatorMg.setExternalError(t,void 0)}getStepStatus(t){return this.scopeMg.getStepStatus(t)}getStepErrors(t){return this.scopeMg.getStepErrors(t)}internalUpdateState(t){let e={...this.state,...t};t.values&&(e.values=this.computedMg.apply(t.values)),t.errors&&(e.isValid=Object.keys(e.errors).length===0),this.state=e,t.values&&this.persistMg.queueSave(),this.notify(),m.dispatch(this.storeId,this.state)}internalSaveSnapshot(){this.historyMg.saveSnapshot(this.state.values)}applyPersistedValues(t){let e=f({...this.config.initialValues,...t});this.validatorMg.cancelAll(),this.depsMg.evaluateAll(e);let s=this.dirtyMg.rebuild(e,this.config.initialValues);this.internalUpdateState({values:e,errors:{},touched:{},isValidating:{},isValid:!0,isDirty:s,isSubmitting:!1}),this.internalSaveSnapshot(),this.validatorMg.validate()}cleanup(){this.listeners.clear(),this.validatorMg.cancelAll(),this.persistMg.destroy(),this.pluginMg.destroy(),delete m.stores[this.storeId]}notify(){this.listeners.forEach(t=>t())}}, _class8);function Ut(o={}){let t=new L(o);return{getConfig:()=>t.getConfig(),getState:()=>t.getState(),subscribe:t.subscribe.bind(t),setField:t.setField.bind(t),blurField:t.blurField.bind(t),setValues:t.setValues.bind(t),setError:t.setError.bind(t),setErrors:t.setErrors.bind(t),setServerErrors:t.setServerErrors.bind(t),validate:t.validate.bind(t),reset:t.reset.bind(t),submit:t.submit.bind(t),registerMask:t.registerMask.bind(t),getDirtyValues:t.getDirtyValues.bind(t),restorePersisted:t.restorePersisted.bind(t),forceSave:t.forceSave.bind(t),clearPersisted:t.clearPersisted.bind(t),cleanup:t.cleanup.bind(t)}}var Pt=o=>{let t=typeof o.getState=="function"?o.getState():o,e=_optionalChain([o, 'optionalAccess', _94 => _94.getHistoryMetadata, 'optionalCall', _95 => _95()])||{canUndo:!1,canRedo:!1,historyIndex:-1,historySize:0};return{...t,_meta:{canUndo:e.canUndo,canRedo:e.canRedo,totalSteps:e.historySize,currentIndex:e.historyIndex}}},q=null;function Vt(o){q&&(console.warn("[bit-form] Reiniciando ponte do DevTools (Fast Refresh detectado)."),q());let t=null,e=null,s,r=!1,i=()=>{r=!1,t=new WebSocket(o),t.onopen=()=>{console.log("[bit-form] \u{1F50C} Conectado ao CLI DevTools via WebSocket.");let l=Object.entries(m.stores);if(l.length>0){let a=l.reduce((d,[c,u])=>(d[c]=Pt(u),d),{});_optionalChain([t, 'optionalAccess', _96 => _96.send, 'call', _97 => _97(JSON.stringify({type:"STATE_UPDATE",payload:a}))])}e=m.subscribe((a,d)=>{if(_optionalChain([t, 'optionalAccess', _98 => _98.readyState])===WebSocket.OPEN){let c=m.stores[a];c&&t.send(JSON.stringify({type:"STATE_UPDATE",payload:{[a]:Pt(c)}}))}}),s=setInterval(()=>{_optionalChain([t, 'optionalAccess', _99 => _99.readyState])===WebSocket.OPEN&&t.send(JSON.stringify({type:"PING"}))},3e4)},t.onmessage=l=>{try{let{type:a,payload:d}=JSON.parse(l.data);if(a==="ACTION"){let{storeId:c,action:u}=d,h=m.stores[c];h&&typeof h[u]=="function"&&h[u]()}}catch(a){console.warn("[bit-form] Erro ao processar comando do CLI:",a)}},t.onclose=()=>{e&&e(),clearInterval(s),r?console.log("[bit-form] Ponte antiga encerrada com sucesso."):(console.log("[bit-form] Conex\xE3o perdida. Reconectando em 3s..."),setTimeout(i,3e3))}};i();let n=()=>{r=!0,e&&e(),clearInterval(s),t&&(t.readyState===WebSocket.OPEN||t.readyState===WebSocket.CONNECTING)&&t.close(),q=null};return q=n,n}exports.a = m; exports.b = f; exports.c = S; exports.d = T; exports.e = g; exports.f = y; exports.g = Ct; exports.h = St; exports.i = wt; exports.j = E; exports.k = xt; exports.l = p; exports.m = b; exports.n = Y; exports.o = V; exports.p = J; exports.q = K; exports.r = G; exports.s = Z; exports.t = Q; exports.u = tt; exports.v = et; exports.w = st; exports.x = rt; exports.y = it; exports.z = ot; exports.A = nt; exports.B = at; exports.C = lt; exports.D = dt; exports.E = ct; exports.F = ut; exports.G = Ft; exports.H = Dt; exports.I = It; exports.J = At; exports.K = gt; exports.L = pt; exports.M = Rt; exports.N = ft; exports.O = ht; exports.P = mt; exports.Q = yt; exports.R = Ht; exports.S = bt; exports.T = Vt; exports.U = vt; exports.V = Ut;
|
|
133
|
+
//# sourceMappingURL=chunk-25Q2XJBV.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/store/bus.ts","../src/core/utils.ts","../src/devtools/ui/styles.ts","../src/devtools/ui/index.ts","../src/devtools/init-dev-tools.ts"],"names":["rootGlobal","id","state","fn","bitBus","deepClone","obj","item","clone","key","valueEqual","a","b","deepEqual","keysA","keysB","collectDirtyPaths","initial","prefix","result","allKeys","k","p"],"mappings":"AAMA,+wBAAMA,CAAAA,CACJ,OAAO,UAAA,CAAe,GAAA,CAClB,UAAA,CACE,OAAO,MAAA,CAAW,GAAA,CAAc,MAAA,CAAS,MAAA,CAE5CA,CAAAA,CAAW,YAAA,EAAA,CACdA,CAAAA,CAAW,YAAA,CAAe,CACxB,MAAA,CAAQ,CAAC,CAAA,C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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;ACkES,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBG,MAAA;AAAA;AAAA;AAGyB,0CAAA;AAAA;AAE0C,uCAAA;AAC7B,kBAAA;AAAA;AAE6B,gBAAA;AACY,gBAAA;AAAA;AAAA;AAAA;AAIhB,yDAAA;AAAA;AAAA;AAG+B,4EAAA;AAAA;AAAA;AAGA,4EAAA;AAAA;AAAA;AAGpB,2FAAA;AAAA;AAAA;AAAA;AAOxE,QAAA;AAAA;AAEuD,uCAAA;AAIzD,UAAA;AAAA;AAEmD,iCAAA;AAAA;AAShD,QAAA;AAC8E,6DAAA;AACnE,QAAA;AAAA;ACjIzB,IAAA","file":"/home/runner/work/bit-form/bit-form/dist/chunk-SIM4YIOW.cjs","sourcesContent":["import { BitBusListener, BitFormGlobal } from \"./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\" ? global : window) as any);\n\nif (!rootGlobal.__BIT_FORM__) {\n rootGlobal.__BIT_FORM__ = {\n stores: {},\n listeners: new Set<BitBusListener>(),\n\n dispatch(id: string, state: any) {\n this.listeners.forEach((fn: BitBusListener) => fn(id, state));\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","export function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as any as T;\n }\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags) as any as T;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => deepClone(item)) as any as T;\n }\n\n const clone: any = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone((obj as any)[key]);\n }\n }\n return clone as T;\n}\n\n/**\n * Fast equality for single values. Uses === for primitives, deepEqual for objects/arrays.\n * Prefer over deepEqual when comparing a single field value (e.g. isFieldDirty, getStepStatus).\n */\nexport function valueEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n return deepEqual(a, b);\n}\n\nexport function deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n if (a instanceof RegExp && b instanceof RegExp)\n return a.toString() === b.toString();\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !deepEqual(a[key], b[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Collects all paths where obj differs from initial. Used to rebuild dirtyPaths after full state replacement.\n */\nexport function collectDirtyPaths(\n obj: any,\n initial: any,\n prefix = \"\",\n result: Set<string> = new Set(),\n): Set<string> {\n if (valueEqual(obj, initial)) return result;\n if (\n obj === null ||\n typeof obj !== \"object\" ||\n initial === null ||\n typeof initial !== \"object\"\n ) {\n if (prefix) result.add(prefix);\n return result;\n }\n if (Array.isArray(obj) || Array.isArray(initial)) {\n if (!valueEqual(obj, initial) && prefix) result.add(prefix);\n return result;\n }\n const allKeys = new Set([\n ...Object.keys(obj || {}),\n ...Object.keys(initial || {}),\n ]);\n for (const k of allKeys) {\n const p = prefix ? `${prefix}.${k}` : k;\n collectDirtyPaths((obj as any)?.[k], (initial as any)?.[k], p, result);\n }\n return result;\n}\n\nconst pathCache = new Map<string, string[]>();\n\nexport function getDeepValue(obj: any, path: string): any {\n if (!path) return obj;\n\n const keys = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\n\n let current = obj;\n for (const key of keys) {\n if (current === null || current === undefined) return undefined;\n current = current[key];\n }\n return current;\n}\n\nexport function setDeepValue(obj: any, path: string, value: any): any {\n if (!path) return value;\n\n const keys = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\n\n const result = Array.isArray(obj) ? [...obj] : { ...obj };\n let current = result;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const isNextNumeric = /^\\d+$/.test(nextKey);\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n } else {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n\n return result;\n}\n\nexport function cleanPrefixedKeys(\n obj: Record<string, any>,\n prefix: string,\n): Record<string, any> {\n const newObj: Record<string, any> = {};\n const prefixWithDot = `${prefix}.`;\n\n for (const key in obj) {\n if (key !== prefix && !key.startsWith(prefixWithDot)) {\n newObj[key] = obj[key];\n }\n }\n return newObj;\n}\n\nexport const shiftKeys = (\n obj: Record<string, any>,\n path: string,\n removedIndex: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === removedIndex) return;\n\n if (currentIdx > removedIndex) {\n const newIdx = currentIdx - 1;\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const swapKeys = (\n obj: Record<string, any>,\n path: string,\n indexA: number,\n indexB: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === indexA) {\n const newKey = rest ? `${prefix}${indexB}.${rest}` : `${prefix}${indexB}`;\n newObj[newKey] = obj[key];\n } else if (currentIdx === indexB) {\n const newKey = rest ? `${prefix}${indexA}.${rest}` : `${prefix}${indexA}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const moveKeys = (\n obj: Record<string, any>,\n path: string,\n from: number,\n to: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n let newIdx = currentIdx;\n if (currentIdx === from) {\n newIdx = to;\n } else if (from < to && currentIdx > from && currentIdx <= to) {\n newIdx = currentIdx - 1;\n } else if (from > to && currentIdx >= to && currentIdx < from) {\n newIdx = currentIdx + 1;\n }\n\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n });\n return newObj;\n};\n\n/**\n * Checks if a value looks like a server validation error response.\n * Handles shapes like { email: \"Taken\" }, { errors: { email: [\"Taken\"] } }, etc.\n */\nexport function isValidationErrorShape(\n x: unknown,\n): x is Record<string, string | string[]> {\n if (typeof x !== \"object\" || x === null || Array.isArray(x)) return false;\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return false;\n\n return Object.values(obj as Record<string, unknown>).every(\n (v) =>\n typeof v === \"string\" ||\n (Array.isArray(v) && v.every((i) => typeof i === \"string\")),\n );\n}\n\n/**\n * Extracts server errors in the format expected by setServerErrors.\n */\nexport function extractServerErrors(\n x: unknown,\n): Record<string, string | string[]> {\n if (!isValidationErrorShape(x)) return {};\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n return obj as Record<string, string | string[]>;\n}\n","export function getDevToolsCSS(): string {\n return `\n .bit-devtools-container {\n position: fixed;\n bottom: 20px;\n right: 20px;\n z-index: 9999;\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n }\n\n .bit-devtools-trigger {\n background: #10b981;\n color: #fff;\n border: none;\n border-radius: 50%;\n width: 48px;\n height: 48px;\n cursor: pointer;\n box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);\n font-weight: bold;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n font-size: 16px;\n margin-top: 16px;\n }\n .bit-devtools-trigger:hover { transform: scale(1.05); }\n\n .bit-devtools-panel {\n width: 450px;\n max-height: 80vh;\n background: #0f172a;\n color: #f8fafc;\n border-radius: 8px;\n padding: 16px;\n overflow-y: auto;\n box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5), 0 8px 10px -6px rgba(0,0,0,0.5);\n border: 1px solid #334155;\n display: flex;\n flex-direction: column;\n gap: 16px;\n }\n\n .bit-devtools-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding-bottom: 12px;\n border-bottom: 1px solid #1e293b;\n }\n .bit-devtools-header h2 { margin: 0; font-size: 16px; display: flex; align-items: center; gap: 8px; }\n\n .bit-store-block {\n background: #1e293b;\n border-radius: 6px;\n padding: 12px;\n border: 1px solid #334155;\n }\n\n .bit-store-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 12px;\n }\n .bit-store-title { margin: 0; color: #38bdf8; font-size: 14px; font-weight: bold; }\n\n .bit-badge-group { display: flex; gap: 6px; flex-wrap: wrap; }\n .bit-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: bold; }\n .badge-success { background: rgba(16, 185, 129, 0.2); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.2); }\n .badge-error { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.2); }\n .badge-warn { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.2); }\n .badge-info { background: rgba(56, 189, 248, 0.2); color: #7dd3fc; border: 1px solid rgba(56, 189, 248, 0.2); }\n\n .bit-section-title { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin: 12px 0 4px 0; display: block; }\n\n .bit-controls { display: flex; gap: 6px; margin-bottom: 12px; background: #0f172a; padding: 8px; border-radius: 6px; }\n .bit-action-btn { flex: 1; background: #334155; color: #e2e8f0; border: 1px solid #475569; padding: 6px 0; border-radius: 4px; cursor: pointer; font-size: 11px; display: flex; align-items: center; justify-content: center; gap: 4px; transition: all 0.2s; }\n .bit-action-btn:hover:not(:disabled) { background: #475569; }\n .bit-action-btn:disabled { opacity: 0.5; cursor: not-allowed; }\n .bit-btn-reset { color: #fca5a5; border-color: rgba(239,68,68,0.3); }\n .bit-btn-reset:hover { background: rgba(239,68,68,0.1) !important; }\n\n pre.bit-pre { background: #020617; padding: 10px; border-radius: 4px; font-size: 11px; overflow-x: auto; border: 1px solid #1e293b; margin: 0; color: #e2e8f0; }\n pre.bit-error-box { background: rgba(239, 68, 68, 0.05); padding: 10px; border-radius: 4px; font-size: 11px; border: 1px dashed #ef4444; color: #fca5a5; margin: 0; overflow-x: auto; }\n `;\n}\n","import { getDevToolsCSS } from \"./styles\";\nimport type { DevToolsActions } from \"../types\";\n\nexport type { DevToolsActions };\n\nexport class BitFormDevToolsUI {\n private container: HTMLElement;\n private actions: DevToolsActions;\n private rootElement: HTMLDivElement;\n private currentStoresState: Record<string, any> = {};\n private isOpen: boolean = false;\n\n constructor(container: HTMLElement, actions: DevToolsActions) {\n this.container = container;\n this.actions = actions;\n\n if (!document.getElementById(\"bit-devtools-styles\")) {\n const style = document.createElement(\"style\");\n style.id = \"bit-devtools-styles\";\n style.textContent = getDevToolsCSS();\n document.head.appendChild(style);\n }\n\n this.rootElement = document.createElement(\"div\");\n this.rootElement.className = \"bit-devtools-container\";\n this.container.appendChild(this.rootElement);\n\n this.rootElement.addEventListener(\"click\", (e) => {\n const target = e.target as HTMLElement;\n\n // Evento do botão flutuante\n if (target.closest(\".bit-devtools-trigger\")) {\n this.isOpen = !this.isOpen;\n this.render();\n return;\n }\n\n // Eventos dos botões de ação\n const btn = target.closest(\".bit-action-btn\");\n if (btn && !btn.hasAttribute(\"disabled\")) {\n const action = btn.getAttribute(\"data-action\");\n const storeId = btn.getAttribute(\"data-store\");\n\n if (action && storeId) {\n if (action === \"undo\") this.actions.onUndo(storeId);\n if (action === \"redo\") this.actions.onRedo(storeId);\n if (action === \"reset\") this.actions.onReset(storeId);\n }\n }\n });\n }\n\n public updateState(storesState: Record<string, any>) {\n this.currentStoresState = storesState;\n this.render();\n }\n\n private render() {\n const storeEntries = Object.entries(this.currentStoresState);\n if (storeEntries.length === 0) {\n this.rootElement.innerHTML = \"\";\n return;\n }\n\n let panelHtml = \"\";\n\n if (this.isOpen) {\n panelHtml = `\n <div class=\"bit-devtools-panel\">\n <div class=\"bit-devtools-header\">\n <h2><span style=\"font-size: 20px;\">🛠</span> Bit-Form DevTools</h2>\n <span style=\"font-size: 11px; color: #64748b;\">v1.0.0</span>\n </div>\n `;\n\n for (const [id, state] of storeEntries) {\n const hasErrors = Object.keys(state.errors || {}).length > 0;\n\n // Lemos os metadados do histórico que o adaptador injetou\n const meta = state._meta || {\n totalSteps: 0,\n currentIndex: -1,\n canUndo: false,\n canRedo: false,\n };\n const currentStep = meta.currentIndex + 1;\n const totalSteps = meta.totalSteps;\n\n panelHtml += `\n <div class=\"bit-store-block\">\n <div class=\"bit-store-header\">\n <h3 class=\"bit-store-title\">${id}</h3>\n <div class=\"bit-badge-group\">\n <span class=\"bit-badge ${state.isValid ? \"badge-success\" : \"badge-error\"}\">\n ${state.isValid ? \"✓ Valid\" : \"✕ Invalid\"}\n </span>\n ${state.isDirty ? `<span class=\"bit-badge badge-warn\">Dirty</span>` : \"\"}\n ${state.isSubmitting ? `<span class=\"bit-badge badge-info\">⏳ Submitting</span>` : \"\"}\n </div>\n </div>\n\n <span class=\"bit-section-title\">Time Travel (${currentStep}/${totalSteps})</span>\n \n <div class=\"bit-controls\">\n <button class=\"bit-action-btn\" data-action=\"undo\" data-store=\"${id}\" ${meta.canUndo ? \"\" : \"disabled\"}>\n <span>↺</span> Undo\n </button>\n <button class=\"bit-action-btn\" data-action=\"redo\" data-store=\"${id}\" ${meta.canRedo ? \"\" : \"disabled\"}>\n <span>↻</span> Redo\n </button>\n <button class=\"bit-action-btn bit-btn-reset\" data-action=\"reset\" data-store=\"${id}\">\n <span>🗑</span> Reset\n </button>\n </div>\n `;\n\n if (hasErrors) {\n panelHtml += `\n <span class=\"bit-section-title\" style=\"color: #f87171;\">⚠️ Validations Failing</span>\n <pre class=\"bit-error-box\">${JSON.stringify(state.errors, null, 2)}</pre>\n `;\n }\n\n panelHtml += `\n <span class=\"bit-section-title\">Values</span>\n <pre class=\"bit-pre\">${JSON.stringify(state.values, null, 2)}</pre>\n </div>\n `;\n }\n\n panelHtml += `</div>`;\n }\n\n // Botão Flutuante (sempre renderizado)\n const triggerHtml = `\n <button class=\"bit-devtools-trigger\" style=\"transform: ${this.isOpen ? \"scale(0.9)\" : \"scale(1)\"};\" title=\"Abrir DevTools\">\n ${this.isOpen ? \"✖\" : \"Bit\"}\n </button>\n `;\n\n this.rootElement.innerHTML = panelHtml + triggerHtml;\n }\n}\n","import { setupLocalDevTools } from \"./adapters/local\";\nimport { setupRemoteDevTools } from \"./adapters/remote\";\nimport type { BitDevToolsOptions } from \"./types\";\n\nexport type { BitDevToolsOptions };\n\nexport function initDevTools(options: BitDevToolsOptions = {}) {\n const { mode = \"local\", url } = options;\n let containerEl: HTMLElement;\n\n let isAutoCreated = false;\n\n if (typeof options.container === \"string\") {\n const el = document.querySelector<HTMLElement>(options.container);\n if (!el)\n throw new Error(\n `[bit-form] Container '${options.container}' não encontrado na página.`,\n );\n containerEl = el;\n } else if (options.container instanceof HTMLElement) {\n containerEl = options.container;\n } else {\n containerEl = document.createElement(\"div\");\n containerEl.id = \"bit-form-devtools-root\";\n containerEl.style.position = \"fixed\";\n containerEl.style.bottom = \"20px\";\n containerEl.style.right = \"20px\";\n containerEl.style.zIndex = \"9999\";\n containerEl.style.maxHeight = \"80vh\";\n containerEl.style.overflowY = \"auto\";\n containerEl.style.boxShadow = \"0 10px 25px rgba(0,0,0,0.1)\";\n document.body.appendChild(containerEl);\n isAutoCreated = true;\n }\n\n let adapterInstance: any;\n\n if (mode === \"local\") {\n console.log(\"[bit-form] DevTools iniciado em modo Local.\");\n adapterInstance = setupLocalDevTools(containerEl);\n } else if (mode === \"remote\") {\n console.log(\"[bit-form] DevTools iniciado em modo Remote.\");\n adapterInstance = setupRemoteDevTools(containerEl, url);\n } else {\n throw new Error(`[bit-form] Modo DevTools inválido: ${mode}`);\n }\n\n return {\n ...adapterInstance,\n destroy: () => {\n if (adapterInstance && typeof adapterInstance.destroy === \"function\") {\n adapterInstance.destroy();\n }\n\n if (isAutoCreated && containerEl.parentNode) {\n containerEl.parentNode.removeChild(containerEl);\n } else {\n containerEl.innerHTML = \"\";\n }\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/store/bus.ts","../src/core/utils.ts","../src/devtools/ui/styles.ts","../src/devtools/ui/index.ts","../src/devtools/init-dev-tools.ts"],"names":["rootGlobal","id","state","fn","bitBus","deepClone","obj","item","clone","key","valueEqual","a","b","deepEqual","keysA","keysB","collectDirtyPaths","initial","prefix","result","allKeys","k","p"],"mappings":"AAMA,4xBAAMA,CAAAA,CACJ,OAAO,UAAA,CAAe,GAAA,CAClB,UAAA,CACE,OAAO,MAAA,CAAW,GAAA,CAAc,MAAA,CAAS,MAAA,CAE5CA,CAAAA,CAAW,YAAA,EAAA,CACdA,CAAAA,CAAW,YAAA,CAAe,CACxB,MAAA,CAAQ,CAAC,CAAA,CACT,SAAA,CAAW,IAAI,GAAA,CAEf,QAAA,CAASC,CAAAA,CAAYC,CAAAA,CAAY,CAC/B,IAAA,CAAK,SAAA,CAAU,OAAA,CAASC,CAAAA,EAAuBA,CAAAA,CAAGF,CAAAA,CAAIC,CAAK,CAAC,CAC9D,CAAA,CAEA,SAAA,CAAUC,CAAAA,CAAoB,CAC5B,OAAA,IAAA,CAAK,SAAA,CAAU,GAAA,CAAIA,CAAE,CAAA,CACd,CAAA,CAAA,EAAM,CACX,IAAA,CAAK,SAAA,CAAU,MAAA,CAAOA,CAAE,CAC1B,CACF,CACF,CAAA,CAAA,CAGK,IAAMC,CAAAA,CAASJ,CAAAA,CAAW,YAAA,CC7B1B,SAASK,CAAAA,CAAaC,CAAAA,CAAW,CACtC,EAAA,CAAIA,CAAAA,GAAQ,IAAA,EAAQ,OAAOA,CAAAA,EAAQ,QAAA,CACjC,OAAOA,CAAAA,CAGT,EAAA,CAAIA,EAAAA,WAAe,IAAA,CACjB,OAAO,IAAI,IAAA,CAAKA,CAAAA,CAAI,OAAA,CAAQ,CAAC,CAAA,CAE/B,EAAA,CAAIA,EAAAA,WAAe,MAAA,CACjB,OAAO,IAAI,MAAA,CAAOA,CAAAA,CAAI,MAAA,C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-form/bit-form/dist/chunk-25Q2XJBV.cjs","sourcesContent":["import { BitBusListener, BitFormGlobal } from \"./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\" ? global : window) as any);\n\nif (!rootGlobal.__BIT_FORM__) {\n rootGlobal.__BIT_FORM__ = {\n stores: {},\n listeners: new Set<BitBusListener>(),\n\n dispatch(id: string, state: any) {\n this.listeners.forEach((fn: BitBusListener) => fn(id, state));\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","export function deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (obj instanceof Date) {\n return new Date(obj.getTime()) as any as T;\n }\n if (obj instanceof RegExp) {\n return new RegExp(obj.source, obj.flags) as any as T;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => deepClone(item)) as any as T;\n }\n\n const clone: any = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone((obj as any)[key]);\n }\n }\n return clone as T;\n}\n\n/**\n * Fast equality for single values. Uses === for primitives, deepEqual for objects/arrays.\n * Prefer over deepEqual when comparing a single field value (e.g. isFieldDirty, getStepStatus).\n */\nexport function valueEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n return deepEqual(a, b);\n}\n\nexport function deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (\n a === null ||\n typeof a !== \"object\" ||\n b === null ||\n typeof b !== \"object\"\n ) {\n return false;\n }\n\n if (a instanceof Date && b instanceof Date)\n return a.getTime() === b.getTime();\n if (a instanceof RegExp && b instanceof RegExp)\n return a.toString() === b.toString();\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (\n !Object.prototype.hasOwnProperty.call(b, key) ||\n !deepEqual(a[key], b[key])\n ) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Collects all paths where obj differs from initial. Used to rebuild dirtyPaths after full state replacement.\n */\nexport function collectDirtyPaths(\n obj: any,\n initial: any,\n prefix = \"\",\n result: Set<string> = new Set(),\n): Set<string> {\n if (valueEqual(obj, initial)) return result;\n if (\n obj === null ||\n typeof obj !== \"object\" ||\n initial === null ||\n typeof initial !== \"object\"\n ) {\n if (prefix) result.add(prefix);\n return result;\n }\n if (Array.isArray(obj) || Array.isArray(initial)) {\n if (!valueEqual(obj, initial) && prefix) result.add(prefix);\n return result;\n }\n const allKeys = new Set([\n ...Object.keys(obj || {}),\n ...Object.keys(initial || {}),\n ]);\n for (const k of allKeys) {\n const p = prefix ? `${prefix}.${k}` : k;\n collectDirtyPaths((obj as any)?.[k], (initial as any)?.[k], p, result);\n }\n return result;\n}\n\nconst pathCache = new Map<string, string[]>();\n\nexport function getDeepValue(obj: any, path: string): any {\n if (!path) return obj;\n\n const keys = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\n\n let current = obj;\n for (const key of keys) {\n if (current === null || current === undefined) return undefined;\n current = current[key];\n }\n return current;\n}\n\nexport function setDeepValue(obj: any, path: string, value: any): any {\n if (!path) return value;\n\n const keys = pathCache.get(path) || path.split(\".\");\n if (!pathCache.has(path)) pathCache.set(path, keys);\n\n const result = Array.isArray(obj) ? [...obj] : { ...obj };\n let current = result;\n\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n const nextKey = keys[i + 1];\n\n const isNextNumeric = /^\\d+$/.test(nextKey);\n const currentValue = current[key];\n\n if (currentValue === null || currentValue === undefined) {\n current[key] = isNextNumeric ? [] : {};\n } else {\n current[key] = Array.isArray(currentValue)\n ? [...currentValue]\n : { ...currentValue };\n }\n\n current = current[key];\n }\n\n current[keys[keys.length - 1]] = value;\n\n return result;\n}\n\nexport function cleanPrefixedKeys(\n obj: Record<string, any>,\n prefix: string,\n): Record<string, any> {\n const newObj: Record<string, any> = {};\n const prefixWithDot = `${prefix}.`;\n\n for (const key in obj) {\n if (key !== prefix && !key.startsWith(prefixWithDot)) {\n newObj[key] = obj[key];\n }\n }\n return newObj;\n}\n\nexport const shiftKeys = (\n obj: Record<string, any>,\n path: string,\n removedIndex: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === removedIndex) return;\n\n if (currentIdx > removedIndex) {\n const newIdx = currentIdx - 1;\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const swapKeys = (\n obj: Record<string, any>,\n path: string,\n indexA: number,\n indexB: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n if (currentIdx === indexA) {\n const newKey = rest ? `${prefix}${indexB}.${rest}` : `${prefix}${indexB}`;\n newObj[newKey] = obj[key];\n } else if (currentIdx === indexB) {\n const newKey = rest ? `${prefix}${indexA}.${rest}` : `${prefix}${indexA}`;\n newObj[newKey] = obj[key];\n } else {\n newObj[key] = obj[key];\n }\n });\n return newObj;\n};\n\nexport const moveKeys = (\n obj: Record<string, any>,\n path: string,\n from: number,\n to: number,\n) => {\n const newObj: Record<string, any> = {};\n const prefix = `${path}.`;\n\n Object.keys(obj).forEach((key) => {\n if (!key.startsWith(prefix)) {\n newObj[key] = obj[key];\n return;\n }\n const remaining = key.substring(prefix.length);\n const parts = remaining.split(\".\");\n const currentIdx = parseInt(parts[0], 10);\n const rest = parts.slice(1).join(\".\");\n\n let newIdx = currentIdx;\n if (currentIdx === from) {\n newIdx = to;\n } else if (from < to && currentIdx > from && currentIdx <= to) {\n newIdx = currentIdx - 1;\n } else if (from > to && currentIdx >= to && currentIdx < from) {\n newIdx = currentIdx + 1;\n }\n\n const newKey = rest ? `${prefix}${newIdx}.${rest}` : `${prefix}${newIdx}`;\n newObj[newKey] = obj[key];\n });\n return newObj;\n};\n\n/**\n * Checks if a value looks like a server validation error response.\n * Handles shapes like { email: \"Taken\" }, { errors: { email: [\"Taken\"] } }, etc.\n */\nexport function isValidationErrorShape(\n x: unknown,\n): x is Record<string, string | string[]> {\n if (typeof x !== \"object\" || x === null || Array.isArray(x)) return false;\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n if (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return false;\n\n return Object.values(obj as Record<string, unknown>).every(\n (v) =>\n typeof v === \"string\" ||\n (Array.isArray(v) && v.every((i) => typeof i === \"string\")),\n );\n}\n\n/**\n * Extracts server errors in the format expected by setServerErrors.\n */\nexport function extractServerErrors(\n x: unknown,\n): Record<string, string | string[]> {\n if (!isValidationErrorShape(x)) return {};\n\n const obj = (x as Record<string, unknown>).errors ?? x;\n return obj as Record<string, string | string[]>;\n}\n","export function getDevToolsCSS(): string {\n return `\n .bit-devtools-container {\n position: fixed;\n bottom: 20px;\n right: 20px;\n z-index: 9999;\n font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n }\n\n .bit-devtools-trigger {\n background: #10b981;\n color: #fff;\n border: none;\n border-radius: 50%;\n width: 48px;\n height: 48px;\n cursor: pointer;\n box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);\n font-weight: bold;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n font-size: 16px;\n margin-top: 16px;\n }\n .bit-devtools-trigger:hover { transform: scale(1.05); }\n\n .bit-devtools-panel {\n width: 450px;\n max-height: 80vh;\n background: #0f172a;\n color: #f8fafc;\n border-radius: 8px;\n padding: 16px;\n overflow-y: auto;\n box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5), 0 8px 10px -6px rgba(0,0,0,0.5);\n border: 1px solid #334155;\n display: flex;\n flex-direction: column;\n gap: 16px;\n }\n\n .bit-devtools-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding-bottom: 12px;\n border-bottom: 1px solid #1e293b;\n }\n .bit-devtools-header h2 { margin: 0; font-size: 16px; display: flex; align-items: center; gap: 8px; }\n\n .bit-store-block {\n background: #1e293b;\n border-radius: 6px;\n padding: 12px;\n border: 1px solid #334155;\n }\n\n .bit-store-header {\n display: flex;\n justify-content: space-between;\n align-items: center;\n margin-bottom: 12px;\n }\n .bit-store-title { margin: 0; color: #38bdf8; font-size: 14px; font-weight: bold; }\n\n .bit-badge-group { display: flex; gap: 6px; flex-wrap: wrap; }\n .bit-badge { font-size: 10px; padding: 2px 6px; border-radius: 4px; text-transform: uppercase; font-weight: bold; }\n .badge-success { background: rgba(16, 185, 129, 0.2); color: #34d399; border: 1px solid rgba(16, 185, 129, 0.2); }\n .badge-error { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid rgba(239, 68, 68, 0.2); }\n .badge-warn { background: rgba(245, 158, 11, 0.2); color: #fbbf24; border: 1px solid rgba(245, 158, 11, 0.2); }\n .badge-info { background: rgba(56, 189, 248, 0.2); color: #7dd3fc; border: 1px solid rgba(56, 189, 248, 0.2); }\n\n .bit-section-title { font-size: 11px; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; margin: 12px 0 4px 0; display: block; }\n\n .bit-controls { display: flex; gap: 6px; margin-bottom: 12px; background: #0f172a; padding: 8px; border-radius: 6px; }\n .bit-action-btn { flex: 1; background: #334155; color: #e2e8f0; border: 1px solid #475569; padding: 6px 0; border-radius: 4px; cursor: pointer; font-size: 11px; display: flex; align-items: center; justify-content: center; gap: 4px; transition: all 0.2s; }\n .bit-action-btn:hover:not(:disabled) { background: #475569; }\n .bit-action-btn:disabled { opacity: 0.5; cursor: not-allowed; }\n .bit-btn-reset { color: #fca5a5; border-color: rgba(239,68,68,0.3); }\n .bit-btn-reset:hover { background: rgba(239,68,68,0.1) !important; }\n\n pre.bit-pre { background: #020617; padding: 10px; border-radius: 4px; font-size: 11px; overflow-x: auto; border: 1px solid #1e293b; margin: 0; color: #e2e8f0; }\n pre.bit-error-box { background: rgba(239, 68, 68, 0.05); padding: 10px; border-radius: 4px; font-size: 11px; border: 1px dashed #ef4444; color: #fca5a5; margin: 0; overflow-x: auto; }\n `;\n}\n","import { getDevToolsCSS } from \"./styles\";\nimport type { DevToolsActions } from \"../types\";\n\nexport type { DevToolsActions };\n\nexport class BitFormDevToolsUI {\n private container: HTMLElement;\n private actions: DevToolsActions;\n private rootElement: HTMLDivElement;\n private currentStoresState: Record<string, any> = {};\n private isOpen: boolean = false;\n\n constructor(container: HTMLElement, actions: DevToolsActions) {\n this.container = container;\n this.actions = actions;\n\n if (!document.getElementById(\"bit-devtools-styles\")) {\n const style = document.createElement(\"style\");\n style.id = \"bit-devtools-styles\";\n style.textContent = getDevToolsCSS();\n document.head.appendChild(style);\n }\n\n this.rootElement = document.createElement(\"div\");\n this.rootElement.className = \"bit-devtools-container\";\n this.container.appendChild(this.rootElement);\n\n this.rootElement.addEventListener(\"click\", (e) => {\n const target = e.target as HTMLElement;\n\n // Evento do botão flutuante\n if (target.closest(\".bit-devtools-trigger\")) {\n this.isOpen = !this.isOpen;\n this.render();\n return;\n }\n\n // Eventos dos botões de ação\n const btn = target.closest(\".bit-action-btn\");\n if (btn && !btn.hasAttribute(\"disabled\")) {\n const action = btn.getAttribute(\"data-action\");\n const storeId = btn.getAttribute(\"data-store\");\n\n if (action && storeId) {\n if (action === \"undo\") this.actions.onUndo(storeId);\n if (action === \"redo\") this.actions.onRedo(storeId);\n if (action === \"reset\") this.actions.onReset(storeId);\n }\n }\n });\n }\n\n public updateState(storesState: Record<string, any>) {\n this.currentStoresState = storesState;\n this.render();\n }\n\n private render() {\n const storeEntries = Object.entries(this.currentStoresState);\n if (storeEntries.length === 0) {\n this.rootElement.innerHTML = \"\";\n return;\n }\n\n let panelHtml = \"\";\n\n if (this.isOpen) {\n panelHtml = `\n <div class=\"bit-devtools-panel\">\n <div class=\"bit-devtools-header\">\n <h2><span style=\"font-size: 20px;\">🛠</span> Bit-Form DevTools</h2>\n <span style=\"font-size: 11px; color: #64748b;\">v1.0.0</span>\n </div>\n `;\n\n for (const [id, state] of storeEntries) {\n const hasErrors = Object.keys(state.errors || {}).length > 0;\n\n // Lemos os metadados do histórico que o adaptador injetou\n const meta = state._meta || {\n totalSteps: 0,\n currentIndex: -1,\n canUndo: false,\n canRedo: false,\n };\n const currentStep = meta.currentIndex + 1;\n const totalSteps = meta.totalSteps;\n\n panelHtml += `\n <div class=\"bit-store-block\">\n <div class=\"bit-store-header\">\n <h3 class=\"bit-store-title\">${id}</h3>\n <div class=\"bit-badge-group\">\n <span class=\"bit-badge ${state.isValid ? \"badge-success\" : \"badge-error\"}\">\n ${state.isValid ? \"✓ Valid\" : \"✕ Invalid\"}\n </span>\n ${state.isDirty ? `<span class=\"bit-badge badge-warn\">Dirty</span>` : \"\"}\n ${state.isSubmitting ? `<span class=\"bit-badge badge-info\">⏳ Submitting</span>` : \"\"}\n </div>\n </div>\n\n <span class=\"bit-section-title\">Time Travel (${currentStep}/${totalSteps})</span>\n \n <div class=\"bit-controls\">\n <button class=\"bit-action-btn\" data-action=\"undo\" data-store=\"${id}\" ${meta.canUndo ? \"\" : \"disabled\"}>\n <span>↺</span> Undo\n </button>\n <button class=\"bit-action-btn\" data-action=\"redo\" data-store=\"${id}\" ${meta.canRedo ? \"\" : \"disabled\"}>\n <span>↻</span> Redo\n </button>\n <button class=\"bit-action-btn bit-btn-reset\" data-action=\"reset\" data-store=\"${id}\">\n <span>🗑</span> Reset\n </button>\n </div>\n `;\n\n if (hasErrors) {\n panelHtml += `\n <span class=\"bit-section-title\" style=\"color: #f87171;\">⚠️ Validations Failing</span>\n <pre class=\"bit-error-box\">${JSON.stringify(state.errors, null, 2)}</pre>\n `;\n }\n\n panelHtml += `\n <span class=\"bit-section-title\">Values</span>\n <pre class=\"bit-pre\">${JSON.stringify(state.values, null, 2)}</pre>\n </div>\n `;\n }\n\n panelHtml += `</div>`;\n }\n\n // Botão Flutuante (sempre renderizado)\n const triggerHtml = `\n <button class=\"bit-devtools-trigger\" style=\"transform: ${this.isOpen ? \"scale(0.9)\" : \"scale(1)\"};\" title=\"Abrir DevTools\">\n ${this.isOpen ? \"✖\" : \"Bit\"}\n </button>\n `;\n\n this.rootElement.innerHTML = panelHtml + triggerHtml;\n }\n}\n","import { setupLocalDevTools } from \"./adapters/local\";\nimport { setupRemoteDevTools } from \"./adapters/remote\";\nimport type { BitDevToolsOptions } from \"./types\";\n\nexport type { BitDevToolsOptions };\n\nexport function initDevTools(options: BitDevToolsOptions = {}) {\n const { mode = \"local\", url } = options;\n let containerEl: HTMLElement;\n\n let isAutoCreated = false;\n\n if (typeof options.container === \"string\") {\n const el = document.querySelector<HTMLElement>(options.container);\n if (!el)\n throw new Error(\n `[bit-form] Container '${options.container}' não encontrado na página.`,\n );\n containerEl = el;\n } else if (options.container instanceof HTMLElement) {\n containerEl = options.container;\n } else {\n containerEl = document.createElement(\"div\");\n containerEl.id = \"bit-form-devtools-root\";\n containerEl.style.position = \"fixed\";\n containerEl.style.bottom = \"20px\";\n containerEl.style.right = \"20px\";\n containerEl.style.zIndex = \"9999\";\n containerEl.style.maxHeight = \"80vh\";\n containerEl.style.overflowY = \"auto\";\n containerEl.style.boxShadow = \"0 10px 25px rgba(0,0,0,0.1)\";\n document.body.appendChild(containerEl);\n isAutoCreated = true;\n }\n\n let adapterInstance: any;\n\n if (mode === \"local\") {\n console.log(\"[bit-form] DevTools iniciado em modo Local.\");\n adapterInstance = setupLocalDevTools(containerEl);\n } else if (mode === \"remote\") {\n console.log(\"[bit-form] DevTools iniciado em modo Remote.\");\n adapterInstance = setupRemoteDevTools(containerEl, url);\n } else {\n throw new Error(`[bit-form] Modo DevTools inválido: ${mode}`);\n }\n\n return {\n ...adapterInstance,\n destroy: () => {\n if (adapterInstance && typeof adapterInstance.destroy === \"function\") {\n adapterInstance.destroy();\n }\n\n if (isAutoCreated && containerEl.parentNode) {\n containerEl.parentNode.removeChild(containerEl);\n } else {\n containerEl.innerHTML = \"\";\n }\n },\n };\n}\n"]}
|