schema.ts 4.2 KB

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