@naturalcycles/nodejs-lib 15.143.0 → 15.145.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.
@@ -1,11 +1,5 @@
1
1
  import type { ValidationFunction, ValidationFunctionResult } from '@naturalcycles/js-lib'
2
- import {
3
- _isObject,
4
- _isUndefined,
5
- _numberEnumValues,
6
- _stringEnumValues,
7
- getEnumType,
8
- } from '@naturalcycles/js-lib'
2
+ import { _isObject, _isUndefined, _stringEnumValues, getEnumType } from '@naturalcycles/js-lib'
9
3
  import { _uniq } from '@naturalcycles/js-lib/array'
10
4
  import { _assert, _try } from '@naturalcycles/js-lib/error'
11
5
  import type { Set2 } from '@naturalcycles/js-lib/object'
@@ -596,6 +590,18 @@ export class JBuilder<OUT, Opt> extends JSchema<OUT, Opt> {
596
590
  return this.cloneAndUpdateSchema({ default: v })
597
591
  }
598
592
 
593
+ /**
594
+ * Gives an example of a valid input value. It is not validated.
595
+ * The example must be a plain value: `build()` does not keep class instances.
596
+ *
597
+ * ```
598
+ * const schema = j.string().regex(/^[A-Z]{3}-\d{4}$/).example('ABC-1234')
599
+ * ```
600
+ */
601
+ example(example: any): this {
602
+ return this.cloneAndUpdateSchema({ examples: [example] })
603
+ }
604
+
599
605
  instanceof(of: string): this {
600
606
  return this.cloneAndUpdateSchema({ type: 'object', instanceof: of })
601
607
  }
@@ -834,30 +840,34 @@ export class JString<
834
840
  * Expects the JWT to be signed!
835
841
  */
836
842
  jwt(): this {
837
- return this.regex(JWT_REGEX, { msg: 'is not a valid JWT format' })
843
+ return this.regex(JWT_REGEX, { msg: 'is not a valid JWT format' }).example(
844
+ 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIn0.c2lnbmF0dXJl',
845
+ )
838
846
  }
839
847
 
840
848
  url(): this {
841
- return this.regex(URL_REGEX, { msg: 'is not a valid URL format' })
849
+ return this.regex(URL_REGEX, { msg: 'is not a valid URL format' }).example(
850
+ 'https://example.com',
851
+ )
842
852
  }
843
853
 
844
854
  ipv4(): this {
845
- return this.regex(IPV4_REGEX, { msg: 'is not a valid IPv4 format' })
855
+ return this.regex(IPV4_REGEX, { msg: 'is not a valid IPv4 format' }).example('192.0.2.1')
846
856
  }
847
857
 
848
858
  ipv6(): this {
849
- return this.regex(IPV6_REGEX, { msg: 'is not a valid IPv6 format' })
859
+ return this.regex(IPV6_REGEX, { msg: 'is not a valid IPv6 format' }).example('2001:db8::1')
850
860
  }
851
861
 
852
862
  slug(): this {
853
- return this.regex(SLUG_REGEX, { msg: 'is not a valid slug format' })
863
+ return this.regex(SLUG_REGEX, { msg: 'is not a valid slug format' }).example('my-slug')
854
864
  }
855
865
 
856
866
  /**
857
867
  * Validates the 3-part semver format: `major.minor.patch`, e.g `1.2.3`.
858
868
  */
859
869
  semVer(): this {
860
- return this.regex(SEMVER_REGEX, { msg: 'is not a valid semver format' })
870
+ return this.regex(SEMVER_REGEX, { msg: 'is not a valid semver format' }).example('1.2.3')
861
871
  }
862
872
 
863
873
  /**
@@ -866,19 +876,27 @@ export class JString<
866
876
  * Not a semver by the spec, but is used by e.g .NET and some mobile app versions.
867
877
  */
868
878
  semVer4(): this {
869
- return this.regex(SEMVER4_REGEX, { msg: 'is not a valid 4-part semver format' })
879
+ return this.regex(SEMVER4_REGEX, {
880
+ msg: 'is not a valid 4-part semver format',
881
+ }).example('1.2.3.4')
870
882
  }
871
883
 
872
884
  languageTag(): this {
873
- return this.regex(LANGUAGE_TAG_REGEX, { msg: 'is not a valid language format' })
885
+ return this.regex(LANGUAGE_TAG_REGEX, {
886
+ msg: 'is not a valid language format',
887
+ }).example('en-US')
874
888
  }
875
889
 
876
890
  countryCode(): this {
877
- return this.regex(COUNTRY_CODE_REGEX, { msg: 'is not a valid country code format' })
891
+ return this.regex(COUNTRY_CODE_REGEX, {
892
+ msg: 'is not a valid country code format',
893
+ }).example('US')
878
894
  }
879
895
 
