Repository navigation
Expand file tree
/
Copy pathformPreviewBridge.ts
More file actions
831 lines (775 loc) · 26 KB
/
Copy pathformPreviewBridge.ts
File metadata and controls
831 lines (775 loc) · 26 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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
/**
* Form preview host bridge for `public/formulus-injection.js` (`FormulusInjectionScript.js`).
*
* ## Message coverage (sync with `FormulusInterface` / injection script)
*
* | Request `type` | Behavior |
* |----------------|----------|
* | `getVersion` | Returns `FORM_PREVIEW_FORMULUS_INTERFACE_VERSION`. |
* | `getAvailableForms` | Lists form types from the active bundle (`listActiveBundleForms`). |
* | `openFormplayer` | With `options.subObservationMode`, defers response and opens nested preview (when host provides hooks). Otherwise Workbench navigates or stubs. |
* | `getObservations` | Local SQLite via `listObservationsPage`. |
* | `getObservationsByQuery` | `query_observations` with structured `filter` AST. |
* | `submitObservation` / `updateObservation` | Finalize dialog (JSON export or DB). |
* | `persistObservation` | Headless create/update via `saveObservation` (no finalize dialog). |
* | `requestCamera` / `requestLocation` / `requestFile` / `requestAudio` / `requestVideo` / `requestQrcode` / `requestBiometric` | **Stub** — no device bridge in preview. |
* | `launchIntent` / `callSubform` | **Stub** — not supported in preview. |
* | `requestConnectivityStatus` / `requestSyncStatus` | **No-op** success (`result` omitted) so callers resolve. |
* | `runLocalModel` | **Stub** — no on-device ML in preview. |
* | `getCurrentUser` | Active profile `username` + `label` as `displayName` (from `get_settings`). |
* | `getThemeMode` | `'system'`. |
* | `getAttachmentUri` | Basename string or `{ filename }` only; workspace lookup → `convertFileSrc` (or `null`). |
* | `getAttachmentsUri` | `file://` for `attachments/synced/` (canonical listing; matches Formulus `getAttachmentsDirectoryFileUrl`). |
* | `getCustomAppUri` | Tauri asset URL for `bundles/active/` or dev mirror parent when developer mode is on. |
* | `getFormSpecsUri` | `getActiveBundleFormsFileBaseUrl()` (`bundles/active/forms` or dev mirror). |
*
* Messages **without** `messageId` (e.g. `formplayerReadyToReceiveInit` from the iframe stub) are ignored at the host.
*
* Unknown `type` values still receive `{ type: <type>_response, messageId, error }` so the iframe never hangs.
*/
import { convertFileSrc } from '@tauri-apps/api/core';
import { dirname, join } from '@tauri-apps/api/path';
import { tauriClient } from './tauriClient';
import type { ObservationRecord } from '../types/domain';
/** Preview-local sequence counters (device id stub + app scope suffix). */
const previewSequenceCounters = new Map<string, number>();
function previewAllocateSequence(
scopeKey: string,
options?: { startAt?: number; peek?: boolean },
): number {
const key = `device:desktop-preview:${scopeKey.trim()}`;
const startAt = options?.startAt ?? 1;
const last = previewSequenceCounters.get(key) ?? startAt - 1;
const next = last + 1;
if (!options?.peek) {
previewSequenceCounters.set(key, next);
}
return next;
}
/** Matches `FORMULUS_INTERFACE_VERSION` in formplayer (`FormulusInterfaceDefinition.ts`). */
export const FORM_PREVIEW_FORMULUS_INTERFACE_VERSION = '1.6.0';
/** Must match `formplayer-host-stub.js` — delivers `*_response` to pending Formulus promises in iframes. */
export const FORMPLAYER_BRIDGE_RESPONSE_CHANNEL =
'ode-formplayer-bridge-response';
/** Prefix for stub `error` strings so logs and issues are easy to grep. */
export const DESKTOP_FORM_PREVIEW_PREFIX = 'ODE Desktop form preview';
/**
* Every `type` sent by `desktop/public/formulus-injection.js` that uses `messageId` + `*_response`.
* Keep in sync when regenerating the injection script from Formulus.
*/
export const FORMULUS_INJECTION_REQUEST_TYPES = [
'getVersion',
'getAvailableForms',
'openFormplayer',
'getObservations',
'getObservationsByQuery',
'submitObservation',
'updateObservation',
'requestCamera',
'requestLocation',
'requestFile',
'launchIntent',
'callSubform',
'requestAudio',
'requestVideo',
'requestQrcode',
'requestBiometric',
'requestConnectivityStatus',
'requestSyncStatus',
'runLocalModel',
'getCurrentUser',
'getThemeMode',
'getAttachmentUri',
'getAttachmentsUri',
'getCustomAppUri',
'getFormSpecsUri',
'allocateSequence',
'persistObservation',
] as const;
export type FinalizeRequest =
| { kind: 'submit'; formType: string; finalData: Record<string, unknown> }
| {
kind: 'update';
observationId: string;
formType: string;
finalData: Record<string, unknown>;
};
/** Payload when formplayer requests a nested sub-observation session (`openFormplayer` + `subObservationMode`). */
export type FormPreviewDeferOpenSubObservationPayload = {
parentIframe: HTMLIFrameElement;
/** Parent formplayer `contentWindow` from the bridge message (`event.source`). */
parentContentWindow: Window | null;
messageId: string;
formType: string;
params: Record<string, unknown>;
savedData: Record<string, unknown>;
skipFinalize?: boolean;
skipDraftSelection?: boolean;
};
export type FormPreviewBridgeContext = {
iframe: HTMLIFrameElement | null;
/**
* Maps `postMessage` event source to the iframe that should receive `*_response`.
* When omitted, replies go to {@link iframe} (legacy single-embed hosts).
*/
resolveReplyIframe?: (eventSource: Window) => HTMLIFrameElement | null;
onFinalize: (
request: FinalizeRequest,
) => Promise<{ result?: string; error?: string }>;
/**
* When set (Workbench custom app), `openFormplayer` navigates to Form preview instead
* of stubbing. Ignored when `options.subObservationMode` and {@link onDeferOpenSubObservation} are used.
*/
onOpenFormplayerNavigate?: (payload: {
formType: string;
params: Record<string, unknown>;
savedData: Record<string, unknown>;
observationId?: string;
}) => void;
/**
* Form preview: defer `openFormplayer_response` until nested finalize/cancel.
* Host must not reply synchronously for this message id.
*/
onDeferOpenSubObservation?: (
payload: FormPreviewDeferOpenSubObservationPayload,
) => void;
/**
* When finalize originates from the nested sub-observation iframe, return the bridge
* reply payload for `submitObservation` / `updateObservation` without showing the finalize dialog,
* and complete the parent's deferred `openFormplayer` promise separately.
*/
tryCompleteNestedSubObservationFinalize?: (
eventSource: Window,
request: FinalizeRequest,
) => Promise<{ result?: string; error?: string } | null>;
};
function resolveBridgeReplyIframe(
eventSource: Window | null | undefined,
ctx: FormPreviewBridgeContext,
): HTMLIFrameElement | null {
const primary = ctx.iframe;
if (eventSource != null && typeof ctx.resolveReplyIframe === 'function') {
const resolved = ctx.resolveReplyIframe(eventSource);
if (resolved) {
return resolved;
}
if (primary?.contentWindow === eventSource) {
return primary;
}
return null;
}
if (
eventSource != null &&
primary?.contentWindow != null &&
primary.contentWindow === eventSource
) {
return primary;
}
return primary;
}
function buildBridgeResponseBody(
requestType: string,
messageId: string,
payload: { result?: unknown; error?: string },
): Record<string, unknown> {
return { type: `${requestType}_response`, messageId, ...payload };
}
export function postFormplayerBridgeReply(
iframe: HTMLIFrameElement | null,
requestType: string,
messageId: string,
payload: { result?: unknown; error?: string },
/** Prefer a window captured on iframe load (srcdoc / WebView2). */
targetWindow?: Window | null,
): void {
const body = buildBridgeResponseBody(requestType, messageId, payload);
const serialized = JSON.stringify(body);
const win = targetWindow ?? iframe?.contentWindow ?? null;
if (win) {
try {
const deliver = (
win as Window & {
__odeFormplayerDeliverBridgeResponse?: (
requestType: string,
messageId: string,
payload: { result?: unknown; error?: string },
) => void;
}
).__odeFormplayerDeliverBridgeResponse;
if (typeof deliver === 'function') {
deliver(requestType, messageId, payload);
}
} catch {
// cross-origin or inaccessible — fall back below
}
try {
win.postMessage(serialized, '*');
} catch {
// ignore — BroadcastChannel may still reach the iframe
}
}
try {
if (typeof BroadcastChannel !== 'undefined') {
const channel = new BroadcastChannel(FORMPLAYER_BRIDGE_RESPONSE_CHANNEL);
channel.postMessage(body);
channel.close();
}
} catch {
// optional fallback
}
}
function stubReason(detail: string): { error: string } {
return {
error: `${DESKTOP_FORM_PREVIEW_PREFIX}: ${detail}`,
};
}
/** Map `file:///…` to a filesystem path suitable for {@link convertFileSrc} (Linux + Windows). */
function fileUrlToLocalPath(fileUrl: string): string {
const url = new URL(fileUrl);
let pathname = decodeURIComponent(url.pathname.replace(/\+/g, ' '));
if (/^\/[A-Za-z]:\//.test(pathname)) {
pathname = pathname.slice(1);
}
return pathname;
}
/** Paths that cannot be loaded inside the desktop WebView (other host / mobile app dirs). */
function isForeignDeviceFileUrl(url: string): boolean {
const u = url.toLowerCase();
return (
u.includes('/data/user/') ||
u.includes('org.opendataensemble.formulus') ||
u.includes('/var/mobile/') ||
u.includes('/application/')
);
}
/** Raw `file://` URLs are blocked for `<img src>` inside the formplayer iframe; use asset protocol. */
function attachmentFileUrlForWebview(raw: string | null): string | null {
if (raw == null) {
return null;
}
if (!raw.startsWith('file://')) {
return raw;
}
if (isForeignDeviceFileUrl(raw)) {
return null;
}
try {
return convertFileSrc(fileUrlToLocalPath(raw));
} catch {
return null;
}
}
async function resolveAttachmentUriForFormPreview(
fileRef: string | { filename?: string },
): Promise<string | null> {
if (typeof fileRef === 'string') {
const raw = await tauriClient.workspaceAttachmentFileUrl(fileRef);
return attachmentFileUrlForWebview(raw);
}
const fname =
typeof fileRef.filename === 'string' ? fileRef.filename.trim() : '';
if (!fname) {
return null;
}
try {
const raw = await tauriClient.workspaceAttachmentFileUrl(fname);
return attachmentFileUrlForWebview(raw);
} catch {
return null;
}
}
export function mapObservationToFormObservation(
r: ObservationRecord,
): Record<string, unknown> {
const payload =
r.payload && typeof r.payload === 'object' && !Array.isArray(r.payload)
? (r.payload as Record<string, unknown>)
: {};
const nestedData = payload.data;
const data =
nestedData && typeof nestedData === 'object' && !Array.isArray(nestedData)
? (nestedData as Record<string, unknown>)
: payload;
const created = r.extras?.createdAt ?? r.lastSavedAt;
const updated = r.updatedAt ?? r.lastSavedAt;
const synced = r.extras?.syncedAt ?? r.updatedAt ?? r.lastSavedAt;
const tags = r.extras?.tags;
return {
observationId: r.id,
createdAt: new Date(created ?? r.lastSavedAt),
updatedAt: new Date(updated ?? r.lastSavedAt),
syncedAt: new Date(synced ?? r.lastSavedAt),
isDraft: false,
deleted: r.deleted,
formType: r.formType ?? '',
formVersion: r.extras?.formVersion ?? '',
data,
...(tags != null && tags.length > 0 ? { tags } : {}),
};
}
export async function handleFormPreviewBridgeMessage(
rawOrEvent: MessageEvent | unknown,
ctx: FormPreviewBridgeContext,
): Promise<void> {
let raw: unknown;
let eventSource: Window | null | undefined;
if (
typeof globalThis.MessageEvent !== 'undefined' &&
rawOrEvent instanceof globalThis.MessageEvent
) {
raw = rawOrEvent.data;
eventSource = rawOrEvent.source as Window | null;
} else {
raw = rawOrEvent;
eventSource = ctx.iframe?.contentWindow ?? undefined;
}
let data: Record<string, unknown>;
try {
data =
typeof raw === 'string'
? (JSON.parse(raw) as Record<string, unknown>)
: (raw as Record<string, unknown>);
} catch {
return;
}
const t = data.type;
if (typeof t !== 'string') {
return;
}
const messageId = data.messageId;
if (typeof messageId !== 'string' || !messageId) {
return;
}
const replyIframe = resolveBridgeReplyIframe(eventSource, ctx);
const reply = (
requestType: string,
payload: { result?: unknown; error?: string },
) => postFormplayerBridgeReply(replyIframe, requestType, messageId, payload);
try {
switch (t) {
case 'getVersion':
reply('getVersion', {
result: FORM_PREVIEW_FORMULUS_INTERFACE_VERSION,
});
return;
case 'allocateSequence': {
const scopeKey =
typeof data.scopeKey === 'string'
? data.scopeKey
: typeof data.payload === 'string'
? data.payload
: '';
// Injection sends options nested under `options`; fall back to flat
// top-level fields for back-compat with older callers.
const opts = (
data.options && typeof data.options === 'object'
? (data.options as Record<string, unknown>)
: data
) as { startAt?: unknown; peek?: unknown };
const startAt =
typeof opts.startAt === 'number' ? opts.startAt : undefined;
const peek = Boolean(opts.peek);
const result = previewAllocateSequence(scopeKey, { startAt, peek });
reply('allocateSequence', { result });
return;
}
case 'getAvailableForms': {
const rows = await tauriClient.listActiveBundleForms();
const result = rows.map(r => ({
formType: r.formType,
name: r.formType,
version: '',
coreFields: [] as string[],
auxiliaryFields: [] as string[],
}));
reply('getAvailableForms', { result });
return;
}
case 'openFormplayer': {
const formType = String(data.formType ?? '');
const params = (data.params ?? {}) as Record<string, unknown>;
const savedData = (data.savedData ?? {}) as Record<string, unknown>;
const options = data.options as
| {
subObservationMode?: boolean;
skipFinalize?: boolean;
skipDraftSelection?: boolean;
observationId?: string | null;
}
| undefined;
const subObservationMode = Boolean(options?.subObservationMode);
const observationId =
typeof options?.observationId === 'string'
? options.observationId.trim()
: '';
if (subObservationMode && ctx.onDeferOpenSubObservation) {
const parentIframe = resolveBridgeReplyIframe(eventSource, ctx);
if (parentIframe) {
ctx.onDeferOpenSubObservation({
parentIframe,
parentContentWindow:
eventSource != null && typeof eventSource === 'object'
? (eventSource as Window)
: null,
messageId,
formType,
params,
savedData,
skipFinalize: options?.skipFinalize,
skipDraftSelection: options?.skipDraftSelection,
});
return;
}
reply(
'openFormplayer',
stubReason(
'Could not identify the parent formplayer iframe for nested sub-observation open.',
),
);
return;
}
if (ctx.onOpenFormplayerNavigate) {
ctx.onOpenFormplayerNavigate({
formType,
params,
savedData,
...(observationId ? { observationId } : {}),
});
reply('openFormplayer', {
result: {
status: 'cancelled',
formType,
message:
'ODE Desktop opened Form preview in the workbench. The Promise resolves immediately; full completion is not wired back to the custom app yet.',
},
});
return;
}
reply(
'openFormplayer',
stubReason(
'openFormplayer is not supported in form preview (you are already inside formplayer).',
),
);
return;
}
case 'getObservations': {
const formType = String(data.formType ?? '');
const includeDeleted = Boolean(data.includeDeleted);
const page = await tauriClient.listObservationsPage(undefined, {
formType,
includeDeleted,
limit: 5000,
offset: 0,
});
reply('getObservations', {
result: page.rows.map(mapObservationToFormObservation),
});
return;
}
case 'getObservationsByQuery': {
const options = (data.options ?? data) as Record<string, unknown>;
const formType = String(options.formType ?? data.formType ?? '');
const includeDeleted = Boolean(
options.includeDeleted ?? data.includeDeleted,
);
const filter = options.filter ?? data.filter;
const limit =
typeof options.limit === 'number' ? options.limit : undefined;
const rows = await tauriClient.queryObservations({
formType,
includeDeleted,
filter,
limit,
});
reply('getObservationsByQuery', {
result: rows.map(mapObservationToFormObservation),
});
return;
}
case 'submitObservation': {
const formType = String(data.formType ?? '');
const finalData = (data.finalData ?? {}) as Record<string, unknown>;
const req: FinalizeRequest = {
kind: 'submit',
formType,
finalData,
};
if (
eventSource != null &&
typeof ctx.tryCompleteNestedSubObservationFinalize === 'function'
) {
const nested = await ctx.tryCompleteNestedSubObservationFinalize(
eventSource,
req,
);
if (nested != null) {
reply('submitObservation', nested);
return;
}
}
const res = await ctx.onFinalize(req);
reply('submitObservation', res);
return;
}
case 'updateObservation': {
const observationId = String(data.observationId ?? '');
const formType = String(data.formType ?? '');
const finalData = (data.finalData ?? {}) as Record<string, unknown>;
const req: FinalizeRequest = {
kind: 'update',
observationId,
formType,
finalData,
};
if (
eventSource != null &&
typeof ctx.tryCompleteNestedSubObservationFinalize === 'function'
) {
const nested = await ctx.tryCompleteNestedSubObservationFinalize(
eventSource,
req,
);
if (nested != null) {
reply('updateObservation', nested);
return;
}
}
const res = await ctx.onFinalize(req);
reply('updateObservation', res);
return;
}
case 'requestCamera':
reply(
'requestCamera',
stubReason('Camera is not available in ODE Desktop form preview.'),
);
return;
case 'requestLocation':
reply(
'requestLocation',
stubReason(
'GPS / location is not available in ODE Desktop form preview.',
),
);
return;
case 'requestFile':
reply(
'requestFile',
stubReason(
'Native file picker is not wired in ODE Desktop form preview.',
),
);
return;
case 'launchIntent':
reply(
'launchIntent',
stubReason(
'launchIntent is not supported in ODE Desktop form preview.',
),
);
return;
case 'callSubform':
reply(
'callSubform',
stubReason(
'callSubform is not supported in ODE Desktop form preview.',
),
);
return;
case 'requestAudio':
reply(
'requestAudio',
stubReason(
'Audio recording is not available in ODE Desktop form preview.',
),
);
return;
case 'requestVideo':
reply(
'requestVideo',
stubReason(
'Video recording is not available in ODE Desktop form preview.',
),
);
return;
case 'requestQrcode':
reply(
'requestQrcode',
stubReason(
'QR scanning is not available in ODE Desktop form preview.',
),
);
return;
case 'requestBiometric':
reply(
'requestBiometric',
stubReason(
'Biometric auth is not available in ODE Desktop form preview.',
),
);
return;
case 'requestConnectivityStatus':
reply('requestConnectivityStatus', {});
return;
case 'requestSyncStatus':
reply('requestSyncStatus', {});
return;
case 'runLocalModel':
reply(
'runLocalModel',
stubReason(
'runLocalModel is not available in ODE Desktop form preview.',
),
);
return;
case 'getCurrentUser': {
try {
const settings = await tauriClient.getSettings();
const active = settings.profiles.find(
p => p.id === settings.activeProfileId,
);
const username = (active?.username ?? '').trim();
const label = (active?.label ?? '').trim();
reply('getCurrentUser', {
result: {
username,
...(label ? { displayName: label } : {}),
},
});
} catch (e) {
reply('getCurrentUser', {
error: e instanceof Error ? e.message : String(e),
});
}
return;
}
case 'getThemeMode':
reply('getThemeMode', { result: 'system' });
return;
case 'getAttachmentUri': {
try {
const ref = data.fileName ?? data.filename;
if (ref == null) {
reply('getAttachmentUri', { result: null });
return;
}
if (typeof ref === 'string' && !ref.trim()) {
reply('getAttachmentUri', { result: null });
return;
}
if (typeof ref === 'object' && ref !== null && !Array.isArray(ref)) {
const o = ref as Record<string, unknown>;
const hasFn =
typeof o.filename === 'string' && o.filename.trim() !== '';
if (!hasFn) {
reply('getAttachmentUri', { result: null });
return;
}
}
const result = await resolveAttachmentUriForFormPreview(ref);
reply('getAttachmentUri', { result });
} catch (e) {
reply('getAttachmentUri', {
error: e instanceof Error ? e.message : String(e),
});
}
return;
}
case 'getAttachmentsUri': {
try {
const url =
await tauriClient.workspaceDirectoryFileUrl('attachments/synced');
reply('getAttachmentsUri', { result: url });
} catch (e) {
reply('getAttachmentsUri', {
error: e instanceof Error ? e.message : String(e),
});
}
return;
}
case 'getCustomAppUri': {
try {
const ws = await tauriClient.getWorkspace();
if (!ws) {
reply('getCustomAppUri', { error: 'No workspace configured.' });
return;
}
const settings = await tauriClient.getSettings();
const active = settings.profiles.find(
p => p.id === settings.activeProfileId,
);
const useDevMirror = Boolean(active?.customAppDeveloperMode);
const bundleSegment = useDevMirror ? 'dev-local' : 'active';
const appDirPath = await join(ws, 'bundles', bundleSegment, 'app');
const bundleBasePath = await dirname(appDirPath);
const u = convertFileSrc(bundleBasePath);
const url = u.endsWith('/') ? u : `${u}/`;
reply('getCustomAppUri', { result: url });
} catch (e) {
reply('getCustomAppUri', {
error: e instanceof Error ? e.message : String(e),
});
}
return;
}
case 'getFormSpecsUri': {
try {
const url = await tauriClient.getActiveBundleFormsFileBaseUrl();
reply('getFormSpecsUri', { result: url });
} catch (e) {
reply('getFormSpecsUri', {
error: e instanceof Error ? e.message : String(e),
});
}
return;
}
case 'persistObservation': {
const input = (data.input ?? data) as {
formType?: string;
finalData?: Record<string, unknown>;
observationId?: string | null;
};
const formType = String(input.formType ?? '').trim();
if (!formType) {
reply('persistObservation', {
error: 'persistObservation: formType is required',
});
return;
}
if (
!input.finalData ||
typeof input.finalData !== 'object' ||
Array.isArray(input.finalData)
) {
reply('persistObservation', {
error: 'persistObservation: finalData object is required',
});
return;
}
const existingId =
typeof input.observationId === 'string'
? input.observationId.trim()
: '';
const id = existingId || crypto.randomUUID();
await tauriClient.saveObservation({
id,
formType,
payload: input.finalData,
});
reply('persistObservation', {
result: { observationId: id, formData: input.finalData },
});
return;
}
default:
reply(t, {
error: `${DESKTOP_FORM_PREVIEW_PREFIX}: unhandled message type "${t}" (regenerate FORMULUS_INJECTION_REQUEST_TYPES or add a case).`,
});
}
} catch (e) {
reply(t, {
error: e instanceof Error ? e.message : String(e),
});
}
}