BluKavantUI Design system
OUTSYSTEMS

Explore the source & backend

Inspect the real customer-workspace files, follow a save to SQLite, and download a runnable project.

← OutSystems export & modernization
THE DOWNLOAD, OPENED UP

Real files. Ready for your editor.

Browse the actual files from the customer-workspace ZIP. The frontend, backend, shared types and tests are plain source files you can edit in your own project.

The live demo adds a separate sample database for each visitor, automatic two-hour cleanup and a reset action. Download the live-demo source ↓. The original source walkthrough below remains matched to the v1.0.0 project.

client/main.ts

The actual browser entry: Grid and Drawer configuration, load/save requests, drafts, validation and event handlers. Change the interface here.

Download this file ↓
Verbatim source · Interface
import '@blukavantui/web/theme.css';
import '@blukavantui/web/grid.css';
import '@blukavantui/web/drawer.css';
import '@blukavantui/web/button.css';
import { createGrid } from '@blukavantui/web/grid';
import { createDrawer } from '@blukavantui/web/drawer';
import { createButton } from '@blukavantui/web/button';
import { mountAppearanceSelector } from '@blukavantui/web/theme';
import type { Customer, Session, SaveIssue } from '../shared/customer.ts';
import './style.css';

const root = document.querySelector<HTMLDivElement>('#app')!;
let session: Session | null = null;
let teardown = () => {};
class ApiError extends Error {
  status: number; issues: SaveIssue[];
  constructor(status: number, message: string, issues: SaveIssue[] = []) { super(message); this.status = status; this.issues = issues; }
}
async function api<T>(path: string, body?: unknown): Promise<T> {
  const response = await fetch(`/api${path}`, {
    method: body === undefined ? 'GET' : 'POST', credentials: 'same-origin',
    headers: body === undefined ? {} : { 'Content-Type': 'application/json', 'X-CSRF-Token': session?.csrf || '' },
    body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(15000),
  });
  if (response.status === 204) return undefined as T;
  const data = await response.json();
  if (!response.ok) throw new ApiError(response.status, data.error || 'The request failed.', data.issues);
  return data as T;
}
function text(id: string, value: string) { document.getElementById(id)!.textContent = value; }
const message = (error: unknown) => error instanceof Error ? error.message : 'The request could not be completed.';
const logo = '<span class="brand-mark" aria-hidden="true">b<span>k</span></span><span>BluKavant<span class="brand-sub">WORKSPACE</span></span>';
const icon = (path: string) => `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${path}</svg>`;
const peopleIcon = icon('<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2m20 0v-2a4 4 0 0 0-3-3.87"/><circle cx="9" cy="7" r="4"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>');

async function showLogin() {
  teardown(); session = null;
  root.innerHTML = `<main id="main" class="login-page"><div class="login-story"><div class="brand">${logo}</div><div class="login-copy"><span class="eyebrow">YOUR CUSTOMER WORKSPACE</span><h1>Every customer.<br>A clearer picture.</h1><p>A familiar place to explore your accounts and keep the details up to date.</p><div class="story-line"></div><span class="story-caption">Built with BluKavantUI</span></div><span class="login-footnote">Customer workspace · Local preview</span></div><section class="login-panel"><div class="login-card"><span class="eyebrow">WELCOME BACK</span><h2>Open your workspace</h2><p class="muted">Sign in to browse and manage customer records.</p><form id="login-form"><label>Username<input name="username" autocomplete="username" required value="editor"></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button class="primary-button" type="submit">Sign in <span aria-hidden="true">→</span></button></form><p id="login-error" class="error" role="alert"></p><div id="demo-entry" hidden><div class="or"><span>LOCAL DEMO</span></div><p class="muted">Explore 250 sample customers. Changes are saved on this computer.</p><button id="demo-editor" class="primary-button" type="button">Continue as editor <span aria-hidden="true">→</span></button><button id="demo-viewer" class="secondary-button" type="button">Explore as viewer</button><p class="demo-note">Editor can save changes. Viewer has read-only access.</p></div></div></section></main>`;
  async function login(username: string, password: string) {
    const controls = [...root.querySelectorAll<HTMLButtonElement>('button')]; controls.forEach(b => b.disabled = true);
    text('login-error', '');
    try { session = await api<Session>('/login', { username, password }); await showWorkspace(); }
    catch (error) { const output = document.getElementById('login-error'); if (output) output.textContent = message(error); controls.forEach(b => b.disabled = false); }
  }
  root.querySelector<HTMLFormElement>('#login-form')!.onsubmit = e => {
    e.preventDefault(); const data = new FormData(e.currentTarget as HTMLFormElement); void login(String(data.get('username')), String(data.get('password')));
  };
  try {
    const config = await api<{ demo: boolean }>('/config');
    if (config.demo) {
      document.getElementById('demo-entry')!.hidden = false;
      root.querySelector<HTMLFormElement>('#login-form')!.hidden = true;
      document.getElementById('demo-editor')!.onclick = () => void login('editor', 'local-demo');
      document.getElementById('demo-viewer')!.onclick = () => void login('viewer', 'local-demo');
    }
  } catch { text('login-error', 'Could not reach the server. Refresh the page to try again.'); }
}

