From 5f9e1fc0d5cfc44199e7ab56f9e5cfd67c1d0f36 Mon Sep 17 00:00:00 2001 From: Giulio Canti Date: Wed, 2 Dec 2026 13:42:59 +0100 Subject: [PATCH 1/3] Add Schema.isWellFormed for UTF-16 strings (#11335) --- .changeset/schema-is-well-formed.md | 5 + packages/effect/src/Schema.ts | 32 ++++ packages/effect/src/SchemaRepresentation.ts | 18 +++ .../effect/src/internal/arbitrary/regexp.ts | 32 ++-- .../effect/src/internal/arbitrary/schema.ts | 142 ++++++++++-------- .../internal/schema/schemaCodegenBuiltIns.ts | 1 + .../effect/test/arbitrary/Arbitrary.test.ts | 128 ++++++++++++++++ packages/effect/test/schema/Schema.test.ts | 23 +++ .../representation/builtInRevivers.test.ts | 11 ++ .../schema/representation/codegen.test.ts | 1 + .../test/schema/toJsonSchemaDocument.test.ts | 10 ++ 11 files changed, 331 insertions(+), 72 deletions(-) create mode 100644 .changeset/schema-is-well-formed.md diff --git a/.changeset/schema-is-well-formed.md b/.changeset/schema-is-well-formed.md new file mode 100644 index 00000000000..30878af5c12 --- /dev/null +++ b/.changeset/schema-is-well-formed.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Add `Schema.isWellFormed()` to validate Unicode strings and generate well-formed examples with `Arbitrary.schema`. diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 0fc4a8341ac..5f8e1c6f97e 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -90,6 +90,7 @@ import * as SchemaTransformation from "./SchemaTransformation.ts" import * as SemVer_ from "./SemVer.ts" import * as SemVerRange_ from "./SemVerRange.ts" import type { StandardJSONSchemaV1, StandardSchemaV1 } from "./StandardSchema.ts" +import * as Str from "./String.ts" import type { Assign, Lambda, Mutable, Simplify } from "./Struct.ts" import * as Struct_ from "./Struct.ts" import type { IsUnion, RequiredKeys } from "./Types.ts" @@ -6919,6 +6920,36 @@ export function isTrimmed(annotations?: Annotations.Filter) { } ) } +/** + * Validates that a string contains no unpaired UTF-16 surrogates. + * + * **When to use** + * + * Use when text must cross an encoding boundary that requires well-formed Unicode. + * + * **Details** + * + * Accepts empty strings and supplementary characters such as emoji. Arbitrary + * generation preserves complete surrogate pairs when shrinking examples. + * JSON Schema expresses this check as a Unicode pattern. + * + * @see {@link isMaxCodePoints} for limiting the code point count + * @stability stable + * @category validation + * @since 4.3.0 + */ +export function isWellFormed(annotations?: Annotations.Filter) { + return makeFilter(Str.isWellFormed, { + expected: "a well-formed Unicode string", + representation: { + id: "effect/schema/isWellFormed", + payload: null + }, + toJsonSchema: () => ({ pattern: /^[^\uD800-\uDFFF]*$/u.source }), + arbitraryConstraint: { wellFormed: true }, + ...annotations + }) +} /** * Validates that a string matches the specified regular expression pattern. * @@ -19091,6 +19122,7 @@ export declare namespace Annotations { readonly maxLength?: number | undefined readonly minCodePoints?: number | undefined readonly maxCodePoints?: number | undefined + readonly wellFormed?: true | undefined readonly minSize?: number | undefined readonly maxSize?: number | undefined readonly minProperties?: number | undefined diff --git a/packages/effect/src/SchemaRepresentation.ts b/packages/effect/src/SchemaRepresentation.ts index 65d89423f04..a91ce46719d 100644 --- a/packages/effect/src/SchemaRepresentation.ts +++ b/packages/effect/src/SchemaRepresentation.ts @@ -805,6 +805,24 @@ export const isTrimmedReviver: FilterReviver = makeReviverFilter( ({ annotations }) => Schema.isTrimmed(annotations) ) +/** + * Reviver for persisted `isWellFormed` checks. + * + * **When to use** + * + * Use when reconstructing documents containing checks created by {@link Schema.isWellFormed}. + * + * @see {@link Schema.isWellFormed} for creating the corresponding check + * @stability stable + * @category validation + * @since 4.3.0 + */ +export const isWellFormedReviver: FilterReviver = makeReviverFilter( + "effect/schema/isWellFormed", + Schema.Null, + ({ annotations }) => Schema.isWellFormed(annotations) +) + /** * Reviver for persisted `isPattern` checks. * diff --git a/packages/effect/src/internal/arbitrary/regexp.ts b/packages/effect/src/internal/arbitrary/regexp.ts index af8d52b5289..c9e278c616a 100644 --- a/packages/effect/src/internal/arbitrary/regexp.ts +++ b/packages/effect/src/internal/arbitrary/regexp.ts @@ -1,4 +1,5 @@ import type * as Schema from "../../Schema.ts" +import * as Str from "../../String.ts" import * as Model from "./model.ts" type Pattern = Schema.Annotations.ToArbitrary.Pattern @@ -146,13 +147,16 @@ function concatenation(nodes: ReadonlyArray): Node { } } -function alternation(nodes: ReadonlyArray): Node { +function alternation(nodes: ReadonlyArray, wellFormed = false): Node { const flattened: Array = [] for (const node of nodes) { if (node._tag === "Alternation") flattened.push(...node.nodes) else flattened.push(node) } - return flattened.length === 1 ? flattened[0] : { _tag: "Alternation", nodes: flattened } + const choices = wellFormed && flattened.length > 1 + ? flattened.filter((node) => node._tag !== "Literal" || Str.isWellFormed(node.value)) + : flattened + return choices.length === 1 ? choices[0] : { _tag: "Alternation", nodes: choices } } function normalizeIntervals(intervals: ReadonlyArray): ReadonlyArray { @@ -276,25 +280,28 @@ class Parser { private index = 0 private supported = true private readonly source: string - private readonly dotAll: boolean + private readonly flags: string + private readonly wellFormed: boolean - constructor(source: string, dotAll: boolean) { + constructor({ flags, source }: Pattern, wellFormed: boolean) { this.source = source - this.dotAll = dotAll + this.flags = flags + this.wellFormed = wellFormed } parse(): Node | undefined { - const node = this.parseAlternation() + const node = this.parseAlternation(true) return this.supported && this.index === this.source.length ? node : undefined } - private parseAlternation(): Node { + private parseAlternation(root = false): Node { const nodes = [this.parseConcatenation()] while (this.peek() === "|") { this.index++ nodes.push(this.parseConcatenation()) } - return alternation(nodes) + // Without the Unicode flag, a surrogate can pair with a literal outside its group. + return alternation(nodes, this.wellFormed && (root || this.flags.includes("u"))) } private parseConcatenation(): Node { @@ -317,7 +324,7 @@ class Parser { case "$": return empty case ".": - return character(this.dotAll ? codePointIntervals : complementIntervals(lineTerminatorIntervals)) + return character(this.flags.includes("s") ? codePointIntervals : complementIntervals(lineTerminatorIntervals)) case "[": return this.parseCharacterClass() case "(": @@ -789,7 +796,7 @@ function minimumLength(node: Node): number { case "Concatenation": return node.nodes.reduce((sum, child) => sum + minimumLength(child), 0) case "Repetition": - return minimumLength(node.node) * node.minimum + return node.minimum === 0 ? 0 : minimumLength(node.node) * node.minimum } } @@ -826,12 +833,12 @@ function addUnanchoredSurroundings(node: Node, source: string, flags: string): N * https://github.com/dubzzz/fast-check/blob/v4.9.0/packages/fast-check/src/arbitrary/stringMatching.ts */ /** @internal */ -export function compile(pattern: Pattern): Compiled | undefined { +export function compile(pattern: Pattern, wellFormed = false): Compiled | undefined { const { flags, source } = pattern // Case folding, multiline assertions, and Unicode sets require dedicated AST semantics. Falling back preserves the // contract that a constructively supported pattern never silently ignores one of its flags. if (flags.includes("i") || flags.includes("m") || flags.includes("v")) return undefined - const parsed = new Parser(source, flags.includes("s")).parse() + const parsed = new Parser(pattern, wellFormed).parse() if (parsed === undefined) return undefined const restricted = flags.includes("u") ? parsed : restrictCharacterCodePoints(parsed, 0xffff) const node = addUnanchoredSurroundings(restricted, source, flags) @@ -841,6 +848,7 @@ export function compile(pattern: Pattern): Compiled | undefined { return { minimumLength: minimum, generate: (state, minimumLength, maximumLength) => { + if (minimum === Number.POSITIVE_INFINITY) return undefined const lengths = possibleLengths(node, maximumLength, cache) const candidates: Array = [] for (let length = minimumLength; length <= maximumLength; length++) { diff --git a/packages/effect/src/internal/arbitrary/schema.ts b/packages/effect/src/internal/arbitrary/schema.ts index 9af410aaf6c..c67e97a2875 100644 --- a/packages/effect/src/internal/arbitrary/schema.ts +++ b/packages/effect/src/internal/arbitrary/schema.ts @@ -10,6 +10,8 @@ import * as Schema from "../../Schema.ts" import * as SchemaAST from "../../SchemaAST.ts" import * as SchemaGetter from "../../SchemaGetter.ts" import * as SchemaParser from "../../SchemaParser.ts" +import * as Str from "../../String.ts" +import type { Mutable } from "../../Types.ts" import * as InternalArray from "../array.ts" import { done } from "../core.ts" import { effectIsExit } from "../effect.ts" @@ -31,6 +33,7 @@ interface Checks { const infinity = Number.POSITIVE_INFINITY const finiteNumberConstraint: FilterConstraint = { number: "finite" } +const wellFormedTemplatePart: FilterConstraint = { number: "finite", wellFormed: true } const optionComputation = (self: Effect.Effect): Model.Computation> => { const result = Effect.matchCauseEffectEager(self, { onFailure: Model.onTypedFailure(() => Effect.succeedNone), @@ -93,48 +96,47 @@ function mergeOrderedBound( : [self, selfExclusive] } -function mergeMinimum(self: number | undefined, that: number | undefined): number | undefined { - return self === undefined ? that : that === undefined ? self : Math.max(self, that) -} +const cardinalities = [ + ["minLength", "maxLength"], + ["minCodePoints", "maxCodePoints"], + ["minSize", "maxSize"], + ["minProperties", "maxProperties"] +] as const -function mergeMaximum(self: number | undefined, that: number | undefined): number | undefined { - return self === undefined ? that : that === undefined ? self : Math.min(self, that) +function mergeCardinality( + self: number | undefined, + that: number | undefined, + combine: (a: number, b: number) => number +): number | undefined { + return self === undefined ? that : that === undefined ? self : combine(self, that) } -function mergeConstraint(self: FilterConstraint | undefined, that: FilterConstraint): FilterConstraint { - const order = that.order ?? self?.order - if (self?.order !== undefined && that.order !== undefined && self.order !== that.order) { +function mergeConstraint(self: FilterConstraint = {}, that: FilterConstraint): FilterConstraint { + const order = that.order ?? self.order + if (self.order !== undefined && that.order !== undefined && self.order !== that.order) { throw new Error("Cannot merge ordered arbitrary constraints with different Order instances") } const [minimum, exclusiveMinimum] = order === undefined - ? [that.minimum ?? self?.minimum, that.exclusiveMinimum ?? self?.exclusiveMinimum] + ? [that.minimum ?? self.minimum, that.exclusiveMinimum ?? self.exclusiveMinimum] : mergeOrderedBound( order, - self?.minimum, - self?.exclusiveMinimum, + self.minimum, + self.exclusiveMinimum, that.minimum, that.exclusiveMinimum, -1 ) const [maximum, exclusiveMaximum] = order === undefined - ? [that.maximum ?? self?.maximum, that.exclusiveMaximum ?? self?.exclusiveMaximum] + ? [that.maximum ?? self.maximum, that.exclusiveMaximum ?? self.exclusiveMaximum] : mergeOrderedBound( order, - self?.maximum, - self?.exclusiveMaximum, + self.maximum, + self.exclusiveMaximum, that.maximum, that.exclusiveMaximum, 1 ) - const minLength = mergeMinimum(self?.minLength, that.minLength) - const maxLength = mergeMaximum(self?.maxLength, that.maxLength) - const minCodePoints = mergeMinimum(self?.minCodePoints, that.minCodePoints) - const maxCodePoints = mergeMaximum(self?.maxCodePoints, that.maxCodePoints) - const minSize = mergeMinimum(self?.minSize, that.minSize) - const maxSize = mergeMaximum(self?.maxSize, that.maxSize) - const minProperties = mergeMinimum(self?.minProperties, that.minProperties) - const maxProperties = mergeMaximum(self?.maxProperties, that.maxProperties) - const patterns = self?.patterns === undefined + const patterns = self.patterns === undefined ? that.patterns : that.patterns === undefined ? self.patterns @@ -142,30 +144,29 @@ function mergeConstraint(self: FilterConstraint | undefined, that: FilterConstra Schema.Annotations.ToArbitrary.Pattern, ...Array ] - const number = self?.number === "integer" || that.number === "integer" + const number = self.number === "integer" || that.number === "integer" ? "integer" - : self?.number === "finite" || that.number === "finite" + : self.number === "finite" || that.number === "finite" ? "finite" : undefined - const uniqueBy = that.uniqueBy ?? self?.uniqueBy - return { - ...(order === undefined ? undefined : { order }), - ...(minimum === undefined ? undefined : { minimum }), - ...(exclusiveMinimum === true ? { exclusiveMinimum: true } : undefined), - ...(maximum === undefined ? undefined : { maximum }), - ...(exclusiveMaximum === true ? { exclusiveMaximum: true } : undefined), - ...(minLength === undefined ? undefined : { minLength }), - ...(maxLength === undefined ? undefined : { maxLength }), - ...(minCodePoints === undefined ? undefined : { minCodePoints }), - ...(maxCodePoints === undefined ? undefined : { maxCodePoints }), - ...(minSize === undefined ? undefined : { minSize }), - ...(maxSize === undefined ? undefined : { maxSize }), - ...(minProperties === undefined ? undefined : { minProperties }), - ...(maxProperties === undefined ? undefined : { maxProperties }), - ...(patterns === undefined ? undefined : { patterns }), - ...(number === undefined ? undefined : { number }), - ...(uniqueBy === undefined ? undefined : { uniqueBy }) + const uniqueBy = that.uniqueBy ?? self.uniqueBy + const out: Mutable = {} + if (order !== undefined) out.order = order + if (minimum !== undefined) out.minimum = minimum + if (exclusiveMinimum === true) out.exclusiveMinimum = true + if (maximum !== undefined) out.maximum = maximum + if (exclusiveMaximum === true) out.exclusiveMaximum = true + for (const [min, max] of cardinalities) { + const lower = mergeCardinality(self[min], that[min], Math.max) + const upper = mergeCardinality(self[max], that[max], Math.min) + if (lower !== undefined) out[min] = lower + if (upper !== undefined) out[max] = upper } + if (self.wellFormed || that.wellFormed) out.wellFormed = true + if (patterns !== undefined) out.patterns = patterns + if (number !== undefined) out.number = number + if (uniqueBy !== undefined) out.uniqueBy = uniqueBy + return out } function collectChecks(checks: SchemaAST.Checks | undefined, inherited: FilterConstraint | undefined): Checks { @@ -208,13 +209,9 @@ function applyFilters( function validateConstraint(constraint: FilterConstraint | undefined, path: ReadonlyArray): void { if (constraint === undefined) return - const cardinalities = [ - [constraint.minLength, constraint.maxLength], - [constraint.minCodePoints, constraint.maxCodePoints], - [constraint.minSize, constraint.maxSize], - [constraint.minProperties, constraint.maxProperties] - ] as const - for (const [minimum, maximum] of cardinalities) { + for (const [min, max] of cardinalities) { + const minimum = constraint[min] + const maximum = constraint[max] if ( minimum !== undefined && (!Number.isSafeInteger(minimum) || minimum < 0) || maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum < 0) || @@ -740,10 +737,11 @@ function stringSample( options: { readonly minimumLength: number readonly minimumCodePoints: number | undefined + readonly wellFormed: boolean readonly pattern: Regexp.Compiled | undefined } ): Model.Sample { - const { minimumCodePoints, pattern } = options + const { minimumCodePoints, pattern, wellFormed } = options const minimum = Math.max(options.minimumLength, pattern?.minimumLength ?? 0) const codePoints = minimumCodePoints !== undefined const minimumUnits = minimumCodePoints ?? minimum @@ -754,8 +752,11 @@ function stringSample( return Effect.suspend(() => { for (let next = candidates.next(); !next.done; next = candidates.next()) { const candidate = next.value.value - // Reject pattern mismatches here so they do not consume the runner's shrink budget. - if (candidate.length < minimum || seen.has(candidate) || pattern?.test(candidate) === false) continue + // Skip invalid candidates before they consume the runner's shrink budget. + if ( + candidate.length < minimum || seen.has(candidate) || pattern?.test(candidate) === false || + wellFormed && !Str.isWellFormed(candidate) + ) continue seen.add(candidate) return Effect.succeed(sample(next.value)) } @@ -825,15 +826,22 @@ const stringEdgeCases = [ "😀" ] as const -function randomString(state: Model.GenerationState, minimum: number, maximum: number): string { +const wellFormedStringEdgeCases = stringEdgeCases.filter(Str.isWellFormed) + +function randomString( + state: Model.GenerationState, + minimum: number, + maximum: number, + edgeCases: ReadonlyArray +): string { if (Model.randomInt(state, 1, state.biasFactor) === 1) { let eligible = 0 - for (const value of stringEdgeCases) { + for (const value of edgeCases) { if (value.length >= minimum && value.length <= maximum) eligible++ } if (eligible > 0) { let target = Model.randomIndex(state, eligible) - for (const value of stringEdgeCases) { + for (const value of edgeCases) { if (value.length < minimum || value.length > maximum) continue if (target-- === 0) return value } @@ -1143,10 +1151,12 @@ export function compile(schema: S): Model.Compiled< } ) case "String": { + const wellFormed = constraint?.wellFormed === true + const edgeCases = wellFormed ? wellFormedStringEdgeCases : stringEdgeCases const patterns: Array = [] const unsupported: Array = [] for (const candidate of constraint?.patterns ?? []) { - const pattern = Regexp.compile(candidate) + const pattern = Regexp.compile(candidate, wellFormed) if (pattern !== undefined) patterns.push(pattern) else unsupported.push(candidate) } @@ -1188,12 +1198,13 @@ export function compile(schema: S): Model.Compiled< ? pattern.generate(state, minimum, upper) : hasCodePoints ? randomCodePointString(state, minimum, upper, minCodePoints, Math.min(maxCodePoints, upper)) - : randomString(state, minimum, upper) + : randomString(state, minimum, upper, edgeCases) if (value === undefined) return Model.discarded return state.shrinks ? stringSample(value, { minimumLength: minimum, - minimumCodePoints: hasCodePoints ? minCodePoints : undefined, + minimumCodePoints: hasCodePoints || wellFormed ? minCodePoints : undefined, + wellFormed, pattern }) : Model.makeSample(value) @@ -1304,7 +1315,18 @@ export function compile(schema: S): Model.Compiled< ) } case "TemplateLiteral": { - const parts = ast.parts.map((part, index) => recurAt(part, path, index, finiteNumberConstraint)) + const isWellFormedBoundary = (index: number, step: number) => { + while (ast.literals[index] === "") index += step + const part = ast.parts[index] + const literal = ast.literals[index] + return part === undefined || part._tag === "Number" || (literal !== undefined && Str.isWellFormed(literal)) + } + const parts = ast.parts.map((part, index) => { + // A dynamic part can contain a lone surrogate if a neighboring part can complete the pair. + const wellFormed = constraint?.wellFormed && ast.literals[index] === undefined && + isWellFormedBoundary(index - 1, -1) && isWellFormedBoundary(index + 1, 1) + return recurAt(part, path, index, wellFormed ? wellFormedTemplatePart : finiteNumberConstraint) + }) return Model.makeCompiled( parts, () => sumCosts(parts.map((part) => part.minCost)), diff --git a/packages/effect/src/internal/schema/schemaCodegenBuiltIns.ts b/packages/effect/src/internal/schema/schemaCodegenBuiltIns.ts index bbdaabbeff0..db691d29891 100644 --- a/packages/effect/src/internal/schema/schemaCodegenBuiltIns.ts +++ b/packages/effect/src/internal/schema/schemaCodegenBuiltIns.ts @@ -52,6 +52,7 @@ function between(render: PrintArgument): PrintArgument { const checkArguments: Record = { isTrimmed: noArguments, + isWellFormed: noArguments, isPattern: (payload) => { if (!isObject(payload) || typeof payload.source !== "string" || typeof payload.flags !== "string") return undefined const { source, flags } = payload diff --git a/packages/effect/test/arbitrary/Arbitrary.test.ts b/packages/effect/test/arbitrary/Arbitrary.test.ts index cc8fd585e19..def33d12e3a 100644 --- a/packages/effect/test/arbitrary/Arbitrary.test.ts +++ b/packages/effect/test/arbitrary/Arbitrary.test.ts @@ -288,6 +288,134 @@ describe("Arbitrary", { concurrent: false }, () => { } })) + describe("isWellFormed", () => { + const schema = Schema.String.check(Schema.isWellFormed()) + + for ( + const [name, field, width] of [ + ["strings", schema, 40], + ["literal patterns", schema.check(Schema.isPattern(/^foo$/u)), 20], + ["template literals", Schema.TemplateLiteral(["id:", Schema.String]).check(Schema.isWellFormed()), 40], + [ + "templates with an empty suffix", + Schema.TemplateLiteral(["id:", Schema.String, ""]).check(Schema.isWellFormed()), + 40 + ] + ] as const + ) { + it.effect(`constructs wide objects of well-formed ${name} without discards`, () => + Effect.gen(function*() { + const wide = Schema.Struct( + Object.fromEntries(Array.from({ length: width }, (_, i) => [`field${i}`, field])) + ) + const result = yield* Arbitrary.checkEffect(Arbitrary.schema(wide), Schema.is(wide), { + runs: 500, + seed: 123, + maxDiscards: 0 + }) + assert.strictEqual(result._tag, "Passed") + })) + } + + it.effect("combines well-formedness with length, code point, and pattern checks", () => + Effect.gen(function*() { + for ( + const checked of [ + schema.check(Schema.isBetweenLength(2, 4)), + schema.check(Schema.isMinCodePoints(2), Schema.isMaxCodePoints(3)), + schema.check(Schema.isBetweenLength(32, 32), Schema.isBetweenCodePoints(16, 16)), + Schema.String.check(Schema.isPattern(/^a[\u{1f600}-\u{1f64f}]+$/u), Schema.isWellFormed()), + schema.check(Schema.isPattern(/^a[\u{1f600}-\u{1f64f}]+$/u)) + ] + ) { + const values = yield* Arbitrary.sampleEffect(Arbitrary.schema(checked), { + count: 100, + maxDiscards: 0, + seed: 123, + size: 4 + }) + assert.isTrue(values.every(Schema.is(checked))) + } + })) + + it.effect("starts a property check with the well-formed literal alternative", () => + Effect.gen(function*() { + for ( + const [pattern, expected] of [ + [/^(?:foo|\uD800)$/u, "foo"], + [/^id:(?:foo|\uD800)$/u, "id:foo"], + [/^(?:(?:\uD800|\uDC00)!|okay)$/u, "okay"] + ] as const + ) { + const checked = schema.check(Schema.isPattern(pattern)) + const result = yield* Arbitrary.checkEffect(Arbitrary.schema(checked), (value) => value === expected, { + runs: 20, + seed: 123, + maxDiscards: 0 + }) + assert.strictEqual(result._tag, "Passed") + } + })) + + it.effect("generates a well-formed string next to a number in a template", () => + Effect.gen(function*() { + const prefix = Schema.String.check(Schema.isPattern(/^(?:foo|\uD800)$/u)) + const checked = Schema.TemplateLiteral([prefix, Schema.Int]).check(Schema.isWellFormed()) + const result = yield* Arbitrary.checkEffect(Arbitrary.schema(checked), Schema.is(checked), { + runs: 20, + seed: 123, + maxDiscards: 0 + }) + assert.strictEqual(result._tag, "Passed") + })) + + it.effect("keeps surrogate pairs that span a group or an empty template literal", () => + Effect.gen(function*() { + for ( + const checked of [ + schema.check(Schema.isPattern(/^(?:ab|\uD83D)\uDE00$/)), + Schema.TemplateLiteral([ + Schema.String.check(Schema.isPattern(/^(?:ab|\uD83D)$/)), + "", + Schema.String.check(Schema.isPattern(/^\uDE00$/)) + ]).check(Schema.isWellFormed()) + ] + ) { + const values = yield* Arbitrary.sampleEffect(Arbitrary.schema(checked), { + count: 1, + size: 0, + maxDiscards: 0 + }) + assert.deepStrictEqual(values, ["😀"]) + } + })) + + it.effect("handles optional and required patterns with no well-formed match in their group", () => + Effect.gen(function*() { + const optional = schema.check(Schema.isPattern(/^(?:\uD800|[^\s\S])?$/u)) + const values = yield* Arbitrary.sampleEffect(Arbitrary.schema(optional), { count: 1, maxDiscards: 0 }) + assert.deepStrictEqual(values, [""]) + + const required = schema.check(Schema.isPattern(/^(?:\uD800|[^\s\S])$/u)) + const result = yield* Arbitrary.checkEffect(Arbitrary.schema(required), () => true, { maxDiscards: 0 }) + assert.strictEqual(result._tag, "Exhausted") + })) + + it.effect("shrinks a well-formed string by whole code points", () => + Effect.gen(function*() { + const result = yield* Arbitrary.checkEffect(Arbitrary.schema(schema), (value) => value === "", { + runs: 1, + size: 2, + seed: 17 + }) + assert.strictEqual(result._tag, "Falsified") + if (result._tag === "Falsified") { + assert.strictEqual(result.initialInput, "😀") + assert.strictEqual(result.shrunkInput, "\0") + } + })) + }) + it.effect("constructs strings with code point bounds and UTF-16 length bounds", () => Effect.gen(function*() { const schemas = [ diff --git a/packages/effect/test/schema/Schema.test.ts b/packages/effect/test/schema/Schema.test.ts index c4f82c93684..96f178f190d 100644 --- a/packages/effect/test/schema/Schema.test.ts +++ b/packages/effect/test/schema/Schema.test.ts @@ -1535,6 +1535,29 @@ Expected a string including "c"` ) }) + describe("isWellFormed", () => { + const schema = Schema.String.check(Schema.isWellFormed()) + + it("validates complete surrogate pairs and rejects isolated halves", async () => { + const asserts = new TestSchema.Asserts(schema) + for (const value of ["", "abc", "\0\n", "é", "e\u0301", "😀", "a😀b", "\uDBFF\uDFFF"]) { + await asserts.decoding().succeed(value) + await asserts.encoding().succeed(value) + } + for (const value of ["\uD800", "\uDC00", "a\uD800b", "\uDC00\uD800", "😀\uD800", "\uD800\n"]) { + await asserts.decoding().fail(value, "Expected a well-formed Unicode string") + await asserts.encoding().fail(value, "Expected a well-formed Unicode string") + } + }) + + it("allows custom annotations", async () => { + const asserts = new TestSchema.Asserts( + Schema.String.check(Schema.isWellFormed({ expected: "complete text" })) + ) + await asserts.decoding().fail("\uD800", "Expected complete text") + }) + }) + it("isLowercased", async () => { const schema = Schema.String.check(Schema.isLowercased()) const asserts = new TestSchema.Asserts(schema) diff --git a/packages/effect/test/schema/representation/builtInRevivers.test.ts b/packages/effect/test/schema/representation/builtInRevivers.test.ts index 65ec10d83f6..f39787cd493 100644 --- a/packages/effect/test/schema/representation/builtInRevivers.test.ts +++ b/packages/effect/test/schema/representation/builtInRevivers.test.ts @@ -153,6 +153,17 @@ describe("SchemaRepresentation built-in string revivers", () => { }) }) + it("revives isWellFormed", () => { + assertFilterReviver({ + schema: Schema.String.check(Schema.isWellFormed()), + id: "effect/schema/isWellFormed", + payload: null, + reviver: SchemaRepresentation.isWellFormedReviver, + valid: "😀", + invalid: "\uD800" + }) + }) + it("revives isPattern", () => { assertFilterReviver({ schema: Schema.String.check(Schema.isPattern(/^a+$/i)), diff --git a/packages/effect/test/schema/representation/codegen.test.ts b/packages/effect/test/schema/representation/codegen.test.ts index fd562d95ffb..0bc34561dc7 100644 --- a/packages/effect/test/schema/representation/codegen.test.ts +++ b/packages/effect/test/schema/representation/codegen.test.ts @@ -306,6 +306,7 @@ describe("Codegen.Module.addSchemas", { concurrent: false }, () => { const stringChecks: ReadonlyArray< readonly [string, SchemaAST.Check, ReadonlyArray, ReadonlyArray] > = [ + ["well formed", Schema.isWellFormed(), ["", "😀", "a"], ["\uD800", "\uDC00"]], ["min length", Schema.isMinLength(1), ["a"], [""]], ["min code points", Schema.isMinCodePoints(2), ["😀a"], ["😀"]], ["max code points", Schema.isMaxCodePoints(3), ["😀😀😀"], ["abcd"]], diff --git a/packages/effect/test/schema/toJsonSchemaDocument.test.ts b/packages/effect/test/schema/toJsonSchemaDocument.test.ts index c293f94bc66..db8b9316b3d 100644 --- a/packages/effect/test/schema/toJsonSchemaDocument.test.ts +++ b/packages/effect/test/schema/toJsonSchemaDocument.test.ts @@ -1408,6 +1408,16 @@ describe("toJsonSchemaDocument", () => { }) }) + it("exports well-formed Unicode validation", () => { + const schema = Schema.String.check(Schema.isWellFormed()) + const jsonSchema = { type: "string", pattern: "^[^\\uD800-\\uDFFF]*$" } as const + assertJsonSchemaDocument(schema, { schema: jsonSchema }) + const validate = ajvDraft2020_12.compile(jsonSchema) + for (const value of ["", "a", "😀", "e\u0301", "\uD800", "\uDC00", "\uD800\n"]) { + assert.strictEqual(validate(value), Schema.is(schema)(value)) + } + }) + it("exports code point checks with matching JSON Schema validation", () => { for ( const [check, keywords] of [ From 3706211df2bb5017e377fdd684b94de3faab4046 Mon Sep 17 00:00:00 2001 From: Harry Solovay <4893548+harrysolovay@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:25:19 -0500 Subject: [PATCH 2/3] Add Schema.isNonBlank check (#11248) Co-authored-by: Effect Bot Co-authored-by: Giulio Canti --- .changeset/add-schema-is-non-blank.md | 5 ++++ packages/effect/src/Schema.ts | 30 +++++++++++++++++++ packages/effect/src/SchemaRepresentation.ts | 13 ++++++++ packages/effect/src/String.ts | 5 +++- .../internal/schema/schemaCodegenBuiltIns.ts | 1 + packages/effect/test/schema/Schema.test.ts | 17 +++++++++++ .../representation/builtInRevivers.test.ts | 11 +++++++ .../schema/representation/codegen.test.ts | 1 + .../test/schema/toJsonSchemaDocument.test.ts | 13 ++++++++ .../schema/SchemaBuiltInRevivers.tst.ts | 1 + 10 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 .changeset/add-schema-is-non-blank.md diff --git a/.changeset/add-schema-is-non-blank.md b/.changeset/add-schema-is-non-blank.md new file mode 100644 index 00000000000..ed2abb4d230 --- /dev/null +++ b/.changeset/add-schema-is-non-blank.md @@ -0,0 +1,5 @@ +--- +"effect": patch +--- + +Add `Schema.isNonBlank` to reject empty and whitespace-only strings while preserving accepted strings unchanged, including surrounding whitespace. Add `SchemaRepresentation.isNonBlankReviver` to reconstruct persisted checks. diff --git a/packages/effect/src/Schema.ts b/packages/effect/src/Schema.ts index 5f8e1c6f97e..2fcf5327663 100644 --- a/packages/effect/src/Schema.ts +++ b/packages/effect/src/Schema.ts @@ -6920,6 +6920,36 @@ export function isTrimmed(annotations?: Annotations.Filter) { } ) } + +/** + * Checks for at least one non-whitespace character, preserving the string + * unchanged, including leading and trailing whitespace. + * + * **When to use** + * + * Use when free-form text is required. To also forbid surrounding whitespace, + * combine {@link isNonEmpty} with {@link isTrimmed} instead. + * + * **Details** + * + * Rejects empty and whitespace-only strings using the same whitespace semantics + * as `String.hasNonWhitespace`. Supports JSON Schema pattern output and arbitrary + * generation through {@link isPattern}. + * + * @stability unstable + * @category validation + * @since 4.3.0 + */ +export function isNonBlank(annotations?: Annotations.Filter) { + return isPattern(Str.NON_WHITESPACE_REGEXP, { + expected: "a string with at least one non-whitespace character", + representation: { + id: "effect/schema/isNonBlank", + payload: null + }, + ...annotations + }) +} /** * Validates that a string contains no unpaired UTF-16 surrogates. * diff --git a/packages/effect/src/SchemaRepresentation.ts b/packages/effect/src/SchemaRepresentation.ts index a91ce46719d..46a73c398f5 100644 --- a/packages/effect/src/SchemaRepresentation.ts +++ b/packages/effect/src/SchemaRepresentation.ts @@ -805,6 +805,19 @@ export const isTrimmedReviver: FilterReviver = makeReviverFilter( ({ annotations }) => Schema.isTrimmed(annotations) ) +/** + * Reconstructs persisted {@link Schema.isNonBlank} checks. + * + * @stability unstable + * @category validation + * @since 4.3.0 + */ +export const isNonBlankReviver: FilterReviver = makeReviverFilter( + "effect/schema/isNonBlank", + Schema.Null, + ({ annotations }) => Schema.isNonBlank(annotations) +) + /** * Reviver for persisted `isWellFormed` checks. * diff --git a/packages/effect/src/String.ts b/packages/effect/src/String.ts index 58f8ce9183c..1c8ac0f2a2e 100644 --- a/packages/effect/src/String.ts +++ b/packages/effect/src/String.ts @@ -479,6 +479,9 @@ interface WellFormedNative { export const isWellFormed = (self: string): boolean => (self as WellFormedNative).isWellFormed?.() ?? !loneSurrogate.test(self) +/** @internal */ +export const NON_WHITESPACE_REGEXP = /\S/u + /** * Checks whether a string contains at least one non-whitespace character. * @@ -502,7 +505,7 @@ export const isWellFormed = (self: string): boolean => * @category predicates * @since 4.2.0 */ -export const hasNonWhitespace = (self: string): boolean => /\S/u.test(self) +export const hasNonWhitespace = (self: string): boolean => NON_WHITESPACE_REGEXP.test(self) /** * Returns the JavaScript string length, measured in UTF-16 code units. diff --git a/packages/effect/src/internal/schema/schemaCodegenBuiltIns.ts b/packages/effect/src/internal/schema/schemaCodegenBuiltIns.ts index db691d29891..3fdcd09a29d 100644 --- a/packages/effect/src/internal/schema/schemaCodegenBuiltIns.ts +++ b/packages/effect/src/internal/schema/schemaCodegenBuiltIns.ts @@ -52,6 +52,7 @@ function between(render: PrintArgument): PrintArgument { const checkArguments: Record = { isTrimmed: noArguments, + isNonBlank: noArguments, isWellFormed: noArguments, isPattern: (payload) => { if (!isObject(payload) || typeof payload.source !== "string" || typeof payload.flags !== "string") return undefined diff --git a/packages/effect/test/schema/Schema.test.ts b/packages/effect/test/schema/Schema.test.ts index 96f178f190d..157349bc5e3 100644 --- a/packages/effect/test/schema/Schema.test.ts +++ b/packages/effect/test/schema/Schema.test.ts @@ -10884,6 +10884,23 @@ describe("Check", () => { ) }) + it("isNonBlank", async () => { + const schema = Schema.String.check(Schema.isNonBlank()) + const asserts = new TestSchema.Asserts(schema) + + if (verifyGeneration) { + asserts.arbitrary().verifyGeneration() + } + + const decoding = asserts.decoding() + await decoding.succeed(" text ") + await decoding.succeed("hello\n") + await decoding.succeed("\u200b") + const message = "Expected a string with at least one non-whitespace character" + await decoding.fail("", message) + await decoding.fail(" \t\r\n\u00a0\u2028\ufeff", message) + }) + it("isAscii", async () => { const schema = Schema.String.check(Schema.isAscii()) const asserts = new TestSchema.Asserts(schema) diff --git a/packages/effect/test/schema/representation/builtInRevivers.test.ts b/packages/effect/test/schema/representation/builtInRevivers.test.ts index f39787cd493..e46ff238c85 100644 --- a/packages/effect/test/schema/representation/builtInRevivers.test.ts +++ b/packages/effect/test/schema/representation/builtInRevivers.test.ts @@ -208,6 +208,17 @@ describe("SchemaRepresentation built-in string revivers", () => { }) }) + it("revives isNonBlank", () => { + assertFilterReviver({ + schema: Schema.String.check(Schema.isNonBlank()), + id: "effect/schema/isNonBlank", + payload: null, + reviver: SchemaRepresentation.isNonBlankReviver, + valid: " text ", + invalid: " " + }) + }) + it("revives isTrimmed", () => { assertFilterReviver({ schema: Schema.String.check(Schema.isTrimmed()), diff --git a/packages/effect/test/schema/representation/codegen.test.ts b/packages/effect/test/schema/representation/codegen.test.ts index 0bc34561dc7..56bb4f006c3 100644 --- a/packages/effect/test/schema/representation/codegen.test.ts +++ b/packages/effect/test/schema/representation/codegen.test.ts @@ -316,6 +316,7 @@ describe("Codegen.Module.addSchemas", { concurrent: false }, () => { ["includes", Schema.isIncluding("a"), ["bab"], ["bb"]], ["GUID", Schema.isGUID({ message: "message" }), ["00000000-0000-0000-0000-000000000000"], ["a"]], ["ASCII", Schema.isAscii(), ["abc"], ["é"]], + ["non blank", Schema.isNonBlank(), [" a "], ["", " "]], ["pattern and flags", Schema.isPattern(/^a+$/i), ["AAA"], ["b"]] ] for (const [name, check, accepts, rejects] of stringChecks) { diff --git a/packages/effect/test/schema/toJsonSchemaDocument.test.ts b/packages/effect/test/schema/toJsonSchemaDocument.test.ts index db8b9316b3d..d79c194259d 100644 --- a/packages/effect/test/schema/toJsonSchemaDocument.test.ts +++ b/packages/effect/test/schema/toJsonSchemaDocument.test.ts @@ -1322,6 +1322,19 @@ describe("toJsonSchemaDocument", () => { }) }) + it("isNonBlank", () => { + assertJsonSchemaDocument( + Schema.String.annotate({ description: "description" }).check(Schema.isNonBlank()), + { + schema: { + "type": "string", + "description": "description", + "pattern": "\\S" + } + } + ) + }) + it("isLowercased", () => { const schema = Schema.String.check(Schema.isLowercased()) assertJsonSchemaDocument(schema, { diff --git a/packages/effect/typetest/schema/SchemaBuiltInRevivers.tst.ts b/packages/effect/typetest/schema/SchemaBuiltInRevivers.tst.ts index 7f8ccb93dbe..617b147796f 100644 --- a/packages/effect/typetest/schema/SchemaBuiltInRevivers.tst.ts +++ b/packages/effect/typetest/schema/SchemaBuiltInRevivers.tst.ts @@ -5,6 +5,7 @@ describe("Schema built-in revivers", () => { it("composes every built-in reviver without casts", () => { const revivers: ReadonlyArray = [ SchemaRepresentation.isTrimmedReviver, + SchemaRepresentation.isNonBlankReviver, SchemaRepresentation.isPatternReviver, SchemaRepresentation.isStringFiniteReviver, SchemaRepresentation.isStringBigIntReviver, From ce2bdbd3c3696d22b96a36575ef199516385b02f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20De=20Boey?= Date: Thu, 22 Oct 2026 17:37:36 +0200 Subject: [PATCH 3/3] Support the `openapi-3.0` target in `Schema.toStandardJSONSchemaV1` --- .../standard-json-schema-openapi-3-0.md | 5 + packages/effect/src/JsonSchema.ts | 173 ++++++++++++++++++ .../src/internal/schema/standardSchema.ts | 8 + packages/effect/test/JsonSchema.test.ts | 151 +++++++++++++++ .../schema/toStandardJSONSchemaV1.test.ts | 147 ++++++++++++++- 5 files changed, 483 insertions(+), 1 deletion(-) create mode 100644 .changeset/standard-json-schema-openapi-3-0.md diff --git a/.changeset/standard-json-schema-openapi-3-0.md b/.changeset/standard-json-schema-openapi-3-0.md new file mode 100644 index 00000000000..4fd5c16ef15 --- /dev/null +++ b/.changeset/standard-json-schema-openapi-3-0.md @@ -0,0 +1,5 @@ +--- +"effect": minor +--- + +Support the `openapi-3.0` target in `Schema.toStandardJSONSchemaV1`. diff --git a/packages/effect/src/JsonSchema.ts b/packages/effect/src/JsonSchema.ts index a36428bcc15..69b0bad2644 100644 --- a/packages/effect/src/JsonSchema.ts +++ b/packages/effect/src/JsonSchema.ts @@ -798,6 +798,28 @@ export function toMultiDocumentComponents( } } +/** + * Converts a `Document<"draft-2020-12">` to OpenAPI 3.0 Schema Objects for a + * standalone schema. + * + * This builds on the Draft-04 conversion, so definitions are referenced via + * `#/definitions/` rather than `#/components/schemas/`. It writes + * `{ type: "null" }` as `nullable: true` on a typed `anyOf` branch, and as + * `{ enum: [null] }` where no such branch exists, because `nullable` only + * applies next to `type`. It also splits `type` arrays, writes the first of + * `examples` as `example` and drops the root `$schema`. Tuples, pattern + * properties, dependencies and schema identifiers throw. + * + * @internal + */ +export function toStandaloneOpenApi3_0( + document: Document<"draft-2020-12"> +): { readonly schema: JsonSchema; readonly definitions: Definitions } { + return convertDocument(document, openApi30Adapter, { + booleanAdapter: (schema) => schema ? {} : { not: {} } + }) +} + /** @internal */ export const VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP = /^[a-zA-Z0-9.\-_]+$/ @@ -1753,3 +1775,154 @@ function convertDraft04ExclusiveBound( InternalRecord.assignProperty(out, boundKey, bound) } } + +const OPEN_API_30_TARGET_COLLISIONS = ["discriminator", "example", "externalDocs", "nullable", "xml"] +const OPEN_API_30_UNSUPPORTED_KEYWORDS = [ + "$anchor", + "$id", + "dependentRequired", + "dependentSchemas", + "patternProperties", + "prefixItems" +] +// Keywords that `nullable` cannot be combined with, because they would also +// apply to `null` once the null branch is merged into the typed branch. +const OPEN_API_30_NULLABLE_BRANCH_BLOCKERS = ["$ref", "allOf", "anyOf", "contains", "if", "not", "oneOf"] +const OPEN_API_30_HOISTABLE_KEYWORDS = new Set([ + "$comment", + "default", + "deprecated", + "description", + "examples", + "readOnly", + "title", + "writeOnly" +]) + +function openApi30Adapter(source: JsonSchema, context: Context): JsonSchema { + rejectKeywordCollisions(source, OPEN_API_30_TARGET_COLLISIONS, "OpenAPI 3.0", "Draft 2020-12") + for (const key of OPEN_API_30_UNSUPPORTED_KEYWORDS) { + if (Object.hasOwn(source, key)) { + unsupported( + key, + "OpenAPI 3.0", + key === "prefixItems" ? "items must be a single schema" : "the target dialect has no equivalent" + ) + } + } + if (Object.hasOwn(source, "$schema") && !isMetaSchemaUri(source.$schema, META_SCHEMA_URI_DRAFT_2020_12)) { + unsupported("$schema", "OpenAPI 3.0", "a Schema Object cannot declare a dialect") + } + + const nullableIndex = getOpenApi30NullableIndex(source) + const out = nullableIndex === undefined + ? draft04Adapter(source, context) + : convertOpenApi30NullableAnyOf(source, source.anyOf as ReadonlyArray, nullableIndex, context) + + delete out.$schema + convertOpenApi30Type(out) + if (Array.isArray(out.examples)) { + const examples = out.examples + delete out.examples + if (examples.length > 0) InternalRecord.assignProperty(out, "example", examples[0]) + } + return out +} + +// Returns the `anyOf` branch that can absorb the `{ type: "null" }` branches +// as `nullable: true`. +function getOpenApi30NullableIndex(source: JsonSchema): number | undefined { + if (!Array.isArray(source.anyOf) || Object.hasOwn(source, "$ref") || !source.anyOf.some(isOpenApi30NullSchema)) { + return undefined + } + const index = source.anyOf.findIndex((branch) => + Predicate.isObject(branch) && + typeof branch.type === "string" && + branch.type !== "null" && + !OPEN_API_30_NULLABLE_BRANCH_BLOCKERS.some((key) => Object.hasOwn(branch, key)) && + !(Object.hasOwn(branch, "const") && Object.hasOwn(branch, "enum")) + ) + return index === -1 ? undefined : index +} + +function isOpenApi30NullSchema(schema: unknown): boolean { + return Predicate.isObject(schema) && schema.type === "null" && Object.keys(schema).length === 1 +} + +function convertOpenApi30NullableAnyOf( + source: JsonSchema, + anyOf: ReadonlyArray, + nullableIndex: number, + context: Context +): JsonSchema { + const rest: JsonSchema = {} + for (const key of Object.keys(source)) { + if (key !== "anyOf") InternalRecord.assignProperty(rest, key, source[key]) + } + const branches = anyOf.flatMap((branch, index) => isOpenApi30NullSchema(branch) ? [] : [index]) + const nullableBranch = anyOf[nullableIndex] as JsonSchema + + if ( + branches.length === 1 && + Object.keys(rest).every((key) => OPEN_API_30_HOISTABLE_KEYWORDS.has(key) && !Object.hasOwn(nullableBranch, key)) + ) { + const out = context.schemaAt(nullableBranch, ["anyOf", String(nullableIndex)], []) as JsonSchema + setOpenApi30Nullable(out) + const annotations = draft04Adapter(rest, context) + for (const key of Object.keys(annotations)) InternalRecord.assignProperty(out, key, annotations[key]) + return out + } + + const out = draft04Adapter(rest, context) + InternalRecord.assignProperty( + out, + "anyOf", + branches.map((sourceIndex, targetIndex) => { + const branch = context.schemaAt( + anyOf[sourceIndex], + ["anyOf", String(sourceIndex)], + ["anyOf", String(targetIndex)] + ) as JsonSchema + if (sourceIndex === nullableIndex) { + setOpenApi30Nullable(branch) + } + return branch + }) + ) + return out +} + +function setOpenApi30Nullable(out: JsonSchema): void { + InternalRecord.assignProperty(out, "nullable", true) + if (Array.isArray(out.enum) && !out.enum.includes(null)) { + InternalRecord.assignProperty(out, "enum", [...out.enum, null]) + } +} + +function convertOpenApi30Type(out: JsonSchema): void { + const type = out.type + if (type !== "null" && !Array.isArray(type)) { + return + } + const types = Array.isArray(type) ? type.filter((type) => type !== "null") : [] + const nullable = Array.isArray(type) && types.length < type.length + delete out.type + if (types.length === 0) { + // OpenAPI 3.0 has no `null` type, and `nullable` requires a `type`. + InternalRecord.assignProperty( + out, + "enum", + Array.isArray(out.enum) ? out.enum.filter((value) => value === null) : [null] + ) + } else if (types.length === 1) { + InternalRecord.assignProperty(out, "type", types[0]) + if (nullable) InternalRecord.assignProperty(out, "nullable", true) + } else { + const anyOf = types.map((type, index): JsonSchema => index === 0 && nullable ? { type, nullable: true } : { type }) + if (Object.hasOwn(out, "anyOf")) { + appendAllOf(out, { anyOf }) + } else { + InternalRecord.assignProperty(out, "anyOf", anyOf) + } + } +} diff --git a/packages/effect/src/internal/schema/standardSchema.ts b/packages/effect/src/internal/schema/standardSchema.ts index ce5a05dc86b..23dbb445f99 100644 --- a/packages/effect/src/internal/schema/standardSchema.ts +++ b/packages/effect/src/internal/schema/standardSchema.ts @@ -106,6 +106,14 @@ function toBaseStandardJSONSchemaV1( schema.definitions = doc07.definitions } return schema + } else if (target === "openapi-3.0") { + // OpenAPI 3.0 Schema Objects have no `$schema`. + const doc30 = JsonSchema.toStandaloneOpenApi3_0(doc2020_12) + const schema: JsonSchema.JsonSchema = { ...doc30.schema } + if (Object.keys(doc30.definitions).length > 0) { + schema.definitions = doc30.definitions + } + return schema } throw new globalThis.Error(`Unsupported target: ${target}`) } diff --git a/packages/effect/test/JsonSchema.test.ts b/packages/effect/test/JsonSchema.test.ts index a1df62f7691..8d787e5ded5 100644 --- a/packages/effect/test/JsonSchema.test.ts +++ b/packages/effect/test/JsonSchema.test.ts @@ -2532,6 +2532,157 @@ describe("JsonSchema", () => { }) }) + describe("toStandaloneOpenApi3_0", () => { + function assertToStandaloneOpenApi3_0( + schema: JsonSchema.JsonSchema, + expected: JsonSchema.JsonSchema, + definitions: JsonSchema.Definitions = {}, + expectedDefinitions: JsonSchema.Definitions = {} + ) { + deepStrictEqual(JsonSchema.toStandaloneOpenApi3_0({ dialect: "draft-2020-12", schema, definitions }), { + schema: expected, + definitions: expectedDefinitions + }) + } + + it("drops the canonical meta-schema URI", () => { + assertToStandaloneOpenApi3_0( + { $schema: JsonSchema.META_SCHEMA_URI_DRAFT_2020_12, type: "string" }, + { type: "string" } + ) + }) + + it("rejects custom dialects", () => { + assert.throws( + () => + JsonSchema.toStandaloneOpenApi3_0({ + dialect: "draft-2020-12", + schema: { $schema: "https://example.com/dialect" }, + definitions: {} + }), + /Cannot convert JSON Schema keyword "\$schema" to OpenAPI 3.0/ + ) + }) + + it("lowers const and exclusive bounds like Draft-04", () => { + assertToStandaloneOpenApi3_0( + { type: "number", const: 1, exclusiveMinimum: 0, exclusiveMaximum: 10 }, + { type: "number", enum: [1], minimum: 0, exclusiveMinimum: true, maximum: 10, exclusiveMaximum: true } + ) + }) + + it("writes the first example as example", () => { + assertToStandaloneOpenApi3_0({ type: "string", examples: ["a", "b"] }, { type: "string", example: "a" }) + assertToStandaloneOpenApi3_0({ type: "string", examples: [] }, { type: "string" }) + }) + + describe("null", () => { + it("writes a null branch as nullable on the typed branch", () => { + assertToStandaloneOpenApi3_0( + { anyOf: [{ type: "null" }, { type: "string", minLength: 1 }], description: "d" }, + { type: "string", minLength: 1, nullable: true, description: "d" } + ) + }) + + it("adds null to the enum of the typed branch", () => { + assertToStandaloneOpenApi3_0( + { anyOf: [{ type: "string", enum: ["a"] }, { type: "null" }] }, + { type: "string", enum: ["a", null], nullable: true } + ) + assertToStandaloneOpenApi3_0( + { anyOf: [{ type: "string", const: "a" }, { type: "null" }] }, + { type: "string", enum: ["a", null], nullable: true } + ) + }) + + it("keeps the other branches of a union", () => { + assertToStandaloneOpenApi3_0( + { anyOf: [{ $ref: "#/$defs/A" }, { type: "string" }, { type: "null" }, { type: "null" }] }, + { anyOf: [{ $ref: "#/definitions/A" }, { type: "string", nullable: true }] }, + { A: { type: "number" } }, + { A: { type: "number" } } + ) + }) + + it("keeps the union when siblings are not annotations", () => { + assertToStandaloneOpenApi3_0( + { anyOf: [{ type: "string" }, { type: "null" }], minLength: 1 }, + { minLength: 1, anyOf: [{ type: "string", nullable: true }] } + ) + }) + + it("writes null as an enum when no branch has a type", () => { + assertToStandaloneOpenApi3_0( + { anyOf: [{ $ref: "#/$defs/A" }, { type: "null" }] }, + { anyOf: [{ $ref: "#/definitions/A" }, { enum: [null] }] }, + { A: { type: "string" } }, + { A: { type: "string" } } + ) + assertToStandaloneOpenApi3_0( + { anyOf: [{ type: "object", allOf: [{ $ref: "#/$defs/A" }] }, { type: "null" }] }, + { anyOf: [{ type: "object", allOf: [{ $ref: "#/definitions/A" }] }, { enum: [null] }] }, + { A: { type: "object" } }, + { A: { type: "object" } } + ) + assertToStandaloneOpenApi3_0({ type: "null", description: "d" }, { enum: [null], description: "d" }) + assertToStandaloneOpenApi3_0({ type: "null", enum: [null, "a"] }, { enum: [null] }) + }) + + it("splits type arrays", () => { + assertToStandaloneOpenApi3_0({ type: ["string", "null"] }, { type: "string", nullable: true }) + assertToStandaloneOpenApi3_0({ type: ["null"] }, { enum: [null] }) + assertToStandaloneOpenApi3_0( + { type: ["string", "number", "null"], minLength: 1 }, + { minLength: 1, anyOf: [{ type: "string", nullable: true }, { type: "number" }] } + ) + assertToStandaloneOpenApi3_0( + { type: ["string", "number"], anyOf: [{ minLength: 1 }, { minimum: 1 }] }, + { + anyOf: [{ minLength: 1 }, { minimum: 1 }], + allOf: [{ anyOf: [{ type: "string" }, { type: "number" }] }] + } + ) + }) + + it("reads back with fromSchemaOpenApi3_0", () => { + const roundtrip = (schema: JsonSchema.JsonSchema) => + JsonSchema.fromSchemaOpenApi3_0( + JsonSchema.toStandaloneOpenApi3_0({ dialect: "draft-2020-12", schema, definitions: {} }).schema + ).schema + deepStrictEqual(roundtrip({ type: "null" }), { enum: [null] }) + deepStrictEqual(roundtrip({ anyOf: [{ type: "string" }, { type: "null" }] }), { type: ["string", "null"] }) + }) + }) + + it("rewrites definition references", () => { + assertToStandaloneOpenApi3_0( + { type: "array", items: { $ref: "#/$defs/A" } }, + { type: "array", items: { $ref: "#/definitions/A" } }, + { A: { anyOf: [{ type: "string" }, { $ref: "#/$defs/A" }] } }, + { A: { anyOf: [{ type: "string" }, { $ref: "#/definitions/A" }] } } + ) + }) + + it("rejects keywords without an OpenAPI 3.0 equivalent", () => { + const convert = (schema: JsonSchema.JsonSchema) => () => + JsonSchema.toStandaloneOpenApi3_0({ dialect: "draft-2020-12", schema, definitions: {} }) + assert.throws( + convert({ type: "array", prefixItems: [{ type: "string" }] }), + /Cannot convert JSON Schema keyword "prefixItems" to OpenAPI 3.0: items must be a single schema/ + ) + assert.throws( + convert({ type: "object", patternProperties: { "^a": { type: "string" } } }), + /Cannot convert JSON Schema keyword "patternProperties" to OpenAPI 3.0/ + ) + assert.throws( + convert({ dependentRequired: { a: ["b"] } }), + /Cannot convert JSON Schema keyword "dependentRequired" to OpenAPI 3.0/ + ) + assert.throws(convert({ $id: "a.json" }), /Cannot convert JSON Schema keyword "\$id" to OpenAPI 3.0/) + assert.throws(convert({ nullable: true }), /Cannot convert JSON Schema keyword "nullable" to OpenAPI 3.0/) + }) + }) + describe("toMultiDocumentOpenApi3_1", () => { it("rejects opaque keywords that OpenAPI 3.1 would activate", () => { for ( diff --git a/packages/effect/test/schema/toStandardJSONSchemaV1.test.ts b/packages/effect/test/schema/toStandardJSONSchemaV1.test.ts index 25f0be6f13d..a53cba69d78 100644 --- a/packages/effect/test/schema/toStandardJSONSchemaV1.test.ts +++ b/packages/effect/test/schema/toStandardJSONSchemaV1.test.ts @@ -1,4 +1,4 @@ -import { assertTrue, deepStrictEqual, strictEqual } from "@effect/vitest/utils" +import { assertTrue, deepStrictEqual, strictEqual, throws } from "@effect/vitest/utils" import { Schema } from "effect" import type { StandardJSONSchemaV1 } from "effect/StandardSchema" import { describe, it } from "vitest" @@ -163,4 +163,149 @@ describe("toStandardJSONSchemaV1", () => { }) }) }) + + describe("openapi-3.0", () => { + it("should return the input JSON Schema", () => { + const schema = Schema.Struct({ a: Schema.NullOr(Schema.FiniteFromString) }) + const standardJSONSchema = Schema.toStandardJSONSchemaV1(schema) + deepStrictEqual(standardConvertToJSONSchemaInput(standardJSONSchema, "openapi-3.0"), { + "type": "object", + "properties": { + "a": { "type": "string", "nullable": true } + }, + "required": ["a"], + "additionalProperties": {} + }) + }) + + it("should return the output JSON Schema", () => { + const schema = Schema.Struct({ a: Schema.NullOr(Schema.FiniteFromString) }) + const standardJSONSchema = Schema.toStandardJSONSchemaV1(schema) + deepStrictEqual(standardConvertToJSONSchemaOutput(standardJSONSchema, "openapi-3.0"), { + "type": "object", + "properties": { + "a": { "type": "number", "nullable": true } + }, + "required": ["a"], + "additionalProperties": {} + }) + }) + + it("a nullable schema", () => { + const schema = Schema.NullOr(Schema.String).annotate({ description: "name", examples: ["a", null] }) + const standardJSONSchema = Schema.toStandardJSONSchemaV1(schema) + deepStrictEqual(standardConvertToJSONSchemaInput(standardJSONSchema, "openapi-3.0"), { + "type": "string", + "nullable": true, + "description": "name", + "example": "a" + }) + }) + + it("a nullable literal", () => { + const schema = Schema.NullOr(Schema.Literal("cat")) + const standardJSONSchema = Schema.toStandardJSONSchemaV1(schema) + deepStrictEqual(standardConvertToJSONSchemaInput(standardJSONSchema, "openapi-3.0"), { + "type": "string", + "enum": ["cat", null], + "nullable": true + }) + }) + + it("a nullable union", () => { + const schema = Schema.Union([Schema.Boolean, Schema.Int, Schema.Null]) + const standardJSONSchema = Schema.toStandardJSONSchemaV1(schema) + deepStrictEqual(standardConvertToJSONSchemaInput(standardJSONSchema, "openapi-3.0"), { + "anyOf": [ + { "type": "boolean", "nullable": true }, + { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 } + ] + }) + }) + + it("a nullable reference", () => { + const schema = Schema.NullOr(Schema.String.annotate({ identifier: "id" })) + const standardJSONSchema = Schema.toStandardJSONSchemaV1(schema) + deepStrictEqual(standardConvertToJSONSchemaInput(standardJSONSchema, "openapi-3.0"), { + "anyOf": [ + { "$ref": "#/definitions/id" }, + { "enum": [null] } + ], + "definitions": { + "id": { + "type": "string" + } + } + }) + }) + + it("null", () => { + const standardJSONSchema = Schema.toStandardJSONSchemaV1(Schema.Null) + deepStrictEqual(standardConvertToJSONSchemaInput(standardJSONSchema, "openapi-3.0"), { + "enum": [null] + }) + }) + + it("a literal", () => { + const standardJSONSchema = Schema.toStandardJSONSchemaV1(Schema.Literal("cat")) + deepStrictEqual(standardConvertToJSONSchemaInput(standardJSONSchema, "openapi-3.0"), { + "type": "string", + "enum": ["cat"] + }) + }) + + it("exclusive bounds", () => { + const schema = Schema.Finite.check(Schema.isGreaterThan(0), Schema.isLessThan(10)) + const standardJSONSchema = Schema.toStandardJSONSchemaV1(schema) + deepStrictEqual(standardConvertToJSONSchemaInput(standardJSONSchema, "openapi-3.0"), { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true, + "maximum": 10, + "exclusiveMaximum": true + }) + }) + + it("a schema with identifier", () => { + const S = Schema.String.annotate({ identifier: "id" }) + const schema = Schema.Struct({ a: S, b: S }) + const standardJSONSchema = Schema.toStandardJSONSchemaV1(schema) + deepStrictEqual(standardConvertToJSONSchemaInput(standardJSONSchema, "openapi-3.0"), { + "type": "object", + "properties": { + "a": { "$ref": "#/definitions/id" }, + "b": { "$ref": "#/definitions/id" } + }, + "required": ["a", "b"], + "additionalProperties": {}, + "definitions": { + "id": { + "type": "string" + } + } + }) + }) + + it("should throw for a tuple", () => { + const standardJSONSchema = Schema.toStandardJSONSchemaV1(Schema.Tuple([Schema.String])) + throws( + () => standardConvertToJSONSchemaInput(standardJSONSchema, "openapi-3.0"), + new Error( + `Cannot convert JSON Schema keyword "prefixItems" to OpenAPI 3.0: items must be a single schema` + ) + ) + }) + }) + + it("should throw for an unsupported target", () => { + const standardJSONSchema = Schema.toStandardJSONSchemaV1(Schema.String) + throws( + () => standardConvertToJSONSchemaInput(standardJSONSchema, "draft-04"), + new Error("Unsupported target: draft-04") + ) + throws( + () => standardConvertToJSONSchemaOutput(standardJSONSchema, "draft-04"), + new Error("Unsupported target: draft-04") + ) + }) })