@naturalcycles/nodejs-lib 15.142.0 → 15.144.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.
@@ -336,6 +336,11 @@ export function createAjv(opt) {
336
336
  keyword: 'enumNames',
337
337
  schemaType: 'array',
338
338
  });
339
+ // Annotation only (the keys are validated by `properties`), registered so strict mode doesn't reject it
340
+ ajv.addKeyword({
341
+ keyword: 'enumKeys',
342
+ schemaType: 'object',
343
+ });
339
344
  // Annotation only (validated by the custom keywords, e.g `IsoDate`).
340
345
  // `true` makes Ajv skip the format check, while unknown formats would throw in strict mode.
341
346
  for (const format of jFormats) {
@@ -385,6 +385,22 @@ export declare class JObject<OUT extends AnyObject, Opt extends boolean = false>
385
385
  minProperties(minProperties: number): this;
386
386
  maxProperties(maxProperties: number): this;
387
387
  exclusiveProperties(propNames: readonly (keyof OUT & string)[]): this;
388
+ /**
389
+ * For an object that uses values of an enum as keys, with a different schema per key.
390
+ * Keeps the names of those keys in the built schema.
391
+ *
392
+ * ```
393
+ * const schema = j
394
+ * .object<Settings>({
395
+ * [Color.RED]: j.boolean(),
396
+ * [Color.BLUE]: j.array(j.string()),
397
+ * })
398
+ * .enumKeys(Color)
399
+ * ```
400
+ *
401
+ * When every key has the same schema, prefer `j.object.withEnumKeys`!
402
+ */
403
+ enumKeys(keyEnum: StringEnum | NumberEnum | JEnum<any, any>): this;
388
404
  }
389
405
  interface JObjectOpts {
390
406
  hasIsOfTypeCheck?: false;
@@ -437,6 +453,14 @@ declare class JSet2Builder<OUT, Opt> extends JBuilder<Set2<OUT>, Opt> {
437
453
  }
438
454
  export declare class JEnum<OUT extends string | number | boolean | null, Opt extends boolean = false> extends JBuilder<OUT, Opt> {
439
455
  constructor(enumValues: readonly OUT[], baseType: EnumBaseType, opt?: JsonBuilderRuleOpt, enumNames?: readonly string[]);
456
+ /**
457
+ * Keeps only the listed values of the enum.
458
+ *
459
+ * ```
460
+ * const schema = j.enum(Color).only([Color.RED, Color.BLUE])
461
+ * ```
462
+ */
463
+ only<const U extends OUT>(values: readonly U[]): JEnum<U, Opt>;
440
464
  branded<B extends OUT>(): JEnum<B, Opt>;
441
465
  }
442
466
  export declare class JTuple<ITEMS extends JSchema<any, any>[]> extends JBuilder<TupleOut<ITEMS>, false> {
@@ -473,6 +497,11 @@ declare function withEnumKeys<const T extends readonly (string | number)[] | Str
473
497
  } : {
474
498
  [P in K]: SchemaOut<S>;
475
499
  }, false>;
500
+ declare function withEnumKeys<K extends string | number, S extends JSchema<any, any>, Opt extends boolean = SchemaOpt<S>>(keys: JEnum<K, any>, schema: S): JObject<Opt extends true ? {
501
+ [P in `${K}`]?: SchemaOut<S>;
502
+ } : {
503
+ [P in `${K}`]: SchemaOut<S>;
504
+ }, false>;
476
505
  /**
477
506
  * On creation - compiles ajv validation function.
478
507
  * Provides convenient methods, error reporting, etc.
@@ -613,6 +642,11 @@ export interface JsonSchema<OUT = unknown> {
613
642
  * Annotation only (not validated), lets consumers render `1` as e.g `PREVENT`.
614
643
  */
615
644
  enumNames?: readonly string[];
645
+ /**
646
+ * The enum whose values are the keys of the object, as `j.enum` builds it. Set by `j.object.withEnumKeys`.
647
+ * Annotation only (not validated), lets consumers render the key `1` as e.g `PREVENT`.
648
+ */
649
+ enumKeys?: JsonSchema;
616
650
  hasIsOfTypeCheck?: boolean;
617
651
  email?: JsonSchemaStringEmailOptions;
618
652
  Set2?: JsonSchema;
@@ -1,4 +1,4 @@
1
- import { _isObject, _isUndefined, _numberEnumValues, _stringEnumValues, getEnumType, } from '@naturalcycles/js-lib';
1
+ import { _isObject, _isUndefined, _stringEnumValues, getEnumType } from '@naturalcycles/js-lib';
2
2
  import { _uniq } from '@naturalcycles/js-lib/array';
3
3
  import { _assert, _try } from '@naturalcycles/js-lib/error';
4
4
  import { _deepCopy, _filterNullishValues, _sortObject } from '@naturalcycles/js-lib/object';
@@ -890,6 +890,28 @@ export class JObject extends JBuilder {
890
890
  const exclusiveProperties = this.schema.exclusiveProperties ?? [];
891
891
  return this.cloneAndUpdateSchema({ exclusiveProperties: [...exclusiveProperties, propNames] });
892
892
  }
893
+ /**
894
+ * For an object that uses values of an enum as keys, with a different schema per key.
895
+ * Keeps the names of those keys in the built schema.
896
+ *
897
+ * ```
898
+ * const schema = j
899
+ * .object<Settings>({
900
+ * [Color.RED]: j.boolean(),
901
+ * [Color.BLUE]: j.array(j.string()),
902
+ * })
903
+ * .enumKeys(Color)
904
+ * ```
905
+ *
906
+ * When every key has the same schema, prefer `j.object.withEnumKeys`!
907
+ */
908
+ enumKeys(keyEnum) {
909
+ const properties = this.schema.properties ?? {};
910
+ const keyEnumSchema = keyEnum instanceof JEnum ? keyEnum : j.enum(keyEnum);
911
+ const enumValues = keyEnumSchema.build().enum;
912
+ const keys = enumValues.filter(value => Object.hasOwn(properties, String(value)));
913
+ return this.cloneAndUpdateSchema({ enumKeys: keyEnumSchema.only(keys).build() });
914
+ }
893
915
  }
