diff --git a/README.md b/README.md index 321921eb..65903754 100644 --- a/README.md +++ b/README.md @@ -666,6 +666,11 @@ Otherwise, instead of raising an error, null values will be coerced as follows: - `object` -> `{}` - `array` -> `[]` +The same applies to `undefined` when it is an item of an array or the value +passed to `stringify()`. A property of an object set to `undefined` is skipped +instead, as described in Missing fields, and a +`required` one still throws. + #### Large Arrays diff --git a/index.js b/index.js index 3f147b9f..7edabedd 100644 --- a/index.js +++ b/index.js @@ -1018,7 +1018,7 @@ function buildObject (context, location, input) { // ${asComment(schemaRef)} function ${functionName} (input) { const obj = ${toJSON('input')} - if (obj === null) return ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_OBJECT'} + if (obj == null) return ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_OBJECT'} let json = '' ${buildInnerObject(context, location, 'obj', true)} @@ -1033,7 +1033,7 @@ function buildObject (context, location, input) { const objVar = `obj_${context.uid++}` const code = ` const ${objVar} = ${toJSON(input)} - if (${objVar} === null) { + if (${objVar} == null) { json += ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_OBJECT'} } else { ${buildInnerObject(context, location, objVar)} @@ -1149,7 +1149,7 @@ function buildArray (context, location, input) { ` functionCode += ` - if (obj === null) return ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_ARRAY'} + if (obj == null) return ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_ARRAY'} if (!Array.isArray(obj)) { throw new TypeError(${JSON.stringify(`The value of '${schemaRef}' does not match schema definition.`)}) } @@ -1274,7 +1274,7 @@ function buildArray (context, location, input) { const objVar = `obj_${context.uid++}` let inlinedCode = ` const ${objVar} = ${input} - if (${objVar} === null) { + if (${objVar} == null) { json += ${nullable ? 'JSON_STR_NULL' : 'JSON_STR_EMPTY_ARRAY'} } else if (!Array.isArray(${objVar})) { throw new TypeError(${JSON.stringify(`The value of '${safeSchemaRef}' does not match schema definition.`)}) @@ -1368,11 +1368,11 @@ function buildArrayTypeCondition (type, accessor) { let condition switch (type) { case 'null': - condition = `${accessor} === null` + condition = `${accessor} == null` break case 'string': condition = `typeof ${accessor} === 'string' || - ${accessor} === null || + ${accessor} == null || ${accessor} instanceof Date || ${accessor} instanceof RegExp || ( @@ -1432,7 +1432,7 @@ function buildMultiTypeSerializer (context, location, input) { switch (type) { case 'null': code += ` - ${statement} (${input} === null) { + ${statement} (${input} == null) { ${nestedResult} } ` @@ -1441,7 +1441,7 @@ function buildMultiTypeSerializer (context, location, input) { code += ` ${statement}( typeof ${input} === "string" || - ${input} === null || + ${input} == null || ${input} instanceof Date || ${input} instanceof RegExp || ( @@ -1465,7 +1465,7 @@ function buildMultiTypeSerializer (context, location, input) { } case 'integer': { code += ` - ${statement}(Number.isInteger(${input}) || ${input} === null) { + ${statement}(Number.isInteger(${input}) || ${input} == null) { ${nestedResult} } ` @@ -1476,7 +1476,7 @@ function buildMultiTypeSerializer (context, location, input) { // by this branch and serialized as an object (dropping its items). Exclude // arrays here so a sibling `array` type in the same `type` list can match. code += ` - ${statement}((typeof ${input} === "object" && !Array.isArray(${input})) || ${input} === null) { + ${statement}((typeof ${input} === "object" && !Array.isArray(${input})) || ${input} == null) { ${nestedResult} } ` @@ -1484,7 +1484,7 @@ function buildMultiTypeSerializer (context, location, input) { } default: { code += ` - ${statement}(typeof ${input} === "${type}" || ${input} === null) { + ${statement}(typeof ${input} === "${type}" || ${input} == null) { ${nestedResult} } ` @@ -1517,7 +1517,7 @@ function buildSingleTypeSerializer (context, location, input) { } else { return ` if (typeof ${input} !== 'string') { - if (${input} === null) { + if (${input} == null) { json += JSON_STR_EMPTY_STRING } else if (${input} instanceof Date) { json += asDateTime(${input}) @@ -1652,7 +1652,7 @@ function buildConstSerializer (location, input) { if (hasNullType) { code += ` - if (${input} === null) { + if (${input} == null) { json += JSON_STR_NULL } else { ` @@ -1905,7 +1905,7 @@ function buildValue (context, location, input) { const nullable = schema.nullable === true if (nullable) { code += ` - if (${input} === null) { + if (${input} == null) { json += JSON_STR_NULL } else { ` diff --git a/lib/projection.js b/lib/projection.js index 5f3bd88f..f1911c5d 100644 --- a/lib/projection.js +++ b/lib/projection.js @@ -35,9 +35,10 @@ // schemas. // // Semantics match the string codegen byte for byte: input.toJSON() honoured, -// `required` missing throws, `undefined` omitted, `default` applied, null -// string -> "", null number -> 0, null object -> {}, Date in a string -> ISO, -// numbers via the asNumber/asInteger rules, booleans via truthiness. +// `required` missing throws, an `undefined` property omitted, `default` +// applied, null or undefined string -> "", number -> 0, object -> {}, +// array -> [], Date in a string -> ISO, numbers via the asNumber/asInteger +// rules, booleans via truthiness. const PRIMITIVES = new Set(['string', 'number', 'integer', 'boolean']) @@ -143,15 +144,15 @@ function primitiveExpr (schema, src, pointerIdx) { const err = `typeMismatch(${pointerIdx})` const single = primitiveExpr({ ...schema, type: base, nullable: false }, src, pointerIdx) if (base === 'string') { - return `(${src} === null ? null : (typeof ${src} === 'string' || ${src} instanceof Date || ${src} instanceof RegExp || (typeof ${src} === 'object' && typeof ${src}.toString === 'function' && ${src}.toString !== Object.prototype.toString)) ? ${single} : ${err})` + return `(${src} == null ? null : (typeof ${src} === 'string' || ${src} instanceof Date || ${src} instanceof RegExp || (typeof ${src} === 'object' && typeof ${src}.toString === 'function' && ${src}.toString !== Object.prototype.toString)) ? ${single} : ${err})` } if (base === 'number') { - return `(${src} === null ? null : typeof ${src} === 'number' ? ${single} : ${err})` + return `(${src} == null ? null : typeof ${src} === 'number' ? ${single} : ${err})` } - return `(${src} === null ? null : typeof ${src} === 'boolean' ? ${src} : ${err})` + return `(${src} == null ? null : typeof ${src} === 'boolean' ? ${src} : ${err})` } if (schema.nullable === true) { - return `(${src} === null ? null : ${primitiveExpr({ ...schema, nullable: false }, src, pointerIdx)})` + return `(${src} == null ? null : ${primitiveExpr({ ...schema, nullable: false }, src, pointerIdx)})` } switch (schema.type) { case 'string': @@ -212,8 +213,8 @@ class Emitter { const result = this.id('r') out.push(`${indent}const ${o} = (${src} !== null && typeof ${src} === 'object' && typeof ${src}.toJSON === 'function') ? ${src}.toJSON() : ${src}`) out.push(`${indent}let ${result}`) - out.push(`${indent}if (${o} === null) {`) - // a null input is written as {} (same as the codegen), or as null when nullable + out.push(`${indent}if (${o} == null) {`) + // a null or undefined input is written as {} (same as the codegen), or as null when nullable out.push(`${indent} ${result} = ${schema.nullable === true ? 'null' : '{}'}`) out.push(`${indent}} else {`) for (const k of requiredList) { @@ -268,8 +269,8 @@ class Emitter { const i = this.id('i') const result = this.id('r') out.push(`${indent}let ${result}`) - out.push(`${indent}if (${src} === null) {`) - // a null input is written as [] (same as the codegen), or as null when nullable + out.push(`${indent}if (${src} == null) {`) + // a null or undefined input is written as [] (same as the codegen), or as null when nullable out.push(`${indent} ${result} = ${schema.nullable === true ? 'null' : '[]'}`) out.push(`${indent}} else {`) out.push(`${indent} if (!Array.isArray(${src})) typeMismatch(${this.pointerIndex(schema[POINTER])})`) @@ -347,13 +348,13 @@ ${body.join('\n')} const projectionHelpers = ` const asStringValue = (v) => { if (typeof v === 'string') return v - if (v === null) return '' + if (v == null) return '' if (v instanceof Date) return serializer.asDateTimeValue(v) if (v instanceof RegExp) return v.source return v.toString() } const asDateTimeValue = (v) => { - if (v === null) return '' + if (v == null) return '' if (v instanceof Date) return serializer.asDateTimeValue(v) if (typeof v === 'string') return v throw new Error('The value "' + v + '" cannot be converted to a date-time.') @@ -364,7 +365,7 @@ const projectionHelpers = ` const asDateValue = (v) => typeof v === 'string' ? v : serializer.asDate(v).slice(1, -1) const asTimeValue = (v) => typeof v === 'string' ? v : serializer.asTime(v).slice(1, -1) const asNumberValue = (v) => { - const num = typeof v === 'number' ? v : Number(v) + const num = typeof v === 'number' ? v : v == null ? 0 : Number(v) if (num !== num) throw new Error('The value "' + v + '" cannot be converted to a number.') return (num === Infinity || num === -Infinity) ? null : num } diff --git a/lib/serializer.js b/lib/serializer.js index 8d2f1e6c..cc4d85ea 100644 --- a/lib/serializer.js +++ b/lib/serializer.js @@ -117,6 +117,9 @@ module.exports = class Serializer { } else if (typeof i === 'bigint') { return i.toString() } + if (i == null) { + return '0' + } /* eslint no-undef: "off" */ const integer = this.parseInteger(i) // check if number is Infinity or NaN @@ -128,6 +131,9 @@ module.exports = class Serializer { } asNumber (i) { + if (i == null) { + return '0' + } // fast cast to number const num = Number(i) // check if number is NaN @@ -146,7 +152,7 @@ module.exports = class Serializer { } asDateTime (date) { - if (date === null) return '""' + if (date == null) return '""' if (date instanceof Date) { return asDateTimeString(date) } @@ -157,7 +163,7 @@ module.exports = class Serializer { } asDate (date) { - if (date === null) return '""' + if (date == null) return '""' if (date instanceof Date) { const year = asYear(date.getFullYear()) if (year === null) { @@ -172,7 +178,7 @@ module.exports = class Serializer { } asTime (date) { - if (date === null) return '""' + if (date == null) return '""' if (date instanceof Date) { const hours = TWO_DIGITS[date.getHours()] // undefined only for an invalid Date; let toISOString() raise as before @@ -241,7 +247,7 @@ module.exports = class Serializer { if (j > 0) json += ',' if (typeof item === 'string') { json += asString(item) - } else if (item === null) { + } else if (item == null) { json += '""' } else if (item instanceof Date) { json += asDateTimeString(item) diff --git a/test/missing-values.test.js b/test/missing-values.test.js index 5ddf4771..34537cee 100644 --- a/test/missing-values.test.js +++ b/test/missing-values.test.js @@ -86,3 +86,263 @@ test('handle null when value should be boolean', (t) => { t.assert.equal('{"bool":false}', stringify({ bool: null })) }) + +test('handle undefined when value should be string', (t) => { + t.plan(1) + + const stringify = build({ + type: 'string' + }) + + t.assert.equal('""', stringify(undefined)) +}) + +test('handle undefined in array of strings', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: { + type: 'string' + } + }) + + t.assert.equal('["test1","test2","test3",""]', stringify(['test1', 'test2', 'test3', undefined])) +}) + +test('handle undefined in array of integers', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: { + type: 'integer' + } + }) + + t.assert.equal('[1,2,0]', stringify([1, 2, undefined])) +}) + +test('handle undefined in array of numbers', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: { + type: 'number' + } + }) + + t.assert.equal('[1.5,0]', stringify([1.5, undefined])) +}) + +test('handle undefined in array of booleans', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: { + type: 'boolean' + } + }) + + t.assert.equal('[true,false]', stringify([true, undefined])) +}) + +test('handle undefined in array of objects', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: { + type: 'object', + properties: { + str: { + type: 'string' + } + } + } + }) + + t.assert.equal('[{"str":"test"},{}]', stringify([{ str: 'test' }, undefined])) +}) + +test('handle undefined in array of date-time strings', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: { + type: 'string', + format: 'date-time' + } + }) + + t.assert.equal('["2020-01-01T00:00:00.000Z",""]', stringify(['2020-01-01T00:00:00.000Z', undefined])) +}) + +test('handle undefined in array of date strings', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: { + type: 'string', + format: 'date' + } + }) + + t.assert.equal('["2020-01-01",""]', stringify(['2020-01-01', undefined])) +}) + +test('handle undefined in array of time strings', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: { + type: 'string', + format: 'time' + } + }) + + t.assert.equal('["00:00:00",""]', stringify(['00:00:00', undefined])) +}) + +test('handle undefined when value is nullable', (t) => { + t.plan(1) + + const stringify = build({ + type: 'string', + nullable: true + }) + + t.assert.equal('null', stringify(undefined)) +}) + +test('handle undefined in tuple of strings', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: [ + { + type: 'string' + }, + { + type: 'string' + } + ] + }) + + t.assert.equal('["test",""]', stringify(['test', undefined])) +}) + +test('handle undefined in array with multiple item types', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: { + type: ['string', 'integer'] + } + }) + + t.assert.equal('["test",""]', stringify(['test', undefined])) +}) + +test('handle undefined in nested arrays', (t) => { + t.plan(1) + + const stringify = build({ + type: 'array', + items: { + type: 'array', + items: { + type: 'string' + } + } + }) + + t.assert.equal('[["test"],[]]', stringify([['test'], undefined])) +}) + +test('undefined object properties are still skipped', (t) => { + t.plan(1) + + const stringify = build({ + type: 'object', + properties: { + str: { + type: 'string' + } + } + }) + + t.assert.equal('{}', stringify({ str: undefined })) +}) + +test('handle undefined in multi-type, tuple and const positions', (t) => { + t.plan(6) + + t.assert.equal('["a",null]', build({ type: 'array', items: { type: ['null', 'string'] } })(['a', undefined])) + t.assert.equal('[1,0]', build({ type: 'array', items: { type: ['integer', 'string'] } })([1, undefined])) + t.assert.equal('[{},{}]', build({ type: 'array', items: { type: ['object', 'string'] } })([{}, undefined])) + t.assert.equal('[true,false]', build({ type: 'array', items: { type: ['boolean', 'string'] } })([true, undefined])) + t.assert.equal('[null]', build({ type: 'array', items: [{ type: 'null' }] })([undefined])) + t.assert.equal('["x",null]', build({ type: 'array', items: { type: ['string', 'null'], const: 'x' } })(['x', undefined])) +}) + +test('handle undefined in an array of strings of any length', (t) => { + // from 8 elements an array of strings takes the primitive array path + const stringify = build({ type: 'array', items: { type: 'string' } }) + const lengths = [1, 4, 7, 8, 9, 40] + t.plan(lengths.length * 3) + for (const length of lengths) { + for (const position of [0, Math.floor(length / 2), length - 1]) { + const input = Array.from({ length }, (_, i) => i === position ? undefined : 'item ' + i) + const expected = JSON.stringify(input.map((item) => item === undefined ? '' : item)) + t.assert.equal(stringify(input), expected, `length ${length}, undefined at ${position}`) + } + } +}) + +test("undefined gives the same output with objectMechanism 'native'", (t) => { + // forceProjection enables the projection on every Node.js version + const native = { objectMechanism: 'native', forceProjection: true } + const withUndefined = (first, more) => [first, undefined, ...Array.from({ length: 9 }, () => more), undefined] + const cases = [ + [{ type: 'array', items: { type: 'string' } }, withUndefined('a', 'b'), '["a","","b","b","b","b","b","b","b","b","b",""]'], + [{ type: 'array', items: { type: 'string' } }, [undefined, 'a'], '["","a"]'], + [{ type: 'array', items: { type: 'number' } }, withUndefined(1.5, 2), '[1.5,0,2,2,2,2,2,2,2,2,2,0]'], + [{ type: 'array', items: { type: 'integer' } }, [1, undefined], '[1,0]'], + [{ type: 'array', items: { type: 'boolean' } }, [true, undefined], '[true,false]'], + [{ type: 'array', items: { type: 'string', format: 'date-time' } }, ['2026-01-02T03:04:05.000Z', undefined], '["2026-01-02T03:04:05.000Z",""]'], + [{ type: 'array', items: { type: 'string', format: 'date' } }, ['2026-01-02', undefined], '["2026-01-02",""]'], + [{ type: 'array', items: { type: 'string', format: 'time' } }, ['03:04:05', undefined], '["03:04:05",""]'], + [{ type: 'array', items: { type: 'string', nullable: true } }, ['a', undefined], '["a",null]'], + [{ type: 'array', items: { type: 'number', nullable: true } }, [1, undefined], '[1,null]'], + [{ type: 'array', items: { type: ['string', 'null'] } }, ['a', undefined], '["a",null]'], + [{ type: 'array', items: { type: ['null', 'number'] } }, [1, undefined], '[1,null]'], + [{ type: 'array', items: { type: ['boolean', 'null'] } }, [true, undefined], '[true,null]'], + [{ type: 'array', items: { type: 'object', properties: { a: { type: 'string' } } } }, [{ a: 'x' }, undefined], '[{"a":"x"},{}]'], + [{ type: 'array', items: { type: 'object', nullable: true, properties: { a: { type: 'string' } } } }, [{ a: 'x' }, undefined], '[{"a":"x"},null]'], + [{ type: 'array', items: { type: 'array', items: { type: 'string' } } }, [['x'], undefined], '[["x"],[]]'], + [{ type: 'array', items: { type: 'array', nullable: true, items: { type: 'string' } } }, [['x'], undefined], '[["x"],null]'], + [{ type: 'object', properties: { a: { type: 'string' } } }, undefined, '{}'], + [{ type: 'object', nullable: true, properties: { a: { type: 'string' } } }, undefined, 'null'], + [{ type: 'object', properties: { a: { type: 'string' } } }, { toJSON () { return undefined } }, '{}'], + [{ type: 'array', items: { type: 'string' } }, undefined, '[]'], + [{ type: 'array', nullable: true, items: { type: 'string' } }, undefined, 'null'], + // an undefined property is still skipped, and a required one still throws + [{ type: 'object', properties: { a: { type: 'string' }, b: { type: 'string' } } }, { a: undefined, b: 'x' }, '{"b":"x"}'] + ] + t.plan(cases.length * 2 + 2) + for (const [schema, input, expected] of cases) { + t.assert.equal(build(schema)(input), expected, 'default: ' + JSON.stringify(schema)) + t.assert.equal(build(schema, native)(input), expected, 'native: ' + JSON.stringify(schema)) + } + const required = { type: 'object', required: ['a'], properties: { a: { type: 'string' } } } + t.assert.throws(() => build(required)({ a: undefined }), /"a" is required!/) + t.assert.throws(() => build(required, native)({ a: undefined }), /"a" is required!/) +})