@arrirpc/schema 0.73.0 → 0.74.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.mjs CHANGED
@@ -1,12 +1,33 @@
1
1
  import { isSchemaFormProperties, isSchemaFormValues, isSchemaFormElements, isSchemaFormDiscriminator, isSchemaFormEmpty, isSchemaFormType, isSchemaFormEnum, isSchemaFormRef } from '@arrirpc/type-defs';
2
+ import { i as isAScalarSchema, a as isAObjectSchema, b as isAStringEnumSchema, c as isAAraySchema, d as isARecordSchema, e as isADiscriminatorSchema, f as isARefSchema, g as createStandardSchemaProperty, n as newValidationContext, h as hideInvalidProperties, V as VALIDATOR_KEY, j as isObject } from './shared/schema.CZrExOkx.mjs';
3
+ export { N as NumberTypeValues, k as isASchema } from './shared/schema.CZrExOkx.mjs';
2
4
  import { camelCase } from 'scule';
3
- import { u as uint8Max, a as uint8Min, b as uint16Max, c as uint16Min, d as uint32Max, e as uint32Min, i as int8Max, f as int8Min, g as int16Max, h as int16Min, j as int32Max, k as int32Min, l as isAScalarSchema, m as isAObjectSchema, n as isAStringEnumSchema, o as isAAraySchema, p as isARecordSchema, q as isADiscriminatorSchema, r as isARefSchema, s as errors, V as ValidationError, t as createStandardSchemaProperty, v as any, w as array, x as boolean, y as clone, z as coerce, A as discriminator, B as enumerator, C as extend, D as float32, E as float64, F as int16, G as int32, H as int64, I as int8, J as nullable, K as number, L as object, M as omit, N as optional, O as parse, P as partial, Q as pick, R as record, S as recursive, T as safeCoerce, U as safeParse, W as serialize, X as string, Y as stringEnum, Z as timestamp, _ as uint16, $ as uint32, a0 as uint64, a1 as uint8, a2 as validate, a3 as SCHEMA_METADATA } from './shared/schema.PNAcAdz3.mjs';
4
- export { ah as NumberTypeValues, ac as STR_ESCAPE, aj as hideInvalidProperties, a5 as int64Max, a4 as int64Min, ag as isASchema, ai as isObject, af as isValidationError, a8 as parseObjectSchema, ae as sanitizeJson, aa as serializeObject, ad as serializeSmallString, ab as serializeString, a7 as uint64Max, a6 as uint64Min, a9 as validateObjectSchema } from './shared/schema.PNAcAdz3.mjs';
5
5
 
