@sveltejs/vite-plugin-svelte 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/package.json +12 -17
  2. package/src/{handle-hot-update.ts → handle-hot-update.js} +35 -20
  3. package/src/index.d.ts +215 -0
  4. package/src/{index.ts → index.js} +50 -71
  5. package/src/{preprocess.ts → preprocess.js} +37 -28
  6. package/src/types/compile.d.ts +48 -0
  7. package/src/types/id.d.ts +31 -0
  8. package/src/types/log.d.ts +24 -0
  9. package/src/types/options.d.ts +20 -0
  10. package/src/types/plugin-api.d.ts +11 -0
  11. package/src/types/vite-plugin-svelte-stats.d.ts +30 -0
  12. package/src/utils/{compile.ts → compile.js} +32 -66
  13. package/src/utils/{dependencies.ts → dependencies.js} +14 -11
  14. package/src/utils/{error.ts → error.js} +21 -14
  15. package/src/utils/{esbuild.ts → esbuild.js} +23 -17
  16. package/src/utils/{hash.ts → hash.js} +14 -3
  17. package/src/utils/{id.ts → id.js} +59 -60
  18. package/src/utils/{load-raw.ts → load-raw.js} +16 -16
  19. package/src/utils/{load-svelte-config.ts → load-svelte-config.js} +12 -10
  20. package/src/utils/{log.ts → log.js} +81 -48
  21. package/src/utils/{optimizer.ts → optimizer.js} +15 -7
  22. package/src/utils/{options.ts → options.js} +146 -295
  23. package/src/utils/{preprocess.ts → preprocess.js} +28 -12
  24. package/src/utils/{resolve.ts → resolve.js} +18 -9
  25. package/src/utils/{sourcemaps.ts → sourcemaps.js} +22 -14
  26. package/src/utils/{svelte-version.ts → svelte-version.js} +15 -7
  27. package/src/utils/vite-plugin-svelte-cache.js +253 -0
  28. package/src/utils/{vite-plugin-svelte-stats.ts → vite-plugin-svelte-stats.js} +66 -62
  29. package/src/utils/{watch.ts → watch.js} +30 -22
  30. package/dist/index.d.ts +0 -259
  31. package/dist/index.js +0 -2428
  32. package/dist/index.js.map +0 -1
  33. package/src/__tests__/fixtures/preprocess/foo.scss +0 -3
  34. package/src/__tests__/preprocess.spec.ts +0 -51
  35. package/src/ui/inspector/Inspector.svelte +0 -384
  36. package/src/ui/inspector/load-inspector.js +0 -15
  37. package/src/ui/inspector/options.ts +0 -131
  38. package/src/ui/inspector/plugin.ts +0 -97
  39. package/src/ui/inspector/utils.ts +0 -13
  40. package/src/utils/__tests__/compile.spec.ts +0 -49
  41. package/src/utils/__tests__/sourcemaps.spec.ts +0 -79
  42. package/src/utils/__tests__/svelte-version.spec.ts +0 -102
  43. package/src/utils/vite-plugin-svelte-cache.ts +0 -182
  44. /package/src/utils/{constants.ts → constants.js} +0 -0
