-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathFormulusInterfaceDefinition.ts
More file actions
755 lines (698 loc) · 27.1 KB
/
Copy pathFormulusInterfaceDefinition.ts
File metadata and controls
755 lines (698 loc) · 27.1 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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
/**
* 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;
/** Sub-observation session: embedded child form returns JSON to parent; do not persist as a top-level observation. */
subObservationMode?: boolean;
/** Skip the Finalize page and submit from the last content page (sub-observation fast path). */
skipFinalize?: boolean;
/** Skip DraftSelector when the host orchestrates the session (e.g. programmatic open). */
skipDraftSelection?: boolean;
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 (immediate bridge payload after capture).
*
* **Observation JSON:** persist only portable fields — {@link id}, {@link type},
* {@link filename} (basename only, e.g. `<guid>.jpg`), {@link timestamp}, and {@link metadata}.
* Do **not** persist {@link uri} or {@link url}; resolve thumbnails and playback URLs with
* {@link FormulusInterface.getAttachmentUri}.
*
* @property {string} filename - Stable attachment basename, not a directory path.
* @property {string} uri - Native absolute filesystem path on the host (debugging / RN use); ephemeral.
* @property {string} url - Transient `file://` (or similar) for the same file as {@link uri}; ephemeral.
*/
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;
};
}
/**
* Attachment reference for {@link FormulusInterface.getAttachmentUri} when not passing a basename string.
* Use `filename` only (observation JSON must not store file paths or `uri` — resolve display URLs via this API).
*/
export interface AttachmentDisplayDescriptor {
filename?: string;
}
/**
* Audio-specific bridge payload after recording.
*
* **Observation JSON:** persist only **`type`**, **`filename`** (basename),
* **`timestamp`**, and **`metadata`** (portable subset). Do **not** persist **`uri`**,
* **`url`**, or **`base64`**; resolve playback URLs with {@link FormulusInterface.getAttachmentUri}.
*
* @property {string} uri - Native path or `file://` URL — ephemeral.
* @property {string} [base64] - Optional (e.g. browser mocks).
* @property {string} [url] - Optional data/http URL — ephemeral.
*/
export interface AudioResultData {
type: 'audio';
filename: string;
uri?: string;
base64?: string;
url?: string;
timestamp: string;
metadata: {
duration: number;
format: string;
size: number;
sampleRate?: number;
channels?: number;
};
}
/**
* Video-specific bridge payload after recording.
*
* **Observation JSON:** persist only **`type`**, **`filename`** (basename),
* **`timestamp`**, and **`metadata`**. Do **not** persist **`uri`** / **`url`**;
* resolve playback URLs with {@link FormulusInterface.getAttachmentUri}.
*/
export interface VideoResultData {
type: 'video';
filename: string;
uri?: string;
url?: string;
timestamp: string;
metadata: {
duration: number;
format: string;
size: number;
width?: number;
height?: 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 from the native document picker (bridge payload).
*
* **Observation persistence:** store {@link FileResultData.filename} as **basename only**
* (draft/synced attachment key), plus portable {@link FileResultData.metadata} fields such as
* `mimeType`, `size`, `extension`, and optional **{@link FileResultData.metadata.originalFileName}**
* for display. Do **not** persist bridge-only paths: {@link FileResultData.uri},
* {@link FileResultData.url}, or {@link FileResultData.metadata.originalPath}.
*
* @property {'file'} type - Always `file` for file selection results
* @property {string} filename - Stable basename under attachments (e.g. uuid.pdf)
* @property {string} uri - Ephemeral absolute path of the draft copy (native → WebView)
* @property {string} [url] - Ephemeral `file://` URL for the draft copy
*/
export interface FileResultData {
type: 'file';
filename: string;
uri: string;
url?: string;
mimeType: string;
size: number;
timestamp: string;
metadata: {
extension: string;
/** Original picker display name; safe to persist on observations. */
originalFileName?: string;
/** Ephemeral native path from the picker; do not persist. */
originalPath?: string;
};
}
/**
* GPS / location capture result (in-form field), from native GeolocationService.
*/
export interface LocationResultData {
type: 'location';
latitude: number;
longitude: number;
accuracy?: number;
altitude?: number | null;
altitudeAccuracy?: number | null;
timestamp: string;
}
/**
* Type aliases for specific action results
*/
export type CameraResult = ActionResult<CameraResultData>;
export type AudioResult = ActionResult<AudioResultData>;
export type VideoResult = ActionResult<VideoResultData>;
export type QrcodeResult = ActionResult<QrcodeResultData>;
export type FileResult = ActionResult<FileResultData>;
export type LocationResult = ActionResult<LocationResultData>;
/**
* @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;
}
/**
* Input for {@link FormulusInterface.persistObservation}.
* @property formType - Form type id the observation belongs to
* @property finalData - Observation JSON to store (must match the form schema)
* @property observationId - Provide to update an existing observation; omit/null to create
*/
export interface PersistObservationInput {
formType: string;
finalData: Record<string, unknown>;
observationId?: string | null;
}
/**
* Result of {@link FormulusInterface.persistObservation}.
* @property observationId - The id of the created/updated observation
* @property formData - The stored data (attachment paths normalized to committed locations)
*/
export interface PersistObservationResult {
observationId: string;
formData: Record<string, unknown>;
}
/**
* Result of {@link FormulusInterface.sync}.
* @property version - Final repository/data version reported by the server after sync
*/
export interface SyncResult {
version: number;
}
/**
* Result of {@link FormulusInterface.getConnectivityStatus}.
* @property online - Whether the configured Synkronus server answered a `/health` probe
* @property serverUrl - The configured server URL, or null if none is set
* @property checkedAt - Epoch milliseconds when the probe completed
*/
export interface ConnectivityStatus {
online: boolean;
serverUrl: string | null;
checkedAt: number;
}
/**
* 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 bridge API (the interface contract
* version, e.g. for {@link isCompatibleVersion} checks).
* @returns {Promise<string>} The API version (semver)
*/
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.
* Reserved keys are not treated as observation data:
* `defaultData` (prefill), `theme`/`darkMode`/`themeColors` (theming), and
* `context` — a read-only **session context** object (device role, selected cluster,
* ...) that Formplayer never persists and exposes to extensions as
* `window.formulusSessionContext`. Draft bypass is not a param key — use
* `options.skipDraftSelection` on {@link openFormplayer} (same as `skipFinalize`).
* @param {Object} savedData - Previously saved form data (for editing)
* @param {Object} [options] - Session options (not persisted as observation data)
* @param {string|null} [options.observationId] - When set, finalize updates this
* observation instead of creating a new one
* @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>,
options?: {
subObservationMode?: boolean;
skipFinalize?: boolean;
skipDraftSelection?: boolean;
observationId?: string | null;
},
): 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.filter - Structured observation filter AST
* @param options.whereClause - Deprecated; use filter
* @returns {Promise<FormObservation[]>} Array of filtered observations
*/
getObservationsByQuery(options: {
formType: string;
isDraft?: boolean;
includeDeleted?: boolean;
filter?: import('@ode/observation-query').ObservationFilter;
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 (captures into the form GPS field).
* @param {string} fieldId - The ID of the field
* @returns {Promise<LocationResult>} Promise that resolves with location result or rejects on error
*/
requestLocation(fieldId: string): Promise<LocationResult>;
/**
* Return the best cached device fix (if any) without forcing a new GPS read.
* @param fieldId Optional field id for parity with `requestLocation`
*/
getCachedLocation(fieldId?: string): Promise<LocationResult | null>;
/**
* Allocate the next monotonic integer in a device-local scope.
* Formulus prepends `device:{deviceId}:` to the app-authored `scopeKey` suffix.
* @param scopeKey App suffix, e.g. `af:A12:person` (no device prefix).
* @param options `startAt` default 1; `peek` returns next without consuming.
*/
allocateSequence(
scopeKey: string,
options?: { startAt?: number; peek?: boolean },
): Promise<number>;
/**
* Subscribe to location updates while the custom app WebView is active.
* Updates arrive as `locationWatchUpdate` window messages.
*/
watchLocation(
fieldId: string,
): Promise<{ status: 'started' | 'error'; message?: string }>;
/** Stop a prior `watchLocation` subscription for `fieldId`. */
stopWatchLocation(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 video recording for a field (camera / picker — host-defined).
* @param {string} fieldId - The ID of the field
* @returns {Promise<VideoResult>} Promise that resolves with video result or rejects on error/cancellation
*/
requestVideo(fieldId: string): Promise<VideoResult>;
/**
* 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 an attachment to a WebView-loadable URL (`file://`, `http(s):`, or host-specific).
*
* **String `fileName`:** basename only (e.g. `photo.filename`). Lookup order, first hit wins:
* 1. `attachments/draft/<name>` — unsaved capture (formplayer preview)
* 2. `attachments/synced/<name>` — canonical committed / downloaded copy
* 3. `attachments/pending/<name>` — queued for upload (fallback only)
* Legacy locations (`attachments/<name>` and `attachments/pending_upload/<name>`) are also checked.
* Path segments and ".." are rejected.
*
* **`AttachmentDisplayDescriptor`:** `{ filename }` basename only (same lookup as a string argument).
*
* @param fileName - Basename string, or `{ filename? }` (never a stored `uri` — use this method to resolve URLs)
* @returns Display URL, or `null` if none
*/
getAttachmentUri(
fileName: string | AttachmentDisplayDescriptor,
): Promise<string | null>;
/**
* Base `file://` URL for the canonical attachments directory (trailing slash).
* Returns the `synced/` subfolder — only committed/downloaded files are
* iterable from here. Drafts and the upload queue are excluded by design so
* custom apps can safely list this directory.
*
* **Breaking change (v2 layout):** this used to return the `attachments/`
* parent directory, which mixed committed files with `draft/` and
* `pending_upload/` subfolders. Custom apps that iterate this URL will now
* see only fully-committed attachments.
*
* @returns e.g. `file:///.../attachments/synced/`
*/
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>;
/**
* Persist an observation **without opening Formplayer** (headless write).
*
* Intended for custom apps that create or update records programmatically.
* Uses the same persistence path as a Formplayer submit, including promotion
* of any referenced draft attachments. Provide `observationId` to update an
* existing row; omit it to create a new one.
*
* @since 1.3.0
* @param {PersistObservationInput} input - The observation to persist
* @returns {Promise<PersistObservationResult>} The stored observation id and data
*/
persistObservation(
input: PersistObservationInput,
): Promise<PersistObservationResult>;
/**
* Trigger a synchronization with Synkronus (pull + push).
*
* Resolves when the sync completes; rejects if a sync is already in progress
* or the sync fails. Attachments are excluded by default for speed.
*
* @since 1.3.0
* @param {{ includeAttachments?: boolean }} [options] - Sync options
* @returns {Promise<SyncResult>} The final data version after sync
*/
sync(options?: { includeAttachments?: boolean }): Promise<SyncResult>;
/**
* Probe connectivity to the configured Synkronus server (`GET /health`).
*
* Never rejects for an offline device — returns `{ online: false }` so callers
* can branch on connectivity without try/catch. Suitable for the
* "verify subject details when online, fall back when offline" pattern.
*
* @since 1.3.0
* @returns {Promise<ConnectivityStatus>} The current connectivity status
*/
getConnectivityStatus(): Promise<ConnectivityStatus>;
/**
* Read the device's last-known Synkronus data revision (`current_version`
* from the most recent successful sync). Reflects server-stream alignment
* only — not unsynced local edits. Use with periodic polling or after
* {@link sync} to detect when another device has pushed changes.
*
* @since 1.4.0
* @returns {Promise<number>} Non-negative revision count (0 if never synced)
*/
getCurrentDataRevisionCount(): Promise<number>;
}
/**
* 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.5.0';
/** 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;
}