@aws-cdk/cloud-assembly-schema
Advanced tools
Comparing version 1.66.0 to 1.67.0
@@ -181,2 +181,13 @@ 'use strict'; | ||
function getEnumerableProperty(object, key){ | ||
// Determine if `key` shows up in `for(var key in object)` | ||
// First test Object.hasOwnProperty.call as an optimization: that guarantees it does | ||
if(Object.hasOwnProperty.call(object, key)) return object[key]; | ||
// Test `key in object` as an optimization; false means it won't | ||
if(!(key in object)) return; | ||
while(object = Object.getPrototypeOf(object)){ | ||
if(Object.propertyIsEnumerable.call(object, key)) return object[key]; | ||
} | ||
} | ||
/** | ||
@@ -198,4 +209,3 @@ * Validates properties | ||
} | ||
var prop = Object.hasOwnProperty.call(instance, property) ? instance[property] : undefined; | ||
var prop = getEnumerableProperty(instance, property); | ||
var res = this.validateSchema(prop, properties[property], options, ctx.makeChild(properties[property], property)); | ||
@@ -211,3 +221,3 @@ if(res.instance !== result.instance[property]) result.instance[property] = res.instance; | ||
* This ignores properties with definitions in the properties schema attribute, but no other attributes. | ||
* If too many more types of property-existance tests pop up they may need their own class of tests (like `type` has) | ||
* If too many more types of property-existence tests pop up they may need their own class of tests (like `type` has) | ||
* @private | ||
@@ -256,4 +266,10 @@ * @return {boolean} | ||
for (var pattern in patternProperties) { | ||
var expr = new RegExp(pattern, 'u'); | ||
if (!expr.test(property)) { | ||
try { | ||
var regexp = new RegExp(pattern, 'u'); | ||
} catch(_e) { | ||
// In the event the stricter handling causes an error, fall back on the forgiving handling | ||
// DEPRECATED | ||
regexp = new RegExp(pattern); | ||
} | ||
if (!regexp.test(property)) { | ||
continue; | ||
@@ -487,3 +503,3 @@ } | ||
if (instance === undefined && schema.required === true) { | ||
// A boolean form is implemented for reverse-compatability with schemas written against older drafts | ||
// A boolean form is implemented for reverse-compatibility with schemas written against older drafts | ||
result.addError({ | ||
@@ -495,3 +511,3 @@ name: 'required', | ||
schema.required.forEach(function(n){ | ||
if(instance[n]===undefined){ | ||
if(getEnumerableProperty(instance, n)===undefined){ | ||
result.addError({ | ||
@@ -517,3 +533,10 @@ name: 'required', | ||
var result = new ValidatorResult(instance, schema, options, ctx); | ||
var regexp = new RegExp(schema.pattern, 'u'); | ||
var pattern = schema.pattern; | ||
try { | ||
var regexp = new RegExp(pattern, 'u'); | ||
} catch(_e) { | ||
// In the event the stricter handling causes an error, fall back on the forgiving handling | ||
// DEPRECATED | ||
regexp = new RegExp(pattern); | ||
} | ||
if (!instance.match(regexp)) { | ||
@@ -520,0 +543,0 @@ result.addError({ |
@@ -98,2 +98,3 @@ /* | ||
allowUnknownAttributes?: boolean; | ||
preValidateProperty?: PreValidatePropertyFunction; | ||
rewrite?: RewriteFunction; | ||
@@ -110,2 +111,6 @@ propertyName?: string; | ||
export interface PreValidatePropertyFunction { | ||
(instance: any, key: string, schema: Schema, options: Options, ctx: SchemaContext): any; | ||
} | ||
export interface SchemaContext { | ||
@@ -112,0 +117,0 @@ schema: Schema; |
@@ -33,3 +33,3 @@ "use strict"; | ||
if(!helpers.deepCompareStrict(found[ourBase], schema)){ | ||
throw new Error('Schema <'+schema+'> already exists with different definition'); | ||
throw new Error('Schema <'+ourBase+'> already exists with different definition'); | ||
} | ||
@@ -36,0 +36,0 @@ return found[ourBase]; |
@@ -106,2 +106,5 @@ 'use strict'; | ||
Validator.prototype.validate = function validate (instance, schema, options, ctx) { | ||
if((typeof schema !== 'boolean' && typeof schema !== 'object') || schema === null){ | ||
throw new SchemaError('Expected `schema` to be an object or boolean'); | ||
} | ||
if (!options) { | ||
@@ -124,10 +127,7 @@ options = {}; | ||
} | ||
if (schema) { | ||
var result = this.validateSchema(instance, schema, options, ctx); | ||
if (!result) { | ||
throw new Error('Result undefined'); | ||
} | ||
return result; | ||
var result = this.validateSchema(instance, schema, options, ctx); | ||
if (!result) { | ||
throw new Error('Result undefined'); | ||
} | ||
throw new SchemaError('no schema specified', schema); | ||
return result; | ||
}; | ||
@@ -134,0 +134,0 @@ |
{ | ||
"author": "Tom de Grunt <tom@degrunt.nl>", | ||
"name": "jsonschema", | ||
"version": "1.2.7", | ||
"version": "1.2.10", | ||
"license": "MIT", | ||
@@ -6,0 +6,0 @@ "dependencies": {}, |
[![Build Status](https://secure.travis-ci.org/tdegrunt/jsonschema.svg)](http://travis-ci.org/tdegrunt/jsonschema) | ||
# jsonschema | ||
[JSON schema](http://json-schema.org/) validator, which is designed to be fast and simple to use. | ||
@@ -8,5 +9,7 @@ The latest IETF published draft is v6, this library is mostly v4 compatible. | ||
## Contributing & bugs | ||
Please fork the repository, make the changes in your fork and include tests. Once you're done making changes, send in a pull request. | ||
### Bug reports | ||
Please include a test which shows why the code fails. | ||
@@ -17,2 +20,3 @@ | ||
### Simple | ||
Simple object validation using JSON schemas. | ||
@@ -83,2 +87,3 @@ | ||
### Example for Array schema | ||
```json | ||
@@ -101,8 +106,11 @@ var arraySchema = { | ||
### Definitions | ||
All schema definitions are supported, $schema is ignored. | ||
### Types | ||
All types are supported | ||
### Formats | ||
#### Disabling the format keyword. | ||
@@ -114,5 +122,7 @@ | ||
#### String Formats | ||
All formats are supported, phone numbers are expected to follow the [E.123](http://en.wikipedia.org/wiki/E.123) standard. | ||
#### Custom Formats | ||
You may add your own custom format functions. Format functions accept the input | ||
@@ -141,7 +151,48 @@ being validated and return a boolean value. If the returned value is `true`, then | ||
### Results | ||
The first error found will be thrown as an `Error` object if `options.throwError` is `true`. Otherwise all results will be appended to the `result.errors` array which also contains the success flag `result.valid`. | ||
When `oneOf` or `anyOf` validations fail, errors that caused any of the sub-schemas referenced therein to fail are not reported, unless `options.nestedErrors` is truthy. This option may be useful when troubleshooting validation errors in complex schemas. | ||
The first error found will be thrown as an `Error` object if `options.throwError` is `true`. Otherwise all results will be appended to the `result.errors` array. Each item in this array is a `ValidationError` with the following properties: | ||
* property: string. Describes the property path. Starts with `instance` (this is configurable with the `options.propertyName` option), and is delimited with a dot (`.`). | ||
* message: string. A human-readable message for debugging use. Provided in English and subject to change. | ||
* schema: object. The schema containing the keyword that failed | ||
* instance: any. The instance that failed | ||
* name: string. The keyword within the schema that failed. | ||
* argument: any. Provides information about the keyword that failed. | ||
#### "nestedErrors" option | ||
When `oneOf` or `anyOf` validations fail, errors that caused any of the sub-schemas referenced therein to fail are normally suppressed, because it is not necessary to fix all of them. And in the case of `oneOf`, it would itself be an error to fix all of the listed errors. | ||
This behavor may be configured with `options.nestedErrors`. If truthy, it will emit all the errors from the subschemas. This option may be useful when troubleshooting validation errors in complex schemas: | ||
```javascript | ||
var schema = { | ||
oneOf: [ | ||
{ type: 'string', minLength: 32, maxLength: 32 }, | ||
{ type: 'string', maxLength: 16 }, | ||
{ type: 'number' }, | ||
] | ||
}; | ||
var validator = new Validator(); | ||
var result = validator.validate('This string is 28 chars long', schema, {nestedErrors: true}); | ||
// result.toString() reads out: | ||
// 0: instance does not meet minimum length of 32 | ||
// 1: instance does not meet maximum length of 16 | ||
// 2: instance is not of a type(s) number | ||
// 3: instance is not exactly one from [subschema 0],[subschema 1],[subschema 2] | ||
``` | ||
#### Localizing Error Messages | ||
To provide localized, human-readable errors, use the `name` string as a translation key. Feel free to open an issue for support relating to localizing error messages. For example: | ||
``` | ||
var localized = result.errors.map(function(err){ | ||
return localeService.translate(err.name); | ||
}); | ||
``` | ||
### Custom properties | ||
Specify your own JSON Schema properties with the validator.attributes property: | ||
@@ -151,4 +202,4 @@ | ||
validator.attributes.contains = function validateContains(instance, schema, options, ctx) { | ||
if(typeof instance!='string') return; | ||
if(typeof schema.contains!='string') throw new jsonschema.SchemaError('"contains" expects a string', schema); | ||
if(typeof instance !== 'string') return; | ||
if(typeof schema.contains !== 'string') throw new jsonschema.SchemaError('"contains" expects a string', schema); | ||
if(instance.indexOf(schema.contains)<0){ | ||
@@ -158,3 +209,3 @@ return 'does not contain the string ' + JSON.stringify(schema.contains); | ||
} | ||
var result = validator.validate("i am an instance", { type:"string", contains: "i am" }); | ||
var result = validator.validate("I am an instance", { type:"string", contains: "I am" }); | ||
// result.valid === true; | ||
@@ -164,3 +215,3 @@ ``` | ||
The instance passes validation if the function returns nothing. A single validation error is produced | ||
if the fuction returns a string. Any number of errors (maybe none at all) may be returned by passing a | ||
if the function returns a string. Any number of errors (maybe none at all) may be returned by passing a | ||
`ValidatorResult` object, which may be used like so: | ||
@@ -177,2 +228,3 @@ | ||
### Dereferencing schemas | ||
Sometimes you may want to download schemas from remote sources, like a database, or over HTTP. When importing a schema, | ||
@@ -197,3 +249,63 @@ unknown references are inserted into the `validator.unresolvedRefs` Array. Asynchronously shift elements off this array and import | ||
### Default base URI | ||
Schemas should typically have an `id` with an absolute, full URI. However if the schema you are using contains only relative URI references, the `base` option will be used to resolve these. | ||
This following example would throw a `SchemaError` if the `base` option were unset: | ||
```javascript | ||
var result = validate(["Name"], { | ||
id: "/schema.json", | ||
type: "array", | ||
items: { $ref: "http://example.com/schema.json#/definitions/item" }, | ||
definitions: { | ||
item: { type: "string" }, | ||
}, | ||
}, { base: 'http://example.com/' }); | ||
``` | ||
### Rewrite Hook | ||
The `rewrite` option lets you change the value of an instance after it has successfully been validated. This will mutate the `instance` passed to the validate function. This can be useful for unmarshalling data and parsing it into native instances, such as changing a string to a `Date` instance. | ||
The `rewrite` option accepts a function with the following arguments: | ||
* instance: any | ||
* schema: object | ||
* options: object | ||
* ctx: object | ||
* return value: any new value for the instance | ||
The value may be removed by returning `undefined`. | ||
If you don't want to change the value, call `return instance`. | ||
Here is an example that can convert a property expecting a date into a Date instance: | ||
```javascript | ||
const schema = { | ||
properties: { | ||
date: {id: 'http://example.com/date', type: 'string'}, | ||
}, | ||
}; | ||
const value = { | ||
date: '2020-09-30T23:39:27.060Z', | ||
}; | ||
function unmarshall(instance, schema){ | ||
if(schema.id === 'http://example.com/date'){ | ||
return new Date(instance); | ||
} | ||
return instance; | ||
} | ||
const v = new Validator(); | ||
const res = v.validate(value, schema, {rewrite: unmarshall}); | ||
assert(res.instance.date instanceof Date); | ||
``` | ||
### Pre-Property Validation Hook | ||
If some processing of properties is required prior to validation a function may be passed via the options parameter of the validate function. For example, say you needed to perform type coercion for some properties: | ||
@@ -205,3 +317,3 @@ | ||
// Skip nulls and undefineds | ||
// Skip null and undefined | ||
if (value === null || typeof value == 'undefined') { | ||
@@ -236,3 +348,27 @@ return; | ||
### Skip validation of certain keywords | ||
Use the "skipAttributes" option to skip validation of certain keywords. Provide an array of keywords to ignore. | ||
For skipping the "format" keyword, see the disableFormat option. | ||
### Fail on unknown keywords | ||
By default, JSON Schema is supposed to ignore unknown schema keywords. | ||
You can change this behavior to require that all keywords used in a schema have a defined behavior, by using setting the "allowUnknownAttributes" option to false. | ||
This example will throw a `SchemaError`: | ||
```javascript | ||
var schema = { | ||
type: "string", | ||
format: "email", | ||
example: "foo", | ||
}; | ||
var result = validate("Name", schema, { allowUnknownAttributes: false }); | ||
``` | ||
## Tests | ||
Uses [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) as well as our own tests. | ||
@@ -239,0 +375,0 @@ You'll need to update and init the git submodules: |
{ | ||
"name": "@aws-cdk/cloud-assembly-schema", | ||
"version": "1.66.0", | ||
"version": "1.67.0", | ||
"description": "Cloud Assembly Schema", | ||
@@ -57,6 +57,6 @@ "main": "lib/index.js", | ||
"@types/mock-fs": "^4.10.0", | ||
"cdk-build-tools": "1.66.0", | ||
"cdk-build-tools": "1.67.0", | ||
"jest": "^26.4.2", | ||
"mock-fs": "^4.13.0", | ||
"pkglint": "1.66.0", | ||
"pkglint": "1.67.0", | ||
"typescript-json-schema": "^0.43.0" | ||
@@ -86,3 +86,3 @@ }, | ||
"dependencies": { | ||
"jsonschema": "^1.2.7", | ||
"jsonschema": "^1.2.10", | ||
"semver": "^7.3.2" | ||
@@ -89,0 +89,0 @@ }, |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
3
377278
98
5392
Updatedjsonschema@^1.2.10