@slopit/adapter-vanilla 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aaron Steven White
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,293 @@
1
+ import { RecorderConfig, TrialConfig, AdapterData, BaseRecorder } from '@slopit/adapter-shared';
2
+ export { AdapterData } from '@slopit/adapter-shared';
3
+ import { StimulusInfo, PlatformInfo, ResponseInfo, SlopitSession } from '@slopit/core';
4
+ export { BehavioralData, ResponseInfo, SlopitSession, SlopitTrial, StimulusInfo } from '@slopit/core';
5
+
6
+ /**
7
+ * Types for the vanilla adapter.
8
+ *
9
+ * @module
10
+ */
11
+
12
+ /**
13
+ * Configuration for VanillaRecorder.
14
+ *
15
+ * Extends the base RecorderConfig with platform identification options.
16
+ */
17
+ interface VanillaRecorderConfig extends RecorderConfig {
18
+ /**
19
+ * Platform name for identification.
20
+ *
21
+ * @default "vanilla"
22
+ */
23
+ platformName?: string;
24
+ /**
25
+ * Platform version string.
26
+ *
27
+ * @default "1.0.0"
28
+ */
29
+ platformVersion?: string;
30
+ }
31
+ /**
32
+ * Trial configuration for VanillaRecorder.
33
+ *
34
+ * Extends the base TrialConfig with a more flexible stimulus type.
35
+ */
36
+ interface VanillaTrialConfig extends Omit<TrialConfig, "stimulus"> {
37
+ /**
38
+ * Stimulus information for this trial.
39
+ *
40
+ * Accepts either a StimulusInfo object or a plain string.
41
+ * Strings are automatically converted to text stimuli.
42
+ */
43
+ stimulus?: StimulusInfo | string;
44
+ }
45
+ /**
46
+ * Result of a completed trial.
47
+ *
48
+ * Contains trial identification, behavioral data, and timing information.
49
+ * This type extends the base CompletedTrial to maintain type compatibility
50
+ * while providing a more convenient interface.
51
+ */
52
+ interface VanillaTrialResult {
53
+ /**
54
+ * Unique trial identifier.
55
+ */
56
+ trialId: string;
57
+ /**
58
+ * Zero-indexed position of the trial in the session.
59
+ */
60
+ trialIndex: number;
61
+ /**
62
+ * Trial type identifier.
63
+ */
64
+ trialType?: string | undefined;
65
+ /**
66
+ * Start time in milliseconds (Unix timestamp).
67
+ */
68
+ startTime: number;
69
+ /**
70
+ * End time in milliseconds (Unix timestamp).
71
+ */
72
+ endTime: number;
73
+ /**
74
+ * Collected behavioral data and flags.
75
+ */
76
+ data: AdapterData;
77
+ /**
78
+ * Response time in milliseconds (computed from endTime - startTime).
79
+ */
80
+ rt: number;
81
+ }
82
+
83
+ /**
84
+ * Framework-agnostic SlopitRecorder implementation.
85
+ *
86
+ * @module
87
+ */
88
+
89
+ /**
90
+ * Framework-agnostic SlopitRecorder for custom experiment implementations.
91
+ *
92
+ * This is a reference implementation that can be used directly or as a
93
+ * template for building custom platform-specific adapters.
94
+ *
95
+ * @example
96
+ * ```typescript
97
+ * const recorder = new SlopitRecorder({
98
+ * participantId: "P001",
99
+ * studyId: "study_1",
100
+ * });
101
+ *
102
+ * // Start a trial
103
+ * recorder.startTrial({
104
+ * trialId: "trial_1",
105
+ * targetElement: document.querySelector("textarea"),
106
+ * });
107
+ *
108
+ * // Later, when trial ends
109
+ * const result = recorder.endTrial("participant response text");
110
+ *
111
+ * // At experiment end
112
+ * const session = recorder.exportSession();
113
+ * ```
114
+ */
115
+ declare class SlopitRecorder extends BaseRecorder {
116
+ private platformName;
117
+ private platformVersion;
118
+ private discoveryCleanup;
119
+ /**
120
+ * Creates a new SlopitRecorder.
121
+ *
122
+ * @param config - Recorder configuration
123
+ */
124
+ constructor(config?: VanillaRecorderConfig);
125
+ /**
126
+ * Gets platform-specific information.
127
+ *
128
+ * @returns Platform information for session export
129
+ */
130
+ protected getPlatformInfo(): PlatformInfo;
131
+ /**
132
+ * Normalizes a VanillaTrialConfig to a TrialConfig.
133
+ *
134
+ * @param config - Vanilla trial config with optional string stimulus
135
+ * @returns Trial config compatible with base class
136
+ */
137
+ private normalizeTrialConfig;
138
+ /**
139
+ * Start capturing behavioral data for a trial.
140
+ *
141
+ * @param config - Trial configuration
142
+ * @throws Error if a trial is already in progress
143
+ *
144
+ * @example
145
+ * ```typescript
146
+ * recorder.startTrial({
147
+ * trialId: "trial_1",
148
+ * targetElement: document.querySelector("textarea"),
149
+ * stimulus: "Please describe your experience.",
150
+ * });
151
+ * ```
152
+ */
153
+ startTrial(config: VanillaTrialConfig): void;
154
+ /**
155
+ * Start a trial with automatic element discovery.
156
+ *
157
+ * Use this when the target element may not exist yet (e.g., dynamically
158
+ * rendered content). The method uses a MutationObserver to watch for
159
+ * the element to appear in the DOM.
160
+ *
161
+ * @param config - Trial configuration (without targetElement)
162
+ * @param selector - CSS selector for target element
163
+ * @param container - Container to search within (default: document)
164
+ * @param timeout - Max time to wait for element (default: 5000ms)
165
+ * @returns Promise that resolves when the trial starts
166
+ * @throws Error if element is not found within timeout
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * await recorder.startTrialWithDiscovery(
171
+ * { trialId: "trial_1" },
172
+ * "textarea.response-input",
173
+ * document.body,
174
+ * 3000
175
+ * );
176
+ * ```
177
+ */
178
+ startTrialWithDiscovery(config: VanillaTrialConfig, selector: string, container?: HTMLElement | Document, timeout?: number): Promise<void>;
179
+ /**
180
+ * End the current trial and return captured data.
181
+ *
182
+ * This method accepts either a string or ResponseInfo for convenience.
183
+ * Strings are automatically converted to text responses with character
184
+ * and word counts.
185
+ *
186
+ * @param response - The participant's response (text string or ResponseInfo)
187
+ * @returns The completed trial with behavioral data
188
+ * @throws Error if no trial is in progress
189
+ *
190
+ * @example
191
+ * ```typescript
192
+ * // With a simple text response
193
+ * const result = recorder.endTrial("The participant's typed response");
194
+ *
195
+ * // With a ResponseInfo object
196
+ * const result = recorder.endTrial({
197
+ * type: "text",
198
+ * value: "Response text",
199
+ * characterCount: 13,
200
+ * wordCount: 2,
201
+ * });
202
+ * ```
203
+ */
204
+ endTrial(response?: string | ResponseInfo, platformData?: Record<string, unknown>): VanillaTrialResult;
205
+ /**
206
+ * Check if a trial is currently in progress.
207
+ *
208
+ * @returns True if a trial is active
209
+ *
210
+ * @example
211
+ * ```typescript
212
+ * if (recorder.isTrialActive()) {
213
+ * recorder.endTrial(responseText);
214
+ * }
215
+ * ```
216
+ */
217
+ isTrialActive(): boolean;
218
+ /**
219
+ * Get the current trial ID, or null if no trial is active.
220
+ *
221
+ * @returns The current trial ID or null
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * const trialId = recorder.getCurrentTrialId();
226
+ * if (trialId !== null) {
227
+ * console.log(`Recording trial: ${trialId}`);
228
+ * }
229
+ * ```
230
+ */
231
+ getCurrentTrialId(): string | null;
232
+ /**
233
+ * Get the number of completed trials.
234
+ *
235
+ * @returns The count of completed trials
236
+ *
237
+ * @example
238
+ * ```typescript
239
+ * console.log(`Completed ${recorder.getTrialCount()} trials`);
240
+ * ```
241
+ */
242
+ getTrialCount(): number;
243
+ /**
244
+ * Reset the recorder for a new session.
245
+ *
246
+ * Clears all trials, detaches any active capture, and generates a new
247
+ * session ID. Use this when starting a new experiment session with the
248
+ * same participant.
249
+ *
250
+ * @example
251
+ * ```typescript
252
+ * // After completing a session
253
+ * const session = recorder.exportSession();
254
+ * await saveSession(session);
255
+ *
256
+ * // Reset for a new session
257
+ * recorder.resetSession();
258
+ * ```
259
+ */
260
+ resetSession(): void;
261
+ /**
262
+ * Export the session data.
263
+ *
264
+ * @returns Complete session data in SlopitSession format
265
+ *
266
+ * @example
267
+ * ```typescript
268
+ * const session = recorder.exportSession();
269
+ * await fetch("/api/sessions", {
270
+ * method: "POST",
271
+ * headers: { "Content-Type": "application/json" },
272
+ * body: JSON.stringify(session),
273
+ * });
274
+ * ```
275
+ */
276
+ exportSession(): SlopitSession;
277
+ /**
278
+ * Export session data as a JSON string.
279
+ *
280
+ * Convenience method for storing or transmitting session data.
281
+ *
282
+ * @returns JSON string representation of the session
283
+ *
284
+ * @example
285
+ * ```typescript
286
+ * const json = recorder.exportSessionJSON();
287
+ * localStorage.setItem("session", json);
288
+ * ```
289
+ */
290
+ exportSessionJSON(): string;
291
+ }
292
+
293
+ export { SlopitRecorder, SlopitRecorder as VanillaRecorder, type VanillaRecorderConfig, type VanillaTrialConfig, type VanillaTrialResult };
package/dist/index.js ADDED
@@ -0,0 +1,297 @@
1
+ import { BaseRecorder, discoverElement } from '@slopit/adapter-shared';
2
+
3
+ // src/recorder.ts
4
+ var SlopitRecorder = class extends BaseRecorder {
5
+ platformName;
6
+ platformVersion;
7
+ discoveryCleanup = null;
8
+ /**
9
+ * Creates a new SlopitRecorder.
10
+ *
11
+ * @param config - Recorder configuration
12
+ */
13
+ constructor(config) {
14
+ super(config);
15
+ this.platformName = config?.platformName ?? "vanilla";
16
+ this.platformVersion = config?.platformVersion ?? "1.0.0";
17
+ }
18
+ /**
19
+ * Gets platform-specific information.
20
+ *
21
+ * @returns Platform information for session export
22
+ */
23
+ getPlatformInfo() {
24
+ return {
25
+ name: this.platformName,
26
+ version: this.platformVersion,
27
+ adapterVersion: "0.1.0"
28
+ };
29
+ }
30
+ /**
31
+ * Normalizes a VanillaTrialConfig to a TrialConfig.
32
+ *
33
+ * @param config - Vanilla trial config with optional string stimulus
34
+ * @returns Trial config compatible with base class
35
+ */
36
+ normalizeTrialConfig(config) {
37
+ const stimulus = typeof config.stimulus === "string" ? { type: "text", content: config.stimulus } : config.stimulus;
38
+ const trialConfig = {};
39
+ if (config.trialId !== void 0) {
40
+ trialConfig.trialId = config.trialId;
41
+ }
42
+ if (config.trialIndex !== void 0) {
43
+ trialConfig.trialIndex = config.trialIndex;
44
+ }
45
+ if (config.trialType !== void 0) {
46
+ trialConfig.trialType = config.trialType;
47
+ }
48
+ if (config.targetElement !== void 0) {
49
+ trialConfig.targetElement = config.targetElement;
50
+ }
51
+ if (config.targetSelector !== void 0) {
52
+ trialConfig.targetSelector = config.targetSelector;
53
+ }
54
+ if (stimulus !== void 0) {
55
+ trialConfig.stimulus = stimulus;
56
+ }
57
+ return trialConfig;
58
+ }
59
+ /**
60
+ * Start capturing behavioral data for a trial.
61
+ *
62
+ * @param config - Trial configuration
63
+ * @throws Error if a trial is already in progress
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * recorder.startTrial({
68
+ * trialId: "trial_1",
69
+ * targetElement: document.querySelector("textarea"),
70
+ * stimulus: "Please describe your experience.",
71
+ * });
72
+ * ```
73
+ */
74
+ startTrial(config) {
75
+ super.startTrial(this.normalizeTrialConfig(config));
76
+ }
77
+ /**
78
+ * Start a trial with automatic element discovery.
79
+ *
80
+ * Use this when the target element may not exist yet (e.g., dynamically
81
+ * rendered content). The method uses a MutationObserver to watch for
82
+ * the element to appear in the DOM.
83
+ *
84
+ * @param config - Trial configuration (without targetElement)
85
+ * @param selector - CSS selector for target element
86
+ * @param container - Container to search within (default: document)
87
+ * @param timeout - Max time to wait for element (default: 5000ms)
88
+ * @returns Promise that resolves when the trial starts
89
+ * @throws Error if element is not found within timeout
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * await recorder.startTrialWithDiscovery(
94
+ * { trialId: "trial_1" },
95
+ * "textarea.response-input",
96
+ * document.body,
97
+ * 3000
98
+ * );
99
+ * ```
100
+ */
101
+ startTrialWithDiscovery(config, selector, container = document, timeout = 5e3) {
102
+ return new Promise((resolve, reject) => {
103
+ const element = container.querySelector(selector);
104
+ if (element !== null) {
105
+ this.startTrial({ ...config, targetElement: element });
106
+ resolve();
107
+ return;
108
+ }
109
+ this.discoveryCleanup = discoverElement({
110
+ selector,
111
+ container,
112
+ timeout,
113
+ onFound: (el) => {
114
+ this.discoveryCleanup = null;
115
+ this.startTrial({ ...config, targetElement: el });
116
+ resolve();
117
+ },
118
+ onTimeout: () => {
119
+ this.discoveryCleanup = null;
120
+ this.startTrial(config);
121
+ reject(new Error(`Element "${selector}" not found within ${timeout}ms`));
122
+ }
123
+ });
124
+ });
125
+ }
126
+ /**
127
+ * End the current trial and return captured data.
128
+ *
129
+ * This method accepts either a string or ResponseInfo for convenience.
130
+ * Strings are automatically converted to text responses with character
131
+ * and word counts.
132
+ *
133
+ * @param response - The participant's response (text string or ResponseInfo)
134
+ * @returns The completed trial with behavioral data
135
+ * @throws Error if no trial is in progress
136
+ *
137
+ * @example
138
+ * ```typescript
139
+ * // With a simple text response
140
+ * const result = recorder.endTrial("The participant's typed response");
141
+ *
142
+ * // With a ResponseInfo object
143
+ * const result = recorder.endTrial({
144
+ * type: "text",
145
+ * value: "Response text",
146
+ * characterCount: 13,
147
+ * wordCount: 2,
148
+ * });
149
+ * ```
150
+ */
151
+ endTrial(response, platformData) {
152
+ if (this.discoveryCleanup !== null) {
153
+ this.discoveryCleanup();
154
+ this.discoveryCleanup = null;
155
+ }
156
+ let responseInfo;
157
+ if (typeof response === "string") {
158
+ responseInfo = {
159
+ type: "text",
160
+ value: response,
161
+ characterCount: response.length,
162
+ wordCount: response.trim().split(/\s+/).filter((w) => w.length > 0).length
163
+ };
164
+ } else if (response !== void 0) {
165
+ responseInfo = response;
166
+ }
167
+ const trial = super.endTrial(responseInfo, platformData);
168
+ return {
169
+ trialId: trial.trialId,
170
+ trialIndex: trial.trialIndex,
171
+ trialType: trial.trialType,
172
+ startTime: trial.startTime,
173
+ endTime: trial.endTime,
174
+ data: {
175
+ behavioral: trial.behavioral ?? {
176
+ keystrokes: [],
177
+ focus: [],
178
+ paste: [],
179
+ mouse: [],
180
+ scroll: [],
181
+ clipboard: [],
182
+ inputDuration: [],
183
+ metrics: {}
184
+ },
185
+ flags: trial.captureFlags ?? []
186
+ },
187
+ rt: trial.endTime - trial.startTime
188
+ };
189
+ }
190
+ /**
191
+ * Check if a trial is currently in progress.
192
+ *
193
+ * @returns True if a trial is active
194
+ *
195
+ * @example
196
+ * ```typescript
197
+ * if (recorder.isTrialActive()) {
198
+ * recorder.endTrial(responseText);
199
+ * }
200
+ * ```
201
+ */
202
+ isTrialActive() {
203
+ return this.isTrialInProgress();
204
+ }
205
+ /**
206
+ * Get the current trial ID, or null if no trial is active.
207
+ *
208
+ * @returns The current trial ID or null
209
+ *
210
+ * @example
211
+ * ```typescript
212
+ * const trialId = recorder.getCurrentTrialId();
213
+ * if (trialId !== null) {
214
+ * console.log(`Recording trial: ${trialId}`);
215
+ * }
216
+ * ```
217
+ */
218
+ getCurrentTrialId() {
219
+ const trial = this.getCurrentTrial();
220
+ return trial?.trialId ?? null;
221
+ }
222
+ /**
223
+ * Get the number of completed trials.
224
+ *
225
+ * @returns The count of completed trials
226
+ *
227
+ * @example
228
+ * ```typescript
229
+ * console.log(`Completed ${recorder.getTrialCount()} trials`);
230
+ * ```
231
+ */
232
+ getTrialCount() {
233
+ return this.getTrials().length;
234
+ }
235
+ /**
236
+ * Reset the recorder for a new session.
237
+ *
238
+ * Clears all trials, detaches any active capture, and generates a new
239
+ * session ID. Use this when starting a new experiment session with the
240
+ * same participant.
241
+ *
242
+ * @example
243
+ * ```typescript
244
+ * // After completing a session
245
+ * const session = recorder.exportSession();
246
+ * await saveSession(session);
247
+ *
248
+ * // Reset for a new session
249
+ * recorder.resetSession();
250
+ * ```
251
+ */
252
+ resetSession() {
253
+ if (this.discoveryCleanup !== null) {
254
+ this.discoveryCleanup();
255
+ this.discoveryCleanup = null;
256
+ }
257
+ this.reset();
258
+ }
259
+ /**
260
+ * Export the session data.
261
+ *
262
+ * @returns Complete session data in SlopitSession format
263
+ *
264
+ * @example
265
+ * ```typescript
266
+ * const session = recorder.exportSession();
267
+ * await fetch("/api/sessions", {
268
+ * method: "POST",
269
+ * headers: { "Content-Type": "application/json" },
270
+ * body: JSON.stringify(session),
271
+ * });
272
+ * ```
273
+ */
274
+ exportSession() {
275
+ return super.exportSession();
276
+ }
277
+ /**
278
+ * Export session data as a JSON string.
279
+ *
280
+ * Convenience method for storing or transmitting session data.
281
+ *
282
+ * @returns JSON string representation of the session
283
+ *
284
+ * @example
285
+ * ```typescript
286
+ * const json = recorder.exportSessionJSON();
287
+ * localStorage.setItem("session", json);
288
+ * ```
289
+ */
290
+ exportSessionJSON() {
291
+ return JSON.stringify(this.exportSession());
292
+ }
293
+ };
294
+
295
+ export { SlopitRecorder, SlopitRecorder as VanillaRecorder };
296
+ //# sourceMappingURL=index.js.map
297
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/recorder.ts"],"names":[],"mappings":";;;AAqCO,IAAM,cAAA,GAAN,cAA6B,YAAA,CAAa;AAAA,EACvC,YAAA;AAAA,EACA,eAAA;AAAA,EACA,gBAAA,GAAwC,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhD,YAAY,MAAA,EAAgC;AAC1C,IAAA,KAAA,CAAM,MAAM,CAAA;AACZ,IAAA,IAAA,CAAK,YAAA,GAAe,QAAQ,YAAA,IAAgB,SAAA;AAC5C,IAAA,IAAA,CAAK,eAAA,GAAkB,QAAQ,eAAA,IAAmB,OAAA;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOmB,eAAA,GAAgC;AACjD,IAAA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eA,iBAAA,GAA4B;AAC1B,IAAA,OAAO,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,aAAA,EAAe,CAAA;AAAA,EAC5C;AACF","file":"index.js","sourcesContent":["/**\n * Framework-agnostic SlopitRecorder implementation.\n *\n * @module\n */\n\nimport { BaseRecorder, type TrialConfig, discoverElement } from \"@slopit/adapter-shared\";\nimport type { PlatformInfo, ResponseInfo, SlopitSession, StimulusInfo } from \"@slopit/core\";\n\nimport type { VanillaRecorderConfig, VanillaTrialConfig, VanillaTrialResult } from \"./types.js\";\n\n/**\n * Framework-agnostic SlopitRecorder for custom experiment implementations.\n *\n * This is a reference implementation that can be used directly or as a\n * template for building custom platform-specific adapters.\n *\n * @example\n * ```typescript\n * const recorder = new SlopitRecorder({\n * participantId: \"P001\",\n * studyId: \"study_1\",\n * });\n *\n * // Start a trial\n * recorder.startTrial({\n * trialId: \"trial_1\",\n * targetElement: document.querySelector(\"textarea\"),\n * });\n *\n * // Later, when trial ends\n * const result = recorder.endTrial(\"participant response text\");\n *\n * // At experiment end\n * const session = recorder.exportSession();\n * ```\n */\nexport class SlopitRecorder extends BaseRecorder {\n private platformName: string;\n private platformVersion: string;\n private discoveryCleanup: (() => void) | null = null;\n\n /**\n * Creates a new SlopitRecorder.\n *\n * @param config - Recorder configuration\n */\n constructor(config?: VanillaRecorderConfig) {\n super(config);\n this.platformName = config?.platformName ?? \"vanilla\";\n this.platformVersion = config?.platformVersion ?? \"1.0.0\";\n }\n\n /**\n * Gets platform-specific information.\n *\n * @returns Platform information for session export\n */\n protected override getPlatformInfo(): PlatformInfo {\n return {\n name: this.platformName,\n version: this.platformVersion,\n adapterVersion: \"0.1.0\",\n };\n }\n\n /**\n * Normalizes a VanillaTrialConfig to a TrialConfig.\n *\n * @param config - Vanilla trial config with optional string stimulus\n * @returns Trial config compatible with base class\n */\n private normalizeTrialConfig(config: VanillaTrialConfig): TrialConfig {\n // Extract stimulus and convert string to StimulusInfo\n const stimulus: StimulusInfo | undefined =\n typeof config.stimulus === \"string\"\n ? { type: \"text\", content: config.stimulus }\n : config.stimulus;\n\n // Build the trial config explicitly, only including defined properties\n const trialConfig: TrialConfig = {};\n\n if (config.trialId !== undefined) {\n trialConfig.trialId = config.trialId;\n }\n if (config.trialIndex !== undefined) {\n trialConfig.trialIndex = config.trialIndex;\n }\n if (config.trialType !== undefined) {\n trialConfig.trialType = config.trialType;\n }\n if (config.targetElement !== undefined) {\n trialConfig.targetElement = config.targetElement;\n }\n if (config.targetSelector !== undefined) {\n trialConfig.targetSelector = config.targetSelector;\n }\n if (stimulus !== undefined) {\n trialConfig.stimulus = stimulus;\n }\n\n return trialConfig;\n }\n\n /**\n * Start capturing behavioral data for a trial.\n *\n * @param config - Trial configuration\n * @throws Error if a trial is already in progress\n *\n * @example\n * ```typescript\n * recorder.startTrial({\n * trialId: \"trial_1\",\n * targetElement: document.querySelector(\"textarea\"),\n * stimulus: \"Please describe your experience.\",\n * });\n * ```\n */\n override startTrial(config: VanillaTrialConfig): void {\n super.startTrial(this.normalizeTrialConfig(config));\n }\n\n /**\n * Start a trial with automatic element discovery.\n *\n * Use this when the target element may not exist yet (e.g., dynamically\n * rendered content). The method uses a MutationObserver to watch for\n * the element to appear in the DOM.\n *\n * @param config - Trial configuration (without targetElement)\n * @param selector - CSS selector for target element\n * @param container - Container to search within (default: document)\n * @param timeout - Max time to wait for element (default: 5000ms)\n * @returns Promise that resolves when the trial starts\n * @throws Error if element is not found within timeout\n *\n * @example\n * ```typescript\n * await recorder.startTrialWithDiscovery(\n * { trialId: \"trial_1\" },\n * \"textarea.response-input\",\n * document.body,\n * 3000\n * );\n * ```\n */\n startTrialWithDiscovery(\n config: VanillaTrialConfig,\n selector: string,\n container: HTMLElement | Document = document,\n timeout = 5000,\n ): Promise<void> {\n return new Promise((resolve, reject) => {\n // Try immediate discovery first\n const element = container.querySelector(selector) as HTMLElement | null;\n if (element !== null) {\n this.startTrial({ ...config, targetElement: element });\n resolve();\n return;\n }\n\n // Use MutationObserver for delayed discovery\n this.discoveryCleanup = discoverElement({\n selector,\n container: container as HTMLElement,\n timeout,\n onFound: (el) => {\n this.discoveryCleanup = null;\n this.startTrial({ ...config, targetElement: el });\n resolve();\n },\n onTimeout: () => {\n this.discoveryCleanup = null;\n // Start trial anyway without element\n this.startTrial(config);\n reject(new Error(`Element \"${selector}\" not found within ${timeout}ms`));\n },\n });\n });\n }\n\n /**\n * End the current trial and return captured data.\n *\n * This method accepts either a string or ResponseInfo for convenience.\n * Strings are automatically converted to text responses with character\n * and word counts.\n *\n * @param response - The participant's response (text string or ResponseInfo)\n * @returns The completed trial with behavioral data\n * @throws Error if no trial is in progress\n *\n * @example\n * ```typescript\n * // With a simple text response\n * const result = recorder.endTrial(\"The participant's typed response\");\n *\n * // With a ResponseInfo object\n * const result = recorder.endTrial({\n * type: \"text\",\n * value: \"Response text\",\n * characterCount: 13,\n * wordCount: 2,\n * });\n * ```\n */\n override endTrial(\n response?: string | ResponseInfo,\n platformData?: Record<string, unknown>,\n ): VanillaTrialResult {\n // Clean up any pending discovery\n if (this.discoveryCleanup !== null) {\n this.discoveryCleanup();\n this.discoveryCleanup = null;\n }\n\n // Normalize response: convert string to ResponseInfo\n let responseInfo: ResponseInfo | undefined;\n if (typeof response === \"string\") {\n responseInfo = {\n type: \"text\",\n value: response,\n characterCount: response.length,\n wordCount: response\n .trim()\n .split(/\\s+/)\n .filter((w) => w.length > 0).length,\n };\n } else if (response !== undefined) {\n responseInfo = response;\n }\n\n // Call the base class endTrial\n const trial = super.endTrial(responseInfo, platformData);\n\n return {\n trialId: trial.trialId,\n trialIndex: trial.trialIndex,\n trialType: trial.trialType,\n startTime: trial.startTime,\n endTime: trial.endTime,\n data: {\n behavioral: trial.behavioral ?? {\n keystrokes: [],\n focus: [],\n paste: [],\n mouse: [],\n scroll: [],\n clipboard: [],\n inputDuration: [],\n metrics: {},\n },\n flags: trial.captureFlags ?? [],\n },\n rt: trial.endTime - trial.startTime,\n };\n }\n\n /**\n * Check if a trial is currently in progress.\n *\n * @returns True if a trial is active\n *\n * @example\n * ```typescript\n * if (recorder.isTrialActive()) {\n * recorder.endTrial(responseText);\n * }\n * ```\n */\n isTrialActive(): boolean {\n return this.isTrialInProgress();\n }\n\n /**\n * Get the current trial ID, or null if no trial is active.\n *\n * @returns The current trial ID or null\n *\n * @example\n * ```typescript\n * const trialId = recorder.getCurrentTrialId();\n * if (trialId !== null) {\n * console.log(`Recording trial: ${trialId}`);\n * }\n * ```\n */\n getCurrentTrialId(): string | null {\n const trial = this.getCurrentTrial();\n return trial?.trialId ?? null;\n }\n\n /**\n * Get the number of completed trials.\n *\n * @returns The count of completed trials\n *\n * @example\n * ```typescript\n * console.log(`Completed ${recorder.getTrialCount()} trials`);\n * ```\n */\n getTrialCount(): number {\n return this.getTrials().length;\n }\n\n /**\n * Reset the recorder for a new session.\n *\n * Clears all trials, detaches any active capture, and generates a new\n * session ID. Use this when starting a new experiment session with the\n * same participant.\n *\n * @example\n * ```typescript\n * // After completing a session\n * const session = recorder.exportSession();\n * await saveSession(session);\n *\n * // Reset for a new session\n * recorder.resetSession();\n * ```\n */\n resetSession(): void {\n // Clean up pending discovery\n if (this.discoveryCleanup !== null) {\n this.discoveryCleanup();\n this.discoveryCleanup = null;\n }\n this.reset();\n }\n\n /**\n * Export the session data.\n *\n * @returns Complete session data in SlopitSession format\n *\n * @example\n * ```typescript\n * const session = recorder.exportSession();\n * await fetch(\"/api/sessions\", {\n * method: \"POST\",\n * headers: { \"Content-Type\": \"application/json\" },\n * body: JSON.stringify(session),\n * });\n * ```\n */\n override exportSession(): SlopitSession {\n return super.exportSession();\n }\n\n /**\n * Export session data as a JSON string.\n *\n * Convenience method for storing or transmitting session data.\n *\n * @returns JSON string representation of the session\n *\n * @example\n * ```typescript\n * const json = recorder.exportSessionJSON();\n * localStorage.setItem(\"session\", json);\n * ```\n */\n exportSessionJSON(): string {\n return JSON.stringify(this.exportSession());\n }\n}\n\n// Also export as VanillaRecorder for clarity\nexport { SlopitRecorder as VanillaRecorder };\n"]}
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@slopit/adapter-vanilla",
3
+ "version": "0.1.0",
4
+ "description": "Framework-agnostic adapter for slopit behavioral capture",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": {
8
+ "name": "Aaron Steven White",
9
+ "email": "aaron.white@rochester.edu",
10
+ "url": "https://aaronstevenwhite.io"
11
+ },
12
+ "homepage": "https://slopit.github.io",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/slopit/slopit.git",
16
+ "directory": "packages/adapter-vanilla"
17
+ },
18
+ "bugs": {
19
+ "url": "https://github.com/slopit/slopit/issues"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "keywords": [
25
+ "behavioral-research",
26
+ "experiment",
27
+ "psychology",
28
+ "ai-detection",
29
+ "crowdsourcing",
30
+ "vanilla"
31
+ ],
32
+ "exports": {
33
+ ".": {
34
+ "import": "./dist/index.js",
35
+ "types": "./dist/index.d.ts"
36
+ }
37
+ },
38
+ "files": [
39
+ "dist"
40
+ ],
41
+ "dependencies": {
42
+ "@slopit/adapter-shared": "0.1.0",
43
+ "@slopit/behavioral": "0.1.0",
44
+ "@slopit/core": "0.1.0"
45
+ },
46
+ "devDependencies": {
47
+ "jsdom": "^25.0.1",
48
+ "tsup": "^8.3.5",
49
+ "typescript": "^5.7.2",
50
+ "vitest": "^2.1.8"
51
+ },
52
+ "scripts": {
53
+ "build": "tsup",
54
+ "typecheck": "tsc --noEmit",
55
+ "test": "vitest run",
56
+ "test:watch": "vitest",
57
+ "clean": "rm -rf dist"
58
+ }
59
+ }