Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -758,11 +758,11 @@ const stringify = fastJson(schema, { objectMechanism: 'native' })

The projection covers schemas made only of:

- `object` with `properties` (no `patternProperties`, `dependencies`,
combinators or `$ref`; `additionalProperties` absent or `false`), with at
least one property;
- `object` with `properties` (no `patternProperties`, `dependencies` or
combinators; `additionalProperties` absent or `false`), with at least one
property;
- `string` (with any `format` except `unsafe`), `number`, `integer`, `boolean`,
without `const`, combinators or `$ref`;
without `const` or combinators;
- the two-element forms `['string', 'null']`, `['number', 'null']` and
`['boolean', 'null']` (in either order), with the same strict type dispatch
as the default mechanism;
Expand All @@ -771,6 +771,13 @@ The projection covers schemas made only of:

Each of them can be `nullable: true` and can have an `enum`.

Each of them can also be reached through a `$ref`, to a definition of the same
schema or to an external schema. Two kinds of `$ref` keep the default
mechanism: a recursive one, and one with other keywords next to it (a
`nullable` or a `default`, for instance; `title`, `description` and the other
annotations are fine). The same holds for a root schema that is itself a
`$ref` with its `definitions` next to it.

Any other schema silently uses the default mechanism, so the option is always
safe to enable. The projection only pays off where V8 has the fast path, so on
Node.js 24 and older the option is a no-op and the default mechanism is used.
Expand Down
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -554,7 +554,11 @@ function build (schema, options) {
// `forceProjection` is an internal, undocumented escape hatch used by the
// test suite to exercise the projection on runtimes where it is gated off.
if (context.objectMechanism === 'native' && (options.forceProjection === true || PROJECTION_SUPPORTED)) {
projection = buildProjection(schema)
projection = buildProjection(location, {
resolve: (location) => resolveRef(context, location),
pointer: (location) => getSafeSchemaRef(context, location),
ignoredSiblings: IGNORED_REF_SIBLING_KEYWORDS
})
}
if (projection === null) {
code = buildValue(context, location, 'input')
Expand Down
108 changes: 78 additions & 30 deletions lib/projection.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@
// always taken, even when the user's input would have bailed out of it.
//
// Projectable schemas (every node must be one of these):
// - object with `properties` only: no patternProperties, combinators, $ref,
// - object with `properties` only: no patternProperties, combinators,
// dependencies, and additionalProperties absent or false; at least one
// property;
// - string / number / integer / boolean without const, combinators, $ref;
// - string / number / integer / boolean without const or combinators;
// a string may have any format but 'unsafe', which is written unescaped;
// - the two-element forms ['string'|'number'|'boolean', 'null'] (any order),
// with the strict no-coercion dispatch of the multi-type codegen;
Expand All @@ -23,6 +23,9 @@
// elements get their own scratch tree from a per-element slot pool.
// Any of them may be `nullable: true` (null is then written as null) and may
// carry an `enum`, which the codegen does not use once the type is known.
// Any of them may be reached through a $ref, to the same schema or to an
// external one, as long as the $ref has no keyword next to it that the codegen
// would merge and the target is not recursive.
// Anything else makes buildProjection return null and the caller falls back to
// the string codegen, so the option never changes output for unsupported
// schemas.
Expand All @@ -47,37 +50,78 @@ function nullableMultiType (schema) {

function hasDispatchKeyword (s) {
return s.const !== undefined || s.allOf !== undefined || s.anyOf !== undefined ||
s.oneOf !== undefined || s.if !== undefined || s.$ref !== undefined
s.oneOf !== undefined || s.if !== undefined
}

function isProjectable (schema, depth = 0) {
if (typeof schema !== 'object' || schema === null || depth > 32) return false
if (hasDispatchKeyword(schema)) return false
if (Array.isArray(schema.type)) return nullableMultiType(schema) !== null
// The JSON pointer of a projected node, as the codegen writes it in its errors.
const POINTER = Symbol('pointer')

// A $ref is projected by expanding its target in place, so a schema that is
// used many times is also copied many times. Past this number of expanded
// nodes the schema is left to the codegen, which shares one function per schema.
const MAX_REF_NODES = 1000

// Returns a copy of the schema at `location`, with every $ref replaced by its
// target and every node tagged with its JSON pointer, or null when the schema
// is not projectable.
function resolveProjectable (location, refs, state, depth) {
const schema = location.schema
if (typeof schema !== 'object' || schema === null || depth > 32) return null

// truthiness, as in the codegen: an empty $ref is not a reference
if (!schema.$ref) return resolveNode(location, refs, state, depth)

// the codegen merges the keywords next to a $ref with its target
for (const key in schema) {
if (!refs.ignoredSiblings.has(key)) return null
}
location = refs.resolve(location)

// a target that is already being expanded is a recursive schema
const target = location.getSchemaRef()
if (state.open.has(target)) return null
state.open.add(target)
const node = resolveNode(location, refs, state, depth)
state.open.delete(target)
return node
}

function resolveNode (location, refs, state, depth) {
const schema = location.schema
if (state.open.size !== 0 && ++state.refNodes > MAX_REF_NODES) return null
if (hasDispatchKeyword(schema)) return null

const node = { ...schema, [POINTER]: refs.pointer(location) }
if (Array.isArray(schema.type)) return nullableMultiType(schema) !== null ? node : null

if (schema.type === 'object') {
if ((schema.additionalProperties !== undefined && schema.additionalProperties !== false) ||
schema.patternProperties !== undefined ||
schema.dependencies !== undefined ||
typeof schema.properties !== 'object' || schema.properties === null) {
return false
return null
}
const keys = Object.keys(schema.properties)
if (keys.length === 0) return false
if (keys.length === 0) return null
const propertiesLocation = location.getPropertyLocation('properties')
node.properties = Object.create(null)
for (const key of keys) {
if (!isProjectable(schema.properties[key], depth + 1)) return false
const property = resolveProjectable(propertiesLocation.getPropertyLocation(key), refs, state, depth + 1)
if (property === null) return null
node.properties[key] = property
}
return true
return node
}

if (schema.type === 'array') {
if (schema.items === undefined || Array.isArray(schema.items) || schema.additionalItems !== undefined) return false
return isProjectable(schema.items, depth + 1)
if (schema.items === undefined || Array.isArray(schema.items) || schema.additionalItems !== undefined) return null
node.items = resolveProjectable(location.getPropertyLocation('items'), refs, state, depth + 1)
return node.items !== null ? node : null
}

if (!PRIMITIVES.has(schema.type)) return false
if (!PRIMITIVES.has(schema.type)) return null
// the codegen reads `format` only for a string
return schema.type !== 'string' || schema.format !== 'unsafe'
return schema.type !== 'string' || schema.format !== 'unsafe' ? node : null
}

function primitiveExpr (schema, src, pointerIdx) {
Expand Down Expand Up @@ -178,7 +222,7 @@ class Emitter {
return `${holder}.${field}`
}

fillObject (schema, src, dst, out, indent, pointer, holder, slotFields) {
fillObject (schema, src, dst, out, indent, holder, slotFields) {
const props = schema.properties
const requiredList = schema.required || []
const required = new Set(requiredList)
Expand Down Expand Up @@ -213,7 +257,7 @@ class Emitter {
out.push(`${indent} ${dst}[${ks}] = undefined`)
}
out.push(`${indent} } else {`)
out.push(`${indent} ${dst}[${ks}] = ${this.valueExpr(p, v, out, indent + ' ', `${pointer}/properties/${k}`, holder, slotFields)}`)
out.push(`${indent} ${dst}[${ks}] = ${this.valueExpr(p, v, out, indent + ' ', holder, slotFields)}`)
out.push(`${indent} }`)
}
out.push(`${indent}}`)
Expand All @@ -232,27 +276,27 @@ class Emitter {

// Returns an expression for the projected value of `src`; may push
// preparatory statements to `out` (filling a nested scratch) first.
valueExpr (schema, src, out, indent, pointer, holder, slotFields) {
valueExpr (schema, src, out, indent, holder, slotFields) {
if (schema.type === 'object') {
const scratch = this.allocScratch(schema, holder, slotFields)
return this.fillObject(schema, src, scratch, out, indent, pointer, holder, slotFields)
return this.fillObject(schema, src, scratch, out, indent, holder, slotFields)
}
if (schema.type === 'array') {
const pool = this.allocArray(holder, slotFields)
return this.fillArray(schema, src, pool, out, indent, pointer, holder, slotFields)
return this.fillArray(schema, src, pool, out, indent, holder, slotFields)
}
return primitiveExpr(schema, src, this.pointerIndex(pointer))
return primitiveExpr(schema, src, this.pointerIndex(schema[POINTER]))
}

fillArray (schema, src, pool, out, indent, pointer, holder, slotFields) {
fillArray (schema, src, pool, out, indent, holder, slotFields) {
const items = schema.items
const n = this.id('n')
const i = this.id('i')
const result = this.resultOf(schema, pool, out, indent)
out.push(`${indent}if (${src} === null) {`)
out.push(`${indent} ${result !== pool ? `${result} = null` : `${pool}.length = 0`}`)
out.push(`${indent}} else {`)
out.push(`${indent} if (!Array.isArray(${src})) typeMismatch(${this.pointerIndex(pointer)})`)
out.push(`${indent} if (!Array.isArray(${src})) typeMismatch(${this.pointerIndex(schema[POINTER])})`)
out.push(`${indent} const ${n} = ${src}.length`)
// Assigning to `length` is not a plain store: it goes through the array
// length setter even when the value does not change, and that costs more
Expand All @@ -272,7 +316,7 @@ class Emitter {
const innerHolder = this.id('slot')
const innerFields = []
const inner = []
const expr = this.valueExpr(items, el, inner, indent + ' ', `${pointer}/items`, innerHolder, innerFields)
const expr = this.valueExpr(items, el, inner, indent + ' ', innerHolder, innerFields)
this.decls.push(`function ${factory} () { return { ${innerFields.map(([f, lit]) => `${f}: ${lit}`).join(', ')} } }`)
out.push(`${indent} for (let ${i} = ${slots}.length; ${i} < ${n}; ${i}++) ${slots}[${i}] = ${factory}()`)
out.push(`${indent} for (let ${i} = 0; ${i} < ${n}; ${i}++) {`)
Expand All @@ -283,7 +327,7 @@ class Emitter {
out.push(`${indent} }`)
} else {
out.push(`${indent} for (let ${i} = 0; ${i} < ${n}; ${i}++) {`)
out.push(`${indent} ${pool}[${i}] = ${primitiveExpr(items, `${src}[${i}]`, this.pointerIndex(`${pointer}/items`))}`)
out.push(`${indent} ${pool}[${i}] = ${primitiveExpr(items, `${src}[${i}]`, this.pointerIndex(items[POINTER]))}`)
out.push(`${indent} }`)
}
out.push(`${indent}}`)
Expand All @@ -292,14 +336,18 @@ class Emitter {
}

// Returns the full body of the context function (declarations + main) or null
// when the schema is not projectable.
function buildProjection (schema) {
if (!isProjectable(schema)) return null
// when the schema at `location` is not projectable. `refs` is how the codegen
// reads a $ref: `resolve(location)` gives the location of its target,
// `pointer(location)` the JSON pointer used in the errors, `ignoredSiblings`
// the keywords that may stand next to a $ref without changing its target.
function buildProjection (location, refs) {
const schema = resolveProjectable(location, refs, { open: new Set(), refNodes: 0 }, 0)
if (schema === null) return null
if (schema.type !== 'object' && schema.type !== 'array') return null // primitive roots gain nothing
const em = new Emitter()
const body = []
// root object: a null input serializes as {} (same as the codegen)
const rootExpr = em.valueExpr(schema, 'input', body, ' ', '#', null, null)
const rootExpr = em.valueExpr(schema, 'input', body, ' ', null, null)
// The scratch objects are shared by every call of a serializer, so a call
// that starts while another one is filling them (a getter or a toJSON() of
// the input serializing with the same function) would overwrite the values
Expand Down Expand Up @@ -400,4 +448,4 @@ const projectionHelpers = `
}
`

module.exports = { buildProjection, isProjectable }
module.exports = { buildProjection }
Loading
Loading