Repository navigation
Expand file tree
/
Copy pathapi.ts
More file actions
304 lines (287 loc) · 10.4 KB
/
Copy pathapi.ts
File metadata and controls
304 lines (287 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// The four flag APIs: which ones are configured, loading flags, and toggling one in an environment.
import {
environmentStates,
type EnvState,
type Flag,
fromFlagsmith,
fromGrowthBook,
fromLaunchDarkly,
fromUnleash,
type FsEnvironment,
type FsFeature,
type FsFeatureState,
type GbEnvironment,
type GbFeature,
type LdEnvironment,
type LdFlag,
ldTogglePatch,
normalizeUrl,
parseList,
type Provider,
PROVIDER_NAMES,
PROVIDERS,
results,
type UnleashEnvironment,
type UnleashFeature,
} from "./lib.ts";
export interface Prefs {
launchdarklyToken?: string;
launchdarklyProject?: string;
unleashUrl?: string;
unleashToken?: string;
unleashProject?: string;
flagsmithKey?: string;
flagsmithProject?: string;
flagsmithUrl?: string;
growthbookKey?: string;
growthbookUrl?: string;
}
export interface Account {
provider: Provider;
base: string;
headers: Record<string, string>;
projects: string[];
}
export const TOKEN_PAGES: Record<Provider, string> = {
launchdarkly: "https://app.launchdarkly.com/settings/authorization",
unleash: "https://docs.getunleash.io/reference/api-tokens-and-client-keys",
flagsmith: "https://app.flagsmith.com/organisation-settings",
growthbook: "https://app.growthbook.io/settings/keys",
};
export class SetupError extends Error {
constructor(readonly provider: Provider, message: string) {
super(message);
}
}
const trim = (v: unknown) => String(v ?? "").trim();
function url(provider: Provider, input: string): string | SetupError {
try {
return normalizeUrl(input);
} catch {
return new SetupError(provider, `“${input}” is not a web address: fix the ${PROVIDER_NAMES[provider]} address`);
}
}
/** The providers that are configured; a half-filled one is an error to show. */
export function accounts(p: Prefs): (Account | SetupError)[] {
const out: (Account | SetupError)[] = [];
const ld = trim(p.launchdarklyToken);
if (ld) {
out.push({
provider: "launchdarkly",
base: "https://app.launchdarkly.com/api/v2",
headers: { Authorization: ld },
projects: parseList(p.launchdarklyProject || "default"),
});
}
const unUrl = trim(p.unleashUrl), unToken = trim(p.unleashToken);
if (unUrl || unToken) {
if (!unUrl || !unToken) {
out.push(new SetupError("unleash", `Add the Unleash ${unUrl ? "token" : "address"} in Settings`));
} else {
const base = url("unleash", unUrl);
out.push(
base instanceof SetupError ? base : {
provider: "unleash",
base: base.replace(/\/api$/, ""),
headers: { Authorization: unToken },
projects: parseList(p.unleashProject || "default"),
},
);
}
}
const fsKey = trim(p.flagsmithKey), fsProject = trim(p.flagsmithProject);
if (fsKey || fsProject) {
if (!fsKey || !fsProject) {
out.push(
new SetupError("flagsmith", `Add the Flagsmith ${fsKey ? "project ID" : "organisation API key"} in Settings`),
);
} else {
const base = url("flagsmith", trim(p.flagsmithUrl) || "https://api.flagsmith.com/api/v1");
out.push(
base instanceof SetupError ? base : {
provider: "flagsmith",
base: /\/api\/v1$/.test(base) ? base : `${base}/api/v1`,
headers: { Authorization: `Api-Key ${fsKey}` },
projects: parseList(fsProject),
},
);
}
}
const gbKey = trim(p.growthbookKey);
if (gbKey) {
const base = url("growthbook", trim(p.growthbookUrl) || "https://api.growthbook.io");
out.push(
base instanceof SetupError ? base : {
provider: "growthbook",
base: base.replace(/\/api\/v1$/, ""),
headers: { Authorization: `Bearer ${gbKey}` },
projects: [],
},
);
}
return out.sort((a, b) => PROVIDERS.indexOf(a.provider) - PROVIDERS.indexOf(b.provider));
}
async function call<T>(
a: Account,
path: string,
o: { method?: string; body?: unknown; signal?: AbortSignal; contentType?: string } = {},
): Promise<T> {
const name = PROVIDER_NAMES[a.provider];
let res: Response;
try {
res = await fetch(`${a.base}${path}`, {
method: o.method ?? "GET",
signal: o.signal,
headers: {
...a.headers,
Accept: "application/json",
...(o.body === undefined ? {} : { "Content-Type": o.contentType ?? "application/json" }),
},
body: o.body === undefined ? undefined : JSON.stringify(o.body),
});
} catch (e) {
if (o.signal?.aborted) throw e;
throw new Error(`Can't reach ${name} at ${new URL(a.base).host}: ${(e as Error).message}`);
}
if (res.status === 401) throw new SetupError(a.provider, `${name} rejected the token`);
const text = await res.text();
let body: unknown;
try {
body = text ? JSON.parse(text) : undefined;
} catch {
body = undefined;
}
if (!res.ok) {
const b = body as
| { message?: string; detail?: string; error?: string; details?: { message?: string }[] }
| undefined;
const why = b?.message || b?.detail || b?.error || b?.details?.[0]?.message || "";
if (res.status === 403) throw new Error(`${name} refused it${why ? `: ${why}` : ""}. Check the token's role`);
if (res.status === 404) {
throw new Error(`${name}: not found${why ? ` (${why})` : ""}. Check the project in Settings`);
}
if (res.status === 429) throw new Error(`${name} is rate limiting: try again in a minute`);
throw new Error(`${name} answered ${res.status}${why ? `: ${why}` : ""}`);
}
if (text && body === undefined) throw new Error(`${name} didn't answer with JSON: check the address`);
return body as T;
}
// --- Loading ------------------------------------------------------------------------
async function launchdarkly(a: Account, signal: AbortSignal): Promise<Flag[]> {
const lists = await Promise.all(a.projects.map(async (project) => {
const p = encodeURIComponent(project);
const [envs, flags] = await Promise.all([
call<{ items: LdEnvironment[] }>(a, `/projects/${p}/environments?limit=50`, { signal }).then((r) => r.items)
.catch(() => [] as LdEnvironment[]),
call<{ items: LdFlag[] }>(a, `/flags/${p}?summary=0&limit=100&sort=name`, { signal }),
]);
return flags.items.map((f) => fromLaunchDarkly(project, f, envs));
}));
return lists.flat();
}
async function unleash(a: Account, signal: AbortSignal): Promise<Flag[]> {
const envs = await call<{ environments: UnleashEnvironment[] }>(a, "/api/admin/environments", { signal })
.then((r) => r.environments).catch(() => [] as UnleashEnvironment[]);
const lists = await Promise.all(a.projects.map(async (project) => {
const r = await call<{ features: UnleashFeature[] }>(
a,
`/api/admin/projects/${encodeURIComponent(project)}/features`,
{ signal },
);
return r.features.map((f) => fromUnleash(a.base, project, f, envs));
}));
return lists.flat();
}
async function flagsmith(a: Account, signal: AbortSignal): Promise<Flag[]> {
const lists = await Promise.all(a.projects.map(async (project) => {
const [envs, features, tags] = await Promise.all([
call<FsEnvironment[] | { results: FsEnvironment[] }>(a, `/environments/?project=${encodeURIComponent(project)}`, {
signal,
}).then(results),
call<{ results: FsFeature[] }>(a, `/projects/${encodeURIComponent(project)}/features/?page_size=100`, { signal })
.then(results),
call<{ id: number; label: string }[] | { results: { id: number; label: string }[] }>(
a,
`/projects/${encodeURIComponent(project)}/tags/`,
{ signal },
).then(results).catch(() => []),
]);
const states = await Promise.all(envs.map(async (env) => ({
env,
states: environmentStates(
await call<{ results: FsFeatureState[] } | FsFeatureState[]>(
a,
`/environments/${encodeURIComponent(env.api_key)}/featurestates/?page_size=999`,
{ signal },
).then(results).catch(() => [] as FsFeatureState[]),
),
})));
const names = new Map(tags.map((t) => [t.id, t.label]));
return features.map((f) => fromFlagsmith(a.base, project, f, states, names));
}));
return lists.flat();
}
async function growthbook(a: Account, signal: AbortSignal): Promise<Flag[]> {
const envs = await call<{ environments: GbEnvironment[] }>(a, "/api/v1/environments", { signal })
.then((r) => r.environments).catch(() => [] as GbEnvironment[]);
const features: GbFeature[] = [];
let offset = 0;
for (let i = 0; i < 5; i++) {
const r = await call<{ features: GbFeature[]; hasMore?: boolean; nextOffset?: number }>(
a,
`/api/v1/features?limit=100&offset=${offset}`,
{ signal },
);
features.push(...r.features);
if (!r.hasMore || r.nextOffset === undefined) break;
offset = r.nextOffset;
}
return features.map((f) => fromGrowthBook(a.base, f, envs));
}
export function loadFlags(a: Account, signal: AbortSignal): Promise<Flag[]> {
switch (a.provider) {
case "launchdarkly":
return launchdarkly(a, signal);
case "unleash":
return unleash(a, signal);
case "flagsmith":
return flagsmith(a, signal);
case "growthbook":
return growthbook(a, signal);
}
}
// --- Toggling -----------------------------------------------------------------------
/** Turns the flag on or off (the opposite of `env.on`) in one environment. */
export async function toggle(a: Account, f: Flag, env: EnvState): Promise<void> {
const on = !env.on;
switch (a.provider) {
case "launchdarkly":
await call(a, `/flags/${encodeURIComponent(f.project)}/${encodeURIComponent(f.key)}`, {
method: "PATCH",
body: { comment: "Toggled from Backslash", patch: ldTogglePatch(env.key, on) },
});
return;
case "unleash":
await call(
a,
`/api/admin/projects/${encodeURIComponent(f.project)}/features/${encodeURIComponent(f.key)}/environments/${
encodeURIComponent(env.key)
}/${on ? "on" : "off"}`,
{ method: "POST", body: {} },
);
return;
case "flagsmith":
if (env.ref === undefined) throw new Error(`No Flagsmith state for ${f.name} in ${env.name}`);
await call(a, `/environments/${encodeURIComponent(env.key)}/featurestates/${env.ref}/`, {
method: "PATCH",
body: { enabled: on },
});
return;
case "growthbook":
await call(a, `/api/v1/features/${encodeURIComponent(f.key)}/toggle`, {
method: "POST",
body: { environments: { [env.key]: on }, reason: "Toggled from Backslash" },
});
return;
}
}