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
7 changes: 7 additions & 0 deletions .changeset/numeric-32-bit-schemas.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"effect-app": minor
---

Add bounded 32-bit numeric schemas: `Int32`, `NonNegativeInt32`, `PositiveInt32` (signed Java `Integer` range, `format: "int32"`) and `NonNegativeNumber32`, `PositiveNumber32` (finite IEEE 754 binary32 range, `format: "float"`). Limits are enforced on decode and encode and emitted as JSON Schema / OpenAPI `minimum`/`maximum`. Float bounds are Java's `Float.MAX_VALUE` / `Float.MIN_VALUE` literals (`3.4028235E38`, `1.4E-45`), so every accepted value stays finite in binary32 and `PositiveNumber32` values stay non-zero (no overflow / underflow). Values are not rounded. Brands extend the existing `Int`/`NonNegativeInt`/`PositiveInt`/`NonNegativeNumber`/`PositiveNumber` brands. Bound constants `INT32_MIN`, `INT32_MAX`, `FLOAT32_MIN_POSITIVE`, `FLOAT32_MAX` are exported.

`flattenSimpleAllOf` now intersects repeated bounds (tighter `minimum`/`maximum`/length bounds win) and keeps the `allOf` when other non-annotation keywords conflict, instead of letting the last `allOf` member overwrite parent constraints.
50 changes: 47 additions & 3 deletions packages/effect-app/src/Schema/SpecialJsonSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,53 @@ export function specialJsonSchemaDocument(
}
}

const lowerBoundKeywords = new Set(["minimum", "exclusiveMinimum", "minLength", "minItems", "minProperties"])
const upperBoundKeywords = new Set(["maximum", "exclusiveMaximum", "maxLength", "maxItems", "maxProperties"])
const annotationKeywords = new Set([
"title",
"description",
"default",
"examples",
"readOnly",
"writeOnly",
"deprecated",
"$comment"
])
const isAnnotationKeyword = (key: string) => annotationKeywords.has(key) || key.startsWith("x-")

// Every keyword of an `allOf` member applies, so a repeated bound reduces to its tighter value.
// Returns `undefined` on any other conflicting validation keyword: then the `allOf` is kept.
function mergeAllOfEntry(
merged: Record<string, unknown>,
entry: Record<string, unknown>
): Record<string, unknown> | undefined {
const out = { ...merged }
for (const [key, value] of Object.entries(entry)) {
const current = out[key]
if (!(key in out) || isAnnotationKeyword(key)) {
out[key] = value
} else if (typeof current === "number" && typeof value === "number" && lowerBoundKeywords.has(key)) {
out[key] = Math.max(current, value)
} else if (typeof current === "number" && typeof value === "number" && upperBoundKeywords.has(key)) {
out[key] = Math.min(current, value)
} else if (JSON.stringify(current) !== JSON.stringify(value)) {
return undefined
}
}
if (typeof out["minimum"] === "number" && typeof out["exclusiveMinimum"] === "number") {
delete out[out["exclusiveMinimum"] >= out["minimum"] ? "minimum" : "exclusiveMinimum"]
}
if (typeof out["maximum"] === "number" && typeof out["exclusiveMaximum"] === "number") {
delete out[out["exclusiveMaximum"] <= out["maximum"] ? "maximum" : "exclusiveMaximum"]
}
return out
}