880
896
  currency(): this {
881
- return this.regex(CURRENCY_REGEX, { msg: 'is not a valid currency format' })
897
+ return this.regex(CURRENCY_REGEX, {
898
+ msg: 'is not a valid currency format',
899
+ }).example('USD')
882
900
  }
883
901
 
884
902
  /**
@@ -895,11 +913,13 @@ export class JString<
895
913
  base64Url(): this {
896
914
  return this.regex(BASE64URL_REGEX, {
897
915
  msg: 'contains characters not allowed in Base64 URL characterset',
898
- })
916
+ }).example('abc-DEF_123')
899
917
  }
900
918
 
901
919
  uuid(): this {
902
- return this.regex(UUID_REGEX, { msg: 'is an invalid UUID' })
920
+ return this.regex(UUID_REGEX, { msg: 'is an invalid UUID' }).example(
921
+ '123e4567-e89b-12d3-a456-426614174000',
922
+ )
903
923
  }
904
924
  }
905
925
 
@@ -1204,6 +1224,30 @@ export class JObject<OUT extends AnyObject, Opt extends boolean = false> extends
1204
1224
  const exclusiveProperties = this.schema.exclusiveProperties ?? []
1205
1225
  return this.cloneAndUpdateSchema({ exclusiveProperties: [...exclusiveProperties, propNames] })
1206
1226
  }
1227
+
1228
+ /**
1229
+ * For an object that uses values of an enum as keys, with a different schema per key.
1230
+ * Keeps the names of those keys in the built schema.
1231
+ *
1232
+ * ```
1233
+ * const schema = j
1234
+ * .object<Settings>({
1235
+ * [Color.RED]: j.boolean(),
1236
+ * [Color.BLUE]: j.array(j.string()),
1237
+ * })
1238
+ * .enumKeys(Color)
1239
+ * ```
1240
+ *
1241
+ * When every key has the same schema, prefer `j.object.withEnumKeys`!
1242
+ */
1243
+ enumKeys(keyEnum: StringEnum | NumberEnum | JEnum<any, any>): this {
1244
+ const properties = this.schema.properties ?? {}
1245
+ const keyEnumSchema: JEnum<any, any> = keyEnum instanceof JEnum ? keyEnum : j.enum(keyEnum)
1246
+ const enumValues: readonly (string | number)[] = keyEnumSchema.build().enum
1247
+ const keys = enumValues.filter(value => Object.hasOwn(properties, String(value)))
1248
+
1249
+ return this.cloneAndUpdateSchema({ enumKeys: keyEnumSchema.only(keys).build() })
1250
+ }
1207
1251
  }
1208
1252
 
1209
1253
  interface JObjectOpts {
@@ -1387,6 +1431,28 @@ export class JEnum<
1387
1431
  if (opt?.msg) this.setErrorMessage('enum', opt.msg)
1388
1432
  }
1389
1433
 
1434
+ /**
1435
+ * Keeps only the listed values of the enum.
1436
+ *
1437
+ * ```
1438
+ * const schema = j.enum(Color).only([Color.RED, Color.BLUE])
1439
+ * ```
1440
+ */
1441
+ only<const U extends OUT>(values: readonly U[]): JEnum<U, Opt> {
1442
+ const enumValues: readonly OUT[] = this.schema.enum
1443
+ const listedValues: readonly OUT[] = values
1444
+
1445
+ const unknownValues = listedValues.filter(value => !enumValues.includes(value))
1446
+ _assert(!unknownValues.length, `Values are not in the enum: ${unknownValues.join(', ')}`)
1447
+
1448
+ const isListed = enumValues.map(value => listedValues.includes(value))
1449
+
1450
+ return this.cloneAndUpdateSchema({
1451
+ enum: enumValues.filter((_, index) => isListed[index]),
1452
+ enumNames: this.schema.enumNames?.filter((_, index) => isListed[index]),
1453
+ }) as any
1454
+ }
1455
+
1390
1456
  branded<B extends OUT>(): JEnum<B, Opt> {
1391
1457
  return this as any as JEnum<B, Opt>
1392
1458
  }
