-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
define-integration.ts
57 lines (51 loc) · 1.49 KB
/
define-integration.ts
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
import type { AstroIntegration } from "../@types/astro.js";
import { AstroError, AstroErrorData, errorMap } from "../core/errors/index.js";
import { z } from "../../zod.mjs";
type AstroIntegrationSetupFn<Options extends z.ZodTypeAny> = (params: {
name: string;
options: z.output<Options>;
}) => Omit<AstroIntegration, "name">;
/** TODO: */
export const defineIntegration = <
TOptionsSchema extends z.ZodTypeAny = z.ZodNever,
TSetup extends
AstroIntegrationSetupFn<TOptionsSchema> = AstroIntegrationSetupFn<TOptionsSchema>,
>({
name,
optionsSchema,
setup,
}: {
name: string;
optionsSchema?: TOptionsSchema;
setup: TSetup;
}): ((
...args: [z.input<TOptionsSchema>] extends [never]
? []
: undefined extends z.input<TOptionsSchema>
? [options?: z.input<TOptionsSchema>]
: [options: z.input<TOptionsSchema>]
) => AstroIntegration & ReturnType<TSetup>) => {
return (...args): AstroIntegration & ReturnType<TSetup> => {
const parsedOptions = (optionsSchema ?? z.never().optional()).safeParse(
args[0],
{
errorMap,
},
);
if (!parsedOptions.success) {
throw new AstroError({
...AstroErrorData.AstroIntegrationInvalidOptions,
message: AstroErrorData.AstroIntegrationInvalidOptions.message(
name,
parsedOptions.error.issues.map((i) => i.message).join('\n')
),
});
}
const options = parsedOptions.data as z.output<TOptionsSchema>;
const integration = setup({ name, options }) as ReturnType<TSetup>;
return {
name,
...integration,
};
};
};