@slopit/adapter-jspsych 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.
package/README.md ADDED
@@ -0,0 +1,661 @@
1
+ # @slopit/adapter-jspsych
2
+
3
+ jsPsych 8.x adapter for slopit behavioral capture.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @slopit/adapter-jspsych
9
+ ```
10
+
11
+ **Peer Dependencies:**
12
+
13
+ - `jspsych` ^8.0.0
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import { initJsPsych } from "jspsych";
19
+ import { SlopitSurveyTextPlugin, exportToSlopit } from "@slopit/adapter-jspsych";
20
+
21
+ const jsPsych = initJsPsych({
22
+ on_finish: () => {
23
+ // export all data in slopit format
24
+ const session = exportToSlopit(jsPsych, {
25
+ participantId: jsPsych.data.urlVariables().PROLIFIC_PID,
26
+ studyId: "my-study-001",
27
+ });
28
+
29
+ // send to server
30
+ fetch("/api/submit", {
31
+ method: "POST",
32
+ headers: { "Content-Type": "application/json" },
33
+ body: JSON.stringify(session),
34
+ });
35
+ },
36
+ });
37
+
38
+ const timeline = [
39
+ {
40
+ type: SlopitSurveyTextPlugin,
41
+ prompt: "Describe your morning routine in detail:",
42
+ rows: 6,
43
+ minLength: 50,
44
+ slopit: {
45
+ keystroke: { enabled: true },
46
+ focus: { enabled: true },
47
+ paste: { enabled: true, prevent: false },
48
+ },
49
+ },
50
+ ];
51
+
52
+ jsPsych.run(timeline);
53
+ ```
54
+
55
+ ## API
56
+
57
+ ### SlopitSurveyTextPlugin
58
+
59
+ A jsPsych plugin for text responses with integrated behavioral capture.
60
+
61
+ #### Parameters
62
+
63
+ | Parameter | Type | Default | Description |
64
+ |-----------|------|---------|-------------|
65
+ | prompt | string | required | The prompt or question to display (supports HTML) |
66
+ | placeholder | string | "" | Placeholder text for the textarea |
67
+ | rows | number | 5 | Number of rows for the textarea |
68
+ | columns | number | 40 | Number of columns for the textarea |
69
+ | required | boolean | true | Whether a response is required |
70
+ | minLength | number | 0 | Minimum character count (0 for no minimum) |
71
+ | maxLength | number | 0 | Maximum character count (0 for no maximum) |
72
+ | buttonLabel | string | "Continue" | Text for the submit button |
73
+ | slopit | SlopitConfig | default config | Behavioral capture configuration |
74
+
75
+ #### Data Generated
76
+
77
+ | Field | Type | Description |
78
+ |-------|------|-------------|
79
+ | response | string | The participant's text response |
80
+ | rt | number | Response time in milliseconds |
81
+ | characterCount | number | Character count of response |
82
+ | wordCount | number | Word count of response |
83
+ | slopit | object | Behavioral capture data and flags |
84
+
85
+ #### Basic Usage
86
+
87
+ ```typescript
88
+ import { SlopitSurveyTextPlugin } from "@slopit/adapter-jspsych";
89
+
90
+ const trial = {
91
+ type: SlopitSurveyTextPlugin,
92
+ prompt: "What are your thoughts on this topic?",
93
+ };
94
+ ```
95
+
96
+ #### With All Options
97
+
98
+ ```typescript
99
+ const trial = {
100
+ type: SlopitSurveyTextPlugin,
101
+ prompt: `
102
+ <h3>Essay Question</h3>
103
+ <p>Please write a detailed response about your experience.</p>
104
+ `,
105
+ placeholder: "Type your response here...",
106
+ rows: 8,
107
+ columns: 60,
108
+ required: true,
109
+ minLength: 100,
110
+ maxLength: 2000,
111
+ buttonLabel: "Submit Response",
112
+ slopit: {
113
+ keystroke: {
114
+ enabled: true,
115
+ captureKeyUp: true,
116
+ includeModifiers: true,
117
+ },
118
+ focus: {
119
+ enabled: true,
120
+ useVisibilityAPI: true,
121
+ useBlurFocus: true,
122
+ },
123
+ paste: {
124
+ enabled: true,
125
+ prevent: false,
126
+ capturePreview: true,
127
+ previewLength: 200,
128
+ },
129
+ clipboard: {
130
+ enabled: true,
131
+ capturePaste: true,
132
+ captureCopyCut: true,
133
+ },
134
+ mouse: {
135
+ enabled: true,
136
+ captureClicks: true,
137
+ captureMovement: true,
138
+ throttleMs: 50,
139
+ },
140
+ scroll: {
141
+ enabled: true,
142
+ throttleMs: 100,
143
+ },
144
+ inputDuration: {
145
+ enabled: true,
146
+ trackKeystrokes: true,
147
+ trackPastes: true,
148
+ },
149
+ },
150
+ };
151
+ ```
152
+
153
+ #### Preventing Paste
154
+
155
+ ```typescript
156
+ const trial = {
157
+ type: SlopitSurveyTextPlugin,
158
+ prompt: "Write your response without copying from other sources:",
159
+ slopit: {
160
+ paste: {
161
+ enabled: true,
162
+ prevent: true,
163
+ warnMessage: "Pasting is not allowed for this question.",
164
+ },
165
+ },
166
+ };
167
+ ```
168
+
169
+ ### exportToSlopit
170
+
171
+ Exports jsPsych data to the SlopitSession format for server-side analysis.
172
+
173
+ ```typescript
174
+ import { exportToSlopit } from "@slopit/adapter-jspsych";
175
+
176
+ const session = exportToSlopit(jsPsych, options);
177
+ ```
178
+
179
+ #### ExportOptions
180
+
181
+ | Option | Type | Default | Description |
182
+ |--------|------|---------|-------------|
183
+ | participantId | string | undefined | Participant ID (e.g., from Prolific) |
184
+ | studyId | string | undefined | Study ID for grouping sessions |
185
+ | trialFilter | function | undefined | Filter function to select trials |
186
+ | includePlatformData | boolean | true | Whether to include raw jsPsych trial data |
187
+
188
+ #### Basic Export
189
+
190
+ ```typescript
191
+ const session = exportToSlopit(jsPsych);
192
+ console.log(JSON.stringify(session, null, 2));
193
+ ```
194
+
195
+ #### With Participant Metadata
196
+
197
+ ```typescript
198
+ const urlParams = jsPsych.data.urlVariables();
199
+
200
+ const session = exportToSlopit(jsPsych, {
201
+ participantId: urlParams.PROLIFIC_PID,
202
+ studyId: "attention-check-study-v2",
203
+ });
204
+ ```
205
+
206
+ #### Filtering Trials
207
+
208
+ ```typescript
209
+ // only export trials with slopit data
210
+ const session = exportToSlopit(jsPsych, {
211
+ trialFilter: (trial) => trial.slopit !== undefined,
212
+ });
213
+
214
+ // only export specific trial types
215
+ const session = exportToSlopit(jsPsych, {
216
+ trialFilter: (trial) => trial.trial_type === "slopit-survey-text",
217
+ });
218
+ ```
219
+
220
+ #### Excluding Platform Data
221
+
222
+ ```typescript
223
+ // minimize payload size by excluding raw jsPsych data
224
+ const session = exportToSlopit(jsPsych, {
225
+ includePlatformData: false,
226
+ });
227
+ ```
228
+
229
+ ### getSlopitDataFromTrial
230
+
231
+ Retrieves slopit data from a specific trial.
232
+
233
+ ```typescript
234
+ import { getSlopitDataFromTrial } from "@slopit/adapter-jspsych";
235
+
236
+ const data = getSlopitDataFromTrial(jsPsych, trialIndex);
237
+ if (data) {
238
+ console.log("Behavioral data:", data.behavioral);
239
+ console.log("Flags:", data.flags);
240
+ }
241
+ ```
242
+
243
+ ## Configuration
244
+
245
+ ### SlopitConfig
246
+
247
+ The `slopit` parameter accepts the same configuration as `BehavioralCaptureConfig` from `@slopit/behavioral`, plus an optional `enabled` flag.
248
+
249
+ ```typescript
250
+ interface SlopitConfig {
251
+ enabled?: boolean; // enable/disable slopit for this trial (default: true)
252
+ keystroke?: KeystrokeCaptureConfig;
253
+ focus?: FocusCaptureConfig;
254
+ paste?: PasteCaptureConfig;
255
+ clipboard?: ClipboardCaptureConfig;
256
+ mouse?: MouseCaptureConfig;
257
+ scroll?: ScrollCaptureConfig;
258
+ inputDuration?: InputDurationCaptureConfig;
259
+ }
260
+ ```
261
+
262
+ ### Default Configuration
263
+
264
+ When no `slopit` parameter is provided, the plugin uses these defaults:
265
+
266
+ ```typescript
267
+ {
268
+ keystroke: { enabled: true },
269
+ focus: { enabled: true },
270
+ paste: { enabled: true, prevent: false },
271
+ }
272
+ ```
273
+
274
+ ## Examples
275
+
276
+ ### Complete Experiment
277
+
278
+ ```typescript
279
+ import { initJsPsych } from "jspsych";
280
+ import htmlKeyboardResponse from "@jspsych/plugin-html-keyboard-response";
281
+ import { SlopitSurveyTextPlugin, exportToSlopit } from "@slopit/adapter-jspsych";
282
+
283
+ const jsPsych = initJsPsych({
284
+ on_finish: async () => {
285
+ const session = exportToSlopit(jsPsych, {
286
+ participantId: jsPsych.data.urlVariables().PROLIFIC_PID,
287
+ studyId: "writing-study-v1",
288
+ });
289
+
290
+ await fetch("/api/submit", {
291
+ method: "POST",
292
+ headers: { "Content-Type": "application/json" },
293
+ body: JSON.stringify(session),
294
+ });
295
+
296
+ // redirect to completion page
297
+ window.location.href = "https://example.com/complete";
298
+ },
299
+ });
300
+
301
+ const timeline = [];
302
+
303
+ // instructions
304
+ timeline.push({
305
+ type: htmlKeyboardResponse,
306
+ stimulus: `
307
+ <h2>Writing Task</h2>
308
+ <p>You will be asked to write several short responses.</p>
309
+ <p>Please type your responses yourself without using AI assistance.</p>
310
+ <p>Press any key to continue.</p>
311
+ `,
312
+ });
313
+
314
+ // writing trials
315
+ const prompts = [
316
+ "Describe a memorable experience from your childhood.",
317
+ "Explain your opinion on a current social issue.",
318
+ "Write about a goal you hope to achieve in the next year.",
319
+ ];
320
+
321
+ for (const prompt of prompts) {
322
+ timeline.push({
323
+ type: SlopitSurveyTextPlugin,
324
+ prompt: `<p>${prompt}</p>`,
325
+ rows: 6,
326
+ minLength: 100,
327
+ slopit: {
328
+ keystroke: { enabled: true, captureKeyUp: true },
329
+ focus: { enabled: true },
330
+ paste: { enabled: true },
331
+ mouse: { enabled: true, throttleMs: 100 },
332
+ },
333
+ });
334
+ }
335
+
336
+ // debrief
337
+ timeline.push({
338
+ type: htmlKeyboardResponse,
339
+ stimulus: `
340
+ <h2>Thank you!</h2>
341
+ <p>Your responses have been recorded.</p>
342
+ <p>Press any key to complete the study.</p>
343
+ `,
344
+ });
345
+
346
+ jsPsych.run(timeline);
347
+ ```
348
+
349
+ ### With Intervention Warnings
350
+
351
+ ```typescript
352
+ import { initJsPsych } from "jspsych";
353
+ import { SlopitSurveyTextPlugin, getSlopitDataFromTrial } from "@slopit/adapter-jspsych";
354
+
355
+ const jsPsych = initJsPsych();
356
+
357
+ const writingTrial = {
358
+ type: SlopitSurveyTextPlugin,
359
+ prompt: "Write a short paragraph about your hobbies:",
360
+ rows: 5,
361
+ minLength: 50,
362
+ slopit: {
363
+ keystroke: { enabled: true },
364
+ paste: { enabled: true },
365
+ },
366
+ };
367
+
368
+ // check for suspicious behavior after trial
369
+ const checkTrial = {
370
+ type: "call-function",
371
+ func: () => {
372
+ const lastTrialIndex = jsPsych.data.get().count() - 1;
373
+ const data = getSlopitDataFromTrial(jsPsych, lastTrialIndex);
374
+
375
+ if (data?.flags && data.flags.length > 0) {
376
+ const pasteFlags = data.flags.filter(f => f.type === "paste_detected");
377
+ if (pasteFlags.length > 0) {
378
+ console.log("Warning: Paste detected in response");
379
+ }
380
+ }
381
+ },
382
+ };
383
+
384
+ const timeline = [writingTrial, checkTrial];
385
+ jsPsych.run(timeline);
386
+ ```
387
+
388
+ ### Multiple Response Types
389
+
390
+ ```typescript
391
+ import { initJsPsych } from "jspsych";
392
+ import surveyMultiChoice from "@jspsych/plugin-survey-multi-choice";
393
+ import { SlopitSurveyTextPlugin, exportToSlopit } from "@slopit/adapter-jspsych";
394
+
395
+ const jsPsych = initJsPsych();
396
+
397
+ const timeline = [
398
+ // multiple choice (no slopit capture)
399
+ {
400
+ type: surveyMultiChoice,
401
+ questions: [
402
+ {
403
+ prompt: "What is your age range?",
404
+ options: ["18-24", "25-34", "35-44", "45+"],
405
+ required: true,
406
+ },
407
+ ],
408
+ },
409
+
410
+ // text response with slopit
411
+ {
412
+ type: SlopitSurveyTextPlugin,
413
+ prompt: "Please describe your educational background:",
414
+ rows: 4,
415
+ slopit: {
416
+ keystroke: { enabled: true },
417
+ focus: { enabled: true },
418
+ },
419
+ },
420
+
421
+ // longer essay with full capture
422
+ {
423
+ type: SlopitSurveyTextPlugin,
424
+ prompt: "Write about a challenge you overcame:",
425
+ rows: 8,
426
+ minLength: 200,
427
+ slopit: {
428
+ keystroke: { enabled: true, captureKeyUp: true },
429
+ focus: { enabled: true },
430
+ paste: { enabled: true },
431
+ mouse: { enabled: true },
432
+ scroll: { enabled: true },
433
+ inputDuration: { enabled: true },
434
+ },
435
+ },
436
+ ];
437
+
438
+ jsPsych.run(timeline);
439
+ ```
440
+
441
+ ### Accessing Data During Experiment
442
+
443
+ ```typescript
444
+ import { initJsPsych } from "jspsych";
445
+ import htmlButtonResponse from "@jspsych/plugin-html-button-response";
446
+ import { SlopitSurveyTextPlugin, getSlopitDataFromTrial } from "@slopit/adapter-jspsych";
447
+
448
+ const jsPsych = initJsPsych();
449
+
450
+ const timeline = [
451
+ {
452
+ type: SlopitSurveyTextPlugin,
453
+ prompt: "Write about your day:",
454
+ rows: 5,
455
+ },
456
+ {
457
+ type: htmlButtonResponse,
458
+ stimulus: () => {
459
+ const lastIndex = jsPsych.data.get().count() - 1;
460
+ const data = getSlopitDataFromTrial(jsPsych, lastIndex);
461
+
462
+ if (!data) return "<p>No behavioral data captured.</p>";
463
+
464
+ const metrics = data.behavioral?.metrics?.keystroke;
465
+ const timing = data.behavioral?.metrics?.timing;
466
+
467
+ return `
468
+ <h3>Your Writing Statistics</h3>
469
+ <p>Keystrokes: ${metrics?.totalKeystrokes ?? 0}</p>
470
+ <p>Mean typing interval: ${Math.round(metrics?.meanIKI ?? 0)}ms</p>
471
+ <p>Characters per minute: ${Math.round(timing?.charactersPerMinute ?? 0)}</p>
472
+ `;
473
+ },
474
+ choices: ["Continue"],
475
+ },
476
+ ];
477
+
478
+ jsPsych.run(timeline);
479
+ ```
480
+
481
+ ## Data Structure
482
+
483
+ ### Trial Data Output
484
+
485
+ Each SlopitSurveyTextPlugin trial generates data in this structure:
486
+
487
+ ```typescript
488
+ {
489
+ response: "The participant's typed response...",
490
+ rt: 45230,
491
+ characterCount: 234,
492
+ wordCount: 42,
493
+ slopit: {
494
+ behavioral: {
495
+ keystrokes: [
496
+ { time: 1234, key: "T", code: "KeyT", event: "keydown", textLength: 1 },
497
+ { time: 1300, key: "T", code: "KeyT", event: "keyup" },
498
+ // ... more keystrokes
499
+ ],
500
+ focus: [
501
+ { time: 15000, event: "blur" },
502
+ { time: 18500, event: "focus", blurDuration: 3500 },
503
+ ],
504
+ paste: [
505
+ { time: 25000, textLength: 50, precedingKeystrokes: 3, blocked: false },
506
+ ],
507
+ metrics: {
508
+ keystroke: {
509
+ totalKeystrokes: 280,
510
+ printableKeystrokes: 250,
511
+ deletions: 15,
512
+ meanIKI: 152.3,
513
+ stdIKI: 45.2,
514
+ medianIKI: 140,
515
+ pauseCount: 5,
516
+ productProcessRatio: 0.84,
517
+ },
518
+ focus: {
519
+ blurCount: 1,
520
+ totalBlurDuration: 3500,
521
+ hiddenCount: 0,
522
+ totalHiddenDuration: 0,
523
+ },
524
+ timing: {
525
+ firstKeystrokeLatency: 1234,
526
+ totalResponseTime: 45230,
527
+ charactersPerMinute: 310,
528
+ },
529
+ },
530
+ },
531
+ flags: [
532
+ {
533
+ type: "paste_detected",
534
+ severity: "medium",
535
+ message: "1 paste event(s) detected",
536
+ timestamp: 1706123456789,
537
+ details: { count: 1 },
538
+ },
539
+ ],
540
+ },
541
+ trial_type: "slopit-survey-text",
542
+ trial_index: 2,
543
+ time_elapsed: 48500,
544
+ }
545
+ ```
546
+
547
+ ### Exported Session Structure
548
+
549
+ The `exportToSlopit` function produces a `SlopitSession` object:
550
+
551
+ ```typescript
552
+ {
553
+ schemaVersion: "1.0.0",
554
+ sessionId: "session_1706123456789_a1b2c3d4",
555
+ participantId: "P12345",
556
+ studyId: "writing-study-v1",
557
+ platform: {
558
+ name: "jspsych",
559
+ version: "8.0.0",
560
+ adapterVersion: "0.1.0",
561
+ },
562
+ environment: {
563
+ userAgent: "Mozilla/5.0 ...",
564
+ language: "en-US",
565
+ platform: "MacIntel",
566
+ screenWidth: 2560,
567
+ screenHeight: 1440,
568
+ // ... more environment data
569
+ },
570
+ timing: {
571
+ startTime: 1706123400000,
572
+ endTime: 1706123856789,
573
+ duration: 456789,
574
+ },
575
+ trials: [
576
+ {
577
+ trialId: "trial-0",
578
+ trialIndex: 0,
579
+ trialType: "slopit-survey-text",
580
+ startTime: 3270,
581
+ endTime: 48500,
582
+ rt: 45230,
583
+ response: {
584
+ type: "text",
585
+ value: "The participant's typed response...",
586
+ characterCount: 234,
587
+ wordCount: 42,
588
+ },
589
+ behavioral: { /* BehavioralData */ },
590
+ captureFlags: [ /* CaptureFlag[] */ ],
591
+ platformData: { /* raw jsPsych trial data */ },
592
+ },
593
+ // ... more trials
594
+ ],
595
+ globalEvents: {
596
+ focus: [],
597
+ errors: [],
598
+ },
599
+ }
600
+ ```
601
+
602
+ ## Styling
603
+
604
+ The plugin generates HTML with CSS classes you can style:
605
+
606
+ ```css
607
+ /* container */
608
+ .slopit-survey-text {
609
+ max-width: 800px;
610
+ margin: 0 auto;
611
+ }
612
+
613
+ /* prompt area */
614
+ .slopit-prompt {
615
+ margin-bottom: 1rem;
616
+ font-size: 1.1em;
617
+ }
618
+
619
+ /* textarea container */
620
+ .slopit-input-container {
621
+ margin-bottom: 1rem;
622
+ }
623
+
624
+ /* the textarea itself */
625
+ #slopit-response {
626
+ width: 100%;
627
+ padding: 0.5rem;
628
+ font-size: 1rem;
629
+ font-family: inherit;
630
+ border: 1px solid #ccc;
631
+ border-radius: 4px;
632
+ }
633
+
634
+ /* character counter */
635
+ .slopit-char-counter {
636
+ text-align: right;
637
+ font-size: 0.9em;
638
+ color: #666;
639
+ margin-top: 0.25rem;
640
+ }
641
+
642
+ /* submit button container */
643
+ .slopit-button-container {
644
+ text-align: center;
645
+ }
646
+
647
+ /* validation error message */
648
+ .slopit-validation-error {
649
+ color: red;
650
+ margin-top: 10px;
651
+ text-align: center;
652
+ }
653
+ ```
654
+
655
+ ## Keyboard Shortcuts
656
+
657
+ - **Ctrl+Enter** or **Cmd+Enter**: Submit the response
658
+
659
+ ## License
660
+
661
+ MIT
@@ -0,0 +1,197 @@
1
+ import { BehavioralCaptureConfig } from '@slopit/behavioral';
2
+ import { JsPsychExtension, JsPsychExtensionInfo, JsPsych } from 'jspsych';
3
+ import { BehavioralData, CaptureFlag, SlopitSession } from '@slopit/core';
4
+
5
+ /**
6
+ * Configuration for slopit behavioral capture in jsPsych.
7
+ */
8
+ interface SlopitConfig extends BehavioralCaptureConfig {
9
+ /**
10
+ * Enable/disable slopit capture for this trial.
11
+ * @default true
12
+ */
13
+ enabled?: boolean;
14
+ /**
15
+ * CSS selector for the input element to monitor.
16
+ *
17
+ * If not specified, the extension searches for textarea or text input elements.
18
+ *
19
+ * @default "textarea, input[type='text']"
20
+ */
21
+ targetSelector?: string;
22
+ }
23
+ /**
24
+ * Data generated by slopit behavioral capture.
25
+ */
26
+ interface SlopitData {
27
+ /**
28
+ * Behavioral capture data including events and metrics.
29
+ */
30
+ behavioral: BehavioralData;
31
+ /**
32
+ * Flags generated during capture indicating potential AI-assisted responses.
33
+ */
34
+ flags: CaptureFlag[];
35
+ }
36
+
37
+ /**
38
+ * jsPsych extension for adding behavioral capture to existing plugins.
39
+ *
40
+ * @module
41
+ */
42
+
43
+ /**
44
+ * Extension parameters passed to individual trials.
45
+ */
46
+ interface SlopitExtensionParams extends BehavioralCaptureConfig {
47
+ /**
48
+ * CSS selector for the input element to monitor.
49
+ *
50
+ * If not specified, the extension will search for textarea or text input
51
+ * elements within the trial display.
52
+ *
53
+ * @default "textarea, input[type='text']"
54
+ */
55
+ targetSelector?: string;
56
+ }
57
+ /**
58
+ * jsPsych extension for behavioral capture.
59
+ *
60
+ * This extension wraps existing jsPsych plugins to add behavioral capture
61
+ * without requiring plugin modifications. It attaches to text input elements
62
+ * and collects keystroke dynamics, focus events, and clipboard operations.
63
+ *
64
+ * @example
65
+ * ```javascript
66
+ * import { initJsPsych } from "jspsych";
67
+ * import jsPsychSurveyText from "@jspsych/plugin-survey-text";
68
+ * import { SlopitExtension } from "@slopit/adapter-jspsych";
69
+ *
70
+ * const jsPsych = initJsPsych({
71
+ * extensions: [{ type: SlopitExtension }],
72
+ * });
73
+ *
74
+ * const trial = {
75
+ * type: jsPsychSurveyText,
76
+ * questions: [{ prompt: "Describe your morning routine:" }],
77
+ * extensions: [
78
+ * {
79
+ * type: SlopitExtension,
80
+ * params: {
81
+ * targetSelector: "textarea",
82
+ * keystroke: { enabled: true },
83
+ * paste: { enabled: true, prevent: false },
84
+ * },
85
+ * },
86
+ * ],
87
+ * };
88
+ * ```
89
+ */
90
+ declare class SlopitExtension implements JsPsychExtension {
91
+ static info: JsPsychExtensionInfo;
92
+ private jsPsych;
93
+ private capture;
94
+ private params;
95
+ private startTime;
96
+ private attachedElement;
97
+ private observerCleanup;
98
+ /**
99
+ * Creates a new SlopitExtension instance.
100
+ *
101
+ * @param jsPsych - The jsPsych instance
102
+ */
103
+ constructor(jsPsych: JsPsych);
104
+ /**
105
+ * Initializes the extension. Called once when jsPsych initializes.
106
+ *
107
+ * @param _params - Initialization parameters (unused)
108
+ * @returns Promise that resolves when initialization is complete
109
+ */
110
+ initialize(_params: Record<string, unknown>): Promise<void>;
111
+ /**
112
+ * Called when a trial using this extension begins.
113
+ *
114
+ * @param params - Extension parameters for this trial
115
+ */
116
+ on_start(params: SlopitExtensionParams): void;
117
+ /**
118
+ * Called after the trial display is rendered.
119
+ *
120
+ * Searches for the target element and attaches behavioral capture.
121
+ *
122
+ * @param params - Extension parameters for this trial
123
+ */
124
+ on_load(params: SlopitExtensionParams): void;
125
+ /**
126
+ * Called when the trial ends.
127
+ *
128
+ * @returns Object containing behavioral capture data
129
+ */
130
+ on_finish(): {
131
+ slopit: SlopitData;
132
+ } | Record<string, never>;
133
+ /**
134
+ * Attaches behavioral capture to the target element.
135
+ *
136
+ * @param element - The element to attach to
137
+ * @param params - Extension parameters
138
+ */
139
+ private attachCapture;
140
+ }
141
+
142
+ /**
143
+ * Options for exporting jsPsych data to SlopitSession format.
144
+ */
145
+ interface ExportOptions {
146
+ /**
147
+ * Participant ID (e.g., from Prolific).
148
+ */
149
+ participantId?: string;
150
+ /**
151
+ * Study ID.
152
+ */
153
+ studyId?: string;
154
+ /**
155
+ * Filter function to select which trials to include.
156
+ * @param trial - The jsPsych trial data
157
+ * @returns true to include, false to exclude
158
+ */
159
+ trialFilter?: (trial: Record<string, unknown>) => boolean;
160
+ /**
161
+ * Whether to include raw platform data for each trial.
162
+ * @default true
163
+ */
164
+ includePlatformData?: boolean;
165
+ }
166
+ /**
167
+ * Export jsPsych data to SlopitSession format.
168
+ *
169
+ * @param jsPsych - The jsPsych instance
170
+ * @param options - Export options
171
+ * @returns SlopitSession object
172
+ *
173
+ * @example
174
+ * ```javascript
175
+ * const session = exportToSlopit(jsPsych, {
176
+ * participantId: jsPsych.data.urlVariables().PROLIFIC_PID,
177
+ * studyId: "my-study-001",
178
+ * });
179
+ *
180
+ * // Send to server or save
181
+ * console.log(JSON.stringify(session));
182
+ * ```
183
+ */
184
+ declare function exportToSlopit(jsPsych: JsPsych, options?: ExportOptions): SlopitSession;
185
+ /**
186
+ * Get slopit data from a specific trial.
187
+ *
188
+ * @param jsPsych - The jsPsych instance
189
+ * @param trialIndex - The trial index to get data from
190
+ * @returns The slopit data or undefined if not found
191
+ */
192
+ declare function getSlopitDataFromTrial(jsPsych: JsPsych, trialIndex: number): {
193
+ behavioral: unknown;
194
+ flags: unknown[];
195
+ } | undefined;
196
+
197
+ export { type ExportOptions, type SlopitConfig, type SlopitData, SlopitExtension, type SlopitExtensionParams, exportToSlopit, getSlopitDataFromTrial };
package/dist/index.js ADDED
@@ -0,0 +1,203 @@
1
+ import { discoverElement, createSessionMetadata, completeSession, createTextResponse } from '@slopit/adapter-shared';
2
+ import { createBehavioralCapture } from '@slopit/behavioral';
3
+ import { ParameterType } from 'jspsych';
4
+
5
+ // src/extension.ts
6
+ var SlopitExtension = class {
7
+ static info = {
8
+ name: "slopit",
9
+ version: "0.1.0",
10
+ data: {
11
+ slopit: {
12
+ type: ParameterType.OBJECT
13
+ }
14
+ }
15
+ };
16
+ jsPsych;
17
+ capture = null;
18
+ params = null;
19
+ startTime = 0;
20
+ attachedElement = null;
21
+ observerCleanup = null;
22
+ /**
23
+ * Creates a new SlopitExtension instance.
24
+ *
25
+ * @param jsPsych - The jsPsych instance
26
+ */
27
+ constructor(jsPsych) {
28
+ this.jsPsych = jsPsych;
29
+ }
30
+ /**
31
+ * Initializes the extension. Called once when jsPsych initializes.
32
+ *
33
+ * @param _params - Initialization parameters (unused)
34
+ * @returns Promise that resolves when initialization is complete
35
+ */
36
+ initialize(_params) {
37
+ return Promise.resolve();
38
+ }
39
+ /**
40
+ * Called when a trial using this extension begins.
41
+ *
42
+ * @param params - Extension parameters for this trial
43
+ */
44
+ on_start(params) {
45
+ this.params = params;
46
+ this.startTime = performance.now();
47
+ }
48
+ /**
49
+ * Called after the trial display is rendered.
50
+ *
51
+ * Searches for the target element and attaches behavioral capture.
52
+ *
53
+ * @param params - Extension parameters for this trial
54
+ */
55
+ on_load(params) {
56
+ const displayElement = this.jsPsych.getDisplayElement();
57
+ const selector = params.targetSelector ?? "textarea, input[type='text']";
58
+ const cleanup = discoverElement({
59
+ selector,
60
+ container: displayElement,
61
+ timeout: 5e3,
62
+ onFound: (element) => {
63
+ this.attachCapture(element, params);
64
+ },
65
+ onTimeout: () => {
66
+ console.warn("[slopit] Target element not found within timeout");
67
+ }
68
+ });
69
+ this.observerCleanup = cleanup;
70
+ }
71
+ /**
72
+ * Called when the trial ends.
73
+ *
74
+ * @returns Object containing behavioral capture data
75
+ */
76
+ on_finish() {
77
+ if (this.observerCleanup !== null) {
78
+ this.observerCleanup();
79
+ this.observerCleanup = null;
80
+ }
81
+ if (this.capture === null) {
82
+ return {};
83
+ }
84
+ const behavioral = this.capture.getData();
85
+ const flags = this.capture.getFlags();
86
+ this.capture.detach();
87
+ this.capture = null;
88
+ this.attachedElement = null;
89
+ this.params = null;
90
+ return {
91
+ slopit: {
92
+ behavioral,
93
+ flags
94
+ }
95
+ };
96
+ }
97
+ /**
98
+ * Attaches behavioral capture to the target element.
99
+ *
100
+ * @param element - The element to attach to
101
+ * @param params - Extension parameters
102
+ */
103
+ attachCapture(element, params) {
104
+ if (this.capture !== null) {
105
+ return;
106
+ }
107
+ const config = {};
108
+ if (params.keystroke !== void 0) {
109
+ config.keystroke = params.keystroke;
110
+ }
111
+ if (params.focus !== void 0) {
112
+ config.focus = params.focus;
113
+ }
114
+ if (params.paste !== void 0) {
115
+ config.paste = params.paste;
116
+ }
117
+ if (params.clipboard !== void 0) {
118
+ config.clipboard = params.clipboard;
119
+ }
120
+ if (params.mouse !== void 0) {
121
+ config.mouse = params.mouse;
122
+ }
123
+ if (params.scroll !== void 0) {
124
+ config.scroll = params.scroll;
125
+ }
126
+ if (params.inputDuration !== void 0) {
127
+ config.inputDuration = params.inputDuration;
128
+ }
129
+ this.capture = createBehavioralCapture(config);
130
+ this.capture.attach(element, this.startTime);
131
+ this.attachedElement = element;
132
+ }
133
+ };
134
+ function exportToSlopit(jsPsych, options = {}) {
135
+ const allTrials = jsPsych.data.get().values();
136
+ const filteredTrials = options.trialFilter ? allTrials.filter(options.trialFilter) : allTrials;
137
+ const sessionStartTime = jsPsych.getStartTime()?.getTime() ?? Date.now();
138
+ const trials = filteredTrials.map((trial, index) => {
139
+ return convertTrial(trial, index, options.includePlatformData ?? true);
140
+ });
141
+ const sessionBase = createSessionMetadata(
142
+ {
143
+ name: "jspsych",
144
+ version: jsPsych.version(),
145
+ adapterVersion: "0.1.0"
146
+ },
147
+ {
148
+ ...options.participantId !== void 0 ? { participantId: options.participantId } : {},
149
+ ...options.studyId !== void 0 ? { studyId: options.studyId } : {},
150
+ startTime: sessionStartTime
151
+ }
152
+ );
153
+ return completeSession(sessionBase, trials);
154
+ }
155
+ function convertTrial(trial, index, includePlatformData) {
156
+ const timeElapsed = Number(trial["time_elapsed"] ?? 0);
157
+ const rt = Number(trial["rt"] ?? 0);
158
+ const converted = {
159
+ trialId: String(trial["trial_id"] ?? `trial-${index}`),
160
+ trialIndex: index,
161
+ trialType: String(trial["trial_type"] ?? "unknown"),
162
+ startTime: timeElapsed - rt,
163
+ endTime: timeElapsed,
164
+ rt
165
+ };
166
+ if (trial["response"] !== void 0) {
167
+ const response = trial["response"];
168
+ if (typeof response === "string") {
169
+ converted.response = createTextResponse(response);
170
+ } else {
171
+ converted.response = {
172
+ type: "other",
173
+ value: response
174
+ };
175
+ }
176
+ }
177
+ if (trial["slopit"] && typeof trial["slopit"] === "object") {
178
+ const sd = trial["slopit"];
179
+ if (sd["behavioral"]) {
180
+ converted.behavioral = sd["behavioral"];
181
+ }
182
+ if (sd["flags"] && Array.isArray(sd["flags"])) {
183
+ converted.captureFlags = sd["flags"];
184
+ }
185
+ }
186
+ if (includePlatformData) {
187
+ const platformData = { ...trial };
188
+ delete platformData["slopit"];
189
+ converted.platformData = platformData;
190
+ }
191
+ return converted;
192
+ }
193
+ function getSlopitDataFromTrial(jsPsych, trialIndex) {
194
+ const trial = jsPsych.data.get().filter({ trial_index: trialIndex }).values()[0];
195
+ if (!trial || !trial["slopit"]) {
196
+ return void 0;
197
+ }
198
+ return trial["slopit"];
199
+ }
200
+
201
+ export { SlopitExtension, exportToSlopit, getSlopitDataFromTrial };
202
+ //# sourceMappingURL=index.js.map
203
+ //#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EACT;AAEA,EAAA,OAAO,MAAM,QAAQ,CAAA;AACvB","file":"index.js","sourcesContent":["/**\n * jsPsych extension for adding behavioral capture to existing plugins.\n *\n * @module\n */\n\nimport { discoverElement } from \"@slopit/adapter-shared\";\nimport {\n type BehavioralCapture,\n type BehavioralCaptureConfig,\n createBehavioralCapture,\n} from \"@slopit/behavioral\";\nimport {\n type JsPsych,\n type JsPsychExtension,\n type JsPsychExtensionInfo,\n ParameterType,\n} from \"jspsych\";\nimport type { SlopitData } from \"./types.js\";\n\n/**\n * Extension parameters passed to individual trials.\n */\nexport interface SlopitExtensionParams extends BehavioralCaptureConfig {\n /**\n * CSS selector for the input element to monitor.\n *\n * If not specified, the extension will search for textarea or text input\n * elements within the trial display.\n *\n * @default \"textarea, input[type='text']\"\n */\n targetSelector?: string;\n}\n\n/**\n * jsPsych extension for behavioral capture.\n *\n * This extension wraps existing jsPsych plugins to add behavioral capture\n * without requiring plugin modifications. It attaches to text input elements\n * and collects keystroke dynamics, focus events, and clipboard operations.\n *\n * @example\n * ```javascript\n * import { initJsPsych } from \"jspsych\";\n * import jsPsychSurveyText from \"@jspsych/plugin-survey-text\";\n * import { SlopitExtension } from \"@slopit/adapter-jspsych\";\n *\n * const jsPsych = initJsPsych({\n * extensions: [{ type: SlopitExtension }],\n * });\n *\n * const trial = {\n * type: jsPsychSurveyText,\n * questions: [{ prompt: \"Describe your morning routine:\" }],\n * extensions: [\n * {\n * type: SlopitExtension,\n * params: {\n * targetSelector: \"textarea\",\n * keystroke: { enabled: true },\n * paste: { enabled: true, prevent: false },\n * },\n * },\n * ],\n * };\n * ```\n */\nclass SlopitExtension implements JsPsychExtension {\n static info: JsPsychExtensionInfo = {\n name: \"slopit\",\n version: \"0.1.0\",\n data: {\n slopit: {\n type: ParameterType.OBJECT,\n },\n },\n };\n\n private jsPsych: JsPsych;\n private capture: BehavioralCapture | null = null;\n private params: SlopitExtensionParams | null = null;\n private startTime = 0;\n private attachedElement: HTMLElement | null = null;\n private observerCleanup: (() => void) | null = null;\n\n /**\n * Creates a new SlopitExtension instance.\n *\n * @param jsPsych - The jsPsych instance\n */\n constructor(jsPsych: JsPsych) {\n this.jsPsych = jsPsych;\n }\n\n /**\n * Initializes the extension. Called once when jsPsych initializes.\n *\n * @param _params - Initialization parameters (unused)\n * @returns Promise that resolves when initialization is complete\n */\n initialize(_params: Record<string, unknown>): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * Called when a trial using this extension begins.\n *\n * @param params - Extension parameters for this trial\n */\n on_start(params: SlopitExtensionParams): void {\n this.params = params;\n this.startTime = performance.now();\n }\n\n /**\n * Called after the trial display is rendered.\n *\n * Searches for the target element and attaches behavioral capture.\n *\n * @param params - Extension parameters for this trial\n */\n on_load(params: SlopitExtensionParams): void {\n const displayElement = this.jsPsych.getDisplayElement();\n const selector = params.targetSelector ?? \"textarea, input[type='text']\";\n\n const cleanup = discoverElement({\n selector,\n container: displayElement,\n timeout: 5000,\n onFound: (element) => {\n this.attachCapture(element, params);\n },\n onTimeout: () => {\n console.warn(\"[slopit] Target element not found within timeout\");\n },\n });\n this.observerCleanup = cleanup;\n }\n\n /**\n * Called when the trial ends.\n *\n * @returns Object containing behavioral capture data\n */\n on_finish(): { slopit: SlopitData } | Record<string, never> {\n if (this.observerCleanup !== null) {\n this.observerCleanup();\n this.observerCleanup = null;\n }\n\n if (this.capture === null) {\n return {};\n }\n\n const behavioral = this.capture.getData();\n const flags = this.capture.getFlags();\n\n this.capture.detach();\n this.capture = null;\n this.attachedElement = null;\n this.params = null;\n\n return {\n slopit: {\n behavioral,\n flags,\n },\n };\n }\n\n /**\n * Attaches behavioral capture to the target element.\n *\n * @param element - The element to attach to\n * @param params - Extension parameters\n */\n private attachCapture(element: HTMLElement, params: SlopitExtensionParams): void {\n if (this.capture !== null) {\n return; // Already attached\n }\n\n // Build config object, omitting undefined properties\n const config: BehavioralCaptureConfig = {};\n\n if (params.keystroke !== undefined) {\n config.keystroke = params.keystroke;\n }\n if (params.focus !== undefined) {\n config.focus = params.focus;\n }\n if (params.paste !== undefined) {\n config.paste = params.paste;\n }\n if (params.clipboard !== undefined) {\n config.clipboard = params.clipboard;\n }\n if (params.mouse !== undefined) {\n config.mouse = params.mouse;\n }\n if (params.scroll !== undefined) {\n config.scroll = params.scroll;\n }\n if (params.inputDuration !== undefined) {\n config.inputDuration = params.inputDuration;\n }\n\n this.capture = createBehavioralCapture(config);\n this.capture.attach(element, this.startTime);\n this.attachedElement = element;\n }\n}\n\nexport { SlopitExtension };\n","import { completeSession, createSessionMetadata, createTextResponse } from \"@slopit/adapter-shared\";\nimport type { SlopitSession, SlopitTrial } from \"@slopit/core\";\nimport type { JsPsych } from \"jspsych\";\n\n/**\n * Options for exporting jsPsych data to SlopitSession format.\n */\nexport interface ExportOptions {\n /**\n * Participant ID (e.g., from Prolific).\n */\n participantId?: string;\n\n /**\n * Study ID.\n */\n studyId?: string;\n\n /**\n * Filter function to select which trials to include.\n * @param trial - The jsPsych trial data\n * @returns true to include, false to exclude\n */\n trialFilter?: (trial: Record<string, unknown>) => boolean;\n\n /**\n * Whether to include raw platform data for each trial.\n * @default true\n */\n includePlatformData?: boolean;\n}\n\n/**\n * Export jsPsych data to SlopitSession format.\n *\n * @param jsPsych - The jsPsych instance\n * @param options - Export options\n * @returns SlopitSession object\n *\n * @example\n * ```javascript\n * const session = exportToSlopit(jsPsych, {\n * participantId: jsPsych.data.urlVariables().PROLIFIC_PID,\n * studyId: \"my-study-001\",\n * });\n *\n * // Send to server or save\n * console.log(JSON.stringify(session));\n * ```\n */\nexport function exportToSlopit(jsPsych: JsPsych, options: ExportOptions = {}): SlopitSession {\n const allTrials = jsPsych.data.get().values() as Record<string, unknown>[];\n const filteredTrials = options.trialFilter ? allTrials.filter(options.trialFilter) : allTrials;\n\n const sessionStartTime = jsPsych.getStartTime()?.getTime() ?? Date.now();\n\n const trials: SlopitTrial[] = filteredTrials.map((trial, index) => {\n return convertTrial(trial, index, options.includePlatformData ?? true);\n });\n\n // Use shared utilities to create session metadata\n const sessionBase = createSessionMetadata(\n {\n name: \"jspsych\",\n version: jsPsych.version(),\n adapterVersion: \"0.1.0\",\n },\n {\n ...(options.participantId !== undefined ? { participantId: options.participantId } : {}),\n ...(options.studyId !== undefined ? { studyId: options.studyId } : {}),\n startTime: sessionStartTime,\n },\n );\n\n // Complete the session with trials and end time\n return completeSession(sessionBase, trials);\n}\n\nfunction convertTrial(\n trial: Record<string, unknown>,\n index: number,\n includePlatformData: boolean,\n): SlopitTrial {\n const timeElapsed = Number(trial[\"time_elapsed\"] ?? 0);\n const rt = Number(trial[\"rt\"] ?? 0);\n\n const converted: SlopitTrial = {\n trialId: String(trial[\"trial_id\"] ?? `trial-${index}`),\n trialIndex: index,\n trialType: String(trial[\"trial_type\"] ?? \"unknown\"),\n startTime: timeElapsed - rt,\n endTime: timeElapsed,\n rt: rt,\n };\n\n // Extract response if present\n if (trial[\"response\"] !== undefined) {\n const response = trial[\"response\"];\n if (typeof response === \"string\") {\n converted.response = createTextResponse(response);\n } else {\n converted.response = {\n type: \"other\",\n value: response,\n };\n }\n }\n\n // Extract slopit behavioral data if present\n if (trial[\"slopit\"] && typeof trial[\"slopit\"] === \"object\") {\n const sd = trial[\"slopit\"] as Record<string, unknown>;\n if (sd[\"behavioral\"]) {\n converted.behavioral = sd[\"behavioral\"] as NonNullable<SlopitTrial[\"behavioral\"]>;\n }\n if (sd[\"flags\"] && Array.isArray(sd[\"flags\"])) {\n converted.captureFlags = sd[\"flags\"] as NonNullable<SlopitTrial[\"captureFlags\"]>;\n }\n }\n\n // Include raw platform data if requested\n if (includePlatformData) {\n const platformData = { ...trial };\n delete platformData[\"slopit\"];\n converted.platformData = platformData;\n }\n\n return converted;\n}\n\n/**\n * Get slopit data from a specific trial.\n *\n * @param jsPsych - The jsPsych instance\n * @param trialIndex - The trial index to get data from\n * @returns The slopit data or undefined if not found\n */\nexport function getSlopitDataFromTrial(\n jsPsych: JsPsych,\n trialIndex: number,\n): { behavioral: unknown; flags: unknown[] } | undefined {\n const trial = jsPsych.data.get().filter({ trial_index: trialIndex }).values()[0] as\n | Record<string, unknown>\n | undefined;\n\n if (!trial || !trial[\"slopit\"]) {\n return undefined;\n }\n\n return trial[\"slopit\"] as { behavioral: unknown; flags: unknown[] };\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@slopit/adapter-jspsych",
3
+ "version": "0.1.0",
4
+ "description": "jsPsych integration 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-jspsych"
17
+ },
18
+ "bugs": {
19
+ "url": "https://github.com/slopit/slopit/issues"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "keywords": [
25
+ "jspsych",
26
+ "behavioral-research",
27
+ "experiment",
28
+ "psychology",
29
+ "ai-detection",
30
+ "crowdsourcing"
31
+ ],
32
+ "exports": {
33
+ ".": {
34
+ "import": "./dist/index.js",
35
+ "types": "./dist/index.d.ts"
36
+ }
37
+ },
38
+ "files": [
39
+ "dist"
40
+ ],
41
+ "peerDependencies": {
42
+ "jspsych": "^8.0.0"
43
+ },
44
+ "dependencies": {
45
+ "@slopit/adapter-shared": "0.1.0",
46
+ "@slopit/behavioral": "0.1.0",
47
+ "@slopit/core": "0.1.0"
48
+ },
49
+ "devDependencies": {
50
+ "jspsych": "^8.2.2",
51
+ "@jspsych/plugin-survey-text": "^2.0.0",
52
+ "@jspsych/plugin-survey-html-form": "^2.1.0",
53
+ "@jspsych/plugin-html-keyboard-response": "^2.0.0",
54
+ "jsdom": "^25.0.1",
55
+ "tsup": "^8.3.5",
56
+ "typescript": "^5.7.2",
57
+ "vitest": "^2.1.8"
58
+ },
59
+ "scripts": {
60
+ "build": "tsup",
61
+ "typecheck": "tsc --noEmit",
62
+ "test": "vitest run",
63
+ "test:watch": "vitest",
64
+ "clean": "rm -rf dist"
65
+ }
66
+ }