@adriansteffan/reactive 0.2.7 → 0.5.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/README.md +796 -229
- package/bin/add.js +56 -0
- package/bin/deploy.js +48 -0
- package/bin/download.js +28 -0
- package/bin/ghsetup.js +21 -0
- package/bin/native.js +81 -0
- package/bin/setup.js +11 -17
- package/bin/study-deploy.js +60 -0
- package/bin/undeploy.js +15 -0
- package/extras/transcription/compose.yaml +32 -0
- package/{template → extras}/transcription/transcribe.py +4 -9
- package/package.json +62 -64
- package/src/bun-env.d.ts +1 -0
- package/src/bun-plugin.ts +22 -0
- package/src/components/canvasblock.tsx +209 -537
- package/src/components/checkdevice.tsx +64 -84
- package/src/components/fullscreenblock.tsx +130 -0
- package/src/components/icons.tsx +50 -0
- package/src/components/index.ts +9 -11
- package/src/components/microphonecheck.tsx +76 -38
- package/src/components/plaininput.tsx +45 -40
- package/src/components/prolificending.tsx +64 -28
- package/src/components/quest.tsx +89 -87
- package/src/components/{randomdotkinetogram.tsx → randomdotkinematogram.tsx} +205 -267
- package/src/components/{voicerecorder.tsx → recorder.tsx} +81 -106
- package/src/components/requestfilepermission.tsx +63 -0
- package/src/components/stimulus.tsx +373 -0
- package/src/components/storeui.tsx +94 -148
- package/src/components/text.tsx +61 -59
- package/src/components/tutorial.tsx +45 -47
- package/src/components/upload.tsx +133 -309
- package/src/components/voicerecording.tsx +90 -94
- package/src/core/backend.ts +20 -0
- package/src/core/bytecode.ts +178 -0
- package/src/core/columns.ts +50 -0
- package/src/core/component.ts +238 -0
- package/src/core/development.ts +32 -0
- package/src/core/experiment.ts +263 -0
- package/src/core/files.ts +291 -0
- package/src/core/params.ts +166 -0
- package/src/core/platform.ts +29 -0
- package/src/core/rows.ts +106 -0
- package/src/core/simulation.ts +158 -0
- package/src/core/slides.ts +178 -0
- package/src/core/store.ts +22 -0
- package/src/core/timeline.ts +399 -0
- package/src/fonts/AtkinsonHyperlegible-Bold.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-BoldItalic.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-Italic.woff2 +0 -0
- package/src/fonts/AtkinsonHyperlegible-Regular.woff2 +0 -0
- package/src/index.css +5 -7
- package/src/mod.tsx +31 -17
- package/src/native.ts +127 -0
- package/src/quest.ts +2 -0
- package/src/runner/contexts.ts +35 -0
- package/src/runner/devpanel.tsx +68 -0
- package/src/runner/experimentrunner.tsx +210 -0
- package/src/runner/fullscreenguard.tsx +93 -0
- package/src/runner/paraminput.tsx +86 -0
- package/src/runner/progressbar.tsx +20 -0
- package/src/runner/settingsscreen.tsx +517 -0
- package/src/{utils → runner}/theme.ts +9 -8
- package/src/server.ts +93 -0
- package/src/tutorial.ts +3 -0
- package/src/utils/array.ts +30 -62
- package/src/utils/canvas.ts +66 -0
- package/src/utils/ddm.ts +47 -70
- package/src/utils/distributions.ts +352 -61
- package/src/utils/fullscreen.ts +38 -0
- package/src/utils/ids.ts +11 -0
- package/src/utils/keys.ts +46 -0
- package/src/utils/llm.ts +15 -15
- package/src/utils/time.ts +12 -0
- package/src/utils/tts.ts +24 -24
- package/template/.dockerignore +3 -1
- package/template/.env.example +5 -0
- package/template/.github/workflows/deploy.yml +25 -0
- package/template/.gitignore +14 -0
- package/template/Dockerfile +9 -14
- package/template/README.md +74 -214
- package/template/biome.json +34 -0
- package/template/build.ts +20 -0
- package/template/bunfig.toml +3 -0
- package/template/docker-compose.yaml +4 -33
- package/template/index.html +2 -2
- package/template/package.json +16 -89
- package/template/public/.gitkeep +0 -0
- package/template/server.ts +32 -0
- package/template/simulate.ts +4 -44
- package/template/src/Experiment.tsx +76 -128
- package/template/src/bun-env.d.ts +1 -0
- package/template/src/index.css +1 -9
- package/template/src/main.tsx +25 -10
- package/template/tsconfig.json +4 -6
- package/.claude/settings.local.json +0 -61
- package/.eslintrc.cjs +0 -18
- package/.playwright-mcp/console-2026-04-07T14-22-59-060Z.log +0 -1
- package/.playwright-mcp/console-2026-09-20T12-17-32-043Z.log +0 -1
- package/.playwright-mcp/page-2026-09-20T12-17-32-084Z.yml +0 -10
- package/.prettierrc +0 -5
- package/Dockerfile +0 -20
- package/dist/mod-BTpABl23.js +0 -87435
- package/dist/mod.d.ts +0 -947
- package/dist/reactive.es.js +0 -87
- package/dist/reactive.umd.js +0 -10255
- package/dist/style.css +0 -5
- package/dist/web-DV4cj_8Q.js +0 -435
- package/dist/web-DprbPn6i.js +0 -12
- package/planned.md +0 -103
- package/postcss.config.js +0 -6
- package/raw-loader-hooks.mjs +0 -25
- package/raw-loader.mjs +0 -5
- package/rdk_doc.md +0 -341
- package/src/components/enterfullscreen.tsx +0 -230
- package/src/components/exitfullscreen.tsx +0 -113
- package/src/components/experimentprovider.tsx +0 -69
- package/src/components/experimentrunner.tsx +0 -497
- package/src/components/mobilefilepermission.tsx +0 -68
- package/src/components/settingsscreen.tsx +0 -770
- package/src/types/array.d.ts +0 -6
- package/src/utils/audiodevice.ts +0 -4
- package/src/utils/bytecode.ts +0 -261
- package/src/utils/common.ts +0 -291
- package/src/utils/ddm.test.ts +0 -233
- package/src/utils/distributions.test.ts +0 -209
- package/src/utils/nodecompat.ts +0 -11
- package/src/utils/overlays.ts +0 -19
- package/src/utils/request.ts +0 -25
- package/src/utils/simulation.ts +0 -299
- package/src/utils/upload.ts +0 -275
- package/src/vite-env.d.ts +0 -1
- package/template/.env.template +0 -2
- package/template/.eslintrc.cjs +0 -18
- package/template/.prettierrc +0 -5
- package/template/backend/package-lock.json +0 -2544
- package/template/backend/package.json +0 -31
- package/template/backend/src/backend.ts +0 -131
- package/template/backend/tsconfig.json +0 -110
- package/template/capacitor.config.ts +0 -15
- package/template/electron/main.js +0 -131
- package/template/electron/preload.js +0 -9
- package/template/electron.vite.config.js +0 -45
- package/template/package-lock.json +0 -12467
- package/template/postcss.config.js +0 -5
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Bold.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-BoldItalic.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Italic.ttf +0 -0
- package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Regular.ttf +0 -0
- package/template/shared.vite.config.js +0 -39
- package/template/src/vite-env.d.ts +0 -2
- package/template/tsconfig.node.json +0 -12
- package/template/vite.config.js +0 -11
- package/tsconfig.json +0 -30
- package/tsconfig.node.json +0 -12
- package/vite.config.ts +0 -39
- /package/{template → extras}/transcription/Dockerfile.cpu +0 -0
- /package/{template → extras}/transcription/Dockerfile.gpu +0 -0
- /package/{template/public/Atkinson_Hyperlegible → src/fonts}/OFL.txt +0 -0
package/src/utils/simulation.ts
DELETED
|
@@ -1,299 +0,0 @@
|
|
|
1
|
-
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
compileTimeline,
|
|
5
|
-
advanceToNextContent,
|
|
6
|
-
applyMetadata,
|
|
7
|
-
TrialResult,
|
|
8
|
-
ComponentResultData,
|
|
9
|
-
TimelineItem,
|
|
10
|
-
Store,
|
|
11
|
-
} from './bytecode';
|
|
12
|
-
import { Param } from './common';
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
export type ParticipantState = Record<string, any>;
|
|
16
|
-
|
|
17
|
-
export type SimulatorResult = {
|
|
18
|
-
responseData: any;
|
|
19
|
-
participantState: ParticipantState;
|
|
20
|
-
storeUpdates?: Record<string, any>;
|
|
21
|
-
duration?: number;
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
export type SimulateFunction = (
|
|
25
|
-
trialProps: Record<string, any>,
|
|
26
|
-
experimentState: {
|
|
27
|
-
data: TrialResult[];
|
|
28
|
-
store: Store;
|
|
29
|
-
},
|
|
30
|
-
simulators: Record<string, any>,
|
|
31
|
-
participant: ParticipantState,
|
|
32
|
-
) => SimulatorResult | Promise<SimulatorResult>;
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
interface ComponentSimulation {
|
|
36
|
-
simulate: SimulateFunction;
|
|
37
|
-
defaultSimulators: Record<string, any>;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
const simulationRegistry: Record<string, ComponentSimulation> = {};
|
|
41
|
-
|
|
42
|
-
export function registerSimulation(
|
|
43
|
-
type: string,
|
|
44
|
-
simulate: SimulateFunction,
|
|
45
|
-
defaultSimulators: Record<string, any>,
|
|
46
|
-
) {
|
|
47
|
-
simulationRegistry[type] = { simulate, defaultSimulators };
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function getSimulation(type: string): ComponentSimulation | undefined {
|
|
51
|
-
return simulationRegistry[type];
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export const noopSimulate: SimulateFunction = (_trialProps, _experimentState, _simulators, participant) => ({
|
|
55
|
-
responseData: {},
|
|
56
|
-
participantState: participant,
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
export function resolveSimulation(content: any, data: TrialResult[], store: Store) {
|
|
60
|
-
const trialProps =
|
|
61
|
-
typeof content.props === 'function' ? content.props(data, store) : content.props || {};
|
|
62
|
-
const registration = simulationRegistry[content.type];
|
|
63
|
-
const simulateFn = typeof content.simulate === 'function' ? content.simulate : registration?.simulate;
|
|
64
|
-
|
|
65
|
-
if (!simulateFn) {
|
|
66
|
-
throw new Error(`No simulation registered for trial type '${content.type}' (name: '${content.name ?? 'unnamed'}'). Register one with registerSimulation() or add a simulate function to the timeline item.`);
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
const simulators = { ...registration?.defaultSimulators, ...content.simulators };
|
|
70
|
-
return { trialProps, simulateFn, simulators };
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
let _backendUrl = 'http://localhost:8001/backend';
|
|
74
|
-
export function setBackendUrl(url: string) { _backendUrl = url; }
|
|
75
|
-
export function getBackendUrl() { return _backendUrl; }
|
|
76
|
-
|
|
77
|
-
let _initialParticipant: ParticipantState | undefined;
|
|
78
|
-
export function getInitialParticipant() { return _initialParticipant; }
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
export async function simulateParticipant(
|
|
82
|
-
timeline: TimelineItem[],
|
|
83
|
-
participant: ParticipantState,
|
|
84
|
-
): Promise<TrialResult[]> {
|
|
85
|
-
_initialParticipant = { ...participant };
|
|
86
|
-
let currentParticipantState = { ...participant };
|
|
87
|
-
const bytecode = compileTimeline(timeline);
|
|
88
|
-
let store: Store = {};
|
|
89
|
-
const data: TrialResult[] = [
|
|
90
|
-
{
|
|
91
|
-
index: -1,
|
|
92
|
-
trialNumber: -1,
|
|
93
|
-
start: 0,
|
|
94
|
-
end: 0,
|
|
95
|
-
duration: 0,
|
|
96
|
-
type: '',
|
|
97
|
-
name: '',
|
|
98
|
-
responseData: {
|
|
99
|
-
userAgent: 'simulated',
|
|
100
|
-
params: {
|
|
101
|
-
// Unregistered URL params from participant.urlParams appear in the CSV with a `url_` prefix.
|
|
102
|
-
...Object.fromEntries(
|
|
103
|
-
Object.entries((participant as any)?.urlParams ?? {}).map(([name, value]) => [name, {
|
|
104
|
-
value,
|
|
105
|
-
registered: false,
|
|
106
|
-
defaultValue: undefined,
|
|
107
|
-
type: undefined,
|
|
108
|
-
description: undefined,
|
|
109
|
-
}]),
|
|
110
|
-
),
|
|
111
|
-
// Registered params win on name collision.
|
|
112
|
-
...Object.fromEntries(
|
|
113
|
-
(Param.getRegistry() || []).map((p: any) => [p.name, {
|
|
114
|
-
value: p.value !== undefined ? p.value : p.defaultValue,
|
|
115
|
-
registered: true,
|
|
116
|
-
defaultValue: p.defaultValue,
|
|
117
|
-
type: p.type,
|
|
118
|
-
description: p.description,
|
|
119
|
-
}]),
|
|
120
|
-
),
|
|
121
|
-
},
|
|
122
|
-
},
|
|
123
|
-
},
|
|
124
|
-
];
|
|
125
|
-
|
|
126
|
-
const getStore = () => store;
|
|
127
|
-
const getData = () => data;
|
|
128
|
-
const onUpdateStore = (s: Store) => { store = s; };
|
|
129
|
-
|
|
130
|
-
let trialNumber = 0;
|
|
131
|
-
let currentTime = 0;
|
|
132
|
-
|
|
133
|
-
let pointer = advanceToNextContent(bytecode, 0, getStore, getData, onUpdateStore);
|
|
134
|
-
|
|
135
|
-
while (pointer < bytecode.instructions.length) {
|
|
136
|
-
const content = (bytecode.instructions[pointer] as any).content;
|
|
137
|
-
if (typeof content !== 'object' || content === null || typeof content.type !== 'string') {
|
|
138
|
-
pointer = advanceToNextContent(bytecode, pointer + 1, getStore, getData, onUpdateStore);
|
|
139
|
-
continue;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
const { trialProps, simulateFn, simulators } = resolveSimulation(content, data, store);
|
|
143
|
-
|
|
144
|
-
const result = await simulateFn(
|
|
145
|
-
trialProps,
|
|
146
|
-
{ data, store },
|
|
147
|
-
simulators,
|
|
148
|
-
currentParticipantState,
|
|
149
|
-
);
|
|
150
|
-
currentParticipantState = result.participantState;
|
|
151
|
-
if (result.storeUpdates) store = { ...store, ...result.storeUpdates };
|
|
152
|
-
|
|
153
|
-
trialNumber++;
|
|
154
|
-
const duration = result.duration ?? 0;
|
|
155
|
-
const startTime = currentTime;
|
|
156
|
-
currentTime += duration;
|
|
157
|
-
|
|
158
|
-
let trialData: ComponentResultData = {
|
|
159
|
-
index: pointer,
|
|
160
|
-
trialNumber,
|
|
161
|
-
start: startTime,
|
|
162
|
-
end: currentTime,
|
|
163
|
-
duration,
|
|
164
|
-
type: content.type,
|
|
165
|
-
name: content.name ?? '',
|
|
166
|
-
...(content.csv !== undefined ? { csv: content.csv } : {}),
|
|
167
|
-
responseData: result.responseData,
|
|
168
|
-
};
|
|
169
|
-
|
|
170
|
-
data.push(applyMetadata(trialData, content, data, store));
|
|
171
|
-
pointer = advanceToNextContent(bytecode, pointer + 1, getStore, getData, onUpdateStore);
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
return data;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
export interface RunSimulationConfig {
|
|
179
|
-
participants: ParticipantState[] | { generator: (index: number) => ParticipantState; count: number } | (() => ParticipantState[]);
|
|
180
|
-
/** Seed for reproducible simulations. Each participant gets seed + workerIndex. */
|
|
181
|
-
seed?: number;
|
|
182
|
-
backendPort?: number;
|
|
183
|
-
concurrency?: number;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
export async function orchestrateSimulation(config: RunSimulationConfig, scriptPath: string): Promise<void> {
|
|
187
|
-
const { spawn } = await import('child_process');
|
|
188
|
-
|
|
189
|
-
const port = config.backendPort ?? 8001;
|
|
190
|
-
const backendUrl = `http://localhost:${port}/backend`;
|
|
191
|
-
|
|
192
|
-
const participantCount = typeof config.participants === 'function'
|
|
193
|
-
? config.participants().length
|
|
194
|
-
: Array.isArray(config.participants)
|
|
195
|
-
? config.participants.length
|
|
196
|
-
: config.participants.count;
|
|
197
|
-
|
|
198
|
-
const backend = spawn('node', ['src/backend.ts'], {
|
|
199
|
-
cwd: './backend',
|
|
200
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
201
|
-
});
|
|
202
|
-
|
|
203
|
-
// Wait for backend to signal readiness before spawning workers
|
|
204
|
-
await new Promise<void>((resolve, reject) => {
|
|
205
|
-
backend.on('error', reject);
|
|
206
|
-
|
|
207
|
-
backend.stdout?.on('data', (data: any) => {
|
|
208
|
-
const msg = data.toString();
|
|
209
|
-
if (msg.includes('REACTIVE_BACKEND_READY')) {
|
|
210
|
-
resolve();
|
|
211
|
-
}
|
|
212
|
-
});
|
|
213
|
-
|
|
214
|
-
backend.stderr?.on('data', (data: any) => {
|
|
215
|
-
console.error(`[backend] ${data.toString().trim()}`);
|
|
216
|
-
});
|
|
217
|
-
|
|
218
|
-
setTimeout(() => reject(new Error('Backend did not start within 10 seconds')), 10000);
|
|
219
|
-
});
|
|
220
|
-
|
|
221
|
-
console.log(`Backend running on port ${port}`);
|
|
222
|
-
|
|
223
|
-
try {
|
|
224
|
-
const concurrency = config.concurrency ?? (await import('os')).cpus().length;
|
|
225
|
-
console.log(`Simulating ${participantCount} participants (concurrency: ${concurrency})...`);
|
|
226
|
-
|
|
227
|
-
let completed = 0;
|
|
228
|
-
const errors: { index: number; error: string }[] = [];
|
|
229
|
-
|
|
230
|
-
const writeProgress = () => {
|
|
231
|
-
const pct = Math.min(100, Math.round((completed / participantCount) * 100));
|
|
232
|
-
const filled = Math.floor(pct / 2);
|
|
233
|
-
const bar = '█'.repeat(filled) + '░'.repeat(50 - filled);
|
|
234
|
-
process.stdout.write(`\r ${bar} ${completed}/${participantCount} (${pct}%)`);
|
|
235
|
-
};
|
|
236
|
-
|
|
237
|
-
const spawnWorker = (i: number) => new Promise<void>((resolve) => {
|
|
238
|
-
let stderr = '';
|
|
239
|
-
const worker = spawn('node', [scriptPath], {
|
|
240
|
-
env: {
|
|
241
|
-
...process.env,
|
|
242
|
-
_REACTIVE_WORKER_INDEX: String(i),
|
|
243
|
-
_REACTIVE_BACKEND_URL: backendUrl,
|
|
244
|
-
...(config.seed !== undefined ? { _REACTIVE_SIMULATION_SEED: String(config.seed) } : {}),
|
|
245
|
-
},
|
|
246
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
247
|
-
});
|
|
248
|
-
|
|
249
|
-
worker.stderr?.on('data', (data: any) => { stderr += data.toString(); });
|
|
250
|
-
|
|
251
|
-
worker.on('close', (code: number) => {
|
|
252
|
-
if (code !== 0) {
|
|
253
|
-
errors.push({ index: i, error: stderr.trim() || `exited with code ${code}` });
|
|
254
|
-
}
|
|
255
|
-
completed++;
|
|
256
|
-
writeProgress();
|
|
257
|
-
resolve();
|
|
258
|
-
});
|
|
259
|
-
worker.on('error', (err: Error) => {
|
|
260
|
-
errors.push({ index: i, error: err.message });
|
|
261
|
-
completed++;
|
|
262
|
-
writeProgress();
|
|
263
|
-
resolve();
|
|
264
|
-
});
|
|
265
|
-
});
|
|
266
|
-
|
|
267
|
-
writeProgress();
|
|
268
|
-
|
|
269
|
-
// Worker pool: always keep `concurrency` workers running
|
|
270
|
-
let nextIndex = 0;
|
|
271
|
-
await new Promise<void>((resolveAll) => {
|
|
272
|
-
const startNext = () => {
|
|
273
|
-
if (nextIndex >= participantCount) {
|
|
274
|
-
if (completed >= participantCount) resolveAll();
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
const i = nextIndex++;
|
|
278
|
-
spawnWorker(i).then(startNext);
|
|
279
|
-
};
|
|
280
|
-
for (let j = 0; j < Math.min(concurrency, participantCount); j++) {
|
|
281
|
-
startNext();
|
|
282
|
-
}
|
|
283
|
-
});
|
|
284
|
-
|
|
285
|
-
process.stdout.write('\n');
|
|
286
|
-
|
|
287
|
-
if (errors.length > 0) {
|
|
288
|
-
console.error(`\n${errors.length} participant(s) failed:`);
|
|
289
|
-
for (const { index, error } of errors) {
|
|
290
|
-
console.error(` Participant ${index}: ${error}`);
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
console.log(`Simulation complete. ${completed - errors.length}/${participantCount} participants simulated successfully.`);
|
|
295
|
-
} finally {
|
|
296
|
-
backend.kill();
|
|
297
|
-
console.log('Backend stopped.');
|
|
298
|
-
}
|
|
299
|
-
}
|
package/src/utils/upload.ts
DELETED
|
@@ -1,275 +0,0 @@
|
|
|
1
|
-
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
2
|
-
|
|
3
|
-
import { FileUpload, Store, TrialData } from './common';
|
|
4
|
-
|
|
5
|
-
type DataObject = {
|
|
6
|
-
[key: string]: string | number | boolean | null | undefined;
|
|
7
|
-
};
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
const flattenerRegistry: Record<string, {
|
|
11
|
-
csv: string | null;
|
|
12
|
-
flatten?: (item: TrialData) => any[];
|
|
13
|
-
}[]> = {};
|
|
14
|
-
|
|
15
|
-
export function registerFlattener(
|
|
16
|
-
type: string,
|
|
17
|
-
csv: string | null,
|
|
18
|
-
flatten?: (item: TrialData) => any[],
|
|
19
|
-
) {
|
|
20
|
-
if (!flattenerRegistry[type]) flattenerRegistry[type] = [];
|
|
21
|
-
flattenerRegistry[type].push({ csv, flatten });
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
// Reusable flattener for components whose responseData is an array of objects.
|
|
25
|
-
// Each array element becomes a CSV row. Non-array responseData produces an empty result.
|
|
26
|
-
export function arrayFlattener(item: TrialData): any[] {
|
|
27
|
-
const responseData = item.responseData;
|
|
28
|
-
if (Array.isArray(responseData)) {
|
|
29
|
-
return responseData.map((i) => ({ block: item.name, ...i }));
|
|
30
|
-
}
|
|
31
|
-
return [];
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
export function escapeCsvValue(value: any): string {
|
|
35
|
-
if (value === null || value === undefined) {
|
|
36
|
-
return '';
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const stringValue = typeof value === 'object' ? JSON.stringify(value) : String(value);
|
|
40
|
-
|
|
41
|
-
if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
|
|
42
|
-
const escapedValue = stringValue.replace(/"/g, '""');
|
|
43
|
-
return `"${escapedValue}"`;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
return stringValue;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export function convertArrayOfObjectsToCSV(data: DataObject[]): string {
|
|
50
|
-
if (!data || data.length === 0) {
|
|
51
|
-
return '';
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const headerSet = new Set<string>();
|
|
55
|
-
data.forEach((obj) => {
|
|
56
|
-
Object.keys(obj).forEach((key) => {
|
|
57
|
-
headerSet.add(key);
|
|
58
|
-
});
|
|
59
|
-
});
|
|
60
|
-
const headers = Array.from(headerSet);
|
|
61
|
-
|
|
62
|
-
const headerRow = headers.map((header) => escapeCsvValue(header)).join(',');
|
|
63
|
-
|
|
64
|
-
const dataRows = data.map((obj) => {
|
|
65
|
-
return headers
|
|
66
|
-
.map((header) => {
|
|
67
|
-
const value = obj[header];
|
|
68
|
-
return escapeCsvValue(value);
|
|
69
|
-
})
|
|
70
|
-
.join(',');
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
return [headerRow, ...dataRows].join('\n');
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
// Extracts experiment parameter values (URL params / registered params) from the initial metadata trial.
|
|
77
|
-
// Each param entry has { value, defaultValue, registered, ... } — we pick value if set, otherwise the default.
|
|
78
|
-
// Unregistered params (raw URL params not declared via getParam) are prefixed with `url_` so they're
|
|
79
|
-
// visibly distinguishable from intentional study variables in the CSV.
|
|
80
|
-
function extractParams(data: any[]): Record<string, any> {
|
|
81
|
-
const paramsSource = data?.[0]?.responseData?.params;
|
|
82
|
-
if (!paramsSource || typeof paramsSource !== 'object') return {};
|
|
83
|
-
const result: Record<string, any> = {};
|
|
84
|
-
for (const [name, details] of Object.entries(paramsSource) as [string, any][]) {
|
|
85
|
-
if (details && typeof details === 'object') {
|
|
86
|
-
const key = details.registered ? name : `url_${name}`;
|
|
87
|
-
result[key] = details.value ?? details.defaultValue;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
return result;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// Built-in fields on every trial data object — not user data.
|
|
94
|
-
// Used to distinguish user-provided metadata from framework fields when building CSVs.
|
|
95
|
-
const trialBuiltinKeys = new Set(['index', 'trialNumber', 'start', 'end', 'duration', 'type', 'name', 'csv', 'responseData', 'metadata']);
|
|
96
|
-
// Subset of builtins that represent trial identity/timing — included in non-session CSVs with trial_ prefix
|
|
97
|
-
const trialInfoKeys = new Set(['index', 'trialNumber', 'start', 'end', 'duration', 'type', 'name']);
|
|
98
|
-
|
|
99
|
-
// Automatically builds CSV files from trial data using the flattener registry.
|
|
100
|
-
// Each trial is routed to a CSV file based on: item.csv override > registry default > skipped.
|
|
101
|
-
// The 'session' group is special: all trials merge into a single row, with keys namespaced
|
|
102
|
-
// by trial name (e.g. 'nickname_value', 'devicecheck_browser') to avoid collisions.
|
|
103
|
-
// All other groups produce multi-row CSVs, one row per trial (or more if the flattener expands them).
|
|
104
|
-
function autoBuildCSVs(sessionID: string, data: any[], sessionData?: Record<string, any>): FileUpload[] {
|
|
105
|
-
const files: FileUpload[] = [];
|
|
106
|
-
|
|
107
|
-
// Group trials by their target CSV file name.
|
|
108
|
-
// A component can register multiple targets, so one trial may appear in multiple groups.
|
|
109
|
-
// A per-item csv override replaces all registered targets.
|
|
110
|
-
const groups: Record<string, { item: any; flatten?: (item: TrialData) => any[] }[]> = {};
|
|
111
|
-
for (const item of data) {
|
|
112
|
-
if (item.index === -1) continue; // skip initial metadata entry
|
|
113
|
-
const csvOverride = item.csv;
|
|
114
|
-
const targets = csvOverride
|
|
115
|
-
? (Array.isArray(csvOverride) ? csvOverride : [csvOverride]).map((csv: string) => ({ csv }))
|
|
116
|
-
: flattenerRegistry[item.type] ?? [];
|
|
117
|
-
for (const target of targets) {
|
|
118
|
-
if (!target.csv) continue;
|
|
119
|
-
if (!groups[target.csv]) groups[target.csv] = [];
|
|
120
|
-
groups[target.csv].push({ item, flatten: 'flatten' in target ? target.flatten : undefined });
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// 'session' group: one row per participant with metadata + responseData namespaced by trial name
|
|
125
|
-
const row: Record<string, any> = {
|
|
126
|
-
sessionID,
|
|
127
|
-
userAgent: data?.[0]?.responseData?.userAgent,
|
|
128
|
-
...extractParams(data),
|
|
129
|
-
...sessionData,
|
|
130
|
-
};
|
|
131
|
-
if (groups['session']) {
|
|
132
|
-
for (const { item } of groups['session']) {
|
|
133
|
-
const prefix = item.name || item.type;
|
|
134
|
-
// Add user-provided metadata (non-builtin top-level keys), namespaced by trial name
|
|
135
|
-
for (const [key, value] of Object.entries(item)) {
|
|
136
|
-
if (!trialBuiltinKeys.has(key)) row[`${prefix}_${key}`] = typeof value === 'object' && value !== null && !Array.isArray(value) ? JSON.stringify(value) : value;
|
|
137
|
-
}
|
|
138
|
-
// Add responseData fields, namespaced by trial name
|
|
139
|
-
if (item.responseData && typeof item.responseData === 'object' && !Array.isArray(item.responseData)) {
|
|
140
|
-
for (const [key, value] of Object.entries(item.responseData)) {
|
|
141
|
-
row[`${prefix}_${key}`] = typeof value === 'object' && value !== null && !Array.isArray(value) ? JSON.stringify(value) : value;
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
delete groups['session'];
|
|
146
|
-
}
|
|
147
|
-
if (Object.keys(row).length > 1) {
|
|
148
|
-
files.push({
|
|
149
|
-
filename: `session.${sessionID}.${Date.now()}.csv`,
|
|
150
|
-
content: convertArrayOfObjectsToCSV([row]),
|
|
151
|
-
encoding: 'utf8' as const,
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// All other groups: multi-row CSVs using registered flatteners (or raw responseData spread).
|
|
156
|
-
// Each row is prepended with standard trial fields (prefixed trial_) plus any extra
|
|
157
|
-
// metadata fields (unprefixed). The flattener's output overwrites these if keys collide.
|
|
158
|
-
for (const [csvName, entries] of Object.entries(groups)) {
|
|
159
|
-
const rows = entries.flatMap(({ item, flatten }) => {
|
|
160
|
-
const base: Record<string, any> = {};
|
|
161
|
-
for (const [key, value] of Object.entries(item)) {
|
|
162
|
-
if (trialBuiltinKeys.has(key)) {
|
|
163
|
-
if (trialInfoKeys.has(key)) base[`trial_${key}`] = value;
|
|
164
|
-
} else {
|
|
165
|
-
base[key] = typeof value === 'object' && value !== null && !Array.isArray(value) ? JSON.stringify(value) : value;
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
// When no flatten function is registered, spread responseData directly.
|
|
169
|
-
const flatRows = flatten
|
|
170
|
-
? flatten(item)
|
|
171
|
-
: [item.responseData && typeof item.responseData === 'object' ? { ...item.responseData } : {}];
|
|
172
|
-
return flatRows.map((row: any) => {
|
|
173
|
-
const merged = { ...base, ...row };
|
|
174
|
-
for (const k of Object.keys(merged)) {
|
|
175
|
-
const v = merged[k];
|
|
176
|
-
if (typeof v === 'object' && v !== null && !Array.isArray(v)) merged[k] = JSON.stringify(v);
|
|
177
|
-
}
|
|
178
|
-
return merged;
|
|
179
|
-
});
|
|
180
|
-
});
|
|
181
|
-
if (rows.length > 0) {
|
|
182
|
-
files.push({
|
|
183
|
-
filename: `${csvName}.${sessionID}.${Date.now()}.csv`,
|
|
184
|
-
content: convertArrayOfObjectsToCSV(rows),
|
|
185
|
-
encoding: 'utf8' as const,
|
|
186
|
-
});
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
return files;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
let audioFileIndex = 0;
|
|
194
|
-
export function generateAudioFilename(label: string): string {
|
|
195
|
-
return `audio_${label}_${audioFileIndex++}_${Date.now()}.webm`;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
// Scans trial data for audio recordings (type: 'audiorecording' with data64),
|
|
199
|
-
// extracts them as separate .webm files, and replaces the binary data in-place
|
|
200
|
-
// with a filename reference. This keeps CSVs and raw JSON clean.
|
|
201
|
-
function extractAudioRecordings(data: any[]): FileUpload[] {
|
|
202
|
-
const files: FileUpload[] = [];
|
|
203
|
-
|
|
204
|
-
const processRecording = (obj: any, nameHint: string) => {
|
|
205
|
-
if (obj?.type === 'audiorecording' && obj.data64) {
|
|
206
|
-
const filename = obj._audioPreUploadedFilename ?? generateAudioFilename(nameHint);
|
|
207
|
-
files.push({
|
|
208
|
-
filename,
|
|
209
|
-
content: obj.data64,
|
|
210
|
-
encoding: 'base64' as const,
|
|
211
|
-
_alreadyUploaded: !!obj._audioPreUploaded,
|
|
212
|
-
});
|
|
213
|
-
obj.audioFile = filename;
|
|
214
|
-
delete obj.data64;
|
|
215
|
-
delete obj.blob;
|
|
216
|
-
delete obj.url;
|
|
217
|
-
delete obj._audioPreUploaded;
|
|
218
|
-
delete obj._audioPreUploadedFilename;
|
|
219
|
-
}
|
|
220
|
-
};
|
|
221
|
-
|
|
222
|
-
for (const item of data) {
|
|
223
|
-
const rd = item.responseData;
|
|
224
|
-
if (!rd || typeof rd !== 'object') continue;
|
|
225
|
-
|
|
226
|
-
// Direct responseData is an audio recording (VoiceRecording component)
|
|
227
|
-
processRecording(rd, item.name || item.type);
|
|
228
|
-
|
|
229
|
-
// Nested in responseData (Quest voicerecorder questions)
|
|
230
|
-
if (!Array.isArray(rd)) {
|
|
231
|
-
for (const [key, value] of Object.entries(rd)) {
|
|
232
|
-
if (value && typeof value === 'object') {
|
|
233
|
-
processRecording(value, `${item.name || item.type}_${key}`);
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
return files;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
export function buildUploadFiles(config: {
|
|
243
|
-
sessionID: string;
|
|
244
|
-
data: any[];
|
|
245
|
-
store?: Store;
|
|
246
|
-
generateFiles?: (sessionID: string, data: any[], store?: Store) => FileUpload[];
|
|
247
|
-
sessionData?: Record<string, any>;
|
|
248
|
-
uploadRaw?: boolean;
|
|
249
|
-
}): FileUpload[] {
|
|
250
|
-
const {
|
|
251
|
-
sessionID,
|
|
252
|
-
data,
|
|
253
|
-
store,
|
|
254
|
-
generateFiles,
|
|
255
|
-
sessionData,
|
|
256
|
-
uploadRaw = true,
|
|
257
|
-
} = config;
|
|
258
|
-
|
|
259
|
-
const files: FileUpload[] = generateFiles ? generateFiles(sessionID, data, store) : [];
|
|
260
|
-
|
|
261
|
-
// Extract audio recordings as separate files before serialization
|
|
262
|
-
files.push(...extractAudioRecordings(data));
|
|
263
|
-
|
|
264
|
-
if (uploadRaw) {
|
|
265
|
-
files.push({
|
|
266
|
-
filename: `${sessionID}.raw.json`,
|
|
267
|
-
content: JSON.stringify(data),
|
|
268
|
-
encoding: 'utf8',
|
|
269
|
-
});
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
files.push(...autoBuildCSVs(sessionID, data, sessionData));
|
|
273
|
-
|
|
274
|
-
return files;
|
|
275
|
-
}
|
package/src/vite-env.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
/// <reference types="vite/client" />
|
package/template/.env.template
DELETED
package/template/.eslintrc.cjs
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
module.exports = {
|
|
2
|
-
root: true,
|
|
3
|
-
env: { browser: true, es2020: true, node: true, commonjs: true },
|
|
4
|
-
extends: [
|
|
5
|
-
'eslint:recommended',
|
|
6
|
-
'plugin:@typescript-eslint/recommended',
|
|
7
|
-
'plugin:react-hooks/recommended',
|
|
8
|
-
],
|
|
9
|
-
ignorePatterns: ['dist', '.eslintrc.cjs'],
|
|
10
|
-
parser: '@typescript-eslint/parser',
|
|
11
|
-
plugins: ['react-refresh'],
|
|
12
|
-
rules: {
|
|
13
|
-
'react-refresh/only-export-components': [
|
|
14
|
-
'warn',
|
|
15
|
-
{ allowConstantExport: true },
|
|
16
|
-
],
|
|
17
|
-
},
|
|
18
|
-
}
|