@apify/input_schema 3.29.2 → 4.0.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/cjs/index.cjs DELETED
@@ -1,609 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
-
21
- // src/index.ts
22
- var index_exports = {};
23
- __export(index_exports, {
24
- ensureAjvSupportsDraft2019: () => ensureAjvSupportsDraft2019,
25
- getCustomErrorMessage: () => getCustomErrorMessage,
26
- inputSchema: () => import_json_schemas.inputSchema,
27
- m: () => m,
28
- makeInputJsFieldsReadable: () => makeInputJsFieldsReadable,
29
- parseAjvError: () => parseAjvError,
30
- validateExistenceOfRequiredFields: () => validateExistenceOfRequiredFields,
31
- validateInputSchema: () => validateInputSchema,
32
- validateInputUsingValidator: () => validateInputUsingValidator,
33
- validateRegexpPattern: () => validateRegexpPattern
34
- });
35
- module.exports = __toCommonJS(index_exports);
36
-
37
- // src/intl.ts
38
- var intlStrings = {
39
- "inputSchema.validation.generic": "Field {rootName}.{fieldKey} {message}",
40
- "inputSchema.validation.required": "Field {rootName}.{fieldKey} is required",
41
- "inputSchema.validation.proxyRequired": "Field {rootName}.{fieldKey} is required. Please provide custom proxy URLs or use Apify Proxy.",
42
- "inputSchema.validation.requestListSourcesInvalid": "Items in {rootName}.{fieldKey} at positions [{invalidIndexes}] do not contain valid URLs",
43
- "inputSchema.validation.arrayKeysInvalid": 'Keys in {rootName}.{fieldKey} at positions [{invalidIndexes}] must match regular expression "{pattern}"',
44
- "inputSchema.validation.arrayValuesInvalid": 'Values in {rootName}.{fieldKey} at positions [{invalidIndexes}] must match regular expression "{pattern}"',
45
- "inputSchema.validation.objectKeysInvalid": 'Keys [{invalidKeys}] in {rootName}.{fieldKey} must match regular expression "{pattern}',
46
- "inputSchema.validation.objectValuesInvalid": 'Keys [{invalidKeys}] in {rootName}.{fieldKey} must have string value which matches regular expression "{pattern}"',
47
- "inputSchema.validation.additionalProperty": "Property {rootName}.{fieldKey} is not allowed.",
48
- "inputSchema.validation.proxyGroupsNotAvailable": "You currently do not have access to proxy groups: {groups}",
49
- "inputSchema.validation.customProxyInvalid": 'Proxy URL "{invalidUrl}" has invalid format, it must be socks[4|4a|5|5h]|http[s]://[username[:password]]@hostname:port.',
50
- "inputSchema.validation.apifyProxyCountryInvalid": 'Country code "{invalidCountry}" is invalid. Only ISO 3166-1 alpha-2 country codes are supported.',
51
- "inputSchema.validation.apifyProxyCountryWithoutApifyProxyForbidden": "The country for Apify Proxy can be specified only when using Apify Proxy.",
52
- "inputSchema.validation.noAvailableAutoProxy": "Currently you do not have access to any proxy group usable in automatic mode.",
53
- "inputSchema.validation.noMatchingDefinition": "Field schema.properties.{fieldKey} is not matching any input schema type definition. Please make sure that it's type is valid.",
54
- "inputSchema.validation.missingRequiredField": "Field schema.properties.{fieldKey} does not exist, but it is specified in schema.required. Either define the field or remove it from schema.required.",
55
- "inputSchema.validation.proxyGroupMustBeArrayOfStrings": "Field {rootName}.{fieldKey}.apifyProxyGroups must be an array of strings.",
56
- "inputSchema.validation.secretFieldSchemaChanged": "The field schema.properties.{fieldKey} is a secret field, but its schema has changed. Please update the value in the input editor.",
57
- "inputSchema.validation.deprecatedProperty": "Property schema.properties.{fieldKey}.{property} is deprecated and no longer supported. Please remove it from the input schema. See https://docs.apify.com/platform/actors/development/actor-definition/input-schema/specification/v1#deprecation-of-patternkey-and-patternvalue for migration instructions.",
58
- "inputSchema.validation.regexpNotValid": 'The regular expression "{pattern}" in field schema.properties.{fieldKey} must be valid.',
59
- "inputSchema.validation.regexpNotSafe": 'The regular expression "{pattern}" in field schema.properties.{fieldKey} may cause excessive backtracking or be unsafe to execute.'
60
- };
61
- function m(stringId, variables) {
62
- let text = intlStrings[stringId];
63
- if (!text) return stringId;
64
- if (variables) {
65
- Object.keys(variables).forEach((variableName) => {
66
- text = text.split(`{${variableName}}`).join(variables[variableName]);
67
- });
68
- }
69
- return text;
70
- }
71
- __name(m, "m");
72
-
73
- // src/input_schema.ts
74
- var import_json_schemas = require("@apify/json_schemas");
75
-
76
- // src/utilities.ts
77
- var import_acorn_loose = require("acorn-loose");
78
- var import_countries_list = require("countries-list");
79
- var import_consts = require("@apify/consts");
80
- var import_input_secrets = require("@apify/input_secrets");
81
- function validateProxyField(fieldKey, value, isRequired = false, options = null) {
82
- const fieldErrors = [];
83
- if (isRequired) {
84
- if (value === null) return fieldErrors;
85
- if (!value) {
86
- const message = m("inputSchema.validation.required", { rootName: "input", fieldKey });
87
- fieldErrors.push(message);
88
- return fieldErrors;
89
- }
90
- const { useApifyProxy: useApifyProxy2, proxyUrls: proxyUrls2 } = value;
91
- if (!useApifyProxy2 && (!Array.isArray(proxyUrls2) || proxyUrls2.length === 0)) {
92
- fieldErrors.push(m("inputSchema.validation.proxyRequired", { rootName: "input", fieldKey }));
93
- return fieldErrors;
94
- }
95
- }
96
- if (!value) return fieldErrors;
97
- const { useApifyProxy, proxyUrls, apifyProxyGroups, apifyProxyCountry } = value;
98
- if (!useApifyProxy && Array.isArray(proxyUrls)) {
99
- let invalidUrl = false;
100
- proxyUrls.forEach((url) => {
101
- if (!import_consts.PROXY_URL_REGEX.test(url.trim())) invalidUrl = url.trim();
102
- });
103
- if (invalidUrl) {
104
- fieldErrors.push(m("inputSchema.validation.customProxyInvalid", { invalidUrl }));
105
- }
106
- }
107
- if (!useApifyProxy && apifyProxyCountry) {
108
- fieldErrors.push(m("inputSchema.validation.apifyProxyCountryWithoutApifyProxyForbidden"));
109
- }
110
- if (!useApifyProxy) return fieldErrors;
111
- if (apifyProxyCountry && !import_countries_list.countries[apifyProxyCountry]) {
112
- fieldErrors.push(m("inputSchema.validation.apifyProxyCountryInvalid", { invalidCountry: apifyProxyCountry }));
113
- }
114
- if (!options) return fieldErrors;
115
- const isStringsArray = /* @__PURE__ */ __name((array) => array.every((item) => typeof item === "string"), "isStringsArray");
116
- if (apifyProxyGroups && !(Array.isArray(apifyProxyGroups) && isStringsArray(apifyProxyGroups))) {
117
- fieldErrors.push(m("inputSchema.validation.proxyGroupMustBeArrayOfStrings", { rootName: "input", fieldKey }));
118
- return fieldErrors;
119
- }
120
- const selectedProxyGroups = apifyProxyGroups || [];
121
- if (!selectedProxyGroups.length && !options.hasAutoProxyGroups) {
122
- fieldErrors.push(m("inputSchema.validation.noAvailableAutoProxy"));
123
- return fieldErrors;
124
- }
125
- const availableProxyGroupsById = {};
126
- (options.availableProxyGroups || []).forEach((group) => {
127
- availableProxyGroupsById[group] = true;
128
- });
129
- const unavailableProxyGroups = selectedProxyGroups.filter((group) => !availableProxyGroupsById[group]);
130
- if (unavailableProxyGroups.length) {
131
- fieldErrors.push(
132
- m("inputSchema.validation.proxyGroupsNotAvailable", {
133
- rootName: "input",
134
- fieldKey,
135
- groups: unavailableProxyGroups.join(", ")
136
- })
137
- );
138
- }
139
- const blockedProxyGroupsById = options.disabledProxyGroups || {};
140
- selectedProxyGroups.filter((group) => blockedProxyGroupsById[group]).forEach((blockedGroup) => {
141
- fieldErrors.push(blockedProxyGroupsById[blockedGroup]);
142
- });
143
- return fieldErrors;
144
- }
145
- __name(validateProxyField, "validateProxyField");
146
- function validateInputUsingValidator(validator, inputSchema, input, options = {}) {
147
- const isValid = validator(input);
148
- const { properties } = inputSchema;
149
- const required = inputSchema.required || [];
150
- let errors = [];
151
- if (!isValid) {
152
- errors = validator.errors.filter((error) => {
153
- if (error.keyword === "type" && error.instancePath) {
154
- const path = error.instancePath.replace(/^\//, "").split("/")[0];
155
- const propSchema = inputSchema.properties?.[path];
156
- const value = input[path];
157
- if (propSchema?.isSecret && typeof value === "string" && (propSchema.type === "object" || propSchema.type === "array") && (0, import_input_secrets.isEncryptedValueForFieldType)(value, propSchema.type)) {
158
- return false;
159
- }
160
- }
161
- return true;
162
- }).map((error) => parseAjvError(error, "input", properties, input)).filter((error) => !!error);
163
- }
164
- Object.keys(properties).forEach((property) => {
165
- const value = input[property];
166
- const { type, editor, patternKey, patternValue, isSecret } = properties[property];
167
- const fieldErrors = [];
168
- if (type === "object" && editor === "proxy") {
169
- const proxyValidationErrors = validateProxyField(
170
- property,
171
- value,
172
- required.includes(property),
173
- options.proxy
174
- );
175
- proxyValidationErrors.forEach((error) => {
176
- fieldErrors.push(error);
177
- });
178
- }
179
- if (type === "array" && value && Array.isArray(value)) {
180
- if (editor === "requestListSources") {
181
- const invalidIndexes = [];
182
- value.forEach((item, index) => {
183
- if (!item) invalidIndexes.push(index);
184
- else if (!item.url && !item.requestsFromUrl) invalidIndexes.push(index);
185
- else if (item.url && !import_consts.URL_REGEX.test(item.url)) invalidIndexes.push(index);
186
- else if (item.requestsFromUrl && !import_consts.URL_REGEX.test(item.requestsFromUrl)) invalidIndexes.push(index);
187
- });
188
- if (invalidIndexes.length) {
189
- fieldErrors.push(
190
- m("inputSchema.validation.requestListSourcesInvalid", {
191
- rootName: "input",
192
- fieldKey: property,
193
- invalidIndexes: invalidIndexes.join(",")
194
- })
195
- );
196
- }
197
- }
198
- if (patternKey && editor === "keyValue") {
199
- const check = new RegExp(patternKey);
200
- const invalidIndexes = [];
201
- value.forEach((item, index) => {
202
- if (!check.test(item.key)) invalidIndexes.push(index);
203
- });
204
- if (invalidIndexes.length) {
205
- const customError = getCustomErrorMessage(inputSchema, `properties/${property}/patternKey`);
206
- fieldErrors.push(
207
- customError ?? m("inputSchema.validation.arrayKeysInvalid", {
208
- rootName: "input",
209
- fieldKey: property,
210
- invalidIndexes: invalidIndexes.join(","),
211
- pattern: patternKey
212
- })
213
- );
214
- }
215
- }
216
- if (patternValue && editor === "keyValue") {
217
- const check = new RegExp(patternValue);
218
- const invalidIndexes = [];
219
- value.forEach((item, index) => {
220
- if (!check.test(item.value)) invalidIndexes.push(index);
221
- });
222
- if (invalidIndexes.length) {
223
- const customError = getCustomErrorMessage(inputSchema, `properties/${property}/patternValue`);
224
- fieldErrors.push(
225
- customError ?? m("inputSchema.validation.arrayValuesInvalid", {
226
- rootName: "input",
227
- fieldKey: property,
228
- invalidIndexes: invalidIndexes.join(","),
229
- pattern: patternValue
230
- })
231
- );
232
- }
233
- } else if (patternValue && editor === "stringList") {
234
- const check = new RegExp(patternValue);
235
- const invalidIndexes = [];
236
- value.forEach((item, index) => {
237
- if (!check.test(item)) invalidIndexes.push(index);
238
- });
239
- if (invalidIndexes.length) {
240
- const customError = getCustomErrorMessage(inputSchema, `properties/${property}/patternValue`);
241
- fieldErrors.push(
242
- customError ?? m("inputSchema.validation.arrayValuesInvalid", {
243
- rootName: "input",
244
- fieldKey: property,
245
- invalidIndexes: invalidIndexes.join(","),
246
- pattern: patternValue
247
- })
248
- );
249
- }
250
- }
251
- }
252
- if (type === "object" && value && typeof value === "object") {
253
- if (patternKey) {
254
- const check = new RegExp(patternKey);
255
- const invalidKeys = [];
256
- Object.keys(value).forEach((key) => {
257
- if (!check.test(key)) invalidKeys.push(key);
258
- });
259
- if (invalidKeys.length) {
260
- const customError = getCustomErrorMessage(inputSchema, `properties/${property}/patternKey`);
261
- fieldErrors.push(
262
- customError ?? m("inputSchema.validation.objectKeysInvalid", {
263
- rootName: "input",
264
- fieldKey: property,
265
- invalidKeys: invalidKeys.join(","),
266
- pattern: patternKey
267
- })
268
- );
269
- }
270
- }
271
- if (patternValue) {
272
- const check = new RegExp(patternValue);
273
- const invalidKeys = [];
274
- Object.keys(value).forEach((key) => {
275
- const propertyValue = value[key];
276
- if (typeof propertyValue !== "string" || !check.test(propertyValue)) invalidKeys.push(key);
277
- });
278
- if (invalidKeys.length) {
279
- const customError = getCustomErrorMessage(inputSchema, `properties/${property}/patternValue`);
280
- fieldErrors.push(
281
- customError ?? m("inputSchema.validation.objectValuesInvalid", {
282
- rootName: "input",
283
- fieldKey: property,
284
- invalidKeys: invalidKeys.join(","),
285
- pattern: patternValue
286
- })
287
- );
288
- }
289
- }
290
- }
291
- if (isSecret && value && typeof value === "string") {
292
- if ((0, import_input_secrets.isEncryptedValueForFieldType)(value, type) && !(0, import_input_secrets.isEncryptedValueForFieldSchema)(value, properties[property])) {
293
- fieldErrors.push(m("inputSchema.validation.secretFieldSchemaChanged", { fieldKey: property }));
294
- }
295
- }
296
- if (fieldErrors.length > 0) {
297
- const message = fieldErrors.join(", ");
298
- errors.push({ fieldKey: property, message });
299
- }
300
- });
301
- return errors;
302
- }
303
- __name(validateInputUsingValidator, "validateInputUsingValidator");
304
- function makeInputJsFieldsReadable(json, jsFields, jsonSpacing = 4, globalSpacing = 0) {
305
- const parsedJson = JSON.parse(json);
306
- const replacements = {};
307
- jsFields.forEach((field) => {
308
- let maybeFunction = parsedJson[field];
309
- if (!maybeFunction || typeof maybeFunction !== "string") return;
310
- let ast;
311
- try {
312
- ast = (0, import_acorn_loose.parse)(maybeFunction, { ecmaVersion: "latest" });
313
- } catch {
314
- return;
315
- }
316
- const isMultiline = maybeFunction.includes("\n");
317
- const isSingleFunction = ast && ast.body.length === 1 && (ast.body[0].type === "FunctionDeclaration" || ast.body[0].type === "ExpressionStatement" && ast.body[0].expression.type === "ArrowFunctionExpression");
318
- if (!isSingleFunction && !isMultiline) return;
319
- const spaces = isSingleFunction ? " ".repeat(jsonSpacing) : "";
320
- maybeFunction = maybeFunction.split("\n").join(`
321
- ${spaces}`).trim();
322
- const replacementValue = isSingleFunction ? maybeFunction.replace(/[;]+$/g, "") : `\`${maybeFunction}\``;
323
- const replacementToken = `<<<REPLACEMENT_TOKEN:${Math.random()}>>>`;
324
- replacements[replacementToken] = replacementValue;
325
- parsedJson[field] = replacementToken;
326
- });
327
- let niceJson = JSON.stringify(parsedJson, null, jsonSpacing);
328
- Object.entries(replacements).forEach(([replacementToken, replacementValue]) => {
329
- niceJson = niceJson.replace(`"${replacementToken}"`, replacementValue);
330
- });
331
- const globalSpaces = new Array(globalSpacing).fill(" ").join("");
332
- niceJson = niceJson.split("\n").join(`
333
- ${globalSpaces}`);
334
- return niceJson;
335
- }
336
- __name(makeInputJsFieldsReadable, "makeInputJsFieldsReadable");
337
- var DRAFT_2019_09_META_SCHEMA = "https://json-schema.org/draft/2019-09/schema";
338
- function ensureAjvSupportsDraft2019(ajvInstance) {
339
- const metaSchema = ajvInstance.getSchema(DRAFT_2019_09_META_SCHEMA);
340
- if (!metaSchema) {
341
- throw new Error(
342
- `The provided Ajv instance does not support draft-2019-09 (missing meta-schema ${DRAFT_2019_09_META_SCHEMA}).`
343
- );
344
- }
345
- }
346
- __name(ensureAjvSupportsDraft2019, "ensureAjvSupportsDraft2019");
347
- function validateRegexpPattern(pattern, fieldKey) {
348
- try {
349
- new RegExp(pattern);
350
- } catch {
351
- const message = m("inputSchema.validation.regexpNotValid", { pattern, fieldKey });
352
- throw new Error(`Input schema is not valid (${message})`);
353
- }
354
- }
355
- __name(validateRegexpPattern, "validateRegexpPattern");
356
-
357
- // src/input_schema.ts
358
- var { definitions } = import_json_schemas.inputSchema;
359
- var [fieldDefinitions, subFieldDefinitions] = Object.values(definitions).reduce(
360
- (acc, definition) => {
361
- if (definition.title.startsWith("Utils:") || definition.title.startsWith("Component:")) {
362
- return acc;
363
- }
364
- if (definition.title.startsWith("Sub-schema:")) {
365
- acc[1].push(definition);
366
- } else {
367
- acc[0].push(definition);
368
- }
369
- return acc;
370
- },
371
- [[], []]
372
- );
373
- function getCustomErrorMessage(rootSchema, schemaPath) {
374
- if (!schemaPath) return null;
375
- const pathParts = schemaPath.replace(/^#\//, "").split("/").filter(Boolean);
376
- const keyword = pathParts.pop();
377
- if (!keyword) return null;
378
- let schemaFragment = rootSchema;
379
- for (const key of pathParts) {
380
- if (schemaFragment && typeof schemaFragment === "object") {
381
- schemaFragment = schemaFragment[key];
382
- } else {
383
- return null;
384
- }
385
- }
386
- if (typeof schemaFragment !== "object") {
387
- return null;
388
- }
389
- const { errorMessage } = schemaFragment;
390
- if (!errorMessage) return null;
391
- if (typeof errorMessage === "object" && keyword in errorMessage) {
392
- return errorMessage[keyword];
393
- }
394
- return null;
395
- }
396
- __name(getCustomErrorMessage, "getCustomErrorMessage");
397
- function parseAjvError(error, rootName, properties = {}, input = {}) {
398
- let fieldKey;
399
- let message;
400
- const cleanPropertyName = /* @__PURE__ */ __name((name) => {
401
- return name.replace(/^\/|\/$/g, "").replace(/\//g, ".");
402
- }, "cleanPropertyName");
403
- const customError = getCustomErrorMessage({ properties }, error.schemaPath);
404
- if (customError) {
405
- fieldKey = cleanPropertyName(error.instancePath);
406
- return { fieldKey, message: customError };
407
- }
408
- if (error.keyword === "type") {
409
- fieldKey = cleanPropertyName(error.instancePath);
410
- if (properties[fieldKey] && properties[fieldKey].nullable && input[fieldKey] === null) {
411
- return null;
412
- }
413
- message = m("inputSchema.validation.generic", { rootName, fieldKey, message: error.message });
414
- } else if (error.keyword === "required") {
415
- fieldKey = cleanPropertyName(`${error.instancePath}/${error.params.missingProperty}`);
416
- message = m("inputSchema.validation.required", { rootName, fieldKey });
417
- } else if (error.keyword === "additionalProperties") {
418
- fieldKey = cleanPropertyName(`${error.instancePath}/${error.params.additionalProperty}`);
419
- message = m("inputSchema.validation.additionalProperty", { rootName, fieldKey });
420
- } else if (error.keyword === "unevaluatedProperties") {
421
- fieldKey = cleanPropertyName(`${error.instancePath}/${error.params.unevaluatedProperty}`);
422
- message = m("inputSchema.validation.additionalProperty", { rootName, fieldKey });
423
- } else if (error.keyword === "enum") {
424
- fieldKey = cleanPropertyName(error.instancePath);
425
- const errorMessage = `${error.message}: "${error.params.allowedValues.join('", "')}"`;
426
- message = m("inputSchema.validation.generic", { rootName, fieldKey, message: errorMessage });
427
- } else if (error.keyword === "const") {
428
- fieldKey = cleanPropertyName(error.instancePath);
429
- message = m("inputSchema.validation.generic", { rootName, fieldKey, message: error.message });
430
- } else {
431
- fieldKey = cleanPropertyName(error.instancePath);
432
- message = m("inputSchema.validation.generic", { rootName, fieldKey, message: error.message });
433
- }
434
- return { fieldKey, message };
435
- }
436
- __name(parseAjvError, "parseAjvError");
437
- function selectBestError(errors) {
438
- const branchPattern = /\/(oneOf|anyOf)\/\d+\//;
439
- const nonBranchErrors = errors.filter(
440
- (e) => !branchPattern.test(e.schemaPath) && e.keyword !== "oneOf" && e.keyword !== "anyOf"
441
- );
442
- return nonBranchErrors[0] ?? errors[0];
443
- }
444
- __name(selectBestError, "selectBestError");
445
- var validateAgainstSchemaOrThrow = /* @__PURE__ */ __name((validator, obj, inputSchema, rootName) => {
446
- if (validator.validate(inputSchema, obj)) return;
447
- let bestError = selectBestError(validator.errors);
448
- const branchPattern = /\/(oneOf|anyOf)\/\d+\//;
449
- if (bestError.keyword === "enum" && branchPattern.test(bestError.schemaPath)) {
450
- const propName = bestError.instancePath.replace(/^\//, "");
451
- if (propName && !propName.includes("/")) {
452
- const topLevelEnum = inputSchema?.properties?.[propName]?.enum;
453
- if (Array.isArray(topLevelEnum) && !topLevelEnum.includes(obj[propName])) {
454
- bestError = { ...bestError, params: { allowedValues: topLevelEnum } };
455
- }
456
- }
457
- }
458
- const errorMessage = parseAjvError(bestError, rootName)?.message;
459
- throw new Error(`Input schema is not valid (${errorMessage})`);
460
- }, "validateAgainstSchemaOrThrow");
461
- function validateBasicStructure(validator, obj) {
462
- const { $id, ...schemaWithoutId } = import_json_schemas.inputSchema;
463
- const schemaWithoutProperties = {
464
- ...schemaWithoutId,
465
- properties: { ...import_json_schemas.inputSchema.properties, properties: { type: "object" } }
466
- };
467
- validateAgainstSchemaOrThrow(validator, obj, schemaWithoutProperties, "schema");
468
- }
469
- __name(validateBasicStructure, "validateBasicStructure");
470
- function validateFieldAgainstSchemaDefinition(validator, fieldSchema, fieldKey, isSubField = false) {
471
- const relevantDefinitions = isSubField ? subFieldDefinitions : fieldDefinitions;
472
- const matchingDefinitions = Object.values(relevantDefinitions).filter((definition2) => {
473
- return definition2.properties.type.enum ? (
474
- // This is a normal case where fieldSchema.type can be only one possible value matching definition.properties.type.enum.0
475
- definition2.properties.type.enum[0] === fieldSchema.type
476
- ) : (
477
- // This is a type "Any" where fieldSchema.type is an array of possible values
478
- Array.isArray(fieldSchema.type)
479
- );
480
- });
481
- if (matchingDefinitions.length === 0) {
482
- const errorMessage = m("inputSchema.validation.noMatchingDefinition", { fieldKey });
483
- throw new Error(`Input schema is not valid (${errorMessage})`);
484
- }
485
- const enhanceDefinition = /* @__PURE__ */ __name((definition2) => {
486
- return {
487
- ...definition2,
488
- definitions
489
- };
490
- }, "enhanceDefinition");
491
- if (matchingDefinitions.length === 1) {
492
- validateAgainstSchemaOrThrow(
493
- validator,
494
- fieldSchema,
495
- enhanceDefinition(matchingDefinitions[0]),
496
- `schema.properties.${fieldKey}`
497
- );
498
- return;
499
- }
500
- if (fieldSchema.enum) {
501
- const definition2 = matchingDefinitions.filter((item) => !!item.properties.enum).pop();
502
- if (!definition2) throw new Error('Input schema validation failed to find "enum property" definition');
503
- validateAgainstSchemaOrThrow(
504
- validator,
505
- fieldSchema,
506
- enhanceDefinition(definition2),
507
- `schema.properties.${fieldKey}`
508
- );
509
- return;
510
- }
511
- if (fieldSchema.resourceType) {
512
- const definition2 = matchingDefinitions.filter((item) => !!item.properties.resourceType).pop();
513
- if (!definition2) throw new Error('Input schema validation failed to find "resource property" definition');
514
- validateAgainstSchemaOrThrow(
515
- validator,
516
- fieldSchema,
517
- enhanceDefinition(definition2),
518
- `schema.properties.${fieldKey}`
519
- );
520
- return;
521
- }
522
- const definition = matchingDefinitions.filter((item) => !item.properties.enum && !item.properties.resourceType).pop();
523
- if (!definition)
524
- throw new Error('Input schema validation failed to find other than "enum" or "resource" definition');
525
- validateAgainstSchemaOrThrow(
526
- validator,
527
- fieldSchema,
528
- enhanceDefinition(definition),
529
- `schema.properties.${fieldKey}`
530
- );
531
- }
532
- __name(validateFieldAgainstSchemaDefinition, "validateFieldAgainstSchemaDefinition");
533
- function validateField(validator, fieldSchema, fieldKey, isSubField = false) {
534
- for (const property of ["patternKey", "patternValue"]) {
535
- if (property in fieldSchema) {
536
- const message = m("inputSchema.validation.deprecatedProperty", { fieldKey, property });
537
- throw new Error(`Input schema is not valid (${message})`);
538
- }
539
- }
540
- validateFieldAgainstSchemaDefinition(validator, fieldSchema, fieldKey, isSubField);
541
- const { pattern } = fieldSchema;
542
- if (pattern) validateRegexpPattern(pattern, `${fieldKey}.pattern`);
543
- }
544
- __name(validateField, "validateField");
545
- function validateSubFields(validator, fieldSchema, fieldKey) {
546
- Object.entries(fieldSchema.properties).forEach(([subFieldKey, subFieldSchema]) => {
547
- if (subFieldSchema.type === "object" && subFieldSchema.properties) {
548
- validateSubFields(validator, subFieldSchema, `${fieldKey}.${subFieldKey}`);
549
- }
550
- if (subFieldSchema.type === "array" && subFieldSchema.items) {
551
- validateArrayField(validator, subFieldSchema, `${fieldKey}.${subFieldKey}`);
552
- }
553
- validateField(validator, subFieldSchema, `${fieldKey}.${subFieldKey}`, true);
554
- });
555
- }
556
- __name(validateSubFields, "validateSubFields");
557
- function validateArrayField(validator, fieldSchema, fieldKey) {
558
- const arraySchema = fieldSchema.items;
559
- if (!arraySchema) return;
560
- if (arraySchema.type === "object" && arraySchema.properties) {
561
- validateSubFields(validator, arraySchema, `${fieldKey}.items`);
562
- }
563
- if (arraySchema.type === "array" && arraySchema.items) {
564
- validateArrayField(validator, arraySchema, `${fieldKey}.items`);
565
- }
566
- }
567
- __name(validateArrayField, "validateArrayField");
568
- function validateProperties(inputSchema, validator) {
569
- Object.entries(inputSchema.properties).forEach(([fieldKey, fieldSchema]) => {
570
- if (fieldSchema.type === "object" && fieldSchema.properties) {
571
- validateSubFields(validator, fieldSchema, fieldKey);
572
- }
573
- if (fieldSchema.type === "array" && fieldSchema.items) {
574
- validateArrayField(validator, fieldSchema, fieldKey);
575
- }
576
- validateField(validator, fieldSchema, fieldKey);
577
- });
578
- }
579
- __name(validateProperties, "validateProperties");
580
- function validateExistenceOfRequiredFields(inputSchema) {
581
- if (!inputSchema?.required?.length) return;
582
- Object.values(inputSchema?.required).forEach((fieldKey) => {
583
- if (inputSchema?.properties[fieldKey]) return;
584
- throw new Error(m("inputSchema.validation.missingRequiredField", { fieldKey }));
585
- });
586
- }
587
- __name(validateExistenceOfRequiredFields, "validateExistenceOfRequiredFields");
588
- function validateInputSchema(validator, inputSchema) {
589
- ensureAjvSupportsDraft2019(validator);
590
- validateBasicStructure(validator, inputSchema);
591
- validateProperties(inputSchema, validator);
592
- validateExistenceOfRequiredFields(inputSchema);
593
- validateAgainstSchemaOrThrow(validator, inputSchema, import_json_schemas.inputSchema, "schema");
594
- }
595
- __name(validateInputSchema, "validateInputSchema");
596
- // Annotate the CommonJS export names for ESM import in node:
597
- 0 && (module.exports = {
598
- ensureAjvSupportsDraft2019,
599
- getCustomErrorMessage,
600
- inputSchema,
601
- m,
602
- makeInputJsFieldsReadable,
603
- parseAjvError,
604
- validateExistenceOfRequiredFields,
605
- validateInputSchema,
606
- validateInputUsingValidator,
607
- validateRegexpPattern
608
- });
609
- //# sourceMappingURL=index.cjs.map