@planeasyinc/fe-core 0.1.24 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/conditions.d.ts +7 -0
  2. package/dist/conditions.d.ts.map +1 -0
  3. package/dist/conditions.js +62 -0
  4. package/dist/conditions.js.map +1 -0
  5. package/dist/control-traverser.d.ts +3 -0
  6. package/dist/control-traverser.d.ts.map +1 -0
  7. package/dist/control-traverser.js +15 -0
  8. package/dist/control-traverser.js.map +1 -0
  9. package/dist/engine.d.ts +102 -0
  10. package/dist/engine.d.ts.map +1 -0
  11. package/dist/engine.js +506 -0
  12. package/dist/engine.js.map +1 -0
  13. package/dist/index.d.ts +8 -584
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +7 -815
  16. package/dist/index.js.map +1 -1
  17. package/dist/runtime.d.ts +41 -0
  18. package/dist/runtime.d.ts.map +1 -0
  19. package/dist/runtime.js +98 -0
  20. package/dist/runtime.js.map +1 -0
  21. package/dist/schema-guard.d.ts +3 -0
  22. package/dist/schema-guard.d.ts.map +1 -0
  23. package/dist/schema-guard.js +50 -0
  24. package/dist/schema-guard.js.map +1 -0
  25. package/dist/types-list.d.ts +3 -0
  26. package/dist/types-list.d.ts.map +1 -0
  27. package/dist/types-list.js +43 -0
  28. package/dist/types-list.js.map +1 -0
  29. package/dist/types.d.ts +424 -0
  30. package/dist/types.d.ts.map +1 -0
  31. package/dist/types.js +2 -0
  32. package/dist/types.js.map +1 -0
  33. package/dist/validators/default-validators.d.ts +4 -0
  34. package/dist/validators/default-validators.d.ts.map +1 -0
  35. package/dist/validators/default-validators.js +171 -0
  36. package/dist/validators/default-validators.js.map +1 -0
  37. package/dist/validators/index.d.ts +5 -0
  38. package/dist/validators/index.d.ts.map +1 -0
  39. package/dist/validators/index.js +5 -0
  40. package/dist/validators/index.js.map +1 -0
  41. package/dist/validators/pattern-cache.d.ts +2 -0
  42. package/dist/validators/pattern-cache.d.ts.map +1 -0
  43. package/dist/validators/pattern-cache.js +27 -0
  44. package/dist/validators/pattern-cache.js.map +1 -0
  45. package/dist/validators/registry.d.ts +14 -0
  46. package/dist/validators/registry.d.ts.map +1 -0
  47. package/dist/validators/registry.js +24 -0
  48. package/dist/validators/registry.js.map +1 -0
  49. package/dist/validators/types.d.ts +15 -0
  50. package/dist/validators/types.d.ts.map +1 -0
  51. package/dist/validators/types.js +2 -0
  52. package/dist/validators/types.js.map +1 -0
  53. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,816 +1,8 @@
