Files

198 lines
6.8 KiB
TypeScript
Raw Permalink Normal View History

2026-10-12 07:47:42 -04:00
import { getBootstrapExtensions, getBootstrapThemeChain } from '@/bootstrap';
2026-10-05 18:10:18 -04:00
import type { ExtensionDefinition, ExtensionSetupContext } from '@/sdk';
import { isObject } from '@/lib/objects';
import {
abortExtensionRegistryBatch,
commitExtensionRegistryBatch,
createExtensionRegistryBatch,
registerScreen,
registerSlotComponent,
registerExtensionTableColumn,
registerFormExtension,
2026-10-12 07:54:37 -04:00
registerViewOverride,
2026-10-05 18:10:18 -04:00
failExtensionLoad,
clearExtensionError,
setExtensionState,
prepareExtensions,
getLoadableExtensions,
type ExtensionRegistryBatch,
2026-10-07 17:27:33 -04:00
type SiteExtensionEntry,
2026-10-05 18:10:18 -04:00
} from '@/extensions/registry';
import type { ExtensionTableColumnRegistration } from './tableTypes';
import type { FormExtension } from './formTypes';
2026-10-05 18:10:18 -04:00
import { startExtensionDevelopmentReload } from './development';
export const EXTENSION_IMPORT_TIMEOUT_MS = 15_000;
const isThenable = <T>(value: T): value is T & PromiseLike<void> =>
isObject(value) && 'then' in value && value.then instanceof Function;
2026-10-12 21:41:35 -04:00
/** Rejects when the import takes longer than an extension bundle may; the theme chain is held to the same limit. */
export const withImportTimeout = async <T>(promise: Promise<T>): Promise<T> => {
2026-10-05 18:10:18 -04:00
let timeout: ReturnType<typeof setTimeout> | undefined;
const timer = new Promise<never>((_, reject) => {
timeout = setTimeout(() => {
reject(new Error(`bundle import exceeded ${EXTENSION_IMPORT_TIMEOUT_MS}ms`));
}, EXTENSION_IMPORT_TIMEOUT_MS);
});
try {
return await Promise.race([promise, timer]);
} finally {
if (timeout !== undefined) {
clearTimeout(timeout);
}
}
};
2026-10-11 02:33:18 -04:00
/**
2026-10-12 07:54:37 -04:00
* Guests are sent no screens or view overrides, since neither renders on the sign-in pages, so
2026-10-11 02:33:18 -04:00
* the same setup() skips those registrations there instead of failing on undeclared names.
*/
2026-10-05 18:10:18 -04:00
const createContext = (entry: SiteExtensionEntry, batch: ExtensionRegistryBatch): ExtensionSetupContext => ({
meta: { id: entry.id, version: entry.version },
config: entry.config ?? {},
2026-10-12 07:54:37 -04:00
views: {
override: (name, view) => {
if (entry.views) {
registerViewOverride(entry.id, name, view, batch);
2026-10-11 02:33:18 -04:00
}
},
2026-10-05 18:10:18 -04:00
},
slots: {
register: (name, component) =>
registerSlotComponent(entry.id, name, component as Parameters<typeof registerSlotComponent>[2], batch),
},
screens: {
2026-10-11 02:33:18 -04:00
register: (id, component, options) => {
if (entry.screens) {
registerScreen(entry.id, id, component, batch, options);
}
},
2026-10-05 18:10:18 -04:00
},
columns: {
register: (name, column) =>
registerExtensionTableColumn(
{
...column,
name,
extensionId: entry.id,
component: column.component as ExtensionTableColumnRegistration['component'],
},
batch
),
},
forms: {
extend: (form, component) =>
registerFormExtension({ extensionId: entry.id, form, component: component as FormExtension }, batch),
},
2026-10-05 18:10:18 -04:00
});
export type ExtensionModule = object;
type ModuleImporter = (url: string) => Promise<ExtensionModule>;
const nativeImport: ModuleImporter = (url) => import(/* @vite-ignore */ url);
/** Rewrites the browser's missing-export error into an actionable SDK version message. */
const describeBootError = (cause: unknown): Error => {
const error = cause instanceof Error ? cause : new Error(String(cause));
const message = error.message;
const match = message.match(/does not provide an export named '([^']+)'/);
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
if (!match) {
return error;
}
return new Error(
`this extension needs an SDK export ('${match[1]}') that the panel's current frontend build does not provide - ` +
'update the panel, or rebuild its frontend if it is older than the installed panel version'
);
};
2026-10-13 15:06:23 -04:00
/** The bundle's definition; null for a theme without `setup`, which has nothing to register. */
const parseExtensionDefinition = <T extends object>(module: T, theme: boolean): ExtensionDefinition | null => {
const definition = 'default' in module && isObject(module.default) ? module.default : undefined;
if (theme && definition && !('setup' in definition)) {
return null;
2026-10-05 18:10:18 -04:00
}
2026-10-13 15:06:23 -04:00
if (!definition || !('setup' in definition) || !(definition.setup instanceof Function)) {
2026-10-05 18:10:18 -04:00
throw new Error('bundle has no default export with a setup() function');
}
2026-10-13 15:06:23 -04:00
return definition as ExtensionDefinition;
2026-10-05 18:10:18 -04:00
};
let loading: Promise<void> | undefined;
let importBundle: ModuleImporter = nativeImport;
const failedImports = new Set<string>();
async function bootExtension(entry: SiteExtensionEntry): Promise<void> {
let module: ExtensionModule;
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
try {
2026-10-12 21:41:35 -04:00
module = await withImportTimeout(importBundle(entry.entry));
2026-10-05 18:10:18 -04:00
} catch (cause) {
failedImports.add(entry.id);
failExtensionLoad(entry.id, 'boot', describeBootError(cause));
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return;
}
const batch = createExtensionRegistryBatch();
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
try {
2026-10-13 15:06:23 -04:00
const definition = parseExtensionDefinition(module, entry.theme === true);
const setupResult = definition?.setup(createContext(entry, batch));
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
if (isThenable(setupResult)) {
void Promise.resolve(setupResult).catch(() => {});
throw new Error('setup() must register synchronously and must not return a promise');
}
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
commitExtensionRegistryBatch(entry.id, batch);
} catch (cause) {
2026-10-08 16:53:20 -04:00
if (!batch.closed) {
abortExtensionRegistryBatch(batch);
}
2026-10-05 18:10:18 -04:00
failExtensionLoad(entry.id, 'boot', describeBootError(cause));
}
}
2026-10-07 17:27:33 -04:00
/** Call once after the core mounts. The route tree has already registered each extension's class prefix. */
2026-10-05 18:10:18 -04:00
export function loadExtensions(importModule: ModuleImporter = nativeImport): Promise<void> {
2026-10-08 16:53:20 -04:00
if (loading) {
return loading;
}
2026-10-05 18:10:18 -04:00
importBundle = importModule;
2026-10-07 17:27:33 -04:00
const entries = prepareExtensions(getBootstrapExtensions());
2026-10-08 16:53:20 -04:00
2026-10-13 15:06:23 -04:00
// A theme with JavaScript is an entry too; one poller per package.
const ids = new Set(entries.map(({ id }) => id));
startExtensionDevelopmentReload([...entries, ...getBootstrapThemeChain().filter(({ id }) => !ids.has(id))]);
2026-10-07 17:27:33 -04:00
loading = Promise.all(entries.map(bootExtension)).then(() => {});
2026-10-08 16:53:20 -04:00
2026-10-05 18:10:18 -04:00
return loading;
}
export function canRetryExtension(id: string): boolean {
return failedImports.has(id);
}
2026-10-07 17:27:33 -04:00
/** Only a failed import can be retried, once per failure. */
2026-10-05 18:10:18 -04:00
export function retryExtension(id: string): Promise<void> {
const entry = getLoadableExtensions()?.find((candidate) => candidate.id === id);
2026-10-08 16:53:20 -04:00
if (!entry || !failedImports.delete(id)) {
return Promise.resolve();
}
2026-10-05 18:10:18 -04:00
clearExtensionError(id, 'boot');
setExtensionState({ id, status: 'loading' });
2026-10-08 16:53:20 -04:00
2026-10-07 17:27:33 -04:00
return bootExtension(entry);
2026-10-05 18:10:18 -04:00
}