import parser from "parse-address"; export interface Address { number: string; prefix: string; street: string; type: string; city: string; state: string; zip: string; sec_unit_num?: string; sec_unit_type?: string; suffix?: string; addressee?: string; plus4?: string; } export interface AttomAddress { street_name: string; street_dir_prefix: string; street_dir_suffix: string; street_number: string; street_suffix: string; unit_prefix: string; unit_value: string; city: string; state: string; zipcode: string; zipcode_suffix: string; } export function addressParser(address: string): Address | null { return parser.parseLocation(address) as Address | null; } export function constructUSPSAddress(address: string) { const addressLines = []; const parsed = addressParser(address); if (!parsed) { return null; } // Handle the addressee (recipient's name or company name) if (parsed.addressee) { addressLines.push(parsed.addressee.replace(/\s/g, "+")); } // Start constructing the primary street address let streetAddress = parsed.number ? parsed.number : ""; // Handle the prefix (directional e.g., N, S, E, W) if (parsed.prefix) { streetAddress += ` ${parsed.prefix.toUpperCase()}`; } // Handle the main street name if (parsed.street) { streetAddress += ` ${parsed.street.toUpperCase()}`; } // Handle the street type (e.g., St, Ave, Blvd) if (parsed.type) { streetAddress += ` ${parsed.type.toUpperCase()}`; } // Handle the suffix (directional suffix e.g., NE, NW, SE, SW) if (parsed.suffix) { streetAddress += ` ${parsed.suffix.toUpperCase()}`; } // Add the constructed street address to our address lines if (streetAddress.trim()) { addressLines.push(streetAddress.trim().replace(/\s/g, "+")); } // Handle secondary address components like Apt, Suite, etc. if (parsed.sec_unit_type && parsed.sec_unit_num) { addressLines.push( `+${parsed.sec_unit_type.toUpperCase()}+${parsed.sec_unit_num}` ); } // Handle city, state, and ZIP code components if (parsed.city && parsed.state && parsed.zip) { let zipLine = `-${parsed.city.trim().replace(/\s/g, "+")}-${parsed.state .trim() .replace(/\s/g, "+")}-${parsed.zip}`; addressLines.push(zipLine); } return { address: addressLines.join(""), hasCity: !!parsed?.city, zipcode: parsed?.zip, }; }