/**
* Flattens `allOf` entries into the parent when the parent already has a
* `type` and every `allOf` entry is a plain constraint object (no `$ref`,
* no `type`). Merged properties from `allOf` entries win on conflict.
* no `type`). Repeated bounds keep the tighter value, annotations from
* `allOf` entries win, and any other conflicting keyword keeps the `allOf`.
*/
export function flattenSimpleAllOf(obj: unknown): unknown {
if (obj === null || typeof obj !== "object") return obj
Expand All @@ -50,9 +93,10 @@ export function flattenSimpleAllOf(obj: unknown): unknown {
)
if (canFlatten) {
const { allOf: _, ...rest } = result
const merged: Record<string, unknown> = { ...rest }
let merged: Record<string, unknown> | undefined = rest
for (const entry of allOf) {
Object.assign(merged, entry)
merged = mergeAllOfEntry(merged, entry)
if (merged === undefined) return result
}
return merged
}
Expand Down
165 changes: 165 additions & 0 deletions packages/effect-app/src/Schema/numbers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,168 @@ export type NonNegativeDecimal = NonNegativeNumber
export const PositiveDecimal = PositiveNumber
/** @deprecated Not an actual decimal */
export type PositiveDecimal = PositiveNumber

/** Signed 32-bit integer bounds, matching Java `Integer.MIN_VALUE` / `Integer.MAX_VALUE`. */
export const INT32_MIN = -2147483648
export const INT32_MAX = 2147483647
/**
* Java's `Float.MAX_VALUE` literal `3.4028235E38` (as written by `Float.toString`). Rounds to the largest
* finite IEEE 754 binary32 value; anything accepted up to it stays finite in binary32 (no overflow).
*/
export const FLOAT32_MAX = 3.4028235e38
/**
* Java's `Float.MIN_VALUE` literal `1.4E-45` (as written by `Float.toString`). Rounds to the smallest
* positive binary32 value (subnormal `2^-149`); anything accepted from it stays non-zero (no underflow).
*/
export const FLOAT32_MIN_POSITIVE = 1.4e-45

// The upper-bound check also carries the OpenAPI `format`, so Effect inlines it next to the
// tightened `minimum`/`maximum` instead of emitting a separate `allOf` member.
const isInt32Maximum = () =>
S.isLessThanOrEqualTo(INT32_MAX, { toJsonSchema: () => ({ maximum: INT32_MAX, format: "int32" }) })
const isFloat32Maximum = () =>
S.isLessThanOrEqualTo(FLOAT32_MAX, { toJsonSchema: () => ({ maximum: FLOAT32_MAX, format: "float" }) })

export interface Int32Brand extends Simplify<B.Brand<"Int32"> & IntBrand> {}
export type Int32 = number & Int32Brand
/**
* Signed 32-bit integer (`[-2147483648, 2147483647]`), JSON Schema `format: "int32"`.
* `.withConstructorDefault` => `0` (construction-only).
*/
export interface Int32Schema extends BrandedSchema<S.Int, Int32> {
(i: number, options?: SchemaAST.ParseOptions): Int32
readonly withConstructorDefault: S.withConstructorDefault<BrandedSchema<S.Int, Int32>>
}
export const Int32: Int32Schema = extendM(
S.Int.pipe(
S.check(S.isGreaterThanOrEqualTo(INT32_MIN), isInt32Maximum()),
fromBrand<Int32>(nominal<Int32>(), { identifier: "Int32", jsonSchema: {} }),
withDefaultMake
),
(s) => ({
/** Construction-only default `0`. NOT applied during decode. See file-level note. */
withConstructorDefault: s.pipe(S.withConstructorDefault(Effect.sync(() => s(0))))
})
)

export interface NonNegativeInt32Brand
extends Simplify<B.Brand<"NonNegativeInt32"> & Int32Brand & NonNegativeIntBrand & NonNegativeNumber32Brand>
{}
export type NonNegativeInt32 = number & NonNegativeInt32Brand
/**
* Non-negative signed 32-bit integer (`[0, 2147483647]`), JSON Schema `format: "int32"`.
* `.withConstructorDefault` => `0` (construction-only).
*/
export interface NonNegativeInt32Schema extends BrandedSchema<S.Int, NonNegativeInt32> {
(i: number, options?: SchemaAST.ParseOptions): NonNegativeInt32
readonly withConstructorDefault: S.withConstructorDefault<BrandedSchema<S.Int, NonNegativeInt32>>
}
export const NonNegativeInt32: NonNegativeInt32Schema = extendM(
S.Int.pipe(
S.check(S.isGreaterThanOrEqualTo(0), isInt32Maximum()),
fromBrand<NonNegativeInt32>(nominal<NonNegativeInt32>(), { identifier: "NonNegativeInt32", jsonSchema: {} }),
withDefaultMake
),
(s) => ({
/** Construction-only default `0`. NOT applied during decode. See file-level note. */
withConstructorDefault: s.pipe(S.withConstructorDefault(Effect.sync(() => s(0))))
})
)

export interface PositiveInt32Brand
extends Simplify<B.Brand<"PositiveInt32"> & NonNegativeInt32Brand & PositiveIntBrand & PositiveNumber32Brand>
{}
export type PositiveInt32 = number & PositiveInt32Brand
/**
* Positive signed 32-bit integer (`[1, 2147483647]`), JSON Schema `format: "int32"`.
* `.withConstructorDefault` => `1` (construction-only).
*/
export interface PositiveInt32Schema extends BrandedSchema<S.Int, PositiveInt32> {
(i: number, options?: SchemaAST.ParseOptions): PositiveInt32
readonly withConstructorDefault: S.withConstructorDefault<BrandedSchema<S.Int, PositiveInt32>>
}
export const PositiveInt32: PositiveInt32Schema = extendM(
S.Int.pipe(
// `>= 1` rather than `> 0`: same integer set, but an inclusive `minimum` that Java generators keep exact
S.check(S.isGreaterThanOrEqualTo(1), isInt32Maximum()),
fromBrand<PositiveInt32>(nominal<PositiveInt32>(), { identifier: "PositiveInt32", jsonSchema: {} }),
withDefaultMake
),
(s) => ({
/** Construction-only default `1`. NOT applied during decode. See file-level note. */
withConstructorDefault: s.pipe(S.withConstructorDefault(Effect.sync(() => s(1))))
})
)

export interface NonNegativeNumber32Brand extends Simplify<B.Brand<"NonNegativeNumber32"> & NonNegativeNumberBrand> {}
export type NonNegativeNumber32 = number & NonNegativeNumber32Brand
/**
* Non-negative finite number within IEEE 754 binary32 range (`[0, 3.4028235e38]`),
* JSON Schema `format: "float"`.
*
* Range-only: values are kept as-is (no rounding to binary32); a binary32 consumer rounds to its
* nearest float (~7 significant digits). Values above `FLOAT32_MAX` are rejected (overflow to
* `Infinity`, conservatively from Java's literal). Tiny values below `FLOAT32_MIN_POSITIVE` are accepted:
* they may underflow to `0` in binary32, which keeps them non-negative. `.withConstructorDefault` => `0` (construction-only).
*/
export interface NonNegativeNumber32Schema extends BrandedSchema<S.Finite, NonNegativeNumber32> {
(i: number, options?: SchemaAST.ParseOptions): NonNegativeNumber32
readonly withConstructorDefault: S.withConstructorDefault<BrandedSchema<S.Finite, NonNegativeNumber32>>
}
export const NonNegativeNumber32: NonNegativeNumber32Schema = extendM(
S.Finite.pipe(
S.check(
S.isGreaterThanOrEqualTo(0, {
arbitraryConstraint: { order: Order.Number, minimum: 0, maximum: realisticMaximum }
}),
isFloat32Maximum()
),
fromBrand<NonNegativeNumber32>(nominal<NonNegativeNumber32>(), {
identifier: "NonNegativeNumber32",
jsonSchema: {}
}),
withDefaultMake
),
(s) => ({
/** Construction-only default `0`. NOT applied during decode. See file-level note. */
withConstructorDefault: s.pipe(S.withConstructorDefault(Effect.sync(() => s(0))))
})
)

export interface PositiveNumber32Brand
extends Simplify<B.Brand<"PositiveNumber32"> & NonNegativeNumber32Brand & PositiveNumberBrand>
{}
export type PositiveNumber32 = number & PositiveNumber32Brand
/**
* Positive finite number within IEEE 754 binary32 range
* (`[1.4e-45, 3.4028235e38]`), JSON Schema `format: "float"`.
*
* Range-only: values are kept as-is (no rounding to binary32); a binary32 consumer rounds to its
* nearest float (~7 significant digits). Values above `FLOAT32_MAX` (overflow to `Infinity`) and
* values below `FLOAT32_MIN_POSITIVE` (underflow to `0`, losing positivity) are rejected, conservatively
* from Java's `Float` literals.
* `.withConstructorDefault` => `1` (construction-only).
*/
export interface PositiveNumber32Schema extends BrandedSchema<S.Finite, PositiveNumber32> {
(i: number, options?: SchemaAST.ParseOptions): PositiveNumber32
readonly withConstructorDefault: S.withConstructorDefault<BrandedSchema<S.Finite, PositiveNumber32>>
}
export const PositiveNumber32: PositiveNumber32Schema = extendM(
S.Finite.pipe(
S.check(
S.isGreaterThanOrEqualTo(FLOAT32_MIN_POSITIVE, {
arbitraryConstraint: { order: Order.Number, minimum: FLOAT32_MIN_POSITIVE, maximum: realisticMaximum }
}),
isFloat32Maximum()
),
fromBrand<PositiveNumber32>(nominal<PositiveNumber32>(), {
identifier: "PositiveNumber32",
jsonSchema: {}
}),
withDefaultMake
),
(s) => ({
/** Construction-only default `1`. NOT applied during decode. See file-level note. */
withConstructorDefault: s.pipe(S.withConstructorDefault(Effect.sync(() => s(1))))
})
)
Loading
Loading