894
916
  export class JObjectInfer extends JBuilder {
895
917
  constructor(props) {
@@ -992,6 +1014,24 @@ export class JEnum extends JBuilder {
992
1014
  if (opt?.msg)
993
1015
  this.setErrorMessage('enum', opt.msg);
994
1016
  }
1017
+ /**
1018
+ * Keeps only the listed values of the enum.
1019
+ *
1020
+ * ```
1021
+ * const schema = j.enum(Color).only([Color.RED, Color.BLUE])
1022
+ * ```
1023
+ */
1024
+ only(values) {
1025
+ const enumValues = this.schema.enum;
1026
+ const listedValues = values;
1027
+ const unknownValues = listedValues.filter(value => !enumValues.includes(value));
1028
+ _assert(!unknownValues.length, `Values are not in the enum: ${unknownValues.join(', ')}`);
1029
+ const isListed = enumValues.map(value => listedValues.includes(value));
1030
+ return this.cloneAndUpdateSchema({
1031
+ enum: enumValues.filter((_, index) => isListed[index]),
1032
+ enumNames: this.schema.enumNames?.filter((_, index) => isListed[index]),
1033
+ });
1034
+ }
995
1035
  branded() {
996
1036
  return this;
997
1037
  }
@@ -1048,29 +1088,24 @@ function withRegexKeys(keyRegex, schema) {
1048
1088
  },
1049
1089
  });
1050
1090
  }
