mailer/src/contact.ts

80 lines
1.8 KiB
TypeScript
Raw Normal View History

import accounts from '../config/account.json' with { type: 'json' }
import dkim from '../config/dkim.json' with { type: 'json' }
2024-03-28 22:32:46 +01:00
export type AddressString = `${string}@${string}.${string}`
2024-03-28 22:32:46 +01:00
export class Contact {
#name: string
#address: AddressString
2024-03-28 22:32:46 +01:00
constructor(
{ name, address }: {
name: string
address: AddressString
2024-03-28 22:32:46 +01:00
},
) {
this.#name = name
this.#address = address
}
static expand(shortName: string): Contact {
if (!(shortName in accounts)) {
2024-03-28 22:32:46 +01:00
throw new Error('unknown short name contact')
}
const { name, address } = accounts[shortName as keyof typeof accounts]
2024-03-28 22:32:46 +01:00
2024-04-04 17:11:32 +02:00
if (typeof name !== 'string') {
2024-03-28 22:32:46 +01:00
throw new SyntaxError(
`missing key "name" in contact short name config for "${shortName}"`,
)
}
2024-04-04 17:11:32 +02:00
if (typeof address !== 'string') {
2024-03-28 22:32:46 +01:00
throw new SyntaxError(
`missing key "address" in contact short name config for "${shortName}"`,
)
}
const addressRegExp = new RegExp(String.raw`\w+@(\w+\.)?${dkim.domainName}`)
if (!(addressRegExp.test(address))) {
2024-03-28 22:32:46 +01:00
throw new SyntaxError(
`invalid "address" in contact short name config for "${shortName}"`,
)
}
//@ts-ignore checked against regex
return new Contact({ name, address })
}
static fromString(raw: string): Contact {
const [_, name, address] =
raw.match(/(.*)<(\S+@\S+\.\S+)>/)?.map((match) => match.trim()) ?? []
if (typeof address !== 'string') {
throw new Error('address is empty')
}
//@ts-ignore checked against regex
return new Contact({ name, address })
}
toString(): string {
return `${this.#name} <${this.#address}>`
}
toJSON(): { name: string; address: AddressString } {
2024-03-28 22:32:46 +01:00
return {
name: this.#name,
address: this.#address,
} as const
}
get name(): string {
2024-03-28 22:32:46 +01:00
return this.#name
}
get address(): AddressString {
2024-03-28 22:32:46 +01:00
return this.#address
}
}