import { computed, createApp, onMounted, reactive, ref, watch } from "vue";
import "gnexus-ui-kit/dist/css/kit.css";
import "gnexus-ui-kit/dist/assets/fonts/phosphor-icons/src/css/icons.css";
import {
GnAlert,
GnBadge,
GnButton,
GnCard,
GnConfirmDialog,
GnDescriptionList,
GnEmptyState,
GnInput,
GnMetricCard,
GnPageHeader,
GnSearchField,
GnToastProvider,
GnToolbar,
GnUserCard,
useToast
} from "gnexus-ui-kit/vue";
import {
locale,
localeOptions,
savedLocale,
setLocale,
t
} from "./i18n/index.js";
import "./styles.css";
const encodePath = path =>
String(path || "")
.split("/")
.map(encodeURIComponent)
.join("/");
const pretty = value =>
typeof value === "string" ? value : JSON.stringify(value ?? null, null, 2);
const defaultDocTemplate = () => {
const today = new Date().toISOString().slice(0, 10);
return `---\nowner: gmikcon\nstatus: draft\nlast_reviewed: ${today}\nreview_interval: 30d\nconfidence: medium\nsource_of_truth: manual\n---\n\n# New document\n\n`;
};
const IssueList = {
components: { GnBadge },
props: {
issues: { type: Array, default: () => [] }
},
setup() {
return { t };
},
template: `
<div class="gnb-issues">
<p v-if="!issues.length" class="gnb-muted">{{ t('status.noIssues') }}</p>
<div v-for="issue in issues" :key="issue.path + issue.code + issue.message" class="gnb-issue">
<div class="gnb-badges">
<GnBadge :variant="issue.severity === 'error' ? 'danger' : 'warning'">{{ issue.severity }}</GnBadge>
<code>{{ issue.code }}</code>
<span class="gnb-muted">{{ issue.path }}</span>
</div>
<p>{{ issue.message }}</p>
</div>
</div>
`
};
const AppScreen = {
components: {
GnAlert,
GnBadge,
GnButton,
GnCard,
GnConfirmDialog,
GnDescriptionList,
GnEmptyState,
GnInput,
GnMetricCard,
GnPageHeader,
GnSearchField,
GnToolbar,
GnUserCard,
IssueList
},
setup() {
const toast = useToast();
const booting = ref(true);
const authEnabled = ref(false);
const user = ref(null);
const localeOverride = ref(null);
const storage = ref("unknown");
const healthStatus = ref("unknown");
const pageError = ref("");
const activePage = ref("docs");
const drawerOpen = ref(false);
const docs = ref([]);
const docQuery = ref("");
const searchResults = ref([]);
const searching = ref(false);
const selectedDocPath = ref("");
const selectedDoc = ref(null);
const docLoading = ref(false);
const docError = ref("");
const docHistory = ref([]);
const historyError = ref("");
const docDiff = ref("");
const diffError = ref("");
const proposal = reactive({
target: "10-systems/example.md",
summary: "",
reason: "",
content: defaultDocTemplate()
});
const proposalRunning = ref(false);
const inventoryTypes = ref([]);
const inventoryType = ref("");
const inventoryRecords = ref([]);
const inventoryFilter = ref("");
const selectedInventoryId = ref("");
const inventoryRaw = ref(false);
const inventoryRawText = ref("");
const inventoryLoading = ref(false);
const inventoryError = ref("");
const changes = ref([]);
const selectedChangeId = ref("");
const selectedChange = ref(null);
const changeLoading = ref(false);
const changeError = ref("");
const applyingChange = ref(false);
const validation = ref(null);
const freshness = ref(null);
const keys = ref([]);
const keysShowAll = ref(false);
const keysLoading = ref(false);
const keysError = ref("");
const issuedToken = ref("");
const issuedKey = ref(null);
const keyForm = reactive({ consumer: "claude-code", name: "" });
const confirmState = reactive({
open: false,
title: "",
message: "",
confirmText: "",
variant: "warning",
action: null
});
let searchTimer = null;
const userDisplayName = computed(
() =>
user.value?.display_name ||
user.value?.email ||
user.value?.user_id ||
""
);
const userInitials = computed(() => {
const source = userDisplayName.value || "?";
return source
.split(/\s+/)
.slice(0, 2)
.map(part => part[0])
.join("")
.toUpperCase()
.slice(0, 2);
});
const isAuthenticated = computed(
() => !authEnabled.value || Boolean(user.value)
);
const canWrite = computed(
() => !authEnabled.value || Boolean(user.value)
);
const isAdmin = computed(() => user.value?.system_role === "admin");
const storageIsDb = computed(() => storage.value === "db");
const navItems = computed(() => [
{ id: "docs", label: t("nav.docs"), icon: "ph-files" },
{ id: "inventory", label: t("nav.inventory"), icon: "ph-database" },
{ id: "changes", label: t("nav.changes"), icon: "ph-git-pull-request" },
{ id: "status", label: t("nav.status"), icon: "ph-heartbeat" },
...(authEnabled.value && user.value
? [{ id: "keys", label: t("nav.keys"), icon: "ph-key" }]
: []),
{ id: "settings", label: t("nav.settings"), icon: "ph-sliders" }
]);
const pageMeta = computed(
() =>
({
docs: { title: t("docs.title"), subtitle: t("docs.subtitle") },
inventory: {
title: t("inventory.title"),
subtitle: t("inventory.subtitle")
},
changes: {
title: t("changes.title"),
subtitle: t("changes.subtitle")
},
status: { title: t("status.title"), subtitle: t("status.subtitle") },
keys: { title: t("keys.title"), subtitle: t("keys.subtitle") },
settings: {
title: t("settings.title"),
subtitle: t("settings.subtitle")
}
})[activePage.value] || {
title: t("app.title"),
subtitle: t("app.subtitle")
}
);
const pageTitle = computed(() => pageMeta.value.title);
const pageSubtitle = computed(() => pageMeta.value.subtitle);
const activeLocaleLabel = computed(
() =>
(localeOptions.find(option => option.value === locale.value) || localeOptions[0])
.label
);
const settingsItems = computed(() => [
{
key: "storage",
term: t("settings.storage"),
value: storage.value || t("common.unknown")
},
{
key: "health",
term: t("common.status"),
value: healthStatus.value || t("common.unknown")
},
{
key: "auth",
term: t("settings.auth"),
value: authEnabled.value ? t("auth.title") : t("settings.authDisabled")
},
{
key: "account",
term: t("auth.account"),
value: user.value
? `${userDisplayName.value} · ${user.value.email || user.value.user_id}`
: t("common.none")
},
{
key: "language",
term: t("settings.language"),
value: activeLocaleLabel.value
}
]);
const filteredInventory = computed(() => {
const query = inventoryFilter.value.trim().toLowerCase();
if (!query) return inventoryRecords.value;
return inventoryRecords.value.filter(item =>
[item.id, item.name, item.fqdn, item.host]
.filter(Boolean)
.some(value => String(value).toLowerCase().includes(query))
);
});
const selectedInventoryRecord = computed(
() =>
inventoryRecords.value.find(
item => item.id === selectedInventoryId.value
) || null
);
const inventoryDisplay = computed(() => {
if (inventoryRaw.value) return inventoryRawText.value;
return selectedInventoryRecord.value
? pretty(selectedInventoryRecord.value)
: "";
});
const formatDate = value => {
if (!value) return "—";
const date = new Date(value);
return Number.isNaN(date.getTime())
? String(value)
: date.toLocaleString(locale.value);
};
const statusLabel = status =>
({
draft: t("changes.draft"),
pending: t("changes.pending"),
applied: t("changes.appliedStatus"),
rejected: t("changes.rejected")
})[status] || status;
const changeStatusVariant = status =>
status === "applied"
? "success"
: status === "rejected"
? "danger"
: "secondary";
const isLatestVersion = versionNo => {
if (!docHistory.value.length) return false;
const latest = Math.max(
...docHistory.value.map(version => version.version_no)
);
return versionNo === latest;
};
async function request(path, options = {}) {
const response = await fetch(`/api${path}`, {
credentials: "same-origin",
...options
});
if (response.status === 401) {
user.value = null;
throw new Error(t("errors.unauthorized"));
}
if (response.status === 204) return null;
if (!response.ok) {
const text = await response.text();
let detail = text;
try {
const data = JSON.parse(text);
detail = data.detail || data.error || text;
} catch {
/* keep text */
}
throw new Error(`${response.status}: ${detail}`);
}
const contentType = response.headers.get("content-type") || "";
return contentType.includes("application/json")
? response.json()
: response.text();
}
const apiGet = path => request(path);
const apiSend = (path, method, body) =>
request(path, {
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
body: body ? JSON.stringify(body) : undefined
});
async function loadMe() {
booting.value = true;
pageError.value = "";
try {
const response = await fetch("/api/me", {
credentials: "same-origin"
});
if (!response.ok) {
throw new Error(`/me ${response.status}`);
}
const data = await response.json();
authEnabled.value = Boolean(data.auth_enabled);
user.value = data.user || null;
localeOverride.value = data.locale || null;
if (data.user && data.locale_effective) {
setLocale(data.locale_effective);
} else if (!data.user) {
setLocale(savedLocale() || data.locale_effective || "en");
}
const params = new URLSearchParams(window.location.search);
if (params.get("auth_error")) {
pageError.value = t("auth.denied");
window.history.replaceState({}, "", window.location.pathname);
}
} catch (error) {
pageError.value =
error instanceof Error ? error.message : t("errors.loadFailed");
} finally {
booting.value = false;
}
if (isAuthenticated.value) {
await loadAll();
}
}
async function loadAll() {
pageError.value = "";
const results = await Promise.allSettled([
apiGet("/health"),
apiGet("/docs"),
apiGet("/inventory"),
apiGet("/changes"),
apiGet("/validate"),
apiGet("/health/freshness"),
authEnabled.value && user.value
? apiGet("/mcp-keys")
: Promise.resolve(null)
]);
const [health, docsResult, inventoryResult, changesResult, validationResult, freshnessResult, keysResult] =
results;
if (health.status === "fulfilled") {
storage.value = health.value?.storage || "unknown";
healthStatus.value = health.value?.status || "unknown";
}
if (docsResult.status === "fulfilled") {
docs.value = docsResult.value || [];
if (
selectedDocPath.value &&
docs.value.some(doc => doc.path === selectedDocPath.value)
) {
await loadDoc(selectedDocPath.value);
} else if (docs.value.length) {
await loadDoc(docs.value[0].path);
}
}
if (inventoryResult.status === "fulfilled") {
inventoryTypes.value = inventoryResult.value || [];
if (
inventoryType.value &&
inventoryTypes.value.includes(inventoryType.value)
) {
await loadInventoryType(inventoryType.value);
} else if (inventoryTypes.value.length) {
await loadInventoryType(inventoryTypes.value[0]);
}
}
if (changesResult.status === "fulfilled") {
changes.value = changesResult.value || [];
if (
selectedChangeId.value &&
changes.value.some(change => change.id === selectedChangeId.value)
) {
await loadChange(selectedChangeId.value);
} else if (changes.value.length) {
await loadChange(changes.value[0].id);
} else {
selectedChangeId.value = "";
selectedChange.value = null;
}
}
if (validationResult.status === "fulfilled") {
validation.value = validationResult.value;
}
if (freshnessResult.status === "fulfilled") {
freshness.value = freshnessResult.value;
}
if (keysResult.status === "fulfilled" && keysResult.value) {
keys.value = keysResult.value.items || [];
}
const failed = results.find(result => result.status === "rejected");
if (failed) {
pageError.value =
failed.reason?.message || t("errors.loadFailed");
}
}
async function loadDoc(path) {
if (!path) return;
if (docQuery.value) docQuery.value = "";
selectedDocPath.value = path;
selectedDoc.value = null;
docLoading.value = true;
docError.value = "";
docHistory.value = [];
historyError.value = "";
docDiff.value = "";
diffError.value = "";
try {
selectedDoc.value = await apiGet(
`/docs/read?path=${encodeURIComponent(path)}`
);
if (storageIsDb.value) {
try {
docHistory.value = await apiGet(
`/documents/${encodePath(path)}/history`
);
} catch {
historyError.value = t("docs.noHistory");
}
} else {
historyError.value = t("docs.noHistory");
}
} catch (error) {
docError.value =
error instanceof Error ? error.message : t("errors.loadFailed");
} finally {
docLoading.value = false;
}
}
async function requestDiff(fromVersion, toVersion) {
docDiff.value = "";
diffError.value = "";
if (!selectedDocPath.value) return;
try {
const data = await apiGet(
`/documents/${encodePath(selectedDocPath.value)}/diff?from=${fromVersion}&to=${toVersion}`
);
docDiff.value = data.diff || "";
if (!docDiff.value) diffError.value = t("docs.noDiff");
} catch (error) {
diffError.value =
error instanceof Error ? error.message : t("errors.loadFailed");
}
}
async function loadDiffFrom(versionNo) {
const latest = docHistory.value.length
? Math.max(...docHistory.value.map(version => version.version_no))
: versionNo;
await requestDiff(versionNo, latest);
}
async function loadLatestDiff() {
if (!docHistory.value.length) return;
const latest = Math.max(
...docHistory.value.map(version => version.version_no)
);
await requestDiff(Math.max(1, latest - 1), latest);
}
function restoreVersion(versionNo) {
askConfirm({
title: t("docs.restoreConfirm"),
message: t("docs.restoreConfirmText", { version: versionNo }),
confirmText: t("docs.restore"),
variant: "warning",
action: async () => {
try {
await apiSend(
`/documents/${encodePath(selectedDocPath.value)}/restore/${versionNo}?summary=${encodeURIComponent(
`${t("docs.restoreConfirm")} ${versionNo}`
)}`,
"POST"
);
toast.success({ title: t("docs.restored") });
await loadDoc(selectedDocPath.value);
await refreshChanges();
} catch (error) {
toast.danger({
title: t("errors.actionFailed"),
text: error instanceof Error ? error.message : t("errors.actionFailed")
});
}
}
});
}
async function submitProposal() {
if (
!proposal.summary.trim() ||
!proposal.target.trim() ||
!proposal.content.trim()
) {
toast.warning({
title: t("common.error"),
text: t("docs.proposalMeta")
});
return;
}
proposalRunning.value = true;
try {
const created = await apiSend("/changes", "POST", {
kind: "doc",
target: proposal.target.trim(),
summary: proposal.summary.trim(),
reason: proposal.reason.trim(),
payload: { content: proposal.content }
});
toast.success({
title: t("docs.proposalCreated"),
text: created.target || created.id
});
proposal.summary = "";
proposal.reason = "";
activePage.value = "changes";
drawerOpen.value = false;
await refreshChanges();
await loadChange(created.id);
} catch (error) {
toast.danger({
title: t("errors.actionFailed"),
text: error instanceof Error ? error.message : t("errors.actionFailed")
});
} finally {
proposalRunning.value = false;
}
}
async function refreshChanges() {
try {
changes.value = await apiGet("/changes");
if (
selectedChangeId.value &&
changes.value.some(change => change.id === selectedChangeId.value)
) {
await loadChange(selectedChangeId.value);
} else if (changes.value.length) {
await loadChange(changes.value[0].id);
} else {
selectedChangeId.value = "";
selectedChange.value = null;
}
} catch (error) {
changeError.value =
error instanceof Error ? error.message : t("errors.loadFailed");
}
}
async function loadChange(id) {
selectedChangeId.value = id;
changeLoading.value = true;
changeError.value = "";
try {
selectedChange.value = await apiGet(
`/changes/${encodeURIComponent(id)}`
);
} catch (error) {
selectedChange.value = null;
changeError.value =
error instanceof Error ? error.message : t("errors.loadFailed");
} finally {
changeLoading.value = false;
}
}
function applyChange(change) {
if (!change) return;
askConfirm({
title: t("changes.applyConfirm"),
message: t("changes.applyConfirmText"),
confirmText: t("changes.apply"),
variant: "success",
action: async () => {
applyingChange.value = true;
try {
await apiSend(
`/changes/${encodeURIComponent(change.id)}/apply`,
"POST"
);
toast.success({ title: t("changes.applied") });
await refreshChanges();
await refreshStatus();
} catch (error) {
toast.danger({
title: t("errors.actionFailed"),
text: error instanceof Error ? error.message : t("errors.actionFailed")
});
} finally {
applyingChange.value = false;
}
}
});
}
async function refreshStatus() {
const results = await Promise.allSettled([
apiGet("/validate"),
apiGet("/health/freshness")
]);
if (results[0].status === "fulfilled") validation.value = results[0].value;
if (results[1].status === "fulfilled") freshness.value = results[1].value;
}
async function loadInventoryType(type) {
if (!type) return;
inventoryType.value = type;
selectedInventoryId.value = "";
inventoryLoading.value = true;
inventoryError.value = "";
try {
inventoryRecords.value = (await apiGet(`/inventory/${encodeURIComponent(type)}`)) || [];
selectedInventoryId.value = inventoryRecords.value[0]?.id || "";
if (inventoryRaw.value) await refreshInventoryRaw();
} catch (error) {
inventoryRecords.value = [];
inventoryError.value =
error instanceof Error ? error.message : t("errors.loadFailed");
} finally {
inventoryLoading.value = false;
}
}
async function refreshInventoryRaw() {
if (!inventoryType.value) {
inventoryRawText.value = "";
return;
}
try {
const data = await apiGet(
`/inventory/${encodeURIComponent(inventoryType.value)}?raw=true`
);
inventoryRawText.value = data.raw || "";
} catch (error) {
inventoryError.value =
error instanceof Error ? error.message : t("errors.loadFailed");
inventoryRaw.value = false;
}
}
async function toggleInventoryRaw() {
inventoryRaw.value = !inventoryRaw.value;
if (inventoryRaw.value) {
await refreshInventoryRaw();
}
}
async function loadKeys() {
if (!user.value) return;
keysLoading.value = true;
keysError.value = "";
try {
const data = await apiGet(
`/mcp-keys${keysShowAll.value ? "?all=true" : ""}`
);
keys.value = data.items || [];
} catch (error) {
keysError.value =
error instanceof Error ? error.message : t("errors.loadFailed");
} finally {
keysLoading.value = false;
}
}
async function createKey() {
if (!keyForm.consumer.trim()) {
toast.warning({ title: t("common.error"), text: t("keys.consumer") });
return;
}
keysLoading.value = true;
keysError.value = "";
try {
const data = await apiSend("/mcp-keys", "POST", {
consumer: keyForm.consumer.trim(),
name: keyForm.name.trim()
});
issuedToken.value = data.token;
issuedKey.value = data;
keyForm.name = "";
toast.success({ title: t("keys.issuedTitle") });
await loadKeys();
} catch (error) {
keysError.value =
error instanceof Error ? error.message : t("errors.actionFailed");
} finally {
keysLoading.value = false;
}
}
function rotateKey(key) {
askConfirm({
title: t("keys.rotate"),
message: t("keys.issuedText"),
confirmText: t("keys.rotate"),
variant: "warning",
action: async () => {
try {
const data = await apiSend(
`/mcp-keys/${encodeURIComponent(key.key_id)}/rotate`,
"POST"
);
issuedToken.value = data.token;
issuedKey.value = data;
toast.success({ title: t("keys.rotated") });
await loadKeys();
} catch (error) {
toast.danger({
title: t("errors.actionFailed"),
text: error instanceof Error ? error.message : t("errors.actionFailed")
});
}
}
});
}
function revokeKey(key) {
askConfirm({
title: t("keys.revokeConfirm"),
message: t("keys.revokeConfirmText"),
confirmText: t("keys.revoke"),
variant: "danger",
action: async () => {
try {
await apiSend(
`/mcp-keys/${encodeURIComponent(key.key_id)}`,
"DELETE"
);
toast.success({ title: t("keys.revoked") });
await loadKeys();
} catch (error) {
toast.danger({
title: t("errors.actionFailed"),
text: error instanceof Error ? error.message : t("errors.actionFailed")
});
}
}
});
}
async function copyToken() {
try {
await navigator.clipboard.writeText(issuedToken.value);
toast.success({ title: t("common.copied") });
} catch {
toast.danger({ title: t("errors.actionFailed") });
}
}
function dismissIssued() {
issuedToken.value = "";
issuedKey.value = null;
}
async function toggleAllKeys() {
if (!isAdmin.value) return;
keysShowAll.value = !keysShowAll.value;
await loadKeys();
}
async function changeLocale(value) {
if (!authEnabled.value || !user.value) {
setLocale(value);
localeOverride.value = null;
toast.success({ title: t("common.saved") });
return;
}
try {
if (value === "auto") {
await apiSend("/me", "PATCH", { locale: "" });
const data = await apiGet("/me");
user.value = data.user;
localeOverride.value = null;
setLocale(data.locale_effective || "en");
} else {
await apiSend("/me", "PATCH", { locale: value });
localeOverride.value = value;
setLocale(value);
}
toast.success({ title: t("common.saved") });
} catch (error) {
toast.danger({
title: t("errors.saveFailed"),
text: error instanceof Error ? error.message : t("errors.saveFailed")
});
}
}
function login() {
window.location.assign("/api/auth/login");
}
function logout() {
askConfirm({
title: t("auth.logoutConfirm"),
message: t("auth.logoutConfirmText"),
confirmText: t("nav.logout"),
variant: "danger",
action: async () => {
try {
await apiSend("/auth/logout", "POST");
} catch {
/* the local session is cleared regardless */
}
user.value = null;
localeOverride.value = null;
activePage.value = "docs";
toast.info({ title: t("auth.loggedOut") });
}
});
}
function askConfirm({ title, message, confirmText, variant, action }) {
confirmState.title = title || "";
confirmState.message = message || "";
confirmState.confirmText = confirmText || "";
confirmState.variant = variant || "warning";
confirmState.action = action || null;
confirmState.open = true;
}
function runConfirm() {
const action = confirmState.action;
confirmState.action = null;
if (action) action();
}
function clearConfirm() {
confirmState.action = null;
}
function go(page) {
activePage.value = page;
drawerOpen.value = false;
if (page === "keys") loadKeys();
if (page === "status") refreshStatus();
}
async function refreshAll() {
await loadMe();
}
watch(docQuery, value => {
window.clearTimeout(searchTimer);
const query = value.trim();
if (!query) {
searchResults.value = [];
searching.value = false;
return;
}
searching.value = true;
searchTimer = window.setTimeout(async () => {
try {
searchResults.value = await apiGet(
`/search?q=${encodeURIComponent(query)}`
);
} catch (error) {
toast.danger({
title: t("errors.loadFailed"),
text: error instanceof Error ? error.message : t("errors.loadFailed")
});
} finally {
searching.value = false;
}
}, 300);
});
onMounted(loadMe);
return {
activeLocaleLabel,
activePage,
applyingChange,
applyChange,
authEnabled,
booting,
canWrite,
changeError,
changeLoading,
changes,
changeStatusVariant,
clearConfirm,
confirmState,
copyToken,
createKey,
diffError,
dismissIssued,
docDiff,
docError,
docHistory,
docLoading,
docQuery,
docs,
drawerOpen,
filteredInventory,
formatDate,
freshness,
go,
healthStatus,
historyError,
inventoryDisplay,
inventoryError,
inventoryFilter,
inventoryLoading,
inventoryRaw,
inventoryRecords,
inventoryType,
inventoryTypes,
isAdmin,
isLatestVersion,
issuedKey,
issuedToken,
keyForm,
keys,
keysError,
keysLoading,
keysShowAll,
loadDiffFrom,
loadDoc,
loadInventoryType,
loadKeys,
loadLatestDiff,
locale,
localeOptions,
localeOverride,
login,
logout,
navItems,
pageError,
pageSubtitle,
pageTitle,
pretty,
proposal,
proposalRunning,
refreshAll,
restoreVersion,
revokeKey,
rotateKey,
runConfirm,
searchResults,
searching,
selectedChange,
selectedChangeId,
selectedDoc,
selectedDocPath,
selectedInventoryId,
selectedInventoryRecord,
setActiveLocale: changeLocale,
settingsItems,
statusLabel,
storage,
storageIsDb,
submitProposal,
t,
toast,
toggleAllKeys,
toggleInventoryRaw,
user,
userDisplayName,
userInitials,
validation
};
},
template: `
<main class="gnb-app">
<div v-if="booting" class="gnb-boot">
<p>{{ t('common.loading') }}…</p>
</div>
<section v-else-if="authEnabled && !user" class="gnb-gate">
<GnPageHeader
:title="t('auth.title')"
:subtitle="t('auth.subtitle')"
:kicker="t('app.kicker')"
accent
/>
<GnCard :title="t('app.title')">
<p class="gnb-lead">{{ t('auth.loginText') }}</p>
<GnAlert v-if="pageError" variant="danger">{{ pageError }}</GnAlert>
<div class="gnb-actions">
<GnButton icon="ph-sign-in" variant="accent" @click="login">{{ t('auth.login') }}</GnButton>
<GnButton icon="ph-arrow-clockwise" variant="secondary" @click="refreshAll">{{ t('auth.recheck') }}</GnButton>
</div>
</GnCard>
</section>
<section v-else class="gnb-shell">
<aside class="gnb-sidebar" :class="{ 'is-open': drawerOpen }">
<div class="gnb-brand">
<span class="gnb-brand-mark">GB</span>
<span class="gnb-brand-copy">
<strong>{{ t('app.title') }}</strong>
<small>{{ t('app.kicker') }}</small>
</span>
</div>
<nav class="gnb-nav">
<button
v-for="item in navItems"
:key="item.id"
type="button"
class="gnb-nav-item"
:class="{ 'is-active': activePage === item.id }"
@click="go(item.id)"
>
<i :class="['ph', item.icon]"></i>
<span>{{ item.label }}</span>
</button>
</nav>
<div class="gnb-sidebar-footer">
<GnUserCard
v-if="user"
:name="userDisplayName"
:email="user.email || ''"
:avatar="{ initials: userInitials }"
compact
/>
<button type="button" class="gnb-nav-item" @click="go('settings')">
<i class="ph ph-sliders"></i><span>{{ t('nav.settings') }}</span>
</button>
<button v-if="authEnabled && user" type="button" class="gnb-nav-item" @click="logout">
<i class="ph ph-sign-out"></i><span>{{ t('nav.logout') }}</span>
</button>
</div>
</aside>
<div v-if="drawerOpen" class="gnb-backdrop" @click="drawerOpen = false"></div>
<section class="gnb-main">
<GnPageHeader
:title="pageTitle"
:subtitle="pageSubtitle"
:kicker="t('app.kicker')"
accent
>
<template #actions>
<GnButton class="gnb-mobile-menu" variant="secondary" icon="ph-list" @click="drawerOpen = true">{{ t('nav.menu') }}</GnButton>
<GnButton variant="secondary" icon="ph-arrow-clockwise" :loading="booting" @click="refreshAll">{{ t('common.refresh') }}</GnButton>
</template>
</GnPageHeader>
<GnAlert v-if="pageError" variant="danger">{{ pageError }}</GnAlert>
<section v-if="activePage === 'docs'" class="gnb-page">
<div class="gnb-split">
<aside class="gnb-list gnb-panel">
<GnSearchField v-model="docQuery" :placeholder="t('docs.searchPlaceholder')" />
<div v-if="docQuery.trim()" class="gnb-list-body">
<p v-if="searching" class="gnb-muted">{{ t('common.loading') }}…</p>
<GnEmptyState v-else-if="!searchResults.length" :title="t('docs.noResults')" icon="ph-magnifying-glass" />
<button
v-for="result in searchResults"
:key="result.path"
type="button"
class="gnb-row gnb-row-button"
@click="loadDoc(result.path)"
>
<strong>{{ result.title }}</strong>
<span>{{ result.path }}</span>
<small v-for="match in result.matches" :key="result.path + '-' + match.line">{{ match.line }}: {{ match.text }}</small>
</button>
</div>
<div v-else class="gnb-list-body">
<GnEmptyState v-if="!docs.length" :title="t('docs.noDocs')" icon="ph-files" />
<button
v-for="doc in docs"
:key="doc.path"
type="button"
class="gnb-row gnb-row-button"
:class="{ 'is-active': doc.path === selectedDocPath }"
@click="loadDoc(doc.path)"
>
<strong>{{ doc.title }}</strong>
<span>{{ doc.path }}</span>
</button>
</div>
</aside>
<section class="gnb-detail">
<GnToolbar :title="selectedDoc?.path || t('docs.title')" :meta="docLoading ? t('common.loading') : t('common.preview')">
<template #actions>
<GnButton v-if="selectedDoc && storageIsDb" size="sm" variant="secondary" icon="ph-git-diff" @click="loadLatestDiff">{{ t('common.diff') }}</GnButton>
</template>
</GnToolbar>
<GnAlert v-if="docError" variant="danger">{{ docError }}</GnAlert>
<GnEmptyState v-else-if="!selectedDoc" :title="t('docs.select')" icon="ph-file-text" />
<div v-else class="gnb-doc">
<GnCard :title="t('docs.frontmatter')">
<pre class="gnb-pre">{{ pretty(selectedDoc.frontmatter) }}</pre>
</GnCard>
<GnCard :title="t('docs.body')">
<pre class="gnb-pre">{{ selectedDoc.body }}</pre>
</GnCard>
<GnCard>
<template #title><span>{{ t('docs.versions') }}</span></template>
<p v-if="historyError" class="gnb-muted">{{ historyError }}</p>
<GnEmptyState v-else-if="!docHistory.length" :title="t('docs.noHistory')" icon="ph-clock" />
<div v-else class="gnb-history">
<div v-for="version in docHistory" :key="version.version_no" class="gnb-history-row">
<button type="button" class="gnb-row-button" @click="loadDiffFrom(version.version_no)">
<strong>v{{ version.version_no }} · {{ version.summary || t('common.unknown') }}</strong>
<span>{{ version.actor_kind }} / {{ version.actor_name || '—' }} · {{ version.via }} · {{ formatDate(version.created_at) }}</span>
</button>
<GnButton
v-if="storageIsDb && !isLatestVersion(version.version_no)"
size="sm"
variant="secondary"
icon="ph-arrow-counter-clockwise"
@click="restoreVersion(version.version_no)"
>{{ t('docs.restore') }}</GnButton>
</div>
</div>
<div v-if="docDiff" class="gnb-diff">
<GnToolbar :title="t('docs.diffTitle')">
<template #actions>
<GnButton size="sm" variant="secondary" @click="docDiff = ''">{{ t('common.close') }}</GnButton>
</template>
</GnToolbar>
<pre class="gnb-pre">{{ docDiff }}</pre>
</div>
<GnAlert v-else-if="diffError" variant="warning">{{ diffError }}</GnAlert>
</GnCard>
<GnCard>
<template #title>
<span>{{ t('docs.proposalTitle') }}</span>
<small class="gnb-muted">{{ t('docs.proposalMeta') }}</small>
</template>
<div class="gnb-form">
<GnInput v-model="proposal.summary" :label="t('common.summary')" icon="ph-note-pencil" />
<GnInput v-model="proposal.target" :label="t('common.target')" icon="ph-file-md" :placeholder="t('docs.targetPlaceholder')" />
<GnInput v-model="proposal.reason" :label="t('common.reason')" icon="ph-question" />
<label class="gnb-field">
<span>{{ t('common.content') }}</span>
<textarea v-model="proposal.content" rows="12" class="input gnb-textarea" :placeholder="t('docs.contentPlaceholder')"></textarea>
</label>
<div class="gnb-actions">
<GnButton variant="success" icon="ph-plus" :loading="proposalRunning" :disabled="!canWrite" @click="submitProposal">{{ t('docs.submit') }}</GnButton>
</div>
</div>
</GnCard>
</div>
</section>
</div>
</section>
<section v-else-if="activePage === 'inventory'" class="gnb-page">
<div class="gnb-split">
<aside class="gnb-list gnb-panel">
<GnEmptyState v-if="!inventoryTypes.length" :title="t('inventory.noTypes')" icon="ph-database" />
<button
v-for="type in inventoryTypes"
:key="type"
type="button"
class="gnb-row gnb-row-button"
:class="{ 'is-active': type === inventoryType }"
@click="loadInventoryType(type)"
>
<strong>{{ type }}</strong>
<span>{{ type === inventoryType ? t('inventory.recordCount', { n: inventoryRecords.length }) : '—' }}</span>
</button>
</aside>
<section class="gnb-detail">
<GnToolbar
:title="inventoryType || t('inventory.title')"
:meta="inventoryLoading ? t('common.loading') : t('inventory.recordCount', { n: inventoryRecords.length })"
>
<template #actions>
<GnButton size="sm" :variant="inventoryRaw ? 'accent' : 'secondary'" @click="toggleInventoryRaw">
{{ inventoryRaw ? t('inventory.jsonView') : t('inventory.rawView') }}
</GnButton>
</template>
</GnToolbar>
<GnAlert v-if="inventoryError" variant="danger">{{ inventoryError }}</GnAlert>
<GnEmptyState v-else-if="!inventoryType" :title="t('inventory.selectType')" icon="ph-database" />
<div v-else class="gnb-split gnb-inventory-detail">
<aside class="gnb-list gnb-panel">
<GnSearchField v-model="inventoryFilter" :placeholder="t('inventory.filterPlaceholder')" />
<div class="gnb-list-body">
<GnEmptyState v-if="!filteredInventory.length" :title="t('inventory.noRecords')" icon="ph-database" />
<button
v-for="item in filteredInventory"
:key="item.id || item.fqdn || item.name"
type="button"
class="gnb-row gnb-row-button"
:class="{ 'is-active': item.id === selectedInventoryId }"
@click="selectedInventoryId = item.id"
>
<strong>{{ item.name || item.fqdn || item.id || t('common.unknown') }}</strong>
<span>{{ item.id || t('common.none') }}</span>
</button>
</div>
</aside>
<GnCard>
<template #title>
<span>{{ inventoryRaw ? t('inventory.rawView') : t('common.json') }}</span>
</template>
<GnAlert v-if="inventoryRaw" variant="info">{{ t('inventory.rawNotice') }}</GnAlert>
<pre v-if="inventoryDisplay" class="gnb-pre">{{ inventoryDisplay }}</pre>
<GnEmptyState v-else :title="t('inventory.selectRecord')" icon="ph-database" />
</GnCard>
</div>
</section>
</div>
</section>
<section v-else-if="activePage === 'changes'" class="gnb-page">
<div class="gnb-split">
<aside class="gnb-list gnb-panel">
<GnEmptyState v-if="!changes.length" :title="t('changes.noChanges')" icon="ph-git-pull-request" />
<button
v-for="change in changes"
:key="change.id"
type="button"
class="gnb-row gnb-row-button"
:class="{ 'is-active': change.id === selectedChangeId }"
@click="selectedChangeId = change.id; loadChange(change.id)"
>
<strong>{{ change.summary }}</strong>
<span>{{ statusLabel(change.status) }} · {{ change.kind }} · {{ change.target }}</span>
<GnBadge :variant="changeStatusVariant(change.status)">{{ statusLabel(change.status) }}</GnBadge>
</button>
</aside>
<section class="gnb-detail">
<GnToolbar
:title="selectedChange?.summary || t('changes.title')"
:meta="changeLoading ? t('common.loading') : statusLabel(selectedChange?.status || '')"
>
<template #actions>
<GnButton
v-if="selectedChange && ['draft', 'pending'].includes(selectedChange.status) && canWrite"
variant="success"
icon="ph-check"
:loading="applyingChange"
@click="applyChange(selectedChange)"
>{{ t('changes.apply') }}</GnButton>
</template>
</GnToolbar>
<GnAlert v-if="changeError" variant="danger">{{ changeError }}</GnAlert>
<GnEmptyState v-else-if="!selectedChange" :title="t('changes.select')" icon="ph-git-pull-request" />
<div v-else class="gnb-change-detail">
<GnCard :title="t('common.details')">
<pre class="gnb-pre">{{ pretty(selectedChange) }}</pre>
</GnCard>
<GnCard :title="t('changes.validation')">
<p v-if="!selectedChange.validation" class="gnb-muted">{{ t('changes.noValidation') }}</p>
<template v-else>
<div class="gnb-badges">
<GnBadge :variant="selectedChange.validation.status === 'ok' ? 'success' : 'danger'">{{ selectedChange.validation.status }}</GnBadge>
<span>{{ t('common.issueCount', { n: selectedChange.validation.issue_count || 0 }) }}</span>
</div>
<IssueList :issues="selectedChange.validation.issues || []" />
</template>
</GnCard>
</div>
</section>
</div>
</section>
<section v-else-if="activePage === 'status'" class="gnb-page">
<div class="gnb-metrics">
<GnMetricCard
:label="t('status.validation')"
:value="validation?.status || t('common.unknown')"
icon="ph-shield-check"
:meta="t('common.issueCount', { n: validation?.issue_count || 0 })"
/>
<GnMetricCard
:label="t('status.freshness')"
:value="freshness?.status || t('common.unknown')"
icon="ph-clock"
:meta="t('common.issueCount', { n: freshness?.issue_count || 0 })"
/>
<GnMetricCard
:label="t('status.documents')"
:value="String(freshness?.document_count ?? '—')"
icon="ph-files"
:meta="t('status.storage') + ': ' + storage"
/>
</div>
<div class="gnb-split">
<GnCard :title="t('status.validation')">
<IssueList :issues="(validation && validation.issues) || []" />
</GnCard>
<GnCard :title="t('status.freshness')">
<IssueList :issues="(freshness && freshness.issues) || []" />
</GnCard>
</div>
</section>
<section v-else-if="activePage === 'keys'" class="gnb-page">
<GnAlert v-if="!authEnabled" variant="info">{{ t('keys.notConfigured') }}</GnAlert>
<div v-else class="gnb-split">
<GnCard :title="t('keys.createTitle')">
<p class="gnb-muted">{{ t('keys.createMeta') }}</p>
<div class="gnb-form">
<GnInput v-model="keyForm.consumer" :label="t('keys.consumer')" icon="ph-robot" placeholder="navi" />
<GnInput v-model="keyForm.name" :label="t('keys.name')" icon="ph-tag" />
<div class="gnb-actions">
<GnButton variant="success" icon="ph-key" :loading="keysLoading" @click="createKey">{{ t('keys.create') }}</GnButton>
<GnButton v-if="isAdmin" variant="secondary" @click="toggleAllKeys">{{ keysShowAll ? t('keys.own') : t('keys.showAll') }}</GnButton>
</div>
</div>
<GnAlert v-if="issuedToken && issuedKey" variant="success">
<strong>{{ t('keys.issuedTitle') }}</strong>
<p>{{ t('keys.issuedText') }}</p>
<p class="gnb-muted">{{ issuedKey.consumer }} · …{{ issuedKey.token_hint }}</p>
<code class="gnb-token">{{ issuedToken }}</code>
<div class="gnb-actions">
<GnButton size="sm" icon="ph-copy" variant="secondary" @click="copyToken">{{ t('keys.copyToken') }}</GnButton>
<GnButton size="sm" variant="secondary" @click="dismissIssued">{{ t('common.close') }}</GnButton>
</div>
</GnAlert>
<GnAlert v-if="keysError" variant="danger">{{ keysError }}</GnAlert>
</GnCard>
<GnCard :title="keysShowAll ? t('keys.showAll') : t('keys.own')">
<GnEmptyState v-if="!keys.length" :title="t('keys.noKeys')" icon="ph-key" />
<div v-else class="gnb-keys">
<div v-for="key in keys" :key="key.key_id" class="gnb-key-row">
<div class="gnb-key-copy">
<strong>{{ key.name }}</strong>
<span class="gnb-muted">{{ key.consumer }} · {{ key.role || t('common.unknown') }} · {{ (key.scopes || []).join(', ') }} · …{{ key.token_hint }}</span>
<span class="gnb-muted">{{ t('common.created') }}: {{ formatDate(key.created_at) }} · {{ t('common.lastUsed') }}: {{ formatDate(key.last_used_at) }}</span>
<div class="gnb-badges">
<GnBadge v-if="key.revoked_at" variant="danger">{{ t('common.revoked') }}</GnBadge>
<GnBadge v-if="key.stale_at" variant="warning">{{ t('common.stale') }}</GnBadge>
</div>
</div>
<div class="gnb-actions">
<GnButton v-if="!key.revoked_at" size="sm" variant="secondary" icon="ph-arrows-clockwise" @click="rotateKey(key)">{{ t('keys.rotate') }}</GnButton>
<GnButton v-if="!key.revoked_at" size="sm" variant="danger" icon="ph-trash" @click="revokeKey(key)">{{ t('keys.revoke') }}</GnButton>
</div>
</div>
</div>
</GnCard>
</div>
</section>
<section v-else-if="activePage === 'settings'" class="gnb-page">
<div class="gnb-split">
<GnCard :title="t('settings.language')">
<p class="gnb-muted">{{ t('settings.languageMeta') }}</p>
<div class="gnb-actions gnb-language-actions">
<GnButton v-if="authEnabled" :variant="localeOverride ? 'secondary' : 'accent'" @click="setActiveLocale('auto')">{{ t('auth.localeAuto') }}</GnButton>
<GnButton
v-for="option in localeOptions"
:key="option.value"
:variant="locale === option.value ? 'accent' : 'secondary'"
@click="setActiveLocale(option.value)"
>{{ option.label }}</GnButton>
</div>
</GnCard>
<GnCard :title="t('common.details')">
<GnDescriptionList :items="settingsItems" />
<div v-if="authEnabled && user" class="gnb-actions">
<GnButton variant="danger" icon="ph-sign-out" @click="logout">{{ t('nav.logout') }}</GnButton>
</div>
</GnCard>
</div>
</section>
</section>
</section>
<GnConfirmDialog
v-model:open="confirmState.open"
:title="confirmState.title"
:message="confirmState.message"
:confirm-text="confirmState.confirmText || t('common.confirm')"
:cancel-text="t('common.cancel')"
:confirm-variant="confirmState.variant"
@confirm="runConfirm"
@cancel="clearConfirm"
/>
</main>
`
};
const App = {
components: {
AppScreen,
GnToastProvider
},
template: `
<GnToastProvider>
<AppScreen />
</GnToastProvider>
`
};
createApp(App).mount("#app");