Upload files to "/"

This commit is contained in:
2026-11-11 00:08:35 +00:00
parent 44fed4420a
commit fd4cc1da87
5 changed files with 460 additions and 0 deletions
+60
View File
@@ -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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
// Full page for the PDF of the wikitext source.
function markupPage(title, text) {
return '<!DOCTYPE html><html><head><meta charset="utf-8"><title>' + esc(title) + '</title><style>' +
'body{margin:0;font:11px/1.45 Consolas,"Cascadia Mono","Courier New",monospace;color:#111}' +
'h1{font:bold 15px/1.3 "Segoe UI",Arial,sans-serif;margin:0 0 10px}' +
'pre{margin:0;white-space:pre-wrap;word-break:break-word;tab-size:4}' +
'</style></head><body><h1>' + esc(title) + '</h1><pre>' + esc(text.replace(/\r\n?/g, '\n')) + '</pre></body></html>';
}
// 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 = '&nbsp;'.repeat(lead) + esc(l.slice(lead)).replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
return '<p style="font-family:Consolas;font-size:10pt;margin:0">' + (body || '&nbsp;') + '</p>';
});
return '<h1>' + esc(title) + '</h1>' + lines.join('');
}
function wrapDoc(title, body) {
return '<!DOCTYPE html><html><head><meta charset="utf-8"><title>' + esc(title) + '</title></head><body>' + body + '</body></html>';
}
// 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&nbsp;$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(/<img\b[^>]*>/gi, '')), null, opts);
}
return Buffer.isBuffer(out) ? out : Buffer.from(await out.arrayBuffer ? await out.arrayBuffer() : out);
}
module.exports = { markupPage, markupBody, toDocx, fixSpaces, PAPER };
+24
View File
@@ -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)
});
+80
View File
@@ -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(/<!--[\s\S]*?(-->|$)/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 };
+198
View File
@@ -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(/<link[^>]+rel=["']EditURI["'][^>]*href=["']([^"']+)["']/i) ||
html.match(/<link[^>]+href=["']([^"']+)["'][^>]*rel=["']EditURI["']/i);
if (m) add(m[1].replace(/&amp;/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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function buildLiveDoc(json, api, title) {
const p = json.parse;
const base = new URL(api).origin + '/';
let head = asString(p.headhtml);
if (!/<head[\s>]/i.test(head)) {
head = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>';
}
head = head.replace(/<script[\s\S]*?<\/script>/gi, '');
head = head.replace(/<head[^>]*>/i, (m) => m + '<base href="' + base + '" target="_blank">');
const titleHtml = asString(p.displaytitle) || escHtml(title || '');
const body =
'<div class="mw-body" id="content" role="main" style="margin:0;padding:16px 24px;border:0;max-width:none;min-height:0;background:transparent">' +
'<h1 id="firstHeading" class="firstHeading mw-first-heading">' + titleHtml + '</h1>' +
'<div id="bodyContent" class="vector-body mw-body-content">' +
'<div id="mw-content-text">' + asString(p.text) + '</div>' +
asString(p.categorieshtml) +
'</div></div></body></html>';
return head + body;
}
module.exports = { connect, parseWiki, buildLiveDoc, explain, normalizeInput, candidateApis };
+98
View File
@@ -0,0 +1,98 @@
// Offline thesaurus built on the Princeton WordNet 3.1 database files in ./wordnet.
// WordNet is free to use under its own license (see wordnet/LICENSE and the file headers).
'use strict';
const fs = require('fs');
const path = require('path');
const DIR = path.join(__dirname, 'wordnet');
const POS = { noun: 'n', verb: 'v', adj: 'a', adv: 'r' };
const POS_NAME = { noun: 'Noun', verb: 'Verb', adj: 'Adjective', adv: 'Adverb' };
const index = {}; // pos -> Map(lemma -> [offsets])
const data = {}; // pos -> Buffer
function load(pos) {
if (index[pos]) return;
const m = new Map();
const txt = fs.readFileSync(path.join(DIR, 'index.' + pos), 'latin1');
txt.split('\n').forEach((line) => {
if (!line || line.charAt(0) === ' ') return;
const f = line.split(' ');
const ptrCnt = parseInt(f[3], 10);
const senseCnt = parseInt(f[4 + ptrCnt], 10);
const offs = f.slice(6 + ptrCnt, 6 + ptrCnt + senseCnt);
m.set(f[0], offs);
});
index[pos] = m;
data[pos] = fs.readFileSync(path.join(DIR, 'data.' + pos));
}
function synset(pos, off) {
const buf = data[pos];
const start = parseInt(off, 10);
let end = buf.indexOf(10, start);
if (end < 0) end = buf.length;
const line = buf.toString('latin1', start, end);
const bar = line.indexOf('|');
const head = line.slice(0, bar).split(' ');
const gloss = line.slice(bar + 1).trim();
const wc = parseInt(head[3], 16);
const words = [];
for (let i = 0; i < wc; i++) {
words.push(head[4 + i * 2].replace(/\(.*\)$/, '').replace(/_/g, ' '));
}
return { words, gloss: gloss.split(';')[0].replace(/^\s+|\s+$/g, '') };
}
const IRREGULAR = {
was: 'be', were: 'be', is: 'be', are: 'be', been: 'be', am: 'be', had: 'have', has: 'have', did: 'do', does: 'do', done: 'do',
went: 'go', gone: 'go', goes: 'go', said: 'say', made: 'make', took: 'take', taken: 'take', came: 'come', saw: 'see', seen: 'see',
got: 'get', gave: 'give', given: 'give', knew: 'know', known: 'know', thought: 'think', told: 'tell', found: 'find', began: 'begin',
begun: 'begin', ran: 'run', wrote: 'write', written: 'write', men: 'man', women: 'woman', children: 'child', people: 'person',
feet: 'foot', teeth: 'tooth', mice: 'mouse', better: 'good', best: 'good', worse: 'bad', worst: 'bad', bigger: 'big', biggest: 'big'
};
function candidates(w) {
const out = [w];
if (IRREGULAR[w]) out.push(IRREGULAR[w]);
const add = (x) => { if (x && x.length > 1 && out.indexOf(x) < 0) out.push(x); };
if (/ies$/.test(w)) { add(w.slice(0, -3) + 'y'); }
if (/(s|x|z|ch|sh)es$/.test(w)) add(w.slice(0, -2));
if (/s$/.test(w) && !/ss$/.test(w)) add(w.slice(0, -1));
if (/ied$/.test(w)) add(w.slice(0, -3) + 'y');
if (/ed$/.test(w)) { add(w.slice(0, -2)); add(w.slice(0, -1)); if (/(.)\1ed$/.test(w)) add(w.slice(0, -3)); }
if (/ing$/.test(w)) { add(w.slice(0, -3)); add(w.slice(0, -3) + 'e'); if (/(.)\1ing$/.test(w)) add(w.slice(0, -4)); }
if (/ier$|iest$/.test(w)) add(w.replace(/ier$|iest$/, 'y'));
if (/er$/.test(w)) { add(w.slice(0, -2)); add(w.slice(0, -1)); if (/(.)\1er$/.test(w)) add(w.slice(0, -3)); }
if (/est$/.test(w)) { add(w.slice(0, -3)); add(w.slice(0, -2)); }
if (/ly$/.test(w)) add(w.slice(0, -2));
return out;
}
// Returns [{pos: 'Noun', senses: [{gloss, words: [..]}]}] for a word or phrase, with the word itself left out.
function lookup(raw) {
const word = String(raw || '').trim().toLowerCase().replace(/\s+/g, '_');
if (!word) return { word: '', lemma: '', groups: [] };
let lemma = word;
let groups = [];
const tried = candidates(word);
for (const cand of tried) {
const g = [];
Object.keys(POS).forEach((pos) => {
load(pos);
const offs = index[pos].get(cand);
if (!offs) return;
const senses = [];
offs.forEach((o) => {
const s = synset(pos, o);
const words = s.words.filter((x) => x.toLowerCase() !== cand.replace(/_/g, ' '));
if (words.length) senses.push({ gloss: s.gloss, words });
});
if (senses.length) g.push({ pos: POS_NAME[pos], senses });
});
if (g.length) { groups = g; lemma = cand; break; }
}
return { word: String(raw).trim(), lemma: lemma.replace(/_/g, ' '), groups };
}
module.exports = { lookup };