Move URL deep-link parser into the shared library for the Electron shell

The web shell defines applyWebURLParameters/triggerWebURLAction, but the
Electron renderer never loads muSRFitweb.js, so legacy musrflow:// deep
links silently did nothing (the functions' typeof guards fell back to an
empty result). The parser now lives in muSRFitlib.js, which both shells
load, and a rewritten test drives the real parser through the Electron
IPC handler instead of stubbing it.
This commit is contained in:
Zaher Salman committed 2026-10-10 23:28:46 +02:00
1 parent 54bf5af192
commit 88df374787
3 files changed
+227 -202

No files matched your search

+178
View File
@@ -13109,3 +13109,181 @@ async function startFit() {
setMusrfitActionState("", "idle");
}
}
// URL deep links (web query strings on the deployed page and legacy desktop
// links such as musrflow://.../muSRFlow?action=plot&YEAR=...&BeamLine=...&
// RunNumbers=...) initialize the same run controls the user edits by hand.
// They live here in the shared library so both shells can apply them: the web
// page consumes them from the address bar, and the Electron renderer applies
// them when the main process forwards a protocol link it received.
function findWebURLSelectValue(selectElement, requestedValue) {
// URL values come from links written by people and older CGI pages, so match
// instrument names case-insensitively while still returning the exact option
// value used by the current GUI. No arbitrary DOM ids or values are accepted.
if (!selectElement || requestedValue === undefined || requestedValue === null) {
return "";
}
let requested = String(requestedValue).trim().toLowerCase();
if (requested === "") {
return "";
}
let options = selectElement.options ? Array.from(selectElement.options) : [];
for (let option of options) {
if (String(option.value).toLowerCase() === requested) {
return option.value;
}
}
return "";
}
function applyWebURLParameters(search) {
// Deep links are deliberately a small whitelist. They initialize the same GUI
// controls a user would edit manually. The optional plot action is handled only
// after parameter initialization; server paths and other internal settings are
// never exposed through URL parameter names.
let result = {
applied: {},
errors: [],
action: ""
};
if (search === undefined || search === null) {
search = (typeof window !== "undefined" && window.location
&& typeof window.location.search === "string")
? window.location.search : "";
}
if (!search) {
return result;
}
let params = new URLSearchParams(search);
let instrumentInput = document.getElementById("instrName");
let yearInput = document.getElementById("selYear");
let runInput = document.getElementById("runNumbers");
if (!instrumentInput || !yearInput || !runInput) {
result.errors.push("Run controls are not available.");
return result;
}
// Apply the instrument first because it determines the minimum valid year and
// the default histogram groups used by the rest of the Runs tab.
if (params.has("BeamLine")) {
let requestedBeamLine = params.get("BeamLine");
let instrumentValue = findWebURLSelectValue(instrumentInput, requestedBeamLine);
if (instrumentValue) {
instrumentInput.value = instrumentValue;
result.applied.BeamLine = instrumentValue;
} else {
result.errors.push("Unsupported BeamLine: " + requestedBeamLine);
}
}
if (params.has("YEAR")) {
let requestedYear = String(params.get("YEAR") || "").trim();
let yearNumber = Number(requestedYear);
let currentMax = Number(yearInput.max) || new Date().getFullYear();
let instrument = (typeof instPars !== "undefined")
? instPars[instrumentInput.value] : null;
let minimumYear = instrument && instrument.minYear
? Number(instrument.minYear) : Number(yearInput.min || 0);
let validYear = /^\d{4}$/.test(requestedYear)
&& Number.isInteger(yearNumber)
&& yearNumber >= minimumYear
&& yearNumber <= currentMax;
if (validYear) {
yearInput.value = requestedYear;
result.applied.YEAR = requestedYear;
} else {
let rangeText = minimumYear > 0
? minimumYear + "-" + currentMax : "a supported four-digit year";
result.errors.push("Invalid YEAR " + requestedYear + " (expected " + rangeText + ").");
}
}
if (params.has("RunNumbers")) {
let requestedRuns = String(params.get("RunNumbers") || "").trim();
let expandedRuns = (typeof arrayRunNumbers === "function")
? arrayRunNumbers(requestedRuns) : [];
if (requestedRuns !== "" && expandedRuns.length > 0) {
// Preserve the compact text exactly as supplied so bookmarked links keep
// ranges such as 520-525 instead of expanding them into a long list.
runInput.value = requestedRuns;
result.applied.RunNumbers = requestedRuns;
} else {
result.errors.push("Invalid RunNumbers: " + (requestedRuns || "(empty)"));
}
}
if (params.has("action")) {
let requestedAction = String(params.get("action") || "").trim().toLowerCase();
if (requestedAction === "plot") {
// Automatic plotting is intentionally allowed only for a fully specified
// run deep link. YEAR may be omitted and then keeps the GUI's current year.
if (result.applied.BeamLine && result.applied.RunNumbers) {
result.action = "plot";
} else {
result.errors.push("action=plot requires BeamLine and RunNumbers.");
}
} else if (requestedAction !== "") {
result.errors.push("Unsupported action: " + requestedAction);
}
}
if (Object.keys(result.applied).length > 0) {
// Reuse the normal GUI update path so deep-link initialization cannot drift
// from manual editing behavior. This keeps histogram defaults, RUN-path
// validation, and the shared All object synchronized without generating MSR.
if (typeof defaultHistograms === "function") {
defaultHistograms(1);
}
if (typeof updateResolvedDataPathPreview === "function") {
updateResolvedDataPathPreview();
}
if (typeof prepCFG === "function") {
prepCFG();
}
}
if (result.errors.length > 0) {
let message = result.errors.join(" ");
if (typeof setRunInputWarning === "function") {
setRunInputWarning(message, "URL parameters");
}
if (typeof setFitStatus === "function") {
setFitStatus("Some URL parameters were ignored.", {
level: "warning",
details: "URL parameters: " + message
});
}
}
return result;
}
async function triggerWebURLAction(result) {
if (!result || result.action !== "plot") return 0;
// Build the parameter table first. cfgParams() returns the pending initial-
// parameter guess, so a header-based Frq guess is guaranteed to finish before
// the URL-triggered Plot starts. If guessing is disabled, this resolves at once.
if (typeof cfgParams === "function") {
let guess = cfgParams();
if (guess && typeof guess.then === "function") {
await guess;
}
}
if (typeof startPlot !== "function") {
if (typeof setFitStatus === "function") {
setFitStatus("Plot is not available for this URL.", {
level: "error",
details: "URL action: Plot is not available."
});
}
return 0;
}
return await startPlot();
}
-171
View File
@@ -295,28 +295,6 @@ window.MusrfitParameterPlotPlatform.openPlot = function(options = {}) {
);
return true;
};
function findWebURLSelectValue(selectElement, requestedValue) {
// URL values come from links written by people and older CGI pages, so match
// instrument names case-insensitively while still returning the exact option
// value used by the current GUI. No arbitrary DOM ids or values are accepted.
if (!selectElement || requestedValue === undefined || requestedValue === null) {
return "";
}
let requested = String(requestedValue).trim().toLowerCase();
if (requested === "") {
return "";
}
let options = selectElement.options ? Array.from(selectElement.options) : [];
for (let option of options) {
if (String(option.value).toLowerCase() === requested) {
return option.value;
}
}
return "";
}
async function gzipWebSharedText(text) {
if (typeof CompressionStream !== "function") {
// Older browsers can still create a compatible, uncompressed link.
@@ -388,155 +366,6 @@ async function copyWebDesktopConfigurationLink() {
});
}
function applyWebURLParameters(search) {
// Deep links are deliberately a small whitelist. They initialize the same GUI
// controls a user would edit manually. The optional plot action is handled only
// after parameter initialization; server paths and other internal settings are
// never exposed through URL parameter names.
let result = {
applied: {},
errors: [],
action: ""
};
if (search === undefined || search === null) {
search = window.location && typeof window.location.search === "string"
? window.location.search : "";
}
if (!search) {
return result;
}
let params = new URLSearchParams(search);
let instrumentInput = document.getElementById("instrName");
let yearInput = document.getElementById("selYear");
let runInput = document.getElementById("runNumbers");
if (!instrumentInput || !yearInput || !runInput) {
result.errors.push("Run controls are not available.");
return result;
}
// Apply the instrument first because it determines the minimum valid year and
// the default histogram groups used by the rest of the Runs tab.
if (params.has("BeamLine")) {
let requestedBeamLine = params.get("BeamLine");
let instrumentValue = findWebURLSelectValue(instrumentInput, requestedBeamLine);
if (instrumentValue) {
instrumentInput.value = instrumentValue;
result.applied.BeamLine = instrumentValue;
} else {
result.errors.push("Unsupported BeamLine: " + requestedBeamLine);
}
}
if (params.has("YEAR")) {
let requestedYear = String(params.get("YEAR") || "").trim();
let yearNumber = Number(requestedYear);
let currentMax = Number(yearInput.max) || new Date().getFullYear();
let instrument = (typeof instPars !== "undefined")
? instPars[instrumentInput.value] : null;
let minimumYear = instrument && instrument.minYear
? Number(instrument.minYear) : Number(yearInput.min || 0);
let validYear = /^\d{4}$/.test(requestedYear)
&& Number.isInteger(yearNumber)
&& yearNumber >= minimumYear
&& yearNumber <= currentMax;
if (validYear) {
yearInput.value = requestedYear;
result.applied.YEAR = requestedYear;
} else {
let rangeText = minimumYear > 0
? minimumYear + "-" + currentMax : "a supported four-digit year";
result.errors.push("Invalid YEAR " + requestedYear + " (expected " + rangeText + ").");
}
}
if (params.has("RunNumbers")) {
let requestedRuns = String(params.get("RunNumbers") || "").trim();
let expandedRuns = (typeof arrayRunNumbers === "function")
? arrayRunNumbers(requestedRuns) : [];
if (requestedRuns !== "" && expandedRuns.length > 0) {
// Preserve the compact text exactly as supplied so bookmarked links keep
// ranges such as 520-525 instead of expanding them into a long list.
runInput.value = requestedRuns;
result.applied.RunNumbers = requestedRuns;
} else {
result.errors.push("Invalid RunNumbers: " + (requestedRuns || "(empty)"));
}
}
if (params.has("action")) {
let requestedAction = String(params.get("action") || "").trim().toLowerCase();
if (requestedAction === "plot") {
// Automatic plotting is intentionally allowed only for a fully specified
// run deep link. YEAR may be omitted and then keeps the GUI's current year.
if (result.applied.BeamLine && result.applied.RunNumbers) {
result.action = "plot";
} else {
result.errors.push("action=plot requires BeamLine and RunNumbers.");
}
} else if (requestedAction !== "") {
result.errors.push("Unsupported action: " + requestedAction);
}
}
if (Object.keys(result.applied).length > 0) {
// Reuse the normal GUI update path so deep-link initialization cannot drift
// from manual editing behavior. This keeps histogram defaults, RUN-path
// validation, and the shared All object synchronized without generating MSR.
if (typeof defaultHistograms === "function") {
defaultHistograms(1);
}
if (typeof updateResolvedDataPathPreview === "function") {
updateResolvedDataPathPreview();
}
if (typeof prepCFG === "function") {
prepCFG();
}
}
if (result.errors.length > 0) {
let message = result.errors.join(" ");
if (typeof setRunInputWarning === "function") {
setRunInputWarning(message, "URL parameters");
}
if (typeof setFitStatus === "function") {
setFitStatus("Some URL parameters were ignored.", {
level: "warning",
details: "URL parameters: " + message
});
}
}
return result;
}
async function triggerWebURLAction(result) {
if (!result || result.action !== "plot") return 0;
// Build the parameter table first. cfgParams() returns the pending initial-
// parameter guess, so a header-based Frq guess is guaranteed to finish before
// the URL-triggered Plot starts. If guessing is disabled, this resolves at once.
if (typeof cfgParams === "function") {
let guess = cfgParams();
if (guess && typeof guess.then === "function") {
await guess;
}
}
if (typeof startPlot !== "function") {
if (typeof setFitStatus === "function") {
setFitStatus("Plot is not available for this URL.", {
level: "error",
details: "URL action: Plot is not available."
});
}
return 0;
}
return await startPlot();
}
async function initializeWebURLParameters() {
// Capture one-shot startup input, then clean the address bar immediately.
// Shared configuration decoding can continue asynchronously afterwards.
+49 -31
View File
@@ -25,7 +25,7 @@ function loadSharedConfigurationHelpers() {
}
};
const elements = {};
const sandbox = {
const sandbox = {URLSearchParams: URLSearchParams,
URL: URL,
console: { log: function() {} },
confirm: function() { return true; },
@@ -75,6 +75,7 @@ function loadSharedConfigurationWithPlotHelpers() {
setItem: function(key, value) { storageMap[key] = String(value); }
};
const sandbox = {
URLSearchParams: URLSearchParams,
URL: URL,
console: { log: function() {} },
confirm: function() { return true; },
@@ -250,51 +251,67 @@ function testElectronMenuAndRendererAreConnected() {
}
// A legacy web deep link (musrflow://…/muSRFlow?action=plot&YEAR=…&BeamLine=…&
// RunNumbers=…) is dispatched through the shared web URL parser instead of the
// RunNumbers=…) is dispatched through the shared URL parser instead of the
// encoded-fragment restore path, and its plot action runs the established Plot
// flow. This mirrors exactly what the Electron renderer does when the main
// process forwards such a link from the command line or a second instance.
// process forwards such a link from the command line or a second instance. The
// parser lives in the shared library so the Electron shell (which never loads
// the web shell) still has it; stubbing the parser here would mask a missing
// function exactly like the one this test guards against.
async function testElectronLegacyDeepLinkUsesWebParser() {
const env = loadSharedConfigurationHelpers();
const lib = env.sandbox;
let parsedSearch = "";
let triggerCalls = 0;
let triggeredResult = null;
lib.applyWebURLParameters = function(search) {
parsedSearch = search;
return {
applied: { BeamLine: "LEM", YEAR: "2026", RunNumbers: "3557" },
errors: [], action: "plot"
};
};
lib.triggerWebURLAction = async function(result) {
triggerCalls++;
triggeredResult = result;
return 1;
const instrumentInput = {
value: "",
options: [{ value: "LEM" }, { value: "GPS" }]
};
const yearInput = { value: "", min: "1998", max: "2026" };
const runInput = { value: "" };
env.elements.instrName = instrumentInput;
env.elements.selYear = yearInput;
env.elements.runNumbers = runInput;
lib.instPars = { LEM: { minYear: "2001" }, GPS: { minYear: "1993" } };
lib.defaultHistograms = function() {};
lib.updateResolvedDataPathPreview = function() {};
lib.prepCFG = function() {};
let startPlotCalls = 0;
lib.startPlot = async function() { startPlotCalls++; return 1; };
lib.cfgParams = function() { return null; };
lib.setRunInputWarning = function() {};
lib.setFitStatus = function() {};
// The Electron shell relies on the shared library for the parser; without
// it the deep link would silently do nothing (the bug this guards against).
assert.strictEqual(typeof lib.applyWebURLParameters, "function");
assert.strictEqual(typeof lib.triggerWebURLAction, "function");
lib.firstLoad();
const legacyURL = "musrflow://musruser.psi.ch/muSRFlow?action=plot&YEAR=2026&BeamLine=LEM&RunNumbers=3557";
await env.ipcListeners.openSharedConfiguration(legacyURL);
assert.strictEqual(parsedSearch, "?action=plot&YEAR=2026&BeamLine=LEM&RunNumbers=3557");
assert.strictEqual(triggerCalls, 1);
assert.strictEqual(triggeredResult.action, "plot");
assert.strictEqual(runInput.value, "3557");
assert.strictEqual(instrumentInput.value, "LEM");
assert.strictEqual(yearInput.value, "2026");
assert.strictEqual(startPlotCalls, 1);
// A legacy URL without a plot action initializes controls only.
triggerCalls = 0;
lib.applyWebURLParameters = function() {
return { applied: { BeamLine: "LEM" }, errors: [], action: "" };
};
await env.ipcListeners.openSharedConfiguration("musrflow://musruser.psi.ch/muSRFlow?BeamLine=LEM");
assert.strictEqual(triggerCalls, 0);
startPlotCalls = 0;
await env.ipcListeners.openSharedConfiguration("musrflow://musruser.psi.ch/muSRFlow?BeamLine=GPS");
assert.strictEqual(instrumentInput.value, "GPS");
assert.strictEqual(startPlotCalls, 0);
// A musrflow:// URL with no query string is ignored, not restored.
triggerCalls = 0;
let parserCalls = 0;
lib.applyWebURLParameters = function() { parserCalls++; return { applied: {}, action: "" }; };
startPlotCalls = 0;
await env.ipcListeners.openSharedConfiguration("musrflow://open/");
assert.strictEqual(triggerCalls, 0);
assert.strictEqual(parserCalls, 0);
assert.strictEqual(startPlotCalls, 0);
assert.strictEqual(runInput.value, "3557");
// Invalid values surface through the shared warning channel, same as on the
// web page, instead of a silent no-op.
let warning = "";
lib.setRunInputWarning = function(message) { warning = message; };
await env.ipcListeners.openSharedConfiguration(
"musrflow://musruser.psi.ch/muSRFlow?BeamLine=UNKNOWN");
assert.match(warning, /Unsupported BeamLine/);
}
// Extract a top-level function body from a source file and evaluate it so the
@@ -600,6 +617,7 @@ async function testElectronSharedURLRestoresThroughListener() {
function buildHardenedSandbox(bridgeZlib, extraAPI) {
const hardenedElements = {};
const hardenedSandbox = {
URLSearchParams: URLSearchParams,
URL: URL,
console: { log: function() {} },
confirm: function() { return true; },