feat: add WhatsApp ID normalization utility
parent
5f457097b5
commit
be653f0355
@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Normalizes a WhatsApp ID by removing the domain part (@s.whatsapp.net, @g.us)
|
||||
* and any participant identifier (:12).
|
||||
* Handles potential variations like participant IDs in group messages.
|
||||
*
|
||||
* Examples:
|
||||
* - '1234567890@s.whatsapp.net' -> '1234567890'
|
||||
* - '1234567890-1234567890@g.us' -> '1234567890-1234567890'
|
||||
* - '1234567890:12@s.whatsapp.net' -> '1234567890' (handles participant format)
|
||||
* - 'status_me@broadcast' -> 'status_me' (handles status broadcast)
|
||||
*
|
||||
* @param id The raw WhatsApp ID string. Can be null or undefined.
|
||||
* @returns The normalized ID string, or null if the input is null/undefined or invalid after normalization.
|
||||
*/
|
||||
export function normalizeWhatsAppId(id: string | null | undefined): string | null {
|
||||
if (!id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Remove domain part (@s.whatsapp.net, @g.us, @broadcast etc.)
|
||||
let normalized = id.split('@')[0];
|
||||
|
||||
// Handle potential participant format like '1234567890:12' by taking the part before ':'
|
||||
normalized = normalized.split(':')[0];
|
||||
|
||||
// Basic validation: should contain alphanumeric characters, possibly hyphens for group IDs
|
||||
// Allows simple numbers, group IDs with hyphens, and potentially status_me
|
||||
if (!/^[a-zA-Z0-9_-]+$/.test(normalized)) {
|
||||
console.warn(`[normalizeWhatsAppId] Invalid characters found in WhatsApp ID after normalization: ${id} -> ${normalized}`);
|
||||
// Return null for clearly invalid IDs after normalization
|
||||
return null;
|
||||
}
|
||||
|
||||
// Prevent empty strings after normalization
|
||||
if (normalized.length === 0) {
|
||||
console.warn(`[normalizeWhatsAppId] Empty string resulted from normalization: ${id}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a given raw JID represents a group chat.
|
||||
*
|
||||
* @param jid The raw JID string (e.g., '123-456@g.us').
|
||||
* @returns True if the JID ends with '@g.us', false otherwise.
|
||||
*/
|
||||
export function isGroupId(jid: string | null | undefined): boolean {
|
||||
return !!jid && jid.endsWith('@g.us');
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a given raw JID represents a standard user chat.
|
||||
*
|
||||
* @param jid The raw JID string (e.g., '123456@s.whatsapp.net').
|
||||
* @returns True if the JID ends with '@s.whatsapp.net', false otherwise.
|
||||
*/
|
||||
export function isUserJid(jid: string | null | undefined): boolean {
|
||||
return !!jid && jid.endsWith('@s.whatsapp.net');
|
||||
}
|
Loading…
Reference in New Issue