File size: 2,026 Bytes
bc20498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { loadEnv } from 'vite';
import { debug } from './debug.js';

/** @type {import('./public.d.ts').Options} */
export const defaultInspectorOptions = {
	toggleKeyCombo: process.platform === 'darwin' ? 'meta-shift' : 'control-shift',
	navKeys: { parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' },
	escapeKeys: ['Backspace', 'Escape'],
	openKey: 'Enter',
	holdMode: true,
	showToggleButton: 'active',
	toggleButtonPos: 'top-right',
	customStyles: true
};

/**
 * @param {import('vite').ResolvedConfig} config
 * @returns {Partial<import('./public.d.ts').Options> | boolean | void}
 */
export function parseEnvironmentOptions(config) {
	const env = loadEnv(config.mode, config.envDir ?? process.cwd(), 'SVELTE_INSPECTOR');
	const options = env?.SVELTE_INSPECTOR_OPTIONS;
	const toggle = env?.SVELTE_INSPECTOR_TOGGLE;
	if (options) {
		try {
			const parsed = JSON.parse(options);
			const parsedType = typeof parsed;
			if (parsedType === 'boolean') {
				return parsed;
			} else if (parsedType === 'object') {
				if (Array.isArray(parsed)) {
					throw new Error('invalid type, expected object map but got array');
				}
				const parsedKeys = Object.keys(parsed);
				const defaultKeys = Object.keys(defaultInspectorOptions);
				const unknownKeys = parsedKeys.filter((k) => !defaultKeys.includes(k));
				if (unknownKeys.length) {
					config.logger.warn(
						`[vite-plugin-svelte-inspector] ignoring unknown options in environment SVELTE_INSPECTOR_OPTIONS: ${unknownKeys.join(
							', '
						)}`
					);
					for (const key of unknownKeys) {
						delete parsed[key];
					}
				}
				debug('loaded environment config', parsed);
				return parsed;
			}
		} catch (e) {
			config.logger.error(
				`[vite-plugin-svelte-inspector] failed to parse inspector options from environment SVELTE_INSPECTOR_OPTIONS="${options}"\n${e}`
			);
		}
	} else if (toggle) {
		const keyConfig = {
			toggleKeyCombo: toggle
		};
		debug('loaded environment config', keyConfig);
		return keyConfig;
	}
}