1051
- /**
1052
- * Builds the object schema with the indicated `keys` and uses the `schema` for their validation.
1053
- */
1054
1091
  function withEnumKeys(keys, schema) {
1055
- let enumValues;
1056
- if (Array.isArray(keys)) {
1057
- _assert(isEveryItemPrimitive(keys), 'Every item in the key list should be string, number or symbol');
1058
- enumValues = keys;
1092
+ let keyEnum;
1093
+ if (keys instanceof JEnum) {
1094
+ keyEnum = keys;
1095
+ }
1096
+ else if (Array.isArray(keys)) {
1097
+ keyEnum = j.enum(keys);
1059
1098
  }
1060
1099
  else if (typeof keys === 'object') {
1061
1100
  const enumType = getEnumType(keys);
1062
1101
  _assert(enumType === 'NumberEnum' || enumType === 'StringEnum', 'The key list should be StringEnum or NumberEnum');
1063
- if (enumType === 'NumberEnum') {
1064
- enumValues = _numberEnumValues(keys);
1065
- }
1066
- else if (enumType === 'StringEnum') {
1067
- enumValues = _stringEnumValues(keys);
1068
- }
1102
+ keyEnum = j.enum(keys);
1069
1103
  }
1070
- _assert(enumValues, 'The key list should be an array of values, NumberEnum or a StringEnum');
1071
- const typedValues = enumValues;
1072
- const props = Object.fromEntries(typedValues.map(key => [key, schema]));
1073
- return new JObject(props, { hasIsOfTypeCheck: false });
1104
+ _assert(keyEnum, 'The key list should be an array of values, NumberEnum or a StringEnum');
1105
+ const keyValues = keyEnum.build().enum;
1106
+ _assert(isEveryItemPrimitive(keyValues), 'Every item in the key list should be string, number or symbol');
1107
+ const props = Object.fromEntries(keyValues.map(key => [key, schema]));
1108
+ return new JObject(props, { hasIsOfTypeCheck: false }).enumKeys(keyEnum);
1074
1109
  }
1075
1110
  // ==== AjvSchema compat wrapper ====
1076
1111
  /**
@@ -58,6 +58,7 @@ export function mergeJsonSchemaObjects(schema1, schema2) {
58
58
  }
59
59
  s1.propertyNames = s2.propertyNames || s1.propertyNames;
60
60
  s1.keySchema = s2.keySchema || s1.keySchema;
61
+ s1.enumKeys = s2.enumKeys || s1.enumKeys;
61
62
  s1.minProperties = s2.minProperties ?? s1.minProperties;
62
63
  s1.maxProperties = s2.maxProperties ?? s1.maxProperties;
63
64
  // Merge `required`
@@ -12,6 +12,8 @@ declare class Zip2 {
12
12
  */
13
13
  decompressZstdOrInflate(buf: Uint8Array): Promise<Buffer<ArrayBuffer>>;
14
14
  decompressZstdOrInflateSync(buf: Uint8Array): Buffer<ArrayBuffer>;
15
+ autoDecompressToStringSync(buf: Uint8Array): string;
16
+ autoDecompressSync(buf: Uint8Array): Buffer;
15
17
  /**
16
18
  * deflateBuffer uses `deflate`.
17
19
  * It's 9 bytes shorter than `gzip`.
package/dist/zip/zip2.js CHANGED
@@ -32,6 +32,16 @@ class Zip2 {
32
32
  }
33
33
  return zlib.inflateSync(buf);
34
34
  }
35
+ autoDecompressToStringSync(buf) {
36
+ return this.autoDecompressSync(buf).toString();
37
+ }
38
+ autoDecompressSync(buf) {
39
+ if (this.isZstdBuffer(buf))
40
+ return zlib.zstdDecompressSync(buf);
41
+ if (this.isGzipBuffer(buf))
42
+ return zlib.gunzipSync(buf);
43
+ return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
44
+ }
35
45
  /**
36
46
  * deflateBuffer uses `deflate`.
37
47
  * It's 9 bytes shorter than `gzip`.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@naturalcycles/nodejs-lib",
3
3
  "type": "module",
4
- "version": "15.142.0",
4
+ "version": "15.144.0",
5
5
  "dependencies": {
6
6
  "@naturalcycles/js-lib": "^15",
7
7
  "@standard-schema/spec": "^1",
@@ -14,7 +14,7 @@
14
14
  "yaml": "^2"
15
15
  },
16
16
  "devDependencies": {
17
- "@naturalcycles/dev-lib": "20.72.0",
17
+ "@naturalcycles/dev-lib": "0.0.0",
18
18
  "typescript": "^7"
19
19
  },
20
20
  "exports": {
@@ -391,6 +391,12 @@ export function createAjv(opt?: Options): Ajv2020 {
391
391
  schemaType: 'array',
392
392
  })
393
393
 
394
+ // Annotation only (the keys are validated by `properties`), registered so strict mode doesn't reject it
395
+ ajv.addKeyword({
396
+ keyword: 'enumKeys',
397
+ schemaType: 'object',
398
+ })
399
+
394
400
  // Annotation only (validated by the custom keywords, e.g `IsoDate`).
395
401
  // `true` makes Ajv skip the format check, while unknown formats would throw in strict mode.
396
402
  for (const format of jFormats) {
@@ -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'
@@ -1204,6 +1198,30 @@ export class JObject<OUT extends AnyObject, Opt extends boolean = false> extends
1204
1198
  const exclusiveProperties = this.schema.exclusiveProperties ?? []
1205
1199
  return this.cloneAndUpdateSchema({ exclusiveProperties: [...exclusiveProperties, propNames] })
1206
1200
  }
1201
+
1202
+ /**
1203
+ * For an object that uses values of an enum as keys, with a different schema per key.
1204
+ * Keeps the names of those keys in the built schema.
1205
+ *
1206
+ * ```
1207
+ * const schema = j
1208
+ * .object<Settings>({
1209
+ * [Color.RED]: j.boolean(),
1210
+ * [Color.BLUE]: j.array(j.string()),
1211
+ * })
1212
+ * .enumKeys(Color)
1213
+ * ```
1214
+ *
1215
+ * When every key has the same schema, prefer `j.object.withEnumKeys`!
1216
+ */
1217
+ enumKeys(keyEnum: StringEnum | NumberEnum | JEnum<any, any>): this {
1218
+ const properties = this.schema.properties ?? {}
1219
+ const keyEnumSchema: JEnum<any, any> = keyEnum instanceof JEnum ? keyEnum : j.enum(keyEnum)
1220
+ const enumValues: readonly (string | number)[] = keyEnumSchema.build().enum
1221
+ const keys = enumValues.filter(value => Object.hasOwn(properties, String(value)))
1222
+
1223
+ return this.cloneAndUpdateSchema({ enumKeys: keyEnumSchema.only(keys).build() })
1224
+ }
1207
1225
  }
