/*
* VirtuaaliApuri - ID-less install snippet (/widget/script.js).
*
* The same file for every client. It asks which bot is linked to this page's
* hostname (/widget/by-host//bot.json, backed by bot_domains.py) and then
* loads the classic per-bot loader /widget//script.js exactly as if the
* client had pasted that tag themselves. Everything the loader does - rollout
* gate, self-heal, editor bridge, data-* options - keeps working unchanged,
* because this file only decides WHICH loader to load.
*
* NOTE: served through Jinja (render_template). Never write two opening curly
* braces in a row, or a curly brace followed by '#', anywhere in this file -
* not even in a comment - or the route 500s.
*/
(function () {
'use strict';
if (window.__vaGenericLoaderRan) return;
window.__vaGenericLoaderRan = true;
var DEFAULT_BASE = 'https://js.virtuaaliapuri.com';
var FETCH_TIMEOUT_MS = 5000;
// Same list as the loader's self-heal: caching plugins that re-serve our
// script from the client's own domain. The script origin is then the
// client, not us, so it must not become the base URL.
var OPTIMIZER_CACHE = /\/(?:wp-content\/cache\/(?:min|autoptimize|minify|breeze)|wp-content\/litespeed|siteground-optimizer-assets)\//i;
var LOADER_SRC = /\/widget\/[^\/?#]+\/script\.js(?:[?#]|$)/;
var self = document.currentScript;
function log(message) {
try { console.log('[Widget] ' + message); } catch (_) {}
}
function resolveBase() {
try {
var declared = self && self.getAttribute && self.getAttribute('data-base-url');
if (declared) return new URL(declared, window.location.href).origin;
} catch (_) {}
try {
var src = (self && self.src) || '';
if (src && !OPTIMIZER_CACHE.test(src)) return new URL(src, window.location.href).origin;
} catch (_) {}
return DEFAULT_BASE;
}
function normalizeHost(value) {
var host = String(value || '').toLowerCase().replace(/\.$/, '');
if (host.indexOf('www.') === 0) host = host.slice(4);
return host;
}
function editorParams() {
try {
var params = new URLSearchParams(window.location.search || '');
return params.get('va_editor') === '1' ? params : null;
} catch (_) {
return null;
}
}
// The panel's install check opens the site with ?va_editor=1. When no bot
// is linked the classic loader never runs, so tell the panel ourselves -
// it can then say "generic snippet found, domain not linked yet".
function reportUnlinked(host) {
var params = editorParams();
if (!params) return;
var target = window.parent && window.parent !== window ? window.parent : window.opener;
if (!target || !target.postMessage) return;
var message = {
source: 'virtuaaliapuri-editor-bridge',
type: 'VA_GENERIC_UNLINKED',
host: host,
url: window.location.href
};
var origin = params.get('va_parent_origin') || '*';
try { target.postMessage(message, origin); } catch (_) { target.postMessage(message, '*'); }
}
function loaderAlreadyOnPage() {
var scripts = document.getElementsByTagName('script');
for (var i = 0; i < scripts.length; i++) {
var s = scripts[i];
if (s === self || s.getAttribute('data-va-generic') === '1') continue;
if (s.src && LOADER_SRC.test(s.src)) return s.src;
}
return '';
}
function injectLoader(base, botId) {
// Both snippets on one page would mount two widgets. The explicit
// per-bot tag is the one the client chose on purpose - it wins.
var existing = loaderAlreadyOnPage();
if (existing) {
log('generic snippet standing down, per-bot loader already on page: ' + existing);
return;
}
var script = document.createElement('script');
script.src = base + '/widget/' + encodeURIComponent(botId) + '/script.js';
script.async = true;
if (self && self.attributes) {
for (var i = 0; i < self.attributes.length; i++) {
var attr = self.attributes[i];
// data-* are the loader's options; data-minify is WP Rocket's
// own "I rewrote this" marker and must not travel along.
if (attr.name.indexOf('data-') === 0 && attr.name !== 'data-minify') {
script.setAttribute(attr.name, attr.value);
}
}
var crossOrigin = self.getAttribute('crossorigin');
if (crossOrigin !== null) script.setAttribute('crossorigin', crossOrigin);
}
script.setAttribute('data-base-url', base);
script.setAttribute('data-va-generic', '1');
(document.head || document.documentElement).appendChild(script);
}
function fetchBot(base, host) {
var url = base + '/widget/by-host/' + encodeURIComponent(host) + '/bot.json';
var controller = typeof AbortController === 'function' ? new AbortController() : null;
var timer = controller ? setTimeout(function () { controller.abort(); }, FETCH_TIMEOUT_MS) : null;
function done() { if (timer) clearTimeout(timer); }
return fetch(url, { credentials: 'omit', signal: controller ? controller.signal : undefined })
.then(function (res) {
done();
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
}, function (err) {
done();
throw err;
});
}
try {
var host = normalizeHost(window.location.hostname);
if (!host) return;
var base = resolveBase();
// Consent-light (2026-09-25): no localStorage cache of the lookup any
// more - it was written for every visitor on first load. The lookup
// response is HTTP-cached (max-age 300 s, routes/v2_domains.py), so a
// returning visitor's boot is still a cache hit. Cost: during a lookup
// outage the widget does not load (it used to fall back to the last
// bot this browser resolved).
fetchBot(base, host).then(function (data) {
var botId = data && data.botId;
if (!botId) {
log('no bot linked to ' + host + ' yet');
reportUnlinked(host);
return;
}
injectLoader(base, botId);
}).catch(function (err) {
log('bot lookup failed for ' + host + ': ' + ((err && err.message) || err));
});
} catch (err) {
log('generic snippet failed: ' + ((err && err.message) || err));
}
})();