Something went wrong. Try again.
A reusable desktop shell: your sidecar, your index, safe APIs, installers for every platform
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277// mollusc.json: loading, validation, defaults, and `${var}` substitution. Pure// Node with no Electron in it, so the CLI and the tests use it as well.import { readFile } from 'node:fs/promises';import { join } from 'node:path';
export const CONFIG_FILE = 'mollusc.json';
// Everything a page may be allowed to call through the bridge. The main// process implements exactly these; `api` picks from them.export const API_NAMES = [ 'fs.read', 'fs.write', 'fs.list', 'fs.stat', 'fs.mkdir', 'fs.trash', 'dialog.open', 'dialog.save', 'dialog.message', 'shell.openExternal', 'shell.showInFolder', 'window.close', 'window.hide', 'notification.show', 'app.info', 'app.setBadge', 'app.quit',];
// What `${…}` may name in any string of the config. `port` is the sidecar's// port; `token` a secret made fresh at each launch that the sidecar and the// page share (the page reads it as `mollusc.env.token`); the others are// directories.export const VARIABLES = ['port', 'token', 'appDir', 'userData', 'home'];
// What the renderers may reach: anything, or loopback alone (see main.js).export const NETWORKS = ['any', 'loopback'];
export const TITLE_BAR_STYLES = ['default', 'hidden', 'hiddenInset', 'customButtonsOnHover'];
// What a menu item's `action` may ask of the shell (see menu.js).export const MENU_ACTIONS = ['showWindow'];
const KNOWN_KEYS = ['$schema', 'id', 'name', 'version', 'description', 'author', 'icon', 'sidecar', 'window', 'api', 'menu', 'fileTypes', 'urlSchemes', 'tray', 'permissions', 'roots', 'network', 'build', 'dev'];const ID_RE = /^[a-z0-9]+(\.[a-z0-9-]+)+$/i;const VAR_RE = /\$\{([a-zA-Z]+)\}/g;const ABSOLUTE_URL_RE = /^[a-z][a-z0-9+.-]*:/i;const WINDOW_BOOLEANS = ['show', 'frame', 'transparent', 'resizable', 'movable', 'minimizable', 'maximizable', 'fullscreenable', 'alwaysOnTop', 'skipTaskbar', 'popover', 'maximized', 'remember'];
export async function loadConfig (appDir) { const file = join(appDir, CONFIG_FILE); let text; try { text = await readFile(file, 'utf8'); } catch (err) { throw new Error(err.code === 'ENOENT' ? `No ${CONFIG_FILE} in ${appDir}` : `Cannot read ${file}: ${err.message}`); } let raw; try { raw = JSON.parse(text); } catch (err) { throw new Error(`${file} is not valid JSON: ${err.message}`); } const { errors, warnings } = validate(raw); if (errors.length) throw new Error(`${file}:\n ${errors.join('\n ')}`); return { config: normalize(raw), warnings, appDir, file };}
export function validate (raw) { const errors = []; const warnings = []; if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { errors: ['the config must be a JSON object'], warnings }; const err = (m) => errors.push(m); const str = (key, value, { required = false, re, hint } = {}) => { if (value == null) { if (required) err(`${key} is required`); return; } if (typeof value !== 'string' || !value) err(`${key} must be a non-empty string`); else if (re && !re.test(value)) err(`${key} ${hint}`); }; const bool = (key, value) => { if (value != null && typeof value !== 'boolean') err(`${key} must be true or false`); }; const num = (key, value) => { if (value != null && !Number.isFinite(value)) err(`${key} must be a number`); }; const obj = (key, value, required = false) => { if (value == null) { if (required) err(`${key} is required`); return false; } if (typeof value !== 'object' || Array.isArray(value)) { err(`${key} must be an object`); return false; } return true; }; const arr = (key, value, each) => { if (value == null) return; if (!Array.isArray(value)) { err(`${key} must be an array`); return; } value.forEach((v, i) => each(`${key}[${i}]`, v)); }; const strings = (key, value) => arr(key, value, (k, v) => str(k, v, { required: true })); const env = (key, value) => { if (obj(key, value)) for (const [k, v] of Object.entries(value)) str(`${key}.${k}`, v, { required: true }); }; const menu = (key, value) => arr(key, value, (k, item) => { if (!obj(k, item, true)) return; str(`${k}.label`, item.label); str(`${k}.role`, item.role); str(`${k}.send`, item.send); if (item.action != null && !MENU_ACTIONS.includes(item.action)) err(`${k}.action must be one of ${MENU_ACTIONS.join(', ')}`); if (item.items != null && item.submenu != null) err(`${k} has both items and submenu`); menu(`${k}.items`, item.items); menu(`${k}.submenu`, item.submenu); }); const sidecar = (key, s) => { bool(`${key}.node`, s.node); strings(`${key}.args`, s.args); if (s.node) { if (!Array.isArray(s.args) || !s.args.length) err(`${key}.args must start with the script to run when ${key}.node is true`); if (s.command != null && s.command !== 'node') err(`${key}.command must be "node" or omitted when ${key}.node is true`); } else str(`${key}.command`, s.command, { required: true }); env(`${key}.env`, s.env); str(`${key}.ready`, s.ready, { re: ABSOLUTE_URL_RE, hint: 'must be a URL' }); bool(`${key}.keepAlive`, s.keepAlive); bool(`${key}.attach`, s.attach); num(`${key}.readyTimeout`, s.readyTimeout); if (s.port != null && !(Number.isInteger(s.port) && s.port > 0 && s.port < 65536)) err(`${key}.port must be a port number`); if (s.attach && s.port == null) err(`${key}.attach needs ${key}.port: it attaches to a sidecar already on that port`); if (s.attach && !s.ready) err(`${key}.attach needs ${key}.ready, to tell whether one is already running`); }; const window = (key, w) => { str(`${key}.url`, w.url, { required: true }); if (typeof w.url === 'string' && !ABSOLUTE_URL_RE.test(w.url) && (w.url.startsWith('/') || w.url.split(/[\\/]/).includes('..'))) { err(`${key}.url must be a URL or a path relative to the app directory`); } for (const k of ['width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight', 'x', 'y']) num(`${key}.${k}`, w[k]); str(`${key}.title`, w.title); if (w.titleBarStyle != null && !TITLE_BAR_STYLES.includes(w.titleBarStyle)) err(`${key}.titleBarStyle must be one of ${TITLE_BAR_STYLES.join(', ')}`); const bg = w.backgroundColor; if (bg != null && typeof bg !== 'string' && !(typeof bg === 'object' && typeof bg.light === 'string' && typeof bg.dark === 'string')) { err(`${key}.backgroundColor must be a colour or { light, dark }`); } for (const k of WINDOW_BOOLEANS) bool(`${key}.${k}`, w[k]); }; // A command line to run: a string (through the shell) or [command, ...args]. const commandLine = (key, v) => { if (typeof v === 'string') { if (!v) err(`${key} must not be empty`); } else if (!Array.isArray(v) || !v.length || v.some((a) => typeof a !== 'string')) err(`${key} must be a command string or [command, ...args]`); };
str('id', raw.id, { required: true, re: ID_RE, hint: 'must be a reverse-DNS identifier like com.example.app' }); str('name', raw.name, { required: true, re: /^[a-z0-9][a-z0-9._-]*$/i, hint: 'must be a plain name: letters, digits, dots, dashes, underscores' }); str('version', raw.version, { required: true, re: /^\d+\.\d+\.\d+/, hint: 'must look like 1.2.3' }); str('description', raw.description); str('author', raw.author); str('icon', raw.icon);
if (obj('sidecar', raw.sidecar)) sidecar('sidecar', raw.sidecar); if (obj('window', raw.window)) window('window', raw.window);
arr('api', raw.api, (k, v) => { if (typeof v !== 'string') err(`${k} must be a string`); else if (!API_NAMES.includes(v)) err(`${k}: unknown api "${v}" (known: ${API_NAMES.join(', ')})`); }); menu('menu', raw.menu); arr('fileTypes', raw.fileTypes, (k, v) => { if (!obj(k, v, true)) return; const ext = Array.isArray(v.ext) ? v.ext : [v.ext]; if (!ext.length || ext.some((e) => typeof e !== 'string' || !e)) err(`${k}.ext must be an extension or a list of them`); str(`${k}.name`, v.name, { required: true }); str(`${k}.description`, v.description); str(`${k}.role`, v.role); str(`${k}.icon`, v.icon); str(`${k}.mimeType`, v.mimeType); // Alternate: can open the type without claiming to be its default app. if (v.rank != null && !['Owner', 'Default', 'Alternate', 'None'].includes(v.rank)) err(`${k}.rank must be Owner, Default, Alternate or None`); }); arr('urlSchemes', raw.urlSchemes, (k, v) => str(k, v, { required: true, re: /^[a-z][a-z0-9+.-]*$/i, hint: 'must be a URL scheme like myapp' })); if (raw.tray != null && obj('tray', raw.tray)) { str('tray.icon', raw.tray.icon, { required: true }); str('tray.tooltip', raw.tray.tooltip); str('tray.click', raw.tray.click); menu('tray.menu', raw.tray.menu); } if (raw.window?.popover && !raw.tray) err('window.popover needs a tray to hang from'); strings('permissions', raw.permissions); strings('roots', raw.roots); if (raw.network != null && !NETWORKS.includes(raw.network)) err(`network must be one of ${NETWORKS.join(', ')}`); if (obj('build', raw.build)) { strings('build.files', raw.build.files); str('build.productName', raw.build.productName); bool('build.modules', raw.build.modules); // Where installers go: `out`, say, when a bundler already builds the page into dist/. str('build.output', raw.build.output, { re: /^(?!\/)(?!.*(^|[\\/])\.\.([\\/]|$)).+$/, hint: 'must be a directory inside the app' }); arr('build.before', raw.build.before, commandLine); for (const k of ['mac', 'win', 'linux', 'dmg', 'nsis']) obj(`build.${k}`, raw.build[k]); } if (obj('dev', raw.dev)) { const d = raw.dev; strings('dev.reload', d.reload); strings('dev.restart', d.restart); arr('dev.before', d.before, commandLine); // dev.sidecar and dev.window are laid over their top-level namesakes when // running from source; the result has to hold up on its own. if (obj('dev.sidecar', d.sidecar)) sidecar('dev.sidecar', { ...raw.sidecar, ...d.sidecar }); if (obj('dev.window', d.window)) window('dev.window', { ...raw.window, ...d.window }); arr('dev.serve', d.serve, (k, s) => { if (!obj(k, s, true)) return; str(`${k}.command`, s.command, { required: true }); strings(`${k}.args`, s.args); env(`${k}.env`, s.env); str(`${k}.ready`, s.ready, { re: ABSOLUTE_URL_RE, hint: 'must be a URL' }); num(`${k}.readyTimeout`, s.readyTimeout); }); }
for (const name of variablesIn(raw)) { if (!VARIABLES.includes(name)) err(`unknown variable \${${name}} (known: ${VARIABLES.map((v) => `\${${v}}`).join(', ')})`); } if (!raw.window && !raw.tray) warnings.push('neither window nor tray is set: the app will have no UI'); for (const k of Object.keys(raw)) if (!KNOWN_KEYS.includes(k)) warnings.push(`unknown key "${k}" is ignored`); return { errors, warnings };}
const sidecarDefaults = (s) => ({ args: [], env: {}, ready: null, node: false, keepAlive: false, attach: false, port: null, readyTimeout: 30000, ...s, command: s.command ?? (s.node ? 'node' : undefined),});
// Fills in defaults so the rest of the shell never has to check for absence.export function normalize (raw) { const c = structuredClone(raw); c.description ??= ''; c.icon ??= null; c.sidecar = c.sidecar ? sidecarDefaults(c.sidecar) : null; c.window = c.window ? { width: 1200, height: 800, ...c.window } : null; c.api ??= []; c.menu ??= null; c.fileTypes = (c.fileTypes ?? []).map((ft) => ({ ...ft, ext: Array.isArray(ft.ext) ? ft.ext : [ft.ext] })); c.urlSchemes ??= []; c.tray ??= null; c.permissions ??= []; c.roots ??= null; c.network ??= 'any'; c.build = { before: [], output: 'dist', ...c.build }; c.dev = { serve: [], before: [], ...c.dev }; c.dev.serve = c.dev.serve.map((s) => ({ args: [], env: {}, ready: null, readyTimeout: 30000, ...s })); return c;}
// The config as it applies when running from source: dev.sidecar and// dev.window laid over the top-level ones.export function forDev (config) { const c = structuredClone(config); const { sidecar, window } = c.dev; if (sidecar) c.sidecar = sidecarDefaults({ ...config.sidecar, ...sidecar }); if (window) c.window = { ...config.window, ...window }; return c;}
export function variablesIn (value, found = new Set()) { if (typeof value === 'string') for (const m of value.matchAll(VAR_RE)) found.add(m[1]); else if (Array.isArray(value)) for (const v of value) variablesIn(v, found); else if (value && typeof value === 'object') for (const v of Object.values(value)) variablesIn(v, found); return found;}
export const usesVariable = (value, name) => variablesIn(value).has(name);
// Replaces `${name}` in every string of `value` with `vars[name]`.export function substitute (value, vars) { if (typeof value === 'string') { return value.replace(VAR_RE, (m, name) => { if (!(name in vars) || vars[name] == null) throw new Error(`${m} is not available here`); return String(vars[name]); }); } if (Array.isArray(value)) return value.map((v) => substitute(v, vars)); if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, substitute(v, vars)])); return value;}
// The host part of the app's own origin: app://<host>/…export const appHost = (config) => config.id.toLowerCase();
export const originOf = (url) => { try { const u = new URL(url); return `${u.protocol}//${u.host}`; } catch { return null; }};
// Where the main window goes: a localhost URL as given, or a path in the app// directory served from the app's own `app://` origin.export function windowTarget (config) { const { url } = config.window; if (ABSOLUTE_URL_RE.test(url)) return { url, origin: originOf(url), kind: 'http' }; const rel = url.replace(/\\/g, '/').replace(/^\.\//, ''); const origin = `app://${appHost(config)}`; return { url: `${origin}/${rel}`, origin, kind: 'app', path: rel };}