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
34 changes: 22 additions & 12 deletions ark/schema/roots/root.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ import type {
StandardJSONSchemaV1,
StandardSchemaV1
} from "../shared/standardSchema.ts"
import type { ToJsonSchema } from "../shared/toJsonSchema.ts"
import { ToJsonSchema } from "../shared/toJsonSchema.ts"
import { arkKind, hasArkKind } from "../shared/utils.ts"
import { assertDefaultValueAssignability } from "../structure/optional.ts"
import type { Prop } from "../structure/prop.ts"
Expand Down Expand Up @@ -108,16 +108,8 @@ export abstract class BaseRoot<
return { value: out }
},
jsonSchema: {
input: opts =>
this.rawIn.toJsonSchema({
target: validateStandardJsonSchemaTarget(opts.target),
...opts.libraryOptions
}) as never,
output: opts =>
this.rawOut.toJsonSchema({
target: validateStandardJsonSchemaTarget(opts.target),
...opts.libraryOptions
}) as never
input: opts => toStandardJsonSchema(this.rawIn, opts),
output: opts => toStandardJsonSchema(this.rawOut, opts)
}
}
}
Expand Down Expand Up @@ -211,7 +203,7 @@ export abstract class BaseRoot<
// metaJson serializes non-primitives like [5] to references like
// "$ark.array1", so prefer the original value when it is valid JSON
// (jsonData's object domain also allows functions, so exclude them)
result[k] =
const jsonValue =
typeof v !== "function" && $ark.intrinsic.jsonData.allows(v) ? v
: k === "default" ?
ctx.fallback.defaultValue({
Expand All @@ -220,6 +212,7 @@ export abstract class BaseRoot<
value: v as never
})
: (this.metaJson as dict)[k]
if (jsonValue !== undefined) result[k] = jsonValue
}

return result
Expand Down Expand Up @@ -732,6 +725,23 @@ const validateStandardJsonSchemaTarget = (
return target
}

const toStandardJsonSchema = (
node: BaseRoot,
opts: StandardJSONSchemaV1.Options
): Record<string, unknown> => {
const ctx = mergeToJsonSchemaConfigs(node.$.resolvedConfig.toJsonSchema, {
target: validateStandardJsonSchemaTarget(opts.target),
...opts.libraryOptions
})
const fallback = flatMorph(ctx.fallback, (code, handler) => [
code,
handler === ToJsonSchema.defaultConfig.fallback[code] ?
ToJsonSchema.standardFallback[code]
: handler
]) as ToJsonSchema.HandlerByCode
return node.toJsonSchema({ ...ctx, fallback }) as never
}

export const exclusivizeRangeSchema = <schema extends UnknownRangeSchema>(
schema: schema
): schema =>
Expand Down
24 changes: 22 additions & 2 deletions ark/schema/shared/toJsonSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,24 @@ const defaultConfig: ToJsonSchema.Context = {
}
}

// Standard JSON Schema converters only throw for unsupported options, so
// these keep the part of a type JSON Schema can represent, or {} if none
const standardFallback: ToJsonSchema.HandlerByCode = {
arrayObject: ctx => ctx.base,
// draft-07 tuples keep their prefix in items
arrayPostfix: ({ base: { items, additionalItems, ...base } }) =>
(Array.isArray(items) ? { ...base, items } : base) as never,
defaultValue: () => undefined,
domain: ctx => ctx.base,
morph: ctx => ctx.base,
patternIntersection: ctx => ctx.base,
predicate: ctx => ctx.base,
proto: ctx => ctx.base,
symbolKey: ctx => ctx.base,
unit: ctx => ctx.base,
date: ctx => ctx.base
}

