@arrirpc/schema 0.73.0 → 0.74.0

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