EnergyVenom's picture
Patchwise Agent Studio: Oracle AI Agent Studio cycles
af1bee9 verified
Raw History Blame Contribute Delete
9.81 kB
'use strict';
// Shared HTML helpers + page shell (layout, page/act wrappers) for every module pack. Labels are bound with
// <label for> so Playwright getByLabel works; banners use role=status / role=alert.
const R = require('./registry');
const { AppError } = require('./errors');
const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
let fid = 0;
const inp = (name, label, { type = 'text', value = '', tid, attrs = '' } = {}) => { const id = `f${++fid}`;
return `<div class="f"><label for="${id}">${esc(label)}</label> <input id="${id}" name="${name}" type="${type}" value="${esc(value)}"${tid ? ` data-testid="${tid}"` : ''} ${attrs}></div>`; };
const sel = (name, label, opts, { value = '', tid } = {}) => { const id = `f${++fid}`;
return `<div class="f"><label for="${id}">${esc(label)}</label> <select id="${id}" name="${name}"${tid ? ` data-testid="${tid}"` : ''}>${opts.map((o) => { const [v, t] = Array.isArray(o) ? o : [o, o]; return `<option value="${esc(v)}"${String(v) === String(value) ? ' selected' : ''}>${esc(t)}</option>`; }).join('')}</select></div>`; };
const hid = (name, value) => `<input type="hidden" name="${name}" value="${esc(value)}">`;
// MOCK_UI_DRIFT (co-worker self-heal demo only; default empty = no change): JSON map of button label -> drifted label,
// e.g. MOCK_UI_DRIFT='{"Submit":"Submit Request"}' simulates a patch renaming a button.
const UI_DRIFT = (() => { try { return JSON.parse(process.env.MOCK_UI_DRIFT || '{}'); } catch { return {}; } })();
const drift = (label) => (Object.prototype.hasOwnProperty.call(UI_DRIFT, label) ? UI_DRIFT[label] : label);
const btn = (label, attrs = '') => `<button type="submit" ${attrs}>${esc(drift(label))}</button>`;
const form = (action, inner, method = 'post') => `<form method="${method}" action="${action}">${inner}</form>`;
const table = (name, heads, rows, tid) => `<table aria-label="${esc(name)}"${tid ? ` data-testid="${tid}"` : ''}><thead><tr>${heads.map((h) => `<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${rows.join('')}</tbody></table>`;
const tr = (cells, attrs = '') => `<tr ${attrs}>${cells.map((c) => `<td>${c}</td>`).join('')}</tr>`;
const money = (n) => (n === null || n === undefined ? '' : Number(n).toFixed(2));
const dl = (pairs) => `<dl>${pairs.filter(Boolean).map(([k, v, tid]) => `<dt>${esc(k)}</dt><dd${tid ? ` data-testid="${tid}"` : ''}>${v}</dd>`).join('')}</dl>`;
const T = (s) => esc(String(s).replace(/_/g, ' '));
const back = (p) => hid('__back', p);
const roleOf = (req) => req.get('X-Mock-Role') || ((/(?:^|;\s*)mock_role=([a-z_0-9]+)/.exec(req.get('cookie') || '') || [])[1]) || null;
function layout(req, role, title, body, status = 200) {
const ok = req.query.ok ? `<div class="banner ok" role="status" data-testid="success-banner">${esc(req.query.ok)}</div>` : '';
const er = req.query.error ? `<div class="banner err" role="alert" data-testid="error-banner">${esc(req.query.error)}</div>` : '';
const p = role && R.persona(role);
const tasks = p ? `<nav aria-label="Tasks"><b>Tasks</b> ${R.tasksFor(role).map((t) => `<a href="${t.href}">${esc(t.label)}</a>`).join(' ')}</nav>` : '';
const who = p ? `<div class="who">Persona: <b data-testid="current-role">${esc(p.label)}</b>
${form('/worklist', btn(`Notifications`, `aria-label="Notifications" data-testid="notifications-btn"`), 'get')} <span data-testid="notification-count">${R.worklist(role).length}</span>
${form('/logout', btn('Sign out'))}</div>` : '';
const mods = R.packs().map((m) => m.name).join(' | ');
return { status, html: `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${esc(title)} - Mock Fusion</title>
<style>*{box-sizing:border-box}body{font-family:"Segoe UI",system-ui,-apple-system,Roboto,Arial,sans-serif;font-size:14px;line-height:1.45;color:#1f2a37;margin:0;background:#f3f5f7}
header{background:#1f4e79;color:#fff;padding:0 24px;min-height:52px;display:flex;align-items:center;gap:12px}header b{font-size:17px;font-weight:600;letter-spacing:.2px}
header .sub{opacity:.8;font-size:13px;border-left:1px solid rgba(255,255,255,.35);padding-left:12px}header small{margin-left:auto;background:rgba(255,255,255,.16);border-radius:999px;padding:3px 12px;font-size:12px}
.who{display:flex;align-items:center;gap:10px;padding:8px 24px;background:#fff;border-bottom:1px solid #dfe3e8;color:#5b6776}.who b{color:#1f2a37;background:#e8f0f8;border-radius:999px;padding:3px 12px}
.who form{display:inline;margin:0}.who form:last-of-type{margin-left:auto}.who button{background:#fff;color:#1f4e79;border:1px solid #c3cad3}
.who [data-testid=notification-count]{background:#1f4e79;color:#fff;border-radius:999px;min-width:22px;text-align:center;padding:1px 7px;font-size:12px;font-weight:600}
nav{display:flex;flex-wrap:wrap;align-items:center;gap:4px 6px;padding:8px 24px;background:#fff;border-bottom:1px solid #dfe3e8}
nav b{font-size:11px;text-transform:uppercase;letter-spacing:.6px;color:#5b6776;margin-right:8px}nav a{padding:5px 12px;border-radius:6px;color:#1f4e79;text-decoration:none;font-weight:500}nav a:hover{background:#e8f0f8}
main{max-width:1180px;margin:0 auto;padding:20px 24px 28px}h1{font-size:22px;font-weight:600;margin:4px 0 16px}h2{font-size:16px;font-weight:600;margin:0 0 8px}a{color:#0b6bcb}
.banner{padding:10px 14px;margin-bottom:14px;border-radius:6px;border-left:4px solid;font-weight:500}.ok{background:#e6f4ea;border-color:#2e7d32;color:#1b5e20}.err{background:#fdecea;border-color:#c62828;color:#8e1b1b}
fieldset,section{background:#fff;border:1px solid #dfe3e8;border-radius:8px;padding:14px 16px;margin:14px 0}fieldset fieldset{background:#f8fafb}legend{font-weight:600;padding:0 6px}
dl{display:grid;grid-template-columns:max-content 1fr;gap:6px 24px;background:#fff;border:1px solid #dfe3e8;border-radius:8px;padding:14px 16px;margin:12px 0}
section dl,fieldset dl{border:0;padding:0;margin:6px 0}dt{color:#5b6776}dd{margin:0;font-weight:600}
table{border-collapse:collapse;background:#fff;margin:12px 0;border:1px solid #dfe3e8}th{background:#eef2f6;text-align:left;font-weight:600;color:#3b4756}
td,th{border-bottom:1px solid #dfe3e8;padding:7px 12px;vertical-align:middle}tbody tr:hover{background:#f8fafb}td form{display:inline;margin:0}
form{margin:8px 0}.f{display:inline-flex;flex-direction:column;gap:3px;margin:6px 16px 6px 0;vertical-align:top}.f label{font-size:12px;font-weight:600;color:#5b6776}
input:not([type=checkbox]):not([type=radio]):not([type=hidden]),select,textarea{font:inherit;color:inherit;padding:6px 9px;border:1px solid #c3cad3;border-radius:6px;background:#fff;min-width:190px}
input:focus,select:focus,textarea:focus{outline:2px solid #9cc4ee;border-color:#0b6bcb}
button{font:inherit;font-weight:600;background:#0b6bcb;color:#fff;border:1px solid #0b6bcb;border-radius:6px;padding:6px 14px;cursor:pointer}button:hover{background:#0958a8}td button{padding:3px 10px}
footer{max-width:1180px;margin:0 auto;padding:0 24px 24px;color:#7b8794;font-size:11.5px}</style></head><body>
<header><b>Mock Fusion</b> <span class="sub">Practice pod</span> <small>(local test double, not Oracle software)</small></header>${who}${tasks}
<main><h1 data-testid="page-title">${esc(title)}</h1>${ok}${er}${body}</main>
<footer>Modules loaded: <span data-testid="loaded-modules">${esc(mods)}</span></footer></body></html>` };
}
const forbidden = (role, moduleId) => new AppError(403, 'FORBIDDEN', `Persona ${role} has no access to the ${moduleId} module.`);
/** GET page wrapper. moduleId (optional) restricts the page to personas registered by that pack (else 403). */
function page(fn, moduleId) {
return (req, res) => {
const role = roleOf(req);
if (!R.persona(role)) return res.redirect('/login');
try {
if (moduleId && !R.inModule(role, moduleId)) throw forbidden(role, moduleId);
const out = fn(req, role); if (out) res.status(out.status).send(out.html);
} catch (e) {
if (e instanceof AppError) { const o = layout({ query: { error: e.message } }, role, e.status === 403 ? 'Not Authorized' : 'Error', ''); return res.status(e.status).send(o.html); }
console.error(e); res.status(500).send('Internal error');
}
};
}
/** POST action wrapper: fn returns [redirectPath, successMessage]; AppError -> redirect back with ?error=. */
function act(fn, moduleId) {
return (req, res) => {
const role = roleOf(req);
if (!R.persona(role)) return res.redirect('/login');
try {
if (moduleId && !R.inModule(role, moduleId)) throw forbidden(role, moduleId);
const [path, msg] = fn(req, role); res.redirect(`${path}${path.includes('?') ? '&' : '?'}ok=${encodeURIComponent(msg)}`);
} catch (e) {
if (!(e instanceof AppError)) { console.error(e); return res.status(500).send('Internal error'); }
const b = req.body.__back || (req.get('referer') ? new URL(req.get('referer')).pathname : '/');
res.redirect(`${b}?error=${encodeURIComponent(e.message)}`);
}
};
}
/** JSON wrapper for REST routers. Return created(body) for 201. */
function wrap(fn) {
return (req, res) => {
try { const out = fn(req, roleOf(req)); if (out && out.__status) return res.status(out.__status).json(out.body); res.json(out); } catch (e) {
if (e instanceof AppError) return res.status(e.status).json({ title: e.code, error: e.code, message: e.message, detail: e.message });
console.error(e); res.status(500).json({ error: 'INTERNAL', message: e.message });
}
};
}
const created = (body) => ({ __status: 201, body });
module.exports = { esc, inp, sel, hid, btn, form, table, tr, money, dl, T, back, roleOf, layout, page, act, wrap, created };