9.7 KiB · text History 905ae26
.pragma library

// Pure helpers: colours, labels and the shapes of Vigil's /api/0 JSON.
// Levels, statuses and monitor states read as they do in the Android app
// (android/…/ui/Common.kt, Triage.kt, MonitorsTab.kt in the vigil repo).

// The web's status colours (Vigil's StatusColors, OKLCh → sRGB):
//   error   oklch(0.58 0.253 17.6)    warning oklch(0.66 0.179 58.3)
//   info    oklch(0.58 0.158 242.0)   success oklch(0.60 0.118 184.7)
var colors = {
    error: "#ea003e",
    warning: "#df6f00",
    info: "#0082ce",
    success: "#009689",
    muted: "#8a8a8a"
}

// ── issues ──────────────────────────────────────────────────────────────

// An issue's key across projects: ids are per project.
function issueKey(issue) {
    return (issue.project ? issue.project.id : "?") + "/" + issue.id
}

// An event level's colour, as the web's level badges.
function levelColor(level) {
    switch ((level || "").toLowerCase()) {
    case "fatal":
    case "error": return colors.error
    case "warning": return colors.warning
    case "info": return colors.info
    case "debug": return colors.success
    default: return colors.muted
    }
}

function levelLabel(level) {
    return (level || "error").toLowerCase()
}

// "Resolved in next release", "Ignored", "Unresolved".
function statusLabel(issue) {
    var s = issue.status || "unresolved"
    if (s === "resolved" && issue.statusDetails && issue.statusDetails.inNextRelease) return "Resolved in next release"
    return s.charAt(0).toUpperCase() + s.substring(1)
}

function statusColor(issue) {
    switch (issue.status) {
    case "resolved": return colors.success
    case "ignored": return colors.warning
    default: return colors.error
    }
}

// The status actions that make sense from where the issue is, likeliest
// first: [{status, label}]. As the Android app's triageOptions().
function triageOptions(issue) {
    var resolve = { status: "resolved", label: "Resolve", icon: "checkmark" }
    var next = { status: "resolvedInNextRelease", label: "Resolve in Next Release", icon: "checkmark" }
    var ignore = { status: "ignored", label: "Ignore", icon: "view-hidden" }
    var unresolve = { status: "unresolved", label: "Unresolve", icon: "edit-undo" }
    switch (issue.status) {
    case "resolved": return [unresolve, ignore]
    case "ignored": return [unresolve, resolve, next]
    default: return [resolve, next, ignore]
    }
}

// What a status change leaves the issue as, by the server's reply.
function applying(issue, update, reply) {
    var out = Object.assign({}, issue)
    if (update.status !== undefined) {
        var sent = update.status
        var status = sent === "resolvedInNextRelease" ? "resolved" : sent === "muted" ? "ignored" : sent
        var next = status === "resolved"
                   && (reply && reply.statusDetails ? !!reply.statusDetails.inNextRelease : sent === "resolvedInNextRelease")
        out.status = status
        out.statusDetails = { inNextRelease: next }
    }
    if (update.assignedTo !== undefined) out.assignedTo = reply ? reply.assignedTo || null : null
    return out
}

function assigneeLabel(a) {
    if (!a) return ""
    return a.name || a.email || "someone"
}

// "1.2k" for counts the row has no room for.
function compactCount(raw) {
    var n = parseInt(raw, 10)
    if (isNaN(n)) return String(raw || "0")
    if (n < 1000) return String(n)
    if (n < 1000000) return (n / 1000).toFixed(1).replace(/\.0$/, "") + "k"
    return (n / 1000000).toFixed(1).replace(/\.0$/, "") + "M"
}

// ── time ────────────────────────────────────────────────────────────────

function parseTime(iso) {
    if (iso === null || iso === undefined || iso === "") return NaN
    if (typeof iso === "number") return iso * 1000      // epoch seconds (breadcrumbs)
    var t = new Date(iso).getTime()
    // Naive timestamps are UTC on the server.
    if (isNaN(t)) t = new Date(iso + "Z").getTime()
    return t
}

function span(secs) {
    if (secs < 3600) return Math.max(1, Math.floor(secs / 60)) + "m"
    if (secs < 86400) return Math.floor(secs / 3600) + "h"
    if (secs < 2592000) return Math.floor(secs / 86400) + "d"
    if (secs < 31536000) return Math.floor(secs / 2592000) + "mo"
    return Math.floor(secs / 31536000) + "y"
}

// "3m ago", "in 2h", "just now".
function relativeTime(iso, now) {
    var then = parseTime(iso)
    if (isNaN(then)) return ""
    var secs = Math.round(((now || Date.now()) - then) / 1000)
    if (secs > -60 && secs < 60) return "just now"
    return secs > 0 ? span(secs) + " ago" : "in " + span(-secs)
}

