dynamic.ts 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. import { Npm } from "../../npm"
  2. import { Effect, Option } from "effect"
  3. import { pathToFileURL } from "url"
  4. import { PluginV2 } from "../../plugin"
  5. export const DynamicProviderPlugin = PluginV2.define({
  6. id: PluginV2.ID.make("dynamic-provider"),
  7. effect: Effect.gen(function* () {
  8. const npm = yield* Npm.Service
  9. return {
  10. "aisdk.sdk": Effect.fn(function* (evt) {
  11. if (evt.sdk) return
  12. const installedPath = evt.package.startsWith("file://")
  13. ? evt.package
  14. : Option.getOrUndefined((yield* npm.add(evt.package).pipe(Effect.orDie)).entrypoint)
  15. if (!installedPath) throw new Error(`Package ${evt.package} has no import entrypoint`)
  16. const mod = yield* Effect.promise(async () => {
  17. return (await import(
  18. installedPath.startsWith("file://") ? installedPath : pathToFileURL(installedPath).href
  19. )) as Record<string, (options: any) => any>
  20. }).pipe(Effect.orDie)
  21. const match = Object.keys(mod).find((name) => name.startsWith("create"))
  22. if (!match) throw new Error(`Package ${evt.package} has no provider factory export`)
  23. evt.sdk = mod[match](evt.options)
  24. }),
  25. }
  26. }),
  27. })