@adriansteffan/reactive 0.2.6 → 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.
Files changed (156) hide show
  1. package/README.md +796 -229
  2. package/bin/add.js +56 -0
  3. package/bin/deploy.js +48 -0
  4. package/bin/download.js +28 -0
  5. package/bin/ghsetup.js +21 -0
  6. package/bin/native.js +81 -0
  7. package/bin/setup.js +11 -17
  8. package/bin/study-deploy.js +60 -0
  9. package/bin/undeploy.js +15 -0
  10. package/extras/transcription/compose.yaml +32 -0
  11. package/{template → extras}/transcription/transcribe.py +4 -9
  12. package/package.json +62 -64
  13. package/src/bun-env.d.ts +1 -0
  14. package/src/bun-plugin.ts +22 -0
  15. package/src/components/canvasblock.tsx +209 -537
  16. package/src/components/checkdevice.tsx +64 -84
  17. package/src/components/fullscreenblock.tsx +130 -0
  18. package/src/components/icons.tsx +50 -0
  19. package/src/components/index.ts +9 -11
  20. package/src/components/microphonecheck.tsx +76 -38
  21. package/src/components/plaininput.tsx +48 -41
  22. package/src/components/prolificending.tsx +64 -28
  23. package/src/components/quest.tsx +89 -87
  24. package/src/components/{randomdotkinetogram.tsx → randomdotkinematogram.tsx} +205 -267
  25. package/src/components/{voicerecorder.tsx → recorder.tsx} +81 -106
  26. package/src/components/requestfilepermission.tsx +63 -0
  27. package/src/components/stimulus.tsx +373 -0
  28. package/src/components/storeui.tsx +94 -148
  29. package/src/components/text.tsx +61 -59
  30. package/src/components/tutorial.tsx +45 -47
  31. package/src/components/upload.tsx +133 -309
  32. package/src/components/voicerecording.tsx +90 -94
  33. package/src/core/backend.ts +20 -0
  34. package/src/core/bytecode.ts +178 -0
  35. package/src/core/columns.ts +50 -0
  36. package/src/core/component.ts +238 -0
  37. package/src/core/development.ts +32 -0
  38. package/src/core/experiment.ts +263 -0
  39. package/src/core/files.ts +291 -0
  40. package/src/core/params.ts +166 -0
  41. package/src/core/platform.ts +29 -0
  42. package/src/core/rows.ts +106 -0
  43. package/src/core/simulation.ts +158 -0
  44. package/src/core/slides.ts +178 -0
  45. package/src/core/store.ts +22 -0
  46. package/src/core/timeline.ts +399 -0
  47. package/src/fonts/AtkinsonHyperlegible-Bold.woff2 +0 -0
  48. package/src/fonts/AtkinsonHyperlegible-BoldItalic.woff2 +0 -0
  49. package/src/fonts/AtkinsonHyperlegible-Italic.woff2 +0 -0
  50. package/src/fonts/AtkinsonHyperlegible-Regular.woff2 +0 -0
  51. package/src/index.css +5 -7
  52. package/src/mod.tsx +31 -17
  53. package/src/native.ts +127 -0
  54. package/src/quest.ts +2 -0
  55. package/src/runner/contexts.ts +35 -0
  56. package/src/runner/devpanel.tsx +68 -0
  57. package/src/runner/experimentrunner.tsx +210 -0
  58. package/src/runner/fullscreenguard.tsx +93 -0
  59. package/src/runner/paraminput.tsx +86 -0
  60. package/src/runner/progressbar.tsx +20 -0
  61. package/src/runner/settingsscreen.tsx +517 -0
  62. package/src/{utils → runner}/theme.ts +9 -8
  63. package/src/server.ts +93 -0
  64. package/src/tutorial.ts +3 -0
  65. package/src/utils/array.ts +30 -62
  66. package/src/utils/canvas.ts +66 -0
  67. package/src/utils/ddm.ts +47 -70
  68. package/src/utils/distributions.ts +352 -61
  69. package/src/utils/fullscreen.ts +38 -0
  70. package/src/utils/ids.ts +11 -0
  71. package/src/utils/keys.ts +46 -0
  72. package/src/utils/llm.ts +15 -15
  73. package/src/utils/time.ts +12 -0
  74. package/src/utils/tts.ts +24 -24
  75. package/template/.dockerignore +3 -1
  76. package/template/.env.example +5 -0
  77. package/template/.github/workflows/deploy.yml +25 -0
  78. package/template/.gitignore +14 -0
  79. package/template/Dockerfile +9 -14
  80. package/template/README.md +74 -214
  81. package/template/biome.json +34 -0
  82. package/template/build.ts +20 -0
  83. package/template/bunfig.toml +3 -0
  84. package/template/docker-compose.yaml +4 -33
  85. package/template/index.html +2 -2
  86. package/template/package.json +16 -89
  87. package/template/public/.gitkeep +0 -0
  88. package/template/server.ts +32 -0
  89. package/template/simulate.ts +4 -44
  90. package/template/src/Experiment.tsx +76 -128
  91. package/template/src/bun-env.d.ts +1 -0
  92. package/template/src/index.css +1 -9
  93. package/template/src/main.tsx +25 -10
  94. package/template/tsconfig.json +4 -6
  95. package/.claude/settings.local.json +0 -61
  96. package/.eslintrc.cjs +0 -18
  97. package/.playwright-mcp/console-2026-04-07T14-22-59-060Z.log +0 -1
  98. package/.prettierrc +0 -5
  99. package/Dockerfile +0 -20
  100. package/dist/mod-HDegGPrf.js +0 -87434
  101. package/dist/mod.d.ts +0 -946
  102. package/dist/reactive.es.js +0 -87
  103. package/dist/reactive.umd.js +0 -10255
  104. package/dist/style.css +0 -5
  105. package/dist/web-7BbR1Ad7.js +0 -435
  106. package/dist/web-CATfZO1Q.js +0 -12
  107. package/planned.md +0 -103
  108. package/postcss.config.js +0 -6
  109. package/raw-loader-hooks.mjs +0 -25
  110. package/raw-loader.mjs +0 -5
  111. package/rdk_doc.md +0 -341
  112. package/src/components/enterfullscreen.tsx +0 -230
  113. package/src/components/exitfullscreen.tsx +0 -113
  114. package/src/components/experimentprovider.tsx +0 -69
  115. package/src/components/experimentrunner.tsx +0 -497
  116. package/src/components/mobilefilepermission.tsx +0 -68
  117. package/src/components/settingsscreen.tsx +0 -770
  118. package/src/types/array.d.ts +0 -6
  119. package/src/utils/audiodevice.ts +0 -4
  120. package/src/utils/bytecode.ts +0 -261
  121. package/src/utils/common.ts +0 -291
  122. package/src/utils/ddm.test.ts +0 -233
  123. package/src/utils/distributions.test.ts +0 -209
  124. package/src/utils/nodecompat.ts +0 -11
  125. package/src/utils/overlays.ts +0 -19
  126. package/src/utils/request.ts +0 -25
  127. package/src/utils/simulation.ts +0 -299
  128. package/src/utils/upload.ts +0 -275
  129. package/src/vite-env.d.ts +0 -1
  130. package/template/.env.template +0 -2
  131. package/template/.eslintrc.cjs +0 -18
  132. package/template/.prettierrc +0 -5
  133. package/template/backend/package-lock.json +0 -2544
  134. package/template/backend/package.json +0 -31
  135. package/template/backend/src/backend.ts +0 -131
  136. package/template/backend/tsconfig.json +0 -110
  137. package/template/capacitor.config.ts +0 -15
  138. package/template/electron/main.js +0 -131
  139. package/template/electron/preload.js +0 -9
  140. package/template/electron.vite.config.js +0 -45
  141. package/template/package-lock.json +0 -12467
  142. package/template/postcss.config.js +0 -5
  143. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Bold.ttf +0 -0
  144. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-BoldItalic.ttf +0 -0
  145. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Italic.ttf +0 -0
  146. package/template/public/Atkinson_Hyperlegible/AtkinsonHyperlegible-Regular.ttf +0 -0
  147. package/template/shared.vite.config.js +0 -39
  148. package/template/src/vite-env.d.ts +0 -2
  149. package/template/tsconfig.node.json +0 -12
  150. package/template/vite.config.js +0 -11
  151. package/tsconfig.json +0 -30
  152. package/tsconfig.node.json +0 -12
  153. package/vite.config.ts +0 -39
  154. /package/{template → extras}/transcription/Dockerfile.cpu +0 -0
  155. /package/{template → extras}/transcription/Dockerfile.gpu +0 -0
  156. /package/{template/public/Atkinson_Hyperlegible → src/fonts}/OFL.txt +0 -0
