diff --git a/packages/effect/src/schema/AST.ts b/packages/effect/src/schema/AST.ts index 80e40c8eed..ca93d0f766 100644 --- a/packages/effect/src/schema/AST.ts +++ b/packages/effect/src/schema/AST.ts @@ -15,7 +15,6 @@ import { memoize } from "../Function.ts" import { effectIsExit } from "../internal/effect.ts" import * as internalRecord from "../internal/record.ts" import * as RegEx from "../primitives/RegExp.ts" -import type { Annotated } from "./Annotations.ts" import * as Annotations from "./Annotations.ts" import * as Check from "./Check.ts" import * as Getter from "./Getter.ts" @@ -308,7 +307,7 @@ export type Checks = readonly [Check.Check, ...Array>] * @category model * @since 4.0.0 */ -export abstract class Base implements Annotated { +export abstract class Base { readonly annotations: Annotations.Annotations | undefined readonly checks: Checks | undefined readonly encoding: Encoding | undefined @@ -382,6 +381,7 @@ export class Declaration extends Base { } /** @internal */ getExpected(): string { + // Annotations on checks are ignored internally const expected = this.annotations?.identifier ?? this.annotations?.title if (Predicate.isString(expected)) return expected return "" @@ -2070,15 +2070,17 @@ export function record(key: AST, value: AST, keyValueCombiner: KeyValueCombiner return new TypeLiteral([], [new IndexSignature(false, key, value, keyValueCombiner)]) } -/** @internal */ -export function isOptional(ast: AST): boolean { - return ast.context?.isOptional ?? false -} - // ------------------------------------------------------------------------------------- // Public APIs // ------------------------------------------------------------------------------------- +/** + * @since 4.0.0 + */ +export function isOptional(ast: AST): boolean { + return ast.context?.isOptional ?? false +} + /** * @since 4.0.0 */ diff --git a/packages/effect/src/schema/Annotations.ts b/packages/effect/src/schema/Annotations.ts index 3c0d4d87bd..99b1233e4f 100644 --- a/packages/effect/src/schema/Annotations.ts +++ b/packages/effect/src/schema/Annotations.ts @@ -20,14 +20,6 @@ export interface Annotations { readonly [x: string]: unknown } -/** - * @category Model - * @since 4.0.0 - */ -export interface Annotated { - readonly annotations: Annotations | undefined -} - /** * @category Model * @since 4.0.0 @@ -98,6 +90,9 @@ export interface Declaration readonly "~sentinels"?: ReadonlyArray | undefined } +/** @internal */ +export const STRUCTURAL_ANNOTATION_KEY = "~structural" + /** * @category Model * @since 4.0.0 @@ -162,39 +157,50 @@ export function combine(existing: A | undefined, incoming return out } -/** @internal */ -export function getAnnotations(ast: AST.AST): Annotations | undefined { +/** + * Get all annotations from the AST. + * If the AST has checks, it will return the annotations from the last check. + * + * @since 4.0.0 + */ +export function get(ast: AST.AST): Annotations | undefined { return ast.checks ? ast.checks[ast.checks.length - 1].annotations : ast.annotations } -/** @internal */ -export function getAnnotation(f: (annotations: Annotations | undefined) => A | undefined) { - return (ast: AST.AST): A | undefined => f(getAnnotations(ast)) +/** + * Get an annotation from the AST. + * If the AST has checks, it will return the annotations from the last check. + * + * @since 4.0.0 + */ +export function getAt(key: string, parser: (u: unknown) => u is A) { + return (ast: AST.AST): A | undefined => { + const value = get(ast)?.[key] + if (parser(value)) return value + } } -/** @internal */ -export const getIdentifierAnnotation = getAnnotation((annotations) => { - const identifier = annotations?.identifier - if (Predicate.isString(identifier)) return identifier -}) +/** + * @since 4.0.0 + */ +export const getIdentifier = getAt("identifier", Predicate.isString) -/** @internal */ -export const getDescriptionAnnotation = getAnnotation((annotations) => { - const description = annotations?.description - if (Predicate.isString(description)) return description -}) +/** + * @since 4.0.0 + */ +export const getDescription = getAt("description", Predicate.isString) /** @internal */ export const getExpected = memoize((ast: AST.AST): string => { - return getIdentifierAnnotation(ast) ?? ast.getExpected(getExpected) + return getIdentifier(ast) ?? ast.getExpected(getExpected) }) /** @internal */ -export const BRAND_KEY = "~effect/schema/Check/brand" +export const BRAND_ANNOTATION_KEY = "~effect/schema/Check/brand" /** @internal */ export function getBrand(check: Check.Check): string | symbol | undefined { - const brand = check.annotations?.[BRAND_KEY] + const brand = check.annotations?.[BRAND_ANNOTATION_KEY] if (Predicate.isString(brand) || Predicate.isSymbol(brand)) { return brand } diff --git a/packages/effect/src/schema/Check.ts b/packages/effect/src/schema/Check.ts index dcf233b98a..bdeabbd3a6 100644 --- a/packages/effect/src/schema/Check.ts +++ b/packages/effect/src/schema/Check.ts @@ -19,7 +19,7 @@ import * as Issue from "./Issue.ts" * @category model * @since 4.0.0 */ -export class Filter extends Class implements Annotations.Annotated { +export class Filter extends Class { readonly _tag = "Filter" readonly run: (input: E, self: AST.AST, options: AST.ParseOptions) => Issue.Issue | undefined readonly annotations: Annotations.Filter | undefined @@ -55,7 +55,7 @@ export class Filter extends Class implements Annotations.Annotated { * @category model * @since 4.0.0 */ -export class FilterGroup extends Class implements Annotations.Annotated { +export class FilterGroup extends Class { readonly _tag = "FilterGroup" readonly checks: readonly [Check, Check, ...Array>] readonly annotations: Annotations.Filter | undefined @@ -151,7 +151,7 @@ export function makeBrand( brand: B, annotations?: Annotations.Filter ): Refinement, T> { - return brand_.annotate(Annotations.combine({ [Annotations.BRAND_KEY]: brand }, annotations)) + return brand_.annotate(Annotations.combine({ [Annotations.BRAND_ANNOTATION_KEY]: brand }, annotations)) } /** @@ -1168,7 +1168,7 @@ export function minLength(minLength: number, annotations?: Annotations.Filter) { _tag: "minLength", minLength }, - "~structural": true, + [Annotations.STRUCTURAL_ANNOTATION_KEY]: true, arbitrary: { _tag: "Constraints", constraints: { @@ -1220,7 +1220,7 @@ export function maxLength(maxLength: number, annotations?: Annotations.Filter) { _tag: "maxLength", maxLength }, - "~structural": true, + [Annotations.STRUCTURAL_ANNOTATION_KEY]: true, arbitrary: { _tag: "Constraints", constraints: { @@ -1264,7 +1264,7 @@ export function length(length: number, annotations?: Annotations.Filter) { _tag: "length", length }, - "~structural": true, + [Annotations.STRUCTURAL_ANNOTATION_KEY]: true, arbitrary: { _tag: "Constraints", constraints: { @@ -1299,7 +1299,7 @@ export function minSize(minSize: number, annotations?: Annotations.Filter) { _tag: "minSize", minSize }, - "~structural": true, + [Annotations.STRUCTURAL_ANNOTATION_KEY]: true, arbitrary: { _tag: "Constraints", constraints: { @@ -1328,7 +1328,7 @@ export function maxSize(maxSize: number, annotations?: Annotations.Filter) { _tag: "maxSize", maxSize }, - "~structural": true, + [Annotations.STRUCTURAL_ANNOTATION_KEY]: true, arbitrary: { _tag: "Constraints", constraints: { @@ -1357,7 +1357,7 @@ export function size(size: number, annotations?: Annotations.Filter) { _tag: "size", size }, - "~structural": true, + [Annotations.STRUCTURAL_ANNOTATION_KEY]: true, arbitrary: { _tag: "Constraints", constraints: { @@ -1391,7 +1391,7 @@ export function minEntries(minEntries: number, annotations?: Annotations.Filter) _tag: "minEntries", minEntries }, - "~structural": true, + [Annotations.STRUCTURAL_ANNOTATION_KEY]: true, arbitrary: { _tag: "Constraints", constraints: { @@ -1424,7 +1424,7 @@ export function maxEntries(maxEntries: number, annotations?: Annotations.Filter) _tag: "maxEntries", maxEntries }, - "~structural": true, + [Annotations.STRUCTURAL_ANNOTATION_KEY]: true, arbitrary: { _tag: "Constraints", constraints: { @@ -1457,7 +1457,7 @@ export function entries(entries: number, annotations?: Annotations.Filter) { _tag: "entries", entries }, - "~structural": true, + [Annotations.STRUCTURAL_ANNOTATION_KEY]: true, arbitrary: { _tag: "Constraints", constraints: { diff --git a/packages/effect/src/schema/Issue.ts b/packages/effect/src/schema/Issue.ts index 1fafd2a02a..72f03839b9 100644 --- a/packages/effect/src/schema/Issue.ts +++ b/packages/effect/src/schema/Issue.ts @@ -626,18 +626,18 @@ function toDefaultIssues( } } -function formatCheck(filter: Check.Check): string { - const out = filter.annotations?.description ?? filter.annotations?.title +function formatCheck(check: Check.Check): string { + const out = check.annotations?.description ?? check.annotations?.title if (Predicate.isString(out)) return out - const brand = Annotations.getBrand(filter) + const brand = Annotations.getBrand(check) if (brand !== undefined) return `Brand<"${String(brand)}">` - switch (filter._tag) { + switch (check._tag) { case "Filter": return "" case "FilterGroup": - return filter.checks.map((check) => formatCheck(check)).join(" & ") + return check.checks.map((check) => formatCheck(check)).join(" & ") } } diff --git a/packages/effect/src/schema/Schema.ts b/packages/effect/src/schema/Schema.ts index 83147f78c7..aa1b91210f 100644 --- a/packages/effect/src/schema/Schema.ts +++ b/packages/effect/src/schema/Schema.ts @@ -119,7 +119,7 @@ export interface Bottom< readonly "EncodingServices": RE readonly "~type.make.in": TypeMakeIn - readonly "~type.make": TypeMake + readonly "~type.make": TypeMake // useful to type the `refine` interface readonly "~type.constructor.default": TypeConstructorDefault readonly "Iso": Iso @@ -145,86 +145,35 @@ export interface Bottom< const TypeId = "~effect/schema/Schema" -abstract class BottomImpl< - T, - E, - RD, - RE, - Ast extends AST.AST, - RebuildOut extends Top, - AnnotateIn extends Annotations.Annotations, - TypeMakeIn = T, - Iso = T, - TypeMake = TypeMakeIn, - TypeMutability extends Mutability = "readonly", - TypeOptionality extends Optionality = "required", - TypeConstructorDefault extends ConstructorDefault = "no-default", - EncodedMutability extends Mutability = "readonly", - EncodedOptionality extends Optionality = "required" -> extends Pipeable.Class implements - Bottom< - T, - E, - RD, - RE, - Ast, - RebuildOut, - AnnotateIn, - TypeMakeIn, - Iso, - TypeMake, - TypeMutability, - TypeOptionality, - TypeConstructorDefault, - EncodedMutability, - EncodedOptionality - > -{ - readonly [TypeId] = TypeId - - declare readonly "Type": T - declare readonly "Encoded": E - declare readonly "DecodingServices": RD - declare readonly "EncodingServices": RE - - declare readonly "~rebuild.out": RebuildOut - declare readonly "~annotate.in": AnnotateIn - - declare readonly "~type.make.in": TypeMakeIn - declare readonly "~type.make": TypeMake - declare readonly "~type.constructor.default": TypeConstructorDefault - declare readonly "Iso": Iso - - declare readonly "~type.mutability": TypeMutability - declare readonly "~type.optionality": TypeOptionality - declare readonly "~encoded.mutability": EncodedMutability - declare readonly "~encoded.optionality": EncodedOptionality - - readonly ast: Ast - readonly makeSync: (input: this["~type.make.in"], options?: MakeOptions) => this["Type"] - - constructor(ast: Ast) { - super() - this.ast = ast - this.makeSync = ToParser.makeSync(this) - } - abstract rebuild(ast: this["ast"]): this["~rebuild.out"] - annotate(annotations: this["~annotate.in"]): this["~rebuild.out"] { +const Proto = { + [TypeId]: TypeId, + pipe() { + return Pipeable.pipeArguments(this, arguments) + }, + annotate(this: Top, annotations: Annotations.Annotations) { return this.rebuild(AST.annotate(this.ast, annotations)) - } - annotateKey(annotations: Annotations.Key): this["~rebuild.out"] { + }, + annotateKey(this: Top, annotations: Annotations.Key) { return this.rebuild(AST.annotateKey(this.ast, annotations)) - } + }, check( - ...checks: readonly [ - Check.Check, - ...Array> - ] - ): this["~rebuild.out"] { + this: Top, + ...checks: readonly [Check.Check, ...Array>] + ) { return this.rebuild(AST.appendChecks(this.ast, checks)) } } +/** @internal */ +export function makeProto(ast: AST.AST, options: object): S { + const self = Object.create(Proto) + Object.assign(self, options) + self.ast = ast + self.rebuild = (ast: AST.AST) => makeProto(ast, options) + self.makeSync = ToParser.makeSync(self) + return self +} + /** * Reveals the complete Bottom interface type of a schema, exposing all 14 type * parameters. @@ -737,34 +686,6 @@ export const encodeUnknownSync = ToParser.encodeUnknownSync */ export const encodeSync = ToParser.encodeSync -class make$ extends BottomImpl< - S["Type"], - S["Encoded"], - S["DecodingServices"], - S["EncodingServices"], - S["ast"], - S["~rebuild.out"], - S["~annotate.in"], - S["~type.make.in"], - S["Iso"], - S["~type.make"], - S["~type.mutability"], - S["~type.optionality"], - S["~type.constructor.default"], - S["~encoded.mutability"], - S["~encoded.optionality"] -> { - readonly rebuild: (ast: S["ast"]) => S["~rebuild.out"] - - constructor( - ast: S["ast"], - rebuild: (ast: S["ast"]) => S["~rebuild.out"] - ) { - super(ast) - this.rebuild = rebuild - } -} - /** * Creates a schema from an AST (Abstract Syntax Tree) node. * @@ -780,25 +701,8 @@ class make$ extends BottomImpl< * @category Constructors * @since 4.0.0 */ -export function make(ast: S["ast"]): Bottom< - S["Type"], - S["Encoded"], - S["DecodingServices"], - S["EncodingServices"], - S["ast"], - S["~rebuild.out"], - S["~annotate.in"], - S["~type.make.in"], - S["Iso"], - S["~type.make"], - S["~type.mutability"], - S["~type.optionality"], - S["~type.constructor.default"], - S["~encoded.mutability"], - S["~encoded.optionality"] -> { - const rebuild = (ast: AST.AST) => new make$(ast, rebuild) - return rebuild(ast) +export function make(ast: S["ast"]): S { + return makeProto(ast, {}) } /** @@ -842,15 +746,6 @@ interface optionalKeyLambda extends Lambda { readonly "~lambda.out": this["~lambda.in"] extends Top ? optionalKey : never } -class makeWithSchema$ extends make$ { - readonly schema: S - - constructor(ast: AST.AST, schema: S) { - super(ast, (ast) => new makeWithSchema$(ast, schema)) - this.schema = schema - } -} - /** * Creates an exact optional key schema for struct fields. Unlike `optional`, * this creates exact optional properties (not `| undefined`) that can be @@ -872,8 +767,8 @@ class makeWithSchema$ extends make$ { * * @since 4.0.0 */ -export const optionalKey = lambda(function optionalKey(self: S): optionalKey { - return new makeWithSchema$>(AST.optionalKey(self.ast), self) +export const optionalKey = lambda(function optionalKey(schema: S): optionalKey { + return makeProto(AST.optionalKey(schema.ast), { schema }) }) /** @@ -950,8 +845,8 @@ interface mutableKeyLambda extends Lambda { /** * @since 4.0.0 */ -export const mutableKey = lambda(function mutableKey(self: S): mutableKey { - return new makeWithSchema$>(AST.mutableKey(self.ast), self) +export const mutableKey = lambda(function mutableKey(schema: S): mutableKey { + return makeProto(AST.mutableKey(schema.ast), { schema }) }) /** @@ -987,8 +882,8 @@ interface typeCodecLambda extends Lambda { /** * @since 4.0.0 */ -export const typeCodec = lambda(function typeCodec(self: S): typeCodec { - return new makeWithSchema$>(AST.typeAST(self.ast), self) +export const typeCodec = lambda(function typeCodec(schema: S): typeCodec { + return makeProto(AST.typeAST(schema.ast), { schema }) }) /** @@ -1024,9 +919,13 @@ interface encodedCodecLambda extends Lambda { /** * @since 4.0.0 */ -export const encodedCodec = lambda(function encodedCodec(self: S): encodedCodec { - return new makeWithSchema$>(AST.encodedAST(self.ast), self) -}) +export const encodedCodec = lambda( + function encodedCodec(schema: S): encodedCodec { + return makeProto(AST.encodedAST(schema.ast), { schema }) + } +) + +const FlipTypeId = "~effect/schema/Schema/flip" /** * @since 4.0.0 @@ -1050,15 +949,11 @@ export interface flip extends S["~type.optionality"] > { + readonly "~rebuild.out": this + readonly [FlipTypeId]: typeof FlipTypeId readonly schema: S } -const FlipTypeId = "~effect/schema/Schema/flip$" - -class flip$ extends makeWithSchema$> implements flip { - readonly [FlipTypeId] = FlipTypeId -} - function isFlip$(schema: Top): schema is flip { return Predicate.hasProperty(schema, FlipTypeId) && schema[FlipTypeId] === FlipTypeId } @@ -1071,7 +966,7 @@ export function flip(schema: S): flip { if (isFlip$(schema)) { return schema.schema.rebuild(AST.flip(schema.ast)) } - return new flip$(AST.flip(schema.ast), schema) + return makeProto(AST.flip(schema.ast), { [FlipTypeId]: FlipTypeId, schema }) } /** @@ -1084,16 +979,6 @@ export interface Literal readonly literal: L } -class Literal$ extends make$> implements Literal { - declare readonly "~rebuild.out": this - readonly literal: L - - constructor(ast: AST.LiteralType, literal: L) { - super(ast, (ast) => new Literal$(ast, literal)) - this.literal = literal - } -} - /** * @see {@link Literals} for a schema that represents a union of literals. * @see {@link tag} for a schema that represents a literal value that can be @@ -1101,7 +986,7 @@ class Literal$ extends make$> implements Liter * @since 4.0.0 */ export function Literal(literal: L): Literal { - return new Literal$(new AST.LiteralType(literal), literal) + return makeProto(new AST.LiteralType(literal), { literal }) } /** @@ -1162,18 +1047,6 @@ export interface TemplateLiteral extends readonly parts: Parts } -class TemplateLiteral$ extends make$> - implements TemplateLiteral -{ - declare readonly "~rebuild.out": this - readonly parts: Parts - - constructor(ast: AST.TemplateLiteral, parts: Parts) { - super(ast, (ast) => new TemplateLiteral$(ast, parts)) - this.parts = parts - } -} - function templateLiteralFromParts(parts: Parts) { return new AST.TemplateLiteral(parts.map((part) => isSchema(part) ? part.ast : new AST.LiteralType(part))) } @@ -1182,7 +1055,7 @@ function templateLiteralFromParts(parts: Pa * @since 4.0.0 */ export function TemplateLiteral(parts: Parts): TemplateLiteral { - return new TemplateLiteral$(templateLiteralFromParts(parts), [...parts] as Parts) + return makeProto(templateLiteralFromParts(parts), { parts }) } /** @@ -1215,27 +1088,17 @@ export interface TemplateLiteralParser exte Annotations.Annotations > { + readonly "~rebuild.out": this readonly parts: Parts } -class TemplateLiteralParser$ extends make$> - implements TemplateLiteralParser -{ - readonly parts: Parts - - constructor(ast: AST.TupleType, parts: Parts) { - super(ast, (ast) => new TemplateLiteralParser$(ast, parts)) - this.parts = parts - } -} - /** * @since 4.0.0 */ export function TemplateLiteralParser( parts: Parts ): TemplateLiteralParser { - return new TemplateLiteralParser$(templateLiteralFromParts(parts).asTemplateLiteralParser(), [...parts] as Parts) + return makeProto(templateLiteralFromParts(parts).asTemplateLiteralParser(), { parts: [...parts] }) } /** @@ -1248,27 +1111,17 @@ export interface Enums readonly enums: A } -class Enums$ extends make$> implements Enums { - declare readonly "~rebuild.out": this - readonly enums: A - - constructor(ast: AST.Enums, enums: A) { - super(ast, (ast) => new Enums$(ast, enums)) - this.enums = enums - } -} - /** * @since 4.0.0 */ export function Enums(enums: A): Enums { - return new Enums$( + return makeProto( new AST.Enums( Object.keys(enums).filter( (key) => typeof enums[enums[key]] !== "number" ).map((key) => [key, enums[key]]) ), - enums + { enums } ) } @@ -1612,30 +1465,27 @@ export interface Struct extends ): Struct>> } -class Struct$ extends make$> implements Struct { - declare readonly "~rebuild.out": this - readonly fields: Fields - constructor(ast: AST.TypeLiteral, fields: Fields) { - super(ast, (ast) => new Struct$(ast, fields)) - // clone to avoid accidental external mutation - this.fields = { ...fields } - } - mapFields( - f: (fields: Fields) => To, - options?: { - readonly preserveChecks?: boolean | undefined - } | undefined - ): Struct { - const fields = f(this.fields) - return new Struct$(AST.struct(fields, options?.preserveChecks ? this.ast.checks : undefined), fields) - } +function makeStruct(ast: AST.TypeLiteral, fields: Fields): Struct { + return makeProto(ast, { + fields, + mapFields( + this: Struct, + f: (fields: Fields) => To, + options?: { + readonly preserveChecks?: boolean | undefined + } | undefined + ): Struct { + const fields = f(this.fields) + return makeStruct(AST.struct(fields, options?.preserveChecks ? this.ast.checks : undefined), fields) + } + }) } /** * @since 4.0.0 */ export function Struct(fields: Fields): Struct { - return new Struct$(AST.struct(fields, undefined), fields) + return makeStruct(AST.struct(fields, undefined), fields) } /** @@ -1816,20 +1666,6 @@ export interface Record$ extends readonly value: Value } -class Record$$ extends make$> - implements Record$ -{ - declare readonly "~rebuild.out": this - readonly key: Key - readonly value: Value - - constructor(ast: AST.TypeLiteral, key: Key, value: Value) { - super(ast, (ast) => new Record$$(ast, key, value)) - this.key = key - this.value = value - } -} - /** * @since 4.0.0 */ @@ -1846,7 +1682,7 @@ export function Record( const keyValueCombiner = options?.keyValueCombiner?.decode || options?.keyValueCombiner?.encode ? new AST.KeyValueCombiner(options.keyValueCombiner.decode, options.keyValueCombiner.encode) : undefined - return new Record$$(AST.record(key.ast, value.ast, keyValueCombiner), key, value) + return makeProto(AST.record(key.ast, value.ast, keyValueCombiner), { key, value }) } /** @@ -1934,22 +1770,6 @@ export interface StructWithRest< readonly records: Records } -class StructWithRest$$ - extends make$> - implements StructWithRest -{ - declare readonly "~rebuild.out": this - readonly schema: S - readonly records: Records - - constructor(ast: AST.TypeLiteral, schema: S, records: Records) { - super(ast, (ast) => new StructWithRest$$(ast, this.schema, this.records)) - this.schema = schema - // clone to avoid accidental external mutation - this.records = [...records] as any - } -} - /** * @since 4.0.0 */ @@ -1958,9 +1778,9 @@ export function StructWithRest< const Records extends StructWithRest.Records >( schema: S, - rest: Records + records: Records ): StructWithRest { - return new StructWithRest$$(AST.structWithRest(schema.ast, rest.map(AST.getAST)), schema, rest) + return makeProto(AST.structWithRest(schema.ast, records.map(AST.getAST)), { schema, records }) } /** @@ -2079,24 +1899,20 @@ export interface Tuple extends ): Tuple>> } -class Tuple$ extends make$> implements Tuple { - declare readonly "~rebuild.out": this - readonly elements: Elements - constructor(ast: AST.TupleType, elements: Elements) { - super(ast, (ast) => new Tuple$(ast, elements)) - // clone to avoid accidental external mutation - this.elements = [...elements] as any - } - - mapElements( - f: (elements: Elements) => To, - options?: { - readonly preserveChecks?: boolean | undefined - } | undefined - ): Tuple>> { - const elements = f(this.elements) - return new Tuple$(AST.tuple(elements, options?.preserveChecks ? this.ast.checks : undefined), elements) - } +function makeTuple(ast: AST.TupleType, elements: Elements): Tuple { + return makeProto(ast, { + elements, + mapElements( + this: Tuple, + f: (elements: Elements) => To, + options?: { + readonly preserveChecks?: boolean | undefined + } | undefined + ): Tuple>> { + const elements = f(this.elements) + return makeTuple(AST.tuple(elements, options?.preserveChecks ? this.ast.checks : undefined), elements) + } + }) } /** @@ -2104,7 +1920,7 @@ class Tuple$ extends make$> imp * @since 4.0.0 */ export function Tuple>(elements: Elements): Tuple { - return new Tuple$(AST.tuple(elements), elements) + return makeTuple(AST.tuple(elements), elements) } /** @@ -2196,20 +2012,6 @@ export interface TupleWithRest< readonly rest: Rest } -class TupleWithRest$ | mutable>, Rest extends TupleWithRest.Rest> - extends make$> -{ - readonly schema: S - readonly rest: Rest - - constructor(ast: AST.TupleType, schema: S, rest: Rest) { - super(ast, (ast) => new TupleWithRest$(ast, this.schema, this.rest)) - this.schema = schema - // clone to avoid accidental external mutation - this.rest = [...rest] - } -} - /** * @category Constructors * @since 4.0.0 @@ -2217,11 +2019,8 @@ class TupleWithRest$ | mutable | mutable>, const Rest extends TupleWithRest.Rest ->( - schema: S, - rest: Rest -): TupleWithRest { - return new TupleWithRest$(AST.tupleWithRest(schema.ast, rest.map(AST.getAST)), schema, rest) +>(schema: S, rest: Rest): TupleWithRest { + return makeProto(AST.tupleWithRest(schema.ast, rest.map(AST.getAST)), { schema, rest }) } /** @@ -2253,11 +2052,8 @@ interface ArrayLambda extends Lambda { * @category Constructors * @since 4.0.0 */ -export const Array = lambda(function Array(item: S): Array$ { - return new makeWithSchema$>( - new AST.TupleType(false, [], [item.ast]), - item - ) +export const Array = lambda(function Array(schema: S): Array$ { + return makeProto(new AST.TupleType(false, [], [schema.ast]), { schema }) }) /** @@ -2290,11 +2086,8 @@ interface NonEmptyArrayLambda extends Lambda { * @since 4.0.0 */ export const NonEmptyArray = lambda( - function NonEmptyArray(item: S): NonEmptyArray { - return new makeWithSchema$>( - new AST.TupleType(false, [item.ast], [item.ast]), - item - ) + function NonEmptyArray(schema: S): NonEmptyArray { + return makeProto(new AST.TupleType(false, [schema.ast], [schema.ast]), { schema }) } ) @@ -2351,8 +2144,8 @@ interface mutableLambda extends Lambda { /** * @since 4.0.0 */ -export const mutable = lambda(function mutable(self: S): mutable { - return new makeWithSchema$>(AST.mutable(self.ast), self) +export const mutable = lambda(function mutable(schema: S): mutable { + return makeProto(AST.mutable(schema.ast), { schema }) }) /** @@ -2366,7 +2159,6 @@ export interface readonly$ extends S["EncodingServices"], S["ast"], readonly$, - // we keep "~annotate.in", "~type.make" and "~type.make.in" as they are because they are contravariant S["~annotate.in"], S["~type.make.in"], S["Iso"], @@ -2390,8 +2182,8 @@ interface readonlyLambda extends Lambda { /** * @since 4.0.0 */ -export const readonly = lambda(function readonly(self: S): readonly$ { - return new makeWithSchema$>(AST.mutable(self.ast), self) +export const readonly = lambda(function readonly(schema: S): readonly$ { + return makeProto(AST.readonly(schema.ast), { schema }) }) /** @@ -2428,29 +2220,26 @@ export interface Union> extends ): Union>> } -class Union$> extends make$> implements Union { - declare readonly "~rebuild.out": this - override readonly ast: AST.UnionType - readonly members: Members - - constructor(ast: AST.UnionType, members: Members) { - super(ast, (ast) => new Union$(ast, members)) - this.ast = ast - this.members = members - } - - mapMembers>( - f: (members: Members) => To, - options?: { - readonly preserveChecks?: boolean | undefined - } | undefined - ): Union>> { - const members = f(this.members) - return new Union$( - AST.union(members, this.ast.mode, options?.preserveChecks ? this.ast.checks : undefined), - members - ) - } +function makeUnion>( + ast: AST.UnionType, + members: Members +): Union { + return makeProto(ast, { + members, + mapMembers>( + this: Union, + f: (members: Members) => To, + options?: { + readonly preserveChecks?: boolean | undefined + } | undefined + ): Union>> { + const members = f(this.members) + return makeUnion( + AST.union(members, this.ast.mode, options?.preserveChecks ? this.ast.checks : undefined), + members + ) + } + }) } /** @@ -2468,7 +2257,7 @@ export function Union>( members: Members, options?: { mode?: "anyOf" | "oneOf" } ): Union { - return new Union$(AST.union(members, options?.mode ?? "anyOf", undefined), members) + return makeUnion(AST.union(members, options?.mode ?? "anyOf", undefined), members) } /** @@ -2496,30 +2285,6 @@ export interface Literals> extends pick>(literals: L2): Literals } -class Literals$> extends make$> implements Literals { - declare readonly "~rebuild.out": this - readonly literals: L - readonly members: { readonly [K in keyof L]: Literal } - - constructor( - ast: AST.UnionType, - literals: L, - members: { readonly [K in keyof L]: Literal } - ) { - super(ast, (ast) => new Literals$(ast, literals, members)) - this.literals = literals - this.members = members - } - - mapMembers>(f: (members: this["members"]) => To): Union>> { - return Union(f(this.members)) - } - - pick>(literals: L2): Literals { - return Literals(literals) - } -} - /** * @see {@link Literal} for a schema that represents a single literal. * @category Constructors @@ -2527,7 +2292,19 @@ class Literals$> extends make$> */ export function Literals>(literals: L): Literals { const members = literals.map(Literal) as { readonly [K in keyof L]: Literal } - return new Literals$(AST.union(members, "anyOf", undefined), [...literals] as L, members) + return makeProto(AST.union(members, "anyOf", undefined), { + literals, + members, + mapMembers>( + this: Literals, + f: (members: Literals["members"]) => To + ): Union>> { + return Union(f(this.members)) + }, + pick>(literals: L2): Literals { + return Literals(literals) + } + }) } /** @@ -2645,7 +2422,7 @@ export interface refine extends S["DecodingServices"], S["EncodingServices"], S["ast"], - refine, + refine, Annotations.Bottom, S["~type.make.in"], T, @@ -2656,7 +2433,9 @@ export interface refine extends S["~encoded.mutability"], S["~encoded.optionality"] > -{} +{ + readonly "~rebuild.out": this +} /** * @category Filtering @@ -2727,11 +2506,10 @@ export function decodingMiddleware( options: AST.ParseOptions ) => Effect.Effect, Issue.Issue, RD> ) { - return (self: S): decodingMiddleware => { - return new makeWithSchema$>( - AST.decodingMiddleware(self.ast, new Transformation.Middleware(decode, identity)), - self - ) + return (schema: S): decodingMiddleware => { + return makeProto(AST.decodingMiddleware(schema.ast, new Transformation.Middleware(decode, identity)), { + schema + }) } } @@ -2770,11 +2548,8 @@ export function encodingMiddleware( options: AST.ParseOptions ) => Effect.Effect, Issue.Issue, RE> ) { - return (self: S): encodingMiddleware => { - return new makeWithSchema$>( - AST.encodingMiddleware(self.ast, new Transformation.Middleware(identity, encode)), - self - ) + return (schema: S): encodingMiddleware => { + return makeProto(AST.encodingMiddleware(schema.ast, new Transformation.Middleware(identity, encode)), { schema }) } } @@ -2850,26 +2625,6 @@ export interface decodeTo extends decodeTo {} -class decodeTo$ extends make$> - implements decodeTo -{ - declare readonly "~rebuild.out": this - override readonly ast: From["ast"] - readonly from: From - readonly to: To - - constructor( - ast: From["ast"], - from: From, - to: To - ) { - super(ast, (ast) => new decodeTo$(ast, from, to)) - this.ast = ast - this.from = from - this.to = to - } -} - /** * @since 4.0.0 */ @@ -2889,14 +2644,16 @@ export function decodeTo { - return new decodeTo$( + return makeProto( AST.decodeTo( from.ast, to.ast, transformation ? Transformation.make(transformation) : Transformation.passthrough() ), - from, - to + { + from, + to + } ) } } @@ -2953,25 +2710,31 @@ export function encode(transformation: { /** * @since 4.0.0 */ -export interface withConstructorDefault - extends - Bottom< - S["Type"], - S["Encoded"], - S["DecodingServices"], - S["EncodingServices"], - S["ast"], - withConstructorDefault, - S["~annotate.in"], - S["~type.make.in"], - S["Iso"], - S["~type.make"], - S["~type.mutability"], - S["~type.optionality"], - "with-default", - S["~encoded.mutability"], - S["~encoded.optionality"] - > +export interface WithoutConstructorDefault { + readonly "~type.constructor.default": "no-default" +} + +/** + * @since 4.0.0 + */ +export interface withConstructorDefault extends + Bottom< + S["Type"], + S["Encoded"], + S["DecodingServices"], + S["EncodingServices"], + S["ast"], + withConstructorDefault, + S["~annotate.in"], + S["~type.make.in"], + S["Iso"], + S["~type.make"], + S["~type.mutability"], + S["~type.optionality"], + "with-default", + S["~encoded.mutability"], + S["~encoded.optionality"] + > { readonly "~rebuild.out": this readonly schema: S @@ -2980,15 +2743,15 @@ export interface withConstructorDefault( +export function withConstructorDefault( defaultValue: ( input: O.Option // `S["~type.make.in"]` instead of `S["Type"]` is intentional here because // it makes easier to define the default value if there are nested defaults ) => O.Option | Effect.Effect> ) { - return (self: S): withConstructorDefault => { - return new makeWithSchema$>(AST.withConstructorDefault(self.ast, defaultValue), self) + return (schema: S): withConstructorDefault => { + return makeProto(AST.withConstructorDefault(schema.ast, defaultValue), { schema }) } } @@ -3260,50 +3023,6 @@ export interface TaggedUnion> extends } } -class TaggedUnion$> extends make$> implements TaggedUnion { - declare readonly "~rebuild.out": this - override readonly ast: AST.UnionType - readonly cases: Cases - readonly isAnyOf: ( - keys: ReadonlyArray - ) => (value: Cases[keyof Cases]["Type"]) => value is Extract - readonly guards: { [K in keyof Cases]: (u: unknown) => u is Cases[K]["Type"] } - readonly match: { - ( - value: Cases[keyof Cases]["Type"], - cases: { [K in keyof Cases]: (value: Cases[K]["Type"]) => Output } - ): Output - ( - cases: { [K in keyof Cases]: (value: Cases[K]["Type"]) => Output } - ): (value: Cases[keyof Cases]["Type"]) => Output - } - - constructor( - ast: AST.UnionType, - cases: Cases, - isAnyOf: ( - keys: ReadonlyArray - ) => (value: Cases[keyof Cases]["Type"]) => value is Extract, - guards: { [K in keyof Cases]: (u: unknown) => u is Cases[K]["Type"] }, - match: { - ( - value: Cases[keyof Cases]["Type"], - cases: { [K in keyof Cases]: (value: Cases[K]["Type"]) => Output } - ): Output - ( - cases: { [K in keyof Cases]: (value: Cases[K]["Type"]) => Output } - ): (value: Cases[keyof Cases]["Type"]) => Output - } - ) { - super(ast, (ast) => new TaggedUnion$(ast, cases, isAnyOf, guards, match)) - this.ast = ast - this.cases = cases - this.isAnyOf = isAnyOf - this.guards = guards - this.match = match - } -} - /** * @since 4.0.0 * @experimental @@ -3318,7 +3037,7 @@ export function TaggedUnion extends S["~encoded.optionality"] > { + // intentionally left without `readonly "~rebuild.out": this` new(_: never): S["Type"] & Brand } @@ -4485,6 +4205,7 @@ export interface Class { + // intentionally left without `readonly "~rebuild.out": this` new(props: S["~type.make.in"], options?: MakeOptions): S["Type"] & Inherited readonly identifier: string readonly fields: S["fields"] @@ -4586,7 +4307,7 @@ function makeClass< ) => Class>>, Self> { return (newFields, annotations) => { const fields = { ...schema.fields, ...newFields } - const struct: any = new Struct$(AST.struct(fields, schema.ast.checks), fields) + const struct: any = makeStruct(AST.struct(fields, schema.ast.checks), fields) return makeClass(this, identifier, struct, annotations) } } diff --git a/packages/effect/src/schema/Serializer.ts b/packages/effect/src/schema/Serializer.ts index b26df05fe0..848b48c2cb 100644 --- a/packages/effect/src/schema/Serializer.ts +++ b/packages/effect/src/schema/Serializer.ts @@ -227,7 +227,7 @@ export function ensureArray( return Schema.make>(goEnsureArray(codec.ast)) } -const ENSURE_ARRAY_FLAG = "~effect/schema/Serializer/ensureArray" +const ENSURE_ARRAY_ANNOTATION_KEY = "~effect/schema/Serializer/ensureArray" /** @internal */ export const goEnsureArray = memoize((ast: AST.AST): AST.AST => { @@ -240,7 +240,7 @@ export const goEnsureArray = memoize((ast: AST.AST): AST.AST => { } return AST.replaceEncoding(ast, AST.replaceLastLink(links, new AST.Link(to, last.transformation))) } - if (AST.isUnionType(ast) && ast.annotations?.[ENSURE_ARRAY_FLAG]) { + if (AST.isUnionType(ast) && ast.annotations?.[ENSURE_ARRAY_ANNOTATION_KEY]) { return ast } const out: AST.AST = (ast as any).go?.(goEnsureArray) ?? ast @@ -258,7 +258,7 @@ export const goEnsureArray = memoize((ast: AST.AST): AST.AST => { ) ], "anyOf", - { [ENSURE_ARRAY_FLAG]: true } + { [ENSURE_ARRAY_ANNOTATION_KEY]: true } ) return out.context?.isOptional ? AST.optionalKey(ensure) : ensure } diff --git a/packages/effect/src/schema/ToArbitrary.ts b/packages/effect/src/schema/ToArbitrary.ts index 5d87ae697b..5b0578de02 100644 --- a/packages/effect/src/schema/ToArbitrary.ts +++ b/packages/effect/src/schema/ToArbitrary.ts @@ -143,7 +143,7 @@ export function make(schema: Schema.Schema): FastCheck.Arbitrary { const arbitraryMemoMap = new WeakMap>() -function getArbitraryAnnotation( +function getAnnotation( annotations: Annotations.Annotations | undefined ): | Annotation.Declaration> @@ -265,16 +265,16 @@ function resetContext(ctx: Context | undefined): Context | undefined { } const go = memoize((ast: AST.AST): LazyArbitrary => { - // --------------------------------------------- - // handle annotations - // --------------------------------------------- if (ast.checks) { const filters = AST.getFilters(ast.checks) const f = mergeFiltersConstraints(filters) const out = go(AST.replaceChecks(ast, undefined)) return (fc, ctx) => applyChecks(ast, filters, out(fc, f(ctx))) } - const annotation = getArbitraryAnnotation(ast.annotations) + // --------------------------------------------- + // handle annotations + // --------------------------------------------- + const annotation = getAnnotation(ast.annotations) if (annotation) { switch (annotation._tag) { case "Declaration": { diff --git a/packages/effect/src/schema/ToEquivalence.ts b/packages/effect/src/schema/ToEquivalence.ts index 68a063bb64..7f5aac2a23 100644 --- a/packages/effect/src/schema/ToEquivalence.ts +++ b/packages/effect/src/schema/ToEquivalence.ts @@ -49,13 +49,10 @@ export function override(override: () => Equivalence.Equiv } } -function getEquivalenceAnnotation( - annotations: Annotations.Annotations | undefined -): Annotation.Declaration> | Annotation.Override | undefined { - return annotations?.equivalence as any -} - -const getAnnotation = Annotations.getAnnotation(getEquivalenceAnnotation) +const getAnnotation = Annotations.getAt( + "equivalence", + (u: unknown): u is Annotation.Declaration> | Annotation.Override => Predicate.isObject(u) +) const go = memoize((ast: AST.AST): Equivalence.Equivalence => { // --------------------------------------------- diff --git a/packages/effect/src/schema/ToFormat.ts b/packages/effect/src/schema/ToFormat.ts index 24b80acaee..2014e6b566 100644 --- a/packages/effect/src/schema/ToFormat.ts +++ b/packages/effect/src/schema/ToFormat.ts @@ -3,6 +3,7 @@ */ import type { Format } from "../data/Format.ts" import * as Option from "../data/Option.ts" +import * as Predicate from "../data/Predicate.ts" import { memoize } from "../Function.ts" import { format, formatPropertyKey } from "../interfaces/Inspectable.ts" import * as Annotations from "./Annotations.ts" @@ -42,13 +43,10 @@ export function override(override: () => Format } } -function getFormatAnnotation( - annotations: Annotations.Annotations | undefined -): Annotation.Declaration> | Annotation.Override | undefined { - return annotations?.format as any -} - -const getAnnotation = Annotations.getAnnotation(getFormatAnnotation) +const getAnnotation = Annotations.getAt( + "format", + (u: unknown): u is Annotation.Declaration> | Annotation.Override => Predicate.isObject(u) +) const defaultFormat = () => format diff --git a/packages/effect/src/schema/ToJsonSchema.ts b/packages/effect/src/schema/ToJsonSchema.ts index fc29f6b402..858015ff1d 100644 --- a/packages/effect/src/schema/ToJsonSchema.ts +++ b/packages/effect/src/schema/ToJsonSchema.ts @@ -316,7 +316,7 @@ type GoOptions = { } function getId(ast: AST.AST): string | undefined { - const id = Annotations.getIdentifierAnnotation(ast) + const id = Annotations.getIdentifier(ast) if (id !== undefined) return id if (AST.isSuspend(ast)) { return getId(ast.thunk()) diff --git a/packages/effect/src/schema/ToParser.ts b/packages/effect/src/schema/ToParser.ts index a81c84bebe..ba0f92c037 100644 --- a/packages/effect/src/schema/ToParser.ts +++ b/packages/effect/src/schema/ToParser.ts @@ -9,6 +9,7 @@ import * as Option from "../data/Option.ts" import * as Effect from "../Effect.ts" import * as Exit from "../Exit.ts" import { memoize } from "../Function.ts" +import * as Annotations from "./Annotations.ts" import * as AST from "./AST.ts" import * as Issue from "./Issue.ts" import type * as Schema from "./Schema.ts" @@ -356,7 +357,7 @@ const go = memoize( sroa = Effect.catchEager(sroa, (issue) => { const issues: Array = [] AST.collectIssues( - checks.filter((check) => check.annotations?.["~structural"]), + checks.filter((check) => check.annotations?.[Annotations.STRUCTURAL_ANNOTATION_KEY]), ou.value, issues, ast, diff --git a/packages/effect/src/unstable/ai/McpSchema.ts b/packages/effect/src/unstable/ai/McpSchema.ts index 97720b1b23..0b47e1696b 100644 --- a/packages/effect/src/unstable/ai/McpSchema.ts +++ b/packages/effect/src/unstable/ai/McpSchema.ts @@ -2,6 +2,7 @@ * @since 4.0.0 */ import * as Option from "../../data/Option.ts" +import * as Predicate from "../../data/Predicate.ts" import type * as Effect from "../../Effect.ts" import { constFalse, constTrue } from "../../Function.ts" import * as Check from "../../schema/Check.ts" @@ -18,14 +19,14 @@ import * as RpcMiddleware from "../rpc/RpcMiddleware.ts" /** * @since 4.0.0 */ -export interface optionalWithDefault +export interface optionalWithDefault extends Schema.withConstructorDefault>, Schema.optionalKey>> {} /** * @since 4.0.0 */ -export const optionalWithDefault = ( +export const optionalWithDefault = ( schema: S, defaultValue: () => Schema.optionalKey["Type"] ): optionalWithDefault => @@ -2027,11 +2028,15 @@ export type FromClientEncoded = ClientRequestEncoded | ClientNotificationEncoded */ export type FromServerEncoded = ServerResultEncoded | ServerNotificationEncoded +const ParamSchemaTypeId = "~effect/ai/McpSchema/ParamSchema" + /** * @since 4.0.0 * @category Parameters */ -export const ParamAnnotation: unique symbol = Symbol.for("effect/ai/McpSchema/ParamNameId") +export function isParam(schema: Schema.Top): schema is Param { + return Predicate.hasProperty(schema, ParamSchemaTypeId) +} /** * @since 4.0.0 @@ -2044,7 +2049,7 @@ export interface Param extends S["DecodingServices"], S["EncodingServices"], S["ast"], - S["~rebuild.out"], + Param, S["~annotate.in"], S["~type.make.in"], S["Iso"], @@ -2056,10 +2061,10 @@ export interface Param extends S["~encoded.optionality"] > { - readonly "~effect/ai/McpSchema/Param": { - readonly name: Name - readonly schema: S - } + readonly "~rebuild.out": this + readonly [ParamSchemaTypeId]: typeof ParamSchemaTypeId + readonly name: Name + readonly schema: S } /** @@ -2068,5 +2073,9 @@ export interface Param extends * @since 4.0.0 * @category Parameters */ -export const param = (id: Id, schema: S): Param => - schema.annotate({ mcpServerParam: id }) as any +export function param( + name: Name, + schema: S +): Param { + return Schema.makeProto(schema.ast, { [ParamSchemaTypeId]: ParamSchemaTypeId, name, schema }) +} diff --git a/packages/effect/src/unstable/ai/McpServer.ts b/packages/effect/src/unstable/ai/McpServer.ts index 43d70012ae..e479d0aca1 100644 --- a/packages/effect/src/unstable/ai/McpServer.ts +++ b/packages/effect/src/unstable/ai/McpServer.ts @@ -9,6 +9,7 @@ import * as Exit from "../../Exit.ts" import * as Layer from "../../Layer.ts" import * as Queue from "../../Queue.ts" import * as RcMap from "../../RcMap.ts" +import * as SchemaAnnotations from "../../schema/Annotations.ts" import * as AST from "../../schema/AST.ts" import * as Schema from "../../schema/Schema.ts" import * as Serializer from "../../schema/Serializer.ts" @@ -38,6 +39,7 @@ import { GetPromptResult, InternalError, InvalidParams, + isParam, ListPromptsResult, ListResourcesResult, ListResourceTemplatesResult, @@ -868,8 +870,8 @@ export const registerPrompt = < for (const [name, prop] of Object.entries(props)) { args.push({ name, - description: prop.ast.annotations?.description as string, - required: prop.ast.context?.isOptional !== true + description: SchemaAnnotations.getDescription(prop.ast), + required: !AST.isOptional(prop.ast) }) } const prompt = new Prompt({ @@ -1030,8 +1032,8 @@ const compileUriTemplate = (segments: TemplateStringsArray, ...schemas: Readonly const key = String(i) arr.push(schema) routerPath += `:${key}${segment.replace(":", "::")}` - const paramName = schema.ast.annotations?.mcpServerParam ?? `param${key}` - params[paramName as string] = schema + const paramName = isParam(schema) ? schema.name : `param${key}` + params[paramName] = schema uriPath += `{${paramName}}${segment}` } pathSchema = Schema.Tuple(arr) diff --git a/packages/effect/src/unstable/cluster/Snowflake.ts b/packages/effect/src/unstable/cluster/Snowflake.ts index 6c43b69f13..88cbba0593 100644 --- a/packages/effect/src/unstable/cluster/Snowflake.ts +++ b/packages/effect/src/unstable/cluster/Snowflake.ts @@ -58,9 +58,7 @@ export declare namespace Snowflake { */ export interface SnowflakeFromBigInt extends Schema.refine, Schema.BigInt> -{ - readonly "~rebuild.out": SnowflakeFromBigInt -} +{} /** * @since 4.0.0 diff --git a/packages/effect/src/unstable/httpapi/HttpApi.ts b/packages/effect/src/unstable/httpapi/HttpApi.ts index 3cfdd48bfa..427e981f2d 100644 --- a/packages/effect/src/unstable/httpapi/HttpApi.ts +++ b/packages/effect/src/unstable/httpapi/HttpApi.ts @@ -270,7 +270,7 @@ export const reflect = ( const emptyMap = new Map() function getDescriptionOrIdentifier(ast: AST.AST): string | undefined { - return Annotations.getDescriptionAnnotation(ast) ?? Annotations.getIdentifierAnnotation(ast) + return Annotations.getDescription(ast) ?? Annotations.getIdentifier(ast) } const extractMembers = ( @@ -286,14 +286,14 @@ const extractMembers = ( }>() function process(type: Schema.Top) { const status = getStatus(type.ast) - const isEmpty = type.ast.annotations?.httpApiIsEmpty + const isEmpty = HttpApiSchema.getHttpApiIsEmpty(type.ast) const current = members.get(status) members.set( status, { description: current?.description ?? getDescriptionOrIdentifier(type.ast), ast: UndefinedOr.map(current?.ast, (ast) => HttpApiSchema.UnionUnifyAST(ast, type.ast)) ?? - (!isEmpty && HttpApiSchema.isVoid(type.ast) ? undefined : type.ast) + (!isEmpty && HttpApiSchema.isVoidEncoded(type.ast) ? undefined : type.ast) } ) } @@ -319,7 +319,7 @@ const extractPayloads = (topAst: AST.AST): ReadonlyMap => { const endpoint = handler.endpoint const isMultipartStream = endpoint.payloadSchema?.pipe( - ({ ast }) => ast.annotations?.httpApiMultipartStream !== undefined - ) ?? constFalse + ({ ast }) => HttpApiSchema.getHttpApiMultipartStream(ast) !== undefined + ) ?? false const multipartLimits = endpoint.payloadSchema?.pipe( - ({ ast }) => ast.annotations?.httpApiMultipartStream ?? ast.annotations?.httpApiMultipart + ({ ast }) => HttpApiSchema.getHttpApiMultipartStream(ast) ?? HttpApiSchema.getHttpApiMultipart(ast) ) const decodePath = UndefinedOr.map(endpoint.pathSchema, Schema.decodeUnknownEffect) const decodePayload = handler.withFullRequest || isMultipartStream @@ -638,7 +638,7 @@ const responseTransformation = ( decode: decodeForbidden, encode(data: I) { const ast = schema.ast - const isEmpty = HttpApiSchema.isVoid(ast) + const isEmpty = HttpApiSchema.isVoidEncoded(ast) const status = getStatus(ast) if (isEmpty) { return Effect.succeed(Response.empty({ status })) diff --git a/packages/effect/src/unstable/httpapi/HttpApiSchema.ts b/packages/effect/src/unstable/httpapi/HttpApiSchema.ts index 979de62f4f..0549084a4a 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiSchema.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiSchema.ts @@ -20,50 +20,51 @@ declare module "../../schema/Annotations.ts" { readonly httpApiIsEmpty?: true | undefined readonly httpApiMultipart?: Multipart_.withLimits.Options | undefined readonly httpApiMultipartStream?: Multipart_.withLimits.Options | undefined - readonly httpApiParam?: { - readonly name: string - readonly schema: Schema.Top - } | undefined readonly httpApiStatus?: number | undefined } } -/** - * @since 4.0.0 - * @category reflection - */ -export const isVoid = (ast: AST.AST): boolean => { +function isEncoding(u: unknown): u is Encoding { + return Predicate.isObject(u) // TODO: Add more checks? +} + +function isMultipartWithLimitsOptions(u: unknown): u is Multipart_.withLimits.Options { + return Predicate.isObject(u) // TODO: Add more checks? +} + +/** @internal */ +export const getHttpApiIsEmpty = Annotations.getAt("httpApiIsEmpty", Predicate.isBoolean) +const getHttpApiEncoding = Annotations.getAt("httpApiEncoding", isEncoding) +/** @internal */ +export const getHttpApiMultipart = Annotations.getAt("httpApiMultipart", isMultipartWithLimitsOptions) +/** @internal */ +export const getHttpApiMultipartStream = Annotations.getAt("httpApiMultipartStream", isMultipartWithLimitsOptions) +const getHttpApiStatus = Annotations.getAt("httpApiStatus", Predicate.isNumber) + +/** @internal */ +export function isVoidEncoded(ast: AST.AST): boolean { ast = AST.encodedAST(ast) switch (ast._tag) { - case "VoidKeyword": { + case "VoidKeyword": return true - } - case "Suspend": { - return isVoid(ast.thunk()) - } - default: { + case "Suspend": + return isVoidEncoded(ast.thunk()) + default: return false - } } } -const getHttpApiStatusAnnotation = Annotations.getAnnotation((annotations) => { - const status = annotations?.httpApiStatus - if (Predicate.isNumber(status)) return status -}) +/** + * @since 4.0.0 + * @category reflection + */ +export const getStatusSuccess = (self: AST.AST): number => getHttpApiStatus(self) ?? (isVoidEncoded(self) ? 204 : 200) /** * @since 4.0.0 * @category reflection */ -export const getStatusSuccess = (self: AST.AST): number => - getHttpApiStatusAnnotation(self) ?? (isVoid(self) ? 204 : 200) - -/** - * @since 4.0.0 - * @category reflection - */ -export const getStatusError = (self: AST.AST): number => getHttpApiStatusAnnotation(self) ?? 500 +export const getStatusError = (self: AST.AST): number => getHttpApiStatus(self) ?? 500 function isHttpApiAnnotationKey(key: string): boolean { return key.startsWith("httpApi") @@ -78,7 +79,7 @@ export const getHttpApiAnnotations = (self: Annotations.Annotations | undefined) if (!self) return out for (const [key, value] of Object.entries(self)) { - if (isHttpApiAnnotationKey(key)) { + if (isHttpApiAnnotationKey(key) && value !== undefined) { out[key] = value } } @@ -123,13 +124,13 @@ function shouldExtractUnion(ast: AST.UnionType): boolean { if (ast.encoding) return false if ( ast.types.some((ast) => { - const annotations = Annotations.getAnnotations(ast) + const annotations = Annotations.get(ast) return annotations && Object.keys(annotations).some(isHttpApiAnnotationKey) }) ) { return true } - return Annotations.getAnnotations(ast) === undefined + return Annotations.get(ast) === undefined } /** @@ -151,7 +152,7 @@ export interface Param extends S["DecodingServices"], S["EncodingServices"], S["ast"], - S["~rebuild.out"], + Param, S["~annotate.in"], S["~type.make.in"], S["Iso"], @@ -163,36 +164,27 @@ export interface Param extends S["~encoded.optionality"] > { - readonly "~effect/httpapi/HttpApiSchema/Param": { - readonly name: Name - readonly schema: S - } + readonly "~rebuild.out": this + readonly name: Name + readonly schema: S } /** * @since 4.0.0 * @category path params */ -export const param: { - ( - name: Name - ): >( - schema: S - ) => Param - >( - name: Name, - schema: S - ): Param -} = function(name: string) { +export function param( + name: Name +): (schema: S) => Param +export function param( + name: Name, + schema: S +): Param +export function param(name: string): any { if (arguments.length === 1) { - return (schema: Schema.Top) => - schema.annotate({ - httpApiParam: { name, schema } - }) + return (schema: Schema.Top) => Schema.makeProto(schema.ast, { name, schema }) } - return arguments[1].annotate({ - httpApiParam: { name, schema: arguments[1] } - }) + return Schema.makeProto(arguments[1].ast, { name, schema: arguments[1] }) } /** @@ -290,31 +282,24 @@ export interface NoContent extends Schema.Void { */ export const NoContent: NoContent = Empty(204) as any -/** @internal */ -export type MultipartTypeId = "~effect/httpapi/HttpApiSchema/Multipart" +/** + * @since 4.0.0 + * @category multipart + */ +export const MultipartTypeId = "~effect/httpapi/HttpApiSchema/Multipart" /** * @since 4.0.0 * @category multipart */ -export interface Multipart extends - Schema.Bottom< - S["Type"] & Brand, - S["Encoded"], - S["DecodingServices"], - S["EncodingServices"], - S["ast"], - S["~rebuild.out"], - S["~annotate.in"], - S["~type.make.in"], - S["Iso"], - S["~type.make"], - S["~type.mutability"], - S["~type.optionality"], - S["~type.constructor.default"], - S["~encoded.mutability"], - S["~encoded.optionality"] - > +export type MultipartTypeId = typeof MultipartTypeId + +/** + * @since 4.0.0 + * @category multipart + */ +export interface Multipart + extends Schema.refine, S["~rebuild.out"]> {} /** @@ -328,35 +313,28 @@ export const Multipart = (self: S, options?: { readonly maxTotalSize?: FileSystem.SizeInput | undefined readonly fieldMimeTypes?: ReadonlyArray | undefined }): Multipart => - self.annotate({ + self.pipe(Schema.brand(MultipartTypeId, { httpApiMultipart: options ?? {} - }) as Multipart - -/** @internal */ -export type MultipartStreamTypeId = "~effect/httpapi/HttpApiSchema/MultipartStream" + })) /** * @since 4.0.0 * @category multipart */ -export interface MultipartStream extends - Schema.Bottom< - S["Type"] & Brand, - S["Encoded"], - S["DecodingServices"], - S["EncodingServices"], - S["ast"], - S["~rebuild.out"], - S["~annotate.in"], - S["~type.make.in"], - S["Iso"], - S["~type.make"], - S["~type.mutability"], - S["~type.optionality"], - S["~type.constructor.default"], - S["~encoded.mutability"], - S["~encoded.optionality"] - > +export const MultipartStreamTypeId = "~effect/httpapi/HttpApiSchema/MultipartStream" + +/** + * @since 4.0.0 + * @category multipart + */ +export type MultipartStreamTypeId = typeof MultipartStreamTypeId + +/** + * @since 4.0.0 + * @category multipart + */ +export interface MultipartStream + extends Schema.refine, S["~rebuild.out"]> {} /** @@ -370,9 +348,9 @@ export const MultipartStream = (self: S, options?: { readonly maxTotalSize?: FileSystem.SizeInput | undefined readonly fieldMimeTypes?: ReadonlyArray | undefined }): MultipartStream => - self.annotate({ + self.pipe(Schema.brand(MultipartStreamTypeId, { httpApiMultipartStream: options ?? {} - }) as MultipartStream + })) /** * @since 4.0.0 @@ -467,8 +445,9 @@ const encodingJson: Encoding = { * @since 4.0.0 * @category annotations */ -export const getEncoding = (ast: AST.AST, fallback = encodingJson): Encoding => - ast.annotations?.httpApiEncoding ?? fallback +export function getEncoding(ast: AST.AST, fallback = encodingJson): Encoding { + return getHttpApiEncoding(ast) ?? fallback +} /** * @since 4.0.0 @@ -538,7 +517,7 @@ export interface EmptyErrorClass extends never, never, AST.Declaration, - EmptyErrorClass, + EmptyErrorClass, // TODO: Fix this Annotations.Annotations > { diff --git a/packages/effect/src/unstable/httpapi/OpenApi.ts b/packages/effect/src/unstable/httpapi/OpenApi.ts index d2edc30eaa..ca105d01f9 100644 --- a/packages/effect/src/unstable/httpapi/OpenApi.ts +++ b/packages/effect/src/unstable/httpapi/OpenApi.ts @@ -323,7 +323,7 @@ export const fromApi = ( op.responses[status] = { description: description ?? defaultDescription() } - if (ast && !ast.annotations?.httpApiIsEmpty) { + if (ast && !HttpApiSchema.getHttpApiIsEmpty(ast)) { const encoding = HttpApiSchema.getEncoding(ast) op.responses[status].content = { [encoding.contentType]: { diff --git a/packages/effect/src/unstable/rpc/Rpc.ts b/packages/effect/src/unstable/rpc/Rpc.ts index e54db342b5..869d4f50dc 100644 --- a/packages/effect/src/unstable/rpc/Rpc.ts +++ b/packages/effect/src/unstable/rpc/Rpc.ts @@ -728,10 +728,7 @@ export const make = < _tag: tag, payloadSchema, successSchema: options?.stream ? - RpcSchema.Stream({ - success: successSchema, - error: errorSchema - }) : + RpcSchema.Stream(successSchema, errorSchema) : successSchema, errorSchema: options?.stream ? Schema.Never : errorSchema, annotations: ServiceMap.empty(), @@ -757,7 +754,7 @@ export const exitSchema = ( } const rpc = self as any as AnyWithProps const failures = new Set([rpc.errorSchema]) - const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema.ast) + const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema) if (streamSchemas) { failures.add(streamSchemas.error) } diff --git a/packages/effect/src/unstable/rpc/RpcClient.ts b/packages/effect/src/unstable/rpc/RpcClient.ts index a2a4717b7a..f37cf8f16d 100644 --- a/packages/effect/src/unstable/rpc/RpcClient.ts +++ b/packages/effect/src/unstable/rpc/RpcClient.ts @@ -772,7 +772,7 @@ const rpcSchemas = (rpc: Rpc.AnyWithProps) => { if (rpcSchemasCache.has(rpc)) { return rpcSchemasCache.get(rpc)! } - const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema.ast) + const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema) const entry: RpcSchemas = { decodeChunk: streamSchemas ? Schema.decodeUnknownEffect(Serializer.json(Schema.NonEmptyArray(streamSchemas.success))) : diff --git a/packages/effect/src/unstable/rpc/RpcSchema.ts b/packages/effect/src/unstable/rpc/RpcSchema.ts index 2d5d94700e..ef3a0c3d2d 100644 --- a/packages/effect/src/unstable/rpc/RpcSchema.ts +++ b/packages/effect/src/unstable/rpc/RpcSchema.ts @@ -1,35 +1,33 @@ /** * @since 4.0.0 */ -import type { Annotations } from "../../schema/Annotations.ts" +import * as Predicate from "../../data/Predicate.ts" +import type * as Annotations from "../../schema/Annotations.ts" import type * as AST from "../../schema/AST.ts" import * as Schema from "../../schema/Schema.ts" import * as Stream_ from "../../stream/Stream.ts" -/** - * @since 4.0.0 - * @category Stream - */ -export const StreamSchemaTypeId = "~effect/rpc/RpcSchema/StreamSchema" +const StreamSchemaTypeId = "~effect/rpc/RpcSchema/StreamSchema" /** * @since 4.0.0 * @category Stream */ -export const isStreamSchema = (schema: Schema.Top): schema is Stream => - schema.ast.annotations !== undefined && StreamSchemaTypeId in schema.ast.annotations +export function isStreamSchema(schema: Schema.Top): schema is Stream { + return Predicate.hasProperty(schema, StreamSchemaTypeId) +} -/** - * @since 4.0.0 - * @category Stream - */ -export function getStreamSchemas( - ast: AST.AST -): { +/** @internal */ +export function getStreamSchemas(schema: Schema.Top): { readonly success: Schema.Top readonly error: Schema.Top } | undefined { - return ast.annotations?.[StreamSchemaTypeId] as any + return isStreamSchema(schema) ? + { + success: schema.success, + error: schema.error + } : + undefined } /** @@ -42,28 +40,23 @@ export interface Stream extends Stream_.Stream, A["DecodingServices"] | E["DecodingServices"], A["EncodingServices"] | E["EncodingServices"], - AST.AST, + AST.Declaration, Stream, - Annotations + Annotations.Declaration, readonly []> > { + readonly "~rebuild.out": this + readonly [StreamSchemaTypeId]: typeof StreamSchemaTypeId readonly success: A readonly error: E } +const schema = Schema.declare(Stream_.isStream) + /** * @since 4.0.0 * @category Stream */ -export const Stream = ( - options: { - readonly error: E - readonly success: A - } -): Stream => { - const schema = Schema.declare(Stream_.isStream, { [StreamSchemaTypeId]: options }) - return Object.assign( - schema, - options - ) as any as Stream +export function Stream(success: A, error: E): Stream { + return Schema.makeProto(schema.ast, { [StreamSchemaTypeId]: StreamSchemaTypeId, success, error }) } diff --git a/packages/effect/src/unstable/rpc/RpcServer.ts b/packages/effect/src/unstable/rpc/RpcServer.ts index b84abaca41..3d472062f7 100644 --- a/packages/effect/src/unstable/rpc/RpcServer.ts +++ b/packages/effect/src/unstable/rpc/RpcServer.ts @@ -492,7 +492,7 @@ export const make: ( let schemas = schemasCache.get(rpc) if (!schemas) { const entry = services.mapUnsafe.get(rpc.key) as Rpc.Handler - const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema.ast) + const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema) schemas = { decode: Schema.decodeUnknownEffect(Serializer.json(rpc.payloadSchema as any)), encodeChunk: Schema.encodeUnknownEffect( diff --git a/packages/effect/src/unstable/schema/VariantSchema.ts b/packages/effect/src/unstable/schema/VariantSchema.ts index cafb3c0284..8c1911a7dc 100644 --- a/packages/effect/src/unstable/schema/VariantSchema.ts +++ b/packages/effect/src/unstable/schema/VariantSchema.ts @@ -217,7 +217,7 @@ export interface Class< S["DecodingServices"], S["EncodingServices"], AST.Declaration, - Class, + Schema.decodeTo, S>, Annotations.Declaration, S["~type.make.in"], S["Iso"], @@ -460,35 +460,23 @@ export const Override = (value: A): A & Brand<"Override"> => value as any * @since 4.0.0 * @category overrideable */ -export interface Overrideable extends - Schema.Bottom< - S["Type"] & Brand<"Override">, - S["Encoded"], - S["DecodingServices"], - S["EncodingServices"], - S["ast"], - Overrideable, - Annotations.Bottom>, - S["~type.make.in"] & Brand<"Override"> | undefined, - S["Iso"] & Brand<"Override">, - S["Type"] & Brand<"Override"> | undefined, - S["~type.mutability"], - S["~type.optionality"], - "with-default", - S["~encoded.mutability"], - S["~encoded.optionality"] - > +export interface Overrideable + extends Schema.refine, Schema.withConstructorDefault> {} /** * @since 4.0.0 * @category overrideable */ -export const Overrideable = (schema: S, options: { - readonly defaultValue: Effect.Effect -}): Overrideable => - (schema as any).pipe( - Schema.withConstructorDefault(constant(Effect.asSome(options.defaultValue))) +export const Overrideable = ( + schema: S, + options: { + readonly defaultValue: Effect.Effect + } +) => + schema.pipe( + Schema.withConstructorDefault(constant(Effect.asSome(options.defaultValue))), + Schema.brand("Override") ) const StructProto = { diff --git a/packages/effect/test/cluster/MessageStorage.test.ts b/packages/effect/test/cluster/MessageStorage.test.ts index c0c9bb4c01..fbd2b0733d 100644 --- a/packages/effect/test/cluster/MessageStorage.test.ts +++ b/packages/effect/test/cluster/MessageStorage.test.ts @@ -135,10 +135,7 @@ export class PrimaryKeyTest extends Rpc.make("PrimaryKeyTest", { }) {} export class StreamRpc extends Rpc.make("StreamTest", { - success: RpcSchema.Stream({ - success: Schema.Void, - error: Schema.Never - }), + success: RpcSchema.Stream(Schema.Void, Schema.Never), payload: { id: Schema.Number }, diff --git a/packages/effect/test/cluster/TestEntity.ts b/packages/effect/test/cluster/TestEntity.ts index 793538c193..90b88295fe 100644 --- a/packages/effect/test/cluster/TestEntity.ts +++ b/packages/effect/test/cluster/TestEntity.ts @@ -12,10 +12,7 @@ export class User extends Schema.Class("User")({ }) {} export class StreamWithKey extends Rpc.make("StreamWithKey", { - success: RpcSchema.Stream({ - success: Schema.Number, - error: Schema.Never - }), + success: RpcSchema.Stream(Schema.Number, Schema.Never), payload: { key: Schema.String }, primaryKey: ({ key }) => key }) {} diff --git a/packages/effect/test/schema/Schema.test.ts b/packages/effect/test/schema/Schema.test.ts index 39caeb779a..68f88646b4 100644 --- a/packages/effect/test/schema/Schema.test.ts +++ b/packages/effect/test/schema/Schema.test.ts @@ -70,6 +70,12 @@ describe("Schema", () => { ) }) + it("should expose the literal", () => { + const schema = Schema.Literal("a") + strictEqual(schema.literal, "a") + strictEqual(schema.annotate({}).literal, "a") + }) + it(`"a"`, async () => { const schema = Schema.Literal("a") @@ -780,6 +786,7 @@ Unexpected key it("should expose the item schema", () => { const schema = Schema.Array(Schema.String) strictEqual(schema.schema, Schema.String) + strictEqual(schema.annotate({}).schema, Schema.String) }) it("readonly string[]", async () => {