Files
Genarrative/src/services/customWorldRoleReferences.ts
2026-04-27 22:50:18 +08:00

71 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type {
CustomWorldRoleProfile,
} from '../types';
type CustomWorldRoleReferenceProfile = {
playableNpcs: CustomWorldRoleProfile[];
storyNpcs: CustomWorldRoleProfile[];
};
function normalizeRoleReference(value: string | null | undefined) {
return (value ?? '')
.trim()
.replace(/^character-npc[-:]/i, '')
.replace(/^(playable|story|role|npc)[-_:]/i, '')
.replace(/\s+/g, '')
.replace(/[(].*?[)]/g, '');
}
function getRoleReferenceAliases(role: CustomWorldRoleProfile) {
return [
role.id,
role.name,
role.title,
`${role.name}${role.title}`,
`${role.title}${role.name}`,
`${role.role}${role.name}`,
`${role.name}${role.role}`,
]
.map(normalizeRoleReference)
.filter(Boolean);
}
export function findCustomWorldRoleByReference(
profile: CustomWorldRoleReferenceProfile | null | undefined,
reference: string | null | undefined,
) {
const normalizedReference = normalizeRoleReference(reference);
if (!profile || !normalizedReference) {
return null;
}
const roles = [...profile.storyNpcs, ...profile.playableNpcs];
return (
roles.find((role) =>
getRoleReferenceAliases(role).includes(normalizedReference),
) ?? null
);
}
export function resolveCustomWorldRoleIdReference(
profile: CustomWorldRoleReferenceProfile | null | undefined,
reference: string | null | undefined,
) {
const role = findCustomWorldRoleByReference(profile, reference);
return role?.id ?? reference?.trim() ?? '';
}
export function resolveCustomWorldRoleIdReferences(
profile: CustomWorldRoleReferenceProfile | null | undefined,
references: Array<string | null | undefined>,
) {
return [
...new Set(
references
.map((reference) => resolveCustomWorldRoleIdReference(profile, reference))
.map((reference) => reference.trim())
.filter(Boolean),
),
];
}