forked from expo/expo-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
279 lines (253 loc) · 8.54 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import Ajv, { ErrorObject, Options } from 'ajv';
import addFormats from 'ajv-formats';
import fs from 'fs';
import traverse from 'json-schema-traverse';
import get from 'lodash/get';
import path from 'path';
import imageProbe from 'probe-image-size';
import readChunk from 'read-chunk';
import { SchemerError, ValidationError } from './Error';
import { fieldPathToSchema, schemaPointerToFieldPath } from './Util';
type Meta = {
asset?: boolean;
dimensions?: {
width: number;
height: number;
};
square?: boolean;
contentTypePattern?: string;
contentTypeHuman?: string;
};
type SchemerOptions = Options & {
rootDir?: string;
};
type AssetField = { fieldPath: string; data: string; meta: Meta };
export { SchemerError, ValidationError, ErrorCodes, ErrorCode } from './Error';
export default class Schemer {
options: SchemerOptions;
ajv: Ajv;
schema: object;
rootDir: string;
manualValidationErrors: ValidationError[];
// Schema is a JSON Schema object
constructor(schema: object, options: SchemerOptions = {}) {
this.options = {
allErrors: true,
verbose: true,
meta: true,
strict: false,
unicodeRegExp: false,
...options,
};
this.ajv = new Ajv(this.options);
addFormats(this.ajv, { mode: 'full' });
this.schema = schema;
this.rootDir = this.options.rootDir || __dirname;
this.manualValidationErrors = [];
}
_formatAjvErrorMessage({
keyword,
instancePath,
params,
parentSchema,
data,
message,
}: ErrorObject) {
const meta = parentSchema && (parentSchema as any).meta;
// This removes the "." in front of a fieldPath
instancePath = instancePath.slice(1);
switch (keyword) {
case 'additionalProperties': {
return new ValidationError({
errorCode: 'SCHEMA_ADDITIONAL_PROPERTY',
fieldPath: instancePath,
message: `should NOT have additional property '${(params as any).additionalProperty}'`,
data,
meta,
});
}
case 'required':
return new ValidationError({
errorCode: 'SCHEMA_MISSING_REQUIRED_PROPERTY',
fieldPath: instancePath,
message: `is missing required property '${(params as any).missingProperty}'`,
data,
meta,
});
case 'pattern': {
//@TODO Parse the message in a less hacky way. Perhaps for regex validation errors, embed the error message under the meta tag?
const regexHuman = meta?.regexHuman;
const regexErrorMessage = regexHuman
? `'${instancePath}' should be a ${regexHuman[0].toLowerCase() + regexHuman.slice(1)}`
: `'${instancePath}' ${message}`;
return new ValidationError({
errorCode: 'SCHEMA_INVALID_PATTERN',
fieldPath: instancePath,
message: regexErrorMessage,
data,
meta,
});
}
case 'not': {
const notHuman = meta?.notHuman;
const notHumanErrorMessage = notHuman
? `'${instancePath}' should be ${notHuman[0].toLowerCase() + notHuman.slice(1)}`
: `'${instancePath}' ${message}`;
return new ValidationError({
errorCode: 'SCHEMA_INVALID_NOT',
fieldPath: instancePath,
message: notHumanErrorMessage,
data,
meta,
});
}
default:
return new ValidationError({
errorCode: 'SCHEMA_VALIDATION_ERROR',
fieldPath: instancePath,
message: message || 'Validation error',
data,
meta,
});
}
}
getErrors(): ValidationError[] {
// Convert AJV JSONSchema errors to our ValidationErrors
let valErrors: ValidationError[] = [];
if (this.ajv.errors) {
valErrors = this.ajv.errors.map(e => this._formatAjvErrorMessage(e));
}
return [...valErrors, ...this.manualValidationErrors];
}
_throwOnErrors() {
// Clean error state after each validation
const errors = this.getErrors();
if (errors.length > 0) {
this.manualValidationErrors = [];
this.ajv.errors = [];
throw new SchemerError(errors);
}
}
async validateAll(data: any) {
await this._validateSchemaAsync(data);
await this._validateAssetsAsync(data);
this._throwOnErrors();
}
async validateAssetsAsync(data: any) {
await this._validateAssetsAsync(data);
this._throwOnErrors();
}
async validateSchemaAsync(data: any) {
await this._validateSchemaAsync(data);
this._throwOnErrors();
}
_validateSchemaAsync(data: any) {
this.ajv.validate(this.schema, data);
}
async _validateAssetsAsync(data: any) {
const assets: AssetField[] = [];
traverse(this.schema, { allKeys: true }, (subSchema, jsonPointer, a, b, c, d, property) => {
if (property && subSchema.meta && subSchema.meta.asset) {
const fieldPath = schemaPointerToFieldPath(jsonPointer);
assets.push({
fieldPath,
data: get(data, fieldPath),
meta: subSchema.meta,
});
}
});
await Promise.all(assets.map(this._validateAssetAsync.bind(this)));
}
async _validateImageAsync({ fieldPath, data, meta }: AssetField) {
if (meta && meta.asset && data) {
const { dimensions, square, contentTypePattern }: Meta = meta;
// filePath could be an URL
const filePath = path.resolve(this.rootDir, data);
try {
// NOTE(nikki): The '4100' below should be enough for most file types, though we
// could probably go shorter....
// http://www.garykessler.net/library/file_sigs.html
// The metadata content for .jpgs might be located a lot farther down the file, so this
// may pose problems in the future.
// This cases on whether filePath is a remote URL or located on the machine
const probeResult = fs.existsSync(filePath)
? imageProbe.sync(await readChunk(filePath, 0, 4100))
: await imageProbe(data, { useElectronNet: false });
if (!probeResult) {
return;
}
const { width, height, type, mime } = probeResult;
if (contentTypePattern && !mime.match(new RegExp(contentTypePattern))) {
this.manualValidationErrors.push(
new ValidationError({
errorCode: 'INVALID_CONTENT_TYPE',
fieldPath,
message: `field '${fieldPath}' should point to ${meta.contentTypeHuman} but the file at '${data}' has type ${type}`,
data,
meta,
})
);
}
if (dimensions && (dimensions.height !== height || dimensions.width !== width)) {
this.manualValidationErrors.push(
new ValidationError({
errorCode: 'INVALID_DIMENSIONS',
fieldPath,
message: `'${fieldPath}' should have dimensions ${dimensions.width}x${dimensions.height}, but the file at '${data}' has dimensions ${width}x${height}`,
data,
meta,
})
);
}
if (square && width !== height) {
this.manualValidationErrors.push(
new ValidationError({
errorCode: 'NOT_SQUARE',
fieldPath,
message: `image should be square, but the file at '${data}' has dimensions ${width}x${height}`,
data,
meta,
})
);
}
} catch {
this.manualValidationErrors.push(
new ValidationError({
errorCode: 'INVALID_ASSET_URI',
fieldPath,
message: `cannot access file at '${data}'`,
data,
meta,
})
);
}
}
}
async _validateAssetAsync({ fieldPath, data, meta }: AssetField) {
if (meta && meta.asset && data) {
if (meta.contentTypePattern && meta.contentTypePattern.startsWith('^image')) {
await this._validateImageAsync({ fieldPath, data, meta });
}
}
}
async validateProperty(fieldPath: string, data: any) {
const subSchema = fieldPathToSchema(this.schema, fieldPath);
this.ajv.validate(subSchema, data);
if (subSchema.meta && subSchema.meta.asset) {
await this._validateAssetAsync({ fieldPath, data, meta: subSchema.meta });
}
this._throwOnErrors();
}
validateName(name: string) {
return this.validateProperty('name', name);
}
validateSlug(slug: string) {
return this.validateProperty('slug', slug);
}
validateSdkVersion(version: string) {
return this.validateProperty('sdkVersion', version);
}
validateIcon(iconPath: string) {
return this.validateProperty('icon', iconPath);
}
}