async function showWorkspace() {
  teardown();
  const editor = session!.user.role === 'editor';
  root.innerHTML = `<div class="workspace"><aside class="sidebar"><a href="/" class="brand" aria-label="BluKavant workspace">${logo}</a><div class="nav-caption">WORKSPACE</div><a class="nav-item active" href="#main" aria-current="page">${peopleIcon}<span>Customers</span><span class="nav-count">250</span></a><div class="sidebar-bottom"><div class="local-badge"><span class="live-dot"></span>Local workspace</div><p>Your data stays in this app.</p><div class="profile"><span class="avatar">${editor ? 'E' : 'V'}</span><span><strong>${editor ? 'Demo editor' : 'Demo viewer'}</strong><small>${editor ? 'Can edit customers' : 'Read-only access'}</small></span><button id="logout" title="Sign out" aria-label="Sign out">${icon('<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4m7 14 5-5-5-5m5 5H9"/>')}</button></div></div></aside><div class="workspace-body"><header class="topbar"><div class="breadcrumb">Workspace <span>/</span> <strong>Customers</strong></div><div class="topbar-actions"><span class="sample-pill">Sample data</span><div id="appearance"></div></div></header><main id="main" tabindex="-1"><div class="page-heading"><div><span class="eyebrow">CUSTOMER OPERATIONS</span><h1>Customer workspace<span class="title-dot">.</span></h1><p class="muted">A clear view of your customers. Keep every detail current.</p></div><div id="reload"></div></div><section class="metrics" aria-label="Customer overview"><article><span>Total customers</span><strong id="total">—</strong><small>Across your workspace</small></article><article><span>Active accounts</span><strong id="active">—</strong><small><span class="live-dot"></span>Currently active</small></article><article><span>Total seats</span><strong id="seats">—</strong><small>Across all customers</small></article><article><span>Total revenue</span><strong id="revenue">—</strong><small>USD · all customers</small></article></section><section class="records" aria-labelledby="records-title"><div class="records-heading"><div><h2 id="records-title">All customers <span id="count-badge" class="count-badge">—</span></h2><p>${editor ? 'Select Edit customer to update a record.' : 'You can browse, search and filter customer records.'}</p></div><span class="permission-pill">${editor ? 'Editor access' : 'View only'}</span></div><div class="filter-bar"><label class="search"><span aria-hidden="true">${icon('<circle cx="10.5" cy="10.5" r="6.5"/><path d="m16 16 4 4"/>')}</span><input id="search" type="search" placeholder="Search customers…" aria-label="Search customers"><kbd aria-hidden="true">/</kbd></label><label class="status-filter">Status<select id="status-filter"><option value="all">All statuses</option><option value="active">Active</option><option value="inactive">Inactive</option></select></label><button id="clear-filters" class="text-button" type="button">Clear search &amp; status</button></div><div id="grid-region" aria-label="Customer records"></div><div class="records-footer"><span id="status" role="status" aria-live="polite">Loading customers…</span><span class="saved-note"><span class="live-dot"></span>Saved to this workspace</span></div><p id="page-error" class="error" role="alert"></p></section><footer class="page-footer"><span>BluKavant customer workspace</span><span>250 sample records · independent application</span></footer></main></div></div><div id="drawer-host"></div>`;
  mountAppearanceSelector(document.getElementById('appearance')!);
  let rows: Customer[] = [];
  let original: Customer | null = null;
  let loading = false, saving = false, outcomeUnknown = false, disposed = false;
  const search = document.getElementById('search') as HTMLInputElement;
  const filter = document.getElementById('status-filter') as HTMLSelectElement;
  const form = document.createElement('form'); form.className = 'customer-form';
  form.innerHTML = `<div class="record-identity"><span class="avatar large" id="customer-initial">C</span><div><strong id="customer-title"></strong><span id="customer-meta"></span></div></div><label>Customer name<input id="edit-name" name="name" required maxlength="200" autocomplete="organization"></label><div class="field-pair"><label>Seats<input id="edit-seats" name="seats" required inputmode="numeric" pattern="[0-9]+"></label><label>Revenue (USD)<input id="edit-revenue" name="revenue" required inputmode="decimal" pattern="[0-9]+([.][0-9]{1,2})?"></label></div><div class="editor-note">Changes are saved when you choose <strong>Save customer</strong>. Cancel leaves the stored record unchanged.</div><div id="drawer-error" class="error" role="alert"></div><div class="version-note">Version checked on save. If another session updates this record, reload customers before trying again.</div>`;
  const name = form.querySelector<HTMLInputElement>('#edit-name')!;
  const seats = form.querySelector<HTMLInputElement>('#edit-seats')!;
  const revenue = form.querySelector<HTMLInputElement>('#edit-revenue')!;
  function enableControls() {
    reload.update({ IsDisabled: loading || saving || !!original, IsLoading: loading });
    document.querySelector<HTMLButtonElement>('#logout')!.disabled = saving || !!original;
    form.querySelectorAll<HTMLInputElement>('input').forEach(input => input.disabled = saving || outcomeUnknown);
  }
  function closeEditor() { if (saving) return; drawer.update({ IsOpen: false }); original = null; enableControls(); }
  const drawer = createDrawer(document.getElementById('drawer-host')!, {
    Title: 'Edit customer', Description: 'Keep this customer’s details up to date.', Size: 'Medium',
    Content: form, ConfirmLabel: 'Save customer', IsOpen: false, ExtendedClass: 'customer-drawer',
  }, {
    OpenChanged: open => { if (!open) closeEditor(); },
    Confirm: () => void save(),
    Error: error => { text('drawer-error', String(error)); },
  });
  function openEditor(row: Customer) {
    if (!editor || loading || saving || original || outcomeUnknown) return;
    original = structuredClone(row);
    name.value = row.Name; seats.value = String(row.Seats); revenue.value = row.Revenue.toFixed(2);
    text('customer-title', row.Name); text('customer-meta', `Customer #${row.Id} · Version ${row.Version}`); text('customer-initial', row.Name.slice(0, 1)); text('drawer-error', '');
    drawer.update({ IsOpen: true, IsBusy: false, CloseOnBackdrop: true, CloseOnEscape: true, InstanceKey: row.Id }); enableControls();
  }
  const grid = createGrid<Customer>(document.getElementById('grid-region')!, {
    RowKeyField: 'Id', Mode: 'Client', Rows: [],
    Columns: [
      ...(editor ? [{ Field: 'Id' as const, Header: 'Action', Renderer: 'Action' as const, ActionKey: 'edit', ActionLabel: 'Edit customer', Width: 150, MinWidth: 150, IsSortable: false, IsFilterable: false }] : []),
      { Field: 'Name', Header: 'Customer', Flex: 2, MinWidth: 220, IsSortable: true, IsFilterable: true },
      { Field: 'Seats', Header: 'Seats', Type: 'Number', Width: 120, MinWidth: 110, IsSortable: true, IsFilterable: true, DecimalPlaces: 0 },
      { Field: 'Revenue', Header: 'Revenue', Type: 'Currency', Flex: 1, MinWidth: 150, IsSortable: true, IsFilterable: true },
      { Field: 'Active', Header: 'Active', Type: 'Boolean', Renderer: 'Badge', Width: 110, MinWidth: 110, IsSortable: true, IsFilterable: true },
    ],
    Config: { Height: '580px', RowHeight: 48, SelectionMode: 'None', IsReadOnly: true, ShowEditToolbar: false, EnablePagination: true, PageSize: 10, CurrencyCode: 'USD', Locale: 'en-US', IsLoading: true },
    Events: { OnRowAction: event => openEditor(event.Row), OnRowDoubleClick: event => openEditor(event.Row), OnDataError: event => text('page-error', event.Message) },
  });
  const reload = createButton(document.getElementById('reload')!, { Label: 'Reload customers', Variant: 'Outlined', Color: 'Default' }, { Click: () => load() });
  function renderRows() {
    const visible = rows.filter(row => filter.value === 'all' || row.Active === (filter.value === 'active'));
    grid.setData(visible); grid.setSearch(search.value);
    text('total', rows.length.toLocaleString()); text('active', rows.filter(row => row.Active).length.toLocaleString());
    text('seats', rows.reduce((sum, row) => sum + row.Seats, 0).toLocaleString());
    text('revenue', new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(rows.reduce((sum, row) => sum + row.Revenue, 0)));
    text('count-badge', String(visible.length));
  }
  async function load() {
    if (original || saving || loading) return;
    loading = true; enableControls(); text('page-error', ''); text('status', 'Loading customers…');
    grid.update({ Config: { IsLoading: true } });
    try {
      const currentSession = await api<Session>('/session'); if (disposed) return;
      const roleChanged = currentSession.user.role !== session!.user.role;
      session = currentSession;
      if (roleChanged) { await showWorkspace(); return; }
      const result = await api<{ rows: Customer[] }>('/customers'); if (disposed) return;
      rows = result.rows; outcomeUnknown = false; renderRows();
      text('status', `Loaded ${rows.length} customers. All changes are saved to the database.`);
    } catch (error) {
      if (disposed) return;
      text('page-error', message(error)); text('status', 'Loading failed. Use Reload customers to retry.');
      if (error instanceof ApiError && error.status === 401) { await showLogin(); return; }
    } finally { if (!disposed) { loading = false; grid.update({ Config: { IsLoading: false } }); enableControls(); } }
  }
  async function save() {
    if (!original || saving || outcomeUnknown || !editor) return;
    if (!form.reportValidity()) return;
    const draft = { ...original, Name: name.value.trim(), Seats: Number(seats.value), Revenue: Number(revenue.value) };
    if (!draft.Name || draft.Name.length > 200) { text('drawer-error', 'Enter a customer name of 1 to 200 characters.'); return; }
    if (!/^\d+$/.test(seats.value) || draft.Seats > 1000000) { text('drawer-error', 'Seats must be a whole number from 0 to 1000000.'); return; }
    if (!/^\d+(\.\d{1,2})?$/.test(revenue.value) || draft.Revenue > 1000000000) { text('drawer-error', 'Revenue must be 0–1000000000, with at most two decimal places.'); return; }
    if (draft.Name === original.Name && draft.Seats === original.Seats && draft.Revenue === original.Revenue) { text('drawer-error', 'No changes to save.'); return; }
    saving = true; text('drawer-error', '');
    drawer.update({ IsBusy: true, CloseOnBackdrop: false, CloseOnEscape: false }); enableControls();
    try {
      const result = await api<{ rows: Customer[] }>('/customers/save', { requestId: crypto.randomUUID(), changes: [{ original, draft }] });
      if (disposed) return;
      const saved = result.rows[0]; if (!saved || saved.Id !== original.Id || saved.Version !== original.Version + 1) throw new Error('Unexpected save response.');
      rows = rows.map(row => row.Id === saved.Id ? saved : row); renderRows();
      saving = false; closeEditor(); text('status', `Saved ${saved.Name} · version ${saved.Version}. Reload to confirm the stored values.`);
    } catch (error) {
      if (disposed) return;
      if (!(error instanceof ApiError) || error.status >= 500) { outcomeUnknown = true; text('drawer-error', 'The save result could not be confirmed. Close this editor and reload customers before editing again. Your draft is still shown here.'); }
      else text('drawer-error', message(error));
    } finally {
      if (!disposed) { saving = false; drawer.update({ IsBusy: outcomeUnknown, CloseOnEscape: true, CloseOnBackdrop: true }); enableControls(); }
    }
  }
  form.onsubmit = e => { e.preventDefault(); void save(); };
  search.oninput = () => grid.setSearch(search.value);
  filter.onchange = () => { renderRows(); text('status', filter.value === 'all' ? 'Showing all customer statuses.' : `Showing ${filter.value} customers.`); };
  document.getElementById('clear-filters')!.onclick = () => { search.value = ''; filter.value = 'all'; renderRows(); text('status', 'Search and status filters cleared.'); };
  document.getElementById('logout')!.onclick = async () => {
    if (saving || original) return;
    try { await api('/logout', {}); await showLogin(); }
    catch (error) {
      if (error instanceof ApiError && [401,403].includes(error.status)) await showLogin();
      else text('page-error', message(error));
    }
  };
  const keyHandler = (event: KeyboardEvent) => { if (event.key === '/' && !original && !/INPUT|TEXTAREA|SELECT/.test((event.target as HTMLElement).tagName)) { event.preventDefault(); search.focus(); } };
  const beforeUnload = (event: BeforeUnloadEvent) => { if (saving || original && (name.value !== original.Name || seats.value !== String(original.Seats) || Number(revenue.value) !== original.Revenue)) event.preventDefault(); };
  window.addEventListener('keydown', keyHandler); window.addEventListener('beforeunload', beforeUnload);
  teardown = () => { disposed = true; grid.destroy(); drawer.destroy(); reload.destroy(); window.removeEventListener('keydown', keyHandler); window.removeEventListener('beforeunload', beforeUnload); };
  await load();
}
try { session = await api<Session>('/session'); await showWorkspace(); }
catch { await showLogin(); }

