diff --git a/exporter.js b/exporter.js
new file mode 100644
index 0000000..dfcf909
--- /dev/null
+++ b/exporter.js
@@ -0,0 +1,60 @@
+// Export helpers: wikitext source as HTML for PDF and Word, and the Word (.docx) writer.
+'use strict';
+const HTMLtoDOCX = require('html-to-docx');
+
+const PAPER = {
+ Letter: { w: 12240, h: 15840 },
+ A4: { w: 11906, h: 16838 }
+};
+
+function esc(s) {
+ return String(s).replace(/&/g, '&').replace(//g, '>');
+}
+
+// Full page for the PDF of the wikitext source.
+function markupPage(title, text) {
+ return '
' + esc(title) + '
' + esc(title) + '
' + esc(text.replace(/\r\n?/g, '\n')) + '
';
+}
+
+// Body markup for Word: one paragraph per line so spacing and line breaks survive.
+function markupBody(title, text) {
+ const lines = text.replace(/\r\n?/g, '\n').split('\n').map((l) => {
+ const lead = /^ */.exec(l)[0].length;
+ const body = ' '.repeat(lead) + esc(l.slice(lead)).replace(/\t/g, ' ');
+ return '
' + (body || ' ') + '
';
+ });
+ return '
' + esc(title) + '
' + lines.join('');
+}
+
+function wrapDoc(title, body) {
+ return '' + esc(title) + '' + body + '';
+}
+
+// The Word writer drops a lone space between two inline elements, so make those spaces non-breaking.
+function fixSpaces(html) {
+ const inl = 'b|i|u|s|em|strong|span|a|code|sup|sub|small|big|cite|abbr|q|mark|del|ins';
+ const re = new RegExp('((?:' + inl + ')>)\\s+(<(?:' + inl + '|img)[\\s>])', 'gi');
+ let prev;
+ do { prev = html; html = html.replace(re, '$1 $2'); } while (html !== prev);
+ return html;
+}
+
+async function toDocx(title, body, paper) {
+ body = fixSpaces(body);
+ const p = PAPER[paper] || PAPER.Letter;
+ const opts = { title, pageSize: { width: p.w, height: p.h }, table: { row: { cantSplit: true } }, footer: false, pageNumber: false };
+ let out;
+ try {
+ out = await HTMLtoDOCX(wrapDoc(title, body), null, opts);
+ } catch (e) {
+ // Pictures that cannot be fetched can sink the whole file, so try again without them.
+ out = await HTMLtoDOCX(wrapDoc(title, body.replace(/]*>/gi, '')), null, opts);
+ }
+ return Buffer.isBuffer(out) ? out : Buffer.from(await out.arrayBuffer ? await out.arrayBuffer() : out);
+}
+
+module.exports = { markupPage, markupBody, toDocx, fixSpaces, PAPER };
diff --git a/preload.js b/preload.js
new file mode 100644
index 0000000..cfbd536
--- /dev/null
+++ b/preload.js
@@ -0,0 +1,24 @@
+'use strict';
+const { contextBridge, ipcRenderer } = require('electron');
+
+contextBridge.exposeInMainWorld('wn', {
+ getConfig: () => ipcRenderer.invoke('config:get'),
+ setConfig: (patch) => ipcRenderer.invoke('config:set', patch),
+ listNotes: (query) => ipcRenderer.invoke('notes:list', query),
+ readNote: (file) => ipcRenderer.invoke('notes:read', file),
+ writeNote: (file, text) => ipcRenderer.invoke('notes:write', file, text),
+ writeNoteSync: (file, text) => ipcRenderer.sendSync('notes:writeSync', file, text),
+ createNote: (base) => ipcRenderer.invoke('notes:create', base),
+ renameNote: (file, title) => ipcRenderer.invoke('notes:rename', file, title),
+ deleteNote: (file) => ipcRenderer.invoke('notes:delete', file),
+ pickFolder: () => ipcRenderer.invoke('dialog:pickFolder'),
+ pickCss: () => ipcRenderer.invoke('dialog:pickCss'),
+ readCss: (p) => ipcRenderer.invoke('css:read', p),
+ connect: (url) => ipcRenderer.invoke('wiki:connect', url),
+ parse: (req) => ipcRenderer.invoke('wiki:parse', req),
+ spellCheck: (text) => ipcRenderer.invoke('spell:check', text),
+ spellSuggest: (word) => ipcRenderer.invoke('spell:suggest', word),
+ spellAdd: (word) => ipcRenderer.invoke('spell:add', word),
+ thesaurus: (word) => ipcRenderer.invoke('thes:lookup', word),
+ exportFile: (req) => ipcRenderer.invoke('export:run', req)
+});
diff --git a/spell.js b/spell.js
new file mode 100644
index 0000000..73caf3f
--- /dev/null
+++ b/spell.js
@@ -0,0 +1,80 @@
+// Offline spell checker for wikitext. Markup that is not prose (templates, tags, link targets,
+// URLs, attributes, comments, code) is blanked out first so it is never flagged.
+'use strict';
+const fs = require('fs');
+const path = require('path');
+const nspell = require('nspell');
+
+const LANGS = { 'en-US': 1, 'en-GB': 1 };
+const cache = {};
+
+function speller(lang) {
+ if (!LANGS[lang]) lang = 'en-US';
+ if (!cache[lang]) {
+ const dir = path.join(__dirname, 'dict', lang);
+ cache[lang] = nspell({ aff: fs.readFileSync(path.join(dir, 'index.aff')), dic: fs.readFileSync(path.join(dir, 'index.dic')) });
+ }
+ return cache[lang];
+}
+
+function proseMask(text) {
+ const out = text.split('');
+ const blank = (a, b) => { for (let i = a; i < b; i++) if (out[i] !== '\n') out[i] = ' '; };
+ const kill = (re) => { let m; const s = out.join(''); while ((m = re.exec(s))) blank(m.index, m.index + m[0].length); };
+ kill(/|$)/g);
+ kill(/<(nowiki|pre|source|syntaxhighlight|math|code|score|kbd)\b[^>]*>[\s\S]*?<\/\1>/gi);
+ // templates, innermost out
+ let s = out.join('');
+ let depth = 0;
+ let st = 0;
+ for (let i = 0; i < s.length; i++) {
+ if (s[i] === '{' && s[i + 1] === '{') { if (depth === 0) st = i; depth++; i++; }
+ else if (s[i] === '}' && s[i + 1] === '}' && depth > 0) { depth--; i++; if (depth === 0) blank(st, i + 1); }
+ }
+ if (depth > 0) blank(st, out.length);
+ kill(/\[\[(?:File|Image|Media|Category):[^\]\n]*\]\]/gi);
+ // link targets: keep the shown text of [[target|shown]], hide target of [[target]] only when piped
+ kill(/\[\[[^\]|\n]*\|/g);
+ kill(/\[\[[^\]\n]*\]\]/g); // unpiped links are names; skip them
+ kill(/\[(?:https?|ftp):\/\/\S+/gi);
+ kill(/(?:https?|ftp):\/\/\S+/gi);
+ kill(/<\/?[A-Za-z][^>\n]*>/g);
+ kill(/?\w+;/g);
+ kill(/[A-Za-z_:-]+\s*=\s*"[^"\n]*"/g);
+ kill(/[A-Za-z_:-]+\s*=\s*[^\s|!"'>]+/g);
+ kill(/__[A-Z]+__/g);
+ kill(/^\{\|.*$/gm);
+ kill(/^\|[-+}]?.*(?:class|style)=.*$/gm);
+ return out.join('');
+}
+
+function check(text, lang, personal, ignore) {
+ const sp = speller(lang);
+ (personal || []).forEach((w) => sp.add(w));
+ const ign = new Set((ignore || []).map((w) => w.toLowerCase()));
+ const masked = proseMask(text);
+ const out = [];
+ const re = /[\p{L}][\p{L}'’]*/gu;
+ let m;
+ while ((m = re.exec(masked))) {
+ let w = m[0].replace(/[’]/g, "'");
+ let len = m[0].length;
+ w = w.replace(/'+$/, '');
+ len = w.length;
+ if (w.length < 2) continue;
+ if (/^[A-Z]{2,}s?$/.test(w)) continue; // acronyms
+ if (/[a-z][A-Z]/.test(w)) continue; // camelCase
+ if (ign.has(w.toLowerCase())) continue;
+ if (sp.correct(w)) continue;
+ if (/'s$/i.test(w) && sp.correct(w.slice(0, -2))) continue;
+ if (/^[A-Z]/.test(w) === false && sp.correct(w.charAt(0).toUpperCase() + w.slice(1))) continue;
+ out.push({ start: m.index, end: m.index + len, word: w });
+ }
+ return out;
+}
+
+function suggest(word, lang) {
+ return speller(lang).suggest(word).slice(0, 8);
+}
+
+module.exports = { check, suggest, proseMask };
diff --git a/wikiapi.js b/wikiapi.js
new file mode 100644
index 0000000..ba75867
--- /dev/null
+++ b/wikiapi.js
@@ -0,0 +1,198 @@
+'use strict';
+// Talks to any standard MediaWiki site through its public api.php.
+// Pure Node code (no Electron imports) so it can be tested on its own.
+// A fetch function is passed in so the app can use Electron's network stack.
+
+const UA = 'Swiftmark/1.0 (desktop wikitext editor)';
+
+function normalizeInput(input) {
+ let s = String(input || '').trim();
+ if (!s) throw new Error('Enter your wiki address first.');
+ if (!/^https?:\/\//i.test(s)) s = 'https://' + s;
+ return new URL(s);
+}
+
+async function fetchText(fetchFn, url, init, timeoutMs) {
+ const ctl = new AbortController();
+ const timer = setTimeout(() => ctl.abort(), timeoutMs || 15000);
+ try {
+ const headers = Object.assign({ 'User-Agent': UA }, (init && init.headers) || {});
+ const opts = Object.assign({}, init, { headers, signal: ctl.signal });
+ const res = await fetchFn(url, opts);
+ const body = await res.text();
+ return { status: res.status, body };
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+function candidateApis(u, html) {
+ const out = [];
+ const add = (x) => {
+ try {
+ const s = new URL(x, u).toString();
+ if (!out.includes(s)) out.push(s);
+ } catch (e) { /* ignore bad candidate */ }
+ };
+
+ if (/api\.php$/i.test(u.pathname)) add(u.origin + u.pathname);
+
+ if (html) {
+ const m = html.match(/]+rel=["']EditURI["'][^>]*href=["']([^"']+)["']/i) ||
+ html.match(/]+href=["']([^"']+)["'][^>]*rel=["']EditURI["']/i);
+ if (m) add(m[1].replace(/&/g, '&').split('?')[0]);
+ }
+
+ const p = u.pathname;
+ let base = p.replace(/\/+$/, '');
+ const i1 = p.search(/\/index\.php/i);
+ const i2 = p.search(/\/wiki\//i);
+ if (i1 >= 0) base = p.slice(0, i1);
+ else if (i2 >= 0) base = p.slice(0, i2);
+ add(base + '/api.php');
+ add(base + '/w/api.php');
+ add(u.origin + '/w/api.php');
+ add(u.origin + '/api.php');
+ add(u.origin + '/wiki/api.php');
+ add(u.origin + '/mediawiki/api.php');
+ add(base + '/mediawiki/api.php');
+ return out.slice(0, 9);
+}
+
+async function probe(fetchFn, api) {
+ try {
+ const url = api + '?action=query&meta=siteinfo&siprop=general&format=json&formatversion=2';
+ const r = await fetchText(fetchFn, url, {});
+ let j;
+ try { j = JSON.parse(r.body); } catch (e) {
+ if (r.status === 401 || r.status === 403) return { ok: false, kind: 'blocked', status: r.status };
+ if (r.status === 404) return { ok: false, kind: 'notfound', status: r.status };
+ return { ok: false, kind: 'notapi', status: r.status };
+ }
+ if (j.error) {
+ const code = j.error.code || '';
+ const priv = /^(readapidenied|permissiondenied|login-required)/.test(code);
+ return { ok: false, kind: priv ? 'private' : 'apierror', code, info: j.error.info || '' };
+ }
+ if (j.query && j.query.general) {
+ return { ok: true, name: j.query.general.sitename, generator: j.query.general.generator };
+ }
+ return { ok: false, kind: 'notapi' };
+ } catch (e) {
+ return { ok: false, kind: 'unreachable', message: e.message };
+ }
+}
+
+async function parseWiki(fetchFn, api, text, title) {
+ const params = new URLSearchParams({
+ action: 'parse',
+ format: 'json',
+ formatversion: '2',
+ contentmodel: 'wikitext',
+ text: String(text),
+ title: title || 'Preview',
+ prop: 'text|headhtml|categorieshtml|displaytitle',
+ disableeditsection: '1',
+ disablelimitreport: '1',
+ preview: '1',
+ pst: '1'
+ });
+ let r;
+ try {
+ r = await fetchText(fetchFn, api, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
+ body: params.toString()
+ }, 30000);
+ } catch (e) {
+ return { ok: false, kind: 'unreachable', message: e.message };
+ }
+ let j;
+ try { j = JSON.parse(r.body); } catch (e) {
+ return { ok: false, kind: (r.status === 401 || r.status === 403) ? 'blocked' : 'notapi', status: r.status };
+ }
+ if (j.error) {
+ const code = j.error.code || '';
+ const priv = /^(readapidenied|permissiondenied|login-required)/.test(code);
+ return { ok: false, kind: priv ? 'private' : 'apierror', code, info: j.error.info || '' };
+ }
+ if (!j.parse || typeof j.parse.text === 'undefined') {
+ return { ok: false, kind: 'apierror', code: 'noparse', info: 'Unexpected answer from the API.' };
+ }
+ return { ok: true, json: j };
+}
+
+function explain(f, u) {
+ const host = u ? u.host : 'the server';
+ switch (f.kind) {
+ case 'private':
+ return 'The API refused the request because ' + host + ' does not let logged out visitors read the wiki.';
+ case 'blocked':
+ return 'The server answered with HTTP ' + (f.status || '401 or 403') + ', so something (a firewall, a security plugin or CDN bot protection) is blocking API requests.';
+ case 'unreachable':
+ return 'Could not reach ' + host + (f.message ? ' (' + f.message + ').' : '.');
+ case 'apierror':
+ return 'The API answered with an error' + (f.code ? ' (' + f.code + ')' : '') + (f.info ? ': ' + f.info : '.');
+ default:
+ return 'Could not find api.php at any of the usual locations. The address may be wrong, or the API may be disabled or moved.';
+ }
+}
+
+async function connect(input, fetchFn) {
+ const u = normalizeInput(input);
+ let html = '';
+ let pageErr = null;
+ try {
+ const r = await fetchText(fetchFn, u.toString(), {});
+ html = r.body;
+ } catch (e) { pageErr = e; }
+
+ const rank = { private: 5, blocked: 4, apierror: 3, unreachable: 2, notapi: 1, notfound: 1 };
+ let worst = null;
+ const note = (f) => { if (!worst || (rank[f.kind] || 0) > (rank[worst.kind] || 0)) worst = f; };
+
+ for (const api of candidateApis(u, html)) {
+ const p = await probe(fetchFn, api);
+ if (!p.ok) { note(p); continue; }
+ const t = await parseWiki(fetchFn, api, "''test''", 'Test');
+ if (t.ok) return { ok: true, api, siteName: p.name || u.host, generator: p.generator || '' };
+ note(t);
+ }
+ if (!worst) worst = { kind: 'notfound' };
+ if (pageErr && (worst.kind === 'notfound' || worst.kind === 'notapi')) {
+ worst = { kind: 'unreachable', message: pageErr.message };
+ }
+ return { ok: false, kind: worst.kind, detail: explain(worst, u) };
+}
+
+function asString(x) {
+ if (typeof x === 'string') return x;
+ if (x && typeof x['*'] === 'string') return x['*'];
+ return '';
+}
+
+function escHtml(s) {
+ return String(s).replace(/&/g, '&').replace(//g, '>');
+}
+
+function buildLiveDoc(json, api, title) {
+ const p = json.parse;
+ const base = new URL(api).origin + '/';
+ let head = asString(p.headhtml);
+ if (!/]/i.test(head)) {
+ head = '';
+ }
+ head = head.replace(/