forked from opengeos/GeoLibre
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject.ts
More file actions
1364 lines (1285 loc) · 52.5 KB
/
Copy pathproject.ts
File metadata and controls
1364 lines (1285 loc) · 52.5 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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
DEFAULT_BASEMAP,
DEFAULT_LAYER_STYLE,
DEFAULT_LEGEND_CONFIG,
DEFAULT_PROJECT_PREFERENCES,
DEFAULT_DASHBOARD_COLUMNS,
DEFAULT_MAP_GRID_LAYOUT,
DEFAULT_STORY_MAP,
MAX_DASHBOARD_COLUMNS,
MAX_MAP_GRID_DIM,
MIN_DASHBOARD_COLUMNS,
PROJECT_VERSION,
type DashboardWidget,
type DashboardWidgetAggregation,
type DashboardWidgetType,
type GeoLibreLayer,
type GeoLibreProject,
type IndicatorAggregation,
type LayerGroup,
type LayerStyle,
type LegendConfig,
type LegendCustomEntry,
type LegendCustomItem,
type LegendItemOverride,
type MapGridLayout,
type MapScaleUnit,
type MapViewState,
MAX_PROCESSING_HISTORY,
type ProcessingModel,
type ProcessingRun,
type ProcessingRunKind,
type SecondaryMapView,
type ProcessingModelStep,
type ProjectPluginControlPosition,
type ProjectPluginState,
type ProjectPreferences,
type RuntimeEnvironmentVariable,
type StoryChapter,
type StoryChapterAlignment,
type StoryChapterAnimation,
type StoryInsetPosition,
type StoryLayerOpacityChange,
type StoryMap,
type StorySlideMode,
type StyleLibraryEntry,
} from "./types";
import { DEFAULT_LAYER_GROUP_OPACITY, normalizeGroupContiguity } from "./layer-groups";
import { normalizeStyleLibraryEntries } from "./style-library";
import { getEllipsoid } from "./ellipsoids";
/** Placeholder name a project carries before the user names it. */
export const DEFAULT_PROJECT_NAME = "Untitled Project";
export interface CreateProjectOptions {
basemapStyleUrl?: string;
mapView?: MapViewState;
/** Celestial body the project describes; defaults to Earth when omitted. */
ellipsoidId?: string;
}
export function createDefaultMapView(): MapViewState {
return {
center: [-100, 40],
zoom: 2,
bearing: 0,
pitch: 0,
};
}
export function createEmptyProject(
name = DEFAULT_PROJECT_NAME,
options: CreateProjectOptions = {},
): GeoLibreProject {
return {
version: PROJECT_VERSION,
name,
mapView: options.mapView ?? createDefaultMapView(),
basemapStyleUrl: options.basemapStyleUrl ?? DEFAULT_BASEMAP,
basemapVisible: true,
basemapOpacity: 1,
layers: [],
layerGroups: [],
styles: {},
preferences: options.ellipsoidId
? {
...DEFAULT_PROJECT_PREFERENCES,
map: {
...DEFAULT_PROJECT_PREFERENCES.map,
ellipsoidId: getEllipsoid(options.ellipsoidId).id,
},
}
: DEFAULT_PROJECT_PREFERENCES,
legend: { ...DEFAULT_LEGEND_CONFIG },
metadata: {},
};
}
export function serializeProject(project: GeoLibreProject): string {
return JSON.stringify(project, null, 2);
}
export function parseProject(json: string): GeoLibreProject {
const data = JSON.parse(json) as Partial<GeoLibreProject>;
if (!data.version || !data.name || !data.mapView) {
throw new Error("Invalid GeoLibre project: missing required fields");
}
const layerGroups = normalizeLayerGroups(data.layerGroups);
const validGroupIds = new Set(layerGroups.map((g) => g.id));
const layers = (data.layers ?? [])
.map(normalizeLayer)
.map((layer) =>
layer.groupId && !validGroupIds.has(layer.groupId) ? { ...layer, groupId: undefined } : layer,
);
const selectedLayerId =
data.selectedLayerId === null
? null
: typeof data.selectedLayerId === "string" &&
layers.some((layer) => layer.id === data.selectedLayerId)
? data.selectedLayerId
: undefined;
const basemapStyleUrl = data.basemapStyleUrl ?? DEFAULT_BASEMAP;
const basemapVisible = data.basemapVisible ?? true;
const basemapOpacity = data.basemapOpacity ?? 1;
const { mapLayout, secondaryMapViews } = resolveMapGrid(
normalizeMapLayout(data.mapLayout),
normalizeSecondaryMapViews(data.secondaryMapViews),
{ mapView: data.mapView },
);
const styleLibrary = normalizeStyleLibraryEntries(data.styleLibrary);
return {
version: data.version,
name: data.name,
mapView: data.mapView,
basemapStyleUrl,
basemapVisible,
basemapOpacity,
layers,
...(selectedLayerId !== undefined ? { selectedLayerId } : {}),
...(layerGroups.length > 0 ? { layerGroups } : {}),
styles: data.styles ?? {},
preferences: normalizeProjectPreferences(data.preferences),
plugins: normalizeProjectPlugins(data.plugins) ?? undefined,
legend: normalizeLegendConfig(data.legend),
storymap: normalizeStoryMap(data.storymap) ?? undefined,
models: normalizeModels(data.models) ?? undefined,
processingHistory: normalizeProcessingHistory(data.processingHistory) ?? undefined,
widgets: normalizeWidgets(data.widgets) ?? undefined,
...(data.dashboardColumns === undefined
? {}
: { dashboardColumns: normalizeDashboardColumns(data.dashboardColumns) }),
// Only persist the grid when it is larger than a single pane, so default
// single-map projects serialize byte-identically to before this feature.
...(mapLayout.rows * mapLayout.cols > 1
? {
mapLayout,
secondaryMapViews,
...(normalizeString(data.primaryMapLabel)
? { primaryMapLabel: normalizeString(data.primaryMapLabel) }
: {}),
}
: {}),
...(styleLibrary.length > 0 ? { styleLibrary } : {}),
metadata: data.metadata ?? {},
};
}
/**
* Coerce an untrusted (possibly hand-edited) `layerGroups` array into valid
* {@link LayerGroup} records, dropping entries without a usable id and
* de-duplicating by id. Always returns an array (empty when absent).
*
* @param value Raw `layerGroups` value from the project JSON.
* @returns Normalized, de-duplicated group definitions.
*/
function normalizeLayerGroups(value: unknown): LayerGroup[] {
if (!Array.isArray(value)) return [];
const groups: LayerGroup[] = [];
const seen = new Set<string>();
for (const entry of value) {
if (!entry || typeof entry !== "object") continue;
const candidate = entry as Partial<LayerGroup>;
const id = typeof candidate.id === "string" ? candidate.id.trim() : "";
if (!id || seen.has(id)) continue;
seen.add(id);
const opacity =
typeof candidate.opacity === "number" && Number.isFinite(candidate.opacity)
? Math.min(Math.max(candidate.opacity, 0), 1)
: DEFAULT_LAYER_GROUP_OPACITY;
groups.push({
id,
name: typeof candidate.name === "string" ? candidate.name : id,
collapsed: candidate.collapsed === true,
visible: candidate.visible !== false,
opacity,
});
}
return groups;
}
/**
* Coerce an untrusted (possibly hand-edited) legend config into a valid
* {@link LegendConfig}, dropping malformed entries. Returns undefined when no
* usable config is present so the default is applied downstream.
*/
function normalizeLegendConfig(legend: unknown): LegendConfig | undefined {
if (!legend || typeof legend !== "object") return undefined;
const candidate = legend as Partial<LegendConfig>;
const order = Array.isArray(candidate.order) ? uniqueStrings(candidate.order) : [];
const overrides: Record<string, LegendItemOverride> = {};
if (candidate.overrides && typeof candidate.overrides === "object") {
for (const [key, value] of Object.entries(candidate.overrides)) {
if (!key.trim() || !value || typeof value !== "object") continue;
const override = value as Partial<LegendItemOverride>;
const normalized: LegendItemOverride = {};
// Mirror setLegendItemLabel / renderedLabel: a blank or whitespace-only
// label is treated as "no override", so don't persist it.
if (typeof override.label === "string" && override.label.trim() !== "") {
normalized.label = override.label;
}
// Only the truthy hidden flag is meaningful; `hidden: false` is the
// default, so dropping it keeps round-tripped projects from accumulating
// no-op overrides (matches what the UI mutations store).
if (override.hidden === true) normalized.hidden = true;
if (normalized.label !== undefined || normalized.hidden !== undefined) {
overrides[key.trim()] = normalized;
}
}
}
// Hand-authored entries: keep only well-formed items (string label + color);
// an entry whose items all fail validation is dropped entirely so the panel
// never renders an empty custom section from a hand-edited file.
const customEntries: Record<string, LegendCustomEntry> = {};
if (
candidate.customEntries &&
typeof candidate.customEntries === "object" &&
!Array.isArray(candidate.customEntries)
) {
for (const [key, value] of Object.entries(candidate.customEntries)) {
if (!key.trim() || !value || typeof value !== "object" || Array.isArray(value)) continue;
const entry = value as Partial<LegendCustomEntry>;
if (!Array.isArray(entry.items)) continue;
const items: LegendCustomItem[] = [];
for (const item of entry.items) {
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
const row = item as Partial<LegendCustomItem>;
if (typeof row.label !== "string" || typeof row.color !== "string") continue;
const shape =
row.shape === "circle" || row.shape === "line" || row.shape === "square"
? row.shape
: undefined;
// Proportional symbol size in map pixels; bounded so a hand-edited file
// cannot ask the panel for an absurd swatch.
const size =
typeof row.size === "number" && Number.isFinite(row.size) && row.size > 0
? Math.min(row.size, 1000)
: undefined;
items.push({
label: row.label,
color: row.color,
...(shape ? { shape } : {}),
...(size !== undefined ? { size } : {}),
});
}
if (items.length === 0) continue;
customEntries[key.trim()] = {
...(typeof entry.title === "string" && entry.title.trim() !== ""
? { title: entry.title }
: {}),
items,
};
}
}
const panelPosition =
candidate.panelPosition === "top-left" ||
candidate.panelPosition === "top-right" ||
candidate.panelPosition === "bottom-left" ||
candidate.panelPosition === "bottom-right"
? candidate.panelPosition
: undefined;
// Hand-resized panel dimensions: keep only sane finite values so a
// hand-edited file can't collapse the panel or blow it past any viewport.
const panelSize = (value: unknown): number | undefined =>
typeof value === "number" && Number.isFinite(value) && value >= 120 && value <= 4000
? Math.round(value)
: undefined;
const panelWidth = panelSize(candidate.panelWidth);
const panelHeight = panelSize(candidate.panelHeight);
return {
title: typeof candidate.title === "string" ? candidate.title : DEFAULT_LEGEND_CONFIG.title,
groupByLayer: normalizeBoolean(candidate.groupByLayer, DEFAULT_LEGEND_CONFIG.groupByLayer),
order,
overrides,
...(Object.keys(customEntries).length > 0 ? { customEntries } : {}),
...(candidate.panelVisible === true ? { panelVisible: true } : {}),
...(candidate.panelCollapsed === true ? { panelCollapsed: true } : {}),
...(panelPosition ? { panelPosition } : {}),
...(panelWidth !== undefined ? { panelWidth } : {}),
...(panelHeight !== undefined ? { panelHeight } : {}),
};
}
/**
* Validate and coerce a story map loaded from an untrusted project file.
*
* Returns null when the value carries no chapters so empty story maps stay out
* of the saved project, mirroring how plugins are only persisted when present.
*
* @param storymap Raw value read from the project JSON.
* @returns A normalized story map, or null when there is nothing to keep.
*/
export function normalizeStoryMap(storymap: unknown): StoryMap | null {
if (!storymap || typeof storymap !== "object") return null;
const candidate = storymap as Partial<StoryMap>;
// Drop duplicate chapter ids so updates/removals stay unambiguous and keyed
// rendering stays stable.
const seenChapterIds = new Set<string>();
const chapters = Array.isArray(candidate.chapters)
? candidate.chapters.map(normalizeStoryChapter).filter((chapter): chapter is StoryChapter => {
if (!chapter || seenChapterIds.has(chapter.id)) return false;
seenChapterIds.add(chapter.id);
return true;
})
: [];
const normalized: StoryMap = {
title: normalizeString(candidate.title),
subtitle: normalizeString(candidate.subtitle),
byline: normalizeString(candidate.byline),
footer: normalizeString(candidate.footer),
theme: candidate.theme === "light" ? "light" : "dark",
showMarkers: normalizeBoolean(candidate.showMarkers, false),
markerColor: normalizeString(candidate.markerColor) || DEFAULT_STORY_MAP.markerColor,
inset: normalizeBoolean(candidate.inset, false),
insetPosition: STORY_INSET_POSITIONS.has(candidate.insetPosition as StoryInsetPosition)
? (candidate.insetPosition as StoryInsetPosition)
: DEFAULT_STORY_MAP.insetPosition,
hideChapterNav: normalizeBoolean(candidate.hideChapterNav, false),
startSlide: STORY_SLIDE_MODES.has(candidate.startSlide as StorySlideMode)
? (candidate.startSlide as StorySlideMode)
: DEFAULT_STORY_MAP.startSlide,
endSlide: STORY_SLIDE_MODES.has(candidate.endSlide as StorySlideMode)
? (candidate.endSlide as StorySlideMode)
: DEFAULT_STORY_MAP.endSlide,
chapters,
};
// Keep the story if it has chapters or any author-entered settings; only a
// wholly-default, chapter-less story is dropped (so blank stories stay out of
// saved projects without discarding settings entered before the first chapter).
return storyMapHasContent(normalized) ? normalized : null;
}
/** Whether a story map carries chapters or any non-default setting. */
export function storyMapHasContent(story: StoryMap): boolean {
if (story.chapters.length > 0) return true;
return (
story.title.trim() !== "" ||
story.subtitle.trim() !== "" ||
story.byline.trim() !== "" ||
story.footer.trim() !== "" ||
story.theme !== DEFAULT_STORY_MAP.theme ||
story.showMarkers !== DEFAULT_STORY_MAP.showMarkers ||
story.markerColor !== DEFAULT_STORY_MAP.markerColor ||
story.inset !== DEFAULT_STORY_MAP.inset ||
story.insetPosition !== DEFAULT_STORY_MAP.insetPosition ||
story.hideChapterNav !== DEFAULT_STORY_MAP.hideChapterNav ||
story.startSlide !== DEFAULT_STORY_MAP.startSlide ||
story.endSlide !== DEFAULT_STORY_MAP.endSlide
);
}
const STORY_ALIGNMENTS = new Set<StoryChapterAlignment>(["left", "center", "right", "full"]);
const STORY_ANIMATIONS = new Set<StoryChapterAnimation>(["flyTo", "easeTo", "jumpTo"]);
const STORY_INSET_POSITIONS = new Set<StoryInsetPosition>([
"top-left",
"top-right",
"bottom-left",
"bottom-right",
]);
const STORY_SLIDE_MODES = new Set<StorySlideMode>(["none", "blank", "black", "global", "adjacent"]);
function normalizeStoryChapter(chapter: unknown): StoryChapter | null {
if (!chapter || typeof chapter !== "object") return null;
const candidate = chapter as Partial<StoryChapter>;
const id = normalizeString(candidate.id);
if (!id) return null;
const location = candidate.location;
const center = location?.center;
if (
!Array.isArray(center) ||
center.length !== 2 ||
!center.every((value) => Number.isFinite(value))
) {
return null;
}
return {
id,
title: normalizeString(candidate.title),
description: normalizeString(candidate.description),
image: normalizeString(candidate.image) || undefined,
alignment: STORY_ALIGNMENTS.has(candidate.alignment as StoryChapterAlignment)
? (candidate.alignment as StoryChapterAlignment)
: "left",
hidden: normalizeBoolean(candidate.hidden, false),
location: {
// Clamp to valid lng/lat so a hand-edited file can't make flyTo throw.
center: [
clampCoordinate(Number(center[0]), -180, 180),
clampCoordinate(Number(center[1]), -90, 90),
],
// Clamp to MapLibre's valid ranges so a stored value matches the camera
// that actually lands (bearing wraps to 0-360).
zoom: clamp(normalizeNumber(location?.zoom, 2), 0, 24),
pitch: clamp(normalizeNumber(location?.pitch, 0), 0, 85),
bearing: ((normalizeNumber(location?.bearing, 0) % 360) + 360) % 360,
},
mapAnimation: STORY_ANIMATIONS.has(candidate.mapAnimation as StoryChapterAnimation)
? (candidate.mapAnimation as StoryChapterAnimation)
: "flyTo",
rotateAnimation: normalizeBoolean(candidate.rotateAnimation, false),
onChapterEnter: normalizeOpacityChanges(candidate.onChapterEnter),
onChapterExit: normalizeOpacityChanges(candidate.onChapterExit),
};
}
function normalizeOpacityChanges(value: unknown): StoryLayerOpacityChange[] {
if (!Array.isArray(value)) return [];
return value
.map((entry): StoryLayerOpacityChange | null => {
if (!entry || typeof entry !== "object") return null;
const candidate = entry as Partial<StoryLayerOpacityChange>;
const layerId = normalizeString(candidate.layerId);
if (!layerId) return null;
const id = normalizeString(candidate.id);
return {
...(id ? { id } : {}),
layerId,
opacity: clamp(normalizeNumber(candidate.opacity, 1), 0, 1),
...(Number.isFinite(candidate.duration)
? { duration: Math.max(0, Number(candidate.duration)) }
: {}),
};
})
.filter((entry): entry is StoryLayerOpacityChange => Boolean(entry));
}
function normalizeString(value: unknown): string {
return typeof value === "string" ? value : "";
}
/**
* Coerce an untrusted (possibly hand-edited) `models` array into valid
* {@link ProcessingModel} records. Drops models and steps without a usable id or
* tool id, de-duplicates models by id, and keeps step `parameters` as a plain
* object (the runner validates parameter values per tool at run time). Returns
* `null` when there is nothing worth persisting, so a model-less project stays
* free of the key.
*
* @param value Raw `models` value from the project JSON.
* @returns Normalized models, or `null` when none survive.
*/
export function normalizeModels(value: unknown): ProcessingModel[] | null {
if (!Array.isArray(value)) return null;
const models: ProcessingModel[] = [];
const seen = new Set<string>();
for (const entry of value) {
if (!entry || typeof entry !== "object") continue;
const candidate = entry as Partial<ProcessingModel>;
const id = normalizeString(candidate.id).trim();
if (!id || seen.has(id)) continue;
const steps: ProcessingModelStep[] = [];
const rawSteps = Array.isArray(candidate.steps) ? candidate.steps : [];
const seenStepIds = new Set<string>();
for (const rawStep of rawSteps) {
if (!rawStep || typeof rawStep !== "object") continue;
const step = rawStep as Partial<ProcessingModelStep>;
const stepId = normalizeString(step.id).trim();
const toolId = normalizeString(step.toolId).trim();
if (!stepId || !toolId || seenStepIds.has(stepId)) continue;
seenStepIds.add(stepId);
const inputParam = normalizeString(step.inputParam).trim();
steps.push({
id: stepId,
toolId,
parameters:
step.parameters && typeof step.parameters === "object"
? (step.parameters as Record<string, unknown>)
: {},
...(inputParam ? { inputParam } : {}),
});
}
seen.add(id);
models.push({ id, name: normalizeString(candidate.name), steps });
}
return models.length > 0 ? models : null;
}
const PROCESSING_RUN_KINDS = new Set<ProcessingRunKind>([
"vector",
"statistics",
"network",
"whitebox",
"raster",
"conversion",
"algorithm",
]);
/**
* Coerce an untrusted (possibly hand-edited) `processingHistory` array into
* valid {@link ProcessingRun} records. Drops entries without a usable id, tool
* id, or known kind, de-duplicates by id, keeps `parameters` as a plain object,
* and caps the list at {@link MAX_PROCESSING_HISTORY} (keeping the newest,
* i.e. last, entries). Returns `null` when nothing survives, so a history-less
* project stays free of the key.
*
* @param value Raw `processingHistory` value from the project JSON.
* @returns Normalized runs, or `null` when none survive.
*/
export function normalizeProcessingHistory(value: unknown): ProcessingRun[] | null {
if (!Array.isArray(value)) return null;
// Bound the work for a crafted or corrupted file (shared/collaboration
// projects reach this path too): only the newest entries can survive the
// cap anyway, so ignore all but a generous tail up front.
const source =
value.length > MAX_PROCESSING_HISTORY * 10 ? value.slice(-MAX_PROCESSING_HISTORY * 10) : value;
const runs: ProcessingRun[] = [];
const seen = new Set<string>();
for (const entry of source) {
if (!entry || typeof entry !== "object") continue;
const candidate = entry as Partial<ProcessingRun>;
const id = normalizeString(candidate.id).trim();
const toolId = normalizeString(candidate.toolId).trim();
const kind = candidate.kind;
if (!id || !toolId || seen.has(id)) continue;
if (!kind || !PROCESSING_RUN_KINDS.has(kind)) continue;
seen.add(id);
const inputLayerNames =
candidate.inputLayerNames && typeof candidate.inputLayerNames === "object"
? Object.fromEntries(
Object.entries(candidate.inputLayerNames).filter(
([, name]) => typeof name === "string",
),
)
: undefined;
const outputLayerNames = Array.isArray(candidate.outputLayerNames)
? candidate.outputLayerNames.filter((name): name is string => typeof name === "string")
: undefined;
runs.push({
id,
kind,
toolId,
toolName: normalizeString(candidate.toolName) || toolId,
engine: normalizeString(candidate.engine),
parameters:
candidate.parameters && typeof candidate.parameters === "object"
? (candidate.parameters as Record<string, unknown>)
: {},
...(inputLayerNames && Object.keys(inputLayerNames).length > 0 ? { inputLayerNames } : {}),
...(outputLayerNames?.length ? { outputLayerNames } : {}),
...(normalizeString(candidate.inputPath)
? { inputPath: normalizeString(candidate.inputPath) }
: {}),
...(normalizeString(candidate.outputPath)
? { outputPath: normalizeString(candidate.outputPath) }
: {}),
startedAt: normalizeString(candidate.startedAt),
...(Number.isFinite(candidate.durationMs)
? { durationMs: Math.max(0, Number(candidate.durationMs)) }
: {}),
// Only an explicit "success" earns the green checkmark; a missing or
// corrupted status from hand-edited JSON degrades to "error" rather than
// presenting an indeterminate run as having succeeded.
status: candidate.status === "success" ? "success" : "error",
...(normalizeString(candidate.error) ? { error: normalizeString(candidate.error) } : {}),
});
}
if (runs.length === 0) return null;
return runs.slice(-MAX_PROCESSING_HISTORY);
}
/**
* Coerce an untrusted (possibly hand-edited) camera object into a valid
* {@link MapViewState}, falling back to the default view for missing parts.
*/
export function normalizeMapViewState(value: unknown): MapViewState {
const fallback = createDefaultMapView();
if (!value || typeof value !== "object") return fallback;
const candidate = value as Partial<MapViewState>;
const center = Array.isArray(candidate.center) ? candidate.center : fallback.center;
// Clamp to MapLibre's valid ranges (matching normalizeStoryChapter) so a
// hand-edited project file can't store an out-of-range camera that jumpTo
// would silently clamp or reject, leaving the saved state inconsistent with
// what lands on screen. Bearing wraps into [0, 360).
const view: MapViewState = {
center: [
clampCoordinate(normalizeNumber(center[0], fallback.center[0]), -180, 180),
clampCoordinate(normalizeNumber(center[1], fallback.center[1]), -90, 90),
],
zoom: clamp(normalizeNumber(candidate.zoom, fallback.zoom), 0, 24),
bearing: ((normalizeNumber(candidate.bearing, fallback.bearing) % 360) + 360) % 360,
pitch: clamp(normalizeNumber(candidate.pitch, fallback.pitch), 0, 85),
};
if (
Array.isArray(candidate.bbox) &&
candidate.bbox.length === 4 &&
candidate.bbox.every((n) => Number.isFinite(n))
) {
view.bbox = [
Number(candidate.bbox[0]),
Number(candidate.bbox[1]),
Number(candidate.bbox[2]),
Number(candidate.bbox[3]),
];
}
return view;
}
/**
* Coerce an untrusted `mapLayout` into a valid {@link MapGridLayout}. Returns
* null when absent or effectively single-pane so default projects stay
* byte-identical (the field is only written when the grid is larger than 1x1).
*/
export function normalizeMapLayout(value: unknown): MapGridLayout | null {
if (!value || typeof value !== "object") return null;
const candidate = value as Partial<MapGridLayout>;
const rows = clamp(Math.floor(normalizeNumber(candidate.rows, 1)), 1, MAX_MAP_GRID_DIM);
const cols = clamp(Math.floor(normalizeNumber(candidate.cols, 1)), 1, MAX_MAP_GRID_DIM);
if (rows * cols <= 1) return null;
return {
rows,
cols,
syncView: normalizeBoolean(candidate.syncView, DEFAULT_MAP_GRID_LAYOUT.syncView),
};
}
/**
* Coerce an untrusted `secondaryMapViews` array into valid
* {@link SecondaryMapView} records, dropping entries without a usable id and
* de-duplicating by id. Returns null when none are valid.
*/
export function normalizeSecondaryMapViews(value: unknown): SecondaryMapView[] | null {
if (!Array.isArray(value)) return null;
const views: SecondaryMapView[] = [];
const seen = new Set<string>();
for (const entry of value) {
if (!entry || typeof entry !== "object") continue;
const candidate = entry as Partial<SecondaryMapView>;
const id = normalizeString(candidate.id).trim();
if (!id || seen.has(id)) continue;
seen.add(id);
const label = normalizeString(candidate.label);
// Only the known engine ids survive; an absent/unknown value is omitted so
// the pane defaults to the 2D map (back-compat with pre-globe projects).
const viewKind =
candidate.viewKind === "cesium" || candidate.viewKind === "maplibre"
? candidate.viewKind
: undefined;
views.push({
id,
view: normalizeMapViewState(candidate.view),
...(label ? { label } : {}),
...(viewKind ? { viewKind } : {}),
layerVisibility: normalizeLayerVisibility(candidate.layerVisibility),
});
}
return views.length > 0 ? views : null;
}
/** Coerce an untrusted per-layer visibility map into `Record<string, boolean>`. */
function normalizeLayerVisibility(value: unknown): Record<string, boolean> {
if (!value || typeof value !== "object") return {};
const result: Record<string, boolean> = {};
for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {
if (typeof raw === "boolean") result[key] = raw;
}
return result;
}
/**
* Reconcile a parsed grid layout with its secondary panes so the store invariant
* holds: `secondaryMapViews.length === rows * cols - 1`. Surplus panes are
* dropped; missing panes are filled by cloning the primary map. A null/absent
* layout (or a 1x1 grid) collapses to the single-map default.
*/
export function resolveMapGrid(
layout: MapGridLayout | null,
secondaryViews: SecondaryMapView[] | null,
primary: { mapView: MapViewState },
): { mapLayout: MapGridLayout; secondaryMapViews: SecondaryMapView[] } {
if (!layout) {
return { mapLayout: { ...DEFAULT_MAP_GRID_LAYOUT }, secondaryMapViews: [] };
}
const desired = layout.rows * layout.cols - 1;
let views = secondaryViews ?? [];
if (views.length > desired) {
views = views.slice(0, desired);
} else if (views.length < desired) {
const seen = new Set(views.map((v) => v.id));
const additions: SecondaryMapView[] = [];
for (let i = views.length; i < desired; i++) {
let id = `secondary-${i}`;
// Append a counter (rather than growing the string) so a crafted file
// with colliding ids resolves in O(1) per attempt instead of O(n).
let suffix = 0;
while (seen.has(id)) id = `secondary-${i}-${++suffix}`;
seen.add(id);
additions.push({
id,
view: { ...primary.mapView },
layerVisibility: {},
});
}
views = [...views, ...additions];
}
return { mapLayout: layout, secondaryMapViews: views };
}
/** A 3- or 6-digit hex color, the only widget color format we persist. */
const HEX_COLOR = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
/** Upper bound for a persisted histogram bin count, mirroring the chart
* renderer's clamp (`MAX_HISTOGRAM_BINS` in the desktop app's chart helpers). */
const MAX_PERSISTED_BINS = 50;
// Spelled as a Record so adding a member to DashboardWidgetType fails to
// compile until it is listed here. A plain array accepted a short list
// silently, and a type missing from it makes normalizeWidgets drop every widget
// of that type — which is how selector widgets vanished on save and reload.
const DASHBOARD_WIDGET_TYPES = Object.keys({
histogram: true,
scatter: true,
bar: true,
line: true,
box: true,
pie: true,
indicator: true,
selector: true,
} satisfies Record<DashboardWidgetType, true>) as readonly DashboardWidgetType[];
const DASHBOARD_WIDGET_AGGREGATIONS: readonly DashboardWidgetAggregation[] = [
"count",
"sum",
"mean",
];
const INDICATOR_AGGREGATIONS: readonly IndicatorAggregation[] = [
"count",
"sum",
"mean",
"min",
"max",
"median",
];
/**
* Coerce an untrusted (possibly hand-edited) `widgets` array into valid
* {@link DashboardWidget} records. Drops widgets without a usable id, layer id,
* or recognized chart type, de-duplicates by id, and keeps only the optional
* keys that are present and well-typed (the Dashboard panel falls back to
* sensible defaults for anything missing). Returns `null` when there is nothing
* worth persisting, so a widget-less project stays free of the key.
*
* @param value Raw `widgets` value from the project JSON.
* @returns Normalized widgets, or `null` when none survive.
*/
export function normalizeWidgets(value: unknown): DashboardWidget[] | null {
if (!Array.isArray(value)) return null;
const widgets: DashboardWidget[] = [];
const seen = new Set<string>();
for (const entry of value) {
if (!entry || typeof entry !== "object") continue;
const candidate = entry as Partial<DashboardWidget>;
const id = normalizeString(candidate.id).trim();
const layerId = normalizeString(candidate.layerId).trim();
if (!id || !layerId || seen.has(id)) continue;
const type = candidate.type;
if (!type || !DASHBOARD_WIDGET_TYPES.includes(type)) continue;
seen.add(id);
const widget: DashboardWidget = { id, layerId, type };
const title = normalizeString(candidate.title).trim();
if (title) widget.title = title;
const color = normalizeString(candidate.color).trim();
if (HEX_COLOR.test(color)) widget.color = color;
const field = normalizeString(candidate.field).trim();
if (field) widget.field = field;
const xField = normalizeString(candidate.xField).trim();
if (xField) widget.xField = xField;
const yField = normalizeString(candidate.yField).trim();
if (yField) widget.yField = yField;
if (typeof candidate.bins === "number" && Number.isFinite(candidate.bins)) {
// Persist only a sane positive bin count; the histogram renderer clamps to
// [1, 50], so mirror that here rather than round-tripping 0 or huge values.
const bins = Math.trunc(candidate.bins);
if (bins >= 1) widget.bins = Math.min(MAX_PERSISTED_BINS, bins);
}
const category = normalizeString(candidate.category).trim();
if (category) widget.category = category;
if (
candidate.aggregation &&
DASHBOARD_WIDGET_AGGREGATIONS.includes(candidate.aggregation) &&
// A pie has no "average"; the renderer would silently treat mean as sum,
// so drop it here and let the default (count) stand for hand-edited files.
!(type === "pie" && candidate.aggregation === "mean")
) {
widget.aggregation = candidate.aggregation;
}
const valueField = normalizeString(candidate.valueField).trim();
if (valueField) widget.valueField = valueField;
// Indicator widget fields (issue #1381). Only an indicator reads them, so
// drop them elsewhere rather than round-tripping dead configuration.
if (type === "indicator") {
if (
candidate.indicatorAggregation &&
INDICATOR_AGGREGATIONS.includes(candidate.indicatorAggregation)
) {
widget.indicatorAggregation = candidate.indicatorAggregation;
}
// Prefix/suffix are not trimmed: a leading/trailing space is intentional
// (e.g. " ha" or "$ ").
const prefix = normalizeString(candidate.prefix);
if (prefix) widget.prefix = prefix;
const suffix = normalizeString(candidate.suffix);
if (suffix) widget.suffix = suffix;
}
// Selector widget fields (issue #1381). Only a selector reads the flag, and
// false is the default, so persist it only when it is on.
if (type === "selector" && candidate.multiple === true) {
widget.multiple = true;
}
widgets.push(widget);
}
return widgets.length > 0 ? widgets : null;
}
/**
* Clamp an untrusted dashboard column count into the supported range, falling
* back to the default for a missing or non-finite value.
*
* @param value Raw `dashboardColumns` value from the project JSON.
* @returns An integer column count within [MIN, MAX].
*/
export function normalizeDashboardColumns(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
return DEFAULT_DASHBOARD_COLUMNS;
}
return Math.max(MIN_DASHBOARD_COLUMNS, Math.min(MAX_DASHBOARD_COLUMNS, Math.trunc(value)));
}
function normalizeProjectPreferences(preferences: unknown): ProjectPreferences {
if (!preferences || typeof preferences !== "object") {
return DEFAULT_PROJECT_PREFERENCES;
}
const candidate = preferences as Partial<ProjectPreferences>;
const map = candidate.map ?? {};
// Every MapPreferences field is normalized explicitly below, so the map
// object is not spread in: that would forward unknown keys from a
// hand-edited project file straight into app state.
return {
map: {
...DEFAULT_PROJECT_PREFERENCES.map,
bounds: normalizeBounds((map as Partial<ProjectPreferences["map"]>).bounds),
minZoom: normalizeNumber(
(map as Partial<ProjectPreferences["map"]>).minZoom,
DEFAULT_PROJECT_PREFERENCES.map.minZoom,
),
maxZoom: normalizeNumber(
(map as Partial<ProjectPreferences["map"]>).maxZoom,
DEFAULT_PROJECT_PREFERENCES.map.maxZoom,
),
maxPitch: normalizeNumber(
(map as Partial<ProjectPreferences["map"]>).maxPitch,
DEFAULT_PROJECT_PREFERENCES.map.maxPitch,
),
restrictBounds: Boolean((map as Partial<ProjectPreferences["map"]>).restrictBounds),
renderWorldCopies: normalizeBoolean(
(map as Partial<ProjectPreferences["map"]>).renderWorldCopies,
true,
),
projection:
(map as Partial<ProjectPreferences["map"]>).projection === "mercator"
? "mercator"
: "globe",
// Coerce unknown/missing bodies to Earth so measurements never break.
ellipsoidId: getEllipsoid((map as Partial<ProjectPreferences["map"]>).ellipsoidId).id,
scaleUnit: normalizeScaleUnit((map as Partial<ProjectPreferences["map"]>).scaleUnit),
},
environmentVariables: Array.isArray(candidate.environmentVariables)
? candidate.environmentVariables
.map(normalizeEnvironmentVariable)
.filter((variable): variable is RuntimeEnvironmentVariable => Boolean(variable))
: [],
geocoding: normalizeGeocodingPreferences(candidate.geocoding),
};
}
function normalizeGeocodingPreferences(geocoding: unknown): ProjectPreferences["geocoding"] {
if (!geocoding || typeof geocoding !== "object") {
return { ...DEFAULT_PROJECT_PREFERENCES.geocoding, apiKeys: {} };
}
const candidate = geocoding as Partial<ProjectPreferences["geocoding"]>;
const apiKeys: Record<string, string> = {};
if (candidate.apiKeys && typeof candidate.apiKeys === "object") {
for (const [key, value] of Object.entries(candidate.apiKeys)) {
const normalizedKey = key.trim();
if (normalizedKey && typeof value === "string") {
apiKeys[normalizedKey] = value;
}
}
}
return {
providerId:
typeof candidate.providerId === "string" && candidate.providerId.trim()
? candidate.providerId.trim()
: DEFAULT_PROJECT_PREFERENCES.geocoding.providerId,
apiKeys,
forwardEndpoint:
typeof candidate.forwardEndpoint === "string" && candidate.forwardEndpoint.trim()
? candidate.forwardEndpoint.trim()
: undefined,
reverseEndpoint:
typeof candidate.reverseEndpoint === "string" && candidate.reverseEndpoint.trim()
? candidate.reverseEndpoint.trim()
: undefined,
email:
typeof candidate.email === "string" && candidate.email.trim()
? candidate.email.trim()
: undefined,
};
}
/** Coerce an unknown value to a supported scale unit, defaulting to metric. */
function normalizeScaleUnit(value: unknown): MapScaleUnit {
return value === "imperial" || value === "nautical" ? value : "metric";
}
function normalizeBounds(bounds: unknown): ProjectPreferences["map"]["bounds"] {
if (
Array.isArray(bounds) &&
bounds.length === 4 &&
bounds.every((value) => Number.isFinite(value))
) {
// Clamp to valid lng/lat ranges so the stored bounds match what the map
// controller applies, then keep the ordering check so an empty or
// inverted region falls back to the default instead of being persisted.
const west = clampCoordinate(Number(bounds[0]), -180, 180);
const south = clampCoordinate(Number(bounds[1]), -85, 85);
const east = clampCoordinate(Number(bounds[2]), -180, 180);
const north = clampCoordinate(Number(bounds[3]), -85, 85);
if (west < east && south < north) {
return [west, south, east, north];
}
}
return DEFAULT_PROJECT_PREFERENCES.map.bounds;
}
function normalizeNumber(value: unknown, fallback: number): number {
return Number.isFinite(value) ? Number(value) : fallback;
}
function clamp(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, value));
}
function clampCoordinate(value: number, min: number, max: number): number {
return clamp(value, min, max);
}
function normalizeBoolean(value: unknown, fallback: boolean): boolean {
return typeof value === "boolean" ? value : fallback;
}
const ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
function normalizeEnvironmentVariable(variable: unknown): RuntimeEnvironmentVariable | null {
if (!variable || typeof variable !== "object") return null;
const candidate = variable as Partial<RuntimeEnvironmentVariable>;
const key = typeof candidate.key === "string" ? candidate.key.trim() : "";
if (!key || !ENVIRONMENT_VARIABLE_NAME_PATTERN.test(key)) return null;
return {
key,
value: typeof candidate.value === "string" ? candidate.value : "",
enabled: normalizeBoolean(candidate.enabled, true),
};
}
const PROJECT_PLUGIN_CONTROL_POSITIONS = new Set<ProjectPluginControlPosition>([