mirror of
https://github.com/pterodactyl/panel.git
synced 2026-11-30 11:25:52 -05:00
registry cleanup
This commit is contained in:
+9
-4
@@ -178,11 +178,14 @@ export interface SiteExtensionEntry {
|
||||
version: string;
|
||||
} | null;
|
||||
}
|
||||
interface StagedScreen {
|
||||
importer: ScreenImporter;
|
||||
options: Readonly<ScreenOptions>;
|
||||
}
|
||||
export interface ExtensionRegistryBatch {
|
||||
closed: boolean;
|
||||
slots: BatchedSlotRegistration[];
|
||||
screens: Map<string, ScreenImporter>;
|
||||
screenOptions: Map<string, ScreenOptions>;
|
||||
screens: Map<string, StagedScreen>;
|
||||
columns: ExtensionTableColumnRegistration[];
|
||||
components: Map<ComponentName, ComponentReplacement<ComponentName>>;
|
||||
}
|
||||
@@ -193,7 +196,9 @@ export interface ExtensionRuntimeState {
|
||||
}
|
||||
export declare class ExtensionImportError extends Error {
|
||||
}
|
||||
export declare function subscribeExtensionRegistry(key: string, listener: () => void): () => void;
|
||||
/** Every change notifies every listener; each getter returns the same value until its own data changes. */
|
||||
export declare function subscribeExtensionRegistry(listener: () => void): () => void;
|
||||
export declare function useExtensionRegistry<T>(read: () => T): T;
|
||||
export declare function getExtensionLoadState(id: string): ExtensionRuntimeState | undefined;
|
||||
export declare function getScreenComponent(extensionId: string, screenId: string): LazyExoticComponent<ComponentType<ScreenComponentProps>> | undefined;
|
||||
/** Undefined until the screen's bundle has loaded. */
|
||||
@@ -215,7 +220,7 @@ export declare function createExtensionRegistryBatch(): ExtensionRegistryBatch;
|
||||
export declare function commitExtensionRegistryBatch(extensionId: string, batch: ExtensionRegistryBatch): void;
|
||||
export declare function registerComponentReplacement<TName extends ComponentName>(extensionId: string, name: TName, replacement: ComponentReplacement<TName>, batch: ExtensionRegistryBatch): void;
|
||||
export declare function abortExtensionRegistryBatch(batch: ExtensionRegistryBatch): void;
|
||||
export declare function registerSlotComponent(extensionId: string, name: SlotName, component: ComponentType<SlotComponentProps>, batch?: ExtensionRegistryBatch): void;
|
||||
export declare function registerSlotComponent(extensionId: string, name: SlotName, component: ComponentType<SlotComponentProps>, batch: ExtensionRegistryBatch): void;
|
||||
export declare function getSlotComponents(name: SlotName): readonly SlotRegistration[];
|
||||
export declare function registerExtensionTableColumn(column: ExtensionTableColumnRegistration, batch: ExtensionRegistryBatch): void;
|
||||
export declare function getExtensionTableColumns(name: ExtensionTableName): readonly ExtensionTableColumnRegistration[];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useState, useSyncExternalStore } from 'react';
|
||||
import React, { useState } from 'react';
|
||||
import { AlertCircle, FileArchive, RefreshCw, Settings2, Trash2, UploadCloud } from 'lucide-react';
|
||||
import { getExtensionStates, subscribeExtensionRegistry } from '@/extensions/registry';
|
||||
import { getExtensionStates, useExtensionRegistry } from '@/extensions/registry';
|
||||
import { cn } from '@/lib/cn';
|
||||
import { httpErrorToHuman } from '@/api/http';
|
||||
import {
|
||||
@@ -47,8 +47,6 @@ import { FileInput } from '@/components/form/controls';
|
||||
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';
|
||||
import { emptyCompactClass } from '@/components/ui/styles';
|
||||
|
||||
const subscribeRuntime = (listener: () => void) => subscribeExtensionRegistry('states', listener);
|
||||
|
||||
type ExtensionState = NonNullable<AdminExtension['state']>;
|
||||
|
||||
type ActionButtonProps = {
|
||||
@@ -674,7 +672,7 @@ function EmptyExtensionsState() {
|
||||
}
|
||||
|
||||
export default function ExtensionsContainer() {
|
||||
const runtimeStates = useSyncExternalStore(subscribeRuntime, getExtensionStates);
|
||||
const runtimeStates = useExtensionRegistry(getExtensionStates);
|
||||
const runtimeFailures = runtimeStates.filter((state) => state.status === 'failed');
|
||||
const { data, error, isFetching, refetch } = useAdminExtensions();
|
||||
const extensions = data?.data ?? [];
|
||||
|
||||
@@ -1,13 +1,26 @@
|
||||
/** @vitest-environment jsdom */
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
|
||||
import AppToaster from '@/components/elements/AppToaster';
|
||||
import { lazy, Suspense, useState } from 'react';
|
||||
import { lazy, Suspense, useState, type ComponentType } from 'react';
|
||||
import { QueryClient, QueryClientProvider, useSuspenseQuery } from '@tanstack/react-query';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { SlotComponentProps } from '@/extensions/registry';
|
||||
import type * as RegistryModule from '@/extensions/registry';
|
||||
import type { SlotComponentProps, SlotName } from '@/extensions/registry';
|
||||
|
||||
afterEach(cleanup);
|
||||
|
||||
/** What the loader does for an extension whose setup registers one slot component. */
|
||||
function registerSlot(
|
||||
registry: typeof RegistryModule,
|
||||
extensionId: string,
|
||||
name: SlotName,
|
||||
component: ComponentType<SlotComponentProps>
|
||||
) {
|
||||
const batch = registry.createExtensionRegistryBatch();
|
||||
registry.registerSlotComponent(extensionId, name, component, batch);
|
||||
registry.commitExtensionRegistryBatch(extensionId, batch);
|
||||
}
|
||||
|
||||
describe('extension Slot', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
@@ -20,8 +33,8 @@ describe('extension Slot', () => {
|
||||
const First = ({ data }: SlotComponentProps) => <span>first:{(data as { pathname: string }).pathname}</span>;
|
||||
const Second = ({ data }: SlotComponentProps) => <span>second:{(data as { pathname: string }).pathname}</span>;
|
||||
|
||||
registry.registerSlotComponent('first-extension', 'auth.login.before', First);
|
||||
registry.registerSlotComponent('second-extension', 'auth.login.before', Second);
|
||||
registerSlot(registry, 'first-extension', 'auth.login.before', First);
|
||||
registerSlot(registry, 'second-extension', 'auth.login.before', Second);
|
||||
|
||||
render(<Slot name={'auth.login.before'} data={{ pathname: 'survival', params: {}, search: {} }} />);
|
||||
|
||||
@@ -39,8 +52,8 @@ describe('extension Slot', () => {
|
||||
};
|
||||
const Healthy = () => <span>healthy extension</span>;
|
||||
|
||||
registry.registerSlotComponent('broken-extension', 'dashboard.before', Broken);
|
||||
registry.registerSlotComponent('healthy-extension', 'dashboard.before', Healthy);
|
||||
registerSlot(registry, 'broken-extension', 'dashboard.before', Broken);
|
||||
registerSlot(registry, 'healthy-extension', 'dashboard.before', Healthy);
|
||||
|
||||
render(<Slot name={'dashboard.before'} />);
|
||||
|
||||
@@ -63,8 +76,8 @@ it('keeps the host and healthy registrations visible while a lazy slot loads', a
|
||||
resolve = done;
|
||||
})
|
||||
);
|
||||
registry.registerSlotComponent('lazy', 'dashboard.after', Lazy);
|
||||
registry.registerSlotComponent('healthy', 'dashboard.after', () => <span>healthy sibling</span>);
|
||||
registerSlot(registry, 'lazy', 'dashboard.after', Lazy);
|
||||
registerSlot(registry, 'healthy', 'dashboard.after', () => <span>healthy sibling</span>);
|
||||
render(
|
||||
<Suspense fallback={<p>whole page waiting</p>}>
|
||||
<button>Core control</button>
|
||||
@@ -86,7 +99,7 @@ it('isolates suspense queries and lets an errored query recover on explicit retr
|
||||
const { data } = useSuspenseQuery({ queryKey: ['extension-recovery'], queryFn, retry: false });
|
||||
return <span>{data}</span>;
|
||||
}
|
||||
registry.registerSlotComponent('query', 'account.overview.before', QuerySlot);
|
||||
registerSlot(registry, 'query', 'account.overview.before', QuerySlot);
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
@@ -109,10 +122,10 @@ it('shows late registrations without resetting healthy mod state', async () => {
|
||||
const [count, setCount] = useState(0);
|
||||
return <button onClick={() => setCount(count + 1)}>Count {count}</button>;
|
||||
}
|
||||
registry.registerSlotComponent('counter', 'account.overview.after', Counter);
|
||||
registerSlot(registry, 'counter', 'account.overview.after', Counter);
|
||||
render(<Slot name='account.overview.after' />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Count 0' }));
|
||||
act(() => registry.registerSlotComponent('late', 'account.overview.after', () => <span>late arrival</span>));
|
||||
act(() => registerSlot(registry, 'late', 'account.overview.after', () => <span>late arrival</span>));
|
||||
await waitFor(() => expect(screen.getByText('late arrival')).toBeVisible());
|
||||
expect(screen.getByRole('button', { name: 'Count 1' })).toBeVisible();
|
||||
});
|
||||
@@ -120,7 +133,7 @@ it('shows late registrations without resetting healthy mod state', async () => {
|
||||
it('keeps recovery controls outside clickable slot hosts', async () => {
|
||||
const registry = await import('@/extensions/registry');
|
||||
const { default: Slot } = await import('@/extensions/Slot');
|
||||
registry.registerSlotComponent('row-failure', 'panel.overview.before', () => {
|
||||
registerSlot(registry, 'row-failure', 'panel.overview.before', () => {
|
||||
throw new Error('broken row');
|
||||
});
|
||||
render(
|
||||
@@ -141,7 +154,7 @@ it('reports a failure repeated in every row once and retries every row together'
|
||||
const registry = await import('@/extensions/registry');
|
||||
const { default: Slot } = await import('@/extensions/Slot');
|
||||
let broken = true;
|
||||
registry.registerSlotComponent('rows', 'dashboard.serverRow.after', () => {
|
||||
registerSlot(registry, 'rows', 'dashboard.serverRow.after', () => {
|
||||
if (broken) throw new Error('row failed');
|
||||
return <span>row ready</span>;
|
||||
});
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
import { useCallback, useSyncExternalStore } from 'react';
|
||||
import { getSlotComponents, subscribeExtensionRegistry, type SlotProps } from '@/extensions/registry';
|
||||
import { getSlotComponents, useExtensionRegistry, type SlotProps } from '@/extensions/registry';
|
||||
import ExtensionMount from '@/extensions/ExtensionMount';
|
||||
|
||||
export default function Slot({ name, data }: SlotProps) {
|
||||
const subscribe = useCallback(
|
||||
(listener: () => void) => subscribeExtensionRegistry(`slot:${name}`, listener),
|
||||
[name]
|
||||
);
|
||||
const snapshot = useCallback(() => getSlotComponents(name), [name]);
|
||||
const registrations = useSyncExternalStore(subscribe, snapshot);
|
||||
const registrations = useExtensionRegistry(() => getSlotComponents(name));
|
||||
const resetKey =
|
||||
data && 'resource' in data
|
||||
? `${data.kind}:${data.resource.attributes.id}`
|
||||
|
||||
@@ -98,7 +98,7 @@ export function createComponentSession() {
|
||||
}
|
||||
};
|
||||
pending.set(name, stop);
|
||||
unsubscribe = subscribeExtensionRegistry(`extension:${extensionId}`, check);
|
||||
unsubscribe = subscribeExtensionRegistry(check);
|
||||
check();
|
||||
};
|
||||
return {
|
||||
|
||||
@@ -328,7 +328,6 @@ describe('declared component replacements', () => {
|
||||
'Duplicate'
|
||||
);
|
||||
registry.abortExtensionRegistryBatch(batch);
|
||||
expect(batch.components.size).toBe(0);
|
||||
expect(() => registry.registerComponentReplacement('views', 'dashboard.serverCard', Component, batch)).toThrow(
|
||||
'closed'
|
||||
);
|
||||
|
||||
@@ -14,9 +14,15 @@ describe('extensions/registry', () => {
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
const registerSlot = (extensionId: string, name: RegistryModule.SlotName) => {
|
||||
const batch = registry.createExtensionRegistryBatch();
|
||||
registry.registerSlotComponent(extensionId, name, Component, batch);
|
||||
registry.commitExtensionRegistryBatch(extensionId, batch);
|
||||
};
|
||||
|
||||
it('returns slot components in registration order', () => {
|
||||
registry.registerSlotComponent('one', 'dashboard.before', Component);
|
||||
registry.registerSlotComponent('two', 'dashboard.before', Component);
|
||||
registerSlot('one', 'dashboard.before');
|
||||
registerSlot('two', 'dashboard.before');
|
||||
|
||||
expect(registry.getSlotComponents('dashboard.before').map((r) => r.extensionId)).toEqual(['one', 'two']);
|
||||
expect(new Set(registry.getSlotComponents('dashboard.before').map((r) => r.id)).size).toBe(2);
|
||||
@@ -24,7 +30,8 @@ describe('extensions/registry', () => {
|
||||
});
|
||||
|
||||
it('rejects unknown slot names loudly', () => {
|
||||
expect(() => registry.registerSlotComponent('ext', 'dashboard.typo' as never, Component)).toThrow(
|
||||
const batch = registry.createExtensionRegistryBatch();
|
||||
expect(() => registry.registerSlotComponent('ext', 'dashboard.typo' as never, Component, batch)).toThrow(
|
||||
/Unknown slot/
|
||||
);
|
||||
});
|
||||
@@ -93,20 +100,24 @@ describe('extensions/registry', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('publishes stable immutable slot snapshots only to relevant subscribers', () => {
|
||||
it('publishes stable immutable slot snapshots once per committed batch', () => {
|
||||
const changed = vi.fn();
|
||||
const unrelated = vi.fn();
|
||||
const unsubscribe = registry.subscribeExtensionRegistry('slot:dashboard.before', changed);
|
||||
registry.subscribeExtensionRegistry('slot:dashboard.after', unrelated);
|
||||
const unsubscribe = registry.subscribeExtensionRegistry(changed);
|
||||
const before = registry.getSlotComponents('dashboard.before');
|
||||
const after = registry.getSlotComponents('dashboard.after');
|
||||
expect(registry.getSlotComponents('dashboard.before')).toBe(before);
|
||||
registry.registerSlotComponent('demo', 'dashboard.before', Component);
|
||||
const batch = registry.createExtensionRegistryBatch();
|
||||
registry.registerSlotComponent('demo', 'dashboard.before', Component, batch);
|
||||
registry.registerSlotComponent('demo', 'dashboard.before', Component, batch);
|
||||
expect(changed).not.toHaveBeenCalled();
|
||||
registry.commitExtensionRegistryBatch('demo', batch);
|
||||
expect(before).toHaveLength(0);
|
||||
expect(registry.getSlotComponents('dashboard.before')).toHaveLength(2);
|
||||
expect(Object.isFrozen(registry.getSlotComponents('dashboard.before'))).toBe(true);
|
||||
expect(registry.getSlotComponents('dashboard.after')).toBe(after);
|
||||
expect(changed).toHaveBeenCalledTimes(1);
|
||||
expect(unrelated).not.toHaveBeenCalled();
|
||||
unsubscribe();
|
||||
registry.registerSlotComponent('demo', 'dashboard.before', Component);
|
||||
registerSlot('late', 'dashboard.before');
|
||||
expect(changed).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
@@ -115,7 +126,7 @@ describe('extensions/registry', () => {
|
||||
{ id: 'demo', entry: '/demo.js', screens: [{ id: 'main', area: 'account', path: 'probe' }] },
|
||||
]);
|
||||
const changed = vi.fn();
|
||||
registry.subscribeExtensionRegistry('table:admin.nodes', changed);
|
||||
registry.subscribeExtensionRegistry(changed);
|
||||
const batch = registry.createExtensionRegistryBatch();
|
||||
const column = {
|
||||
extensionId: 'demo',
|
||||
@@ -146,9 +157,20 @@ describe('extensions/registry', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('shows the latest remaining failure once another context recovers', () => {
|
||||
registry.setExtensionState({ id: 'demo', status: 'loaded' });
|
||||
registry.reportExtensionError('demo', 'first', new Error('one'));
|
||||
registry.reportExtensionError('demo', 'second', new Error('two'));
|
||||
registry.reportExtensionError('demo', 'third', new Error('three'));
|
||||
registry.clearExtensionError('demo', 'third');
|
||||
|
||||
expect(registry.getExtensionStates()).toEqual([{ id: 'demo', status: 'failed', error: 'second: two' }]);
|
||||
expect(registry.getExtensionLoadState('demo')?.status).toBe('loaded');
|
||||
});
|
||||
|
||||
it('publishes stable diagnostics snapshots and restores state after a mount recovers', () => {
|
||||
const changed = vi.fn();
|
||||
registry.subscribeExtensionRegistry('states', changed);
|
||||
registry.subscribeExtensionRegistry(changed);
|
||||
registry.setExtensionState({ id: 'demo', status: 'loaded' });
|
||||
const before = registry.getExtensionStates();
|
||||
expect(registry.getExtensionStates()).toBe(before);
|
||||
@@ -261,7 +283,7 @@ describe('extensions/registry', () => {
|
||||
registry.abortExtensionRegistryBatch(missing);
|
||||
|
||||
const changed = vi.fn();
|
||||
registry.subscribeExtensionRegistry('extension:demo', changed);
|
||||
registry.subscribeExtensionRegistry(changed);
|
||||
const batch = registry.createExtensionRegistryBatch();
|
||||
registry.registerScreen('demo', 'gated', importer, batch, { visible });
|
||||
registry.registerScreen('demo', 'open', importer, batch, { badge });
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { lazy, type ComponentType, type LazyExoticComponent } from 'react';
|
||||
import { lazy, useSyncExternalStore, type ComponentType, type LazyExoticComponent } from 'react';
|
||||
import type { Server } from '@/api/server/types';
|
||||
import type { ExtensionConfig } from '@/sdk';
|
||||
import type { AppForm } from '@/components/form';
|
||||
@@ -378,11 +378,14 @@ export interface SiteExtensionEntry {
|
||||
components?: ComponentName[];
|
||||
development?: { url: string; version: string } | null;
|
||||
}
|
||||
interface StagedScreen {
|
||||
importer: ScreenImporter;
|
||||
options: Readonly<ScreenOptions>;
|
||||
}
|
||||
export interface ExtensionRegistryBatch {
|
||||
closed: boolean;
|
||||
slots: BatchedSlotRegistration[];
|
||||
screens: Map<string, ScreenImporter>;
|
||||
screenOptions: Map<string, ScreenOptions>;
|
||||
screens: Map<string, StagedScreen>;
|
||||
columns: ExtensionTableColumnRegistration[];
|
||||
components: Map<ComponentName, ComponentReplacement<ComponentName>>;
|
||||
}
|
||||
@@ -398,28 +401,39 @@ const emptyColumns: readonly ExtensionTableColumnRegistration[] = Object.freeze(
|
||||
const emptySlots: readonly SlotRegistration[] = Object.freeze([]);
|
||||
const screens: ExtensionScreenRegistration[] = [];
|
||||
export class ExtensionImportError extends Error {}
|
||||
const implementations = new Map<string, LazyExoticComponent<ComponentType<ScreenComponentProps>>>();
|
||||
const screenOptions = new Map<string, Readonly<ScreenOptions>>();
|
||||
const screenImplementations = new Map<
|
||||
string,
|
||||
{ component: LazyExoticComponent<ComponentType<ScreenComponentProps>>; options: Readonly<ScreenOptions> }
|
||||
>();
|
||||
const emptyConfig: ExtensionConfig = Object.freeze({});
|
||||
const componentReplacements = new Map<ComponentName, ComponentReplacement<ComponentName>>();
|
||||
const loadStates = new Map<string, ExtensionRuntimeState>();
|
||||
const states = new Map<string, ExtensionRuntimeState>();
|
||||
/** Failures of mounted extension code, by extension and then by context, the latest last. */
|
||||
const mountErrors = new Map<string, Map<string, string>>();
|
||||
const subscriptions = new Map<string, Set<() => void>>();
|
||||
const listeners = new Set<() => void>();
|
||||
let entries: readonly SiteExtensionEntry[] | undefined;
|
||||
let nextSlotRegistrationId = 1;
|
||||
let stateSnapshot: readonly ExtensionRuntimeState[] = [];
|
||||
|
||||
export function subscribeExtensionRegistry(key: string, listener: () => void): () => void {
|
||||
const listeners = subscriptions.get(key) ?? new Set();
|
||||
/** Every change notifies every listener; each getter returns the same value until its own data changes. */
|
||||
export function subscribeExtensionRegistry(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
subscriptions.set(key, listeners);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (!listeners.size) subscriptions.delete(key);
|
||||
};
|
||||
}
|
||||
function notify(key: string): void {
|
||||
subscriptions.get(key)?.forEach((listener) => listener());
|
||||
export function useExtensionRegistry<T>(read: () => T): T {
|
||||
return useSyncExternalStore(subscribeExtensionRegistry, read);
|
||||
}
|
||||
/** The latest failure of mounted code overrides the load state. */
|
||||
function runtimeState(id: string): ExtensionRuntimeState | undefined {
|
||||
const latest = [...(mountErrors.get(id) ?? [])].at(-1);
|
||||
return latest ? Object.freeze({ id, status: 'failed', error: `${latest[0]}: ${latest[1]}` }) : loadStates.get(id);
|
||||
}
|
||||
function publish(): void {
|
||||
const ids = new Set([...loadStates.keys(), ...mountErrors.keys()]);
|
||||
stateSnapshot = Object.freeze([...ids].flatMap((id) => runtimeState(id) ?? []));
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
export function getExtensionLoadState(id: string): ExtensionRuntimeState | undefined {
|
||||
return loadStates.get(id);
|
||||
@@ -428,11 +442,11 @@ export function getScreenComponent(
|
||||
extensionId: string,
|
||||
screenId: string
|
||||
): LazyExoticComponent<ComponentType<ScreenComponentProps>> | undefined {
|
||||
return implementations.get(`${extensionId}:${screenId}`);
|
||||
return screenImplementations.get(`${extensionId}:${screenId}`)?.component;
|
||||
}
|
||||
/** Undefined until the screen's bundle has loaded. */
|
||||
export function getScreenOptions(extensionId: string, screenId: string): Readonly<ScreenOptions> | undefined {
|
||||
return screenOptions.get(`${extensionId}:${screenId}`);
|
||||
return screenImplementations.get(`${extensionId}:${screenId}`)?.options;
|
||||
}
|
||||
export function getExtensionConfig(extensionId: string): ExtensionConfig {
|
||||
return entries?.find((entry) => entry.id === extensionId)?.config ?? emptyConfig;
|
||||
@@ -449,49 +463,32 @@ export function getComponentReplacement(name: ComponentName): ComponentReplaceme
|
||||
return componentReplacements.get(name);
|
||||
}
|
||||
|
||||
let stateSnapshot: readonly ExtensionRuntimeState[] = [];
|
||||
export function getExtensionStates(): readonly ExtensionRuntimeState[] {
|
||||
return stateSnapshot;
|
||||
}
|
||||
function publishStates(): void {
|
||||
stateSnapshot = Object.freeze([...states.values()]);
|
||||
notify('states');
|
||||
}
|
||||
function refreshExtensionState(extensionId: string): void {
|
||||
const remaining = mountErrors.get(extensionId)?.entries().next().value;
|
||||
if (remaining) {
|
||||
states.set(
|
||||
extensionId,
|
||||
Object.freeze({ id: extensionId, status: 'failed', error: `${remaining[0]}: ${remaining[1]}` })
|
||||
);
|
||||
} else {
|
||||
const state = loadStates.get(extensionId);
|
||||
if (state) states.set(extensionId, state);
|
||||
}
|
||||
}
|
||||
export function setExtensionState(state: ExtensionRuntimeState): void {
|
||||
const snapshot = Object.freeze({ ...state });
|
||||
loadStates.set(state.id, snapshot);
|
||||
refreshExtensionState(state.id);
|
||||
notify(`extension:${state.id}`);
|
||||
publishStates();
|
||||
loadStates.set(state.id, Object.freeze({ ...state }));
|
||||
publish();
|
||||
}
|
||||
/** Records a failure, unless the same one is already recorded for the context; returns its message. */
|
||||
function recordError(extensionId: string, context: string, cause: unknown): string | undefined {
|
||||
const message = cause instanceof Error ? cause.message : String(cause);
|
||||
const errors = mountErrors.get(extensionId) ?? new Map<string, string>();
|
||||
if (errors.get(context) === message) return undefined;
|
||||
console.error(`[extensions] "${extensionId}" failed in ${context}:`, cause);
|
||||
errors.delete(context);
|
||||
errors.set(context, message);
|
||||
mountErrors.set(extensionId, errors);
|
||||
return message;
|
||||
}
|
||||
/** Repeat reports of the same failure in a context are ignored. */
|
||||
export function reportExtensionError(extensionId: string, context: string, cause: unknown): void {
|
||||
const message = cause instanceof Error ? cause.message : String(cause);
|
||||
const errors = mountErrors.get(extensionId) ?? new Map<string, string>();
|
||||
if (errors.get(context) === message && states.get(extensionId)?.status === 'failed') return;
|
||||
console.error(`[extensions] "${extensionId}" failed in ${context}:`, cause);
|
||||
errors.set(context, message);
|
||||
mountErrors.set(extensionId, errors);
|
||||
states.set(extensionId, Object.freeze({ id: extensionId, status: 'failed', error: `${context}: ${message}` }));
|
||||
publishStates();
|
||||
if (recordError(extensionId, context, cause) !== undefined) publish();
|
||||
}
|
||||
export function failExtensionLoad(id: string, context: string, cause: unknown): void {
|
||||
reportExtensionError(id, context, cause);
|
||||
const state = states.get(id)!;
|
||||
loadStates.set(id, state);
|
||||
notify(`extension:${id}`);
|
||||
const message = recordError(id, context, cause) ?? mountErrors.get(id)!.get(context)!;
|
||||
loadStates.set(id, Object.freeze({ id, status: 'failed', error: `${context}: ${message}` }));
|
||||
publish();
|
||||
}
|
||||
|
||||
/** Restrict extension paths to static segments and named parameters, with a static namespace. */
|
||||
@@ -607,71 +604,61 @@ function assertBatchOpen(batch: ExtensionRegistryBatch): void {
|
||||
if (batch.closed) throw new Error('Extension registration batch is closed.');
|
||||
}
|
||||
export function createExtensionRegistryBatch(): ExtensionRegistryBatch {
|
||||
return {
|
||||
closed: false,
|
||||
slots: [],
|
||||
screens: new Map(),
|
||||
screenOptions: new Map(),
|
||||
columns: [],
|
||||
components: new Map(),
|
||||
};
|
||||
return { closed: false, slots: [], screens: new Map(), columns: [], components: new Map() };
|
||||
}
|
||||
function appendSlotRegistration(name: SlotName, registration: SlotRegistration, publish = true): void {
|
||||
/** Keeps registrations in the order the panel advertises their extensions; the sort is stable. */
|
||||
function mergeByEntryOrder<TKey, TItem extends { extensionId: string }>(
|
||||
map: Map<TKey, readonly TItem[]>,
|
||||
key: TKey,
|
||||
added: readonly TItem[]
|
||||
): void {
|
||||
const order = (id: string) => entries?.findIndex((entry) => entry.id === id) ?? 0;
|
||||
slots.set(
|
||||
name,
|
||||
Object.freeze(
|
||||
[...(slots.get(name) ?? []), registration].sort(
|
||||
(a, b) => order(a.extensionId) - order(b.extensionId) || a.id - b.id
|
||||
)
|
||||
)
|
||||
map.set(
|
||||
key,
|
||||
Object.freeze([...(map.get(key) ?? []), ...added].sort((a, b) => order(a.extensionId) - order(b.extensionId)))
|
||||
);
|
||||
if (publish) notify(`slot:${name}`);
|
||||
}
|
||||
|
||||
export function commitExtensionRegistryBatch(extensionId: string, batch: ExtensionRegistryBatch): void {
|
||||
assertBatchOpen(batch);
|
||||
for (const screen of screens.filter((screen) => screen.extensionId === extensionId)) {
|
||||
if (!batch.screens.has(screen.id)) throw new Error(`Missing implementation for screen "${screen.id}"`);
|
||||
if (screen.when?.runtime && !batch.screenOptions.get(screen.id)?.visible) {
|
||||
const staged = batch.screens.get(screen.id);
|
||||
if (!staged) throw new Error(`Missing implementation for screen "${screen.id}"`);
|
||||
if (screen.when?.runtime && !staged.options.visible) {
|
||||
throw new Error(`Missing visibility predicate for screen "${screen.id}"`);
|
||||
}
|
||||
}
|
||||
for (const name of entries?.find((entry) => entry.id === extensionId)?.components ?? []) {
|
||||
if (!batch.components.has(name)) throw new Error(`Missing implementation for component "${name}"`);
|
||||
}
|
||||
const changed = new Set<SlotName>();
|
||||
for (const registration of batch.slots) {
|
||||
appendSlotRegistration(registration.name, registration, false);
|
||||
changed.add(registration.name);
|
||||
batch.closed = true;
|
||||
for (const name of new Set(batch.slots.map((slot) => slot.name))) {
|
||||
mergeByEntryOrder(
|
||||
slots,
|
||||
name,
|
||||
batch.slots.filter((slot) => slot.name === name)
|
||||
);
|
||||
}
|
||||
batch.screens.forEach((importer, id) =>
|
||||
implementations.set(
|
||||
`${extensionId}:${id}`,
|
||||
lazy(() =>
|
||||
for (const name of new Set(batch.columns.map((column) => column.name))) {
|
||||
mergeByEntryOrder(
|
||||
tableColumns,
|
||||
name,
|
||||
batch.columns.filter((column) => column.name === name)
|
||||
);
|
||||
}
|
||||
batch.screens.forEach(({ importer, options }, id) =>
|
||||
screenImplementations.set(`${extensionId}:${id}`, {
|
||||
component: lazy(() =>
|
||||
importer().catch((cause: unknown) => {
|
||||
throw new ExtensionImportError('Unable to load extension screen', { cause });
|
||||
})
|
||||
)
|
||||
)
|
||||
),
|
||||
options,
|
||||
})
|
||||
);
|
||||
batch.screenOptions.forEach((options, id) => screenOptions.set(`${extensionId}:${id}`, options));
|
||||
batch.components.forEach((replacement, name) => componentReplacements.set(name, replacement));
|
||||
batch.closed = true;
|
||||
for (const name of new Set(batch.columns.map((column) => column.name))) {
|
||||
const order = (id: string) => entries?.findIndex((entry) => entry.id === id) ?? 0;
|
||||
tableColumns.set(
|
||||
name,
|
||||
Object.freeze(
|
||||
[...(tableColumns.get(name) ?? []), ...batch.columns.filter((column) => column.name === name)].sort(
|
||||
(a, b) => order(a.extensionId) - order(b.extensionId)
|
||||
)
|
||||
)
|
||||
);
|
||||
notify(`table:${name}`);
|
||||
}
|
||||
setExtensionState({ id: extensionId, status: 'loaded' });
|
||||
changed.forEach((name) => notify(`slot:${name}`));
|
||||
loadStates.set(extensionId, Object.freeze({ id: extensionId, status: 'loaded' }));
|
||||
publish();
|
||||
}
|
||||
|
||||
export function registerComponentReplacement<TName extends ComponentName>(
|
||||
@@ -695,25 +682,17 @@ export function registerComponentReplacement<TName extends ComponentName>(
|
||||
}
|
||||
export function abortExtensionRegistryBatch(batch: ExtensionRegistryBatch): void {
|
||||
assertBatchOpen(batch);
|
||||
batch.slots = [];
|
||||
batch.columns = [];
|
||||
batch.screens.clear();
|
||||
batch.screenOptions.clear();
|
||||
batch.components.clear();
|
||||
batch.closed = true;
|
||||
}
|
||||
export function registerSlotComponent(
|
||||
extensionId: string,
|
||||
name: SlotName,
|
||||
component: ComponentType<SlotComponentProps>,
|
||||
batch?: ExtensionRegistryBatch
|
||||
batch: ExtensionRegistryBatch
|
||||
): void {
|
||||
if (!SLOT_NAMES.includes(name)) throw new Error(`Unknown slot "${name}"`);
|
||||
const registration = Object.freeze({ id: nextSlotRegistrationId++, extensionId, name, component });
|
||||
if (batch) {
|
||||
assertBatchOpen(batch);
|
||||
batch.slots.push(registration);
|
||||
} else appendSlotRegistration(name, registration);
|
||||
assertBatchOpen(batch);
|
||||
batch.slots.push(Object.freeze({ id: nextSlotRegistrationId++, extensionId, name, component }));
|
||||
}
|
||||
export function getSlotComponents(name: SlotName): readonly SlotRegistration[] {
|
||||
return slots.get(name) ?? emptySlots;
|
||||
@@ -752,8 +731,7 @@ export function registerScreen(
|
||||
if (visible && !screen.when?.runtime) {
|
||||
throw new Error(`Screen "${id}" must declare "when": { "runtime": true } to register a visibility predicate.`);
|
||||
}
|
||||
batch.screens.set(id, component);
|
||||
batch.screenOptions.set(id, Object.freeze({ visible, badge }));
|
||||
batch.screens.set(id, { importer: component, options: Object.freeze({ visible, badge }) });
|
||||
}
|
||||
export function getExtensionScreens(area: ScreenArea, parent?: ScreenParent): readonly ExtensionScreenRegistration[] {
|
||||
return screens
|
||||
@@ -762,7 +740,7 @@ export function getExtensionScreens(area: ScreenArea, parent?: ScreenParent): re
|
||||
}
|
||||
export function clearExtensionError(extensionId: string, context: string): void {
|
||||
const errors = mountErrors.get(extensionId);
|
||||
errors?.delete(context);
|
||||
refreshExtensionState(extensionId);
|
||||
publishStates();
|
||||
if (!errors?.delete(context)) return;
|
||||
if (!errors.size) mountErrors.delete(extensionId);
|
||||
publish();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useSyncExternalStore, type FunctionComponent } from 'react';
|
||||
import { type FunctionComponent } from 'react';
|
||||
import { useLocation } from '@tanstack/react-router';
|
||||
import Spinner from '@/components/elements/Spinner';
|
||||
import { NotFound } from '@/components/elements/ScreenBlock';
|
||||
@@ -11,7 +11,7 @@ import { ScreenGate } from './screenNavigation';
|
||||
import {
|
||||
getExtensionLoadState,
|
||||
getScreenComponent,
|
||||
subscribeExtensionRegistry,
|
||||
useExtensionRegistry,
|
||||
type ExtensionScreenRegistration,
|
||||
type ScreenArea,
|
||||
} from '@/extensions/registry';
|
||||
@@ -22,11 +22,7 @@ export function extensionScreenComponent(
|
||||
): FunctionComponent {
|
||||
const { extensionId, id } = registration;
|
||||
function ScreenImplementation() {
|
||||
const subscribe = useCallback(
|
||||
(listener: () => void) => subscribeExtensionRegistry(`extension:${extensionId}`, listener),
|
||||
[]
|
||||
);
|
||||
const state = useSyncExternalStore(subscribe, () => getExtensionLoadState(extensionId));
|
||||
const state = useExtensionRegistry(() => getExtensionLoadState(extensionId));
|
||||
const data = useRouteSlotData();
|
||||
const resource = useCurrentResource();
|
||||
const Lazy = getScreenComponent(extensionId, id);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useMemo, useSyncExternalStore, type ReactNode } from 'react';
|
||||
import { useMemo, type ReactNode } from 'react';
|
||||
import { useLocation } from '@tanstack/react-router';
|
||||
import { useCurrentUser } from '@/api/account/queries';
|
||||
import { useServerQuery } from '@/api/server/queries';
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
getExtensionLoadState,
|
||||
getScreenOptions,
|
||||
matchesScreenCondition,
|
||||
subscribeExtensionRegistry,
|
||||
useExtensionRegistry,
|
||||
type ExtensionScreenRegistration,
|
||||
type ScreenContext,
|
||||
type ScreenOptions,
|
||||
@@ -24,14 +24,6 @@ function useAreaServer(screen: Screen) {
|
||||
return useServerQuery(screen.area === 'server' ? (id ?? '') : '').data;
|
||||
}
|
||||
|
||||
function useExtensionStore<T>(extensionId: string, read: () => T): T {
|
||||
const subscribe = useCallback(
|
||||
(listener: () => void) => subscribeExtensionRegistry(`extension:${extensionId}`, listener),
|
||||
[extensionId]
|
||||
);
|
||||
return useSyncExternalStore(subscribe, read);
|
||||
}
|
||||
|
||||
function useScreenContext(screen: Screen): ScreenContext {
|
||||
const user = useCurrentUser();
|
||||
const server = useAreaServer(screen);
|
||||
@@ -68,8 +60,8 @@ function ConditionalScreen({
|
||||
const { extensionId, id, when } = screen;
|
||||
const server = useAreaServer(screen);
|
||||
const pathname = useLocation({ select: (location) => location.pathname });
|
||||
const visible = useExtensionStore(extensionId, () => getScreenOptions(extensionId, id)?.visible);
|
||||
const failed = useExtensionStore(extensionId, () => getExtensionLoadState(extensionId)?.status === 'failed');
|
||||
const visible = useExtensionRegistry(() => getScreenOptions(extensionId, id)?.visible);
|
||||
const failed = useExtensionRegistry(() => getExtensionLoadState(extensionId)?.status === 'failed');
|
||||
|
||||
if (!matchesScreenCondition(when, server)) return hidden;
|
||||
if (!when?.runtime) return children;
|
||||
@@ -134,7 +126,7 @@ function LiveBadge({
|
||||
function RegisteredBadge({ screen, fallback }: { screen: Screen; fallback: ReactNode }) {
|
||||
const { extensionId, id } = screen;
|
||||
const pathname = useLocation({ select: (location) => location.pathname });
|
||||
const badge = useExtensionStore(extensionId, () => getScreenOptions(extensionId, id)?.badge);
|
||||
const badge = useExtensionRegistry(() => getScreenOptions(extensionId, id)?.badge);
|
||||
if (!badge) return fallback;
|
||||
return (
|
||||
<ExtensionMount
|
||||
|
||||
@@ -1,19 +1,14 @@
|
||||
import { useCallback, useMemo, useSyncExternalStore } from 'react';
|
||||
import { useMemo } from 'react';
|
||||
import type { ColumnDef } from '@tanstack/react-table';
|
||||
import ExtensionMount from './ExtensionMount';
|
||||
import { getExtensionTableColumns, subscribeExtensionRegistry } from './registry';
|
||||
import { getExtensionTableColumns, useExtensionRegistry } from './registry';
|
||||
|
||||
import type { ExtensionTableName, ExtensionTableRows } from './tableTypes';
|
||||
|
||||
export function useExtensionTableColumns<TName extends ExtensionTableName>(
|
||||
name: TName
|
||||
): ColumnDef<ExtensionTableRows[TName]>[] {
|
||||
const subscribe = useCallback(
|
||||
(changed: () => void) => subscribeExtensionRegistry(`table:${name}`, changed),
|
||||
[name]
|
||||
);
|
||||
const snapshot = useCallback(() => getExtensionTableColumns(name), [name]);
|
||||
const columns = useSyncExternalStore(subscribe, snapshot);
|
||||
const columns = useExtensionRegistry(() => getExtensionTableColumns(name));
|
||||
return useMemo(
|
||||
() =>
|
||||
columns.map(({ id, label, extensionId, component: Component }) => ({
|
||||
|
||||
Reference in New Issue
Block a user