function clockTime(iso) {
    var t = parseTime(iso)
    if (isNaN(t)) return ""
    var d = new Date(t)
    function two(n) { return n < 10 ? "0" + n : "" + n }
    return two(d.getHours()) + ":" + two(d.getMinutes()) + ":" + two(d.getSeconds())
}

function within(iso, now, hours) {
    var t = parseTime(iso)
    return !isNaN(t) && now - t <= hours * 3600 * 1000
}

// ── events ──────────────────────────────────────────────────────────────

function entry(event, type) {
    var es = (event && event.entries) || []
    for (var i = 0; i < es.length; i++) if (es[i] && es[i].type === type) return es[i].data || null
    return null
}

// Exceptions, outermost (the one raised last) first, as Sentry shows them.
function exceptions(event) {
    var d = entry(event, "exception")
    var values = d && d.values ? d.values.slice() : []
    return values.reverse()
}

function message(event) {
    var d = entry(event, "message")
    return (d && d.formatted) || (event && event.message) || ""
}

// The newest in-app frames first, at most `max`; every frame when none
// is in-app.
function topFrames(exception, max) {
    var frames = exception && exception.stacktrace && exception.stacktrace.frames ? exception.stacktrace.frames.slice() : []
    frames.reverse()
    var inApp = frames.filter(function(f) { return f && f.inApp })
    return (inApp.length > 0 ? inApp : frames).slice(0, max)
}

function frameLabel(f) {
    var where = f.filename || f.absPath || f.module || f["package"] || "?"
    var line = f.lineNo ? ":" + f.lineNo + (f.colNo ? ":" + f.colNo : "") : ""
    return { fn: f["function"] || "<anonymous>", where: where + line }
}

// The last `max` breadcrumbs, newest last.
function breadcrumbs(event, max) {
    var d = entry(event, "breadcrumbs")
    var values = d && d.values ? d.values : []
    return values.slice(Math.max(0, values.length - max))
}

function crumbText(b) {
    if (b.message) return b.message
    if (b.data) {
        if (b.data.url) return (b.data.method ? b.data.method + " " : "") + b.data.url + (b.data.status_code ? " → " + b.data.status_code : "")
        try { return JSON.stringify(b.data) } catch (e) {}
    }
    return ""
}

// ── monitors ────────────────────────────────────────────────────────────

// A cron monitor's state: {label, color, rank, failing}.
function cronState(m) {
    if (m.status === "disabled") return { label: "disabled", color: colors.muted, rank: 3, failing: false }
    if (m.health === "error") return { label: "failing", color: colors.error, rank: 0, failing: true }
    if (m.health === "ok") return { label: "ok", color: colors.success, rank: 1, failing: false }
    return { label: "waiting", color: colors.info, rank: 2, failing: false }
}

// An uptime monitor's: up, down, pending or paused.
function uptimeState(m) {
    switch (m.status) {
    case "down": return { label: "down", color: colors.error, rank: 0, failing: true }
    case "pending": return { label: "pending", color: colors.info, rank: 1, failing: false }
    case "up": return { label: "up", color: colors.success, rank: 2, failing: false }
    default: return { label: m.status || "paused", color: colors.muted, rank: 3, failing: false }
    }
}

// ── health ──────────────────────────────────────────────────────────────
//
// A circle's colour: "failing" (a monitor failing, or an issue regressed
// in the window), "new" (an issue first seen in the window), "ok", or
// "unknown" (not loaded yet).

var healthRank = { unknown: 0, ok: 1, "new": 2, failing: 3 }

function worse(a, b) {
    return (healthRank[b] || 0) > (healthRank[a] || 0) ? b : a
}

function healthColor(health) {
    switch (health) {
    case "failing": return colors.error
    case "new": return colors.warning
    case "ok": return colors.success
    default: return colors.muted
    }
}

// ── API helpers ─────────────────────────────────────────────────────────

// The next cursor in a Sentry Link header, or "" on the last page.
function nextCursor(link) {
    if (!link) return ""
    var parts = link.split(",")
    for (var i = 0; i < parts.length; i++) {
        var p = parts[i]
        if (p.indexOf('rel="next"') === -1) continue
        if (p.indexOf('results="true"') === -1) return ""
        var m = p.match(/cursor="([^"]*)"/)
        return m ? m[1] : ""
    }
    return ""
}

function parseList(json) {
    try {
        var v = JSON.parse(json || "[]")
        return Array.isArray(v) ? v.filter(function(x) { return typeof x === "string" && x !== "" }) : []
    } catch (e) {
        return []
    }
}