client/style.css

The standalone shell, spacing, typography, responsive layout and component presentation. These are ordinary stylesheets in the project.

Download this file ↓
Verbatim source · Design
@font-face{font-family:Inter;src:local('Inter');font-display:swap}
:root{font-family:Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;color:#252633;background:#f6f6f9;font-synthesis:none;--surface:#fff;--canvas:#f6f6f9;--ink:#252633;--muted:#737480;--line:#e7e7ee;--accent:#6554c6;--soft:#f0edf9;--side:#fafafd;--green:#248768}
*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button,a,input,select{outline-offset:4px}button{cursor:pointer}button:disabled{cursor:wait;opacity:.55}a{color:inherit;text-decoration:none}[hidden]{display:none!important}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #8974e4}h1,h2,p{margin:0}.muted{color:var(--muted);line-height:1.7}.error{color:#b42318;font-size:14px;line-height:1.6;white-space:pre-wrap}.error:empty{display:none}.skip-link{position:fixed;left:12px;top:-80px;z-index:10000;padding:12px;background:var(--surface)}.skip-link:focus{top:12px}.boot-message{padding:40px}.brand{display:flex;gap:12px;align-items:center;font-size:21px;font-weight:720;letter-spacing:-.65px}.brand-mark{display:flex;align-items:center;justify-content:center;width:39px;height:39px;background:var(--accent);border-radius:12px;color:white;font-size:28px;letter-spacing:-3px;padding-right:3px;font-weight:650}.brand-mark>span{font-size:22px;align-self:flex-end;margin-bottom:6px}.brand-sub{display:block;font-size:9px;letter-spacing:2.4px;color:var(--muted);margin-top:5px;font-weight:600}.eyebrow{font-size:10px;letter-spacing:2px;font-weight:700;color:var(--muted)}
.workspace{display:flex;min-height:100vh}.sidebar{position:fixed;width:232px;height:100dvh;background:var(--side);border-right:1px solid var(--line);padding:30px 20px;display:flex;flex-direction:column}.sidebar .brand{padding-left:6px}.nav-caption{font-size:10px;letter-spacing:1.7px;font-weight:650;color:var(--muted);margin:49px 15px 15px}.nav-item{display:flex;align-items:center;gap:12px;padding:13px;border-radius:9px;font-size:13px;font-weight:600}.nav-item.active{background:var(--soft);color:var(--accent)}.nav-count{margin-left:auto;font-size:10px;background:var(--surface);padding:3px 6px;border-radius:5px}.sidebar-bottom{margin-top:auto;font-size:11px}.local-badge{display:flex;align-items:center;gap:8px;font-weight:600}.live-dot{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--green);vertical-align:middle}.sidebar-bottom>p{margin:8px 0 24px;color:var(--muted)}.profile{display:flex;align-items:center;gap:10px;padding-top:21px;border-top:1px solid var(--line)}.avatar{display:flex;align-items:center;justify-content:center;background:var(--soft);color:var(--accent);font-size:13px;font-weight:700;width:34px;height:34px;border-radius:50%;flex-shrink:0}.profile strong{font-size:12px;font-weight:600}.profile small{display:block;font-size:10px;color:var(--muted);margin-top:4px}.profile button{border:0;background:transparent;margin-left:auto;color:var(--muted);padding:8px}.workspace-body{margin-left:232px;min-width:0;flex:1}.topbar{height:76px;padding:0 44px;border-bottom:1px solid var(--line);background:var(--surface);display:flex;justify-content:space-between;align-items:center}.breadcrumb{font-size:12px;color:var(--muted);display:flex;gap:15px}.breadcrumb strong{font-weight:500;color:var(--ink)}.topbar-actions{display:flex;align-items:center;gap:18px}.sample-pill{font-size:10px;padding:5px 9px;border:1px solid var(--line);border-radius:6px;color:var(--muted)}#appearance select{font-size:11px;background:transparent;border:0;color:var(--muted);padding:7px}main#main:not(.login-page){padding:40px 44px 24px;max-width:1600px;margin:0 auto}.page-heading{display:flex;justify-content:space-between;align-items:center;gap:20px;margin-bottom:32px}.page-heading h1{font-size:30px;letter-spacing:-1px;font-weight:650;margin:10px 0}.title-dot{color:var(--accent)}.page-heading p{font-size:13px}.page-heading .blu-button{font-size:12px}.metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin-bottom:30px}.metrics article{background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:22px}.metrics article>span{font-size:11px;color:var(--muted);font-weight:500}.metrics strong{display:block;font-size:29px;letter-spacing:-1px;font-weight:600;margin:14px 0 9px}.metrics small{font-size:10px;color:var(--muted)}.metrics .live-dot{margin-right:4px}.records{border:1px solid var(--line);border-radius:13px;background:var(--surface);overflow:hidden}.records-heading{display:flex;justify-content:space-between;align-items:center;padding:25px 26px 22px;gap:16px}.records h2{display:flex;gap:10px;align-items:center;font-size:16px;font-weight:600;letter-spacing:-.3px}.count-badge{font-size:10px;font-weight:500;background:var(--soft);color:var(--accent);border-radius:5px;padding:4px 7px}.records-heading p{font-size:11px;color:var(--muted);margin-top:8px}.permission-pill{font-size:10px;border:1px solid var(--line);border-radius:99px;padding:6px 9px;color:var(--muted);white-space:nowrap}.filter-bar{padding:0 26px 20px;display:flex;gap:12px;align-items:center;flex-wrap:wrap}.search{display:flex;align-items:center;gap:10px;border:1px solid var(--line);border-radius:7px;padding:9px 12px;flex:1;max-width:360px;color:var(--muted);background:var(--surface);min-width:180px}.search input{border:0;background:transparent;width:100%;font-size:12px;color:var(--ink);min-width:0}.search input:focus{outline:none}.search:focus-within{outline:2px solid var(--accent);outline-offset:2px}.search svg{display:block;width:16px;height:16px}.search kbd{font-size:10px;border:1px solid var(--line);padding:1px 5px;border-radius:3px}.status-filter{display:flex;align-items:center;gap:8px;font-size:11px;color:var(--muted)}.status-filter select{font-size:12px;border:1px solid var(--line);padding:10px 25px 10px 10px;border-radius:7px;background:var(--surface);color:var(--ink)}.text-button{border:0;background:transparent;color:var(--accent);font-size:11px;padding:10px;margin-left:auto}#grid-region{min-width:0;padding:0 16px}#grid-region .blu-grid{border-radius:0}#grid-region .blu-grid-toolbar{display:none}.records-footer{padding:18px 26px;border-top:1px solid var(--line);display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:10px;color:var(--muted);line-height:1.6}.saved-note{white-space:nowrap}.saved-note .live-dot{margin-right:5px}#page-error{padding:0 26px 18px}.page-footer{display:flex;justify-content:space-between;font-size:10px;color:var(--muted);margin-top:22px}.customer-form{display:grid;gap:24px}.customer-form label,.login-card form label{display:grid;gap:9px;font-size:12px;font-weight:500}.customer-form input,.login-card input{min-width:0;width:100%;background:var(--surface);color:var(--ink);border:1px solid var(--line);padding:12px 13px;border-radius:7px;font-size:14px;min-height:45px}.field-pair{display:grid;grid-template-columns:1fr 1fr;gap:16px}.editor-note{font-size:12px;line-height:1.8;color:var(--muted);background:var(--canvas);border-radius:8px;padding:16px}.editor-note strong{font-weight:500;color:var(--ink)}.version-note{font-size:11px;line-height:1.8;color:var(--muted);padding-top:10px;border-top:1px solid var(--line)}.record-identity{display:flex;gap:12px;align-items:center;padding-bottom:22px;border-bottom:1px solid var(--line)}.avatar.large{width:46px;height:46px;font-size:20px}.record-identity strong{display:block;font-size:15px}.record-identity span:not(.avatar){display:block;color:var(--muted);font-size:11px;margin-top:5px}
.login-page{min-height:100dvh;display:grid;grid-template-columns:1fr 1fr}.login-story{padding:48px 64px;background:#eeebf6;display:flex;flex-direction:column;color:#302c42}.login-copy{margin:auto 0;padding:60px 0}.login-copy h1{font-size:clamp(38px,4vw,60px);line-height:1.15;font-weight:600;letter-spacing:-2px;margin:22px 0}.login-copy p{color:#716b82;max-width:350px;font-size:15px;line-height:1.9}.story-line{width:56px;height:2px;background:#b6a8d4;margin:42px 0 22px}.story-caption,.login-footnote{font-size:11px;letter-spacing:.4px;color:#82798f}.login-panel{display:grid;place-items:center;padding:48px;background:var(--surface)}.login-card{width:100%;max-width:360px}.login-card h2{font-size:28px;font-weight:600;letter-spacing:-1px;margin:16px 0 10px}.login-card>.muted{font-size:13px}.login-card form{display:grid;gap:20px;margin-top:28px}.primary-button,.secondary-button{width:100%;border-radius:8px;padding:13px 17px;min-height:46px;font-size:13px;font-weight:550;display:flex;align-items:center;justify-content:space-between}.primary-button{background:var(--accent);color:#fff;border:1px solid var(--accent)}.secondary-button{border:1px solid var(--line);color:var(--ink);background:var(--surface);justify-content:center;margin-top:12px}.primary-button:hover{filter:brightness(1.08)}.or{display:flex;gap:12px;align-items:center;font-size:9px;color:var(--muted);letter-spacing:1.7px;margin:32px 0 20px}.or:before,.or:after{content:'';height:1px;background:var(--line);flex:1}#demo-entry>.muted{font-size:12px;margin-bottom:20px}.demo-note{font-size:10px;line-height:1.7;color:var(--muted);text-align:center;margin-top:18px}.login-card .error{margin-top:18px}
html[data-bluui-appearance="Dark"],html[data-bluui-theme="dark"],:root[data-theme="dark"]{--surface:#20212a;--canvas:#181920;--ink:#e9e8ef;--muted:#a4a2b1;--line:#343540;--accent:#b2a0f2;--soft:#302b42;--side:#1d1e26;--green:#65c3a4;color:var(--ink);background:var(--canvas)}
@media(min-width:1600px){main#main:not(.login-page){padding-top:52px}.page-heading{margin-bottom:38px}.metrics{margin-bottom:36px}}
@media(max-width:1100px){.sidebar{width:200px;padding:25px 14px}.workspace-body{margin-left:200px}.topbar{padding:0 26px}main#main:not(.login-page){padding:30px 26px}.metrics{gap:10px}.metrics article{padding:17px}.metrics strong{font-size:24px}.saved-note{display:none}}
@media(max-width:760px){.sidebar{position:relative;width:auto;height:auto;padding:16px 20px;flex-direction:row;justify-content:space-between;border-right:0;border-bottom:1px solid var(--line)}.sidebar .brand{font-size:17px;padding:0}.brand-sub{font-size:8px}.brand-mark{width:33px;height:33px;font-size:24px}.sidebar .nav-caption,.sidebar .nav-item,.sidebar .local-badge,.sidebar-bottom>p,.profile>span{display:none}.sidebar-bottom{margin:0}.profile{border:0;padding:0}.profile button{display:flex;padding:8px}.workspace{display:block}.workspace-body{margin:0}.topbar{height:58px;padding:0 20px}.topbar-actions{gap:8px}.sample-pill{display:none}main#main:not(.login-page){padding:26px 18px}.page-heading{display:block;margin-bottom:24px}.page-heading h1{font-size:27px}.page-heading p{font-size:12px}#reload{margin-top:20px}.metrics{grid-template-columns:1fr 1fr;gap:10px;margin-bottom:22px}.metrics article{padding:18px}.metrics strong{font-size:27px}.records-heading{padding:20px 17px}.permission-pill{font-size:9px}.records-heading p{max-width:200px;font-size:10px;line-height:1.6}.filter-bar{padding:0 17px 17px;gap:12px}.search{max-width:none;flex-basis:100%}.status-filter{flex:1}#grid-region{padding:0 5px}.records-footer{padding:15px 17px}.page-footer{gap:14px;line-height:1.6}.page-footer span:last-child{text-align:right}.login-page{grid-template-columns:1fr}.login-story{padding:25px}.login-copy,.login-footnote{display:none}.login-panel{padding:45px 24px;align-items:start}.login-card{max-width:400px}.login-card h2{font-size:27px}}
@media(prefers-reduced-motion:reduce){*,*:before,*:after{scroll-behavior:auto!important;animation:none!important;transition:none!important}}

shared/customer.ts

The shared customer, change, session and error types used by browser and server. Runtime validation still happens on the backend.

Download this file ↓
Verbatim source · Data contract
export interface Customer {
  Id: string;
  Name: string;
  Seats: number;
  Revenue: number;
  Active: boolean;
  Joined: string;
  LastActivity: string;
  Version: number;
}
export interface CustomerChange { original: Customer; draft: Customer }
export interface SaveIssue { RowId: string; Field: string; Code: string; Message: string }
export interface User { name: string; role: 'editor' | 'viewer' }
export interface Session { user: User; csrf: string }

server/app.ts

Express routes for sign-in, reads and saves, with server-enforced authorization and CSRF checks. The UI calls this backend over HTTP.

Download this file ↓
Verbatim source · API
import express from 'express';
import type { Request, Response, NextFunction } from 'express';
import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';
import type { DatabaseSync } from 'node:sqlite';
import { AppError, listCustomers, saveCustomers } from './database.ts';
import type { User } from '../shared/customer.ts';

export interface AppOptions { demo: boolean; password?: string; secureCookies?: boolean }
export function createApp(db: DatabaseSync, options: AppOptions) {
  if (!options.demo && (!options.password || options.password.length < 12)) throw new Error('Set APP_PASSWORD to at least 12 characters outside local demo mode.');
  const app = express();
  const sessions = new Map<string, { user: User; csrf: string; expires: number }>();
  const failures = new Map<string, { count: number; until: number }>();
  const salt = randomBytes(16);
  const passwordHash = scryptSync(options.demo ? 'local-demo' : options.password!, salt, 32);
  app.disable('x-powered-by');
  app.use((_req, res, next) => {
    res.set({ 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'same-origin', 'X-Frame-Options': 'DENY' }); next();
  });
  app.use('/api', (_req, res, next) => { res.set('Cache-Control', 'no-store'); next(); });
  app.use(express.json({ limit: '1mb' }));
  app.use('/api', (req, _res, next) => {
    const origin = req.get('origin');
    if (origin) {
      try { if (new URL(origin).host !== req.get('host')) throw new Error(); }
      catch { return next(new AppError(403, 'FORBIDDEN', 'Cross-origin requests are not allowed.')); }
    }
    next();
  });
  const cookieToken = (req: Request) => /(?:^|;\s*)blu_session=([a-f0-9]{64})(?:;|$)/.exec(req.headers.cookie || '')?.[1];
  const sessionFor = (req: Request) => {
    const token = cookieToken(req); const session = token ? sessions.get(token) : undefined;
    if (!session || session.expires < Date.now()) { if (token) sessions.delete(token); return undefined; }
    return session;
  };
  const requireSession = (req: Request, _res: Response, next: NextFunction) => {
    if (!sessionFor(req)) return next(new AppError(401, 'UNAUTHORIZED', 'Sign in to continue.')); next();
  };
  const requireCsrf = (req: Request, _res: Response, next: NextFunction) => {
    if (req.get('x-csrf-token') !== sessionFor(req)?.csrf) return next(new AppError(403, 'FORBIDDEN', 'Your session could not be verified. Sign in again.')); next();
  };
  app.get('/api/health', (_req, res) => res.json({ status: 'ok', storage: 'sqlite', outsystemsRequired: false }));
  app.get('/api/config', (_req, res) => res.json({ demo: options.demo }));
  app.post('/api/login', (req, res, next) => {
    const key = req.ip || 'local'; const now = Date.now();
    const limited = failures.get(key);
    if (limited && limited.until > now && limited.count >= 10) return next(new AppError(429, 'RATE_LIMITED', 'Too many sign-in attempts. Try again in a minute.'));
    const { username, password } = req.body || {};
    if (typeof password !== 'string' || password.length > 200 || typeof username !== 'string') return next(new AppError(400, 'INVALID_REQUEST', 'Enter your username and password.'));
    const allowedUser = username === 'editor' || (options.demo && username === 'viewer');
    if (!allowedUser || !timingSafeEqual(passwordHash, scryptSync(password, salt, 32))) {
      failures.set(key, { count: limited && limited.until > now ? limited.count + 1 : 1, until: now + 60000 });
      return next(new AppError(401, 'UNAUTHORIZED', 'The username or password is incorrect.'));
    }
    failures.delete(key);
    for (const [id, s] of sessions) if (s.expires < now) sessions.delete(id);
    const old = cookieToken(req); if (old) sessions.delete(old);
    const token = randomBytes(32).toString('hex');
    const session = { user: { name: username, role: username as User['role'] }, csrf: randomBytes(24).toString('hex'), expires: now + 8 * 60 * 60 * 1000 };
    sessions.set(token, session);
    res.cookie('blu_session', token, { httpOnly: true, sameSite: 'strict', secure: options.secureCookies ?? false, maxAge: 8 * 60 * 60 * 1000, path: '/' });
    res.json({ user: session.user, csrf: session.csrf });
  });
  app.get('/api/session', requireSession, (req, res) => { const s = sessionFor(req)!; res.json({ user: s.user, csrf: s.csrf }); });
  app.post('/api/logout', requireSession, requireCsrf, (req, res) => { sessions.delete(cookieToken(req)!); res.clearCookie('blu_session', { path: '/' }); res.status(204).end(); });
  app.get('/api/customers', requireSession, (_req, res) => res.json({ rows: listCustomers(db) }));
  app.post('/api/customers/save', requireSession, requireCsrf, (req, res, next) => {
    const session = sessionFor(req)!;
    if (session.user.role !== 'editor') return next(new AppError(403, 'FORBIDDEN', 'Only editors can save customers.'));
    try { res.json(saveCustomers(db, session.user.name, req.body)); } catch (error) { next(error); }
  });
  app.use('/api', (_req, _res, next) => next(new AppError(404, 'NOT_FOUND', 'This API route does not exist.')));
  app.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => {
    if (error instanceof AppError) return void res.status(error.status).json({ error: error.message, issues: error.issues });
    const status = (error as { status?: number })?.status;
    if (status === 400 || status === 413) return void res.status(status).json({ error: status === 413 ? 'Request is too large.' : 'Invalid JSON request.' });
    console.error('Request failed:', error instanceof Error ? error.message : 'Unknown error');
    res.status(500).json({ error: 'The request could not be completed. Reload before trying again.' });
  });
  return app;
}

server/database.ts

SQLite schema, sample seeding, validation, atomic writes, version checks and request deduplication. Data survives a browser reload.

Download this file ↓
Verbatim source · Persistence
import { DatabaseSync } from 'node:sqlite';
import { createHash } from 'node:crypto';
import type { Customer, CustomerChange, SaveIssue } from '../shared/customer.ts';

export class AppError extends Error {
  status: number;
  issues: SaveIssue[];
  constructor(status: number, code: string, message: string, row = '', field = '') {
    super(message); this.status = status;
    this.issues = [{ RowId: row, Field: field, Code: code, Message: message }];
  }
}
const fields = ['Id', 'Name', 'Seats', 'Revenue', 'Active', 'Joined', 'LastActivity', 'Version'] as const;
const editable = ['Name', 'Seats', 'Revenue'] as const;
const select = `SELECT CAST(id AS TEXT) AS Id, name AS Name, seats AS Seats,
  revenue_cents / 100.0 AS Revenue, active AS Active, joined AS Joined,
  last_activity AS LastActivity, version AS Version FROM customers`;
const map = (row: Record<string, unknown>): Customer => ({ ...row, Active: Boolean(row.Active) }) as unknown as Customer;

export function openDatabase(path: string) {
  const db = new DatabaseSync(path);
  db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
    CREATE TABLE IF NOT EXISTS customers (
      id INTEGER PRIMARY KEY, name TEXT NOT NULL, seats INTEGER NOT NULL CHECK(seats BETWEEN 0 AND 1000000),
      revenue_cents INTEGER NOT NULL CHECK(revenue_cents BETWEEN 0 AND 100000000000), active INTEGER NOT NULL,
      joined TEXT NOT NULL, last_activity TEXT NOT NULL, version INTEGER NOT NULL DEFAULT 1
    );
    CREATE TABLE IF NOT EXISTS save_requests (username TEXT NOT NULL, request_id TEXT NOT NULL,
      digest TEXT NOT NULL, response TEXT NOT NULL, PRIMARY KEY(username, request_id));
    CREATE TABLE IF NOT EXISTS audit (id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL,
      username TEXT NOT NULL, saved_at TEXT NOT NULL, old_version INTEGER NOT NULL, new_version INTEGER NOT NULL);
  `);
  if ((db.prepare('SELECT count(*) AS count FROM customers').get()!.count as number) === 0) {
    const names = ['Atlas Labs', 'Northstar', 'CalTech Labs', 'Bluehaven', 'Cedar Works', 'Aster Studio', 'Summit Health', 'Harbor Systems', 'Lumen Group', 'Evergreen'];
    const insert = db.prepare('INSERT INTO customers VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
    db.exec('BEGIN');
    try {
      for (let i = 1; i <= 250; i++) insert.run(i, i <= 10 ? names[i - 1]! : `${names[(i - 1) % names.length]} ${String(i).padStart(3, '0')}`, 8 + (i * 17) % 240, (1200 + (i * 1391) % 60000) * 100, i % 5 !== 0 ? 1 : 0, `2025-${String(1 + i % 12).padStart(2, '0')}-${String(1 + i % 27).padStart(2, '0')}`, '2026-10-01T12:00:00Z', 1);
      db.exec('COMMIT');
    } catch (error) { db.exec('ROLLBACK'); throw error; }
  }
  return db;
}
export function listCustomers(db: DatabaseSync): Customer[] {
  return db.prepare(`${select} ORDER BY id`).all().map(map);
}
function validateRow(value: unknown): asserts value is Customer {
  if (!value || typeof value !== 'object' || Array.isArray(value)) throw new AppError(400, 'INVALID_REQUEST', 'Invalid customer record.');
  const row = value as Customer;
  if (Object.keys(row).some(key => !(fields as readonly string[]).includes(key)) || fields.some(key => !(key in row))) throw new AppError(400, 'INVALID_REQUEST', 'Customer fields are missing or unknown.');
  if (typeof row.Id !== 'string' || !/^[1-9]\d*$/.test(row.Id) || !Number.isSafeInteger(Number(row.Id))) throw new AppError(400, 'INVALID_REQUEST', 'Invalid customer ID.');
  if (!Number.isInteger(row.Version) || row.Version < 1 || row.Version >= 2147483647) throw new AppError(400, 'INVALID_REQUEST', 'Invalid customer version.', row.Id, 'Version');
  if (typeof row.Name !== 'string' || !row.Name.trim() || row.Name.length > 200) throw new AppError(422, 'VALIDATION_FAILED', 'Enter a customer name of 1 to 200 characters.', row.Id, 'Name');
  if (!Number.isInteger(row.Seats) || row.Seats < 0 || row.Seats > 1000000) throw new AppError(422, 'VALIDATION_FAILED', 'Seats must be a whole number from 0 to 1000000.', row.Id, 'Seats');
  if (typeof row.Revenue !== 'number' || !Number.isFinite(row.Revenue) || row.Revenue < 0 || row.Revenue > 1000000000 || Math.abs(row.Revenue * 100 - Math.round(row.Revenue * 100)) > 0.00001) throw new AppError(422, 'VALIDATION_FAILED', 'Revenue must be 0–1000000000, with at most two decimal places.', row.Id, 'Revenue');
  if (typeof row.Active !== 'boolean' || typeof row.Joined !== 'string' || typeof row.LastActivity !== 'string') throw new AppError(400, 'INVALID_REQUEST', 'Invalid customer field types.', row.Id);
}

export function saveCustomers(db: DatabaseSync, username: string, body: unknown): { rows: Customer[] } {
  if (!body || typeof body !== 'object') throw new AppError(400, 'INVALID_REQUEST', 'Invalid save request.');
  const { requestId, changes } = body as { requestId: unknown; changes: unknown };
  if (typeof requestId !== 'string' || !/^[a-zA-Z0-9-]{16,80}$/.test(requestId)) throw new AppError(400, 'INVALID_REQUEST', 'A valid request ID is required.');
  if (!Array.isArray(changes) || changes.length < 1 || changes.length > 250) throw new AppError(400, 'INVALID_REQUEST', 'Submit between 1 and 250 changed customers.');
  const digest = createHash('sha256').update(JSON.stringify(changes)).digest('hex');
  db.exec('BEGIN IMMEDIATE');
  try {
    const prior = db.prepare('SELECT digest, response FROM save_requests WHERE username=? AND request_id=?').get(username, requestId);
    if (prior) {
      if (prior.digest !== digest) throw new AppError(409, 'REQUEST_REUSED', 'This request ID was already used for different changes.');
      db.exec('COMMIT'); return JSON.parse(prior.response as string);
    }
    const seen = new Set<string>();
    const prepared: CustomerChange[] = [];
    for (const change of changes) {
      if (!change || typeof change !== 'object') throw new AppError(400, 'INVALID_REQUEST', 'Invalid change record.');
      const { original, draft } = change;
      validateRow(original); validateRow(draft);
      if (original.Id !== draft.Id || original.Version !== draft.Version || seen.has(original.Id)) throw new AppError(400, 'INVALID_REQUEST', 'Customer IDs or versions do not match, or a row is duplicated.', original.Id);
      seen.add(original.Id);
      for (const key of ['Active', 'Joined', 'LastActivity'] as const) if (original[key] !== draft[key]) throw new AppError(400, 'READ_ONLY_FIELD', `${key} is read-only on this screen.`, original.Id, key);
      const normalized = { ...draft, Name: draft.Name.trim() };
      if (editable.every(key => original[key] === normalized[key])) throw new AppError(422, 'NO_CHANGES', 'No changes to save.', original.Id);
      const stored = db.prepare(`${select} WHERE id=?`).get(original.Id);
      if (!stored) throw new AppError(409, 'CONFLICT', 'This customer no longer exists. Reload customers.', original.Id);
      const current = map(stored);
      if (fields.some(key => current[key] !== original[key])) throw new AppError(409, 'CONFLICT', 'Another session changed this customer. Close the editor and reload before editing again.', original.Id, 'Version');
      prepared.push({ original, draft: normalized });
    }
    const rows: Customer[] = [];
    for (const { original, draft } of prepared) {
      db.prepare('UPDATE customers SET name=?, seats=?, revenue_cents=?, version=version+1 WHERE id=? AND version=?').run(draft.Name, draft.Seats, Math.round(draft.Revenue * 100), original.Id, original.Version);
      db.prepare('INSERT INTO audit(customer_id, username, saved_at, old_version, new_version) VALUES (?, ?, ?, ?, ?)').run(original.Id, username, new Date().toISOString(), original.Version, original.Version + 1);
      rows.push(map(db.prepare(`${select} WHERE id=?`).get(original.Id)!));
    }
    const response = { rows };
    db.prepare('INSERT INTO save_requests VALUES (?, ?, ?, ?)').run(username, requestId, digest, JSON.stringify(response));
    db.exec('COMMIT'); return response;
  } catch (error) { db.exec('ROLLBACK'); throw error; }
}

server/index.ts

Starts the HTTP server and database. This example serves both the compiled frontend and API from one local service, with separate source folders.

Download this file ↓
Verbatim source · Server entry
import express from 'express';
import { mkdirSync } from 'node:fs';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createServer as createHttpServer } from 'node:http';
import { openDatabase } from './database.ts';
import { createApp } from './app.ts';

const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const host = process.env.HOST || '127.0.0.1';
const port = Number(process.env.PORT || 3375);
const production = process.env.NODE_ENV === 'production';
const demo = !process.env.APP_PASSWORD && !production;
if (demo && !['127.0.0.1', '::1', 'localhost'].includes(host)) throw new Error('Local demo accounts require a loopback host. Set APP_PASSWORD before exposing the application.');
const path = resolve(process.env.DB_PATH || resolve(root, 'data/customers.sqlite'));
mkdirSync(dirname(path), { recursive: true });
const db = openDatabase(path);
const app = createApp(db, { demo, password: process.env.APP_PASSWORD, secureCookies: production });
const server = createHttpServer(app);
let vite: { close(): Promise<void> } | undefined;
if (process.env.DEV === '1') {
  const { createServer } = await import('vite');
  const development = await createServer({ root, configFile: false, server: { middlewareMode: true, hmr: { server } }, appType: 'spa' });
  vite = development;
  app.use(development.middlewares);
} else {
  app.use(express.static(resolve(root, 'dist')));
  app.get('/', (_req, res) => res.sendFile(resolve(root, 'dist/index.html')));
}
server.listen(port, host, () => console.log(`BluKavant customer workspace: http://${host}:${port}\nStorage: ${path}\n${demo ? 'Local demo mode (editor / viewer).' : 'Password authentication enabled.'}`));
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => server.close(async () => { await vite?.close(); db.close(); process.exit(0); }));

tests/api.test.ts

Executable integration tests covering authorization, invalid input, saved data, stale versions, atomic batches and concurrent writers.

Download this file ↓
Verbatim source · Tests
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { once } from 'node:events';
import { randomUUID } from 'node:crypto';
import { openDatabase, listCustomers } from '../server/database.ts';
import { createApp } from '../server/app.ts';
import type { Customer } from '../shared/customer.ts';

test('standalone API: authentication, validation, atomicity, concurrency and durable storage', async t => {
  const directory = mkdtempSync(join(tmpdir(), 'blu-grid-test-'));
  const path = join(directory, 'test.sqlite');
  const db = openDatabase(path);
  const app = createApp(db, { demo: true });
  const server = app.listen(0, '127.0.0.1'); await once(server, 'listening');
  const address = server.address() as { port: number };
  const base = `http://127.0.0.1:${address.port}`;
  t.after(() => { server.close(); db.close(); rmSync(directory, { recursive: true, force: true }); });
  const call = (path: string, body?: unknown, auth?: { cookie: string; csrf: string }, extra: Record<string,string> = {}) => fetch(base + path, {
    method: body === undefined ? 'GET' : 'POST', headers: { ...(body === undefined ? {} : { 'Content-Type':'application/json' }), ...(auth ? { Cookie: auth.cookie, 'X-CSRF-Token': auth.csrf } : {}), ...extra }, body: body === undefined ? undefined : JSON.stringify(body),
  });
  const login = async (username: string) => {
    const response = await call('/api/login', { username, password: 'local-demo' }); assert.equal(response.status, 200);
    const data = await response.json(); const cookie = response.headers.get('set-cookie')!;
    assert.match(cookie, /HttpOnly/i); assert.match(cookie, /SameSite=Strict/i);
    return { cookie: cookie.split(';')[0]!, csrf: data.csrf as string };
  };
  let editor: Awaited<ReturnType<typeof login>>, viewer: Awaited<ReturnType<typeof login>>;
  let first: Customer, second: Customer;
  await t.test('anonymous access is rejected and local health is independent', async () => {
    assert.equal((await call('/api/customers')).status, 401);
    assert.equal((await call('/api/customers/save', {})).status, 401);
    assert.equal((await (await call('/api/health')).json()).outsystemsRequired, false);
    editor = await login('editor'); viewer = await login('viewer');
    const rows = (await (await call('/api/customers', undefined, editor)).json()).rows;
    assert.equal(rows.length, 250); first = rows[0]; second = rows[1];
  });
  const make = (original: Customer, values: Partial<Customer>) => ({ original, draft: { ...original, ...values } });
  const body = (...changes: unknown[]) => ({ requestId: randomUUID(), changes });
  await t.test('viewer cannot save; CSRF and cross-origin requests are rejected', async () => {
    const request = body(make(first, { Name: 'Updated' }));
    assert.equal((await call('/api/customers/save', request, viewer)).status, 403);
    assert.equal((await call('/api/customers/save', request, { ...editor, csrf: 'invalid' })).status, 403);
    assert.equal((await call('/api/customers/save', request, editor, { Origin: 'https://example.com' })).status, 403);
    assert.equal((await call('/api/customers', undefined, viewer)).status, 200);
  });
  await t.test('server independently rejects invalid names, seats, money and read-only fields', async () => {
    for (const values of [{ Name: ' ' }, { Name: 'x'.repeat(201) }, { Seats: -1 }, { Seats: 2.5 }, { Seats: 1000001 }, { Revenue: -1 }, { Revenue: 1.234 }, { Revenue: 1000000001 }, { Active: !first.Active }]) {
      const response = await call('/api/customers/save', body(make(first, values)), editor);
      assert.ok([400,422].includes(response.status), JSON.stringify(values));
    }
    assert.equal((await call('/api/customers/save', body(make(first, {})), editor)).status, 422);
    assert.equal((await call('/api/customers/save', body(make(first, { Seats: 20 }), make(first, { Seats: 21 })), editor)).status, 400);
    assert.equal(listCustomers(db)[0]!.Version, 1);
  });
  let request: ReturnType<typeof body>, saved: Customer;
  await t.test('save returns canonical data, increments version and records audit', async () => {
    request = body(make(first, { Name: '  Independent customer  ', Seats: 32, Revenue: 10.01 }));
    const response = await call('/api/customers/save', request, editor); assert.equal(response.status, 200);
    saved = (await response.json()).rows[0];
    assert.equal(saved.Name, 'Independent customer'); assert.equal(saved.Revenue, 10.01); assert.equal(saved.Version, 2);
    assert.equal(db.prepare('SELECT count(*) AS count FROM audit').get()!.count, 1);
  });
  await t.test('same request retry is idempotent; changed replay is rejected', async () => {
    const retry = await call('/api/customers/save', request, editor); assert.equal(retry.status, 200);
    assert.deepEqual((await retry.json()).rows[0], saved);
    assert.equal(db.prepare('SELECT count(*) AS count FROM audit').get()!.count, 1);
    const changed = { ...request, changes: [make(first, { Seats: 99 })] };
    assert.equal((await call('/api/customers/save', changed, editor)).status, 409);
  });
  await t.test('stale versions and tampered baselines cannot overwrite a newer record', async () => {
    const stale = await call('/api/customers/save', body(make(first, { Name: 'Stale overwrite' })), editor);
    assert.equal(stale.status, 409); assert.equal((await stale.json()).issues[0].Code, 'CONFLICT');
    const tampered = { ...saved, Name: 'Fake baseline' };
    assert.equal((await call('/api/customers/save', body(make(tampered, { Seats: 99 })), editor)).status, 409);
    assert.equal(listCustomers(db)[0]!.Name, saved.Name);
  });
  await t.test('one conflict rolls back an entire multirow batch', async () => {
    const response = await call('/api/customers/save', body(make(second, { Seats: 777 }), make(first, { Seats: 888 })), editor);
    assert.equal(response.status, 409); assert.equal(listCustomers(db)[1]!.Seats, second.Seats);
    assert.equal(listCustomers(db)[1]!.Version, 1);
  });
  await t.test('parallel writers yield one successful save and one conflict', async () => {
    const responses = await Promise.all([call('/api/customers/save', body(make(second, { Seats: 41 })), editor), call('/api/customers/save', body(make(second, { Seats: 42 })), editor)]);
    assert.deepEqual(responses.map(r => r.status).sort(), [200,409]);
    assert.equal(listCustomers(db)[1]!.Version, 2);
  });
  await t.test('a separately opened database reads saved data without browser storage', () => {
    const reopened = openDatabase(path);
    assert.deepEqual(listCustomers(reopened)[0], saved); reopened.close();
  });
  await t.test('logout revokes the session and malformed requests fail safely', async () => {
    const malformed = await fetch(base + '/api/customers/save', { method: 'POST', body: '{bad', headers: { 'Content-Type':'application/json' } });
    assert.equal(malformed.status, 400);
    assert.equal((await call('/api/logout', {}, editor)).status, 204);
    assert.equal((await call('/api/customers', undefined, editor)).status, 401);
  });
});

package.json

The pinned SDK, dependencies and scripts for building, testing and starting the application. The full ZIP includes the npm lockfile and SDK archive.

Download this file ↓
Verbatim source · Build commands
{
  "name": "blukavant-grid-standalone",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=24.0.0" },
  "scripts": {
    "dev": "node --watch --experimental-strip-types server/dev.ts",
    "start": "node --experimental-strip-types server/index.ts",
    "build": "tsc --noEmit && vite build",
    "test": "node --experimental-strip-types --test tests/*.test.ts",
    "check": "npm run build && npm test"
  },
  "dependencies": {
    "@blukavantui/web": "file:vendor/blukavantui-web-0.9.0.tgz",
    "express": "^5.1.0"
  },
  "devDependencies": {
    "@types/express": "^5.0.0",
    "@types/node": "~24.12.0",
    "typescript": "~6.0.3",
    "vite": "~8.3.4"
  }
}

README.md

Setup, persistence, configuration, production limitations and migration provenance included in the download.

Download this file ↓
Verbatim source · Run instructions
# BluKavant customer workspace

A standalone TypeScript + Express reconstruction of `BluGrid_Sample.McpExamples.McpCustomerDemo`, using the real `@blukavantui/web` Grid, Drawer and Button components. It runs without OutSystems, Service Studio or either MCP server.

## Run locally

Requires Node.js 24 or newer.

```sh
npm ci
npm run build
npm start
```

Open **http://127.0.0.1:3375/** and choose **Continue as editor**. **Explore as viewer** demonstrates read-only access. The local demo uses public demonstration credentials (`editor` or `viewer`, password `local-demo`); it binds to loopback and refuses non-loopback binding with those credentials.

For development with live frontend updates and server restart:

```sh
npm run dev
```

If a preview is already running, stop it or use `PORT=3376 npm run dev`.

## What works

- 250 clearly labeled synthetic customer records in SQLite.
- BluKavant grid search, column filtering/sorting, status filter and pagination.
- Edit customer name, seats and revenue through a BluKavant drawer; cancel does not save.
- Server-side validation with the original limits: name 1–200 characters, seats 0–1,000,000 integer, revenue 0–1,000,000,000 with at most two decimals.
- Version and complete-baseline checks prevent lost updates. Conflicts preserve the draft.
- Atomic batch saves, canonical response records, audit entries, and idempotency for repeated requests.
- Editor/viewer permissions enforced on the server, session cookies, CSRF checks, and sign-out.
- Responsive layout and Light / Dark / System appearance.

The dataset is new sample data, not a copy of the live OutSystems database. The source screen edits only Name, Seats and Revenue, so Active, Joined and LastActivity are read-only here. The original shared OutSystems save action supports additional fields for other screens; that wider capability is intentionally outside this screen migration.

## Persistence and configuration

`data/customers.sqlite` is created on first startup and seeded only when empty. Browser refreshes and server restarts preserve changes. SQLite stores revenue as integer cents. Keep the database and its WAL files together when taking a live filesystem backup, or use SQLite's backup facility.

| Variable | Default | Purpose |
| --- | --- | --- |
| `PORT` | `3375` | HTTP port |
| `HOST` | `127.0.0.1` | Listening address |
| `DB_PATH` | `data/customers.sqlite` | Database file |
| `APP_PASSWORD` | unset | Password for the `editor` account; minimum 12 characters. Disables demo accounts and demo buttons. |
| `NODE_ENV` | unset | `production` requires `APP_PASSWORD` and enables Secure cookies; serve behind HTTPS. |

Production mode uses a single configured editor account. It is a small independent application, not a migration of OutSystems user identities, SSO or role assignments. Sessions are held in memory and are revoked on restart. For a shared production deployment, connect an identity provider and use an appropriate shared session store. No deployment was performed as part of this prototype.

## Project map

```text
client/        TypeScript UI, BluKavant components, responsive styles
server/        Express API, authentication, SQLite transactions
shared/        Customer and session types
tests/         API integration tests using a temporary database
vendor/        Pinned BluKavantUI 0.9.0 package, including upstream notices
```

The SDK tarball is included, so running this app does not require the BluKavant website to be online. `npm ci` needs the npm registry for Express/build dependencies. The application itself makes only same-origin `/api` requests. Theme preference may use browser storage; customer records are stored only in SQLite.

## Verification

```sh
npm run check
```

This type-checks and builds the frontend, then runs API integration tests covering authorization, CSRF/origin rejection, validation, saves, idempotency, stale-version conflicts, tampered baselines, all-or-nothing batch behavior, concurrent writes, durable database reads and logout.

The browser test changed customer 102's seats from 62 to 63, reloaded the saved value, then restored 62 through the same API. The record's version increased to 3 as expected. There are no OutSystems writes.

## Migration provenance

This example reconstructs the saved MCP model of BluGrid_Sample.McpExamples.McpCustomerDemo. Live BluKavantUI MCP contracts were used. OutSystems MCP tool discovery and module inventory succeeded; the fresh screen extraction did not complete when Service Studio became unresponsive. Parity with the latest model remains unverified.

The public download includes application source, tests and the pinned web SDK. It excludes local databases, credentials, session caches, private MCP inventories and native model exports. On first startup it creates its own 250 synthetic customers. Component license and upstream notices remain inside the SDK package.

Guide: https://blukavantui.blutekmedia.com/export-outsystems

Files match the versioned ZIP byte-for-byte. The full project also includes its lockfile, build configuration and pinned SDK with license notices. These source views exclude private MCP extracts and local databases.

A BACKEND YOU CAN INSPECT

Follow a save all the way to the database.

  1. The browser sends the draft

    client/main.ts calls POST /api/customers/save with the original record, draft and request ID.

  2. Express checks the caller

    server/app.ts checks the session, CSRF token and editor role before passing the request to the save service.

  3. SQLite commits the change

    server/database.ts validates the fields, checks the original version and writes within a transaction. It returns the canonical saved row.

  4. Reload reads the saved value

    GET /api/customers reads from SQLite. Customer data is not stored in browser localStorage.

Verified against the runnable example

The existing 11-test suite passes, including authorization, stale versions and atomic batches. A local browser check changed a customer’s seats, saved, and reloaded the persisted value through this backend.

To use another backend, preserve this API contract and implement its authorization, validation and persistence there. That adapter is application work; the example does not include a universal connector.

CHOOSE WHAT RUNS BEHIND THE UI

One interface. More than one destination.

Express is a Node.js framework; SQLite is the relational database used by this example. Your agent can implement the same behavior with a different framework and database. The browser still talks to your API, not directly to the database.

Example combinationWhat your agent buildsReference
Fastify + PostgreSQLRoutes, request validation and a PostgreSQL repository behind the customer API.Fastify database guide ↗
NestJS + MySQLControllers, services and a MySQL data layer, preserving the same permissions and responses.NestJS database guide ↗
Express + MySQL / PostgreSQLKeep the Node.js routing layer; replace the SQLite repository, schema and transactions.Express database guide ↗
Node.js or ASP.NET + SQL ServerAn API service with a SQL Server driver, connection pool, schema migrations and transaction handling.SQL Server Node.js driver ↗
OutSystems or another low-code backendAn API adapter to the services you retain, with their authentication and access controls.Explore the UI-first path →

Architecture examples, not additional runnable starters. The downloads above contain Express + SQLite. Changing databases requires implementing and testing the schema, queries, transactions and connection settings.

Example brief for your agent · choose the target stack
Rebuild this customer workflow with BluKavantUI and my chosen backend.
Target: Node.js + Fastify + PostgreSQL.
Alternatives: NestJS + MySQL; Express + MySQL;
Node.js or ASP.NET + SQL Server; an existing API-backed service.

Keep the frontend separate and preserve the documented JSON contract.
Implement session authentication, roles, validation, CSRF protection,
version conflicts, atomic saves and duplicate-request handling.
Map the schema and provide database migrations and configuration.
Keep database credentials on the server. Add connection pooling.
Run the same load/edit/save/cancel/reload tests against the replacement.
Provide editable source, setup commands and deployment instructions.
Identify retained OutSystems services and test before cutting over.
THE COMPLETE MIGRATION EXAMPLE

Complete customer workspace · 250 sample records

This is the application shown in the before-and-after story: 250 synthetic customers, search/filter/sort/pagination, an edit drawer, SQLite persistence, editor/viewer access, server validation, atomic writes, version checks and request deduplication.

The independent customer workspace with customer grid, status filters and summary cards
Actual standalone app preview. Records are synthetic; it does not read the live OutSystems database.
Run the complete example
# Unzip blukavant-customer-workspace-1.0.0.zip, then:
cd blukavant-customer-workspace
npm ci
npm run check
npm start
# Open http://127.0.0.1:3375/
# Choose Continue as editor or Explore as viewer.

The public demo credentials are editor or viewer, password local-demo. This mode binds to loopback. The README documents APP_PASSWORD, HTTPS production cookies, database paths and the limitations of its single-account deployment mode. The example does not migrate your SSO, users or role assignments.

What was verified

The workspace passed its TypeScript/build checks and 11 automated tests including the parent test. Browser checks covered save/reload persistence, cancel, filters, pagination, viewer access and a 390 px mobile layout. API checks covered authorization, CSRF, validation, stale versions, batch rollback and concurrent writes.

Where the source came from

Live BluKavantUI MCP calls supplied the web contracts. OutSystems MCP discovery and a module inventory succeeded, but a fresh screen export stalled when Service Studio became unresponsive. This reconstruction used previously saved MCP screen/action/entity exports. Parity with the latest Service Studio model remains unverified.

REBUILD THE SAVE FLOW

Save flow, validation & concurrency

The complete example separates the original record from the draft. The browser sends a request ID, the full original baseline and a full draft with only the three permitted fields changed. The server reads the current row inside a transaction, checks permission and validation, compares the expected version and baseline, then returns canonical saved rows with new versions.

Save contract · schematic, not a complete request
POST /api/customers/save
Cookie: app-owned session
X-CSRF-Token: token from the current session

{
  "requestId": "a-new-unique-id",
  "changes": [{
    "original": { "Id": "102", "Version": 3, "...": "all original fields" },
    "draft": { "Id": "102", "Version": 3, "Name": "Northstar", "Seats": 63, "Revenue": 12500.50, "...": "unchanged fields" }
  }]
}

Use the actual Customer and request types from the download; the ellipsis above only indicates omitted fields. Expected outcomes include 401 for an absent session, 403 for forbidden access or a failed CSRF check, 422 for validation and 409 for conflicts. Keep the draft visible on failure. On success, replace the row with the server’s canonical response rather than assuming the submitted draft is the stored value.

Never trust a browser role flag, hidden field or disabled button. Enforce editable-field allowlists, numeric limits, record access and concurrency on the server. Persist idempotency outcomes in the same transaction as the writes so repeated requests cannot duplicate a change. An unknown network outcome needs reconciliation; it must not be presented as a confirmed save.

A SIMPLE NODE.JS + EXPRESS SETUP

One API. One TypeScript entry. A real grid.

For a smaller starting point, this read-only example keeps the same browser/API boundary: Express returns three synthetic customers, Vite builds the browser code, and the Grid displays the response. It has no OutSystems connections and no authentication or writes. Use Node.js 24 or newer.

Install, build and run
# Unzip blukavant-express-grid-1.0.0.zip, then:
cd blukavant-express-grid
npm ci
npm run build
npm start
# Open http://127.0.0.1:3377/

npm ci installs the locked dependencies. npm run build type-checks the code and bundles the frontend into dist/. npm start runs Express, which serves that directory and /api/customers from the same origin. This earlier v1.0.0 example retains the combined SDK 0.9.0 in vendor/; other packages come from npm. For new projects, use Community Basic Grid or install the licensed Pro Grid alongside Community, as shown in Getting started.

Replace the load action with an Express route

Express serves the browser build and a JSON API with three synthetic customers. Replace the fixture with an authorized database query when connecting real data.

server.ts
import express from 'express';
import { fileURLToPath } from 'node:url';
import type { Customer } from './customer.ts';

const app = express();
const rows: Customer[] = [
  { Id: '1', Name: 'Atlas Labs', Seats: 12, Revenue: 2400 },
  { Id: '2', Name: 'Northstar', Seats: 24, Revenue: 4800 },
  { Id: '3', Name: 'Harbor Systems', Seats: 8, Revenue: 1600 },
];

app.get('/api/customers', (_request, response) => response.json({ rows }));
app.get('/api/health', (_request, response) => response.json({ status: 'ok', outsystemsRequired: false }));
app.use(express.static(fileURLToPath(new URL('./dist', import.meta.url))));
const port = Number(process.env.PORT || 3377);
app.listen(port, '127.0.0.1', () => console.log(`Open http://127.0.0.1:${port}/`));

Define the shared JSON contract

The frontend and backend agree on these fields. TypeScript does not validate network data at runtime; validate external input at the API boundary.

customer.ts
export interface Customer {
  Id: string;
  Name: string;
  Seats: number;
  Revenue: number;
}

Mount the web component and load data

The native Grid Block becomes createGrid. Fetch the rows from your API, apply them with setData, and destroy the instance when its view is removed.

client/main.ts
import '@blukavantui/web/theme.css';
import '@blukavantui/web/grid.css';
import { createGrid } from '@blukavantui/web/grid';
import type { Customer } from '../customer.ts';
import './style.css';

const host = document.querySelector<HTMLElement>('#customers')!;
const status = document.querySelector<HTMLElement>('#status')!;
const grid = createGrid<Customer>(host, {
  RowKeyField: 'Id',
  Mode: 'Client',
  Rows: [],
  Columns: [
    { Field: 'Name', Header: 'Customer', Flex: 2, MinWidth: 180, IsSortable: true, IsFilterable: true },
    { Field: 'Seats', Header: 'Seats', Type: 'Number', MinWidth: 100, IsSortable: true },
    { Field: 'Revenue', Header: 'Revenue', Type: 'Currency', MinWidth: 140, IsSortable: true },
  ],
  Config: { Height: '400px', IsReadOnly: true, ShowEditToolbar: false, EnablePagination: true, PageSize: 10, CurrencyCode: 'USD' },
});

try {
  const response = await fetch('/api/customers');
  if (!response.ok) throw new Error('Customers could not be loaded.');
  const data: { rows: Customer[] } = await response.json();
  grid.setData(data.rows);
  status.textContent = `${data.rows.length} sample customers loaded from Express.`;
} catch (error) {
  status.textContent = error instanceof Error ? error.message : 'Could not load customers.';
}
// In a framework, call destroy() in its component unmount hook.
if (import.meta.hot) import.meta.hot.dispose(() => grid.destroy());

Dependencies and commands

Pinned dependencies and scripts for installation, type checking, the browser build, and the Express server.

package.json
{
  "name": "blukavant-express-grid",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=24.0.0" },
  "scripts": {
    "build": "tsc --noEmit && vite build",
    "start": "node server.ts"
  },
  "dependencies": {
    "@blukavantui/web": "file:vendor/blukavantui-web-0.9.0.tgz",
    "express": "^5.1.0"
  },
  "devDependencies": {
    "@types/express": "^5.0.0",
    "@types/node": "~24.12.0",
    "typescript": "~6.0.3",
    "vite": "~8.3.4"
  }
}

TypeScript configuration

Check the browser and server code before running the app.

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2023",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "lib": ["ES2023", "DOM"],
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "erasableSyntaxOnly": true,
    "skipLibCheck": true,
    "types": ["node", "vite/client"]
  },
  "include": ["*.ts", "client/**/*.ts"]
}

The browser entry

The page supplies the grid host and loads the TypeScript entry through Vite.

index.html
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>BluKavantUI · Express starter</title></head>
<body><main><span class="eyebrow">TypeScript + Express</span><h1>A grid in your own application.</h1><p>Three synthetic customers, served by a standalone Node.js API. Sort a column to try the grid.</p><div id="customers" aria-label="Customer grid"></div><p id="status" role="status">Loading customers…</p></main><script type="module" src="/client/main.ts"></script></body>
</html>

Page styles

Layout styles sit alongside the shared BluKavantUI theme and Grid stylesheet.

client/style.css
body { margin: 0; background: #f6f7fb; color: #1f2937; font-family: system-ui, sans-serif; }
main { max-width: 1040px; margin: 64px auto; padding: 0 24px; }
h1 { font-size: clamp(28px, 5vw, 42px); letter-spacing: -.04em; margin: 12px 0; }
p { line-height: 1.65; }
.eyebrow { text-transform: uppercase; letter-spacing: .12em; font-size: 12px; color: #5144c6; font-weight: 700; }
#customers { margin-top: 28px; min-width: 0; }
#status { font-size: 14px; }

The ZIP also includes the npm lockfile and the pinned BluKavantUI SDK in vendor/.

Node runs the server’s erasable TypeScript syntax; it does not type-check it or transform JSX. That is why the build runs tsc --noEmit separately. Vite handles browser TypeScript and CSS. See the Node.js TypeScript documentation, Express static-file guide and Vite production-build guide.

Make the dependency boundary visible

Open the browser Network panel. The example loads local assets and calls its own /api/customers. Close Service Studio and disconnect the MCPs: the page should still work. Calling a retained OutSystems REST endpoint is a valid hybrid architecture, but it still depends on OutSystems.

Example v1.0.0 · SDK 0.9.0. Saved-model reconstruction; current Service Studio parity unverified. Local example rechecked October 21, 2026.

Search BluKavantUI