feat(csr): add the api block transport

This commit is contained in:
2026-08-19 15:37:23 +05:30
parent 323f57b32b
commit b457ad1d54
3 changed files with 154 additions and 1 deletions
+60
View File
@@ -1380,6 +1380,7 @@ export const REACTIVE_RUNTIME = String.raw`
state: stateProxy,
output: outputProxy,
server: serverProxy,
callApi: wrnexusCallApi,
props: propsProxy,
refs: refsProxy,
};
@@ -4246,6 +4247,65 @@ export const REACTIVE_RUNTIME = String.raw`
});
}
/*
* Transport for compiled api blocks.
*
* Only the request and the failure shape live here. A block's response and
* error bodies are page code, so they are emitted into the browser module
* and applied by the caller.
*/
function readCsrfToken() {
var meta = document.querySelector('meta[name="wrnexus-csrf"]');
if (meta) return meta.getAttribute("content") || "";
var match = /(?:^|;\s*)wrn-csrf=([^;]+)/.exec(document.cookie || "");
return match ? decodeURIComponent(match[1]) : "";
}
function wrnexusCallApi(path, method, input) {
var verb = String(method || "GET").toUpperCase();
var values = input || {};
var url = path;
var headers = { accept: "application/json" };
var init = { method: verb, credentials: "same-origin", headers: headers };
if (verb === "GET" || verb === "HEAD") {
var query = [];
Object.keys(values).forEach(function (key) {
var value = values[key];
// An omitted filter must not become "name=undefined".
if (value === undefined || value === null || value === "") return;
query.push(encodeURIComponent(key) + "=" + encodeURIComponent(String(value)));
});
if (query.length) url = path + "?" + query.join("&");
} else {
headers["content-type"] = "application/json";
headers["x-csrf-token"] = readCsrfToken();
init.body = JSON.stringify(values);
}
return fetch(url, init).then(function (response) {
return response.json().then(
function (data) {
if (response.ok) return data;
var message =
data && data.error ? String(data.error) : "Request failed with " + response.status;
var failure = new Error(message);
failure.status = response.status;
failure.data = data;
throw failure;
},
function () {
var failure = new Error("Response was not valid JSON");
failure.status = response.status;
failure.data = undefined;
throw failure;
},
);
});
}
window.__wrnexusCallApi = wrnexusCallApi;
function dispatchComponentEvent(root, name, detail) {
if (!root || !name) return null;
var EventConstructor =