summaryrefslogtreecommitdiff
path: root/frontend/src/plugin-loader.tsx
blob: 2bdfcec163487f1d29bdc049a9b08c87754d0544 (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
import { ToastNotification } from '@decky/api';
import {
  EUIMode,
  ModalRoot,
  Navigation,
  PanelSection,
  PanelSectionRow,
  QuickAccessTab,
  findSP,
  quickAccessMenuClasses,
  showModal,
  sleep,
} from '@decky/ui';
import { FC, lazy } from 'react';
import { FaDownload, FaExclamationCircle, FaPlug } from 'react-icons/fa';

import DeckyIcon from './components/DeckyIcon';
import { DeckyState, DeckyStateContextProvider, UserInfo, useDeckyState } from './components/DeckyState';
import { File, FileSelectionType } from './components/modals/filepicker';
import { deinitFilepickerPatches, initFilepickerPatches } from './components/modals/filepicker/patches';
import MultiplePluginsInstallModal from './components/modals/MultiplePluginsInstallModal';
import PluginInstallModal from './components/modals/PluginInstallModal';
import PluginUninstallModal from './components/modals/PluginUninstallModal';
import NotificationBadge from './components/NotificationBadge';
import PluginView from './components/PluginView';
import { useQuickAccessVisible } from './components/QuickAccessVisibleState';
import WithSuspense from './components/WithSuspense';
import ErrorBoundaryHook from './errorboundary-hook';
import { FrozenPluginService } from './frozen-plugins-service';
import { HiddenPluginsService } from './hidden-plugins-service';
import Logger from './logger';
import { NotificationService } from './notification-service';
import { InstallType, Plugin, PluginLoadType } from './plugin';
import RouterHook from './router-hook';
import { deinitSteamFixes, initSteamFixes } from './steamfixes';
import { checkForPluginUpdates } from './store';
import TabsHook from './tabs-hook';
import Toaster from './toaster';
import { getVersionInfo } from './updater';
import { getSetting, setSetting } from './utils/settings';
import TranslationHelper, { TranslationClass } from './utils/TranslationHelper';

const StorePage = lazy(() => import('./components/store/Store'));
const SettingsPage = lazy(() => import('./components/settings'));

const FilePicker = lazy(() => import('./components/modals/filepicker'));

declare global {
  interface Window {
    __DECKY_SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED_deckyLoaderAPIInit?: {
      connect: (version: number, key: string) => any; // Returns the backend API used above, no real point adding types to this.
    };
  }
}

/** Map of event names to event listeners */
type listenerMap = Map<string, Set<(...args: any) => any>>;

interface DeckyRequestInit extends RequestInit {
  excludedHeaders: string[];
}

const callPluginMethod = DeckyBackend.callable<[pluginName: string, method: string, ...args: any], any>(
  'loader/call_plugin_method',
);

class PluginLoader extends Logger {
  private plugins: Plugin[] = [];
  public errorBoundaryHook: ErrorBoundaryHook = new ErrorBoundaryHook();
  private tabsHook: TabsHook = new TabsHook();
  public routerHook: RouterHook = new RouterHook();
  public toaster: Toaster = new Toaster();
  private deckyState: DeckyState = new DeckyState();
  // stores a map of plugin names to all their event listeners
  private pluginEventListeners: Map<string, listenerMap> = new Map();

  public frozenPluginsService = new FrozenPluginService(this.deckyState);
  public hiddenPluginsService = new HiddenPluginsService(this.deckyState);
  public notificationService = new NotificationService(this.deckyState);

  private reloadLock: boolean = false;
  // stores a list of plugin names which requested to be reloaded
  private pluginReloadQueue: { name: string; version?: string; loadType: PluginLoadType }[] = [];

  private loaderUpdateToast?: ToastNotification;
  private pluginUpdateToast?: ToastNotification;

  constructor() {
    super(PluginLoader.name);

    DeckyBackend.addEventListener('loader/notify_updates', this.notifyUpdates.bind(this));
    DeckyBackend.addEventListener('loader/import_plugin', this.importPlugin.bind(this));
    DeckyBackend.addEventListener('loader/unload_plugin', this.unloadPlugin.bind(this));
    DeckyBackend.addEventListener('loader/add_plugin_install_prompt', this.addPluginInstallPrompt.bind(this));
    DeckyBackend.addEventListener(
      'loader/add_multiple_plugins_install_prompt',
      this.addMultiplePluginsInstallPrompt.bind(this),
    );
    DeckyBackend.addEventListener('updater/update_download_percentage', () => {
      this.deckyState.setIsLoaderUpdating(true);
    });
    DeckyBackend.addEventListener(`loader/plugin_event`, this.pluginEventListener);

    this.tabsHook.init();

    const TabBadge = () => {
      const { updates, hasLoaderUpdate } = useDeckyState();
      return <NotificationBadge show={(updates && updates.size > 0) || hasLoaderUpdate} />;
    };

    this.tabsHook.add({
      id: QuickAccessTab.Decky,
      title: null,
      content: (
        <DeckyStateContextProvider deckyState={this.deckyState}>
          <PluginView />
        </DeckyStateContextProvider>
      ),
      icon: (
        <DeckyStateContextProvider deckyState={this.deckyState}>
          <FaPlug />
          <TabBadge />
        </DeckyStateContextProvider>
      ),
    });

    this.routerHook.addRoute('/decky/store', () => (
      <DeckyStateContextProvider deckyState={this.deckyState}>
        <WithSuspense route={true}>
          <StorePage />
        </WithSuspense>
      </DeckyStateContextProvider>
    ));
    this.routerHook.addRoute('/decky/settings', () => {
      return (
        <DeckyStateContextProvider deckyState={this.deckyState}>
          <WithSuspense route={true}>
            <SettingsPage />
          </WithSuspense>
        </DeckyStateContextProvider>
      );
    });

    initSteamFixes();

    initFilepickerPatches();

    this.initPluginBackendAPI();

    Promise.all([this.getUserInfo(), this.updateVersion()])
      .then(() => this.loadPlugins())
      .then(() => this.log('Initialized'))
      .then(() => sleep(30000)) // Internet might not immediately be up
      .then(() => this.checkPluginUpdates());
  }

  private checkForSP(): boolean {
    try {
      return !!findSP();
    } catch (e) {
      this.warn('Error checking for SP tab', e);
      return false;
    }
  }

  private async runCrashChecker() {
    const spExists = this.checkForSP();
    await sleep(5000);
    if (spExists && !this.checkForSP()) {
      // SP died after plugin loaded. Give up and let the loader's crash loop detection handle it.
      this.error('SP died during startup. Restarting webhelper.');
      await this.restartWebhelper();
    }
  }

  private getPluginsFromBackend = DeckyBackend.callable<
    [],
    { name: string; version: string; load_type: PluginLoadType }[]
  >('loader/get_plugins');

  private restartWebhelper = DeckyBackend.callable<[], void>('utilities/restart_webhelper');

  private async loadPlugins() {
    let registration: any;
    const uiMode = await new Promise(
      (r) =>
        (registration = SteamClient.UI.RegisterForUIModeChanged((mode: EUIMode) => {
          r(mode);
          registration.unregister();
        })),
    );
    if (uiMode == EUIMode.GamePad) {
      // wait for SP window to exist before loading plugins
      while (!findSP()) {
        await sleep(100);
      }
    }
    this.runCrashChecker();
    const plugins = await this.getPluginsFromBackend();
    const pluginLoadPromises = [];
    const loadStart = performance.now();
    for (const plugin of plugins) {
      if (!this.hasPlugin(plugin.name))
        pluginLoadPromises.push(this.importPlugin(plugin.name, plugin.version, plugin.load_type, false));
    }
    await Promise.all(pluginLoadPromises);
    const loadEnd = performance.now();
    this.log(`Loaded ${plugins.length} plugins in ${loadEnd - loadStart}ms`);

    this.checkPluginUpdates();
  }

  public async getUserInfo() {
    const userInfo = await DeckyBackend.call<[], UserInfo>('utilities/get_user_info');
    setSetting('user_info.user_name', userInfo.username);
    setSetting('user_info.user_home', userInfo.path);
  }

  public async updateVersion() {
    const versionInfo = await getVersionInfo();
    this.deckyState.setVersionInfo(versionInfo);

    return versionInfo;
  }

  public async notifyUpdates() {
    const versionInfo = await this.updateVersion();
    if (versionInfo?.remote && versionInfo?.remote?.tag_name != versionInfo?.current) {
      this.deckyState.setHasLoaderUpdate(true);
      if (this.notificationService.shouldNotify('deckyUpdates')) {
        this.loaderUpdateToast && this.loaderUpdateToast.dismiss();
        await this.routerHook.waitForUnlock();
        this.loaderUpdateToast = this.toaster.toast({
          title: <TranslationHelper transClass={TranslationClass.PLUGIN_LOADER} transText="decky_title" />,
          body: (
            <TranslationHelper
              transClass={TranslationClass.PLUGIN_LOADER}
              transText="decky_update_available"
              i18nArgs={{ tag_name: versionInfo?.remote?.tag_name }}
            />
          ),
          logo: <DeckyIcon />,
          icon: <FaDownload />,
          onClick: () => Navigation.Navigate('/decky/settings'),
        });
      }
    }
    await sleep(7000);
    await this.notifyPluginUpdates();
  }

  public async checkPluginUpdates() {
    const frozenPlugins = this.deckyState.publicState().frozenPlugins;

    const updates = await checkForPluginUpdates(this.plugins.filter((p) => !frozenPlugins.includes(p.name)));
    this.deckyState.setUpdates(updates);
    return updates;
  }

  public async notifyPluginUpdates() {
    const updates = await this.checkPluginUpdates();
    if (updates?.size > 0 && this.notificationService.shouldNotify('pluginUpdates')) {
      this.pluginUpdateToast && this.pluginUpdateToast.dismiss();
      this.pluginUpdateToast = this.toaster.toast({
        title: <TranslationHelper transClass={TranslationClass.PLUGIN_LOADER} transText="decky_title" />,
        body: (
          <TranslationHelper
            transClass={TranslationClass.PLUGIN_LOADER}
            transText="plugin_update"
            i18nArgs={{ count: updates.size }}
          />
        ),
        logo: <DeckyIcon />,
        icon: <FaDownload />,
        onClick: () => Navigation.Navigate('/decky/settings/plugins'),
      });
    }
  }

  public addPluginInstallPrompt(
    artifact: string,
    version: string,
    request_id: string,
    hash: string,
    install_type: number,
  ) {
    showModal(
      <PluginInstallModal
        artifact={artifact}
        version={version}
        hash={hash}
        installType={install_type}
        onOK={() => DeckyBackend.call<[string]>('utilities/confirm_plugin_install', request_id)}
        onCancel={() => DeckyBackend.call<[string]>('utilities/cancel_plugin_install', request_id)}
      />,
    );
  }

  public addMultiplePluginsInstallPrompt(
    request_id: string,
    requests: { name: string; version: string; hash: string; install_type: InstallType }[],
  ) {
    showModal(
      <MultiplePluginsInstallModal
        requests={requests}
        onOK={() => DeckyBackend.call<[string]>('utilities/confirm_plugin_install', request_id)}
        onCancel={() => DeckyBackend.call<[string]>('utilities/cancel_plugin_install', request_id)}
      />,
    );
  }

  public uninstallPlugin(name: string, title: string, buttonText: string, description: string) {
    showModal(<PluginUninstallModal name={name} title={title} buttonText={buttonText} description={description} />);
  }

  public hasPlugin(name: string) {
    return Boolean(this.plugins.find((plugin) => plugin.name == name));
  }

  public dismountAll() {
    for (const plugin of this.plugins) {
      this.log(`Dismounting ${plugin.name}`);
      plugin.onDismount?.();
    }
  }

  public init() {
    getSetting('developer.enabled', false).then((val) => {
      if (val) import('./developer').then((developer) => developer.startup());
    });

    // Grab and set plugin order
    getSetting<string[]>('pluginOrder', []).then((pluginOrder) => {
      this.debug('pluginOrder: ', pluginOrder);
      this.deckyState.setPluginOrder(pluginOrder);
    });

    this.frozenPluginsService.init();
    this.hiddenPluginsService.init();
    this.notificationService.init();
  }

  public deinit() {
    this.routerHook.removeRoute('/decky/store');
    this.routerHook.removeRoute('/decky/settings');
    deinitSteamFixes();
    deinitFilepickerPatches();
    this.routerHook.deinit();
    this.tabsHook.deinit();
    this.toaster.deinit();
    this.errorBoundaryHook.deinit();
  }

  public unloadPlugin(name: string, skipStateUpdate: boolean = false) {
    const plugin = this.plugins.find((plugin) => plugin.name === name);
    plugin?.onDismount?.();
    this.plugins = this.plugins.filter((p) => p !== plugin);
    if (!skipStateUpdate) this.deckyState.setPlugins(this.plugins);
  }

  public async importPlugin(
    name: string,
    version?: string | undefined,
    loadType: PluginLoadType = PluginLoadType.ESMODULE_V1,
    useQueue: boolean = true,
  ) {
    if (useQueue && this.reloadLock) {
      this.log('Reload currently in progress, adding to queue', name);
      this.pluginReloadQueue.push({ name, version: version, loadType });
      return;
    }

    try {
      if (useQueue) this.reloadLock = true;
      this.log(`Trying to load ${name}`);

      this.unloadPlugin(name, true);
      const startTime = performance.now();
      await this.importReactPlugin(name, version, loadType);
      const endTime = performance.now();

      this.deckyState.setPlugins(this.plugins);
      this.log(`Loaded ${name} in ${endTime - startTime}ms`);
    } catch (e) {
      throw e;
    } finally {
      if (useQueue) {
        this.reloadLock = false;
        const nextPlugin = this.pluginReloadQueue.shift();
        if (nextPlugin) {
          this.importPlugin(nextPlugin.name, nextPlugin.version, loadType);
        }
      }
    }
  }

  private async importReactPlugin(
    name: string,
    version?: string,
    loadType: PluginLoadType = PluginLoadType.ESMODULE_V1,
  ) {
    let spExists = this.checkForSP();
    try {
      switch (loadType) {
        case PluginLoadType.ESMODULE_V1:
          const plugin_exports = await import(`http://127.0.0.1:1337/plugins/${name}/dist/index.js?t=${Date.now()}`);
          let plugin = plugin_exports.default();

          this.plugins.push({
            ...plugin,
            name: name,
            version: version,
            loadType,
          });
          break;

        case PluginLoadType.LEGACY_EVAL_IIFE:
          let res = await fetch(`http://127.0.0.1:1337/plugins/${name}/frontend_bundle`, {
            credentials: 'include',
            headers: {
              'X-Decky-Auth': deckyAuthToken,
            },
          });
          if (res.ok) {
            let plugin_export: (serverAPI: any) => Plugin = await eval(
              (await res.text()) + `\n//# sourceURL=decky://decky/legacy_plugin/${encodeURIComponent(name)}/index.js`,
            );
            let plugin = plugin_export(this.createLegacyPluginAPI(name));
            this.plugins.push({
              ...plugin,
              name: name,
              version: version,
              loadType,
            });
          } else throw new Error(`${name} frontend_bundle not OK`);
          break;

        default:
          throw new Error(`${name} has no defined loadType.`);
      }
    } catch (e) {
      this.error('Error loading plugin ' + name, e);
      const TheError: FC<{}> = () => (
        <PanelSection>
          <PanelSectionRow>
            <div className={quickAccessMenuClasses.FriendsTitle} style={{ display: 'flex', justifyContent: 'center' }}>
              <TranslationHelper transClass={TranslationClass.PLUGIN_LOADER} transText="error" />
            </div>
          </PanelSectionRow>
          <PanelSectionRow>
            <pre style={{ overflowX: 'scroll' }}>
              <code>{e instanceof Error ? '' + e.stack : JSON.stringify(e)}</code>
            </pre>
          </PanelSectionRow>
          <PanelSectionRow>
            <div className={quickAccessMenuClasses.Text}>
              <TranslationHelper
                transClass={TranslationClass.PLUGIN_LOADER}
                transText="plugin_error_uninstall"
                i18nArgs={{ name: name }}
              />
            </div>
          </PanelSectionRow>
        </PanelSection>
      );
      this.plugins.push({
        name: name,
        version: version,
        content: <TheError />,
        icon: <FaExclamationCircle />,
        loadType,
      });
      this.toaster.toast({
        title: (
          <TranslationHelper
            transClass={TranslationClass.PLUGIN_LOADER}
            transText="plugin_load_error.toast"
            i18nArgs={{ name: name }}
          />
        ),
        body: '' + e,
        icon: <FaExclamationCircle />,
      });
    }

    if (spExists && !this.checkForSP()) {
      // SP died after plugin loaded. Give up and let the loader's crash loop detection handle it.
      this.error('SP died after loading plugin. Restarting webhelper.');
      await this.restartWebhelper();
    }
  }

  async callServerMethod(methodName: string, args = {}) {
    this.warn(
      `Calling ${methodName} via callServerMethod, which is deprecated and will be removed in a future release. Please switch to the backend API.`,
    );
    return await DeckyBackend.call<[methodName: string, kwargs: any], any>(
      'utilities/_call_legacy_utility',
      methodName,
      args,
    );
  }

  openFilePickerLegacy(
    startPath: string,
    selectFiles?: boolean,
    regex?: RegExp,
  ): Promise<{ path: string; realpath: string }> {
    this.warn('openFilePicker is deprecated and will be removed. Please migrate to openFilePickerV2');
    if (selectFiles) {
      return this.openFilePicker(FileSelectionType.FILE, startPath, true, true, regex);
    } else {
      return this.openFilePicker(FileSelectionType.FOLDER, startPath, false, true, regex);
    }
  }

  openFilePicker(
    select: FileSelectionType,
    startPath: string,
    includeFiles?: boolean,
    includeFolders?: boolean,
    filter?: RegExp | ((file: File) => boolean),
    extensions?: string[],
    showHiddenFiles?: boolean,
    allowAllFiles?: boolean,
    max?: number,
  ): Promise<{ path: string; realpath: string }> {
    return new Promise((resolve, reject) => {
      const Content = ({ closeModal }: { closeModal?: () => void }) => (
        // Purposely outside of the FilePicker component as lazy-loaded ModalRoots don't focus correctly
        <ModalRoot
          onCancel={() => {
            reject('User canceled');
            closeModal?.();
          }}
        >
          <WithSuspense>
            <FilePicker
              startPath={startPath}
              includeFiles={includeFiles}
              includeFolders={includeFolders}
              filter={filter}
              validFileExtensions={extensions}
              allowAllFiles={allowAllFiles}
              defaultHidden={showHiddenFiles}
              onSubmit={resolve}
              closeModal={closeModal}
              fileSelType={select}
              max={max}
            />
          </WithSuspense>
        </ModalRoot>
      );
      showModal(<Content />);
    });
  }

  // Useful for audio/video streams
  getExternalResourceURL(url: string) {
    return `http://127.0.0.1:1337/fetch?auth=${deckyAuthToken}&fetch_url=${encodeURIComponent(url)}`;
  }

  // Same syntax as fetch but only supports the url-based syntax and an object for headers since it's the most common usage pattern
  fetchNoCors(input: string, init?: DeckyRequestInit | undefined): Promise<Response> {
    const { headers: initHeaders = {}, ...restOfInit } = init || {};
    const getPrefixedHeaders = () => {
      let prefixedInitHeaders: { [name: string]: any } = {};
      for (const [key, value] of Object.entries(initHeaders)) {
        prefixedInitHeaders[`X-Decky-Header-${key}`] = value;
      }
      return prefixedInitHeaders;
    };
    const headers: { [name: string]: string } = getPrefixedHeaders();

    if (init?.excludedHeaders) {
      headers['X-Decky-Fetch-Excluded-Headers'] = init.excludedHeaders.join(', ');
    }

    return fetch(this.getExternalResourceURL(input), {
      ...restOfInit,
      credentials: 'include',
      headers,
    });
  }

  async legacyFetchNoCors(url: string, request: any = {}) {
    let method: string;
    const req = { headers: {}, ...request, data: request.body };
    req?.body && delete req.body;
    if (!request.method) {
      method = 'POST';
    } else {
      method = request.method;
      delete req.method;
    }
    try {
      const ret = await DeckyBackend.call<
        [method: string, url: string, extra_opts?: any],
        { status: number; headers: { [key: string]: string }; body: string }
      >('utilities/http_request', method, url, req);
      return { success: true, result: ret };
    } catch (e) {
      return { success: false, result: e?.toString() };
    }
  }

  initPluginBackendAPI() {
    // Things will break *very* badly if plugin code touches this outside of @decky/api, so lets make that clear.
    window.__DECKY_SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED_deckyLoaderAPIInit = {
      connect: (version: number, pluginName: string) => {
        if (version < 1 || version > 2) {
          console.warn(`Plugin ${pluginName} requested unsupported api version ${version}.`);
        }

        const eventListeners: listenerMap = new Map();
        this.pluginEventListeners.set(pluginName, eventListeners);

        const backendAPI = {
          call: (methodName: string, ...args: any) => {
            return callPluginMethod(pluginName, methodName, ...args);
          },
          callable: (methodName: string) => {
            return (...args: any) => callPluginMethod(pluginName, methodName, ...args);
          },
          addEventListener: (event: string, listener: (...args: any) => any) => {
            if (!eventListeners.has(event)) {
              eventListeners.set(event, new Set([listener]));
            } else {
              eventListeners.get(event)?.add(listener);
            }
            return listener;
          },
          removeEventListener: (event: string, listener: (...args: any) => any) => {
            if (eventListeners.has(event)) {
              const set = eventListeners.get(event);
              set?.delete(listener);
            }
          },
          openFilePicker: this.openFilePicker.bind(this),
          executeInTab: DeckyBackend.callable<
            [tab: String, runAsync: Boolean, code: string],
            { success: boolean; result: any }
          >('utilities/execute_in_tab'),
          fetchNoCors: this.fetchNoCors.bind(this),
          getExternalResourceURL: this.getExternalResourceURL.bind(this),
          injectCssIntoTab: DeckyBackend.callable<[tab: string, style: string], string>(
            'utilities/inject_css_into_tab',
          ),
          removeCssFromTab: DeckyBackend.callable<[tab: string, cssId: string]>('utilities/remove_css_from_tab'),
          routerHook: this.routerHook,
          toaster: this.toaster,
          _version: 1,
        } as any;

        if (version >= 2) {
          backendAPI._version = 2;
          backendAPI.useQuickAccessVisible = useQuickAccessVisible;
        }

        this.debug(`${pluginName} connected to loader API.`);
        return backendAPI;
      },
    };
  }

  pluginEventListener = (data: { plugin: string; event: string; args: any }) => {
    const { plugin, event, args } = data;
    this.debug(`Recieved plugin event ${event} for ${plugin} with args`, args);
    if (!this.pluginEventListeners.has(plugin)) {
      this.warn(`plugin ${plugin} does not have event listeners`);
      return;
    }
    const eventListeners = this.pluginEventListeners.get(plugin)!;
    if (eventListeners.has(event)) {
      for (const listener of eventListeners.get(event)!) {
        (async () => {
          try {
            await listener(...args);
          } catch (e) {
            this.error(`error in event ${event}`, e, listener);
          }
        })();
      }
    } else {
      this.warn(`event ${event} has no listeners`);
    }
  };

  createLegacyPluginAPI(pluginName: string) {
    const pluginAPI = {
      routerHook: this.routerHook,
      toaster: this.toaster,
      // Legacy
      callServerMethod: this.callServerMethod.bind(this),
      openFilePicker: this.openFilePickerLegacy.bind(this),
      openFilePickerV2: this.openFilePicker.bind(this),
      // Legacy
      async callPluginMethod(methodName: string, args = {}) {
        return DeckyBackend.call<[pluginName: string, methodName: string, kwargs: any], any>(
          'loader/call_legacy_plugin_method',
          pluginName,
          methodName,
          args,
        );
      },
      fetchNoCors: this.legacyFetchNoCors.bind(this),
      executeInTab: DeckyBackend.callable<
        [tab: String, runAsync: Boolean, code: string],
        { success: boolean; result: any }
      >('utilities/execute_in_tab'),
      injectCssIntoTab: DeckyBackend.callable<[tab: string, style: string], string>('utilities/inject_css_into_tab'),
      removeCssFromTab: DeckyBackend.callable<[tab: string, cssId: string]>('utilities/remove_css_from_tab'),
    };

    return pluginAPI;
  }
}

export default PluginLoader;