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

userInputAnswers.ts

65 lines2.6 KB

1import * as Option from "effect/Option";
2import * as Predicate from "effect/Predicate";
3import * as Schema from "effect/Schema";
4​
5import type { UserInputQuestion } from "@t3tools/contracts";
6​
7// Older request rows can carry less than the current contract, so each
8// question decodes on its own and a malformed one does not hide the rest.
9// Question ids are the answer keys, so they are read as-is and never trimmed.
10const decodeAskedQuestion = Schema.decodeUnknownOption(
11 Schema.Struct({ id: Schema.String, header: Schema.String, question: Schema.String }),
12);
13const decodeAskedQuestions = Schema.decodeUnknownOption(
14 Schema.Struct({ questions: Schema.Array(Schema.Unknown) }),
15);
16​
17type AskedQuestion = Pick<UserInputQuestion, "id" | "header" | "question">;
18​
19/** The questions a `user-input.requested` payload asked, in order. */
20export function readUserInputQuestions(payload: unknown): ReadonlyArray<AskedQuestion> {
21 return Option.match(decodeAskedQuestions(payload), {
22 onNone: () => [],
23 onSome: ({ questions }) =>
24 questions.flatMap((question) => Option.toArray(decodeAskedQuestion(question))),
25 });
27​
28function formatAnswer(value: unknown): string | undefined {
29 if (Array.isArray(value)) {
30 const parts = value.map(formatAnswer).filter(Predicate.isString);
31 return parts.length > 0 ? parts.join(", ") : undefined;
32 }
33 if (Predicate.isString(value)) return value.trim() || undefined;
34 if (Predicate.isNumber(value) || Predicate.isBoolean(value)) return String(value);
35 if (Predicate.isObject(value)) return JSON.stringify(value);
36 return undefined;
38​
39/**
40 * The submitted answers as one `Question: answer` line per question, in the
41 * order they were asked; multi-select answers join with commas. Answers whose
42 * question is unknown (older history, keys the provider chose) still list
43 * under their key so nothing the user typed goes missing.
44 */
45export function formatUserInputAnswers(
46 questions: ReadonlyArray<AskedQuestion>,
47 answers: unknown,
48): string | undefined {
49 if (!Predicate.isObject(answers)) return undefined;
50 const lines: string[] = [];
51 const seen = new Set<string>();
52 for (const question of questions) {
53 seen.add(question.id);
54 const answer = formatAnswer(answers[question.id]);
55 if (answer === undefined) continue;
56 const label = question.header || question.question || question.id;
57 lines.push(`${label}: ${answer}`);
58 }
59 for (const [key, value] of Object.entries(answers)) {
60 if (seen.has(key)) continue;
61 const answer = formatAnswer(value);
62 if (answer !== undefined) lines.push(`${key}: ${answer}`);
63 }
64 return lines.length > 0 ? lines.join("\n") : undefined;