sc-theme-builder/lib/onLoad.js
2026-07-01 20:07:28 -05:00

35 lines
1.8 KiB
JavaScript

// lib/onLoad.js
// Idempotent per-tenant bootstrap + active-CSS rehydration (ARCHITECTURE.md 5.6).
const db = require("@saltcorn/data/db");
const { getState } = require("@saltcorn/data/db/state");
const { eachTenant } = require("@saltcorn/admin-models/models/tenant"); // canonical (folded fix)
const themeStore = require("./themeStore");
const cssCache = require("./cssCache");
const { getActivePointer } = require("./activePointer");
const { PLUGIN_NAME } = require("./constants");
async function bootstrapTenant() {
// 1) HOT-PATH SHORT-CIRCUIT: if the table already exists for THIS tenant, skip all DDL
// work cheaply (loadPlugin re-runs onLoad on every activate). (folded review fix)
await themeStore.ensureTableForCurrentTenant(); // Table.findOne first; Table.create only if null
// 2) Rehydrate the active-CSS cache from the persisted pointer so the live site is themed
// immediately after a restart/new worker (folded review fix: rehydration was unowned).
try {
const { activeThemeId, activeByRole } = getActivePointer();
const keys = new Set();
if (activeThemeId) keys.add(null); // default key
for (const r of Object.keys(activeByRole)) keys.add(Number(r));
for (const roleKey of keys) {
const id = roleKey == null ? activeThemeId : activeByRole[roleKey];
if (id) await cssCache.warm(id, roleKey); // recompile -> cache
}
} catch (e) { getState().log(3, `theme-builder rehydrate failed: ${e.message}`); }
}
// eachTenant self-selects single vs multi: it runs default_schema FIRST then iterates
// DB-backed tenants only in MT mode. No hand-rolled is_it_multi_tenant branch. (folded fix)
async function onLoad(/* rawCfg */) {
await eachTenant(bootstrapTenant);
}
module.exports = { onLoad, bootstrapTenant };