-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
863 lines (807 loc) · 31.7 KB
/
Copy pathmain.ts
File metadata and controls
863 lines (807 loc) · 31.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
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
import papi, { logger } from '@papi/backend';
import type {
ExecutionActivationContext,
ExecutionToken,
IWebViewProvider,
OpenWebViewOptions,
SavedWebViewDefinition,
WebViewDefinition,
} from '@papi/core';
import type { SegmentationDelta } from 'interlinearizer';
import interlinearizerReact from './interlinearizer.web-view?inline';
import interlinearizerStyles from './interlinearizer.web-view.scss?inline';
import * as projectStorage from './services/projectStorage';
import { isDraftProject, isSegmentationDelta, isTextAnalysis } from './types/type-guards';
// #region WebView provider
/**
* WebView type identifier for the Interlinearizer. Used when registering the provider and when
* opening the WebView from the platform.
*/
const mainWebViewType = 'interlinearizer.mainWebView';
/** Options passed to `papi.webViews.openWebView` when opening the Interlinearizer. */
export interface InterlinearizerOpenOptions extends OpenWebViewOptions {
/** Paratext project ID to load in the Interlinearizer WebView. */
projectId?: string;
}
/** WebView provider that provides the Interlinearizer React WebView when Platform.Bible requests it. */
const mainWebViewProvider: IWebViewProvider = {
/**
* Returns the Interlinearizer WebView definition (React component + styles) for the given saved
* definition. Rejects if the requested webViewType does not match this provider's type.
*
* @param savedWebView - Platform-provided definition (webViewType, etc.).
* @param openWebViewOptions - Options passed by the caller; may include a projectId to link.
* @throws {TypeError} When savedWebView.webViewType is not the Interlinearizer type.
*/
async getWebView(
savedWebView: SavedWebViewDefinition,
openWebViewOptions?: InterlinearizerOpenOptions,
): Promise<WebViewDefinition | undefined> {
if (savedWebView.webViewType !== mainWebViewType) {
throw new TypeError(
`${mainWebViewType} provider received request to provide a ${savedWebView.webViewType} WebView`,
);
}
return {
...savedWebView,
projectId: openWebViewOptions?.projectId ?? savedWebView.projectId,
title: 'Interlinearizer',
content: interlinearizerReact,
styles: interlinearizerStyles,
};
},
};
// #endregion
// #region Module state
/**
* Execution token stored during activation for use in command handlers that call `papi.storage`.
* Set in `activate()` before any command can be invoked.
*/
let executionToken: ExecutionToken;
/**
* Tracks the WebView ID opened for each project so subsequent opens of the same project bring that
* tab to front instead of opening a duplicate. Populated and pruned via `onDidOpenWebView` and
* `onDidCloseWebView` subscriptions registered during activation.
*/
const openWebViewsByProject = new Map<string, string>();
// #endregion
// #region Command handlers
/**
* Opens the Interlinearizer WebView for the given project. If no projectId is provided, shows a
* project picker dialog. Each project gets its own tab; reopening an already-open project brings
* that tab to front.
*
* @returns The WebView ID of the opened (or focused) tab, or `undefined` if the user cancels.
* @throws If `papi.dialogs.selectProject` rejects (e.g. platform error while showing the dialog).
* @throws If `papi.webViews.openWebView` rejects (e.g. the platform cannot open or focus the tab).
*/
async function openInterlinearizer(projectId?: string): Promise<string | undefined> {
const resolvedProjectId =
projectId ??
(await papi.dialogs.selectProject({
title: '%interlinearizer_dialog_open_title%',
prompt: '%interlinearizer_dialog_open_prompt%',
}));
if (!resolvedProjectId) return undefined;
const options: InterlinearizerOpenOptions = {
existingId: openWebViewsByProject.get(resolvedProjectId),
projectId: resolvedProjectId,
};
return papi.webViews.openWebView(mainWebViewType, undefined, options);
}
/**
* Opens the Interlinearizer for the project associated with the given WebView. Called from the
* WebView context menu, which passes the tab's WebView ID as the argument.
*
* @param webViewId - ID of an open WebView whose project to use; if omitted falls back to a picker.
* @returns The WebView ID of the opened (or focused) tab, or `undefined` if the user cancels.
* @throws If `papi.webViews.getOpenWebViewDefinition` rejects.
* @throws If the project picker dialog or the WebView open fails.
*/
async function openInterlinearizerForWebView(webViewId?: string): Promise<string | undefined> {
if (!webViewId) return openInterlinearizer();
const webViewDefinition = await papi.webViews.getOpenWebViewDefinition(webViewId);
return openInterlinearizer(webViewDefinition?.projectId);
}
/**
* Creates a new interlinearizer project for the given source project. Called from the WebView via
* `papi.commands.sendCommand` after the user fills in the create-project modal. Returns the
* persisted project serialized as a JSON string.
*
* @param sourceProjectId - Platform.Bible project ID of the source text to interlinearize.
* @param analysisLanguages - BCP 47 tags for languages used in glosses and annotations (e.g.
* `['en']`). Required and must be non-empty.
* @param targetProjectId - Optional Platform.Bible project ID of the target text for bilateral
* alignment projects. Omit for analysis-only projects.
* @param name - Optional user-facing name for the project.
* @param description - Optional user-facing description for the project.
* @throws If storage fails. The error is logged and an error notification is sent before rethrowing
* so the frontend `catch` block can suppress it without sending a second notification.
*/
async function createInterlinearProject(
sourceProjectId: string,
analysisLanguages: string[],
targetProjectId?: string,
name?: string,
description?: string,
): Promise<string> {
try {
const project = await projectStorage.createProject(
executionToken,
sourceProjectId,
analysisLanguages,
targetProjectId,
name,
description,
);
return JSON.stringify(project);
} catch (e) {
logger.error('Interlinearizer: failed to create project', e);
await papi.notifications
.send({
message: '%interlinearizer_error_create_project_failed%',
severity: 'error',
})
.catch(() => {});
throw e;
}
}
/**
* Deletes an interlinearizer project by UUID. No-ops silently if the project does not exist. Called
* from the WebView via `papi.commands.sendCommand` when the user deletes a project from the
* select-project modal.
*
* @throws {SyntaxError} If the project-IDs index contains invalid JSON.
* @throws {Error} If the stored project-IDs index is not an array of strings (a corrupt index).
* @throws If `papi.storage.readUserData` rejects for a non-ENOENT reason while reading the index,
* if `papi.storage.deleteUserData` rejects for a non-ENOENT reason, or if
* `papi.storage.writeUserData` rejects when updating the index. All storage errors are logged and
* shown as a notification before being re-thrown so the caller can handle failure UX.
*/
async function deleteInterlinearProject(interlinearProjectId: string): Promise<void> {
try {
await projectStorage.deleteProject(executionToken, interlinearProjectId);
} catch (e) {
logger.error('Interlinearizer: failed to delete project', e);
await papi.notifications
.send({
message: '%interlinearizer_error_delete_project_failed%',
severity: 'error',
})
.catch(() => {});
throw e;
}
}
/**
* Updates the metadata of an existing interlinearizer project. Called from the WebView when the
* user saves edits in the project info modal.
*
* @param interlinearProjectId - UUID of the interlinearizer project to update.
* @param name - New user-facing name, or `undefined` to clear it.
* @param description - New user-facing description, or `undefined` to clear it.
* @param analysisLanguages - New BCP 47 analysis language tags. Required and must be non-empty;
* pass the current value to leave it unchanged.
* @param targetProjectId - New target-project ID; omit to clear the target binding.
* @returns The updated project as a JSON string, or `undefined` if no project with the given ID
* exists.
* @throws If storage fails. The error is logged and an error notification is sent before rethrowing
* so the frontend `catch` block can suppress it without sending a second notification.
*/
async function updateProjectMetadata(
interlinearProjectId: string,
name: string | undefined,
description: string | undefined,
analysisLanguages: string[],
targetProjectId?: string,
): Promise<string | undefined> {
try {
const updated = await projectStorage.updateProjectMetadata(
executionToken,
interlinearProjectId,
name,
description,
analysisLanguages,
targetProjectId,
);
return updated ? JSON.stringify(updated) : undefined;
} catch (e) {
logger.error('Interlinearizer: failed to update project metadata', e);
await papi.notifications
.send({
message: '%interlinearizer_error_update_project_failed%',
severity: 'error',
})
.catch(() => {});
throw e;
}
}
/**
* Loads the interlinearizer project with the given ID, including its full `TextAnalysis`. The
* WebView calls this when the active project changes to load the stored analysis into the
* interlinearizer.
*
* @param interlinearProjectId - UUID of the interlinearizer project to fetch.
* @returns JSON-stringified `InterlinearProject`, or `undefined` if no project with that ID exists.
* @throws {SyntaxError} If the project's storage value contains invalid JSON.
* @throws {Error} If the stored record was written by a newer build.
* @throws If `papi.storage.readUserData` rejects for a non-ENOENT reason. The error is logged
* before rethrowing.
*/
async function getInterlinearProject(interlinearProjectId: string): Promise<string | undefined> {
try {
const project = await projectStorage.getProject(executionToken, interlinearProjectId);
return project ? JSON.stringify(project) : undefined;
} catch (e) {
logger.error('Interlinearizer: failed to get project', e);
throw e;
}
}
/**
* Persists an updated `TextAnalysis` for an interlinearizer project. Called from the WebView via
* `papi.commands.sendCommand` after each gloss write so that analysis changes survive tab restores
* and project switches.
*
* @param interlinearProjectId - UUID of the interlinearizer project to update.
* @param analysisJson - JSON-stringified `TextAnalysis` to persist.
* @param segmentationJson - Optional JSON-stringified `SegmentationDelta` to persist, or `"null"`
* to clear stored boundaries. Omit to leave the project's existing boundaries unchanged.
* @returns The saved `InterlinearProject` (carrying the refreshed `updatedAt`) as a JSON string, or
* `undefined` if no project with the given ID exists. Returned so the WebView can refresh its
* cached Modified time without a second read.
* @throws If JSON parsing, validation, or storage fails. The error is logged and an error
* notification is sent before rethrowing so the frontend `catch` block can suppress it without a
* second notification.
*/
async function saveInterlinearAnalysis(
interlinearProjectId: string,
analysisJson: string,
segmentationJson?: string,
): Promise<string | undefined> {
try {
const analysis = JSON.parse(analysisJson);
if (!isTextAnalysis(analysis)) {
throw new TypeError('saveInterlinearAnalysis: analysisJson does not conform to TextAnalysis');
}
// undefined ⇒ leave boundaries unchanged; null ⇒ clear them; an object ⇒ set them.
let segmentation: SegmentationDelta | null | undefined;
if (segmentationJson !== undefined) {
const parsed: unknown = JSON.parse(segmentationJson);
// eslint-disable-next-line no-null/no-null -- JSON.parse('null') yields null, the clear sentinel
if (parsed === null) {
// eslint-disable-next-line no-null/no-null -- explicit "clear boundaries" sentinel from the WebView
segmentation = null;
} else if (isSegmentationDelta(parsed)) {
segmentation = parsed;
} else {
throw new TypeError(
'saveInterlinearAnalysis: segmentationJson does not conform to SegmentationDelta',
);
}
}
const updated = await projectStorage.updateAnalysis(
executionToken,
interlinearProjectId,
analysis,
segmentation,
);
return updated ? JSON.stringify(updated) : undefined;
} catch (e) {
logger.error('Interlinearizer: failed to save analysis', e);
await papi.notifications
.send({
message: '%interlinearizer_error_save_analysis_failed%',
severity: 'error',
})
.catch(() => {});
throw e;
}
}
/**
* Returns the draft working buffer for a source project as a JSON string, creating a fresh empty
* draft when none has been written. The WebView loads this on mount to seed the editor.
*
* @param sourceProjectId - Platform.Bible source project ID whose draft to fetch.
* @throws {SyntaxError} If the draft's storage value contains invalid JSON.
* @throws {Error} If the stored draft was written by a newer build.
* @throws If `papi.storage.readUserData` rejects for a non-ENOENT reason. The error is logged
* before rethrowing.
*/
async function getInterlinearDraft(sourceProjectId: string): Promise<string> {
try {
const draft = await projectStorage.getDraft(executionToken, sourceProjectId);
return JSON.stringify(draft);
} catch (e) {
logger.error('Interlinearizer: failed to get draft', e);
throw e;
}
}
/**
* Persists the draft working buffer for a source project. Called from the WebView after every edit
* (auto-save) and whenever the draft is reset (New), opened from a project, or wiped.
*
* @param sourceProjectId - Platform.Bible source project ID whose draft to write.
* @param draftJson - JSON-stringified `DraftProject` to persist.
* @throws If JSON parsing, validation, or storage fails, or if the stored draft was written by a
* newer build and so must not be overwritten. The error is logged and an error notification is
* sent before rethrowing so the frontend `catch` block can suppress it without a second
* notification.
*/
async function saveInterlinearDraft(sourceProjectId: string, draftJson: string): Promise<void> {
try {
const draft = JSON.parse(draftJson);
if (!isDraftProject(draft)) {
throw new TypeError('saveInterlinearDraft: draftJson does not conform to DraftProject');
}
await projectStorage.saveDraft(executionToken, sourceProjectId, draft);
} catch (e) {
logger.error('Interlinearizer: failed to save draft', e);
await papi.notifications
.send({
message: '%interlinearizer_error_save_draft_failed%',
severity: 'error',
})
.catch(() => {});
throw e;
}
}
/**
* Returns all interlinearizer projects for the given source project as a JSON string. The WebView
* deserializes this to populate its project picker and to decide whether to prompt "create new" or
* "select existing" when the user opens the project menu.
*
* @param sourceProjectId - Platform.Bible project ID of the source text to query.
* @throws {SyntaxError} If the project-IDs index contains invalid JSON. Corrupted individual
* project records are logged and skipped, not thrown.
* @throws {Error} If the stored project-IDs index is not an array of strings (a corrupt index).
* @throws If `papi.storage.readUserData` rejects for a non-ENOENT reason. Callers can use this to
* distinguish a storage outage from a legitimately empty list.
*/
async function getProjectsForSource(sourceProjectId: string): Promise<string> {
try {
const projects = await projectStorage.getProjectsForSource(executionToken, sourceProjectId);
return JSON.stringify(projects);
} catch (e) {
logger.error('Interlinearizer: failed to list projects for source', e);
throw e;
}
}
// #endregion
// #region Lifecycle
/**
* Extension entry point. Registers the Interlinearizer WebView provider, its commands,
* project-setting validators, and WebView lifecycle subscriptions. Called by the platform when the
* extension is loaded. Every registration is added to `context` so the platform can dispose them on
* deactivation.
*/
export async function activate(context: ExecutionActivationContext): Promise<void> {
logger.debug('Interlinearizer extension is activating!');
executionToken = context.executionToken;
// Opportunistically retry deleting any project records orphaned by a failed rollback on a prior
// run (see projectStorage.createProject). Fire-and-forget: a cleanup failure must never block or
// fail activation, and the sweep will run again on the next activation.
projectStorage.sweepPendingCleanup(executionToken).catch((e) => {
logger.error('Interlinearizer: pending-cleanup sweep failed during activation:', e);
});
const mainWebViewProviderRegistration = await papi.webViewProviders.registerWebViewProvider(
mainWebViewType,
mainWebViewProvider,
);
const openForWebViewCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.openForWebView',
openInterlinearizerForWebView,
{
method: {
summary: 'Open the Interlinearizer for the project associated with a WebView',
params: [
{
name: 'webViewId',
required: false,
summary: 'The WebView ID whose project to open; if omitted a picker dialog is shown',
schema: { type: 'string' },
},
],
// `undefined` (returned on cancel) is not a JSON type and cannot appear in a JSON-RPC
// response, so the schema only describes the shape when a value is present.
result: {
name: 'return value',
summary: 'The ID of the opened WebView, if opened; omitted when the user cancels',
schema: { type: 'string' },
},
},
},
);
/** Returns whether the supplied project-setting value is a boolean. */
/* v8 ignore next 3 */
function isBoolean(newValue: unknown): Promise<boolean> {
return Promise.resolve(typeof newValue === 'boolean');
}
const continuousScrollValidatorRegistration = await papi.projectSettings.registerValidator(
'interlinearizer.continuousScroll',
isBoolean,
);
const hideInactiveLinkButtonsValidatorRegistration = await papi.projectSettings.registerValidator(
'interlinearizer.hideInactiveLinkButtons',
isBoolean,
);
const simplifyPhrasesValidatorRegistration = await papi.projectSettings.registerValidator(
'interlinearizer.simplifyPhrases',
isBoolean,
);
const showMorphologyValidatorRegistration = await papi.projectSettings.registerValidator(
'interlinearizer.showMorphology',
isBoolean,
);
const showFreeTranslationValidatorRegistration = await papi.projectSettings.registerValidator(
'interlinearizer.showFreeTranslation',
isBoolean,
);
const showVerseGutterValidatorRegistration = await papi.projectSettings.registerValidator(
'interlinearizer.showVerseGutter',
isBoolean,
);
const createProjectCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.createProject',
createInterlinearProject,
{
method: {
summary: 'Create a new interlinearizer project',
params: [
{
name: 'sourceProjectId',
required: true,
summary: 'Platform.Bible project ID of the source text to interlinearize',
schema: { type: 'string' },
},
{
name: 'analysisLanguages',
required: true,
summary:
'BCP 47 tags for gloss / annotation languages (e.g. ["en"]); must be non-empty',
schema: { type: 'array', items: { type: 'string' } },
},
{
name: 'targetProjectId',
required: false,
summary:
'Optional Platform.Bible project ID of the target text for bilateral alignment projects',
schema: { type: 'string' },
},
{
name: 'name',
required: false,
summary: 'Optional user-facing name for the project',
schema: { type: 'string' },
},
{
name: 'description',
required: false,
summary: 'Optional user-facing description for the project',
schema: { type: 'string' },
},
],
result: {
name: 'return value',
summary:
'JSON-stringified InterlinearProject for the new project; rejects (throws) on storage failure',
schema: { type: 'string' },
},
},
},
);
const getProjectCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.getProject',
getInterlinearProject,
{
method: {
summary: 'Return the interlinearizer project with the given UUID as a JSON string',
params: [
{
name: 'interlinearProjectId',
required: true,
summary: 'UUID of the interlinearizer project to fetch',
schema: { type: 'string' },
},
],
result: {
name: 'return value',
summary: 'JSON-stringified InterlinearProject, or undefined if not found',
schema: { type: 'string' },
},
},
},
);
const saveAnalysisCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.saveAnalysis',
saveInterlinearAnalysis,
{
method: {
summary: 'Persist an updated TextAnalysis for an interlinearizer project',
params: [
{
name: 'interlinearProjectId',
required: true,
summary: 'UUID of the interlinearizer project to update',
schema: { type: 'string' },
},
{
name: 'analysisJson',
required: true,
summary: 'JSON-stringified TextAnalysis to persist',
schema: { type: 'string' },
},
{
name: 'segmentationJson',
required: false,
summary:
'JSON-stringified SegmentationDelta to persist, or "null" to clear stored boundaries; omit to leave them unchanged',
schema: { type: 'string' },
},
],
result: {
name: 'return value',
summary:
'JSON-stringified InterlinearProject with the refreshed updatedAt, or undefined if not found',
schema: { type: 'string' },
},
},
},
);
const getProjectsForSourceCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.getProjectsForSource',
getProjectsForSource,
{
method: {
summary: 'Return all interlinearizer projects for a source project as a JSON string',
params: [
{
name: 'sourceProjectId',
required: true,
summary: 'Platform.Bible project ID of the source text to query',
schema: { type: 'string' },
},
],
result: {
name: 'return value',
summary: 'JSON-stringified InterlinearProject[] for the given source',
schema: { type: 'string' },
},
},
},
);
const getDraftCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.getDraft',
getInterlinearDraft,
{
method: {
summary: 'Return the draft working buffer for a source project as a JSON string',
params: [
{
name: 'sourceProjectId',
required: true,
summary: 'Platform.Bible source project ID whose draft to fetch',
schema: { type: 'string' },
},
],
result: {
name: 'return value',
summary: 'JSON-stringified DraftProject; a fresh empty draft when none exists',
schema: { type: 'string' },
},
},
},
);
const saveDraftCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.saveDraft',
saveInterlinearDraft,
{
method: {
summary: 'Persist the draft working buffer for a source project',
params: [
{
name: 'sourceProjectId',
required: true,
summary: 'Platform.Bible source project ID whose draft to write',
schema: { type: 'string' },
},
{
name: 'draftJson',
required: true,
summary: 'JSON-stringified DraftProject to persist',
schema: { type: 'string' },
},
],
result: { name: 'return value', summary: 'void', schema: { type: 'null' } },
},
},
);
const updateProjectMetadataCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.updateProjectMetadata',
updateProjectMetadata,
{
method: {
summary:
'Update the name, description, and analysis language of an existing interlinearizer project',
params: [
{
name: 'interlinearProjectId',
required: true,
summary: 'UUID of the interlinearizer project to update',
schema: { type: 'string' },
},
{
name: 'name',
required: false,
summary: 'New user-facing name; omit to clear',
schema: { type: 'string' },
},
{
name: 'description',
required: false,
summary: 'New user-facing description; omit to clear',
schema: { type: 'string' },
},
{
name: 'analysisLanguages',
required: true,
summary:
'New BCP 47 analysis language tags; must be non-empty (pass current value to leave unchanged)',
schema: { type: 'array', items: { type: 'string' } },
},
{
name: 'targetProjectId',
required: false,
summary: 'New target-project ID; omit to clear the target binding',
schema: { type: 'string' },
},
],
result: {
name: 'return value',
summary:
'JSON-stringified updated InterlinearProject, or undefined if no project with that ID exists; rejects (throws) on storage failure',
schema: { type: 'string' },
},
},
},
);
const deleteProjectCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.deleteProject',
deleteInterlinearProject,
{
method: {
summary: 'Delete an interlinearizer project by UUID',
params: [
{
name: 'interlinearProjectId',
required: true,
summary: 'UUID of the interlinearizer project to delete',
schema: { type: 'string' },
},
],
result: { name: 'return value', summary: 'void', schema: { type: 'null' } },
},
},
);
const openSelectProjectModalCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.openSelectProjectModal',
// Handled entirely in the WebView; backend registration makes the command known to the platform.
/* v8 ignore next */ async () => {},
{
method: {
summary: 'Open the project-selector modal in the Interlinearizer WebView',
params: [],
result: { name: 'return value', summary: 'void', schema: { type: 'null' } },
},
},
);
const openNewProjectModalCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.openNewProjectModal',
// Handled entirely in the WebView; backend registration makes the command known to the platform.
/* v8 ignore next */ async () => {},
{
method: {
summary: 'Open the create-project modal in the Interlinearizer WebView',
params: [],
result: { name: 'return value', summary: 'void', schema: { type: 'null' } },
},
},
);
const openProjectInfoModalCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.openProjectInfoModal',
// Handled entirely in the WebView; backend registration makes the command known to the platform.
/* v8 ignore next */ async () => {},
{
method: {
summary:
'Open the project-info modal for the active project in the Interlinearizer WebView',
params: [],
result: { name: 'return value', summary: 'void', schema: { type: 'null' } },
},
},
);
const saveCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.save',
// Handled entirely in the WebView; backend registration makes the command known to the platform.
/* v8 ignore next */ async () => {},
{
method: {
summary:
'Save the current draft to the active project (handled in the Interlinearizer WebView)',
params: [],
result: { name: 'return value', summary: 'void', schema: { type: 'null' } },
},
},
);
const openSaveAsModalCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.openSaveAsModal',
// Handled entirely in the WebView; backend registration makes the command known to the platform.
/* v8 ignore next */ async () => {},
{
method: {
summary: 'Open the Save As modal in the Interlinearizer WebView',
params: [],
result: { name: 'return value', summary: 'void', schema: { type: 'null' } },
},
},
);
const wipeCommandRegistration = await papi.commands.registerCommand(
'interlinearizer.wipe',
// Handled entirely in the WebView; backend registration makes the command known to the platform.
/* v8 ignore next */ async () => {},
{
method: {
summary:
"Open the wipe dialog to remove the current book's or the whole draft's analysis (handled in the WebView)",
params: [],
result: { name: 'return value', summary: 'void', schema: { type: 'null' } },
},
},
);
const webViewOpenUnsubscriber = papi.webViews.onDidOpenWebView(({ webView }) => {
if (webView.webViewType !== mainWebViewType || !webView.projectId) return;
openWebViewsByProject.set(webView.projectId, webView.id);
});
const webViewCloseUnsubscriber = papi.webViews.onDidCloseWebView(({ webView }) => {
if (webView.webViewType !== mainWebViewType || !webView.projectId) return;
if (openWebViewsByProject.get(webView.projectId) === webView.id)
openWebViewsByProject.delete(webView.projectId);
});
context.registrations.add(
mainWebViewProviderRegistration,
openForWebViewCommandRegistration,
continuousScrollValidatorRegistration,
hideInactiveLinkButtonsValidatorRegistration,
simplifyPhrasesValidatorRegistration,
showMorphologyValidatorRegistration,
showFreeTranslationValidatorRegistration,
showVerseGutterValidatorRegistration,
createProjectCommandRegistration,
getProjectCommandRegistration,
saveAnalysisCommandRegistration,
getProjectsForSourceCommandRegistration,
getDraftCommandRegistration,
saveDraftCommandRegistration,
updateProjectMetadataCommandRegistration,
deleteProjectCommandRegistration,
openSelectProjectModalCommandRegistration,
openNewProjectModalCommandRegistration,
openProjectInfoModalCommandRegistration,
saveCommandRegistration,
openSaveAsModalCommandRegistration,
wipeCommandRegistration,
webViewOpenUnsubscriber,
webViewCloseUnsubscriber,
);
logger.debug('Interlinearizer extension finished activating!');
}
/**
* Extension teardown. Called by the platform when the extension is unloaded. Registrations added
* during activate are disposed by the platform.
*
* @returns True to indicate successful deactivation; the platform may use this for logging.
*/
export async function deactivate(): Promise<boolean> {
openWebViewsByProject.clear();
logger.debug('Interlinearizer extension is deactivating!');
return true;
}
// #endregion