forked from OpenDataEnsemble/ode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormulusInterfaceDefinition.ts
More file actions
524 lines (483 loc) · 17.7 KB
/
FormulusInterfaceDefinition.ts
File metadata and controls
524 lines (483 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
/**
* FormulusInterfaceDefinition.ts
*
* This module defines the shared interface between the Formulus React Native app and the Formplayer WebView.
* It serves as the single source of truth for the interface definition.
*
* NOTE: This file should be manually copied to client projects that need to interact with the Formulus app.
* If you've checked out the monorepo use:
* cp ..\formulus\src\webview\FormulusInterfaceDefinition.ts .\src\FormulusInterfaceDefinition.ts
*
* Interface version: see `FORMULUS_INTERFACE_VERSION` below (single source of truth).
*/
/**
* Extension metadata for custom app extensions
*/
export interface ExtensionMetadata {
definitions?: Record<string, unknown>;
functions?: Record<
string,
{
name: string;
module: string;
export?: string;
}
>;
renderers?: Record<
string,
{
name: string;
format: string;
module: string;
tester?: string;
renderer?: string;
}
>;
basePath?: string; // Base path for loading modules
}
/**
* Data passed to the Formulus app when a form is initialized
* @property {string} formType - The form type (e.g. 'form1')
* @property {string | null} observationId - The observation ID (generated by the database on first form submission). NULL if this is a new form.
* @property {Record<string, unknown>} params - Host parameters for the formplayer WebView. Put **field prefills** in `params.defaultData` (a plain object). Top-level keys are reserved for bridge/UI: `defaultData`, `theme`, `darkMode`, `themeColors` (and any future keys added to the formplayer allowlist)—do not rely on those being stored on the observation. If `defaultData` is omitted, legacy behavior copies every other top-level key as prefill data (still excluding the reserved keys above). On load and submit, when the JSON Schema has non-empty root `properties`, the formplayer keeps only those property keys plus `locale` so polluted rows are cleaned on re-save.
* @property {Record<string, unknown>} savedData - Previously saved form data (for editing)
* @property {any} [formSchema] - JSON Schema for the form structure and validation (optional)
* @property {any} [uiSchema] - UI Schema for form rendering layout (optional)
* @property {ExtensionMetadata} [extensions] - Custom app extensions (optional)
* @property {object} [customQuestionTypes] - Custom question type manifest from custom_app (optional)
*/
export interface FormInitData {
formType: string;
observationId: string | null;
params: Record<string, unknown>;
savedData: Record<string, unknown>;
formSchema?: unknown;
uiSchema?: unknown;
operationId?: string;
extensions?: ExtensionMetadata;
customQuestionTypes?: {
custom_types: Record<string, { source: string }>;
validators?: Record<string, { source: string }>;
};
}
/**
* Generic result type for media/action requests (camera, audio, etc.)
* @property {string} fieldId - The ID of the field that triggered the action
* @property {'success' | 'cancelled' | 'error'} status - The outcome status
* @property {string} [message] - Optional message (mainly for errors)
* @property {T} [data] - Action-specific result data (only present on success)
*/
export interface ActionResult<T = unknown> {
fieldId: string;
status: 'success' | 'cancelled' | 'error';
message?: string;
data?: T;
}
/**
* Camera-specific result data
* @property {'image'} type - Always 'image' for camera results
* @property {string} filename - Generated filename for the image
* @property {string} timestamp - ISO timestamp when image was captured
* @property {object} metadata - Image metadata (dimensions, size, etc.)
*/
export interface CameraResultData {
type: 'image';
id: string;
filename: string;
uri: string;
url: string;
timestamp: string;
metadata: {
width: number;
height: number;
size: number;
mimeType: string;
source: string;
quality: number;
originalFileName?: string;
persistentStorage: boolean;
storageLocation: string;
};
}
/**
* Audio-specific result data
* @property {'audio'} type - Always 'audio' for audio results
* @property {string} filename - Generated filename for the audio
* @property {string} base64 - Base64 encoded audio data
* @property {string} url - Data URL for the audio
* @property {string} timestamp - ISO timestamp when audio was recorded
* @property {object} metadata - Audio metadata (duration, format, etc.)
*/
export interface AudioResultData {
type: 'audio';
filename: string;
base64: string;
url: string;
timestamp: string;
metadata: {
duration: number;
format: string;
sampleRate: number;
channels: number;
size: number;
};
}
/**
* QR code-specific result data
* @property {'qrcode'} type - Always 'qrcode' for QR code results
* @property {string} value - The decoded QR code string value
* @property {string} timestamp - ISO timestamp when QR code was scanned
*/
export interface QrcodeResultData {
type: 'qrcode';
value: string;
timestamp: string;
}
/**
* File selection result data
* @property {'file'} type - Always 'file' for file selection results
* @property {string} filename - Original filename of the selected file
* @property {string} uri - Local file URI (no base64 encoding)
* @property {string} mimeType - MIME type of the selected file
* @property {number} size - File size in bytes
* @property {string} timestamp - ISO timestamp when file was selected
* @property {object} metadata - File metadata (extension, original path, etc.)
*/
export interface FileResultData {
type: 'file';
filename: string;
uri: string; // Local file URI (no base64 encoding)
mimeType: string;
size: number;
timestamp: string;
metadata: {
extension: string;
originalPath?: string;
};
}
/**
* Type aliases for specific action results
*/
export type CameraResult = ActionResult<CameraResultData>;
export type AudioResult = ActionResult<AudioResultData>;
export type QrcodeResult = ActionResult<QrcodeResultData>;
export type FileResult = ActionResult<FileResultData>;
/**
* @deprecated Use ActionResult<CameraResultData> instead
* Data passed to the Formulus app when an attachment is ready
* @property {string} fieldId - The ID of the field
* @property {string} type - The type of the attachment
* @property {any} [key: string] - Additional properties based on type
*/
export interface AttachmentData {
fieldId: string;
type:
| 'image'
| 'location'
| 'file'
| 'intent'
| 'subform'
| 'audio'
| 'signature'
| 'biometric'
| 'connectivity'
| 'sync'
| 'ml_result';
[key: string]: unknown;
}
/**
* Information about a form
* @property {string} formType - The form type (e.g. 'form1')
* @property {string} name - The name of the form
* @property {string} version - The version of the form
* @property {string[]} coreFields - The core fields of the form
* @property {string[]} auxiliaryFields - The auxiliary fields of the form
*/
export interface FormInfo {
formType: string;
name: string;
version: string;
coreFields: string[];
auxiliaryFields: string[];
}
/**
* Information about a form observation
* @property {string} observationId - The observation ID (generated by the database on first form submission)
* @property {Date} createdAt - The date the observation was created
* @property {Date} updatedAt - The date the observation was last updated
* @property {Date} syncedAt - The date the observation was synced
* @property {boolean} isDraft - Whether the observation is a draft
* @property {boolean} deleted - Whether the observation has been deleted
* @property {string} formType - The form type (e.g. 'form1')
* @property {string} formVersion - The version of the form
* @property {Record<string, any>} data - The form data
*/
export interface FormObservation {
observationId: string;
createdAt: Date;
updatedAt: Date;
syncedAt: Date;
isDraft: boolean;
deleted: boolean;
formType: string;
formVersion: string;
data: Record<string, unknown>;
}
/**
* Result returned when a form is completed or closed
* @property {'form_submitted' | 'form_updated' | 'draft_saved' | 'cancelled' | 'error'} status - The outcome status
* @property {string} [observationId] - The observation ID (present on successful submission/update)
* @property {Record<string, any>} [formData] - The final form data (present on successful submission/update)
* @property {string} [message] - Optional message (mainly for errors or additional context)
* @property {string} formType - The form type that was being edited
*/
export interface FormCompletionResult {
status:
| 'form_submitted'
| 'form_updated'
| 'draft_saved'
| 'cancelled'
| 'error';
observationId?: string;
formData?: Record<string, unknown>;
message?: string;
formType: string;
}
/**
* Interface for the Formulus app methods that will be injected into the WebViews for custom_app and FormPlayer
* @namespace formulus
*/
export interface FormulusInterface {
/**
* Get the current version of the Formulus API
* @returns {Promise<string>} The API version
*/
getVersion(): Promise<string>;
/**
* Get a list of available forms
* @returns {Promise<FormInfo[]>} Array of form information objects
*/
getAvailableForms(): Promise<FormInfo[]>;
/**
* Open Formplayer with the specified form
* @param {string} formType - The identifier of the formtype to open
* @param {Object} params - Additional parameters for form initialization
* @param {Object} savedData - Previously saved form data (for editing)
* @returns {Promise<FormCompletionResult>} Promise that resolves when the form is completed/closed with result details
*/
openFormplayer(
formType: string,
params: Record<string, unknown>,
savedData: Record<string, unknown>,
): Promise<FormCompletionResult>;
/**
* Get observations for a specific form
* @param {string} formType - The identifier of the formtype
* @param {boolean} [isDraft=false] - Deprecated: drafts are handled only in formplayer; ignored in Formulus
* @param {boolean} [includeDeleted=false] - Whether to include deleted observations (default false = exclude)
* @returns {Promise<FormObservation[]>} Array of form observations
*/
getObservations(
formType: string,
isDraft?: boolean,
includeDeleted?: boolean,
): Promise<FormObservation[]>;
/**
* Get observations with optional WHERE clause filtering (for dynamic choice lists).
* Supports format: data.field = 'value' AND data.other = 'value'
* Age filtering via age_from_dob(data.dob) is handled client-side in formplayer.
* @param options - Query options
* @param options.formType - Form type to query
* @param options.isDraft - Deprecated: drafts handled in formplayer; ignored
* @param options.includeDeleted - Include deleted (default false)
* @param options.whereClause - SQL-like WHERE clause for filtering (e.g. "data.sex = 'male'")
* @returns {Promise<FormObservation[]>} Array of filtered observations
*/
getObservationsByQuery(options: {
formType: string;
isDraft?: boolean;
includeDeleted?: boolean;
whereClause?: string | null;
}): Promise<FormObservation[]>;
/**
* Submit a completed form
* @param {string} formType - The identifier of the formtype
* @param {Object} finalData - The final form data to submit
* @returns {Promise<string>} The observationId of the submitted form
*/
submitObservation(
formType: string,
finalData: Record<string, unknown>,
): Promise<string>;
/**
* Update an existing form
* @param {string} observationId - The identifier of the observation
* @param {string} formType - The identifier of the formtype
* @param {Object} finalData - The final form data to update
* @returns {Promise<string>} The observationId of the updated form
*/
updateObservation(
observationId: string,
formType: string,
finalData: Record<string, unknown>,
): Promise<string>;
/**
* Request camera access for a field
* @param {string} fieldId - The ID of the field
* @returns {Promise<CameraResult>} Promise that resolves with camera result or rejects on error/cancellation
*/
requestCamera(fieldId: string): Promise<CameraResult>;
/**
* Request location for a field
* @param {string} fieldId - The ID of the field
* @returns {Promise<void>}
*/
requestLocation(fieldId: string): Promise<void>;
/**
* Request file selection for a field
* @param {string} fieldId - The ID of the field
* @returns {Promise<FileResult>} Promise that resolves with file result or rejects on error/cancellation
*/
requestFile(fieldId: string): Promise<FileResult>;
/**
* Launch an external intent
* @param {string} fieldId - The ID of the field
* @param {Object} intentSpec - The intent specification
* @returns {Promise<void>}
*/
launchIntent(
fieldId: string,
intentSpec: Record<string, unknown>,
): Promise<void>;
/**
* Call a subform
* @param {string} fieldId - The ID of the field
* @param {string} formType - The ID of the subform
* @param {Object} options - Additional options for the subform
* @returns {Promise<void>}
*/
callSubform(
fieldId: string,
formType: string,
options: Record<string, unknown>,
): Promise<void>;
/**
* Request audio recording for a field
* @param {string} fieldId - The ID of the field
* @returns {Promise<AudioResult>} Promise that resolves with audio result or rejects on error/cancellation
*/
requestAudio(fieldId: string): Promise<AudioResult>;
/**
* Request QR code scanning for a field
* @param {string} fieldId - The ID of the field
* @returns {Promise<QrcodeResult>} Promise that resolves with QR code result or rejects on error/cancellation
*/
requestQrcode(fieldId: string): Promise<QrcodeResult>;
/**
* Request biometric authentication
* @param {string} fieldId - The ID of the field
* @returns {Promise<void>}
*/
requestBiometric(fieldId: string): Promise<void>;
/**
* Request the current connectivity status
* @returns {Promise<void>}
*/
requestConnectivityStatus(): Promise<void>;
/**
* Request the current sync status
* @returns {Promise<void>}
*/
requestSyncStatus(): Promise<void>;
/**
* Run a local ML model
* @param {string} fieldId - The ID of the field
* @param {string} modelId - The ID of the model to run
* @param {Object} input - The input data for the model
* @returns {Promise<void>}
*/
runLocalModel(
fieldId: string,
modelId: string,
input: Record<string, unknown>,
): Promise<void>;
/**
* Get information about the currently authenticated user.
* When no one is logged in, resolves with `{ username: '' }` (does not reject).
* @returns {Promise<{username: string, displayName?: string, role?: 'read-only' | 'read-write' | 'admin'}>} User information including role
*/
getCurrentUser(): Promise<{
username: string;
displayName?: string;
role?: 'read-only' | 'read-write' | 'admin';
}>;
/**
* Get the current theme mode (System / Light / Dark) so custom apps can match the host app.
* @returns {Promise<'light' | 'dark' | 'system'>} Current theme mode; 'system' means follow device preference.
*/
getThemeMode(): Promise<'light' | 'dark' | 'system'>;
/**
* Resolve a synced or camera-saved attachment to a WebView-loadable `file://` URL.
* Checks `{DocumentDirectory}/attachments/draft/` (unsaved capture), then `attachments/`,
* then `pending_upload/`. Pass the basename only (e.g. `photo.filename` from observation
* data); path segments and ".." are rejected.
* @param fileName - Attachment file basename
* @returns `file://` URL if the file exists, otherwise `null`
*/
getAttachmentUri(fileName: string): Promise<string | null>;
/**
* Base `file://` URL for the attachments directory (trailing slash).
* @returns e.g. `file:///.../attachments/`
*/
getAttachmentsUri(): Promise<string>;
/**
* Base `file://` URL for the custom app bundle root (`DocumentDirectory/app/`, trailing slash).
* @returns App directory URL for extensions, question_types, etc.
*/
getCustomAppUri(): Promise<string>;
/**
* Primary `file://` URL for downloaded form specs (`DocumentDirectory/forms/`, trailing slash).
* Some bundles also use files under the custom app `forms/` subdirectory.
* @returns Forms directory URL
*/
getFormSpecsUri(): Promise<string>;
}
/**
* Interface for callback methods that the Formplayer WebView implements
*/
export interface FormulusCallbacks {
onFormInit?: (
formType: string,
observationId: string | null,
params: Record<string, unknown>,
savedData: Record<string, unknown>,
) => void;
onReceiveFocus?: () => void;
}
/**
* Current version of the interface
*/
export const FORMULUS_INTERFACE_VERSION = '1.2.1';
/** Parses major.minor.patch from the start of a version string (ignores prerelease after `-`). */
function semverSegments(version: string): [number, number, number] {
const core = version.split('-')[0].split('+')[0].trim();
const parts = core.split('.').map(s => parseInt(s, 10));
const major = Number.isFinite(parts[0]) ? parts[0]! : 0;
const minor = Number.isFinite(parts[1]) ? parts[1]! : 0;
const patch = Number.isFinite(parts[2]) ? parts[2]! : 0;
return [major, minor, patch];
}
function compareSemver(a: string, b: string): number {
const [aMaj, aMin, aPat] = semverSegments(a);
const [bMaj, bMin, bPat] = semverSegments(b);
if (aMaj !== bMaj) return aMaj > bMaj ? 1 : -1;
if (aMin !== bMin) return aMin > bMin ? 1 : -1;
if (aPat !== bPat) return aPat > bPat ? 1 : -1;
return 0;
}
/**
* Returns true if the running interface version is at least `requiredVersion` (semver major.minor.patch).
*/
export function isCompatibleVersion(requiredVersion: string): boolean {
return compareSemver(FORMULUS_INTERFACE_VERSION, requiredVersion) >= 0;
}