service-use.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { Context, Effect } from "effect"
  2. type EffectMethod = (...args: ReadonlyArray<never>) => Effect.Effect<unknown, unknown, unknown>
  3. type ServiceUse<Identifier, Shape> = {
  4. readonly [Key in keyof Shape as Shape[Key] extends EffectMethod ? Key : never]: Shape[Key] extends (
  5. ...args: infer Args
  6. ) => infer Return
  7. ? Args extends ReadonlyArray<unknown>
  8. ? Return extends Effect.Effect<infer A, infer E, infer R>
  9. ? (...args: Args) => Effect.Effect<A, E, R | Identifier>
  10. : never
  11. : never
  12. : never
  13. }
  14. export const serviceUse = <Identifier, Shape>(tag: Context.Service<Identifier, Shape>) => {
  15. const cache = new Map<string, (...args: unknown[]) => Effect.Effect<unknown, unknown, unknown>>()
  16. // This is the only dynamic boundary: TypeScript knows the accessor shape,
  17. // but Proxy property names are runtime values.
  18. const access = new Proxy(
  19. {},
  20. {
  21. get: (_, key) => {
  22. if (typeof key !== "string") return undefined
  23. const cached = cache.get(key)
  24. if (cached) return cached
  25. const accessor = (...args: unknown[]) =>
  26. tag.use((service) => {
  27. // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- Proxy keys are checked at runtime.
  28. const method = service[key as keyof Shape]
  29. if (typeof method !== "function") return Effect.die(new Error(`Service method not found: ${key}`))
  30. // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- ServiceUse exposes only Effect-returning methods.
  31. return (method as (...args: unknown[]) => Effect.Effect<unknown, unknown, unknown>)(...args)
  32. })
  33. cache.set(key, accessor)
  34. return accessor
  35. },
  36. },
  37. )
  38. // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- Proxy implements the mapped accessor surface lazily.
  39. return access as ServiceUse<Identifier, Shape>
  40. }