@remoteoss/json-schema-form 0.11.11-dev.20250220174843 → 1.0.0-beta.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/dist/index.js DELETED
@@ -1,2140 +0,0 @@
1
-
2
- /*!
3
- Copyright (c) 2025 Remote Technology, Inc.
4
- NPM Package: @remoteoss/json-schema-form@0.11.11-dev.20250220174843
5
- Generated: Thu, 20 Feb 2025 17:48:57 GMT
6
-
7
- MIT License
8
-
9
- Copyright (c) 2023 Remote Technology, Inc.
10
-
11
- Permission is hereby granted, free of charge, to any person obtaining a copy
12
- of this software and associated documentation files (the "Software"), to deal
13
- in the Software without restriction, including without limitation the rights
14
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
- copies of the Software, and to permit persons to whom the Software is
16
- furnished to do so, subject to the following conditions:
17
-
18
- The above copyright notice and this permission notice shall be included in all
19
- copies or substantial portions of the Software.
20
-
21
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
- SOFTWARE.
28
-
29
- */
30
-
31
- // src/createHeadlessForm.js
32
- import get3 from "lodash/get";
33
- import isNil3 from "lodash/isNil";
34
- import omit3 from "lodash/omit";
35
- import omitBy2 from "lodash/omitBy";
36
- import pick2 from "lodash/pick";
37
- import size from "lodash/size";
38
-
39
- // src/calculateConditionalProperties.js
40
- import merge2 from "lodash/merge";
41
- import omit2 from "lodash/omit";
42
-
43
- // src/helpers.js
44
- import get2 from "lodash/get";
45
- import isNil from "lodash/isNil";
46
- import omit from "lodash/omit";
47
- import omitBy from "lodash/omitBy";
48
- import set from "lodash/set";
49
- import { lazy } from "yup";
50
-
51
- // src/utils.js
52
- function convertDiskSizeFromTo(from, to) {
53
- const units = ["bytes", "kb", "mb"];
54
- return function convert(value) {
55
- return value * Math.pow(1024, units.indexOf(from.toLowerCase())) / Math.pow(1024, units.indexOf(to.toLowerCase()));
56
- };
57
- }
58
- function hasProperty(object2, propertyName) {
59
- return Object.prototype.hasOwnProperty.call(object2, propertyName);
60
- }
61
-
62
- // src/internals/checkIfConditionMatches.js
63
- function checkIfConditionMatchesProperties(node, formValues, formFields, logic) {
64
- if (typeof node.if === "boolean") {
65
- return node.if;
66
- }
67
- return Object.keys(node.if.properties ?? {}).every((name) => {
68
- const currentProperty = node.if.properties[name];
69
- const value = formValues[name];
70
- const hasEmptyValue = typeof value === "undefined" || // NOTE: This is a "Remote API" dependency, as empty fields are sent as "null".
71
- value === null;
72
- const hasIfExplicit = node.if.required?.includes(name);
73
- if (hasEmptyValue && !hasIfExplicit) {
74
- return true;
75
- }
76
- if (hasProperty(currentProperty, "const")) {
77
- return compareFormValueWithSchemaValue(value, currentProperty.const);
78
- }
79
- if (currentProperty.contains?.pattern) {
80
- const formValue = value || [];
81
- if (Array.isArray(formValue)) {
82
- const pattern = new RegExp(currentProperty.contains.pattern);
83
- return (value || []).some((item) => pattern.test(item));
84
- }
85
- }
86
- if (currentProperty.enum) {
87
- return currentProperty.enum.includes(value);
88
- }
89
- if (currentProperty.properties) {
90
- return checkIfConditionMatchesProperties(
91
- { if: currentProperty },
92
- formValues[name],
93
- getField(name, formFields).fields,
94
- logic
95
- );
96
- }
97
- const field = getField(name, formFields);
98
- return validateFieldSchema(
99
- {
100
- ...field,
101
- ...currentProperty,
102
- required: true
103
- },
104
- value
105
- );
106
- });
107
- }
108
- function checkIfMatchesValidationsAndComputedValues(node, formValues, logic, parentID) {
109
- const validationsMatch = Object.entries(node.if.validations ?? {}).every(([name, property]) => {
110
- const currentValue = logic.getScope(parentID).applyValidationRuleInCondition(name, formValues);
111
- if (Object.hasOwn(property, "const") && currentValue === property.const)
112
- return true;
113
- return false;
114
- });
115
- const computedValuesMatch = Object.entries(node.if.computedValues ?? {}).every(
116
- ([name, property]) => {
117
- const currentValue = logic.getScope(parentID).applyComputedValueRuleInCondition(name, formValues);
118
- if (Object.hasOwn(property, "const") && currentValue === property.const)
119
- return true;
120
- return false;
121
- }
122
- );
123
- return computedValuesMatch && validationsMatch;
124
- }
125
-
126
- // src/internals/helpers.js
127
- import merge from "lodash/fp/merge";
128
- import get from "lodash/get";
129
- import isEmpty from "lodash/isEmpty";
130
- import isFunction from "lodash/isFunction";
131
- function pickXKey(node, key) {
132
- const deprecatedKeys = ["presentation", "errorMessage"];
133
- return get(node, `x-jsf-${key}`, deprecatedKeys.includes(key) ? node?.[key] : void 0);
134
- }
135
- function getFieldDescription(node, customProperties = {}) {
136
- const nodeDescription = node?.description ? {
137
- description: node.description
138
- } : {};
139
- const customDescription = customProperties?.description ? {
140
- description: isFunction(customProperties.description) ? customProperties.description(node?.description, {
141
- ...node,
142
- ...customProperties
143
- }) : customProperties.description
144
- } : {};
145
- const nodePresentation = pickXKey(node, "presentation");
146
- const presentation = !isEmpty(nodePresentation) && {
147
- presentation: { ...nodePresentation, ...customDescription }
148
- };
149
- return merge(nodeDescription, { ...customDescription, ...presentation });
150
- }
151
-
152
- // src/internals/fields.js
153
- var jsonTypes = {
154
- STRING: "string",
155
- NUMBER: "number",
156
- INTEGER: "integer",
157
- OBJECT: "object",
158
- ARRAY: "array",
159
- BOOLEAN: "boolean",
160
- NULL: "null"
161
- };
162
- var supportedTypes = {
163
- TEXT: "text",
164
- NUMBER: "number",
165
- SELECT: "select",
166
- FILE: "file",
167
- RADIO: "radio",
168
- GROUP_ARRAY: "group-array",
169
- EMAIL: "email",
170
- DATE: "date",
171
- CHECKBOX: "checkbox",
172
- FIELDSET: "fieldset"
173
- };
174
- var jsonTypeToInputType = {
175
- [jsonTypes.STRING]: ({ oneOf, format }) => {
176
- if (format === "email")
177
- return supportedTypes.EMAIL;
178
- if (format === "date")
179
- return supportedTypes.DATE;
180
- if (format === "data-url")
181
- return supportedTypes.FILE;
182
- if (oneOf)
183
- return supportedTypes.RADIO;
184
- return supportedTypes.TEXT;
185
- },
186
- [jsonTypes.NUMBER]: () => supportedTypes.NUMBER,
187
- [jsonTypes.INTEGER]: () => supportedTypes.NUMBER,
188
- [jsonTypes.OBJECT]: () => supportedTypes.FIELDSET,
189
- [jsonTypes.ARRAY]: ({ items }) => {
190
- if (items.properties)
191
- return supportedTypes.GROUP_ARRAY;
192
- return supportedTypes.SELECT;
193
- },
194
- [jsonTypes.BOOLEAN]: () => supportedTypes.CHECKBOX
195
- };
196
- function getInputType(fieldProperties, strictInputType, name) {
197
- const presentation = pickXKey(fieldProperties, "presentation") ?? {};
198
- const presentationInputType = presentation?.inputType;
199
- if (presentationInputType) {
200
- return presentationInputType;
201
- }
202
- if (strictInputType) {
203
- throw Error(`Strict error: Missing inputType to field "${name || fieldProperties.title}".
204
- You can fix the json schema or skip this error by calling createHeadlessForm(schema, { strictInputType: false })`);
205
- }
206
- if (!fieldProperties.type) {
207
- if (fieldProperties.items?.properties) {
208
- return supportedTypes.GROUP_ARRAY;
209
- }
210
- if (fieldProperties.properties) {
211
- return supportedTypes.SELECT;
212
- }
213
- return jsonTypeToInputType[jsonTypes.STRING](fieldProperties);
214
- }
215
- return jsonTypeToInputType[fieldProperties.type]?.(fieldProperties);
216
- }
217
- function _composeFieldFile({ name, label, description, accept, required = true, ...attrs }) {
218
- return {
219
- type: supportedTypes.FILE,
220
- name,
221
- label,
222
- description,
223
- required,
224
- accept,
225
- ...attrs
226
- };
227
- }
228
- function _composeFieldText({ name, label, description, required = true, ...attrs }) {
229
- return {
230
- type: supportedTypes.TEXT,
231
- name,
232
- label,
233
- description,
234
- required,
235
- ...attrs
236
- };
237
- }
238
- function _composeFieldEmail({ name, label, required = true, ...attrs }) {
239
- return {
240
- type: supportedTypes.EMAIL,
241
- name,
242
- label,
243
- required,
244
- ...attrs
245
- };
246
- }
247
- function _composeFieldNumber({
248
- name,
249
- label,
250
- percentage = false,
251
- required = true,
252
- minimum,
253
- maximum,
254
- ...attrs
255
- }) {
256
- let minValue = minimum;
257
- let maxValue = maximum;
258
- if (percentage) {
259
- minValue = minValue ?? 0;
260
- maxValue = maxValue ?? 100;
261
- }
262
- return {
263
- type: supportedTypes.NUMBER,
264
- name,
265
- label,
266
- percentage,
267
- required,
268
- minimum: minValue,
269
- maximum: maxValue,
270
- ...attrs
271
- };
272
- }
273
- function _composeFieldDate({ name, label, required = true, ...attrs }) {
274
- return {
275
- type: supportedTypes.DATE,
276
- name,
277
- label,
278
- required,
279
- ...attrs
280
- };
281
- }
282
- function _composeFieldRadio({ name, label, options, required = true, ...attrs }) {
283
- return {
284
- type: supportedTypes.RADIO,
285
- name,
286
- label,
287
- options,
288
- required,
289
- ...attrs
290
- };
291
- }
292
- function _composeFieldSelect({ name, label, options, required = true, ...attrs }) {
293
- return {
294
- type: supportedTypes.SELECT,
295
- name,
296
- label,
297
- options,
298
- required,
299
- ...attrs
300
- };
301
- }
302
- function _composeNthFieldGroup({ name, label, required, nthFieldGroup, ...attrs }) {
303
- return [
304
- {
305
- ...nthFieldGroup,
306
- type: supportedTypes.GROUP_ARRAY,
307
- name,
308
- label,
309
- required,
310
- ...attrs
311
- }
312
- ];
313
- }
314
- function _composeFieldCheckbox({
315
- required = true,
316
- name,
317
- label,
318
- description,
319
- default: defaultValue,
320
- checkboxValue,
321
- ...attrs
322
- }) {
323
- return {
324
- type: supportedTypes.CHECKBOX,
325
- required,
326
- name,
327
- label,
328
- description,
329
- checkboxValue,
330
- ...defaultValue && { default: defaultValue },
331
- ...attrs
332
- };
333
- }
334
- function _composeFieldset({ name, label, fields, variant, ...attrs }) {
335
- return {
336
- type: supportedTypes.FIELDSET,
337
- name,
338
- label,
339
- fields,
340
- variant,
341
- ...attrs
342
- };
343
- }
344
- var _composeFieldArbitraryClosure = (inputType) => (attrs) => ({
345
- type: inputType,
346
- ...attrs
347
- });
348
- var inputTypeMap = {
349
- text: _composeFieldText,
350
- select: _composeFieldSelect,
351
- radio: _composeFieldRadio,
352
- date: _composeFieldDate,
353
- number: _composeFieldNumber,
354
- "group-array": _composeNthFieldGroup,
355
- fieldset: _composeFieldset,
356
- file: _composeFieldFile,
357
- email: _composeFieldEmail,
358
- checkbox: _composeFieldCheckbox
359
- };
360
- function _composeFieldCustomClosure(defaultComposeFn) {
361
- return ({ fieldCustomization, ...attrs }) => {
362
- const { description, ...restFieldCustomization } = fieldCustomization;
363
- const fieldDescription = getFieldDescription(attrs, fieldCustomization);
364
- const { nthFieldGroup, ...restAttrs } = attrs;
365
- const commonAttrs = {
366
- ...restAttrs,
367
- ...restFieldCustomization,
368
- ...fieldDescription
369
- };
370
- if (attrs.inputType === supportedTypes.GROUP_ARRAY) {
371
- return [
372
- {
373
- ...nthFieldGroup,
374
- ...commonAttrs
375
- }
376
- ];
377
- }
378
- return {
379
- ...defaultComposeFn(attrs),
380
- ...commonAttrs
381
- };
382
- };
383
- }
384
-
385
- // src/jsonLogic.js
386
- import jsonLogic from "json-logic-js";
387
-
388
- // src/yupSchema.js
389
- import flow from "lodash/flow";
390
- import noop from "lodash/noop";
391
- import { randexp } from "randexp";
392
- import { string, number, boolean, object, array, mixed } from "yup";
393
- var DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
394
- var baseString = string().trim();
395
- var todayDateHint = (/* @__PURE__ */ new Date()).toISOString().substring(0, 10);
396
- var convertBytesToKB = convertDiskSizeFromTo("Bytes", "KB");
397
- var convertKbBytesToMB = convertDiskSizeFromTo("KB", "MB");
398
- var validateOnlyStrings = string().trim().nullable().test(
399
- "is-string",
400
- "${path} must be a `string` type, but the final value was: `${value}`.",
401
- (value, context) => {
402
- if (context.originalValue !== null && context.originalValue !== void 0) {
403
- return typeof context.originalValue === "string";
404
- }
405
- return true;
406
- }
407
- );
408
- var compareDates = (d1, d2) => {
409
- let date1 = new Date(d1).getTime();
410
- let date2 = new Date(d2).getTime();
411
- if (date1 < date2) {
412
- return "LESSER";
413
- } else if (date1 > date2) {
414
- return "GREATER";
415
- } else {
416
- return "EQUAL";
417
- }
418
- };
419
- var validateMinDate = (value, minDate) => {
420
- const compare = compareDates(value, minDate);
421
- return compare === "GREATER" || compare === "EQUAL" ? true : false;
422
- };
423
- var validateMaxDate = (value, minDate) => {
424
- const compare = compareDates(value, minDate);
425
- return compare === "LESSER" || compare === "EQUAL" ? true : false;
426
- };
427
- var validateRadioOrSelectOptions = (value, options) => {
428
- if (value === void 0)
429
- return true;
430
- const exactMatch = options.some((option) => option.value === value);
431
- if (exactMatch)
432
- return true;
433
- const patternMatch = options.some((option) => option.pattern?.test(value));
434
- return !!patternMatch;
435
- };
436
- var yupSchemas = {
437
- text: validateOnlyStrings,
438
- radioOrSelectString: (options) => {
439
- return string().nullable().transform((value) => {
440
- if (value === "") {
441
- return void 0;
442
- }
443
- if (options?.some((option) => option.value === null)) {
444
- return value;
445
- }
446
- return value === null ? void 0 : value;
447
- }).test(
448
- "matchesOptionOrPattern",
449
- ({ value }) => `The option ${JSON.stringify(value)} is not valid.`,
450
- (castValue, { originalValue }) => {
451
- if (castValue !== void 0 && typeof originalValue !== "string") {
452
- return false;
453
- }
454
- return validateRadioOrSelectOptions(castValue, options);
455
- }
456
- );
457
- },
458
- date: ({ minDate, maxDate }) => {
459
- let dateString = string().nullable().transform((value) => {
460
- if (value === "") {
461
- return void 0;
462
- }
463
- return value === null ? void 0 : value;
464
- }).trim().matches(
465
- /(?:\d){4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9]|3[0-1])/,
466
- `Must be a valid date in ${DEFAULT_DATE_FORMAT.toLocaleLowerCase()} format. e.g. ${todayDateHint}`
467
- );
468
- if (minDate) {
469
- dateString = dateString.test(
470
- "minDate",
471
- `The date must be ${minDate} or after.`,
472
- (value) => validateMinDate(value, minDate)
473
- );
474
- }
475
- if (maxDate) {
476
- dateString = dateString.test(
477
- "maxDate",
478
- `The date must be ${maxDate} or before.`,
479
- (value) => validateMaxDate(value, maxDate)
480
- );
481
- }
482
- return dateString;
483
- },
484
- radioOrSelectNumber: (options) => mixed().typeError("The value must be a number").transform((value) => {
485
- if (options?.some((option) => option.value === null)) {
486
- return value;
487
- }
488
- return value === null ? void 0 : value;
489
- }).test(
490
- "matchesOptionOrPattern",
491
- ({ value }) => {
492
- return `The option ${JSON.stringify(value)} is not valid.`;
493
- },
494
- (value) => {
495
- if (value !== void 0 && typeof value !== "number")
496
- return false;
497
- return validateRadioOrSelectOptions(value, options);
498
- }
499
- ).nullable(),
500
- radioOrSelectBoolean: (options) => {
501
- return boolean().nullable().transform((value) => {
502
- if (options?.some((option) => option.value === null)) {
503
- return value;
504
- }
505
- return value === null ? void 0 : value;
506
- }).test(
507
- "matchesOptionOrPattern",
508
- ({ originalValue }) => {
509
- return `The option ${JSON.stringify(originalValue)} is not valid.`;
510
- },
511
- (castValue, { originalValue }) => {
512
- if (typeof originalValue !== "boolean" && castValue !== void 0)
513
- return false;
514
- return validateRadioOrSelectOptions(castValue, options);
515
- }
516
- );
517
- },
518
- number: number().typeError("The value must be a number").nullable(),
519
- file: array().nullable(),
520
- email: string().trim().email("Please enter a valid email address").nullable(),
521
- fieldset: object().nullable(),
522
- checkbox: string().trim().nullable(),
523
- checkboxBool: boolean().typeError('The value must be a boolean, but received "${value}"').nullable(),
524
- multiple: {
525
- select: array().nullable(),
526
- "group-array": array().nullable()
527
- },
528
- null: mixed().typeError("The value must be null").test(
529
- "matchesNullValue",
530
- ({ value }) => `The value ${JSON.stringify(value)} is not valid.`,
531
- (value) => value === void 0 || value === null
532
- )
533
- };
534
- var yupSchemasToJsonTypes = {
535
- string: yupSchemas.text,
536
- number: yupSchemas.number,
537
- integer: yupSchemas.number,
538
- object: yupSchemas.fieldset,
539
- array: yupSchemas.multiple.select,
540
- boolean: yupSchemas.checkboxBool,
541
- null: yupSchemas.null
542
- };
543
- function getRequiredErrorMessage(inputType, { inlineError, configError }) {
544
- if (inlineError)
545
- return inlineError;
546
- if (configError)
547
- return configError;
548
- if (inputType === supportedTypes.CHECKBOX)
549
- return "Please acknowledge this field";
550
- return "Required field";
551
- }
552
- var getJsonTypeInArray = (jsonType) => {
553
- return Array.isArray(jsonType) ? jsonType.find((val) => val !== "null") : jsonType;
554
- };
555
- var getOptions = (field) => {
556
- const allValues = field.options?.map((option) => ({
557
- value: option.value,
558
- pattern: option.pattern ? new RegExp(option.pattern) : null
559
- }));
560
- const isOptionalWithNull = Array.isArray(field.jsonType) && // @TODO should also check the "oneOf" directly looking for "null"
561
- // option but we don't have direct access at this point.
562
- // Otherwise the JSON Schema validator will fail as explained in PR#18
563
- field.jsonType.includes("null");
564
- return isOptionalWithNull ? [...allValues, { option: null }] : allValues;
565
- };
566
- var getYupSchema = ({ inputType, ...field }) => {
567
- const jsonType = getJsonTypeInArray(field.jsonType);
568
- const hasOptions = field.options?.length > 0;
569
- const generateOptionSchema = (type) => {
570
- const optionValues = getOptions(field);
571
- switch (type) {
572
- case "number":
573
- return yupSchemas.radioOrSelectNumber(optionValues);
574
- case "boolean":
575
- return yupSchemas.radioOrSelectBoolean(optionValues);
576
- default:
577
- return yupSchemas.radioOrSelectString(optionValues);
578
- }
579
- };
580
- if (hasOptions) {
581
- if (Array.isArray(field.jsonType)) {
582
- return field.jsonType.includes("number") ? generateOptionSchema("number") : generateOptionSchema("string");
583
- }
584
- return generateOptionSchema(field.jsonType);
585
- }
586
- if (field.format === "date") {
587
- return yupSchemas.date({ minDate: field.minDate, maxDate: field.maxDate });
588
- }
589
- return yupSchemas[inputType] || yupSchemasToJsonTypes[jsonType];
590
- };
591
- function buildYupSchema(field, config, logic) {
592
- const { inputType, jsonType: jsonTypeValue, errorMessage = {}, ...propertyFields } = field;
593
- const isCheckboxBoolean = typeof propertyFields.checkboxValue === "boolean";
594
- let baseSchema;
595
- const errorMessageFromConfig = config?.inputTypes?.[inputType]?.errorMessage || {};
596
- const jsonType = getJsonTypeInArray(field.jsonType);
597
- if (propertyFields.multiple) {
598
- baseSchema = yupSchemas.multiple[inputType] || yupSchemasToJsonTypes.array;
599
- } else if (isCheckboxBoolean) {
600
- baseSchema = yupSchemas.checkboxBool;
601
- } else {
602
- baseSchema = getYupSchema(field);
603
- }
604
- if (!baseSchema) {
605
- return noop;
606
- }
607
- const randomPlaceholder = propertyFields.pattern && randexp(propertyFields.pattern);
608
- const requiredMessage = getRequiredErrorMessage(inputType, {
609
- inlineError: errorMessage.required,
610
- configError: errorMessageFromConfig.required
611
- });
612
- function withRequired(yupSchema) {
613
- if (isCheckboxBoolean) {
614
- return yupSchema.oneOf([true], requiredMessage).required(requiredMessage);
615
- }
616
- return yupSchema.required(requiredMessage);
617
- }
618
- function withInteger(yupSchema) {
619
- return yupSchema.integer(
620
- (message) => errorMessage.integer ?? errorMessageFromConfig.integer ?? `Must not contain decimal points. E.g. ${Math.floor(message.value)} instead of ${message.value}`
621
- );
622
- }
623
- function withMin(yupSchema) {
624
- return yupSchema.min(
625
- propertyFields.minimum,
626
- (message) => errorMessage.minimum ?? errorMessageFromConfig.minimum ?? `Must be greater or equal to ${message.min}`
627
- );
628
- }
629
- function withMinLength(yupSchema) {
630
- return yupSchema.min(
631
- propertyFields.minLength,
632
- (message) => errorMessage.minLength ?? errorMessageFromConfig.minLength ?? `Please insert at least ${message.min} characters`
633
- );
634
- }
635
- function withMax(yupSchema) {
636
- return yupSchema.max(
637
- propertyFields.maximum,
638
- (message) => errorMessage.maximum ?? errorMessageFromConfig.maximum ?? `Must be smaller or equal to ${message.max}`
639
- );
640
- }
641
- function withMaxLength(yupSchema) {
642
- return yupSchema.max(
643
- propertyFields.maxLength,
644
- (message) => errorMessage.maxLength ?? errorMessageFromConfig.maxLength ?? `Please insert up to ${message.max} characters`
645
- );
646
- }
647
- function withMatches(yupSchema) {
648
- return yupSchema.matches(
649
- propertyFields.pattern,
650
- () => errorMessage.pattern ?? errorMessageFromConfig.pattern ?? `Must have a valid format. E.g. ${randomPlaceholder}`
651
- );
652
- }
653
- function isValidFileInput(files) {
654
- return files === void 0 || files === null || files.every(
655
- (file) => file instanceof File || Object.prototype.hasOwnProperty.call(file, "name")
656
- );
657
- }
658
- function withFile(yupSchema) {
659
- return yupSchema.test("isValidFile", "Not a valid file.", isValidFileInput);
660
- }
661
- function withMaxFileSize(yupSchema) {
662
- return yupSchema.test(
663
- "isValidFileSize",
664
- errorMessage.maxFileSize ?? errorMessageFromConfig.maxFileSize ?? `File size too large. The limit is ${convertKbBytesToMB(propertyFields.maxFileSize)} MB.`,
665
- (files) => isValidFileInput(files) && !files?.some((file) => convertBytesToKB(file.size) > propertyFields.maxFileSize)
666
- );
667
- }
668
- function withFileFormat(yupSchema) {
669
- return yupSchema.test(
670
- "isSupportedFormat",
671
- errorMessage.accept ?? errorMessageFromConfig.accept ?? `Unsupported file format. The acceptable formats are ${propertyFields.accept}.`,
672
- (files) => isValidFileInput(files) && files?.length > 0 ? files.some((file) => {
673
- const fileType = file.name.split(".").pop();
674
- return propertyFields.accept.includes(fileType.toLowerCase());
675
- }) : true
676
- );
677
- }
678
- function withConst(yupSchema) {
679
- return yupSchema.test(
680
- "isConst",
681
- errorMessage.const ?? errorMessageFromConfig.const ?? `The only accepted value is ${propertyFields.const}.`,
682
- (value) => propertyFields.required === false && value === void 0 || value === null || value === propertyFields.const
683
- );
684
- }
685
- function withBaseSchema() {
686
- const customErrorMsg = errorMessage.type || errorMessageFromConfig.type;
687
- if (customErrorMsg) {
688
- return baseSchema.typeError(customErrorMsg);
689
- }
690
- return baseSchema;
691
- }
692
- function buildFieldSetSchema(innerFields) {
693
- const fieldSetShape = {};
694
- innerFields.forEach((fieldSetfield) => {
695
- if (fieldSetfield.fields) {
696
- fieldSetShape[fieldSetfield.name] = object().shape(
697
- buildFieldSetSchema(fieldSetfield.fields)
698
- );
699
- } else {
700
- fieldSetShape[fieldSetfield.name] = buildYupSchema(
701
- {
702
- ...fieldSetfield,
703
- inputType: fieldSetfield.type
704
- },
705
- config
706
- )();
707
- }
708
- });
709
- return fieldSetShape;
710
- }
711
- function buildGroupArraySchema() {
712
- return object().shape(
713
- propertyFields.nthFieldGroup.fields().reduce(
714
- (schema, groupArrayField) => ({
715
- ...schema,
716
- [groupArrayField.name]: buildYupSchema(groupArrayField, config)()
717
- }),
718
- {}
719
- )
720
- );
721
- }
722
- const validators = [withBaseSchema];
723
- if (inputType === supportedTypes.GROUP_ARRAY) {
724
- validators[0] = () => withBaseSchema().of(buildGroupArraySchema());
725
- } else if (inputType === supportedTypes.FIELDSET) {
726
- validators[0] = () => withBaseSchema().shape(buildFieldSetSchema(propertyFields.fields));
727
- }
728
- if (propertyFields.required) {
729
- validators.push(withRequired);
730
- }
731
- if (inputType === supportedTypes.FILE) {
732
- validators.push(withFile);
733
- }
734
- if (jsonType === "integer") {
735
- validators.push(withInteger);
736
- }
737
- if (typeof propertyFields.minimum !== "undefined") {
738
- validators.push(withMin);
739
- }
740
- if (typeof propertyFields.minLength !== "undefined") {
741
- validators.push(withMinLength);
742
- }
743
- if (propertyFields.maximum !== void 0) {
744
- validators.push(withMax);
745
- }
746
- if (propertyFields.maxLength) {
747
- validators.push(withMaxLength);
748
- }
749
- if (propertyFields.pattern) {
750
- validators.push(withMatches);
751
- }
752
- if (propertyFields.maxFileSize) {
753
- validators.push(withMaxFileSize);
754
- }
755
- if (propertyFields.accept) {
756
- validators.push(withFileFormat);
757
- }
758
- if (typeof propertyFields.const !== "undefined") {
759
- validators.push(withConst);
760
- }
761
- if (propertyFields.jsonLogicValidations) {
762
- propertyFields.jsonLogicValidations.forEach(
763
- (id) => validators.push(yupSchemaWithCustomJSONLogic({ field, id, logic, config }))
764
- );
765
- }
766
- return flow(validators);
767
- }
768
- function getNoSortEdges(fields = []) {
769
- return fields.reduce((list, field) => {
770
- if (field.noSortEdges) {
771
- list.push(field.name);
772
- }
773
- return list;
774
- }, []);
775
- }
776
- function getSchema(fields = [], config) {
777
- const newSchema = {};
778
- fields.forEach((field) => {
779
- if (field.schema) {
780
- if (field.name) {
781
- if (field.inputType === supportedTypes.FIELDSET) {
782
- const fieldsetSchema = buildYupSchema(field, config)();
783
- newSchema[field.name] = fieldsetSchema;
784
- } else {
785
- newSchema[field.name] = field.schema;
786
- }
787
- } else {
788
- Object.assign(newSchema, getSchema(field.fields, config));
789
- }
790
- }
791
- });
792
- return newSchema;
793
- }
794
- function buildCompleteYupSchema(fields, config) {
795
- return object().shape(getSchema(fields, config), getNoSortEdges(fields));
796
- }
797
-
798
- // src/jsonLogic.js
799
- function createValidationChecker(schema) {
800
- const scopes = /* @__PURE__ */ new Map();
801
- function createScopes(jsonSchema, key = "root") {
802
- const sampleEmptyObject = buildSampleEmptyObject(schema);
803
- scopes.set(key, createValidationsScope(jsonSchema));
804
- Object.entries(jsonSchema?.properties ?? {}).filter(([, property]) => property.type === "object" || property.type === "array").forEach(([key2, property]) => {
805
- if (property.type === "array") {
806
- createScopes(property.items, `${key2}[]`);
807
- } else {
808
- createScopes(property, key2);
809
- }
810
- });
811
- validateInlineRules(jsonSchema, sampleEmptyObject);
812
- }
813
- createScopes(schema);
814
- return {
815
- scopes,
816
- getScope(name = "root") {
817
- return scopes.get(name);
818
- }
819
- };
820
- }
821
- function createValidationsScope(schema) {
822
- const validationMap = /* @__PURE__ */ new Map();
823
- const computedValuesMap = /* @__PURE__ */ new Map();
824
- const logic = schema?.["x-jsf-logic"] ?? {
825
- validations: {},
826
- computedValues: {}
827
- };
828
- const validations = Object.entries(logic.validations ?? {});
829
- const computedValues = Object.entries(logic.computedValues ?? {});
830
- const sampleEmptyObject = buildSampleEmptyObject(schema);
831
- validations.forEach(([id, validation]) => {
832
- if (!validation.rule) {
833
- throw Error(`[json-schema-form] json-logic error: Validation "${id}" has missing rule.`);
834
- }
835
- checkRuleIntegrity(validation.rule, id, sampleEmptyObject);
836
- validationMap.set(id, validation);
837
- });
838
- computedValues.forEach(([id, computedValue]) => {
839
- if (!computedValue.rule) {
840
- throw Error(`[json-schema-form] json-logic error: Computed value "${id}" has missing rule.`);
841
- }
842
- checkRuleIntegrity(computedValue.rule, id, sampleEmptyObject);
843
- computedValuesMap.set(id, computedValue);
844
- });
845
- function validate(rule, values) {
846
- return jsonLogic.apply(
847
- rule,
848
- replaceUndefinedValuesWithNulls({ ...sampleEmptyObject, ...values })
849
- );
850
- }
851
- return {
852
- validationMap,
853
- computedValuesMap,
854
- validate,
855
- applyValidationRuleInCondition(id, values) {
856
- const validation = validationMap.get(id);
857
- return validate(validation.rule, values);
858
- },
859
- applyComputedValueInField(id, values, fieldName) {
860
- const validation = computedValuesMap.get(id);
861
- if (validation === void 0) {
862
- throw Error(
863
- `[json-schema-form] json-logic error: Computed value "${id}" doesn't exist in field "${fieldName}".`
864
- );
865
- }
866
- return validate(validation.rule, values);
867
- },
868
- applyComputedValueRuleInCondition(id, values) {
869
- const validation = computedValuesMap.get(id);
870
- return validate(validation.rule, values);
871
- }
872
- };
873
- }
874
- function replaceUndefinedValuesWithNulls(values = {}) {
875
- return Object.entries(values).reduce((prev, [key, value]) => {
876
- return { ...prev, [key]: value === void 0 || value === null ? NaN : value };
877
- }, {});
878
- }
879
- function yupSchemaWithCustomJSONLogic({ field, logic, config, id }) {
880
- const { parentID = "root" } = config;
881
- const validation = logic.getScope(parentID).validationMap.get(id);
882
- if (validation === void 0) {
883
- throw Error(
884
- `[json-schema-form] json-logic error: "${field.name}" required validation "${id}" doesn't exist.`
885
- );
886
- }
887
- return (yupSchema) => yupSchema.test(
888
- `${field.name}-validation-${id}`,
889
- validation?.errorMessage ?? "This field is invalid.",
890
- (value, { parent }) => {
891
- if (value === void 0 && !field.required)
892
- return true;
893
- return jsonLogic.apply(validation.rule, parent);
894
- }
895
- );
896
- }
897
- var HANDLEBARS_REGEX = /\{\{([^{}]+)\}\}/g;
898
- function replaceHandlebarsTemplates({
899
- value: toReplace,
900
- logic,
901
- formValues,
902
- parentID,
903
- name: fieldName
904
- }) {
905
- if (typeof toReplace === "string") {
906
- return toReplace.replace(HANDLEBARS_REGEX, (match, key) => {
907
- return logic.getScope(parentID).applyComputedValueInField(key.trim(), formValues, fieldName);
908
- });
909
- } else if (typeof toReplace === "object") {
910
- const { value, ...rules } = toReplace;
911
- if (Object.keys(rules).length > 1 && !value) {
912
- throw Error("Cannot define multiple rules without a template string with key `value`.");
913
- }
914
- const computedTemplateValue = Object.entries(rules).reduce((prev, [key, rule]) => {
915
- const computedValue = logic.getScope(parentID).validate(rule, formValues);
916
- return prev.replaceAll(`{{${key}}}`, computedValue);
917
- }, value);
918
- return computedTemplateValue.replace(/\{\{([^{}]+)\}\}/g, (match, key) => {
919
- return logic.getScope(parentID).applyComputedValueInField(key.trim(), formValues, fieldName);
920
- });
921
- }
922
- return toReplace;
923
- }
924
- function calculateComputedAttributes(fieldParams, { parentID = "root" } = {}) {
925
- return ({ logic, isRequired, config, formValues }) => {
926
- const { name, computedAttributes } = fieldParams;
927
- const attributes = Object.fromEntries(
928
- Object.entries(computedAttributes).map(handleComputedAttribute(logic, formValues, parentID, name)).filter(([, value]) => value !== null)
929
- );
930
- return {
931
- ...attributes,
932
- schema: buildYupSchema(
933
- { ...fieldParams, ...attributes, required: isRequired },
934
- config,
935
- logic
936
- )
937
- };
938
- };
939
- }
940
- function handleComputedAttribute(logic, formValues, parentID, name) {
941
- return ([key, value]) => {
942
- switch (key) {
943
- case "description":
944
- return [key, replaceHandlebarsTemplates({ value, logic, formValues, parentID, name })];
945
- case "title":
946
- return ["label", replaceHandlebarsTemplates({ value, logic, formValues, parentID, name })];
947
- case "x-jsf-errorMessage":
948
- return [
949
- "errorMessage",
950
- handleNestedObjectForComputedValues(value, formValues, parentID, logic, name)
951
- ];
952
- case "x-jsf-presentation": {
953
- if (value.statement) {
954
- return [
955
- "statement",
956
- handleNestedObjectForComputedValues(value.statement, formValues, parentID, logic, name)
957
- ];
958
- }
959
- return [
960
- key,
961
- handleNestedObjectForComputedValues(value.statement, formValues, parentID, logic, name)
962
- ];
963
- }
964
- case "const":
965
- default: {
966
- if (typeof value === "object" && value.rule) {
967
- return [key, logic.getScope(parentID).validate(value.rule, formValues)];
968
- }
969
- return [key, logic.getScope(parentID).applyComputedValueInField(value, formValues, name)];
970
- }
971
- }
972
- };
973
- }
974
- function handleNestedObjectForComputedValues(values, formValues, parentID, logic, name) {
975
- return Object.fromEntries(
976
- Object.entries(values).map(([key, value]) => {
977
- return [key, replaceHandlebarsTemplates({ value, logic, formValues, parentID, name })];
978
- })
979
- );
980
- }
981
- function buildSampleEmptyObject(schema = {}) {
982
- const sample = {};
983
- if (typeof schema !== "object" || !schema.properties) {
984
- return schema;
985
- }
986
- for (const key in schema.properties) {
987
- if (schema.properties[key].type === "object") {
988
- sample[key] = buildSampleEmptyObject(schema.properties[key]);
989
- } else if (schema.properties[key].type === "array") {
990
- const itemSchema = schema.properties[key].items;
991
- sample[key] = buildSampleEmptyObject(itemSchema);
992
- } else {
993
- sample[key] = true;
994
- }
995
- }
996
- return sample;
997
- }
998
- function validateInlineRules(jsonSchema, sampleEmptyObject) {
999
- const properties = (jsonSchema?.properties || jsonSchema?.items?.properties) ?? {};
1000
- Object.entries(properties).filter(([, property]) => property["x-jsf-logic-computedAttrs"] !== void 0).forEach(([fieldName, property]) => {
1001
- Object.entries(property["x-jsf-logic-computedAttrs"]).filter(([, value]) => typeof value === "object").forEach(([key, item]) => {
1002
- Object.values(item).forEach((rule) => {
1003
- checkRuleIntegrity(
1004
- rule,
1005
- fieldName,
1006
- sampleEmptyObject,
1007
- (item2) => `[json-schema-form] json-logic error: fieldName "${item2.var}" doesn't exist in field "${fieldName}.x-jsf-logic-computedAttrs.${key}".`
1008
- );
1009
- });
1010
- });
1011
- });
1012
- }
1013
- function checkRuleIntegrity(rule, id, data, errorMessage = (item) => `[json-schema-form] json-logic error: rule "${id}" has no variable "${item.var}".`) {
1014
- Object.entries(rule ?? {}).map(([operator, subRule]) => {
1015
- if (!Array.isArray(subRule) && subRule !== null && subRule !== void 0)
1016
- return;
1017
- throwIfUnknownOperator(operator, subRule, id);
1018
- subRule.map((item) => {
1019
- const isVar = item !== null && typeof item === "object" && Object.hasOwn(item, "var");
1020
- if (isVar) {
1021
- const exists = jsonLogic.apply({ var: removeIndicesFromPath(item.var) }, data);
1022
- if (exists === null) {
1023
- throw Error(errorMessage(item));
1024
- }
1025
- } else {
1026
- checkRuleIntegrity(item, id, data);
1027
- }
1028
- });
1029
- });
1030
- }
1031
- function throwIfUnknownOperator(operator, subRule, id) {
1032
- try {
1033
- jsonLogic.apply({ [operator]: subRule });
1034
- } catch (e) {
1035
- if (e.message === `Unrecognized operation ${operator}`) {
1036
- throw Error(
1037
- `[json-schema-form] json-logic error: in "${id}" rule there is an unknown operator "${operator}".`
1038
- );
1039
- }
1040
- }
1041
- }
1042
- var regexToGetIndices = /\.\d+\./g;
1043
- function removeIndicesFromPath(path) {
1044
- const intermediatePath = path.replace(regexToGetIndices, ".");
1045
- return intermediatePath.replace(/\.\d+$/, "");
1046
- }
1047
- function processJSONLogicNode({
1048
- node,
1049
- formFields,
1050
- formValues,
1051
- accRequired,
1052
- parentID,
1053
- logic
1054
- }) {
1055
- const requiredFields = new Set(accRequired);
1056
- if (node.allOf) {
1057
- node.allOf.map(
1058
- (allOfNode) => processJSONLogicNode({ node: allOfNode, formValues, formFields, logic, parentID })
1059
- ).forEach(({ required: allOfItemRequired }) => {
1060
- allOfItemRequired.forEach(requiredFields.add, requiredFields);
1061
- });
1062
- }
1063
- if (node.if) {
1064
- const matchesPropertyCondition = checkIfConditionMatchesProperties(
1065
- node,
1066
- formValues,
1067
- formFields,
1068
- logic
1069
- );
1070
- const matchesValidationsAndComputedValues = matchesPropertyCondition && checkIfMatchesValidationsAndComputedValues(node, formValues, logic, parentID);
1071
- const isConditionMatch = matchesPropertyCondition && matchesValidationsAndComputedValues;
1072
- let nextNode;
1073
- if (isConditionMatch && node.then) {
1074
- nextNode = node.then;
1075
- }
1076
- if (!isConditionMatch && node.else) {
1077
- nextNode = node.else;
1078
- }
1079
- if (nextNode) {
1080
- const { required: branchRequired } = processNode({
1081
- node: nextNode,
1082
- formValues,
1083
- formFields,
1084
- accRequired,
1085
- logic,
1086
- parentID
1087
- });
1088
- branchRequired.forEach((field) => requiredFields.add(field));
1089
- }
1090
- }
1091
- return { required: requiredFields };
1092
- }
1093
-
1094
- // src/helpers.js
1095
- var dynamicInternalJsfAttrs = [
1096
- "isVisible",
1097
- // Driven from conditionals state
1098
- "fields",
1099
- // driven from group-array
1100
- "getComputedAttributes",
1101
- // From json-logic
1102
- "computedAttributes",
1103
- // From json-logic
1104
- "calculateConditionalProperties",
1105
- // driven from conditionals
1106
- "calculateCustomValidationProperties",
1107
- // To be deprecated in favor of json-logic
1108
- "scopedJsonSchema",
1109
- // The respective JSON Schema
1110
- // HOTFIX/TODO Internal customizations, check test conditions.test.js for more info.
1111
- "Component",
1112
- "calculateDynamicProperties",
1113
- "visibilityCondition"
1114
- ];
1115
- var dynamicInternalJsfAttrsObj = Object.fromEntries(
1116
- dynamicInternalJsfAttrs.map((k) => [k, true])
1117
- );
1118
- function removeConditionalStaleAttributes(field, conditionalAttrs, rootAttrs) {
1119
- Object.keys(field).forEach((key) => {
1120
- if (conditionalAttrs[key] === void 0 && rootAttrs[key] === void 0 && // Don't remove attrs that were declared in the root field.
1121
- dynamicInternalJsfAttrsObj[key] === void 0) {
1122
- field[key] = void 0;
1123
- }
1124
- });
1125
- }
1126
- function hasType(type, typeName) {
1127
- return Array.isArray(type) ? type.includes(typeName) : type === typeName;
1128
- }
1129
- function getField(fieldName, fields) {
1130
- if (Array.isArray(fields)) {
1131
- return fields.find(({ name }) => name === fieldName);
1132
- } else {
1133
- return fields[fieldName];
1134
- }
1135
- }
1136
- function validateFieldSchema(field, value, logic) {
1137
- const validator = buildYupSchema(field, {}, logic);
1138
- return validator().isValidSync(value);
1139
- }
1140
- function compareFormValueWithSchemaValue(formValue, schemaValue) {
1141
- const currentPropertyValue = typeof schemaValue === "number" ? schemaValue : schemaValue || void 0;
1142
- return String(formValue) === String(currentPropertyValue);
1143
- }
1144
- function isFieldFilled(fieldValue) {
1145
- return Array.isArray(fieldValue) ? fieldValue.length > 0 : !!fieldValue;
1146
- }
1147
- function findFirstAnyOfMatch(nodes, formValues) {
1148
- return nodes.find(
1149
- ({ required }) => required?.some((fieldName) => isFieldFilled(formValues[fieldName]))
1150
- ) || nodes[0];
1151
- }
1152
- function getPrefillSubFieldValues(field, defaultValues, parentFieldKeyPath) {
1153
- let initialValue = defaultValues ?? {};
1154
- let fieldKeyPath = field.name;
1155
- if (parentFieldKeyPath) {
1156
- fieldKeyPath = fieldKeyPath ? `${parentFieldKeyPath}.${fieldKeyPath}` : parentFieldKeyPath;
1157
- }
1158
- const subFields = field.fields;
1159
- if (Array.isArray(subFields)) {
1160
- const subFieldValues = {};
1161
- subFields.forEach((subField) => {
1162
- Object.assign(
1163
- subFieldValues,
1164
- getPrefillSubFieldValues(subField, initialValue[field.name], fieldKeyPath)
1165
- );
1166
- });
1167
- if (field.inputType === supportedTypes.FIELDSET && field.valueGroupingDisabled) {
1168
- Object.assign(initialValue, subFieldValues);
1169
- } else {
1170
- initialValue[field.name] = subFieldValues;
1171
- }
1172
- } else {
1173
- if (typeof initialValue !== "object") {
1174
- console.warn(
1175
- `Field "${parentFieldKeyPath}"'s value is "${initialValue}", but should be type object.`
1176
- );
1177
- initialValue = getPrefillValues([field], {
1178
- // TODO nested fieldsets are not handled
1179
- });
1180
- } else {
1181
- initialValue = getPrefillValues([field], initialValue);
1182
- }
1183
- }
1184
- return initialValue;
1185
- }
1186
- function getPrefillValues(fields, initialValues = {}) {
1187
- fields.forEach((field) => {
1188
- const fieldName = field.name;
1189
- switch (field.type) {
1190
- case supportedTypes.GROUP_ARRAY: {
1191
- initialValues[fieldName] = initialValues[fieldName]?.map(
1192
- (subFieldValues) => getPrefillValues(field.fields(), subFieldValues)
1193
- );
1194
- break;
1195
- }
1196
- case supportedTypes.FIELDSET: {
1197
- const subFieldValues = getPrefillSubFieldValues(field, initialValues);
1198
- Object.assign(initialValues, subFieldValues);
1199
- break;
1200
- }
1201
- default: {
1202
- if (!initialValues[fieldName]) {
1203
- initialValues[fieldName] = field.default;
1204
- }
1205
- break;
1206
- }
1207
- }
1208
- });
1209
- return initialValues;
1210
- }
1211
- function updateField(field, requiredFields, node, formValues, logic, config) {
1212
- if (!field) {
1213
- return;
1214
- }
1215
- const fieldIsRequired = requiredFields.has(field.name);
1216
- if (node.properties && hasProperty(node.properties, field.name)) {
1217
- field.isVisible = !!node.properties[field.name];
1218
- }
1219
- if (fieldIsRequired) {
1220
- field.isVisible = true;
1221
- }
1222
- const updateAttributes = (fieldAttrs) => {
1223
- Object.entries(fieldAttrs).forEach(([key, value]) => {
1224
- field[key] = value;
1225
- if (key === "schema" && typeof value === "function") {
1226
- field[key] = value();
1227
- }
1228
- if (key === "value") {
1229
- const readOnlyPropertyWasUpdated = typeof fieldAttrs.readOnly !== "undefined";
1230
- const isReadonlyByDefault = field.readOnly;
1231
- const isReadonly = readOnlyPropertyWasUpdated ? fieldAttrs.readOnly : isReadonlyByDefault;
1232
- if (!isReadonly && (value === null || field.inputType === "checkbox")) {
1233
- field.value = void 0;
1234
- }
1235
- }
1236
- });
1237
- };
1238
- if (field.getComputedAttributes) {
1239
- const newAttributes = field.getComputedAttributes({
1240
- field,
1241
- isRequired: fieldIsRequired,
1242
- node,
1243
- formValues,
1244
- config,
1245
- logic
1246
- });
1247
- updateAttributes(newAttributes);
1248
- }
1249
- if (field.calculateConditionalProperties) {
1250
- const { rootFieldAttrs, newAttributes } = field.calculateConditionalProperties({
1251
- isRequired: fieldIsRequired,
1252
- conditionBranch: node,
1253
- formValues
1254
- });
1255
- updateAttributes(newAttributes);
1256
- removeConditionalStaleAttributes(field, newAttributes, rootFieldAttrs);
1257
- }
1258
- if (field.calculateCustomValidationProperties) {
1259
- const newAttributes = field.calculateCustomValidationProperties(
1260
- fieldIsRequired,
1261
- node,
1262
- formValues
1263
- );
1264
- updateAttributes(newAttributes);
1265
- }
1266
- }
1267
- function processNode({
1268
- node,
1269
- formValues,
1270
- formFields,
1271
- accRequired = /* @__PURE__ */ new Set(),
1272
- parentID = "root",
1273
- logic
1274
- }) {
1275
- const requiredFields = new Set(accRequired);
1276
- Object.keys(node.properties ?? []).forEach((fieldName) => {
1277
- const field = getField(fieldName, formFields);
1278
- updateField(field, requiredFields, node, formValues, logic, { parentID });
1279
- });
1280
- node.required?.forEach((fieldName) => {
1281
- requiredFields.add(fieldName);
1282
- updateField(getField(fieldName, formFields), requiredFields, node, formValues, logic, {
1283
- parentID
1284
- });
1285
- });
1286
- if (node.if !== void 0) {
1287
- const matchesCondition = checkIfConditionMatchesProperties(node, formValues, formFields, logic);
1288
- if (matchesCondition && node.then) {
1289
- const { required: branchRequired } = processNode({
1290
- node: node.then,
1291
- formValues,
1292
- formFields,
1293
- accRequired: requiredFields,
1294
- parentID,
1295
- logic
1296
- });
1297
- branchRequired.forEach((field) => requiredFields.add(field));
1298
- } else if (node.else) {
1299
- const { required: branchRequired } = processNode({
1300
- node: node.else,
1301
- formValues,
1302
- formFields,
1303
- accRequired: requiredFields,
1304
- parentID,
1305
- logic
1306
- });
1307
- branchRequired.forEach((field) => requiredFields.add(field));
1308
- }
1309
- }
1310
- if (node.anyOf) {
1311
- const firstMatchOfAnyOf = findFirstAnyOfMatch(node.anyOf, formValues);
1312
- firstMatchOfAnyOf.required?.forEach((fieldName) => {
1313
- requiredFields.add(fieldName);
1314
- });
1315
- node.anyOf.forEach(({ required = [] }) => {
1316
- required.forEach((fieldName) => {
1317
- const field = getField(fieldName, formFields);
1318
- updateField(field, requiredFields, node, formValues, logic, { parentID });
1319
- });
1320
- });
1321
- }
1322
- if (node.allOf) {
1323
- node.allOf.map(
1324
- (allOfNode) => processNode({
1325
- node: allOfNode,
1326
- formValues,
1327
- formFields,
1328
- accRequired: requiredFields,
1329
- parentID,
1330
- logic
1331
- })
1332
- ).forEach(({ required: allOfItemRequired }) => {
1333
- allOfItemRequired.forEach(requiredFields.add, requiredFields);
1334
- });
1335
- }
1336
- if (node.properties) {
1337
- Object.entries(node.properties).forEach(([name, nestedNode]) => {
1338
- const inputType = getInputType(nestedNode);
1339
- if (inputType === supportedTypes.FIELDSET) {
1340
- processNode({
1341
- node: nestedNode,
1342
- formValues: formValues[name] || {},
1343
- formFields: getField(name, formFields).fields,
1344
- parentID: name,
1345
- logic
1346
- });
1347
- }
1348
- if (inputType === supportedTypes.GROUP_ARRAY) {
1349
- const values = formValues[name];
1350
- if (Array.isArray(values)) {
1351
- const newFields = [];
1352
- const field = getField(name, formFields);
1353
- values.forEach((value) => {
1354
- const fields = field.fields();
1355
- processNode({
1356
- node: nestedNode.items,
1357
- formValues: value,
1358
- formFields: fields,
1359
- parentID: name,
1360
- logic
1361
- });
1362
- newFields.push(fields);
1363
- });
1364
- field.dynamicFields = newFields;
1365
- }
1366
- }
1367
- });
1368
- }
1369
- if (node["x-jsf-logic"]) {
1370
- const { required: requiredFromLogic } = processJSONLogicNode({
1371
- node: node["x-jsf-logic"],
1372
- formValues,
1373
- formFields,
1374
- accRequired: requiredFields,
1375
- parentID,
1376
- logic
1377
- });
1378
- requiredFromLogic.forEach((field) => requiredFields.add(field));
1379
- }
1380
- return {
1381
- required: requiredFields
1382
- };
1383
- }
1384
- function clearValuesIfNotVisible(fields, formValues) {
1385
- fields.forEach(({ isVisible = true, name, inputType, fields: nestedFields }) => {
1386
- if (!isVisible) {
1387
- formValues[name] = null;
1388
- }
1389
- if (inputType === supportedTypes.FIELDSET && nestedFields && formValues[name]) {
1390
- clearValuesIfNotVisible(nestedFields, formValues[name]);
1391
- }
1392
- });
1393
- }
1394
- function updateFieldsProperties(fields, formValues, jsonSchema, logic) {
1395
- if (!jsonSchema?.properties) {
1396
- return;
1397
- }
1398
- processNode({ node: jsonSchema, formValues, formFields: fields, logic });
1399
- clearValuesIfNotVisible(fields, formValues);
1400
- }
1401
- var notNullOption = (opt) => opt.const !== null;
1402
- function flatPresentation(item) {
1403
- return Object.entries(item).reduce((newItem, [key, value]) => {
1404
- if (key === "x-jsf-presentation") {
1405
- return {
1406
- ...newItem,
1407
- ...value
1408
- };
1409
- }
1410
- return {
1411
- ...newItem,
1412
- [key]: value
1413
- };
1414
- }, {});
1415
- }
1416
- function getFieldOptions(node, presentation) {
1417
- function convertToOptions(nodeOptions) {
1418
- return nodeOptions.filter(notNullOption).map(({ title, const: cons, ...item }) => ({
1419
- label: title,
1420
- value: cons,
1421
- ...flatPresentation(item)
1422
- }));
1423
- }
1424
- if (presentation.options) {
1425
- return presentation.options;
1426
- }
1427
- if (node.oneOf || presentation.inputType === "radio") {
1428
- return convertToOptions(node.oneOf || []);
1429
- }
1430
- if (node.items?.anyOf) {
1431
- return convertToOptions(node.items.anyOf);
1432
- }
1433
- return null;
1434
- }
1435
- function extractParametersFromNode(schemaNode) {
1436
- if (!schemaNode) {
1437
- return {};
1438
- }
1439
- const presentation = pickXKey(schemaNode, "presentation") ?? {};
1440
- const errorMessage = pickXKey(schemaNode, "errorMessage") ?? {};
1441
- const jsonLogicValidations = schemaNode["x-jsf-logic-validations"];
1442
- const computedAttributes = schemaNode["x-jsf-logic-computedAttrs"];
1443
- const decoratedComputedAttributes = getDecoratedComputedAttributes(computedAttributes);
1444
- const node = omit(schemaNode, ["x-jsf-presentation", "presentation"]);
1445
- const description = presentation?.description || node.description;
1446
- const statementDescription = presentation.statement?.description;
1447
- const value = typeof node.const !== "undefined" && typeof node.default !== "undefined" && node.const === node.default ? { forcedValue: node.const } : {};
1448
- return omitBy(
1449
- {
1450
- const: node.const,
1451
- ...value,
1452
- label: node.title,
1453
- readOnly: node.readOnly,
1454
- ...node.deprecated && {
1455
- deprecated: {
1456
- description: presentation.deprecated?.description
1457
- // @TODO/@IDEA These might be useful down the road :thinking:
1458
- // version: presentation.deprecated.version, // e.g. "1.1"
1459
- // replacement: presentation.deprecated.replacement, // e.g. ['contract_duration_type']
1460
- }
1461
- },
1462
- pattern: node.pattern,
1463
- options: getFieldOptions(node, presentation),
1464
- items: node.items,
1465
- maxLength: node.maxLength,
1466
- minLength: node.minLength,
1467
- minimum: node.minimum,
1468
- maximum: node.maximum,
1469
- maxFileSize: node.maxFileSize,
1470
- // @deprecated in favor of presentation.maxFileSize
1471
- default: node.default,
1472
- format: node.format,
1473
- // Checkboxes conditions
1474
- // — For checkboxes that only accept one value (string)
1475
- ...presentation?.inputType === "checkbox" && { checkboxValue: node.const },
1476
- // - For checkboxes with boolean value
1477
- ...presentation?.inputType === "checkbox" && node.type === "boolean" && {
1478
- // true is what describes this checkbox as a boolean, regardless if its required or not
1479
- checkboxValue: true
1480
- },
1481
- ...hasType(node.type, "array") && {
1482
- multiple: true
1483
- },
1484
- // Handle [name].presentation
1485
- ...presentation,
1486
- jsonLogicValidations,
1487
- computedAttributes: decoratedComputedAttributes,
1488
- description,
1489
- extra: presentation.extra,
1490
- statement: presentation.statement && {
1491
- ...presentation.statement,
1492
- description: statementDescription
1493
- },
1494
- // Support scoped conditions (fieldsets)
1495
- if: node.if,
1496
- then: node.then,
1497
- else: node.else,
1498
- anyOf: node.anyOf,
1499
- allOf: node.allOf,
1500
- errorMessage
1501
- },
1502
- isNil
1503
- );
1504
- }
1505
- function yupToFormErrors(yupError) {
1506
- if (!yupError) {
1507
- return yupError;
1508
- }
1509
- const errors = {};
1510
- if (yupError.inner) {
1511
- if (yupError.inner.length === 0) {
1512
- return set(errors, yupError.path, yupError.message);
1513
- }
1514
- yupError.inner.forEach((err) => {
1515
- if (!get2(errors, err.path)) {
1516
- set(errors, err.path, err.message);
1517
- }
1518
- });
1519
- }
1520
- return errors;
1521
- }
1522
- var handleValuesChange = (fields, jsonSchema, config, logic) => (values) => {
1523
- updateFieldsProperties(fields, values, jsonSchema, logic);
1524
- const lazySchema = lazy(() => buildCompleteYupSchema(fields, config));
1525
- let errors;
1526
- try {
1527
- lazySchema.validateSync(values, {
1528
- abortEarly: false
1529
- });
1530
- } catch (err) {
1531
- if (err.name === "ValidationError") {
1532
- errors = err;
1533
- } else {
1534
- console.warn(`Warning: An unhandled error was caught during validationSchema`, err);
1535
- }
1536
- }
1537
- return {
1538
- yupError: errors,
1539
- formErrors: yupToFormErrors(errors)
1540
- };
1541
- };
1542
- function getDecoratedComputedAttributes(computedAttributes) {
1543
- const isEqualConstAndDefault = computedAttributes?.const === computedAttributes?.default;
1544
- return {
1545
- ...computedAttributes ?? {},
1546
- ...computedAttributes?.const && computedAttributes?.default && isEqualConstAndDefault ? { forcedValue: computedAttributes.const } : {}
1547
- };
1548
- }
1549
-
1550
- // src/calculateConditionalProperties.js
1551
- function isFieldRequired(node, field) {
1552
- return (
1553
- // Check base root required
1554
- field.scopedJsonSchema?.required?.includes(field.name) || // Check conditional required
1555
- node?.required?.includes(field.name)
1556
- );
1557
- }
1558
- function rebuildFieldset(fields, property) {
1559
- if (property?.properties) {
1560
- return fields.map((field) => {
1561
- const propertyConditionals = property.properties[field.name];
1562
- if (!propertyConditionals) {
1563
- return field;
1564
- }
1565
- const newFieldParams = extractParametersFromNode(propertyConditionals);
1566
- if (field.fields) {
1567
- return {
1568
- ...field,
1569
- ...newFieldParams,
1570
- fields: rebuildFieldset(field.fields, propertyConditionals)
1571
- };
1572
- }
1573
- return {
1574
- ...field,
1575
- ...newFieldParams,
1576
- required: isFieldRequired(property, field)
1577
- };
1578
- });
1579
- }
1580
- return fields.map((field) => ({
1581
- ...field,
1582
- required: isFieldRequired(property, field)
1583
- }));
1584
- }
1585
- function calculateConditionalProperties({ fieldParams, customProperties, logic, config }) {
1586
- return ({ isRequired, conditionBranch, formValues }) => {
1587
- const conditionalProperty = conditionBranch?.properties?.[fieldParams.name];
1588
- if (conditionalProperty) {
1589
- const presentation = pickXKey(conditionalProperty, "presentation") ?? {};
1590
- const fieldDescription = getFieldDescription(conditionalProperty, customProperties);
1591
- const newFieldParams = extractParametersFromNode({
1592
- ...conditionalProperty,
1593
- ...fieldDescription
1594
- });
1595
- let fieldSetFields;
1596
- if (fieldParams.inputType === supportedTypes.FIELDSET) {
1597
- fieldSetFields = rebuildFieldset(fieldParams.fields, conditionalProperty);
1598
- newFieldParams.fields = fieldSetFields;
1599
- }
1600
- const { computedAttributes, ...restNewFieldParams } = newFieldParams;
1601
- const calculatedComputedAttributes = computedAttributes ? calculateComputedAttributes(newFieldParams, config)({ logic, formValues }) : {};
1602
- const jsonLogicValidations = [
1603
- ...fieldParams.jsonLogicValidations ?? [],
1604
- ...restNewFieldParams.jsonLogicValidations ?? []
1605
- ];
1606
- const base = {
1607
- isVisible: true,
1608
- required: isRequired,
1609
- ...presentation?.inputType && { type: presentation.inputType },
1610
- ...calculatedComputedAttributes,
1611
- ...calculatedComputedAttributes.value ? { value: calculatedComputedAttributes.value } : { value: void 0 },
1612
- schema: buildYupSchema(
1613
- {
1614
- ...fieldParams,
1615
- ...restNewFieldParams,
1616
- ...calculatedComputedAttributes,
1617
- jsonLogicValidations,
1618
- // If there are inner fields (case of fieldset) they need to be updated based on the condition
1619
- fields: fieldSetFields,
1620
- required: isRequired
1621
- },
1622
- config,
1623
- logic
1624
- )
1625
- };
1626
- return {
1627
- rootFieldAttrs: fieldParams,
1628
- newAttributes: omit2(merge2(base, presentation, newFieldParams), ["inputType"])
1629
- };
1630
- }
1631
- const isVisible = isRequired;
1632
- return {
1633
- rootFieldAttrs: fieldParams,
1634
- newAttributes: {
1635
- isVisible,
1636
- required: isRequired,
1637
- schema: buildYupSchema({
1638
- ...fieldParams,
1639
- ...extractParametersFromNode(conditionBranch),
1640
- required: isRequired
1641
- })
1642
- }
1643
- };
1644
- };
1645
- }
1646
-
1647
- // src/calculateCustomValidationProperties.js
1648
- import inRange from "lodash/inRange";
1649
- import isFunction2 from "lodash/isFunction";
1650
- import isNil2 from "lodash/isNil";
1651
- import isObject from "lodash/isObject";
1652
- import mapValues from "lodash/mapValues";
1653
- import pick from "lodash/pick";
1654
- var SUPPORTED_CUSTOM_VALIDATION_FIELD_PARAMS = ["minimum", "maximum"];
1655
- var isCustomValidationAllowed = (fieldParams) => (customValidation, customValidationKey) => {
1656
- if (isNil2(customValidation)) {
1657
- return false;
1658
- }
1659
- const { minimum, maximum } = fieldParams;
1660
- const isAllowed = inRange(
1661
- customValidation,
1662
- minimum ?? -Infinity,
1663
- maximum ? maximum + 1 : Infinity
1664
- );
1665
- if (!isAllowed) {
1666
- const errorMessage = `Custom validation for ${fieldParams.name} is not allowed because ${customValidationKey}:${customValidation} is less strict than the original range: ${minimum} to ${maximum}`;
1667
- if (true) {
1668
- throw new Error(errorMessage);
1669
- } else {
1670
- console.warn(errorMessage);
1671
- }
1672
- }
1673
- return isAllowed;
1674
- };
1675
- function calculateCustomValidationProperties(fieldParams, customProperties) {
1676
- return (isRequired, conditionBranch, formValues) => {
1677
- const params = { ...fieldParams, ...conditionBranch?.properties?.[fieldParams.name] };
1678
- const presentation = pickXKey(params, "presentation") ?? {};
1679
- const supportedParams = pick(customProperties, SUPPORTED_CUSTOM_VALIDATION_FIELD_PARAMS);
1680
- const checkIfAllowed = isCustomValidationAllowed(params);
1681
- const customErrorMessages = [];
1682
- const fieldParamsWithNewValidation = mapValues(
1683
- supportedParams,
1684
- (customValidationValue, customValidationKey) => {
1685
- const originalValidation = params[customValidationKey];
1686
- const customValidation = isFunction2(customValidationValue) ? customValidationValue(formValues, params) : customValidationValue;
1687
- if (isObject(customValidation)) {
1688
- if (checkIfAllowed(customValidation[customValidationKey], customValidationKey)) {
1689
- customErrorMessages.push(pickXKey(customValidation, "errorMessage"));
1690
- return customValidation[customValidationKey];
1691
- }
1692
- return originalValidation;
1693
- }
1694
- return checkIfAllowed(customValidation, customValidationKey) ? customValidation : originalValidation;
1695
- }
1696
- );
1697
- const errorMessage = Object.assign({ ...params.errorMessage }, ...customErrorMessages);
1698
- return {
1699
- ...params,
1700
- ...fieldParamsWithNewValidation,
1701
- type: presentation?.inputType || params.inputType,
1702
- errorMessage,
1703
- required: isRequired,
1704
- schema: buildYupSchema({
1705
- ...params,
1706
- ...fieldParamsWithNewValidation,
1707
- errorMessage,
1708
- required: isRequired
1709
- })
1710
- };
1711
- };
1712
- }
1713
-
1714
- // src/createHeadlessForm.js
1715
- function sortByOrderOrPosition(a, b, order) {
1716
- if (order) {
1717
- return order.indexOf(a.name) - order.indexOf(b.name);
1718
- }
1719
- return a.position - b.position;
1720
- }
1721
- function removeInvalidAttributes(fields) {
1722
- return omit3(fields, ["items", "maxFileSize", "isDynamic"]);
1723
- }
1724
- function buildFieldParameters(name, fieldProperties, required = [], config = {}, logic) {
1725
- const { position } = pickXKey(fieldProperties, "presentation") ?? {};
1726
- let fields;
1727
- const inputType = getInputType(fieldProperties, config.strictInputType, name);
1728
- if (inputType === supportedTypes.FIELDSET) {
1729
- fields = getFieldsFromJSONSchema(
1730
- fieldProperties,
1731
- {
1732
- customProperties: get3(config, `customProperties.${name}.customProperties`, {}),
1733
- parentID: name
1734
- },
1735
- logic
1736
- );
1737
- }
1738
- if (inputType === supportedTypes.GROUP_ARRAY) {
1739
- fields = () => getFieldsFromJSONSchema(
1740
- fieldProperties.items,
1741
- {
1742
- customProperties: get3(config, `customProperties.${name}.customProperties`, {}),
1743
- parentID: name
1744
- },
1745
- logic
1746
- );
1747
- }
1748
- const result = {
1749
- name,
1750
- inputType,
1751
- jsonType: fieldProperties.type,
1752
- type: inputType,
1753
- // @deprecated in favor of inputType,
1754
- required: required?.includes(name) ?? false,
1755
- fields,
1756
- position,
1757
- ...extractParametersFromNode(fieldProperties)
1758
- };
1759
- return omitBy2(result, isNil3);
1760
- }
1761
- function convertJSONSchemaPropertiesToFieldParameters({ properties, required, "x-jsf-order": order }, config = {}) {
1762
- const sortFields = (a, b) => sortByOrderOrPosition(a, b, order);
1763
- return Object.entries(properties).filter(([, value]) => typeof value === "object").map(([key, value]) => buildFieldParameters(key, value, required, config)).sort(sortFields).map(({ position, ...fieldParams }) => fieldParams);
1764
- }
1765
- function applyFieldsDependencies(fieldsParameters, node) {
1766
- if (node?.then) {
1767
- fieldsParameters.filter(
1768
- ({ name }) => node.then?.properties?.[name] || node.then?.required?.includes(name) || node.else?.properties?.[name] || node.else?.required?.includes(name)
1769
- ).forEach((property) => {
1770
- property.isDynamic = true;
1771
- });
1772
- applyFieldsDependencies(fieldsParameters, node.then);
1773
- }
1774
- if (node?.anyOf) {
1775
- fieldsParameters.filter(({ name }) => node.anyOf.some(({ required }) => required?.includes(name))).forEach((property) => {
1776
- property.isDynamic = true;
1777
- });
1778
- applyFieldsDependencies(fieldsParameters, node.then);
1779
- }
1780
- if (node?.allOf) {
1781
- node.allOf.forEach((condition) => {
1782
- applyFieldsDependencies(fieldsParameters, condition);
1783
- });
1784
- }
1785
- if (node?.["x-jsf-logic"]) {
1786
- applyFieldsDependencies(fieldsParameters, node["x-jsf-logic"]);
1787
- }
1788
- }
1789
- function getCustomPropertiesForField(fieldParams, config) {
1790
- return config?.customProperties?.[fieldParams.name];
1791
- }
1792
- function getComposeFunctionForField(fieldParams, hasCustomizations) {
1793
- const composeFn = inputTypeMap[fieldParams.inputType] || _composeFieldArbitraryClosure(fieldParams.inputType);
1794
- if (hasCustomizations) {
1795
- return _composeFieldCustomClosure(composeFn);
1796
- }
1797
- return composeFn;
1798
- }
1799
- function buildField(fieldParams, config, scopedJsonSchema, logic) {
1800
- const customProperties = getCustomPropertiesForField(fieldParams, config);
1801
- const composeFn = getComposeFunctionForField(fieldParams, !!customProperties);
1802
- const yupSchema = buildYupSchema(fieldParams, config, logic);
1803
- const calculateConditionalFieldsClosure = fieldParams.isDynamic && calculateConditionalProperties({ fieldParams, customProperties, logic, config });
1804
- const calculateCustomValidationPropertiesClosure = calculateCustomValidationProperties(
1805
- fieldParams,
1806
- customProperties
1807
- );
1808
- const getComputedAttributes = Object.keys(fieldParams.computedAttributes).length > 0 && calculateComputedAttributes(fieldParams, config);
1809
- const hasCustomValidations = !!customProperties && size(pick2(customProperties, SUPPORTED_CUSTOM_VALIDATION_FIELD_PARAMS)) > 0;
1810
- const finalFieldParams = {
1811
- // invalid attribute cleanup
1812
- ...removeInvalidAttributes(fieldParams),
1813
- // calculateConditionalProperties function if needed
1814
- ...!!calculateConditionalFieldsClosure && {
1815
- calculateConditionalProperties: calculateConditionalFieldsClosure
1816
- },
1817
- // calculateCustomValidationProperties function if needed
1818
- ...hasCustomValidations && {
1819
- calculateCustomValidationProperties: calculateCustomValidationPropertiesClosure
1820
- },
1821
- ...getComputedAttributes && { getComputedAttributes },
1822
- // field customization properties
1823
- ...customProperties && { fieldCustomization: customProperties },
1824
- // base schema
1825
- schema: yupSchema(),
1826
- scopedJsonSchema
1827
- };
1828
- return composeFn(finalFieldParams);
1829
- }
1830
- function getFieldsFromJSONSchema(scopedJsonSchema, config, logic) {
1831
- if (!scopedJsonSchema) {
1832
- return [];
1833
- }
1834
- const fieldParamsList = convertJSONSchemaPropertiesToFieldParameters(scopedJsonSchema, config);
1835
- applyFieldsDependencies(fieldParamsList, scopedJsonSchema);
1836
- const fields = [];
1837
- fieldParamsList.forEach((fieldParams) => {
1838
- if (fieldParams.inputType === "group-array") {
1839
- const groupArrayItems = convertJSONSchemaPropertiesToFieldParameters(fieldParams.items);
1840
- const groupArrayFields = groupArrayItems.map((groupArrayItem) => {
1841
- const customProperties = null;
1842
- const composeFn = getComposeFunctionForField(groupArrayItem, !!customProperties);
1843
- return composeFn(groupArrayItem);
1844
- });
1845
- fieldParams.nthFieldGroup = {
1846
- name: fieldParams.name,
1847
- label: fieldParams.label,
1848
- description: fieldParams.description,
1849
- fields: () => groupArrayFields,
1850
- addFieldText: fieldParams.addFieldText
1851
- };
1852
- buildField(fieldParams, config, scopedJsonSchema, logic).forEach((groupField) => {
1853
- fields.push(groupField);
1854
- });
1855
- } else {
1856
- fields.push(buildField(fieldParams, config, scopedJsonSchema, logic));
1857
- }
1858
- });
1859
- return fields;
1860
- }
1861
- function createHeadlessForm(jsonSchema, customConfig = {}) {
1862
- const config = {
1863
- strictInputType: true,
1864
- ...customConfig
1865
- };
1866
- try {
1867
- const logic = createValidationChecker(jsonSchema);
1868
- const fields = getFieldsFromJSONSchema(jsonSchema, config, logic);
1869
- const handleValidation = handleValuesChange(fields, jsonSchema, config, logic);
1870
- updateFieldsProperties(
1871
- fields,
1872
- getPrefillValues(fields, config.initialValues),
1873
- jsonSchema,
1874
- logic
1875
- );
1876
- return {
1877
- fields,
1878
- handleValidation,
1879
- isError: false
1880
- };
1881
- } catch (error) {
1882
- console.error("JSON Schema invalid!", error);
1883
- return {
1884
- fields: [],
1885
- isError: true,
1886
- error
1887
- };
1888
- }
1889
- }
1890
-
1891
- // src/modify.js
1892
- import difference from "lodash/difference";
1893
- import get4 from "lodash/get";
1894
- import intersection from "lodash/intersection";
1895
- import merge3 from "lodash/merge";
1896
- import mergeWith from "lodash/mergeWith";
1897
- import set2 from "lodash/set";
1898
- var WARNING_TYPES = {
1899
- FIELD_TO_CHANGE_NOT_FOUND: "FIELD_TO_CHANGE_NOT_FOUND",
1900
- ORDER_MISSING_FIELDS: "ORDER_MISSING_FIELDS",
1901
- FIELD_TO_CREATE_EXISTS: "FIELD_TO_CREATE_EXISTS",
1902
- PICK_MISSED_FIELD: "PICK_MISSED_FIELD"
1903
- };
1904
- function shortToFullPath(path) {
1905
- return path.replace(".", ".properties.");
1906
- }
1907
- function mergeReplaceArray(_, newVal) {
1908
- return Array.isArray(newVal) ? newVal : void 0;
1909
- }
1910
- function standardizeAttrs(attrs) {
1911
- const { errorMessage, presentation, properties, ...rest } = attrs;
1912
- return {
1913
- ...rest,
1914
- ...presentation ? { "x-jsf-presentation": presentation } : {},
1915
- ...errorMessage ? { "x-jsf-errorMessage": errorMessage } : {}
1916
- };
1917
- }
1918
- function isConditionalReferencingAnyPickedField(condition, fieldsToPick) {
1919
- const { if: ifCondition, then: thenCondition, else: elseCondition } = condition;
1920
- const inIf = intersection(ifCondition.required, fieldsToPick);
1921
- if (inIf.length > 0) {
1922
- return true;
1923
- }
1924
- const inThen = intersection(thenCondition.required, fieldsToPick) || intersection(Object.keys(thenCondition.properties), fieldsToPick);
1925
- if (inThen.length > 0) {
1926
- return true;
1927
- }
1928
- const inElse = intersection(elseCondition.required, fieldsToPick) || intersection(Object.keys(elseCondition.properties), fieldsToPick);
1929
- if (inElse.length > 0) {
1930
- return true;
1931
- }
1932
- return false;
1933
- }
1934
- function rewriteFields(schema, fieldsConfig) {
1935
- if (!fieldsConfig)
1936
- return { warnings: null };
1937
- const warnings = [];
1938
- const fieldsToModify = Object.entries(fieldsConfig);
1939
- fieldsToModify.forEach(([shortPath, mutation]) => {
1940
- const fieldPath = shortToFullPath(shortPath);
1941
- if (!get4(schema.properties, fieldPath)) {
1942
- warnings.push({
1943
- type: WARNING_TYPES.FIELD_TO_CHANGE_NOT_FOUND,
1944
- message: `Changing field "${shortPath}" was ignored because it does not exist.`
1945
- });
1946
- return;
1947
- }
1948
- const fieldAttrs = get4(schema.properties, fieldPath);
1949
- const fieldChanges = typeof mutation === "function" ? mutation(fieldAttrs) : mutation;
1950
- mergeWith(
1951
- get4(schema.properties, fieldPath),
1952
- {
1953
- ...fieldAttrs,
1954
- ...standardizeAttrs(fieldChanges)
1955
- },
1956
- mergeReplaceArray
1957
- );
1958
- if (fieldChanges.properties) {
1959
- const result = rewriteFields(get4(schema.properties, fieldPath), fieldChanges.properties);
1960
- warnings.push(result.warnings);
1961
- }
1962
- });
1963
- return { warnings: warnings.flat() };
1964
- }
1965
- function rewriteAllFields(schema, configCallback, context) {
1966
- if (!configCallback)
1967
- return null;
1968
- const parentName = context?.parent;
1969
- Object.entries(schema.properties).forEach(([fieldName, fieldAttrs]) => {
1970
- const fullName = parentName ? `${parentName}.${fieldName}` : fieldName;
1971
- mergeWith(
1972
- get4(schema.properties, fieldName),
1973
- {
1974
- ...fieldAttrs,
1975
- ...standardizeAttrs(configCallback(fullName, fieldAttrs))
1976
- },
1977
- mergeReplaceArray
1978
- );
1979
- if (fieldAttrs.properties) {
1980
- rewriteAllFields(fieldAttrs, configCallback, {
1981
- parent: fieldName
1982
- });
1983
- }
1984
- });
1985
- }
1986
- function reorderFields(schema, configOrder) {
1987
- if (!configOrder)
1988
- return { warnings: null };
1989
- const warnings = [];
1990
- const originalOrder = schema["x-jsf-order"] || [];
1991
- const orderConfig = typeof configOrder === "function" ? configOrder(originalOrder) : configOrder;
1992
- const remaining = difference(originalOrder, orderConfig);
1993
- if (remaining.length > 0) {
1994
- warnings.push({
1995
- type: WARNING_TYPES.ORDER_MISSING_FIELDS,
1996
- message: `Some fields got forgotten in the new order. They were automatically appended: ${remaining.join(
1997
- ", "
1998
- )}`
1999
- });
2000
- }
2001
- schema["x-jsf-order"] = [...orderConfig, ...remaining];
2002
- return { warnings };
2003
- }
2004
- function createFields(schema, fieldsConfig) {
2005
- if (!fieldsConfig)
2006
- return { warnings: null };
2007
- const warnings = [];
2008
- const fieldsToCreate = Object.entries(fieldsConfig);
2009
- fieldsToCreate.forEach(([shortPath, fieldAttrs]) => {
2010
- const fieldPath = shortToFullPath(shortPath);
2011
- if (fieldAttrs.properties) {
2012
- const result = createFields(get4(schema.properties, fieldPath), fieldAttrs.properties);
2013
- warnings.push(result.warnings);
2014
- }
2015
- const fieldInSchema = get4(schema.properties, fieldPath);
2016
- if (fieldInSchema) {
2017
- warnings.push({
2018
- type: WARNING_TYPES.FIELD_TO_CREATE_EXISTS,
2019
- message: `Creating field "${shortPath}" was ignored because it already exists.`
2020
- });
2021
- return;
2022
- }
2023
- const fieldInObjectPath = set2({}, fieldPath, standardizeAttrs(fieldAttrs));
2024
- merge3(schema.properties, fieldInObjectPath);
2025
- });
2026
- return { warnings: warnings.flat() };
2027
- }
2028
- function pickFields(originalSchema, fieldsToPick) {
2029
- if (!fieldsToPick) {
2030
- return { schema: originalSchema, warnings: null };
2031
- }
2032
- const newSchema = {
2033
- properties: {}
2034
- };
2035
- Object.entries(originalSchema).forEach(([attrKey, attrValue]) => {
2036
- switch (attrKey) {
2037
- case "properties":
2038
- fieldsToPick.forEach((fieldPath) => {
2039
- set2(newSchema.properties, fieldPath, attrValue[fieldPath]);
2040
- });
2041
- break;
2042
- case "x-jsf-order":
2043
- case "required":
2044
- newSchema[attrKey] = attrValue.filter((fieldName) => fieldsToPick.includes(fieldName));
2045
- break;
2046
- case "allOf": {
2047
- const newAllOf = originalSchema.allOf.filter(
2048
- (condition) => isConditionalReferencingAnyPickedField(condition, fieldsToPick)
2049
- );
2050
- newSchema[attrKey] = newAllOf;
2051
- break;
2052
- }
2053
- default:
2054
- newSchema[attrKey] = attrValue;
2055
- }
2056
- });
2057
- let missingFields = {};
2058
- newSchema.allOf?.forEach((condition) => {
2059
- const { if: ifCondition, then: thenCondition, else: elseCondition } = condition;
2060
- const index = originalSchema.allOf.indexOf(condition);
2061
- missingFields = {
2062
- ...missingFields,
2063
- ...findMissingFields(ifCondition, {
2064
- fields: fieldsToPick,
2065
- path: `allOf[${index}].if`
2066
- }),
2067
- ...findMissingFields(thenCondition, {
2068
- fields: fieldsToPick,
2069
- path: `allOf[${index}].then`
2070
- }),
2071
- ...findMissingFields(elseCondition, {
2072
- fields: fieldsToPick,
2073
- path: `allOf[${index}].else`
2074
- })
2075
- };
2076
- });
2077
- const warnings = [];
2078
- if (Object.keys(missingFields).length > 0) {
2079
- Object.entries(missingFields).forEach(([fieldName]) => {
2080
- set2(newSchema.properties, fieldName, originalSchema.properties[fieldName]);
2081
- });
2082
- warnings.push({
2083
- type: WARNING_TYPES.PICK_MISSED_FIELD,
2084
- message: `The picked fields are in conditionals that refeer other fields. They added automatically: ${Object.keys(
2085
- missingFields
2086
- ).map((name) => `"${name}"`).join(", ")}. Check "meta" for more details.`,
2087
- meta: missingFields
2088
- });
2089
- }
2090
- return { schema: newSchema, warnings };
2091
- }
2092
- function findMissingFields(conditional, { fields, path }) {
2093
- if (!conditional) {
2094
- return null;
2095
- }
2096
- let missingFields = {};
2097
- conditional.required?.forEach((fieldName) => {
2098
- if (!fields.includes(fieldName)) {
2099
- missingFields[fieldName] = {
2100
- path
2101
- };
2102
- }
2103
- });
2104
- Object.entries(conditional.properties || []).forEach(([fieldName]) => {
2105
- if (!fields.includes(fieldName)) {
2106
- missingFields[fieldName] = { path };
2107
- }
2108
- });
2109
- return missingFields;
2110
- }
2111
- function modify(originalSchema, config) {
2112
- const schema = JSON.parse(JSON.stringify(originalSchema));
2113
- const resultRewrite = rewriteFields(schema, config.fields);
2114
- rewriteAllFields(schema, config.allFields);
2115
- const resultCreate = createFields(schema, config.create);
2116
- const resultPick = pickFields(schema, config.pick);
2117
- const finalSchema = resultPick.schema;
2118
- const resultReorder = reorderFields(finalSchema, config.orderRoot);
2119
- if (!config.muteLogging) {
2120
- console.warn(
2121
- "json-schema-form modify(): We highly recommend you to handle/report the returned `warnings` as they highlight possible bugs in your modifications. To mute this log, pass `muteLogging: true` to the config."
2122
- );
2123
- }
2124
- const warnings = [
2125
- resultRewrite.warnings,
2126
- resultCreate.warnings,
2127
- resultPick.warnings,
2128
- resultReorder.warnings
2129
- ].flat().filter(Boolean);
2130
- return {
2131
- schema: finalSchema,
2132
- warnings
2133
- };
2134
- }
2135
- export {
2136
- buildCompleteYupSchema,
2137
- createHeadlessForm,
2138
- modify,
2139
- pickXKey
2140
- };