feat(plugin): add plugin framework workflow

This commit is contained in:
t8y2 authored and GitHub committed 2026-09-13 10:39:17 +08:00
1 parent 3767f4a83b
commit b5072f1a3e
247 files changed
+33841 -2256

No files matched your search

+330
View File
@@ -0,0 +1,330 @@
import { describe, expect, it } from "vitest";
import type { InstalledPlugin, PluginConnectionProviderContribution } from "@/types/database";
import { buildPluginConnectionConfig, createFrontendPluginRegistry, initialPluginFormValues, parsePluginConnectionProviderOptionValue, pluginConnectionActionsForDialog, pluginConnectionFormValues, pluginConnectionProviderIcon, pluginConnectionProviderOptionValue } from "./frontendPlugin";
function installedPlugin(id: string, contributions: InstalledPlugin["manifest"]["contributions"] = []): InstalledPlugin {
return {
compatibility: { compatible: true },
manifest: {
id,
name: id,
version: "1.0.0",
drivers: [],
contributions,
},
};
}
function connectionProvider(overrides: Partial<PluginConnectionProviderContribution> = {}): PluginConnectionProviderContribution {
return {
type: "connection-provider",
id: "connection",
label: "Example",
database_type: "example",
fields: [
{ key: "host", label: "Host", type: "text", required: true },
{ key: "port", label: "Port", type: "number", default: 1234 },
{ key: "tls", label: "TLS", type: "boolean", default: false },
],
...overrides,
};
}
describe("FrontendPluginRegistry", () => {
it("round-trips plugin connection provider picker values", () => {
const value = pluginConnectionProviderOptionValue("example/plugin", "ssh:main");
expect(parsePluginConnectionProviderOptionValue(value)).toEqual({ pluginId: "example/plugin", providerId: "ssh:main" });
expect(parsePluginConnectionProviderOptionValue("mysql")).toBeNull();
});
it("indexes declarative connection providers", () => {
const registry = createFrontendPluginRegistry([installedPlugin("com.example.plugin", [connectionProvider()])]);
expect(registry.listConnectionProviders()).toHaveLength(1);
expect(registry.listConnectionProviders()[0]?.contribution.database_type).toBe("example");
});
it("indexes workbench, connection provider, and filesystem contributions", () => {
const registry = createFrontendPluginRegistry([
installedPlugin("com.example.plugin", [
{
type: "connection-provider",
id: "example.connection",
label: "Example",
database_type: "example",
fields: [],
workbench: "example.main",
filesystem_provider: "example.files",
},
{ type: "workbench", id: "example.main", label: "Example Workbench" },
{ type: "filesystem-provider", id: "example.files", label: "Example Files", schemes: ["example"], root_uri: "example:/home", capabilities: ["read", "write"] },
]),
]);
expect(registry.listConnectionProviders()).toHaveLength(1);
expect(registry.listWorkbenches()[0]?.contribution.id).toBe("example.main");
expect(registry.listFilesystemProviders()[0]?.contribution.schemes).toEqual(["example"]);
expect(registry.listFilesystemProviders()[0]?.contribution.root_uri).toBe("example:/home");
expect(registry.listConnectionProviders()[0]?.contribution.filesystem_provider).toBe("example.files");
});
it("indexes result-view contributions", () => {
const registry = createFrontendPluginRegistry([installedPlugin("com.example.plugin", [{ type: "result-view", id: "example.graph", label: "Graph" }])]);
const views = registry.listResultViews();
expect(views).toHaveLength(1);
expect(views[0]?.contribution.id).toBe("example.graph");
expect(views[0]?.contribution.label).toBe("Graph");
});
it("indexes context-menu contributions per menu surface", () => {
const registry = createFrontendPluginRegistry([
installedPlugin("com.example.plugin", [
{ type: "context-menu", id: "example.inspect", label: "Inspect endpoint", menu: "connection" },
{ type: "context-menu", id: "example.other", label: "Wrong surface", menu: "tree" },
]),
]);
const items = registry.listContextMenuItems("connection");
expect(items).toHaveLength(1);
expect(items[0]?.contribution.id).toBe("example.inspect");
expect(items[0]?.plugin.manifest.id).toBe("com.example.plugin");
expect(registry.listContextMenuItems("tree")).toHaveLength(1);
expect(registry.listContextMenuItems("missing")).toHaveLength(0);
});
it("prefers provider display metadata and falls back to plugin metadata", () => {
const explicit = installedPlugin("com.example.explicit", [
{
type: "connection-provider",
id: "explicit.connection",
label: "Explicit connection",
icon: "assets/provider.svg",
database_type: "explicit",
fields: [],
},
]);
explicit.manifest.name = "Explicit plugin";
explicit.manifest.icon = "assets/plugin.svg";
const fallback = installedPlugin("com.example.fallback", [
{
type: "connection-provider",
id: "fallback.connection",
label: "",
database_type: "fallback",
fields: [],
},
]);
fallback.manifest.name = "Fallback plugin";
fallback.manifest.icon = "assets/fallback.svg";
const registry = createFrontendPluginRegistry([explicit, fallback]);
const [explicitEntry, fallbackEntry] = registry.listConnectionProviders();
expect(explicitEntry?.contribution.label).toBe("Explicit connection");
expect(pluginConnectionProviderIcon(explicitEntry!)).toBe("assets/provider.svg");
expect(fallbackEntry?.contribution.label).toBe("Fallback plugin");
expect(pluginConnectionProviderIcon(fallbackEntry!)).toBe("assets/fallback.svg");
});
it("falls back to provider id and the generic icon when metadata is absent", () => {
const plugin = installedPlugin("com.example.minimal", [
{
type: "connection-provider",
id: "minimal.connection",
label: "",
database_type: "minimal",
fields: [],
},
]);
plugin.manifest.name = "";
const entry = createFrontendPluginRegistry([plugin]).listConnectionProviders()[0]!;
expect(entry.contribution.label).toBe("minimal.connection");
expect(pluginConnectionProviderIcon(entry)).toBeUndefined();
});
it("drops unsafe icon paths before rendering", () => {
const plugin = installedPlugin("com.example.unsafe", [
{
type: "connection-provider",
id: "unsafe.connection",
label: "Unsafe",
icon: "../outside.svg",
database_type: "unsafe",
fields: [],
},
]);
plugin.manifest.icon = "\\outside.svg";
const definition = createFrontendPluginRegistry([plugin]).listPlugins()[0]!;
const entry = createFrontendPluginRegistry([plugin]).listConnectionProviders()[0]!;
expect(definition.plugin.manifest.icon).toBeUndefined();
expect(pluginConnectionProviderIcon(entry)).toBeUndefined();
});
it("localizes plugin metadata, contributions, and form fields", () => {
const plugin = installedPlugin("com.example.plugin", [connectionProvider({ id: "example.connection", description: "English description" })]);
plugin.manifest.localizations = {
"zh-CN": {
name: "示例插件",
description: "插件说明",
contributions: {
"example.connection": {
label: "示例连接",
description: "连接说明",
fields: {
host: { label: "主机", placeholder: "请输入主机" },
},
},
},
},
};
const registry = createFrontendPluginRegistry([plugin], "zh-CN");
const definition = registry.listPlugins()[0]!;
const contribution = registry.listConnectionProviders()[0]!.contribution;
expect(definition.plugin.manifest.name).toBe("示例插件");
expect(definition.plugin.manifest.description).toBe("插件说明");
expect(contribution.label).toBe("示例连接");
expect(contribution.description).toBe("连接说明");
expect(contribution.fields[0]).toMatchObject({ label: "主机", placeholder: "请输入主机" });
expect(plugin.manifest.name).toBe("com.example.plugin");
});
it("normalizes connection actions in manifest order and localizes their labels", () => {
const plugin = installedPlugin("com.example.actions", [
{
type: "connection-provider",
id: "example.connection",
label: "Example",
database_type: "example",
fields: [],
capabilities: ["test"],
actions: [
{
id: "discover",
label: "Discover",
description: "Discover an endpoint",
variant: "outline",
requires_valid_form: false,
},
{ id: "edit", label: "Edit", variant: "secondary", when: "edit" },
],
},
]);
plugin.manifest.localizations = {
"zh-CN": {
contributions: {
"example.connection": {
actions: {
discover: { label: "发现地址", description: "自动发现连接地址" },
},
},
},
},
};
const actions = createFrontendPluginRegistry([plugin], "zh-CN").listConnectionProviders()[0]?.contribution.actions;
expect(actions?.map((action) => action.id)).toEqual(["discover", "edit"]);
expect(actions?.[0]).toMatchObject({
label: "发现地址",
description: "自动发现连接地址",
requires_valid_form: false,
});
expect(actions?.[1]).toMatchObject({ label: "Edit", variant: "secondary", when: "edit" });
});
it("treats omitted and explicitly empty custom action lists equivalently", () => {
const registry = createFrontendPluginRegistry([
installedPlugin("com.example.defaults", [{ type: "connection-provider", id: "default.connection", label: "Default", database_type: "default", fields: [] }]),
installedPlugin("com.example.empty", [{ type: "connection-provider", id: "empty.connection", label: "Empty", database_type: "empty", fields: [], actions: [] }]),
]);
const [defaults, empty] = registry.listConnectionProviders();
expect(defaults?.contribution.actions).toBeUndefined();
expect(empty?.contribution.actions).toEqual([]);
expect(pluginConnectionActionsForDialog(defaults!.contribution, false)).toEqual(pluginConnectionActionsForDialog(empty!.contribution, false));
});
it("builds compatible default footer actions and filters create/edit actions", () => {
const provider: PluginConnectionProviderContribution = {
type: "connection-provider",
id: "example.connection",
label: "Example",
database_type: "example",
fields: [],
capabilities: ["test"],
};
expect(pluginConnectionActionsForDialog(provider, false).map((action) => action.kind)).toEqual(["test", "save-and-connect"]);
expect(pluginConnectionActionsForDialog(provider, true).map((action) => action.kind)).toEqual(["test", "save"]);
expect(
pluginConnectionActionsForDialog(
{
...provider,
actions: [
{ id: "create", label: "Create", when: "create" },
{ id: "edit", label: "Edit", when: "edit" },
{ id: "always", label: "Always", when: "always" },
],
},
true,
).map((action) => action.id),
).toEqual(["edit", "always", "test", "save"]);
});
it("creates initial values only from declared defaults", () => {
const values = initialPluginFormValues(connectionProvider());
expect(values).toEqual({ port: 1234, tls: false });
expect(values).not.toHaveProperty("host");
});
it("maps provider fields into common, config, and secret storage", () => {
const provider: PluginConnectionProviderContribution = {
type: "connection-provider",
id: "example.ssh",
label: "SSH",
database_type: "ssh",
fields: [
{ key: "display_name", label: "Name", type: "text", binding: "name" },
{ key: "host", label: "Host", type: "text", binding: "host" },
{ key: "port", label: "Port", type: "number", binding: "port", default: 22 },
{ key: "private_key", label: "Private key", type: "password" },
{ key: "keepalive", label: "Keepalive", type: "boolean", default: true },
],
};
const config = buildPluginConnectionConfig("example.plugin", provider, {
display_name: "Production SSH",
host: "example.com",
port: 2222,
private_key: "secret-key",
keepalive: false,
});
expect(config).toMatchObject({
name: "Production SSH",
db_type: "plugin",
host: "example.com",
port: 2222,
plugin_id: "example.plugin",
plugin_connection_provider: "example.ssh",
plugin_connection_type: "ssh",
external_config: { keepalive: false },
connection_secrets: { private_key: "secret-key" },
});
expect(pluginConnectionFormValues(provider, config)).toMatchObject({
display_name: "Production SSH",
host: "example.com",
port: 2222,
private_key: "secret-key",
keepalive: false,
});
});
});
@@ -0,0 +1,302 @@
import type {
ConnectionConfig,
InstalledPlugin,
PluginConnectionAction,
PluginConnectionProviderContribution,
PluginContribution,
PluginContributionLocalization,
PluginContextMenuContribution,
PluginResultViewContribution,
PluginFilesystemProviderContribution,
PluginFormField,
PluginFormFieldLocalization,
PluginFormFieldValue,
PluginManifestLocalization,
PluginWorkbenchContribution,
} from "@/types/database";
import { uuid } from "@/lib/common/utils";
import { clonePluginData } from "./pluginData";
const PLUGIN_CONNECTION_PROVIDER_OPTION_PREFIX = "plugin-provider:";
export interface FrontendPluginDefinition {
plugin: InstalledPlugin;
contributions: PluginContribution[];
diagnostics: string[];
}
export interface PluginContributionEntry<T extends PluginContribution> {
plugin: InstalledPlugin;
contribution: T;
}
export class FrontendPluginRegistry {
private readonly definitions: FrontendPluginDefinition[];
constructor(plugins: readonly InstalledPlugin[] = [], locale = "en") {
this.definitions = plugins.map((plugin) => normalizeFrontendPlugin(plugin, locale));
}
listPlugins(): FrontendPluginDefinition[] {
return [...this.definitions];
}
findPlugin(pluginId: string): FrontendPluginDefinition | undefined {
return this.definitions.find((definition) => definition.plugin.manifest.id === pluginId);
}
listConnectionProviders(): PluginContributionEntry<PluginConnectionProviderContribution>[] {
return this.listContributions("connection-provider");
}
listWorkbenches(): PluginContributionEntry<PluginWorkbenchContribution>[] {
return this.listContributions("workbench");
}
listFilesystemProviders(): PluginContributionEntry<PluginFilesystemProviderContribution>[] {
return this.listContributions("filesystem-provider");
}
/** Native context-menu entries declared for a specific menu surface such as `connection`. */
listContextMenuItems(menu: string): PluginContributionEntry<PluginContextMenuContribution>[] {
return this.listContributions("context-menu").filter((entry) => entry.contribution.menu === menu);
}
/** Plugin-rendered query-result views offered from the results toolbar. */
listResultViews(): PluginContributionEntry<PluginResultViewContribution>[] {
return this.listContributions("result-view");
}
findWorkbench(pluginId: string, contributionId: string): PluginContributionEntry<PluginWorkbenchContribution> | undefined {
return this.listWorkbenches().find((entry) => entry.plugin.manifest.id === pluginId && entry.contribution.id === contributionId);
}
private listContributions<T extends PluginContribution["type"]>(type: T): Array<PluginContributionEntry<Extract<PluginContribution, { type: T }>>> {
return this.definitions
.filter((definition) => definition.plugin.compatibility.compatible)
.flatMap((definition) => definition.contributions.filter((contribution): contribution is Extract<PluginContribution, { type: T }> => contribution.type === type).map((contribution) => ({ plugin: definition.plugin, contribution })))
.sort((left, right) => `${left.plugin.manifest.name}:${left.contribution.label || left.contribution.id}`.localeCompare(`${right.plugin.manifest.name}:${right.contribution.label || right.contribution.id}`));
}
}
export function createFrontendPluginRegistry(plugins: readonly InstalledPlugin[], locale = "en"): FrontendPluginRegistry {
return new FrontendPluginRegistry(plugins, locale);
}
export function pluginConnectionProviderOptionValue(pluginId: string, providerId: string): string {
return `${PLUGIN_CONNECTION_PROVIDER_OPTION_PREFIX}${encodeURIComponent(pluginId)}/${encodeURIComponent(providerId)}`;
}
export function parsePluginConnectionProviderOptionValue(value: string): { pluginId: string; providerId: string } | null {
if (!value.startsWith(PLUGIN_CONNECTION_PROVIDER_OPTION_PREFIX)) return null;
const encoded = value.slice(PLUGIN_CONNECTION_PROVIDER_OPTION_PREFIX.length);
const separator = encoded.indexOf("/");
if (separator <= 0 || separator === encoded.length - 1) return null;
try {
const pluginId = decodeURIComponent(encoded.slice(0, separator));
const providerId = decodeURIComponent(encoded.slice(separator + 1));
return pluginId && providerId ? { pluginId, providerId } : null;
} catch {
return null;
}
}
export function pluginConnectionProviderIcon(entry: PluginContributionEntry<PluginConnectionProviderContribution>): string | undefined {
return entry.contribution.icon || entry.plugin.manifest.icon;
}
export function pluginConnectionActionsForDialog(contribution: PluginConnectionProviderContribution, editing: boolean): PluginConnectionAction[] {
const actions: PluginConnectionAction[] = [
...(contribution.actions || []).map((action) => ({ ...action, kind: "custom" as const })),
...((contribution.capabilities || []).includes("test") ? [{ id: "test", kind: "test" as const, variant: "outline" as const }] : []),
editing ? ({ id: "save", kind: "save", variant: "default", close_on_success: true } satisfies PluginConnectionAction) : ({ id: "save-and-connect", kind: "save-and-connect", variant: "default", close_on_success: true } satisfies PluginConnectionAction),
];
return actions.filter((action) => action.when === undefined || action.when === "always" || (action.when === "edit" ? editing : !editing));
}
export function initialPluginFormValues(contribution: PluginConnectionProviderContribution): Record<string, PluginFormFieldValue> {
return Object.fromEntries(contribution.fields.filter((field) => field.default !== undefined).map((field) => [field.key, field.default])) as Record<string, PluginFormFieldValue>;
}
export function pluginConnectionFormValues(contribution: PluginConnectionProviderContribution, config?: ConnectionConfig): Record<string, PluginFormFieldValue> {
const values = initialPluginFormValues(contribution);
if (!config) return values;
const externalConfig = isRecord(config.external_config) ? config.external_config : {};
const secrets = config.connection_secrets || {};
for (const field of contribution.fields) {
const binding = effectiveFieldBinding(field);
const value =
binding === "name"
? config.name
: binding === "host"
? config.host
: binding === "port"
? config.port
: binding === "username"
? config.username
: binding === "password"
? config.password
: binding === "database"
? config.database
: binding === "secret"
? secrets[field.key]
: externalConfig[field.key];
if (isPluginFormFieldValue(value)) values[field.key] = value;
}
return values;
}
export function buildPluginConnectionConfig(pluginId: string, contribution: PluginConnectionProviderContribution, values: Record<string, PluginFormFieldValue>, existing?: ConnectionConfig): ConnectionConfig {
const externalConfig: Record<string, unknown> = isRecord(existing?.external_config) ? clonePluginData(existing.external_config) : {};
const connectionSecrets = { ...existing?.connection_secrets };
const config: ConnectionConfig = {
id: existing?.id || uuid(),
name: existing?.name || contribution.label,
note: existing?.note,
db_type: "plugin",
driver_profile: existing?.driver_profile || "plugin",
driver_label: contribution.label,
host: existing?.host || "",
port: existing?.port || 0,
username: existing?.username || "",
password: existing?.password || "",
database: existing?.database,
external_config: externalConfig,
plugin_id: pluginId,
plugin_connection_provider: contribution.id,
plugin_connection_type: contribution.database_type,
connection_secrets: connectionSecrets,
transport_layers: existing?.transport_layers || [],
connect_timeout_secs: existing?.connect_timeout_secs || 10,
query_timeout_secs: existing?.query_timeout_secs || 60,
idle_timeout_secs: existing?.idle_timeout_secs || 60,
keepalive_interval_secs: existing?.keepalive_interval_secs || 30,
read_only: existing?.read_only || false,
is_production: existing?.is_production || false,
production_databases: existing?.production_databases || [],
};
for (const field of contribution.fields) {
const value = values[field.key] ?? field.default;
const binding = effectiveFieldBinding(field);
if (binding === "config") {
if (value === undefined) delete externalConfig[field.key];
else externalConfig[field.key] = value;
} else if (binding === "secret") {
if (value === undefined || value === "") delete connectionSecrets[field.key];
else connectionSecrets[field.key] = String(value);
} else if (binding === "name") {
config.name = String(value || contribution.label);
} else if (binding === "host") {
config.host = String(value || "");
} else if (binding === "port") {
config.port = typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.min(65535, Math.trunc(value))) : 0;
} else if (binding === "username") {
config.username = String(value || "");
} else if (binding === "password") {
config.password = String(value || "");
} else if (binding === "database") {
config.database = value === undefined || value === "" ? undefined : String(value);
}
}
return config;
}
function effectiveFieldBinding(field: PluginFormField): NonNullable<PluginFormField["binding"]> {
return field.binding || (field.type === "password" ? "secret" : "config");
}
function normalizeFrontendPlugin(plugin: InstalledPlugin, locale: string): FrontendPluginDefinition {
const localization = pluginLocalization(plugin, locale);
const localizedPlugin = localizePluginMetadata(plugin, localization);
const contributions = (localizedPlugin.manifest.contributions || []).map((contribution) => localizeContribution(contribution, localization?.contributions?.[contribution.id], localizedPlugin.manifest.name));
const diagnostics: string[] = [];
if (!plugin.compatibility.compatible) diagnostics.push(...(plugin.compatibility.errors || []));
return { plugin: localizedPlugin, contributions, diagnostics };
}
function pluginLocalization(plugin: InstalledPlugin, locale: string): PluginManifestLocalization | undefined {
const localizations = plugin.manifest.localizations;
if (!localizations || !locale) return undefined;
const normalizedLocale = locale.replace("_", "-").toLowerCase();
const exact = Object.entries(localizations).find(([key]) => key.replace("_", "-").toLowerCase() === normalizedLocale)?.[1];
if (exact) return exact;
const language = normalizedLocale.split("-")[0];
return Object.entries(localizations).find(([key]) => key.replace("_", "-").toLowerCase() === language)?.[1];
}
function localizePluginMetadata(plugin: InstalledPlugin, localization?: PluginManifestLocalization): InstalledPlugin {
return {
...plugin,
manifest: {
...plugin.manifest,
name: localizedRequiredText(plugin.manifest.name, localization?.name),
icon: optionalPluginAssetPath(plugin.manifest.icon),
description: localizedOptionalText(plugin.manifest.description, localization?.description),
},
};
}
function localizeContribution(contribution: PluginContribution, localization: PluginContributionLocalization | undefined, pluginName: string): PluginContribution {
const fallbackLabel = contribution.type === "connection-provider" ? optionalTrimmed(contribution.label) || optionalTrimmed(pluginName) || contribution.id : contribution.label;
const localized = {
...contribution,
label: localizedRequiredText(fallbackLabel, localization?.label),
description: localizedOptionalText(contribution.description, localization?.description),
} as PluginContribution;
if (localized.type === "connection-provider") {
localized.icon = optionalPluginAssetPath(localized.icon);
localized.fields = localized.fields.map((field) => localizeField(field, localization?.fields?.[field.key]));
localized.actions = localized.actions?.map((action) => ({
...action,
label: localizedRequiredText(action.label, localization?.actions?.[action.id]?.label),
description: localizedOptionalText(action.description, localization?.actions?.[action.id]?.description),
}));
} else if (localized.type === "workbench") {
localized.icon = optionalPluginAssetPath(localized.icon);
}
return localized;
}
function localizeField(field: PluginFormField, localization?: PluginFormFieldLocalization): PluginFormField {
if (!localization) return field;
return {
...field,
label: localizedRequiredText(field.label, localization.label),
description: localizedOptionalText(field.description, localization.description),
placeholder: localizedOptionalText(field.placeholder, localization.placeholder),
options: field.options?.map((option) => ({ ...option, label: localizedRequiredText(option.label, localization.options?.[option.value]) })),
};
}
function localizedRequiredText(fallback: string, localized: unknown): string {
return nonEmptyString(localized) ? localized.trim() : fallback;
}
function localizedOptionalText(fallback: string | undefined, localized: unknown): string | undefined {
return typeof localized === "string" ? localized.trim() : fallback;
}
function optionalTrimmed(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const trimmed = value.trim();
return trimmed || undefined;
}
function optionalPluginAssetPath(value: unknown): string | undefined {
const path = optionalTrimmed(value);
if (!path || path.startsWith("/") || path.startsWith("\\") || path.includes("\\")) return undefined;
const parts = path.split("/");
return parts.some((part) => !part || part === "." || part === "..") ? undefined : path;
}
function nonEmptyString(value: unknown): value is string {
return typeof value === "string" && value.trim().length > 0;
}
function isPluginFormFieldValue(value: unknown): value is PluginFormFieldValue {
return value === undefined || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
}
function isRecord(value: unknown): value is Record<string, any> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -0,0 +1,4 @@
export interface PluginCenterFocus {
pluginId?: string;
providerId?: string;
}
+103
View File
@@ -0,0 +1,103 @@
import { isProxy, toRaw } from "vue";
export const MAX_PLUGIN_WORKBENCH_CONTEXT_BYTES = 2 * 1024 * 1024;
export function clonePluginData<T>(value: T): T {
const unwrapped = unwrapVueProxies(value);
try {
if (typeof structuredClone === "function") return structuredClone(unwrapped);
return JSON.parse(JSON.stringify(unwrapped)) as T;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Plugin data cannot be cloned: ${message}`);
}
}
export function snapshotPluginWorkbenchContext<T extends object>(value: T): T {
const snapshot = snapshotValue(value, "context", new WeakSet<object>());
if (!snapshot || Array.isArray(snapshot) || typeof snapshot !== "object") {
throw new Error("Plugin workbench context must be an object");
}
const size = new TextEncoder().encode(JSON.stringify(snapshot)).byteLength;
if (size > MAX_PLUGIN_WORKBENCH_CONTEXT_BYTES) {
throw new Error(`Plugin workbench context exceeds ${MAX_PLUGIN_WORKBENCH_CONTEXT_BYTES} bytes`);
}
return snapshot as T;
}
type PluginContextValue = boolean | number | string | null | PluginContextValue[] | { [key: string]: PluginContextValue } | undefined;
function snapshotValue(value: unknown, path: string, ancestors: WeakSet<object>): PluginContextValue {
if (value === undefined) return undefined;
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
if (typeof value === "number") {
if (Number.isFinite(value)) return value;
throw new Error(`Plugin workbench context contains a non-finite number at ${path}`);
}
if (typeof value !== "object") throw new Error(`Plugin workbench context contains an unsupported value at ${path}`);
const raw = isProxy(value) ? toRaw(value) : value;
if (ancestors.has(raw)) throw new Error(`Plugin workbench context contains a circular reference at ${path}`);
const prototype = Object.getPrototypeOf(raw);
if (!Array.isArray(raw) && prototype !== Object.prototype && prototype !== null) {
throw new Error(`Plugin workbench context requires plain data at ${path}`);
}
ancestors.add(raw);
try {
if (Array.isArray(raw)) {
return raw.map((item, index) => snapshotValue(item, `${path}[${index}]`, ancestors) ?? null);
}
const result: { [key: string]: PluginContextValue } = {};
for (const [key, item] of Object.entries(raw)) {
const snapshot = snapshotValue(item, `${path}.${key}`, ancestors);
if (snapshot !== undefined) result[key] = snapshot;
}
return result;
} finally {
ancestors.delete(raw);
}
}
function unwrapVueProxies<T>(value: T, seen = new WeakMap<object, unknown>()): T {
const rawValue = isProxy(value) ? toRaw(value) : value;
if (!rawValue || typeof rawValue !== "object") return rawValue;
const object = rawValue as object;
const existing = seen.get(object);
if (existing) return existing as T;
if (rawValue instanceof Date || rawValue instanceof RegExp || rawValue instanceof ArrayBuffer || ArrayBuffer.isView(rawValue)) {
return rawValue;
}
if (Array.isArray(rawValue)) {
const result: unknown[] = [];
seen.set(object, result);
rawValue.forEach((item, index) => {
result[index] = unwrapVueProxies(item, seen);
});
return result as T;
}
if (rawValue instanceof Map) {
const result = new Map<unknown, unknown>();
seen.set(object, result);
rawValue.forEach((item, key) => result.set(unwrapVueProxies(key, seen), unwrapVueProxies(item, seen)));
return result as T;
}
if (rawValue instanceof Set) {
const result = new Set<unknown>();
seen.set(object, result);
rawValue.forEach((item) => result.add(unwrapVueProxies(item, seen)));
return result as T;
}
const prototype = Object.getPrototypeOf(rawValue);
if (prototype !== Object.prototype && prototype !== null) return rawValue;
const result = Object.create(prototype) as Record<PropertyKey, unknown>;
seen.set(object, result);
for (const key of Reflect.ownKeys(rawValue)) {
const descriptor = Object.getOwnPropertyDescriptor(rawValue, key);
if (!descriptor || !("value" in descriptor)) continue;
Object.defineProperty(result, key, { ...descriptor, value: unwrapVueProxies(descriptor.value, seen) });
}
return result as T;
}
+37
View File
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { pluginFilesystemParentUri, pluginFilesystemRootUri, sortPluginFilesystemEntries, uniquePluginFilesystemEntries } from "./pluginFilesystem";
describe("plugin filesystem navigation", () => {
it("derives a default root from the first declared scheme", () => {
expect(pluginFilesystemRootUri({ schemes: ["sftp"] })).toBe("sftp:/");
expect(pluginFilesystemRootUri({ schemes: ["s3"], root_uri: "s3://bucket/" })).toBe("s3://bucket/");
});
it("keeps parent navigation inside the declared root", () => {
expect(pluginFilesystemParentUri("sftp:/home/user/files/", "sftp:/")).toBe("sftp:/home/user/");
expect(pluginFilesystemParentUri("s3://bucket/reports/2026/", "s3://bucket/")).toBe("s3://bucket/reports/");
expect(pluginFilesystemParentUri("s3://bucket/reports/", "s3://bucket/reports/")).toBeUndefined();
});
it("sorts directories before naturally ordered files", () => {
const sorted = sortPluginFilesystemEntries([
{ name: "file10.txt", uri: "sample:/file10.txt", kind: "file" },
{ name: "folder", uri: "sample:/folder/", kind: "directory" },
{ name: "file2.txt", uri: "sample:/file2.txt", kind: "file" },
]);
expect(sorted.map((entry) => entry.name)).toEqual(["folder", "file2.txt", "file10.txt"]);
});
it("removes duplicate entries by URI while preserving the latest metadata", () => {
expect(
uniquePluginFilesystemEntries([
{ name: "object.txt", uri: "s3:/object.txt", kind: "file", size: 1 },
{ name: "object.txt", uri: "s3:/object.txt", kind: "file", size: 2 },
{ name: "other.txt", uri: "s3:/other.txt", kind: "file" },
]),
).toEqual([
{ name: "object.txt", uri: "s3:/object.txt", kind: "file", size: 2 },
{ name: "other.txt", uri: "s3:/other.txt", kind: "file" },
]);
});
});
@@ -0,0 +1,34 @@
import type { PluginFilesystemEntry, PluginFilesystemProviderContribution } from "@/types/database";
export function pluginFilesystemRootUri(provider: Pick<PluginFilesystemProviderContribution, "root_uri" | "schemes">): string {
return provider.root_uri || `${provider.schemes[0]}:/`;
}
export function pluginFilesystemParentUri(uri: string, root: string): string | undefined {
if (!uri || uri === root) return undefined;
const schemeEnd = uri.indexOf(":");
if (schemeEnd < 1) return root;
const minimumEnd = uri.startsWith("//", schemeEnd + 1)
? (() => {
const authorityEnd = uri.indexOf("/", schemeEnd + 3);
return authorityEnd < 0 ? uri.length : authorityEnd + 1;
})()
: schemeEnd + 2;
const normalized = uri.endsWith("/") && uri.length > minimumEnd ? uri.slice(0, -1) : uri;
const separator = normalized.lastIndexOf("/");
const parent = separator < minimumEnd ? uri.slice(0, minimumEnd) : uri.slice(0, separator + 1);
return parent.length < root.length ? root : parent;
}
export function sortPluginFilesystemEntries(entries: readonly PluginFilesystemEntry[]): PluginFilesystemEntry[] {
return [...entries].sort((left, right) => {
const leftDirectory = left.kind === "directory";
const rightDirectory = right.kind === "directory";
if (leftDirectory !== rightDirectory) return leftDirectory ? -1 : 1;
return left.name.localeCompare(right.name, undefined, { numeric: true, sensitivity: "base" });
});
}
export function uniquePluginFilesystemEntries(entries: readonly PluginFilesystemEntry[]): PluginFilesystemEntry[] {
return [...new Map(entries.map((entry) => [entry.uri, entry])).values()];
}
+321
View File
@@ -0,0 +1,321 @@
import { describe, expect, it, vi } from "vitest";
import { reactive, readonly } from "vue";
import { PluginHostBridge, pluginSandboxDocument } from "./pluginHostBridge";
import type { InstalledPlugin, PluginWorkbenchContribution } from "@/types/database";
function plugin(permissions: string[] = []): InstalledPlugin {
return {
manifest: { id: "sample", name: "Sample", version: "1.0.0", permissions, drivers: [], contributions: [] },
compatibility: { compatible: true },
};
}
const workbench: PluginWorkbenchContribution = { type: "workbench", id: "sample.main", label: "Sample" };
describe("PluginHostBridge", () => {
it("binds backend calls to the owning plugin identity", async () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const invoke = vi.fn().mockResolvedValue({ ok: true });
const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
invoke,
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
});
expect(
bridge.handleWindowMessage({
source: target,
data: { source: "dbx-plugin", version: 1, type: "request", id: "1", method: "backend.invoke", params: { method: "sample/hello", params: { name: "DBX" } } },
} as MessageEvent),
).toBe(true);
await vi.waitFor(() => expect(messages).toHaveLength(1));
expect(invoke).toHaveBeenCalledWith("sample", "sample/hello", { name: "DBX" }, undefined);
expect(messages[0]).toMatchObject({ source: "dbx-host", type: "response", id: "1", result: { ok: true } });
});
it("sends the current DBX locale in the init message", () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const bridge = new PluginHostBridge(
plugin(),
workbench,
{ connectionId: "connection" },
() => target,
{
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
},
"zh-CN",
);
bridge.sendInit();
expect(messages[0]).toMatchObject({ source: "dbx-host", type: "init", locale: "zh-CN", context: { connectionId: "connection" } });
});
it("snapshots nested Vue reactive context values before sending them to the plugin", () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const context = {
connectionId: "connection",
values: reactive({ path: "/tmp", options: readonly({ recursive: true }) }),
};
const bridge = new PluginHostBridge(plugin(), workbench, context, () => target, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
});
bridge.sendInit();
expect(messages[0]).toMatchObject({
type: "init",
context: { connectionId: "connection", values: { path: "/tmp", options: { recursive: true } } },
});
expect((messages[0] as { context: typeof context }).context).not.toBe(context);
});
it("reports unsupported plugin context values", () => {
expect(
() =>
new PluginHostBridge(plugin(), workbench, { value: () => undefined }, () => null, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
}),
).toThrow("Plugin workbench context contains an unsupported value");
});
it("rejects circular and oversized plugin contexts", () => {
const circular: Record<string, unknown> = {};
circular.self = circular;
expect(
() =>
new PluginHostBridge(plugin(), workbench, circular, () => null, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
}),
).toThrow("circular reference");
expect(
() =>
new PluginHostBridge(plugin(), workbench, { value: "x".repeat(2 * 1024 * 1024) }, () => null, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
}),
).toThrow("exceeds");
});
it("rejects privileged host calls without manifest permission", async () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
openWorkbench: vi.fn(),
});
bridge.handleWindowMessage({
source: target,
data: { source: "dbx-plugin", version: 1, type: "request", id: "2", method: "host.openWorkbench", params: { contributionId: "sample.other" } },
} as MessageEvent);
await vi.waitFor(() => expect(messages).toHaveLength(1));
expect(messages[0]).toMatchObject({ id: "2", error: "Plugin has not declared permission 'host.workbench'" });
});
it("opens only the owning plugin filesystem with explicit permission", async () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const openFilesystem = vi.fn();
const bridge = new PluginHostBridge(plugin(["host.filesystem"]), workbench, {}, () => target, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
openFilesystem,
});
bridge.handleWindowMessage({
source: target,
data: {
source: "dbx-plugin",
version: 1,
type: "request",
id: "filesystem",
method: "host.openFilesystem",
params: { providerId: "sample.files", context: { connectionId: "connection" } },
},
} as MessageEvent);
await vi.waitFor(() => expect(messages).toHaveLength(1));
expect(openFilesystem).toHaveBeenCalledWith("sample", "sample.files", { connectionId: "connection" });
expect(messages[0]).toMatchObject({ id: "filesystem", result: null });
});
it("forwards events and binary traffic only with declared permissions", async () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const sendBinary = vi.fn().mockResolvedValue(undefined);
const bridge = new PluginHostBridge(plugin(["host.events", "host.binary"]), workbench, {}, () => target, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary,
readAsset: vi.fn(),
});
bridge.forwardEvent({ pluginId: "sample", method: "sample/progress", params: { value: 50 } });
bridge.forwardBinary({ pluginId: "sample", channel: "pty", dataBase64: "AQI=" });
bridge.handleWindowMessage({
source: target,
data: { source: "dbx-plugin", version: 1, type: "request", id: "3", method: "backend.sendBinary", params: { channel: "pty", dataBase64: "AQI=" } },
} as MessageEvent);
await vi.waitFor(() => expect(messages).toHaveLength(3));
expect(messages[0]).toMatchObject({ type: "event", method: "sample/progress" });
expect(messages[1]).toMatchObject({ type: "binary", channel: "pty" });
expect(sendBinary).toHaveBeenCalledWith("sample", "pty", "AQI=");
expect(messages[2]).toMatchObject({ type: "response", id: "3", result: null });
});
it("returns delayed responses to the iframe that issued the request", async () => {
const firstMessages: unknown[] = [];
const secondMessages: unknown[] = [];
const first = { postMessage: (message: unknown) => firstMessages.push(message) } as unknown as Window;
const second = { postMessage: (message: unknown) => secondMessages.push(message) } as unknown as Window;
let current = first;
let resolveInvoke: (value: unknown) => void = () => {};
const invoke = vi.fn().mockImplementation(
() =>
new Promise((resolve) => {
resolveInvoke = resolve;
}),
);
const bridge = new PluginHostBridge(plugin(), workbench, {}, () => current, {
invoke,
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
});
bridge.handleWindowMessage({
source: first,
data: { source: "dbx-plugin", version: 1, type: "request", id: "4", method: "backend.invoke", params: { method: "sample/slow" } },
} as MessageEvent);
current = second;
resolveInvoke({ ok: true });
await vi.waitFor(() => expect(firstMessages).toHaveLength(1));
expect(firstMessages[0]).toMatchObject({ type: "response", id: "4", result: { ok: true } });
expect(secondMessages).toHaveLength(0);
});
it("pushes context and locale updates without rebuilding the iframe", async () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const bridge = new PluginHostBridge(plugin(), workbench, { connectionId: "first" }, () => target, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
});
bridge.updateContext({ connectionId: "second", values: { path: "/tmp" } });
bridge.updateLocale("ja");
expect(messages[0]).toMatchObject({ source: "dbx-host", type: "context", context: { connectionId: "second" } });
expect(messages[1]).toMatchObject({ source: "dbx-host", type: "env", locale: "ja" });
bridge.handleWindowMessage({ source: target, data: { source: "dbx-plugin", version: 1, type: "request", id: "ctx", method: "host.getContext" } } as MessageEvent);
await vi.waitFor(() => expect(messages).toHaveLength(3));
expect(messages[2]).toMatchObject({ type: "response", id: "ctx", result: { connectionId: "second", values: { path: "/tmp" } } });
});
it("accepts zero-copy binary requests and forwards binary frames as raw buffers", async () => {
const messages: unknown[] = [];
const target = {
postMessage: (message: unknown, _origin?: string, _transfer?: Transferable[]) => messages.push(message),
} as unknown as Window;
const sendBinary = vi.fn().mockResolvedValue(undefined);
const bridge = new PluginHostBridge(plugin(["host.binary"]), workbench, {}, () => target, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary,
readAsset: vi.fn(),
});
bridge.forwardBinary({ pluginId: "sample", channel: "pty", dataBase64: "AQID" });
expect(messages[0]).toMatchObject({ type: "binary", channel: "pty" });
expect((messages[0] as { data: ArrayBuffer }).data).toBeInstanceOf(ArrayBuffer);
expect(Array.from(new Uint8Array((messages[0] as { data: ArrayBuffer }).data))).toEqual([1, 2, 3]);
const bytes = new Uint8Array([4, 5, 6]).buffer;
bridge.handleWindowMessage({
source: target,
data: { source: "dbx-plugin", version: 1, type: "request", id: "bin", method: "backend.sendBinary", params: { channel: "pty" }, data: bytes },
} as MessageEvent);
await vi.waitFor(() => expect(messages).toHaveLength(2));
expect(sendBinary).toHaveBeenCalledWith("sample", "pty", "BAUG");
expect(messages[1]).toMatchObject({ type: "response", id: "bin", result: null });
});
it("rejects binary transfer requests without the host.binary permission", async () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, {
invoke: vi.fn(),
notify: vi.fn(),
sendBinary: vi.fn(),
readAsset: vi.fn(),
});
bridge.handleWindowMessage({
source: target,
data: { source: "dbx-plugin", version: 1, type: "request", id: "denied", method: "backend.sendBinary", params: { channel: "pty" }, data: new Uint8Array([1]).buffer },
} as MessageEvent);
await vi.waitFor(() => expect(messages).toHaveLength(1));
expect(messages[0]).toMatchObject({ id: "denied", error: "Plugin has not declared permission 'host.binary'" });
});
it("injects the SDK, the official UI kit, and a restrictive sandbox CSP", () => {
const document = pluginSandboxDocument("<html><head></head><body>Hello</body></html>");
expect(document).toContain("window.dbxPlugin");
expect(document).toContain("get locale() { return locale; }");
expect(document).toContain("openFilesystem");
expect(document).toContain("connect-src 'none'");
expect(document).toContain(".dbx-btn");
expect(document).toContain("var(--color-background");
});
it("opens connect-src only for declared host.network origins", () => {
const allowed = pluginSandboxDocument("<html><head></head><body></body></html>", ["host.events", "host.network:https://api.vendor.com", "host.network:https://metrics.vendor.com:8443", "host.network:http://insecure.vendor.com", "host.network:https://evil.vendor.com/path"]);
expect(allowed).toContain("connect-src https://api.vendor.com https://metrics.vendor.com:8443;");
expect(allowed).not.toContain("insecure.vendor.com");
expect(allowed).not.toContain("evil.vendor.com");
const closed = pluginSandboxDocument("<html><head></head><body></body></html>", ["host.events"]);
expect(closed).toContain("connect-src 'none';");
});
it("sends the theme in init and pushes theme updates through env messages", () => {
const messages: unknown[] = [];
const target = { postMessage: (message: unknown) => messages.push(message) } as unknown as Window;
const theme = { appearance: "dark" as const, tokens: { "--color-background": "#09090b" } };
const bridge = new PluginHostBridge(plugin(), workbench, {}, () => target, { invoke: vi.fn(), notify: vi.fn(), sendBinary: vi.fn(), readAsset: vi.fn() }, "en", theme);
bridge.sendInit();
expect(messages[0]).toMatchObject({ type: "init", theme: { appearance: "dark", tokens: { "--color-background": "#09090b" } } });
bridge.updateTheme({ appearance: "light", tokens: {} });
expect(messages[1]).toMatchObject({ type: "env", locale: "en", theme: { appearance: "light" } });
});
});
@@ -0,0 +1,457 @@
import type { InstalledPlugin, PluginBinaryEvent, PluginEvent, PluginUiAssetPayload, PluginWorkbenchContribution } from "@/types/database";
import { clonePluginData, snapshotPluginWorkbenchContext } from "./pluginData";
const PLUGIN_MESSAGE_SOURCE = "dbx-plugin";
const HOST_MESSAGE_SOURCE = "dbx-host";
const BRIDGE_VERSION = 1;
const MAX_BRIDGE_PAYLOAD_BYTES = 2 * 1024 * 1024;
const MAX_BRIDGE_BINARY_BYTES = 8 * 1024 * 1024;
export interface PluginBridgeTheme {
appearance: "light" | "dark";
/** Resolved DBX design tokens (`--color-*`, `--radius-*`, ...) for the current theme. */
tokens: Record<string, string>;
}
export interface PluginWorkbenchContext {
connectionId?: string;
database?: string;
schema?: string;
values?: Record<string, unknown>;
[key: string]: unknown;
}
export interface PluginHostBridgeApi {
invoke<T = unknown>(pluginId: string, method: string, params?: unknown, timeoutMs?: number): Promise<T>;
notify(pluginId: string, method: string, params?: unknown): Promise<void>;
sendBinary(pluginId: string, channel: string, dataBase64: string): Promise<void>;
readAsset(pluginId: string, path: string): Promise<PluginUiAssetPayload>;
openWorkbench?(pluginId: string, contributionId: string, context?: PluginWorkbenchContext): Promise<void> | void;
openFilesystem?(pluginId: string, providerId: string, context?: PluginWorkbenchContext): Promise<void> | void;
}
interface PluginRequestMessage {
source: typeof PLUGIN_MESSAGE_SOURCE;
version: typeof BRIDGE_VERSION;
type: "request";
id: string;
method: string;
params?: unknown;
/** Optional zero-copy binary payload transferred with the request. */
data?: ArrayBuffer;
}
export class PluginHostBridge {
private context: PluginWorkbenchContext;
private locale: string;
private theme?: PluginBridgeTheme;
constructor(
private readonly plugin: InstalledPlugin,
private readonly workbench: PluginWorkbenchContribution,
context: PluginWorkbenchContext,
private readonly targetWindow: () => Window | null,
private readonly api: PluginHostBridgeApi,
locale = "en",
theme?: PluginBridgeTheme,
) {
this.context = snapshotPluginWorkbenchContext(context);
this.locale = locale;
this.theme = theme ? clonePluginData(theme) : undefined;
}
handleWindowMessage(event: MessageEvent): boolean {
const target = this.targetWindow();
if (!target || event.source !== target || !isRecord(event.data)) return false;
if (event.data.source !== PLUGIN_MESSAGE_SOURCE || event.data.version !== BRIDGE_VERSION) return false;
if (event.data.type === "ready") {
this.sendInit();
return true;
}
if (event.data.type !== "request" || !validRequestMessage(event.data)) return false;
void this.handleRequest(event.data, target);
return true;
}
sendInit(): void {
this.post({
source: HOST_MESSAGE_SOURCE,
version: BRIDGE_VERSION,
type: "init",
pluginId: this.plugin.manifest.id,
contributionId: this.workbench.id,
locale: this.locale,
theme: this.theme ? clonePluginData(this.theme) : undefined,
permissions: [...(this.plugin.manifest.permissions || [])],
context: snapshotPluginWorkbenchContext(this.context),
});
}
/**
* Push a new workbench context into the already-loaded plugin UI instead of
* rebuilding the iframe. Identity changes (plugin/contribution) still require
* a full reload; context-only changes must not lose plugin state.
*/
updateContext(context: PluginWorkbenchContext): void {
this.context = snapshotPluginWorkbenchContext(context);
this.post({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "context", context: snapshotPluginWorkbenchContext(this.context) });
}
/** Notify the plugin UI about a locale change without a reload. */
updateLocale(locale: string): void {
this.locale = locale;
this.post({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "env", locale });
}
/** Push resolved theme tokens so the plugin UI can follow DBX light/dark and palette changes. */
updateTheme(theme: PluginBridgeTheme): void {
this.theme = clonePluginData(theme);
this.post({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "env", locale: this.locale, theme: this.theme });
}
forwardEvent(event: PluginEvent): void {
if (event.pluginId !== this.plugin.manifest.id || !this.hasPermission("host.events")) return;
this.post({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "event", method: event.method, params: event.params });
}
forwardBinary(event: PluginBinaryEvent): void {
if (event.pluginId !== this.plugin.manifest.id || !this.hasPermission("host.binary")) return;
const target = this.targetWindow();
if (!target) return;
const buffer = base64ToBytes(event.dataBase64);
target.postMessage({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "binary", channel: event.channel, data: buffer }, "*", [buffer]);
}
private async handleRequest(request: PluginRequestMessage, target: Window): Promise<void> {
try {
enforcePayloadLimit(request.params);
const result = await this.dispatch(request.method, request.params, request.data);
this.respond(target, request.id, { result: result ?? null });
} catch (error) {
this.respond(target, request.id, { error: error instanceof Error ? error.message : String(error) });
}
}
private async dispatch(method: string, params: unknown, binary?: ArrayBuffer): Promise<unknown> {
if (method === "host.getContext") return snapshotPluginWorkbenchContext(this.context);
if (method === "backend.invoke") {
const input = requireRecord(params, "backend.invoke params");
const backendMethod = requireProtocolName(input.method, "backend method");
const timeoutMs = input.timeoutMs === undefined ? undefined : requireTimeout(input.timeoutMs);
return this.api.invoke(this.plugin.manifest.id, backendMethod, input.params ?? null, timeoutMs);
}
if (method === "backend.notify") {
const input = requireRecord(params, "backend.notify params");
await this.api.notify(this.plugin.manifest.id, requireProtocolName(input.method, "backend method"), input.params ?? null);
return null;
}
if (method === "backend.sendBinary") {
this.requirePermission("host.binary");
const input = requireRecord(params, "backend.sendBinary params");
const channel = requireProtocolName(input.channel, "binary channel");
if (binary instanceof ArrayBuffer) {
if (binary.byteLength > MAX_BRIDGE_BINARY_BYTES) throw new Error("Plugin binary payload exceeds 8 MiB; chunk the transfer");
await this.api.sendBinary(this.plugin.manifest.id, channel, bytesToBase64(new Uint8Array(binary)));
return null;
}
await this.api.sendBinary(this.plugin.manifest.id, channel, requireBase64(input.dataBase64));
return null;
}
if (method === "ui.readAsset") {
const input = requireRecord(params, "ui.readAsset params");
return this.api.readAsset(this.plugin.manifest.id, requireSafeAssetPath(input.path));
}
if (method === "host.openWorkbench") {
this.requirePermission("host.workbench");
if (!this.api.openWorkbench) throw new Error("Host workbench navigation is unavailable");
const input = requireRecord(params, "host.openWorkbench params");
await this.api.openWorkbench(this.plugin.manifest.id, requireProtocolName(input.contributionId, "workbench contribution"), isRecord(input.context) ? input.context : undefined);
return null;
}
if (method === "host.openFilesystem") {
this.requirePermission("host.filesystem");
if (!this.api.openFilesystem) throw new Error("Host filesystem navigation is unavailable");
const input = requireRecord(params, "host.openFilesystem params");
await this.api.openFilesystem(this.plugin.manifest.id, requireProtocolName(input.providerId, "filesystem provider"), isRecord(input.context) ? input.context : undefined);
return null;
}
throw new Error(`Unsupported plugin host method '${method}'`);
}
private requirePermission(permission: string): void {
if (!this.hasPermission(permission)) throw new Error(`Plugin has not declared permission '${permission}'`);
}
private hasPermission(permission: string): boolean {
return (this.plugin.manifest.permissions || []).includes(permission);
}
private respond(target: Window, id: string, payload: { result?: unknown; error?: string }): void {
target.postMessage({ source: HOST_MESSAGE_SOURCE, version: BRIDGE_VERSION, type: "response", id, ...payload }, "*");
}
private post(message: Record<string, unknown>): void {
this.targetWindow()?.postMessage(message, "*");
}
}
/**
* Parse `host.network:<origin>` permission entries into CSP connect-src
* origins. Must stay aligned with `parse_host_network_permission` in
* crates/dbx-core/src/plugins/manifest.rs.
*/
export function pluginNetworkOrigins(permissions: readonly string[] | undefined): string[] {
const origins = new Set<string>();
for (const permission of permissions || []) {
if (!permission.startsWith("host.network:")) continue;
const origin = permission.slice("host.network:".length);
if (!/^https:\/\/[A-Za-z0-9._-]+(?::[0-9]+)?$/.test(origin)) continue;
origins.add(origin);
if (origins.size >= 8) break;
}
return [...origins];
}
export function pluginSandboxDocument(html: string, permissions?: readonly string[]): string {
const networkOrigins = pluginNetworkOrigins(permissions);
const connectSrc = networkOrigins.length > 0 ? `connect-src ${networkOrigins.join(" ")};` : "connect-src 'none';";
const csp = `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' blob:; style-src 'unsafe-inline' blob:; img-src data: blob:; font-src data: blob:; ${connectSrc} media-src data: blob:;">`;
const sdk = `<script>${pluginSdkSource()}</script>`;
const uiKit = `<style>${pluginUiKitCss()}</style>`;
const injection = `${csp}${uiKit}${sdk}`;
if (/<head(?:\s[^>]*)?>/i.test(html)) return html.replace(/<head(?:\s[^>]*)?>/i, (head) => `${head}${injection}`);
return `<!doctype html><html><head>${injection}</head><body>${html}</body></html>`;
}
/**
* Minimal official component kit for plugin workbenches. Every class is built
* on the DBX design tokens the host pushes through the bridge, so plugin UI
* follows light/dark and palette changes without any plugin-side logic.
*/
export function pluginUiKitCss(): string {
return `
:root { color-scheme: light dark; }
* { box-sizing: border-box; }
body {
margin: 0;
font-family: var(--font-sans, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif);
font-size: 13px;
line-height: 1.5;
color: var(--color-foreground, #18181b);
background: var(--color-background, #ffffff);
}
.dbx-card {
border: 1px solid var(--color-border, #e4e4e7);
border-radius: var(--radius-lg, 10px);
background: var(--color-card, #ffffff);
padding: 14px 16px;
}
.dbx-section-title {
font-size: 11px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--color-muted-foreground, #71717a);
margin: 0 0 10px;
}
.dbx-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 6px;
height: 30px;
padding: 0 12px;
border-radius: var(--radius-md, 8px);
border: 1px solid var(--color-border, #d4d4d8);
background: var(--color-background, #ffffff);
color: var(--color-foreground, #18181b);
font-size: 13px;
cursor: pointer;
}
.dbx-btn:hover { background: var(--color-muted, #f4f4f5); }
.dbx-btn--primary { background: var(--color-primary, #2563eb); border-color: var(--color-primary, #2563eb); color: var(--color-primary-foreground, #ffffff); }
.dbx-btn--primary:hover { background: var(--color-primary, #2563eb); opacity: 0.9; }
.dbx-btn--danger { background: var(--color-destructive, #dc2626); border-color: var(--color-destructive, #dc2626); color: var(--color-destructive-foreground, #ffffff); }
.dbx-btn--ghost { border-color: transparent; background: transparent; }
.dbx-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.dbx-label { display: inline-flex; font-size: 12px; font-weight: 500; color: var(--color-foreground, #18181b); }
.dbx-input, .dbx-select, .dbx-textarea {
width: 100%;
height: 30px;
padding: 0 10px;
border-radius: var(--radius-md, 8px);
border: 1px solid var(--color-input, #d4d4d8);
background: var(--color-background, #ffffff);
color: var(--color-foreground, #18181b);
font-size: 13px;
font-family: inherit;
}
.dbx-textarea { height: auto; min-height: 64px; padding: 6px 10px; resize: vertical; }
.dbx-input:focus, .dbx-select:focus, .dbx-textarea:focus { outline: 2px solid var(--color-ring, #93c5fd); outline-offset: 1px; border-color: var(--color-ring, #93c5fd); }
.dbx-hint { font-size: 12px; color: var(--color-muted-foreground, #71717a); }
.dbx-row { display: grid; grid-template-columns: minmax(96px, auto) minmax(0, 1fr); gap: 8px 12px; align-items: center; margin-bottom: 10px; }
.dbx-table { width: 100%; border-collapse: collapse; font-size: 12px; }
.dbx-table th { text-align: left; font-weight: 600; color: var(--color-muted-foreground, #71717a); border-bottom: 1px solid var(--color-border, #e4e4e7); padding: 6px 8px; }
.dbx-table td { border-bottom: 1px solid var(--color-border, #e4e4e7); padding: 6px 8px; }
.dbx-badge { display: inline-flex; align-items: center; height: 20px; padding: 0 8px; border-radius: 999px; background: var(--color-primary-alpha, rgba(37, 99, 235, 0.12)); color: var(--color-primary, #2563eb); font-size: 11px; font-weight: 500; }
.dbx-link { color: var(--color-primary, #2563eb); text-decoration: none; cursor: pointer; }
.dbx-link:hover { text-decoration: underline; }
`.trim();
}
function pluginSdkSource(): string {
return `(() => {
const pending = new Map();
const listeners = { event: new Set(), binary: new Set(), init: new Set(), context: new Set() };
let sequence = 0;
let context;
let locale = 'en';
let theme;
let resolveReady;
const applyTheme = (value) => {
if (!value || typeof value !== 'object') return;
theme = value;
const root = document.documentElement;
root.dataset.dbxTheme = value.appearance === 'dark' ? 'dark' : 'light';
const tokens = value.tokens && typeof value.tokens === 'object' ? value.tokens : {};
for (const [name, tokenValue] of Object.entries(tokens)) {
if (/^--[a-z0-9-]+$/i.test(name) && typeof tokenValue === 'string') root.style.setProperty(name, tokenValue);
}
};
const ready = new Promise((resolve) => { resolveReady = resolve; });
const request = (method, params, options = {}) => new Promise((resolve, reject) => {
const id = String(++sequence);
pending.set(id, { resolve, reject });
const message = { source: '${PLUGIN_MESSAGE_SOURCE}', version: ${BRIDGE_VERSION}, type: 'request', id, method, params };
if (options.transfer) {
message.data = options.transfer;
parent.postMessage(message, '*', [options.transfer]);
} else {
parent.postMessage(message, '*');
}
});
const decode = (value) => Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
const encode = (value) => {
const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary);
};
window.dbxPlugin = Object.freeze({
ready,
get context() { return context; },
get locale() { return locale; },
get theme() { return theme; },
request,
invoke: (method, params, options = {}) => request('backend.invoke', { method, params, timeoutMs: options.timeoutMs }),
notify: (method, params) => request('backend.notify', { method, params }),
sendBinary: (channel, data) => {
if (typeof data === 'string') return request('backend.sendBinary', { channel, dataBase64: data });
const bytes = data instanceof ArrayBuffer ? data : (data instanceof Uint8Array ? data.buffer : new Uint8Array(data).buffer);
return request('backend.sendBinary', { channel }, { transfer: bytes });
},
readAsset: (path) => request('ui.readAsset', { path }),
readAssetUrl: async (path) => {
const asset = await request('ui.readAsset', { path });
return URL.createObjectURL(new Blob([decode(asset.dataBase64)], { type: asset.contentType }));
},
openWorkbench: (contributionId, childContext) => request('host.openWorkbench', { contributionId, context: childContext }),
openFilesystem: (providerId, childContext) => request('host.openFilesystem', { providerId, context: childContext }),
onEvent: (listener) => { listeners.event.add(listener); return () => listeners.event.delete(listener); },
onBinary: (listener) => { listeners.binary.add(listener); return () => listeners.binary.delete(listener); },
onContext: (listener) => { listeners.context.add(listener); return () => listeners.context.delete(listener); },
onInit: (listener) => { listeners.init.add(listener); if (context !== undefined) listener(context); return () => listeners.init.delete(listener); },
decodeBase64: decode,
encodeBase64: encode,
});
addEventListener('message', (event) => {
if (event.source !== parent || !event.data || event.data.source !== '${HOST_MESSAGE_SOURCE}' || event.data.version !== ${BRIDGE_VERSION}) return;
const message = event.data;
if (message.type === 'response') {
const handler = pending.get(message.id);
if (!handler) return;
pending.delete(message.id);
if (message.error) handler.reject(new Error(message.error)); else handler.resolve(message.result);
} else if (message.type === 'init') {
context = message.context;
locale = typeof message.locale === 'string' ? message.locale : 'en';
applyTheme(message.theme);
resolveReady(context);
listeners.init.forEach((listener) => listener(context));
dispatchEvent(new CustomEvent('dbx-plugin-init', { detail: message }));
} else if (message.type === 'context') {
context = message.context;
listeners.context.forEach((listener) => listener(context));
dispatchEvent(new CustomEvent('dbx-plugin-context', { detail: context }));
} else if (message.type === 'env') {
if (typeof message.locale === 'string') locale = message.locale;
if (message.theme) applyTheme(message.theme);
listeners.event.forEach((listener) => listener(message));
dispatchEvent(new CustomEvent('dbx-plugin-env', { detail: message }));
} else if (message.type === 'event') {
listeners.event.forEach((listener) => listener(message));
dispatchEvent(new CustomEvent('dbx-plugin-event', { detail: message }));
} else if (message.type === 'binary') {
const payload = { channel: message.channel, data: message.data ? new Uint8Array(message.data) : new Uint8Array(0) };
listeners.binary.forEach((listener) => listener(payload));
dispatchEvent(new CustomEvent('dbx-plugin-binary', { detail: payload }));
}
});
parent.postMessage({ source: '${PLUGIN_MESSAGE_SOURCE}', version: ${BRIDGE_VERSION}, type: 'ready' }, '*');
})();`;
}
function validRequestMessage(value: Record<string, unknown>): value is Record<string, unknown> & PluginRequestMessage {
return typeof value.id === "string" && value.id.length > 0 && value.id.length <= 128 && typeof value.method === "string" && value.method.length > 0 && value.method.length <= 128;
}
function requireRecord(value: unknown, label: string): Record<string, unknown> {
if (!isRecord(value)) throw new Error(`${label} must be an object`);
return value;
}
function requireProtocolName(value: unknown, label: string): string {
if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/.test(value)) throw new Error(`${label} is invalid`);
return value;
}
function requireTimeout(value: unknown): number {
if (typeof value !== "number" || !Number.isFinite(value)) throw new Error("timeoutMs must be a number");
return Math.min(120_000, Math.max(1, Math.round(value)));
}
function base64ToBytes(value: string): ArrayBuffer {
const binary = atob(value);
const bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
return bytes.buffer;
}
function bytesToBase64(bytes: Uint8Array): string {
let binary = "";
const chunkSize = 0x8000;
for (let offset = 0; offset < bytes.length; offset += chunkSize) {
binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
}
return btoa(binary);
}
function requireBase64(value: unknown): string {
if (typeof value !== "string" || value.length > MAX_BRIDGE_PAYLOAD_BYTES * 2 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) throw new Error("Binary payload must be base64");
return value;
}
function requireSafeAssetPath(value: unknown): string {
if (typeof value !== "string" || !value || value.startsWith("/") || value.split("/").some((part) => !part || part === "." || part === "..")) throw new Error("Plugin asset path is invalid");
return value;
}
function enforcePayloadLimit(value: unknown): void {
if (value === undefined) return;
const bytes = new TextEncoder().encode(JSON.stringify(value)).byteLength;
if (bytes > MAX_BRIDGE_PAYLOAD_BYTES) throw new Error("Plugin bridge request is too large");
}
function isRecord(value: unknown): value is Record<string, any> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+84
View File
@@ -0,0 +1,84 @@
import { describe, expect, it } from "vitest";
import { buildMarketplacePluginListings, filterMarketplacePluginListings, selectMarketplaceArtifact } from "./pluginMarketplace";
import type { InstalledPlugin, PluginRepositoryCatalogResult } from "@/types/database";
const result: PluginRepositoryCatalogResult = {
repository: { id: "dbx-official", name: "DBX Marketplace", kind: "official", enabled: true, managed: true },
target: "darwin-arm64",
catalog: {
catalogVersion: 1,
repository: { id: "dbx-official", name: "DBX Marketplace" },
plugins: [
{
id: "example.hello",
name: "Hello",
description: "Greets the user",
publisher: "DBX",
verified: true,
tags: ["sample"],
permissions: [],
latestVersion: "1.1.0",
versions: [
{
version: "1.1.0",
artifacts: [{ target: "darwin-arm64", url: "https://plugins.example.com/hello.dbxp", sha256: "a".repeat(64), signingKeyId: "dbx.release" }],
},
],
localizations: { "zh-CN": { name: "你好工作台", description: "用于验证插件工作台" } },
},
],
},
};
function installed(version: string): InstalledPlugin {
return {
manifest: {
manifest_version: 1,
id: "example.hello",
name: "Hello",
version,
publisher: "DBX",
description: "",
engines: { dbx: "", host_api: "" },
permissions: [],
entrypoints: {},
contributions: [],
drivers: [],
protocol_version: 1,
},
compatibility: { compatible: true, errors: [], warnings: [], target: "darwin-arm64" },
};
}
describe("plugin marketplace listings", () => {
it("localizes, detects updates, and filters by repository", () => {
const listings = buildMarketplacePluginListings([result], [installed("1.0.0")], "zh-CN");
expect(listings[0]).toMatchObject({ name: "你好工作台", status: "update", target: "darwin-arm64" });
expect(filterMarketplacePluginListings(listings, "验证", "dbx-official")).toHaveLength(1);
});
it("marks a plugin unsupported when the current target has no artifact", () => {
const unsupported = structuredClone(result);
unsupported.target = "linux-x64";
expect(buildMarketplacePluginListings([unsupported], [], "en")[0].status).toBe("unsupported");
});
it("uses a universal artifact when the current target has no exact artifact", () => {
const universal = structuredClone(result);
universal.target = "linux-x64";
universal.catalog!.plugins[0].versions[0].artifacts = [{ target: "universal", url: "https://plugins.example.com/hello-universal.dbxp", sha256: "b".repeat(64), signingKeyId: "dbx.release" }];
expect(buildMarketplacePluginListings([universal], [], "en")[0]).toMatchObject({ status: "install", artifact: { target: "universal" } });
});
it("prefers an exact artifact over the universal fallback", () => {
const artifacts = [
{ target: "universal", url: "https://plugins.example.com/hello-universal.dbxp", sha256: "a".repeat(64), signingKeyId: "dbx.release" },
{ target: "darwin-arm64", url: "https://plugins.example.com/hello-darwin.dbxp", sha256: "b".repeat(64), signingKeyId: "dbx.release" },
];
expect(selectMarketplaceArtifact(artifacts, "darwin-arm64")?.target).toBe("darwin-arm64");
});
});
@@ -0,0 +1,90 @@
import type { InstalledPlugin, PluginMarketplaceArtifact, PluginMarketplacePlugin, PluginRepository, PluginRepositoryCatalogResult } from "@/types/database";
export type MarketplacePluginStatus = "install" | "installed" | "update" | "unsupported";
export const UNIVERSAL_PLUGIN_TARGET = "universal";
export interface MarketplacePluginListing {
key: string;
repository: PluginRepository;
plugin: PluginMarketplacePlugin;
name: string;
description: string;
target: string;
artifact?: PluginMarketplaceArtifact;
installed?: InstalledPlugin;
verified: boolean;
status: MarketplacePluginStatus;
}
export function buildMarketplacePluginListings(results: readonly PluginRepositoryCatalogResult[], installedPlugins: readonly InstalledPlugin[], locale: string): MarketplacePluginListing[] {
const installedById = new Map(installedPlugins.map((plugin) => [plugin.manifest.id, plugin]));
return results
.flatMap((result) =>
(result.catalog?.plugins || []).map((plugin) => {
const localized = marketplacePluginLocalization(plugin, locale);
const latestVersion = plugin.versions.find((version) => version.version === plugin.latestVersion);
const artifact = latestVersion ? selectMarketplaceArtifact(latestVersion.artifacts, result.target) : undefined;
const installed = installedById.get(plugin.id);
const status: MarketplacePluginStatus = !artifact ? "unsupported" : !installed ? "install" : compareVersions(plugin.latestVersion, installed.manifest.version || "0.0.0") > 0 ? "update" : "installed";
return {
key: `${result.repository.id}:${plugin.id}`,
repository: result.repository,
plugin,
name: localized.name,
description: localized.description,
target: result.target,
artifact,
installed,
verified: plugin.verified && listingRepositoryCanVerify(result.repository),
status,
};
}),
)
.sort((left, right) => left.name.localeCompare(right.name));
}
export function selectMarketplaceArtifact(artifacts: readonly PluginMarketplaceArtifact[], target: string): PluginMarketplaceArtifact | undefined {
return artifacts.find((candidate) => candidate.target === target) || artifacts.find((candidate) => candidate.target === UNIVERSAL_PLUGIN_TARGET);
}
function listingRepositoryCanVerify(repository: PluginRepository): boolean {
return repository.kind === "official" || repository.kind === "enterprise";
}
export function filterMarketplacePluginListings(listings: readonly MarketplacePluginListing[], query: string, repositoryId: string): MarketplacePluginListing[] {
const normalizedQuery = query.trim().toLocaleLowerCase();
return listings.filter((listing) => {
if (repositoryId !== "all" && listing.repository.id !== repositoryId) return false;
if (!normalizedQuery) return true;
return [listing.plugin.id, listing.name, listing.description, listing.plugin.publisher, listing.repository.name, ...listing.plugin.tags].join("\n").toLocaleLowerCase().includes(normalizedQuery);
});
}
function marketplacePluginLocalization(plugin: PluginMarketplacePlugin, locale: string): { name: string; description: string } {
const normalizedLocale = locale.replace("_", "-").toLowerCase();
const entries = Object.entries(plugin.localizations || {});
const localization = entries.find(([key]) => key.replace("_", "-").toLowerCase() === normalizedLocale)?.[1] || entries.find(([key]) => key.replace("_", "-").toLowerCase() === normalizedLocale.split("-")[0])?.[1];
return {
name: localization?.name?.trim() || plugin.name,
description: localization?.description?.trim() || plugin.description,
};
}
function compareVersions(left: string, right: string): number {
const leftParts = parseVersion(left);
const rightParts = parseVersion(right);
if (!leftParts || !rightParts) return left.localeCompare(right, undefined, { numeric: true, sensitivity: "base" });
const leftNumbers = leftParts.slice(0, 3) as [number, number, number];
const rightNumbers = rightParts.slice(0, 3) as [number, number, number];
for (let index = 0; index < leftNumbers.length; index += 1) {
if (leftNumbers[index] !== rightNumbers[index]) return leftNumbers[index] - rightNumbers[index];
}
return leftParts[3].localeCompare(rightParts[3]);
}
function parseVersion(version: string): [number, number, number, string] | null {
const match = /^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?/.exec(version);
if (!match) return null;
return [Number(match[1]), Number(match[2]), Number(match[3]), match[4] || "~"];
}