@@ -0,0 +1,291 @@
1
+ import { columnPrefixes, responseColumn } from './columns';
2
+ import { report } from './development';
3
+ import type { RuntimeComponent } from './component';
4
+ import type { ExperimentData, SessionData, TrialData } from './rows';
5
+ import type { Store } from './store';
6
+
7
+ /** A file the experiment saves, such as those that Upload's `generateFiles` adds. */
8
+ export interface FileUpload {
9
+ filename: string;
10
+ content: string;
11
+ encoding?: 'base64' | 'utf8';
12
+ }
13
+
14
+ /** A file to save, which the server may already have from an eager upload, so that only a download includes it. */
15
+ export type UploadFile = FileUpload & { _alreadyUploaded?: boolean };
16
+
17
+ /** A row of a CSV file, by column. */
18
+ export type CsvRow = Record<string, unknown>;
19
+
20
+ /** A trial's row, with its component's response. */
21
+ export type TrialRow<R = any> = Omit<TrialData, 'recorded'> & { recorded: R };
22
+
23
+ /** Turns a trial's row into the row it stands for in a CSV file, or a list of rows. */
24
+ export type Flatten<R = any> = (item: TrialRow<R>) => CsvRow | CsvRow[];
25
+
26
+ /**
27
+ * Where a component's rows go: a file, or files mapped to the functions that flatten rows for them
28
+ * or to `true` for one row per trial, or `null` for none.
29
+ */
30
+ export type ComponentCsv<R = any> = string | null | { [file: string]: Flatten<R> | true };
31
+
32
+ /**
33
+ * A trial's columns in the session CSV, the single row per participant: `true` for its response's
34
+ * fields, or a function that returns them. A response that is a list has no fields, so it needs the function.
35
+ */
36
+ export type SessionColumns<R = any> = (R extends readonly unknown[] ? never : true) | ((item: TrialRow<R>) => CsvRow);
37
+
38
+ /** A CSV file that a component's rows go to, with the function that turns a row into its CSV rows. */
39
+ export type CsvTarget = { file: string; flatten?: Flatten };
40
+
41
+ /**
42
+ * What a trial's `.csv()` takes: a new name for its component's only file, its component's files
43
+ * mapped to new names or to `null`, or `null` for no CSV at all.
44
+ */
45
+ export type TrialCsv = string | CsvRenames | null;
46
+ type CsvRenames = Record<string, string | null>;
47
+
48
+ /** The files a trial's rows go to: its component's, as the trial's `.csv()` renames them, each keeping its flattener. */
49
+ export function trialCsv(type: string, own: readonly CsvTarget[], csv: TrialCsv | undefined): CsvTarget[] {
50
+ if (csv === undefined) return [...own];
51
+ if (csv === null) return [];
52
+ const files = own.map((target) => `'${target.file}'`).join(', ');
53
+ let targets: CsvTarget[];
54
+ if (typeof csv === 'string') {
55
+ if (own.length > 1) {
56
+ throw new Error(
57
+ `${type} writes the CSV files ${files}, so a trial's .csv() needs to say which of them it renames, as in .csv({ ${own[0].file}: 'practice' }).`,
58
+ );
59
+ }
60
+ targets = [{ file: csv, flatten: own[0]?.flatten }];
61
+ } else {
62
+ for (const file of Object.keys(csv)) {
63
+ if (!own.some((target) => target.file === file)) {
64
+ throw new Error(`A trial's .csv() renames the CSV file '${file}', but ${type} writes ${own.length > 0 ? files : 'none'}.`);
65
+ }
66
+ }
67
+ targets = own.flatMap((target) => {
68
+ if (!(target.file in csv)) return [target];
69
+ const file = csv[target.file];
70
+ return file === null ? [] : [{ file, flatten: target.flatten }];
71
+ });
72
+ }
73
+ if (targets.some((target) => target.file === 'session')) {
74
+ throw new Error(
75
+ "A trial's .csv() cannot name a file 'session', which is the session CSV. To put the trial's columns in the session row, use .session(true).",
76
+ );
77
+ }
78
+ return targets;
79
+ }
80
+
81
+ // Objects and lists are written as JSON, and a value with a comma, quote or line break is quoted
82
+ function escapeCsvValue(value: unknown): string {
83
+ if (value === null || value === undefined) return '';
84
+ const text = typeof value === 'object' ? JSON.stringify(value) : String(value);
85
+ return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
86
+ }
87
+
88
+ /** A CSV with a column for every key that any of the rows has. */
89
+ export function convertArrayOfObjectsToCSV(rows: readonly CsvRow[]): string {
90
+ const headers = [...new Set(rows.flatMap((row) => Object.keys(row)))];
91
+ return [headers, ...rows.map((row) => headers.map((header) => row[header]))]
92
+ .map((values) => values.map(escapeCsvValue).join(','))
93
+ .join('\n');
94
+ }
95
+
96
+ // The session's params as columns. URL params that the experiment does not declare are prefixed
97
+ // with `url_`, which sets them apart from the study's own variables.
98
+ function paramColumns(session: SessionData): Record<string, unknown> {
99
+ const result: Record<string, unknown> = {};
100
+ for (const [name, param] of Object.entries(session.params)) {
101
+ result[param.registered ? name : columnPrefixes.url + name] = param.value;
102
+ }
103
+ return result;
104
+ }
105
+
106
+ // The fields of a trial's row that become trial_ columns in the CSVs other than the session's
107
+ const trialColumns = ['trialNumber', 'startMs', 'endMs', 'durationMs', 'type', 'name'] as const;
108
+
109
+ // Automatically builds CSV files from trial data.
110
+ // Each trial is routed to a CSV file based on: the trial's .csv() > its component's csv > skipped.
111
+ // The session CSV is a single row, in which the trials that go there have columns namespaced by
112
+ // trial name (e.g. 'nickname_value', 'devicecheck_browser') to avoid collisions.
113
+ // All other groups produce multi-row CSVs, one row per trial (or more if the flattener expands them).
114
+ function autoBuildCSVs(
115
+ sessionId: string,
116
+ data: ExperimentData,
117
+ components: ReadonlyMap<string, RuntimeComponent>,
118
+ sessionData?: Record<string, any>,
119
+ ): FileUpload[] {
120
+ const files: FileUpload[] = [];
121
+
122
+ // Group trials by their target CSV file name.
123
+ // A trial's .csv() can name several files, so one trial may appear in multiple groups.
124
+ const groups: Record<string, { item: TrialData; flatten?: Flatten }[]> = {};
125
+ for (const item of data.trials) {
126
+ for (const { file, flatten } of trialCsv(item.type, components.get(item.type)?.reactive.csv ?? [], item.csv)) {
127
+ groups[file] ??= [];
128
+ groups[file].push({ item, flatten });
129
+ }
130
+ }
131
+
132
+ // The session CSV: one row per participant, with the columns of the trials that go there
133
+ const row: CsvRow = {
134
+ sessionId,
135
+ userAgent: data.session.userAgent,
136
+ buildSeed: data.session.buildSeed,
137
+ ...paramColumns(data.session),
138
+ };
139
+ for (const [key, value] of Object.entries(sessionData ?? {})) row[columnPrefixes.session + key] = value;
140
+ for (const item of data.trials) {
141
+ const columns = components.get(item.type)?.reactive.session;
142
+ if (!(item.session ?? columns !== undefined)) continue;
143
+ const prefix = item.name || item.type;
144
+ // Add metadata, namespaced by trial name
145
+ for (const [key, value] of Object.entries(item.metadata ?? {})) row[`${prefix}_${columnPrefixes.meta}${key}`] = value;
146
+ // Add the response's fields, or those the component's session function returns, namespaced by trial name
147
+ const fields = typeof columns === 'function' ? columns(item) : item.recorded;
148
+ if (fields === undefined || fields === null) continue;
149
+ if (typeof fields !== 'object' || Array.isArray(fields)) {
150
+ report(
151
+ `The ${item.type} trial '${prefix}' gives the session CSV ${Array.isArray(fields) ? 'a list' : JSON.stringify(fields)}, but its one row per participant takes an object's fields as columns. Give the component a session function that returns them, as in session: (item) => ({ … }).`,
152
+ );
153
+ continue;
154
+ }
155
+ for (const [key, value] of Object.entries(fields)) row[`${prefix}_${responseColumn(key)}`] = value;
156
+ }
157
+ files.push({ filename: `session.${sessionId}.${Date.now()}.csv`, content: convertArrayOfObjectsToCSV([row]), encoding: 'utf8' });
158
+
159
+ // All other groups: multi-row CSVs, through the flatteners or from the responses. Each row is
160
+ // prepended with standard trial fields (prefixed trial_) and the trial's metadata (prefixed meta_).
161
+ for (const [csvName, entries] of Object.entries(groups)) {
162
+ const rows = entries.flatMap(({ item, flatten }) => {
163
+ const base: CsvRow = {};
164
+ for (const key of trialColumns) base[columnPrefixes.trial + key] = item[key];
165
+ // A flattener's rows, and the items of a response that is a list, are rows of their own, which
166
+ // can carry metadata of their own, as CanvasBlock's slides do; any other response is one row
167
+ const output = flatten ? flatten(item) : item.recorded;
168
+ const flatRows: { fields: Record<string, any>; metadata?: Record<string, any> }[] =
169
+ flatten || Array.isArray(output)
170
+ ? [output].flat().map((row) => {
171
+ const { metadata, ...fields } = typeof row === 'object' && row !== null ? row : { value: row };
172
+ return { fields, metadata: metadata as Record<string, any> | undefined };
173
+ })
174
+ : [{ fields: typeof output === 'object' && output !== null ? output : {} }];
175
+ return flatRows.map(({ fields, metadata }) => {
176
+ const merged = { ...base };
177
+ // Next to a row's own metadata, the trial's moves to columns of its own
178
+ const trialMeta = metadata ? columnPrefixes.slideblockMeta : columnPrefixes.meta;
179
+ for (const [key, value] of Object.entries(item.metadata ?? {})) merged[trialMeta + key] = value;
180
+ for (const [key, value] of Object.entries(metadata ?? {})) merged[columnPrefixes.meta + key] = value;
181
+ for (const [key, value] of Object.entries(fields)) merged[responseColumn(key)] = value;
182
+ return merged;
183
+ });
184
+ });
185
+ if (rows.length > 0) {
186
+ files.push({
187
+ filename: `${csvName}.${sessionId}.${Date.now()}.csv`,
188
+ content: convertArrayOfObjectsToCSV(rows),
189
+ encoding: 'utf8',
190
+ });
191
+ }
192
+ }
193
+
194
+ return files;
195
+ }
196
+
197
+ /** The file a recording is saved as: named after its trial, and unique in the session. */
198
+ export function audioFilename(label: string, trialNumber: number): string {
199
+ return `audio_${label}_${trialNumber}.webm`;
200
+ }
201
+
202
+ // The content the server already has under each filename, from recordings uploaded early. It only
203
+ // spares sending them again, which would save the same content under the same name.
204
+ const uploadedRecordings = new Map<string, string>();
205
+
206
+ export function markRecordingUploaded(filename: string, data64: string) {
207
+ uploadedRecordings.set(filename, data64);
208
+ }
209
+
210
+ // Scans trial data for audio recordings (type: 'audiorecording' with data64) and extracts them as
211
+ // separate .webm files. The returned rows reference the files by name instead of holding the
212
+ // binary data, which keeps CSVs and raw JSON clean.
213
+ function extractAudioRecordings(trials: TrialData[]): { files: UploadFile[]; trials: TrialData[] } {
214
+ const files: UploadFile[] = [];
215
+
216
+ const extract = (obj: any, label: string, trialNumber: number) => {
217
+ if (obj?.type !== 'audiorecording' || !obj.data64) return obj;
218
+ const filename = obj.audioFile ?? audioFilename(label, trialNumber);
219
+ files.push({
220
+ filename,
221
+ content: obj.data64,
222
+ encoding: 'base64' as const,
223
+ _alreadyUploaded: uploadedRecordings.get(filename) === obj.data64,
224
+ });
225
+ const { data64: _data64, blob: _blob, url: _url, ...rest } = obj;
226
+ return { ...rest, audioFile: filename };
227
+ };
228
+
229
+ const rows = trials.map((item) => {
230
+ const rd = item.recorded;
231
+ if (!rd || typeof rd !== 'object') return item;
232
+
233
+ const label = item.name || item.type;
234
+ // What the trial recorded is itself an audio recording (VoiceRecording component)
235
+ let recorded = extract(rd, label, item.trialNumber);
236
+
237
+ // or holds recordings among its fields (Quest voicerecorder questions)
238
+ if (recorded === rd && !Array.isArray(rd)) {
239
+ recorded = Object.fromEntries(
240
+ Object.entries(rd).map(([key, value]) => [
241
+ key,
242
+ value && typeof value === 'object' ? extract(value, `${label}_${key}`, item.trialNumber) : value,
243
+ ]),
244
+ );
245
+ }
246
+
247
+ return { ...item, recorded };
248
+ });
249
+
250
+ return { files, trials: rows };
251
+ }
252
+
253
+ export function buildUploadFiles(config: {
254
+ sessionId: string;
255
+ data: ExperimentData;
256
+ store: Store;
257
+ /** The components of the timeline, by name, which say where their rows go. */
258
+ components: ReadonlyMap<string, RuntimeComponent>;
259
+ generateFiles?: (input: { sessionId: string; data: ExperimentData; store: Store }) => FileUpload[];
260
+ sessionData?: Record<string, any>;
261
+ uploadRaw?: boolean;
262
+ }): UploadFile[] {
263
+ const {
264
+ sessionId,
265
+ data,
266
+ store,
267
+ components,
268
+ generateFiles,
269
+ sessionData,
270
+ uploadRaw = true,
271
+ } = config;
272
+
273
+ const files: UploadFile[] = generateFiles ? generateFiles({ sessionId, data, store }) : [];
274
+
275
+ // Extract audio recordings as separate files before serialization
276
+ const recordings = extractAudioRecordings(data.trials);
277
+ files.push(...recordings.files);
278
+ const saved = { ...data, trials: recordings.trials };
279
+
280
+ if (uploadRaw) {
281
+ files.push({
282
+ filename: `${sessionId}.raw.json`,
283
+ content: JSON.stringify(saved),
284
+ encoding: 'utf8',
285
+ });
286
+ }
287
+
288
+ files.push(...autoBuildCSVs(sessionId, saved, components, sessionData));
289
+
290
+ return files;
291
+ }
@@ -0,0 +1,166 @@
1
+ import type { ReservedParamName } from './columns';
2
+
3
+ /** A param: an input of the experiment or a setting of a component, read from the URL. */
4
+ export interface ParamSpec {
5
+ /** The values the param can take. */
6
+ values?: readonly (string | number)[];
7
+ /** Used when the URL does not set the param. A function is called once per participant. */
8
+ default: unknown;
9
+ description?: string;
10
+ }
11
+
12
+ type Widen<T> = T extends boolean
13
+ ? boolean
14
+ : T extends number
15
+ ? number
16
+ : T extends string
17
+ ? string
18
+ : T extends readonly (infer E)[]
19
+ ? Widen<E>[]
20
+ : T;
21
+
22
+ export type ParamValue<S> = S extends { values: readonly (infer V)[] }
23
+ ? V
24
+ : S extends { default: infer D }
25
+ ? Widen<D extends () => infer R ? R : D>
26
+ : never;
27
+
28
+ export type ParamValues<Params> = { [K in keyof Params]: ParamValue<Params[K]> };
29
+
30
+ /**
31
+ * Params as declared, checked by the types: a param with `values` has a default among them, also
32
+ * when a function computes it, and no param takes a session CSV column that the library writes.
33
+ */
34
+ export type CheckedParams<Params> = {
35
+ [K in keyof Params]: K extends ReservedParamName
36
+ ? `The session CSV keeps '${K & string}' for a column of its own, so the param needs another name`
37
+ : Params[K] extends { values: readonly (infer V)[] }
38
+ ? Omit<Params[K], 'default'> & { default: V | (() => V) }
39
+ : Params[K];
40
+ };
41
+
42
+ /** The library's own params, available in every experiment. */
43
+ export const libraryParams: Record<string, ParamSpec> = {
44
+ dev: { default: false, description: 'Enable the developer inspector panel' },
45
+ };
46
+
47
+ export type ParamType = 'string' | 'number' | 'boolean' | 'array' | 'json';
48
+
49
+ export function paramType(spec: ParamSpec): ParamType {
50
+ if (spec.values) return spec.values.every((v) => typeof v === 'number') ? 'number' : 'string';
51
+ const value = spec.default;
52
+ if (typeof value === 'boolean') return 'boolean';
53
+ if (typeof value === 'number') return 'number';
54
+ if (Array.isArray(value)) return 'array';
55
+ if (typeof value === 'object' && value !== null) return 'json';
56
+ return 'string';
57
+ }
58
+
59
+ /** Turns a value from the URL into the param's type. */
60
+ export function parseParam(name: string, spec: ParamSpec, raw: unknown): unknown {
61
+ if (spec.values) return spec.values.find((v) => String(v) === String(raw)) ?? raw;
62
+ // Values from the base64 link already have their type
63
+ if (typeof raw !== 'string') return raw;
64
+
65
+ const fallback = spec.default;
66
+ if (typeof fallback === 'string') return raw;
67
+ if (typeof fallback === 'boolean') {
68
+ if (!['true', 'false'].includes(raw.toLowerCase())) {
69
+ throw new Error(`The param '${name}' must be true or false, but the URL sets it to '${raw}'.`);
70
+ }
71
+ return raw.toLowerCase() === 'true';
72
+ }
73
+ if (typeof fallback === 'number') {
74
+ if (raw.trim() === '' || Number.isNaN(Number(raw))) {
75
+ throw new Error(`The param '${name}' must be a number, but the URL sets it to '${raw}'.`);
76
+ }
77
+ return Number(raw);
78
+ }
79
+ try {
80
+ return JSON.parse(raw);
81
+ } catch {
82
+ // A computed default does not say which type it has, so text that is not JSON stays text
83
+ if (typeof fallback === 'function') return raw;
84
+ throw new Error(`The param '${name}' must be JSON, but the URL sets it to '${raw}'.`);
85
+ }
86
+ }
87
+
88
+ const allowed = (spec: ParamSpec, value: unknown) =>
89
+ !spec.values || spec.values.includes(value as string | number);
90
+
91
+ const hasType: Record<ParamType, (value: unknown) => boolean> = {
92
+ string: (value) => typeof value === 'string',
93
+ number: (value) => typeof value === 'number' && !Number.isNaN(value),
94
+ boolean: (value) => typeof value === 'boolean',
95
+ array: Array.isArray,
96
+ json: (value) => typeof value === 'object' && value !== null && !Array.isArray(value),
97
+ };
98
+
99
+ // Whatever set it, a param has its declared type: one of its values, or the type of its default.
100
+ // A default that a function computes declares no type, so only `values` can check it.
101
+ function check(name: string, spec: ParamSpec, value: unknown) {
102
+ if (spec.values) {
103
+ if (!allowed(spec, value)) {
104
+ throw new Error(
105
+ `The param '${name}' must be one of ${spec.values.map((v) => JSON.stringify(v)).join(', ')}, but it is ${JSON.stringify(value)}.`,
106
+ );
107
+ }
108
+ return;
109
+ }
110
+ if (typeof spec.default === 'function') return;
111
+ const type = paramType(spec);
112
+ if (!hasType[type](value)) {
113
+ throw new Error(`The param '${name}' must be of type ${type}, like its default, but it is ${JSON.stringify(value)}.`);
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Resolves each param from, in this order: `overrides` (a simulated participant's params), the
119
+ * URL's params, `previous` (values kept across hot reloads), and its default.
120
+ */
121
+ export function resolveParams(
122
+ params: Record<string, ParamSpec> = {},
123
+ sources: {
124
+ url?: Record<string, unknown>;
125
+ overrides?: Record<string, unknown>;
126
+ previous?: Record<string, unknown>;
127
+ } = {},
128
+ ): Record<string, unknown> {
129
+ const values: Record<string, unknown> = {};
130
+ for (const [name, spec] of Object.entries(params)) {
131
+ const raw = sources.url?.[name];
132
+ const previous = sources.previous;
133
+ let value: unknown;
134
+ if (sources.overrides && name in sources.overrides) {
135
+ value = sources.overrides[name];
136
+ } else if (raw !== undefined && raw !== null) {
137
+ value = parseParam(name, spec, raw);
138
+ } else if (previous && name in previous && allowed(spec, previous[name])) {
139
+ value = previous[name];
140
+ } else {
141
+ if (previous && name in previous) {
142
+ console.warn(`The param '${name}' no longer allows ${JSON.stringify(previous[name])}, so it was set again.`);
143
+ }
144
+ value = typeof spec.default === 'function' ? spec.default() : spec.default;
145
+ }
146
+
147
+ check(name, spec, value);
148
+ values[name] = value;
149
+ }
150
+ return values;
151
+ }
152
+
153
+ /** The params in a URL: the plain ones, and those in the base64 JSON of `_b`, which take precedence. */
154
+ export function urlParams(search = window.location.search): Record<string, unknown> {
155
+ const searchParams = new URLSearchParams(search);
156
+ const plain: Record<string, unknown> = Object.fromEntries(searchParams);
157
+ delete plain._b;
158
+ const encoded = searchParams.get('_b');
159
+ if (!encoded) return plain;
160
+ try {
161
+ return { ...plain, ...JSON.parse(atob(encoded)) };
162
+ } catch {
163
+ // An unreadable _b is ignored
164
+ return plain;
165
+ }
166
+ }
@@ -0,0 +1,29 @@
1
+ // Set by @adriansteffan/reactive/native when the experiment runs as an Android or iOS app
2
+
3
+ export interface FileBackend {
4
+ directoryExists(path: string): Promise<boolean>;
5
+ createDirectory(path: string): Promise<void>;
6
+ saveFile(filename: string, content: string, directory: string): Promise<void>;
7
+ }
8
+
9
+ export interface NativeIntegration {
10
+ createFileBackend(parentFolder?: string): FileBackend;
11
+ canWriteFiles(): Promise<boolean>;
12
+ enterFullscreen(): void;
13
+ exitFullscreen(): void;
14
+ }
15
+
16
+ let nativeIntegration: NativeIntegration | null = null;
17
+
18
+ export function registerNative(integration: NativeIntegration) {
19
+ nativeIntegration = integration;
20
+ }
21
+
22
+ export function getNative(): NativeIntegration | null {
23
+ return nativeIntegration;
24
+ }
25
+
26
+ /** `native` when the experiment runs as an Android or iOS app. */
27
+ export type Platform = 'native' | 'web';
28
+
29
+ export const getPlatform = (): Platform => (getNative() ? 'native' : 'web');
@@ -0,0 +1,106 @@
1
+ import type { Run } from './experiment';
2
+ import type { TrialCsv } from './files';
3
+ import { report } from './development';
4
+ import { type ParamType, paramType } from './params';
5
+ import { type TimelineContext, resolve, type TrialContent } from './timeline';
6
+
7
+ /** One row of the data: what a trial recorded, its timing, and what identifies it. */
8
+ export interface TrialData {
9
+ /** The order in which the participant saw the trial, from 1. */
10
+ trialNumber: number;
11
+ /** The component's name. */
12
+ type: string;
13
+ name: string;
14
+ /** Set with `.csv()`: how the row's CSV files differ from its component's. */
15
+ csv?: TrialCsv;
16
+ /** Set with `.session()`: whether the row has columns in the session CSV, unlike its component's. */
17
+ session?: boolean;
18
+ recorded: any;
19
+ /** Set with `.metadata()`. */
20
+ metadata?: Record<string, any>;
21
+ startMs: number;
22
+ endMs: number;
23
+ durationMs: number;
24
+ }
25
+
26
+ /** The row a trial records when it ends, the same whether a participant or a simulation ran it. */
27
+ export function createTrialRow(
28
+ content: TrialContent,
29
+ trial: { trialNumber: number; startMs: number; endMs: number; recorded: unknown },
30
+ context: TimelineContext,
31
+ ): TrialData {
32
+ const metadata = resolve(content.metadata, context);
33
+ return {
34
+ trialNumber: trial.trialNumber,
35
+ startMs: trial.startMs,
36
+ endMs: trial.endMs,
37
+ durationMs: trial.endMs - trial.startMs,
38
+ type: content.type,
39
+ name: content.name ?? '',
40
+ ...(content.csv !== undefined ? { csv: content.csv } : {}),
41
+ ...(content.session !== undefined ? { session: content.session } : {}),
42
+ recorded: trial.recorded,
43
+ ...(metadata !== undefined ? { metadata } : {}),
44
+ };
45
+ }
46
+
47
+ /** A param as the session recorded it: its value, and how the experiment declared it. */
48
+ export interface RecordedParam {
49
+ value: unknown;
50
+ /** `false` for a URL param that nothing declares. */
51
+ registered: boolean;
52
+ defaultValue: unknown;
53
+ type: ParamType | undefined;
54
+ description: string | undefined;
55
+ }
56
+
57
+ /** What a session records about itself when it starts. */
58
+ export interface SessionData {
59
+ userAgent: string;
60
+ /** Every param by name, including URL params that nothing declares. */
61
+ params: Record<string, RecordedParam>;
62
+ /** Seeds the random draws made while the timeline was built, so that it can be built again. */
63
+ buildSeed: number;
64
+ /** The timeline's named trials, which a component's `getAll` and `getLatest` check a name against. */
65
+ namedTrials: { type: string; name: string }[];
66
+ }
67
+
68
+ /** Everything a session records: the session itself, and a row for each trial. */
69
+ export interface ExperimentData {
70
+ session: SessionData;
71
+ /** A row for each trial that has ended, in the order the participant saw them, so `trials[i].trialNumber` is `i + 1`. */
72
+ trials: TrialData[];
73
+ }
74
+
75
+ /** The data a session starts with: its params and how it was built, and no trials yet. */
76
+ export function createExperimentData(info: { userAgent: string; url: Record<string, unknown>; run: Run }): ExperimentData {
77
+ const { specs, params: values, buildSeed } = info.run;
78
+ const params: Record<string, RecordedParam> = {};
79
+ // URL params that nothing declares are recorded too, and appear in the CSVs with a url_ prefix
80
+ for (const [name, value] of Object.entries(info.url)) {
81
+ if (!(name in specs)) {
82
+ params[name] = { value, registered: false, defaultValue: undefined, type: undefined, description: undefined };
83
+ }
84
+ }
85
+ for (const [name, spec] of Object.entries(specs)) {
86
+ params[name] = {
87
+ value: values[name],
88
+ registered: true,
89
+ defaultValue: typeof spec.default === 'function' ? undefined : spec.default,
90
+ type: paramType(spec),
91
+ description: spec.description,
92
+ };
93
+ }
94
+ return {
95
+ session: { userAgent: info.userAgent, params, buildSeed, namedTrials: info.run.compiled.namedTrials },
96
+ trials: [],
97
+ };
98
+ }
99
+
100
+ /** The rows of a component's trials, or of its trial with this name, in the order they ran. */
101
+ export function rowsOf(type: string, data: ExperimentData, name?: string): TrialData[] {
102
+ if (name !== undefined && !data.session.namedTrials.some((trial) => trial.type === type && trial.name === name)) {
103
+ report(`There is no ${type} trial named '${name}' in the timeline.`);
104
+ }
105
+ return data.trials.filter((row) => row.type === type && (name === undefined || row.name === name));
106
+ }