-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevApi.ts
More file actions
2687 lines (2593 loc) · 114 KB
/
Copy pathdevApi.ts
File metadata and controls
2687 lines (2593 loc) · 114 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 {
Box3,
Box3Helper,
Group,
type Material,
Object3D,
PerspectiveCamera,
Scene,
Vector2,
Vector3
} from 'three'
import type { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import {
clearAircraftRangeCache,
getAircraftAssetCacheSnapshot
} from './aircraftAssets/rangeCache'
import {
clearMsfsBehaviorDocumentCache,
getMsfsBehaviorAssetSnapshot
} from './msfs/behavior'
import {
AircraftRuntime,
SharedMsfsRuntimeHost,
type RuntimeBridgeEvent,
type RuntimeEffectEvent,
type RuntimeHtmlEvent,
type RuntimeKeyEvent,
type RuntimeSoundEvent
} from './msfs/runtime'
import {
mapMsfsLocalVarToCanonicalState,
mapMsfsSimVarToCanonicalState,
} from './msfs/compatibilityBridge'
import type {
CompiledBehaviorSet,
CompiledExpression,
ImportedAircraft,
ImportDiagnostic,
RuntimeState
} from './msfs/types'
import {
getMsfsPackageSourceCacheSnapshot,
refreshMsfsPackageSourceVersions
} from './msfs/packageAssets'
import type { RendererInfo } from './rendering/createAppRenderer'
import { MsfsInteractionAdapter, type InteractionResolution, type MsfsInteractionTarget } from './msfs/interactionAdapter'
import { CockpitInteractionDispatcher, type CanonicalCockpitAction, type CockpitInteractionChannel, type CockpitInteractionOperation, type CockpitRelativeDirection } from './input/cockpitInteraction'
import { CockpitInteractionHistory, CockpitInteractionTrace } from './input/cockpitInteractionHistory'
import { DEFAULT_COCKPIT_INPUT_STORE, effectiveCockpitInputProfile, loadCockpitInputStore, saveCockpitInputStore, updateCockpitInputSettings, type CockpitInputStoreV1 } from './input/cockpitInputProfiles'
import { listCanonicalEngineCommands, type SimCommand, type SimUnit } from './sim/engine'
import type {
CockpitCameraController,
CockpitInteractionPickRegistry,
CockpitPerfDiagnostics,
FpsCounterSnapshot,
LoadedAircraftModel,
VCockpitHtmlGaugeRuntime,
ViewerConfigProfile
} from './main'
declare global {
interface Window {
__DevApi?: ViewerDevApi
}
}
type DevApiResponse<T = unknown> = {
readonly ok: boolean
readonly summary: string
readonly data: T
readonly warnings?: readonly string[]
}
type DevApiInteractionResult<T = unknown> = {
readonly ok: boolean
readonly code: string
readonly message: string
readonly data: T
readonly suggestions: readonly string[]
}
const interactionResult = <T>(ok: boolean, code: string, message: string, data: T, suggestions: readonly string[] = []): DevApiInteractionResult<T> =>
({ ok, code, message, data, suggestions })
const interactionResolutionFailure = (target: string, result: Extract<InteractionResolution, { ok: false }>) =>
interactionResult(false, result.code, result.code === 'TARGET_AMBIGUOUS' ? `Interaction target "${target}" is ambiguous.` : `Interaction target "${target}" was not found.`, { target, candidates: result.candidates }, result.candidates)
function resolveInteractionRequest(
targetName: string,
resolution: InteractionResolution,
busyTargetIds: ReadonlySet<string>,
rejectBusy = true
): { readonly ok: true; readonly target: MsfsInteractionTarget } | { readonly ok: false; readonly result: DevApiInteractionResult } {
if (!resolution.ok) return { ok: false, result: interactionResolutionFailure(targetName, resolution) }
if (rejectBusy && busyTargetIds.has(resolution.target.id)) {
return { ok: false, result: interactionResult(false, 'TARGET_BUSY', `${targetName} is busy.`, { target: resolution.target.id }) }
}
return resolution
}
export const __devApiInteractionTestHooks = { resolveInteractionRequest }
type InteractionSelector = { readonly interaction?: CockpitInteractionChannel; readonly variant?: string }
type InteractionActionOptions = InteractionSelector & { readonly steps?: number }
type DevApiInteractions = {
readonly list: (options?: { readonly filter?: string; readonly limit?: number }) => DevApiInteractionResult
readonly describe: (target: string) => DevApiInteractionResult
readonly active: () => DevApiInteractionResult
readonly history: (options?: { readonly limit?: number }) => DevApiInteractionResult
readonly trace: { readonly snapshot: () => DevApiInteractionResult; readonly enable: (enabled?: boolean) => DevApiInteractionResult }
readonly profiles: {
readonly list: () => DevApiInteractionResult
readonly get: (profileId: string) => DevApiInteractionResult
readonly effective: (profileId?: string, aircraftId?: string) => DevApiInteractionResult
readonly export: () => DevApiInteractionResult
readonly import: (store: CockpitInputStoreV1) => DevApiInteractionResult
}
readonly settings: { readonly get: () => DevApiInteractionResult; readonly set: (settings: Partial<CockpitInputStoreV1['globalSettings']>) => DevApiInteractionResult }
readonly press: (target: string, options?: InteractionSelector) => Promise<DevApiInteractionResult>
readonly hold: (target: string, options?: InteractionSelector) => Promise<DevApiInteractionResult>
readonly release: (target: string, options?: InteractionSelector) => Promise<DevApiInteractionResult>
readonly turn: (target: string, options: InteractionActionOptions & { readonly direction: CockpitRelativeDirection }) => Promise<DevApiInteractionResult>
readonly increase: (target: string, options?: InteractionActionOptions) => Promise<DevApiInteractionResult>
readonly decrease: (target: string, options?: InteractionActionOptions) => Promise<DevApiInteractionResult>
readonly adjust: (target: string, options: InteractionSelector & { readonly delta: number; readonly unit?: string }) => Promise<DevApiInteractionResult>
readonly set: (target: string, options: InteractionSelector & { readonly value: number | boolean | string; readonly unit?: string }) => Promise<DevApiInteractionResult>
readonly on: (target: string, options?: InteractionSelector) => Promise<DevApiInteractionResult>
readonly off: (target: string, options?: InteractionSelector) => Promise<DevApiInteractionResult>
readonly toggle: (target: string, options?: InteractionSelector) => Promise<DevApiInteractionResult>
readonly cancel: (target: string) => DevApiInteractionResult
readonly cancelAll: () => DevApiInteractionResult
readonly dispatch: (target: string, action: CanonicalCockpitAction) => Promise<DevApiInteractionResult>
}
type DevApiStateValue = number | string | boolean
type DevApiCommandPayload = SimCommand['payload']
const DEV_API_STATE_UNITS = new Set<SimUnit>([
'unitless',
'number',
'ratio',
'percent',
'boolean',
'seconds',
'meters',
'feet',
'metersPerSecond',
'knots',
'celsius',
'kelvin',
])
function parseDevApiStateUnit(unit: string | null | undefined): SimUnit | undefined {
if (unit == null || unit.trim() === '') {
return undefined
}
const normalized = unit.trim()
return DEV_API_STATE_UNITS.has(normalized as SimUnit) ? (normalized as SimUnit) : undefined
}
type DevApiWasmModuleImport = {
readonly module: string
readonly name: string
readonly kind: string
}
type DevApiWasmModuleExport = {
readonly name: string
readonly kind: string
}
type DevApiWasmModuleInfo = {
readonly url: string
readonly status: 'resolved-url-only' | 'compiled' | 'fetch-error' | 'too-large' | 'inspect-error'
readonly byteLength: number
readonly imports: readonly DevApiWasmModuleImport[]
readonly exports: readonly DevApiWasmModuleExport[]
readonly error: string | null
readonly inspectedAt: string | null
}
type DevApiListKind =
| 'nodes'
| 'nodeAnimations'
| 'components'
| 'interactions'
| 'gauges'
| 'animations'
| 'animationTriggers'
| 'canonicalVisuals'
| 'materials'
| 'inputEvents'
| 'variables'
| 'state'
| 'commands'
| 'diagnostics'
| 'events'
| 'settings'
| 'camera'
type DevApiDiagnosticsOptions = {
readonly severity?: string
readonly filter?: string
readonly limit?: number
readonly includeGauges?: boolean
}
type DevApiBenchOptions = {
readonly includeEvents?: boolean
}
type StoredBenchRun = {
readonly id: string
readonly kind: string
readonly createdAt: string
readonly localDate: string
readonly localTime: string
readonly commit: unknown
readonly ok: boolean
readonly summary: string
readonly data: unknown
}
type DevApiEventWaitKind = 'key' | 'html' | 'sound' | 'effect' | 'bridge'
type DevApiWaitCondition =
| string
| {
readonly kind?: string
readonly target?: string
readonly var?: string
readonly unit?: string | null
readonly equals?: number
readonly above?: number
readonly below?: number
readonly minimum?: number
readonly captured?: boolean
readonly eventKind?: DevApiEventWaitKind
readonly name?: string
readonly phase?: string
readonly action?: string
readonly direction?: string
readonly handledByBinding?: boolean
readonly sequenceAbove?: number
readonly from?: number
readonly epsilon?: number
}
type DevApiWaitEvaluationState = {
varChangedBaseline?: number
interactionExecutionBaseline?: number
}
type DevApiRuntimeEvent =
| RuntimeKeyEvent
| RuntimeHtmlEvent
| RuntimeSoundEvent
| RuntimeEffectEvent
| RuntimeBridgeEvent
type ViewerDevApi = {
readonly ready: () => Promise<DevApiResponse>
readonly status: () => DevApiResponse
readonly help: () => DevApiResponse
readonly schema: () => DevApiResponse
readonly report: () => DevApiResponse
readonly reset: (options?: { readonly runtime?: boolean; readonly coldAndDark?: boolean }) => DevApiResponse
readonly find: (query: string, options?: { readonly limit?: number }) => DevApiResponse
readonly list: (options?: { readonly kind?: DevApiListKind; readonly filter?: string; readonly limit?: number }) => DevApiResponse
readonly interactions: DevApiInteractions
readonly checkComponent: (target: string) => DevApiResponse
readonly checkMaterial: (target: string, options?: { readonly descendants?: boolean }) => DevApiResponse
readonly checkGauge: (
key?: string,
options?: { readonly screenshot?: boolean; readonly surface?: string; readonly source?: string }
) => DevApiResponse
readonly inspectWasm: (
key?: string,
options?: { readonly maxBytes?: number; readonly surface?: string; readonly source?: string }
) => Promise<DevApiResponse>
readonly checkParam: (names: string | readonly string[]) => DevApiResponse
readonly setParam: (name: string, value: number, unit?: string | null) => DevApiResponse
readonly diagnostics: (options?: DevApiDiagnosticsOptions) => DevApiResponse
readonly readVar: (name: string, unit?: string | null) => DevApiResponse
readonly writeVar: (name: string, value: number, unit?: string | null) => DevApiResponse
readonly readState: (key: string) => DevApiResponse
readonly writeState: (key: string, value: DevApiStateValue, unit?: string | null) => DevApiResponse
readonly dispatchCommand: (type: string, payload?: DevApiCommandPayload) => DevApiResponse
readonly keyEvent: (name: string, args?: readonly number[]) => DevApiResponse
readonly bridgeCall: (name: string, args?: readonly number[]) => DevApiResponse
readonly events: (options?: { readonly kind?: 'key' | 'html' | 'sound' | 'effect' | 'bridge' | 'interaction'; readonly limit?: number }) => DevApiResponse
readonly watch: (
targets: string | readonly string[],
options?: { readonly durationMs?: number; readonly intervalMs?: number; readonly unit?: string | null }
) => Promise<DevApiResponse>
readonly waitFor: (condition: DevApiWaitCondition, timeoutMs?: number) => Promise<DevApiResponse>
readonly perf: () => DevApiResponse
readonly assetCache: {
readonly snapshot: () => DevApiResponse
readonly refreshPackageVersions: () => Promise<DevApiResponse>
readonly clearDdsRanges: () => Promise<DevApiResponse>
}
readonly bench: {
readonly startup: () => DevApiResponse
readonly cockpitLod0: (options?: DevApiBenchOptions) => Promise<DevApiResponse>
readonly all: (options?: DevApiBenchOptions) => Promise<DevApiResponse>
readonly history: (options?: { readonly limit?: number }) => DevApiResponse
readonly clearHistory: () => DevApiResponse
}
readonly screenshot: (options?: { readonly target?: 'viewport' | 'gauge'; readonly key?: string }) => DevApiResponse
readonly visualCheck: (target?: string) => DevApiResponse
readonly highlight: (target: string, options?: { readonly durationMs?: number }) => DevApiResponse
readonly camera: {
readonly enterCockpit: () => Promise<DevApiResponse>
readonly exitCockpit: () => DevApiResponse
readonly getPose: () => DevApiResponse
readonly setPose: (pose: {
readonly position?: readonly number[]
readonly target?: readonly number[]
}) => DevApiResponse
readonly frame: (target: string) => DevApiResponse
}
readonly settings: {
readonly get: () => DevApiResponse
readonly set: (settings: Partial<ViewerConfigProfile>) => Promise<DevApiResponse>
}
}
type ViewerDevApiContext = {
readonly packageRoot: string
readonly packageData: {
readonly packageName: string
readonly manifest?: { readonly packageVersion?: string } | null
readonly diagnostics: readonly ImportDiagnostic[]
}
readonly aircraft: ImportedAircraft
readonly scene: Scene
readonly renderer: RendererInfo['renderer']
readonly camera: PerspectiveCamera
readonly controls: OrbitControls
readonly rendererInfo: RendererInfo
readonly getEffectiveSearchParams: () => URLSearchParams
readonly getCompiledBehaviors: () => CompiledBehaviorSet
readonly getLoadedModel: () => LoadedAircraftModel
readonly getRuntime: () => AircraftRuntime
readonly getRuntimeHost: () => SharedMsfsRuntimeHost
readonly getRuntimeState: () => RuntimeState
readonly getFpsSnapshot: () => FpsCounterSnapshot
readonly getSettingsSnapshot: () => Record<string, unknown>
readonly getCockpitPerfDiagnostics: () => CockpitPerfDiagnostics
readonly cockpitInteractionStats: Record<string, unknown>
readonly getCockpitInteractionPickRegistry: () => CockpitInteractionPickRegistry
readonly getCockpitInteractionAdapter: () => MsfsInteractionAdapter
readonly getCockpitInteractionDispatcher: () => CockpitInteractionDispatcher<MsfsInteractionTarget>
readonly getCockpitCameraController: () => CockpitCameraController
readonly getCockpitBenchmarkState: () => Record<string, unknown>
readonly runCockpitBenchmark: (options?: {
readonly targetInteriorLodIndex?: number
readonly forceCold?: boolean
}) => Promise<unknown>
readonly applySettings: (settings: Partial<ViewerConfigProfile>) => Promise<string | null>
}
function getLoadStageHistory(): readonly Record<string, unknown>[] {
const value = (globalThis as Record<string, unknown>).__msfsLoadStageHistory
return Array.isArray(value)
? value.filter((entry): entry is Record<string, unknown> => (
entry != null && typeof entry === 'object'
))
: []
}
function getStartupBenchmarkData(): Record<string, unknown> {
const loadStageHistory = getLoadStageHistory()
const sceneReadyIndex = loadStageHistory.findIndex(entry => entry.stage === 'scene:ready')
const history = sceneReadyIndex >= 0
? loadStageHistory.slice(0, sceneReadyIndex + 1)
: loadStageHistory
const first = history[0] ?? null
const latest = history.at(-1) ?? null
const currentLoadStage = loadStageHistory.at(-1) ?? null
const firstNowMs = typeof first?.nowMs === 'number' ? first.nowMs : null
const latestNowMs = typeof latest?.nowMs === 'number' ? latest.nowMs : null
const previousByStage = new Map<string, Record<string, unknown>>()
const firstByStage = new Map<string, Record<string, unknown>>()
const lastByStage = new Map<string, Record<string, unknown>>()
const stages = history.map((entry, index) => {
const stage = typeof entry.stage === 'string' ? entry.stage : null
const nowMs = typeof entry.nowMs === 'number' ? entry.nowMs : null
const previous = stage != null ? previousByStage.get(stage) ?? null : null
if (stage != null) {
if (!firstByStage.has(stage)) {
firstByStage.set(stage, entry)
}
previousByStage.set(stage, entry)
lastByStage.set(stage, entry)
}
const previousNowMs = typeof previous?.nowMs === 'number' ? previous.nowMs : null
return {
index,
stage,
aircraftId: typeof entry.aircraftId === 'string' ? entry.aircraftId : null,
packageRoot: typeof entry.packageRoot === 'string' ? entry.packageRoot : null,
timestamp: typeof entry.timestamp === 'number' ? entry.timestamp : null,
elapsedFromFirstMs:
firstNowMs != null && nowMs != null ? Number((nowMs - firstNowMs).toFixed(1)) : null,
elapsedSincePreviousSameStageMs:
previousNowMs != null && nowMs != null ? Number((nowMs - previousNowMs).toFixed(1)) : null
}
})
const elapsedFromFirst = (entry: Record<string, unknown> | null): number | null => {
const nowMs = typeof entry?.nowMs === 'number' ? entry.nowMs : null
return firstNowMs != null && nowMs != null ? Number((nowMs - firstNowMs).toFixed(1)) : null
}
const elapsedBetween = (
start: Record<string, unknown> | null,
end: Record<string, unknown> | null
): number | null => {
const startMs = typeof start?.nowMs === 'number' ? start.nowMs : null
const endMs = typeof end?.nowMs === 'number' ? end.nowMs : null
return startMs != null && endMs != null ? Number((endMs - startMs).toFixed(1)) : null
}
const firstStage = (stage: string): Record<string, unknown> | null => firstByStage.get(stage) ?? null
const lastStage = (stage: string): Record<string, unknown> | null => lastByStage.get(stage) ?? null
const milestoneNames = [
'init:start',
'import:package',
'compile:behaviors',
'renderer:create',
'gltf:load',
'gltf:lod:fetch',
'gltf:lod:json:loaded',
'gltf:lod:parse:start',
'gltf:lod:parse:done',
'gltf:lod:ready',
'gltf:loaded',
'scene:ready'
]
const milestones = milestoneNames.flatMap(stage => {
const entry = firstStage(stage)
return entry == null
? []
: [{
stage,
elapsedFromFirstMs: elapsedFromFirst(entry),
timestamp: typeof entry.timestamp === 'number' ? entry.timestamp : null
}]
})
return {
ready: typeof latest?.stage === 'string' && latest.stage !== 'init:error',
totalElapsedMs:
firstNowMs != null && latestNowMs != null ? Number((latestNowMs - firstNowMs).toFixed(1)) : null,
currentElapsedMs:
firstNowMs != null ? Number((performance.now() - firstNowMs).toFixed(1)) : null,
currentStage: latest,
currentLoadStage,
stageCount: history.length,
totalLoadStageCount: loadStageHistory.length,
milestones,
phases: {
importPackageMs: elapsedBetween(firstStage('init:start'), firstStage('import:package')),
behaviorCompileToRendererCreateMs: elapsedBetween(
firstStage('compile:behaviors'),
firstStage('renderer:create')
),
rendererCreateToGltfLoadMs: elapsedBetween(
firstStage('renderer:create'),
firstStage('gltf:load')
),
gltfLoadToLoadedMs: elapsedBetween(firstStage('gltf:load'), firstStage('gltf:loaded')),
gltfLoadToSceneReadyMs: elapsedBetween(firstStage('gltf:load'), firstStage('scene:ready')),
gltfParseMs: elapsedBetween(firstStage('gltf:lod:parse:start'), firstStage('gltf:lod:parse:done')),
gltfNormalizeAndReadyMs: elapsedBetween(
firstStage('gltf:lod:parse:done'),
lastStage('gltf:lod:ready')
),
sceneFinalizeMs: elapsedBetween(firstStage('gltf:loaded'), firstStage('scene:ready'))
},
stages
}
}
function stripCockpitBenchmarkEvents(result: unknown): unknown {
if (result == null || typeof result !== 'object') {
return result
}
const { events: _events, ...rest } = result as Record<string, unknown>
return rest
}
const DEV_API_BENCH_HISTORY_KEY = 'msfs.devapi.bench.history.v1'
const DEV_API_BENCH_HISTORY_LIMIT = 50
function readBenchHistory(): readonly StoredBenchRun[] {
try {
const parsed = JSON.parse(window.localStorage.getItem(DEV_API_BENCH_HISTORY_KEY) ?? '[]')
return Array.isArray(parsed)
? parsed.filter((entry): entry is StoredBenchRun => (
entry != null &&
typeof entry === 'object' &&
typeof (entry as Record<string, unknown>).id === 'string'
))
: []
} catch {
return []
}
}
function writeBenchHistory(history: readonly StoredBenchRun[]): void {
window.localStorage.setItem(
DEV_API_BENCH_HISTORY_KEY,
JSON.stringify(history.slice(-DEV_API_BENCH_HISTORY_LIMIT))
)
}
function clearBenchHistory(): void {
window.localStorage.removeItem(DEV_API_BENCH_HISTORY_KEY)
}
function createLocalBenchTimestamp(now: Date): {
readonly localDate: string
readonly localTime: string
} {
return {
localDate: now.toLocaleDateString(undefined, {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}),
localTime: now.toLocaleTimeString(undefined, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
})
}
}
async function getDevApiGitMetadata(): Promise<unknown> {
try {
const response = await fetch('/__devapi/git.json', { cache: 'no-store' })
if (!response.ok) {
return {
available: false,
error: `HTTP ${response.status}`
}
}
return await response.json()
} catch (error) {
return {
available: false,
error: error instanceof Error ? error.message : String(error)
}
}
}
function storeBenchRun(run: StoredBenchRun): StoredBenchRun {
const history = [...readBenchHistory(), run].slice(-DEV_API_BENCH_HISTORY_LIMIT)
writeBenchHistory(history)
return run
}
function getDevApiAssetCacheSnapshot(): Record<string, unknown> {
const resources = performance.getEntriesByType('resource') as PerformanceResourceTiming[]
const packageResources = resources.filter(entry => {
try {
const url = new URL(entry.name)
return url.searchParams.has('assetVersion') ||
url.pathname.startsWith('/aircrafts/') ||
url.pathname.startsWith('/vendor/msfs-stock/')
} catch {
return false
}
})
const xmlResources = packageResources.filter(entry => {
try {
return new URL(entry.name).pathname.toLowerCase().endsWith('.xml')
} catch {
return false
}
})
const summarize = (entries: readonly PerformanceResourceTiming[]) => ({
count: entries.length,
transferBytes: entries.reduce((total, entry) => total + entry.transferSize, 0),
encodedBytes: entries.reduce((total, entry) => total + entry.encodedBodySize, 0),
durationMs: entries.reduce((total, entry) => total + entry.duration, 0)
})
return {
packageSources: getMsfsPackageSourceCacheSnapshot(),
behaviorXml: getMsfsBehaviorAssetSnapshot(),
ddsRanges: getAircraftAssetCacheSnapshot(),
resources: {
packageAssets: summarize(packageResources),
xml: summarize(xmlResources)
}
}
}
async function refreshDevApiPackageVersions(): Promise<{
readonly changedRoots: readonly string[]
readonly snapshot: Record<string, unknown>
}> {
const before = new Map(
getMsfsPackageSourceCacheSnapshot().packages.map(source => [source.rootUrl, source.revision])
)
const refreshed = await refreshMsfsPackageSourceVersions()
const changedRoots = refreshed
.filter(source => source.revision == null || before.get(source.rootUrl) !== source.revision)
.map(source => source.rootUrl)
if (changedRoots.length > 0) {
clearMsfsBehaviorDocumentCache()
await clearAircraftRangeCache()
}
return {
changedRoots,
snapshot: getDevApiAssetCacheSnapshot()
}
}
export function installViewerBootDevApi(): void {
const installedAt = performance.now()
const ok = <T>(summary: string, data: T, warnings?: readonly string[]): DevApiResponse<T> => ({
ok: true,
summary,
data,
...(warnings != null && warnings.length > 0 ? { warnings } : {})
})
const fail = <T>(summary: string, data: T, warnings?: readonly string[]): DevApiResponse<T> => ({
ok: false,
summary,
data,
...(warnings != null && warnings.length > 0 ? { warnings } : {})
})
const sleep = (delayMs: number): Promise<void> =>
new Promise(resolve => window.setTimeout(resolve, Math.max(0, delayMs)))
const getLoadStage = (): Record<string, unknown> | null => {
const value = (globalThis as Record<string, unknown>).__msfsLoadStage
return typeof value === 'object' && value != null ? value as Record<string, unknown> : null
}
const getGltfLoadingManagerStats = (): Record<string, unknown> | null => {
const value = (globalThis as Record<string, unknown>).__msfsGltfLoadingManagerStats
return typeof value === 'object' && value != null ? value as Record<string, unknown> : null
}
const loadingData = (): Record<string, unknown> => ({
ready: false,
loadStage: getLoadStage(),
gltfLoadingManager: getGltfLoadingManagerStats(),
elapsedMs: performance.now() - installedAt,
location: window.location.href
})
const unavailable = (method: string): DevApiResponse =>
fail('Viewer is still loading; full DevApi is not ready yet.', {
...loadingData(),
method
}, [
'Use __DevApi.status() or __DevApi.diagnostics() to inspect boot progress, then retry after __DevApi.ready().'
])
let consoleApi: ViewerDevApi
const bootApi: Partial<ViewerDevApi> = {
ready: async () => {
while (window.__DevApi === consoleApi) {
await sleep(250)
}
return window.__DevApi?.ready?.() ?? unavailable('ready')
},
status: () => ok('Viewer is still loading.', loadingData()),
help: () => ok('Boot DevApi is available while the full viewer loads.', {
methods: [
'__DevApi.status()',
'__DevApi.diagnostics()',
'__DevApi.assetCache.snapshot()',
'__DevApi.bench.startup()',
'await __DevApi.bench.all()',
'__DevApi.bench.history()',
'await __DevApi.ready()'
],
note: 'Interaction, camera, gauge, and runtime helpers become available after model loading completes.'
}),
schema: () => ok('Returned boot DevApi schema summary.', {
ready: false,
methods: ['ready', 'status', 'help', 'schema', 'diagnostics', 'report', 'inspectWasm', 'assetCache.snapshot', 'assetCache.refreshPackageVersions', 'assetCache.clearDdsRanges', 'bench.startup', 'bench.all', 'bench.history']
}),
diagnostics: () => ok('Returned boot diagnostics.', {
...loadingData(),
diagnostics: []
}),
report: () => ok('Returned boot report.', {
...loadingData(),
diagnostics: [],
performance: {
fps: null
}
}),
assetCache: {
snapshot: () => ok('Collected package asset cache diagnostics.', getDevApiAssetCacheSnapshot()),
refreshPackageVersions: async () => ok(
'Refreshed package asset versions.',
await refreshDevApiPackageVersions()
),
clearDdsRanges: async () => {
await clearAircraftRangeCache()
return ok('Cleared cached DDS byte ranges.', getDevApiAssetCacheSnapshot())
}
},
bench: {
startup: () => ok('Collected startup benchmark.', getStartupBenchmarkData()),
cockpitLod0: async () => unavailable('bench.cockpitLod0'),
all: async () => unavailable('bench.all'),
history: (options = {}) => {
const limit = Math.max(1, Math.min(DEV_API_BENCH_HISTORY_LIMIT, Math.floor(options.limit ?? DEV_API_BENCH_HISTORY_LIMIT)))
return ok('Collected stored benchmark history.', {
storageKey: DEV_API_BENCH_HISTORY_KEY,
entries: readBenchHistory().slice(-limit)
})
},
clearHistory: () => {
clearBenchHistory()
return ok('Cleared stored benchmark history.', {
storageKey: DEV_API_BENCH_HISTORY_KEY
})
}
},
camera: {
enterCockpit: async () => unavailable('camera.enterCockpit'),
exitCockpit: () => unavailable('camera.exitCockpit'),
getPose: () => unavailable('camera.getPose'),
setPose: () => unavailable('camera.setPose'),
frame: () => unavailable('camera.frame')
},
settings: {
get: () => unavailable('settings.get'),
set: async () => unavailable('settings.set')
},
inspectWasm: async () => unavailable('inspectWasm')
}
const proxy = new Proxy(bootApi, {
get(target, property, receiver) {
if (property in target) {
return Reflect.get(target, property, receiver)
}
if (typeof property === 'string') {
return () => unavailable(property)
}
return undefined
}
}) as ViewerDevApi
consoleApi = wrapDevApiForConsole(proxy, error =>
fail('Boot DevApi call failed.', {
name: error instanceof Error ? error.name : 'Error',
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack ?? null : null
})
)
window.__DevApi = consoleApi
;(globalThis as Record<string, unknown>).__DevApi = consoleApi
}
export function installViewerDevApi(context: ViewerDevApiContext): void {
let highlightGroup: Group | null = null
const ok = <T>(summary: string, data: T, warnings?: readonly string[]): DevApiResponse<T> => ({
ok: true,
summary,
data,
...(warnings != null && warnings.length > 0 ? { warnings } : {})
})
const fail = <T>(summary: string, data: T, warnings?: readonly string[]): DevApiResponse<T> => ({
ok: false,
summary,
data,
...(warnings != null && warnings.length > 0 ? { warnings } : {})
})
const sleep = (delayMs: number): Promise<void> =>
new Promise(resolve => window.setTimeout(resolve, Math.max(0, delayMs)))
const inspectedWasmModules = new Map<string, DevApiWasmModuleInfo>()
const getWasmModuleInfo = (url: string): DevApiWasmModuleInfo =>
inspectedWasmModules.get(url) ?? {
url,
status: 'resolved-url-only',
byteLength: 0,
imports: [],
exports: [],
error: null,
inspectedAt: null
}
const storeWasmModuleInfo = (info: DevApiWasmModuleInfo): DevApiWasmModuleInfo => {
inspectedWasmModules.set(info.url, info)
return info
}
const getLoadStage = (): Record<string, unknown> | null => {
const value = (globalThis as Record<string, unknown>).__msfsLoadStage
return typeof value === 'object' && value != null ? value as Record<string, unknown> : null
}
const getDiagnostics = (): readonly ImportDiagnostic[] => dedupeDiagnostics([
...context.packageData.diagnostics,
...context.getCompiledBehaviors().diagnostics,
...context.getRuntimeState().diagnostics,
...(context.getLoadedModel().interior?.vcockpitBinding?.diagnostics ?? [])
])
const diagnosticCounts = (): Record<string, number> => {
const counts = { error: 0, warning: 0, info: 0, other: 0 }
for (const diagnostic of getDiagnostics()) {
if (diagnostic.severity === 'error') counts.error += 1
else if (diagnostic.severity === 'warning') counts.warning += 1
else if (diagnostic.severity === 'info') counts.info += 1
else counts.other += 1
}
return counts
}
const matchesDiagnosticFilter = (diagnostic: ImportDiagnostic, filter: string): boolean =>
!filter || `${diagnostic.severity} ${diagnostic.code} ${diagnostic.message} ${diagnostic.sourcePath ?? ''}`.toLowerCase().includes(filter)
const collectGaugeDiagnostics = (filter = '', limit = 500): readonly Record<string, unknown>[] => {
const rows: Record<string, unknown>[] = []
for (const gauge of gauges()) {
if (rows.length >= limit) break
const summary = summarizeGauge(gauge)
const scriptErrors = Array.isArray(summary.scriptErrors) ? summary.scriptErrors : []
const assetErrors = Array.isArray(summary.assetErrors) ? summary.assetErrors : []
const resourceErrors = Array.isArray(summary.resourceErrors) ? summary.resourceErrors : []
const bridgeStats = typeof summary.bridgeStats === 'object' && summary.bridgeStats != null
? summary.bridgeStats as Record<string, unknown>
: null
const runtimeErrorCount = typeof bridgeStats?.runtimeErrorCount === 'number' ? bridgeStats.runtimeErrorCount : 0
const unsupportedCalls = Array.isArray(bridgeStats?.unsupportedCalls) ? bridgeStats.unsupportedCalls : []
if (
scriptErrors.length === 0 &&
assetErrors.length === 0 &&
resourceErrors.length === 0 &&
runtimeErrorCount === 0 &&
unsupportedCalls.length === 0
) {
continue
}
const haystack = `${gauge.gaugeKey} ${gauge.surface} ${gauge.source} ${JSON.stringify({
scriptErrors,
assetErrors,
resourceErrors,
runtimeErrorCount,
unsupportedCalls
})}`.toLowerCase()
if (filter && !haystack.includes(filter)) continue
rows.push({
key: gauge.gaugeKey,
surface: gauge.surface,
source: gauge.source,
status: gauge.status,
scriptErrors,
assetErrors,
resourceErrors,
bridge: {
runtimeErrorCount,
unsupportedCalls,
wasmBridge: bridgeStats?.wasmBridge ?? null,
status: bridgeStats?.status ?? null
}
})
}
return rows
}
const collectDiagnosticsReport = (options: DevApiDiagnosticsOptions = {}): Record<string, unknown> => {
const severity = options.severity?.trim()
const filter = options.filter?.trim().toLowerCase() ?? ''
const limit = Math.max(1, Math.min(5_000, Math.floor(options.limit ?? 500)))
const diagnostics = getDiagnostics().filter(diagnostic =>
(severity == null || severity === '' || diagnostic.severity === severity) &&
matchesDiagnosticFilter(diagnostic, filter)
)
const gaugeDiagnostics = options.includeGauges === false ? [] : collectGaugeDiagnostics(filter, limit)
return {
counts: diagnosticCounts(),
filters: {
severity: severity == null || severity === '' ? null : severity,
filter: filter || null,
limit,
includeGauges: options.includeGauges !== false
},
diagnostics: diagnostics.slice(0, limit),
truncatedDiagnostics: Math.max(0, diagnostics.length - limit),
gaugeDiagnostics,
status: statusData()
}
}
const gauges = (): readonly VCockpitHtmlGaugeRuntime[] =>
context.getLoadedModel().interior?.vcockpitBinding?.htmlGaugeRuntimes ?? []
const isCapturableGauge = (runtime: VCockpitHtmlGaugeRuntime): boolean =>
runtime.captured ||
runtime.captureImage != null ||
runtime.staticCaptureImage != null ||
runtime.textureName.toUpperCase() !== 'NO_TEXTURE'
const summarizeGauge = (runtime: VCockpitHtmlGaugeRuntime): Record<string, unknown> => ({
key: runtime.gaugeKey,
surface: runtime.surface,
textureName: runtime.textureName,
source: runtime.source,
resolvedUrl: runtime.resolvedUrl,
status: runtime.status,
captured: runtime.captured,
needsCapture: runtime.needsCapture,
lastRenderStatus: runtime.lastRenderStatus,
lastRenderKind: runtime.lastRenderKind,
lastCaptureError: runtime.lastCaptureError,
captureAttemptCount: runtime.captureAttemptCount,
capturable: isCapturableGauge(runtime),
backendOnly: !isCapturableGauge(runtime),
hasIframe: runtime.iframe != null,
hasCaptureImage: runtime.captureImage != null || runtime.staticCaptureImage != null,
...summarizeGaugeFrame(runtime)
})
const summarizeGaugeFrame = (runtime: VCockpitHtmlGaugeRuntime): Record<string, unknown> => {
const frameDocument = runtime.iframe?.contentDocument
const frameWindow = runtime.iframe?.contentWindow as
| (Window & {
readonly __msfsGaugeDirtyStats?: unknown
readonly __msfsInstrumentRuntimeStats?: unknown
readonly __msfsGaugeBridgeStats?: unknown
readonly __msfsGaugeErrors?: unknown
readonly __msfsGaugeAssetErrors?: unknown
readonly __msfsGaugeResourceErrors?: unknown
})
| null
| undefined
const bridgeStats = frameWindow?.__msfsGaugeBridgeStats ?? null
const wasmModuleUrl = getWasmModuleUrl(runtime)
return {
domNodeCount: frameDocument?.getElementsByTagName('*').length ?? null,
canvasCount: frameDocument?.querySelectorAll('canvas').length ?? null,
svgCount: frameDocument?.querySelectorAll('svg').length ?? null,
dirtyStats: frameWindow?.__msfsGaugeDirtyStats ?? null,
instrumentStats: frameWindow?.__msfsInstrumentRuntimeStats ?? null,
bridgeStats: wasmModuleUrl == null
? bridgeStats
: {
...(typeof bridgeStats === 'object' ? bridgeStats : {}),
wasmModuleInfo: getWasmModuleInfo(wasmModuleUrl)
},
scriptErrors: frameWindow?.__msfsGaugeErrors ?? null,
assetErrors: frameWindow?.__msfsGaugeAssetErrors ?? null,
resourceErrors: frameWindow?.__msfsGaugeResourceErrors ?? null
}
}
const getWasmModuleUrl = (runtime: VCockpitHtmlGaugeRuntime): string | null => {
if (runtime.status !== 'loaded-wasm-bridge') {
return null
}
if (runtime.wasmModuleUrl != null) {
return runtime.wasmModuleUrl
}
if (runtime.resolvedUrl == null) {
return null
}
try {
return new URL(runtime.resolvedUrl).searchParams.get('wasmModuleUrl')
} catch {
return null
}
}
const canvasDataUrl = (canvas: HTMLCanvasElement): string | null => {
try {
return canvas.toDataURL('image/png')
} catch {
return null
}
}
const findObject = (query: string): Object3D | null => {
const needle = query.trim().toLowerCase()
if (!needle) return null
let found: Object3D | null = null
context.getLoadedModel().scene.traverse(object => {
if (found != null) return
if (object.name.toLowerCase() === needle) found = object
})
context.getLoadedModel().scene.traverse(object => {
if (found != null) return
if ((object.name || object.type).toLowerCase().includes(needle)) found = object
})
return found
}
const collectNodes = (filter = '', limit = 500): readonly Record<string, unknown>[] => {
const needle = filter.trim().toLowerCase()
const rows: Record<string, unknown>[] = []
context.getLoadedModel().scene.traverse(object => {
if (rows.length >= limit) return
const label = object.name || object.type
if (needle && !label.toLowerCase().includes(needle)) return
rows.push({
name: object.name || null,
type: object.type,
visible: object.visible,
childCount: object.children.length,
parent: object.parent?.name || object.parent?.type || null,
position: object.position.toArray()