Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

userInput.ts

80 lines2.7 KB

1import {
2 type OrchestrationV2TurnItem,
3 type OrchestrationV2UserInputQuestion,
4 type UserInputAttachmentAnswerPayload,
5} from "@t3tools/contracts";
6import { composerContextProviderTextForDisplay } from "@t3tools/shared/composerContextReferences";
7​
8function record(value: unknown): Record<string, unknown> | undefined {
9 return value !== null && typeof value === "object" && !Array.isArray(value)
10 ? (value as Record<string, unknown>)
11 : undefined;
13​
14type AnsweredQuestion = Pick<OrchestrationV2UserInputQuestion, "id" | "options">;
15​
16export function userInputRequestQuestions(
17 item: OrchestrationV2TurnItem | undefined,
18): ReadonlyArray<AnsweredQuestion> | undefined {
19 return item?.type === "user_input_request" ? item.questions : undefined;
21​
22export function getQuestionAnswerText(
23 value: unknown,
24 question?: Pick<AnsweredQuestion, "options">,
25): string {
26 if (typeof value === "string") {
27 // Options with an explicit value were submitted as that value, not their label.
28 const option = question?.options.find((candidate) => candidate.value === value);
29 // Answers holding context chips are stored in provider form.
30 return option ? option.label : composerContextProviderTextForDisplay(value);
31 }
32 if (Array.isArray(value)) {
33 return value
34 .map((entry) => getQuestionAnswerText(entry, question))
35 .filter(Boolean)
36 .join(", ");
37 }
38 const nested = record(value);
39 return nested ? getQuestionAnswerText(nested.answers, question) : "";
41​
42export function getQuestionTextPreview(answer: UserInputAttachmentAnswerPayload): string {
43 return Object.values(answer.questionTextById ?? {})
44 .map((text) => text.replace(/\s+/g, " ").trim())
45 .filter(Boolean)
46 .join(" · ");
48​
49export function getQuestionAnswerPreview(
50 answer: UserInputAttachmentAnswerPayload,
51 questions?: ReadonlyArray<AnsweredQuestion>,
52): string {
53 const answers = Object.entries(answer.answers)
54 .map(([questionId, value]) =>
55 getQuestionAnswerText(
56 value,
57 questions?.find((question) => question.id === questionId),
58 ),
59 )
60 .filter(Boolean);
61 const attachments = Object.values(answer.attachmentsByQuestionId)
62 .flat()
63 .map((attachment) => attachment.name);
64 return (
65 answers.length > 0
66 ? answers.join(" · ")
67 : attachments.length > 0
68 ? attachments.join(", ")
69 : Object.values(answer.questionTextById ?? {}).join(" · ")
70 )
71 .replace(/\s+/g, " ")
72 .trim();
74​
75export function hasQuestionAnswer(answer: UserInputAttachmentAnswerPayload): boolean {
76 return (
77 Object.values(answer.answers).some((value) => getQuestionAnswerText(value)) ||
78 Object.values(answer.attachmentsByQuestionId).some((attachments) => attachments.length > 0)
79 );