Welcome to mirror list, hosted at ThFree Co, Russian Federation.

index-no-csp.html « pre « browser « webview « contrib « workbench « vs « src - github.com/microsoft/vscode.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: bdd7ba83949f85dc33f34c32553ed75679d4bc2c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
<!DOCTYPE html>
<html lang="en" style="width: 100%; height: 100%;">

<head>
	<meta charset="UTF-8">

	<!-- Disable pinch zooming -->
	<meta name="viewport"
		content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">

	<meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>

<body style="margin: 0; overflow: hidden; width: 100%; height: 100%" role="document">
	<!-- TODO: Remove additional script tag once Firefox is fixed https://bugzilla.mozilla.org/show_bug.cgi?id=1737882 -->
	<script></script>
	<script async type="module">
		// @ts-check
		/// <reference lib="dom" />

		const isSafari = (
			navigator.vendor && navigator.vendor.indexOf('Apple') > -1 &&
			navigator.userAgent &&
			navigator.userAgent.indexOf('CriOS') === -1 &&
			navigator.userAgent.indexOf('FxiOS') === -1
		);

		const isFirefox = (
			navigator.userAgent &&
			navigator.userAgent.indexOf('Firefox') >= 0
		);

		const searchParams = new URL(location.toString()).searchParams;
		const ID = searchParams.get('id');
		const webviewOrigin = searchParams.get('origin');
		const onElectron = searchParams.get('platform') === 'electron';
		const expectedWorkerVersion = parseInt(searchParams.get('swVersion'));

		/**
		 * Use polling to track focus of main webview and iframes within the webview
		 *
		 * @param {Object} handlers
		 * @param {() => void} handlers.onFocus
		 * @param {() => void} handlers.onBlur
		 */
		const trackFocus = ({ onFocus, onBlur }) => {
			const interval = 250;
			let isFocused = document.hasFocus();
			setInterval(() => {
				const isCurrentlyFocused = document.hasFocus();
				if (isCurrentlyFocused === isFocused) {
					return;
				}
				isFocused = isCurrentlyFocused;
				if (isCurrentlyFocused) {
					onFocus();
				} else {
					onBlur();
				}
			}, interval);
		};

		const getActiveFrame = () => {
			return /** @type {HTMLIFrameElement | undefined} */ (document.getElementById('active-frame'));
		};

		const getPendingFrame = () => {
			return /** @type {HTMLIFrameElement | undefined} */ (document.getElementById('pending-frame'));
		};

		/**
		 * @template T
		 * @param {T | undefined | null} obj
		 * @return {T}
		 */
		function assertIsDefined(obj) {
			if (typeof obj === 'undefined' || obj === null) {
				throw new Error('Found unexpected null');
			}
			return obj;
		}

		const vscodePostMessageFuncName = '__vscode_post_message__';

		const defaultStyles = document.createElement('style');
		defaultStyles.id = '_defaultStyles';
		defaultStyles.textContent = `
			html {
				scrollbar-color: var(--vscode-scrollbarSlider-background) var(--vscode-editor-background);
			}

			body {
				background-color: transparent;
				color: var(--vscode-editor-foreground);
				font-family: var(--vscode-font-family);
				font-weight: var(--vscode-font-weight);
				font-size: var(--vscode-font-size);
				margin: 0;
				padding: 0 20px;
			}

			img, video {
				max-width: 100%;
				max-height: 100%;
			}

			a, a code {
				color: var(--vscode-textLink-foreground);
			}

			a:hover {
				color: var(--vscode-textLink-activeForeground);
			}

			a:focus,
			input:focus,
			select:focus,
			textarea:focus {
				outline: 1px solid -webkit-focus-ring-color;
				outline-offset: -1px;
			}

			code {
				color: var(--vscode-textPreformat-foreground);
			}

			blockquote {
				background: var(--vscode-textBlockQuote-background);
				border-color: var(--vscode-textBlockQuote-border);
			}

			kbd {
				color: var(--vscode-editor-foreground);
				border-radius: 3px;
				vertical-align: middle;
				padding: 1px 3px;

				background-color: hsla(0,0%,50%,.17);
				border: 1px solid rgba(71,71,71,.4);
				border-bottom-color: rgba(88,88,88,.4);
				box-shadow: inset 0 -1px 0 rgba(88,88,88,.4);
			}
			.vscode-light kbd {
				background-color: hsla(0,0%,87%,.5);
				border: 1px solid hsla(0,0%,80%,.7);
				border-bottom-color: hsla(0,0%,73%,.7);
				box-shadow: inset 0 -1px 0 hsla(0,0%,73%,.7);
			}

			::-webkit-scrollbar {
				width: 10px;
				height: 10px;
			}

			::-webkit-scrollbar-corner {
				background-color: var(--vscode-editor-background);
			}

			::-webkit-scrollbar-thumb {
				background-color: var(--vscode-scrollbarSlider-background);
			}
			::-webkit-scrollbar-thumb:hover {
				background-color: var(--vscode-scrollbarSlider-hoverBackground);
			}
			::-webkit-scrollbar-thumb:active {
				background-color: var(--vscode-scrollbarSlider-activeBackground);
			}`;

		/**
		 * @param {boolean} allowMultipleAPIAcquire
		 * @param {*} [state]
		 * @return {string}
		 */
		function getVsCodeApiScript(allowMultipleAPIAcquire, state) {
			const encodedState = state ? encodeURIComponent(state) : undefined;
			return /* js */`
					globalThis.acquireVsCodeApi = (function() {
						const originalPostMessage = window.parent['${vscodePostMessageFuncName}'].bind(window.parent);
						const doPostMessage = (channel, data, transfer) => {
							originalPostMessage(channel, data, transfer);
						};

						let acquired = false;

						let state = ${state ? `JSON.parse(decodeURIComponent("${encodedState}"))` : undefined};

						return () => {
							if (acquired && !${allowMultipleAPIAcquire}) {
								throw new Error('An instance of the VS Code API has already been acquired');
							}
							acquired = true;
							return Object.freeze({
								postMessage: function(message, transfer) {
									doPostMessage('onmessage', { message, transfer }, transfer);
								},
								setState: function(newState) {
									state = newState;
									doPostMessage('do-update-state', JSON.stringify(newState));
									return newState;
								},
								getState: function() {
									return state;
								}
							});
						};
					})();
					delete window.parent;
					delete window.top;
					delete window.frameElement;
				`;
		}

		/** @type {Promise<void>} */
		const workerReady = new Promise((resolve, reject) => {
			if (!areServiceWorkersEnabled()) {
				return reject(new Error('Service Workers are not enabled. Webviews will not work. Try disabling private/incognito mode.'));
			}

			const swPath = `service-worker.js?v=${expectedWorkerVersion}&vscode-resource-base-authority=${searchParams.get('vscode-resource-base-authority')}&remoteAuthority=${searchParams.get('remoteAuthority') ?? ''}`;
			navigator.serviceWorker.register(swPath)
				.then(() => navigator.serviceWorker.ready)
				.then(async registration => {
					/**
					 * @param {MessageEvent} event
					 */
					const versionHandler = async (event) => {
						if (event.data.channel !== 'version') {
							return;
						}

						navigator.serviceWorker.removeEventListener('message', versionHandler);
						if (event.data.version === expectedWorkerVersion) {
							return resolve();
						} else {
							console.log(`Found unexpected service worker version. Found: ${event.data.version}. Expected: ${expectedWorkerVersion}`);
							console.log(`Attempting to reload service worker`);

							// If we have the wrong version, try once (and only once) to unregister and re-register
							// Note that `.update` doesn't seem to work desktop electron at the moment so we use
							// `unregister` and `register` here.
							return registration.unregister()
								.then(() => navigator.serviceWorker.register(swPath))
								.then(() => navigator.serviceWorker.ready)
								.finally(() => { resolve(); });
						}
					};
					navigator.serviceWorker.addEventListener('message', versionHandler);

					const postVersionMessage = (/** @type {ServiceWorker} */ controller) => {
						controller.postMessage({ channel: 'version' });
					};

					// At this point, either the service worker is ready and
					// became our controller, or we need to wait for it.
					// Note that navigator.serviceWorker.controller could be a
					// controller from a previously loaded service worker.
					const currentController = navigator.serviceWorker.controller;
					if (currentController?.scriptURL.endsWith(swPath)) {
						// service worker already loaded & ready to receive messages
						postVersionMessage(currentController);
					} else {
						// either there's no controlling service worker, or it's an old one:
						// wait for it to change before posting the message
						const onControllerChange = () => {
							navigator.serviceWorker.removeEventListener('controllerchange', onControllerChange);
							postVersionMessage(navigator.serviceWorker.controller);
						};
						navigator.serviceWorker.addEventListener('controllerchange', onControllerChange);
					}
				}).catch(error => {
					reject(new Error(`Could not register service workers: ${error}.`));
				});
		});

		/**
		 *  @type {import('../webviewMessages').WebviewHostMessaging}
		 */
		const hostMessaging = new class HostMessaging {

			constructor() {
				this.channel = new MessageChannel();

				/** @type {Map<string, Array<(event: MessageEvent, data: any) => void>>} */
				this.handlers = new Map();

				this.channel.port1.onmessage = (e) => {
					const channel = e.data.channel;
					const handlers = this.handlers.get(channel);
					if (handlers) {
						for (const handler of handlers) {
							handler(e, e.data.args);
						}
					} else {
						console.log('no handler for ', e);
					}
				};
			}

			postMessage(channel, data, transfer) {
				this.channel.port1.postMessage({ channel, data }, transfer);
			}

			onMessage(channel, handler) {
				let handlers = this.handlers.get(channel);
				if (!handlers) {
					handlers = [];
					this.handlers.set(channel, handlers);
				}
				handlers.push(handler);
			}

			async signalReady() {
				const start = (/** @type {string} */ parentOrigin) => {
					window.parent.postMessage({ target: ID, channel: 'webview-ready', data: {} }, parentOrigin, [this.channel.port2]);
				};

				const parentOrigin = searchParams.get('parentOrigin');

				const hostname = location.hostname;

				if (!crypto.subtle) {
					// cannot validate, not running in a secure context
					throw new Error(`'crypto.subtle' is not available so webviews will not work. This is likely because the editor is not running in a secure context (https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).`);
				}

				// Here the `parentOriginHash()` function from `src/vs/workbench/common/webview.ts` is inlined
				// compute a sha-256 composed of `parentOrigin` and `salt` converted to base 32
				let parentOriginHash;
				try {
					const strData = JSON.stringify({ parentOrigin, salt: webviewOrigin });
					const encoder = new TextEncoder();
					const arrData = encoder.encode(strData);
					const hash = await crypto.subtle.digest('sha-256', arrData);
					const hashArray = Array.from(new Uint8Array(hash));
					const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
					// sha256 has 256 bits, so we need at most ceil(lg(2^256-1)/lg(32)) = 52 chars to represent it in base 32
					parentOriginHash = BigInt(`0x${hashHex}`).toString(32).padStart(52, '0');
				} catch (err) {
					throw err instanceof Error ? err : new Error(String(err));
				}

				if (hostname === parentOriginHash || hostname.startsWith(parentOriginHash + '.')) {
					// validation succeeded!
					return start(parentOrigin);
				}

				throw new Error(`Expected '${parentOriginHash}' as hostname or subdomain!`);
			}
		}();

		const unloadMonitor = new class {

			constructor() {
				this.confirmBeforeClose = 'keyboardOnly';
				this.isModifierKeyDown = false;

				hostMessaging.onMessage('set-confirm-before-close', (_e, data) => {
					this.confirmBeforeClose = data;
				});

				hostMessaging.onMessage('content', (_e, data) => {
					this.confirmBeforeClose = data.confirmBeforeClose;
				});

				window.addEventListener('beforeunload', (event) => {
					if (onElectron) {
						return;
					}

					switch (this.confirmBeforeClose) {
						case 'always': {
							event.preventDefault();
							event.returnValue = '';
							return '';
						}
						case 'never': {
							break;
						}
						case 'keyboardOnly':
						default: {
							if (this.isModifierKeyDown) {
								event.preventDefault();
								event.returnValue = '';
								return '';
							}
							break;
						}
					}
				});
			}

			onIframeLoaded(/** @type {HTMLIFrameElement} */ frame) {
				assertIsDefined(frame.contentWindow).addEventListener('keydown', e => {
					this.isModifierKeyDown = e.metaKey || e.ctrlKey || e.altKey;
				});

				assertIsDefined(frame.contentWindow).addEventListener('keyup', () => {
					this.isModifierKeyDown = false;
				});
			}
		};

		// state
		let firstLoad = true;
		/** @type {any} */
		let loadTimeout;
		let styleVersion = 0;

		/** @type {Array<{ readonly message: any, transfer?: ArrayBuffer[] }>} */
		let pendingMessages = [];

		const initData = {
			/** @type {number | undefined} */
			initialScrollProgress: undefined,

			/** @type {{ [key: string]: string } | undefined} */
			styles: undefined,

			/** @type {string | undefined} */
			activeTheme: undefined,

			/** @type {string | undefined} */
			themeId: undefined,

			/** @type {string | undefined} */
			themeLabel: undefined,

			/** @type {boolean} */
			screenReader: false,

			/** @type {boolean} */
			reduceMotion: false,
		};

		hostMessaging.onMessage('did-load-resource', (_event, data) => {
			navigator.serviceWorker.ready.then(registration => {
				assertIsDefined(registration.active).postMessage({ channel: 'did-load-resource', data }, data.data?.buffer ? [data.data.buffer] : []);
			});
		});

		hostMessaging.onMessage('did-load-localhost', (_event, data) => {
			navigator.serviceWorker.ready.then(registration => {
				assertIsDefined(registration.active).postMessage({ channel: 'did-load-localhost', data });
			});
		});

		navigator.serviceWorker.addEventListener('message', event => {
			switch (event.data.channel) {
				case 'load-resource':
				case 'load-localhost':
					hostMessaging.postMessage(event.data.channel, event.data);
					return;
			}
		});
		/**
		 * @param {HTMLDocument?} document
		 * @param {HTMLElement?} body
		 */
		const applyStyles = (document, body) => {
			if (!document) {
				return;
			}

			if (body) {
				body.classList.remove('vscode-light', 'vscode-dark', 'vscode-high-contrast', 'vscode-high-contrast-light', 'vscode-reduce-motion', 'vscode-using-screen-reader');

				if (initData.activeTheme) {
					body.classList.add(initData.activeTheme);
					if (initData.activeTheme === 'vscode-high-contrast-light') {
						// backwards compatibility
						body.classList.add('vscode-high-contrast');
					}
				}

				if (initData.reduceMotion) {
					body.classList.add('vscode-reduce-motion');
				}

				if (initData.screenReader) {
					body.classList.add('vscode-using-screen-reader');
				}

				body.dataset.vscodeThemeKind = initData.activeTheme;
				/** @deprecated data-vscode-theme-name will be removed, use data-vscode-theme-id instead */
				body.dataset.vscodeThemeName = initData.themeLabel || '';
				body.dataset.vscodeThemeId = initData.themeId || '';
			}

			if (initData.styles) {
				const documentStyle = document.documentElement.style;

				// Remove stale properties
				for (let i = documentStyle.length - 1; i >= 0; i--) {
					const property = documentStyle[i];

					// Don't remove properties that the webview might have added separately
					if (property && property.startsWith('--vscode-')) {
						documentStyle.removeProperty(property);
					}
				}

				// Re-add new properties
				for (const [variable, value] of Object.entries(initData.styles)) {
					documentStyle.setProperty(`--${variable}`, value);
				}
			}
		};

		/**
		 * @param {MouseEvent} event
		 */
		const handleInnerClick = (event) => {
			if (!event?.view?.document) {
				return;
			}

			const baseElement = event.view.document.querySelector('base');

			for (const pathElement of event.composedPath()) {
				/** @type {any} */
				const node = pathElement;
				if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) {
					if (node.getAttribute('href') === '#') {
						event.view.scrollTo(0, 0);
					} else if (node.hash && (node.getAttribute('href') === node.hash || (baseElement && node.href === baseElement.href + node.hash))) {
						const fragment = node.hash.slice(1);
						const decodedFragment = decodeURIComponent(fragment);
						const scrollTarget = event.view.document.getElementById(fragment) ?? event.view.document.getElementById(decodedFragment);
						if (scrollTarget) {
							scrollTarget.scrollIntoView();
						} else if (decodedFragment.toLowerCase() === 'top') {
							event.view.scrollTo(0, 0);
						}
					} else {
						hostMessaging.postMessage('did-click-link', { uri: node.href.baseVal || node.href });
					}
					event.preventDefault();
					return;
				}
			}
		};

		/**
		 * @param {MouseEvent} event
		 */
		const handleAuxClick = (event) => {
			// Prevent middle clicks opening a broken link in the browser
			if (!event?.view?.document) {
				return;
			}

			if (event.button === 1) {
				for (const pathElement of event.composedPath()) {
					/** @type {any} */
					const node = pathElement;
					if (node.tagName && node.tagName.toLowerCase() === 'a' && node.href) {
						event.preventDefault();
						return;
					}
				}
			}
		};

		/**
		 * @param {KeyboardEvent} e
		 */
		const handleInnerKeydown = (e) => {
			// If the keypress would trigger a browser event, such as copy or paste,
			// make sure we block the browser from dispatching it. Instead VS Code
			// handles these events and will dispatch a copy/paste back to the webview
			// if needed
			if (isUndoRedo(e) || isPrint(e) || isFindEvent(e) || isSaveEvent(e)) {
				e.preventDefault();
			} else if (isCopyPasteOrCut(e)) {
				if (onElectron) {
					e.preventDefault();
				} else {
					return; // let the browser handle this
				}
			} else if (!onElectron && (isCloseTab(e) || isNewWindow(e))) {
				// Prevent Ctrl+W closing window / Ctrl+N opening new window in PWA.
				// (No effect in a regular browser tab.)
				e.preventDefault();
			}

			hostMessaging.postMessage('did-keydown', {
				key: e.key,
				keyCode: e.keyCode,
				code: e.code,
				shiftKey: e.shiftKey,
				altKey: e.altKey,
				ctrlKey: e.ctrlKey,
				metaKey: e.metaKey,
				repeat: e.repeat
			});
		};
		/**
		 * @param {KeyboardEvent} e
		 */
		const handleInnerUp = (e) => {
			hostMessaging.postMessage('did-keyup', {
				key: e.key,
				keyCode: e.keyCode,
				code: e.code,
				shiftKey: e.shiftKey,
				altKey: e.altKey,
				ctrlKey: e.ctrlKey,
				metaKey: e.metaKey,
				repeat: e.repeat
			});
		};

		/**
		 * @param {KeyboardEvent} e
		 * @return {boolean}
		 */
		function isCopyPasteOrCut(e) {
			const hasMeta = e.ctrlKey || e.metaKey;
			const shiftInsert = e.shiftKey && e.key.toLowerCase() === 'insert';
			return (hasMeta && ['c', 'v', 'x'].includes(e.key.toLowerCase())) || shiftInsert;
		}

		/**
		 * @param {KeyboardEvent} e
		 * @return {boolean}
		 */
		function isUndoRedo(e) {
			const hasMeta = e.ctrlKey || e.metaKey;
			return hasMeta && ['z', 'y'].includes(e.key.toLowerCase());
		}

		/**
		 * @param {KeyboardEvent} e
		 * @return {boolean}
		 */
		function isPrint(e) {
			const hasMeta = e.ctrlKey || e.metaKey;
			return hasMeta && e.key.toLowerCase() === 'p';
		}

		/**
		 * @param {KeyboardEvent} e
		 * @return {boolean}
		 */
		function isFindEvent(e) {
			const hasMeta = e.ctrlKey || e.metaKey;
			return hasMeta && e.key.toLowerCase() === 'f';
		}

		/**
		 * @param {KeyboardEvent} e
		 * @return {boolean}
		 */
		function isSaveEvent(e) {
			const hasMeta = e.ctrlKey || e.metaKey;
			return hasMeta && e.key.toLowerCase() === 's';
		}

		/**
		 * @param {KeyboardEvent} e
		 * @return {boolean}
		 */
		function isCloseTab(e) {
			const hasMeta = e.ctrlKey || e.metaKey;
			return hasMeta && e.key.toLowerCase() === 'w';
		}

		/**
		 * @param {KeyboardEvent} e
		 * @return {boolean}
		 */
		function isNewWindow(e) {
			const hasMeta = e.ctrlKey || e.metaKey;
			return hasMeta && e.key.toLowerCase() === 'n';
		}

		let isHandlingScroll = false;

		/**
		 * @param {WheelEvent} event
		 */
		const handleWheel = (event) => {
			if (isHandlingScroll) {
				return;
			}

			hostMessaging.postMessage('did-scroll-wheel', {
				deltaMode: event.deltaMode,
				deltaX: event.deltaX,
				deltaY: event.deltaY,
				deltaZ: event.deltaZ,
				detail: event.detail,
				type: event.type
			});
		};

		/**
		 * @param {Event} event
		 */
		const handleInnerScroll = (event) => {
			if (isHandlingScroll) {
				return;
			}

			const target = /** @type {HTMLDocument | null} */ (event.target);
			const currentTarget = /** @type {Window | null} */ (event.currentTarget);
			if (!currentTarget || !target?.body) {
				return;
			}

			const progress = currentTarget.scrollY / target.body.clientHeight;
			if (isNaN(progress)) {
				return;
			}

			isHandlingScroll = true;
			window.requestAnimationFrame(() => {
				try {
					hostMessaging.postMessage('did-scroll', { scrollYPercentage: progress });
				} catch (e) {
					// noop
				}
				isHandlingScroll = false;
			});
		};

		function handleInnerDragStartEvent(/** @type {DragEvent} */ e) {
			if (e.defaultPrevented) {
				// Extension code has already handled this event
				return;
			}

			if (!e.dataTransfer || e.shiftKey) {
				return;
			}

			// Only handle drags from outside editor for now
			if (e.dataTransfer.items.length && Array.prototype.every.call(e.dataTransfer.items, item => item.kind === 'file')) {
				hostMessaging.postMessage('drag-start', undefined);
			}
		}

		/**
		 * @param {() => void} callback
		 */
		function onDomReady(callback) {
			if (document.readyState === 'interactive' || document.readyState === 'complete') {
				callback();
			} else {
				document.addEventListener('DOMContentLoaded', callback);
			}
		}

		function areServiceWorkersEnabled() {
			try {
				return !!navigator.serviceWorker;
			} catch (e) {
				return false;
			}
		}

		/**
		 * @typedef {{
		 *     contents: string;
		 *     options: {
		 *         readonly allowScripts: boolean;
		 *         readonly allowForms: boolean;
		 *         readonly allowMultipleAPIAcquire: boolean;
		 *     }
		 *     state: any;
		 *     cspSource: string;
		 * }} ContentUpdateData
		 */

		/**
		 * @param {ContentUpdateData} data
		 * @return {string}
		 */
		function toContentHtml(data) {
			const options = data.options;
			const text = data.contents;
			const newDocument = new DOMParser().parseFromString(text, 'text/html');

			newDocument.querySelectorAll('a').forEach(a => {
				if (!a.title) {
					const href = a.getAttribute('href');
					if (typeof href === 'string') {
						a.title = href;
					}
				}
			});

			// Set default aria role
			if (!newDocument.body.hasAttribute('role')) {
				newDocument.body.setAttribute('role', 'document');
			}

			// Inject default script
			if (options.allowScripts) {
				const defaultScript = newDocument.createElement('script');
				defaultScript.id = '_vscodeApiScript';
				defaultScript.textContent = getVsCodeApiScript(options.allowMultipleAPIAcquire, data.state);
				newDocument.head.prepend(defaultScript);
			}

			// Inject default styles
			newDocument.head.prepend(defaultStyles.cloneNode(true));

			applyStyles(newDocument, newDocument.body);

			// Strip out unsupported http-equiv tags
			for (const metaElement of Array.from(newDocument.querySelectorAll('meta'))) {
				const httpEquiv = metaElement.getAttribute('http-equiv');
				if (httpEquiv && !/^(content-security-policy|default-style|content-type)$/i.test(httpEquiv)) {
					console.warn(`Removing unsupported meta http-equiv: ${httpEquiv}`);
					metaElement.remove();
				}
			}

			// Check for CSP
			const csp = newDocument.querySelector('meta[http-equiv="Content-Security-Policy"]');
			if (!csp) {
				hostMessaging.postMessage('no-csp-found', undefined);
			} else {
				try {
					// Attempt to rewrite CSPs that hardcode old-style resource endpoint
					const cspContent = csp.getAttribute('content');
					if (cspContent) {
						const newCsp = cspContent.replace(/(vscode-webview-resource|vscode-resource):(?=(\s|;|$))/g, data.cspSource);
						csp.setAttribute('content', newCsp);
					}
				} catch (e) {
					console.error(`Could not rewrite csp: ${e}`);
				}
			}

			// set DOCTYPE for newDocument explicitly as DOMParser.parseFromString strips it off
			// and DOCTYPE is needed in the iframe to ensure that the user agent stylesheet is correctly overridden
			return '<!DOCTYPE html>\n' + newDocument.documentElement.outerHTML;
		}

		onDomReady(() => {
			if (!document.body) {
				return;
			}

			hostMessaging.onMessage('styles', (_event, data) => {
				++styleVersion;

				initData.styles = data.styles;
				initData.activeTheme = data.activeTheme;
				initData.themeLabel = data.themeLabel;
				initData.themeId = data.themeId;
				initData.reduceMotion = data.reduceMotion;
				initData.screenReader = data.screenReader;

				const target = getActiveFrame();
				if (!target) {
					return;
				}

				if (target.contentDocument) {
					applyStyles(target.contentDocument, target.contentDocument.body);
				}
			});

			// propagate focus
			hostMessaging.onMessage('focus', () => {
				const activeFrame = getActiveFrame();
				if (!activeFrame || !activeFrame.contentWindow) {
					// Focus the top level webview instead
					window.focus();
					return;
				}

				if (document.activeElement === activeFrame) {
					// We are already focused on the iframe (or one of its children) so no need
					// to refocus.
					return;
				}

				activeFrame.contentWindow.focus();
			});

			// update iframe-contents
			let updateId = 0;
			hostMessaging.onMessage('content', async (_event, /** @type {ContentUpdateData} */ data) => {
				const currentUpdateId = ++updateId;
				try {
					await workerReady;
				} catch (e) {
					console.error(`Webview fatal error: ${e}`);
					hostMessaging.postMessage('fatal-error', { message: e + '' });
					return;
				}

				if (currentUpdateId !== updateId) {
					return;
				}

				const options = data.options;
				const newDocument = toContentHtml(data);

				const initialStyleVersion = styleVersion;

				const frame = getActiveFrame();
				const wasFirstLoad = firstLoad;
				// keep current scrollY around and use later
				/** @type {(body: HTMLElement, window: Window) => void} */
				let setInitialScrollPosition;
				if (firstLoad) {
					firstLoad = false;
					setInitialScrollPosition = (body, window) => {
						if (typeof initData.initialScrollProgress === 'number' && !isNaN(initData.initialScrollProgress)) {
							if (window.scrollY === 0) {
								window.scroll(0, body.clientHeight * initData.initialScrollProgress);
							}
						}
					};
				} else {
					const scrollY = frame && frame.contentDocument && frame.contentDocument.body ? assertIsDefined(frame.contentWindow).scrollY : 0;
					setInitialScrollPosition = (body, window) => {
						if (window.scrollY === 0) {
							window.scroll(0, scrollY);
						}
					};
				}

				// Clean up old pending frames and set current one as new one
				const previousPendingFrame = getPendingFrame();
				if (previousPendingFrame) {
					previousPendingFrame.setAttribute('id', '');
					document.body.removeChild(previousPendingFrame);
				}
				if (!wasFirstLoad) {
					pendingMessages = [];
				}

				const newFrame = document.createElement('iframe');
				newFrame.setAttribute('id', 'pending-frame');
				newFrame.setAttribute('frameborder', '0');

				const sandboxRules = new Set(['allow-same-origin', 'allow-pointer-lock']);
				if (options.allowScripts) {
					sandboxRules.add('allow-scripts');
					sandboxRules.add('allow-downloads');
				}
				if (options.allowForms) {
					sandboxRules.add('allow-forms');
				}
				newFrame.setAttribute('sandbox', Array.from(sandboxRules).join(' '));

				const allowRules = ['cross-origin-isolated;', 'autoplay'];
				if (!isFirefox && options.allowScripts) {
					allowRules.push('clipboard-read;', 'clipboard-write;');
				}
				newFrame.setAttribute('allow', allowRules.join(' '));
				// We should just be able to use srcdoc, but I wasn't
				// seeing the service worker applying properly.
				// Fake load an empty on the correct origin and then write real html
				// into it to get around this.
				const fakeUrlParams = new URLSearchParams({ id: ID });
				if (globalThis.crossOriginIsolated) {
					fakeUrlParams.set('vscode-coi', '3'); /*COOP+COEP*/
				}
				newFrame.src = `./fake.html?${fakeUrlParams.toString()}`;

				newFrame.style.cssText = 'display: block; margin: 0; overflow: hidden; position: absolute; width: 100%; height: 100%; visibility: hidden';
				document.body.appendChild(newFrame);

				/**
				 * @param {Document} contentDocument
				 */
				function onFrameLoaded(contentDocument) {
					// Workaround for https://bugs.chromium.org/p/chromium/issues/detail?id=978325
					setTimeout(() => {
						contentDocument.open();
						contentDocument.write(newDocument);
						contentDocument.close();
						hookupOnLoadHandlers(newFrame);

						if (initialStyleVersion !== styleVersion) {
							applyStyles(contentDocument, contentDocument.body);
						}
					}, 0);
				}

				if (!options.allowScripts && isSafari) {
					// On Safari for iframes with scripts disabled, the `DOMContentLoaded` never seems to be fired: https://bugs.webkit.org/show_bug.cgi?id=33604
					// Use polling instead.
					const interval = setInterval(() => {
						// If the frame is no longer mounted, loading has stopped
						if (!newFrame.parentElement) {
							clearInterval(interval);
							return;
						}

						const contentDocument = assertIsDefined(newFrame.contentDocument);
						if (contentDocument.location.pathname.endsWith('/fake.html') && contentDocument.readyState !== 'loading') {
							clearInterval(interval);
							onFrameLoaded(contentDocument);
						}
					}, 10);
				} else {
					assertIsDefined(newFrame.contentWindow).addEventListener('DOMContentLoaded', e => {
						const contentDocument = e.target ? (/** @type {HTMLDocument} */ (e.target)) : undefined;
						onFrameLoaded(assertIsDefined(contentDocument));
					});
				}

				/**
				 * @param {Document} contentDocument
				 * @param {Window} contentWindow
				 */
				const onLoad = (contentDocument, contentWindow) => {
					if (contentDocument && contentDocument.body) {
						// Workaround for https://github.com/microsoft/vscode/issues/12865
						// check new scrollY and reset if necessary
						setInitialScrollPosition(contentDocument.body, contentWindow);
					}

					const newFrame = getPendingFrame();
					if (newFrame && newFrame.contentDocument && newFrame.contentDocument === contentDocument) {
						const wasFocused = document.hasFocus();
						const oldActiveFrame = getActiveFrame();
						if (oldActiveFrame) {
							document.body.removeChild(oldActiveFrame);
						}
						// Styles may have changed since we created the element. Make sure we re-style
						if (initialStyleVersion !== styleVersion) {
							applyStyles(newFrame.contentDocument, newFrame.contentDocument.body);
						}
						newFrame.setAttribute('id', 'active-frame');
						newFrame.style.visibility = 'visible';

						contentWindow.addEventListener('scroll', handleInnerScroll);
						contentWindow.addEventListener('wheel', handleWheel);

						if (wasFocused) {
							contentWindow.focus();
						}

						pendingMessages.forEach((message) => {
							contentWindow.postMessage(message.message, window.origin, message.transfer);
						});
						pendingMessages = [];
					}
				};

				/**
				 * @param {HTMLIFrameElement} newFrame
				 */
				function hookupOnLoadHandlers(newFrame) {
					clearTimeout(loadTimeout);
					loadTimeout = undefined;
					loadTimeout = setTimeout(() => {
						clearTimeout(loadTimeout);
						loadTimeout = undefined;
						onLoad(assertIsDefined(newFrame.contentDocument), assertIsDefined(newFrame.contentWindow));
					}, 200);

					const contentWindow = assertIsDefined(newFrame.contentWindow);

					contentWindow.addEventListener('load', function (e) {
						const contentDocument = /** @type {Document} */ (e.target);

						if (loadTimeout) {
							clearTimeout(loadTimeout);
							loadTimeout = undefined;
							onLoad(contentDocument, this);
						}
					});

					// Bubble out various events
					contentWindow.addEventListener('click', handleInnerClick);
					contentWindow.addEventListener('auxclick', handleAuxClick);
					contentWindow.addEventListener('keydown', handleInnerKeydown);
					contentWindow.addEventListener('keyup', handleInnerUp);
					contentWindow.addEventListener('contextmenu', e => {
						if (e.defaultPrevented) {
							// Extension code has already handled this event
							return;
						}

						e.preventDefault();

						/** @type { Record<string, boolean>} */
						let context = {};

						/** @type {HTMLElement | null} */
						let el = e.target;
						while (true) {
							if (!el) {
								break;
							}

							// Search self/ancestors for the closest context data attribute
							el = el.closest('[data-vscode-context]');
							if (!el) {
								break;
							}

							try {
								context = { ...JSON.parse(el.dataset.vscodeContext), ...context };
							} catch (e) {
								console.error(`Error parsing 'data-vscode-context' as json`, el, e);
							}

							el = el.parentElement;
						}

						hostMessaging.postMessage('did-context-menu', {
							clientX: e.clientX,
							clientY: e.clientY,
							context: context
						});
					});

					contentWindow.addEventListener('dragenter', handleInnerDragStartEvent);
					contentWindow.addEventListener('dragover', handleInnerDragStartEvent);

					unloadMonitor.onIframeLoaded(newFrame);
				}
			});

			// Forward message to the embedded iframe
			hostMessaging.onMessage('message', (_event, data) => {
				const pending = getPendingFrame();
				if (!pending) {
					const target = getActiveFrame();
					if (target) {
						assertIsDefined(target.contentWindow).postMessage(data.message, window.origin, data.transfer);
						return;
					}
				}
				pendingMessages.push(data);
			});

			hostMessaging.onMessage('initial-scroll-position', (_event, progress) => {
				initData.initialScrollProgress = progress;
			});

			hostMessaging.onMessage('execCommand', (_event, data) => {
				const target = getActiveFrame();
				if (!target) {
					return;
				}
				assertIsDefined(target.contentDocument).execCommand(data);
			});

			/** @type {string | undefined} */
			let lastFindValue = undefined;

			hostMessaging.onMessage('find', (_event, data) => {
				const target = getActiveFrame();
				if (!target) {
					return;
				}

				if (!data.previous && lastFindValue !== data.value && target.contentWindow) {
					// Reset selection so we start search at the head of the last search
					const selection = target.contentWindow.getSelection();
					if (selection) {
						selection.collapse(selection.anchorNode);
					}
				}
				lastFindValue = data.value;

				const didFind = (/** @type {any} */ (target.contentWindow)).find(
					data.value,
					/* caseSensitive*/ false,
					/* backwards*/ data.previous,
					/* wrapAround*/ true,
					/* wholeWord */ false,
					/* searchInFrames*/ false,
					false);
				hostMessaging.postMessage('did-find', didFind);
			});

			hostMessaging.onMessage('find-stop', (_event, data) => {
				const target = getActiveFrame();
				if (!target) {
					return;
				}

				lastFindValue = undefined;

				if (!data.clearSelection && target.contentWindow) {
					const selection = target.contentWindow.getSelection();
					if (selection) {
						for (let i = 0; i < selection.rangeCount; i++) {
							selection.removeRange(selection.getRangeAt(i));
						}
					}
				}
			});

			trackFocus({
				onFocus: () => hostMessaging.postMessage('did-focus', undefined),
				onBlur: () => hostMessaging.postMessage('did-blur', undefined)
			});

			(/** @type {any} */ (window))[vscodePostMessageFuncName] = (/** @type {string} */ command, /** @type {any} */ data) => {
				switch (command) {
					case 'onmessage':
					case 'do-update-state':
						hostMessaging.postMessage(command, data);
						break;
				}
			};

			// Also forward events before the contents of the webview have loaded
			window.addEventListener('keydown', handleInnerKeydown);
			window.addEventListener('dragenter', handleInnerDragStartEvent);
			window.addEventListener('dragover', handleInnerDragStartEvent);

			hostMessaging.signalReady();
		});
	</script>
</body>

</html>