@travetto/schema 5.0.0-rc.8 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -63,28 +63,28 @@ User:
63
63
 
64
64
  ### Fields
65
65
  This schema provides a powerful base for data binding and validation at runtime. Additionally there may be types that cannot be detected, or some information that the programmer would like to override. Below are the supported field decorators:
66
- * [@Field](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L31) defines a field that will be serialized.
67
- * [@Required](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L71) defines a that field should be required
68
- * [@Enum](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L78) defines the allowable values that a field can have
69
- * [@Match](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L99) defines a regular expression that the field value should match
70
- * [@MinLength](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L107) enforces min length of a string
71
- * [@MaxLength](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L117) enforces max length of a string
72
- * [@Min](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L107) enforces min value for a date or a number
73
- * [@Max](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L117) enforces max value for a date or a number
74
- * [@Email](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L144) ensures string field matches basic email regex
75
- * [@Telephone](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L151) ensures string field matches basic telephone regex
76
- * [@Url](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L158) ensures string field matches basic url regex
77
- * [@Ignore](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L197) exclude from auto schema registration
78
- * [@Integer](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L172) ensures number passed in is only a whole number
79
- * [@Float](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L178) ensures number passed in allows fractional values
80
- * [@Currency](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L190) provides support for standard currency
81
- * [@Text](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L86) indicates that a field is expecting natural language input, not just discrete values
82
- * [@LongText](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L91) same as text, but expects longer form content
83
- * [@Readonly](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L58) defines a that field should not be bindable external to the class
84
- * [@Writeonly](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L52) defines a that field should not be exported in serialization, but that it can be bound to
85
- * [@Secret](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L64) marks a field as being sensitive. This is used by certain logging activities to ensure sensitive information is not logged out.
86
- * [@Specifier](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L206) attributes additional specifiers to a field, allowing for more specification beyond just the field's type.
87
- * [@SubTypeField](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L212) allows for promoting a given field as the owner of the sub type discriminator (defaults to `type`).
66
+ * [@Field](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L30) defines a field that will be serialized.
67
+ * [@Required](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L70) defines a that field should be required
68
+ * [@Enum](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L77) defines the allowable values that a field can have
69
+ * [@Match](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L98) defines a regular expression that the field value should match
70
+ * [@MinLength](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L106) enforces min length of a string
71
+ * [@MaxLength](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L116) enforces max length of a string
72
+ * [@Min](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L106) enforces min value for a date or a number
73
+ * [@Max](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L116) enforces max value for a date or a number
74
+ * [@Email](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L143) ensures string field matches basic email regex
75
+ * [@Telephone](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L150) ensures string field matches basic telephone regex
76
+ * [@Url](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L157) ensures string field matches basic url regex
77
+ * [@Ignore](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L196) exclude from auto schema registration
78
+ * [@Integer](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L171) ensures number passed in is only a whole number
79
+ * [@Float](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L177) ensures number passed in allows fractional values
80
+ * [@Currency](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L189) provides support for standard currency
81
+ * [@Text](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L85) indicates that a field is expecting natural language input, not just discrete values
82
+ * [@LongText](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L90) same as text, but expects longer form content
83
+ * [@Readonly](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L57) defines a that field should not be bindable external to the class
84
+ * [@Writeonly](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L51) defines a that field should not be exported in serialization, but that it can be bound to
85
+ * [@Secret](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L63) marks a field as being sensitive. This is used by certain logging activities to ensure sensitive information is not logged out.
86
+ * [@Specifier](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L205) attributes additional specifiers to a field, allowing for more specification beyond just the field's type.
87
+ * [@SubTypeField](https://github.com/travetto/travetto/tree/main/module/schema/src/decorator/field.ts#L211) allows for promoting a given field as the owner of the sub type discriminator (defaults to `type`).
88
88
  Additionally, schemas can be nested to form more complex data structures that are able to bound and validated.
89
89
 
90
90
  Just like the class, all fields can be defined with
@@ -312,7 +312,7 @@ This feature is meant to allow for simple Typescript types to be able to be back
312
312
 
313
313
  **Code: Simple Custom Type**
314
314
  ```typescript
315
- import { DataUtil } from '@travetto/runtime';
315
+ import { DataUtil } from '@travetto/schema';
316
316
 
317
317
  /**
318
318
  * @concrete #PointImpl
@@ -329,7 +329,8 @@ export class PointImpl {
329
329
 
330
330
  static bindSchema(input: unknown): [number, number] | typeof INVALID | undefined {
331
331
  if (Array.isArray(input) && input.length === 2) {
332
- return input.map(x => DataUtil.coerceType(x, Number, false)) as [number, number];
332
+ const [a, b] = input.map(x => DataUtil.coerceType(x, Number, false));
333
+ return [a, b];
333
334
  } else {
334
335
  return INVALID;
335
336
  }
@@ -378,7 +379,7 @@ Validation Failed {
378
379
  ```
379
380
 
380
381
  ## Data Utilities
381
- Data utilities for binding values, and type conversion. Currently [DataUtil](https://github.com/travetto/travetto/tree/main/module/schema/src/data.ts#L10) includes:
382
+ Data utilities for binding values, and type conversion. Currently [DataUtil](https://github.com/travetto/travetto/tree/main/module/schema/src/data.ts#L11) includes:
382
383
  * `deepAssign(a, b, mode ?)` which allows for deep assignment of `b` onto `a`, the `mode` determines how aggressive the assignment is, and how flexible it is. `mode` can have any of the following values:
383
384
  * `loose`, which is the default is the most lenient. It will not error out, and overwrites will always happen
384
385
  * `coerce`, will attempt to force values from `b` to fit the types of `a`, and if it can't it will error out
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@travetto/schema",
3
- "version": "5.0.0-rc.8",
3
+ "version": "5.0.0",
4
4
  "description": "Data type registry for runtime validation, reflection and binding.",
5
5
  "keywords": [
6
6
  "schema",
@@ -27,10 +27,10 @@
27
27
  "directory": "module/schema"
28
28
  },
29
29
  "dependencies": {
30
- "@travetto/registry": "^5.0.0-rc.8"
30
+ "@travetto/registry": "^5.0.0"
31
31
  },
32
32
  "peerDependencies": {
33
- "@travetto/transformer": "^5.0.0-rc.5"
33
+ "@travetto/transformer": "^5.0.0"
34
34
  },
35
35
  "peerDependenciesMeta": {
36
36
  "@travetto/transformer": {
package/src/bind-util.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Class, ConcreteClass, TypedObject } from '@travetto/runtime';
1
+ import { castTo, Class, classConstruct, asFull, TypedObject, castKey } from '@travetto/runtime';
2
2
 
3
3
  import { DataUtil } from './data';
4
4
  import { AllViewⲐ } from './internal/types';
@@ -11,6 +11,10 @@ type BindConfig = {
11
11
  filterValue?: (value: unknown, field: FieldConfig) => boolean;
12
12
  };
13
13
 
14
+ function isInstance<T>(o: unknown): o is T {
15
+ return !!o && !DataUtil.isPrimitive(o);
16
+ }
17
+
14
18
  /**
15
19
  * Utilities for binding objects to schemas
16
20
  */
@@ -35,8 +39,7 @@ export class BindUtil {
35
39
  }
36
40
  }
37
41
  }
38
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
39
- return val as T;
42
+ return castTo(val);
40
43
  }
41
44
 
42
45
  /**
@@ -64,13 +67,11 @@ export class BindUtil {
64
67
  if (!(name in sub)) {
65
68
  sub[name] = typeof key === 'number' ? [] : {};
66
69
  }
67
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
68
- sub = sub[name] as Record<string, unknown>;
70
+ sub = castTo(sub[name]);
69
71
 
70
72
  if (idx && key !== undefined) {
71
73
  sub[key] ??= {};
72
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
73
- sub = sub[key] as Record<string, unknown>;
74
+ sub = castTo(sub[key]);
74
75
  }
75
76
  }
76
77
 
@@ -89,11 +90,9 @@ export class BindUtil {
89
90
  let key = (/^\d+$/.test(idx) ? parseInt(idx, 10) : (idx.trim() || undefined));
90
91
  sub[name] ??= (typeof key === 'string') ? {} : [];
91
92
 
92
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
93
- const arrSub = sub[name] as Record<string, unknown>;
93
+ const arrSub: Record<string, unknown> & { length: number } = castTo(sub[name]);
94
94
  if (key === undefined) {
95
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
96
- key = arrSub.length as number;
95
+ key = arrSub.length;
97
96
  }
98
97
  if (arrSub[key] && DataUtil.isPlainObject(val) && DataUtil.isPlainObject(arrSub[key])) {
99
98
  arrSub[key] = DataUtil.deepAssign(arrSub[key], val, 'coerce');
@@ -127,8 +126,7 @@ export class BindUtil {
127
126
  }
128
127
  }
129
128
  } else {
130
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
131
- out[pre] = (value ?? '') as V;
129
+ out[pre] = castTo(value ?? '');
132
130
  }
133
131
  }
134
132
  return out;
@@ -147,24 +145,19 @@ export class BindUtil {
147
145
  if (data === null || data === undefined) {
148
146
  return data;
149
147
  }
150
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
151
- const cls = SchemaRegistry.resolveInstanceType<T>(cons, data as T);
148
+ const cls = SchemaRegistry.resolveInstanceType<T>(cons, asFull<T>(data));
152
149
  if (data instanceof cls) {
153
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
154
- return data as T;
150
+ return castTo(data);
155
151
  } else {
156
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
157
- const tgt = new (cls as ConcreteClass<T>)() as T;
158
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
159
- SchemaRegistry.ensureInstanceTypeField(cls, tgt as T & { type?: string });
152
+ const tgt = classConstruct<T & { type?: string }>(cls);
153
+ SchemaRegistry.ensureInstanceTypeField(cls, tgt);
160
154
 
161
155
  for (const k of TypedObject.keys(tgt)) { // Do not retain undefined fields
162
156
  if (tgt[k] === undefined) {
163
157
  delete tgt[k];
164
158
  }
165
159
  }
166
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
167
- return this.bindSchemaToObject(cls, tgt, data as object, cfg);
160
+ return this.bindSchemaToObject(cls, tgt, data, cfg);
168
161
  }
169
162
  }
170
163
 
@@ -179,14 +172,13 @@ export class BindUtil {
179
172
  const view = cfg.view ?? AllViewⲐ; // Does not convey
180
173
  delete cfg.view;
181
174
 
182
- if (!!data && !DataUtil.isPrimitive(data)) {
175
+ if (!!data && isInstance<T>(data)) {
183
176
  const conf = SchemaRegistry.get(cons);
184
177
 
185
178
  // If no configuration
186
179
  if (!conf) {
187
180
  for (const k of TypedObject.keys(data)) {
188
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
189
- obj[k] = data[k as keyof typeof data];
181
+ obj[k] = data[k];
190
182
  }
191
183
  } else {
192
184
 
@@ -217,8 +209,7 @@ export class BindUtil {
217
209
  continue;
218
210
  }
219
211
 
220
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
221
- let v: unknown = data[inboundField as keyof typeof data];
212
+ let v: unknown = data[castKey<T>(inboundField)];
222
213
 
223
214
  // Filtering values
224
215
  if (cfg.filterValue && !cfg.filterValue(v, field)) {
@@ -248,8 +239,7 @@ export class BindUtil {
248
239
  }
249
240
  }
250
241
 
251
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
252
- obj[schemaFieldName as keyof typeof obj] = v as (typeof obj)[keyof typeof obj];
242
+ obj[castKey<T>(schemaFieldName)] = castTo(v);
253
243
 
254
244
  if (field.accessor) {
255
245
  Object.defineProperty(obj, schemaFieldName, {
package/src/data.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { isNumberObject as isNum, isBooleanObject as isBool, isStringObject as isStr } from 'node:util/types';
2
2
 
3
- import { Class, ClassInstance, TypedObject } from '@travetto/runtime';
3
+ import { asConstructable, castTo, Class, asFull, TypedObject } from '@travetto/runtime';
4
+ import { UnknownType } from './internal/types';
4
5
 
5
6
  const REGEX_PAT = /[\/](.*)[\/](i|g|m|s)?/;
6
7
 
@@ -62,15 +63,13 @@ export class DataUtil {
62
63
  if (isArrA !== isArrB || isSimpA !== isSimpB) {
63
64
  throw new Error(`Cannot merge differing types ${a} and ${b}`);
64
65
  }
65
- if (isArrB) { // Arrays
66
+ if (Array.isArray(b)) { // Arrays
66
67
  ret = a; // Write onto A
67
68
  if (mode === 'replace') {
68
69
  ret = b;
69
70
  } else {
70
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
71
- const retArr = ret as unknown[];
72
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
73
- const bArr = b as unknown[];
71
+ const retArr: unknown[] = castTo(ret);
72
+ const bArr = b;
74
73
  for (let i = 0; i < bArr.length; i++) {
75
74
  retArr[i] = this.#deepAssignRaw(retArr[i], bArr[i], mode);
76
75
  }
@@ -83,16 +82,13 @@ export class DataUtil {
83
82
  if (mode === 'strict') { // Bail on strict
84
83
  throw new Error(`Cannot merge ${a} [${typeof a}] with ${b} [${typeof b}]`);
85
84
  } else if (mode === 'coerce') { // Force on coerce
86
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
87
- ret = this.coerceType(b, (a as ClassInstance).constructor, false);
85
+ ret = this.coerceType(b, asConstructable(a).constructor, false);
88
86
  }
89
87
  }
90
88
  } else { // Object merge
91
89
  ret = a;
92
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
93
- const bObj = b as Record<string, unknown>;
94
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
95
- const retObj = ret as Record<string, unknown>;
90
+ const bObj: Record<string, unknown> = castTo(b);
91
+ const retObj: Record<string, unknown> = castTo(ret);
96
92
 
97
93
  for (const key of Object.keys(bObj)) {
98
94
  retObj[key] = this.#deepAssignRaw(retObj[key], bObj[key], mode);
@@ -125,11 +121,13 @@ export class DataUtil {
125
121
  */
126
122
  static coerceType(input: unknown, type: typeof String, strict?: boolean): string;
127
123
  static coerceType(input: unknown, type: typeof Number, strict?: boolean): number;
124
+ static coerceType(input: unknown, type: typeof BigInt, strict?: boolean): bigint;
128
125
  static coerceType(input: unknown, type: typeof Boolean, strict?: boolean): boolean;
129
126
  static coerceType(input: unknown, type: typeof Date, strict?: boolean): Date;
130
127
  static coerceType(input: unknown, type: typeof RegExp, strict?: boolean): RegExp;
131
- static coerceType<T>(input: unknown, type: Class<T>, strict?: boolean): T;
132
- static coerceType(input: unknown, type: Class<unknown>, strict = true): unknown {
128
+ static coerceType(input: unknown, type: typeof UnknownType, strict?: boolean): unknown;
129
+ static coerceType<T>(input: unknown, type: Class<T> | Function, strict?: boolean): T;
130
+ static coerceType(input: unknown, type: Class<unknown> | Function, strict = true): unknown {
133
131
  // Do nothing
134
132
  if (input === null || input === undefined) {
135
133
  return input;
@@ -143,14 +141,17 @@ export class DataUtil {
143
141
  case Date: {
144
142
  let res: Date | undefined;
145
143
  if (typeof input === 'object' && 'toDate' in input && typeof input.toDate === 'function') {
146
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
147
- res = input.toDate() as Date;
144
+ res = castTo(input.toDate());
148
145
  } else {
149
- res = typeof input === 'number' || /^[-]?\d+$/.test(`${input}`) ?
150
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
151
- new Date(parseInt(input as string, 10)) : new Date(input as Date);
146
+ res = input instanceof Date ?
147
+ input :
148
+ typeof input === 'number' ?
149
+ new Date(input) :
150
+ (typeof input === 'string' && /^[-]?\d+$/.test(input)) ?
151
+ new Date(parseInt(input, 10)) :
152
+ new Date(input.toString());
152
153
  }
153
- if (strict && Number.isNaN(res.getTime())) {
154
+ if (strict && res && Number.isNaN(res.getTime())) {
154
155
  throw new Error(`Invalid date value: ${input}`);
155
156
  }
156
157
  return res;
@@ -162,6 +163,20 @@ export class DataUtil {
162
163
  }
163
164
  return res;
164
165
  }
166
+ case BigInt: {
167
+ if (typeof input === 'bigint') {
168
+ return input;
169
+ }
170
+ try {
171
+ return BigInt((typeof input === 'boolean' || typeof input === 'number') ?
172
+ input : `${input}`.replace(/n$/i, ''));
173
+ } catch {
174
+ if (strict) {
175
+ throw new Error(`Invalid numeric value: ${input}`);
176
+ }
177
+ return;
178
+ }
179
+ }
165
180
  case Boolean: {
166
181
  const match = `${input}`.match(/^((?<TRUE>true|yes|1|on)|false|no|off|0)$/i);
167
182
  if (strict && !match) {
@@ -186,6 +201,9 @@ export class DataUtil {
186
201
  return;
187
202
  }
188
203
  }
204
+ case UnknownType: {
205
+ return input;
206
+ }
189
207
  case Object: {
190
208
  if (!strict || this.isPlainObject(input)) {
191
209
  return input;
@@ -207,9 +225,8 @@ export class DataUtil {
207
225
  * Clone top level properties to a new object
208
226
  * @param o Object to clone
209
227
  */
210
- static shallowClone<T = unknown>(a: T): T {
211
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
212
- return (Array.isArray(a) ? a.slice(0) : (this.isSimpleValue(a) ? a : { ...(a as {}) })) as T;
228
+ static shallowClone<T>(a: T): T {
229
+ return castTo(Array.isArray(a) ? a.slice(0) : (this.isSimpleValue(a) ? a : { ...castTo<object>(a) }));
213
230
  }
214
231
 
215
232
  /**
@@ -222,8 +239,7 @@ export class DataUtil {
222
239
  if (!a || this.isSimpleValue(a)) {
223
240
  throw new Error(`Cannot merge onto a simple value, ${a}`);
224
241
  }
225
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
226
- return this.#deepAssignRaw(a, b, mode) as T & U;
242
+ return castTo(this.#deepAssignRaw(a, b, mode));
227
243
  }
228
244
 
229
245
  /**
@@ -245,8 +261,7 @@ export class DataUtil {
245
261
  }
246
262
  }
247
263
  }
248
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
249
- return out as T;
264
+ return asFull(out);
250
265
  } else {
251
266
  return obj;
252
267
  }
@@ -1,15 +1,15 @@
1
- import { ClassInstance } from '@travetto/runtime';
1
+ import { Any, castTo, ClassInstance } from '@travetto/runtime';
2
2
 
3
3
  import { SchemaRegistry } from '../service/registry';
4
4
  import { CommonRegExp } from '../validate/regexp';
5
5
  import { ClassList, FieldConfig } from '../service/types';
6
6
 
7
- type PropType<V> = (<T extends Partial<Record<K, V>>, K extends string>(t: T, k: K, idx?: number) => void) & {
7
+ type PropType<V> = (<T extends Partial<Record<K, V>>, K extends string>(t: T, k: K, idx?: TypedPropertyDescriptor<Any> | number) => void) & {
8
8
  Param: (t: unknown, k: string, idx: number) => void;
9
9
  };
10
10
 
11
11
  function prop<V>(obj: Partial<FieldConfig>): PropType<V> {
12
- const fn = (t: ClassInstance, k: string, idx?: number): void => {
12
+ const fn = (t: ClassInstance, k: string, idx?: number | TypedPropertyDescriptor<Any>): void => {
13
13
  if (idx !== undefined && typeof idx === 'number') {
14
14
  SchemaRegistry.registerPendingParamFacet(t.constructor, k, idx, obj);
15
15
  } else {
@@ -18,8 +18,7 @@ function prop<V>(obj: Partial<FieldConfig>): PropType<V> {
18
18
  };
19
19
  fn.Param = fn;
20
20
 
21
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
22
- return fn as PropType<V>;
21
+ return castTo(fn);
23
22
  }
24
23
 
25
24
  /**
@@ -29,7 +28,7 @@ function prop<V>(obj: Partial<FieldConfig>): PropType<V> {
29
28
  * @augments `@travetto/schema:Field`
30
29
  */
31
30
  export function Field(type: ClassList, ...config: Partial<FieldConfig>[]) {
32
- return (f: ClassInstance, k: string, idx?: number): void => {
31
+ return (f: ClassInstance, k: string, idx?: number | TypedPropertyDescriptor<Any>): void => {
33
32
  if (idx !== undefined && typeof idx === 'number') {
34
33
  SchemaRegistry.registerPendingParamConfig(f.constructor, k, idx, type, Object.assign({}, ...config));
35
34
  } else {
@@ -1,4 +1,4 @@
1
- import { Class, DeepPartial } from '@travetto/runtime';
1
+ import { castTo, Class, DeepPartial } from '@travetto/runtime';
2
2
 
3
3
  import { BindUtil } from '../bind-util';
4
4
  import { SchemaRegistry } from '../service/registry';
@@ -28,8 +28,7 @@ export function Schema(cfg?: Partial<Pick<ClassConfig, 'subTypeName' | 'subTypeF
28
28
  */
29
29
  export function Validator<T>(fn: ValidatorFn<T, string>) {
30
30
  return (target: Class<T>): void => {
31
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
32
- SchemaRegistry.getOrCreatePending(target).validators!.push(fn as ValidatorFn<unknown, unknown>);
31
+ SchemaRegistry.getOrCreatePending(target).validators!.push(castTo(fn));
33
32
  };
34
33
  }
35
34
 
@@ -1 +1,2 @@
1
- export const AllViewⲐ: unique symbol = Symbol.for('@travetto/schema:all');
1
+ export const AllViewⲐ: unique symbol = Symbol.for('@travetto/schema:all');
2
+ export class UnknownType { }
@@ -1,4 +1,4 @@
1
- import { Class, AppError, describeFunction } from '@travetto/runtime';
1
+ import { Class, AppError, describeFunction, castTo, classConstruct, asFull, castKey } from '@travetto/runtime';
2
2
  import { MetadataRegistry, RootRegistry, ChangeEvent } from '@travetto/registry';
3
3
 
4
4
  import { ClassList, FieldConfig, ClassConfig, SchemaConfig, ViewFieldsConfig, ViewConfig } from './types';
@@ -51,8 +51,7 @@ class $SchemaRegistry extends MetadataRegistry<ClassConfig, FieldConfig> {
51
51
  */
52
52
  getMetadata<K>(cls: Class, key: symbol): K | undefined {
53
53
  const cfg = this.get(cls);
54
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
55
- return cfg.metadata?.[key] as K;
54
+ return castTo(cfg.metadata?.[key]);
56
55
  }
57
56
 
58
57
  /**
@@ -64,8 +63,7 @@ class $SchemaRegistry extends MetadataRegistry<ClassConfig, FieldConfig> {
64
63
  */
65
64
  getOrCreatePendingMetadata<K>(cls: Class, key: symbol, value: K): K {
66
65
  const cfg = this.getOrCreatePending(cls);
67
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
68
- return ((cfg.metadata ??= {})[key] ??= value) as K;
66
+ return castTo((cfg.metadata ??= {})[key] ??= value);
69
67
  }
70
68
 
71
69
  /**
@@ -73,11 +71,9 @@ class $SchemaRegistry extends MetadataRegistry<ClassConfig, FieldConfig> {
73
71
  */
74
72
  ensureInstanceTypeField<T>(cls: Class, o: T): void {
75
73
  const schema = this.get(cls);
76
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
77
- const typeField = (schema.subTypeField) as keyof T;
74
+ const typeField = castKey<T>(schema.subTypeField);
78
75
  if (schema.subTypeName && typeField in schema.views[AllViewⲐ].schema && !o[typeField]) { // Do we have a type field defined
79
- // @ts-expect-error
80
- o[typeField] = schema.subTypeName; // Assign if missing
76
+ o[typeField] = castTo(schema.subTypeName); // Assign if missing
81
77
  }
82
78
  }
83
79
 
@@ -112,11 +108,9 @@ class $SchemaRegistry extends MetadataRegistry<ClassConfig, FieldConfig> {
112
108
  const baseSchema = this.get(base);
113
109
 
114
110
  if (clsSchema.subTypeName || baseSchema.baseType) { // We have a sub type
115
- // @ts-expect-error
116
- const type = o[baseSchema.subTypeField] ?? clsSchema.subTypeName ?? baseSchema.subTypeName;
111
+ const type = castTo<string>(o[castKey<T>(baseSchema.subTypeField)]) ?? clsSchema.subTypeName ?? baseSchema.subTypeName;
117
112
  const ret = this.#subTypes.get(base)!.get(type)!;
118
- // @ts-expect-error
119
- if (ret && !(new ret() instanceof cls)) {
113
+ if (ret && !(classConstruct(ret) instanceof cls)) {
120
114
  throw new AppError(`Resolved class ${ret.name} is not assignable to ${cls.name}`);
121
115
  }
122
116
  return ret;
@@ -237,8 +231,7 @@ class $SchemaRegistry extends MetadataRegistry<ClassConfig, FieldConfig> {
237
231
  if (!this.#pendingViews.has(target)) {
238
232
  this.#pendingViews.set(target, new Map());
239
233
  }
240
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
241
- const generalConfig = fields as unknown as ViewFieldsConfig<unknown>;
234
+ const generalConfig: ViewFieldsConfig<unknown> = castTo(fields);
242
235
  this.#pendingViews.get(target)!.set(view, generalConfig);
243
236
  }
244
237
 
@@ -262,6 +255,9 @@ class $SchemaRegistry extends MetadataRegistry<ClassConfig, FieldConfig> {
262
255
  if (config.specifiers) {
263
256
  config.specifiers = [...params[idx]?.specifiers ?? [], ...config.specifiers];
264
257
  }
258
+ if (config.enum?.values) {
259
+ config.enum.values = config.enum.values.slice().sort();
260
+ }
265
261
 
266
262
  params[idx] = {
267
263
  // @ts-expect-error
@@ -286,8 +282,7 @@ class $SchemaRegistry extends MetadataRegistry<ClassConfig, FieldConfig> {
286
282
  if (!allViewConf.schema[prop]) {
287
283
  allViewConf.fields.push(prop);
288
284
  // Partial config while building
289
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
290
- allViewConf.schema[prop] = {} as FieldConfig;
285
+ allViewConf.schema[prop] = asFull<FieldConfig>({});
291
286
  }
292
287
  if (config.aliases) {
293
288
  config.aliases = [...allViewConf.schema[prop].aliases ?? [], ...config.aliases];
@@ -295,6 +290,9 @@ class $SchemaRegistry extends MetadataRegistry<ClassConfig, FieldConfig> {
295
290
  if (config.specifiers) {
296
291
  config.specifiers = [...allViewConf.schema[prop].specifiers ?? [], ...config.specifiers];
297
292
  }
293
+ if (config.enum?.values) {
294
+ config.enum.values = config.enum.values.slice().sort();
295
+ }
298
296
 
299
297
  Object.assign(allViewConf.schema[prop], config);
300
298
 
@@ -1,4 +1,4 @@
1
- import { Class, Primitive } from '@travetto/runtime';
1
+ import { Any, Class, Primitive } from '@travetto/runtime';
2
2
 
3
3
  import { AllViewⲐ } from '../internal/types';
4
4
  import { ValidatorFn } from '../validate/types';
@@ -65,7 +65,7 @@ export interface ClassConfig extends DescribableConfig {
65
65
  /**
66
66
  * Global validators
67
67
  */
68
- validators: ValidatorFn<unknown, unknown>[];
68
+ validators: ValidatorFn<Any, unknown>[];
69
69
  /**
70
70
  * Is the class a base type
71
71
  */
@@ -1,4 +1,4 @@
1
- import { Class, ClassInstance, TypedObject } from '@travetto/runtime';
1
+ import { castKey, castTo, Class, ClassInstance, TypedObject } from '@travetto/runtime';
2
2
 
3
3
  import { FieldConfig, SchemaConfig } from '../service/types';
4
4
  import { SchemaRegistry } from '../service/registry';
@@ -18,6 +18,14 @@ function resolveSchema<T>(base: Class<T>, o: T, view?: string): SchemaConfig {
18
18
  ).schema;
19
19
  }
20
20
 
21
+ function isClassInstance<T>(o: unknown): o is ClassInstance<T> {
22
+ return !DataUtil.isPlainObject(o) && o !== null && typeof o === 'object' && !!o.constructor;
23
+ }
24
+
25
+ function isRangeValue(o: unknown): o is number | string | Date {
26
+ return typeof o === 'string' || typeof o === 'number' || o instanceof Date;
27
+ }
28
+
21
29
  declare global {
22
30
  interface RegExp {
23
31
  name?: string;
@@ -42,8 +50,7 @@ export class SchemaValidator {
42
50
  const fields = TypedObject.keys<SchemaConfig>(schema);
43
51
  for (const field of fields) {
44
52
  if (schema[field].access !== 'readonly') { // Do not validate readonly fields
45
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
46
- errors = errors.concat(this.#validateFieldSchema(schema[field], o[field as keyof T], relative));
53
+ errors = errors.concat(this.#validateFieldSchema(schema[field], o[castKey<T>(field)], relative));
47
54
  }
48
55
  }
49
56
 
@@ -174,18 +181,15 @@ export class SchemaValidator {
174
181
  criteria.push(['maxlength', field.maxlength]);
175
182
  }
176
183
 
177
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
178
- if (field.enum && !field.enum.values.includes(value as string)) {
184
+ if (field.enum && !field.enum.values.includes(castTo(value))) {
179
185
  criteria.push(['enum', field.enum]);
180
186
  }
181
187
 
182
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
183
- if (field.min && this.#validateRange(field, 'min', value as number)) {
188
+ if (field.min && (!isRangeValue(value) || this.#validateRange(field, 'min', value))) {
184
189
  criteria.push(['min', field.min]);
185
190
  }
186
191
 
187
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
188
- if (field.max && this.#validateRange(field, 'max', value as number)) {
192
+ if (field.max && (!isRangeValue(value) || this.#validateRange(field, 'max', value))) {
189
193
  criteria.push(['max', field.max]);
190
194
  }
191
195
 
@@ -268,10 +272,8 @@ export class SchemaValidator {
268
272
  * @param view The optional view to limit the scope to
269
273
  */
270
274
  static async validate<T>(cls: Class<T>, o: T, view?: string): Promise<T> {
271
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
272
- if (!DataUtil.isPlainObject(o) && !(o instanceof cls || cls.Ⲑid === (o as ClassInstance<T>).constructor.Ⲑid)) {
273
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
274
- throw new TypeMismatchError(cls.name, (o as ClassInstance).constructor.name);
275
+ if (isClassInstance(o) && !(o instanceof cls || cls.Ⲑid === o.constructor.Ⲑid)) {
276
+ throw new TypeMismatchError(cls.name, o.constructor.name);
275
277
  }
276
278
  cls = SchemaRegistry.resolveInstanceType(cls, o);
277
279
 
@@ -1,12 +1,13 @@
1
1
  import ts from 'typescript';
2
2
  import {
3
3
  type AnyType, DeclarationUtil, LiteralUtil,
4
- DecoratorUtil, DocUtil, ParamDocumentation, TransformerState
4
+ DecoratorUtil, DocUtil, ParamDocumentation, TransformerState, transformCast
5
5
  } from '@travetto/transformer';
6
6
 
7
7
  const SCHEMA_MOD = '@travetto/schema/src/decorator/schema';
8
8
  const FIELD_MOD = '@travetto/schema/src/decorator/field';
9
9
  const COMMON_MOD = '@travetto/schema/src/decorator/common';
10
+ const TYPES_FILE = '@travetto/schema/src/internal/types';
10
11
 
11
12
  export class SchemaTransformUtil {
12
13
 
@@ -27,6 +28,10 @@ export class SchemaTransformUtil {
27
28
  }
28
29
  break;
29
30
  }
31
+ case 'unknown': {
32
+ const imp = state.importFile(TYPES_FILE);
33
+ return state.createAccess(imp.ident, 'UnknownType');
34
+ }
30
35
  case 'shape': {
31
36
  const uniqueId = state.generateUniqueIdentifier(node, type);
32
37
 
@@ -49,7 +54,7 @@ export class SchemaTransformUtil {
49
54
  this.computeField(state, state.factory.createPropertyDeclaration(
50
55
  [], k,
51
56
  v.undefinable || v.nullable ? state.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined,
52
- undefined, undefined
57
+ v.key === 'unknown' ? state.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword) : undefined, undefined
53
58
  ), { type: v, root })
54
59
  )
55
60
  );
@@ -70,7 +75,6 @@ export class SchemaTransformUtil {
70
75
  break;
71
76
  }
72
77
  case 'foreign':
73
- case 'unknown':
74
78
  default: {
75
79
  // Object
76
80
  }
@@ -126,8 +130,7 @@ export class SchemaTransformUtil {
126
130
  // If we have a union type
127
131
  if (primaryExpr.key === 'union') {
128
132
  const values = primaryExpr.subTypes.map(x => x.key === 'literal' ? x.value : undefined)
129
- .filter(x => x !== undefined && x !== null)
130
- .sort();
133
+ .filter(x => x !== undefined && x !== null);
131
134
 
132
135
  if (values.length === primaryExpr.subTypes.length) {
133
136
  attrs.push(state.factory.createPropertyAssignment('enum', state.fromLiteral({
@@ -183,6 +186,7 @@ export class SchemaTransformUtil {
183
186
  state.createDecorator(FIELD_MOD, 'Field', ...params)
184
187
  ];
185
188
 
189
+ let ret: unknown;
186
190
  if (ts.isPropertyDeclaration(node)) {
187
191
  const comments = DocUtil.describeDocs(node);
188
192
  if (comments.description) {
@@ -191,22 +195,19 @@ export class SchemaTransformUtil {
191
195
  })));
192
196
  }
193
197
 
194
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
195
- return state.factory.updatePropertyDeclaration(node as Exclude<typeof node, T>,
196
- newModifiers, node.name, node.questionToken, node.type, node.initializer) as T;
198
+ ret = state.factory.updatePropertyDeclaration(node,
199
+ newModifiers, node.name, node.questionToken, node.type, node.initializer);
197
200
  } else if (ts.isParameter(node)) {
198
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
199
- return state.factory.updateParameterDeclaration(node as Exclude<typeof node, T>,
200
- newModifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) as T;
201
+ ret = state.factory.updateParameterDeclaration(node,
202
+ newModifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer);
201
203
  } else if (ts.isGetAccessorDeclaration(node)) {
202
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
203
- return state.factory.updateGetAccessorDeclaration(node as Exclude<typeof node, T>,
204
- newModifiers, node.name, node.parameters, node.type, node.body) as T;
204
+ ret = state.factory.updateGetAccessorDeclaration(node,
205
+ newModifiers, node.name, node.parameters, node.type, node.body);
205
206
  } else {
206
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
207
- return state.factory.updateSetAccessorDeclaration(node as Exclude<typeof node, T>,
208
- newModifiers, node.name, node.parameters, node.body) as T;
207
+ ret = state.factory.updateSetAccessorDeclaration(node,
208
+ newModifiers, node.name, node.parameters, node.body);
209
209
  }
210
+ return transformCast(ret);
210
211
  }
211
212
 
212
213
  /**