6
- function createParsingTemplate(input, schema) {
6
+ const int8Min = -128;
7
+ const int8Max = 127;
8
+ const uint8Min = 0;
9
+ const uint8Max = 255;
10
+ const int16Min = -32768;
11
+ const int16Max = 32767;
12
+ const uint16Min = 0;
13
+ const uint16Max = 65535;
14
+ const int32Min = -2147483648;
15
+ const int32Max = 2147483647;
16
+ const uint32Min = 0;
17
+ const uint32Max = 4294967295;
18
+ const int64Min = BigInt("-9223372036854775808");
19
+ const int64Max = BigInt("9223372036854775807");
20
+ const uint64Min = BigInt("0");
21
+ const uint64Max = BigInt("18446744073709551615");
22
+
23
+ function createParsingTemplate(input, schema, shouldCoerce = false) {
7
24
  const fallbackTemplate = `
8
- function $fallback(instancePath, schemaPath) {
9
- throw new Error(\`Error parsing input. InstancePath: "\${instancePath}". SchemaPath: "\${schemaPath}"\`);
25
+ function $fallback(instancePath, schemaPath, message) {
26
+ context.errors.push({
27
+ message: message,
28
+ instancePath: instancePath,
29
+ schemaPath: schemaPath,
30
+ })
10
31
  }`;
11
32
  let jsonParseCheck = "";
12
33
  const subFunctions = {};
@@ -16,7 +37,8 @@ function createParsingTemplate(input, schema) {
16
37
  schema,
17
38
  instancePath: "",
18
39
  schemaPath: "",
19
- subFunctions
40
+ subFunctions,
41
+ shouldCoerce
20
42
  });
21
43
  const jsonTemplate = schemaTemplate$1({
22
44
  val: "json",
@@ -24,7 +46,8 @@ function createParsingTemplate(input, schema) {
24
46
  schema,
25
47
  instancePath: "",
26
48
  schemaPath: "",
27
- subFunctions
49
+ subFunctions,
50
+ shouldCoerce
28
51
  });
29
52
  if (isSchemaFormProperties(schema) || isSchemaFormValues(schema) || isSchemaFormElements(schema) || isSchemaFormDiscriminator(schema)) {
30
53
  jsonParseCheck = `if (typeof ${input} === 'string') {
@@ -114,8 +137,27 @@ function anyTemplate$1(input) {
114
137
  return `${input.targetVal} = ${input.val}`;
115
138
  }
116
139
  function booleanTemplate$2(input) {
117
- const errorMessage = input.instancePath.length ? `Expected boolean for ${input.instancePath}` : `Expected boolean`;
140
+ const errorMessage = "expected boolean";
118
141
  const templateParts = [];
142
+ if (input.shouldCoerce) {
143
+ templateParts.push(`if (${input.val} === true || ${input.val} === 'true' || ${input.val} === 'TRUE' || ${input.val} === 1 || ${input.val} === '1') {
144
+ ${input.targetVal} = true;
145
+ }
146
+ else if (${input.val} === false || ${input.val} === 'false' || ${input.val} === 'FALSE' || ${input.val} === 0 || ${input.val} === '0') {
147
+ ${input.targetVal} = false;
148
+ }`);
149
+ if (input.schema.nullable) {
150
+ templateParts.push(`else if (${input.val} === null || ${input.val} === 'null') {
151
+ ${input.targetVal} = null;
152
+ }`);
153
+ }
154
+ templateParts.push(
155
+ `else {
156
+ $fallback("${input.instancePath}", "${input.schemaPath}/type", "${errorMessage}");
157
+ }`
158
+ );
159
+ return templateParts.join("\n");
160
+ }
119
161
  if (input.instancePath.length === 0) {
120
162
  templateParts.push(`if (typeof ${input.val} === 'string') {
121
163
  if (${input.val} === 'true') {
@@ -151,7 +193,7 @@ function booleanTemplate$2(input) {
151
193
  return templateParts.join("\n");
152
194
  }
153
195
  function stringTemplate$2(input) {
154
- const errorMessage = `Expected string at ${input.instancePath}`;
196
+ const errorMessage = `expected string`;
155
197
  const mainTemplate = `if (typeof ${input.val} === 'string') {
156
198
  ${input.targetVal} = ${input.val};
157
199
  } else {
@@ -174,19 +216,21 @@ function getVarName(input) {
174
216
  function floatTemplate$1(input) {
175
217
  const valName = getVarName(`${input.val}Val`);
176
218
  const templateParts = [];
177
- if (input.instancePath.length === 0) {
219
+ if (input.instancePath.length === 0 || input.shouldCoerce) {
178
220
  templateParts.push(`if (typeof ${input.val} === 'string') {
179
221
  const ${valName} = Number(${input.val});
180
- if (!Number.isNaN(parsedVal)) {
222
+ if (!Number.isNaN(${valName})) {
181
223
  ${input.targetVal} = ${valName};
182
224
  }`);
183
225
  if (input.schema.nullable) {
184
- templateParts.push(`if (${input.val} === 'null') {
226
+ templateParts.push(`else if (${input.val} === 'null') {
185
227
  ${input.targetVal} = null;
186
228
  }`);
187
229
  }
188
230
  templateParts.push(
189
- `$fallback("${input.instancePath}", "${input.schemaPath}/type", \`Could not parse number from \${${input.val}}\`);`
231
+ `else {
232
+ $fallback("${input.instancePath}", "${input.schemaPath}/type", \`Could not parse number from \${${input.val}}\`);
233
+ }`
190
234
  );
191
235
  templateParts.push("}");
192
236
  }
@@ -197,31 +241,36 @@ function floatTemplate$1(input) {
197
241
  $fallback("${input.instancePath}", "${input.schemaPath}/type", "${errorMessage}");
198
242
  }`;
199
243
  if (input.schema.nullable) {
200
- templateParts.push(`if (${input.val} === null) {
244
+ templateParts.push(`${input.instancePath.length === 0 || input.shouldCoerce ? "else " : ""}if (${input.val} === null) {
201
245
  ${input.targetVal} = null;
202
246
  } else {
203
247
  ${mainTemplate}
204
248
  }`);
205
249
  } else {
206
- templateParts.push(mainTemplate);
250
+ templateParts.push(
251
+ `${input.instancePath.length === 0 || input.shouldCoerce ? "else " : ""}${mainTemplate}`
252
+ );
207
253
  }
208
254
  return templateParts.join("\n");
209
255
  }
210
256
  function intTemplate$1(input, min, max) {
211
257
  const templateParts = [];
212
- if (input.instancePath.length === 0) {
258
+ const shouldCoerce = input.shouldCoerce || input.instancePath.length === 0;
259
+ if (shouldCoerce) {
213
260
  templateParts.push(`if (typeof ${input.val} === 'string') {
214
261
  const parsedVal = Number(${input.val});
215
262
  if (Number.isInteger(parsedVal) && parsedVal >= ${min} && parsedVal <= ${max}) {
216
- ${input.targetVal} = ${input.val};
263
+ ${input.targetVal} = parsedVal;
217
264
  }`);
218
265
  if (input.schema.nullable) {
219
- templateParts.push(`if (${input.val} === 'null') {
266
+ templateParts.push(`else if (${input.val} === 'null') {
220
267
  ${input.targetVal} = null;
221
268
  }`);
222
269
  }
223
270
  templateParts.push(
224
- `$fallback("${input.instancePath}", "${input.schemaPath}", "Expected valid integer between ${min} and ${max});`
271
+ `else {
272
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Expected valid integer between ${min} and ${max}");
273
+ }`
225
274
  );
226
275
  templateParts.push("}");
227
276
  }
@@ -230,14 +279,15 @@ function intTemplate$1(input, min, max) {
230
279
  } else {
231
280
  $fallback("${input.instancePath}", "${input.schemaPath}", "Expected valid integer between ${min} and ${max}");
232
281
  }`;
282
+ const prefix = shouldCoerce ? `else ` : "";
233
283
  if (input.schema.nullable) {
234
- templateParts.push(`if (${input.val} === null) {
284
+ templateParts.push(`${prefix}if (${input.val} === null) {
235
285
  ${input.targetVal} = null;
236
286
  } else {
237
287
  ${mainTemplate}
238
288
  }`);
239
289
  } else {
240
- templateParts.push(mainTemplate);
290
+ templateParts.push(prefix + mainTemplate);
241
291
  }
242
292
  return templateParts.join("\n");
243
293
  }
@@ -246,7 +296,7 @@ function bigIntTemplate$2(input, isUnsigned) {
246
296
  templateParts.push(
247
297
  `if (typeof ${input.val} === 'string' || typeof ${input.val} === 'number') {`
248
298
  );
249
- if (input.instancePath.length === 0 && input.schema.nullable) {
299
+ if ((input.instancePath.length === 0 || input.shouldCoerce) && input.schema.nullable) {
250
300
  templateParts.push(`if (${input.val} === 'null') {
251
301
  ${input.targetVal} = null;
252
302
  } else {`);
@@ -263,9 +313,9 @@ function bigIntTemplate$2(input, isUnsigned) {
263
313
  templateParts.push(`${input.targetVal} = val;`);
264
314
  }
265
315
  templateParts.push(`} catch(err) {
266
- $fallback("${input.instancePath}", "${input.schemaPath}", "Unable to parse BigInt from ${input.val}.");
316
+ $fallback("${input.instancePath}", "${input.schemaPath}", \`Unable to parse BigInt from \${${input.val}}\`);
267
317
  }`);
268
- if (input.instancePath.length === 0 && input.schema.nullable) {
318
+ if ((input.instancePath.length === 0 || input.shouldCoerce) && input.schema.nullable) {
269
319
  templateParts.push("}");
270
320
  }
271
321
  templateParts.push("}");
@@ -288,12 +338,41 @@ function bigIntTemplate$2(input, isUnsigned) {
288
338
  }`);
289
339
  }
290
340
  templateParts.push(`else {
291
- $fallback("${input.instancePath}", "${input.schemaPath}", "Expected BigInt or Integer string. Got \${${input.val}}");
341
+ $fallback("${input.instancePath}", "${input.schemaPath}", \`Expected BigInt or Integer string. Got \${${input.val}}\`);
292
342
  }`);
293
343
  return templateParts.join("\n");
294
344
  }
295
345
  function timestampTemplate$2(input) {
296
346
  const templateParts = [];
347
+ if (input.shouldCoerce) {
348
+ return `if (typeof ${input.val} === 'string') {
349
+ try {
350
+ const parsedVal = new Date(${input.val});
351
+ if (!Number.isNaN(parsedVal.getMonth())) {
352
+ ${input.targetVal} = parsedVal;
353
+ } ${input.schema.nullable ? `else if (${input.val} === 'null') {
354
+ ${input.targetVal} = null;
355
+ }` : ""} else {
356
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Unable to coerce date");
357
+ }
358
+ } catch (err) {
359
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Unable to parse date");
360
+ }
361
+ } else if (typeof ${input.val} === 'number') {
362
+ const parsedVal = new Date(${input.val});
363
+ if (!Number.isNaN(parsedVal.getMonth())) {
364
+ ${input.targetVal} = parsedVal;
365
+ } else {
366
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Unable to parse date");
367
+ }
368
+ } else if (typeof ${input.val} === 'object' && ${input.val} instanceof Date) {
369
+ ${input.targetVal} = ${input.val};
370
+ }${input.schema.nullable ? ` else if (${input.val} === null) {
371
+ ${input.targetVal} = null;
372
+ }` : ""} else {
373
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Unable to parse date");
374
+ }`;
375
+ }
297
376
  if (input.instancePath.length === 0) {
298
377
  templateParts.push(`if (typeof ${input.val} === 'string') {
299
378
  const parsedVal = new Date(${input.val});
@@ -315,7 +394,7 @@ function timestampTemplate$2(input) {
315
394
  } else if (typeof ${input.val} === 'string') {
316
395
  ${input.targetVal} = new Date(${input.val});
317
396
  } else {
318
- $fallback("${input.instancePath}", "${input.schemaPath}", "Expected instanceof Date or ISO Date string at ${input.instancePath}")
397
+ $fallback("${input.instancePath}", "${input.schemaPath}", "Expected instanceof Date or ISO Date string")
319
398
  }`;
320
399
  if (input.schema.nullable) {
321
400
  templateParts.push(`if (${input.val} === null) {
@@ -332,7 +411,7 @@ function enumTemplate$2(input) {
332
411
  const enumTemplate2 = input.schema.enum.map((val) => `${input.val} === "${val}"`).join(" || ");
333
412
  const errorMessage = `Expected one of the following values: [${input.schema.enum.join(
334
413
  ", "
335
- )}]${input.instancePath.length ? ` at ${input.instancePath}` : ""}.`;
414
+ )}]`;
336
415
  const templateParts = [];
337
416
  templateParts.push(`if (typeof ${input.val} === 'string') {
338
417
  if (${enumTemplate2}) {
@@ -395,7 +474,8 @@ function objectTemplate$2(input) {
395
474
  schema: subSchema,
396
475
  instancePath: `${input.instancePath}/${key}`,
397
476
  schemaPath: `${input.schemaPath}/properties/${key}`,
398
- subFunctions: input.subFunctions
477
+ subFunctions: input.subFunctions,
478
+ shouldCoerce: input.shouldCoerce
399
479
  });
400
480
  parsingParts.push(innerTemplate);
401
481
  }
@@ -408,7 +488,8 @@ function objectTemplate$2(input) {
408
488
  schema: subSchema,
409
489
  instancePath: `${input.instancePath}/${key}`,
410
490
  schemaPath: `${input.schemaPath}/optionalProperties/${key}`,
411
- subFunctions: input.subFunctions
491
+ subFunctions: input.subFunctions,
492
+ shouldCoerce: input.shouldCoerce
412
493
  });
413
494
  parsingParts.push(`if (typeof ${input.val}.${key} === 'undefined') {
414
495
  // ignore undefined
@@ -451,10 +532,11 @@ function arrayTemplate$2(input) {
451
532
  const innerTemplate = schemaTemplate$1({
452
533
  val: itemVar,
453
534
  targetVal: itemResultVar,
454
- instancePath: `${input.instancePath}/[0]`,
535
+ instancePath: `${input.instancePath}/[i]`,
455
536
  schemaPath: `${input.schemaPath}/elements`,
456
537
  schema: input.schema.elements,
457
- subFunctions: input.subFunctions
538
+ subFunctions: input.subFunctions,
539
+ shouldCoerce: input.shouldCoerce
458
540
  });
459
541
  const mainTemplate = `if (Array.isArray(${input.val})) {
460
542
  const ${resultVar} = [];
@@ -489,7 +571,8 @@ function discriminatorTemplate$2(input) {
489
571
  instancePath: `${input.instancePath}`,
490
572
  discriminatorKey: input.schema.discriminator,
491
573
  discriminatorValue: type,
492
- subFunctions: input.subFunctions
574
+ subFunctions: input.subFunctions,
575
+ shouldCoerce: input.shouldCoerce
493
576
  });
494
577
  switchParts.push(`case "${type}": {
495
578
  ${template}
@@ -542,7 +625,8 @@ function recordTemplate$2(input) {
542
625
  instancePath: `${input.instancePath}/[key]`,
543
626
  schemaPath: `${input.schemaPath}/values`,
544
627
  schema: input.schema.values,
545
- subFunctions: input.subFunctions
628
+ subFunctions: input.subFunctions,
629
+ shouldCoerce: input.shouldCoerce
546
630
  });
547
631
  const mainTemplate = `if (typeof ${input.val} === 'object' && ${input.val} !== null) {
548
632
  const ${resultVal} = {};
@@ -592,8 +676,7 @@ function createSerializationV2Template(inputName, schema) {
592
676
  instancePath: "",
593
677
  outputPrefix: "",
594
678
  needsSanitization: [],
595
- subFunctions
596
- };
679
+ subFunctions};
597
680
  const result = template(context);
598
681
  if (isSchemaFormType(schema) || isSchemaFormEnum(schema)) {
599
682
  return result;
@@ -831,8 +914,7 @@ function objectTemplate$1(input) {
831
914
  schemaPath: `${input.schemaPath}/properties/${key}`,
832
915
  outputPrefix: includeComma ? `,"${key}":` : `"${key}":`,
833
916
  needsSanitization: input.needsSanitization,
834
- subFunctions: input.subFunctions
835
- });
917
+ subFunctions: input.subFunctions});
836
918
  templateParts.push(innerTemplate);
837
919
  }
838
920
  if (isAllOptionalKeys) {
@@ -855,8 +937,7 @@ function objectTemplate$1(input) {
855
937
  targetVal: input.targetVal,
856
938
  outputPrefix: `"${key}":`,
857
939
  needsSanitization: input.needsSanitization,
858
- subFunctions: input.subFunctions
859
- });
940
+ subFunctions: input.subFunctions});
860
941
  const innerTemplateWithComma = template({
861
942
  schema: optionalPropSchema,
862
943
  schemaPath: `${input.schemaPath}/optionalProperties/${key}`,
@@ -865,8 +946,7 @@ function objectTemplate$1(input) {
865
946
  targetVal: input.targetVal,
866
947
  outputPrefix: `,"${key}":`,
867
948
  needsSanitization: input.needsSanitization,
868
- subFunctions: input.subFunctions
869
- });
949
+ subFunctions: input.subFunctions});
870
950
  templateParts.push(`if (typeof ${innerVal} !== 'undefined') {
871
951
  if (${hasFieldsVar}) {
872
952
  ${innerTemplateWithComma}
@@ -892,8 +972,7 @@ function objectTemplate$1(input) {
892
972
  targetVal: "json",
893
973
  outputPrefix: `,"${key}":`,
894
974
  needsSanitization: input.needsSanitization,
895
- subFunctions: input.subFunctions
896
- });
975
+ subFunctions: input.subFunctions});
897
976
  const completeInnerTemplate = `if (typeof ${innerVal} !== 'undefined') {
898
977
  ${innerTemplate}
899
978
  }`;
@@ -942,8 +1021,7 @@ function arrayTemplate$1(input) {
942
1021
  targetVal: input.targetVal,
943
1022
  outputPrefix: "",
944
1023
  needsSanitization: input.needsSanitization,
945
- subFunctions: input.subFunctions
946
- });
1024
+ subFunctions: input.subFunctions});
947
1025
  templateParts.push(`for (let i = 0; i < ${input.val}.length; i++) {
948
1026
  const ${itemVarName} = ${input.val}[i];
949
1027
  if (i !== 0) {
@@ -976,8 +1054,7 @@ function recordTemplate$1(input) {
976
1054
  targetVal: input.targetVal,
977
1055
  outputPrefix: "",
978
1056
  needsSanitization: input.needsSanitization,
979
- subFunctions: input.subFunctions
980
- });
1057
+ subFunctions: input.subFunctions});
981
1058
  templateParts.push(`for (let i = 0; i < ${keysVarName}.length; i++) {
982
1059
  const key = ${keysVarName}[i];
983
1060
  const innerVal = ${input.val}[key];
@@ -1045,8 +1122,7 @@ function discriminatorTemplate$1(input) {
1045
1122
  discriminatorValue: val,
1046
1123
  outputPrefix: input.outputPrefix,
1047
1124
  needsSanitization: input.needsSanitization,
1048
- subFunctions: input.subFunctions
1049
- });
1125
+ subFunctions: input.subFunctions});
1050
1126
  templateParts.push(`case '${val}': {
1051
1127
  ${innerTemplate}
1052
1128
  break;
@@ -1114,12 +1190,10 @@ function createValidationTemplate(inputName, schema) {
1114
1190
  const subFunctions = {};
1115
1191
  const template = schemaTemplate({
1116
1192
  val: inputName,
1117
- targetVal: "",
1118
1193
  schema,
1119
1194
  schemaPath: ``,
1120
1195
  instancePath: "",
1121
- subFunctions
1122
- });
1196
+ subFunctions});
1123
1197
  const subFunctionBodies = Object.keys(subFunctions).map(
1124
1198
  (key) => subFunctions[key]
1125
1199
  );
@@ -1239,9 +1313,7 @@ function objectTemplate(input) {
1239
1313
  schemaPath: `${input.schemaPath}/properties/${key}`,
1240
1314
  instancePath: `${input.instancePath}/${key}`,
1241
1315
  val: `${input.val}.${key}`,
1242
- targetVal: "",
1243
- subFunctions: input.subFunctions
1244
- })
1316
+ subFunctions: input.subFunctions})
1245
1317
  );
1246
1318
  }
1247
1319
  if (input.schema.optionalProperties) {
@@ -1252,16 +1324,14 @@ function objectTemplate(input) {
1252
1324
  schemaPath: `${input.schemaPath}/optionalProperties/${key}`,
1253
1325
  instancePath: `${input.instancePath}/${key}`,
1254
1326
  val: `${input.val}.${key}`,
1255
- targetVal: "",
1256
- subFunctions: input.subFunctions
1257
- });
1327
+ subFunctions: input.subFunctions});
1258
1328
  parts.push(
1259
1329
  `(typeof ${input.val}.${key} === 'undefined' || (${template}))`
1260
1330
  );
1261
1331
  }
1262
1332
  }
1263
1333
  let mainTemplate = parts.join(" && ");
1264
- const fnName = refFunctionName(input.schema.metadata.id ?? "");
1334
+ const fnName = refFunctionName(input.schema.metadata?.id ?? "");
1265
1335
  if (Object.keys(input.subFunctions).includes(fnName)) {
1266
1336
  if (!input.subFunctions[fnName]) {
1267
1337
  input.subFunctions[fnName] = `function ${fnName}(input) {
@@ -1288,9 +1358,7 @@ function arrayTemplate(input) {
1288
1358
  instancePath: `${input.instancePath}/item`,
1289
1359
  schemaPath: `${input.schemaPath}/elements`,
1290
1360
  schema: input.schema.elements,
1291
- targetVal: "",
1292
- subFunctions: input.subFunctions
1293
- });
1361
+ subFunctions: input.subFunctions});
1294
1362
  if (input.schema.nullable) {
1295
1363
  return `((Array.isArray(${input.val}) && ${input.val}.every((item) => ${innerTemplate})) || ${input.val} === null)`;
1296
1364
  }
@@ -1302,9 +1370,7 @@ function recordTemplate(input) {
1302
1370
  instancePath: `${input.instancePath}`,
1303
1371
  schemaPath: `${input.schemaPath}/values`,
1304
1372
  val: `${input.val}[key]`,
1305
- targetVal: "",
1306
- subFunctions: input.subFunctions
1307
- });
1373
+ subFunctions: input.subFunctions});
1308
1374
  const mainTemplate = `typeof ${input.val} === 'object' && ${input.val} !== null && Object.keys(${input.val}).every((key) => ${subTemplate})`;
1309
1375
  if (input.schema.nullable) {
1310
1376
  return `((${mainTemplate}) || ${input.val} === null)`;
@@ -1321,18 +1387,16 @@ function discriminatorTemplate(input) {
1321
1387
  parts.push(
1322
1388
  objectTemplate({
1323
1389
  val: input.val,
1324
- targetVal: "",
1325
1390
  schema: subSchema,
1326
1391
  schemaPath: `${input.schemaPath}/mapping/${discriminatorVal}`,
1327
1392
  instancePath: input.instancePath,
1328
1393
  discriminatorKey: input.schema.discriminator,
1329
1394
  discriminatorValue: discriminatorVal,
1330
- subFunctions: input.subFunctions
1331
- })
1395
+ subFunctions: input.subFunctions})
1332
1396
  );
1333
1397
  }
1334
1398
  let mainTemplate = `typeof ${input.val} === 'object' && ${input.val} !== null && (${parts.join(" || ")})`;
1335
- const fnName = refFunctionName(input.schema.metadata.id ?? "");
1399
+ const fnName = refFunctionName(input.schema.metadata?.id ?? "");
1336
1400
  if (Object.keys(input.subFunctions).includes(fnName)) {
1337
1401
  if (!input.subFunctions[fnName]) {
1338
1402
  input.subFunctions[fnName] = `function ${fnName}(input) {
@@ -1360,108 +1424,211 @@ function refTemplate(input) {
1360
1424
  return `${fnName}(${input.val})`;
1361
1425
  }
1362
1426
 
1427
+ function isValueError(input) {
1428
+ if (typeof input !== "object" || !input) {
1429
+ return false;
1430
+ }
1431
+ return "message" in input && typeof input.message === "string" && (typeof input.instancePath === "undefined" || typeof input.instancePath === "string") && (typeof input.schemaPath === "undefined" || typeof input.schemaPath === "string");
1432
+ }
1433
+ function errorMessageFromErrors(errors) {
1434
+ if (errors.length === 0) {
1435
+ return `Input failed validation`;
1436
+ }
1437
+ if (errors.length === 1) {
1438
+ return errors[0].message;
1439
+ }
1440
+ let propStr = "[";
1441
+ for (let i = 0; i < errors.length; i++) {
1442
+ const err = errors[i];
1443
+ if (i > 0) {
1444
+ propStr += ", ";
1445
+ }
1446
+ propStr += err.instancePath;
1447
+ }
1448
+ propStr += "]";
1449
+ return `Invalid input. Affected properties ${propStr}.`;
1450
+ }
1451
+ class ValidationException extends Error {
1452
+ errors;
1453
+ constructor(options) {
1454
+ super(options.message ?? errorMessageFromErrors(options.errors));
1455
+ this.errors = options.errors;
1456
+ }
1457
+ }
1458
+ function isValidationException(input) {
1459
+ return input instanceof ValidationException;
1460
+ }
1461
+
1363
1462
  function compile(schema) {
1364
1463
  const validateCode = createValidationTemplate("input", schema);
1365
- const parser = getCompiledParser("input", schema);
1366
- const parseFn = parser.fn;
1464
+ const parser = getCompiledParser("input", schema, false);
1465
+ const parserFn = parser.fn;
1466
+ const coercer = getCompiledParser("input", schema, true);
1467
+ const coercerFn = coercer.fn;
1367
1468
  const serializer = getCompiledSerializer(schema);
1368
1469
  const serializeFn = serializer.fn;
1470
+ const serialize = (input) => {
1471
+ try {
1472
+ const result2 = serializeFn(input);
1473
+ return {
1474
+ success: true,
1475
+ value: result2
1476
+ };
1477
+ } catch (err) {
1478
+ return {
1479
+ success: false,
1480
+ errors: [
1481
+ {
1482
+ instancePath: "/",
1483
+ message: err instanceof Error ? err.message : `${err}`
1484
+ }
1485
+ ]
1486
+ };
1487
+ }
1488
+ };
1369
1489
  const validate = new Function("input", validateCode);
1370
1490
  const parse = (input) => {
1491
+ const context = newValidationContext();
1371
1492
  try {
1372
- return parseFn(input);
1493
+ const result2 = parserFn(input, context);
1494
+ if (context.errors.length) {
1495
+ return {
1496
+ success: false,
1497
+ errors: context.errors
1498
+ };
1499
+ }
1500
+ return {
1501
+ success: true,
1502
+ value: result2
1503
+ };
1373
1504
  } catch (err) {
1374
- const errors$1 = errors(schema, input);
1375
- let errorMessage = err instanceof Error ? err.message : "";
1376
- if (errors$1.length) {
1377
- errorMessage = errors$1[0].message ?? `Parsing error at ${errors$1[0].instancePath}`;
1505
+ if (context.errors.length) {
1506
+ return {
1507
+ success: false,
1508
+ errors: context.errors
1509
+ };
1378
1510
  }
1379
- throw new ValidationError({
1380
- message: errorMessage,
1381
- errors: errors$1
1382
- });
1511
+ return {
1512
+ success: false,
1513
+ errors: [
1514
+ {
1515
+ message: err instanceof Error ? err.message : `${err}`,
1516
+ instancePath: "/"
1517
+ }
1518
+ ]
1519
+ };
1383
1520
  }
1384
1521
  };
1385
- const result = {
1386
- validate,
1387
- parse,
1388
- safeParse(input) {
1389
- try {
1390
- const result2 = parseFn(input);
1522
+ const coerce = (input) => {
1523
+ const context = newValidationContext();
1524
+ try {
1525
+ const result2 = coercerFn(input, context);
1526
+ if (context.errors.length) {
1391
1527
  return {
1392
- success: true,
1393
- value: result2
1528
+ success: false,
1529
+ errors: context.errors
1394
1530
  };
1395
- } catch (err) {
1396
- const errors$1 = errors(schema, input);
1397
- let errorMessage = err instanceof Error ? err.message : "";
1398
- if (errors$1.length) {
1399
- errorMessage = errors$1[0].message ?? `Parsing error at ${errors$1[0].instancePath}`;
1400
- }
1531
+ }
1532
+ return {
1533
+ success: true,
1534
+ value: result2
1535
+ };
1536
+ } catch (err) {
1537
+ if (context.errors.length) {
1401
1538
  return {
1402
1539
  success: false,
1403
- error: new ValidationError({
1404
- message: errorMessage,
1405
- errors: errors$1
1406
- })
1540
+ errors: context.errors
1407
1541
  };
1408
1542
  }
1543
+ return {
1544
+ success: false,
1545
+ errors: [
1546
+ {
1547
+ message: err instanceof Error ? err.message : `${err}`,
1548
+ instancePath: "/"
1549
+ }
1550
+ ]
1551
+ };
1552
+ }
1553
+ };
1554
+ const result = {
1555
+ schema: JSON.parse(JSON.stringify(schema)),
1556
+ validate,
1557
+ parse,
1558
+ parseUnsafe(input) {
1559
+ const context = newValidationContext();
1560
+ const result2 = parserFn(input, context);
1561
+ if (context.errors.length) {
1562
+ throw new ValidationException({ errors: context.errors });
1563
+ }
1564
+ return result2;
1409
1565
  },
1410
- serialize(input) {
1411
- try {
1412
- return serializeFn(input);
1413
- } catch (err) {
1414
- const errors$1 = errors(schema, input);
1415
- let errorMessage = err instanceof Error ? err.message : "";
1416
- if (errors$1.length) {
1417
- errorMessage = errors$1[0].message ?? `Serialization error at ${errors$1[0].instancePath}`;
1418
- }
1419
- throw new ValidationError({ message: errorMessage, errors: errors$1 });
1566
+ coerce,
1567
+ coerceUnsafe(input) {
1568
+ const context = newValidationContext();
1569
+ const result2 = coercerFn(input, context);
1570
+ if (context.errors.length) {
1571
+ throw new ValidationException({ errors: context.errors });
1420
1572
  }
1573
+ return result2;
1574
+ },
1575
+ serialize,
1576
+ serializeUnsafe(input) {
1577
+ return serializeFn(input);
1421
1578
  },
1422
1579
  compiledCode: {
1423
1580
  validate: validateCode,
1424
1581
  parse: parser.code,
1582
+ coerce: coercer.code,
1425
1583
  serialize: serializer.code
1426
1584
  },
1427
- "~standard": createStandardSchemaProperty(validate, parse)
1585
+ "~standard": createStandardSchemaProperty(validate, (input, ctx) => {
1586
+ const result2 = parse(input);
1587
+ if (!result2.success) {
1588
+ ctx.errors = result2.errors;
1589
+ return undefined;
1590
+ }
1591
+ return result2.value;
1592
+ })
1428
1593
  };
1429
1594
  return result;
1430
1595
  }
1431
- function getCompiledParser(input, schema) {
1432
- const code = createParsingTemplate(input, schema);
1596
+ function getCompiledParser(input, schema, shouldCoerce) {
1597
+ const code = createParsingTemplate(input, schema, shouldCoerce);
1433
1598
  if (isSchemaFormType(schema)) {
1434
1599
  switch (schema.type) {
1435
1600
  case "float32":
1436
1601
  case "float64":
1437
1602
  if (schema.nullable) {
1438
1603
  return {
1439
- fn: nullableFloatParser,
1604
+ fn: nullableFloatDecoder,
1440
1605
  code
1441
1606
  };
1442
1607
  }
1443
1608
  return {
1444
- fn: compiledFloatParser,
1609
+ fn: compiledFloatDecoder,
1445
1610
  code
1446
1611
  };
1447
1612
  case "int64":
1448
1613
  return {
1449
- fn(input2) {
1450
- return bigIntParser(
1614
+ fn(input2, context) {
1615
+ return bigIntDecoder(
1451
1616
  input2,
1452
1617
  false,
1453
- schema.nullable ?? false
1618
+ schema.nullable ?? false,
1619
+ context
1454
1620
  );
1455
1621
  },
1456
1622
  code
1457
1623
  };
1458
1624
  case "uint64":
1459
1625
  return {
1460
- fn(input2) {
1461
- return bigIntParser(
1626
+ fn(input2, context) {
1627
+ return bigIntDecoder(
1462
1628
  input2,
1463
1629
  true,
1464
- schema.nullable ?? false
1630
+ schema.nullable ?? false,
1631
+ context
1465
1632
  );
1466
1633
  },
1467
1634
  code
@@ -1469,106 +1636,191 @@ function getCompiledParser(input, schema) {
1469
1636
  case "int32":
1470
1637
  if (schema.nullable) {
1471
1638
  return {
1472
- fn(input2) {
1473
- return nullableIntParser(input2, int32Min, int32Max);
1639
+ fn(input2, context) {
1640
+ return nullableIntDecoder(
1641
+ input2,
1642
+ int32Min,
1643
+ int32Max,
1644
+ context
1645
+ );
1474
1646
  },
1475
1647
  code
1476
1648
  };
1477
1649
  }
1478
1650
  return {
1479
- fn(input2) {
1480
- return intParser(input2, int32Min, int32Max);
1651
+ fn(input2, context) {
1652
+ return intDecoder(input2, int32Min, int32Max, context);
1481
1653
  },
1482
1654
  code
1483
1655
  };
1484
1656
  case "int16":
1485
1657
  if (schema.nullable) {
1486
1658
  return {
1487
- fn(input2) {
1488
- return nullableIntParser(input2, int16Min, int16Max);
1659
+ fn(input2, context) {
1660
+ return nullableIntDecoder(
1661
+ input2,
1662
+ int16Min,
1663
+ int16Max,
1664
+ context
1665
+ );
1489
1666
  },
1490
1667
  code
1491
1668
  };
1492
1669
  }
1493
1670
  return {
1494
- fn(input2) {
1495
- return intParser(input2, int16Min, int16Max);
1671
+ fn(input2, context) {
1672
+ return intDecoder(input2, int16Min, int16Max, context);
1496
1673
  },
1497
1674
  code
1498
1675
  };
1499
1676
  case "int8":
1500
1677
  if (schema.nullable) {
1501
1678
  return {
1502
- fn(input2) {
1503
- return nullableIntParser(input2, int8Min, int8Max);
1679
+ fn(input2, context) {
1680
+ return nullableIntDecoder(
1681
+ input2,
1682
+ int8Min,
1683
+ int8Max,
1684
+ context
1685
+ );
1504
1686
  },
1505
1687
  code
1506
1688
  };
1507
1689
  }
1508
1690
  return {
1509
- fn(input2) {
1510
- return intParser(input2, int8Min, int8Max);
1691
+ fn(input2, context) {
1692
+ return intDecoder(input2, int8Min, int8Max, context);
1511
1693
  },
1512
1694
  code
1513
1695
  };
1514
1696
  case "uint32":
1515
1697
  if (schema.nullable) {
1516
1698
  return {
1517
- fn(input2) {
1518
- return nullableIntParser(
1699
+ fn(input2, context) {
1700
+ return nullableIntDecoder(
1519
1701
  input2,
1520
1702
  uint32Min,
1521
- uint32Max
1703
+ uint32Max,
1704
+ context
1522
1705
  );
1523
1706
  },
1524
1707
  code
1525
1708
  };
1526
1709
  }
1527
1710
  return {
1528
- fn(input2) {
1529
- return intParser(input2, uint32Min, uint32Max);
1711
+ fn(input2, context) {
1712
+ return intDecoder(input2, uint32Min, uint32Max, context);
1530
1713
  },
1531
1714
  code
1532
1715
  };
1533
1716
  case "uint16":
1534
1717
  if (schema.nullable) {
1535
1718
  return {
1536
- fn(input2) {
1537
- return nullableIntParser(
1719
+ fn(input2, context) {
1720
+ return nullableIntDecoder(
1538
1721
  input2,
1539
1722
  uint16Min,
1540
- uint16Max
1723
+ uint16Max,
1724
+ context
1541
1725
  );
1542
1726
  },
1543
1727
  code
1544
1728
  };
1545
1729
  }
1546
1730
  return {
1547
- fn(input2) {
1548
- return intParser(input2, uint16Min, uint16Max);
1731
+ fn(input2, context) {
1732
+ return intDecoder(input2, uint16Min, uint16Max, context);
1549
1733
  },
1550
1734
  code
1551
1735
  };
1552
1736
  case "uint8":
1553
1737
  if (schema.nullable) {
1554
1738
  return {
1555
- fn(input2) {
1556
- return nullableIntParser(input2, uint8Min, uint8Max);
1739
+ fn(input2, context) {
1740
+ return nullableIntDecoder(
1741
+ input2,
1742
+ uint8Min,
1743
+ uint8Max,
1744
+ context
1745
+ );
1557
1746
  },
1558
1747
  code
1559
1748
  };
1560
1749
  }
1561
1750
  return {
1562
- fn(input2) {
1563
- return intParser(input2, uint8Min, uint8Max);
1751
+ fn(input2, context) {
1752
+ return intDecoder(input2, uint8Min, uint8Max, context);
1564
1753
  },
1565
1754
  code
1566
1755
  };
1567
1756
  case "boolean":
1757
+ if (shouldCoerce) {
1758
+ if (schema.nullable) {
1759
+ return {
1760
+ code,
1761
+ fn(input2, context) {
1762
+ switch (input2) {
1763
+ case true:
1764
+ return true;
1765
+ case false:
1766
+ return false;
1767
+ case "true":
1768
+ case "TRUE":
1769
+ case "1":
1770
+ case 1:
1771
+ return true;
1772
+ case "false":
1773
+ case "FALSE":
1774
+ case "0":
1775
+ case 0:
1776
+ return false;
1777
+ case null:
1778
+ case "null":
1779
+ return null;
1780
+ default:
1781
+ context.errors.push({
1782
+ instancePath: "/",
1783
+ schemaPath: "/type",
1784
+ message: `Unable to coerce ${input2} into boolean`
1785
+ });
1786
+ return undefined;
1787
+ }
1788
+ }
1789
+ };
1790
+ }
1791
+ return {
1792
+ code,
1793
+ fn(input2, context) {
1794
+ switch (input2) {
1795
+ case true:
1796
+ return true;
1797
+ case false:
1798
+ return false;
1799
+ case "true":
1800
+ case "TRUE":
1801
+ case "1":
1802
+ case 1:
1803
+ return true;
1804
+ case "false":
1805
+ case "FALSE":
1806
+ case "0":
1807
+ case 0:
1808
+ return false;
1809
+ default:
1810
+ context.errors.push({
1811
+ instancePath: "/",
1812
+ schemaPath: "/type",
1813
+ message: `Unable to coerce ${input2} into boolean`
1814
+ });
1815
+ return undefined;
1816
+ }
1817
+ }
1818
+ };
1819
+ }
1568
1820
  if (schema.nullable) {
1569
1821
  return {
1570
1822
  code,
1571
- fn(input2) {
1823
+ fn(input2, context) {
1572
1824
  if (typeof input2 === "string") {
1573
1825
  if (input2 === "true") {
1574
1826
  return true;
@@ -1586,20 +1838,17 @@ function getCompiledParser(input, schema) {
1586
1838
  if (input2 === null) {
1587
1839
  return null;
1588
1840
  }
1589
- throw new ValidationError({
1590
- message: `Expected boolean. Got ${typeof input2}`,
1591
- errors: [
1592
- {
1593
- instancePath: "",
1594
- schemaPath: "/type"
1595
- }
1596
- ]
1841
+ context.errors.push({
1842
+ instancePath: "",
1843
+ schemaPath: "/type",
1844
+ message: `Expected boolean. Got ${typeof input2}`
1597
1845
  });
1846
+ return undefined;
1598
1847
  }
1599
1848
  };
1600
1849
  }
1601
1850
  return {
1602
- fn(input2) {
1851
+ fn(input2, context) {
1603
1852
  if (typeof input2 === "string") {
1604
1853
  if (input2 === "true") {
1605
1854
  return true;
@@ -1611,22 +1860,19 @@ function getCompiledParser(input, schema) {
1611
1860
  if (typeof input2 === "boolean") {
1612
1861
  return input2;
1613
1862
  }
1614
- throw new ValidationError({
1615
- message: `Expected boolean. Got ${typeof input2}`,
1616
- errors: [
1617
- {
1618
- instancePath: "",
1619
- schemaPath: "/type"
1620
- }
1621
- ]
1863
+ context.errors.push({
1864
+ instancePath: "",
1865
+ schemaPath: "/type",
1866
+ message: `Expected boolean. Got ${typeof input2}`
1622
1867
  });
1868
+ return undefined;
1623
1869
  },
1624
1870
  code
1625
1871
  };
1626
1872
  case "string":
1627
1873
  if (schema.nullable) {
1628
1874
  return {
1629
- fn(input2) {
1875
+ fn(input2, context) {
1630
1876
  if (typeof input2 === "string") {
1631
1877
  if (input2 === "null") {
1632
1878
  return null;
@@ -1636,44 +1882,100 @@ function getCompiledParser(input, schema) {
1636
1882
  if (input2 === null) {
1637
1883
  return null;
1638
1884
  }
1639
- throw new ValidationError({
1640
- message: `Expected string or null. Got ${typeof input2}.`,
1641
- errors: [
1642
- {
1643
- instancePath: "",
1644
- schemaPath: "/type"
1645
- }
1646
- ]
1885
+ context.errors.push({
1886
+ instancePath: "",
1887
+ schemaPath: "/type",
1888
+ message: `Expected string or null. Got ${typeof input2}.`
1647
1889
  });
1890
+ return undefined;
1648
1891
  },
1649
1892
  code
1650
1893
  };
1651
1894
  }
1652
1895
  return {
1653
- fn(input2) {
1896
+ fn(input2, context) {
1654
1897
  if (typeof input2 === "string") {
1655
1898
  return input2;
1656
1899
  }
1657
- throw new ValidationError({
1900
+ context.errors.push({
1658
1901
  message: `Expected string. Got ${typeof input2}.`,
1659
- errors: [
1660
- {
1661
- instancePath: "",
1662
- schemaPath: "/type"
1663
- }
1664
- ]
1902
+ instancePath: "/",
1903
+ schemaPath: "/type"
1665
1904
  });
1905
+ return undefined;
1666
1906
  },
1667
1907
  code
1668
1908
  };
1669
1909
  case "timestamp":
1910
+ if (shouldCoerce) {
1911
+ if (schema.nullable) {
1912
+ return {
1913
+ fn(input2, context) {
1914
+ if (typeof input2 === "string") {
1915
+ const decodedInput = new Date(input2);
1916
+ if (!Number.isNaN(decodedInput.getMonth())) {
1917
+ return decodedInput;
1918
+ }
1919
+ if (input2 === "null") {
1920
+ return null;
1921
+ }
1922
+ }
1923
+ if (typeof input2 === "number") {
1924
+ const decodedInput = new Date(input2);
1925
+ if (!Number.isNaN(decodedInput.getMonth())) {
1926
+ return decodedInput;
1927
+ }
1928
+ }
1929
+ if (typeof input2 === "object" && input2 instanceof Date) {
1930
+ return input2;
1931
+ }
1932
+ if (input2 === null) {
1933
+ return null;
1934
+ }
1935
+ context.errors.push({
1936
+ instancePath: "",
1937
+ schemaPath: "/type",
1938
+ message: `Expected instanceof Date, ISO Date string, or null. Got ${typeof input2}.`
1939
+ });
1940
+ return undefined;
1941
+ },
1942
+ code
1943
+ };
1944
+ }
1945
+ return {
1946
+ fn(input2, context) {
1947
+ if (typeof input2 === "string") {
1948
+ const decodedInput = new Date(input2);
1949
+ if (!Number.isNaN(decodedInput.getMonth())) {
1950
+ return decodedInput;
1951
+ }
1952
+ }
1953
+ if (typeof input2 === "number") {
1954
+ const decodedInput = new Date(input2);
1955
+ if (!Number.isNaN(decodedInput.getMonth())) {
1956
+ return decodedInput;
1957
+ }
1958
+ }
1959
+ if (typeof input2 === "object" && input2 instanceof Date) {
1960
+ return input2;
1961
+ }
1962
+ context.errors.push({
1963
+ instancePath: "",
1964
+ schemaPath: "/type",
1965
+ message: `Expected instanceof Date or ISO Date string. Got ${typeof input2}.`
1966
+ });
1967
+ return undefined;
1968
+ },
1969
+ code
1970
+ };
1971
+ }
1670
1972
  if (schema.nullable) {
1671
1973
  return {
1672
- fn(input2) {
1974
+ fn(input2, context) {
1673
1975
  if (typeof input2 === "string") {
1674
- const parsedInput = new Date(input2);
1675
- if (!Number.isNaN(parsedInput.getMonth())) {
1676
- return parsedInput;
1976
+ const decodedInput = new Date(input2);
1977
+ if (!Number.isNaN(decodedInput.getMonth())) {
1978
+ return decodedInput;
1677
1979
  }
1678
1980
  if (input2 === "null") {
1679
1981
  return null;
@@ -1685,39 +1987,33 @@ function getCompiledParser(input, schema) {
1685
1987
  if (input2 === null) {
1686
1988
  return null;
1687
1989
  }
1688
- throw new ValidationError({
1689
- message: `Expected instanceof Date, ISO Date string, or null. Got ${typeof input2}.`,
1690
- errors: [
1691
- {
1692
- instancePath: "",
1693
- schemaPath: "/type"
1694
- }
1695
- ]
1990
+ context.errors.push({
1991
+ instancePath: "",
1992
+ schemaPath: "/type",
1993
+ message: `Expected instanceof Date, ISO Date string, or null. Got ${typeof input2}.`
1696
1994
  });
1995
+ return undefined;
1697
1996
  },
1698
1997
  code
1699
1998
  };
1700
1999
  }
1701
2000
  return {
1702
- fn(input2) {
2001
+ fn(input2, context) {
1703
2002
  if (typeof input2 === "string") {
1704
- const parsedInput = new Date(input2);
1705
- if (!Number.isNaN(parsedInput.getMonth())) {
1706
- return parsedInput;
2003
+ const decodedInput = new Date(input2);
2004
+ if (!Number.isNaN(decodedInput.getMonth())) {
2005
+ return decodedInput;
1707
2006
  }
1708
2007
  }
1709
2008
  if (typeof input2 === "object" && input2 instanceof Date) {
1710
2009
  return input2;
1711
2010
  }
1712
- throw new ValidationError({
1713
- message: `Expected instance of Date or ISO date string. Got ${typeof input2}.`,
1714
- errors: [
1715
- {
1716
- instancePath: "",
1717
- schemaPath: "/type"
1718
- }
1719
- ]
2011
+ context.errors.push({
2012
+ instancePath: "",
2013
+ schemaPath: "/type",
2014
+ message: `Expected instance of Date or ISO date string. Got ${typeof input2}.`
1720
2015
  });
2016
+ return undefined;
1721
2017
  },
1722
2018
  code
1723
2019
  };
@@ -1726,7 +2022,7 @@ function getCompiledParser(input, schema) {
1726
2022
  if (isSchemaFormEnum(schema)) {
1727
2023
  if (schema.nullable) {
1728
2024
  return {
1729
- fn(input2) {
2025
+ fn(input2, context) {
1730
2026
  if (typeof input2 === "string") {
1731
2027
  for (const val of schema.enum) {
1732
2028
  if (input2 === val) {
@@ -1740,23 +2036,20 @@ function getCompiledParser(input, schema) {
1740
2036
  if (input2 === null) {
1741
2037
  return null;
1742
2038
  }
1743
- throw new ValidationError({
2039
+ context.errors.push({
2040
+ instancePath: "",
2041
+ schemaPath: "/enum",
1744
2042
  message: `Expected one of the following values: [${schema.enum.join(
1745
2043
  ", "
1746
- )}] or null. Got ${typeof input2}.`,
1747
- errors: [
1748
- {
1749
- instancePath: "",
1750
- schemaPath: "/enum"
1751
- }
1752
- ]
2044
+ )}] or null. Got ${typeof input2}.`
1753
2045
  });
2046
+ return undefined;
1754
2047
  },
1755
2048
  code
1756
2049
  };
1757
2050
  }
1758
2051
  return {
1759
- fn(input2) {
2052
+ fn(input2, context) {
1760
2053
  if (typeof input2 === "string") {
1761
2054
  for (const val of schema.enum) {
1762
2055
  if (input2 === val) {
@@ -1764,70 +2057,58 @@ function getCompiledParser(input, schema) {
1764
2057
  }
1765
2058
  }
1766
2059
  }
1767
- throw new ValidationError({
2060
+ context.errors.push({
2061
+ instancePath: "",
2062
+ schemaPath: "/enum",
1768
2063
  message: `Expected one of the following values: [${schema.enum.join(
1769
2064
  ", "
1770
- )}]. Got ${typeof input2}.`,
1771
- errors: [
1772
- {
1773
- instancePath: "",
1774
- schemaPath: "/enum"
1775
- }
1776
- ]
2065
+ )}]. Got ${typeof input2}.`
1777
2066
  });
2067
+ return undefined;
1778
2068
  },
1779
2069
  code
1780
2070
  };
1781
2071
  }
1782
- return { fn: new Function(input, code), code };
2072
+ return { fn: new Function(input, "context", code), code };
1783
2073
  }
1784
- function compiledFloatParser(input) {
2074
+ function compiledFloatDecoder(input, context) {
1785
2075
  if (typeof input === "string") {
1786
- const parsedVal = Number(input);
1787
- if (!Number.isNaN(parsedVal)) {
1788
- return parsedVal;
2076
+ const decodedVal = Number(input);
2077
+ if (!Number.isNaN(decodedVal)) {
2078
+ return decodedVal;
1789
2079
  }
1790
- throw new ValidationError({
1791
- message: `Unable to parse number from ${input}`,
1792
- errors: [
1793
- {
1794
- instancePath: "",
1795
- schemaPath: "/type"
1796
- }
1797
- ]
2080
+ context.errors.push({
2081
+ instancePath: "",
2082
+ schemaPath: "/type",
2083
+ message: `Unable to decode number from ${input}`
1798
2084
  });
2085
+ return undefined;
1799
2086
  }
1800
2087
  if (typeof input === "number" && !Number.isNaN(input)) {
1801
2088
  return input;
1802
2089
  }
1803
- throw new ValidationError({
1804
- message: `Expected number. Got ${typeof input}`,
1805
- errors: [
1806
- {
1807
- instancePath: "",
1808
- schemaPath: "/type"
1809
- }
1810
- ]
2090
+ context.errors.push({
2091
+ instancePath: "",
2092
+ schemaPath: "/type",
2093
+ message: `Expected number. Got ${typeof input}`
1811
2094
  });
2095
+ return undefined;
1812
2096
  }
1813
- function nullableFloatParser(input) {
2097
+ function nullableFloatDecoder(input, context) {
1814
2098
  if (typeof input === "string") {
1815
- const parsedVal = Number(input);
1816
- if (!Number.isNaN(parsedVal)) {
1817
- return parsedVal;
2099
+ const decodedVal = Number(input);
2100
+ if (!Number.isNaN(decodedVal)) {
2101
+ return decodedVal;
1818
2102
  }
1819
2103
  if (input === "null") {
1820
2104
  return null;
1821
2105
  }
1822
- throw new ValidationError({
1823
- message: `Unable to parse number from ${input}`,
1824
- errors: [
1825
- {
1826
- instancePath: "",
1827
- schemaPath: "/type"
1828
- }
1829
- ]
2106
+ context.errors.push({
2107
+ instancePath: "",
2108
+ schemaPath: "/type",
2109
+ message: `Unable to decode number from ${input}`
1830
2110
  });
2111
+ return undefined;
1831
2112
  }
1832
2113
  if (typeof input === "number" && !Number.isNaN(input)) {
1833
2114
  return input;
@@ -1835,17 +2116,14 @@ function nullableFloatParser(input) {
1835
2116
  if (input === null) {
1836
2117
  return null;
1837
2118
  }
1838
- throw new ValidationError({
1839
- message: `Expected number or null. Got ${typeof input}`,
1840
- errors: [
1841
- {
1842
- instancePath: "",
1843
- schemaPath: "/type"
1844
- }
1845
- ]
2119
+ context.errors.push({
2120
+ instancePath: "",
2121
+ schemaPath: "/type",
2122
+ message: `Expected number or null. Got ${typeof input}`
1846
2123
  });
2124
+ return undefined;
1847
2125
  }
1848
- function bigIntParser(input, isUnsigned, isNullable) {
2126
+ function bigIntDecoder(input, isUnsigned, isNullable, context) {
1849
2127
  if (typeof input === "string" || typeof input === "number") {
1850
2128
  if (isNullable && input === "null") {
1851
2129
  return null;
@@ -1853,70 +2131,71 @@ function bigIntParser(input, isUnsigned, isNullable) {
1853
2131
  try {
1854
2132
  const val = BigInt(input);
1855
2133
  if (isUnsigned) {
1856
- if (val >= BigInt("0")) {
2134
+ if (val >= uint64Min && val <= uint64Max) {
1857
2135
  return val;
1858
2136
  }
1859
- throw new ValidationError({
1860
- message: "uint64 must be greater than or equal to 0",
1861
- errors: [
1862
- {
1863
- message: "uint64 must be greater than or equal to 0",
1864
- schemaPath: "/type",
1865
- instancePath: ""
1866
- }
1867
- ]
2137
+ context.errors.push({
2138
+ message: "uint64 must an integer between 0 and 18,446,744,073,709,551,615",
2139
+ schemaPath: "/type",
2140
+ instancePath: ""
1868
2141
  });
2142
+ return void 0;
2143
+ }
2144
+ if (val >= int64Min && val <= int64Max) {
2145
+ return val;
1869
2146
  }
1870
- return val;
2147
+ context.errors.push({
2148
+ schemaPath: "/type",
2149
+ instancePath: "/",
2150
+ message: `int64 must be an integer between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807`
2151
+ });
2152
+ return void 0;
1871
2153
  } catch (err) {
1872
- throw new ValidationError({
1873
- message: `Error transforming ${input} to BigInt`,
1874
- errors: [
1875
- {
1876
- schemaPath: "/type",
1877
- instancePath: "",
1878
- data: err
1879
- }
1880
- ]
2154
+ context.errors.push({
2155
+ schemaPath: "/type",
2156
+ instancePath: "",
2157
+ data: err,
2158
+ message: `Error transforming ${input} to BigInt`
1881
2159
  });
2160
+ return undefined;
1882
2161
  }
1883
2162
  }
1884
2163
  if (typeof input === "bigint") {
1885
2164
  if (isUnsigned) {
1886
- if (input >= BigInt("0")) {
2165
+ if (input >= uint64Min && input <= uint64Max) {
1887
2166
  return input;
1888
2167
  }
1889
- throw new ValidationError({
2168
+ context.errors.push({
1890
2169
  message: "uint64 must be greater than or equal to 0",
1891
- errors: [
1892
- {
1893
- message: "uint64 must be greater than or equal to 0",
1894
- schemaPath: "/type",
1895
- instancePath: ""
1896
- }
1897
- ]
2170
+ schemaPath: "/type",
2171
+ instancePath: "/"
1898
2172
  });
1899
2173
  }
1900
- return input;
2174
+ if (input >= int64Min && input <= int64Max) {
2175
+ return input;
2176
+ }
2177
+ context.errors.push({
2178
+ schemaPath: "/type",
2179
+ instancePath: "/",
2180
+ message: `int64 must be an integer between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807`
2181
+ });
2182
+ return undefined;
1901
2183
  }
1902
2184
  if (isNullable && input === null) {
1903
2185
  return null;
1904
2186
  }
1905
- throw new ValidationError({
1906
- message: "Expected BigInt or Integer string",
1907
- errors: [
1908
- {
1909
- schemaPath: "/type",
1910
- instancePath: ""
1911
- }
1912
- ]
2187
+ context.errors.push({
2188
+ schemaPath: "/type",
2189
+ instancePath: "/",
2190
+ message: "Expected BigInt or Integer string"
1913
2191
  });
2192
+ return undefined;
1914
2193
  }
1915
- function nullableIntParser(input, minNum, maxNum) {
2194
+ function nullableIntDecoder(input, minNum, maxNum, context) {
1916
2195
  if (typeof input === "string") {
1917
- const parsedInput = Number(input);
1918
- if (Number.isInteger(parsedInput) && parsedInput >= minNum && parsedInput <= maxNum) {
1919
- return parsedInput;
2196
+ const decodedInput = Number(input);
2197
+ if (Number.isInteger(decodedInput) && decodedInput >= minNum && decodedInput <= maxNum) {
2198
+ return decodedInput;
1920
2199
  }
1921
2200
  if (input === "null") {
1922
2201
  return null;
@@ -1928,35 +2207,29 @@ function nullableIntParser(input, minNum, maxNum) {
1928
2207
  if (input === null) {
1929
2208
  return null;
1930
2209
  }
1931
- throw new ValidationError({
1932
- message: `Expected valid integer between ${minNum} & ${maxNum} or null. Got ${typeof input}.`,
1933
- errors: [
1934
- {
1935
- instancePath: "",
1936
- schemaPath: "/type"
1937
- }
1938
- ]
2210
+ context.errors.push({
2211
+ instancePath: "",
2212
+ schemaPath: "/type",
2213
+ message: `Expected valid integer between ${minNum} & ${maxNum} or null. Got ${typeof input}.`
1939
2214
  });
2215
+ return undefined;
1940
2216
  }
1941
- function intParser(input, minNum, maxNum) {
2217
+ function intDecoder(input, minNum, maxNum, context) {
1942
2218
  if (typeof input === "string") {
1943
- const parsedInput = Number(input);
1944
- if (Number.isInteger(parsedInput) && parsedInput >= minNum && parsedInput <= maxNum) {
1945
- return parsedInput;
2219
+ const decodedInput = Number(input);
2220
+ if (Number.isInteger(decodedInput) && decodedInput >= minNum && decodedInput <= maxNum) {
2221
+ return decodedInput;
1946
2222
  }
1947
2223
  }
1948
2224
  if (typeof input === "number" && Number.isInteger(input) && input >= minNum && input <= maxNum) {
1949
2225
  return input;
1950
2226
  }
1951
- throw new ValidationError({
1952
- message: `Expected valid integer between ${minNum} & ${maxNum}`,
1953
- errors: [
1954
- {
1955
- instancePath: "",
1956
- schemaPath: "/type"
1957
- }
1958
- ]
2227
+ context.errors.push({
2228
+ instancePath: "",
2229
+ schemaPath: "/type",
2230
+ message: `Expected valid integer between ${minNum} & ${maxNum}`
1959
2231
  });
2232
+ return undefined;
1960
2233
  }
1961
2234
  function getCompiledSerializer(schema) {
1962
2235
  const code = createSerializationV2Template("input", schema);
@@ -2088,111 +2361,1914 @@ function getCompiledSerializer(schema) {
2088
2361
  };
2089
2362
  }
2090
2363
 
2091
- const _namespace = {
2092
- __proto__: null,
2093
- any: any,
2094
- array: array,
2095
- boolean: boolean,
2096
- clone: clone,
2097
- coerce: coerce,
2098
- compile: compile,
2099
- discriminator: discriminator,
2100
- enumerator: enumerator,
2101
- errors: errors,
2102
- extend: extend,
2103
- float32: float32,
2104
- float64: float64,
2105
- int16: int16,
2106
- int32: int32,
2107
- int64: int64,
2108
- int8: int8,
2109
- nullable: nullable,
2110
- number: number,
2111
- object: object,
2112
- omit: omit,
2113
- optional: optional,
2114
- parse: parse,
2115
- partial: partial,
2116
- pick: pick,
2117
- record: record,
2118
- recursive: recursive,
2119
- safeCoerce: safeCoerce,
2120
- safeParse: safeParse,
2121
- serialize: serialize,
2122
- string: string,
2123
- stringEnum: stringEnum,
2124
- timestamp: timestamp,
2125
- uint16: uint16,
2126
- uint32: uint32,
2127
- uint64: uint64,
2128
- uint8: uint8,
2129
- validate: validate
2130
- };
2364
+ function any(options = {}) {
2365
+ const validate = (input) => true;
2366
+ const parse = (input, context) => {
2367
+ if (context.instancePath.length === 0 && typeof input === "string") {
2368
+ try {
2369
+ return JSON.parse(input);
2370
+ } catch {
2371
+ return input;
2372
+ }
2373
+ }
2374
+ return input;
2375
+ };
2376
+ const validator = {
2377
+ output: undefined,
2378
+ parse,
2379
+ coerce: (input, context) => {
2380
+ if (context.instancePath.length === 0 && typeof input === "string") {
2381
+ try {
2382
+ return JSON.parse(input);
2383
+ } catch {
2384
+ return input;
2385
+ }
2386
+ }
2387
+ return input;
2388
+ },
2389
+ validate,
2390
+ serialize(input) {
2391
+ return JSON.stringify(input);
2392
+ }
2393
+ };
2394
+ const result = {
2395
+ metadata: {
2396
+ id: options.id,
2397
+ description: options.description,
2398
+ isDeprecated: options.isDeprecated
2399
+ },
2400
+ [VALIDATOR_KEY]: validator,
2401
+ "~standard": createStandardSchemaProperty(validate, parse)
2402
+ };
2403
+ hideInvalidProperties(result);
2404
+ return result;
2405
+ }
2131
2406
 
2132
- function isAdaptedSchema(input) {
2133
- return input.metadata[SCHEMA_METADATA]._isAdapted === true;
2407
+ function array(schema, opts = {}) {
2408
+ const validateType = (input) => {
2409
+ return validate$5(schema, input);
2410
+ };
2411
+ const parseType = (input, context) => {
2412
+ return parse$5(schema, input, context, false);
2413
+ };
2414
+ const validator = {
2415
+ output: [],
2416
+ parse: parseType,
2417
+ coerce(input, context) {
2418
+ return parse$5(schema, input, context, true);
2419
+ },
2420
+ validate: validateType,
2421
+ serialize(input, context) {
2422
+ const strParts = [];
2423
+ for (let i = 0; i < input.length; i++) {
2424
+ const item = input[i];
2425
+ const part = schema[VALIDATOR_KEY].serialize(item, {
2426
+ instancePath: `${context.instancePath}/${i}`,
2427
+ schemaPath: `${context.schemaPath}/elements`,
2428
+ errors: context.errors,
2429
+ depth: context.depth + 1,
2430
+ maxDepth: context.maxDepth,
2431
+ exitOnFirstError: context.exitOnFirstError
2432
+ });
2433
+ if (!part) {
2434
+ return undefined;
2435
+ }
2436
+ strParts.push(part);
2437
+ }
2438
+ return `[${strParts.join(",")}]`;
2439
+ }
2440
+ };
2441
+ const result = {
2442
+ elements: schema,
2443
+ metadata: {
2444
+ id: opts.id,
2445
+ description: opts.description,
2446
+ isDeprecated: opts.isDeprecated
2447
+ },
2448
+ [VALIDATOR_KEY]: validator,
2449
+ "~standard": createStandardSchemaProperty(validateType, parseType)
2450
+ };
2451
+ hideInvalidProperties(result);
2452
+ return result;
2453
+ }
2454
+ function validate$5(innerSchema, input) {
2455
+ if (!Array.isArray(input)) {
2456
+ return false;
2457
+ }
2458
+ for (const item of input) {
2459
+ const isValid = innerSchema[VALIDATOR_KEY].validate(item);
2460
+ if (!isValid) {
2461
+ return false;
2462
+ }
2463
+ }
2464
+ return true;
2465
+ }
2466
+ function parse$5(innerSchema, input, context, coerce = false) {
2467
+ let parsedInput = input;
2468
+ if (context.instancePath.length === 0 && typeof input === "string") {
2469
+ try {
2470
+ parsedInput = JSON.parse(input);
2471
+ } catch (_) {
2472
+ context.errors.push({
2473
+ instancePath: context.instancePath,
2474
+ schemaPath: `${context.schemaPath}/elements`,
2475
+ message: `Error at ${context.instancePath}. Invalid JSON.`
2476
+ });
2477
+ return undefined;
2478
+ }
2479
+ }
2480
+ if (!Array.isArray(parsedInput)) {
2481
+ context.errors.push({
2482
+ instancePath: context.instancePath,
2483
+ schemaPath: `${context.schemaPath}/elements`,
2484
+ message: `Error at ${context.instancePath}. Expected array. Got ${typeof input}.`
2485
+ });
2486
+ return undefined;
2487
+ }
2488
+ const result = [];
2489
+ for (let i = 0; i < parsedInput.length; i++) {
2490
+ const item = parsedInput[i];
2491
+ if (coerce) {
2492
+ const parsedItem = innerSchema[VALIDATOR_KEY].coerce(item, {
2493
+ instancePath: `${context.instancePath}/${i}`,
2494
+ schemaPath: `${context.schemaPath}/elements`,
2495
+ errors: context.errors,
2496
+ depth: context.depth + 1,
2497
+ maxDepth: context.maxDepth,
2498
+ exitOnFirstError: context.exitOnFirstError
2499
+ });
2500
+ result.push(parsedItem);
2501
+ } else {
2502
+ const parsedItem = innerSchema[VALIDATOR_KEY].parse(item, {
2503
+ instancePath: `${context.instancePath}/${i}`,
2504
+ schemaPath: `${context.schemaPath}/elements`,
2505
+ errors: context.errors,
2506
+ depth: context.depth + 1,
2507
+ maxDepth: context.maxDepth,
2508
+ exitOnFirstError: context.exitOnFirstError
2509
+ });
2510
+ result.push(parsedItem);
2511
+ }
2512
+ }
2513
+ if (context.errors.length) {
2514
+ return undefined;
2515
+ }
2516
+ return result;
2134
2517
  }
2135
- function validatorFromAdaptedSchema(schema) {
2518
+
2519
+ function boolean(opts = {}) {
2520
+ const validator = {
2521
+ output: false,
2522
+ parse: parse$4,
2523
+ validate: validate$4,
2524
+ serialize: serialize$2,
2525
+ coerce(input, context) {
2526
+ if (validate$4(input)) {
2527
+ return input;
2528
+ }
2529
+ switch (input) {
2530
+ case "true":
2531
+ case "TRUE":
2532
+ case "1":
2533
+ case 1:
2534
+ return true;
2535
+ case "false":
2536
+ case "FALSE":
2537
+ case "0":
2538
+ case 0:
2539
+ return false;
2540
+ }
2541
+ context.errors.push({
2542
+ instancePath: context.instancePath,
2543
+ schemaPath: context.schemaPath,
2544
+ message: `Error at ${context.instancePath}. Unable to coerce ${input} to boolean.`
2545
+ });
2546
+ return undefined;
2547
+ }
2548
+ };
2136
2549
  const result = {
2137
- compiledCode: {
2138
- parse: "",
2139
- serialize: "",
2140
- validate: ""
2550
+ type: "boolean",
2551
+ metadata: {
2552
+ id: opts.id,
2553
+ description: opts.description,
2554
+ isDeprecated: opts.isDeprecated
2141
2555
  },
2142
- validate: schema.metadata[SCHEMA_METADATA].validate,
2143
- parse(input) {
2144
- const context = {
2145
- instancePath: "",
2146
- schemaPath: "",
2147
- errors: []
2148
- };
2149
- return schema.metadata[SCHEMA_METADATA].parse(input, context);
2556
+ [VALIDATOR_KEY]: validator,
2557
+ "~standard": createStandardSchemaProperty(validate$4, parse$4)
2558
+ };
2559
+ hideInvalidProperties(result);
2560
+ return result;
2561
+ }
2562
+ function validate$4(input) {
2563
+ return typeof input === "boolean";
2564
+ }
2565
+ function parse$4(input, data) {
2566
+ if (validate$4(input)) {
2567
+ return input;
2568
+ }
2569
+ if (data.instancePath.length === 0 && typeof input === "string") {
2570
+ if (input === "true") {
2571
+ return true;
2572
+ }
2573
+ if (input === "false") {
2574
+ return false;
2575
+ }
2576
+ data.errors.push({
2577
+ instancePath: data.instancePath,
2578
+ schemaPath: `${data.schemaPath}/type`,
2579
+ message: `Error at ${data.instancePath}. Expected boolean. Got ${typeof input}.`
2580
+ });
2581
+ return undefined;
2582
+ }
2583
+ data.errors.push({
2584
+ instancePath: data.instancePath,
2585
+ schemaPath: `${data.schemaPath}/type`,
2586
+ message: `Error at ${data.instancePath}. Expected boolean. Got ${typeof input}.`
2587
+ });
2588
+ return undefined;
2589
+ }
2590
+ function serialize$2(input) {
2591
+ return `${input}`;
2592
+ }
2593
+
2594
+ function discriminator(propA, propB, propC) {
2595
+ const isIdShorthand = typeof propB === "string";
2596
+ const discriminator2 = isIdShorthand ? propB : propA;
2597
+ const mapping = isIdShorthand ? propC : propB;
2598
+ const opts = isIdShorthand ? { id: propA } : propC ?? {};
2599
+ if (isIdShorthand) {
2600
+ opts.id = propA;
2601
+ }
2602
+ const isType = (input) => {
2603
+ return validate$3(discriminator2, mapping, input);
2604
+ };
2605
+ const parseType = (input, context) => {
2606
+ return parse$3(discriminator2, mapping, input, context, false);
2607
+ };
2608
+ const validator = {
2609
+ output: {},
2610
+ validate: isType,
2611
+ parse: parseType,
2612
+ coerce: (input, context) => {
2613
+ return parse$3(discriminator2, mapping, input, context, true);
2150
2614
  },
2151
- safeParse(input) {
2152
- const context = {
2153
- instancePath: "",
2154
- schemaPath: "",
2155
- errors: []
2156
- };
2157
- try {
2158
- const result2 = schema.metadata[SCHEMA_METADATA].parse(
2159
- input,
2160
- context
2615
+ serialize(input, context) {
2616
+ const discriminatorVal = input[discriminator2] ?? "";
2617
+ const targetSchema = mapping[discriminatorVal];
2618
+ if (!targetSchema) {
2619
+ context.errors.push(
2620
+ discriminatorMappingError(discriminatorVal, context)
2161
2621
  );
2162
- return {
2163
- success: true,
2164
- value: result2
2165
- };
2166
- } catch (err) {
2167
- if (err instanceof ValidationError) {
2168
- return {
2169
- success: false,
2170
- error: err
2171
- };
2172
- }
2173
- return {
2174
- success: false,
2175
- error: new ValidationError({
2176
- message: context.errors[0]?.message ?? `Error parsing input. ${err}`,
2177
- errors: context.errors
2178
- })
2179
- };
2622
+ return undefined;
2180
2623
  }
2624
+ const result2 = targetSchema[VALIDATOR_KEY].serialize(input, {
2625
+ instancePath: context.instancePath,
2626
+ schemaPath: `${context.schemaPath}/mapping/${discriminatorVal}`,
2627
+ errors: context.errors,
2628
+ discriminatorKey: discriminator2,
2629
+ discriminatorValue: discriminatorVal,
2630
+ depth: context.depth,
2631
+ maxDepth: context.maxDepth,
2632
+ exitOnFirstError: context.exitOnFirstError
2633
+ });
2634
+ return result2;
2635
+ }
2636
+ };
2637
+ const result = {
2638
+ discriminator: discriminator2,
2639
+ mapping,
2640
+ metadata: {
2641
+ id: opts.id,
2642
+ description: opts.description,
2643
+ isDeprecated: opts.isDeprecated
2181
2644
  },
2182
- serialize(input) {
2183
- const context = {
2184
- instancePath: "",
2185
- schemaPath: "",
2186
- errors: []
2187
- };
2188
- return schema.metadata[SCHEMA_METADATA].serialize(input, context);
2645
+ [VALIDATOR_KEY]: validator,
2646
+ "~standard": createStandardSchemaProperty(isType, parseType)
2647
+ };
2648
+ hideInvalidProperties(result);
2649
+ return result;
2650
+ }
2651
+ function validate$3(discriminator2, mapping, input) {
2652
+ if (!isObject(input)) {
2653
+ return false;
2654
+ }
2655
+ if (!(discriminator2 in input)) {
2656
+ return false;
2657
+ }
2658
+ const discriminatorOptions = Object.keys(mapping);
2659
+ if (!discriminatorOptions.includes(input[discriminator2])) {
2660
+ return false;
2661
+ }
2662
+ const targetSchema = mapping[input[discriminator2]];
2663
+ if (!targetSchema) {
2664
+ return false;
2665
+ }
2666
+ return targetSchema[VALIDATOR_KEY].validate(input);
2667
+ }
2668
+ function parse$3(discriminator2, mapping, input, context, coerce = false) {
2669
+ let parsedInput = input;
2670
+ if (typeof input === "string" && input.length && context.instancePath.length === 0) {
2671
+ try {
2672
+ parsedInput = JSON.parse(input);
2673
+ } catch (err) {
2674
+ context.errors.push({
2675
+ message: err instanceof Error ? err.message : `${err}`,
2676
+ data: err,
2677
+ instancePath: context.instancePath,
2678
+ schemaPath: context.schemaPath
2679
+ });
2680
+ return undefined;
2681
+ }
2682
+ }
2683
+ if (!isObject(parsedInput)) {
2684
+ context.errors.push({
2685
+ instancePath: context.instancePath,
2686
+ schemaPath: `${context.schemaPath}/discriminator`,
2687
+ message: `Error at ${context.instancePath}. Expected object. Got ${typeof parsedInput}.`
2688
+ });
2689
+ return undefined;
2690
+ }
2691
+ if (!(discriminator2 in parsedInput)) {
2692
+ context.errors.push({
2693
+ instancePath: `${context.instancePath}/${discriminator2}`,
2694
+ schemaPath: `${context.schemaPath}/discriminator`,
2695
+ message: `Error at ${context.instancePath}/${discriminator2}. Discriminator field "${discriminator2}" cannot be undefined`
2696
+ });
2697
+ return undefined;
2698
+ }
2699
+ const acceptedDiscriminatorVals = Object.keys(mapping);
2700
+ const discriminatorVal = parsedInput[discriminator2];
2701
+ if (!acceptedDiscriminatorVals.includes(discriminatorVal)) {
2702
+ context.errors.push({
2703
+ instancePath: `${context.instancePath}/${discriminator2}`,
2704
+ schemaPath: `${context.schemaPath}/discriminator`,
2705
+ message: `Error at ${context.instancePath}/${discriminator2}. "${parsedInput[discriminator2]}" is not one of the accepted discriminator values: [${acceptedDiscriminatorVals.join(
2706
+ ", "
2707
+ )}]`
2708
+ });
2709
+ return undefined;
2710
+ }
2711
+ const targetSchema = mapping[parsedInput[discriminator2]];
2712
+ if (!targetSchema) {
2713
+ return undefined;
2714
+ }
2715
+ if (coerce) {
2716
+ const result2 = targetSchema[VALIDATOR_KEY].coerce(parsedInput, {
2717
+ instancePath: context.instancePath,
2718
+ schemaPath: `${context.schemaPath}/mapping/${discriminatorVal}`,
2719
+ errors: context.errors,
2720
+ discriminatorKey: discriminator2,
2721
+ discriminatorValue: discriminatorVal,
2722
+ depth: context.depth + 1,
2723
+ maxDepth: context.maxDepth,
2724
+ exitOnFirstError: context.exitOnFirstError
2725
+ });
2726
+ return result2;
2727
+ }
2728
+ const result = targetSchema[VALIDATOR_KEY].parse(parsedInput, {
2729
+ instancePath: context.instancePath,
2730
+ schemaPath: `${context.schemaPath}/mapping/${discriminatorVal}`,
2731
+ errors: context.errors,
2732
+ discriminatorKey: discriminator2,
2733
+ discriminatorValue: discriminatorVal,
2734
+ depth: context.depth + 1,
2735
+ maxDepth: context.maxDepth,
2736
+ exitOnFirstError: context.exitOnFirstError
2737
+ });
2738
+ return result;
2739
+ }
2740
+ function discriminatorMappingError(discriminatorVal, data) {
2741
+ return {
2742
+ message: `Error fetching discriminator schema. Mapping for "${discriminatorVal} is undefined.`,
2743
+ instancePath: data.instancePath,
2744
+ schemaPath: data.schemaPath
2745
+ };
2746
+ }
2747
+
2748
+ const stringEnum = enumerator;
2749
+ function enumerator(paramA, paramB) {
2750
+ const isIdShorthand = typeof paramA === "string";
2751
+ const enumVal = isIdShorthand ? paramB : paramA;
2752
+ const meta = isIdShorthand ? { id: paramA } : paramB;
2753
+ const isType = (input) => {
2754
+ if (typeof input !== "string") {
2755
+ return false;
2756
+ }
2757
+ for (const val of enumVal) {
2758
+ if (val === input) {
2759
+ return true;
2760
+ }
2761
+ }
2762
+ return false;
2763
+ };
2764
+ const parse = (input, context) => {
2765
+ if (isType(input)) {
2766
+ return input;
2767
+ }
2768
+ context.errors.push({
2769
+ instancePath: context.instancePath,
2770
+ schemaPath: `${context.schemaPath}/enum`,
2771
+ message: `Error at ${context.instancePath}. Invalid enum value. Expected one of the following values: [${enumVal.join(
2772
+ ", "
2773
+ )}]`
2774
+ });
2775
+ return undefined;
2776
+ };
2777
+ const validator = {
2778
+ output: paramA[0] ?? "",
2779
+ parse,
2780
+ coerce: (input, context) => {
2781
+ if (isType(input)) {
2782
+ return input;
2783
+ }
2784
+ context.errors.push({
2785
+ instancePath: context.instancePath,
2786
+ schemaPath: `${context.schemaPath}/enum`,
2787
+ message: `Error at ${context.instancePath}. Invalid enum value. Expected one of the following values: [${enumVal.join(
2788
+ ", "
2789
+ )}]`
2790
+ });
2791
+ return undefined;
2792
+ },
2793
+ validate: isType,
2794
+ serialize(input, context) {
2795
+ if (context.instancePath.length === 0) {
2796
+ return input;
2797
+ }
2798
+ return `"${input}"`;
2799
+ }
2800
+ };
2801
+ const result = {
2802
+ enum: enumVal,
2803
+ metadata: {
2804
+ id: meta?.id,
2805
+ description: meta?.description,
2806
+ isDeprecated: meta?.isDeprecated
2807
+ },
2808
+ [VALIDATOR_KEY]: validator,
2809
+ "~standard": createStandardSchemaProperty(isType, parse)
2810
+ };
2811
+ hideInvalidProperties(result);
2812
+ return result;
2813
+ }
2814
+
2815
+ function nullable(schema, opts = {}) {
2816
+ const isType = (val) => {
2817
+ if (val === null) {
2818
+ return true;
2819
+ }
2820
+ return schema[VALIDATOR_KEY].validate(val);
2821
+ };
2822
+ const parse = (val, data) => {
2823
+ if (data.instancePath.length === 0 && typeof val === "string" && val === "null") {
2824
+ return null;
2825
+ }
2826
+ if (val === null) {
2827
+ return null;
2828
+ }
2829
+ return schema[VALIDATOR_KEY].parse(val, data);
2830
+ };
2831
+ const validator = {
2832
+ output: null,
2833
+ optional: schema[VALIDATOR_KEY].optional,
2834
+ validate: isType,
2835
+ parse,
2836
+ coerce(val, data) {
2837
+ if (val === null) {
2838
+ return null;
2839
+ }
2840
+ if (val === "null") {
2841
+ return null;
2842
+ }
2843
+ return schema[VALIDATOR_KEY].coerce(val, data);
2844
+ },
2845
+ serialize(val, data) {
2846
+ if (val === null) {
2847
+ return "null";
2848
+ }
2849
+ return schema[VALIDATOR_KEY].serialize(val, data);
2850
+ }
2851
+ };
2852
+ const result = {
2853
+ ...schema,
2854
+ nullable: true,
2855
+ metadata: {
2856
+ id: opts.id ?? schema.metadata?.id,
2857
+ description: opts.description ?? schema.metadata?.description,
2858
+ isDeprecated: opts.isDeprecated ?? schema.metadata?.isDeprecated
2189
2859
  },
2860
+ [VALIDATOR_KEY]: validator,
2190
2861
  "~standard": createStandardSchemaProperty(
2191
- schema.metadata[SCHEMA_METADATA].validate,
2192
- schema.metadata[SCHEMA_METADATA].parse
2862
+ validator.validate,
2863
+ validator.parse
2193
2864
  )
2194
2865
  };
2866
+ hideInvalidProperties(result);
2867
+ return result;
2868
+ }
2869
+ function optional(input, opts = {}) {
2870
+ const isType = (val) => {
2871
+ if (val === undefined) {
2872
+ return true;
2873
+ }
2874
+ return input[VALIDATOR_KEY].validate(val);
2875
+ };
2876
+ const parse = (val, context) => {
2877
+ if (typeof val === "undefined") {
2878
+ return undefined;
2879
+ }
2880
+ if (context.instancePath.length === 0 && val === "undefined") {
2881
+ return undefined;
2882
+ }
2883
+ return input[VALIDATOR_KEY].parse(val, context);
2884
+ };
2885
+ const validator = {
2886
+ output: undefined,
2887
+ optional: true,
2888
+ validate: isType,
2889
+ parse,
2890
+ coerce: (val, data) => {
2891
+ if (typeof val === "undefined") {
2892
+ return undefined;
2893
+ }
2894
+ if (val === "undefined") {
2895
+ return undefined;
2896
+ }
2897
+ return input[VALIDATOR_KEY].coerce(val, data);
2898
+ },
2899
+ serialize: (val, data) => {
2900
+ if (typeof val === "undefined") {
2901
+ return "undefined";
2902
+ }
2903
+ return input[VALIDATOR_KEY].serialize(val, data);
2904
+ }
2905
+ };
2906
+ const result = {
2907
+ ...input,
2908
+ metadata: {
2909
+ id: opts.id ?? input.metadata?.id,
2910
+ description: opts.description ?? input.metadata?.description,
2911
+ isDeprecated: opts.isDeprecated ?? input.metadata?.isDeprecated
2912
+ },
2913
+ [VALIDATOR_KEY]: validator,
2914
+ "~standard": createStandardSchemaProperty(isType, parse)
2915
+ };
2916
+ hideInvalidProperties(result);
2195
2917
  return result;
2196
2918
  }
2919
+ function clone(input, opts = {}) {
2920
+ const validator = {
2921
+ ...input[VALIDATOR_KEY]
2922
+ };
2923
+ const schema = {
2924
+ ...input,
2925
+ metadata: {
2926
+ id: opts.id,
2927
+ description: opts.description,
2928
+ isDeprecated: opts.isDeprecated
2929
+ },
2930
+ [VALIDATOR_KEY]: validator,
2931
+ "~standard": createStandardSchemaProperty(
2932
+ validator.validate,
2933
+ validator.parse
2934
+ )
2935
+ };
2936
+ hideInvalidProperties(schema);
2937
+ return schema;
2938
+ }
2939
+
2940
+ function number(opts = {}) {
2941
+ return float64(opts);
2942
+ }
2943
+ function coerceNumber(input, options) {
2944
+ if (typeof input === "string") {
2945
+ const decodedInput = Number(input);
2946
+ if (Number.isNaN(decodedInput)) {
2947
+ options.errors.push({
2948
+ instancePath: `${options.instancePath}`,
2949
+ schemaPath: `${options.schemaPath}/type`,
2950
+ message: `Error at ${options.instancePath}. Unable to coerce ${typeof input} into a number`
2951
+ });
2952
+ return undefined;
2953
+ }
2954
+ return decodeNumber(decodedInput, options);
2955
+ }
2956
+ return decodeNumber(input, options);
2957
+ }
2958
+ function float32(opts = {}) {
2959
+ return numberScalarType("float32", opts, () => {
2960
+ return {
2961
+ success: true
2962
+ };
2963
+ });
2964
+ }
2965
+ function float64(opts = {}) {
2966
+ return numberScalarType("float64", opts, () => {
2967
+ return {
2968
+ success: true
2969
+ };
2970
+ });
2971
+ }
2972
+ function int8(opts = {}) {
2973
+ return numberScalarType("int8", opts, (input) => {
2974
+ const isValid = validateInt(input, int8Min, int8Max);
2975
+ if (isValid) {
2976
+ return {
2977
+ success: true
2978
+ };
2979
+ }
2980
+ return {
2981
+ success: false,
2982
+ message: `Must be an valid integer between ${int8Min} and ${int8Max}`
2983
+ };
2984
+ });
2985
+ }
2986
+ function uint8(opts = {}) {
2987
+ return numberScalarType("uint8", opts, (input) => {
2988
+ const isValid = validateInt(input, uint8Min, uint8Max);
2989
+ if (isValid) {
2990
+ return {
2991
+ success: true
2992
+ };
2993
+ }
2994
+ return {
2995
+ success: false,
2996
+ message: `Must be a valid integer between ${uint8Min} and ${uint8Max}`
2997
+ };
2998
+ });
2999
+ }
3000
+ function int16(opts = {}) {
3001
+ return numberScalarType("int16", opts, (input) => {
3002
+ const isValid = validateInt(input, int16Min, int16Max);
3003
+ if (isValid) {
3004
+ return {
3005
+ success: true
3006
+ };
3007
+ }
3008
+ return {
3009
+ success: false,
3010
+ message: `Must be a valid integer between ${int16Min} and ${int16Max}`
3011
+ };
3012
+ });
3013
+ }
3014
+ function uint16(opts = {}) {
3015
+ return numberScalarType("uint16", opts, (input) => {
3016
+ const isValid = validateInt(input, uint16Min, uint16Max);
3017
+ if (isValid) {
3018
+ return {
3019
+ success: true
3020
+ };
3021
+ }
3022
+ return {
3023
+ success: false,
3024
+ message: `Must be a valid integer between ${uint16Min} and ${uint16Max}`
3025
+ };
3026
+ });
3027
+ }
3028
+ function int32(opts = {}) {
3029
+ return numberScalarType("int32", opts, (input) => {
3030
+ const isValid = validateInt(input, int32Min, int32Max);
3031
+ if (isValid) {
3032
+ return {
3033
+ success: true
3034
+ };
3035
+ }
3036
+ return {
3037
+ success: false,
3038
+ message: `Must be a valid integer between ${int32Min} and ${int32Max}`
3039
+ };
3040
+ });
3041
+ }
3042
+ function uint32(opts = {}) {
3043
+ return numberScalarType("uint32", opts, (input) => {
3044
+ const isValid = validateInt(input, uint32Min, uint32Max);
3045
+ if (isValid) {
3046
+ return { success: true };
3047
+ }
3048
+ return {
3049
+ success: false,
3050
+ message: `Must be a valid integer between ${uint32Min} and ${uint32Max}`
3051
+ };
3052
+ });
3053
+ }
3054
+ function int64(opts = {}) {
3055
+ function isType(input) {
3056
+ return typeof input === "bigint" && input >= int64Min && input <= int64Max;
3057
+ }
3058
+ function parse(input, context) {
3059
+ if (typeof input === "string" || typeof input === "number") {
3060
+ try {
3061
+ const val = BigInt(input);
3062
+ if (isType(val)) {
3063
+ return val;
3064
+ }
3065
+ context.errors.push({
3066
+ message: `Error at ${context.instancePath}. Invalid int64.`,
3067
+ schemaPath: `${context.schemaPath}/type`,
3068
+ instancePath: context.instancePath
3069
+ });
3070
+ return void 0;
3071
+ } catch (_) {
3072
+ context.errors.push({
3073
+ message: `Error at ${context.instancePath}. Unable to transform ${input} to BigInt`,
3074
+ schemaPath: `${context.schemaPath}/type`,
3075
+ instancePath: context.instancePath
3076
+ });
3077
+ return undefined;
3078
+ }
3079
+ }
3080
+ if (isType(input)) {
3081
+ return input;
3082
+ }
3083
+ context.errors.push({
3084
+ message: `Error at ${context.instancePath}. Expected BigInt or integer string`,
3085
+ schemaPath: `${context.schemaPath}/type`,
3086
+ instancePath: context.instancePath
3087
+ });
3088
+ return undefined;
3089
+ }
3090
+ const validator = {
3091
+ output: BigInt("0"),
3092
+ validate: isType,
3093
+ parse,
3094
+ coerce: parse,
3095
+ serialize(input, context) {
3096
+ if (context.instancePath.length === 0) {
3097
+ return input.toString();
3098
+ }
3099
+ return `"${input.toString()}"`;
3100
+ }
3101
+ };
3102
+ const result = {
3103
+ type: "int64",
3104
+ metadata: {
3105
+ id: opts.id,
3106
+ description: opts.description,
3107
+ isDeprecated: opts.isDeprecated
3108
+ },
3109
+ [VALIDATOR_KEY]: validator,
3110
+ "~standard": createStandardSchemaProperty(isType, parse)
3111
+ };
3112
+ hideInvalidProperties(result);
3113
+ return result;
3114
+ }
3115
+ function uint64(opts = {}) {
3116
+ function isType(input) {
3117
+ return typeof input === "bigint" && input >= uint64Min && input <= uint64Max;
3118
+ }
3119
+ function parse(input, context) {
3120
+ if (typeof input === "string" || typeof input === "number") {
3121
+ try {
3122
+ const val = BigInt(input);
3123
+ if (isType(val)) {
3124
+ return val;
3125
+ }
3126
+ context.errors.push({
3127
+ message: `Error at ${context.instancePath}. Invalid uint64.`,
3128
+ schemaPath: `${context.schemaPath}/type`,
3129
+ instancePath: context.instancePath
3130
+ });
3131
+ return void 0;
3132
+ } catch (_) {
3133
+ context.errors.push({
3134
+ message: `Error at ${context.instancePath}. Unable to transform ${input} to BigInt.`,
3135
+ schemaPath: `${context.schemaPath}/type`,
3136
+ instancePath: context.instancePath
3137
+ });
3138
+ return undefined;
3139
+ }
3140
+ }
3141
+ if (isType(input)) {
3142
+ return input;
3143
+ }
3144
+ context.errors.push({
3145
+ message: `Error at ${context.instancePath}. Expected BigInt or integer string.`,
3146
+ schemaPath: `${context.schemaPath}/type`,
3147
+ instancePath: context.instancePath
3148
+ });
3149
+ return undefined;
3150
+ }
3151
+ const validator = {
3152
+ output: BigInt("0"),
3153
+ validate: isType,
3154
+ parse,
3155
+ coerce: parse,
3156
+ serialize(input, context) {
3157
+ if (context.instancePath.length === 0) {
3158
+ return input.toString();
3159
+ }
3160
+ return `"${input.toString()}"`;
3161
+ }
3162
+ };
3163
+ const result = {
3164
+ type: "uint64",
3165
+ metadata: {
3166
+ id: opts.id,
3167
+ description: opts.description,
3168
+ isDeprecated: opts.isDeprecated
3169
+ },
3170
+ [VALIDATOR_KEY]: validator,
3171
+ "~standard": createStandardSchemaProperty(isType, parse)
3172
+ };
3173
+ hideInvalidProperties(result);
3174
+ return result;
3175
+ }
3176
+ function validateNumber(input) {
3177
+ return typeof input === "number";
3178
+ }
3179
+ function validateInt(input, minVal, maxValue) {
3180
+ return Number.isInteger(input) && input >= minVal && input <= maxValue;
3181
+ }
3182
+ function serializeNumber(input, _context) {
3183
+ return input.toString();
3184
+ }
3185
+ function decodeNumber(input, context) {
3186
+ if (context.instancePath.length === 0 && typeof input === "string") {
3187
+ const result = Number(input);
3188
+ if (Number.isNaN(result)) {
3189
+ context?.errors.push({
3190
+ instancePath: context.instancePath,
3191
+ schemaPath: `${context.schemaPath}/type`,
3192
+ message: `Error at ${context.instancePath}. Invalid number.`
3193
+ });
3194
+ return undefined;
3195
+ }
3196
+ return result;
3197
+ }
3198
+ if (typeof input === "number" && !Number.isNaN(input)) {
3199
+ return input;
3200
+ }
3201
+ context?.errors.push({
3202
+ instancePath: context.instancePath,
3203
+ schemaPath: `${context.schemaPath}/type`,
3204
+ message: `Error at ${context.instancePath}. Invalid number.`
3205
+ });
3206
+ return undefined;
3207
+ }
3208
+ function numberScalarType(type, opts, numTypeMatcher) {
3209
+ const validate = (input) => {
3210
+ const isNum = validateNumber(input);
3211
+ if (!isNum) {
3212
+ return false;
3213
+ }
3214
+ return numTypeMatcher(input).success;
3215
+ };
3216
+ const parse = (input, context) => {
3217
+ const result2 = decodeNumber(input, context);
3218
+ if (context.errors.length) {
3219
+ return undefined;
3220
+ }
3221
+ if (typeof result2 !== "number") {
3222
+ context?.errors.push({
3223
+ instancePath: context.instancePath,
3224
+ schemaPath: `${context.schemaPath}/type`,
3225
+ message: `Error at ${context.instancePath}. Invalid number.`
3226
+ });
3227
+ return undefined;
3228
+ }
3229
+ const matchResult = numTypeMatcher(result2);
3230
+ if (matchResult.success) {
3231
+ return result2;
3232
+ }
3233
+ context?.errors.push({
3234
+ instancePath: context.instancePath,
3235
+ schemaPath: `${context.schemaPath}/type`,
3236
+ message: `Error at ${context.instancePath}. ${matchResult.message}`
3237
+ });
3238
+ return undefined;
3239
+ };
3240
+ const validator = {
3241
+ output: 0,
3242
+ validate,
3243
+ parse,
3244
+ serialize: serializeNumber,
3245
+ coerce(input, options) {
3246
+ const result2 = coerceNumber(input, options);
3247
+ if (typeof result2 !== "number") {
3248
+ options.errors.push({
3249
+ instancePath: options.instancePath,
3250
+ schemaPath: `${options.schemaPath}/type`,
3251
+ message: `Error at ${options.instancePath}. Unable to coerce ${typeof input} to ${type}.`
3252
+ });
3253
+ return undefined;
3254
+ }
3255
+ const matchResult = numTypeMatcher(result2);
3256
+ if (matchResult.success) {
3257
+ return result2;
3258
+ }
3259
+ options.errors.push({
3260
+ instancePath: options.instancePath,
3261
+ schemaPath: `${options.schemaPath}/type`,
3262
+ message: `Error at ${options.instancePath}. ${matchResult.message}`
3263
+ });
3264
+ return undefined;
3265
+ }
3266
+ };
3267
+ const result = {
3268
+ type,
3269
+ metadata: {
3270
+ id: opts.id,
3271
+ description: opts.description,
3272
+ isDeprecated: opts.isDeprecated
3273
+ },
3274
+ [VALIDATOR_KEY]: validator,
3275
+ "~standard": createStandardSchemaProperty(validate, parse)
3276
+ };
3277
+ hideInvalidProperties(result);
3278
+ return result;
3279
+ }
3280
+
3281
+ function object(propA, propB) {
3282
+ const isIdShorthand = typeof propA === "string";
3283
+ const input = isIdShorthand ? propB : propA;
3284
+ const options = isIdShorthand ? { id: propA } : propB ?? {};
3285
+ const schema = {
3286
+ properties: {}
3287
+ };
3288
+ if (typeof options.strict === "boolean") {
3289
+ schema.strict = options.strict;
3290
+ }
3291
+ for (const key of Object.keys(input)) {
3292
+ const prop = input[key];
3293
+ if (prop[VALIDATOR_KEY].optional) {
3294
+ if (!schema.optionalProperties) {
3295
+ schema.optionalProperties = {};
3296
+ }
3297
+ schema.optionalProperties[key] = prop;
3298
+ continue;
3299
+ }
3300
+ schema.properties[key] = prop;
3301
+ }
3302
+ const validate = (input2) => {
3303
+ return validateObjectSchema(schema, input2);
3304
+ };
3305
+ const decode = (input2, context) => {
3306
+ return decodeObjectSchema(
3307
+ schema,
3308
+ input2,
3309
+ context,
3310
+ false
3311
+ );
3312
+ };
3313
+ const validator = {
3314
+ output: {},
3315
+ parse: decode,
3316
+ coerce(input2, context) {
3317
+ return decodeObjectSchema(
3318
+ schema,
3319
+ input2,
3320
+ context,
3321
+ true
3322
+ );
3323
+ },
3324
+ validate,
3325
+ serialize(input2, context) {
3326
+ return serializeObject(
3327
+ schema,
3328
+ input2,
3329
+ context
3330
+ );
3331
+ }
3332
+ };
3333
+ const result = {
3334
+ ...schema,
3335
+ metadata: {
3336
+ id: options.id,
3337
+ description: options.description,
3338
+ isDeprecated: options.isDeprecated
3339
+ },
3340
+ [VALIDATOR_KEY]: validator,
3341
+ "~standard": createStandardSchemaProperty(validate, decode)
3342
+ };
3343
+ hideInvalidProperties(result);
3344
+ return result;
3345
+ }
3346
+ function decodeObjectSchema(schema, input, context, coerce = false) {
3347
+ let parsedInput = input;
3348
+ if (context.instancePath.length === 0 && typeof input === "string") {
3349
+ try {
3350
+ const result2 = JSON.parse(input);
3351
+ parsedInput = result2;
3352
+ } catch (_err) {
3353
+ context.errors.push({
3354
+ instancePath: context.instancePath,
3355
+ schemaPath: `${context.schemaPath}/properties`,
3356
+ message: `Error at ${context.instancePath}. Invalid JSON.`
3357
+ });
3358
+ return undefined;
3359
+ }
3360
+ }
3361
+ if (!isObject(parsedInput)) {
3362
+ context.errors.push({
3363
+ instancePath: context.instancePath,
3364
+ schemaPath: `${context.schemaPath}/properties`,
3365
+ message: `Error at ${context.instancePath}. Expected object`
3366
+ });
3367
+ return undefined;
3368
+ }
3369
+ const result = {};
3370
+ const optionalProps = schema.optionalProperties ?? {};
3371
+ const inputKeys = Object.keys(parsedInput);
3372
+ const requiredKeys = Object.keys(schema.properties);
3373
+ const optionalKeys = Object.keys(optionalProps);
3374
+ if (schema.strict) {
3375
+ for (const key of inputKeys) {
3376
+ if (!requiredKeys.includes(key) && !optionalKeys.includes(key) && key !== context.discriminatorKey) {
3377
+ context.errors.push({
3378
+ instancePath: `${context.instancePath}/${key}`,
3379
+ schemaPath: `${context.schemaPath}/strict`,
3380
+ message: `Error at ${context.instancePath}/${key}. Key '${key}' is not included in the schema. To allow additional input properties set strict to 'false'.`
3381
+ });
3382
+ }
3383
+ }
3384
+ }
3385
+ if (context.errors.length) {
3386
+ return undefined;
3387
+ }
3388
+ if (context.discriminatorKey) {
3389
+ result[context.discriminatorKey] = context.discriminatorValue;
3390
+ }
3391
+ for (const key of requiredKeys) {
3392
+ const val = parsedInput[key];
3393
+ const prop = schema.properties[key];
3394
+ if (coerce) {
3395
+ result[key] = prop[VALIDATOR_KEY].coerce(val, {
3396
+ instancePath: `${context.instancePath}/${key}`,
3397
+ schemaPath: `${context.schemaPath}/properties/${key}`,
3398
+ errors: context.errors,
3399
+ depth: context.depth + 1,
3400
+ maxDepth: context.maxDepth,
3401
+ exitOnFirstError: context.exitOnFirstError
3402
+ });
3403
+ if (context.errors.length && context.exitOnFirstError) {
3404
+ return undefined;
3405
+ }
3406
+ continue;
3407
+ }
3408
+ result[key] = prop[VALIDATOR_KEY].parse(val, {
3409
+ instancePath: `${context.instancePath}/${key}`,
3410
+ schemaPath: `${context.schemaPath}/properties/${key}`,
3411
+ errors: context.errors,
3412
+ depth: context.depth + 1,
3413
+ maxDepth: context.maxDepth,
3414
+ exitOnFirstError: context.exitOnFirstError
3415
+ });
3416
+ if (context.errors.length && context.exitOnFirstError) {
3417
+ return undefined;
3418
+ }
3419
+ }
3420
+ for (const key of optionalKeys) {
3421
+ const val = parsedInput[key];
3422
+ const prop = optionalProps[key];
3423
+ if (val === undefined) {
3424
+ continue;
3425
+ }
3426
+ if (coerce) {
3427
+ result[key] = prop[VALIDATOR_KEY].coerce(val, {
3428
+ instancePath: `${context.instancePath}/${key}`,
3429
+ schemaPath: `${context.schemaPath}/optionalProperties/${key}`,
3430
+ errors: context.errors,
3431
+ depth: context.depth + 1,
3432
+ maxDepth: context.maxDepth,
3433
+ exitOnFirstError: context.exitOnFirstError
3434
+ });
3435
+ if (context.errors.length && context.exitOnFirstError) {
3436
+ return undefined;
3437
+ }
3438
+ continue;
3439
+ }
3440
+ if (typeof val !== "undefined") {
3441
+ result[key] = prop[VALIDATOR_KEY].parse(val, {
3442
+ instancePath: `${context.instancePath}/${key}`,
3443
+ schemaPath: `${context.schemaPath}/optionalProperties/${key}`,
3444
+ errors: context.errors,
3445
+ depth: context.depth + 1,
3446
+ maxDepth: context.maxDepth,
3447
+ exitOnFirstError: context.exitOnFirstError
3448
+ });
3449
+ if (context.errors.length && context.exitOnFirstError) {
3450
+ return undefined;
3451
+ }
3452
+ }
3453
+ }
3454
+ if (context.errors.length) {
3455
+ return undefined;
3456
+ }
3457
+ return result;
3458
+ }
3459
+ function validateObjectSchema(schema, input) {
3460
+ if (!isObject(input)) {
3461
+ return false;
3462
+ }
3463
+ const allowedKeys = schema.strict ? [] : undefined;
3464
+ for (const key of Object.keys(schema.properties)) {
3465
+ const propSchema = schema.properties[key];
3466
+ const isValid = propSchema[VALIDATOR_KEY].validate(input[key]);
3467
+ if (!isValid) return false;
3468
+ allowedKeys?.push(key);
3469
+ }
3470
+ if (schema.optionalProperties) {
3471
+ for (const key of Object.keys(schema.optionalProperties)) {
3472
+ const propsSchema = schema.optionalProperties[key];
3473
+ const isValid = propsSchema[VALIDATOR_KEY].validate(input[key]);
3474
+ if (!isValid) return false;
3475
+ allowedKeys?.push(key);
3476
+ }
3477
+ }
3478
+ if (allowedKeys) {
3479
+ for (const key of Object.keys(input)) {
3480
+ if (!allowedKeys.includes(key)) return false;
3481
+ }
3482
+ }
3483
+ return true;
3484
+ }
3485
+ function pick(inputSchema, keys, options = {}) {
3486
+ const schema = {
3487
+ properties: {},
3488
+ nullable: inputSchema.nullable
3489
+ };
3490
+ if (typeof options.strict === "boolean") {
3491
+ schema.strict = options.strict;
3492
+ }
3493
+ Object.keys(inputSchema.properties).forEach((key) => {
3494
+ if (!schema.properties) {
3495
+ return;
3496
+ }
3497
+ if (keys.includes(key)) {
3498
+ schema.properties[key] = inputSchema.properties[key];
3499
+ }
3500
+ });
3501
+ if (inputSchema.optionalProperties) {
3502
+ schema.optionalProperties = {};
3503
+ Object.keys(inputSchema.optionalProperties).forEach((key) => {
3504
+ if (!schema.optionalProperties || !inputSchema.optionalProperties) {
3505
+ return;
3506
+ }
3507
+ if (keys.includes(key)) {
3508
+ schema.optionalProperties[key] = inputSchema.optionalProperties[key];
3509
+ }
3510
+ });
3511
+ }
3512
+ const parse = (input, context) => {
3513
+ return decodeObjectSchema(schema, input, context, false);
3514
+ };
3515
+ const validate = (input) => {
3516
+ return validateObjectSchema(schema, input);
3517
+ };
3518
+ const result = {
3519
+ ...schema,
3520
+ metadata: {
3521
+ id: options.id,
3522
+ description: options.description,
3523
+ isDeprecated: options.isDeprecated
3524
+ },
3525
+ [VALIDATOR_KEY]: {
3526
+ output: {},
3527
+ parse,
3528
+ coerce(input, context) {
3529
+ return decodeObjectSchema(schema, input, context, false);
3530
+ },
3531
+ validate,
3532
+ serialize(input, context) {
3533
+ return serializeObject(schema, input, context);
3534
+ }
3535
+ },
3536
+ "~standard": createStandardSchemaProperty(validate, parse)
3537
+ };
3538
+ hideInvalidProperties(result);
3539
+ return result;
3540
+ }
3541
+ function omit(inputSchema, keys, options = {}) {
3542
+ const schema = {
3543
+ properties: {
3544
+ ...inputSchema.properties
3545
+ },
3546
+ nullable: inputSchema.nullable
3547
+ };
3548
+ if (typeof options.strict === "boolean") {
3549
+ schema.strict = options.strict;
3550
+ }
3551
+ Object.keys(inputSchema.properties).forEach((key) => {
3552
+ if (keys.includes(key)) {
3553
+ delete schema.properties[key];
3554
+ }
3555
+ });
3556
+ if (inputSchema.optionalProperties) {
3557
+ schema.optionalProperties = {
3558
+ ...inputSchema.optionalProperties
3559
+ };
3560
+ Object.keys(inputSchema.optionalProperties).forEach((key) => {
3561
+ if (!schema.optionalProperties) {
3562
+ return;
3563
+ }
3564
+ if (keys.includes(key)) {
3565
+ delete schema.optionalProperties[key];
3566
+ }
3567
+ });
3568
+ }
3569
+ const validate = (input) => validateObjectSchema(schema, input);
3570
+ const parse = (input, context) => decodeObjectSchema(schema, input, context, false);
3571
+ const result = {
3572
+ ...schema,
3573
+ metadata: {
3574
+ id: options.id,
3575
+ description: options.description,
3576
+ isDeprecated: options.isDeprecated
3577
+ },
3578
+ [VALIDATOR_KEY]: {
3579
+ output: {},
3580
+ validate,
3581
+ parse,
3582
+ serialize(input, context) {
3583
+ return serializeObject(schema, input, context);
3584
+ },
3585
+ coerce(input, context) {
3586
+ return decodeObjectSchema(schema, input, context, true);
3587
+ }
3588
+ },
3589
+ "~standard": createStandardSchemaProperty(validate, parse)
3590
+ };
3591
+ hideInvalidProperties(result);
3592
+ return result;
3593
+ }
3594
+ function serializeObject(schema, input, context) {
3595
+ const strParts = [];
3596
+ if (context.discriminatorKey && context.discriminatorValue) {
3597
+ strParts.push(
3598
+ `"${context.discriminatorKey}":"${context.discriminatorValue}"`
3599
+ );
3600
+ }
3601
+ for (const key of Object.keys(schema.properties)) {
3602
+ const prop = schema.properties[key];
3603
+ const val = input[key];
3604
+ if (typeof val !== "undefined") {
3605
+ strParts.push(
3606
+ `"${key}":${prop[VALIDATOR_KEY].serialize(val, {
3607
+ instancePath: `${context.instancePath}/${key}`,
3608
+ schemaPath: `${context.schemaPath}/properties/${key}`,
3609
+ errors: context.errors,
3610
+ depth: context.depth + 1,
3611
+ maxDepth: context.maxDepth,
3612
+ exitOnFirstError: context.exitOnFirstError
3613
+ })}`
3614
+ );
3615
+ }
3616
+ }
3617
+ if (schema.optionalProperties) {
3618
+ for (const key of Object.keys(schema.optionalProperties)) {
3619
+ const prop = schema.optionalProperties[key];
3620
+ const val = input[key];
3621
+ if (typeof val !== "undefined") {
3622
+ strParts.push(
3623
+ `"${key}":${prop[VALIDATOR_KEY].serialize(val, {
3624
+ instancePath: `${context.instancePath}/${key}`,
3625
+ schemaPath: `${context.schemaPath}/optionalProperties/${key}`,
3626
+ errors: context.errors,
3627
+ depth: context.depth + 1,
3628
+ maxDepth: context.maxDepth,
3629
+ exitOnFirstError: context.exitOnFirstError
3630
+ })}`
3631
+ );
3632
+ }
3633
+ }
3634
+ }
3635
+ return `{${strParts.join(",")}}`;
3636
+ }
3637
+ function extend(baseSchema, inputSchema, options = {}) {
3638
+ const schema = {
3639
+ properties: {
3640
+ ...baseSchema.properties,
3641
+ ...inputSchema.properties
3642
+ },
3643
+ optionalProperties: {
3644
+ ...baseSchema.optionalProperties,
3645
+ ...inputSchema.optionalProperties
3646
+ },
3647
+ metadata: {
3648
+ id: options.id,
3649
+ description: options.description
3650
+ }
3651
+ };
3652
+ if (typeof options.strict === "boolean") {
3653
+ schema.strict = options.strict;
3654
+ }
3655
+ const isType = (input) => validateObjectSchema(schema, input);
3656
+ const validator = {
3657
+ output: {},
3658
+ parse(input, context) {
3659
+ return decodeObjectSchema(schema, input, context, false);
3660
+ },
3661
+ coerce(input, context) {
3662
+ return decodeObjectSchema(schema, input, context, true);
3663
+ },
3664
+ validate: isType,
3665
+ serialize(input, context) {
3666
+ return serializeObject(schema, input, context);
3667
+ }
3668
+ };
3669
+ const result = {
3670
+ ...schema,
3671
+ [VALIDATOR_KEY]: validator,
3672
+ "~standard": createStandardSchemaProperty(
3673
+ validator.validate,
3674
+ validator.parse
3675
+ )
3676
+ };
3677
+ hideInvalidProperties(result);
3678
+ return result;
3679
+ }
3680
+ function partial(schema, options = {}) {
3681
+ const newSchema = {
3682
+ properties: {},
3683
+ optionalProperties: {},
3684
+ nullable: schema.nullable,
3685
+ metadata: {
3686
+ id: options.id,
3687
+ description: options.description
3688
+ }
3689
+ };
3690
+ if (typeof options.strict === "boolean") {
3691
+ schema.strict = options.strict;
3692
+ }
3693
+ for (const key of Object.keys(schema.properties)) {
3694
+ const prop = schema.properties[key];
3695
+ newSchema.optionalProperties[key] = optional(prop);
3696
+ }
3697
+ if (schema.optionalProperties && newSchema.optionalProperties) {
3698
+ for (const key of Object.keys(schema.optionalProperties)) {
3699
+ const prop = schema.optionalProperties[key];
3700
+ if (prop[VALIDATOR_KEY].optional) {
3701
+ newSchema.optionalProperties[key] = prop;
3702
+ } else {
3703
+ newSchema.optionalProperties[key] = optional(prop);
3704
+ }
3705
+ }
3706
+ }
3707
+ const validate = (input) => {
3708
+ return validateObjectSchema(newSchema, input);
3709
+ };
3710
+ const parse = (input, context) => {
3711
+ return decodeObjectSchema(newSchema, input, context, false);
3712
+ };
3713
+ const validator = {
3714
+ output: {},
3715
+ optional: schema[VALIDATOR_KEY].optional,
3716
+ validate,
3717
+ parse,
3718
+ coerce(input, context) {
3719
+ return decodeObjectSchema(newSchema, input, context, true);
3720
+ },
3721
+ serialize(input, context) {
3722
+ return serializeObject(schema, input, context);
3723
+ }
3724
+ };
3725
+ const result = {
3726
+ ...newSchema,
3727
+ [VALIDATOR_KEY]: validator,
3728
+ ["~standard"]: createStandardSchemaProperty(
3729
+ validator.validate,
3730
+ validator.parse
3731
+ )
3732
+ };
3733
+ hideInvalidProperties(result);
3734
+ return result;
3735
+ }
3736
+
3737
+ function string(opts = {}) {
3738
+ const validator = {
3739
+ output: "",
3740
+ parse: decode,
3741
+ coerce: coerce$2,
3742
+ validate: validate$2,
3743
+ serialize(input, context) {
3744
+ if (context.instancePath.length === 0) {
3745
+ return input;
3746
+ }
3747
+ if (input.length < 42) {
3748
+ return serializeSmallString(input);
3749
+ }
3750
+ if (input.length < 5e3 && !STR_ESCAPE.test(input)) {
3751
+ return `"${input}"`;
3752
+ }
3753
+ return JSON.stringify(input);
3754
+ }
3755
+ };
3756
+ const result = {
3757
+ type: "string",
3758
+ metadata: {
3759
+ id: opts.id,
3760
+ description: opts.description,
3761
+ isDeprecated: opts.isDeprecated
3762
+ },
3763
+ [VALIDATOR_KEY]: validator,
3764
+ "~standard": createStandardSchemaProperty(validate$2, decode)
3765
+ };
3766
+ hideInvalidProperties(result);
3767
+ return result;
3768
+ }
3769
+ function serializeString(input) {
3770
+ if (input.length < 42) {
3771
+ return serializeSmallString(input);
3772
+ }
3773
+ if (input.length < 5e3 && !STR_ESCAPE.test(input)) {
3774
+ return `"${input}"`;
3775
+ }
3776
+ return JSON.stringify(input);
3777
+ }
3778
+ function validate$2(input) {
3779
+ return typeof input === "string";
3780
+ }
3781
+ function decode(input, context) {
3782
+ if (validate$2(input)) {
3783
+ return input;
3784
+ }
3785
+ context.errors.push({
3786
+ instancePath: context.instancePath,
3787
+ schemaPath: `${context.schemaPath}/type`,
3788
+ message: `Error at ${context.instancePath}. Expected 'string' got ${typeof input}.`
3789
+ });
3790
+ return undefined;
3791
+ }
3792
+ function coerce$2(input, context) {
3793
+ return decode(input, context);
3794
+ }
3795
+ const STR_ESCAPE = (
3796
+ // eslint-disable-next-line no-control-regex
3797
+ /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/
3798
+ );
3799
+ function serializeSmallString(input) {
3800
+ const len = input.length;
3801
+ let result = "";
3802
+ let last = -1;
3803
+ let point = 255;
3804
+ for (let i = 0; i < len; i++) {
3805
+ point = input.charCodeAt(i);
3806
+ if (point < 32 || point >= 55296 && point <= 57343) {
3807
+ return JSON.stringify(input);
3808
+ }
3809
+ if (point === 34 || // '"'
3810
+ point === 92) {
3811
+ if (last === -1) {
3812
+ last = 0;
3813
+ }
3814
+ result += input.slice(last, i) + "\\";
3815
+ last = i;
3816
+ }
3817
+ }
3818
+ if (last === -1) {
3819
+ return `"${input}"`;
3820
+ }
3821
+ return `"${result}${input.slice(last)}"`;
3822
+ }
3823
+
3824
+ function record(schema, opts = {}) {
3825
+ const validateFn = (input) => {
3826
+ if (!isObject(input)) {
3827
+ return false;
3828
+ }
3829
+ for (const key of Object.keys(input)) {
3830
+ const val = input[key];
3831
+ const isValid = schema[VALIDATOR_KEY].validate(val);
3832
+ if (!isValid) {
3833
+ return false;
3834
+ }
3835
+ }
3836
+ return true;
3837
+ };
3838
+ const parseFn = (input, ctx) => {
3839
+ return parse$2(schema, input, ctx, false);
3840
+ };
3841
+ const validator = {
3842
+ output: {},
3843
+ validate: validateFn,
3844
+ parse: parseFn,
3845
+ coerce(input, data) {
3846
+ return parse$2(schema, input, data, true);
3847
+ },
3848
+ serialize(input, context) {
3849
+ if (context.depth >= context.maxDepth) {
3850
+ context.errors.push({
3851
+ instancePath: context.instancePath,
3852
+ schemaPath: context.schemaPath,
3853
+ message: "Max depth reached"
3854
+ });
3855
+ return undefined;
3856
+ }
3857
+ let result2 = "{";
3858
+ const keys = Object.keys(input);
3859
+ for (let i = 0; i < keys.length; i++) {
3860
+ const key = keys[i];
3861
+ const val = input[key];
3862
+ if (i > 0) result2 += ",";
3863
+ result2 += serializeString(key);
3864
+ result2 += ":";
3865
+ result2 += schema[VALIDATOR_KEY].serialize(val, {
3866
+ instancePath: `${context.instancePath}/${key}`,
3867
+ schemaPath: `${context.schemaPath}/values`,
3868
+ errors: context.errors,
3869
+ exitOnFirstError: context.exitOnFirstError,
3870
+ depth: context.depth + 1,
3871
+ maxDepth: context.maxDepth
3872
+ });
3873
+ }
3874
+ result2 += "}";
3875
+ return result2;
3876
+ }
3877
+ };
3878
+ const result = {
3879
+ values: schema,
3880
+ metadata: {
3881
+ id: opts.id,
3882
+ description: opts.description,
3883
+ isDeprecated: opts.isDeprecated
3884
+ },
3885
+ [VALIDATOR_KEY]: validator,
3886
+ "~standard": createStandardSchemaProperty(validateFn, parseFn)
3887
+ };
3888
+ hideInvalidProperties(result);
3889
+ return result;
3890
+ }
3891
+ function parse$2(schema, input, data, coerce = false) {
3892
+ if (data.depth >= data.maxDepth) {
3893
+ data.errors.push({
3894
+ instancePath: data.instancePath,
3895
+ schemaPath: data.schemaPath,
3896
+ message: "Max depth reached"
3897
+ });
3898
+ return undefined;
3899
+ }
3900
+ let parsedInput = input;
3901
+ if (data.instancePath.length === 0 && typeof input === "string" && input.length > 0) {
3902
+ try {
3903
+ parsedInput = JSON.parse(input);
3904
+ } catch (err) {
3905
+ data.errors.push({
3906
+ message: err instanceof Error ? err.message : `${err}`,
3907
+ instancePath: data.instancePath,
3908
+ schemaPath: data.schemaPath,
3909
+ data: err
3910
+ });
3911
+ return undefined;
3912
+ }
3913
+ }
3914
+ if (!isObject(parsedInput)) {
3915
+ data.errors.push({
3916
+ instancePath: data.instancePath,
3917
+ schemaPath: `${data.schemaPath}/values`,
3918
+ message: `Error at ${data.instancePath} Expected object`
3919
+ });
3920
+ return undefined;
3921
+ }
3922
+ const result = {};
3923
+ for (const key of Object.keys(parsedInput)) {
3924
+ const val = parsedInput[key];
3925
+ if (coerce) {
3926
+ result[key] = schema[VALIDATOR_KEY].coerce(val, {
3927
+ instancePath: `${data.instancePath}/${key}`,
3928
+ schemaPath: `${data.schemaPath}/values`,
3929
+ errors: data.errors,
3930
+ maxDepth: data.maxDepth,
3931
+ depth: data.depth + 1,
3932
+ exitOnFirstError: data.exitOnFirstError
3933
+ });
3934
+ } else {
3935
+ result[key] = schema[VALIDATOR_KEY].parse(val, {
3936
+ instancePath: `${data.instancePath}/${key}`,
3937
+ schemaPath: `${data.schemaPath}/values`,
3938
+ errors: data.errors,
3939
+ maxDepth: data.maxDepth,
3940
+ depth: data.depth + 1,
3941
+ exitOnFirstError: data.exitOnFirstError
3942
+ });
3943
+ }
3944
+ }
3945
+ if (data.errors.length) {
3946
+ return undefined;
3947
+ }
3948
+ return result;
3949
+ }
3950
+
3951
+ let recursiveTypeCount = 0;
3952
+ function recursive(propA, propB) {
3953
+ const isIdShorthand = typeof propA === "string";
3954
+ const callback = isIdShorthand ? propB : propA;
3955
+ const options = isIdShorthand ? { id: propA } : propB ?? {};
3956
+ if (!options.id) {
3957
+ recursiveTypeCount++;
3958
+ console.warn(
3959
+ `[@arrirpc/schema] WARNING: It is highly recommended to specify an ID for recursive types.`
3960
+ );
3961
+ }
3962
+ const id = options.id ?? `TypeRef${recursiveTypeCount}`;
3963
+ const recursiveFns = {};
3964
+ const validator = {
3965
+ output: "",
3966
+ parse(input, context) {
3967
+ if (context.depth >= context.maxDepth) {
3968
+ context.errors.push({
3969
+ message: "Max depth exceeded",
3970
+ instancePath: context.instancePath,
3971
+ schemaPath: context.schemaPath
3972
+ });
3973
+ return undefined;
3974
+ }
3975
+ if (recursiveFns[id]) {
3976
+ return recursiveFns[id].parse(input, {
3977
+ ...context,
3978
+ depth: context.depth + 1
3979
+ });
3980
+ }
3981
+ },
3982
+ serialize(input, context) {
3983
+ if (context.depth >= context.maxDepth) {
3984
+ context.errors.push({
3985
+ message: "Max depth exceeded",
3986
+ instancePath: context.instancePath,
3987
+ schemaPath: context.schemaPath
3988
+ });
3989
+ return undefined;
3990
+ }
3991
+ if (recursiveFns[id]) {
3992
+ return recursiveFns[id].serialize(input, context);
3993
+ }
3994
+ return "";
3995
+ },
3996
+ validate(input) {
3997
+ if (recursiveFns[id]) {
3998
+ return recursiveFns[id].validate(input);
3999
+ }
4000
+ return false;
4001
+ },
4002
+ coerce(input, context) {
4003
+ if (context.depth >= context.maxDepth) {
4004
+ context.errors.push({
4005
+ message: "Max depth exceeded",
4006
+ instancePath: context.instancePath,
4007
+ schemaPath: context.schemaPath
4008
+ });
4009
+ return undefined;
4010
+ }
4011
+ if (recursiveFns[id]) {
4012
+ return recursiveFns[id].coerce(input, context);
4013
+ }
4014
+ }
4015
+ };
4016
+ const refSchema = {
4017
+ ref: id,
4018
+ [VALIDATOR_KEY]: validator,
4019
+ "~standard": createStandardSchemaProperty(
4020
+ validator.validate,
4021
+ validator.parse
4022
+ )
4023
+ };
4024
+ hideInvalidProperties(refSchema);
4025
+ const mainSchema = callback(refSchema);
4026
+ if (!mainSchema.metadata) mainSchema.metadata = {};
4027
+ mainSchema.metadata.id = id;
4028
+ mainSchema.metadata.description = options?.description ?? mainSchema.metadata.description;
4029
+ mainSchema.metadata.isDeprecated = options?.isDeprecated ?? mainSchema.metadata.isDeprecated;
4030
+ recursiveFns[id] = {
4031
+ validate: mainSchema[VALIDATOR_KEY].validate,
4032
+ parse: mainSchema[VALIDATOR_KEY].parse,
4033
+ serialize: mainSchema[VALIDATOR_KEY].serialize,
4034
+ coerce: mainSchema[VALIDATOR_KEY].coerce
4035
+ };
4036
+ return mainSchema;
4037
+ }
4038
+
4039
+ function timestamp(opts = {}) {
4040
+ const validator = {
4041
+ output: /* @__PURE__ */ new Date(),
4042
+ validate: validate$1,
4043
+ parse: parse$1,
4044
+ coerce: coerce$1,
4045
+ serialize: serialize$1
4046
+ };
4047
+ const result = {
4048
+ type: "timestamp",
4049
+ metadata: {
4050
+ id: opts.id,
4051
+ description: opts.description,
4052
+ isDeprecated: opts.isDeprecated
4053
+ },
4054
+ [VALIDATOR_KEY]: validator,
4055
+ "~standard": createStandardSchemaProperty(validate$1, parse$1)
4056
+ };
4057
+ hideInvalidProperties(result);
4058
+ return result;
4059
+ }
4060
+ function validate$1(input) {
4061
+ return typeof input === "object" && input instanceof Date;
4062
+ }
4063
+ function parse$1(input, data) {
4064
+ try {
4065
+ if (validate$1(input)) {
4066
+ return input;
4067
+ }
4068
+ if (typeof input === "string") {
4069
+ const result = Date.parse(input);
4070
+ if (Number.isNaN(result)) {
4071
+ data?.errors.push({
4072
+ message: `Error at ${data.instancePath}. Invalid date string.`,
4073
+ instancePath: data.instancePath,
4074
+ schemaPath: `${data.schemaPath}/type`
4075
+ });
4076
+ return void 0;
4077
+ }
4078
+ return new Date(result);
4079
+ }
4080
+ data.errors.push({
4081
+ message: `Error at ${data.instancePath}. Invalid date.`,
4082
+ instancePath: data.instancePath,
4083
+ schemaPath: `${data.schemaPath}/type`
4084
+ });
4085
+ return void 0;
4086
+ } catch (err) {
4087
+ data.errors.push({
4088
+ message: err instanceof Error ? err.message : `${err}`,
4089
+ instancePath: data.instancePath,
4090
+ schemaPath: data.schemaPath,
4091
+ data: err
4092
+ });
4093
+ return undefined;
4094
+ }
4095
+ }
4096
+ function coerce$1(input, options) {
4097
+ if (typeof input === "number") {
4098
+ return new Date(input);
4099
+ }
4100
+ return parse$1(input, options);
4101
+ }
4102
+ function serialize$1(input, data) {
4103
+ if (data.instancePath.length === 0) {
4104
+ return input.toISOString();
4105
+ }
4106
+ return `"${input.toISOString()}"`;
4107
+ }
4108
+
4109
+ function sanitizeJson(json) {
4110
+ return json.replace(/[\b]/g, "\\b").replace(/[\f]/g, "\\f").replace(/[\n]/g, "\\n").replace(/[\r]/g, "\\r").replace(/[\t]/g, "\\t");
4111
+ }
4112
+ function validate(schema, input) {
4113
+ return schema[VALIDATOR_KEY].validate(input);
4114
+ }
4115
+ function parse(schema, input) {
4116
+ const ctx = newValidationContext();
4117
+ const result = schema[VALIDATOR_KEY].parse(input, ctx);
4118
+ if (ctx.errors.length) {
4119
+ return {
4120
+ success: false,
4121
+ errors: ctx.errors
4122
+ };
4123
+ }
4124
+ return {
4125
+ success: true,
4126
+ value: result
4127
+ };
4128
+ }
4129
+ function parseUnsafe(schema, input) {
4130
+ const ctx = newValidationContext();
4131
+ const result = schema[VALIDATOR_KEY].parse(input, ctx);
4132
+ if (ctx.errors.length) {
4133
+ throw new ValidationException({
4134
+ message: `Unable to parse input. ${ctx.errors[0].message}`,
4135
+ errors: ctx.errors
4136
+ });
4137
+ }
4138
+ return result;
4139
+ }
4140
+ function coerce(schema, input) {
4141
+ const ctx = newValidationContext();
4142
+ const result = schema[VALIDATOR_KEY].coerce(input, ctx);
4143
+ if (ctx.errors.length) {
4144
+ return {
4145
+ success: false,
4146
+ errors: ctx.errors
4147
+ };
4148
+ }
4149
+ return {
4150
+ success: true,
4151
+ value: result
4152
+ };
4153
+ }
4154
+ function coerceUnsafe(schema, input) {
4155
+ const ctx = newValidationContext();
4156
+ const result = schema[VALIDATOR_KEY].coerce(input, ctx);
4157
+ if (ctx.errors.length) {
4158
+ throw new ValidationException({
4159
+ message: `Unable to coerce input. ${ctx.errors[0]?.message}`,
4160
+ errors: ctx.errors
4161
+ });
4162
+ }
4163
+ return result;
4164
+ }
4165
+ function serialize(schema, input) {
4166
+ try {
4167
+ const context = newValidationContext();
4168
+ const result = schema[VALIDATOR_KEY].serialize(input, context);
4169
+ if (context.errors.length || typeof result === "undefined") {
4170
+ return {
4171
+ success: false,
4172
+ errors: context.errors
4173
+ };
4174
+ }
4175
+ return {
4176
+ success: true,
4177
+ value: result
4178
+ };
4179
+ } catch (err) {
4180
+ if (err instanceof ValidationException) {
4181
+ return {
4182
+ success: false,
4183
+ errors: err.errors
4184
+ };
4185
+ }
4186
+ const errList = errors(schema, input);
4187
+ if (errList.length) {
4188
+ return {
4189
+ success: false,
4190
+ errors: errList
4191
+ };
4192
+ }
4193
+ return {
4194
+ success: false,
4195
+ errors: [
4196
+ {
4197
+ message: err instanceof Error ? err.message : `${err}`,
4198
+ instancePath: "/",
4199
+ data: err
4200
+ }
4201
+ ]
4202
+ };
4203
+ }
4204
+ }
4205
+ function serializeUnsafe(schema, input) {
4206
+ const result = serialize(schema, input);
4207
+ if (!result.success) {
4208
+ throw new ValidationException({
4209
+ message: result.errors.length ? result.errors[0].message : `Unknown error`,
4210
+ errors: result.errors
4211
+ });
4212
+ }
4213
+ return result.value;
4214
+ }
4215
+ function errors(schema, input, exitOnFirstError = false) {
4216
+ const errorList = [];
4217
+ try {
4218
+ schema[VALIDATOR_KEY].parse(input, {
4219
+ errors: errorList,
4220
+ instancePath: "",
4221
+ schemaPath: "",
4222
+ depth: 0,
4223
+ maxDepth: 500,
4224
+ exitOnFirstError
4225
+ });
4226
+ } catch (err) {
4227
+ errorList.push({ instancePath: "", schemaPath: "", message: `${err}` });
4228
+ }
4229
+ return errorList;
4230
+ }
4231
+
4232
+ const _namespace = {
4233
+ __proto__: null,
4234
+ any: any,
4235
+ array: array,
4236
+ boolean: boolean,
4237
+ clone: clone,
4238
+ coerce: coerce,
4239
+ coerceUnsafe: coerceUnsafe,
4240
+ compile: compile,
4241
+ discriminator: discriminator,
4242
+ enumerator: enumerator,
4243
+ errors: errors,
4244
+ extend: extend,
4245
+ float32: float32,
4246
+ float64: float64,
4247
+ int16: int16,
4248
+ int32: int32,
4249
+ int64: int64,
4250
+ int8: int8,
4251
+ nullable: nullable,
4252
+ number: number,
4253
+ object: object,
4254
+ omit: omit,
4255
+ optional: optional,
4256
+ parse: parse,
4257
+ parseUnsafe: parseUnsafe,
4258
+ partial: partial,
4259
+ pick: pick,
4260
+ record: record,
4261
+ recursive: recursive,
4262
+ serialize: serialize,
4263
+ serializeUnsafe: serializeUnsafe,
4264
+ string: string,
4265
+ stringEnum: stringEnum,
4266
+ timestamp: timestamp,
4267
+ uint16: uint16,
4268
+ uint32: uint32,
4269
+ uint64: uint64,
4270
+ uint8: uint8,
4271
+ validate: validate
4272
+ };
2197
4273
 
2198
- export { SCHEMA_METADATA, ValidationError, _namespace as a, any, array, boolean, clone, coerce, compile, createStandardSchemaProperty, discriminator, enumerator, errors, extend, float32, float64, getCompiledParser, getCompiledSerializer, createParsingTemplate as getSchemaParsingCode, createSerializationV2Template as getSchemaSerializationCode, createValidationTemplate as getSchemaValidationCode, int16, int16Max, int16Min, int32, int32Max, int32Min, int64, int8, int8Max, int8Min, isAAraySchema, isADiscriminatorSchema, isAObjectSchema, isARecordSchema, isARefSchema, isAScalarSchema, isAStringEnumSchema, isAdaptedSchema, nullable, number, object, omit, optional, parse, partial, pick, record, recursive, safeCoerce, safeParse, serialize, string, stringEnum, timestamp, uint16, uint16Max, uint16Min, uint32, uint32Max, uint32Min, uint64, uint8, uint8Max, uint8Min, validate, validatorFromAdaptedSchema };
4274
+ export { STR_ESCAPE, VALIDATOR_KEY, ValidationException, _namespace as a, any, array, boolean, clone, coerce, coerceUnsafe, compile, decodeObjectSchema, discriminator, enumerator, errorMessageFromErrors, errors, extend, float32, float64, getCompiledParser, getCompiledSerializer, createParsingTemplate as getSchemaDecodingCode, createSerializationV2Template as getSchemaSerializationCode, createValidationTemplate as getSchemaValidationCode, int16, int16Max, int16Min, int32, int32Max, int32Min, int64, int64Max, int64Min, int8, int8Max, int8Min, isAAraySchema, isADiscriminatorSchema, isAObjectSchema, isARecordSchema, isARefSchema, isAScalarSchema, isAStringEnumSchema, isObject, isValidationException, isValueError, newValidationContext, nullable, number, object, omit, optional, parse, parseUnsafe, partial, pick, record, recursive, sanitizeJson, serialize, serializeObject, serializeSmallString, serializeString, serializeUnsafe, string, stringEnum, timestamp, uint16, uint16Max, uint16Min, uint32, uint32Max, uint32Min, uint64, uint64Max, uint64Min, uint8, uint8Max, uint8Min, validate, validateObjectSchema };