From b516dc36467ee71fd3bc7749e24453dfd6be2382 Mon Sep 17 00:00:00 2001
From: robert dennis <31261583+robertdrakedennis@users.noreply.github.com>
Date: Wed, 7 Oct 2026 17:24:38 -0400
Subject: [PATCH] registry cleanup
---
packages/sdk/types/extensions/registry.d.ts | 13 +-
.../admin/extensions/ExtensionsContainer.tsx | 8 +-
resources/scripts/extensions/Slot.spec.tsx | 39 ++--
resources/scripts/extensions/Slot.tsx | 10 +-
.../scripts/extensions/componentSession.tsx | 2 +-
resources/scripts/extensions/loader.spec.ts | 1 -
resources/scripts/extensions/registry.spec.ts | 48 +++--
resources/scripts/extensions/registry.ts | 198 ++++++++----------
resources/scripts/extensions/screen.tsx | 10 +-
.../scripts/extensions/screenNavigation.tsx | 18 +-
resources/scripts/extensions/tableColumns.tsx | 11 +-
11 files changed, 175 insertions(+), 183 deletions(-)
diff --git a/packages/sdk/types/extensions/registry.d.ts b/packages/sdk/types/extensions/registry.d.ts
index e89d59623..65163f4e4 100644
--- a/packages/sdk/types/extensions/registry.d.ts
+++ b/packages/sdk/types/extensions/registry.d.ts
@@ -178,11 +178,14 @@ export interface SiteExtensionEntry {
version: string;
} | null;
}
+interface StagedScreen {
+ importer: ScreenImporter;
+ options: Readonly;
+}
export interface ExtensionRegistryBatch {
closed: boolean;
slots: BatchedSlotRegistration[];
- screens: Map;
- screenOptions: Map;
+ screens: Map;
columns: ExtensionTableColumnRegistration[];
components: Map>;
}
@@ -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(read: () => T): T;
export declare function getExtensionLoadState(id: string): ExtensionRuntimeState | undefined;
export declare function getScreenComponent(extensionId: string, screenId: string): LazyExoticComponent> | 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(extensionId: string, name: TName, replacement: ComponentReplacement, batch: ExtensionRegistryBatch): void;
export declare function abortExtensionRegistryBatch(batch: ExtensionRegistryBatch): void;
-export declare function registerSlotComponent(extensionId: string, name: SlotName, component: ComponentType, batch?: ExtensionRegistryBatch): void;
+export declare function registerSlotComponent(extensionId: string, name: SlotName, component: ComponentType, 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[];
diff --git a/resources/scripts/components/admin/extensions/ExtensionsContainer.tsx b/resources/scripts/components/admin/extensions/ExtensionsContainer.tsx
index b3b9d3644..8c21a9412 100644
--- a/resources/scripts/components/admin/extensions/ExtensionsContainer.tsx
+++ b/resources/scripts/components/admin/extensions/ExtensionsContainer.tsx
@@ -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;
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 ?? [];
diff --git a/resources/scripts/extensions/Slot.spec.tsx b/resources/scripts/extensions/Slot.spec.tsx
index 815d74d3d..c6ea9e544 100644
--- a/resources/scripts/extensions/Slot.spec.tsx
+++ b/resources/scripts/extensions/Slot.spec.tsx
@@ -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
+) {
+ 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) => first:{(data as { pathname: string }).pathname};
const Second = ({ data }: SlotComponentProps) => second:{(data as { pathname: string }).pathname};
- 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();
@@ -39,8 +52,8 @@ describe('extension Slot', () => {
};
const Healthy = () => healthy extension;
- 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();
@@ -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', () => healthy sibling);
+ registerSlot(registry, 'lazy', 'dashboard.after', Lazy);
+ registerSlot(registry, 'healthy', 'dashboard.after', () => healthy sibling);
render(
whole page waiting
}>
@@ -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 {data};
}
- registry.registerSlotComponent('query', 'account.overview.before', QuerySlot);
+ registerSlot(registry, 'query', 'account.overview.before', QuerySlot);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
@@ -109,10 +122,10 @@ it('shows late registrations without resetting healthy mod state', async () => {
const [count, setCount] = useState(0);
return ;
}
- registry.registerSlotComponent('counter', 'account.overview.after', Counter);
+ registerSlot(registry, 'counter', 'account.overview.after', Counter);
render();
fireEvent.click(screen.getByRole('button', { name: 'Count 0' }));
- act(() => registry.registerSlotComponent('late', 'account.overview.after', () => late arrival));
+ act(() => registerSlot(registry, 'late', 'account.overview.after', () => late arrival));
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 row ready;
});
diff --git a/resources/scripts/extensions/Slot.tsx b/resources/scripts/extensions/Slot.tsx
index 03d6ec7ea..e3a3c3281 100644
--- a/resources/scripts/extensions/Slot.tsx
+++ b/resources/scripts/extensions/Slot.tsx
@@ -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}`
diff --git a/resources/scripts/extensions/componentSession.tsx b/resources/scripts/extensions/componentSession.tsx
index 235cfffcb..414952c9b 100644
--- a/resources/scripts/extensions/componentSession.tsx
+++ b/resources/scripts/extensions/componentSession.tsx
@@ -98,7 +98,7 @@ export function createComponentSession() {
}
};
pending.set(name, stop);
- unsubscribe = subscribeExtensionRegistry(`extension:${extensionId}`, check);
+ unsubscribe = subscribeExtensionRegistry(check);
check();
};
return {
diff --git a/resources/scripts/extensions/loader.spec.ts b/resources/scripts/extensions/loader.spec.ts
index 6bc660975..0418319be 100644
--- a/resources/scripts/extensions/loader.spec.ts
+++ b/resources/scripts/extensions/loader.spec.ts
@@ -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'
);
diff --git a/resources/scripts/extensions/registry.spec.ts b/resources/scripts/extensions/registry.spec.ts
index 7881118d2..71acbfd75 100644
--- a/resources/scripts/extensions/registry.spec.ts
+++ b/resources/scripts/extensions/registry.spec.ts
@@ -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 });
diff --git a/resources/scripts/extensions/registry.ts b/resources/scripts/extensions/registry.ts
index 8921207b3..5948aae4f 100644
--- a/resources/scripts/extensions/registry.ts
+++ b/resources/scripts/extensions/registry.ts
@@ -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;
+}
export interface ExtensionRegistryBatch {
closed: boolean;
slots: BatchedSlotRegistration[];
- screens: Map;
- screenOptions: Map;
+ screens: Map;
columns: ExtensionTableColumnRegistration[];
components: Map>;
}
@@ -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>>();
-const screenOptions = new Map>();
+const screenImplementations = new Map<
+ string,
+ { component: LazyExoticComponent>; options: Readonly }
+>();
const emptyConfig: ExtensionConfig = Object.freeze({});
const componentReplacements = new Map>();
const loadStates = new Map();
-const states = new Map();
+/** Failures of mounted extension code, by extension and then by context, the latest last. */
const mountErrors = new Map>();
-const subscriptions = new Map 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(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> | 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 | 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();
+ 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();
- 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(
+ map: Map,
+ 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();
- 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(
@@ -695,25 +682,17 @@ export function registerComponentReplacement(
}
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,
- 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();
}
diff --git a/resources/scripts/extensions/screen.tsx b/resources/scripts/extensions/screen.tsx
index eb2ababc3..a31e5f983 100644
--- a/resources/scripts/extensions/screen.tsx
+++ b/resources/scripts/extensions/screen.tsx
@@ -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);
diff --git a/resources/scripts/extensions/screenNavigation.tsx b/resources/scripts/extensions/screenNavigation.tsx
index 3ca1f0068..8568cd17f 100644
--- a/resources/scripts/extensions/screenNavigation.tsx
+++ b/resources/scripts/extensions/screenNavigation.tsx
@@ -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(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 (
(
name: TName
): ColumnDef[] {
- 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 }) => ({