schema.ts 4.4 KB

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