psytools 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +189 -0
  3. package/dist/cjs/assessment.d.ts +58 -0
  4. package/dist/cjs/assessment.js +233 -0
  5. package/dist/cjs/errors.d.ts +5 -0
  6. package/dist/cjs/errors.js +13 -0
  7. package/dist/cjs/evaluation.d.ts +10 -0
  8. package/dist/cjs/evaluation.js +102 -0
  9. package/dist/cjs/i18n.d.ts +10 -0
  10. package/dist/cjs/i18n.js +35 -0
  11. package/dist/cjs/index.d.ts +8 -0
  12. package/dist/cjs/index.js +23 -0
  13. package/dist/cjs/inventories/common.d.ts +8 -0
  14. package/dist/cjs/inventories/common.js +47 -0
  15. package/dist/cjs/inventories/dass21.d.ts +11 -0
  16. package/dist/cjs/inventories/dass21.js +288 -0
  17. package/dist/cjs/inventories/gad7.d.ts +10 -0
  18. package/dist/cjs/inventories/gad7.js +121 -0
  19. package/dist/cjs/inventories/index.d.ts +15 -0
  20. package/dist/cjs/inventories/index.js +33 -0
  21. package/dist/cjs/inventories/phq9.d.ts +11 -0
  22. package/dist/cjs/inventories/phq9.js +156 -0
  23. package/dist/cjs/package.json +3 -0
  24. package/dist/cjs/response.d.ts +77 -0
  25. package/dist/cjs/response.js +231 -0
  26. package/dist/cjs/types.d.ts +219 -0
  27. package/dist/cjs/types.js +10 -0
  28. package/dist/esm/assessment.d.ts +58 -0
  29. package/dist/esm/assessment.js +228 -0
  30. package/dist/esm/errors.d.ts +5 -0
  31. package/dist/esm/errors.js +9 -0
  32. package/dist/esm/evaluation.d.ts +10 -0
  33. package/dist/esm/evaluation.js +99 -0
  34. package/dist/esm/i18n.d.ts +10 -0
  35. package/dist/esm/i18n.js +31 -0
  36. package/dist/esm/index.d.ts +8 -0
  37. package/dist/esm/index.js +6 -0
  38. package/dist/esm/inventories/common.d.ts +8 -0
  39. package/dist/esm/inventories/common.js +44 -0
  40. package/dist/esm/inventories/dass21.d.ts +11 -0
  41. package/dist/esm/inventories/dass21.js +285 -0
  42. package/dist/esm/inventories/gad7.d.ts +10 -0
  43. package/dist/esm/inventories/gad7.js +118 -0
  44. package/dist/esm/inventories/index.d.ts +15 -0
  45. package/dist/esm/inventories/index.js +25 -0
  46. package/dist/esm/inventories/phq9.d.ts +11 -0
  47. package/dist/esm/inventories/phq9.js +153 -0
  48. package/dist/esm/response.d.ts +77 -0
  49. package/dist/esm/response.js +227 -0
  50. package/dist/esm/types.d.ts +219 -0
  51. package/dist/esm/types.js +9 -0
  52. package/package.json +64 -0
  53. package/schema/assessment-definition.schema.json +129 -0
  54. package/src/assessment.ts +266 -0
  55. package/src/errors.ts +10 -0
  56. package/src/evaluation.ts +140 -0
  57. package/src/i18n.ts +40 -0
  58. package/src/index.ts +43 -0
  59. package/src/inventories/common.ts +47 -0
  60. package/src/inventories/dass21.ts +291 -0
  61. package/src/inventories/gad7.ts +121 -0
  62. package/src/inventories/index.ts +31 -0
  63. package/src/inventories/phq9.ts +156 -0
  64. package/src/response.ts +263 -0
  65. package/src/types.ts +250 -0
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.phq9 = void 0;
4
+ const common_ts_1 = require("./common.js");
5
+ /**
6
+ * PHQ-9 — Patient Health Questionnaire-9 (depression screening).
7
+ *
8
+ * 9 items, 0–3 frequency scale, total score 0–27. Item 9 raises a
9
+ * `suicidality` flag when answered above 0. The PHQ-9 is in the public
10
+ * domain (Kroenke, Spitzer & Williams, 2001; developed with a grant from
11
+ * Pfizer Inc.). Translations follow published validated versions — verify
12
+ * against the official wording before clinical use.
13
+ */
14
+ exports.phq9 = {
15
+ id: "phq9",
16
+ version: "1.0.0",
17
+ title: {
18
+ en: "Patient Health Questionnaire (PHQ-9)",
19
+ tr: "Hasta Sağlığı Anketi (PHQ-9)",
20
+ de: "Gesundheitsfragebogen für Patienten (PHQ-9)",
21
+ },
22
+ description: {
23
+ en: "A 9-item self-report questionnaire for screening and measuring the severity of depression.",
24
+ tr: "Depresyonu taramak ve şiddetini ölçmek için kullanılan 9 maddelik bir öz bildirim ölçeği.",
25
+ de: "Ein Selbstbeurteilungsfragebogen mit 9 Items zum Screening und zur Schweregradmessung von Depression.",
26
+ },
27
+ instructions: common_ts_1.twoWeekInstructions,
28
+ defaultLocale: "en",
29
+ options: common_ts_1.twoWeekFrequencyOptions,
30
+ questions: [
31
+ {
32
+ id: "phq9-1",
33
+ text: {
34
+ en: "Little interest or pleasure in doing things",
35
+ tr: "İşleri yapmaya karşı çok az ilgi ya da zevk duyma",
36
+ de: "Wenig Interesse oder Freude an Ihren Tätigkeiten",
37
+ },
38
+ },
39
+ {
40
+ id: "phq9-2",
41
+ text: {
42
+ en: "Feeling down, depressed, or hopeless",
43
+ tr: "Kendini kederli, çökkün ya da umutsuz hissetme",
44
+ de: "Niedergeschlagenheit, Schwermut oder Hoffnungslosigkeit",
45
+ },
46
+ },
47
+ {
48
+ id: "phq9-3",
49
+ text: {
50
+ en: "Trouble falling or staying asleep, or sleeping too much",
51
+ tr: "Uykuya dalmada ya da uykuyu sürdürmede güçlük ya da çok fazla uyuma",
52
+ de: "Schwierigkeiten ein- oder durchzuschlafen oder vermehrter Schlaf",
53
+ },
54
+ },
55
+ {
56
+ id: "phq9-4",
57
+ text: {
58
+ en: "Feeling tired or having little energy",
59
+ tr: "Kendini yorgun hissetme ya da çok az enerjiye sahip olma",
60
+ de: "Müdigkeit oder Gefühl, keine Energie zu haben",
61
+ },
62
+ },
63
+ {
64
+ id: "phq9-5",
65
+ text: {
66
+ en: "Poor appetite or overeating",
67
+ tr: "İştahsızlık ya da aşırı yeme",
68
+ de: "Verminderter Appetit oder übermäßiges Bedürfnis zu essen",
69
+ },
70
+ },
71
+ {
72
+ id: "phq9-6",
73
+ text: {
74
+ en: "Feeling bad about yourself — or that you are a failure or have let yourself or your family down",
75
+ tr: "Kendiniz hakkında kötü hissetme — kendinizi başarısız biri olarak görme ya da kendinizi veya ailenizi hayal kırıklığına uğrattığınızı düşünme",
76
+ de: "Schlechte Meinung von sich selbst; Gefühl, ein Versager zu sein oder die Familie enttäuscht zu haben",
77
+ },
78
+ },
79
+ {
80
+ id: "phq9-7",
81
+ text: {
82
+ en: "Trouble concentrating on things, such as reading the newspaper or watching television",
83
+ tr: "Gazete okumak ya da televizyon seyretmek gibi işlere konsantre olmada güçlük",
84
+ de: "Schwierigkeiten, sich auf etwas zu konzentrieren, z. B. beim Zeitunglesen oder Fernsehen",
85
+ },
86
+ },
87
+ {
88
+ id: "phq9-8",
89
+ text: {
90
+ en: "Moving or speaking so slowly that other people could have noticed? Or the opposite — being so fidgety or restless that you have been moving around a lot more than usual",
91
+ tr: "Diğer insanların fark edebileceği kadar yavaş hareket etme ya da yavaş konuşma? Ya da tam tersi — her zamankinden çok daha fazla hareket edecek kadar kıpır kıpır ya da huzursuz olma",
92
+ de: "Waren Ihre Bewegungen oder Ihre Sprache so verlangsamt, dass es auch anderen auffallen würde? Oder waren Sie im Gegenteil „zappelig“ oder ruhelos und hatten dadurch einen stärkeren Bewegungsdrang als sonst?",
93
+ },
94
+ },
95
+ {
96
+ id: "phq9-9",
97
+ text: {
98
+ en: "Thoughts that you would be better off dead or of hurting yourself in some way",
99
+ tr: "Ölmüş olmanın ya da kendinize bir şekilde zarar vermenin daha iyi olacağına dair düşünceler",
100
+ de: "Gedanken, dass Sie lieber tot wären oder sich Leid zufügen möchten",
101
+ },
102
+ },
103
+ ],
104
+ scoring: {
105
+ kind: "sum",
106
+ bands: [
107
+ {
108
+ id: "minimal",
109
+ min: 0,
110
+ max: 4,
111
+ label: { en: "Minimal depression", tr: "Minimal depresyon", de: "Minimale Depression" },
112
+ },
113
+ {
114
+ id: "mild",
115
+ min: 5,
116
+ max: 9,
117
+ label: { en: "Mild depression", tr: "Hafif depresyon", de: "Leichte Depression" },
118
+ },
119
+ {
120
+ id: "moderate",
121
+ min: 10,
122
+ max: 14,
123
+ label: { en: "Moderate depression", tr: "Orta düzeyde depresyon", de: "Mittelgradige Depression" },
124
+ },
125
+ {
126
+ id: "moderately-severe",
127
+ min: 15,
128
+ max: 19,
129
+ label: { en: "Moderately severe depression", tr: "Orta-şiddetli düzeyde depresyon", de: "Mittelschwere Depression" },
130
+ },
131
+ {
132
+ id: "severe",
133
+ min: 20,
134
+ max: 27,
135
+ label: { en: "Severe depression", tr: "Şiddetli depresyon", de: "Schwere Depression" },
136
+ },
137
+ ],
138
+ flags: [
139
+ {
140
+ id: "suicidality",
141
+ questionId: "phq9-9",
142
+ minValue: 1,
143
+ label: {
144
+ en: "Self-harm or suicidal ideation reported (item 9) — requires clinical attention",
145
+ tr: "Kendine zarar verme ya da intihar düşüncesi bildirildi (9. madde) — klinik değerlendirme gerektirir",
146
+ de: "Selbstverletzungs- oder Suizidgedanken angegeben (Item 9) — erfordert klinische Abklärung",
147
+ },
148
+ },
149
+ ],
150
+ },
151
+ meta: {
152
+ reference: "Kroenke, K., Spitzer, R. L., & Williams, J. B. (2001). The PHQ-9: validity of a brief depression severity measure. Journal of General Internal Medicine, 16(9), 606-613.",
153
+ license: "Public domain",
154
+ timeframe: "past 2 weeks",
155
+ },
156
+ };
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,77 @@
1
+ import type { AnswerMap, ResponseData, ResponseStatus, ValidationResult } from "./types.ts";
2
+ import type { Assessment } from "./assessment.ts";
3
+ /**
4
+ * A respondent's answers to one assessment.
5
+ *
6
+ * Supports answering one question at a time (`answer`) or all at once
7
+ * (`answerAll`), validates every value against the assessment's option
8
+ * scale, and becomes immutable once submitted.
9
+ */
10
+ export declare class AssessmentResponse {
11
+ readonly assessment: Assessment;
12
+ readonly respondentId?: string;
13
+ readonly meta?: Record<string, unknown>;
14
+ readonly startedAt: Date;
15
+ private readonly values;
16
+ private submittedTime?;
17
+ private state;
18
+ constructor(assessment: Assessment, options?: {
19
+ respondentId?: string;
20
+ meta?: Record<string, unknown>;
21
+ startedAt?: Date;
22
+ });
23
+ /** Answers keyed by question id (a copy — mutate via `answer`). */
24
+ get answers(): AnswerMap;
25
+ get submittedAt(): Date | undefined;
26
+ get isSubmitted(): boolean;
27
+ /** Current lifecycle state (see `ResponseStatus`). */
28
+ get status(): ResponseStatus;
29
+ /**
30
+ * Answers a single question. Re-answering replaces the previous value.
31
+ * @throws PsytoolsError `already_submitted` | `unknown_question` | `invalid_value`
32
+ */
33
+ answer(questionId: string, value: number): this;
34
+ /**
35
+ * Answers many questions at once. Accepts a map of question id -> value,
36
+ * or an array of values in question order.
37
+ */
38
+ answerAll(answers: AnswerMap | number[]): this;
39
+ /** Removes an answer (e.g. respondent deselects a choice). */
40
+ clearAnswer(questionId: string): this;
41
+ /** Ids of required questions that are not answered yet. */
42
+ unanswered(): string[];
43
+ /** Completion ratio in `[0, 1]` over all questions. */
44
+ progress(): number;
45
+ isComplete(): boolean;
46
+ /**
47
+ * Validates the current answers against the assessment: every answered
48
+ * value must belong to the question's option scale, and (unless
49
+ * `partial`) every required question must be answered.
50
+ */
51
+ validate(options?: {
52
+ partial?: boolean;
53
+ }): ValidationResult;
54
+ /**
55
+ * Validates and finalizes the response. After submission the response is
56
+ * immutable. Pass `allowIncomplete` to submit with unanswered optional-use
57
+ * cases (answered values are still validated).
58
+ * @throws PsytoolsError `already_submitted` | `invalid_response`
59
+ */
60
+ submit(options?: {
61
+ allowIncomplete?: boolean;
62
+ submittedAt?: Date;
63
+ }): this;
64
+ /** Plain serializable data (used by `JSON.stringify`). */
65
+ toJSON(): ResponseData;
66
+ /** Serializes to a JSON string (for DB storage etc.). */
67
+ stringify(space?: number): string;
68
+ /**
69
+ * Restores a response from serialized data, validating every answer
70
+ * against the assessment.
71
+ * @throws PsytoolsError `invalid_json` | `assessment_mismatch` | `unknown_question` | `invalid_value`
72
+ */
73
+ static parse(assessment: Assessment, input: string | ResponseData): AssessmentResponse;
74
+ private checkAnswer;
75
+ private assertMutable;
76
+ private refreshState;
77
+ }
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AssessmentResponse = void 0;
4
+ const errors_ts_1 = require("./errors.js");
5
+ /**
6
+ * A respondent's answers to one assessment.
7
+ *
8
+ * Supports answering one question at a time (`answer`) or all at once
9
+ * (`answerAll`), validates every value against the assessment's option
10
+ * scale, and becomes immutable once submitted.
11
+ */
12
+ class AssessmentResponse {
13
+ assessment;
14
+ respondentId;
15
+ meta;
16
+ startedAt;
17
+ values = new Map();
18
+ submittedTime;
19
+ state = "empty";
20
+ constructor(assessment, options) {
21
+ this.assessment = assessment;
22
+ this.respondentId = options?.respondentId;
23
+ this.meta = options?.meta;
24
+ this.startedAt = options?.startedAt ?? new Date();
25
+ }
26
+ /** Answers keyed by question id (a copy — mutate via `answer`). */
27
+ get answers() {
28
+ return Object.fromEntries(this.values);
29
+ }
30
+ get submittedAt() {
31
+ return this.submittedTime;
32
+ }
33
+ get isSubmitted() {
34
+ return this.submittedTime !== undefined;
35
+ }
36
+ /** Current lifecycle state (see `ResponseStatus`). */
37
+ get status() {
38
+ return this.state;
39
+ }
40
+ /**
41
+ * Answers a single question. Re-answering replaces the previous value.
42
+ * @throws PsytoolsError `already_submitted` | `unknown_question` | `invalid_value`
43
+ */
44
+ answer(questionId, value) {
45
+ this.assertMutable();
46
+ const issue = this.checkAnswer(questionId, value);
47
+ if (issue)
48
+ throw new errors_ts_1.PsytoolsError(issue.code, issue.message);
49
+ this.values.set(questionId, value);
50
+ this.refreshState();
51
+ return this;
52
+ }
53
+ /**
54
+ * Answers many questions at once. Accepts a map of question id -> value,
55
+ * or an array of values in question order.
56
+ */
57
+ answerAll(answers) {
58
+ this.assertMutable();
59
+ const entries = Array.isArray(answers)
60
+ ? answers.map((value, i) => {
61
+ const question = this.assessment.questions[i];
62
+ if (!question) {
63
+ throw new errors_ts_1.PsytoolsError("invalid_value", `Got ${answers.length} answers but assessment "${this.assessment.id}" has ${this.assessment.questions.length} questions`);
64
+ }
65
+ return [question.id, value];
66
+ })
67
+ : Object.entries(answers);
68
+ // Validate everything first so a failure does not apply partially.
69
+ for (const [questionId, value] of entries) {
70
+ const issue = this.checkAnswer(questionId, value);
71
+ if (issue)
72
+ throw new errors_ts_1.PsytoolsError(issue.code, issue.message);
73
+ }
74
+ for (const [questionId, value] of entries) {
75
+ this.values.set(questionId, value);
76
+ }
77
+ this.refreshState();
78
+ return this;
79
+ }
80
+ /** Removes an answer (e.g. respondent deselects a choice). */
81
+ clearAnswer(questionId) {
82
+ this.assertMutable();
83
+ this.values.delete(questionId);
84
+ this.refreshState();
85
+ return this;
86
+ }
87
+ /** Ids of required questions that are not answered yet. */
88
+ unanswered() {
89
+ return this.assessment.questions
90
+ .filter((q) => !(q.optional ?? false) && !this.values.has(q.id))
91
+ .map((q) => q.id);
92
+ }
93
+ /** Completion ratio in `[0, 1]` over all questions. */
94
+ progress() {
95
+ const total = this.assessment.questions.length;
96
+ return total === 0 ? 1 : this.values.size / total;
97
+ }
98
+ isComplete() {
99
+ return this.unanswered().length === 0;
100
+ }
101
+ /**
102
+ * Validates the current answers against the assessment: every answered
103
+ * value must belong to the question's option scale, and (unless
104
+ * `partial`) every required question must be answered.
105
+ */
106
+ validate(options) {
107
+ const issues = [];
108
+ for (const [questionId, value] of this.values) {
109
+ const issue = this.checkAnswer(questionId, value);
110
+ if (issue)
111
+ issues.push(issue);
112
+ }
113
+ if (!options?.partial) {
114
+ for (const questionId of this.unanswered()) {
115
+ issues.push({
116
+ code: "missing_answer",
117
+ message: `Question "${questionId}" is not answered`,
118
+ questionId,
119
+ });
120
+ }
121
+ }
122
+ return { valid: issues.length === 0, issues };
123
+ }
124
+ /**
125
+ * Validates and finalizes the response. After submission the response is
126
+ * immutable. Pass `allowIncomplete` to submit with unanswered optional-use
127
+ * cases (answered values are still validated).
128
+ * @throws PsytoolsError `already_submitted` | `invalid_response`
129
+ */
130
+ submit(options) {
131
+ this.assertMutable();
132
+ const result = this.validate({ partial: options?.allowIncomplete });
133
+ if (!result.valid) {
134
+ const details = result.issues.map((issue) => issue.message).join("; ");
135
+ throw new errors_ts_1.PsytoolsError("invalid_response", `Cannot submit response: ${details}`);
136
+ }
137
+ this.submittedTime = options?.submittedAt ?? new Date();
138
+ this.state = "submitted";
139
+ return this;
140
+ }
141
+ /** Plain serializable data (used by `JSON.stringify`). */
142
+ toJSON() {
143
+ const data = {
144
+ assessmentId: this.assessment.id,
145
+ answers: this.answers,
146
+ status: this.state,
147
+ startedAt: this.startedAt.toISOString(),
148
+ };
149
+ if (this.assessment.definition.version !== undefined) {
150
+ data.assessmentVersion = this.assessment.definition.version;
151
+ }
152
+ if (this.respondentId !== undefined)
153
+ data.respondentId = this.respondentId;
154
+ if (this.submittedTime)
155
+ data.submittedAt = this.submittedTime.toISOString();
156
+ if (this.meta !== undefined)
157
+ data.meta = this.meta;
158
+ return data;
159
+ }
160
+ /** Serializes to a JSON string (for DB storage etc.). */
161
+ stringify(space) {
162
+ return JSON.stringify(this.toJSON(), null, space);
163
+ }
164
+ /**
165
+ * Restores a response from serialized data, validating every answer
166
+ * against the assessment.
167
+ * @throws PsytoolsError `invalid_json` | `assessment_mismatch` | `unknown_question` | `invalid_value`
168
+ */
169
+ static parse(assessment, input) {
170
+ let data;
171
+ if (typeof input === "string") {
172
+ try {
173
+ data = JSON.parse(input);
174
+ }
175
+ catch (error) {
176
+ throw new errors_ts_1.PsytoolsError("invalid_json", `Not valid JSON: ${error.message}`);
177
+ }
178
+ }
179
+ else {
180
+ data = input;
181
+ }
182
+ if (data.assessmentId !== assessment.id) {
183
+ throw new errors_ts_1.PsytoolsError("assessment_mismatch", `Response belongs to assessment "${data.assessmentId}", not "${assessment.id}"`);
184
+ }
185
+ const response = new AssessmentResponse(assessment, {
186
+ respondentId: data.respondentId,
187
+ meta: data.meta,
188
+ startedAt: data.startedAt ? new Date(data.startedAt) : undefined,
189
+ });
190
+ response.answerAll(data.answers ?? {});
191
+ if (data.submittedAt) {
192
+ response.submittedTime = new Date(data.submittedAt);
193
+ response.state = "submitted";
194
+ }
195
+ return response;
196
+ }
197
+ checkAnswer(questionId, value) {
198
+ const question = this.assessment.question(questionId);
199
+ if (!question) {
200
+ return {
201
+ code: "unknown_question",
202
+ message: `Question "${questionId}" does not exist in assessment "${this.assessment.id}"`,
203
+ questionId,
204
+ };
205
+ }
206
+ const options = question.options ?? this.assessment.definition.options;
207
+ if (!options.some((option) => option.value === value)) {
208
+ const allowed = options.map((option) => option.value).join(", ");
209
+ return {
210
+ code: "invalid_value",
211
+ message: `Value ${value} is not a valid option for question "${questionId}" (allowed: ${allowed})`,
212
+ questionId,
213
+ };
214
+ }
215
+ return undefined;
216
+ }
217
+ assertMutable() {
218
+ if (this.state === "submitted") {
219
+ throw new errors_ts_1.PsytoolsError("already_submitted", "Response was already submitted and is immutable");
220
+ }
221
+ }
222
+ refreshState() {
223
+ if (this.values.size === 0) {
224
+ this.state = "empty";
225
+ }
226
+ else {
227
+ this.state = this.unanswered().length === 0 ? "complete" : "in-progress";
228
+ }
229
+ }
230
+ }
231
+ exports.AssessmentResponse = AssessmentResponse;
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Core data model for psytools.
3
+ *
4
+ * Everything here is plain, JSON-serializable data. Scoring rules are
5
+ * declarative (not functions) so that a full assessment definition survives
6
+ * `JSON.stringify` -> database -> `JSON.parse` round trips without losing
7
+ * behavior.
8
+ */
9
+ /**
10
+ * A piece of text in one or more locales, keyed by BCP-47 language tag
11
+ * (e.g. `{ en: "Not at all", tr: "Hiç", de: "Überhaupt nicht" }`).
12
+ */
13
+ export type LocalizedText = Record<string, string>;
14
+ /** One choice in an enumerated multiple-choice scale (e.g. a Likert point). */
15
+ export interface AssessmentOption {
16
+ /** Numeric score contributed when this option is chosen. */
17
+ value: number;
18
+ label: LocalizedText;
19
+ }
20
+ /** A single question (item) of an assessment. */
21
+ export interface AssessmentQuestion {
22
+ /** Stable unique id within the assessment, e.g. `"phq9-3"`. */
23
+ id: string;
24
+ text: LocalizedText;
25
+ /**
26
+ * Question-specific options. When omitted, the assessment-level `options`
27
+ * scale applies (the common case for standardized inventories).
28
+ */
29
+ options?: AssessmentOption[];
30
+ /**
31
+ * When true, the answered value is reversed against the option scale
32
+ * (max + min - value) before scoring.
33
+ */
34
+ reverseScored?: boolean;
35
+ /** When true, the question may be left unanswered at submit time. */
36
+ optional?: boolean;
37
+ }
38
+ /** A severity band: an inclusive score range with a localized label. */
39
+ export interface ScoreBand {
40
+ /** Stable machine-readable id, e.g. `"moderate"`. */
41
+ id: string;
42
+ /** Inclusive lower bound. */
43
+ min: number;
44
+ /** Inclusive upper bound. */
45
+ max: number;
46
+ label: LocalizedText;
47
+ }
48
+ /**
49
+ * A clinical flag raised by a single item's answer, independent of the total
50
+ * score — e.g. PHQ-9 item 9 (self-harm ideation) answered above 0.
51
+ */
52
+ export interface ScoreFlag {
53
+ /** Stable machine-readable id, e.g. `"suicidality"`. */
54
+ id: string;
55
+ questionId: string;
56
+ /** The flag is raised when the (raw) answer value is >= this. */
57
+ minValue: number;
58
+ label: LocalizedText;
59
+ }
60
+ /** Sums all answers into a single total score (PHQ-9, GAD-7, ...). */
61
+ export interface SumScoring {
62
+ kind: "sum";
63
+ /** Severity bands the total is matched against. */
64
+ bands?: ScoreBand[];
65
+ flags?: ScoreFlag[];
66
+ }
67
+ /** One subscale of a multi-scale scoring definition. */
68
+ export interface SubscaleDefinition {
69
+ /** Stable machine-readable id, e.g. `"depression"`. */
70
+ id: string;
71
+ label: LocalizedText;
72
+ /** Ids of the questions contributing to this subscale. */
73
+ questionIds: string[];
74
+ /** Multiplier applied to the raw subscale sum (DASS-21 uses 2). */
75
+ multiplier?: number;
76
+ bands?: ScoreBand[];
77
+ }
78
+ /** Scores groups of items into named subscales (DASS-21, ...). */
79
+ export interface SubscaleScoring {
80
+ kind: "subscales";
81
+ subscales: SubscaleDefinition[];
82
+ flags?: ScoreFlag[];
83
+ }
84
+ /** Declarative, serializable scoring rules built into psytools. */
85
+ export type ScoringDefinition = SumScoring | SubscaleScoring;
86
+ /**
87
+ * The complete, serializable description of an assessment.
88
+ *
89
+ * This is the unit you persist, exchange between backend and frontend, and
90
+ * feed to the `Assessment` class.
91
+ */
92
+ export interface AssessmentDefinition {
93
+ /** Stable unique id, e.g. `"phq9"` or `"my-clinic/intake-2026"`. */
94
+ id: string;
95
+ /** Version of this definition (semver or free-form), for provenance. */
96
+ version?: string;
97
+ title: LocalizedText;
98
+ description?: LocalizedText;
99
+ /** Instructions shown to the respondent (incl. the recall timeframe). */
100
+ instructions?: LocalizedText;
101
+ /** Locale used when a requested locale is missing. */
102
+ defaultLocale: string;
103
+ /** Default option scale applied to every question without own options. */
104
+ options: AssessmentOption[];
105
+ questions: AssessmentQuestion[];
106
+ /** Optional declarative scoring. Custom evaluators may be used instead. */
107
+ scoring?: ScoringDefinition;
108
+ /** Free-form metadata (source, license, citation, timeframe, ...). */
109
+ meta?: Record<string, unknown>;
110
+ }
111
+ /** Answers keyed by question id. */
112
+ export type AnswerMap = Record<string, number>;
113
+ /**
114
+ * Lifecycle of a response, tracked as a simple state machine:
115
+ *
116
+ * `empty` -> `in-progress` -> `complete` -> `submitted`
117
+ *
118
+ * Answering and clearing answers moves between the first three states in
119
+ * both directions; `submit()` moves to the terminal `submitted` state.
120
+ */
121
+ export type ResponseStatus = "empty" | "in-progress" | "complete" | "submitted";
122
+ /** Serialized form of an `AssessmentResponse`. */
123
+ export interface ResponseData {
124
+ assessmentId: string;
125
+ /** Version of the assessment definition answered, if it declared one. */
126
+ assessmentVersion?: string;
127
+ answers: AnswerMap;
128
+ /** Informational lifecycle state; recomputed from answers on parse. */
129
+ status?: ResponseStatus;
130
+ /** Opaque identifier of the respondent (client/case id). Optional. */
131
+ respondentId?: string;
132
+ /** ISO-8601 timestamps. */
133
+ startedAt: string;
134
+ submittedAt?: string;
135
+ meta?: Record<string, unknown>;
136
+ }
137
+ /** A single validation problem. */
138
+ export interface ValidationIssue {
139
+ code: "unknown_question" | "invalid_value" | "missing_answer" | "duplicate_question" | "malformed";
140
+ message: string;
141
+ questionId?: string;
142
+ }
143
+ export interface ValidationResult {
144
+ valid: boolean;
145
+ issues: ValidationIssue[];
146
+ }
147
+ /** A resolved severity band in an evaluation result. */
148
+ export interface BandResult {
149
+ id: string;
150
+ label: LocalizedText;
151
+ }
152
+ /** A flag that was raised during evaluation. */
153
+ export interface TriggeredFlag {
154
+ id: string;
155
+ questionId: string;
156
+ value: number;
157
+ label: LocalizedText;
158
+ }
159
+ /** A single numeric score with its possible range and matched band. */
160
+ export interface ScaleScore {
161
+ score: number;
162
+ /** Lowest achievable score. */
163
+ min: number;
164
+ /** Highest achievable score. */
165
+ max: number;
166
+ /** Matched severity band, if bands are defined and one matches. */
167
+ band?: BandResult;
168
+ }
169
+ /** Result of a single-scale evaluation (e.g. PHQ-9 total). */
170
+ export interface ScaleResult extends ScaleScore {
171
+ kind: "scale";
172
+ flags: TriggeredFlag[];
173
+ }
174
+ /** Result of a multi-scale evaluation (e.g. DASS-21 subscales). */
175
+ export interface MultiScaleResult {
176
+ kind: "multiscale";
177
+ scales: Array<ScaleScore & {
178
+ id: string;
179
+ label: LocalizedText;
180
+ }>;
181
+ flags: TriggeredFlag[];
182
+ }
183
+ /** Result of a categorizing evaluation (e.g. attachment style). */
184
+ export interface CategoricalResult {
185
+ kind: "categorical";
186
+ category: string;
187
+ label?: LocalizedText;
188
+ flags?: TriggeredFlag[];
189
+ }
190
+ /** Escape hatch for arbitrary evaluator output. */
191
+ export interface CustomResult {
192
+ kind: "custom";
193
+ data: unknown;
194
+ }
195
+ export type EvaluationResult = ScaleResult | MultiScaleResult | CategoricalResult | CustomResult;
196
+ /**
197
+ * A custom evaluation function. Receives the definition and the validated
198
+ * answers and returns any `EvaluationResult` shape.
199
+ */
200
+ export type Evaluator = (definition: AssessmentDefinition, answers: AnswerMap) => EvaluationResult;
201
+ /** Flat, render-ready projection of an assessment in a single locale. */
202
+ export interface LocalizedAssessmentView {
203
+ id: string;
204
+ locale: string;
205
+ title: string;
206
+ description?: string;
207
+ instructions?: string;
208
+ questions: Array<{
209
+ id: string;
210
+ /** 1-based position, handy for display. */
211
+ index: number;
212
+ text: string;
213
+ optional: boolean;
214
+ options: Array<{
215
+ value: number;
216
+ label: string;
217
+ }>;
218
+ }>;
219
+ }