Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/add-schema-is-non-blank.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions .changeset/schema-is-well-formed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": minor
---

Add `Schema.isWellFormed()` to validate Unicode strings and generate well-formed examples with `Arbitrary.schema`.
62 changes: 62 additions & 0 deletions packages/effect/src/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -6919,6 +6920,66 @@ 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.
*
* **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.
*
Expand Down Expand Up @@ -19091,6 +19152,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
Expand Down
31 changes: 31 additions & 0 deletions packages/effect/src/SchemaRepresentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,37 @@ export const isTrimmedReviver: FilterReviver<null> = makeReviverFilter(
({ annotations }) => Schema.isTrimmed(annotations)
)

/**
* Reconstructs persisted {@link Schema.isNonBlank} checks.
*
* @stability unstable
* @category validation
* @since 4.3.0
*/
export const isNonBlankReviver: FilterReviver<null> = makeReviverFilter(
"effect/schema/isNonBlank",
Schema.Null,
({ annotations }) => Schema.isNonBlank(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<null> = makeReviverFilter(
"effect/schema/isWellFormed",
Schema.Null,
({ annotations }) => Schema.isWellFormed(annotations)
)

/**
* Reviver for persisted `isPattern` checks.
*
Expand Down
5 changes: 4 additions & 1 deletion packages/effect/src/String.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -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.
Expand Down
32 changes: 20 additions & 12 deletions packages/effect/src/internal/arbitrary/regexp.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -146,13 +147,16 @@ function concatenation(nodes: ReadonlyArray<Node>): Node {
}
}

function alternation(nodes: ReadonlyArray<Node>): Node {
function alternation(nodes: ReadonlyArray<Node>, wellFormed = false): Node {
const flattened: Array<Node> = []
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<Interval>): ReadonlyArray<Interval> {
Expand Down Expand Up @@ -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 {
Expand All @@ -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 "(":
Expand Down Expand Up @@ -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
}
}

Expand Down Expand Up @@ -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)
Expand All @@ -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<number> = []
for (let length = minimumLength; length <= maximumLength; length++) {
Expand Down
Loading
Loading