// ==UserScript== // @name Scribe // @namespace https://github.com/majkinetor/musicbrainz-userscripts // @version 2026.11.27 // @description Edit MusicBrainz in your real editor (VS Code, Vim, Notepad…) via the bundled `scribe` localhost helper. Two ways, chosen by trigger: Ctrl+Alt+E edits the FOCUSED text field; on a release Edit page, the corner button (or Ctrl+Alt+R) edits the WHOLE release as one Markdown document and applies your saves back. Cross-browser via GM_xmlhttpRequest. // @author majkinetor // @icon data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4Ij48cGF0aCBkPSJNNDYgMjQgTDI2IDI0IEwyNiAxMDQgTDQ2IDEwNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMmY2ZjU0IiBzdHJva2Utd2lkdGg9IjkiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjxwYXRoIGQ9Ik04MiAyNCBMMTAyIDI0IEwxMDIgMTA0IEw4MiAxMDQiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzJmNmY1NCIgc3Ryb2tlLXdpZHRoPSI5IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNNjQgNDAgTDUxIDY2IEw2NCA5NCBMNzcgNjYgWiIgZmlsbD0iIzJlOWU1YiIgc3Ryb2tlPSIjMmY2ZjU0IiBzdHJva2Utd2lkdGg9IjQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48bGluZSB4MT0iNjQiIHkxPSI3NCIgeDI9IjY0IiB5Mj0iOTIiIHN0cm9rZT0iI2ZmZmZmZiIgc3Ryb2tlLXdpZHRoPSIzLjUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIvPjwvc3ZnPg== // @match *://*.musicbrainz.org/* // @exclude *://*.musicbrainz.org/release/*/edit-relationships* // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant unsafeWindow // @connect 127.0.0.1 // @connect localhost // @connect musicbrainz.org // @run-at document-end // @noframes // ==/UserScript== /* eslint-disable no-undef */ (function () { 'use strict'; // the shared MusicBrainz request gate (#633), here for its browser-check pass (#733) // — generated by dev/net/sync-gate.mjs from dev/net/mb-gate.mjs — DO NOT EDIT const MBN_GAP = 125; const MBN_JITTER = 500; const MBN_BURST = 4; const MBN_KEY = "mbu:mb-gate"; const MBN_VERSION = 1; const MBN_LOCK = "mbu-mb-gate"; const MBN_LOCK_HOLD = 30; const MBN_MAX_HOLD = 60000; const MBN_MAX_LEAD = 10000; const MBN_TRACE_MAX = 400; const MBN_MERGE_WAIT = 100; const MBN_CACHE_TTL = 300000; const MBN_CACHE_MAX = 150; const MBN_INC_ALONE = new Set(["recordings","recording-level-rels","work-level-rels","release-group-level-rels","discids","isrcs"]); function mbnGated(url) { const s = String(url || ''); return /^\/ws\/2\//.test(s) || /^(https?:)?\/\/([a-z0-9-]+\.)*musicbrainz\.org\/ws\/2\//i.test(s); } async function mbnState(fn) { const rw = () => { let s = null, stored = true; try { s = JSON.parse(localStorage.getItem(MBN_KEY) || 'null'); } catch (e) { stored = false; } const g = globalThis.__mbnGate || (globalThis.__mbnGate = { tat: 0, cool: 0, hot: 0 }); if (!stored) s = g; // no storage: this page's copy only else if (!s || typeof s !== 'object') s = { tat: 0, cool: 0, hot: 0 }; // none yet (or cleared): a fresh schedule if (s.version != null && s.version !== MBN_VERSION) throw new Error('Unsupported MusicBrainz gate version: ' + s.version); s.version = MBN_VERSION; // #938: no writer sets a hold past MBN_MAX_HOLD or a lead past MBN_MAX_LEAD, so a value // beyond them is broken (a bug, a clock that jumped): bring it back, for every tab after us const now = Date.now(); if ((s.cool || 0) > now + MBN_MAX_HOLD) s.cool = now + MBN_MAX_HOLD; if ((s.scool || 0) > now + MBN_MAX_HOLD) s.scool = now + MBN_MAX_HOLD; if ((s.leadUntil || 0) > now + MBN_MAX_LEAD) s.leadUntil = now + MBN_MAX_LEAD; // nor a queue longer than a minute: slots that waits left behind (a closed tab) are dropped if ((s.tat || 0) > Math.max(now, s.cool || 0) + 60 * MBN_GAP) s.tat = Math.max(now, s.cool || 0) + 60 * MBN_GAP; if ((s.itat || 0) > Math.max(now, s.cool || 0) + 60 * MBN_GAP) s.itat = Math.max(now, s.cool || 0) + 60 * MBN_GAP; for (const k of ['last', 'ilast']) if ((s[k] || 0) > Math.max(now, s.cool || 0) + 60 * MBN_GAP) s[k] = Math.max(now, s.cool || 0) + 59 * MBN_GAP; const out = fn(s); Object.assign(g, s); try { localStorage.setItem(MBN_KEY, JSON.stringify({ ...s, tat: s.tat || 0, cool: s.cool || 0, hot: s.hot || 0, lead: s.lead || '', leadUntil: s.leadUntil || 0 })); } catch (e) {} return out; }; // The lock is held for rw()'s synchronous moment and MBN_LOCK_HOLD after, so a wait of seconds // means it is stuck (a frozen or sandboxed holder): give up on it and go unlocked rather than // hang every request behind it. // The hold: Chromium hands a localStorage write to another tab's process a moment later, so a // tab taking the lock right after us could read the schedule before our booking and book the // same slot (two tabs at once sent four in a burst of three). Our caller has its answer at // once; only the next holder waits the hold out. let expired = false, settled = false; try { if (typeof navigator !== 'undefined' && navigator.locks && navigator.locks.request) { const ctrl = typeof AbortController === 'function' ? new AbortController() : null; const timeout = mbnSleep(3000, () => settled).then(() => { if (settled) return new Promise(() => {}); // the lock answered first expired = true; try { if (ctrl) ctrl.abort(); } catch (e) {} throw new Error('MusicBrainz gate lock timed out'); }); // Some userscript bridges never settle the request on abort. The timer // must release our wait itself; a late grant must not book twice. let done; const answered = new Promise((res, rej) => { done = { res, rej }; }); navigator.locks.request(MBN_LOCK, ctrl ? { signal: ctrl.signal } : {}, async () => { if (expired) return; try { done.res(rw()); } catch (e) { done.rej(e); return; } await mbnSleep(MBN_LOCK_HOLD); }).catch(e => done.rej(e)); return await Promise.race([answered, timeout]); } } catch (e) { /* no Web Locks here (an insecure or sandboxed context), or stuck: unlocked, like a lone script */ } finally { settled = true; } return rw(); } function mbnSleep(ms, cancelled) { const end = Date.now() + Math.max(0, +ms || 0); const w = globalThis.__mbnWake1 || (globalThis.__mbnWake1 = { all: new Set(), due: new Map(), raf: 0, mo: null, worker: null, stall: null }); const note = () => { // a timer overdue by 2s: note it once a minute, for the log const now = Date.now(); if (w.stall && now - w.stall.at < 60000) return; for (const d of w.due.values()) { if (now - d <= 2000) continue; let state = '', hidden = false; try { state = document.readyState; hidden = !!document.hidden; } catch (e) {} w.stall = { ms: now - d, at: now, state, hidden, told: false }; return; } }; const wake = () => { note(); for (const f of Array.from(w.all)) f(); }; return new Promise(resolve => { let done = false; const tok = {}; const me = () => { if (done) return; let stop = false; try { stop = !!(cancelled && cancelled()); } catch (e) {} const now = Date.now(); if (!stop && now < end) return; done = true; w.due.delete(tok); // a sleep another waker ended is not a late timer: its own timer may still be throttled minutes behind w.all.delete(me); if (!w.all.size) { // the last sleeper: the wakers rest try { if (w.raf) cancelAnimationFrame(w.raf); } catch (e) {} w.raf = 0; try { if (w.mo) w.mo.disconnect(); } catch (e) {} w.mo = null; try { if (w.worker && w.ticking) w.worker.postMessage(0); } catch (e) {} w.ticking = false; } resolve(Math.max(0, now - end)); }; // the plain timer, left to fire after another waker ended the sleep: when it fires late, it says so // with a cancel check it runs in 250ms slices, so a cancel lands where nothing else wakes it (no page) const tick = () => { if (Date.now() - (w.due.get(tok) || Infinity) > 2000) note(); w.due.delete(tok); me(); if (!done) arm(); }; const arm = () => { const d = Math.max(1, Math.min(cancelled ? 250 : 2147483647, end - Date.now())); if (w.due.size < 500) w.due.set(tok, Date.now() + d); setTimeout(tick, d); }; me(); if (done) return; w.all.add(me); arm(); try { // a worker's timers run apart from the page's; a page that forbids blob workers falls back to frames if (w.worker === null && typeof Worker === 'function' && typeof Blob === 'function' && typeof URL !== 'undefined' && URL.createObjectURL) { w.worker = false; const wk = new Worker(URL.createObjectURL(new Blob(['let t=0;onmessage=e=>{clearInterval(t);t=0;if(e.data>0)t=setInterval(()=>postMessage(1),e.data)}'], { type: 'text/javascript' }))); wk.onmessage = () => { const x = globalThis.__mbnWake1; if (x) { x.wake && x.wake(); } }; wk.onerror = () => { w.worker = false; }; w.worker = wk; } w.wake = wake; if (w.worker && !w.ticking) { w.ticking = true; w.worker.postMessage(100); } } catch (e) { w.worker = false; } // no DOM watch: on a busy page (Mission Control's) every change ran the wake, and the lag was felt try { // frames only without a worker: a frame loop runs the wake 60 times a second if (!w.worker && !w.raf && typeof requestAnimationFrame === 'function') { const frame = () => { w.raf = 0; wake(); if (w.all.size && !w.worker) w.raf = requestAnimationFrame(frame); }; w.raf = requestAnimationFrame(frame); } } catch (e) {} }); } function mbnRid() { return Date.now().toString(36).slice(-4) + Math.random().toString(36).slice(2, 6); } function mbnTabId() { return Date.now().toString(36).slice(-4) + Math.random().toString(36).slice(2, 5); } function mbnTabCheck(g) { try { if (window.top !== window || typeof BroadcastChannel === 'undefined') return; const root = document.documentElement, at = 'data-mbn-doc'; const doc = root.getAttribute(at) || (root.setAttribute(at, mbnTabId()), root.getAttribute(at)); const asked = g.tab, bc = new BroadcastChannel(MBN_KEY + '-tab'); bc.onmessage = m => { const d = m.data || {}; if (d.doc === doc) return; let now = ''; try { now = sessionStorage.getItem(MBN_KEY + '-tab') || ''; } catch (e) {} if (d.q) { if (d.tab === (now || g.tab)) bc.postMessage({ tab: d.tab, doc }); return; } // the id this page has now if (d.tab !== asked || g.tab !== asked) return; // not our question, or this copy has already moved on if (!now || now === asked) { now = mbnTabId(); try { sessionStorage.setItem(MBN_KEY + '-tab', now); } catch (e) {} } g.tab = now; // another copy in this page may have renamed it already: then take its new id }; bc.postMessage({ q: 1, tab: asked, doc }); } catch (e) { /* no channel: the id stays shared */ } } function mbnTrace(ev) { try { const g = globalThis.__mbnTrace || (globalThis.__mbnTrace = { tab: '', swept: 0 }); if (!g.tab) { try { g.tab = sessionStorage.getItem(MBN_KEY + '-tab') || ''; } catch (e) {} if (!g.tab) { g.tab = mbnTabId(); try { sessionStorage.setItem(MBN_KEY + '-tab', g.tab); } catch (e) {} } mbnTabCheck(g); } if (!g.buf) g.buf = []; if (!g.flush) { g.flush = () => { try { clearTimeout(g.timer); g.timer = 0; if (!g.buf.length) return; const add = g.buf; g.buf = []; // the tab's id as it is now: a renamed duplicate (mbnTabCheck) renames every copy of the gate in it, // and the frames it holds, which share its sessionStorage try { g.tab = sessionStorage.getItem(MBN_KEY + '-tab') || g.tab; } catch (e) {} const pre = MBN_KEY + '-trace:', key = pre + g.tab, now = Date.now(); let list = []; try { list = JSON.parse(localStorage.getItem(key) || '[]'); } catch (e) {} if (!Array.isArray(list)) list = []; list = list.concat(add); if (list.length > MBN_TRACE_MAX) list = list.slice(-MBN_TRACE_MAX); localStorage.setItem(key, JSON.stringify(list)); // the tab's page title, for the network log's tooltip; a worker frame keeps its tab's try { if (window === window.top && document.title) localStorage.setItem(MBN_KEY + '-title:' + g.tab, String(document.title).slice(0, 200)); } catch (e) {} if (now - g.swept > 60000) { // once a minute: drop the traces of tabs gone quiet for 10 minutes g.swept = now; // one pass over the names: in Firefox each localStorage.key(i) walks the store from its start for (const k of Object.keys(localStorage)) { if (k.indexOf(pre) !== 0 || k === key) continue; let last = 0; try { const l = JSON.parse(localStorage.getItem(k) || '[]'); last = (l[l.length - 1] || {}).t || 0; } catch (e) {} if (now - last > 600000) { localStorage.removeItem(k); localStorage.removeItem(MBN_KEY + '-title:' + k.slice(pre.length)); } } } } catch (e) { /* no storage: no trace */ } }; try { // leaving the page, or hiding it (a phone may never come back): write what waits // the top page notes that it left, so the network log ends its open requests as "page left" // and not as "no answer"; a worker frame closes while its page stays, so it notes nothing addEventListener('pagehide', () => { try { if (window === window.top) g.buf.push({ t: Date.now(), s: '', e: 'left' }); } catch (e) {} g.flush(); }); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') g.flush(); }); } catch (e) {} } // the name is read per call, never kept in the shared object: in String Theory's bundle every // member runs its own copy of the gate with its own GM_info, but globalThis is the bundle's one let script = ''; try { script = String(GM_info.script.name || ''); } catch (e) {} const row = Object.assign({ t: Date.now(), s: script }, ev); if (row.l) row.l = mbnHideUrl(row.l); if (row.u) row.u = mbnHideUrl(row.u); g.buf.push(row); if (g.buf.length > MBN_TRACE_MAX) g.buf = g.buf.slice(-MBN_TRACE_MAX); if (!g.timer) g.timer = setTimeout(g.flush, 1000); } catch (e) { /* no storage: no trace */ } } function mbnHideUrl(s) { return String(s).replace(/([?&;])([^=&#\s]*)=([^&#\s]*)/g, (m, sep, k, v) => { let n = k; try { n = decodeURIComponent(k.replace(/\+/g, ' ')); } catch (e) {} const secret = /(^|[_.-])(token|secret|pass|passwd|password|auth|session|sid|csrf|code|key|apikey|sig|signature)$/i.test(n) || /[a-z](Token|Secret|Key|Password)$/.test(n); return v && secret ? sep + k + '=•••' : m; }); } async function mbnSlot(o) { o = o || {}; const t0 = Date.now(), background = o.background !== false; const tr = (e, x) => mbnTrace(Object.assign({ e, r: o.reason || undefined, en: o.entity || undefined, l: o.label || '', b: background ? 1 : 0, id: o.id || undefined, m: o.m, u: o.u }, x)); // someone else's lead: a background request books its slot only once it ends or lapses // #938: a cap counted from each new `now` moves with it and never caps; count it from when // this wait first saw the value, so a broken one holds at most the longest real one const seen = (v, cap) => { if (v !== seen[cap + 'v']) { seen[cap + 'v'] = v; seen[cap + 't'] = Date.now(); } return Math.min(v, seen[cap + 't'] + cap); }; for (let told = false; background;) { let s = null; try { s = JSON.parse(localStorage.getItem(MBN_KEY) || 'null'); } catch (e) { s = globalThis.__mbnGate; } const left = s && s.lead && s.lead !== o.lead ? seen(s.leadUntil || 0, MBN_MAX_LEAD) - Date.now() : 0; if (left <= 0) break; if (o.cancelled && o.cancelled()) { tr('cancel', { w: Date.now() - t0 }); return { ok: false, waited: Date.now() - t0 }; } if (!told) tr('lead', { w: left, by: String(s.lead).slice(0, 12) }); if (!told && o.log) { told = true; o.log('info', 'MusicBrainz gate: ' + (o.label || 'request') + ' waits for a page being drawn'); } told = true; await mbnSleep(Math.min(left, 250), o.cancelled); } // a hidden tab's background request books only once the background queue is free: queued // ahead, it would hold up the visible tab's requests booked after it. It waits at most // MBN_MAX_LEAD for each queue end it sees, so a broken value doesn't hold it for good // a retry is not new work: it keeps its place at the head (below), hidden tab or not for (let told = false; background && !o.retry && typeof document !== 'undefined' && document.hidden;) { let s = null; try { s = JSON.parse(localStorage.getItem(MBN_KEY) || 'null'); } catch (e) { s = globalThis.__mbnGate; } // #log: the visible tab kept booking, so the queue end kept moving and a hidden wait ran 46s; // it waits MBN_MAX_LEAD in all, then books like any other const left = s && s.tat ? Math.min(seen(s.tat, MBN_MAX_LEAD), t0 + MBN_MAX_LEAD) - Date.now() : 0; if (left <= 0) break; if (o.cancelled && o.cancelled()) { tr('cancel', { w: Date.now() - t0 }); return { ok: false, waited: Date.now() - t0 }; } // #1095: the queue end seen now is not the wait: the visible tab keeps booking, so say the cap too if (!told) tr('hidden', { w: left, cap: t0 + MBN_MAX_LEAD - Date.now() }); told = true; await mbnSleep(Math.min(left, 250), o.cancelled); } // a hold that appears while we queue ends for every waiter at once: each waiter then books // again, so they leave one a second instead of all together into a fresh 503 let booked = null, rebooked = false; const book = head => mbnState(s => { // a search also waits out the search-shed hold: booked with it, the log names the real wait const now = Date.now(), cool = Math.max(s.cool || 0, o.search ? s.scool || 0 : 0), tat = s.tat || 0; // an interactive request (the page's own) never queues behind the background budget: it // has its own line (itat), a burst then one a second, so a page's handful of lookups don't // all leave at once into a 503 (and while MusicBrainz is throttling, no burst at all) let at; if (!background) { const itat = s.itat || 0, hot = s.hot && now <= cool + 30000; // the background lane already spends the burst while its queue reaches past now: the two // lanes bursting together sent five or six in one moment, and they all got a 503. Every booking // moves tat, the page's own too, so tat only past itat holds background bookings: tat > now // alone took the burst from the page's second request on, even with no background work at all const busy = tat > Math.max(now, itat); at = Math.max(now, rebooked || busy ? itat : itat - (hot ? 0 : (MBN_BURST - 1) * MBN_GAP), cool); // log: the burst reaches back from itat, so once a 200 cooled `hot` while a queue still // waited out a hold, a new request took the slot a queued one held and both got a 503; // the burst is for an idle line, never ahead of (or on) a slot still to come if ((s.ilast || 0) > now) at = Math.max(at, s.ilast + MBN_GAP); s.itat = Math.max(itat, at) + MBN_GAP; s.ilast = Math.max(s.ilast || 0, at); } else if (o.retry || head) { // log: a search's retry after its 503 booked at the end of a 13-request queue, three times // 8-12 s, and gave up while requests booked after it got through. A retry leaves first once // the hold ends (retries one a second among themselves, `rhead`), and every background slot // still to come moves one second later to make room (`bslip`, which each waiter adds to its own). // log: a search waiting out a search-shed hold is at the head too: it booked again at the end // each time, behind the lookups that went on meanwhile, ten holds in a row, 36 s for one search at = Math.max(now, cool, s.rhead || 0); s.rhead = at + MBN_GAP; if (tat > at) { s.bslip = (s.bslip || 0) + MBN_GAP; s.tat = tat + MBN_GAP; if ((s.last || 0) > now) s.last += MBN_GAP; s.last = Math.max(s.last || 0, at); if (at > now) tr('book', { w: at - now, why: cool > now && cool >= at ? 'hold' : 'pace', re: 1, head: 1 }); return { at, why: cool > now && cool >= at ? 'MusicBrainz asked everyone to wait' : 'pacing, eight requests a second', slip: s.slip || 0, bslip: s.bslip }; } s.last = Math.max(s.last || 0, at); } else { // #1096: while MusicBrainz throttles, no burst: the queue a hold built up leaves one // a second when it ends, not all in one millisecond into the next 503 const hot = s.hot && now <= cool + 30000; at = Math.max(rebooked || hot ? Math.max(now, tat) : Math.max(now, tat - (MBN_BURST - 1) * MBN_GAP), cool); if ((s.last || 0) > now) at = Math.max(at, s.last + MBN_GAP); // as above s.last = Math.max(s.last || 0, at); } s.tat = Math.max(tat, at) + MBN_GAP; const held = cool > now && cool >= at; const why = held ? 'MusicBrainz asked everyone to wait' : 'pacing, eight requests a second'; // #1112: no queue length here: the slots ahead were 125 ms each plus every hold, so "13 queued" // meant 1.6 s, not 13 requests. The network log counts the requests waiting from the events if (at > now) tr('book', { w: at - now, why: held ? 'hold' : 'pace', re: rebooked ? 1 : 0 }); return { at, why, slip: s.slip || 0, bslip: s.bslip || 0 }; }); booked = await book(); // a cancelled wait hands its slot back when it is still the last one booked, so a page that // drops a queue of lookups (a Stop, a new page) does not leave every later request behind it const giveBack = force => mbnState(s => { if (!force && booked.at <= Date.now()) return; if (s.tat === booked.at + MBN_GAP) s.tat -= MBN_GAP; if (!background && s.itat === booked.at + MBN_GAP) s.itat -= MBN_GAP; if (background ? s.last === booked.at : s.ilast === booked.at) s[background ? 'last' : 'ilast'] = booked.at - MBN_GAP; }); // #999: the wait logs again whenever its end moves later (a hold another tab or script set // while we queued) and every 10s it goes on, so a long wait is never silent let toldUntil = 0, toldAt = 0; for (;;) { if (o.cancelled && o.cancelled()) { await giveBack(); tr('cancel', { w: Date.now() - t0 }); return { ok: false, waited: Date.now() - t0 }; } let cool = 0, scool = 0, slip = 0, bslip = 0; try { const g = JSON.parse(localStorage.getItem(MBN_KEY) || 'null') || {}; cool = g.cool || 0; scool = g.scool || 0; slip = g.slip || 0; bslip = g.bslip || 0; } catch (e) { const g = globalThis.__mbnGate || {}; cool = g.cool || 0; scool = g.scool || 0; slip = g.slip || 0; bslip = g.bslip || 0; } // a hold set since we booked moved our slot later with the rest of the queue // #1112: and the network log says so: a request booked to wait 1.3 s started after 5.8 s, with no event between if (slip > booked.slip) { tr('moved', { w: slip - booked.slip, to: Math.max(0, booked.at + slip - booked.slip - Date.now()) }); booked.at += slip - booked.slip; booked.slip = slip; booked.why = 'MusicBrainz asked everyone to wait'; } // a retry took the head of the background queue: our slot moved a second later with the rest if (background && bslip > booked.bslip) { booked.at += bslip - booked.bslip; booked.bslip = bslip; } // a search also waits out the hold MusicBrainz set for searches const shed = !!o.search && scool > cool; if (o.search) cool = Math.max(cool, scool); const now = Date.now(); cool = seen(cool, MBN_MAX_HOLD); // a hold is never longer than the longest one the gate sets const until = Math.max(booked.at, cool), left = until - now; // a hold that appeared while we queued if (left <= 0) { // every hold that ends past the slot books again, a second or third one included: // booking only once let the waiters of a later hold all leave in the same millisecond if (cool > booked.at) { rebooked = true; booked = await book(shed && background); continue; } break; } if (o.log && until - t0 > 1000 && (!toldAt || until > toldUntil + 1000 || now - toldAt >= 10000)) { const why = cool > booked.at ? (shed ? 'MusicBrainz asked searches to wait' : 'MusicBrainz asked everyone to wait') : booked.why; o.log('info', 'MusicBrainz gate: ' + (o.label || 'request') + (toldAt ? ' still waits, ' + Math.round(left / 100) / 10 + 's to go' : ' waits ' + Math.round((until - t0) / 100) / 10 + 's') + ' (' + why + ')'); toldUntil = until; toldAt = now; } await mbnSleep(Math.min(left, 250), o.cancelled); // in slices, so a cancel lands promptly const st = globalThis.__mbnWake1 && globalThis.__mbnWake1.stall; if (st && !st.told && o.log) { st.told = true; o.log('info', 'MusicBrainz gate: this page\'s timer fired ' + Math.round(st.ms / 100) / 10 + 's late (page ' + (st.state || '?') + (st.hidden ? ', hidden' : '') + '); waits wake on page activity too'); } } // log: a request that waited out a lead or a hold sent anyway, and only after its 503 found the // answer a twin had brought back meanwhile; it looks once more just before it leaves const twin = o.twin && Date.now() - t0 >= MBN_MERGE_WAIT ? await o.twin() : null; // one that didn't wait looked a moment ago if (twin) { await giveBack(true); return { ok: false, waited: Date.now() - t0, twin }; } tr('start', { w: Date.now() - t0, bs: o.bs, bt: o.bt }); return { ok: true, waited: Date.now() - t0 }; } async function mbnLead(token, ms) { return mbnState(s => { if (ms > 0) { // a lead that lapsed unrenewed ends in the log too, so every lead+ has its lead- const now = Date.now(), lapsed = s.lead && (s.leadUntil || 0) < now; if (lapsed) mbnTrace({ e: 'lead-', by: String(s.lead).slice(0, 12), why: 'lapsed', d: s.leadAt ? s.leadUntil - s.leadAt : undefined }); if (s.lead !== token || lapsed) { mbnTrace({ e: 'lead+', by: String(token).slice(0, 12), w: Math.min(ms, MBN_MAX_LEAD) }); s.leadAt = now; } s.lead = token; s.leadUntil = now + Math.min(ms, MBN_MAX_LEAD); } else if (s.lead === token) { const now = Date.now(), late = (s.leadUntil || 0) < now, d = s.leadAt ? (late ? s.leadUntil : now) - s.leadAt : undefined; s.lead = ''; s.leadUntil = 0; s.leadAt = 0; mbnTrace({ e: 'lead-', by: String(token).slice(0, 12), why: late ? 'lapsed' : undefined, d }); } }); } async function mbnAnswer(status, header, o) { o = o || {}; // for the Gate log: MusicBrainz's own rate-limit headers, which say whose budget ran out const rl = {}; for (const [k, n] of [['lim', 'X-RateLimit-Limit'], ['rem', 'X-RateLimit-Remaining'], ['rst', 'X-RateLimit-Reset'], ['who', 'X-RateLimit-Who']]) { try { const v = header ? header(n) : null; if (v != null && v !== '') rl[k] = String(v).slice(0, 40); } catch (e) {} } rl.rs = mbnLength(header); const tr = (x, s) => mbnTrace(Object.assign({ e: 'answer', st: status, r: o.reason || undefined, en: o.entity || undefined, l: o.label || '', b: o.background === false ? 0 : 1, id: o.id || undefined, m: o.m, u: o.u, hot: s ? s.hot || 0 : undefined }, rl, x)); if (status === 429 || status === 503) { const raw = header ? header('Retry-After') : null; const secs = Number(raw), date = raw ? Date.parse(raw) : NaN; const ra = Number.isFinite(secs) ? secs * 1000 : Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0; // MusicBrainz shed searches, not this client: only searches wait, and the shared hot is untouched if (status === 503 && /^search-shed$/i.test(String(rl.who || '').trim())) { const hold = await mbnState(s => { const now = Date.now(); if (now > (s.scool || 0) + 30000) s.shot = 0; if (now >= (s.scool || 0)) s.shot = Math.min((s.shot || 0) + 1, 6); // #1095: a shed clears within a second or so; growing holds only stalled the searches const ms = Math.min(Math.max(1000, ra) + Math.round(Math.random() * MBN_JITTER), MBN_MAX_HOLD); s.scool = Math.max(s.scool || 0, now + ms); tr({ ra: raw == null ? undefined : String(raw).slice(0, 40), shold: s.scool - now, shot: s.shot }, s); return s.scool - now; }); if (o.log) o.log('warn', 'MusicBrainz gate: HTTP 503 (search-shed) — searches hold ' + Math.round(hold / 100) / 10 + 's'); return { throttled: true, hold, shed: true }; } const hold = await mbnState(s => { const now = Date.now(); // One throttle, one step: the requests already in flight when it began all answer // 503 too, and each must not stretch the hold again. A throttle long gone doesn't // count at all: `hot` is shared and persists, and would otherwise slow every later // page for good. const load = /^global$/i.test(String(rl.who || '').trim()); if (now > (s.cool || 0) + 30000) s.hot = 0; // #1095: nor does it count as a throttle of ours: a run of them (a 130s preflight) raised `hot` // to 6, which takes the burst away, and the queue crawled at one a second behind each hold if (!load && now >= (s.cool || 0)) s.hot = Math.min((s.hot || 0) + 1, 6); // the hold grows with each throttle in a row, a Retry-After included, so a long busy // spell gets fewer and fewer requests from us // #1095: a 503 that says MusicBrainz as a whole is out of room (X-RateLimit-Who: global) is // not about our pace: it came to a single request after a quiet spell, and the next one went // through. It holds a flat second (or its Retry-After); growing holds stalled every tab for nothing // #1095: a Retry-After is MusicBrainz's own answer for how long: "Retry-After: 5" held 10s at hot 2, // where Credit Hoarder alone waited the 5. Only a 503 without one grows const ms = Math.min(Math.max(1000, ra) * (load || raw != null ? 1 : Math.max(1, s.hot)) + Math.round(Math.random() * MBN_JITTER), MBN_MAX_HOLD); // #1112 jitter // log: every waiter whose slot a hold passed booked again at the end of the queue, behind // requests booked after it, and a hidden tab's (whose timer wakes late) went last again on // each hold: one waited 40s. The hold now moves the whole queue later by its length, the // slots still to come and every waiter's (`slip`, which each adds to its own), so the // queue keeps its order and its one a second const from = Math.max(now, s.cool || 0); s.cool = Math.max(s.cool || 0, Date.now() + ms); const d = s.cool - from; if (d > 0) { s.slip = (s.slip || 0) + d; for (const k of ['tat', 'itat', 'last', 'ilast', 'rhead']) if ((s[k] || 0) > now) s[k] += d; } tr({ ra: raw == null ? undefined : String(raw).slice(0, 40), hold: s.cool - Date.now() }, s); return s.cool - Date.now(); }); if (o.log) o.log('warn', 'MusicBrainz gate: HTTP ' + status + (raw != null ? ' (Retry-After: ' + raw + ')' : '') + (rl.who ? ' [' + String(rl.who).slice(0, 20) + ']' : '') + ' — every script holds ' + Math.round(hold / 100) / 10 + 's'); return { throttled: true, hold }; } if (status >= 200 && status < 500) await mbnState(s => { if (s.hot) s.hot = Date.now() > (s.cool || 0) + 30000 ? 0 : s.hot - 1; if (o.search && s.shot) s.shot = Date.now() > (s.scool || 0) + 30000 ? 0 : s.shot - 1; tr({}, s); }); else tr({}); return { throttled: false, hold: 0 }; } function mbnBodySize(init) { const b = init && init.body; if (b == null) return undefined; try { if (typeof b === 'string') return new TextEncoder().encode(b).length; if (b instanceof URLSearchParams) return new TextEncoder().encode(b.toString()).length; if (typeof Blob !== 'undefined' && b instanceof Blob) return b.size; if (b.byteLength != null) return b.byteLength; } catch (e) {} return undefined; } function mbnBodyText(init) { const MBN_SECRET = /secret|token|pass|auth|session|csrf|code|key|sig/i; const b = init && init.body; let s = null; try { s = typeof b === 'string' ? b : typeof URLSearchParams !== 'undefined' && b instanceof URLSearchParams ? b.toString() : null; } catch (e) {} if (s == null || s.length > 300) return undefined; const t = s.trim(); if (/^[{[]/.test(t)) { try { const hide = v => Array.isArray(v) ? v.map(hide) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, MBN_SECRET.test(k) ? '•••' : hide(x)])) : v; return JSON.stringify(hide(JSON.parse(t))); } catch (e) { return undefined; } } if (/^[^=&\s]+=\S*$/.test(t)) { // a form: key=value&… return t.split('&').map(kv => { const i = kv.indexOf('='); let k = i < 0 ? kv : kv.slice(0, i); try { k = decodeURIComponent(k.replace(/\+/g, ' ')); } catch (e) {} return i > 0 && MBN_SECRET.test(k) ? kv.slice(0, i + 1) + '•••' : kv; }).join('&'); } return MBN_SECRET.test(t) ? undefined : t; // other text: kept only when nothing in it looks like a secret } function mbnLength(header) { try { const v = header ? header('Content-Length') : null; return v != null && /^\d+$/.test(String(v).trim()) ? +v : undefined; } catch (e) { return undefined; } } function mbnGmSize(x) { try { const h = /^content-length:\s*(\d+)\s*$/im.exec(String(x.responseHeaders || '')); if (h) return +h[1]; const r = x.response; if (r && r.byteLength != null) return r.byteLength; if (typeof Blob !== 'undefined' && r instanceof Blob) return r.size; return typeof x.responseText === 'string' ? x.responseText.length : undefined; } catch (e) { return undefined; } } function mbnReasons(fn) { mbnReasons.fn = fn; } function mbnReasonOf(url, method) { try { return (mbnReasons.fn && mbnReasons.fn(String(url), String(method || 'GET').toUpperCase())) || undefined; } catch (e) { return undefined; } } async function mbnLog(url, init, o) { o = o || {}; let h = '', p = String(url); // a blob: or data: URL stays on this computer: not a network request, not logged if (/^(blob|data):/i.test(p)) return (o.send || fetch)(url, init); // a host that isn't MusicBrainz is external, the page's own one too (Beatport's pages) try { const x = new URL(p, location.href); p = x.pathname + x.search; if (!/(^|\.)musicbrainz\.(org|eu)$/.test(x.hostname)) h = x.host; } catch (e) {} const ev = { r: o.reason || mbnReasonOf(url, (init && init.method) || o.method), en: o.entity || undefined, l: o.label || p.slice(0, 120), u: o.u || (o.label ? p.slice(0, 300) : undefined), b: o.background === false ? 0 : 1, id: o.id || mbnRid(), m: o.m || String((init && init.method) || o.method || 'GET').toUpperCase(), h: h || undefined, x: 1 }; mbnTrace(Object.assign({ e: 'start', bs: mbnBodySize(init), bt: mbnBodyText(init) }, ev)); try { const r = await (o.send || fetch)(url, init); mbnTrace(Object.assign({ e: 'answer', st: r.status, rs: r.rs != null ? r.rs : mbnLength(n => r.headers && r.headers.get(n)) }, ev)); return r; } catch (e) { mbnTrace(Object.assign({ e: 'error', err: String((e && (e.name === 'AbortError' ? 'aborted' : e.message)) || e).slice(0, 80) }, ev)); throw e; } } function mbnGm(opts, fn) { fn = fn || (typeof GM_xmlhttpRequest !== 'undefined' ? GM_xmlhttpRequest : null); let fin = null; mbnLog(opts.url, { method: opts.method || 'GET', body: opts.data }, { send: () => new Promise((ok, no) => { fin = { ok, no }; }) }).catch(() => {}); const end = (x, msg) => { if (!fin) return; const g = fin; fin = null; if (!msg) { g.ok({ status: (x && x.status) || 0, rs: x ? mbnGmSize(x) : undefined }); return; } const e = new Error(msg); if (msg === 'aborted') e.name = 'AbortError'; g.no(e); }; const wrap = (name, msg) => { const f = opts[name]; return (...a) => { end(a[0], msg); if (f) return f(...a); }; }; return fn(Object.assign({}, opts, { onload: wrap('onload'), onerror: wrap('onerror', 'network error'), ontimeout: wrap('ontimeout', 'timeout'), onabort: wrap('onabort', 'aborted') })); } function mbnGmFn(fn) { return fn ? o => mbnGm(o, fn) : null; } function mbnXhr(xhr, url, method, body, o) { mbnLog(url, { method: method || 'GET', body }, { ...o, send: () => new Promise((ok, no) => { xhr.addEventListener('load', () => ok({ status: xhr.status, rs: mbnGmSize({ responseHeaders: xhr.getAllResponseHeaders(), response: xhr.responseType && xhr.responseType !== 'text' ? xhr.response : null, responseText: !xhr.responseType || xhr.responseType === 'text' ? xhr.responseText : null }) })); xhr.addEventListener('error', () => no(new Error('network error'))); xhr.addEventListener('timeout', () => no(new Error('timeout'))); xhr.addEventListener('abort', () => { const e = new Error('aborted'); e.name = 'AbortError'; no(e); }); }) }).catch(() => {}); return xhr; } async function mbnFetch(url, init, o) { o = o || {}; if (!o.reason) { const r = mbnReasonOf(url, init && init.method); if (r) o = Object.assign({}, o, { reason: r }); } // #1098: a write (an edit, an ISRC submit) makes every cached answer old. Marked when it goes out and // again when it is answered: a read sent while the write runs gets the answer from before the write, // and without the second mark it was cached as new (ISRC Scout's links count stayed after a submit) if (!o.wrote && !/^(GET|HEAD)$/i.test(String((init && init.method) || 'GET'))) { mbnEdited(); try { return await mbnFetch(url, init, Object.assign({}, o, { wrote: true })); } finally { mbnEdited(); } } { // the Gate log names a request by what it asks for, or by the caller's name with its path kept in u let p = String(url); try { const u = new URL(p, location.href); p = u.pathname.replace(/^\/ws\/2\//, '') + u.search.replace(/[?&]fmt=json\b/, '').replace(/^&/, '?'); } catch (e) {} o = Object.assign({}, o, o.label ? { u: p.slice(0, 300) } : { label: p.slice(0, 120) }, { m: String((init && init.method) || 'GET').toUpperCase(), bs: mbnBodySize(init), bt: mbnBodyText(init) }); } if (!mbnGated(url)) { return mbnLog(url, init, Object.assign({}, o, { send: async (u, i) => { const r = await fetch(u, i); if (!mbnWebsite(u) || !(await mbnIsCheck(r))) return r; // #733: MusicBrainz's browser check answered instead: nothing was done (a POST is safe // to repeat), so pass the check and ask again return (await mbnReverify(u, i, o)) ? fetch(u, i) : r; } })); } const t0 = Date.now(), give = attempt => o.tries ? attempt >= o.tries : o.background === false ? Date.now() - t0 > 45000 : attempt >= 4; if (o.search === undefined) { // a search (?query=) waits out a search-shed hold, nothing else does let q = false; try { q = new URL(String(url), location.href).searchParams.has('query'); } catch (e) {} o = Object.assign({}, o, { search: q }); } // one id for the request and its retries, so the Gate log keeps it apart from a twin if (!o.id) o = Object.assign({}, o, { id: mbnRid() }); // `at` gives the URL at the moment the request leaves: a queued read's inc list can still grow // set below for a read: (inc, self) => a twin's answer that came back while this one waited, or // null; asked just before it leaves and before a retry let peek = null; const go = async (at, inc, self) => { const twin = peek ? () => peek(inc ? inc() : want, self) : null; for (let attempt = 1; ; attempt++) { const slot = await mbnSlot(Object.assign({}, o, twin ? { twin } : {}, attempt > 1 ? { retry: true } : {})); if (slot.twin) return slot.twin; if (!slot.ok) return null; let r; try { // #log: an o.send that never settles (no timeout of its own) left the request open in // the Gate log for good; mbnWsFetch gives up at 35s, so any send does at 40s let quit = false; const sent = (o.send || mbnWsFetch)(at ? at() : url, init); r = await Promise.race([sent, mbnSleep(40000, () => quit).then(() => { if (!quit) throw new TypeError('no answer in 40s'); return new Promise(() => {}); })]); quit = true; } catch (e) { mbnTrace({ e: 'error', r: o.reason || undefined, en: o.entity || undefined, l: o.label, b: o.background === false ? 0 : 1, id: o.id, m: o.m, err: String((e && (e.name === 'AbortError' ? 'aborted' : e.message)) || e).slice(0, 80) }); throw e; } const a = await mbnAnswer(r.status, n => r.headers.get(n), o); if (!a.throttled) return r; // a background search MusicBrainz sheds twice is given up: searches are what it drops when busy const shed = a.shed && o.background !== false && attempt >= 2; if (give(attempt) || shed) { mbnTrace({ e: 'giveup', r: o.reason || undefined, en: o.entity || undefined, l: o.label, b: o.background === false ? 0 : 1, id: o.id, m: o.m, st: r.status, n: attempt }); return r; } // log: a twin sent apart from this one got its 200 while this one waited: no retry const hit = twin && await twin(); if (hit) return hit; } }; // Reads of the same thing share one fetch, and each caller gets its own clone of the answer. // Two members of String Theory's bundle, or one page drawn twice, otherwise send it twice. // join a read whose inc list the running or queued one already covers waits for its answer // merge a read that differs only in inc joins one still queued: that one then leaves // asking for both inc lists (one page's scripts all ask for its entity at load) // A write (POST, a body) always goes on its own. MBN_INC_ALONE incs change what an answer // costs or needs (a login, a smaller page), so they are never added to a read that lacks them. const m = String((init && init.method) || 'GET').toUpperCase(); let key = '', want = null, base = null; if ((m === 'GET' || m === 'HEAD') && !(init && init.body)) { try { base = new URL(String(url), location.href); // with fmt=json, an Accept: application/json header changes nothing: one script sends it, another doesn't const h = init && init.headers, json = base.searchParams.get('fmt') === 'json'; const he = h ? (typeof h.entries === 'function' ? Array.from(h.entries()) : Array.isArray(h) ? h : Object.entries(h)).filter(([k, v]) => !(json && /^accept$/i.test(k) && /^application\/json$/i.test(String(v).trim()))) : []; const hs = he.length ? JSON.stringify(he) : ''; want = new Set((base.searchParams.get('inc') || '').split(/[\s+]+/).filter(Boolean)); const rest = Array.from(base.searchParams.entries()).filter(([k]) => k !== 'inc').sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : a[1] < b[1] ? -1 : 1); key = m + ' ' + base.origin + base.pathname + '?' + new URLSearchParams(rest) + ' ' + hs; } catch (e) { key = ''; } } if (!key) return go(); const live = globalThis.__mbnLive || (globalThis.__mbnLive = new Map()); const sig = init && init.signal; const mine = () => !(o.cancelled && o.cancelled()) && !(sig && sig.aborted); const covers = (run, inc = want) => { for (const i of inc) if (!run.inc.has(i)) return false; return true; }; // a background read may share a page's read; a page's read shares a background one only once it is sent const bg = o.background !== false, ahead = run => run.sent || !run.bg || bg; // merge: the two have the same MBN_INC_ALONE incs const fits = (run, inc = want) => { for (const i of MBN_INC_ALONE) if (run.inc.has(i) !== inc.has(i)) return false; return true; }; // join or cache: a lookup's answer with more incs answers this one too const lookup = /^\/ws\/2\/[a-z-]+\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(base.pathname); const answers = run => lookup || fits(run); // #1098: a recent answer for the same thing, when no edit went out since const cacheable = !o.fresh && !(init && init.credentials && init.credentials !== 'omit') && !base.searchParams.has('query') && (lookup || fits({ inc: new Set() })); let looked = !cacheable; // answers that came from a twin or the cache: not put in the cache again (that would make them new) const kept = new WeakSet(); // the twin check before a request leaves: a run sent in the meantime that answers it (joined, // as below), else the cache. A run that is itself waiting on a twin is never joined, so two // runs retrying apart can't wait on each other peek = async (inc, self) => { const tb = o.background === false ? 0 : 1; const x = (live.get(key) || []).find(x => x !== self && x.sent && !x.twin && covers(x, inc) && (lookup || fits(x, inc))); if (x) { if (self) self.twin = x; mbnTrace({ e: 'join', r: o.reason || undefined, en: o.entity || undefined, l: o.label, b: tb, id: o.id, m: o.m, with: x.label }); let r = null; try { r = await x.p; } catch (e) { r = null; } if (self) self.twin = null; if (r && r.ok) { r = r.clone(); kept.add(r); return r; } } const hit = cacheable && await mbnCacheGet(key, inc); if (!hit) return null; mbnTrace({ e: 'cache', r: o.reason || undefined, en: o.entity || undefined, l: o.label, b: tb, id: o.id, m: o.m, w: Math.round((Date.now() - hit.at) / 1000) }); kept.add(hit.r); return hit.r; }; for (;;) { const runs = live.get(key) || []; let run = runs.find(x => covers(x) && answers(x) && ahead(x)), how = 'join'; if (!run) { run = runs.find(x => !x.sent && fits(x) && ahead(x)); how = 'merge'; } if (!run && !looked) { looked = true; const hit = await mbnCacheGet(key, want); if (hit) { mbnTrace({ e: 'cache', r: o.reason || undefined, en: o.entity || undefined, l: o.label, b: bg ? 1 : 0, id: o.id, m: o.m, w: Math.round((Date.now() - hit.at) / 1000) }); return hit.r; } // the cache is read asynchronously: the same read asked in that moment is in `live` by now continue; } if (!run) break; const add = how === 'merge' ? Array.from(want).filter(i => !run.inc.has(i)) : []; for (const i of add) run.inc.add(i); mbnTrace({ e: how, r: o.reason || undefined, en: o.entity || undefined, l: o.label, b: o.background === false ? 0 : 1, id: o.id, m: o.m, with: run.label, add: add.join(' ') || undefined }); const p = run.p; // this caller's own Stop or abort still ends its wait, whatever the first caller does const stop = new Promise(res => { if (sig) sig.addEventListener('abort', () => res('stop'), { once: true }); if (o.cancelled) { const t = setInterval(() => { if (o.cancelled()) { clearInterval(t); res('stop'); } }, 250); p.then(() => clearInterval(t), () => clearInterval(t)); } }); let r; try { r = await Promise.race([p, stop]); } catch (e) { if (!mine()) throw e; r = null; } if (r === 'stop') { if (sig && sig.aborted) throw (sig.reason instanceof Error ? sig.reason : new DOMException('The operation was aborted.', 'AbortError')); return null; } // a wider read MusicBrainz refused (a 400 for an inc it won't take here) might not refuse // this one's own: it asks alone if (r && !r.ok && r.status !== 404 && run.inc.size !== want.size) return go(); if (r) return r.clone(); if (!mine()) return null; // the first caller was cancelled or aborted, this one wasn't: it asks for itself } // epoch: the edits known before the read goes out. A read sent before a write and answered after it // is kept under the old epoch, so the cache drops it instead of serving the answer from before the write const run = { inc: new Set(want), sent: false, bg, label: o.label, p: null, twin: null, epoch: mbnEditEpoch() }; // #1097: a new read waits MBN_MERGE_WAIT before it books, so the reads a page's scripts send // at load in the same moment merge into it instead of all leaving on their own // #1097: only background reads wait for others; the lead and interactive reads go at once run.p = mbnSleep(bg && !o.lead ? MBN_MERGE_WAIT : 0).then(() => mine() ? go(() => { run.sent = true; if (run.inc.size === want.size) return url; // nothing merged: as asked const u = new URL(base.href); u.searchParams.set('inc', Array.from(run.inc).join(' ')); return u.href; }, () => run.inc, run) : null); const runs = live.get(key) || []; runs.push(run); live.set(key, runs); try { const r = await run.p; if (r && !r.ok && r.status !== 404 && run.inc.size !== want.size) return go(); // as for a joiner, above if (r && r.ok && cacheable && !kept.has(r) && (lookup || fits(run))) await mbnCachePut(key, run.inc, r.clone(), run.epoch); return r ? r.clone() : r; } finally { const l = live.get(key) || [], i = l.indexOf(run); if (i >= 0) l.splice(i, 1); if (!l.length) live.delete(key); } } function mbnEdited() { try { localStorage.setItem(MBN_KEY + '-edit', String(Date.now())); } catch (e) {} } function mbnEditEpoch() { const g = globalThis.__mbnCacheG || (globalThis.__mbnCacheG = { watch: false }); if (!g.watch && typeof document !== 'undefined') { g.watch = true; try { document.addEventListener('submit', e => { const f = e.target; if (f && /^post$/i.test(f.method || '')) mbnEdited(); }, true); } catch (e) {} } // mbLastWrite: the suite's shared time of the last write to MusicBrainz (Event Horizon's kept answers use it too), // so an edit made where the gate saw no submit (the release editor's own save, another script) is one all the same try { return (localStorage.getItem(MBN_KEY + '-edit') || '0') + '|' + (localStorage.getItem('mbLastWrite') || '0'); } catch (e) { return '0'; } } function mbnCacheUrl(key, inc) { return 'https://mbn-cache.invalid/?k=' + encodeURIComponent(key) + '&inc=' + encodeURIComponent(Array.from(inc).sort().join(' ')); } async function mbnCacheGet(key, want) { try { if (typeof caches === 'undefined') return null; const epoch = mbnEditEpoch(), c = await caches.open(MBN_KEY + '-cache'), pre = mbnCacheUrl(key, []).replace(/&inc=.*$/, '&inc='); for (const q of await c.keys()) { if (q.url.indexOf(pre) !== 0) continue; const inc = decodeURIComponent(q.url.slice(pre.length)).split(' ').filter(Boolean); let ok = true; for (const i of want) if (inc.indexOf(i) < 0) { ok = false; break; } if (!ok) continue; const r = await c.match(q); if (!r) continue; const at = +r.headers.get('x-mbn-at') || 0; if (r.headers.get('x-mbn-epoch') !== epoch || Date.now() - at > MBN_CACHE_TTL) { await c.delete(q); continue; } return { r, at }; } } catch (e) {} return null; } async function mbnCachePut(key, inc, r, epoch = mbnEditEpoch()) { try { if (typeof caches === 'undefined') return; const body = await r.text(), h = new Headers(); h.set('content-type', r.headers.get('content-type') || 'application/json'); h.set('x-mbn-at', String(Date.now())); h.set('x-mbn-epoch', epoch); const c = await caches.open(MBN_KEY + '-cache'); await c.put(mbnCacheUrl(key, inc), new Response(body, { status: r.status, headers: h })); const all = await c.keys(); for (let i = 0; i < all.length - MBN_CACHE_MAX; i++) await c.delete(all[i]); // oldest first } catch (e) {} } function mbnHot() { let s; try { s = JSON.parse(localStorage.getItem(MBN_KEY) || 'null') || {}; } catch (e) { s = globalThis.__mbnGate || {}; } return Date.now() > (s.cool || 0) + 30000 ? 0 : (s.hot || 0); // a throttle long gone is over } function mbnUA() { let n = 'mb-userscripts', v = ''; try { const i = GM_info.script; n = String(i.name || n).replace(/\s+/g, ''); v = i.version || ''; } catch (e) {} return n + (v ? '/' + v : '') + ' ( https://github.com/majkinetor/musicbrainz-userscripts )'; } function mbnWsFetch(url, init) { init = init || {}; const gm = typeof GM_xmlhttpRequest === 'function' ? GM_xmlhttpRequest : (typeof GM !== 'undefined' && GM && typeof GM.xmlHttpRequest === 'function' ? GM.xmlHttpRequest : null); const abs = new URL(String(url), typeof location !== 'undefined' ? location.href : 'https://musicbrainz.org/').href; // #997: a request that asks for the login (credentials 'include' / 'same-origin') on this // page's own origin goes through the page's fetch(): a manager's GM request carries the // cookie only if the browser lets the extension send it (Safari's tracking prevention does // not), and MusicBrainz then answers 401. The User-Agent is the browser's then. const own = typeof location !== 'undefined' && (() => { try { return new URL(abs).origin === location.origin; } catch (e) { return false; } })(); if (!gm || (own && (init.credentials === 'include' || init.credentials === 'same-origin'))) return fetch(url, init); const headers = {}; try { new Headers(init.headers || {}).forEach((v, k) => { headers[k] = v; }); } catch (e) {} headers['User-Agent'] = mbnUA(); return new Promise((resolve, reject) => { const sig = init.signal; if (sig && sig.aborted) { reject(new DOMException('Aborted', 'AbortError')); return; } let req = null, done = false; const onAbort = () => { if (done) return; done = true; try { req && req.abort && req.abort(); } catch (e) {} reject(new DOMException('Aborted', 'AbortError')); }; const fail = m => () => { if (done) return; done = true; if (sig) sig.removeEventListener('abort', onAbort); reject(new TypeError(m)); }; // A request the manager never answers, not even with its own timeout (seen in // Violentmonkey on Firefox): give up on it here, or whoever awaits it, a matching // pass that was told to stop included, waits forever. MusicBrainz answers a search in // seconds even on a slow day; one that took a minute held every lane behind it while // the shared throttle allowed a single one, so the gate stops waiting after half that. // #999 mbnSleep, not a plain timer: with this page's timers held back, a stuck request was never given up on mbnSleep(35000, () => done).then(() => { if (done) return; fail('no answer in 35s')(); try { req && req.abort && req.abort(); } catch (e) {} }); if (sig) sig.addEventListener('abort', onAbort); const res = gm({ method: String(init.method || 'GET').toUpperCase(), url: abs, headers, data: init.body, timeout: 30000, onload: x => { if (done) return; done = true; if (sig) sig.removeEventListener('abort', onAbort); const h = new Headers(); for (const line of String(x.responseHeaders || '').split(/\r?\n/)) { const i = line.indexOf(':'); if (i > 0) try { h.append(line.slice(0, i).trim(), line.slice(i + 1).trim()); } catch (e) {} } const st = x.status || 0; if (st < 200 || st > 599) { reject(new TypeError('network error (status ' + st + ')')); return; } const r = new Response(st === 204 || st === 304 ? null : (x.responseText != null ? x.responseText : ''), { status: st, statusText: x.statusText || '', headers: h }); try { Object.defineProperty(r, 'url', { value: x.finalUrl || abs }); } catch (e) {} resolve(r); }, onerror: fail('network error'), ontimeout: fail('timed out'), onabort: fail('aborted'), }); req = res && typeof res.then === 'function' ? null : res; // GM.xmlHttpRequest returns a promise in some managers }); } function mbnRawHeader(raw, name) { const want = String(name).toLowerCase(); for (const line of String(raw || '').split(/\r?\n/)) { const i = line.indexOf(':'); if (i > 0 && line.slice(0, i).trim().toLowerCase() === want) return line.slice(i + 1).trim(); } return null; } function mbnWebsite(url) { const s = String(url || ''); if (mbnGated(s)) return false; if (/^(https?:)?\/\/([a-z0-9-]+\.)*musicbrainz\.org(\/|$)/i.test(s)) return true; return /^\/(?!\/)/.test(s) && typeof location !== 'undefined' && /(^|\.)musicbrainz\.org$/i.test(location.hostname); } async function mbnIsCheck(r) { try { if (!r || !/text\/html/i.test((r.headers && r.headers.get('content-type')) || '')) return false; const head = (await r.clone().text()).slice(0, 3000); return /\s*Verifying your browser\s*<\/title>|JavaScript is required to access this page/i.test(head); } catch (e) { return false; } } function mbnReverify(url, init, o) { o = o || {}; const log = (lvl, m) => { try { if (o.log) o.log(lvl, m); else (lvl === 'warn' ? console.warn : console.info)('[MusicBrainz gate] ' + m); } catch (e) {} }; const g = globalThis.__mbnCheck || (globalThis.__mbnCheck = { busy: null, failedAt: 0 }); if (g.busy) return g.busy; let target; try { target = new URL(String(url), location.href); } catch (e) { return Promise.resolve(false); } if (target.host !== location.host || typeof document === 'undefined') { log('warn', 'MusicBrainz asked to verify the browser — open any MusicBrainz page, then retry'); return Promise.resolve(false); } if (Date.now() - g.failedAt < 60000) return Promise.resolve(false); // just failed: don't loop // a POST's URL can't be loaded: the check is per browser, so any light GET passes it const method = String((init && init.method) || 'GET').toUpperCase(); const src = method === 'GET' ? target.href : location.origin + '/ws/js/entity/89ad4ac3-39f7-470e-963a-56509c546377'; const t0 = Date.now(); log('warn', 'MusicBrainz asked to verify the browser again ("Verifying your browser") — passing it in a hidden frame'); g.busy = new Promise(resolve => { const fr = document.createElement('iframe'); // fresh each time, never re-navigated fr.setAttribute('aria-hidden', 'true'); fr.setAttribute('data-mbn-check', ''); fr.tabIndex = -1; fr.style.cssText = 'position:fixed;width:1px;height:1px;left:-9999px;top:0;border:0;opacity:0;pointer-events:none'; let loads = 0, done = false; const finish = ok => { if (done) return; done = true; fr.remove(); g.busy = null; mbnTrace({ e: 'check', ok: ok ? 1 : 0, w: Date.now() - t0 }); if (ok) log('info', 'browser check passed in ' + (Date.now() - t0) + ' ms — retrying'); else { g.failedAt = Date.now(); const m = 'MusicBrainz wants to verify your browser — open any MusicBrainz page in another tab, then retry'; log('warn', m + ' (the hidden frame did not clear it in 20 s)'); try { if (o.notify) o.notify(m); } catch (e) {} } resolve(ok); }; // the first load is the check; it posts its answer and is redirected to the real URL fr.onload = () => { loads++; let still; try { const d = fr.contentDocument; still = !d || /<title>\s*Verifying your browser\s*<\/title>|JavaScript is required to access this page/i.test(d.documentElement ? d.documentElement.outerHTML.slice(0, 3000) : ''); } catch (e) { still = loads < 2; } if (!still) finish(true); }; mbnSleep(20000, () => done).then(() => finish(false)); // #999 wakes even with this page's timers held back fr.src = src; (document.body || document.documentElement).appendChild(fr); }); return g.busy; } // </ST-NET> // the shared tooltip (STANDARDS → Standard 14) // <ST-TIP> — generated by dev/ui/sync-ui.mjs from dev/ui/tooltip.mjs — DO NOT EDIT // Tooltips: our own, never the browser's title (dev/ui/tooltip.mjs, STANDARDS → Standard 14). function mbuTipV() { return 13; } function mbuTipCssText() { return "#mbu-tip{position:fixed;left:0;top:0;z-index:var(--mbu-z-tip,2147483647);box-sizing:border-box;max-width:min(330px,calc(100vw - 16px));padding:7px 11px 8px;background:var(--mbu-bg,#fff);color:var(--mbu-text,#222);border:1px solid var(--mbu-border,#cfc6e6);border-radius:9px;box-shadow:0 6px 24px rgba(40,20,80,.2),0 1px 3px rgba(40,20,80,.12);font:12.5px/1.45 var(--mbu-font,-apple-system,Segoe UI,Roboto,Arial,sans-serif);text-align:left;white-space:normal;overflow-wrap:break-word;letter-spacing:normal;text-transform:none;pointer-events:none;visibility:hidden;opacity:0;transform:translateY(-3px);transition:opacity .12s ease,transform .12s ease,visibility 0s linear .12s}#mbu-tip.mbu-tip-up{transform:translateY(3px)}#mbu-tip.mbu-tip-on{visibility:visible;opacity:1;transform:none;transition:opacity .12s ease,transform .12s ease}#mbu-tip.mbu-tip-act.mbu-tip-on{pointer-events:auto}#mbu-tip.mbu-tip-wide{max-width:min(460px,calc(100vw - 16px))}#mbu-tip:has(.mbu-tip-dl){max-width:min(480px,calc(100vw - 16px))}#mbu-tip::before{content:\"\";position:absolute;left:calc(var(--mbu-tip-ax,50%) - 5px);top:-5px;width:8px;height:8px;background:inherit;border:1px solid var(--mbu-border,#cfc6e6);border-right:0;border-bottom:0;transform:rotate(45deg)}#mbu-tip.mbu-tip-up::before{top:auto;bottom:-5px;border:1px solid var(--mbu-border,#cfc6e6);border-left:0;border-top:0}#mbu-tip.mbu-tip-card:not(.mbu-tip-up)::before{background:var(--mbu-bg-raised,#faf9fe)}#mbu-tip .mbu-tip-lead{font-weight:600;color:var(--mbu-text,#222)}#mbu-tip .mbu-tip-p{margin:0;color:var(--mbu-text-dim,#555)}#mbu-tip .mbu-tip-lead+*,#mbu-tip .mbu-tip-p+*,#mbu-tip .mbu-tip-ul+*,#mbu-tip .mbu-tip-rows+*{margin-top:5px}#mbu-tip>.mbu-tip-p:first-child:last-child{color:var(--mbu-text,#222)}#mbu-tip .mbu-tip-warn{color:var(--mbu-warn,#a05a00)}#mbu-tip .mbu-tip-rows{display:grid;grid-template-columns:auto minmax(0,1fr);gap:4px 8px;align-items:start;color:var(--mbu-text-dim,#555)}#mbu-tip .mbu-tip-rows>.mbu-tip-kk,#mbu-tip .mbu-tip-rows>.mbu-tip-dl{min-height:18px}#mbu-tip .mbu-tip-rows>.mbu-tip-k{line-height:18px}#mbu-tip .mbu-tip-rows>:nth-child(odd){justify-self:start}#mbu-tip .mbu-tip-rows>.mbu-tip-span{grid-column:2;justify-self:stretch;margin:-2px 0 0}#mbu-tip .mbu-tip-k{display:inline-block;padding:0;border:0;background:none;color:var(--mbu-text-weak,#888);font:600 11.5px/1.5 var(--mbu-font,-apple-system,Segoe UI,Roboto,Arial,sans-serif);white-space:nowrap}#mbu-tip .mbu-tip-kk{display:inline-flex;align-items:center;gap:3px;color:var(--mbu-accent-text,#5f3ec0);white-space:nowrap}#mbu-tip .mbu-tip-dl{display:inline-flex;align-items:center;gap:6px;font-weight:600;color:var(--mbu-text,#222);white-space:nowrap}#mbu-tip .mbu-tip-dl i{flex:none;width:10px;height:10px;border-radius:50%;box-shadow:inset 0 0 0 1px rgba(0,0,0,.22)}#mbu-tip .mbu-tip-on{color:var(--mbu-accent-text,#5f3ec0)}#mbu-tip .mbu-tip-dl.mbu-tip-on::after{content:\"◂\";margin-left:-2px;font-size:11px}#mbu-tip .mbu-tip-off{opacity:.45}#mbu-tip .mbu-tip-sym{letter-spacing:.2px}#mbu-tip .mbu-tip-mouse{display:block;flex:none;position:relative}#mbu-tip .mbu-tip-mouse rect[fill=none],#mbu-tip .mbu-tip-mouse path[stroke]{stroke:var(--mbu-text-weak,#888);stroke-width:1}#mbu-tip .mbu-tip-kx{font:600 10px/1 var(--mbu-font,-apple-system,Segoe UI,Roboto,Arial,sans-serif);color:var(--mbu-text-weak,#888)}#mbu-tip .mbu-tip-kq{font:600 11.5px/1 var(--mbu-font,-apple-system,Segoe UI,Roboto,Arial,sans-serif);color:var(--mbu-text-weak,#888)}#mbu-tip .mbu-tip-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}#mbu-tip .mbu-tip-o{display:inline-block;padding:0 7px;border-radius:999px;background:var(--mbu-accent-soft,#ece4ff);color:var(--mbu-accent-text,#5f3ec0);font:600 11px/1.6 var(--mbu-font,-apple-system,Segoe UI,Roboto,Arial,sans-serif);white-space:nowrap}#mbu-tip .mbu-tip-ul{margin:0;padding:0 0 0 15px;color:var(--mbu-text-dim,#555)}#mbu-tip .mbu-tip-ul li{margin:1px 0;padding:0}#mbu-tip code{font:11.5px var(--mbu-font-mono,ui-monospace,Consolas,monospace);padding:0 4px;border-radius:4px;background:var(--mbu-bg-sunken,#f4f2f9)}#mbu-tip b{font-weight:600;color:var(--mbu-text,#222)}#mbu-tip a{color:var(--mbu-accent-text,#5f3ec0)}#mbu-tip.mbu-tip-card{padding:0;width:380px;max-width:min(380px,calc(100vw - 16px));overflow:visible}#mbu-tip .mbu-tip-ch{display:flex;align-items:center;gap:8px;padding:8px 11px;border-bottom:1px solid var(--mbu-border-soft,#e2dcef);background:var(--mbu-bg-raised,#faf9fe);border-radius:9px 9px 0 0}#mbu-tip .mbu-tip-ca{margin-left:auto;font-size:11px;color:var(--mbu-text-weak,#999);white-space:nowrap}#mbu-tip .mbu-tip-cb{padding:8px 11px;display:flex;flex-direction:column;gap:6px}#mbu-tip .mbu-tip-cf{display:flex;gap:10px;padding:6px 11px;border-top:1px solid var(--mbu-border-soft,#e2dcef);font-size:11px;color:var(--mbu-text-weak,#999)}#mbu-tip .mbu-tip-cf>:last-child:not(:first-child){margin-left:auto}@media (prefers-reduced-motion:reduce){#mbu-tip,#mbu-tip.mbu-tip-on{transition:none;transform:none}}"; } function mbuTipRoots() { return ".mbu-ov,.mbu-ui,#mbu-logpop,.mbu-logemb,.discogs-bar,.discogs-review-panel-li,#as-root,#as-setup,.as-pop,#as-switch-wrap,#ii-btn,.fs-launch,#tc-bar,#tc-nav-bar,#tc-settings,#tc-anno-wrap,.tc-panel,.tc-toolcfg,.tc-acpop,.tc-recpop,.tc-lppop,.tc-tpppop,.tc-tpp-mpop,.tc-anno-help-pop,.tc-mirror,.tc-addrow,.tc-medopts,.tc-tools,#tc-recwrap,#tc-ri-toolbar,.tc-fmt-flat,.gt-toolbar,.gt-cons,.gt-menu,.gt-pop,.gt-cfg-pop,.gt-wm-pop,#ii-modal,#ii-sxpanel,#mb-pc-panel,#mb-provider-modal-card,.fs-cons,#fs-settings,.fs-overlay,.mmth-pop,.mmth-cfg,.mmth-side,.mmth-pinbar,.mmthf-pop,.mmthf-bar,#falcon-panel,#falcon-launcher,#falcon-item-popup,#falcon-add-page,.falcon-bar,.falcon-addmenu"; } function mbuTipEsc(s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); } function mbuTipLabel(line) { var m = /^([^\s:.,;!?()][^:.,;!?()]{0,40}?): (\S[\s\S]*)$/.exec(line); if (!m || m[1].split(/\s+/).length > 3 || /https?$/i.test(m[1])) return null; return { label: m[1], text: m[2], key: mbuTipIsKey(m[1]) }; } function mbuTipIsKey(label) { return /click|drag|wheel|scroll|hover|double|press|paste|\bkey\b|^(esc|escape|enter|return|tab|space|ctrl|shift|alt|cmd|meta|del|delete|backspace|f\d{1,2})\b|\+|^[↑↓←→]/i.test(label); } function mbuTipInline(s) { return mbuTipEsc(s) .replace(/`([^`]+)`/g, '<code>$1</code>') .replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>') .replace(/\(((?:(?:Ctrl|Alt|Shift|Cmd|Meta)\+)+[^\s()]+)\)/g, function (m, k) { return mbuTipKbd(k); }) .replace(/\s\((Esc|Enter|Space|Tab|[A-Z0-9]|[↑↓←→])\)(?=$|[\s.,;])/g, ' <kbd class="mbu-tip-k">$1</kbd>'); } function mbuTipCap(s) { return s.charAt(0).toUpperCase() + s.slice(1); } function mbuTipMod(k) { return { ctrl: 'C', alt: 'A', shift: '⇧', cmd: '⌘', meta: '⌘' }[String(k).toLowerCase()] || k; } function mbuTipKbd(combo) { var parts = String(combo).split(/\s*\+\s*/); var key = parts.pop(); return '<kbd class="mbu-tip-k mbu-tip-sym"><span class="mbu-tip-sr">' + mbuTipEsc(combo) + '</span><span aria-hidden="true">' + parts.concat('').map(mbuTipMod).join('+') + mbuTipEsc(key.length === 1 ? key.toUpperCase() : mbuTipCap(key)) + '</span></kbd>'; } function mbuTipKey(label) { // two ways to do the same, "Middle-click / Alt+click" or "Click or hover": each drawn, a grey slash between var alts = String(label).split(/\s+(?:\/|or)\s+/i); if (alts.length > 1) return '<span class="mbu-tip-kk">' + alts.map(mbuTipKey).join('<span class="mbu-tip-kx">/</span>') + '</span>'; // a mouse action with where or how it goes, "Click the status", "Click again": the mouse, then the words var q = /^((?:(?:ctrl|alt|shift|cmd|meta)\s*[+-]\s*)*(?:left|right|middle|double)?[- ]?(?:click|drag|wheel|scroll))\s+([^+/]+)$/i.exec(String(label).trim()); if (q) return '<span class="mbu-tip-kk">' + mbuTipKey(q[1]) + '<span class="mbu-tip-kq">' + mbuTipEsc(q[2]) + '</span></span>'; // two mouse actions at once, "Right-click + wheel": each drawn, a grey plus between var both = /^(.*?(?:click|drag|wheel|scroll))\s+\+\s+(.+)$/i.exec(String(label).trim()); if (both) return '<span class="mbu-tip-kk">' + mbuTipKey(both[1]) + '<span class="mbu-tip-kx">+</span>' + mbuTipKey(both[2]) + '</span>'; var m = /^((?:(?:ctrl|alt|shift|cmd|meta)\s*[+-]\s*)*)(left|right|middle|double)?[- ]?(click|drag|wheel|scroll)$/i.exec(String(label).trim()); if (!m) return /^(?:(?:ctrl|alt|shift|cmd|meta)\s*\+\s*)+\S/i.test(label) ? mbuTipKbd(label) : '<span class="mbu-tip-k">' + mbuTipEsc(mbuTipCap(label)) + '</span>'; var mods = m[1] ? m[1].split(/\s*[+-]\s*/).filter(Boolean) : []; var btn = (m[2] || '').toLowerCase(), act = m[3].toLowerCase(); var wheel = btn === 'middle' || act === 'wheel' || act === 'scroll'; // the wheel a filled strip down the middle, as bold as a filled button (a thin wheel vanished at 10px) var fill = wheel ? 'M4 1.4h4V7H4z' : btn === 'right' ? 'M6 1C8.8 1 11 3.2 11 6v1H6z' : 'M6 1C3.2 1 1 3.2 1 6v1h5z'; var svg = '<svg class="mbu-tip-mouse" viewBox="0 0 12 16" width="10" height="13" aria-hidden="true">' + '<path d="' + fill + '" fill="currentColor"/>' + '<rect x="1" y="1" width="10" height="14" rx="5" fill="none" stroke="currentColor" stroke-width="1.3"/>' + '<path d="M1 7h10' + (wheel ? '' : 'M6 1v6') + '" stroke="currentColor" stroke-width="1.1"/>' + '</svg>'; var extra = btn === 'double' ? '×2' : act === 'drag' ? 'drag' : (act === 'wheel' || act === 'scroll') ? '↕' : ''; return '<span class="mbu-tip-kk"><span class="mbu-tip-sr">' + mbuTipEsc(mbuTipCap(label)) + '</span>' + (mods.length ? '<kbd class="mbu-tip-k mbu-tip-sym" aria-hidden="true">' + mods.map(mbuTipMod).join('+') + '</kbd>' : '') + svg + (extra ? '<span class="mbu-tip-kx" aria-hidden="true">' + extra + '</span>' : '') + '</span>'; } function mbuTipText(src) { var raw = String(src == null ? '' : src).replace(/\r/g, '').replace(/^\s+|\s+$/g, ''); if (!raw) return ''; var lines = []; // the shapes the old title texts took, read as the rows they mean: // "… — click to open it" → "…" + "Click: open it" // "… (right-click: guess case all)" → "…" + "Right-click: guess case all" // "Ctrl-click", "Alt-click" → "Ctrl+click", "Alt+click" raw = raw.replace(/\b(Ctrl|Alt|Shift|Cmd)-(click|drag)/gi, '$1+$2') .replace(/\s*\(((?:(?:right|middle|double|ctrl|alt|shift|cmd)[-+ ]?)+click|(?:ctrl|alt|shift|cmd)\+\w+):\s*([^()\n]+)\)(?=\s*(?:$|\n))/gim, function (m, k, t) { return '\n' + mbuTipCap(k) + ': ' + t; }) .replace(/\s+[—–-]\s+((?:(?:right|middle|double|ctrl|alt|shift)[-+ ]?)?click) to ([^\n·]+)/gi, function (m, k, t) { return '\n' + mbuTipCap(k) + ': ' + t; }) .replace(/[.;]\s+((?:right|middle|double|ctrl|alt|shift)[-+ ]?click|click) to ([^\n·.]+)\.?(?=\s*(?:$|\n))/gi, function (m, k, t) { return '\n' + mbuTipCap(k) + ': ' + t; }); raw.split('\n').forEach(function (line) { line = line.replace(/\s+$/, ''); // ' · Label: ' starts a new line; so does '. Label: ' once the line itself opened with a label var parts = line.split(/\s+·\s+/), out = [parts[0]]; for (var i = 1; i < parts.length; i++) { if (mbuTipLabel(parts[i])) out.push(parts[i]); else out[out.length - 1] += ' · ' + parts[i]; } out.forEach(function (seg) { if (!mbuTipLabel(seg)) { lines.push(seg); return; } var bits = seg.split(/(?<=\.)\s+(?=[A-Z][\w+-]*(?:\s[\w+-]+)?:\s)/); bits.forEach(function (b) { lines.push(b); }); }); }); // blocks: lead / paragraph / rows / bullets var blocks = [], rowRun = []; var flushRows = function () { if (!rowRun.length) return; var keyed = rowRun.filter(function (r) { return r.key; }).length; if (rowRun.length >= 2 || keyed || rowRun[0].dot) blocks.push({ t: 'rows', rows: rowRun }); else blocks.push({ t: 'p', s: rowRun[0].line }); rowRun = []; }; lines.forEach(function (line, n) { if (!line.trim()) { flushRows(); return; } var b = /^\s*[-•]\s+(.*)$/.exec(line); if (b) { flushRows(); var last = blocks[blocks.length - 1]; if (last && last.t === 'ul') last.items.push(b[1]); else blocks.push({ t: 'ul', items: [b[1]] }); return; } // a level row, "{#2f6fd6} Exact: …": a dot in the colour before the label; "{#… on}" marks the // chosen level, "{#… off}" dims one past it (a cutoff's table) var lv = /^\{(#[0-9a-f]{3,8})(?: (on|off))?\}\s*(\S[\s\S]*)$/i.exec(line); if (lv) { var ll = mbuTipLabel(lv[3]) || { label: lv[3], text: '' }; rowRun.push({ label: ll.label, text: ll.text, dot: lv[1], st: lv[2] ? lv[2].toLowerCase() : '', line: line }); return; } var l = mbuTipLabel(line); // the first line is a row only as a key or when a label follows: alone, "Release group: when…" is a sentence if (l && (l.key || blocks.length || rowRun.length || (lines[n + 1] && mbuTipLabel(lines[n + 1])))) { l.line = line; rowRun.push(l); return; } flushRows(); blocks.push({ t: 'p', s: line }); }); flushRows(); // one long paragraph: its first sentence becomes the lead if (blocks.length === 1 && blocks[0].t === 'p' && blocks[0].s.length > 110) { var m = /^(.{12,110}?[.!?])\s+(?=[A-Z(“"'])([\s\S]+)$/.exec(blocks[0].s); if (m) blocks = [{ t: 'p', s: m[1].replace(/\.$/, '') }, { t: 'p', s: m[2] }]; } var lead = blocks.length > 1 && blocks[0].t === 'p'; var rowsHtml = function (bl) { return bl.rows.map(function (r) { if (r.dot) { var c = r.st ? ' mbu-tip-' + r.st : ''; return '<span class="mbu-tip-dl' + c + '"><i style="background:' + r.dot + '"></i>' + mbuTipEsc(mbuTipCap(r.label)) + '</span>' + '<span class="mbu-tip-dt' + c + '">' + mbuTipInline(r.text) + '</span>'; } return (r.key ? mbuTipKey(r.label) : '<span class="mbu-tip-o">' + mbuTipEsc(mbuTipCap(r.label)) + '</span>') + '<span>' + mbuTipInline(r.text) + '</span>'; }).join(''); }; var html = function (bl, i, span) { var sp = span ? ' mbu-tip-span' : ''; if (bl.t === 'ul') return '<ul class="mbu-tip-ul' + sp + '">' + bl.items.map(function (x) { return '<li>' + mbuTipInline(x) + '</li>'; }).join('') + '</ul>'; if (bl.t === 'rows') return span ? rowsHtml(bl) : '<div class="mbu-tip-rows">' + rowsHtml(bl) + '</div>'; var warn = /^⚠/.test(bl.s); return '<div class="' + (lead && i === 0 ? 'mbu-tip-lead' : 'mbu-tip-p') + (warn ? ' mbu-tip-warn' : '') + sp + '">' + mbuTipInline(bl.s) + '</div>'; }; // rows with a note between them stay one grid, the note under the row before it, so their labels line up var first = -1, last = -1; blocks.forEach(function (bl, i) { if (bl.t === 'rows') { if (first < 0) first = i; last = i; } }); var out = ''; for (var i = 0; i < blocks.length; i++) { if (i === first && last > first) { out += '<div class="mbu-tip-rows">'; for (; i <= last; i++) out += html(blocks[i], i, true); out += '</div>'; i = last; } else out += html(blocks[i], i, false); } return out; } function mbuTipCard(o) { o = o || {}; var h = ''; if (o.head || o.title || o.aside) { h += '<div class="mbu-tip-ch">' + (o.head || '') + (o.title ? '<b>' + mbuTipEsc(o.title) + '</b>' : '') + (o.aside ? '<span class="mbu-tip-ca">' + mbuTipEsc(o.aside) + '</span>' : '') + '</div>'; } if (o.body) h += '<div class="mbu-tip-cb">' + o.body + '</div>'; if (o.foot || o.footAside) h += '<div class="mbu-tip-cf"><span>' + (o.foot || '') + '</span>' + (o.footAside ? '<span>' + o.footAside + '</span>' : '') + '</div>'; return h; } function mbuTipS() { return mbuTipS.s || (mbuTipS.s = { me: Math.random().toString(36).slice(2, 10), lead: false, els: typeof WeakMap === 'function' ? new WeakMap() : null, prov: [], cur: null, curOpts: null, pend: null, showT: 0, hideT: 0, liveT: 0, warm: 0, quiet: null, tab: false, mx: -1, my: -1, obs: null, }); } function mbuTip(el, content, opts) { if (!el) return el; var _mbuTip = mbuTipS(); mbuTipStart(); opts = opts || {}; if (typeof content === 'function') { if (_mbuTip.els) _mbuTip.els.set(el, { fn: content, opts: opts }); el.setAttribute('data-mbu-tip-own', ''); el.removeAttribute('title'); return el; } if (content == null || content === '') el.removeAttribute('data-tip'); else el.setAttribute('data-tip', String(content)); if (opts.place) el.setAttribute('data-tip-place', opts.place); if (opts.wide) el.setAttribute('data-tip-wide', ''); el.removeAttribute('title'); if (_mbuTip.cur === el) mbuTipRender(); return el; } function mbuTipOn(selector, fn, opts) { mbuTipS().prov.push({ sel: selector, fn: fn, opts: opts || {} }); mbuTipStart(); } function mbuTipShowFor(el, content, opts) { if (!el || content == null || content === '') { mbuTipHide(true); return; } mbuTipStart(); var o = opts || {}; var fn = typeof content === 'function' ? content : function () { return content; }; var S = mbuTipS(); if (S.cur === el) { S.curOpts.fn = fn; if (!mbuTipRender()) mbuTipHide(true); return; } mbuTipShow({ el: el, fn: fn, opts: o }); } function mbuTipHtml(s) { if (mbuTipHtml.tt === undefined) { mbuTipHtml.tt = null; try { var tt = (typeof window !== 'undefined' && window.trustedTypes) || null; if (tt && tt.createPolicy) mbuTipHtml.tt = tt.createPolicy('mbu-tip-' + Math.random().toString(36).slice(2, 8), { createHTML: function (x) { return x; } }); } catch (e) { /* the page allows no new policy: plain strings */ } } return mbuTipHtml.tt ? mbuTipHtml.tt.createHTML(String(s)) : String(s); } function mbuTipCss() { var s = document.getElementById('mbu-tip-css'); if (s && +s.getAttribute('data-v') >= mbuTipV()) return; if (!s) { s = document.createElement('style'); s.id = 'mbu-tip-css'; (document.head || document.documentElement).appendChild(s); } s.setAttribute('data-v', String(mbuTipV())); s.textContent = mbuTipCssText(); } function mbuTipEl() { var t = document.getElementById('mbu-tip'); if (!t) { t = document.createElement('div'); t.id = 'mbu-tip'; t.setAttribute('role', 'tooltip'); } // Falcon's panel, Group Therapy's menus and others sit at the top z-index too; at an equal one // the later element is drawn over, so the tip moves to the end of the page when it is not there // (majkinetor, with a screenshot: Falcon's panel over a tip). It hangs on <html>, not <body>: // Event Horizon isolates <body>, which kept a tip there under the dock's icons (#847) var host = document.documentElement; if (t.parentNode !== host || host.lastElementChild !== t) host.appendChild(t); return t; } function mbuTipFind(node) { var target = node && (node.nodeType === 1 ? node : node.parentElement); if (target && target.closest('[data-mbu-foreign]')) return null; var _mbuTip = mbuTipS(); var tip = document.getElementById('mbu-tip'); for (var el = node && node.nodeType === 1 ? node : node && node.parentElement; el && el !== document.documentElement; el = el.parentElement) { if (el === tip) return null; var reg = _mbuTip.els && _mbuTip.els.get(el); if (reg) return { el: el, fn: reg.fn, opts: reg.opts }; for (var i = 0; i < _mbuTip.prov.length; i++) { var p = _mbuTip.prov[i]; try { if (el.matches(p.sel)) return { el: el, fn: p.fn, opts: p.opts }; } catch (e) { /* a bad selector matches nothing */ } } if (!_mbuTip.lead) continue; if (el.hasAttribute('data-mbu-tip-own')) return null; // another copy's rich tip if (el.hasAttribute('data-tip')) return { el: el, opts: { place: el.getAttribute('data-tip-place'), wide: el.hasAttribute('data-tip-wide') } }; // an <option> keeps its title: the browser draws a dropdown's list, where no page tooltip reaches if (el.hasAttribute('title') && el.getAttribute('title') && el.namespaceURI === 'http://www.w3.org/1999/xhtml' && !/^(OPTION|OPTGROUP)$/.test(el.tagName)) { var root = null; try { root = el.closest(mbuTipRoots()); } catch (e) { /* no roots */ } if (root) { el.setAttribute('data-tip', el.getAttribute('title')); el.removeAttribute('title'); return { el: el, opts: {} }; } } } return null; } function mbuTipRender() { var _mbuTip = mbuTipS(); var a = _mbuTip.cur, o = _mbuTip.curOpts || {}, t = mbuTipEl(), c; if (!a) return false; if (o.fn) { try { c = o.fn(a); } catch (e) { c = null; } if (c == null || c === '') return false; if (typeof c === 'string') t.innerHTML = mbuTipHtml(c); else { t.textContent = ''; t.appendChild(c); } } else { var s = a.getAttribute('data-tip'); if (!s) return false; var h = mbuTipText(s); t.innerHTML = mbuTipHtml(h); // an element with nothing to read of its own is named by its tip if (!a.getAttribute('aria-label') && !/[\p{L}\p{N}]/u.test(a.textContent || '') && !a.querySelector('img[alt]:not([alt=""])')) { a.setAttribute('aria-label', s.split('\n')[0]); } } // a render of the open tip (its text changed) keeps it shown var on = t.classList.contains('mbu-tip-on') && t.getAttribute('data-owner') === _mbuTip.me; t.className = 'mbu-ui' + (o.card ? ' mbu-tip-card' : '') + (o.interactive ? ' mbu-tip-act' : '') + (o.wide ? ' mbu-tip-wide' : '') + (on ? ' mbu-tip-on' : ''); t.setAttribute('data-owner', _mbuTip.me); mbuTipPlace(t, a, o.place); return true; } function mbuTipPlace(t, a, place) { var _mbuTip = mbuTipS(); var r = a.getBoundingClientRect(); if (!r.width && !r.height && a.firstElementChild) r = a.firstElementChild.getBoundingClientRect(); t.style.left = '0px'; t.style.top = '0px'; var w = t.offsetWidth, h = t.offsetHeight, vw = document.documentElement.clientWidth || window.innerWidth, vh = window.innerHeight, gap = 8, m = 6; var below = place !== 'above'; if (below && r.bottom + gap + h > vh - m && r.top - gap - h >= m) below = false; else if (!below && r.top - gap - h < m && r.bottom + gap + h <= vh - m) below = true; var top = below ? r.bottom + gap : r.top - gap - h; // a wide element (a row, a long field): the arrow points where the pointer is var cx = r.left + r.width / 2; if (r.width > 220 && _mbuTip.mx >= r.left && _mbuTip.mx <= r.right) cx = _mbuTip.mx; var left = Math.max(m, Math.min(vw - w - m, Math.round(cx - w / 2))); t.style.left = left + 'px'; t.style.top = Math.max(m, Math.round(top)) + 'px'; t.style.setProperty('--mbu-tip-ax', Math.max(12, Math.min(w - 12, Math.round(cx - left))) + 'px'); t.classList.toggle('mbu-tip-up', !below); } function mbuTipShow(found) { var _mbuTip = mbuTipS(); clearTimeout(_mbuTip.hideT); clearTimeout(_mbuTip.showT); if (_mbuTip.cur && _mbuTip.cur !== found.el) mbuTipHide(true); mbuTipCss(); _mbuTip.cur = found.el; _mbuTip.curOpts = { fn: found.fn, interactive: !!found.opts.interactive, card: !!found.opts.card, wide: !!found.opts.wide, place: found.opts.place }; if (!mbuTipRender()) { _mbuTip.cur = null; return; } var t = mbuTipEl(); found.el.setAttribute('aria-describedby', 'mbu-tip'); // next frame, so the transition runs from the hidden state requestAnimationFrame(function () { if (_mbuTip.cur === found.el) t.classList.add('mbu-tip-on'); }); // the element can go (a re-render) or change its text while the tip is up clearInterval(_mbuTip.liveT); _mbuTip.liveT = setInterval(function () { if (!_mbuTip.cur || !_mbuTip.cur.isConnected) mbuTipHide(true); }, 300); try { if (!_mbuTip.obs) _mbuTip.obs = new MutationObserver(function (ms) { // a repaint that sets the same text again changes nothing if (!_mbuTip.cur || ms.every(function (m) { return m.oldValue === _mbuTip.cur.getAttribute('data-tip'); })) return; if (!mbuTipRender()) mbuTipHide(true); }); _mbuTip.obs.disconnect(); if (!found.fn) _mbuTip.obs.observe(found.el, { attributes: true, attributeOldValue: true, attributeFilter: ['data-tip'] }); } catch (e) { /* no observer: the text is read again on the next hover */ } } function mbuTipHide(now) { var _mbuTip = mbuTipS(); clearTimeout(_mbuTip.showT); clearTimeout(_mbuTip.hideT); _mbuTip.pend = null; var hide = function () { var a = _mbuTip.cur; if (!a) return; _mbuTip.cur = null; clearInterval(_mbuTip.liveT); try { if (_mbuTip.obs) _mbuTip.obs.disconnect(); } catch (e) { /* gone */ } if (a.getAttribute('aria-describedby') === 'mbu-tip') a.removeAttribute('aria-describedby'); var t = document.getElementById('mbu-tip'); if (t && t.getAttribute('data-owner') === _mbuTip.me) t.classList.remove('mbu-tip-on'); _mbuTip.warm = Date.now(); }; if (now) hide(); else _mbuTip.hideT = setTimeout(hide, _mbuTip.curOpts && _mbuTip.curOpts.interactive ? 220 : 70); } function mbuTipStart() { if (mbuTipStart.done || typeof document === 'undefined') return; var _mbuTip = mbuTipS(); var root = document.documentElement; if (!root) { document.addEventListener('DOMContentLoaded', mbuTipStart, { once: true }); return; } mbuTipStart.done = true; if (!root.hasAttribute('data-mbu-tip')) { root.setAttribute('data-mbu-tip', _mbuTip.me); _mbuTip.lead = true; } var inTip = function (n) { var t = document.getElementById('mbu-tip'); return !!(t && n && t.contains(n)); }; window.addEventListener('mousemove', function (e) { _mbuTip.mx = e.clientX; _mbuTip.my = e.clientY; }, { passive: true, capture: true }); window.addEventListener('mouseover', function (e) { _mbuTip.mx = e.clientX; _mbuTip.my = e.clientY; _mbuTip.over = e.target; // :hover can read false in a page that has not seen a real move if (inTip(e.target)) { if (_mbuTip.cur) clearTimeout(_mbuTip.hideT); return; } var f = mbuTipFind(e.target); if (!f) { if (_mbuTip.cur && !_mbuTip.cur.contains(e.target)) mbuTipHide(); return; } if (f.el === _mbuTip.cur) { clearTimeout(_mbuTip.hideT); return; } if (f.el === _mbuTip.quiet || (_mbuTip.pend && _mbuTip.pend.el === f.el)) return; clearTimeout(_mbuTip.showT); _mbuTip.pend = f; var warm = _mbuTip.cur || Date.now() - _mbuTip.warm < 450; _mbuTip.showT = setTimeout(function () { _mbuTip.pend = null; if (f.el.isConnected && f.el.contains(_mbuTip.over)) mbuTipShow(f); }, warm ? 40 : (f.opts.delay != null ? f.opts.delay : 350)); }, true); window.addEventListener('mouseout', function (e) { var to = e.relatedTarget; var q = _mbuTip.quiet; if (q && q.contains(e.target) && !(to && q.contains(to))) _mbuTip.quiet = null; var p = _mbuTip.pend; if (p && p.el.contains(e.target) && !(to && p.el.contains(to))) { clearTimeout(_mbuTip.showT); _mbuTip.pend = null; } var a = _mbuTip.cur; if (!a) return; if (to && (a.contains(to) || (_mbuTip.curOpts.interactive && inTip(to)))) return; if (a.contains(e.target) || inTip(e.target)) mbuTipHide(); }, true); window.addEventListener('mousedown', function (e) { if (inTip(e.target)) return; clearTimeout(_mbuTip.showT); _mbuTip.pend = null; var f = mbuTipFind(e.target); _mbuTip.quiet = f ? f.el : null; // no tip again on the element just clicked until the pointer leaves it _mbuTip.tab = false; if (_mbuTip.cur) mbuTipHide(true); }, true); document.addEventListener('keydown', function (e) { if (!/^(Shift|Control|Alt|Meta|CapsLock)$/.test(e.key)) _mbuTip.tab = e.key === 'Tab'; if (!_mbuTip.cur) return; var interactive = _mbuTip.curOpts && _mbuTip.curOpts.interactive; // typing closes a plain tip, as it does the browser's; modifiers alone don't if (e.key !== 'Escape') { if (!interactive && !/^(Shift|Control|Alt|Meta|CapsLock)$/.test(e.key)) mbuTipHide(true); return; } mbuTipHide(true); if (interactive) e.stopPropagation(); // a card is a popover: Esc closes it and nothing else }, true); // only a scroll that moves the element: a panel repainting elsewhere leaves the tip where it is window.addEventListener('scroll', function (e) { if (_mbuTip.cur && !inTip(e.target) && e.target.contains(_mbuTip.cur)) mbuTipHide(true); }, true); window.addEventListener('blur', function () { if (_mbuTip.cur) mbuTipHide(true); }); document.addEventListener('focusin', function (e) { var el = e.target, vis = false; try { vis = el.matches(':focus-visible'); } catch (x) { /* old browser */ } // a text box is :focus-visible even when a script focuses it (a picker opening), so only Tab's focus shows the tip if (!vis || !_mbuTip.tab) return; var f = mbuTipFind(el); if (f && f.el === el) { clearTimeout(_mbuTip.showT); _mbuTip.showT = setTimeout(function () { if (document.activeElement === el) mbuTipShow(f); }, 150); } }, true); document.addEventListener('focusout', function (e) { if (_mbuTip.cur && _mbuTip.cur === e.target && !(e.relatedTarget && inTip(e.relatedTarget))) mbuTipHide(); }, true); } mbuTipStart(); // </ST-TIP> // From the manager (String Theory shadows GM_info per script, so this is Scribe's own // @version in the bundle too). The literal is only a fallback — it was the ONLY source // before, and had fallen behind: the window title said v2026.7.24 on a 2026.7.29 build. const VERSION = (() => { try { return (typeof GM_info !== 'undefined' && GM_info.script && GM_info.script.version) || '?'; } catch (e) { return '?'; } })(); // GM_info carries the real one; every script manager provides it (a hard-coded copy only ever went stale) const NAME = 'Scribe'; // [ … ] reference-link brackets around a quill nib (currentColor — sits on the dark launcher/panel) // the corner launcher wears the script's own icon (the same picture as @icon), like the other launchers const ICON_URL = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMjggMTI4Ij48cGF0aCBkPSJNNDYgMjQgTDI2IDI0IEwyNiAxMDQgTDQ2IDEwNCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMmY2ZjU0IiBzdHJva2Utd2lkdGg9IjkiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPjxwYXRoIGQ9Ik04MiAyNCBMMTAyIDI0IEwxMDIgMTA0IEw4MiAxMDQiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzJmNmY1NCIgc3Ryb2tlLXdpZHRoPSI5IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNNjQgNDAgTDUxIDY2IEw2NCA5NCBMNzcgNjYgWiIgZmlsbD0iIzJlOWU1YiIgc3Ryb2tlPSIjMmY2ZjU0IiBzdHJva2Utd2lkdGg9IjQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48bGluZSB4MT0iNjQiIHkxPSI3NCIgeDI9IjY0IiB5Mj0iOTIiIHN0cm9rZT0iI2ZmZmZmZiIgc3Ryb2tlLXdpZHRoPSIzLjUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIvPjwvc3ZnPg=='; const SCRIBE_ICON = '<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8.5 4 L5 4 L5 20 L8.5 20"/><path d="M15.5 4 L19 4 L19 20 L15.5 20"/><path d="M12 7.5 L9.6 12.5 L12 17.5 L14.4 12.5 Z" fill="currentColor" stroke="none"/></svg>'; // the PAGE window (MB.releaseEditor lives here); a userscript sandbox `window` is isolated, // so reach the editor model via unsafeWindow (same as Apollo). Falls back to window for tests. const W = (typeof unsafeWindow !== 'undefined' ? unsafeWindow : window); /* ── shared corner-slot convention (#468) ─────────────────────────────── Every floating launcher across these scripts (Apollo Editor, Art Station, Scribe, Falcon) tags its element with data-mb-corner (which screen corner) + data-mb-corner-order (priority — lower sits closest to the actual corner) and calls mbRestackCorner() right after it shows / hides / creates / removes its own element. No MutationObserver needed: whichever script's state just changed triggers a full recompute that repositions every element sharing that corner, regardless of load order — so two independent scripts' buttons never land on the same pixel. The other scripts share it through the ST-UI block (dev/ui/ui-components.mjs); Scribe is not on that block, so this is a copy. */ function mbRestackCorner(corner) { const bottom = corner[0] === 'b'; const els = [...document.querySelectorAll('[data-mb-corner="' + corner + '"]')] .filter(el => getComputedStyle(el).display !== 'none') // offsetParent is always null for position:fixed — not a usable visibility check here .sort((a, b) => (Number(a.dataset.mbCornerOrder) || 0) - (Number(b.dataset.mbCornerOrder) || 0)); // the shared setting cornerFlow = 'row' (the page's localStorage 'mbu.cornerFlow', set from String // Theory's menu; mbuShared in dev/ui/ui-components.mjs) lines the stack up along the edge instead // and cornerSide = 'left' mirrors the corner across the screen ('br' sits bottom-left) let row = false, left = false; try { row = JSON.parse(localStorage.getItem('mbu.cornerFlow')) === 'row'; left = JSON.parse(localStorage.getItem('mbu.cornerSide')) === 'left'; } catch (e) { /* storage blocked */ } const right = (corner[1] === 'r') !== left; let pos = 14; els.forEach(el => { const r = el.getBoundingClientRect(); el.style[bottom ? 'bottom' : 'top'] = (row ? 14 : pos) + 'px'; el.style[right ? 'right' : 'left'] = (row ? pos : 14) + 'px'; el.style[right ? 'left' : 'right'] = 'auto'; pos += (row ? r.width : r.height) + 8; }); } // ── settings (shared defaults with the field-bridge EE) ─────────────────── const cfg = { get port() { return GM_getValue('ee_port', 17999); }, get token() { return GM_getValue('ee_token', 'extedit'); }, }; const base = () => `http://127.0.0.1:${cfg.port}`; const gm = opts => new Promise((res, rej) => mbnGm({ method: opts.method || 'GET', url: opts.url, data: opts.data, timeout: opts.timeout || 30000, headers: Object.assign({ 'X-ExtEdit-Token': cfg.token }, opts.headers || {}), onload: r => res(r), onerror: () => rej(new Error('network')), ontimeout: () => rej(new Error('timeout')), })); const ping = async () => { try { return (await gm({ url: base() + '/ping', timeout: 4000 })).status === 200; } catch (e) { return false; } }; const sleep = ms => new Promise(z => setTimeout(z, ms)); // bottom-right session window: ONE table of the fields changed this session — errored fields // first (each with a ⌖ "go to field" button) then applied changes — with an error-count badge // in the header. ✕ stops editing (closes the session). No other chatter. let panel = null, bodyEl = null, badgeEl = null, tblEl = null, collapsed = false; const trunc = (s, n) => { s = String(s == null ? '' : s).replace(/\n+/g, ' '); n = n || 30; return s.length > n + 2 ? s.slice(0, n) + '…' : s; }; function ensurePanel() { if (panel) return; panel = document.createElement('div'); panel.id = 'scribe-panel'; panel.style.cssText = 'position:fixed;z-index:2147483647;right:12px;bottom:12px;width:360px;max-width:48vw;background:#222c27;color:#e7ece9;border-radius:9px;font:12px -apple-system,Segoe UI,Arial,sans-serif;box-shadow:0 6px 22px rgba(0,0,0,.4);overflow:hidden'; const hdr = document.createElement('div'); // Colour spelled out on the header AND each of its text elements (#564 lesson): dark // userstyles ship `div[style*=background]{color:initial}`, which turns this header's // inherited colour black in Firefox — the title and –/✕ went black-on-dark-green. hdr.style.cssText = 'display:flex;align-items:center;gap:6px;padding:7px 10px;background:#1b2520;color:#e7ece9;cursor:move;user-select:none'; const ic = document.createElement('span'); ic.innerHTML = SCRIBE_ICON; ic.style.cssText = 'display:flex;color:#6cc08a'; const ttl = document.createElement('span'); ttl.textContent = `${NAME} v${VERSION}`; ttl.style.cssText = 'flex:1;font-weight:700;letter-spacing:.2px;color:#e7ece9'; badgeEl = document.createElement('span'); badgeEl.dataset.tip = 'Fields not applied to the page'; badgeEl.style.cssText = 'display:none;background:#c0392b;color:#fff;font-weight:700;font-size:10px;border-radius:9px;padding:1px 7px;min-width:12px;text-align:center'; const col = document.createElement('span'); col.textContent = '–'; col.dataset.tip = 'Collapse'; col.style.cssText = 'padding:0 7px;cursor:pointer;font-weight:700;color:#e7ece9'; const cls = document.createElement('span'); cls.textContent = '✕'; cls.dataset.tip = 'Stop editing this release'; cls.style.cssText = 'padding:0 4px;cursor:pointer;color:#e7ece9'; hdr.append(ic, ttl, badgeEl, col, cls); bodyEl = document.createElement('div'); tblEl = document.createElement('div'); tblEl.style.cssText = 'max-height:60vh;overflow:auto'; bodyEl.append(tblEl); panel.append(hdr, bodyEl); document.body.appendChild(panel); const setCol = c => { collapsed = c; bodyEl.style.display = c ? 'none' : ''; col.textContent = c ? '+' : '–'; col.dataset.tip = c ? 'Expand' : 'Collapse'; }; cls.onclick = e => { e.stopPropagation(); stopSession(); }; // ✕ = stop editing (and close the window) let dragging = false, moved = false, dx = 0, dy = 0; hdr.addEventListener('mousedown', e => { if (e.target === cls || e.target === col) return; dragging = true; moved = false; const r = panel.getBoundingClientRect(); dx = e.clientX - r.left; dy = e.clientY - r.top; e.preventDefault(); }); window.addEventListener('mousemove', e => { if (!dragging) return; moved = true; panel.style.right = 'auto'; panel.style.bottom = 'auto'; panel.style.left = Math.max(0, Math.min(window.innerWidth - 40, e.clientX - dx)) + 'px'; panel.style.top = Math.max(0, Math.min(window.innerHeight - 24, e.clientY - dy)) + 'px'; }); window.addEventListener('mouseup', () => { dragging = false; }); hdr.onclick = e => { if (e.target === cls) return; if (moved) { moved = false; return; } setCol(!collapsed); }; // re-render when MusicBrainz's own validation state flips (reliable observable — no DOM polling) try { const ee = W.MB.releaseEditor.validation.errorsExist; if (ee && ee.subscribe) ee.subscribe(() => { if (session && session.active && !collapsed) renderSession(); }); } catch (e) {} } // the window sits bottom-right, beside the corner launchers (Scribe's own among them), not over them: // left of a column of them, above a row; with the launchers on the left (cornerSide), it's bottom-left function placePanel() { const els = [...document.querySelectorAll('[data-mb-corner="br"]')].filter(e => getComputedStyle(e).display !== 'none').map(e => e.getBoundingClientRect()); let row = false, left = false; try { row = JSON.parse(localStorage.getItem('mbu.cornerFlow')) === 'row'; left = JSON.parse(localStorage.getItem('mbu.cornerSide')) === 'left'; } catch (e) { /* storage blocked */ } const side = (!els.length || row ? 12 : Math.round(left ? Math.max(...els.map(r => r.right)) : innerWidth - Math.min(...els.map(r => r.left))) + 8) + 'px'; panel.style[left ? 'left' : 'right'] = side; panel.style[left ? 'right' : 'left'] = 'auto'; panel.style.bottom = (!els.length || !row ? 12 : Math.round(innerHeight - Math.min(...els.map(r => r.top))) + 8) + 'px'; } function showPanel() { ensurePanel(); panel.style.display = ''; placePanel(); } // bring the editor window to the front so a flagged value can be fixed function reopenEditor() { if (session && session.active) gm({ method: 'POST', url: base() + '/open', headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({ id: session.id }) }).catch(() => {}); } // scroll to + focus + briefly highlight a native MB field (the error row's "go to field" action) function focusNative(target) { const el = typeof target === 'string' ? document.querySelector(target) : target; if (!el) return; try { el.scrollIntoView({ block: 'center', behavior: 'smooth' }); } catch (e) {} try { (el.focus ? el : el.querySelector('input,select,textarea,button')).focus(); } catch (e) {} const prev = el.style.boxShadow; el.style.boxShadow = '0 0 0 3px #e53935'; setTimeout(() => { try { el.style.boxShadow = prev; } catch (e) {} }, 1600); } const sectionHead = (text, kind) => { const h = document.createElement('div'); h.textContent = text; h.style.cssText = 'padding:5px 10px;font-weight:700;font-size:11px;position:sticky;top:0;' + (kind === 'err' ? 'color:#ffd9d4;background:#5e2520' : 'color:#cfeedd;background:#21492f'); return h; }; // MusicBrainz's own validation state. The editor always renders EVERY error row (collapsing the // inactive ones), so scraping the DOM yields false positives ("A release title is required" while a // title exists). The model exposes a reliable boolean instead — surface THAT (the page itself marks // the offending field in red); we don't guess the individual messages. const mbHasErrors = () => { try { return !!W.MB.releaseEditor.validation.errorsExist(); } catch (e) { return false; } }; // render the session table from session.changed (accumulated applied) + session.problems (current) function renderSession(placeholder) { ensurePanel(); panel.style.display = ''; tblEl.innerHTML = ''; const problems = (session && session.problems) || []; const changed = (session && session.changed) || new Map(); const mbErr = mbHasErrors(); const errCount = problems.length + (mbErr ? 1 : 0); badgeEl.style.display = errCount ? '' : 'none'; badgeEl.textContent = String(errCount); if (mbErr) { tblEl.appendChild(sectionHead('⚠ MusicBrainz validation errors', 'err')); const row = document.createElement('div'); row.style.cssText = 'padding:5px 10px;background:#3a2420;border-top:1px solid #4a302c;color:#ffd9d4;line-height:1.35;font-size:11px'; row.textContent = 'The form has errors and won’t submit — the offending fields are marked in red on the page.'; tblEl.appendChild(row); } if (problems.length) { tblEl.appendChild(sectionHead(`⚠ ${problems.length} not applied — fix & save`, 'err')); for (const p of problems) { const row = document.createElement('div'); row.style.cssText = 'display:flex;align-items:center;gap:6px;padding:3px 10px;background:#3a2420;border-top:1px solid #4a302c;color:#ffd9d4'; const f = document.createElement('span'); f.textContent = p.field; f.dataset.tip = p.field; f.style.cssText = 'flex:0 0 40%;color:#e7c9c4;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap'; const v = document.createElement('span'); v.textContent = p.value == null || p.value === '' ? '(empty)' : p.value; v.dataset.tip = v.textContent; v.style.cssText = 'flex:1;color:#ffd9d4;overflow:hidden;text-overflow:ellipsis;white-space:nowrap'; const b = document.createElement('button'); b.textContent = '⌖'; b.dataset.tip = 'Focus this field in MusicBrainz to fix it'; b.style.cssText = 'flex:0 0 auto;cursor:pointer;background:#6b3a34;color:#fff;border:none;border-radius:4px;padding:1px 7px;font-size:12px'; b.onclick = () => (p.focus || reopenEditor)(); row.append(f, v, b); tblEl.appendChild(row); } } if (changed.size) { tblEl.appendChild(sectionHead(`✓ ${changed.size} changed — review & submit`, 'ok')); for (const [field, c] of changed) { const row = document.createElement('div'); row.style.cssText = 'display:flex;align-items:center;gap:6px;padding:3px 10px;border-top:1px solid rgba(255,255,255,.05)'; const f = document.createElement('span'); f.textContent = field; f.dataset.tip = field; f.style.cssText = 'flex:0 0 40%;color:#bfe9cf;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap'; const v = document.createElement('span'); v.textContent = `${trunc(c.from)} → ${trunc(c.to)}`; v.dataset.tip = `${c.from} → ${c.to}`; v.style.cssText = 'flex:1;color:#e7ece9;overflow:hidden;text-overflow:ellipsis;white-space:nowrap'; row.append(f, v); tblEl.appendChild(row); } } if (!problems.length && !changed.size && !mbErr) { const ph = document.createElement('div'); ph.textContent = placeholder || 'Editing — save in your editor to apply.'; ph.style.cssText = 'padding:8px 10px;color:#9aa8a1;font-size:11px'; tblEl.appendChild(ph); } } // ════════════════════ release ⇄ markdown lib ════════════════════ const LANG = { eng: 'English', deu: 'German', fra: 'French', spa: 'Spanish', jpn: 'Japanese', ita: 'Italian', por: 'Portuguese', rus: 'Russian', mul: '[Multiple languages]', zxx: '[No linguistic content]' }; // bracketed names match the editor's <select> option text exactly const SCRIPT = { Latn: 'Latin', Cyrl: 'Cyrillic', Jpan: 'Japanese', Hani: 'Han', Kore: 'Korean', Grek: 'Greek' }; const HOST = [[/discogs\.com/, 'Discogs'], [/bandcamp\.com/, 'Bandcamp'], [/open\.spotify|spotify\.com/, 'Spotify'], [/music\.apple\.com/, 'Apple Music'], [/deezer\.com/, 'Deezer'], [/youtube\.com|youtu\.be/, 'YouTube'], [/tidal\.com/, 'Tidal'], [/qobuz\.com/, 'Qobuz']]; const MBROOT = 'https://musicbrainz.org'; const esc = s => String(s == null ? '' : s).replace(/\\/g, '\\\\').replace(/[\[\]]/g, '\\$&'); const escTitle = s => esc(s).replace(/ — /g, ' \\— '); const unesc = s => String(s == null ? '' : s).replace(/\\(.)/g, '$1'); const norm = s => String(s || '').toLowerCase().replace(/[^a-z0-9]/g, ''); // #623 (sweep, S3): round the TOTAL first — 239.6 s is 4:00, not 3:60 — and show // hours the way MusicBrainz does (1:02:03, not 62:03). Anything else differs from the // editor's own value, so every save reported (and wrote) length changes. function ms2len(ms) { if (!ms) return ''; const t = Math.round(ms / 1000), h = Math.floor(t / 3600), m = Math.floor(t % 3600 / 60), s = String(t % 60).padStart(2, '0'); return h ? `${h}:${String(m).padStart(2, '0')}:${s}` : `${m}:${s}`; } const hostName = u => { for (const [re, n] of HOST) if (re.test(u)) return n; try { return new URL(u).host.replace(/^www\./, ''); } catch (e) { return u; } }; const mbidFromUrl = u => (String(u).match(/\/([0-9a-f-]{36})\b/i) || [])[1] || null; function makeRefs() { const map = new Map(); function ref(display, url, main) { let key = display || main || url, n = 1; while (map.has(key) && map.get(key).url !== url) { n++; key = `${display}·${n}`; } map.set(key, { url, main: main || display }); return key; } return { map, ref }; } const ws2Credit = (ac, R) => ({ lead: '', parts: (ac || []).map(n => ({ label: n.artist ? R.ref(n.name, `${MBROOT}/artist/${n.artist.id}`, n.artist.name) : n.name, join: n.joinphrase || '' })) }); const emitCredit = c => (c.lead || '') + (c.parts || []).map(p => `[${esc(p.label)}]${p.join}`).join(''); function parseCredit(str) { const parts = []; let lead = '', last = 0; const re = /\[((?:\\.|[^\]])*)\]/g; let m, first = true; while ((m = re.exec(str))) { const between = str.slice(last, m.index); if (first) { lead = between; first = false; } else if (parts.length) parts[parts.length - 1].join = between; parts.push({ label: unesc(m[1]), join: '' }); last = re.lastIndex; } if (parts.length) parts[parts.length - 1].join = str.slice(last); else lead = str; return { lead, parts }; } function toModel(r) { const R = makeRefs(); const trep = r['text-representation'] || {}; const entRef = (type, ent, credited) => ent ? R.ref(credited || ent.name || ent.title, `${MBROOT}/${type}/${ent.id}`, ent.name || ent.title) : null; const m = { mbid: r.id, h1: `${(r['artist-credit'] || []).map(a => a.name).join(', ')} — ${r.title}`, info: { title: r.title, disambiguation: r.disambiguation || '', status: r.status || '', packaging: r.packaging || '', barcode: r.barcode || 'none', language: LANG[trep.language] || trep.language || '', script: SCRIPT[trep.script] || trep.script || '', artist: ws2Credit(r['artist-credit'], R), releaseGroup: r['release-group'] ? entRef('release-group', r['release-group']) : null }, events: (r['release-events'] || []).map(ev => ({ date: ev.date || '', country: ev.area ? ev.area.name : '' })), labels: (r['label-info'] || []).map(li => ({ label: li.label ? entRef('label', li.label) : null, catno: li['catalog-number'] || '' })), annotation: (r.annotation || '').trim(), links: (r.relations || []).filter(x => x['target-type'] === 'url').map(rel => { const url = rel.url.resource, host = hostName(url), t = norm(rel.type), h = norm(host), tok = s => (String(s).toLowerCase().match(/[a-z0-9]+/) || [''])[0]; const overlap = (t && h && (t.includes(h) || h.includes(t))) || (tok(host) && tok(host) === tok(rel.type)); return { label: host, url, type: (rel.type && !overlap) ? rel.type : '', begin: rel.begin || '', end: rel.end || '', ended: !!rel.ended }; }), // inline [host](url); suppress a type that just echoes the host (discogs/discogs, amazon.co.uk/"amazon asin") media: (r.media || []).map(med => ({ position: med.position, format: med.format || '', title: med.title || '', tracks: (med.tracks || []).map(t => ({ position: t.position, title: t.title, credit: ws2Credit(t['artist-credit'], R), length: t.length ? ms2len(t.length) : '', recording: entRef('recording', t.recording) })) })), refs: R.map, }; return m; } // Build the SAME model as toModel, but from the LIVE release-editor state (KO observables) instead of // WS2 — used on /release/add (no saved release, no MBID) once the form is structurally set up. function modelFromEditor() { const ed = W.MB && W.MB.releaseEditor; if (!ed) throw new Error('release editor not ready'); const rel = ed.rootField.release(); if (!rel) throw new Error('no release in the editor'); const R = makeRefs(); const selText = fid => { const s = [...document.querySelectorAll('select')].find(x => (x.getAttribute('data-bind') || '').includes('value: ' + fid)); return s && s.selectedIndex >= 0 ? (s.options[s.selectedIndex].textContent || '').trim() : ''; }; const linked = (kind, id) => { try { return (W.MB.linkedEntities[kind][id] || {}).name || ''; } catch (e) { return ''; } }; const fmtDate = d => { if (!d) return ''; const y = u(d.year), mo = u(d.month), da = u(d.day); return (y ? '' + y : '') + (mo ? '-' + String(mo).padStart(2, '0') : '') + (da ? '-' + String(da).padStart(2, '0') : ''); }; const cred = acObs => { const ac = u(acObs) || {}; return { lead: '', parts: (ac.names || []).map(n => { const g = gidOf(n.artist); const an = n.artist ? (u(n.artist.name) || '') : ''; const cr = u(n.name) || an; if (!cr && !g) return null; return { label: g ? R.ref(cr, `${MBROOT}/artist/${g}`, an) : cr, join: u(n.joinPhrase) || '' }; }).filter(Boolean) }; }; const recRef = rec => { const g = gidOf(rec); return g ? R.ref(u(rec.name) || '', `${MBROOT}/recording/${g}`, u(rec.name) || '') : null; }; const names = ((u(rel.artistCredit) || {}).names) || []; const artistNames = names.map(n => (u(n.name) || (n.artist && u(n.artist.name)) || '') + (u(n.joinPhrase) || '')).join('').trim(); const title = u(rel.name) || ''; return { mbid: null, h1: `${artistNames} — ${title}`, info: { title, disambiguation: u(rel.comment) || '', status: selText('statusID'), packaging: selText('packagingID'), barcode: ((rel.barcode && typeof rel.barcode.value === 'function' ? (u(rel.barcode.value) || '') : '')) || 'none', language: selText('languageID'), script: selText('scriptID'), artist: cred(rel.artistCredit), releaseGroup: null }, events: ((typeof rel.events === 'function' && rel.events()) || []).map(ev => ({ date: fmtDate(u(ev.date)), country: linked('area', u(ev.countryID)) })), labels: ((typeof rel.labels === 'function' && rel.labels()) || []).map(li => { const lab = u(li.label), g = gidOf(lab); return { label: g ? R.ref(u(lab.name) || '', `${MBROOT}/label/${g}`, u(lab.name) || '') : null, catno: u(li.catalogNumber) || '' }; }), annotation: (u(rel.annotation) || '').trim(), links: [], media: (rel.mediums() || []).map(med => ({ position: u(med.position), format: linked('medium_format', u(med.formatID)), title: u(med.name) || '', tracks: (med.tracks() || []).map(t => ({ position: u(t.position), title: u(t.name) || '', credit: cred(t.artistCredit), length: u(t.formattedLength) || '', recording: recRef(u(t.recording)) })) })), refs: R.map, }; } function emit(m) { const L = [], P = (...x) => L.push(...x), i = m.info; P(`# ${esc(m.h1)}`, '', `<!-- release ${m.mbid} · format v1 · DO NOT EDIT THIS LINE -->`, ''); // H1 is display-only (never split) — no need to escape the — delimiter here P('## Release information', ''); // blank line after every section header (header ↕ body) // order: Title · Artist · Release group · Status · Language · Script · Barcode · Packaging · Disambiguation P(`- **Title**: ${esc(i.title)}`, `- **Artist**: ${emitCredit(i.artist)}`); if (i.releaseGroup) P(`- **Release group**: [${esc(i.releaseGroup)}]`); // enum values are controlled vocab whose canonical names can include brackets ([Multiple languages]); // a field value parses whole (brackets don't break it), so emit them unescaped to match the <select> text P(`- **Status**: ${i.status}`, `- **Language**: ${i.language}`, `- **Script**: ${i.script}`, `- **Barcode**: ${i.barcode}`, `- **Packaging**: ${i.packaging}`, `- **Disambiguation**: ${esc(i.disambiguation)}`); // always emit Disambiguation (even empty) so it can be filled in P('', '### Release events', ''); for (const e of m.events) P(`- ${[e.date, esc(e.country)].filter(Boolean).join(', ')}`); P('', '### Labels', ''); for (const l of m.labels) P(`- ${l.label ? `[${esc(l.label)}]` : ''}${l.catno ? ' — ' + esc(l.catno) : ''}`); P('', '### Annotation', '', m.annotation, '<!-- /end -->', '', '### External links', '<!-- NOT applied: links round-trip but are not written back yet — add/edit/reorder links in the native editor -->', ''); for (const lk of m.links) { P(`- [${esc(lk.label)}](${lk.url || ''})`); let dr = ''; if (lk.begin || lk.end) dr = `${lk.begin} → ${lk.end}`.trim(); if (lk.ended && !lk.end) dr = (dr ? dr + ' · ' : '') + 'ended'; const parts = [lk.type || null, dr].filter(Boolean); if (parts.length) P(` - ${parts.join(' · ')}`); } P('', '## Tracklist', '', '<!-- track titles, lengths & artists apply; adding/removing/reordering tracks does NOT — do structural changes in the native editor -->', ''); for (const med of m.media) { P(`### Medium ${med.position}${med.format ? ' — ' + esc(med.format) : ''}${med.title ? ' — ' + esc(med.title) : ''}`, ''); for (const t of med.tracks) { const tail = [emitCredit(t.credit), t.length ? `(${t.length})` : ''].filter(Boolean).join(' '); const rec = t.recording ? ' → [' + esc(t.recording) + ']' : ''; P(`${t.position}. ${escTitle(t.title)}${(tail || rec) ? ' — ' + tail + rec : ''}`); } P(''); } P('<!-- references -->'); for (const [lbl, v] of m.refs) P(`[${esc(lbl)}]: ${v.url}${v.main && v.main !== lbl ? ' (' + v.main + ')' : ''}`); return L.join('\n'); } const splitDelim = s => { const m = s.match(/(^|[^\\]) — /); if (!m) return [s, null]; const at = m.index + m[1].length; return [s.slice(0, at), s.slice(at + 3)]; }; // #623 (sweep, S2): an event is emitted as "- <date>, <country>" with either part left // out, so "- Germany" is a country-only event — but the parser took the first comma // part as the date, and a save cleared the country of every date-less event. Read it // by shape: a leading date (YYYY, YYYY-MM, YYYY-MM-DD, or -MM-DD when the year is // unknown) is the date, the rest is the country, which may contain ", " itself. function parseEvent(s) { const m = String(s).match(/^(\d{4}(?:-\d{1,2}){0,2}|(?:-\d{1,2}){1,2})(?:, (.*))?$/); return m ? { date: m[1], country: unesc(m[2] || '') } : { date: '', country: unesc(s) }; } function parse(md) { const lines = md.split('\n'); const m = { mbid: null, h1: '', info: {}, events: [], labels: [], annotation: '', links: [], media: [], refs: new Map() }; const idm = md.match(/<!-- release (\S+) · format/); if (idm) m.mbid = idm[1]; for (const ln of lines) { const r = ln.match(/^\[((?:\\.|[^\]])*)\]:\s+(\S+)(?:\s+\((.*)\))?\s*$/); if (r) m.refs.set(unesc(r[1]), { url: r[2], main: r[3] != null ? r[3] : unesc(r[1]) }); } const field = s => { const r = s.match(/^- \*\*[^*]+\*\*:\s?(.*)$/); return r ? r[1] : null; }; const reflbl = s => { const r = (s || '').match(/^\[((?:\\.|[^\]])*)\]$/); return r ? unesc(r[1]) : null; }; let sec = '', med = null; for (let k = 0; k < lines.length; k++) { let ln = lines[k]; if (/^# /.test(ln)) { m.h1 = unesc(ln.slice(2)); continue; } let mh = ln.match(/^### Medium (\d+)(?: — (.*))?$/); if (mh) { const rest = mh[2] || '', dash = rest.indexOf(' — '); med = { position: +mh[1], format: dash >= 0 ? unesc(rest.slice(0, dash)) : unesc(rest), title: dash >= 0 ? unesc(rest.slice(dash + 3)) : '', tracks: [] }; m.media.push(med); continue; } // check medium BEFORE the generic ## / ### section header let h = ln.match(/^#{2,3} (.+)/); if (h) { sec = h[1].trim(); med = null; if (sec === 'Annotation') { const body = []; k++; while (k < lines.length && lines[k].trim() !== '<!-- /end -->') body.push(lines[k++]); m.annotation = body.join('\n').replace(/^\n+|\n+$/g, ''); } continue; } // ## Release information / ## Tracklist, and ### Release events|Labels|Annotation|External links if (sec === 'Release information') { const v = field(ln); if (v == null) continue; const key = (ln.match(/\*\*([^*]+)\*\*/) || [])[1]; if (key === 'Title') m.info.title = unesc(v); else if (key === 'Disambiguation') m.info.disambiguation = unesc(v); else if (key === 'Status') m.info.status = unesc(v); else if (key === 'Packaging') m.info.packaging = unesc(v); else if (key === 'Barcode') m.info.barcode = v; else if (key === 'Language') m.info.language = unesc(v); else if (key === 'Script') m.info.script = unesc(v); else if (key === 'Artist') m.info.artist = parseCredit(v); else if (key === 'Release group') m.info.releaseGroup = reflbl(v); } else if (sec === 'Release events') { const r = ln.match(/^- (.*)$/); if (r) m.events.push(parseEvent(r[1])); } else if (sec === 'Labels') { const r = ln.match(/^- (.*)$/); if (r) { const sp = splitDelim(r[1]); m.labels.push({ label: reflbl(sp[0]), catno: sp[1] ? unesc(sp[1]) : '' }); } } else if (sec === 'External links') { let r = ln.match(/^- \[((?:\\.|[^\]])*)\](?:\(([^)]*)\))?\s*$/); if (r) { m.links.push({ label: unesc(r[1]), url: (r[2] || '').trim(), type: '', begin: '', end: '', ended: false }); continue; } // [label](url) inline notation (url optional) let a = ln.match(/^ - (.*)$/); if (a && m.links.length) { const lk = m.links[m.links.length - 1]; for (const s of a[1].split(' · ')) { const dm = s.match(/^(\S*) → (\S*)$/); if (dm) { lk.begin = dm[1]; lk.end = dm[2]; } else if (s === 'ended') lk.ended = true; else lk.type = s; } } } else if (med && /^\d+\. /.test(ln)) { const r = ln.match(/^(\d+)\. (.*)$/); let [titlePart, rest] = splitDelim(r[2]); const t = { position: +r[1], title: unesc(titlePart.replace(/\s+$/, '')), credit: { lead: '', parts: [] }, length: '', recording: null }; if (rest != null) { let recM = rest.match(/ → \[((?:\\.|[^\]])*)\]\s*$/); if (recM) { t.recording = unesc(recM[1]); rest = rest.slice(0, recM.index); } let lenM = rest.match(/\((\d?\d:\d\d(?::\d\d)?)\)\s*$/); if (lenM) { t.length = lenM[1]; rest = rest.slice(0, lenM.index); } t.credit = parseCredit(rest.replace(/\s+$/, '')); } med.tracks.push(t); } } return m; } // ════════════════════ MB page glue ════════════════════ const u = v => { try { return typeof v === 'function' ? v() : v; } catch (e) { return undefined; } }; const releaseMbid = () => (location.pathname.match(/release\/([0-9a-f-]{36})/i) || [])[1] || null; // the release EDITOR: /release/<mbid>/edit (existing) OR /release/add (new) — but NOT /edit-relationships // or /edit_annotation (the loose /edit match also fired there, esp. via the String Theory bundle's broad // @match). /release/add has no MBID, so this no longer requires one (exportMd reads the editor there). const onEditPage = () => /\/release\/(?:add|[0-9a-f-]{36}\/edit)(?![-\w])/i.test(location.pathname); async function fetchWs2(id) { const inc = 'artist-credits+labels+recordings+release-groups+url-rels+media+annotation'; const r = await mbnFetch(`/ws/2/release/${id}?inc=${inc}&fmt=json`, { headers: { Accept: 'application/json' } }); if (!r || !r.ok) throw new Error('WS2 ' + r.status); return r.json(); } // existing release → the saved WS2 data; /release/add (no MBID) → the live editor form. async function exportMd() { const id = releaseMbid(); return id ? emit(toModel(await fetchWs2(id))) : emit(modelFromEditor()); } // Apollo mirrors the model from a snapshot and doesn't observe our model writes, so nudge it // to rebuild after we apply (native MB updates on its own). No-op if Apollo isn't installed. async function refreshApollo() { const A = W.__apolloEditor; if (!A) return; try { if ('apolloOn' in A && !A.apolloOn) return; } catch (e) { return; } // Apollo is off — don't switch it on try { // nudge Apollo's Markdown annotation editor to re-read the value we just set (it syncs on // the textarea's input event, not on a programmatic ko change) const ta = document.getElementById('annotation'); if (ta) ta.dispatchEvent(new Event('input', { bubbles: true })); if (typeof A.rebuild === 'function') { await A.rebuild(true); return; } // light: rebuild model + rerender, no re-match (newer Apollo) // older Apollo: refresh its model from the editor, then re-mount the mirror so the rows // actually re-render (showMirror alone doesn't re-render an already-mounted mirror). if (typeof A.buildModel === 'function') await A.buildModel(); if (typeof A.hideMirror === 'function' && typeof A.showMirror === 'function') { A.hideMirror(); await A.showMirror(); } } catch (e) {} } // A new linked artist must be a COMPLETE entity (with MB's internal numeric id), not just {gid,name} // — otherwise MB's React artist-credit widget treats it as unresolved and drops it, leaving plain // text ("set as text only"). Fetch the full entity by gid from MB's internal endpoint and cache it. const _artistCache = new Map(); async function resolveArtist(gid) { if (!gid || _artistCache.has(gid)) return; try { const r = await mbnFetch(`/ws/js/entity/${gid}`, { headers: { accept: 'application/json' } }); if (!r.ok) return; const d = await r.json(); if (d && d.gid && d.id != null) _artistCache.set(gid, W.MB.entity(d, 'artist')); } catch (e) {} } async function resolveArtistsIn(parsed) { const gids = new Set(); const collect = pc => { for (const p of ((pc && pc.parts) || [])) { const ref = parsed.refs.get(p.label); const g = ref && mbidFromUrl(ref.url); if (g) gids.add(g); } }; collect(parsed.info && parsed.info.artist); for (const med of (parsed.media || [])) for (const t of (med.tracks || [])) collect(t.credit); await Promise.all([...gids].map(resolveArtist)); } const gidOf = art => { try { return art ? (typeof art.gid === 'function' ? art.gid() : art.gid) : null; } catch (e) { return null; } }; const creditStr = names => (names || []).map(n => (u(n.name) || '') + (u(n.joinPhrase) || '')).join('') || '(none)'; // Credit apply/diff. The artistCredit is a ko observable wrapping a plain object whose `names` // is a plain array of {name:credited-as, artist, joinPhrase}. We rebuild that array reusing the // existing artist objects (credited-as / join / reorder / drop), build entities for swap/add by // MBID, and name-only entities for brand-new artists. Records a {from,to} diff; writes only when // not `dry`. function applyCredit(acObs, pc, refs, changes, label, dry, problems) { if (!pc || typeof acObs !== 'function') return; const ac = acObs(); if (!ac || !Array.isArray(ac.names)) return; const curNames = ac.names, parts = pc.parts || []; // emptied the field but there ARE artists → can't remove (a release/track requires an artist) → flag it if (!parts.length) { // unset the credit (one empty slot, like the native "clear") — idempotent const alreadyEmpty = !curNames.length || (curNames.length === 1 && !u(curNames[0].name) && !curNames[0].artist); if (!alreadyEmpty) { changes.push({ label, from: creditStr(curNames), to: '(unset)' }); if (!dry) { try { acObs(Object.assign({}, ac, { names: [{ name: '', artist: null, joinPhrase: '' }] })); } catch (e) {} } } return; } const byGid = new Map(); curNames.forEach(n => { const g = gidOf(n.artist); if (g) byGid.set(g, n.artist); }); const desired = []; for (const p of parts) { const r = refs.get(p.label), gid = r && mbidFromUrl(r.url); let artist = gid ? (byGid.get(gid) || _artistCache.get(gid)) : null; // prefer a fully-resolved entity (has the internal id) if (!artist) { try { artist = gid ? W.MB.entity({ gid, name: r.main || p.label }, 'artist') : W.MB.entity({ name: p.label }, 'artist'); } catch (e) { problems && problems.push({ field: label, value: p.label }); return; } } if (!artist || (gid && gidOf(artist) !== gid)) { problems && problems.push({ field: label, value: p.label }); return; } desired.push({ name: p.label, artist, joinPhrase: p.join || '' }); } const sig = arr => arr.map(n => `${gidOf(n.artist) || ''}|${u(n.name) || ''}|${u(n.joinPhrase) || ''}`).join('§'); if (sig(curNames) === sig(desired)) return; changes.push({ label, from: creditStr(curNames), to: creditStr(desired) }); if (!dry) { const write = () => { try { const cur = acObs(); acObs(Object.assign({}, cur || ac, { names: desired })); } catch (e) {} }; write(); // MB's React artist-credit widget re-syncs moments later and drops freshly-built linked entities // (keeping only the credited-as text — the "set as text only" bug); re-assert until it settles. setTimeout(write, 800); setTimeout(write, 1800); } } // Compute the diff between the parsed MD and the live editor model as [{label, from, to}]. // With dry=true it ONLY computes (no writes) — the dry-run preview; otherwise it also applies. function diffMd(parsed, dry) { const ed = W.MB && W.MB.releaseEditor; if (!ed) throw new Error('release editor not ready'); const rel = ed.rootField.release(); const changes = [], problems = []; const setObs = (label, obs, val) => { if (typeof obs !== 'function') return; const f = String(u(obs) == null ? '' : u(obs)), t = String(val == null ? '' : val); if (f !== t) { changes.push({ label, from: f || '(empty)', to: t || '(empty)' }); if (!dry) try { obs(val); } catch (e) {} } }; const i = parsed.info || {}; if (i.title != null) setObs('release title', rel.name, i.title); if (i.disambiguation != null) setObs('disambiguation', rel.comment, i.disambiguation); if (i.barcode != null && rel.barcode && typeof rel.barcode.value === 'function') { const bv = i.barcode === 'none' ? '' : i.barcode, f = String(u(rel.barcode.value) || ''); if (f !== bv) { changes.push({ label: 'barcode', from: f || '(none)', to: bv || '(none)' }); if (!dry) try { rel.barcode.value(bv); } catch (e) {} } } if (parsed.annotation != null) setObs('annotation', rel.annotation, parsed.annotation); if (i.artist) applyCredit(rel.artistCredit, i.artist, parsed.refs, changes, 'release artist', dry, problems); for (const med of (parsed.media || [])) { const lm = rel.mediums()[med.position - 1]; if (!lm) continue; const lts = lm.tracks(); // medium format + title from "### Medium N — format — title" (format is an enum, like status) const _ci = x => String(x).trim().toLowerCase(); let medTitle = med.title; if (med.format && typeof lm.formatID === 'function') { const fsel = [...document.querySelectorAll('select')].filter(s => (s.getAttribute('data-bind') || '').includes('value: formatID'))[med.position - 1]; const opt = fsel && [...fsel.options].find(o => _ci(o.textContent) === _ci(med.format)); if (opt) { const cur = String(u(lm.formatID)); if (cur !== String(opt.value)) { const co = [...fsel.options].find(o => String(o.value) === cur); changes.push({ label: `medium ${med.position} format`, from: (co ? co.textContent.trim() : '') || '(none)', to: opt.textContent.trim() }); if (!dry) try { lm.formatID(opt.value); } catch (e) {} } } else if (fsel && !med.title) medTitle = med.format; // select found but segment-1 isn't a known format → it's the medium title, not a format else if (fsel) problems.push({ field: `medium ${med.position} format`, value: med.format, focus: () => focusNative(fsel) }); // 2-segment header with an invalid format → flag it } if (medTitle) setObs(`medium ${med.position} title`, lm.name, medTitle); // the medium's own title (lm.name) for (const t of med.tracks) { let lt = null; const recUrl = t.recording && parsed.refs.get(t.recording) && parsed.refs.get(t.recording).url; const recGid = recUrl && mbidFromUrl(recUrl); if (recGid) lt = lts.find(x => { const rc = u(x.recording); return rc && u(rc.gid) === recGid; }); if (!lt) lt = lts[t.position - 1]; if (!lt) continue; const tag = `track ${med.position}.${t.position}`; setObs(`${tag} title`, lt.name, t.title); // the "N." marker is position/order, not the `number` field — not written if (t.length != null) setObs(`${tag} length`, lt.formattedLength, t.length); // '' clears an existing length (export always shows present lengths, so '' = removed) applyCredit(lt.artistCredit, t.credit, parsed.refs, changes, `${tag} artist`, dry, problems); } } // release-level enums — name → id via the page's ko-bound <select> options const selFor = fid => [...document.querySelectorAll('select')].find(s => (s.getAttribute('data-bind') || '').includes('value: ' + fid)); const optText = (s, val) => { const o = [...s.options].find(o => o.value === String(val)); return o ? o.textContent.trim() : String(val); }; const setEnum = (label, obs, fid, name) => { if (name == null || typeof obs !== 'function') return; // field absent → leave it; '' means clear (the empty <option>) const s = selFor(fid); if (!s) return; const ci = x => String(x).trim().toLowerCase(); // option text match is case-insensitive (digibook == Digibook) const opt = name === '' ? [...s.options].find(o => o.value === '') : [...s.options].find(o => ci(o.textContent) === ci(name)); if (!opt) { problems.push({ field: label, value: name, focus: () => focusNative(selFor(fid)) }); return; } // unknown value → surface it, don't silently skip const cur = String(u(obs)); if (cur !== String(opt.value)) { changes.push({ label, from: optText(s, cur) || '(none)', to: opt.value === '' ? '(none)' : opt.textContent.trim() }); if (!dry) try { obs(opt.value); } catch (e) {} } }; setEnum('status', rel.statusID, 'statusID', i.status); setEnum('packaging', rel.packagingID, 'packagingID', i.packaging); setEnum('language', rel.languageID, 'languageID', i.language); setEnum('script', rel.scriptID, 'scriptID', i.script); const ci = x => String(x).trim().toLowerCase(); // release events — add/remove to match the MD, then edit each by index const fmtd = (y, mo, d) => (y ? '' + y : '') + (mo ? '-' + String(mo).padStart(2, '0') : '') + (d ? '-' + String(d).padStart(2, '0') : ''); const pevents = parsed.events || []; const evArr = () => (typeof rel.events === 'function' && rel.events()) || []; const ev0 = evArr().length; for (let idx = pevents.length; idx < ev0; idx++) { const le = evArr()[idx]; changes.push({ label: `event ${idx + 1} (remove)`, from: (le && le.date ? fmtd(u(le.date.year), u(le.date.month), u(le.date.day)) : '') || '(event)', to: '(removed)' }); } if (!dry) { const cur = evArr().slice(); for (let idx = cur.length - 1; idx >= pevents.length; idx--) try { rel.events.remove(cur[idx]); } catch (e) {} } for (let idx = ev0; idx < pevents.length; idx++) { const pe = pevents[idx]; changes.push({ label: `event ${idx + 1} (add)`, from: '(none)', to: [pe.date, pe.country].filter(Boolean).join(', ') || '(event)' }); if (!dry) try { rel.events.push(new ed.fields.ReleaseEvent({}, rel)); } catch (e) {} } pevents.forEach((pe, idx) => { const le = evArr()[idx]; if (!le) return; if (le.date && typeof le.date.year === 'function') { const m = (pe.date || '').match(/^(\d{4})?(?:-(\d{1,2}))?(?:-(\d{1,2}))?$/) || []; const ny = m[1] || '', nmo = m[2] || '', nd = m[3] || ''; // STRINGS — a numeric year trips MB's "year should have four digits" check const cy = u(le.date.year), cmo = u(le.date.month), cd = u(le.date.day); const same = (a, b) => String(a == null || a === '' ? '' : +a) === String(b == null || b === '' ? '' : +b); if (!same(cy, ny) || !same(cmo, nmo) || !same(cd, nd)) { changes.push({ label: `event ${idx + 1} date`, from: fmtd(cy, cmo, cd) || '(none)', to: fmtd(ny, nmo, nd) || '(none)' }); if (!dry) try { le.date.year(ny); le.date.month(nmo); le.date.day(nd); } catch (e) {} } } if (pe.country != null && typeof le.countryID === 'function') { // '' clears the country (the empty <option>) const s = selFor('countryID'), opt = s && (pe.country === '' ? [...s.options].find(o => o.value === '') : [...s.options].find(o => ci(o.textContent) === ci(pe.country))); if (opt) { const cur = String(u(le.countryID)); if (cur !== String(opt.value)) { changes.push({ label: `event ${idx + 1} country`, from: (s ? optText(s, cur) : cur) || '(none)', to: opt.value === '' ? '(none)' : opt.textContent.trim() }); if (!dry) try { le.countryID(opt.value); } catch (e) {} } } else problems.push({ field: `event ${idx + 1} country`, value: pe.country, focus: () => focusNative([...document.querySelectorAll('select')].filter(x => (x.getAttribute('data-bind') || '').includes('value: countryID'))[idx]) }); } }); // labels — add/remove to match the MD, then change entity + cat# by index const plabels = parsed.labels || []; const labArr = () => (typeof rel.labels === 'function' && rel.labels()) || []; // a label entity: by MBID if a footer ref resolves, else a brand-new label by name (like new artists) — no link needed const labEnt = pl => { if (!pl.label) return null; const ref = parsed.refs.get(pl.label), gid = ref && mbidFromUrl(ref.url); return gid ? { gid, name: ref.main || pl.label } : { name: pl.label }; }; const lab0 = labArr().length; for (let idx = plabels.length; idx < lab0; idx++) { const ll = labArr()[idx], nm = ll && u(ll.label) && u(u(ll.label).name); changes.push({ label: `label ${idx + 1} (remove)`, from: nm || (ll && u(ll.catalogNumber)) || '(label)', to: '(removed)' }); } if (!dry) { const cur = labArr().slice(); for (let idx = cur.length - 1; idx >= plabels.length; idx--) try { rel.labels.remove(cur[idx]); } catch (e) {} } for (let idx = lab0; idx < plabels.length; idx++) { const pl = plabels[idx], e = labEnt(pl); changes.push({ label: `label ${idx + 1} (add)`, from: '(none)', to: (pl.label || '(label)') + (pl.catno ? ' — ' + pl.catno : '') }); if (!dry) try { rel.labels.push(new ed.fields.ReleaseLabel({ label: e ? W.MB.entity(e, 'label') : null, catalogNumber: pl.catno || '' }, rel)); } catch (e2) {} } plabels.forEach((pl, idx) => { const ll = labArr()[idx]; if (!ll) return; const e = labEnt(pl); if (e && typeof ll.label === 'function') { const curL = u(ll.label), curGid = gidOf(curL), curName = curL ? u(curL.name) : ''; // gid → swap to that exact label; name-only → set/rename to a new label whenever the name // actually changed (so renaming a linked label to plain text works; an unchanged name = no-op, // which preserves an existing link if you only removed its footer) const differs = e.gid ? (curGid !== e.gid) : (curName !== e.name); if (differs) { changes.push({ label: `label ${idx + 1}`, from: curName || '(none)', to: e.name }); if (!dry) try { ll.label(W.MB.entity(e, 'label')); } catch (e2) {} } } if (typeof ll.catalogNumber === 'function') { const f = String(u(ll.catalogNumber) || ''), t = String(pl.catno || ''); if (f !== t) { changes.push({ label: `label ${idx + 1} cat#`, from: f || '(none)', to: t || '(none)' }); if (!dry) try { ll.catalogNumber(t); } catch (e2) {} } } }); return { changes, problems }; } const applyMd = async parsed => { await resolveArtistsIn(parsed); return diffMd(parsed, false).changes; }; // resolve linked artists, then compute + write (test hook) // #395 summarise the accumulated session changes for the edit note — release-level fields by name, and // track / medium / event / label edits as counts. function editNoteStats(changed) { const rel = [], b = { track: 0, medium: 0, event: 0, label: 0 }; for (const l of changed.keys()) { if (/^track /.test(l)) b.track++; else if (/^medium /.test(l)) b.medium++; else if (/^event /.test(l)) b.event++; else if (/^label /.test(l)) b.label++; else rel.push(l); } const plural = (n, w) => n + ' ' + w + (n > 1 ? 's' : ''); const parts = []; if (rel.length) parts.push(rel.join(', ')); if (b.track) parts.push(plural(b.track, 'track field')); if (b.medium) parts.push(plural(b.medium, 'medium field')); if (b.event) parts.push(plural(b.event, 'event field')); if (b.label) parts.push(plural(b.label, 'label field')); return `Edited via Markdown — set ${plural(changed.size, 'field')}: ${parts.join(' · ')}`; } // #395 when Scribe has set at least one field this session, stamp the edit note with the standard header // + a stats line. Re-runnable: replaces our previous block, preserves anything else in the field. function stampEditNote(s) { if (!s.changed.size) return; const ta = document.querySelector('textarea.edit-note, textarea[name="edit-note.text"], textarea[name="edit-note"], textarea[name="edit_note"], #id-edit-note, .edit-note textarea'); if (!ta) return; const gi = (typeof GM_info !== 'undefined' && GM_info.script) || {}; const homepage = gi.homepageURL || gi.homepage || 'https://github.com/majkinetor/musicbrainz-userscripts/blob/main/userscripts/scribe/README.md'; const header = `${NAME} v${gi.version || VERSION} by ${gi.author || 'majkinetor'} - ${homepage}`; const block = `${header}\n${editNoteStats(s.changed)}`; const esc = NAME.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const cleaned = String(ta.value || '').replace(new RegExp('(?:^|\\n)' + esc + ' v[^\\n]*\\n[^\\n]*', 'g'), '').replace(/\n{3,}/g, '\n\n').trim(); const val = cleaned ? cleaned + '\n\n' + block : block; try { const setVal = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set; setVal.call(ta, val); ta.dispatchEvent(new Event('input', { bubbles: true })); ta.dispatchEvent(new Event('change', { bubbles: true })); } catch (e) {} } // Open the release MD in the editor and KEEP it linked: every save applies to the editor, // so you can iterate (edit · save · see it apply · edit more · save …) until you Stop. let session = null; // { id, active, lastMd, changed:Map(field→{from,to}), problems:[] } async function startSession() { if (session && session.active) { showPanel(); renderSession(); return; } if (!onEditPage()) return; session = { id: null, active: false, lastMd: '', changed: new Map(), problems: [] }; renderSession('Exporting release…'); let md; try { md = await exportMd(); } catch (e) { renderSession('Export failed: ' + (e.message || e)); return; } if (!(await ping())) { renderSession(`${NAME} helper not reachable on ${base()}.`); updateLauncher(); return; } const id = 'rel-' + (releaseMbid() || '').slice(0, 8) + '-' + Date.now().toString(36); try { const open = await gm({ method: 'POST', url: base() + '/open', headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({ id, content: md, ext: 'md', name: 'release' }) }); if (open.status !== 200) { renderSession(`Open failed (HTTP ${open.status})`); return; } } catch (e) { renderSession('Open error: ' + (e.message || e)); return; } session.id = id; session.active = true; session.lastMd = md; renderSession('Editing — save in your editor; changes appear here.'); updateLauncher(); poll(session); } async function poll(s) { while (s.active) { let r; try { r = await gm({ url: `${base()}/result?id=${encodeURIComponent(s.id)}`, timeout: 660000 }); } catch (e) { if (!s.active) break; await sleep(1200); continue; } if (!s.active) break; if (r.status === 204) continue; // still editing if (r.status === 404 || r.status === 410) { s.active = false; if (session === s) session = null; if (panel) panel.style.display = 'none'; updateLauncher(); break; } if (r.status !== 200) { await sleep(1200); continue; } let content; try { content = JSON.parse(r.responseText).content || ''; } catch (e) { continue; } if (content.replace(/\s+$/, '') === s.lastMd.replace(/\s+$/, '')) continue; // saved, nothing changed s.lastMd = content; try { const parsed = parse(content); await resolveArtistsIn(parsed); // fetch full entities for any linked artists (with internal id) before applying const { changes, problems } = diffMd(parsed, false); if (changes.length) await refreshApollo(); // make Apollo's mirror reflect the model writes (if Apollo is on) for (const c of changes) { const ex = s.changed.get(c.label); s.changed.set(c.label, { from: ex ? ex.from : c.from, to: c.to }); } // accumulate across the session; keep the original "from" s.problems = problems; stampEditNote(s); // #395 header + stats of what Scribe set, once ≥1 field has changed renderSession(); } catch (e) { renderSession('Apply error: ' + (e.message || e)); } } } function stopSession() { const s = session; if (s) { s.active = false; if (s.id) gm({ url: `${base()}/close?id=${encodeURIComponent(s.id)}` }).catch(() => {}); } session = null; if (panel) panel.style.display = 'none'; // ✕ / stop closes the window updateLauncher(); } window.addEventListener('pagehide', () => { if (session && session.active) gm({ url: `${base()}/close?id=${encodeURIComponent(session.id)}` }).catch(() => {}); }); // ── corner launcher, bottom-right with the other scripts' launchers: shown only while the extedit helper is reachable (pinged) ── let launcher = null, _helperUp = false; function ensureLauncher() { if (launcher) return; launcher = document.createElement('button'); launcher.type = 'button'; launcher.id = 'scribe-launcher'; launcher.dataset.mbCorner = 'br'; launcher.dataset.mbCornerOrder = '15'; // just above Apollo (10), which keeps the corner on the edit page launcher.style.cssText = 'position:fixed;right:14px;bottom:14px;z-index:2147483646;width:40px;height:40px;border-radius:50%;border:none;padding:0;cursor:pointer;display:none;align-items:center;justify-content:center;background:transparent;box-shadow:none;transition:opacity .15s,transform .1s'; const img = document.createElement('img'); img.src = ICON_URL; img.alt = ''; img.style.cssText = 'width:34px;height:34px;display:block;pointer-events:none'; launcher.appendChild(img); launcher.onmouseenter = () => { launcher.style.transform = 'scale(1.06)'; }; launcher.onmouseleave = () => { launcher.style.transform = 'scale(1)'; }; launcher.onclick = () => { if (session && session.active) stopSession(); else startSession(); }; document.body.appendChild(launcher); } function updateLauncher() { if (!launcher) return; const active = !!(session && session.active); launcher.style.display = _helperUp ? 'flex' : 'none'; // no disc, as the other launchers; idle the icon is monochrome, a session shows it in colour, // as Apollo's and Art Station's launchers show they're on (#695) const img = launcher.querySelector('img'); img.style.filter = active ? '' : 'grayscale(1)'; img.style.opacity = active ? '' : '.55'; launcher.style.opacity = active ? '1' : '.85'; launcher.dataset.tip = !_helperUp ? `${NAME} — off\nStart the extedit helper to turn it on` : active ? `${NAME} — editing this release\nClick: stop` : `${NAME} — edit this release as Markdown (Ctrl+Alt+R)`; mbRestackCorner('br'); if (panel && panel.style.display !== 'none') placePanel(); } async function pollHelper() { while (true) { const up = onEditPage() ? await ping() : false; if (up !== _helperUp) { _helperUp = up; ensureLauncher(); updateLauncher(); } await sleep(up ? 15000 : 4000); // re-check often while down (so it appears when you start the helper), relax once up } } // Ctrl+Alt+R toggles the session — only on a release Edit page window.addEventListener('keydown', e => { if (!e.ctrlKey || !e.altKey || e.shiftKey || e.metaKey) return; if (e.code !== 'KeyR' && (e.key || '').toLowerCase() !== 'r') return; if (!onEditPage()) return; e.preventDefault(); e.stopPropagation(); if (session && session.active) stopSession(); else startSession(); }, true); if (onEditPage()) { ensureLauncher(); pollHelper(); } // test/automation hook try { W.__releaseMd = W.__scribe = { exportMd, parse, emit, toModel, applyMd, diffMd, refreshApollo, startSession, stopSession }; } catch (e) {} console.log(`[${NAME}] release editor ready — corner button appears when the helper is running (${base()})`); })(); // ══════════════════════════════════════════════════════════════════════════════ // Field editor — edit the FOCUSED text field in your editor (Ctrl+Alt+E). // Self-contained module; shares the helper port/token (ee_port / ee_token) with the // release editor above. The trigger you use picks the feature: E = field, R = release. // ══════════════════════════════════════════════════════════════════════════════ (function () { 'use strict'; // ── settings (GM-persisted) ─────────────────────────────────────────────── const DEF = { port: 17999, token: 'extedit', hotkey: { ctrl: true, alt: true, shift: false, meta: false, key: 'e' } }; const cfg = { get port() { return GM_getValue('ee_port', DEF.port); }, get token() { return GM_getValue('ee_token', DEF.token); }, get hotkey() { try { return JSON.parse(GM_getValue('ee_hotkey', '')) || DEF.hotkey; } catch (e) { return DEF.hotkey; } }, }; const base = () => `http://127.0.0.1:${cfg.port}`; const hotkeyLabel = h => [h.ctrl && 'Ctrl', h.alt && 'Alt', h.shift && 'Shift', h.meta && 'Meta', (h.key || '').toUpperCase()].filter(Boolean).join('+'); // ── tiny GM request helpers (no CORS / mixed-content wall) ──────────────── const gm = opts => new Promise((resolve, reject) => { mbnGm({ method: opts.method || 'GET', url: opts.url, data: opts.data, timeout: opts.timeout || 30000, headers: Object.assign({ 'X-ExtEdit-Token': cfg.token }, opts.headers || {}), onload: r => resolve(r), onerror: () => reject(new Error('network')), ontimeout: () => reject(new Error('timeout')), }); }); const ping = async () => { try { const r = await gm({ url: base() + '/ping', timeout: 4000 }); return r.status === 200; } catch (e) { return false; } }; // ── toast ───────────────────────────────────────────────────────────────── let toastEl = null, toastT = 0; function toast(msg, kind, sticky) { if (!toastEl) { toastEl = document.createElement('div'); toastEl.style.cssText = 'position:fixed;z-index:2147483647;left:50%;top:14px;transform:translateX(-50%);background:#2c3a33;color:#fff;padding:7px 13px;border-radius:7px;font:13px -apple-system,Segoe UI,Arial,sans-serif;box-shadow:0 4px 16px rgba(0,0,0,.3);max-width:70vw;'; document.body.appendChild(toastEl); } toastEl.textContent = msg; toastEl.style.background = kind === 'err' ? '#b3352e' : kind === 'ok' ? '#2e7d44' : '#2c3a33'; toastEl.style.display = ''; clearTimeout(toastT); if (!sticky) toastT = setTimeout(() => { if (toastEl) toastEl.style.display = 'none'; }, 2600); } // ── editable field read/write ───────────────────────────────────────────── function editableOf(el) { if (!el) return null; const tag = el.tagName; if (tag === 'TEXTAREA') return { el, kind: 'value' }; if (tag === 'INPUT' && /^(text|search|url|email|tel|number|)$/i.test(el.type || 'text')) return { el, kind: 'value' }; if (el.isContentEditable) return { el, kind: 'ce' }; return null; } const readVal = t => t.kind === 'ce' ? t.el.innerText : t.el.value; function writeVal(t, text) { text = text.replace(/\r\n?/g, '\n').replace(/\n$/, ''); if (t.kind === 'ce') { t.el.innerText = text; t.el.dispatchEvent(new InputEvent('input', { bubbles: true })); return; } const proto = t.el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; const set = Object.getOwnPropertyDescriptor(proto, 'value').set; set.call(t.el, text); t.el.dispatchEvent(new Event('input', { bubbles: true })); t.el.dispatchEvent(new Event('change', { bubbles: true })); } // Always .md — the helper (0.3.1+) ignores this and writes .md regardless; still sent so an older // helper opens .md too instead of falling back to .txt. (Plain text is valid Markdown.) const EXT = 'md'; // ── per-field sessions (many fields linked at once) ─────────────────────── const sessions = new Map(); const genId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 8); const sleep = ms => new Promise(z => setTimeout(z, ms)); function fieldLabel(el) { let lbl = ''; if (el.id) { try { const l = document.querySelector(`label[for="${CSS.escape(el.id)}"]`); if (l) lbl = l.textContent; } catch (e) {} } lbl = (lbl || el.getAttribute('aria-label') || el.placeholder || el.name || el.id || el.tagName.toLowerCase()).replace(/\s+/g, ' ').trim(); return lbl.slice(0, 32) || 'field'; } function onHotkeyField(t) { const s = sessions.get(t.el); if (s && s.connected) reopen(s); else connect(t); } async function connect(t) { if (!(await ping())) { toast(`Scribe helper not reachable on ${base()} — start it (see README)`, 'err'); return; } const id = genId(); const s = { id, el: t.el, t, connected: true, label: fieldLabel(t.el) }; sessions.set(t.el, s); setLinked(t.el, true); renderPanel(); try { const open = await gm({ method: 'POST', url: base() + '/open', headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({ id, content: readVal(t), ext: EXT, name: s.label }) }); if (open.status !== 200) { toast(`Open failed (HTTP ${open.status})`, 'err'); disconnect(t.el, true); return; } } catch (e) { toast('Open error: ' + e.message, 'err'); disconnect(t.el, true); return; } toast(`“${s.label}” opened in your editor — save to apply (stays linked; Esc to disconnect)`, 'ok'); poll(s); } async function reopen(s) { try { const r = await gm({ method: 'POST', url: base() + '/open', headers: { 'Content-Type': 'application/json' }, data: JSON.stringify({ id: s.id, reopen: true }) }); if (r.status === 200) toast(`Re-opened “${s.label}” — switch to your editor`, 'ok'); else if (r.status === 404 || r.status === 410) { disconnect(s.el, true); connect(s.t); } else toast(`Re-open failed (HTTP ${r.status})`, 'err'); } catch (e) { toast('Re-open error: ' + e.message, 'err'); } } async function poll(s) { while (s.connected) { let r; try { r = await gm({ url: `${base()}/result?id=${encodeURIComponent(s.id)}`, timeout: 660000 }); } catch (e) { if (!s.connected) break; await sleep(1200); continue; } if (!s.connected) break; if (r.status === 204) continue; if (r.status === 404 || r.status === 410) { toast(`“${s.label}” session ended`); disconnect(s.el, true); break; } if (r.status !== 200) { await sleep(1200); continue; } try { const out = JSON.parse(r.responseText); writeVal(s.t, out.content || ''); flashLinked(s.el); toast(`“${s.label}” updated ✓`, 'ok'); } catch (e) {} } } function disconnect(el, fromServer) { const s = sessions.get(el); if (!s) return; s.connected = false; sessions.delete(el); setLinked(el, false); renderPanel(); if (!fromServer) { gm({ url: `${base()}/close?id=${encodeURIComponent(s.id)}` }).catch(() => {}); toast(`“${s.label}” disconnected`); } } const disconnectAll = () => { for (const el of [...sessions.keys()]) disconnect(el, false); }; // ── "linked" indicator: a glow on the field + a small panel of live links ── const _prevShadow = new WeakMap(); function setLinked(el, on) { if (on) { if (!_prevShadow.has(el)) _prevShadow.set(el, el.style.boxShadow || ''); el.style.boxShadow = '0 0 0 2px #2e9e5b'; } else { el.style.boxShadow = _prevShadow.get(el) || ''; _prevShadow.delete(el); } } function flashLinked(el) { el.style.boxShadow = '0 0 0 3px #57d07e'; setTimeout(() => { if (sessions.has(el)) el.style.boxShadow = '0 0 0 2px #2e9e5b'; }, 380); } const focusField = s => { try { s.el.scrollIntoView({ block: 'center' }); s.el.focus(); } catch (e) {} }; let panel = null; const _btn = 'background:#3d5147;color:#fff;border:none;border-radius:4px;padding:1px 7px;cursor:pointer;font-size:12px;line-height:1.4;'; function renderPanel() { if (!sessions.size) { if (panel) panel.style.display = 'none'; return; } if (!panel) { panel = document.createElement('div'); // sits a little higher than the release-editor panel so they don't overlap when both are active panel.style.cssText = 'position:fixed;z-index:2147483646;right:12px;bottom:64px;background:#2c3a33;color:#fff;border-radius:8px;padding:7px 9px;font:12px -apple-system,Segoe UI,Arial,sans-serif;box-shadow:0 4px 16px rgba(0,0,0,.3);max-width:300px;'; document.body.appendChild(panel); } panel.style.display = ''; panel.textContent = ''; const head = document.createElement('div'); head.style.cssText = 'display:flex;align-items:center;gap:8px;margin-bottom:6px;'; const title = document.createElement('span'); title.textContent = `✎ Fields — ${sessions.size} linked`; title.style.cssText = 'font-weight:600;opacity:.85;flex:1;white-space:nowrap;'; head.appendChild(title); const finishAll = document.createElement('button'); finishAll.textContent = 'Finish all'; finishAll.dataset.tip = 'Disconnect every linked field'; finishAll.style.cssText = _btn; finishAll.onclick = () => disconnectAll(); head.appendChild(finishAll); panel.appendChild(head); for (const s of sessions.values()) { const row = document.createElement('div'); row.style.cssText = 'display:flex;align-items:center;gap:6px;margin:3px 0;'; const dot = document.createElement('span'); dot.textContent = '●'; dot.style.color = '#57d07e'; row.appendChild(dot); const name = document.createElement('span'); name.textContent = s.label; name.dataset.tip = 'Focus this field in the browser'; name.style.cssText = 'flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;cursor:pointer;'; name.onclick = () => focusField(s); row.appendChild(name); const fb = document.createElement('button'); fb.textContent = '◎'; fb.dataset.tip = 'Focus this field in the browser'; fb.style.cssText = _btn; fb.onclick = () => focusField(s); row.appendChild(fb); const rf = document.createElement('button'); rf.textContent = '✎'; rf.dataset.tip = 'Re-open in your editor'; rf.style.cssText = _btn; rf.onclick = () => reopen(s); row.appendChild(rf); const x = document.createElement('button'); x.textContent = '✕'; x.dataset.tip = 'Disconnect'; x.style.cssText = _btn; x.onclick = () => disconnect(s.el, false); row.appendChild(x); panel.appendChild(row); } } window.addEventListener('pagehide', () => { for (const s of sessions.values()) gm({ url: `${base()}/close?id=${encodeURIComponent(s.id)}` }).catch(() => {}); }); // ── hotkey (Ctrl+Alt+E by default) ─────────────────────────────────────── let capturing = false; document.addEventListener('keydown', e => { if (capturing) return; if (e.key === 'Escape') { const te = editableOf(document.activeElement); if (te && sessions.has(te.el)) { e.preventDefault(); disconnect(te.el, false); } return; } const h = cfg.hotkey; if (e.ctrlKey !== !!h.ctrl || e.altKey !== !!h.alt || e.shiftKey !== !!h.shift || e.metaKey !== !!h.meta) return; if ((e.key || '').toLowerCase() !== (h.key || '').toLowerCase()) return; const t = editableOf(document.activeElement); if (!t) return; e.preventDefault(); e.stopPropagation(); onHotkeyField(t); }, true); // ── menu commands (shared helper config) ───────────────────────────────── GM_registerMenuCommand(`Set helper port (now: ${cfg.port})`, () => { const v = prompt('Scribe — helper port', String(cfg.port)); if (v && /^\d+$/.test(v)) { GM_setValue('ee_port', +v); toast('Port set to ' + v, 'ok'); } }); GM_registerMenuCommand('Set helper token', () => { const v = prompt('Scribe — shared token (must match the helper\'s --token)', cfg.token); if (v != null) { GM_setValue('ee_token', v); toast('Token saved', 'ok'); } }); GM_registerMenuCommand(`Set field hotkey (now: ${hotkeyLabel(cfg.hotkey)})`, () => { capturing = true; toast('Press the new hotkey combo…', '', true); const cap = e => { if (['Control', 'Alt', 'Shift', 'Meta'].includes(e.key)) return; e.preventDefault(); e.stopPropagation(); const h = { ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey, meta: e.metaKey, key: e.key.toLowerCase() }; GM_setValue('ee_hotkey', JSON.stringify(h)); document.removeEventListener('keydown', cap, true); capturing = false; toast('Field hotkey set to ' + hotkeyLabel(h), 'ok'); }; document.addEventListener('keydown', cap, true); }); GM_registerMenuCommand('Test helper connection', async () => toast(await ping() ? `Helper OK on ${base()} ✓` : `Helper not reachable on ${base()}`, (await ping()) ? 'ok' : 'err')); GM_registerMenuCommand('Disconnect all field edits', () => { if (sessions.size) disconnectAll(); else toast('No fields are linked'); }); console.log(`[Scribe] field editor ready — ${hotkeyLabel(cfg.hotkey)} in a focused text field; helper ${base()}`); })();