Hyperlinkv0.8.0-beta.28

Schema

Source effect/Schema.ts:1040191 lines
export interface Date extends instanceOf<globalThis.Date> {
  readonly "Rebuild": Date
}

type DateArbitraryConstraints = FastCheck.DateConstraints & {
  readonly valid?: boolean | undefined
}

function dateArbitraryConstraints<T = globalThis.Date>(
  constraint: Annotations.ToArbitrary.GenerationConstraint | undefined,
  ordered: Annotations.ToArbitrary.OrderedConstraint<T> | undefined,
  base?: DateArbitraryConstraints | undefined,
  toDate?: (value: T) => globalThis.Date
): FastCheck.DateConstraints {
  const out: FastCheck.DateConstraints = { ...base }
  delete (out as any).valid
  if (base?.valid || constraint?.valid) {
    out.noInvalidDate = true
  }
  if (ordered?.minimum !== undefined) {
    const minimum = toDate === undefined ? ordered.minimum as globalThis.Date : toDate(ordered.minimum)
    const nextMin = ordered.exclusiveMinimum ? new globalThis.Date(minimum.getTime() + 1) : minimum
    if (out.min === undefined || nextMin.getTime() > out.min.getTime()) {
      out.min = nextMin
    }
  }
  if (ordered?.maximum !== undefined) {
    const maximum = toDate === undefined ? ordered.maximum as globalThis.Date : toDate(ordered.maximum)
    const nextMax = ordered.exclusiveMaximum ? new globalThis.Date(maximum.getTime() - 1) : maximum
    if (out.max === undefined || nextMax.getTime() < out.max.getTime()) {
      out.max = nextMax
    }
  }
  return out
}

const DateString = String.annotate({ expected: "a string in ISO 8601 format that will be decoded as a Date" })

/**
 * Schema for JavaScript `Date` objects.
 *
 * **When to use**
 *
 * Use to validate in-memory values that must already be JavaScript date
 * objects.
 *
 * **Details**
 *
 * This schema accepts any `Date` instance, including invalid dates. The default
 * JSON serializer encodes valid dates as ISO 8601 strings; invalid dates encode
 * as `"Invalid Date"`.
 *
 * **Example** (Defining a Date schema)
 *
 * ```ts
 * import { Schema } from "effect"
 *
 * Schema.decodeUnknownSync(Schema.Date)(new Date("2024-01-01"))
 * // => Date { 2024-01-01T00:00:00.000Z }
 * ```
 *
 * @see {@link DateValid} for accepting only valid Date instances
 * @see {@link DateFromString} for decoding strings into Date instances
 * @see {@link DateFromMillis} for decoding epoch milliseconds into Date instances
 *
 * @category Date
 * @since 4.0.0
 */
export const Date: Date = instanceOf(
  globalThis.Date,
  {
    typeConstructor: {
      _tag: "Date"
    },
    generation: {
      runtime: `Schema.Date`,
      Type: `globalThis.Date`
    },
    expected: "Date",
    toCodecJson: () =>
      link<globalThis.Date>()(
        DateString,
        SchemaTransformation.dateFromString
      ),
    toArbitrary: () => (fc, ctx) =>
      fc.date(dateArbitraryConstraints(
        ctx?.constraint,
        ctx?.constraint?.ordered?.order === Order.Date ? ctx.constraint.ordered : undefined
      ))
  }
)
Referenced by 5 symbols