export const ToJsonSchema = {
Error: ToJsonSchemaError,
throw: (...args: ConstructorParameters<typeof ToJsonSchemaError>): never => {
Expand All @@ -63,7 +81,8 @@ export const ToJsonSchema = {
throwInternalError(
`Unexpected JSON Schema input for ${kind}: ${printable(schema)}`
),
defaultConfig
defaultConfig,
standardFallback
}

export declare namespace ToJsonSchema {
Expand Down Expand Up @@ -175,7 +194,8 @@ export declare namespace ToJsonSchema {
{
arrayObject: (ctx: ArrayObjectContext) => JsonSchema.Structure
arrayPostfix: (ctx: ArrayPostfixContext) => VariadicArraySchema
defaultValue: (ctx: DefaultValueContext) => JsonSchema
// undefined omits the default
defaultValue: (ctx: DefaultValueContext) => JsonSchema | undefined
domain: (ctx: DomainContext) => JsonSchema
morph: (ctx: MorphContext) => JsonSchema
patternIntersection: (
Expand Down
3 changes: 2 additions & 1 deletion ark/schema/structure/sequence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -535,14 +535,15 @@ export class SequenceNode extends BaseConstraint<Sequence.Declaration> {
if (el.kind === "defaultables") {
const value =
typeof el.default === "function" ? el.default() : el.default
valueSchema.default =
const jsonDefault =
$ark.intrinsic.jsonData.allows(value) ?
value
: ctx.fallback.defaultValue({
code: "defaultValue",
base: valueSchema,
value
})
if (jsonDefault !== undefined) valueSchema.default = jsonDefault
}
return valueSchema
})
Expand Down
3 changes: 2 additions & 1 deletion ark/schema/structure/structure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -839,14 +839,15 @@ export class StructureNode extends BaseConstraint<Structure.Declaration> {
if (prop.hasDefault()) {
const value =
typeof prop.default === "function" ? prop.default() : prop.default
valueSchema.default =
const jsonDefault =
$ark.intrinsic.jsonData.allows(value) ?
value
: ctx.fallback.defaultValue({
code: "defaultValue",
base: valueSchema,
value
})
if (jsonDefault !== undefined) valueSchema.default = jsonDefault
}

schema.properties![prop.key] = valueSchema
Expand Down
64 changes: 64 additions & 0 deletions ark/type/__tests__/standardSchema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,70 @@ contextualize(() => {
).throws(writeInvalidJsonSchemaTargetMessage("openapi-3.0"))
})

it("converts what JSON Schema can't represent to {}", () => {
const T = type({
big: "bigint",
date: "Date",
maybe: "string | undefined",
even: type("number").narrow(n => n % 2 === 0),
ends: ["...", "string[]", "number"],
count: ["bigint", "=", () => 0n]
})
const standard: StandardJSONSchemaV1 = T
attest(
standard["~standard"].jsonSchema.input({ target: "draft-2020-12" })
).snap({
$schema: "https://json-schema.org/draft/2020-12/schema",
type: "object",
properties: {
big: {},
date: {},
ends: { type: "array", minItems: 1 },
even: { type: "number" },
maybe: { anyOf: [{ type: "string" }, {}] },
count: {}
},
required: ["big", "date", "ends", "even", "maybe"]
})
})

it("converts the output of a transform to {}", () => {
const T = type("string").pipe(s => s.length)
const standard: StandardJSONSchemaV1 = T
attest(
standard["~standard"].jsonSchema.output({ target: "draft-2020-12" })
).snap({ $schema: "https://json-schema.org/draft/2020-12/schema" })
})

it("keeps a postfix tuple's draft-07 prefix", () => {
const T = type(["string", "...", "number[]", "boolean"])
const standard: StandardJSONSchemaV1 = T
attest(
standard["~standard"].jsonSchema.input({ target: "draft-07" })
).snap({
$schema: "http://json-schema.org/draft-07/schema#",
type: "array",
minItems: 2,
items: [{ type: "string" }]
})
})

it("uses configured fallbacks", () => {
const T = type("bigint")
const standard: StandardJSONSchemaV1 = T
attest(
standard["~standard"].jsonSchema.input({
target: "draft-2020-12",
libraryOptions: {
fallback: { domain: () => ({ type: "integer" }) }
}
})
).snap({
$schema: "https://json-schema.org/draft/2020-12/schema",
type: "integer"
})
})

it("generates different input/output schemas for morphs", () => {
const T = type({ foo: "string.numeric.parse" })
const standard: StandardJSONSchemaV1 = T
Expand Down
Loading