1208
1226
 
1209
1227
  interface JObjectOpts {
@@ -1387,6 +1405,28 @@ export class JEnum<
1387
1405
  if (opt?.msg) this.setErrorMessage('enum', opt.msg)
1388
1406
  }
1389
1407
 
1408
+ /**
1409
+ * Keeps only the listed values of the enum.
1410
+ *
1411
+ * ```
1412
+ * const schema = j.enum(Color).only([Color.RED, Color.BLUE])
1413
+ * ```
1414
+ */
1415
+ only<const U extends OUT>(values: readonly U[]): JEnum<U, Opt> {
1416
+ const enumValues: readonly OUT[] = this.schema.enum
1417
+ const listedValues: readonly OUT[] = values
1418
+
1419
+ const unknownValues = listedValues.filter(value => !enumValues.includes(value))
1420
+ _assert(!unknownValues.length, `Values are not in the enum: ${unknownValues.join(', ')}`)
1421
+
1422
+ const isListed = enumValues.map(value => listedValues.includes(value))
1423
+
1424
+ return this.cloneAndUpdateSchema({
1425
+ enum: enumValues.filter((_, index) => isListed[index]),
1426
+ enumNames: this.schema.enumNames?.filter((_, index) => isListed[index]),
1427
+ }) as any
1428
+ }
1429
+
1390
1430
  branded<B extends OUT>(): JEnum<B, Opt> {
1391
1431
  return this as any as JEnum<B, Opt>
1392
1432
  }
