schema.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import { Option, Schema, SchemaGetter } from "effect"
  2. /**
  3. * Integer greater than zero.
  4. */
  5. export const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0))
  6. /**
  7. * Integer greater than or equal to zero.
  8. */
  9. export const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
  10. /**
  11. * Optional public JSON field that can hold explicit `undefined` on the type
  12. * side but encodes it as an omitted key, matching legacy `JSON.stringify`.
  13. */
  14. export const optionalOmitUndefined = <S extends Schema.Top>(schema: S) =>
  15. Schema.optionalKey(schema).pipe(
  16. Schema.decodeTo(Schema.optional(schema), {
  17. decode: SchemaGetter.passthrough({ strict: false }),
  18. encode: SchemaGetter.transformOptional(Option.filter((value) => value !== undefined)),
  19. }),
  20. )
  21. /**
  22. * Strip `readonly` from a nested type. Stand-in for `effect`'s `Types.DeepMutable`
  23. * until `effect:core/x228my` ("Types.DeepMutable widens unknown to `{}`") lands.
  24. *
  25. * The upstream version falls through `unknown` into `{ -readonly [K in keyof T]: ... }`
  26. * where `keyof unknown = never`, so `unknown` collapses to `{}`. This local
  27. * version gates the object branch on `extends object` (which `unknown` does
  28. * not) so `unknown` passes through untouched.
  29. *
  30. * Primitive bailout matches upstream — without it, branded strings like
  31. * `string & Brand<"SessionID">` fall into the object branch and get their
  32. * prototype methods walked.
  33. *
  34. * Tuple branch preserves readonly tuples (e.g. `ConfigPlugin.Spec`'s
  35. * `readonly [string, Options]`); the general array branch would otherwise
  36. * widen them to unbounded arrays.
  37. */
  38. // eslint-disable-next-line @typescript-eslint/ban-types
  39. export type DeepMutable<T> = T extends string | number | boolean | bigint | symbol | Function
  40. ? T
  41. : T extends readonly [unknown, ...unknown[]]
  42. ? { -readonly [K in keyof T]: DeepMutable<T[K]> }
  43. : T extends readonly (infer U)[]
  44. ? DeepMutable<U>[]
  45. : T extends object
  46. ? { -readonly [K in keyof T]: DeepMutable<T[K]> }
  47. : T
  48. /**
  49. * Attach static methods to a schema object. Designed to be used with `.pipe()`:
  50. *
  51. * @example
  52. * export const Foo = fooSchema.pipe(
  53. * withStatics((schema) => ({
  54. * zero: schema.make(0),
  55. * from: Schema.decodeUnknownOption(schema),
  56. * }))
  57. * )
  58. */
  59. export const withStatics =
  60. <S extends object, M extends Record<string, unknown>>(methods: (schema: S) => M) =>
  61. (schema: S): S & M =>
  62. Object.assign(schema, methods(schema))
  63. /**
  64. * Nominal wrapper for scalar types. The class itself is a valid schema —
  65. * pass it directly to `Schema.decode`, `Schema.decodeEffect`, etc.
  66. *
  67. * Overrides `~type.make` on the derived `Schema.Opaque` so `Schema.Schema.Type`
  68. * of a field using this newtype resolves to `Self` rather than the underlying
  69. * branded phantom. Without that override, passing a class instance to code
  70. * typed against `Schema.Schema.Type<FieldSchema>` would require a cast even
  71. * though the values are structurally equivalent at runtime.
  72. *
  73. * @example
  74. * class QuestionID extends Newtype<QuestionID>()("QuestionID", Schema.String) {
  75. * static make(id: string): QuestionID {
  76. * return this.make(id)
  77. * }
  78. * }
  79. *
  80. * Schema.decodeEffect(QuestionID)(input)
  81. */
  82. export function Newtype<Self>() {
  83. return <const Tag extends string, S extends Schema.Top>(tag: Tag, schema: S) => {
  84. abstract class Base {
  85. declare readonly _newtype: Tag
  86. static make(value: Schema.Schema.Type<S>): Self {
  87. return value as unknown as Self
  88. }
  89. }
  90. Object.setPrototypeOf(Base, schema)
  91. return Base as unknown as (abstract new (_: never) => { readonly _newtype: Tag }) & {
  92. readonly make: (value: Schema.Schema.Type<S>) => Self
  93. } & Omit<Schema.Opaque<Self, S, {}>, "make" | "~type.make"> & {
  94. readonly "~type.make": Self
  95. }
  96. }
  97. }