@remoteoss/json-schema-form 0.11.11-dev.20250220164730 → 1.0.0-alpha.1

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