1
- // src/runtime.ts
2
- function createRuntime() {
3
- const state = {
4
- fields: /* @__PURE__ */ new Map(),
5
- deps: /* @__PURE__ */ new Map()
6
- };
7
- const ensureFieldState = (id) => {
8
- if (!state.fields.has(id)) {
9
- state.fields.set(id, {
10
- visible: true,
11
- enabled: true,
12
- required: false,
13
- touched: false,
14
- dirty: false,
15
- status: "VALID",
16
- errors: []
17
- });
18
- }
19
- return state.fields.get(id);
20
- };
21
- const getFieldState = (id) => {
22
- return state.fields.get(id);
23
- };
24
- const setVisible = (id, visible) => {
25
- const field = ensureFieldState(id);
26
- if (field.visible !== visible) {
27
- field.visible = visible;
28
- }
29
- };
30
- const setEnabled = (id, enabled) => {
31
- const field = ensureFieldState(id);
32
- if (field.enabled !== enabled) {
33
- field.enabled = enabled;
34
- }
35
- };
36
- const setRequired = (id, required) => {
37
- const field = ensureFieldState(id);
38
- if (field.required !== required) {
39
- field.required = required;
40
- }
41
- };
42
- const setTouched = (id, touched) => {
43
- const field = ensureFieldState(id);
44
- if (field.touched !== touched) {
45
- field.touched = touched;
46
- }
47
- };
48
- const setDirty = (id, dirty) => {
49
- const field = ensureFieldState(id);
50
- if (field.dirty !== dirty) {
51
- field.dirty = dirty;
52
- }
53
- };
54
- const setStatus = (id, status) => {
55
- const field = ensureFieldState(id);
56
- if (field.status !== status) {
57
- field.status = status;
58
- }
59
- };
60
- const setErrors = (id, errors) => {
61
- const field = ensureFieldState(id);
62
- field.errors = errors;
63
- if (errors.length > 0) {
64
- field.status = "INVALID";
65
- } else if (field.status === "INVALID") {
66
- field.status = "VALID";
67
- }
68
- };
69
- const addDependency = (sourceId, targetId) => {
70
- if (!state.deps.has(sourceId)) {
71
- state.deps.set(sourceId, /* @__PURE__ */ new Set());
72
- }
73
- state.deps.get(sourceId).add(targetId);
74
- };
75
- const getDependents = (id) => {
76
- return state.deps.get(id) || /* @__PURE__ */ new Set();
77
- };
78
- const getDependenciesKeys = () => {
79
- return [...state.deps.keys()];
80
- };
81
- const api = {
82
- state,
83
- ensureFieldState,
84
- getFieldState,
85
- setVisible,
86
- setEnabled,
87
- setRequired,
88
- setTouched,
89
- setDirty,
90
- setStatus,
91
- setErrors,
92
- addDependency,
93
- getDependents,
94
- getDependenciesKeys
95
- };
96
- return { state, api };
97
- }
98
-
99
- // src/validators.ts
100
- var syncValidators = /* @__PURE__ */ new Map();
101
- var asyncValidators = /* @__PURE__ */ new Map();
102
- function registerValidator(name, fn) {
103
- syncValidators.set(name, fn);
104
- }
105
- function registerAsyncValidator(name, fn) {
106
- asyncValidators.set(name, fn);
107
- }
108
- function getValidator(name) {
109
- return syncValidators.get(name);
110
- }
111
- function getAsyncValidator(name) {
112
- return asyncValidators.get(name);
113
- }
114
- registerValidator("required", (value) => {
115
- if (value == null || value === "" || Array.isArray(value) && value.length === 0) {
116
- return {
117
- valid: false,
118
- error: { code: "required", message: "This field is required" }
119
- };
120
- }
121
- return { valid: true };
122
- });
123
- registerValidator("min", (value, args) => {
124
- if (value != null && typeof args === "number" && value < args) {
125
- return {
126
- valid: false,
127
- error: { code: "min", message: `Minimum value is ${args}`, args: { min: args, actual: value } }
128
- };
129
- }
130
- return { valid: true };
131
- });
132
- registerValidator("max", (value, args) => {
133
- if (value != null && typeof args === "number" && value > args) {
134
- return {
135
- valid: false,
136
- error: { code: "max", message: `Maximum value is ${args}`, args: { max: args, actual: value } }
137
- };
138
- }
139
- return { valid: true };
140
- });
141
- registerValidator("minLength", (value, args) => {
142
- if (typeof value === "string" && typeof args === "number" && value.length < args) {
143
- return {
144
- valid: false,
145
- error: { code: "minLength", message: `Minimum length is ${args}`, args: { requiredLength: args, actualLength: value.length } }
146
- };
147
- }
148
- return { valid: true };
149
- });
150
- registerValidator("maxLength", (value, args) => {
151
- if (typeof value === "string" && typeof args === "number" && value.length > args) {
152
- return {
153
- valid: false,
154
- error: { code: "maxLength", message: `Maximum length is ${args}`, args: { requiredLength: args, actualLength: value.length } }
155
- };
156
- }
157
- return { valid: true };
158
- });
159
- registerValidator("pattern", (value, args) => {
160
- if (typeof value === "string" && typeof args === "string") {
161
- try {
162
- const regex = new RegExp(args);
163
- if (!regex.test(value)) {
164
- return {
165
- valid: false,
166
- error: { code: "pattern", message: "Invalid format", args: { requiredPattern: args, actualValue: value } }
167
- };
168
- }
169
- } catch (e) {
170
- return { valid: true };
171
- }
172
- }
173
- return { valid: true };
174
- });
175
- registerValidator("regex", (value, args) => {
176
- return getValidator("pattern")(value, args);
177
- });
178
- registerValidator("email", (value) => {
179
- if (typeof value === "string" && value) {
180
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
181
- if (!emailRegex.test(value)) {
182
- return {
183
- valid: false,
184
- error: { code: "email", message: "Invalid email address" }
185
- };
186
- }
187
- }
188
- return { valid: true };
189
- });
190
- registerValidator("number", (value) => {
191
- if (value != null && (typeof value !== "number" || !Number.isFinite(value))) {
192
- return {
193
- valid: false,
194
- error: { code: "number", message: "Must be a number" }
195
- };
196
- }
197
- return { valid: true };
198
- });
199
- registerValidator("oneOf", (value, args) => {
200
- if (args && Array.isArray(args) && !args.includes(value)) {
201
- return {
202
- valid: false,
203
- error: { code: "oneOf", message: "Value must be one of the allowed options", args: { allowedValues: args } }
204
- };
205
- }
206
- return { valid: true };
207
- });
208
-
209
- // src/schema-guard.ts
210
- function assertFeForm(x) {
211
- if (!x || typeof x !== "object") {
212
- throw new Error("FeForm must be an object");
213
- }
214
- if (!Array.isArray(x.sections)) {
215
- throw new Error("FeForm.sections must be an array");
216
- }
217
- for (let i = 0; i < x.sections.length; i++) {
218
- const section = x.sections[i];
219
- const sectionPath = `sections[${i}]`;
220
- if (!section || typeof section !== "object") {
221
- throw new Error(`${sectionPath} must be an object`);
222
- }
223
- if (typeof section.id !== "string" || !section.id) {
224
- throw new Error(`${sectionPath}.id must be a non-empty string`);
225
- }
226
- if (!Array.isArray(section.controls)) {
227
- throw new Error(`${sectionPath}.controls must be an array`);
228
- }
229
- validateControls(section.controls, `${sectionPath}.controls`);
230
- }
231
- if (x.controls !== void 0) {
232
- if (!Array.isArray(x.controls)) {
233
- throw new Error("FeForm.controls must be an array if present");
234
- }
235
- validateControls(x.controls, "controls");
236
- }
237
- }
238
- function validateControls(controls, path) {
239
- for (let i = 0; i < controls.length; i++) {
240
- const control = controls[i];
241
- const controlPath = `${path}[${i}]`;
242
- if (!control || typeof control !== "object") {
243
- throw new Error(`${controlPath} must be an object`);
244
- }
245
- if (typeof control.type !== "string" || !control.type) {
246
- throw new Error(`${controlPath}.type must be a non-empty string`);
247
- }
248
- if (typeof control.name !== "string" || !control.name) {
249
- throw new Error(`${controlPath}.name must be a non-empty string`);
250
- }
251
- if (control.controls && Array.isArray(control.controls)) {
252
- validateControls(control.controls, `${controlPath}.controls`);
253
- }
254
- if (control.control && typeof control.control === "object") {
255
- validateControls([control.control], `${controlPath}.control`);
256
- }
257
- }
258
- }
259
-
260
- // src/engine.ts
261
- function isBackendGroup(x) {
262
- return x && Array.isArray(x.conditions);
263
- }
264
- function evalBackendSimple(values, c) {
265
- const id = c.target_id || c.field;
266
- const opName = String(c.condition || "").toLowerCase();
267
- const value = values[id];
268
- switch (opName) {
269
- case "eq":
270
- return value === c.value;
271
- case "neq":
272
- return value !== c.value;
273
- case "gt":
274
- return value != null && c.value != null && value > c.value;
275
- case "gte":
276
- return value != null && c.value != null && value >= c.value;
277
- case "lt":
278
- return value != null && c.value != null && value < c.value;
279
- case "lte":
280
- return value != null && c.value != null && value <= c.value;
281
- case "exists":
282
- return value !== null && value !== void 0;
283
- case "contains":
284
- return value != null && c.value != null && value.includes(c.value);
285
- case "in":
286
- return value != null && c.value != null && c.value.includes(value);
287
- default:
288
- return true;
289
- }
290
- }
291
- function evalBackendGroup(values, g) {
292
- const op = String(g.operation || g.operator || "and").toLowerCase();
293
- const list = (g.conditions || []).filter(Boolean);
294
- if (op === "or") {
295
- return list.some(
296
- (cond) => isBackendGroup(cond) ? evalBackendGroup(values, cond) : evalBackendSimple(values, cond)
297
- );
298
- }
299
- return list.every(
300
- (cond) => isBackendGroup(cond) ? evalBackendGroup(values, cond) : evalBackendSimple(values, cond)
301
- );
302
- }
303
- var FeFormEngine = class {
304
- schema;
305
- state;
306
- runtime;
307
- listeners = /* @__PURE__ */ new Map();
308
- batchMode = false;
309
- pendingEmits = /* @__PURE__ */ new Set();
310
- pendingValueChanges = false;
311
- pendingFieldStateChanges = /* @__PURE__ */ new Map();
312
- pendingErrorsChanges = /* @__PURE__ */ new Map();
313
- asyncValidators = /* @__PURE__ */ new Map();
314
- conditions = /* @__PURE__ */ new Map();
315
- resolvers;
316
- constructor(schema, options = {}, resolvers = {}) {
317
- assertFeForm(schema);
318
- this.schema = schema;
319
- const { state: runtimeState, api: runtimeAPI } = createRuntime();
320
- this.runtime = runtimeAPI;
321
- this.resolvers = resolvers;
322
- this.state = {
323
- values: options.initialValues || this.extractInitialValues(),
324
- errors: {},
325
- touched: {},
326
- dirty: {},
327
- valid: false
328
- };
329
- this.initializeFieldStates();
330
- this.buildDependencyGraph();
331
- this.executeConditions();
332
- if (options.validateOnChange !== false) {
333
- this.validate();
334
- }
335
- }
336
- triggerAction(e) {
337
- this.emit("action", e);
338
- }
339
- initializeFieldStates() {
340
- this.traverseSchema((control) => {
341
- const fieldState = this.runtime.ensureFieldState(control.id);
342
- if (control.required) {
343
- fieldState.required = true;
344
- } else if (control.validators) {
345
- const hasRequired = control.validators.some(
346
- (v) => "function" in v && v.function === "required"
347
- );
348
- fieldState.required = hasRequired;
349
- }
350
- fieldState.visible = true;
351
- fieldState.enabled = true;
352
- });
353
- }
354
- buildDependencyGraph() {
355
- this.traverseSchema((control) => {
356
- if ("condition" in control && control.condition) {
357
- this.extractCondition(control.condition, control.id);
358
- this.extractConditionPaths(control.condition, control.id);
359
- }
360
- });
361
- }
362
- executeConditions() {
363
- const keys = this.runtime.getDependenciesKeys();
364
- keys.forEach((key) => {
365
- this.reevaluateDependents(key);
366
- });
367
- }
368
- extractCondition(condition, targetId) {
369
- this.conditions.set(targetId, condition);
370
- }
371
- extractConditionPaths(condition, targetId) {
372
- if (isBackendGroup(condition)) {
373
- if ("conditions" in condition && condition.conditions) {
374
- for (const cond of condition.conditions) {
375
- this.extractConditionPaths(cond, targetId);
376
- }
377
- }
378
- }
379
- if ("target_id" in condition && condition.target_id) {
380
- this.runtime.addDependency(condition.target_id, targetId);
381
- }
382
- }
383
- reevaluateDependents(changedId) {
384
- const visited = /* @__PURE__ */ new Set();
385
- const queue = [changedId];
386
- while (queue.length > 0) {
387
- const currentId = queue.shift();
388
- if (visited.has(currentId)) continue;
389
- visited.add(currentId);
390
- const dependents = this.runtime.getDependents(currentId);
391
- for (const dependentId of dependents) {
392
- if (!visited.has(dependentId)) {
393
- queue.push(dependentId);
394
- this.evaluateFieldConditions(dependentId);
395
- }
396
- }
397
- }
398
- }
399
- evaluateFieldConditions(id) {
400
- const condition = this.conditions.get(id);
401
- if (!condition) {
402
- if (this.batchMode) {
403
- const state = this.runtime.getFieldState(id);
404
- if (state) {
405
- this.pendingFieldStateChanges.set(id, state);
406
- }
407
- }
408
- return;
409
- }
410
- const result = this.evaluateCondition(condition);
411
- const fieldState = this.runtime.getFieldState(id);
412
- if (fieldState) {
413
- const wasVisible = fieldState.visible;
414
- this.runtime.setVisible(id, result);
415
- if (this.batchMode || wasVisible !== result) {
416
- this.emitFieldStateChange(id);
417
- }
418
- }
419
- }
420
- evaluateCondition(condition) {
421
- const values = this.state.values;
422
- return isBackendGroup(condition) ? evalBackendGroup(values, condition) : evalBackendSimple(values, condition);
423
- }
424
- emitFieldStateChange(id) {
425
- const state = this.runtime.getFieldState(id);
426
- if (!state) return;
427
- if (this.batchMode) {
428
- this.pendingFieldStateChanges.set(id, state);
429
- this.pendingEmits.add("fieldStateChanges");
430
- } else {
431
- this.emit("fieldStateChanges", id, state);
432
- }
433
- }
434
- emitErrorsChange(id, errors) {
435
- if (this.batchMode) {
436
- this.pendingErrorsChanges.set(id, errors);
437
- this.pendingEmits.add("errorsChanges");
438
- } else {
439
- this.emit("errorsChanges", id, errors);
440
- }
441
- }
442
- extractInitialValues() {
443
- const values = {};
444
- this.traverseSchema((control) => {
445
- if ("value" in control && control.value !== void 0) {
446
- values[control.id] = control.value;
447
- }
448
- });
449
- return values;
450
- }
451
- get values() {
452
- return {
453
- get: (id, ctx) => {
454
- if (ctx?.index !== void 0) {
455
- return this.state.values[id]?.[ctx.index];
456
- } else if (ctx?.key !== void 0) {
457
- return this.state.values[id]?.[ctx.key];
458
- } else {
459
- return this.state.values[id];
460
- }
461
- },
462
- set: (id, value, ctx) => {
463
- if (ctx?.index !== void 0) {
464
- this.state.values[id][ctx.index] = value;
465
- } else if (ctx?.key !== void 0) {
466
- this.state.values[id][ctx.key] = value;
467
- } else {
468
- this.state.values[id] = value;
469
- }
470
- this.state.dirty[id] = true;
471
- this.runtime.setDirty(id, true);
472
- if (this.batchMode) {
473
- const state = this.runtime.getFieldState(id);
474
- if (state) {
475
- this.pendingFieldStateChanges.set(id, state);
476
- }
477
- }
478
- this.reevaluateDependents(id);
479
- if (this.batchMode) {
480
- this.pendingValueChanges = true;
481
- this.pendingEmits.add("valueChanges");
482
- } else {
483
- this.emit("valueChanges", this.state.values);
484
- this.validate();
485
- }
486
- },
487
- getAll: () => ({ ...this.state.values })
488
- };
489
- }
490
- get status() {
491
- return {
492
- valid: this.state.valid,
493
- errors: { ...this.state.errors },
494
- touched: { ...this.state.touched },
495
- dirty: { ...this.state.dirty }
496
- };
497
- }
498
- getFieldState(id) {
499
- return this.runtime.ensureFieldState(id);
500
- }
501
- registerValidator(name, fn) {
502
- registerValidator(name, fn);
503
- }
504
- registerAsyncValidator(name, fn) {
505
- registerAsyncValidator(name, fn);
506
- }
507
- batch(fn) {
508
- const wasBatching = this.batchMode;
509
- this.batchMode = true;
510
- this.pendingEmits.clear();
511
- this.pendingValueChanges = false;
512
- this.pendingFieldStateChanges.clear();
513
- this.pendingErrorsChanges.clear();
514
- try {
515
- fn();
516
- } finally {
517
- this.batchMode = wasBatching;
518
- if (!wasBatching) {
519
- if (this.pendingValueChanges) {
520
- this.emit("valueChanges", this.state.values);
521
- }
522
- const affectedIds = /* @__PURE__ */ new Set();
523
- for (const id of this.pendingFieldStateChanges.keys()) {
524
- affectedIds.add(id);
525
- }
526
- for (const id of affectedIds) {
527
- const state = this.runtime.getFieldState(id);
528
- if (state) {
529
- this.emit("fieldStateChanges", id, state);
530
- }
531
- }
532
- for (const [id, errors] of this.pendingErrorsChanges) {
533
- this.emit("errorsChanges", id, errors);
534
- }
535
- this.validate();
536
- for (const id of affectedIds) {
537
- const state = this.runtime.getFieldState(id);
538
- if (state && !this.pendingFieldStateChanges.has(id)) {
539
- this.emit("fieldStateChanges", id, state);
540
- }
541
- }
542
- }
543
- }
544
- }
545
- on(event, listener) {
546
- if (!this.listeners.has(event)) {
547
- this.listeners.set(event, /* @__PURE__ */ new Set());
548
- }
549
- this.listeners.get(event).add(listener);
550
- return () => {
551
- this.listeners.get(event)?.delete(listener);
552
- };
553
- }
554
- emit(event, ...args) {
555
- this.listeners.get(event)?.forEach((listener) => {
556
- try {
557
- listener(...args);
558
- } catch (error) {
559
- console.error(`Error in ${event} listener:`, error);
560
- }
561
- });
562
- }
563
- validate() {
564
- const errors = {};
565
- let isValid = true;
566
- const visitor = (control) => {
567
- const value = this.state.values[control.id];
568
- const fieldErrors = [];
569
- if (control.validators) {
570
- for (const validator of control.validators) {
571
- if ("function" in validator) {
572
- const registryValidator = getValidator(validator.function);
573
- if (registryValidator) {
574
- const ctx = {
575
- get: (id) => this.state.values[id]
576
- };
577
- const result = registryValidator(value, validator.value, ctx);
578
- if (!result.valid && result.error) {
579
- errors[control.id] = result.error.args || { [result.error.code]: true };
580
- isValid = false;
581
- fieldErrors.push({
582
- code: result.error.code,
583
- message: result.error.message,
584
- args: result.error.args
585
- });
586
- this.emitFieldStateChange(control.id);
587
- }
588
- } else {
589
- const error = this.validateControlValidator(validator, value);
590
- if (error) {
591
- errors[control.id] = error;
592
- isValid = false;
593
- fieldErrors.push({
594
- code: validator.function,
595
- args: error
596
- });
597
- this.emitFieldStateChange(control.id);
598
- }
599
- }
600
- }
601
- }
602
- }
603
- if (control.validators) {
604
- for (const validator of control.validators) {
605
- if ("function" in validator) {
606
- const asyncValidator = getAsyncValidator(validator.function);
607
- if (asyncValidator && isValid && !fieldErrors.length) {
608
- const existingController = this.asyncValidators.get(control.id);
609
- if (existingController) {
610
- existingController.abort();
611
- }
612
- const fieldState2 = this.runtime.getFieldState(control.id);
613
- if (fieldState2) {
614
- this.runtime.setStatus(control.id, "PENDING");
615
- this.emitFieldStateChange(control.id);
616
- }
617
- const controller = new AbortController();
618
- this.asyncValidators.set(control.id, controller);
619
- const ctx = {
620
- get: (id) => this.state.values[id],
621
- signal: controller.signal
622
- };
623
- asyncValidator(value, validator.value, ctx).then((result) => {
624
- if (!controller.signal.aborted && this.asyncValidators.get(control.id) === controller) {
625
- if (!result.valid && result.error) {
626
- const currentErrors = { ...this.state.errors };
627
- currentErrors[control.id] = result.error.args || {
628
- [result.error.code]: true
629
- };
630
- this.state.errors = currentErrors;
631
- this.state.valid = false;
632
- const asyncFieldErrors = [
633
- {
634
- code: result.error.code,
635
- message: result.error.message,
636
- args: result.error.args
637
- }
638
- ];
639
- this.runtime.setErrors(control.id, asyncFieldErrors);
640
- this.runtime.setStatus(control.id, "INVALID");
641
- this.emitErrorsChange(control.id, asyncFieldErrors);
642
- this.emitFieldStateChange(control.id);
643
- this.emit("statusChanges", { valid: false, errors: currentErrors });
644
- } else {
645
- this.runtime.setStatus(control.id, "VALID");
646
- this.emitFieldStateChange(control.id);
647
- }
648
- this.asyncValidators.delete(control.id);
649
- }
650
- }).catch((error) => {
651
- if (!controller.signal.aborted) {
652
- console.error(`Async validator error for ${control.id}:`, error);
653
- this.runtime.setStatus(control.id, "VALID");
654
- this.asyncValidators.delete(control.id);
655
- }
656
- });
657
- }
658
- }
659
- }
660
- }
661
- if ("validation" in control && control.validation) {
662
- const error = this.validateBackend(control.validation);
663
- if (error) {
664
- errors[control.id] = error;
665
- isValid = false;
666
- fieldErrors.push({
667
- code: "backendValidation",
668
- args: error
669
- });
670
- }
671
- }
672
- const fieldState = this.runtime.getFieldState(control.id);
673
- if (fieldState) {
674
- const hadErrors = fieldState.errors.length > 0;
675
- this.runtime.setErrors(control.id, fieldErrors);
676
- this.runtime.setStatus(control.id, fieldErrors.length > 0 ? "INVALID" : "VALID");
677
- if (hadErrors !== fieldErrors.length > 0) {
678
- this.emitErrorsChange(control.id, fieldErrors);
679
- }
680
- }
681
- };
682
- const shouldVisit = (control) => {
683
- const state = this.runtime.getFieldState(control.id);
684
- return !!state?.visible;
685
- };
686
- this.traverseSchema(visitor, shouldVisit);
687
- this.state.errors = errors;
688
- this.state.valid = isValid;
689
- if (!this.batchMode) {
690
- this.emit("statusChanges", { valid: isValid, errors });
691
- } else {
692
- this.pendingEmits.add("statusChanges");
693
- }
694
- return isValid;
695
- }
696
- validateControlValidator(validator, value) {
697
- switch (validator.function) {
698
- case "required":
699
- if (value == null || value === "" || Array.isArray(value) && value.length === 0) {
700
- return { required: true };
701
- }
702
- break;
703
- case "min":
704
- if (typeof validator.value === "number" && value != null && value < validator.value) {
705
- return { min: { min: validator.value, actual: value } };
706
- }
707
- break;
708
- case "max":
709
- if (typeof validator.value === "number" && value != null && typeof value === "number" && value > validator.value) {
710
- return { max: { max: validator.value, actual: value } };
711
- }
712
- break;
713
- case "minLength":
714
- if (typeof validator.value === "number" && typeof value === "string" && value.length < validator.value) {
715
- return { minLength: { requiredLength: validator.value, actualLength: value.length } };
716
- }
717
- break;
718
- case "maxLength":
719
- if (typeof validator.value === "number" && typeof value === "string" && value.length > validator.value) {
720
- return { maxLength: { requiredLength: validator.value, actualLength: value.length } };
721
- }
722
- break;
723
- case "pattern":
724
- if (typeof validator.value === "string" && typeof value === "string" && !new RegExp(validator.value).test(value)) {
725
- return { pattern: { requiredPattern: validator.value, actualValue: value } };
726
- }
727
- break;
728
- }
729
- return null;
730
- }
731
- validateBackend(validation) {
732
- const values = this.state.values;
733
- const ok = isBackendGroup(validation) ? evalBackendGroup(values, validation) : evalBackendSimple(values, validation);
734
- if (!ok) {
735
- return { backendValidation: { message: "Validation failed", validation } };
736
- }
737
- return null;
738
- }
739
- markTouched(id) {
740
- this.state.touched[id] = true;
741
- this.runtime.setTouched(id, true);
742
- this.emitFieldStateChange(id);
743
- if (!this.batchMode) {
744
- this.emit("statusChanges", { valid: this.state.valid, errors: this.state.errors });
745
- }
746
- }
747
- markAllTouched() {
748
- this.traverseSchema((control) => {
749
- this.markTouched(control.id);
750
- });
751
- }
752
- markAsDirty(id) {
753
- this.runtime.setDirty(id, true);
754
- this.state.dirty[id] = true;
755
- this.emitFieldStateChange(id);
756
- }
757
- markAllAsDirty() {
758
- this.traverseSchema((control) => {
759
- this.markAsDirty(control.id);
760
- });
761
- }
762
- submit() {
763
- if (!this.validate()) {
764
- return null;
765
- }
766
- const values = this.values.getAll();
767
- this.emit("submit", values);
768
- return values;
769
- }
770
- reset(values) {
771
- this.state.values = values || this.extractInitialValues();
772
- this.state.errors = {};
773
- this.state.touched = {};
774
- this.state.dirty = {};
775
- this.state.valid = false;
776
- this.emit("valueChanges", this.state.values);
777
- this.validate();
778
- }
779
- traverseSchema(visit, shouldVisit = () => true) {
780
- this.schema.sections.forEach((section) => {
781
- section.controls.forEach((control) => this.processControl(control, visit, shouldVisit));
782
- });
783
- if (this.schema.controls) {
784
- this.schema.controls.forEach((control) => this.processControl(control, visit, shouldVisit));
785
- }
786
- }
787
- processControl(control, visit, shouldVisit) {
788
- if (!shouldVisit(control)) return;
789
- if ("controls" in control && control.controls) {
790
- control.controls.forEach((c) => this.processControl(c, visit, shouldVisit));
791
- }
792
- if ("control" in control && control.control) {
793
- this.processControl(control.control, visit, shouldVisit);
794
- }
795
- if ("meta" in control && control.meta && "controls" in control.meta && control.meta.controls) {
796
- control.meta.controls.forEach(
797
- (c) => this.processControl(c, visit, shouldVisit)
798
- );
799
- }
800
- visit(control);
801
- }
802
- };
803
- function createEngine(schema, options, resolvers) {
804
- return new FeFormEngine(schema, options, resolvers);
805
- }
806
- export {
807
- FeFormEngine,
808
- assertFeForm,
809
- createEngine,
810
- createRuntime,
811
- getAsyncValidator,
812
- getValidator,
813
- registerAsyncValidator,
814
- registerValidator
815
- };
1
+ export * from './types';
2
+ export * from './types-list';
3
+ export * from './runtime';
4
+ export * from './validators/types';
5
+ export * from './validators/registry';
6
+ export * from './schema-guard';
7
+ export * from './engine';
816
8
  //# sourceMappingURL=index.js.map