1import type { MainRegionRow } from "@distilled.cloud/fly-io/machines";
2import * as machines from "@distilled.cloud/fly-io/machines";
3import * as Data from "effect/Data";
4import * as Effect from "effect/Effect";
5import { resolveOrgSlug } from "./Environment.ts";
6
7export type CatalogKind = "region" | "org";
8
9export class CatalogNotFound extends Data.TaggedError("Fly.CatalogNotFound")<{
10 kind: CatalogKind;
11 ref: string;
12}> {}
13
14const notFound = (kind: CatalogKind, ref: string) =>
15 new CatalogNotFound({ kind, ref });
16
17/**
18 * Current token organization slug (`getCurrentToken` → `tokens[0].org_slug`).
19 * Feeds `listApps({ org_slug })`. Not a resource.
20 */
21export const currentOrgSlug = resolveOrgSlug;
22
23/**
24 * List Fly platform regions via `getRegions`.
25 */
26export const listRegions = Effect.fn(function* () {
27 const { regions } = yield* machines.getRegions({});
28 return regions ?? [];
29});
30
31/**
32 * Resolve a Fly region by code (`iad`, `ord`, `sjc`, …).
33 */
34export const findRegion = (code: string) =>
35 Effect.gen(function* () {
36 const regions = yield* listRegions();
37 const found = regions.find((item) => item.code === code);
38 if (found === undefined) {
39 return yield* notFound("region", code);
40 }
41 return found;
42 });
43
44export type FlyRegion = MainRegionRow;