Files
Will Browne 2c47d246fc Plugins: Introduce LoadingStrategy for frontend loading logic (#92392)
* do it all

* feat(plugins): move loadingStrategy to ds pluginMeta and add to plugin settings endpoint

* support child plugins and update tests

* use relative path for nested plugins

* feat(plugins): support nested plugins in the plugin loader cache by extracting pluginId from path

* feat(grafana-data): add plugin loading strategy to plugin meta and export

* feat(plugins): pass down loadingStrategy to fe plugin loader

* refactor(plugins): make PluginLoadingStrategy an enum

* feat(plugins): add the loading strategy to the fe plugin loader cache

* feat(plugins): load fe plugin js assets as script tags based on be loadingStrategy

* add more tests

* feat(plugins): add loading strategy to plugin preloader

* feat(plugins): make loadingStrategy a maybe and provide fetch fallback

* test(alerting): update config.apps mocks to include loadingStrategy

* fix format

---------

Co-authored-by: Jack Westbrook <jack.westbrook@gmail.com>
2024-09-09 10:38:35 +01:00

67 lines
1.6 KiB
TypeScript

import { PluginLoadingStrategy } from '@grafana/data';
import { clearPluginSettingsCache } from '../pluginSettings';
import { CACHE_INITIALISED_AT } from './constants';
const cache: Record<string, CachedPlugin> = {};
type CacheablePlugin = {
path: string;
version: string;
loadingStrategy: PluginLoadingStrategy;
};
type CachedPlugin = Omit<CacheablePlugin, 'path'>;
export function registerPluginInCache({ path, version, loadingStrategy }: CacheablePlugin): void {
const key = extractCacheKeyFromPath(path);
if (key && !cache[key]) {
cache[key] = {
version: encodeURI(version),
loadingStrategy,
};
}
}
export function invalidatePluginInCache(pluginId: string): void {
const path = pluginId;
if (cache[path]) {
delete cache[path];
}
clearPluginSettingsCache(pluginId);
}
export function resolveWithCache(url: string, defaultBust = CACHE_INITIALISED_AT): string {
const path = getCacheKey(url);
if (!path) {
return `${url}?_cache=${defaultBust}`;
}
const version = cache[path]?.version;
const bust = version || defaultBust;
return `${url}?_cache=${bust}`;
}
export function getPluginFromCache(path: string): CachedPlugin | undefined {
const key = getCacheKey(path);
if (!key) {
return;
}
return cache[key];
}
export function extractCacheKeyFromPath(path: string) {
const regex = /\/?public\/plugins\/([^\/]+)\//;
const match = path.match(regex);
return match ? match[1] : null;
}
function getCacheKey(address: string): string | undefined {
const key = Object.keys(cache).find((key) => address.includes(key));
if (!key) {
return;
}
return key;
}