All files / src utils.ts

95.65% Statements 22/23
91.66% Branches 11/12
100% Functions 9/9
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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        5x           6x 2x         3x 2x       13x       10x 10x 10x 2x       3x 3x 3x         2x 2x 2x 2x       833x     5x  
import fs from "node:fs";
import os from "node:os";
 
export async function ensureDir(dir: string) {
	await fs.promises.mkdir(dir, { recursive: true });
}
 
export type Provider = "twilio" | "web";
 
export function assertProvider(input: string): asserts input is Provider {
	if (input !== "twilio" && input !== "web") {
		throw new Error("Provider must be 'twilio' or 'web'");
	}
}
 
export function normalizePath(p: string): string {
	if (!p.startsWith("/")) return `/${p}`;
	return p;
}
 
export function withWhatsAppPrefix(number: string): string {
	return number.startsWith("whatsapp:") ? number : `whatsapp:${number}`;
}
 
export function normalizeE164(number: string): string {
	const withoutPrefix = number.replace(/^whatsapp:/, "").trim();
	const digits = withoutPrefix.replace(/[^\d+]/g, "");
	if (digits.startsWith("+")) return `+${digits.slice(1)}`;
	return `+${digits}`;
}
 
export function toWhatsappJid(number: string): string {
	const e164 = normalizeE164(number);
	const digits = e164.replace(/\D/g, "");
	return `${digits}@s.whatsapp.net`;
}
 
export function jidToE164(jid: string): string | null {
	// Convert a WhatsApp JID (with optional device suffix, e.g. 1234:1@s.whatsapp.net) back to +1234.
	const match = jid.match(/^(\d+)(?::\d+)?@s\.whatsapp\.net$/);
	Iif (!match) return null;
	const digits = match[1];
	return `+${digits}`;
}
 
export function sleep(ms: number) {
	return new Promise((resolve) => setTimeout(resolve, ms));
}
 
export const CONFIG_DIR = `${os.homedir()}/.warelay`;