"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Array = exports.Any = void 0; exports.ArrayEnsure = ArrayEnsure; exports.Char = exports.CauseFromSelf = exports.Cause = exports.CapitalizedSchemaId = exports.Capitalized = exports.Capitalize = exports.BrandSchemaId = exports.BooleanFromUnknown = exports.BooleanFromString = exports.Boolean = exports.BigIntFromSelf = exports.BigIntFromNumber = exports.BigInt = exports.BigDecimalFromSelf = exports.BigDecimalFromNumber = exports.BigDecimal = exports.BetweenSchemaId = exports.BetweenDurationSchemaId = exports.BetweenDateSchemaId = exports.BetweenBigIntSchemaId = exports.BetweenBigDecimalSchemaId = exports.ArrayFormatterIssue = void 0; exports.Chunk = Chunk; exports.HashMapFromSelf = exports.HashMap = exports.GreaterThanSchemaId = exports.GreaterThanOrEqualToSchemaId = exports.GreaterThanOrEqualToDurationSchemaId = exports.GreaterThanOrEqualToDateSchemaId = exports.GreaterThanOrEqualToBigIntSchemaId = exports.GreaterThanOrEqualToBigDecimalSchemaId = exports.GreaterThanDurationSchemaId = exports.GreaterThanDateSchemaId = exports.GreaterThanBigIntSchemaId = exports.GreaterThanBigDecimalSchemaId = exports.FromPropertySignature = exports.FiniteSchemaId = exports.Finite = exports.FiberIdFromSelf = exports.FiberId = exports.ExitFromSelf = exports.Exit = exports.Enums = exports.EndsWithSchemaId = exports.EitherFromUnion = exports.EitherFromSelf = exports.Either = exports.DurationFromSelf = exports.DurationFromNanos = exports.DurationFromMillis = exports.Duration = exports.Defect = exports.DateTimeZonedFromSelf = exports.DateTimeZoned = exports.DateTimeUtcFromSelf = exports.DateTimeUtcFromNumber = exports.DateTimeUtcFromDate = exports.DateTimeUtc = exports.DateFromString = exports.DateFromSelfSchemaId = exports.DateFromSelf = exports.DateFromNumber = exports.Date = exports.DataFromSelf = exports.Data = exports.Config = exports.Class = exports.ChunkFromSelf = void 0; exports.HashSet = HashSet; exports.LessThanSchemaId = exports.LessThanOrEqualToSchemaId = exports.LessThanOrEqualToDurationSchemaId = exports.LessThanOrEqualToDateSchemaId = exports.LessThanOrEqualToBigIntSchemaId = exports.LessThanOrEqualToBigDecimalSchemaId = exports.LessThanDurationSchemaId = exports.LessThanDateSchemaId = exports.LessThanBigIntSchemaId = exports.LessThanBigDecimalSchemaId = exports.LengthSchemaId = exports.JsonNumberSchemaId = exports.JsonNumber = exports.ItemsCountSchemaId = exports.IntSchemaId = exports.Int = exports.InstanceOfSchemaId = exports.IncludesSchemaId = exports.HashSetFromSelf = void 0; exports.List = List; exports.ListFromSelf = void 0; exports.Literal = Literal; exports.LowercasedSchemaId = exports.Lowercased = exports.Lowercase = void 0; exports.Map = map; exports.MapFromSelf = exports.MapFromRecord = void 0; exports.NonEmptyArray = exports.Never = exports.NegativeBigIntFromSelf = exports.NegativeBigInt = exports.NegativeBigDecimalSchemaId = exports.NegativeBigDecimalFromSelf = exports.Negative = exports.MultipleOfSchemaId = exports.MinLengthSchemaId = exports.MinItemsSchemaId = exports.MaxLengthSchemaId = exports.MaxItemsSchemaId = void 0; exports.NonEmptyArrayEnsure = NonEmptyArrayEnsure; exports.NonEmptyChunk = NonEmptyChunk; exports.Object = exports.NumberFromString = exports.Number = exports.NullishOr = exports.NullOr = exports.Null = exports.Not = exports.NonPositiveBigIntFromSelf = exports.NonPositiveBigInt = exports.NonPositiveBigDecimalSchemaId = exports.NonPositiveBigDecimalFromSelf = exports.NonPositive = exports.NonNegativeInt = exports.NonNegativeBigIntFromSelf = exports.NonNegativeBigInt = exports.NonNegativeBigDecimalSchemaId = exports.NonNegativeBigDecimalFromSelf = exports.NonNegative = exports.NonNaNSchemaId = exports.NonNaN = exports.NonEmptyTrimmedString = exports.NonEmptyString = exports.NonEmptyChunkFromSelf = void 0; exports.Option = Option; exports.OptionFromNonEmptyTrimmedString = void 0; exports.OptionFromNullOr = OptionFromNullOr; exports.OptionFromNullishOr = OptionFromNullishOr; exports.OptionFromSelf = void 0; exports.OptionFromUndefinedOr = OptionFromUndefinedOr; exports.PropertySignatureTypeId = exports.PropertySignatureTransformation = exports.PropertySignatureDeclaration = exports.PropertyKey = exports.PositiveBigIntFromSelf = exports.PositiveBigInt = exports.PositiveBigDecimalSchemaId = exports.PositiveBigDecimalFromSelf = exports.Positive = exports.PatternSchemaId = void 0; exports.ReadonlyMap = ReadonlyMap; exports.ReadonlyMapFromSelf = exports.ReadonlyMapFromRecord = void 0; exports.ReadonlySet = ReadonlySet; exports.Record = exports.ReadonlySetFromSelf = void 0; exports.Redacted = Redacted; exports.RefineSchemaId = exports.RedactedFromSelf = void 0; exports.Set = set; exports.SetFromSelf = void 0; exports.SortedSet = SortedSet; exports.StringFromUriComponent = exports.StringFromHex = exports.StringFromBase64Url = exports.StringFromBase64 = exports.String = exports.StartsWithSchemaId = exports.SortedSetFromSelf = void 0; exports.Struct = Struct; exports.TrimmedSchemaId = exports.Trimmed = exports.Trim = exports.ToPropertySignature = exports.TimeZoneOffsetFromSelf = exports.TimeZoneOffset = exports.TimeZoneNamedFromSelf = exports.TimeZoneNamed = exports.TimeZoneFromSelf = exports.TimeZone = exports.TemplateLiteralParser = exports.TemplateLiteral = exports.TaggedStruct = exports.TaggedRequest = exports.TaggedError = exports.TaggedClass = exports.SymbolFromSelf = exports.Symbol = void 0; exports.Tuple = Tuple; exports.Uint8 = exports.UUIDSchemaId = exports.UUID = exports.URLFromSelf = exports.URL = exports.ULIDSchemaId = exports.ULID = exports.TypeId = void 0; exports.UndefinedOr = exports.Undefined = exports.UncapitalizedSchemaId = exports.Uncapitalized = exports.Uncapitalize = exports.Uint8ArrayFromSelf = exports.Uint8ArrayFromHex = exports.Uint8ArrayFromBase64Url = exports.Uint8ArrayFromBase64 = exports.Uint8Array = void 0; exports.Union = Union; exports.annotations = exports.Void = exports.ValidDateSchemaId = exports.ValidDateFromSelf = exports.UppercasedSchemaId = exports.Uppercased = exports.Uppercase = exports.Unknown = exports.UniqueSymbolFromSelf = void 0; exports.asSchema = asSchema; exports.asWithResult = exports.asSerializableWithResult = exports.asSerializable = void 0; Object.defineProperty(exports, "asserts", { enumerable: true, get: function () { return ParseResult.asserts; } }); exports.decodeEither = exports.decode = exports.declare = exports.compose = exports.clampDuration = exports.clampBigInt = exports.clampBigDecimal = exports.clamp = exports.capitalized = exports.brand = exports.betweenDuration = exports.betweenDate = exports.betweenBigInt = exports.betweenBigDecimal = exports.between = exports.attachPropertySignature = void 0; Object.defineProperty(exports, "decodeOption", { enumerable: true, get: function () { return ParseResult.decodeOption; } }); exports.decodePromise = void 0; Object.defineProperty(exports, "decodeSync", { enumerable: true, get: function () { return ParseResult.decodeSync; } }); exports.decodeUnknownEither = exports.decodeUnknown = void 0; Object.defineProperty(exports, "decodeUnknownOption", { enumerable: true, get: function () { return ParseResult.decodeUnknownOption; } }); exports.decodeUnknownPromise = void 0; Object.defineProperty(exports, "decodeUnknownSync", { enumerable: true, get: function () { return ParseResult.decodeUnknownSync; } }); exports.encodeEither = exports.encode = exports.element = exports.deserializeSuccess = exports.deserializeFailure = exports.deserializeExit = exports.deserialize = void 0; Object.defineProperty(exports, "encodeOption", { enumerable: true, get: function () { return ParseResult.encodeOption; } }); exports.encodePromise = void 0; Object.defineProperty(exports, "encodeSync", { enumerable: true, get: function () { return ParseResult.encodeSync; } }); exports.encodeUnknownEither = exports.encodeUnknown = void 0; Object.defineProperty(exports, "encodeUnknownOption", { enumerable: true, get: function () { return ParseResult.encodeUnknownOption; } }); exports.encodeUnknownPromise = void 0; Object.defineProperty(exports, "encodeUnknownSync", { enumerable: true, get: function () { return ParseResult.encodeUnknownSync; } }); exports.failureSchema = exports.extend = exports.exitSchema = exports.equivalence = exports.endsWith = exports.encodedSchema = exports.encodedBoundSchema = void 0; exports.filter = filter; exports.greaterThanOrEqualToDuration = exports.greaterThanOrEqualToDate = exports.greaterThanOrEqualToBigInt = exports.greaterThanOrEqualToBigDecimal = exports.greaterThanOrEqualTo = exports.greaterThanDuration = exports.greaterThanDate = exports.greaterThanBigInt = exports.greaterThanBigDecimal = exports.greaterThan = exports.getNumberIndexedAccess = exports.getClassTag = exports.fromKey = exports.fromBrand = exports.format = exports.finite = exports.filterEffect = void 0; exports.head = head; exports.headNonEmpty = headNonEmpty; exports.int = exports.instanceOf = exports.includes = exports.headOrElse = void 0; Object.defineProperty(exports, "is", { enumerable: true, get: function () { return ParseResult.is; } }); exports.keyof = exports.itemsCount = exports.isSchema = exports.isPropertySignature = void 0; exports.lowercased = exports.lessThanOrEqualToDuration = exports.lessThanOrEqualToDate = exports.lessThanOrEqualToBigInt = exports.lessThanOrEqualToBigDecimal = exports.lessThanOrEqualTo = exports.lessThanDuration = exports.lessThanDate = exports.lessThanBigInt = exports.lessThanBigDecimal = exports.lessThan = exports.length = void 0; exports.make = make; exports.parseJson = exports.optionalWith = exports.optionalToRequired = exports.optionalToOptional = exports.optionalElement = exports.optional = exports.omit = exports.nonPositiveBigInt = exports.nonPositiveBigDecimal = exports.nonPositive = exports.nonNegativeBigInt = exports.nonNegativeBigDecimal = exports.nonNegative = exports.nonNaN = exports.nonEmptyString = exports.negativeBigInt = exports.negativeBigDecimal = exports.negative = exports.mutable = exports.multipleOf = exports.minLength = exports.minItems = exports.maxLength = exports.maxItems = exports.makePropertySignature = void 0; exports.parseNumber = parseNumber; exports.transform = exports.tag = exports.symbolWithResult = exports.symbolSerializable = exports.suspend = exports.successSchema = exports.startsWith = exports.standardSchemaV1 = exports.split = exports.serializeSuccess = exports.serializeFailure = exports.serializeExit = exports.serialize = exports.serializableSchema = exports.requiredToOptional = exports.required = exports.rename = exports.propertySignature = exports.positiveBigInt = exports.positiveBigDecimal = exports.positive = exports.pluck = exports.pickLiteral = exports.pick = exports.pattern = exports.partialWith = exports.partial = void 0; exports.transformLiteral = transformLiteral; exports.transformLiterals = transformLiterals; exports.validateEither = exports.validate = exports.validDate = exports.uppercased = exports.uncapitalized = exports.typeSchema = exports.trimmed = exports.transformOrFail = void 0; Object.defineProperty(exports, "validateOption", { enumerable: true, get: function () { return ParseResult.validateOption; } }); exports.validatePromise = void 0; Object.defineProperty(exports, "validateSync", { enumerable: true, get: function () { return ParseResult.validateSync; } }); exports.withDefaults = exports.withDecodingDefault = exports.withConstructorDefault = void 0; var array_ = _interopRequireWildcard(require("./Array.js")); var bigDecimal_ = _interopRequireWildcard(require("./BigDecimal.js")); var bigInt_ = _interopRequireWildcard(require("./BigInt.js")); var boolean_ = _interopRequireWildcard(require("./Boolean.js")); var cause_ = _interopRequireWildcard(require("./Cause.js")); var chunk_ = _interopRequireWildcard(require("./Chunk.js")); var config_ = _interopRequireWildcard(require("./Config.js")); var configError_ = _interopRequireWildcard(require("./ConfigError.js")); var data_ = _interopRequireWildcard(require("./Data.js")); var dateTime = _interopRequireWildcard(require("./DateTime.js")); var duration_ = _interopRequireWildcard(require("./Duration.js")); var Effect = _interopRequireWildcard(require("./Effect.js")); var either_ = _interopRequireWildcard(require("./Either.js")); var Encoding = _interopRequireWildcard(require("./Encoding.js")); var Equal = _interopRequireWildcard(require("./Equal.js")); var Equivalence = _interopRequireWildcard(require("./Equivalence.js")); var exit_ = _interopRequireWildcard(require("./Exit.js")); var fastCheck_ = _interopRequireWildcard(require("./FastCheck.js")); var fiberId_ = _interopRequireWildcard(require("./FiberId.js")); var _Function = require("./Function.js"); var _GlobalValue = require("./GlobalValue.js"); var hashMap_ = _interopRequireWildcard(require("./HashMap.js")); var hashSet_ = _interopRequireWildcard(require("./HashSet.js")); var internalCause_ = _interopRequireWildcard(require("./internal/cause.js")); var errors_ = _interopRequireWildcard(require("./internal/schema/errors.js")); var schemaId_ = _interopRequireWildcard(require("./internal/schema/schemaId.js")); var util_ = _interopRequireWildcard(require("./internal/schema/util.js")); var list_ = _interopRequireWildcard(require("./List.js")); var number_ = _interopRequireWildcard(require("./Number.js")); var option_ = _interopRequireWildcard(require("./Option.js")); var ParseResult = _interopRequireWildcard(require("./ParseResult.js")); var _Pipeable = require("./Pipeable.js"); var Predicate = _interopRequireWildcard(require("./Predicate.js")); var redacted_ = _interopRequireWildcard(require("./Redacted.js")); var Request = _interopRequireWildcard(require("./Request.js")); var scheduler_ = _interopRequireWildcard(require("./Scheduler.js")); var AST = _interopRequireWildcard(require("./SchemaAST.js")); var sortedSet_ = _interopRequireWildcard(require("./SortedSet.js")); var string_ = _interopRequireWildcard(require("./String.js")); var struct_ = _interopRequireWildcard(require("./Struct.js")); function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); } /** * @since 3.10.0 */ /** * @since 3.10.0 * @category symbol */ const TypeId = exports.TypeId = /*#__PURE__*/Symbol.for("effect/Schema"); /** * @category constructors * @since 3.10.0 */ function make(ast) { return class SchemaClass { [TypeId] = variance; static ast = ast; static annotations(annotations) { return make(mergeSchemaAnnotations(this.ast, annotations)); } static pipe() { return (0, _Pipeable.pipeArguments)(this, arguments); } static toString() { return String(ast); } static Type; static Encoded; static Context; static [TypeId] = variance; }; } const variance = { /* c8 ignore next */ _A: _ => _, /* c8 ignore next */ _I: _ => _, /* c8 ignore next */ _R: _ => _ }; const makeStandardResult = exit => exit_.isSuccess(exit) ? exit.value : makeStandardFailureResult(cause_.pretty(exit.cause)); const makeStandardFailureResult = message => ({ issues: [{ message }] }); const makeStandardFailureFromParseIssue = issue => Effect.map(ParseResult.ArrayFormatter.formatIssue(issue), issues => ({ issues: issues.map(issue => ({ path: issue.path, message: issue.message })) })); /** * Returns a "Standard Schema" object conforming to the [Standard Schema * v1](https://standardschema.dev/) specification. * * This function creates a schema whose `validate` method attempts to decode and * validate the provided input synchronously. If the underlying `Schema` * includes any asynchronous components (e.g., asynchronous message resolutions * or checks), then validation will necessarily return a `Promise` instead. * * Any detected defects will be reported via a single issue containing no * `path`. * * @example * ```ts * import { Schema } from "effect" * * const schema = Schema.Struct({ * name: Schema.String * }) * * // ┌─── StandardSchemaV1<{ readonly name: string; }> * // ▼ * const standardSchema = Schema.standardSchemaV1(schema) * ``` * * @category Standard Schema * @since 3.13.0 */ const standardSchemaV1 = (schema, overrideOptions) => { const decodeUnknown = ParseResult.decodeUnknown(schema, { errors: "all" }); return class StandardSchemaV1Class extends make(schema.ast) { static "~standard" = { version: 1, vendor: "effect", validate(value) { const scheduler = new scheduler_.SyncScheduler(); const fiber = Effect.runFork(Effect.matchEffect(decodeUnknown(value, overrideOptions), { onFailure: makeStandardFailureFromParseIssue, onSuccess: value => Effect.succeed({ value }) }), { scheduler }); scheduler.flush(); const exit = fiber.unsafePoll(); if (exit) { return makeStandardResult(exit); } return new Promise(resolve => { fiber.addObserver(exit => { resolve(makeStandardResult(exit)); }); }); } }; }; }; exports.standardSchemaV1 = standardSchemaV1; const builtInAnnotations = { schemaId: AST.SchemaIdAnnotationId, message: AST.MessageAnnotationId, missingMessage: AST.MissingMessageAnnotationId, identifier: AST.IdentifierAnnotationId, title: AST.TitleAnnotationId, description: AST.DescriptionAnnotationId, examples: AST.ExamplesAnnotationId, default: AST.DefaultAnnotationId, documentation: AST.DocumentationAnnotationId, jsonSchema: AST.JSONSchemaAnnotationId, arbitrary: AST.ArbitraryAnnotationId, pretty: AST.PrettyAnnotationId, equivalence: AST.EquivalenceAnnotationId, concurrency: AST.ConcurrencyAnnotationId, batching: AST.BatchingAnnotationId, parseIssueTitle: AST.ParseIssueTitleAnnotationId, parseOptions: AST.ParseOptionsAnnotationId, decodingFallback: AST.DecodingFallbackAnnotationId }; const toASTAnnotations = annotations => { if (!annotations) { return {}; } const out = { ...annotations }; for (const key in builtInAnnotations) { if (key in annotations) { const id = builtInAnnotations[key]; out[id] = annotations[key]; delete out[key]; } } return out; }; const mergeSchemaAnnotations = (ast, annotations) => AST.annotations(ast, toASTAnnotations(annotations)); /** * @since 3.10.0 */ function asSchema(schema) { return schema; } /** * @category formatting * @since 3.10.0 */ const format = schema => String(schema.ast); /** * The `encodedSchema` function allows you to extract the `Encoded` portion of a * schema, creating a new schema that conforms to the properties defined in the * original schema without retaining any refinements or transformations that * were applied previously. * * @since 3.10.0 */ exports.format = format; const encodedSchema = schema => make(AST.encodedAST(schema.ast)); /** * The `encodedBoundSchema` function is similar to `encodedSchema` but preserves * the refinements up to the first transformation point in the original schema. * * @since 3.10.0 */ exports.encodedSchema = encodedSchema; const encodedBoundSchema = schema => make(AST.encodedBoundAST(schema.ast)); /** * The `typeSchema` function allows you to extract the `Type` portion of a * schema, creating a new schema that conforms to the properties defined in the * original schema without considering the initial encoding or transformation * processes. * * @since 3.10.0 */ exports.encodedBoundSchema = encodedBoundSchema; const typeSchema = schema => make(AST.typeAST(schema.ast)); /* c8 ignore start */ exports.typeSchema = typeSchema; /* c8 ignore end */ /** * @category encoding * @since 3.10.0 */ const encodeUnknown = (schema, options) => { const encodeUnknown = ParseResult.encodeUnknown(schema, options); return (u, overrideOptions) => ParseResult.mapError(encodeUnknown(u, overrideOptions), ParseResult.parseError); }; /** * @category encoding * @since 3.10.0 */ exports.encodeUnknown = encodeUnknown; const encodeUnknownEither = (schema, options) => { const encodeUnknownEither = ParseResult.encodeUnknownEither(schema, options); return (u, overrideOptions) => either_.mapLeft(encodeUnknownEither(u, overrideOptions), ParseResult.parseError); }; /** * @category encoding * @since 3.10.0 */ exports.encodeUnknownEither = encodeUnknownEither; const encodeUnknownPromise = (schema, options) => { const parser = encodeUnknown(schema, options); return (u, overrideOptions) => Effect.runPromise(parser(u, overrideOptions)); }; /** * @category encoding * @since 3.10.0 */ exports.encodeUnknownPromise = encodeUnknownPromise; const encode = exports.encode = encodeUnknown; /** * @category encoding * @since 3.10.0 */ const encodeEither = exports.encodeEither = encodeUnknownEither; /** * @category encoding * @since 3.10.0 */ const encodePromise = exports.encodePromise = encodeUnknownPromise; /** * @category decoding * @since 3.10.0 */ const decodeUnknown = (schema, options) => { const decodeUnknown = ParseResult.decodeUnknown(schema, options); return (u, overrideOptions) => ParseResult.mapError(decodeUnknown(u, overrideOptions), ParseResult.parseError); }; /** * @category decoding * @since 3.10.0 */ exports.decodeUnknown = decodeUnknown; const decodeUnknownEither = (schema, options) => { const decodeUnknownEither = ParseResult.decodeUnknownEither(schema, options); return (u, overrideOptions) => either_.mapLeft(decodeUnknownEither(u, overrideOptions), ParseResult.parseError); }; /** * @category decoding * @since 3.10.0 */ exports.decodeUnknownEither = decodeUnknownEither; const decodeUnknownPromise = (schema, options) => { const parser = decodeUnknown(schema, options); return (u, overrideOptions) => Effect.runPromise(parser(u, overrideOptions)); }; /** * @category decoding * @since 3.10.0 */ exports.decodeUnknownPromise = decodeUnknownPromise; const decode = exports.decode = decodeUnknown; /** * @category decoding * @since 3.10.0 */ const decodeEither = exports.decodeEither = decodeUnknownEither; /** * @category decoding * @since 3.10.0 */ const decodePromise = exports.decodePromise = decodeUnknownPromise; /** * @category validation * @since 3.10.0 */ const validate = (schema, options) => { const validate = ParseResult.validate(schema, options); return (u, overrideOptions) => ParseResult.mapError(validate(u, overrideOptions), ParseResult.parseError); }; /** * @category validation * @since 3.10.0 */ exports.validate = validate; const validateEither = (schema, options) => { const validateEither = ParseResult.validateEither(schema, options); return (u, overrideOptions) => either_.mapLeft(validateEither(u, overrideOptions), ParseResult.parseError); }; /** * @category validation * @since 3.10.0 */ exports.validateEither = validateEither; const validatePromise = (schema, options) => { const parser = validate(schema, options); return (u, overrideOptions) => Effect.runPromise(parser(u, overrideOptions)); }; /** * Tests if a value is a `Schema`. * * @category guards * @since 3.10.0 */ exports.validatePromise = validatePromise; const isSchema = u => Predicate.hasProperty(u, TypeId) && Predicate.isObject(u[TypeId]); exports.isSchema = isSchema; function getDefaultLiteralAST(literals) { return AST.isMembers(literals) ? AST.Union.make(AST.mapMembers(literals, literal => new AST.Literal(literal))) : new AST.Literal(literals[0]); } function makeLiteralClass(literals, ast = getDefaultLiteralAST(literals)) { return class LiteralClass extends make(ast) { static annotations(annotations) { return makeLiteralClass(this.literals, mergeSchemaAnnotations(this.ast, annotations)); } static literals = [...literals]; }; } function Literal(...literals) { return array_.isNonEmptyReadonlyArray(literals) ? makeLiteralClass(literals) : Never; } /** * Creates a new `Schema` from a literal schema. * * @example * ```ts * import * as assert from "node:assert" * import { Either, Schema } from "effect" * * const schema = Schema.Literal("a", "b", "c").pipe(Schema.pickLiteral("a", "b")) * * assert.deepStrictEqual(Schema.decodeSync(schema)("a"), "a") * assert.deepStrictEqual(Schema.decodeSync(schema)("b"), "b") * assert.strictEqual(Either.isLeft(Schema.decodeUnknownEither(schema)("c")), true) * ``` * * @category constructors * @since 3.10.0 */ const pickLiteral = (...literals) => _schema => Literal(...literals); /** * @category constructors * @since 3.10.0 */ exports.pickLiteral = pickLiteral; const UniqueSymbolFromSelf = symbol => make(new AST.UniqueSymbol(symbol)); exports.UniqueSymbolFromSelf = UniqueSymbolFromSelf; const getDefaultEnumsAST = enums => new AST.Enums(Object.keys(enums).filter(key => typeof enums[enums[key]] !== "number").map(key => [key, enums[key]])); const makeEnumsClass = (enums, ast = getDefaultEnumsAST(enums)) => class EnumsClass extends make(ast) { static annotations(annotations) { return makeEnumsClass(this.enums, mergeSchemaAnnotations(this.ast, annotations)); } static enums = { ...enums }; }; /** * @category constructors * @since 3.10.0 */ const Enums = enums => makeEnumsClass(enums); /** * @category template literal * @since 3.10.0 */ exports.Enums = Enums; const TemplateLiteral = (...[head, ...tail]) => { const spans = []; let h = ""; let ts = tail; if (isSchema(head)) { if (AST.isLiteral(head.ast)) { h = String(head.ast.literal); } else { ts = [head, ...ts]; } } else { h = String(head); } for (let i = 0; i < ts.length; i++) { const item = ts[i]; if (isSchema(item)) { if (i < ts.length - 1) { const next = ts[i + 1]; if (isSchema(next)) { if (AST.isLiteral(next.ast)) { spans.push(new AST.TemplateLiteralSpan(item.ast, String(next.ast.literal))); i++; continue; } } else { spans.push(new AST.TemplateLiteralSpan(item.ast, String(next))); i++; continue; } } spans.push(new AST.TemplateLiteralSpan(item.ast, "")); } else { spans.push(new AST.TemplateLiteralSpan(new AST.Literal(item), "")); } } if (array_.isNonEmptyArray(spans)) { return make(new AST.TemplateLiteral(h, spans)); } else { return make(new AST.TemplateLiteral("", [new AST.TemplateLiteralSpan(new AST.Literal(h), "")])); } }; exports.TemplateLiteral = TemplateLiteral; function getTemplateLiteralParserCoercedElement(encoded, schema) { const ast = encoded.ast; switch (ast._tag) { case "Literal": { const literal = ast.literal; if (!Predicate.isString(literal)) { const s = String(literal); return transform(Literal(s), schema, { strict: true, decode: () => literal, encode: () => s }); } break; } case "NumberKeyword": return compose(NumberFromString, schema); case "Union": { const members = []; let hasCoercions = false; for (const member of ast.types) { const schema = make(member); const encoded = encodedSchema(schema); const coerced = getTemplateLiteralParserCoercedElement(encoded, schema); if (coerced) { hasCoercions = true; } members.push(coerced ?? schema); } return hasCoercions ? compose(Union(...members), schema) : schema; } } } /** * @category template literal * @since 3.10.0 */ const TemplateLiteralParser = (...params) => { const encodedSchemas = []; const elements = []; const schemas = []; let coerced = false; for (let i = 0; i < params.length; i++) { const param = params[i]; const schema = isSchema(param) ? param : Literal(param); schemas.push(schema); const encoded = encodedSchema(schema); encodedSchemas.push(encoded); const element = getTemplateLiteralParserCoercedElement(encoded, schema); if (element) { elements.push(element); coerced = true; } else { elements.push(schema); } } const from = TemplateLiteral(...encodedSchemas); const re = AST.getTemplateLiteralCapturingRegExp(from.ast); let to = Tuple(...elements); if (coerced) { to = to.annotations({ [AST.AutoTitleAnnotationId]: format(Tuple(...schemas)) }); } return class TemplateLiteralParserClass extends transformOrFail(from, to, { strict: false, decode: (i, _, ast) => { const match = re.exec(i); return match ? ParseResult.succeed(match.slice(1, params.length + 1)) : ParseResult.fail(new ParseResult.Type(ast, i, `${re.source}: no match for ${JSON.stringify(i)}`)); }, encode: tuple => ParseResult.succeed(tuple.join("")) }) { static params = params.slice(); }; }; exports.TemplateLiteralParser = TemplateLiteralParser; const declareConstructor = (typeParameters, options, annotations) => makeDeclareClass(typeParameters, new AST.Declaration(typeParameters.map(tp => tp.ast), (...typeParameters) => options.decode(...typeParameters.map(make)), (...typeParameters) => options.encode(...typeParameters.map(make)), toASTAnnotations(annotations))); const declarePrimitive = (is, annotations) => { const decodeUnknown = () => (input, _, ast) => is(input) ? ParseResult.succeed(input) : ParseResult.fail(new ParseResult.Type(ast, input)); const encodeUnknown = decodeUnknown; return makeDeclareClass([], new AST.Declaration([], decodeUnknown, encodeUnknown, toASTAnnotations(annotations))); }; function makeDeclareClass(typeParameters, ast) { return class DeclareClass extends make(ast) { static annotations(annotations) { return makeDeclareClass(this.typeParameters, mergeSchemaAnnotations(this.ast, annotations)); } static typeParameters = [...typeParameters]; }; } /** * The constraint `R extends Schema.Context
` enforces dependencies solely from `typeParameters`.
* This ensures that when you call `Schema.to` or `Schema.from`, you receive a schema with a `never` context.
*
* @category constructors
* @since 3.10.0
*/
const declare = function () {
if (Array.isArray(arguments[0])) {
const typeParameters = arguments[0];
const options = arguments[1];
const annotations = arguments[2];
return declareConstructor(typeParameters, options, annotations);
}
const is = arguments[0];
const annotations = arguments[1];
return declarePrimitive(is, annotations);
};
/**
* @category schema id
* @since 3.10.0
*/
exports.declare = declare;
const BrandSchemaId = exports.BrandSchemaId = /*#__PURE__*/Symbol.for("effect/SchemaId/Brand");
/**
* @category constructors
* @since 3.10.0
*/
const fromBrand = (constructor, annotations) => self => {
const out = makeBrandClass(self, new AST.Refinement(self.ast, function predicate(a, _, ast) {
const either = constructor.either(a);
return either_.isLeft(either) ? option_.some(new ParseResult.Type(ast, a, either.left.map(v => v.message).join(", "))) : option_.none();
}, toASTAnnotations({
schemaId: BrandSchemaId,
[BrandSchemaId]: {
constructor
},
...annotations
})));
return out;
};
/**
* @category schema id
* @since 3.10.0
*/
exports.fromBrand = fromBrand;
const InstanceOfSchemaId = exports.InstanceOfSchemaId = /*#__PURE__*/Symbol.for("effect/SchemaId/InstanceOf");
/**
* @category constructors
* @since 3.10.0
*/
const instanceOf = (constructor, annotations) => declare(u => u instanceof constructor, {
title: constructor.name,
description: `an instance of ${constructor.name}`,
pretty: () => String,
schemaId: InstanceOfSchemaId,
[InstanceOfSchemaId]: {
constructor
},
...annotations
});
/**
* @category primitives
* @since 3.10.0
*/
exports.instanceOf = instanceOf;
class Undefined extends /*#__PURE__*/make(AST.undefinedKeyword) {}
/**
* @category primitives
* @since 3.10.0
*/
exports.Undefined = Undefined;
class Void extends /*#__PURE__*/make(AST.voidKeyword) {}
/**
* @category primitives
* @since 3.10.0
*/
exports.Void = Void;
class Null extends /*#__PURE__*/make(AST.null) {}
/**
* @category primitives
* @since 3.10.0
*/
exports.Null = Null;
class Never extends /*#__PURE__*/make(AST.neverKeyword) {}
/**
* @category primitives
* @since 3.10.0
*/
exports.Never = Never;
class Unknown extends /*#__PURE__*/make(AST.unknownKeyword) {}
/**
* @category primitives
* @since 3.10.0
*/
exports.Unknown = Unknown;
class Any extends /*#__PURE__*/make(AST.anyKeyword) {}
/**
* @category primitives
* @since 3.10.0
*/
exports.Any = Any;
class BigIntFromSelf extends /*#__PURE__*/make(AST.bigIntKeyword) {}
/**
* @category primitives
* @since 3.10.0
*/
exports.BigIntFromSelf = BigIntFromSelf;
class SymbolFromSelf extends /*#__PURE__*/make(AST.symbolKeyword) {}
/** @ignore */
exports.SymbolFromSelf = SymbolFromSelf;
class String$ extends /*#__PURE__*/make(AST.stringKeyword) {}
/** @ignore */
exports.String = String$;
class Number$ extends /*#__PURE__*/make(AST.numberKeyword) {}
/** @ignore */
exports.Number = Number$;
class Boolean$ extends /*#__PURE__*/make(AST.booleanKeyword) {}
/** @ignore */
exports.Boolean = Boolean$;
class Object$ extends /*#__PURE__*/make(AST.objectKeyword) {}
exports.Object = Object$;
const getDefaultUnionAST = members => AST.Union.make(members.map(m => m.ast));
function makeUnionClass(members, ast = getDefaultUnionAST(members)) {
return class UnionClass extends make(ast) {
static annotations(annotations) {
return makeUnionClass(this.members, mergeSchemaAnnotations(this.ast, annotations));
}
static members = [...members];
};
}
function Union(...members) {
return AST.isMembers(members) ? makeUnionClass(members) : array_.isNonEmptyReadonlyArray(members) ? members[0] : Never;
}
/**
* @category combinators
* @since 3.10.0
*/
const NullOr = self => Union(self, Null);
/**
* @category combinators
* @since 3.10.0
*/
exports.NullOr = NullOr;
const UndefinedOr = self => Union(self, Undefined);
/**
* @category combinators
* @since 3.10.0
*/
exports.UndefinedOr = UndefinedOr;
const NullishOr = self => Union(self, Null, Undefined);
/**
* @category combinators
* @since 3.10.0
*/
exports.NullishOr = NullishOr;
const keyof = self => make(AST.keyof(self.ast));
/**
* @since 3.10.0
*/
exports.keyof = keyof;
const element = self => new ElementImpl(new AST.OptionalType(self.ast, false), self);
/**
* @since 3.10.0
*/
exports.element = element;
const optionalElement = self => new ElementImpl(new AST.OptionalType(self.ast, true), self);
exports.optionalElement = optionalElement;
class ElementImpl {
ast;
from;
[TypeId];
_Token;
constructor(ast, from) {
this.ast = ast;
this.from = from;
}
annotations(annotations) {
return new ElementImpl(new AST.OptionalType(this.ast.type, this.ast.isOptional, {
...this.ast.annotations,
...toASTAnnotations(annotations)
}), this.from);
}
toString() {
return `${this.ast.type}${this.ast.isOptional ? "?" : ""}`;
}
}
const getDefaultTupleTypeAST = (elements, rest) => new AST.TupleType(elements.map(el => isSchema(el) ? new AST.OptionalType(el.ast, false) : el.ast), rest.map(el => isSchema(el) ? new AST.Type(el.ast) : el.ast), true);
function makeTupleTypeClass(elements, rest, ast = getDefaultTupleTypeAST(elements, rest)) {
return class TupleTypeClass extends make(ast) {
static annotations(annotations) {
return makeTupleTypeClass(this.elements, this.rest, mergeSchemaAnnotations(this.ast, annotations));
}
static elements = [...elements];
static rest = [...rest];
};
}
function Tuple(...args) {
return Array.isArray(args[0]) ? makeTupleTypeClass(args[0], args.slice(1)) : makeTupleTypeClass(args, []);
}
function makeArrayClass(value, ast) {
return class ArrayClass extends makeTupleTypeClass([], [value], ast) {
static annotations(annotations) {
return makeArrayClass(this.value, mergeSchemaAnnotations(this.ast, annotations));
}
static value = value;
};
}
const Array$ = value => makeArrayClass(value);
exports.Array = Array$;
function makeNonEmptyArrayClass(value, ast) {
return class NonEmptyArrayClass extends makeTupleTypeClass([value], [value], ast) {
static annotations(annotations) {
return makeNonEmptyArrayClass(this.value, mergeSchemaAnnotations(this.ast, annotations));
}
static value = value;
};
}
/**
* @category constructors
* @since 3.10.0
*/
const NonEmptyArray = value => makeNonEmptyArrayClass(value);
/**
* @category constructors
* @since 3.10.0
*/
exports.NonEmptyArray = NonEmptyArray;
function ArrayEnsure(value) {
return transform(Union(value, Array$(value)), Array$(typeSchema(asSchema(value))), {
strict: true,
decode: i => array_.ensure(i),
encode: a => a.length === 1 ? a[0] : a
});
}
/**
* @category constructors
* @since 3.10.0
*/
function NonEmptyArrayEnsure(value) {
return transform(Union(value, NonEmptyArray(value)), NonEmptyArray(typeSchema(asSchema(value))), {
strict: true,
decode: i => array_.isNonEmptyReadonlyArray(i) ? i : array_.of(i),
encode: a => a.length === 1 ? a[0] : a
});
}
const formatPropertySignatureToken = isOptional => isOptional ? "\"?:\"" : "\":\"";
/**
* @category PropertySignature
* @since 3.10.0
*/
class PropertySignatureDeclaration extends AST.OptionalType {
isReadonly;
defaultValue;
/**
* @since 3.10.0
*/
_tag = "PropertySignatureDeclaration";
constructor(type, isOptional, isReadonly, annotations, defaultValue) {
super(type, isOptional, annotations);
this.isReadonly = isReadonly;
this.defaultValue = defaultValue;
}
/**
* @since 3.10.0
*/
toString() {
const token = formatPropertySignatureToken(this.isOptional);
const type = String(this.type);
return `PropertySignature<${token}, ${type}, never, ${token}, ${type}>`;
}
}
/**
* @category PropertySignature
* @since 3.10.0
*/
exports.PropertySignatureDeclaration = PropertySignatureDeclaration;
class FromPropertySignature extends AST.OptionalType {
isReadonly;
fromKey;
constructor(type, isOptional, isReadonly, annotations, fromKey) {
super(type, isOptional, annotations);
this.isReadonly = isReadonly;
this.fromKey = fromKey;
}
}
/**
* @category PropertySignature
* @since 3.10.0
*/
exports.FromPropertySignature = FromPropertySignature;
class ToPropertySignature extends AST.OptionalType {
isReadonly;
defaultValue;
constructor(type, isOptional, isReadonly, annotations, defaultValue) {
super(type, isOptional, annotations);
this.isReadonly = isReadonly;
this.defaultValue = defaultValue;
}
}
exports.ToPropertySignature = ToPropertySignature;
const formatPropertyKey = p => {
if (p === undefined) {
return "never";
}
if (Predicate.isString(p)) {
return JSON.stringify(p);
}
return String(p);
};
/**
* @category PropertySignature
* @since 3.10.0
*/
class PropertySignatureTransformation {
from;
to;
decode;
encode;
/**
* @since 3.10.0
*/
_tag = "PropertySignatureTransformation";
constructor(from, to, decode, encode) {
this.from = from;
this.to = to;
this.decode = decode;
this.encode = encode;
}
/**
* @since 3.10.0
*/
toString() {
return `PropertySignature<${formatPropertySignatureToken(this.to.isOptional)}, ${this.to.type}, ${formatPropertyKey(this.from.fromKey)}, ${formatPropertySignatureToken(this.from.isOptional)}, ${this.from.type}>`;
}
}
exports.PropertySignatureTransformation = PropertySignatureTransformation;
const mergeSignatureAnnotations = (ast, annotations) => {
switch (ast._tag) {
case "PropertySignatureDeclaration":
{
return new PropertySignatureDeclaration(ast.type, ast.isOptional, ast.isReadonly, {
...ast.annotations,
...annotations
}, ast.defaultValue);
}
case "PropertySignatureTransformation":
{
return new PropertySignatureTransformation(ast.from, new ToPropertySignature(ast.to.type, ast.to.isOptional, ast.to.isReadonly, {
...ast.to.annotations,
...annotations
}, ast.to.defaultValue), ast.decode, ast.encode);
}
}
};
/**
* @since 3.10.0
* @category symbol
*/
const PropertySignatureTypeId = exports.PropertySignatureTypeId = /*#__PURE__*/Symbol.for("effect/PropertySignature");
/**
* @since 3.10.0
* @category guards
*/
const isPropertySignature = u => Predicate.hasProperty(u, PropertySignatureTypeId);
exports.isPropertySignature = isPropertySignature;
class PropertySignatureImpl {
ast;
[TypeId];
[PropertySignatureTypeId] = null;
_TypeToken;
_Key;
_EncodedToken;
_HasDefault;
constructor(ast) {
this.ast = ast;
}
pipe() {
return (0, _Pipeable.pipeArguments)(this, arguments);
}
annotations(annotations) {
return new PropertySignatureImpl(mergeSignatureAnnotations(this.ast, toASTAnnotations(annotations)));
}
toString() {
return String(this.ast);
}
}
/**
* @category PropertySignature
* @since 3.10.0
*/
const makePropertySignature = ast => new PropertySignatureImpl(ast);
exports.makePropertySignature = makePropertySignature;
class PropertySignatureWithFromImpl extends PropertySignatureImpl {
from;
constructor(ast, from) {
super(ast);
this.from = from;
}
annotations(annotations) {
return new PropertySignatureWithFromImpl(mergeSignatureAnnotations(this.ast, toASTAnnotations(annotations)), this.from);
}
}
/**
* Lifts a `Schema` into a `PropertySignature`.
*
* @category PropertySignature
* @since 3.10.0
*/
const propertySignature = self => new PropertySignatureWithFromImpl(new PropertySignatureDeclaration(self.ast, false, true, {}, undefined), self);
/**
* Enhances a property signature with a default constructor value.
*
* @category PropertySignature
* @since 3.10.0
*/
exports.propertySignature = propertySignature;
const withConstructorDefault = exports.withConstructorDefault = /*#__PURE__*/(0, _Function.dual)(2, (self, defaultValue) => {
const ast = self.ast;
switch (ast._tag) {
case "PropertySignatureDeclaration":
return makePropertySignature(new PropertySignatureDeclaration(ast.type, ast.isOptional, ast.isReadonly, ast.annotations, defaultValue));
case "PropertySignatureTransformation":
return makePropertySignature(new PropertySignatureTransformation(ast.from, new ToPropertySignature(ast.to.type, ast.to.isOptional, ast.to.isReadonly, ast.to.annotations, defaultValue), ast.decode, ast.encode));
}
});
const applyDefaultValue = (o, defaultValue) => option_.match(o, {
onNone: () => option_.some(defaultValue()),
onSome: value => option_.some(value === undefined ? defaultValue() : value)
});
const pruneUndefined = ast => AST.pruneUndefined(ast, pruneUndefined, ast => {
const pruned = pruneUndefined(ast.to);
if (pruned) {
return new AST.Transformation(ast.from, pruned, ast.transformation);
}
});
/**
* Enhances a property signature with a default decoding value.
*
* @category PropertySignature
* @since 3.10.0
*/
const withDecodingDefault = exports.withDecodingDefault = /*#__PURE__*/(0, _Function.dual)(2, (self, defaultValue) => {
const ast = self.ast;
switch (ast._tag) {
case "PropertySignatureDeclaration":
{
const to = AST.typeAST(ast.type);
return makePropertySignature(new PropertySignatureTransformation(new FromPropertySignature(ast.type, ast.isOptional, ast.isReadonly, ast.annotations), new ToPropertySignature(pruneUndefined(to) ?? to, false, true, {}, ast.defaultValue), o => applyDefaultValue(o, defaultValue), _Function.identity));
}
case "PropertySignatureTransformation":
{
const to = ast.to.type;
return makePropertySignature(new PropertySignatureTransformation(ast.from, new ToPropertySignature(pruneUndefined(to) ?? to, false, ast.to.isReadonly, ast.to.annotations, ast.to.defaultValue), o => applyDefaultValue(ast.decode(o), defaultValue), ast.encode));
}
}
});
/**
* Enhances a property signature with a default decoding value and a default constructor value.
*
* @category PropertySignature
* @since 3.10.0
*/
const withDefaults = exports.withDefaults = /*#__PURE__*/(0, _Function.dual)(2, (self, defaults) => self.pipe(withDecodingDefault(defaults.decoding), withConstructorDefault(defaults.constructor)));
/**
* Enhances a property signature by specifying a different key for it in the Encoded type.
*
* @category PropertySignature
* @since 3.10.0
*/
const fromKey = exports.fromKey = /*#__PURE__*/(0, _Function.dual)(2, (self, key) => {
const ast = self.ast;
switch (ast._tag) {
case "PropertySignatureDeclaration":
{
return makePropertySignature(new PropertySignatureTransformation(new FromPropertySignature(ast.type, ast.isOptional, ast.isReadonly, ast.annotations, key), new ToPropertySignature(AST.typeAST(ast.type), ast.isOptional, ast.isReadonly, {}, ast.defaultValue), _Function.identity, _Function.identity));
}
case "PropertySignatureTransformation":
return makePropertySignature(new PropertySignatureTransformation(new FromPropertySignature(ast.from.type, ast.from.isOptional, ast.from.isReadonly, ast.from.annotations, key), ast.to, ast.decode, ast.encode));
}
});
/**
* Converts an optional property to a required one through a transformation `Option -> Type`.
*
* - `decode`: `none` as argument means the value is missing in the input.
* - `encode`: `none` as return value means the value will be missing in the output.
*
* @category PropertySignature
* @since 3.10.0
*/
const optionalToRequired = (from, to, options) => makePropertySignature(new PropertySignatureTransformation(new FromPropertySignature(from.ast, true, true, {}, undefined), new ToPropertySignature(to.ast, false, true, {}, undefined), o => option_.some(options.decode(o)), option_.flatMap(options.encode)));
/**
* Converts an optional property to a required one through a transformation `Type -> Option`.
*
* - `decode`: `none` as return value means the value will be missing in the output.
* - `encode`: `none` as argument means the value is missing in the input.
*
* @category PropertySignature
* @since 3.10.0
*/
exports.optionalToRequired = optionalToRequired;
const requiredToOptional = (from, to, options) => makePropertySignature(new PropertySignatureTransformation(new FromPropertySignature(from.ast, false, true, {}, undefined), new ToPropertySignature(to.ast, true, true, {}, undefined), option_.flatMap(options.decode), o => option_.some(options.encode(o))));
/**
* Converts an optional property to another optional property through a transformation `Option -> Option`.
*
* - `decode`:
* - `none` as argument means the value is missing in the input.
* - `none` as return value means the value will be missing in the output.
* - `encode`:
* - `none` as argument means the value is missing in the input.
* - `none` as return value means the value will be missing in the output.
*
* @category PropertySignature
* @since 3.10.0
*/
exports.requiredToOptional = requiredToOptional;
const optionalToOptional = (from, to, options) => makePropertySignature(new PropertySignatureTransformation(new FromPropertySignature(from.ast, true, true, {}, undefined), new ToPropertySignature(to.ast, true, true, {}, undefined), options.decode, options.encode));
exports.optionalToOptional = optionalToOptional;
const optionalPropertySignatureAST = (self, options) => {
const isExact = options?.exact;
const defaultValue = options?.default;
const isNullable = options?.nullable;
const asOption = options?.as == "Option";
const asOptionEncode = options?.onNoneEncoding ? option_.orElse(options.onNoneEncoding) : _Function.identity;
if (isExact) {
if (defaultValue) {
if (isNullable) {
return withConstructorDefault(optionalToRequired(NullOr(self), typeSchema(self), {
decode: option_.match({
onNone: defaultValue,
onSome: a => a === null ? defaultValue() : a
}),
encode: option_.some
}), defaultValue).ast;
} else {
return withConstructorDefault(optionalToRequired(self, typeSchema(self), {
decode: option_.match({
onNone: defaultValue,
onSome: _Function.identity
}),
encode: option_.some
}), defaultValue).ast;
}
} else if (asOption) {
if (isNullable) {
return optionalToRequired(NullOr(self), OptionFromSelf(typeSchema(self)), {
decode: option_.filter(Predicate.isNotNull),
encode: asOptionEncode
}).ast;
} else {
return optionalToRequired(self, OptionFromSelf(typeSchema(self)), {
decode: _Function.identity,
encode: _Function.identity
}).ast;
}
} else {
if (isNullable) {
return optionalToOptional(NullOr(self), typeSchema(self), {
decode: option_.filter(Predicate.isNotNull),
encode: _Function.identity
}).ast;
} else {
return new PropertySignatureDeclaration(self.ast, true, true, {}, undefined);
}
}
} else {
if (defaultValue) {
if (isNullable) {
return withConstructorDefault(optionalToRequired(NullishOr(self), typeSchema(self), {
decode: option_.match({
onNone: defaultValue,
onSome: a => a == null ? defaultValue() : a
}),
encode: option_.some
}), defaultValue).ast;
} else {
return withConstructorDefault(optionalToRequired(UndefinedOr(self), typeSchema(self), {
decode: option_.match({
onNone: defaultValue,
onSome: a => a === undefined ? defaultValue() : a
}),
encode: option_.some
}), defaultValue).ast;
}
} else if (asOption) {
if (isNullable) {
return optionalToRequired(NullishOr(self), OptionFromSelf(typeSchema(self)), {
decode: option_.filter(a => a != null),
encode: asOptionEncode
}).ast;
} else {
return optionalToRequired(UndefinedOr(self), OptionFromSelf(typeSchema(self)), {
decode: option_.filter(Predicate.isNotUndefined),
encode: asOptionEncode
}).ast;
}
} else {
if (isNullable) {
return optionalToOptional(NullishOr(self), UndefinedOr(typeSchema(self)), {
decode: option_.filter(Predicate.isNotNull),
encode: _Function.identity
}).ast;
} else {
return new PropertySignatureDeclaration(UndefinedOr(self).ast, true, true, {}, undefined);
}
}
}
};
/**
* @category PropertySignature
* @since 3.10.0
*/
const optional = self => {
const ast = self.ast === AST.undefinedKeyword || self.ast === AST.neverKeyword ? AST.undefinedKeyword : UndefinedOr(self).ast;
return new PropertySignatureWithFromImpl(new PropertySignatureDeclaration(ast, true, true, {}, undefined), self);
};
/**
* @category PropertySignature
* @since 3.10.0
*/
exports.optional = optional;
const optionalWith = exports.optionalWith = /*#__PURE__*/(0, _Function.dual)(args => isSchema(args[0]), (self, options) => {
return new PropertySignatureWithFromImpl(optionalPropertySignatureAST(self, options), self);
});
const preserveMissingMessageAnnotation = /*#__PURE__*/AST.pickAnnotations([AST.MissingMessageAnnotationId]);
const getDefaultTypeLiteralAST = (fields, records) => {
const ownKeys = util_.ownKeys(fields);
const pss = [];
if (ownKeys.length > 0) {
const from = [];
const to = [];
const transformations = [];
for (let i = 0; i < ownKeys.length; i++) {
const key = ownKeys[i];
const field = fields[key];
if (isPropertySignature(field)) {
const ast = field.ast;
switch (ast._tag) {
case "PropertySignatureDeclaration":
{
const type = ast.type;
const isOptional = ast.isOptional;
const toAnnotations = ast.annotations;
from.push(new AST.PropertySignature(key, type, isOptional, true, preserveMissingMessageAnnotation(ast)));
to.push(new AST.PropertySignature(key, AST.typeAST(type), isOptional, true, toAnnotations));
pss.push(new AST.PropertySignature(key, type, isOptional, true, toAnnotations));
break;
}
case "PropertySignatureTransformation":
{
const fromKey = ast.from.fromKey ?? key;
from.push(new AST.PropertySignature(fromKey, ast.from.type, ast.from.isOptional, true, ast.from.annotations));
to.push(new AST.PropertySignature(key, ast.to.type, ast.to.isOptional, true, ast.to.annotations));
transformations.push(new AST.PropertySignatureTransformation(fromKey, key, ast.decode, ast.encode));
break;
}
}
} else {
from.push(new AST.PropertySignature(key, field.ast, false, true));
to.push(new AST.PropertySignature(key, AST.typeAST(field.ast), false, true));
pss.push(new AST.PropertySignature(key, field.ast, false, true));
}
}
if (array_.isNonEmptyReadonlyArray(transformations)) {
const issFrom = [];
const issTo = [];
for (const r of records) {
const {
indexSignatures,
propertySignatures
} = AST.record(r.key.ast, r.value.ast);
propertySignatures.forEach(ps => {
from.push(ps);
to.push(new AST.PropertySignature(ps.name, AST.typeAST(ps.type), ps.isOptional, ps.isReadonly, ps.annotations));
});
indexSignatures.forEach(is => {
issFrom.push(is);
issTo.push(new AST.IndexSignature(is.parameter, AST.typeAST(is.type), is.isReadonly));
});
}
return new AST.Transformation(new AST.TypeLiteral(from, issFrom, {
[AST.AutoTitleAnnotationId]: "Struct (Encoded side)"
}), new AST.TypeLiteral(to, issTo, {
[AST.AutoTitleAnnotationId]: "Struct (Type side)"
}), new AST.TypeLiteralTransformation(transformations));
}
}
const iss = [];
for (const r of records) {
const {
indexSignatures,
propertySignatures
} = AST.record(r.key.ast, r.value.ast);
propertySignatures.forEach(ps => pss.push(ps));
indexSignatures.forEach(is => iss.push(is));
}
return new AST.TypeLiteral(pss, iss);
};
const lazilyMergeDefaults = (fields, out) => {
const ownKeys = util_.ownKeys(fields);
for (const key of ownKeys) {
const field = fields[key];
if (out[key] === undefined && isPropertySignature(field)) {
const ast = field.ast;
const defaultValue = ast._tag === "PropertySignatureDeclaration" ? ast.defaultValue : ast.to.defaultValue;
if (defaultValue !== undefined) {
out[key] = defaultValue();
}
}
}
return out;
};
function makeTypeLiteralClass(fields, records, ast = getDefaultTypeLiteralAST(fields, records)) {
return class TypeLiteralClass extends make(ast) {
static annotations(annotations) {
return makeTypeLiteralClass(this.fields, this.records, mergeSchemaAnnotations(this.ast, annotations));
}
static fields = {
...fields
};
static records = [...records];
static make = (props, options) => {
const propsWithDefaults = lazilyMergeDefaults(fields, {
...props
});
return getDisableValidationMakeOption(options) ? propsWithDefaults : ParseResult.validateSync(this)(propsWithDefaults);
};
static pick(...keys) {
return Struct(struct_.pick(fields, ...keys));
}
static omit(...keys) {
return Struct(struct_.omit(fields, ...keys));
}
};
}
function Struct(fields, ...records) {
return makeTypeLiteralClass(fields, records);
}
/**
* Returns a property signature that represents a tag.
* A tag is a literal value that is used to distinguish between different types of objects.
* The tag is optional when using the `make` method.
*
* @example
* ```ts
* import * as assert from "node:assert"
* import { Schema } from "effect"
*
* const User = Schema.Struct({
* _tag: Schema.tag("User"),
* name: Schema.String,
* age: Schema.Number
* })
*
* assert.deepStrictEqual(User.make({ name: "John", age: 44 }), { _tag: "User", name: "John", age: 44 })
* ```
*
* @see {@link TaggedStruct}
*
* @since 3.10.0
*/
const tag = tag => Literal(tag).pipe(propertySignature, withConstructorDefault(() => tag));
/**
* A tagged struct is a struct that has a tag property that is used to distinguish between different types of objects.
*
* The tag is optional when using the `make` method.
*
* @example
* ```ts
* import * as assert from "node:assert"
* import { Schema } from "effect"
*
* const User = Schema.TaggedStruct("User", {
* name: Schema.String,
* age: Schema.Number
* })
*
* assert.deepStrictEqual(User.make({ name: "John", age: 44 }), { _tag: "User", name: "John", age: 44 })
* ```
*
* @category constructors
* @since 3.10.0
*/
exports.tag = tag;
const TaggedStruct = (value, fields) => Struct({
_tag: tag(value),
...fields
});
exports.TaggedStruct = TaggedStruct;
function makeRecordClass(key, value, ast) {
return class RecordClass extends makeTypeLiteralClass({}, [{
key,
value
}], ast) {
static annotations(annotations) {
return makeRecordClass(key, value, mergeSchemaAnnotations(this.ast, annotations));
}
static key = key;
static value = value;
};
}
/**
* @category constructors
* @since 3.10.0
*/
const Record = options => makeRecordClass(options.key, options.value);
/**
* @category struct transformations
* @since 3.10.0
*/
exports.Record = Record;
const pick = (...keys) => self => make(AST.pick(self.ast, keys));
/**
* @category struct transformations
* @since 3.10.0
*/
exports.pick = pick;
const omit = (...keys) => self => make(AST.omit(self.ast, keys));
/**
* Given a schema `Schema` and a key `key: K`, this function extracts a specific field from the `A` type,
* producing a new schema that represents a transformation from the `{ readonly [key]: I[K] }` type to `A[K]`.
*
* @example
* ```ts
* import * as Schema from "effect/Schema"
*
* // ---------------------------------------------
* // use case: pull out a single field from a
* // struct through a transformation
* // ---------------------------------------------
*
* const mytable = Schema.Struct({
* column1: Schema.NumberFromString,
* column2: Schema.Number
* })
*
* // const pullOutColumn: S.Schema