@travetto/schema 7.0.0-rc.1 → 7.0.0-rc.3
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 +34 -34
- package/__index__.ts +3 -3
- package/package.json +3 -3
- package/src/bind-util.ts +90 -90
- package/src/data.ts +40 -39
- package/src/decorator/common.ts +5 -5
- package/src/decorator/field.ts +9 -7
- package/src/decorator/input.ts +28 -26
- package/src/decorator/method.ts +3 -1
- package/src/decorator/schema.ts +2 -2
- package/src/internal/types.ts +4 -4
- package/src/name.ts +3 -3
- package/src/service/registry-adapter.ts +64 -61
- package/src/service/registry-index.ts +18 -73
- package/src/service/types.ts +14 -18
- package/src/types.ts +1 -1
- package/src/validate/error.ts +2 -2
- package/src/validate/messages.ts +10 -10
- package/src/validate/regex.ts +22 -0
- package/src/validate/types.ts +4 -4
- package/src/validate/validator.ts +80 -80
- package/support/transformer/util.ts +29 -26
- package/support/transformer.schema.ts +7 -7
- package/src/service/changes.ts +0 -152
- package/src/validate/regexp.ts +0 -22
|
@@ -5,25 +5,25 @@ import { ValidationError, ValidationKindCore, ValidationResult } from './types.t
|
|
|
5
5
|
import { Messages } from './messages.ts';
|
|
6
6
|
import { isValidationError, TypeMismatchError, ValidationResultError } from './error.ts';
|
|
7
7
|
import { DataUtil } from '../data.ts';
|
|
8
|
-
import {
|
|
8
|
+
import { CommonRegexToName } from './regex.ts';
|
|
9
9
|
import { SchemaRegistryIndex } from '../service/registry-index.ts';
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Get the schema config for Class/Schema config, including support for polymorphism
|
|
13
13
|
* @param base The starting type or config
|
|
14
|
-
* @param
|
|
14
|
+
* @param item The item to use for the polymorphic check
|
|
15
15
|
*/
|
|
16
|
-
function resolveFieldMap<T>(base: Class<T>,
|
|
17
|
-
const target = SchemaRegistryIndex.resolveInstanceType(base,
|
|
16
|
+
function resolveFieldMap<T>(base: Class<T>, item: T): SchemaFieldMap {
|
|
17
|
+
const target = SchemaRegistryIndex.resolveInstanceType(base, item);
|
|
18
18
|
return SchemaRegistryIndex.get(target).getFields();
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
-
function isClassInstance<T>(
|
|
22
|
-
return !DataUtil.isPlainObject(
|
|
21
|
+
function isClassInstance<T>(value: unknown): value is ClassInstance<T> {
|
|
22
|
+
return !DataUtil.isPlainObject(value) && value !== null && typeof value === 'object' && !!value.constructor;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
function isRangeValue(
|
|
26
|
-
return typeof
|
|
25
|
+
function isRangeValue(value: unknown): value is number | string | Date {
|
|
26
|
+
return typeof value === 'string' || typeof value === 'number' || value instanceof Date;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
/**
|
|
@@ -35,15 +35,15 @@ export class SchemaValidator {
|
|
|
35
35
|
/**
|
|
36
36
|
* Validate the schema for a given object
|
|
37
37
|
* @param fields The config to validate against
|
|
38
|
-
* @param
|
|
38
|
+
* @param item The object to validate
|
|
39
39
|
* @param relative The relative path as the validation recurses
|
|
40
40
|
*/
|
|
41
|
-
static #validateFields<T>(fields: SchemaFieldMap,
|
|
41
|
+
static #validateFields<T>(fields: SchemaFieldMap, item: T, relative: string): ValidationError[] {
|
|
42
42
|
let errors: ValidationError[] = [];
|
|
43
43
|
|
|
44
44
|
for (const [field, fieldConfig] of TypedObject.entries(fields)) {
|
|
45
45
|
if (fieldConfig.access !== 'readonly') { // Do not validate readonly fields
|
|
46
|
-
errors = errors.concat(this.#validateInputSchema(fieldConfig,
|
|
46
|
+
errors = errors.concat(this.#validateInputSchema(fieldConfig, item[castKey<T>(field)], relative));
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
|
|
@@ -53,13 +53,13 @@ export class SchemaValidator {
|
|
|
53
53
|
/**
|
|
54
54
|
* Validate a single input config against a passed in value
|
|
55
55
|
* @param input The input schema configuration
|
|
56
|
-
* @param
|
|
56
|
+
* @param value The raw value, could be an array or not
|
|
57
57
|
* @param relative The relative path of object traversal
|
|
58
58
|
*/
|
|
59
|
-
static #validateInputSchema(input: SchemaInputConfig,
|
|
59
|
+
static #validateInputSchema(input: SchemaInputConfig, value: unknown, relative: string = ''): ValidationError[] {
|
|
60
60
|
const key = 'name' in input ? input.name : ('index' in input ? input.index : 'unknown');
|
|
61
61
|
const path = `${relative}${relative ? '.' : ''}${key}`;
|
|
62
|
-
const hasValue = !(
|
|
62
|
+
const hasValue = !(value === undefined || value === null || (typeof value === 'string' && value === '') || (Array.isArray(value) && value.length === 0));
|
|
63
63
|
|
|
64
64
|
if (!hasValue) {
|
|
65
65
|
if (input.required?.active !== false) {
|
|
@@ -75,26 +75,26 @@ export class SchemaValidator {
|
|
|
75
75
|
if (type === Object) {
|
|
76
76
|
return [];
|
|
77
77
|
} else if (array) {
|
|
78
|
-
if (!Array.isArray(
|
|
79
|
-
return this.#prepareErrors(path, [{ kind: 'type', type: Array, value
|
|
78
|
+
if (!Array.isArray(value)) {
|
|
79
|
+
return this.#prepareErrors(path, [{ kind: 'type', type: Array, value }]);
|
|
80
80
|
}
|
|
81
81
|
let errors: ValidationError[] = [];
|
|
82
82
|
if (complex) {
|
|
83
|
-
for (let i = 0; i <
|
|
84
|
-
const subErrors = this.#validateFields(resolveFieldMap(type,
|
|
83
|
+
for (let i = 0; i < value.length; i++) {
|
|
84
|
+
const subErrors = this.#validateFields(resolveFieldMap(type, value[i]), value[i], `${path}[${i}]`);
|
|
85
85
|
errors = errors.concat(subErrors);
|
|
86
86
|
}
|
|
87
87
|
} else {
|
|
88
|
-
for (let i = 0; i <
|
|
89
|
-
const subErrors = this.#validateInput(input,
|
|
88
|
+
for (let i = 0; i < value.length; i++) {
|
|
89
|
+
const subErrors = this.#validateInput(input, value[i]);
|
|
90
90
|
errors.push(...this.#prepareErrors(`${path}[${i}]`, subErrors));
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
93
|
return errors;
|
|
94
94
|
} else if (complex) {
|
|
95
|
-
return this.#validateFields(resolveFieldMap(type,
|
|
95
|
+
return this.#validateFields(resolveFieldMap(type, value), value, path);
|
|
96
96
|
} else {
|
|
97
|
-
const fieldErrors = this.#validateInput(input,
|
|
97
|
+
const fieldErrors = this.#validateInput(input, value);
|
|
98
98
|
return this.#prepareErrors(path, fieldErrors);
|
|
99
99
|
}
|
|
100
100
|
}
|
|
@@ -106,13 +106,13 @@ export class SchemaValidator {
|
|
|
106
106
|
* @param value The value to validate
|
|
107
107
|
*/
|
|
108
108
|
static #validateRange(input: SchemaInputConfig, key: 'min' | 'max', value: string | number | Date): boolean {
|
|
109
|
-
const
|
|
110
|
-
const
|
|
109
|
+
const config = input[key]!;
|
|
110
|
+
const parsed = (typeof value === 'string') ?
|
|
111
111
|
(input.type === Date ? Date.parse(value) : parseInt(value, 10)) :
|
|
112
112
|
(value instanceof Date ? value.getTime() : value);
|
|
113
113
|
|
|
114
|
-
const boundary = (typeof
|
|
115
|
-
return key === 'min' ?
|
|
114
|
+
const boundary = (typeof config.limit === 'number' ? config.limit : config.limit.getTime());
|
|
115
|
+
return key === 'min' ? parsed < boundary : parsed > boundary;
|
|
116
116
|
}
|
|
117
117
|
|
|
118
118
|
/**
|
|
@@ -144,15 +144,15 @@ export class SchemaValidator {
|
|
|
144
144
|
}
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
-
if (input.match && !input.match.
|
|
147
|
+
if (input.match && !input.match.regex.test(`${value}`)) {
|
|
148
148
|
criteria.push(['match', input.match]);
|
|
149
149
|
}
|
|
150
150
|
|
|
151
|
-
if (input.minlength && `${value}`.length < input.minlength.
|
|
151
|
+
if (input.minlength && `${value}`.length < input.minlength.limit) {
|
|
152
152
|
criteria.push(['minlength', input.minlength]);
|
|
153
153
|
}
|
|
154
154
|
|
|
155
|
-
if (input.maxlength && `${value}`.length > input.maxlength.
|
|
155
|
+
if (input.maxlength && `${value}`.length > input.maxlength.limit) {
|
|
156
156
|
criteria.push(['maxlength', input.maxlength]);
|
|
157
157
|
}
|
|
158
158
|
|
|
@@ -184,30 +184,30 @@ export class SchemaValidator {
|
|
|
184
184
|
static #prepareErrors(path: string, results: ValidationResult[]): ValidationError[] {
|
|
185
185
|
const out: ValidationError[] = [];
|
|
186
186
|
for (const result of results) {
|
|
187
|
-
const
|
|
187
|
+
const error: ValidationError = {
|
|
188
188
|
...result,
|
|
189
189
|
kind: result.kind,
|
|
190
190
|
value: result.value,
|
|
191
191
|
message: '',
|
|
192
|
-
|
|
192
|
+
regex: CommonRegexToName.get(result.regex!) ?? result.regex?.source ?? '',
|
|
193
193
|
path,
|
|
194
194
|
type: (typeof result.type === 'function' ? result.type.name : result.type)
|
|
195
195
|
};
|
|
196
196
|
|
|
197
|
-
if (!
|
|
198
|
-
delete
|
|
197
|
+
if (!error.regex) {
|
|
198
|
+
delete error.regex;
|
|
199
199
|
}
|
|
200
200
|
|
|
201
201
|
const msg = result.message ?? (
|
|
202
|
-
Messages.get(
|
|
203
|
-
Messages.get(
|
|
202
|
+
Messages.get(error.regex ?? '') ??
|
|
203
|
+
Messages.get(error.kind) ??
|
|
204
204
|
Messages.get('default')!
|
|
205
205
|
);
|
|
206
206
|
|
|
207
|
-
|
|
208
|
-
.replace(/\{([^}]+)\}/g, (_,
|
|
207
|
+
error.message = msg
|
|
208
|
+
.replace(/\{([^}]+)\}/g, (_, key: (keyof ValidationError)) => `${error[key]}`);
|
|
209
209
|
|
|
210
|
-
out.push(
|
|
210
|
+
out.push(error);
|
|
211
211
|
}
|
|
212
212
|
return out;
|
|
213
213
|
}
|
|
@@ -215,7 +215,7 @@ export class SchemaValidator {
|
|
|
215
215
|
/**
|
|
216
216
|
* Validate the class level validations
|
|
217
217
|
*/
|
|
218
|
-
static async #validateClassLevel<T>(cls: Class<T>,
|
|
218
|
+
static async #validateClassLevel<T>(cls: Class<T>, item: T, view?: string): Promise<ValidationError[]> {
|
|
219
219
|
if (!SchemaRegistryIndex.has(cls)) {
|
|
220
220
|
return [];
|
|
221
221
|
}
|
|
@@ -226,19 +226,19 @@ export class SchemaValidator {
|
|
|
226
226
|
// Handle class level validators
|
|
227
227
|
for (const fn of classConfig.validators) {
|
|
228
228
|
try {
|
|
229
|
-
const
|
|
230
|
-
if (
|
|
231
|
-
if (Array.isArray(
|
|
232
|
-
errors.push(...
|
|
229
|
+
const error = await fn(item, view);
|
|
230
|
+
if (error) {
|
|
231
|
+
if (Array.isArray(error)) {
|
|
232
|
+
errors.push(...error);
|
|
233
233
|
} else {
|
|
234
|
-
errors.push(
|
|
234
|
+
errors.push(error);
|
|
235
235
|
}
|
|
236
236
|
}
|
|
237
|
-
} catch (
|
|
238
|
-
if (isValidationError(
|
|
239
|
-
errors.push(
|
|
237
|
+
} catch (error: unknown) {
|
|
238
|
+
if (isValidationError(error)) {
|
|
239
|
+
errors.push(error);
|
|
240
240
|
} else {
|
|
241
|
-
throw
|
|
241
|
+
throw error;
|
|
242
242
|
}
|
|
243
243
|
}
|
|
244
244
|
}
|
|
@@ -248,60 +248,60 @@ export class SchemaValidator {
|
|
|
248
248
|
/**
|
|
249
249
|
* Validate an object against it's constructor's schema
|
|
250
250
|
* @param cls The class to validate the objects against
|
|
251
|
-
* @param
|
|
251
|
+
* @param item The object to validate
|
|
252
252
|
* @param view The optional view to limit the scope to
|
|
253
253
|
*/
|
|
254
|
-
static async validate<T>(cls: Class<T>,
|
|
255
|
-
if (isClassInstance(
|
|
256
|
-
throw new TypeMismatchError(cls.name,
|
|
254
|
+
static async validate<T>(cls: Class<T>, item: T, view?: string): Promise<T> {
|
|
255
|
+
if (isClassInstance(item) && !(item instanceof cls || cls.Ⲑid === item.constructor.Ⲑid)) {
|
|
256
|
+
throw new TypeMismatchError(cls.name, item.constructor.name);
|
|
257
257
|
}
|
|
258
|
-
cls = SchemaRegistryIndex.resolveInstanceType(cls,
|
|
258
|
+
cls = SchemaRegistryIndex.resolveInstanceType(cls, item);
|
|
259
259
|
|
|
260
260
|
const fields = SchemaRegistryIndex.get(cls).getFields(view);
|
|
261
261
|
|
|
262
262
|
// Validate using standard behaviors
|
|
263
263
|
const errors = [
|
|
264
|
-
...this.#validateFields(fields,
|
|
265
|
-
... await this.#validateClassLevel(cls,
|
|
264
|
+
...this.#validateFields(fields, item, ''),
|
|
265
|
+
... await this.#validateClassLevel(cls, item, view)
|
|
266
266
|
];
|
|
267
267
|
if (errors.length) {
|
|
268
268
|
throw new ValidationResultError(errors);
|
|
269
269
|
}
|
|
270
270
|
|
|
271
|
-
return
|
|
271
|
+
return item;
|
|
272
272
|
}
|
|
273
273
|
|
|
274
274
|
/**
|
|
275
275
|
* Validate an entire array of values
|
|
276
276
|
* @param cls The class to validate the objects against
|
|
277
|
-
* @param
|
|
277
|
+
* @param items The values to validate
|
|
278
278
|
* @param view The view to limit by
|
|
279
279
|
*/
|
|
280
|
-
static async validateAll<T>(cls: Class<T>,
|
|
281
|
-
return await Promise.all<T>((
|
|
282
|
-
.map(
|
|
280
|
+
static async validateAll<T>(cls: Class<T>, items: T[], view?: string): Promise<T[]> {
|
|
281
|
+
return await Promise.all<T>((items ?? [])
|
|
282
|
+
.map(item => this.validate(cls, item, view)));
|
|
283
283
|
}
|
|
284
284
|
|
|
285
285
|
/**
|
|
286
286
|
* Validate partial, ignoring required fields as they are partial
|
|
287
287
|
*
|
|
288
288
|
* @param cls The class to validate against
|
|
289
|
-
* @param
|
|
289
|
+
* @param item The value to validate
|
|
290
290
|
* @param view The view to limit by
|
|
291
291
|
*/
|
|
292
|
-
static async validatePartial<T>(cls: Class<T>,
|
|
292
|
+
static async validatePartial<T>(cls: Class<T>, item: T, view?: string): Promise<T> {
|
|
293
293
|
try {
|
|
294
|
-
await this.validate(cls,
|
|
295
|
-
} catch (
|
|
296
|
-
if (
|
|
297
|
-
const errs =
|
|
294
|
+
await this.validate(cls, item, view);
|
|
295
|
+
} catch (error) {
|
|
296
|
+
if (error instanceof ValidationResultError) { // Don't check required fields
|
|
297
|
+
const errs = error.details.errors.filter(validationError => validationError.kind !== 'required');
|
|
298
298
|
if (errs.length) {
|
|
299
|
-
|
|
300
|
-
throw
|
|
299
|
+
error.details.errors = errs;
|
|
300
|
+
throw error;
|
|
301
301
|
}
|
|
302
302
|
}
|
|
303
303
|
}
|
|
304
|
-
return
|
|
304
|
+
return item;
|
|
305
305
|
}
|
|
306
306
|
|
|
307
307
|
/**
|
|
@@ -311,7 +311,7 @@ export class SchemaValidator {
|
|
|
311
311
|
* @param method The method being invoked
|
|
312
312
|
* @param params The params to validate
|
|
313
313
|
*/
|
|
314
|
-
static async validateMethod<T>(cls: Class<T>, method: string
|
|
314
|
+
static async validateMethod<T>(cls: Class<T>, method: string, params: unknown[], prefixes: (string | undefined)[] = []): Promise<void> {
|
|
315
315
|
const errors: ValidationError[] = [];
|
|
316
316
|
const config = SchemaRegistryIndex.get(cls).getMethod(method);
|
|
317
317
|
|
|
@@ -320,22 +320,22 @@ export class SchemaValidator {
|
|
|
320
320
|
errors.push(...[
|
|
321
321
|
... this.#validateInputSchema(param, params[i]),
|
|
322
322
|
... await this.#validateClassLevel(param.type, params[i])
|
|
323
|
-
].map(
|
|
323
|
+
].map(error => {
|
|
324
324
|
if (param.name && typeof param.name === 'string') {
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
325
|
+
error.path = !prefixes[i] ?
|
|
326
|
+
error.path.replace(`${param.name}.`, '') :
|
|
327
|
+
error.path.replace(param.name, prefixes[i]!);
|
|
328
328
|
}
|
|
329
|
-
return
|
|
329
|
+
return error;
|
|
330
330
|
}));
|
|
331
331
|
}
|
|
332
332
|
for (const validator of config.validators) {
|
|
333
|
-
const
|
|
334
|
-
if (
|
|
335
|
-
if (Array.isArray(
|
|
336
|
-
errors.push(...
|
|
333
|
+
const error = await validator(...params);
|
|
334
|
+
if (error) {
|
|
335
|
+
if (Array.isArray(error)) {
|
|
336
|
+
errors.push(...error);
|
|
337
337
|
} else {
|
|
338
|
-
errors.push(
|
|
338
|
+
errors.push(error);
|
|
339
339
|
}
|
|
340
340
|
}
|
|
341
341
|
}
|
|
@@ -22,7 +22,7 @@ export class SchemaTransformUtil {
|
|
|
22
22
|
switch (type.key) {
|
|
23
23
|
case 'pointer': return this.toConcreteType(state, type.target, node, root);
|
|
24
24
|
case 'managed': return state.getOrImport(type);
|
|
25
|
-
case 'tuple': return state.fromLiteral(type.subTypes.map(
|
|
25
|
+
case 'tuple': return state.fromLiteral(type.subTypes.map(subType => this.toConcreteType(state, subType, node, root)!));
|
|
26
26
|
case 'template': return state.createIdentifier(type.ctor.name);
|
|
27
27
|
case 'literal': {
|
|
28
28
|
if ((type.ctor === Array) && type.typeArguments?.length) {
|
|
@@ -60,7 +60,7 @@ class ${uniqueId} extends ${type.mappedClassName} {
|
|
|
60
60
|
}
|
|
61
61
|
case 'unknown': {
|
|
62
62
|
const imp = state.importFile(this.TYPES_IMPORT);
|
|
63
|
-
return state.createAccess(imp.
|
|
63
|
+
return state.createAccess(imp.identifier, 'UnknownType');
|
|
64
64
|
}
|
|
65
65
|
case 'shape': {
|
|
66
66
|
const uniqueId = state.generateUniqueIdentifier(node, type, 'Δ');
|
|
@@ -76,18 +76,18 @@ class ${uniqueId} extends ${type.mappedClassName} {
|
|
|
76
76
|
],
|
|
77
77
|
id, [], [],
|
|
78
78
|
Object.entries(type.fieldTypes)
|
|
79
|
-
.map(([
|
|
79
|
+
.map(([key, value]) =>
|
|
80
80
|
this.computeInput(state, state.factory.createPropertyDeclaration(
|
|
81
|
-
[], /\W/.test(
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
), { type:
|
|
81
|
+
[], /\W/.test(key) ? state.factory.createComputedPropertyName(state.fromLiteral(key)) : key,
|
|
82
|
+
value.undefinable || value.nullable ? state.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined,
|
|
83
|
+
value.key === 'unknown' ? state.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword) : undefined, undefined
|
|
84
|
+
), { type: value, root })
|
|
85
85
|
)
|
|
86
86
|
);
|
|
87
87
|
cls.getText = (): string => [
|
|
88
88
|
`class ${uniqueId} {`,
|
|
89
89
|
...Object.entries(type.fieldTypes)
|
|
90
|
-
.map(([
|
|
90
|
+
.map(([key, value]) => ` ${key}${value.nullable ? '?' : ''}: ${value.name};`),
|
|
91
91
|
'}'
|
|
92
92
|
].join('\n');
|
|
93
93
|
state.addStatements([cls], root || node);
|
|
@@ -135,12 +135,12 @@ class ${uniqueId} extends ${type.mappedClassName} {
|
|
|
135
135
|
attrs.default = node.initializer;
|
|
136
136
|
}
|
|
137
137
|
} else {
|
|
138
|
-
const
|
|
138
|
+
const pair = DeclarationUtil.getAccessorPair(node);
|
|
139
139
|
attrs.accessor = true;
|
|
140
|
-
if (!
|
|
140
|
+
if (!pair.setter) {
|
|
141
141
|
attrs.access = 'readonly';
|
|
142
142
|
}
|
|
143
|
-
if (!
|
|
143
|
+
if (!pair.getter) {
|
|
144
144
|
attrs.access = 'writeonly';
|
|
145
145
|
} else if (!!typeExpr.undefinable) {
|
|
146
146
|
attrs.required = { active: false };
|
|
@@ -160,8 +160,9 @@ class ${uniqueId} extends ${type.mappedClassName} {
|
|
|
160
160
|
// We need to ensure we aren't being tripped up by the wrapper for arrays, sets, etc.
|
|
161
161
|
// If we have a composition type
|
|
162
162
|
if (primaryExpr.key === 'composition') {
|
|
163
|
-
const values = primaryExpr.subTypes
|
|
164
|
-
.
|
|
163
|
+
const values = primaryExpr.subTypes
|
|
164
|
+
.map(subType => subType.key === 'literal' ? subType.value : undefined)
|
|
165
|
+
.filter(value => value !== undefined && value !== null);
|
|
165
166
|
|
|
166
167
|
if (values.length === primaryExpr.subTypes.length) {
|
|
167
168
|
attrs.enum = {
|
|
@@ -170,17 +171,19 @@ class ${uniqueId} extends ${type.mappedClassName} {
|
|
|
170
171
|
};
|
|
171
172
|
}
|
|
172
173
|
} else if (primaryExpr.key === 'template' && primaryExpr.template) {
|
|
173
|
-
const
|
|
174
|
+
const regex = LiteralUtil.templateLiteralToRegex(primaryExpr.template);
|
|
174
175
|
attrs.match = {
|
|
175
|
-
|
|
176
|
+
regex: new RegExp(regex),
|
|
176
177
|
template: primaryExpr.template,
|
|
177
|
-
message: `{path} must match "${
|
|
178
|
+
message: `{path} must match "${regex}"`
|
|
178
179
|
};
|
|
179
180
|
}
|
|
180
181
|
|
|
181
182
|
if (ts.isParameter(node)) {
|
|
182
183
|
const parentComments = DocUtil.describeDocs(node.parent);
|
|
183
|
-
const paramComments: Partial<ParamDocumentation> = (parentComments.params ?? [])
|
|
184
|
+
const paramComments: Partial<ParamDocumentation> = (parentComments.params ?? [])
|
|
185
|
+
.find(param => param.name === node.name.getText()) || {};
|
|
186
|
+
|
|
184
187
|
if (paramComments.description) {
|
|
185
188
|
attrs.description = paramComments.description;
|
|
186
189
|
}
|
|
@@ -192,9 +195,9 @@ class ${uniqueId} extends ${type.mappedClassName} {
|
|
|
192
195
|
}
|
|
193
196
|
|
|
194
197
|
const tags = ts.getJSDocTags(node);
|
|
195
|
-
const aliases = tags.filter(
|
|
198
|
+
const aliases = tags.filter(tag => tag.tagName.getText() === 'alias');
|
|
196
199
|
if (aliases.length) {
|
|
197
|
-
attrs.aliases = aliases.map(
|
|
200
|
+
attrs.aliases = aliases.map(alias => alias.comment).filter(alias => !!alias);
|
|
198
201
|
}
|
|
199
202
|
|
|
200
203
|
const params: ts.Expression[] = [];
|
|
@@ -241,15 +244,15 @@ class ${uniqueId} extends ${type.mappedClassName} {
|
|
|
241
244
|
): T {
|
|
242
245
|
const existingField = state.findDecorator('@travetto/schema', node, 'Field', this.FIELD_IMPORT);
|
|
243
246
|
const existingInput = state.findDecorator('@travetto/schema', node, 'Input', this.INPUT_IMPORT);
|
|
244
|
-
const
|
|
247
|
+
const params = this.computeInputDecoratorParams(state, node, config);
|
|
245
248
|
|
|
246
249
|
let modifiers: ts.ModifierLike[];
|
|
247
250
|
if (existingField) {
|
|
248
|
-
const
|
|
249
|
-
modifiers = DecoratorUtil.spliceDecorators(node, existingField, [
|
|
251
|
+
const decorator = state.createDecorator(this.FIELD_IMPORT, 'Field', ...params);
|
|
252
|
+
modifiers = DecoratorUtil.spliceDecorators(node, existingField, [decorator]);
|
|
250
253
|
} else {
|
|
251
|
-
const
|
|
252
|
-
modifiers = DecoratorUtil.spliceDecorators(node, existingInput, [
|
|
254
|
+
const decorator = state.createDecorator(this.INPUT_IMPORT, 'Input', ...params);
|
|
255
|
+
modifiers = DecoratorUtil.spliceDecorators(node, existingInput, [decorator]);
|
|
253
256
|
}
|
|
254
257
|
|
|
255
258
|
let result: unknown;
|
|
@@ -324,8 +327,8 @@ class ${uniqueId} extends ${type.mappedClassName} {
|
|
|
324
327
|
let cls;
|
|
325
328
|
switch (type?.key) {
|
|
326
329
|
case 'managed': {
|
|
327
|
-
const [
|
|
328
|
-
cls =
|
|
330
|
+
const [decorator] = DeclarationUtil.getDeclarations(type.original!);
|
|
331
|
+
cls = decorator && ts.isClassDeclaration(decorator) ? decorator : undefined;
|
|
329
332
|
break;
|
|
330
333
|
}
|
|
331
334
|
case 'shape': cls = type.original; break;
|
|
@@ -59,8 +59,8 @@ export class SchemaTransformer {
|
|
|
59
59
|
// Determine auto enrol methods
|
|
60
60
|
for (const item of state.getDecoratorList(node)) {
|
|
61
61
|
if (item.targets?.includes('@travetto/schema:Schema')) {
|
|
62
|
-
for (const
|
|
63
|
-
state[AutoEnrollMethods].add(
|
|
62
|
+
for (const option of item.options ?? []) {
|
|
63
|
+
state[AutoEnrollMethods].add(option);
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
66
|
}
|
|
@@ -76,7 +76,7 @@ export class SchemaTransformer {
|
|
|
76
76
|
const comments = DocUtil.describeDocs(node);
|
|
77
77
|
|
|
78
78
|
const existing = state.findDecorator(this, node, 'Schema', SchemaTransformUtil.SCHEMA_IMPORT);
|
|
79
|
-
const cons = node.members.find(
|
|
79
|
+
const cons = node.members.find(member => ts.isConstructorDeclaration(member));
|
|
80
80
|
|
|
81
81
|
const attrs: Record<string, string | boolean | ts.Expression | number | object | unknown[]> = {};
|
|
82
82
|
|
|
@@ -105,9 +105,9 @@ export class SchemaTransformer {
|
|
|
105
105
|
if (cons) {
|
|
106
106
|
attrs.methods = {
|
|
107
107
|
[CONSTRUCTOR_PROPERTY]: {
|
|
108
|
-
parameters: cons.parameters
|
|
109
|
-
|
|
110
|
-
|
|
108
|
+
parameters: cons.parameters
|
|
109
|
+
.map((parameter, i) => SchemaTransformUtil.computeInputDecoratorParams(state, parameter, { index: i }))
|
|
110
|
+
.map(expr => state.extendObjectLiteral({}, ...expr)),
|
|
111
111
|
}
|
|
112
112
|
};
|
|
113
113
|
}
|
|
@@ -163,7 +163,7 @@ export class SchemaTransformer {
|
|
|
163
163
|
node.name,
|
|
164
164
|
node.questionToken,
|
|
165
165
|
node.typeParameters,
|
|
166
|
-
node.parameters.map((
|
|
166
|
+
node.parameters.map((parameter, i) => SchemaTransformUtil.computeInput(state, parameter, { index: i })),
|
|
167
167
|
node.type,
|
|
168
168
|
node.body
|
|
169
169
|
);
|
package/src/service/changes.ts
DELETED
|
@@ -1,152 +0,0 @@
|
|
|
1
|
-
import { EventEmitter } from 'node:events';
|
|
2
|
-
|
|
3
|
-
import { Class } from '@travetto/runtime';
|
|
4
|
-
import { ChangeEvent } from '@travetto/registry';
|
|
5
|
-
|
|
6
|
-
import { SchemaFieldConfig, SchemaClassConfig } from './types.ts';
|
|
7
|
-
|
|
8
|
-
interface FieldMapping {
|
|
9
|
-
path: SchemaFieldConfig[];
|
|
10
|
-
config: SchemaClassConfig;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export interface FieldChangeEvent {
|
|
14
|
-
cls: Class;
|
|
15
|
-
changes: ChangeEvent<SchemaFieldConfig>[];
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
interface SubSchemaChange {
|
|
19
|
-
path: SchemaFieldConfig[];
|
|
20
|
-
fields: ChangeEvent<SchemaFieldConfig>[];
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export interface SchemaChange {
|
|
24
|
-
config: SchemaClassConfig;
|
|
25
|
-
subs: SubSchemaChange[];
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export interface SchemaChangeEvent {
|
|
29
|
-
cls: Class;
|
|
30
|
-
change: SchemaChange;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Schema change listener. Handles all changes that occur via the SchemaRegistryIndex
|
|
35
|
-
*/
|
|
36
|
-
class $SchemaChangeListener {
|
|
37
|
-
|
|
38
|
-
#emitter = new EventEmitter();
|
|
39
|
-
#mapping = new Map<string, Map<string, FieldMapping>>();
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* On schema change, emit the change event for the whole schema
|
|
43
|
-
* @param cb The function to call on schema change
|
|
44
|
-
*/
|
|
45
|
-
onSchemaChange(handler: (e: SchemaChangeEvent) => void): void {
|
|
46
|
-
this.#emitter.on('schema', handler);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* On schema field change, emit the change event for the whole schema
|
|
51
|
-
* @param cb The function to call on schema field change
|
|
52
|
-
*/
|
|
53
|
-
onFieldChange(handler: (e: FieldChangeEvent) => void): void {
|
|
54
|
-
this.#emitter.on('field', handler);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Clear dependency mappings for a given class
|
|
59
|
-
*/
|
|
60
|
-
clearSchemaDependency(cls: Class): void {
|
|
61
|
-
this.#mapping.delete(cls.Ⲑid);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Track a specific class for dependencies
|
|
66
|
-
* @param src The target class
|
|
67
|
-
* @param parent The parent class
|
|
68
|
-
* @param path The path within the object hierarchy to arrive at the class
|
|
69
|
-
* @param config The configuration or the class
|
|
70
|
-
*/
|
|
71
|
-
trackSchemaDependency(src: Class, parent: Class, path: SchemaFieldConfig[], config: SchemaClassConfig): void {
|
|
72
|
-
const idValue = src.Ⲑid;
|
|
73
|
-
if (!this.#mapping.has(idValue)) {
|
|
74
|
-
this.#mapping.set(idValue, new Map());
|
|
75
|
-
}
|
|
76
|
-
this.#mapping.get(idValue)!.set(parent.Ⲑid, { path, config });
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Emit changes to the schema
|
|
81
|
-
* @param cls The class of the event
|
|
82
|
-
* @param changes The changes to send
|
|
83
|
-
*/
|
|
84
|
-
emitSchemaChanges({ cls, changes }: FieldChangeEvent): void {
|
|
85
|
-
const updates = new Map<string, SchemaChange>();
|
|
86
|
-
const clsId = cls.Ⲑid;
|
|
87
|
-
|
|
88
|
-
if (this.#mapping.has(clsId)) {
|
|
89
|
-
const deps = this.#mapping.get(clsId)!;
|
|
90
|
-
for (const depClsId of deps.keys()) {
|
|
91
|
-
if (!updates.has(depClsId)) {
|
|
92
|
-
updates.set(depClsId, { config: deps.get(depClsId)!.config, subs: [] });
|
|
93
|
-
}
|
|
94
|
-
const c = deps.get(depClsId)!;
|
|
95
|
-
updates.get(depClsId)!.subs.push({ path: [...c.path], fields: changes });
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
for (const key of updates.keys()) {
|
|
100
|
-
this.#emitter.emit('schema', { cls: updates.get(key)!.config.class, change: updates.get(key)! });
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* Emit field level changes in the schema
|
|
106
|
-
* @param prev The previous class config
|
|
107
|
-
* @param curr The current class config
|
|
108
|
-
*/
|
|
109
|
-
emitFieldChanges(ev: ChangeEvent<SchemaClassConfig>): void {
|
|
110
|
-
const prev = 'prev' in ev ? ev.prev : undefined;
|
|
111
|
-
const curr = 'curr' in ev ? ev.curr : undefined;
|
|
112
|
-
|
|
113
|
-
const prevFields = new Set(Object.keys(prev?.fields ?? {}));
|
|
114
|
-
const currFields = new Set(Object.keys(curr?.fields ?? {}));
|
|
115
|
-
|
|
116
|
-
const changes: ChangeEvent<SchemaFieldConfig>[] = [];
|
|
117
|
-
|
|
118
|
-
for (const c of currFields) {
|
|
119
|
-
if (!prevFields.has(c) && curr) {
|
|
120
|
-
changes.push({ curr: curr.fields[c], type: 'added' });
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
for (const c of prevFields) {
|
|
125
|
-
if (!currFields.has(c) && prev) {
|
|
126
|
-
changes.push({ prev: prev.fields[c], type: 'removing' });
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// Handle class references changing, but keeping same id
|
|
131
|
-
const compareTypes = (a: Class, b: Class): boolean => a.Ⲑid ? a.Ⲑid === b.Ⲑid : a === b;
|
|
132
|
-
|
|
133
|
-
for (const c of currFields) {
|
|
134
|
-
if (prevFields.has(c) && prev && curr) {
|
|
135
|
-
const prevSchema = prev.fields[c];
|
|
136
|
-
const currSchema = curr.fields[c];
|
|
137
|
-
if (
|
|
138
|
-
JSON.stringify(prevSchema) !== JSON.stringify(currSchema) ||
|
|
139
|
-
!compareTypes(prevSchema.type, currSchema.type)
|
|
140
|
-
) {
|
|
141
|
-
changes.push({ prev: prev.fields[c], curr: curr.fields[c], type: 'changed' });
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// Send field changes
|
|
147
|
-
this.#emitter.emit('field', { cls: curr!.class, changes });
|
|
148
|
-
this.emitSchemaChanges({ cls: curr!.class, changes });
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
export const SchemaChangeListener = new $SchemaChangeListener();
|