@@ -1525,36 +1591,47 @@ function withEnumKeys<
1525
1591
  >(
1526
1592
  keys: T,
1527
1593
  schema: S,
1528
- ): JObject<Opt extends true ? { [P in K]?: SchemaOut<S> } : { [P in K]: SchemaOut<S> }, false> {
1529
- let enumValues: readonly (string | number)[] | undefined
1530
- if (Array.isArray(keys)) {
1531
- _assert(
1532
- isEveryItemPrimitive(keys),
1533
- 'Every item in the key list should be string, number or symbol',
1534
- )
1535
- enumValues = keys
1594
+ ): JObject<Opt extends true ? { [P in K]?: SchemaOut<S> } : { [P in K]: SchemaOut<S> }, false>
1595
+ function withEnumKeys<
1596
+ K extends string | number,
1597
+ S extends JSchema<any, any>,
1598
+ Opt extends boolean = SchemaOpt<S>,
1599
+ >(
1600
+ keys: JEnum<K, any>,
1601
+ schema: S,
1602
+ ): JObject<
1603
+ Opt extends true ? { [P in `${K}`]?: SchemaOut<S> } : { [P in `${K}`]: SchemaOut<S> },
1604
+ false
1605
+ >
1606
+ function withEnumKeys(
1607
+ keys: readonly (string | number)[] | StringEnum | NumberEnum | JEnum<any, any>,
1608
+ schema: JSchema<any, any>,
1609
+ ): JObject<any, false> {
1610
+ let keyEnum: JEnum<any, any> | undefined
1611
+ if (keys instanceof JEnum) {
1612
+ keyEnum = keys
1613
+ } else if (Array.isArray(keys)) {
1614
+ keyEnum = j.enum(keys)
1536
1615
  } else if (typeof keys === 'object') {
1537
1616
  const enumType = getEnumType(keys)
1538
1617
  _assert(
1539
1618
  enumType === 'NumberEnum' || enumType === 'StringEnum',
1540
1619
  'The key list should be StringEnum or NumberEnum',
1541
1620
  )
1542
- if (enumType === 'NumberEnum') {
1543
- enumValues = _numberEnumValues(keys as NumberEnum)
1544
- } else if (enumType === 'StringEnum') {
1545
- enumValues = _stringEnumValues(keys as StringEnum)
1546
- }
1621
+ keyEnum = j.enum(keys)
1547
1622
  }
1548
1623
 
1549
- _assert(enumValues, 'The key list should be an array of values, NumberEnum or a StringEnum')
1624
+ _assert(keyEnum, 'The key list should be an array of values, NumberEnum or a StringEnum')
1625
+
1626
+ const keyValues: readonly unknown[] = keyEnum.build().enum
1627
+ _assert(
1628
+ isEveryItemPrimitive(keyValues),
1629
+ 'Every item in the key list should be string, number or symbol',
1630
+ )
1550
1631
 
1551
- const typedValues = enumValues as readonly K[]
1552
- const props = Object.fromEntries(typedValues.map(key => [key, schema])) as any
1632
+ const props = Object.fromEntries(keyValues.map(key => [key, schema]))
1553
1633
 
1554
- return new JObject<
1555
- Opt extends true ? { [P in K]?: SchemaOut<S> } : { [P in K]: SchemaOut<S> },
1556
- false
1557
- >(props, { hasIsOfTypeCheck: false })
1634
+ return new JObject(props, { hasIsOfTypeCheck: false }).enumKeys(keyEnum)
1558
1635
  }
1559
1636
 
1560
1637
  // ==== AjvSchema compat wrapper ====
@@ -2092,7 +2169,12 @@ export interface JsonSchema<OUT = unknown> {
2092
2169
  minProperties?: number
2093
2170
  maxProperties?: number
2094
2171
 
2095
- default?: OUT
2172
+ default?: unknown
2173
+ /**
2174
+ * Examples of a valid input value.
2175
+ * Annotation only (not validated), lets consumers generate e.g a mock value.
2176
+ */
2177
+ examples?: unknown[]
2096
2178
 
2097
2179
  // https://json-schema.org/understanding-json-schema/reference/conditionals.html#id6
2098
2180
  if?: JsonSchema
@@ -2131,6 +2213,11 @@ export interface JsonSchema<OUT = unknown> {
2131
2213
  * Annotation only (not validated), lets consumers render `1` as e.g `PREVENT`.
2132
2214
  */
2133
2215
  enumNames?: readonly string[]
2216
+ /**
2217
+ * The enum whose values are the keys of the object, as `j.enum` builds it. Set by `j.object.withEnumKeys`.
2218
+ * Annotation only (not validated), lets consumers render the key `1` as e.g `PREVENT`.
2219
+ */
2220
+ enumKeys?: JsonSchema
2134
2221
 
2135
2222
  hasIsOfTypeCheck?: boolean
2136
2223
 
@@ -13,6 +13,7 @@ export const JSON_SCHEMA_ORDER: readonly string[] = [
13
13
  'writeOnly',
14
14
  'type',
15
15
  'default',
16
+ 'examples',
16
17
  // Object,
17
18
  'properties',
18
19
  'required',
@@ -68,6 +69,7 @@ export function mergeJsonSchemaObjects<T1 extends AnyObject, T2 extends AnyObjec
68
69
 
69
70
  s1.propertyNames = s2.propertyNames || s1.propertyNames
70
71
  s1.keySchema = s2.keySchema || s1.keySchema
72
+ s1.enumKeys = s2.enumKeys || s1.enumKeys
71
73
  s1.minProperties = s2.minProperties ?? s1.minProperties
72
74
  s1.maxProperties = s2.maxProperties ?? s1.maxProperties
73
75