From c56123653c879e956d4d907c9a1e0a5da43c77f9 Mon Sep 17 00:00:00 2001 From: Jimmy Bergman Date: Thu, 12 Nov 2020 11:01:06 +0100 Subject: [PATCH 1/2] Add failing test case for array with undefined item and items schema --- test/misc.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/test/misc.js b/test/misc.js index 4ea36d5..fbcd758 100644 --- a/test/misc.js +++ b/test/misc.js @@ -28,6 +28,19 @@ tape('data is undefined', function (t) { t.end() }) +tape('array item is undefined', function (t) { + var validate = validator({type: 'array', minItems: 1, items: { type: 'string' } }) + + t.ok(validate(['a'])) + t.notOk(validate([null]), 'null should not be consider a string array item') + t.notOk(validate([{}]), 'object should not be consider a string array item') + + var arr = [undefined] + t.notOk(validate(arr), 'undefined should not be consider a string array item') + t.ok(arr[0] === undefined, 'array should not be mutated') + t.end() +}) + tape('advanced', function(t) { var validate = validator(cosmic.schema) From 4827cbc231778071f3519ea9241296bda8cecfc2 Mon Sep 17 00:00:00 2001 From: Jimmy Bergman Date: Thu, 12 Nov 2020 11:02:10 +0100 Subject: [PATCH 2/2] Coerce undefined array items to null --- index.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/index.js b/index.js index 26c516d..43b9892 100644 --- a/index.js +++ b/index.js @@ -383,6 +383,9 @@ var compile = function(schema, cache, root, reporter, opts) { var i = genloop() validate('for (var %s = 0; %s < %s.length; %s++) {', i, i, name, i) + // Since undefined is not a valid JSON value, we coerce all undefined items in the array to null + // We do it like this to not have to mutate the original data + validate('if (%s === undefined) %s = %s.map(function (item) { return item === undefined ? null : item })', name+'['+i+']', name, name) visit(name+'['+i+']', node.items, reporter, filter, schemaPath.concat('items')) validate('}')