@@ -1525,36 +1565,47 @@ function withEnumKeys<
1525
1565
  >(
1526
1566
  keys: T,
1527
1567
  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
1568
+ ): JObject<Opt extends true ? { [P in K]?: SchemaOut<S> } : { [P in K]: SchemaOut<S> }, false>
1569
+ function withEnumKeys<
1570
+ K extends string | number,
1571
+ S extends JSchema<any, any>,
1572
+ Opt extends boolean = SchemaOpt<S>,
1573
+ >(
1574
+ keys: JEnum<K, any>,
1575
+ schema: S,
1576
+ ): JObject<
1577
+ Opt extends true ? { [P in `${K}`]?: SchemaOut<S> } : { [P in `${K}`]: SchemaOut<S> },
1578
+ false
1579
+ >
1580
+ function withEnumKeys(
1581
+ keys: readonly (string | number)[] | StringEnum | NumberEnum | JEnum<any, any>,
1582
+ schema: JSchema<any, any>,
1583
+ ): JObject<any, false> {
1584
+ let keyEnum: JEnum<any, any> | undefined
1585
+ if (keys instanceof JEnum) {
1586
+ keyEnum = keys
1587
+ } else if (Array.isArray(keys)) {
1588
+ keyEnum = j.enum(keys)
1536
1589
  } else if (typeof keys === 'object') {
1537
1590
  const enumType = getEnumType(keys)
1538
1591
  _assert(
1539
1592
  enumType === 'NumberEnum' || enumType === 'StringEnum',
1540
1593
  'The key list should be StringEnum or NumberEnum',
1541
1594
  )
1542
- if (enumType === 'NumberEnum') {
1543
- enumValues = _numberEnumValues(keys as NumberEnum)
1544
- } else if (enumType === 'StringEnum') {
1545
- enumValues = _stringEnumValues(keys as StringEnum)
1546
- }
1595
+ keyEnum = j.enum(keys)
1547
1596
  }
1548
1597
 
1549
- _assert(enumValues, 'The key list should be an array of values, NumberEnum or a StringEnum')
1598
+ _assert(keyEnum, 'The key list should be an array of values, NumberEnum or a StringEnum')
1599
+
1600
+ const keyValues: readonly unknown[] = keyEnum.build().enum
1601
+ _assert(
1602
+ isEveryItemPrimitive(keyValues),
1603
+ 'Every item in the key list should be string, number or symbol',
1604
+ )
1550
1605
 
1551
- const typedValues = enumValues as readonly K[]
1552
- const props = Object.fromEntries(typedValues.map(key => [key, schema])) as any
1606
+ const props = Object.fromEntries(keyValues.map(key => [key, schema]))
1553
1607
 
1554
- return new JObject<
1555
- Opt extends true ? { [P in K]?: SchemaOut<S> } : { [P in K]: SchemaOut<S> },
1556
- false
1557
- >(props, { hasIsOfTypeCheck: false })
1608
+ return new JObject(props, { hasIsOfTypeCheck: false }).enumKeys(keyEnum)
1558
1609
  }
1559
1610
 
1560
1611
  // ==== AjvSchema compat wrapper ====
@@ -2131,6 +2182,11 @@ export interface JsonSchema<OUT = unknown> {
2131
2182
  * Annotation only (not validated), lets consumers render `1` as e.g `PREVENT`.
2132
2183
  */
2133
2184
  enumNames?: readonly string[]
2185
+ /**
2186
+ * The enum whose values are the keys of the object, as `j.enum` builds it. Set by `j.object.withEnumKeys`.
2187
+ * Annotation only (not validated), lets consumers render the key `1` as e.g `PREVENT`.
2188
+ */
2189
+ enumKeys?: JsonSchema
2134
2190
 
2135
2191
  hasIsOfTypeCheck?: boolean
2136
2192
 
@@ -68,6 +68,7 @@ export function mergeJsonSchemaObjects<T1 extends AnyObject, T2 extends AnyObjec
68
68
 
69
69
  s1.propertyNames = s2.propertyNames || s1.propertyNames
70
70
  s1.keySchema = s2.keySchema || s1.keySchema
71
+ s1.enumKeys = s2.enumKeys || s1.enumKeys
71
72
  s1.minProperties = s2.minProperties ?? s1.minProperties
72
73
  s1.maxProperties = s2.maxProperties ?? s1.maxProperties
73
74
 
package/src/zip/zip2.ts CHANGED
@@ -42,6 +42,16 @@ class Zip2 {
42
42
  return zlib.inflateSync(buf)
43
43
  }
44
44
 
45
+ autoDecompressToStringSync(buf: Uint8Array): string {
46
+ return this.autoDecompressSync(buf).toString()
47
+ }
48
+
49
+ autoDecompressSync(buf: Uint8Array): Buffer {
50
+ if (this.isZstdBuffer(buf)) return zlib.zstdDecompressSync(buf)
51
+ if (this.isGzipBuffer(buf)) return zlib.gunzipSync(buf)
52
+ return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
53
+ }
54
+
45
55
  /**
46
56
  * deflateBuffer uses `deflate`.
47
57
  * It's 9 bytes shorter than `gzip`.