48 lines
1.4 KiB
TypeScript
48 lines
1.4 KiB
TypeScript
import { identityEnvironmentShape, validateSmtp } from './identity-environment';
|
|
import { z } from 'zod';
|
|
|
|
const schema = z
|
|
.object({
|
|
...identityEnvironmentShape,
|
|
NODE_ENV: z
|
|
.enum(['development', 'test', 'production'])
|
|
.default('development'),
|
|
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
|
|
DATABASE_POOL_SIZE: z.coerce.number().int().min(1).max(50).default(10),
|
|
DATABASE_URL: z.url().refine((value) => /^postgres(ql)?:/.test(value)),
|
|
CORS_ORIGINS: z
|
|
.string()
|
|
.default('')
|
|
.transform((value) =>
|
|
value
|
|
.split(',')
|
|
.map((origin) => origin.trim())
|
|
.filter(Boolean),
|
|
)
|
|
.pipe(
|
|
z.array(
|
|
z.url().refine((value) => {
|
|
if (!URL.canParse(value)) return false;
|
|
const url = new URL(value);
|
|
return (
|
|
['http:', 'https:'].includes(url.protocol) && url.origin === value
|
|
);
|
|
}),
|
|
),
|
|
),
|
|
})
|
|
.superRefine(validateSmtp);
|
|
|
|
export type Environment = z.infer<typeof schema>;
|
|
|
|
export function parseEnvironment(input: NodeJS.ProcessEnv): Environment {
|
|
const result = schema.safeParse(input);
|
|
if (!result.success) {
|
|
const fields = [
|
|
...new Set(result.error.issues.map((issue) => issue.path.join('.'))),
|
|
];
|
|
throw new Error(`Invalid environment configuration: ${fields.join(', ')}`);
|
|
}
|
|
return result.data;
|
|
}
|