Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
import { browser } from '$app/env';
import type { Completion } from '@codemirror/autocomplete';
import Ajv, { type ValidateFunction } from 'ajv';
import { m } from '#lib/paraglide/messages.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import type { SchemaDoc, SchemaStatus } from './types';
const DOCKER_COMPOSE_SCHEMA_URL =
'https://raw.githubusercontent.com/compose-spec/compose-go/refs/heads/main/schema/compose-spec.json';
const SCHEMA_CACHE_KEY = 'arcane.compose.schema.v1';
type SchemaObject = Record<string, unknown>;
type ComposeSchemaContext = {
schema: SchemaObject | null;
validate: ValidateFunction<unknown> | null;
status: SchemaStatus;
message?: string;
};
type ArcaneCompletionSpec = {
label: string;
detail: string;
info: string;
};
let composeSchemaPromise: Promise<ComposeSchemaContext> | null = null;
let composeSchemaContext: ComposeSchemaContext | null = null;
const ARCANE_ROOT_EXTENSION_COMPLETIONS: ArcaneCompletionSpec[] = [
{
label: 'x-arcane',
detail: 'Arcane extension',
info: 'Arcane compose metadata block for project-level theme icons, URLs, and tags.'
}
];
const ARCANE_BLOCK_COMPLETIONS: ArcaneCompletionSpec[] = [
{
label: 'hidden',
get detail() {
return m.editor_compose_hidden_detail();
},
get info() {
return m.editor_compose_hidden_info();
}
},
{
label: 'icon',
detail: 'Arcane project fallback icon',
info: 'Fallback project icon URL or catalog slug used only when icon-light and icon-dark are not set.'
},
{
label: 'icon-light',
detail: 'Arcane project icon for dark theme',
info: 'Light project icon URL or catalog slug used in dark theme.'
},
{
label: 'icon-dark',
detail: 'Arcane project icon for light theme',
info: 'Dark project icon URL or catalog slug used in light theme.'
},
{
label: 'urls',
detail: 'Arcane project URLs',
info: 'Additional project URLs (for example docs or homepage links).'
},
{
label: 'tags',
detail: 'Arcane project tags',
info: 'A tag or list of tags used to group and filter projects. Compose-defined tags are read-only in Arcane.'
},
{
label: 'update-check',
get detail() {
return m.editor_compose_update_check_detail();
},
get info() {
return m.editor_compose_update_check_info();
}
}
];
const ARCANE_SERVICE_EXTENSION_COMPLETIONS: ArcaneCompletionSpec[] = [
{
label: 'x-arcane',
detail: 'Arcane service extension',
info: 'Arcane service metadata block for service theme icon overrides.'
}
];
const ARCANE_SERVICE_BLOCK_COMPLETIONS: ArcaneCompletionSpec[] = [
{
label: 'hidden',
get detail() {
return m.editor_compose_hidden_detail();
},
get info() {
return m.editor_compose_hidden_info();
}
},
{
label: 'icon',
detail: 'Arcane service fallback icon',
info: 'Fallback service icon URL or catalog slug used only when icon-light and icon-dark are not set.'
},
{
label: 'icon-light',
detail: 'Arcane service icon for dark theme',
info: 'Light service icon URL or catalog slug used in dark theme.'
},
{
label: 'icon-dark',
detail: 'Arcane service icon for light theme',
info: 'Dark service icon URL or catalog slug used in light theme.'
},
{
label: 'update-check',
get detail() {
return m.editor_compose_update_check_detail();
},
get info() {
return m.editor_compose_update_check_info();
}
}
];
const ARCANE_TAG_COMPLETIONS: ArcaneCompletionSpec[] = [
{
label: 'name',
detail: 'Arcane project tag name',
info: 'Normalized project tag name used for grouping and filtering.'
},
{
label: 'color',
detail: 'Arcane project tag color',
info: 'Tag color: gray, purple, blue, green, yellow, orange, red, or pink.'
}
];
const ARCANE_TAG_COLORS = ['gray', 'purple', 'blue', 'green', 'yellow', 'orange', 'red', 'pink'];
function getUpdaterCompletionSpecs(): ArcaneCompletionSpec[] {
return [
{ label: 'enabled', detail: m.editor_compose_updater_enabled_detail(), info: m.editor_compose_updater_enabled_info() },
{ label: 'strategy', detail: m.editor_compose_updater_strategy_detail(), info: m.editor_compose_updater_strategy_info() },
{
label: 'constraint',
detail: m.editor_compose_updater_constraint_detail(),
info: m.editor_compose_updater_constraint_info()
},
{
label: 'tag-pattern',
detail: m.editor_compose_updater_tag_pattern_detail(),
info: m.editor_compose_updater_tag_pattern_info()
}
];
}
function getUpdaterPathIndex(path: Array<string | number>): number {
if (isRootArcanePath(path.slice(0, 1)) && path[1] === 'updater') return 1;
if (isServiceArcanePath(path.slice(0, 3)) && path[3] === 'updater') return 3;
return -1;
}
function asSchemaObject(value: unknown): SchemaObject | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
return value as SchemaObject;
}
function readCachedSchema(): SchemaObject | null {
if (!browser) return null;
try {
const raw = localStorage.getItem(SCHEMA_CACHE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as unknown;
return asSchemaObject(parsed);
} catch {
return null;
}
}
function writeCachedSchema(schema: SchemaObject): void {
if (!browser) return;
try {
localStorage.setItem(SCHEMA_CACHE_KEY, JSON.stringify(schema));
} catch {
// ignore cache write failures
}
}
function createValidator(schema: SchemaObject): ValidateFunction<unknown> {
const ajv = new Ajv({
allErrors: true,
strict: false,
strictSchema: false,
allowUnionTypes: true,
validateFormats: false,
validateSchema: false
});
return ajv.compile(schema);
}
function resolveRef(root: SchemaObject, ref: string, visited: Set<string>): SchemaObject | null {
if (!ref.startsWith('#/')) return null;
if (visited.has(ref)) return null;
visited.add(ref);
const segments = ref
.slice(2)
.split('/')
.map((segment) => segment.replace(/~1/g, '/').replace(/~0/g, '~'));
let current: unknown = root;
for (const segment of segments) {
if (!current || typeof current !== 'object') return null;
current = (current as SchemaObject)[segment];
}
return asSchemaObject(current);
}
function expandCandidates(root: SchemaObject, candidate: SchemaObject, visited: Set<string>): SchemaObject[] {
const expanded: SchemaObject[] = [];
const ref = candidate['$ref'];
if (typeof ref === 'string') {
const resolved = resolveRef(root, ref, visited);
if (resolved) {
expanded.push(...expandCandidates(root, resolved, visited));
}
}
const containers = ['allOf', 'anyOf', 'oneOf'];
for (const container of containers) {
const node = candidate[container];
if (Array.isArray(node)) {
for (const item of node) {
const asObject = asSchemaObject(item);
if (asObject) expanded.push(...expandCandidates(root, asObject, visited));
}
}
}
expanded.push(candidate);
return [...new Set(expanded)];
}
function getSegmentCandidates(node: SchemaObject, segment: string | number): SchemaObject[] {
const candidates: unknown[] = [];
if (typeof segment === 'number') {
const prefixItems = node['prefixItems'];
if (Array.isArray(prefixItems) && segment < prefixItems.length) candidates.push(prefixItems[segment]);
candidates.push(node['items']);
} else {
const properties = asSchemaObject(node['properties']);
candidates.push(properties?.[segment]);
const patterns = asSchemaObject(node['patternProperties']);
if (patterns) candidates.push(...Object.values(patterns));
candidates.push(node['additionalProperties']);
}
return candidates.map(asSchemaObject).filter((candidate): candidate is SchemaObject => candidate !== null);
}
function getPathCandidates(root: SchemaObject, path: Array<string | number>): SchemaObject[] {
let candidates: SchemaObject[] = [root];
for (const segment of path) {
candidates = [
...new Set(
candidates.flatMap((candidate) =>
expandCandidates(root, candidate, new Set<string>()).flatMap((node) => getSegmentCandidates(node, segment))
)
)
];
if (candidates.length === 0) break;
}
return candidates;
}
function collectPropertySchemas(root: SchemaObject, path: Array<string | number>): Map<string, SchemaObject> {
const map = new Map<string, SchemaObject>();
const candidates = getPathCandidates(root, path);
for (const candidate of candidates) {
const expanded = expandCandidates(root, candidate, new Set<string>());
for (const node of expanded) {
const properties = asSchemaObject(node['properties']);
if (!properties) continue;
for (const [key, value] of Object.entries(properties)) {
const propertySchema = asSchemaObject(value);
if (propertySchema) {
map.set(key, propertySchema);
}
}
}
}
return map;
}
function extractSchemaDoc(schema: SchemaObject): SchemaDoc {
const title = typeof schema['title'] === 'string' ? schema['title'] : undefined;
const description = typeof schema['description'] === 'string' ? schema['description'] : undefined;
const defaultValue = schema['default'] !== undefined ? JSON.stringify(schema['default']) : undefined;
let examples: string[] | undefined;
if (Array.isArray(schema['examples'])) {
examples = schema['examples'].slice(0, 3).map((value) => JSON.stringify(value));
}
return {
title,
description,
defaultValue,
examples
};
}
function isRootPath(path: Array<string | number>): boolean {
return path.length === 0;
}
function isRootArcanePath(path: Array<string | number>): boolean {
return path.length === 1 && path[0] === 'x-arcane';
}
function isServicePath(path: Array<string | number>): boolean {
return path.length === 2 && path[0] === 'services' && typeof path[1] === 'string';
}
function isServiceArcanePath(path: Array<string | number>): boolean {
return path.length === 3 && path[0] === 'services' && typeof path[1] === 'string' && path[2] === 'x-arcane';
}
function toArcaneCompletion(spec: ArcaneCompletionSpec): Completion {
return {
label: spec.label,
type: 'property',
detail: spec.detail,
info: spec.info,
apply: `${spec.label}: `
};
}
function getArcaneCompletionOptionsForPath(path: Array<string | number>, prefix = ''): Completion[] {
const normalizedPrefix = prefix.toLowerCase();
const updaterPathIndex = getUpdaterPathIndex(path);
let specs: ArcaneCompletionSpec[] = [];
if (updaterPathIndex >= 0 && path.length === updaterPathIndex + 1) {
specs = getUpdaterCompletionSpecs();
} else if (isRootPath(path)) {
specs = ARCANE_ROOT_EXTENSION_COMPLETIONS;
} else if (isRootArcanePath(path)) {
specs = ARCANE_BLOCK_COMPLETIONS;
} else if (isServicePath(path)) {
specs = ARCANE_SERVICE_EXTENSION_COMPLETIONS;
} else if (isServiceArcanePath(path)) {
specs = ARCANE_SERVICE_BLOCK_COMPLETIONS;
} else if (path.length === 3 && path[0] === 'x-arcane' && path[1] === 'tags' && typeof path[2] === 'number') {
specs = ARCANE_TAG_COMPLETIONS;
}
if (isRootArcanePath(path) || isServiceArcanePath(path)) {
specs = [...specs, { label: 'updater', detail: m.editor_compose_updater_detail(), info: m.editor_compose_updater_info() }];
}
return specs
.filter((item) => item.label.toLowerCase().includes(normalizedPrefix))
.sort((a, b) => a.label.localeCompare(b.label))
.map(toArcaneCompletion);
}
const ARCANE_SCHEMA_DOCS: Record<string, SchemaDoc> = {
'x-arcane': {
title: 'x-arcane',
description: 'Arcane extension block for project-level metadata such as theme icons, custom URLs, and tags.'
},
'x-arcane.icon-light': {
title: 'x-arcane.icon-light',
description: 'Light project icon URL or catalog slug used in dark theme.'
},
'x-arcane.icon-dark': {
title: 'x-arcane.icon-dark',
description: 'Dark project icon URL or catalog slug used in light theme.'
},
'x-arcane.icon': {
title: 'x-arcane.icon',
description: 'Fallback project icon URL or catalog slug used only when icon-light and icon-dark are not set.'
},
'x-arcane.hidden': {
title: 'x-arcane.hidden',
get description() {
return m.editor_compose_hidden_info();
}
},
'x-arcane.update-check': {
title: 'x-arcane.update-check',
get description() {
return m.editor_compose_update_check_info();
}
},
'x-arcane.urls': {
title: 'x-arcane.urls',
description: 'Additional project URLs (for example docs, homepage, or dashboards).'
},
'x-arcane.tags': {
title: 'x-arcane.tags',
description:
'A list of project tag objects. Each tag requires a name and color and is read-only in Arcane while defined here.',
examples: ['[{ name: database, color: purple }]']
},
'x-arcane.tags[].name': {
title: 'x-arcane.tags[].name',
description: 'Required tag name. Names are trimmed, normalized to lowercase, and limited to 64 characters.'
},
'x-arcane.tags[].color': {
title: 'x-arcane.tags[].color',
description: 'Required tag color: gray, purple, blue, green, yellow, orange, red, or pink.'
},
'services.<name>.x-arcane': {
title: 'services.<name>.x-arcane',
description: 'Arcane extension block for service-level metadata.'
}
};
function getServiceArcaneSchemaDoc(path: Array<string | number>): SchemaDoc | null {
if (path.length === 3) return ARCANE_SCHEMA_DOCS['services.<name>.x-arcane'] ?? null;
if (path.length === 4 && path[3] === 'hidden')
return { ...ARCANE_SCHEMA_DOCS['x-arcane.hidden'], title: 'services.<name>.x-arcane.hidden' };
if (path.length === 4 && path[3] === 'update-check')
return { ...ARCANE_SCHEMA_DOCS['x-arcane.update-check'], title: 'services.<name>.x-arcane.update-check' };
if (path.length !== 4 || !['icon', 'icon-light', 'icon-dark'].includes(String(path[3]))) return null;
return {
title: `services.<name>.x-arcane.${String(path[3])}`,
description:
path[3] === 'icon'
? 'Fallback service icon URL or catalog slug used only when icon-light and icon-dark are not set.'
: 'Service theme icon URL or catalog slug override.'
};
}
function getArcaneSchemaDocForPath(path: Array<string | number>): SchemaDoc | null {
const updaterPathIndex = getUpdaterPathIndex(path);
if (updaterPathIndex >= 0) {
const title = updaterPathIndex === 1 ? 'x-arcane.updater' : 'services.<name>.x-arcane.updater';
if (path.length === updaterPathIndex + 1) {
return { title, description: m.editor_compose_updater_info() };
}
if (path.length === updaterPathIndex + 2) {
const field = getUpdaterCompletionSpecs().find((spec) => spec.label === path[updaterPathIndex + 1]);
if (field)
return {
title: `${title}.${field.label}`,
description: field.info,
...(field.label === 'strategy' ? { defaultValue: 'digest' } : {})
};
}
return null;
}
if (isServiceArcanePath(path.slice(0, 3))) return getServiceArcaneSchemaDoc(path);
if (path[0] !== 'x-arcane') return null;
if (path.length === 1) return ARCANE_SCHEMA_DOCS['x-arcane'] ?? null;
if (
path.length === 2 &&
['icon', 'icon-light', 'icon-dark', 'urls', 'tags', 'hidden', 'update-check'].includes(String(path[1]))
)
return ARCANE_SCHEMA_DOCS[`x-arcane.${path[1]}`] ?? null;
if (path.length === 4 && path[1] === 'tags' && typeof path[2] === 'number') {
return ARCANE_SCHEMA_DOCS[`x-arcane.tags[].${String(path[3])}`] ?? null;
}
return null;
}
export async function getComposeSchemaContext(): Promise<ComposeSchemaContext> {
if (composeSchemaContext) return composeSchemaContext;
if (composeSchemaPromise) return composeSchemaPromise;
composeSchemaPromise = (async () => {
try {
const requestResult1 = await tryCatch(
(async () => {
const response = await fetch(DOCKER_COMPOSE_SCHEMA_URL, { cache: 'no-store' });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const payload = (await response.json()) as unknown;
const schema = asSchemaObject(payload);
if (!schema) throw new Error('Invalid compose schema payload');
writeCachedSchema(schema);
composeSchemaContext = {
schema,
validate: createValidator(schema),
status: 'ready'
};
return composeSchemaContext;
})()
);
if (requestResult1.error !== null) {
const error = requestResult1.error;
const cached = readCachedSchema();
if (cached) {
composeSchemaContext = {
schema: cached,
validate: createValidator(cached),
status: 'cached',
message: 'Using cached Docker Compose schema'
};
return composeSchemaContext;
}
composeSchemaContext = {
schema: null,
validate: null,
status: 'unavailable',
message: error instanceof Error ? error.message : 'Schema unavailable'
};
return composeSchemaContext;
} else {
return requestResult1.data;
}
} finally {
composeSchemaPromise = null;
}
})();
return composeSchemaPromise;
}
export function getCompletionOptionsForPath(
schema: SchemaObject | null,
path: Array<string | number>,
prefix = ''
): Completion[] {
const normalizedPrefix = prefix.toLowerCase();
const propertyMap = schema ? collectPropertySchemas(schema, path) : new Map<string, SchemaObject>();
const schemaCompletions = Array.from(propertyMap.entries())
.filter(([key]) => key.toLowerCase().includes(normalizedPrefix))
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, propertySchema]) => {
const doc = extractSchemaDoc(propertySchema);
return {
label: key,
type: 'property',
detail: doc.title,
info: doc.description,
apply: `${key}: `
} as Completion;
});
const arcaneCompletions = getArcaneCompletionOptionsForPath(path, prefix);
const merged = new Map<string, Completion>();
for (const completion of schemaCompletions) {
merged.set(completion.label, completion);
}
for (const completion of arcaneCompletions) {
if (!merged.has(completion.label)) {
merged.set(completion.label, completion);
}
}
return Array.from(merged.values()).sort((a, b) => a.label.localeCompare(b.label));
}
export function getEnumValueCompletions(schema: SchemaObject | null, path: Array<string | number>): Completion[] {
const values = new Set<string>();
if (
(path.length === 2 && path[0] === 'x-arcane' && ['hidden', 'update-check'].includes(String(path[1]))) ||
(path.length === 4 && isServiceArcanePath(path.slice(0, 3)) && ['hidden', 'update-check'].includes(String(path[3])))
) {
values.add('true');
values.add('false');
}
const updaterPathIndex = getUpdaterPathIndex(path);
if (updaterPathIndex >= 0 && path.length === updaterPathIndex + 2) {
const field = path[updaterPathIndex + 1];
if (field === 'strategy') {
values.add('auto');
values.add('digest');
values.add('tag');
} else if (field === 'enabled') {
values.add('true');
values.add('false');
}
}
if (getArcaneSchemaDocForPath(path)?.title === 'x-arcane.tags[].color') {
for (const color of ARCANE_TAG_COLORS) values.add(color);
}
if (schema) {
const nodes = getPathCandidates(schema, path).flatMap((candidate) => expandCandidates(schema, candidate, new Set<string>()));
for (const node of nodes) {
if (!Array.isArray(node['enum'])) continue;
for (const value of node['enum'].filter((value) => ['string', 'number', 'boolean'].includes(typeof value))) {
values.add(String(value));
}
}
}
return Array.from(values)
.sort((a, b) => a.localeCompare(b))
.map((value) => ({
label: value,
type: 'enum',
apply: /^\d+$/.test(value) || value === 'true' || value === 'false' ? value : JSON.stringify(value)
}));
}
export function getSchemaDocForPath(schema: SchemaObject | null, path: Array<string | number>): SchemaDoc | null {
const arcaneDoc = getArcaneSchemaDocForPath(path);
if (!schema) return arcaneDoc;
const candidates = getPathCandidates(schema, path);
for (const candidate of candidates) {
const doc = extractSchemaDoc(candidate);
if (doc.title || doc.description || doc.defaultValue || (doc.examples && doc.examples.length > 0)) {
return doc;
}
}
return arcaneDoc;
}
export type { ComposeSchemaContext, SchemaObject };