@@ -1,384 +0,0 @@
1
- <script>
2
- // do not use TS here so that this component works in non-ts projects too
3
- import { onMount } from 'svelte';
4
- // eslint-disable-next-line node/no-missing-import
5
- import options from 'virtual:svelte-inspector-options';
6
- const toggle_combo = options.toggleKeyCombo?.toLowerCase().split('-');
7
- const nav_keys = Object.values(options.navKeys).map((k) => k.toLowerCase());
8
- let enabled = false;
9
- let hasOpened = false;
10
-
11
- const icon = `data:image/svg+xml;base64,${btoa(
12
- `
13
- <svg xmlns="http://www.w3.org/2000/svg" width="21" height="25" viewBox="0 0 107 128">
14
- <title>svelte-inspector-logo</title>
15
- <path d="M94.1566,22.8189c-10.4-14.8851-30.94-19.2971-45.7914-9.8348L22.2825,29.6078A29.9234,29.9234,0,0,0,8.7639,49.6506a31.5136,31.5136,0,0,0,3.1076,20.2318A30.0061,30.0061,0,0,0,7.3953,81.0653a31.8886,31.8886,0,0,0,5.4473,24.1157c10.4022,14.8865,30.9423,19.2966,45.7914,9.8348L84.7167,98.3921A29.9177,29.9177,0,0,0,98.2353,78.3493,31.5263,31.5263,0,0,0,95.13,58.117a30,30,0,0,0,4.4743-11.1824,31.88,31.88,0,0,0-5.4473-24.1157" style="fill:#ff3e00"/><path d="M45.8171,106.5815A20.7182,20.7182,0,0,1,23.58,98.3389a19.1739,19.1739,0,0,1-3.2766-14.5025,18.1886,18.1886,0,0,1,.6233-2.4357l.4912-1.4978,1.3363.9815a33.6443,33.6443,0,0,0,10.203,5.0978l.9694.2941-.0893.9675a5.8474,5.8474,0,0,0,1.052,3.8781,6.2389,6.2389,0,0,0,6.6952,2.485,5.7449,5.7449,0,0,0,1.6021-.7041L69.27,76.281a5.4306,5.4306,0,0,0,2.4506-3.631,5.7948,5.7948,0,0,0-.9875-4.3712,6.2436,6.2436,0,0,0-6.6978-2.4864,5.7427,5.7427,0,0,0-1.6.7036l-9.9532,6.3449a19.0329,19.0329,0,0,1-5.2965,2.3259,20.7181,20.7181,0,0,1-22.2368-8.2427,19.1725,19.1725,0,0,1-3.2766-14.5024,17.9885,17.9885,0,0,1,8.13-12.0513L55.8833,23.7472a19.0038,19.0038,0,0,1,5.3-2.3287A20.7182,20.7182,0,0,1,83.42,29.6611a19.1739,19.1739,0,0,1,3.2766,14.5025,18.4,18.4,0,0,1-.6233,2.4357l-.4912,1.4978-1.3356-.98a33.6175,33.6175,0,0,0-10.2037-5.1l-.9694-.2942.0893-.9675a5.8588,5.8588,0,0,0-1.052-3.878,6.2389,6.2389,0,0,0-6.6952-2.485,5.7449,5.7449,0,0,0-1.6021.7041L37.73,51.719a5.4218,5.4218,0,0,0-2.4487,3.63,5.7862,5.7862,0,0,0,.9856,4.3717,6.2437,6.2437,0,0,0,6.6978,2.4864,5.7652,5.7652,0,0,0,1.602-.7041l9.9519-6.3425a18.978,18.978,0,0,1,5.2959-2.3278,20.7181,20.7181,0,0,1,22.2368,8.2427,19.1725,19.1725,0,0,1,3.2766,14.5024,17.9977,17.9977,0,0,1-8.13,12.0532L51.1167,104.2528a19.0038,19.0038,0,0,1-5.3,2.3287" style="fill:#fff"/>
16
- <polygon points="0,0 15,40 40,20" stroke="#ff3e00" fill="#ff3e00"></polygon>
17
- </svg>
18
- `
19
- .replace(/[\n\r\t\s]+/g, ' ')
20
- .trim()
21
- )}`;
22
-
23
- // location of code in file
24
- let file_loc;
25
- // cursor pos and width for file_loc overlay positioning
26
- let x, y, w;
27
-
28
- let active_el;
29
-
30
- let enabled_ts;
31
-
32
- $: show_toggle =
33
- options.showToggleButton === 'always' || (options.showToggleButton === 'active' && enabled);
34
-
35
- function mousemove(event) {
36
- x = event.x;
37
- y = event.y;
38
- }
39
-
40
- function find_selectable_parent(el, include_self = false) {
41
- if (!include_self) {
42
- el = el.parentNode;
43
- }
44
- while (el) {
45
- if (is_selectable(el)) {
46
- return el;
47
- }
48
- el = el.parentNode;
49
- }
50
- }
51
-
52
- function find_selectable_child(el) {
53
- return [...el.querySelectorAll('*')].find(is_selectable);
54
- }
55
-
56
- function find_selectable_sibling(el, prev = false) {
57
- do {
58
- el = prev ? el.previousElementSibling : el.nextElementSibling;
59
- if (is_selectable(el)) {
60
- return el;
61
- }
62
- } while (el);
63
- }
64
-
65
- function find_selectable_for_nav(key) {
66
- const el = active_el;
67
- if (!el) {
68
- return find_selectable_child(document?.body);
69
- }
70
- switch (key) {
71
- case options.navKeys.parent:
72
- return find_selectable_parent(el);
73
- case options.navKeys.child:
74
- return find_selectable_child(el);
75
- case options.navKeys.next:
76
- return find_selectable_sibling(el) || find_selectable_parent(el);
77
- case options.navKeys.prev:
78
- return find_selectable_sibling(el, true) || find_selectable_parent(el);
79
- default:
80
- return;
81
- }
82
- }
83
-
84
- function is_selectable(el) {
85
- const file = el?.__svelte_meta?.loc?.file;
86
- if (!file || file.includes('node_modules/')) {
87
- return false; // no file or 3rd party
88
- }
89
- const id = el.getAttribute('id');
90
- if (id === 'svelte-announcer' || id?.startsWith('svelte-inspector-')) {
91
- return false; // ignore some elements by id that would be selectable from keyboard nav otherwise
92
- }
93
- return true;
94
- }
95
-
96
- function mouseover({ target }) {
97
- const el = find_selectable_parent(target, true);
98
- activate(el, false);
99
- }
100
-
101
- function activate(el, set_bubble_pos = true) {
102
- if (options.customStyles && el !== active_el) {
103
- if (active_el) {
104
- active_el.classList.remove('svelte-inspector-active-target');
105
- }
106
- if (el) {
107
- el.classList.add('svelte-inspector-active-target');
108
- }
109
- }
110
- if (el) {
111
- const { file, line, column } = el.__svelte_meta.loc;
112
- file_loc = `${file}:${line + 1}:${column + 1}`;
113
- } else {
114
- file_loc = null;
115
- }
116
- active_el = el;
117
- if (set_bubble_pos) {
118
- const pos = el.getBoundingClientRect();
119
- x = Math.ceil(pos.left);
120
- y = Math.ceil(pos.bottom - 20);
121
- }
122
- }
123
-
124
- function open_editor(event) {
125
- if (file_loc) {
126
- stop(event);
127
- fetch(`${options.__internal.base}/__open-in-editor?file=${encodeURIComponent(file_loc)}`);
128
- hasOpened = true;
129
- if (options.holdMode && is_holding()) {
130
- disable();
131
- }
132
- }
133
- }
134
-
135
- function is_key_active(key, event) {
136
- switch (key) {
137
- case 'shift':
138
- case 'control':
139
- case 'alt':
140
- case 'meta':
141
- return event.getModifierState(key.charAt(0).toUpperCase() + key.slice(1));
142
- default:
143
- return key === event.key.toLowerCase();
144
- }
145
- }
146
-
147
- function is_combo(event) {
148
- return toggle_combo?.every((key) => is_key_active(key, event));
149
- }
150
-
151
- function is_nav(event) {
152
- return nav_keys?.some((key) => is_key_active(key, event));
153
- }
154
-
155
- function is_open(event) {
156
- return options.openKey && options.openKey.toLowerCase() === event.key.toLowerCase();
157
- }
158
-
159
- function is_holding() {
160
- return enabled_ts && Date.now() - enabled_ts > 250;
161
- }
162
-
163
- function stop(event) {
164
- event.preventDefault();
165
- event.stopPropagation();
166
- event.stopImmediatePropagation();
167
- }
168
-
169
- function keydown(event) {
170
- if (event.repeat || event.key == null) {
171
- return;
172
- }
173
-
174
- if (is_combo(event)) {
175
- toggle();
176
- if (options.holdMode && enabled) {
177
- enabled_ts = Date.now();
178
- }
179
- } else if (enabled) {
180
- if (is_nav(event)) {
181
- const el = find_selectable_for_nav(event.key);
182
- if (el) {
183
- activate(el);
184
- stop(event);
185
- }
186
- } else if (is_open(event)) {
187
- open_editor(event);
188
- }
189
- }
190
- }
191
-
192
- function keyup(event) {
193
- if (event.repeat || event.key == null) {
194
- return;
195
- }
196
- const k = event.key.toLowerCase();
197
- if (enabled && is_holding() && toggle_combo.includes(k)) {
198
- disable();
199
- } else {
200
- enabled_ts = null;
201
- }
202
- }
203
-
204
- function toggle() {
205
- enabled ? disable() : enable();
206
- }
207
-
208
- function listeners(body, enabled) {
209
- const l = enabled ? body.addEventListener : body.removeEventListener;
210
- l('mousemove', mousemove);
211
- l('mouseover', mouseover);
212
- l('click', open_editor, true);
213
- }
214
-
215
- function enable() {
216
- enabled = true;
217
- const b = document.body;
218
- if (options.customStyles) {
219
- b.classList.add('svelte-inspector-enabled');
220
- }
221
- listeners(b, enabled);
222
- activate_initial_el();
223
- }
224
-
225
- function activate_initial_el() {
226
- const hov = innermost_hover_el();
227
- let el = find_selectable_parent(hov, true);
228
- if (!el) {
229
- const act = document.activeElement;
230
- el = find_selectable_parent(act, true);
231
- }
232
- if (!el) {
233
- el = find_selectable_child(document.body);
234
- }
235
- if (el) {
236
- activate(el);
237
- }
238
- }
239
-
240
- function innermost_hover_el() {
241
- let e = document.body.querySelector(':hover');
242
- let result;
243
- while (e) {
244
- result = e;
245
- e = e.querySelector(':hover');
246
- }
247
- return result;
248
- }
249
-
250
- function disable() {
251
- enabled = false;
252
- hasOpened = false;
253
- enabled_ts = null;
254
- const b = document.body;
255
- listeners(b, enabled);
256
- if (options.customStyles) {
257
- b.classList.remove('svelte-inspector-enabled');
258
- active_el?.classList.remove('svelte-inspector-active-target');
259
- }
260
- active_el = null;
261
- }
262
-
263
- function visibilityChange() {
264
- if (document.visibilityState === 'hidden') {
265
- onLeave();
266
- }
267
- }
268
-
269
- function onLeave() {
270
- if (hasOpened) {
271
- disable();
272
- }
273
- }
274
-
275
- onMount(() => {
276
- const s = document.createElement('style');
277
- s.setAttribute('type', 'text/css');
278
- s.setAttribute('id', 'svelte-inspector-style');
279
- s.textContent = `:root { --svelte-inspector-icon: url(${icon})};`;
280
- document.head.append(s);
281
- if (toggle_combo) {
282
- document.body.addEventListener('keydown', keydown);
283
- if (options.holdMode) {
284
- document.body.addEventListener('keyup', keyup);
285
- }
286
- }
287
- document.addEventListener('visibilitychange', visibilityChange);
288
- document.documentElement.addEventListener('mouseleave', onLeave);
289
- return () => {
290
- // make sure we get rid of everything
291
- disable();
292
- const s = document.head.querySelector('#svelte-inspector-style');
293
- if (s) {
294
- document.head.removeChild(s);
295
- }
296
- if (toggle_combo) {
297
- document.body.removeEventListener('keydown', keydown);
298
- if (options.holdMode) {
299
- document.body.removeEventListener('keyup', keyup);
300
- }
301
- }
302
- document.removeEventListener('visibilitychange', visibilityChange);
303
- document.documentElement.removeEventListener('mouseleave', onLeave);
304
- };
305
- });
306
- </script>
307
-
308
- {#if show_toggle}
309
- <button
310
- id="svelte-inspector-toggle"
311
- class:enabled
312
- style={`background-image: var(--svelte-inspector-icon);${options.toggleButtonPos
313
- .split('-')
314
- .map((p) => `${p}: 8px;`)
315
- .join('')}`}
316
- on:click={() => toggle()}
317
- aria-label={`${enabled ? 'disable' : 'enable'} svelte-inspector`}
318
- />
319
- {/if}
320
- {#if enabled && active_el && file_loc}
321
- {@const loc = active_el.__svelte_meta.loc}
322
- <div
323
- id="svelte-inspector-overlay"
324
- style:left="{Math.min(x + 3, document.documentElement.clientWidth - w - 10)}px"
325
- style:top="{document.documentElement.clientHeight < y + 50 ? y - 30 : y + 30}px"
326
- bind:offsetWidth={w}
327
- >
328
- &lt;{active_el.tagName.toLowerCase()}&gt;&nbsp;{file_loc}
329
- </div>
330
- <div id="svelte-inspector-announcer" aria-live="assertive" aria-atomic="true">
331
- {active_el.tagName.toLowerCase()} in file {loc.file} on line {loc.line} column {loc.column}
332
- </div>
333
- {/if}
334
-
335
- <style>
336
- :global(body.svelte-inspector-enabled *) {
337
- cursor: var(--svelte-inspector-icon), crosshair !important;
338
- }
339
- :global(.svelte-inspector-active-target) {
340
- outline: 2px dashed #ff3e00 !important;
341
- }
342
-
343
- #svelte-inspector-overlay {
344
- position: fixed;
345
- background-color: rgba(0, 0, 0, 0.8);
346
- color: #fff;
347
- padding: 2px 4px;
348
- border-radius: 5px;
349
- z-index: 999999;
350
- pointer-events: none;
351
- }
352
-
353
- #svelte-inspector-toggle {
354
- all: unset;
355
- border: 1px solid #ff3e00;
356
- border-radius: 8px;
357
- position: fixed;
358
- height: 32px;
359
- width: 32px;
360
- background-color: white;
361
- background-position: center;
362
- background-repeat: no-repeat;
363
- cursor: pointer;
364
- }
365
-
366
- #svelte-inspector-announcer {
367
- position: absolute;
368
- left: 0px;
369
- top: 0px;
370
- clip: rect(0px, 0px, 0px, 0px);
371
- clip-path: inset(50%);
372
- overflow: hidden;
373
- white-space: nowrap;
374
- width: 1px;
375
- height: 1px;
376
- }
377
-
378
- #svelte-inspector-toggle:not(.enabled) {
379
- filter: grayscale(1);
380
- }
381
- #svelte-inspector-toggle:hover {
382
- background-color: #facece;
383
- }
384
- </style>
@@ -1,15 +0,0 @@
1
- // eslint-disable-next-line node/no-missing-import
2
- import Inspector from 'virtual:svelte-inspector-path:Inspector.svelte';
3
-
4
- function create_inspector_host() {
5
- const id = 'svelte-inspector-host';
6
- if (document.getElementById(id) != null) {
7
- throw new Error('svelte-inspector-host element already exists');
8
- }
9
- const el = document.createElement('div');
10
- el.setAttribute('id', id);
11
- document.documentElement.appendChild(el);
12
- return el;
13
- }
14
-
15
- new Inspector({ target: create_inspector_host() });
@@ -1,131 +0,0 @@
1
- import * as process from 'process';
2
- import { log } from '../../utils/log';
3
- import { loadEnv, ResolvedConfig } from 'vite';
4
- export const defaultInspectorOptions: InspectorOptions = {
5
- toggleKeyCombo: process.platform === 'darwin' ? 'meta-shift' : 'control-shift',
6
- navKeys: { parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' },
7
- openKey: 'Enter',
8
- holdMode: true,
9
- showToggleButton: 'active',
10
- toggleButtonPos: 'top-right',
11
- customStyles: true
12
- };
13
-
14
- export function parseEnvironmentOptions(
15
- config: ResolvedConfig
16
- ): Partial<InspectorOptions> | boolean | void {
17
- const env = loadEnv(config.mode, config.envDir ?? process.cwd(), 'SVELTE_INSPECTOR');
18
- const options = env?.SVELTE_INSPECTOR_OPTIONS;
19
- const toggle = env?.SVELTE_INSPECTOR_TOGGLE;
20
- if (options) {
21
- try {
22
- const parsed = JSON.parse(options);
23
- const parsedType = typeof parsed;
24
- if (parsedType === 'boolean') {
25
- return parsed;
26
- } else if (parsedType === 'object') {
27
- if (Array.isArray(parsed)) {
28
- throw new Error('invalid type, expected object map but got array');
29
- }
30
- const parsedKeys = Object.keys(parsed);
31
- const defaultKeys = Object.keys(defaultInspectorOptions);
32
- const unknownKeys = parsedKeys.filter((k) => !defaultKeys.includes(k));
33
- if (unknownKeys.length) {
34
- log.warn(
35
- `ignoring unknown options in environment SVELTE_INSPECTOR_OPTIONS: ${unknownKeys.join(
36
- ', '
37
- )}.`,
38
- undefined,
39
- 'inspector'
40
- );
41
- for (const key of unknownKeys) {
42
- delete parsed[key];
43
- }
44
- }
45
- log.debug('loaded environment config', parsed, 'inspector');
46
- return parsed;
47
- }
48
- } catch (e) {
49
- log.error(
50
- `failed to parse inspector options from environment SVELTE_INSPECTOR_OPTIONS="${options}"`,
51
- e,
52
- 'inspector'
53
- );
54
- }
55
- } else if (toggle) {
56
- const keyConfig = {
57
- toggleKeyCombo: toggle
58
- };
59
- log.debug('loaded environment config', keyConfig, 'inspector');
60
- return keyConfig;
61
- }
62
- }
63
-
64
- export interface InspectorOptions {
65
- /**
66
- * define a key combo to toggle inspector,
67
- * @default 'meta-shift' on mac, 'control-shift' on other os
68
- *
69
- * any number of modifiers `control` `shift` `alt` `meta` followed by zero or one regular key, separated by -
70
- * examples: control-shift, control-o, control-alt-s meta-x control-meta
71
- * Some keys have native behavior (e.g. alt-s opens history menu on firefox).
72
- * To avoid conflicts or accidentally typing into inputs, modifier only combinations are recommended.
73
- */
74
- toggleKeyCombo?: string;
75
-
76
- /**
77
- * define keys to select elements with via keyboard
78
- * @default {parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' }
79
- *
80
- * improves accessibility and also helps when you want to select elements that do not have a hoverable surface area
81
- * due to tight wrapping
82
- *
83
- * A note for users of screen-readers:
84
- * If you are using arrow keys to navigate the page itself, change the navKeys to avoid conflicts.
85
- * e.g. navKeys: {parent: 'w', prev: 'a', child: 's', next: 'd'}
86
- *
87
- *
88
- * parent: select closest parent
89
- * child: select first child (or grandchild)
90
- * next: next sibling (or parent if no next sibling exists)
91
- * prev: previous sibling (or parent if no prev sibling exists)
92
- */
93
- navKeys?: { parent: string; child: string; next: string; prev: string };
94
-
95
- /**
96
- * define key to open the editor for the currently selected dom node
97
- *
98
- * @default 'Enter'
99
- */
100
- openKey?: string;
101
-
102
- /**
103
- * inspector is automatically disabled when releasing toggleKeyCombo after holding it for a longpress
104
- * @default true
105
- */
106
- holdMode?: boolean;
107
- /**
108
- * when to show the toggle button
109
- * @default 'active'
110
- */
111
- showToggleButton?: 'always' | 'active' | 'never';
112
-
113
- /**
114
- * where to display the toggle button
115
- * @default top-right
116
- */
117
- toggleButtonPos?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left';
118
-
119
- /**
120
- * inject custom styles when inspector is active
121
- */
122
- customStyles?: boolean;
123
-
124
- /**
125
- * internal options that are automatically set, not to be set or used by users
126
- */
127
- __internal?: {
128
- // vite base url
129
- base: string;
130
- };
131
- }
@@ -1,97 +0,0 @@
1
- import { Plugin, normalizePath } from 'vite';
2
- import { log } from '../../utils/log';
3
- import path from 'path';
4
- import { fileURLToPath } from 'url';
5
- import fs from 'fs';
6
- import { idToFile } from './utils';
7
- import { defaultInspectorOptions, type InspectorOptions, parseEnvironmentOptions } from './options';
8
-
9
- function getInspectorPath() {
10
- const pluginPath = normalizePath(path.dirname(fileURLToPath(import.meta.url)));
11
- return pluginPath.replace(/\/vite-plugin-svelte\/dist$/, '/vite-plugin-svelte/src/ui/inspector/');
12
- }
13
-
14
- export function svelteInspector(): Plugin {
15
- const inspectorPath = getInspectorPath();
16
- log.debug.enabled && log.debug(`svelte inspector path: ${inspectorPath}`);
17
- let inspectorOptions: InspectorOptions;
18
- let disabled = false;
19
-
20
- return {
21
- name: 'vite-plugin-svelte:inspector',
22
- apply: 'serve',
23
- enforce: 'pre',
24
-
25
- configResolved(config) {
26
- const vps = config.plugins.find((p) => p.name === 'vite-plugin-svelte');
27
- if (!vps) {
28
- log.warn('vite-plugin-svelte is missing, inspector disabled', undefined, 'inspector');
29
- disabled = true;
30
- return;
31
- }
32
- const configFileOptions = vps?.api?.options?.inspector;
33
- const environmentOptions = parseEnvironmentOptions(config);
34
- if (!configFileOptions && !environmentOptions) {
35
- log.debug('no options found, inspector disabled', undefined, 'inspector');
36
- disabled = true;
37
- return;
38
- }
39
- if (environmentOptions === true) {
40
- inspectorOptions = defaultInspectorOptions;
41
- } else {
42
- inspectorOptions = {
43
- ...defaultInspectorOptions,
44
- ...configFileOptions,
45
- ...(environmentOptions || {})
46
- };
47
- }
48
- inspectorOptions.__internal = {
49
- base: config.base?.replace(/\/$/, '') || ''
50
- };
51
- },
52
-
53
- async resolveId(importee: string, importer, options) {
54
- if (options?.ssr || disabled) {
55
- return;
56
- }
57
- if (importee.startsWith('virtual:svelte-inspector-options')) {
58
- return importee;
59
- } else if (importee.startsWith('virtual:svelte-inspector-path:')) {
60
- const resolved = importee.replace('virtual:svelte-inspector-path:', inspectorPath);
61
- log.debug.enabled &&
62
- log.debug(`resolved ${importee} with ${resolved}`, undefined, 'inspector');
63
- return resolved;
64
- }
65
- },
66
-
67
- async load(id, options) {
68
- if (options?.ssr || disabled) {
69
- return;
70
- }
71
- if (id === 'virtual:svelte-inspector-options') {
72
- return `export default ${JSON.stringify(inspectorOptions ?? {})}`;
73
- } else if (id.startsWith(inspectorPath)) {
74
- // read file ourselves to avoid getting shut out by vites fs.allow check
75
- const file = idToFile(id);
76
- if (fs.existsSync(file)) {
77
- return await fs.promises.readFile(file, 'utf-8');
78
- } else {
79
- log.error(
80
- `failed to find file for svelte-inspector: ${file}, referenced by id ${id}.`,
81
- undefined,
82
- 'inspector'
83
- );
84
- }
85
- }
86
- },
87
-
88
- transform(code, id, options) {
89
- if (options?.ssr || disabled) {
90
- return;
91
- }
92
- if (id.includes('vite/dist/client/client.mjs')) {
93
- return { code: `${code}\nimport('virtual:svelte-inspector-path:load-inspector.js')` };
94
- }
95
- }
96
- };
97
- }
@@ -1,13 +0,0 @@
1
- const FS_PREFIX = `/@fs/`;
2
- const IS_WINDOWS = process.platform === 'win32';
3
- const queryRE = /\?.*$/s;
4
- const hashRE = /#.*$/s;
5
-
6
- export function idToFile(id: string): string {
7
- // strip /@fs/ but keep leading / on non-windows
8
- if (id.startsWith(FS_PREFIX)) {
9
- id = id = id.slice(IS_WINDOWS ? FS_PREFIX.length : FS_PREFIX.length - 1);
10
- }
11
- // strip query and hash
12
- return id.replace(hashRE, '').replace(queryRE, '');
13
- }
@@ -1,49 +0,0 @@
1
- import { describe, it, expect } from 'vitest';
2
- import { createCompileSvelte } from '../compile';
3
- import { ResolvedOptions } from '../options';
4
- const options: ResolvedOptions = {
5
- compilerOptions: {
6
- dev: false,
7
- format: 'esm',
8
- css: 'external'
9
- },
10
- isBuild: false,
11
- isDebug: false,
12
- isProduction: false,
13
- isServe: false,
14
- root: process.cwd()
15
- };
16
-
17
- describe('createCompileSvelte', () => {
18
- it('returns function', () => {
19
- const compileSvelte = createCompileSvelte(options);
20
- expect(typeof compileSvelte).toBe('function');
21
- });
22
-
23
- describe('compileSvelte', async () => {
24
- it('removes dangling pure annotations', async () => {
25
- const code = `<script>
26
- const x=1;
27
- console.log('something',/* @__PURE__ */ new Date());
28
- console.log('something else');
29
- </script>
30
- <div>{x}</div>`;
31
- const compileSvelte = createCompileSvelte(options);
32
- const output = await compileSvelte(
33
- {
34
- cssId: 'svelte-xxxxx',
35
- query: undefined,
36
- raw: false,
37
- ssr: false,
38
- timestamp: Date.now(),
39
- id: 'id',
40
- filename: '/some/File.svelte',
41
- normalizedFilename: 'some/File.svelte'
42
- },
43
- code,
44
- {}
45
- );
46
- expect(output.compiled.js.code).not.toContain('/* @__PURE__ */\n');
47
- });
48
- });
49
- });