refactor: rename ScadaLink → ZB.MOM.WW.ScadaBridge (code + projects + namespaces)

Solution + 23 src projects + 26 test projects renamed; folders, csproj,
namespaces, and ScadaLinkDbContext/ScadaBridgeDbContext class updated.
ActorSystem "scadalink" → "scadabridge", Akka seed-node URLs migrated.
SQL roles/logins, LDAP domains, CLI command name, and CLI config dir
(~/.scadalink → ~/.scadabridge) also renamed.

Build green; 5 Host.Tests fail awaiting SQL login rename in next commit.
Pre-existing StaleTagMonitor timing flakes unchanged.

Rename script committed at tools/rename-to-scadabridge.sh.
This commit is contained in:
Joseph Doherty
2026-05-28 09:37:45 -04:00
parent 6d87ee3c3b
commit 7b0b9c7365
1531 changed files with 11180 additions and 11054 deletions
@@ -0,0 +1,190 @@
// Audit results grid column UX (#23 follow-ups Task 10).
//
// A tiny, dependency-free helper for the AuditResultsGrid component:
// - drag-to-resize: a pointer-driven handle on each <th>'s right edge,
// - drag-to-reorder: native HTML5 drag-and-drop on the header row,
// - save/load: a sessionStorage round-trip, mirroring treeview-storage.js.
//
// The Blazor component owns the column model; this file is purely the
// browser-side drag plumbing. After a resize or reorder it calls back into
// .NET via a DotNetObjectReference so the component can persist + re-render.
//
// No drag-drop libraries — hand-rolled pointer + native-DnD handlers only.
window.auditGrid = {
// --- sessionStorage wrapper (mirrors window.treeviewStorage) -----------
// Keys are namespaced under "auditGrid:" so they never collide with the
// treeview's "treeview:" namespace.
save: function (key, json) {
try {
sessionStorage.setItem("auditGrid:" + key, json);
} catch {
// Quota / privacy-mode failures are non-fatal — the grid simply
// falls back to defaults on the next load.
}
},
load: function (key) {
try {
return sessionStorage.getItem("auditGrid:" + key);
} catch {
return null;
}
},
// Minimum column width in pixels. A column can never be dragged narrower
// than this so a header can't collapse to an unclickable sliver.
minWidth: 64,
// --- wire-up ----------------------------------------------------------
// `table` is the <table> element, `dotNet` is a DotNetObjectReference
// exposing OnColumnResized / OnColumnReordered. Safe to call on every
// render: it re-scans the header and binds only cells not already bound,
// and always refreshes the live .NET reference. Handlers read the column
// key live from data-col-key at event time, so Blazor reusing a <th> DOM
// node for a different column (after a reorder re-render) is harmless.
init: function (table, dotNet) {
if (!table) {
return;
}
table.__auditGridDotNet = dotNet;
var headerRow = table.tHead && table.tHead.rows[0];
if (!headerRow) {
return;
}
for (var i = 0; i < headerRow.cells.length; i++) {
this._bindHeaderCell(table, headerRow.cells[i]);
}
},
// Bind resize + reorder handlers to a single <th>. Idempotent — a cell
// already carrying handlers is skipped. The handlers resolve the column
// key live (th.getAttribute) so they stay correct if the renderer reuses
// the element for another column.
_bindHeaderCell: function (table, th) {
var self = this;
if (th.__auditGridCellBound) {
return;
}
th.__auditGridCellBound = true;
// --- resize: pointer drag on the handle ---------------------------
var handle = th.querySelector(".audit-grid-resize-handle");
if (handle) {
handle.addEventListener("pointerdown", function (ev) {
ev.preventDefault();
// Stop the pointerdown from also starting a header drag.
ev.stopPropagation();
var startX = ev.clientX;
var startWidth = th.getBoundingClientRect().width;
handle.setPointerCapture(ev.pointerId);
th.classList.add("resizing");
function onMove(moveEv) {
var next = Math.max(self.minWidth, startWidth + (moveEv.clientX - startX));
self._applyWidth(th, next);
}
function onUp() {
handle.releasePointerCapture(ev.pointerId);
handle.removeEventListener("pointermove", onMove);
handle.removeEventListener("pointerup", onUp);
handle.removeEventListener("pointercancel", onUp);
th.classList.remove("resizing");
var key = th.getAttribute("data-col-key");
var finalWidth = Math.round(th.getBoundingClientRect().width);
var dn = table.__auditGridDotNet;
if (key && dn) {
dn.invokeMethodAsync("OnColumnResized", key, finalWidth);
}
}
handle.addEventListener("pointermove", onMove);
handle.addEventListener("pointerup", onUp);
handle.addEventListener("pointercancel", onUp);
});
}
// --- reorder: native HTML5 drag-and-drop on the header ------------
// The whole <th> is draggable; dropping it onto another header swaps
// the dragged column into the drop target's position.
th.setAttribute("draggable", "true");
th.addEventListener("dragstart", function (ev) {
// A resize in progress sets .resizing; never start a reorder then.
if (th.classList.contains("resizing")) {
ev.preventDefault();
return;
}
var key = th.getAttribute("data-col-key");
if (!key) {
ev.preventDefault();
return;
}
table.__auditGridDragKey = key;
ev.dataTransfer.effectAllowed = "move";
// Some browsers require data to be set for the drag to begin.
try { ev.dataTransfer.setData("text/plain", key); } catch { /* ignore */ }
th.classList.add("dragging");
});
th.addEventListener("dragend", function () {
th.classList.remove("dragging");
table.__auditGridDragKey = null;
self._clearDropTargets(table);
});
th.addEventListener("dragover", function (ev) {
// Allowing the drop is what lets dragover/drop fire at all.
var key = th.getAttribute("data-col-key");
if (key && table.__auditGridDragKey && table.__auditGridDragKey !== key) {
ev.preventDefault();
ev.dataTransfer.dropEffect = "move";
th.classList.add("drop-target");
}
});
th.addEventListener("dragleave", function () {
th.classList.remove("drop-target");
});
th.addEventListener("drop", function (ev) {
ev.preventDefault();
th.classList.remove("drop-target");
var key = th.getAttribute("data-col-key");
var fromKey = table.__auditGridDragKey;
table.__auditGridDragKey = null;
if (!key || !fromKey || fromKey === key) {
return;
}
var dn = table.__auditGridDotNet;
if (dn) {
// fromKey moves to occupy toKey's slot; the component computes
// the resulting order and re-renders + persists.
dn.invokeMethodAsync("OnColumnReordered", fromKey, key);
}
});
},
// Apply a width to a <th> via a CSS custom property. The scoped stylesheet
// reads --audit-col-width; absent it, the column falls back to auto.
//
// Known, intentional behaviour: during a live resize drag this updates the
// <th> width immediately, but the <td> body cells only catch up on the next
// .NET re-render (driven by OnColumnResized at pointer-up). The brief
// header/body width mismatch mid-drag is an accepted trade-off for an
// internal tool — not a bug.
_applyWidth: function (th, widthPx) {
th.style.setProperty("--audit-col-width", widthPx + "px");
},
_clearDropTargets: function (table) {
var hits = table.querySelectorAll(".drop-target, .dragging");
for (var i = 0; i < hits.length; i++) {
hits[i].classList.remove("drop-target", "dragging");
}
}
};
@@ -0,0 +1,13 @@
// CentralUI-029: small JS module to replace the JS.InvokeAsync<int>("eval", ...)
// anti-pattern previously used by ConfigurationAuditLog. Exporting a named
// function from an ES module:
// * removes the residual `eval` JS-interop surface,
// * is CSP-friendly (no `unsafe-eval` directive required),
// * matches the module-import pattern (`session-expiry.js`, `audit-grid.js`,
// `nav-state.js`, `transport.js`) the rest of the Central UI follows.
//
// The function returns the same value as `new Date().getTimezoneOffset()` —
// minutes of (UTC - local), positive for time zones west of UTC.
export function getTimezoneOffsetMinutes() {
return new Date().getTimezoneOffset();
}
@@ -0,0 +1,394 @@
// Blazor bridge for Monaco editor.
// Exposes window.MonacoBlazor with createEditor / setValue / getValue / dispose / setMarkers.
// Lazy-loads Monaco's AMD bundle the first time createEditor is called.
(function () {
const VS_BASE = "/_content/ZB.MOM.WW.ScadaBridge.CentralUI/lib/monaco/vs";
const editors = {};
let readyPromise = null;
function ensureLoaded() {
if (readyPromise) return readyPromise;
readyPromise = new Promise(function (resolve, reject) {
const loader = document.createElement("script");
loader.src = VS_BASE + "/loader.js";
loader.onload = function () {
// eslint-disable-next-line no-undef
require.config({ paths: { vs: VS_BASE } });
// eslint-disable-next-line no-undef
require(["vs/editor/editor.main"], function () {
registerCSharpProviders();
resolve();
});
};
loader.onerror = function (e) { reject(e); };
document.head.appendChild(loader);
});
return readyPromise;
}
// ---- Roslyn-backed C# language providers --------------------------------
const KIND_MAP = {
Method: 0, Field: 4, Property: 9, Event: 10, Class: 6,
Module: 8, Variable: 4, Text: 18
};
// Look up the SCADA context for a model by walking the editors map. Blazor
// JS interop serializes records as PascalCase; we normalize to camelCase.
async function lookupContext(model) {
const empty = {
declaredParameters: [], siblingScripts: [], declaredParameterShapes: [],
selfAttributes: [], children: [], parent: null, scriptKind: 0
};
for (const key in editors) {
if (editors[key].editor.getModel() === model) {
try {
const got = await editors[key].dotNetRef.invokeMethodAsync("GetContext");
if (got) {
const kind = got.ScriptKind != null ? got.ScriptKind
: (got.scriptKind != null ? got.scriptKind : 0);
return {
declaredParameters: got.DeclaredParameters || got.declaredParameters || [],
siblingScripts: got.SiblingScripts || got.siblingScripts || [],
declaredParameterShapes: got.DeclaredParameterShapes || got.declaredParameterShapes || [],
selfAttributes: got.SelfAttributes || got.selfAttributes || [],
children: got.Children || got.children || [],
parent: got.Parent || got.parent || null,
scriptKind: kind
};
}
} catch (e) { /* fall through */ }
break;
}
}
return empty;
}
function registerCSharpProviders() {
// ----- Completions ---------------------------------------------------
monaco.languages.registerCompletionItemProvider("csharp", {
triggerCharacters: [".", "(", "\""],
provideCompletionItems: async function (model, position) {
try {
const ctx = await lookupContext(model);
const resp = await fetch("/api/script-analysis/completions", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
codeText: model.getValue(),
line: position.lineNumber,
column: position.column,
declaredParameters: ctx.declaredParameters,
siblingScripts: ctx.siblingScripts,
selfAttributes: ctx.selfAttributes,
children: ctx.children,
parent: ctx.parent,
kind: ctx.scriptKind
})
});
if (!resp.ok) return { suggestions: [] };
const data = await resp.json();
// Snippet items (kind=Method with InsertTextRules=4) need
// the range to extend over Monaco's auto-closed `")` so the
// snippet replaces them cleanly. Detect it once.
const word = model.getWordUntilPosition(position);
const lineLen = model.getLineMaxColumn(position.lineNumber);
const lookahead = model.getValueInRange({
startLineNumber: position.lineNumber,
startColumn: position.column,
endLineNumber: position.lineNumber,
endColumn: Math.min(position.column + 2, lineLen)
});
let snippetTail = 0;
if (lookahead.startsWith("\")")) snippetTail = 2;
else if (lookahead.startsWith("\"")) snippetTail = 1;
const baseRange = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn
};
const snippetRange = {
...baseRange,
endColumn: word.endColumn + snippetTail
};
return {
suggestions: (data.items || []).map(function (it) {
const isSnippet = it.insertTextRules === 4;
return {
label: it.label,
insertText: it.insertText,
detail: it.detail,
kind: KIND_MAP[it.kind] != null ? KIND_MAP[it.kind] : 18,
insertTextRules: isSnippet ? 4 : 0,
range: isSnippet ? snippetRange : baseRange,
command: isSnippet
? { id: "editor.action.triggerParameterHints", title: "Signature help" }
: undefined
};
})
};
} catch (e) {
return { suggestions: [] };
}
}
});
// ----- Hover ---------------------------------------------------------
monaco.languages.registerHoverProvider("csharp", {
provideHover: async function (model, position) {
try {
const ctx = await lookupContext(model);
const resp = await fetch("/api/script-analysis/hover", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
codeText: model.getValue(),
line: position.lineNumber,
column: position.column,
siblingScripts: ctx.siblingScripts,
declaredParameters: ctx.declaredParameterShapes,
selfAttributes: ctx.selfAttributes,
children: ctx.children,
parent: ctx.parent
})
});
if (!resp.ok) return null;
const data = await resp.json();
if (!data.markdown) return null;
return { contents: [{ value: data.markdown }] };
} catch (e) { return null; }
}
});
// ----- Document formatting ------------------------------------------
monaco.languages.registerDocumentFormattingEditProvider("csharp", {
provideDocumentFormattingEdits: async function (model) {
try {
const resp = await fetch("/api/script-analysis/format", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ code: model.getValue() })
});
if (!resp.ok) return [];
const data = await resp.json();
if (typeof data.code !== "string" || data.code === model.getValue()) return [];
return [{
range: model.getFullModelRange(),
text: data.code
}];
} catch (e) { return []; }
}
});
// ----- Inlay hints --------------------------------------------------
monaco.languages.registerInlayHintsProvider("csharp", {
provideInlayHints: async function (model) {
try {
const ctx = await lookupContext(model);
const resp = await fetch("/api/script-analysis/inlay-hints", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
code: model.getValue(),
siblingScripts: ctx.siblingScripts
})
// Note: inlay hints don't yet read children/parent shapes
// because they only label CallShared/CallScript args today.
});
if (!resp.ok) return { hints: [], dispose: function () {} };
const data = await resp.json();
return {
hints: (data.hints || []).map(function (h) {
return {
position: { lineNumber: h.line, column: h.column },
label: h.label,
kind: 2,
paddingRight: true
};
}),
dispose: function () {}
};
} catch (e) { return { hints: [], dispose: function () {} }; }
}
});
// ----- Signature help ------------------------------------------------
monaco.languages.registerSignatureHelpProvider("csharp", {
signatureHelpTriggerCharacters: ["(", ","],
signatureHelpRetriggerCharacters: [","],
provideSignatureHelp: async function (model, position) {
try {
const ctx = await lookupContext(model);
const resp = await fetch("/api/script-analysis/signature-help", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
codeText: model.getValue(),
line: position.lineNumber,
column: position.column,
siblingScripts: ctx.siblingScripts,
children: ctx.children,
parent: ctx.parent
})
});
if (!resp.ok) return null;
const data = await resp.json();
if (!data.label) return null;
return {
value: {
signatures: [{
label: data.label,
parameters: (data.parameters || []).map(function (p) {
return { label: p.label, documentation: p.documentation };
})
}],
activeSignature: 0,
activeParameter: data.activeParameter || 0
},
dispose: function () {}
};
} catch (e) { return null; }
}
});
}
async function fetchDiagnostics(model) {
try {
const ctx = await lookupContext(model);
const resp = await fetch("/api/script-analysis/diagnostics", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
code: model.getValue(),
declaredParameters: ctx.declaredParameters,
siblingScripts: ctx.siblingScripts,
kind: ctx.scriptKind
})
});
if (!resp.ok) return [];
const data = await resp.json();
return data.markers || [];
} catch (e) {
return [];
}
}
async function createEditor(id, host, options, dotNetRef) {
await ensureLoaded();
if (!host) return;
const editor = monaco.editor.create(host, {
value: options.value || "",
language: options.language || "csharp",
theme: "vs",
minimap: { enabled: false },
scrollBeyondLastLine: false,
automaticLayout: true,
fontSize: 13,
lineNumbers: "on",
renderLineHighlight: "line",
readOnly: !!options.readOnly,
tabSize: 4,
insertSpaces: true,
wordWrap: "off",
fixedOverflowWidgets: true
});
let diagTimer = null;
const scheduleDiagnostics = function () {
if (diagTimer) clearTimeout(diagTimer);
diagTimer = setTimeout(async function () {
const model = editor.getModel();
if (!model) return;
const markers = await fetchDiagnostics(model);
monaco.editor.setModelMarkers(model, "scadabridge", markers);
dotNetRef.invokeMethodAsync("OnMarkersChanged", markers).catch(function () {});
}, 500);
};
editor.onDidChangeModelContent(function () {
const value = editor.getValue();
dotNetRef.invokeMethodAsync("OnValueChanged", value).catch(function () {});
if (options.language === "csharp") scheduleDiagnostics();
});
editors[id] = { editor: editor, dotNetRef: dotNetRef };
// Run an initial diagnostic pass so existing scripts show their markers.
if (options.language === "csharp") scheduleDiagnostics();
}
function setEditorOption(id, optionName, value) {
const entry = editors[id];
if (!entry) return;
if (optionName === "theme") {
monaco.editor.setTheme(value);
return;
}
const update = {};
update[optionName] = value;
entry.editor.updateOptions(update);
}
function format(id) {
const entry = editors[id];
if (!entry) return;
entry.editor.getAction("editor.action.formatDocument")?.run();
}
function revealLine(id, line, column) {
const entry = editors[id];
if (!entry) return;
entry.editor.revealLineInCenter(line);
entry.editor.setPosition({ lineNumber: line, column: column || 1 });
entry.editor.focus();
}
function setValue(id, value) {
const entry = editors[id];
if (!entry) return;
if (entry.editor.getValue() !== value) {
entry.editor.setValue(value || "");
}
}
function getValue(id) {
const entry = editors[id];
return entry ? entry.editor.getValue() : null;
}
function setMarkers(id, markers) {
const entry = editors[id];
if (!entry) return;
const model = entry.editor.getModel();
if (!model) return;
monaco.editor.setModelMarkers(model, "scadabridge", markers || []);
}
function dispose(id) {
const entry = editors[id];
if (!entry) return;
try { entry.editor.dispose(); } catch (e) {}
delete editors[id];
}
window.MonacoBlazor = {
createEditor: createEditor,
setValue: setValue,
getValue: getValue,
setMarkers: setMarkers,
setEditorOption: setEditorOption,
format: format,
revealLine: revealLine,
dispose: dispose
};
})();
@@ -0,0 +1,18 @@
// Sidebar nav collapse state — persisted in the `scadabridge_nav` cookie so it
// survives full page reloads and reconnects. Invoked from NavMenu.razor via
// JS interop (window.navState.get / .set), mirroring window.treeviewStorage.
window.navState = {
// Returns the raw cookie value (comma-separated expanded section ids), or
// an empty string when the cookie is absent.
get: function () {
const match = document.cookie.match(/(?:^|;\s*)scadabridge_nav=([^;]*)/);
return match ? decodeURIComponent(match[1]) : "";
},
// Writes the cookie with a one-year lifetime. SameSite=Lax; not HttpOnly
// (JS must write it) and not sensitive.
set: function (value) {
const oneYearSeconds = 60 * 60 * 24 * 365;
document.cookie = "scadabridge_nav=" + encodeURIComponent(value) +
";path=/;max-age=" + oneYearSeconds + ";samesite=lax";
}
};
@@ -0,0 +1,23 @@
// CentralUI-020: client-side helper for the SessionExpiry component's
// idle-logout check. Pings the given URL and reports the HTTP status code so
// the Blazor component can redirect to /login once the server reports 401.
//
// `redirect: "manual"` ensures a 302 (should the endpoint ever start
// redirecting) is reported as an opaque status rather than being followed
// transparently — the component only ever wants to see the real outcome.
export async function ping(url) {
try {
const resp = await fetch(url, {
method: "GET",
credentials: "same-origin",
cache: "no-store",
redirect: "manual",
headers: { "X-Requested-With": "XMLHttpRequest" }
});
return resp.status;
} catch {
// Network failure: report 0 so the caller treats it as inconclusive
// and retries on the next poll rather than logging the user out.
return 0;
}
}
@@ -0,0 +1,20 @@
// Transport bundle export — browser-side download trigger.
//
// The TransportExport wizard (T21) computes a bundle byte[] server-side, encodes
// it to base64, and hands it to this helper to push to the user's browser as a
// file download. The base64 detour avoids binary marshalling headaches over the
// SignalR JS-interop boundary — Blazor Server cannot stream a byte[] back to
// the browser directly without a [JSInvokable] dance.
//
// The link is built fresh and removed each call so back-to-back exports don't
// keep stale URLs around in the DOM.
window.scadabridgeTransport = {
downloadBundle: function (filename, base64Data) {
const link = document.createElement('a');
link.href = "data:application/octet-stream;base64," + base64Data;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
};