40 lines
1.3 KiB
TypeScript
40 lines
1.3 KiB
TypeScript
import type { ActivityItem } from './types.js';
|
|
|
|
const INTERNAL_REDDIT_ID = /@?t2_[a-z0-9]+(?::reddit\.com)?/gi;
|
|
|
|
export interface RedditIdentityResolver {
|
|
resolveSenderDisplay(identity: string): string;
|
|
}
|
|
|
|
function isInternalIdentity(value: string): boolean {
|
|
return value === 'unknown' || value.startsWith('t2_') || /^@t2_[^:]+:/i.test(value);
|
|
}
|
|
|
|
export function resolveRedditUsername(
|
|
identity: string | null | undefined,
|
|
resolver?: RedditIdentityResolver,
|
|
): string | null {
|
|
if (!identity) return null;
|
|
const candidate = resolver?.resolveSenderDisplay(identity) ?? identity;
|
|
if (isInternalIdentity(candidate)) return null;
|
|
return candidate.replace(/^\/?u\//i, '');
|
|
}
|
|
|
|
export function redactInternalRedditIds(message: string, username?: string | null): string {
|
|
return message
|
|
.replace(/u\/@?t2_[a-z0-9]+(?::reddit\.com)?/gi, username ? `u/${username}` : 'Reddit user')
|
|
.replace(INTERNAL_REDDIT_ID, username ?? 'Reddit user');
|
|
}
|
|
|
|
export function presentActivityItem(
|
|
item: ActivityItem,
|
|
resolver?: RedditIdentityResolver,
|
|
): ActivityItem {
|
|
const recipient = resolveRedditUsername(item.recipient, resolver);
|
|
return {
|
|
...item,
|
|
message: redactInternalRedditIds(item.message, recipient),
|
|
...(recipient ? { recipient } : { recipient: undefined }),
|
|
};
|
|
}
|