Code formatting (#280)

This commit is contained in:
Simon Lecoq
2021-04-29 14:32:34 +02:00
committed by GitHub
parent 92090b60b5
commit ce18af8573
98 changed files with 10278 additions and 9807 deletions

View File

@@ -1,321 +1,338 @@
//Imports
import octokit from "@octokit/graphql"
import OctokitRest from "@octokit/rest"
import express from "express"
import ratelimit from "express-rate-limit"
import compression from "compression"
import cache from "memory-cache"
import util from "util"
import setup from "../metrics/setup.mjs"
import mocks from "../mocks/index.mjs"
import metrics from "../metrics/index.mjs"
import octokit from "@octokit/graphql"
import OctokitRest from "@octokit/rest"
import compression from "compression"
import express from "express"
import ratelimit from "express-rate-limit"
import cache from "memory-cache"
import util from "util"
import metrics from "../metrics/index.mjs"
import setup from "../metrics/setup.mjs"
import mocks from "../mocks/index.mjs"
/**App */
export default async function({mock, nosettings} = {}) {
export default async function({mock, nosettings} = {}) {
//Load configuration settings
const {conf, Plugins, Templates} = await setup({nosettings})
const {token, maxusers = 0, restricted = [], debug = false, cached = 30 * 60 * 1000, port = 3000, ratelimiter = null, plugins = null} = conf.settings
mock = mock || conf.settings.mocked
//Load configuration settings
const {conf, Plugins, Templates} = await setup({nosettings})
const {token, maxusers = 0, restricted = [], debug = false, cached = 30*60*1000, port = 3000, ratelimiter = null, plugins = null} = conf.settings
mock = mock || conf.settings.mocked
//Process mocking and default plugin state
for (const plugin of Object.keys(Plugins).filter(x => !["base", "core"].includes(x))) {
//Initialization
const {settings} = conf
if (!settings.plugins[plugin])
settings.plugins[plugin] = {}
//Auto-enable plugin if needed
if (conf.settings["plugins.default"])
settings.plugins[plugin].enabled = settings.plugins[plugin].enabled ?? (console.debug(`metrics/app > auto-enabling ${plugin}`), true)
//Mock plugins tokens if they're undefined
if (mock) {
const tokens = Object.entries(conf.metadata.plugins[plugin].inputs).filter(([key, value]) => (!/^plugin_/.test(key))&&(value.type === "token")).map(([key]) => key)
for (const token of tokens) {
if ((!settings.plugins[plugin][token])||(mock === "force")) {
console.debug(`metrics/app > using mocked token for ${plugin}.${token}`)
settings.plugins[plugin][token] = "MOCKED_TOKEN"
}
}
}
//Process mocking and default plugin state
for (const plugin of Object.keys(Plugins).filter(x => !["base", "core"].includes(x))) {
//Initialization
const {settings} = conf
if (!settings.plugins[plugin])
settings.plugins[plugin] = {}
//Auto-enable plugin if needed
if (conf.settings["plugins.default"])
settings.plugins[plugin].enabled = settings.plugins[plugin].enabled ?? (console.debug(`metrics/app > auto-enabling ${plugin}`), true)
//Mock plugins tokens if they're undefined
if (mock) {
const tokens = Object.entries(conf.metadata.plugins[plugin].inputs).filter(([key, value]) => (!/^plugin_/.test(key)) && (value.type === "token")).map(([key]) => key)
for (const token of tokens) {
if ((!settings.plugins[plugin][token]) || (mock === "force")) {
console.debug(`metrics/app > using mocked token for ${plugin}.${token}`)
settings.plugins[plugin][token] = "MOCKED_TOKEN"
}
}
if (((mock)&&(!conf.settings.token))||(mock === "force")) {
console.debug("metrics/app > using mocked token")
conf.settings.token = "MOCKED_TOKEN"
}
if (debug)
console.debug(util.inspect(conf.settings, {depth:Infinity, maxStringLength:256}))
//Load octokits
const api = {graphql:octokit.graphql.defaults({headers:{authorization:`token ${token}`}}), rest:new OctokitRest.Octokit({auth:token})}
//Apply mocking if needed
if (mock)
Object.assign(api, await mocks(api))
const {graphql, rest} = api
//Setup server
const app = express()
app.use(compression())
const middlewares = []
//Rate limiter middleware
if (ratelimiter) {
app.set("trust proxy", 1)
middlewares.push(ratelimit({
skip(req, _res) {
return !!cache.get(req.params.login)
},
message:"Too many requests: retry later",
headers:true,
...ratelimiter,
}))
}
//Cache headers middleware
middlewares.push((req, res, next) => {
const maxage = Math.round(Number(req.query.cache))
if ((cached)||(maxage > 0))
res.header("Cache-Control", `public, max-age=${Math.round((maxage > 0 ? maxage : cached)/1000)}`)
else
res.header("Cache-Control", "no-store, no-cache")
next()
})
//Base routes
const limiter = ratelimit({max:debug ? Number.MAX_SAFE_INTEGER : 60, windowMs:60*1000, headers:false})
const metadata = Object.fromEntries(Object.entries(conf.metadata.plugins)
.map(([key, value]) => [key, Object.fromEntries(Object.entries(value).filter(([key]) => ["name", "icon", "categorie", "web", "supports"].includes(key)))])
.map(([key, value]) => [key, key === "core" ? {...value, web:Object.fromEntries(Object.entries(value.web).filter(([key]) => /^config[.]/.test(key)).map(([key, value]) => [key.replace(/^config[.]/, ""), value]))} : value]))
const enabled = Object.entries(metadata).filter(([_name, {categorie}]) => categorie !== "core").map(([name]) => ({name, enabled:plugins[name]?.enabled ?? false}))
const templates = Object.entries(Templates).map(([name]) => ({name, enabled:(conf.settings.templates.enabled.length ? conf.settings.templates.enabled.includes(name) : true) ?? false}))
const actions = {flush:new Map()}
let requests = {limit:0, used:0, remaining:0, reset:NaN}
if (!conf.settings.notoken) {
requests = (await rest.rateLimit.get()).data.rate
setInterval(async() => {
try {
requests = (await rest.rateLimit.get()).data.rate
}
catch {
console.debug("metrics/app > failed to update remaining requests")
}
}, 5*60*1000)
}
//Web
app.get("/", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/index.html`))
app.get("/index.html", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/index.html`))
app.get("/favicon.ico", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/favicon.png`))
app.get("/.favicon.png", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/favicon.png`))
app.get("/.opengraph.png", limiter, (req, res) => conf.settings.web?.opengraph ? res.redirect(conf.settings.web?.opengraph) : res.sendFile(`${conf.paths.statics}/opengraph.png`))
//Plugins and templates
app.get("/.plugins", limiter, (req, res) => res.status(200).json(enabled))
app.get("/.plugins.base", limiter, (req, res) => res.status(200).json(conf.settings.plugins.base.parts))
app.get("/.plugins.metadata", limiter, (req, res) => res.status(200).json(metadata))
app.get("/.templates", limiter, (req, res) => res.status(200).json(templates))
app.get("/.templates/:template", limiter, (req, res) => req.params.template in conf.templates ? res.status(200).json(conf.templates[req.params.template]) : res.sendStatus(404))
for (const template in conf.templates)
app.use(`/.templates/${template}/partials`, express.static(`${conf.paths.templates}/${template}/partials`))
//Styles
app.get("/.css/style.css", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/style.css`))
app.get("/.css/style.vars.css", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/style.vars.css`))
app.get("/.css/style.prism.css", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/prismjs/themes/prism-tomorrow.css`))
//Scripts
app.get("/.js/app.js", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/app.js`))
app.get("/.js/app.placeholder.js", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/app.placeholder.js`))
app.get("/.js/ejs.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/ejs/ejs.min.js`))
app.get("/.js/faker.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/faker/dist/faker.min.js`))
app.get("/.js/axios.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/axios/dist/axios.min.js`))
app.get("/.js/axios.min.map", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/axios/dist/axios.min.map`))
app.get("/.js/vue.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/vue/dist/vue.min.js`))
app.get("/.js/vue.prism.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/vue-prism-component/dist/vue-prism-component.min.js`))
app.get("/.js/vue-prism-component.min.js.map", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/vue-prism-component/dist/vue-prism-component.min.js.map`))
app.get("/.js/prism.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/prismjs/prism.js`))
app.get("/.js/prism.yaml.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/prismjs/components/prism-yaml.min.js`))
app.get("/.js/prism.markdown.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/prismjs/components/prism-markdown.min.js`))
//Meta
app.get("/.version", limiter, (req, res) => res.status(200).send(conf.package.version))
app.get("/.requests", limiter, (req, res) => res.status(200).json(requests))
app.get("/.hosted", limiter, (req, res) => res.status(200).json(conf.settings.hosted || null))
//Cache
app.get("/.uncache", limiter, (req, res) => {
const {token, user} = req.query
if (token) {
if (actions.flush.has(token)) {
console.debug(`metrics/app/${actions.flush.get(token)} > flushed cache`)
cache.del(actions.flush.get(token))
return res.sendStatus(200)
}
return res.sendStatus(400)
}
{
const token = `${Math.random().toString(16).replace("0.", "")}${Math.random().toString(16).replace("0.", "")}`
actions.flush.set(token, user)
return res.json({token})
}
})
//About routes
app.use("/about/.statics/", express.static(`${conf.paths.statics}/about`))
app.get("/about/", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/about/index.html`))
app.get("/about/index.html", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/about/index.html`))
app.get("/about/:login", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/about/index.html`))
app.get("/about/query/:login/", ...middlewares, async(req, res) => {
//Check username
const login = req.params.login?.replace(/[\n\r]/g, "")
if (!/^[-\w]+$/i.test(login)) {
console.debug(`metrics/app/${login}/insights > 400 (invalid username)`)
return res.status(400).send("Bad request: username seems invalid")
}
//Compute metrics
try {
//Read cached data if possible
if ((!debug)&&(cached)&&(cache.get(`about.${login}`))) {
console.debug(`metrics/app/${login}/insights > using cached results`)
return res.send(cache.get(`about.${login}`))
}
//Compute metrics
console.debug(`metrics/app/${login}/insights > compute insights`)
const json = await metrics({
login, q:{
template:"classic",
achievements:true, "achievements.threshold":"X",
isocalendar:true, "isocalendar.duration":"full-year",
languages:true, "languages.limit":0,
activity:true, "activity.limit":100, "activity.days":0,
notable:true,
},
}, {graphql, rest, plugins:{achievements:{enabled:true}, isocalendar:{enabled:true}, languages:{enabled:true}, activity:{enabled:true, markdown:"extended"}, notable:{enabled:true}}, conf, convert:"json"}, {Plugins, Templates})
//Cache
if ((!debug)&&(cached)) {
const maxage = Math.round(Number(req.query.cache))
cache.put(`about.${login}`, json, maxage > 0 ? maxage : cached)
}
return res.json(json)
}
//Internal error
catch (error) {
//Not found user
if ((error instanceof Error)&&(/^user not found$/.test(error.message))) {
console.debug(`metrics/app/${login} > 404 (user/organization not found)`)
return res.status(404).send("Not found: unknown user or organization")
}
//GitHub failed request
if ((error instanceof Error)&&(/this may be the result of a timeout, or it could be a GitHub bug/i.test(error.errors?.[0]?.message))) {
console.debug(`metrics/app/${login} > 502 (bad gateway from GitHub)`)
const request = encodeURIComponent(error.errors[0].message.match(/`(?<request>[\w:]+)`/)?.groups?.request ?? "").replace(/%3A/g, ":")
return res.status(500).send(`Internal Server Error: failed to execute request ${request} (this may be the result of a timeout, or it could be a GitHub bug)`)
}
//General error
console.error(error)
return res.status(500).send("Internal Server Error: failed to process metrics correctly")
}
})
//Metrics
const pending = new Map()
app.get("/:login/:repository?", ...middlewares, async(req, res) => {
//Request params
const login = req.params.login?.replace(/[\n\r]/g, "")
const repository = req.params.repository?.replace(/[\n\r]/g, "")
let solve = null
//Check username
if (!/^[-\w]+$/i.test(login)) {
console.debug(`metrics/app/${login} > 400 (invalid username)`)
return res.status(400).send("Bad request: username seems invalid")
}
//Allowed list check
if ((restricted.length)&&(!restricted.includes(login))) {
console.debug(`metrics/app/${login} > 403 (not in allowed users)`)
return res.status(403).send("Forbidden: username not in allowed list")
}
//Prevent multiples requests
if ((!debug)&&(!mock)&&(pending.has(login))) {
console.debug(`metrics/app/${login} > awaiting pending request`)
await pending.get(login)
}
else
pending.set(login, new Promise(_solve => solve = _solve))
//Read cached data if possible
if ((!debug)&&(cached)&&(cache.get(login))) {
console.debug(`metrics/app/${login} > using cached image`)
const {rendered, mime} = cache.get(login)
res.header("Content-Type", mime)
return res.send(rendered)
}
//Maximum simultaneous users
if ((maxusers)&&(cache.size()+1 > maxusers)) {
console.debug(`metrics/app/${login} > 503 (maximum users reached)`)
return res.status(503).send("Service Unavailable: maximum number of users reached, only cached metrics are available")
}
//Repository alias
if (repository) {
console.debug(`metrics/app/${login} > compute repository metrics`)
if (!req.query.template)
req.query.template = "repository"
req.query.repo = repository
}
//Compute rendering
try {
//Render
const q = req.query
console.debug(`metrics/app/${login} > ${util.inspect(q, {depth:Infinity, maxStringLength:256})}`)
const {rendered, mime} = await metrics({login, q}, {
graphql, rest, plugins, conf,
die:q["plugins.errors.fatal"] ?? false,
verify:q.verify ?? false,
convert:["svg", "jpeg", "png", "json", "markdown", "markdown-pdf"].includes(q["config.output"]) ? q["config.output"] : null,
}, {Plugins, Templates})
//Cache
if ((!debug)&&(cached)) {
const maxage = Math.round(Number(req.query.cache))
cache.put(login, {rendered, mime}, maxage > 0 ? maxage : cached)
}
//Send response
res.header("Content-Type", mime)
return res.send(rendered)
}
//Internal error
catch (error) {
//Not found user
if ((error instanceof Error)&&(/^user not found$/.test(error.message))) {
console.debug(`metrics/app/${login} > 404 (user/organization not found)`)
return res.status(404).send("Not found: unknown user or organization")
}
//Invalid template
if ((error instanceof Error)&&(/^unsupported template$/.test(error.message))) {
console.debug(`metrics/app/${login} > 400 (bad request)`)
return res.status(400).send("Bad request: unsupported template")
}
//Unsupported output format or account type
if ((error instanceof Error)&&(/^not supported for: [\s\S]*$/.test(error.message))) {
console.debug(`metrics/app/${login} > 406 (Not Acceptable)`)
return res.status(406).send("Not Acceptable: unsupported output format or account type for specified parameters")
}
//GitHub failed request
if ((error instanceof Error)&&(/this may be the result of a timeout, or it could be a GitHub bug/i.test(error.errors?.[0]?.message))) {
console.debug(`metrics/app/${login} > 502 (bad gateway from GitHub)`)
const request = encodeURIComponent(error.errors[0].message.match(/`(?<request>[\w:]+)`/)?.groups?.request ?? "").replace(/%3A/g, ":")
return res.status(500).send(`Internal Server Error: failed to execute request ${request} (this may be the result of a timeout, or it could be a GitHub bug)`)
}
//General error
console.error(error)
return res.status(500).send("Internal Server Error: failed to process metrics correctly")
}
//After rendering
finally {
solve?.()
}
})
//Listen
app.listen(port, () => console.log([
`Listening on port │ ${port}`,
`Debug mode │ ${debug}`,
`Mocked data │ ${conf.settings.mocked ?? false}`,
`Restricted to users │ ${restricted.size ? [...restricted].join(", ") : "(unrestricted)"}`,
`Cached time │ ${cached} seconds`,
`Rate limiter │ ${ratelimiter ? util.inspect(ratelimiter, {depth:Infinity, maxStringLength:256}) : "(enabled)"}`,
`Max simultaneous users │ ${maxusers ? `${maxusers} users` : "(unrestricted)"}`,
`Plugins enabled │ ${enabled.map(({name}) => name).join(", ")}`,
`SVG optimization │ ${conf.settings.optimize ?? false}`,
"Server ready !",
].join("\n")))
}
}
if (((mock) && (!conf.settings.token)) || (mock === "force")) {
console.debug("metrics/app > using mocked token")
conf.settings.token = "MOCKED_TOKEN"
}
if (debug)
console.debug(util.inspect(conf.settings, {depth:Infinity, maxStringLength:256}))
//Load octokits
const api = {graphql:octokit.graphql.defaults({headers:{authorization:`token ${token}`}}), rest:new OctokitRest.Octokit({auth:token})}
//Apply mocking if needed
if (mock)
Object.assign(api, await mocks(api))
const {graphql, rest} = api
//Setup server
const app = express()
app.use(compression())
const middlewares = []
//Rate limiter middleware
if (ratelimiter) {
app.set("trust proxy", 1)
middlewares.push(ratelimit({
skip(req, _res) {
return !!cache.get(req.params.login)
},
message:"Too many requests: retry later",
headers:true,
...ratelimiter,
}))
}
//Cache headers middleware
middlewares.push((req, res, next) => {
const maxage = Math.round(Number(req.query.cache))
if ((cached) || (maxage > 0))
res.header("Cache-Control", `public, max-age=${Math.round((maxage > 0 ? maxage : cached) / 1000)}`)
else
res.header("Cache-Control", "no-store, no-cache")
next()
})
//Base routes
const limiter = ratelimit({max:debug ? Number.MAX_SAFE_INTEGER : 60, windowMs:60 * 1000, headers:false})
const metadata = Object.fromEntries(
Object.entries(conf.metadata.plugins)
.map(([key, value]) => [key, Object.fromEntries(Object.entries(value).filter(([key]) => ["name", "icon", "categorie", "web", "supports"].includes(key)))])
.map(([key, value]) => [key, key === "core" ? {...value, web:Object.fromEntries(Object.entries(value.web).filter(([key]) => /^config[.]/.test(key)).map(([key, value]) => [key.replace(/^config[.]/, ""), value]))} : value]),
)
const enabled = Object.entries(metadata).filter(([_name, {categorie}]) => categorie !== "core").map(([name]) => ({name, enabled:plugins[name]?.enabled ?? false}))
const templates = Object.entries(Templates).map(([name]) => ({name, enabled:(conf.settings.templates.enabled.length ? conf.settings.templates.enabled.includes(name) : true) ?? false}))
const actions = {flush:new Map()}
let requests = {limit:0, used:0, remaining:0, reset:NaN}
if (!conf.settings.notoken) {
requests = (await rest.rateLimit.get()).data.rate
setInterval(async () => {
try {
requests = (await rest.rateLimit.get()).data.rate
}
catch {
console.debug("metrics/app > failed to update remaining requests")
}
}, 5 * 60 * 1000)
}
//Web
app.get("/", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/index.html`))
app.get("/index.html", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/index.html`))
app.get("/favicon.ico", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/favicon.png`))
app.get("/.favicon.png", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/favicon.png`))
app.get("/.opengraph.png", limiter, (req, res) => conf.settings.web?.opengraph ? res.redirect(conf.settings.web?.opengraph) : res.sendFile(`${conf.paths.statics}/opengraph.png`))
//Plugins and templates
app.get("/.plugins", limiter, (req, res) => res.status(200).json(enabled))
app.get("/.plugins.base", limiter, (req, res) => res.status(200).json(conf.settings.plugins.base.parts))
app.get("/.plugins.metadata", limiter, (req, res) => res.status(200).json(metadata))
app.get("/.templates", limiter, (req, res) => res.status(200).json(templates))
app.get("/.templates/:template", limiter, (req, res) => req.params.template in conf.templates ? res.status(200).json(conf.templates[req.params.template]) : res.sendStatus(404))
for (const template in conf.templates)
app.use(`/.templates/${template}/partials`, express.static(`${conf.paths.templates}/${template}/partials`))
//Styles
app.get("/.css/style.css", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/style.css`))
app.get("/.css/style.vars.css", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/style.vars.css`))
app.get("/.css/style.prism.css", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/prismjs/themes/prism-tomorrow.css`))
//Scripts
app.get("/.js/app.js", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/app.js`))
app.get("/.js/app.placeholder.js", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/app.placeholder.js`))
app.get("/.js/ejs.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/ejs/ejs.min.js`))
app.get("/.js/faker.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/faker/dist/faker.min.js`))
app.get("/.js/axios.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/axios/dist/axios.min.js`))
app.get("/.js/axios.min.map", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/axios/dist/axios.min.map`))
app.get("/.js/vue.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/vue/dist/vue.min.js`))
app.get("/.js/vue.prism.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/vue-prism-component/dist/vue-prism-component.min.js`))
app.get("/.js/vue-prism-component.min.js.map", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/vue-prism-component/dist/vue-prism-component.min.js.map`))
app.get("/.js/prism.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/prismjs/prism.js`))
app.get("/.js/prism.yaml.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/prismjs/components/prism-yaml.min.js`))
app.get("/.js/prism.markdown.min.js", limiter, (req, res) => res.sendFile(`${conf.paths.node_modules}/prismjs/components/prism-markdown.min.js`))
//Meta
app.get("/.version", limiter, (req, res) => res.status(200).send(conf.package.version))
app.get("/.requests", limiter, (req, res) => res.status(200).json(requests))
app.get("/.hosted", limiter, (req, res) => res.status(200).json(conf.settings.hosted || null))
//Cache
app.get("/.uncache", limiter, (req, res) => {
const {token, user} = req.query
if (token) {
if (actions.flush.has(token)) {
console.debug(`metrics/app/${actions.flush.get(token)} > flushed cache`)
cache.del(actions.flush.get(token))
return res.sendStatus(200)
}
return res.sendStatus(400)
}
{
const token = `${Math.random().toString(16).replace("0.", "")}${Math.random().toString(16).replace("0.", "")}`
actions.flush.set(token, user)
return res.json({token})
}
})
//About routes
app.use("/about/.statics/", express.static(`${conf.paths.statics}/about`))
app.get("/about/", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/about/index.html`))
app.get("/about/index.html", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/about/index.html`))
app.get("/about/:login", limiter, (req, res) => res.sendFile(`${conf.paths.statics}/about/index.html`))
app.get("/about/query/:login/", ...middlewares, async (req, res) => {
//Check username
const login = req.params.login?.replace(/[\n\r]/g, "")
if (!/^[-\w]+$/i.test(login)) {
console.debug(`metrics/app/${login}/insights > 400 (invalid username)`)
return res.status(400).send("Bad request: username seems invalid")
}
//Compute metrics
try {
//Read cached data if possible
if ((!debug) && (cached) && (cache.get(`about.${login}`))) {
console.debug(`metrics/app/${login}/insights > using cached results`)
return res.send(cache.get(`about.${login}`))
}
//Compute metrics
console.debug(`metrics/app/${login}/insights > compute insights`)
const json = await metrics(
{
login,
q:{
template:"classic",
achievements:true,
"achievements.threshold":"X",
isocalendar:true,
"isocalendar.duration":"full-year",
languages:true,
"languages.limit":0,
activity:true,
"activity.limit":100,
"activity.days":0,
notable:true,
},
},
{graphql, rest, plugins:{achievements:{enabled:true}, isocalendar:{enabled:true}, languages:{enabled:true}, activity:{enabled:true, markdown:"extended"}, notable:{enabled:true}}, conf, convert:"json"},
{Plugins, Templates},
)
//Cache
if ((!debug) && (cached)) {
const maxage = Math.round(Number(req.query.cache))
cache.put(`about.${login}`, json, maxage > 0 ? maxage : cached)
}
return res.json(json)
}
//Internal error
catch (error) {
//Not found user
if ((error instanceof Error) && (/^user not found$/.test(error.message))) {
console.debug(`metrics/app/${login} > 404 (user/organization not found)`)
return res.status(404).send("Not found: unknown user or organization")
}
//GitHub failed request
if ((error instanceof Error) && (/this may be the result of a timeout, or it could be a GitHub bug/i.test(error.errors?.[0]?.message))) {
console.debug(`metrics/app/${login} > 502 (bad gateway from GitHub)`)
const request = encodeURIComponent(error.errors[0].message.match(/`(?<request>[\w:]+)`/)?.groups?.request ?? "").replace(/%3A/g, ":")
return res.status(500).send(`Internal Server Error: failed to execute request ${request} (this may be the result of a timeout, or it could be a GitHub bug)`)
}
//General error
console.error(error)
return res.status(500).send("Internal Server Error: failed to process metrics correctly")
}
})
//Metrics
const pending = new Map()
app.get("/:login/:repository?", ...middlewares, async (req, res) => {
//Request params
const login = req.params.login?.replace(/[\n\r]/g, "")
const repository = req.params.repository?.replace(/[\n\r]/g, "")
let solve = null
//Check username
if (!/^[-\w]+$/i.test(login)) {
console.debug(`metrics/app/${login} > 400 (invalid username)`)
return res.status(400).send("Bad request: username seems invalid")
}
//Allowed list check
if ((restricted.length) && (!restricted.includes(login))) {
console.debug(`metrics/app/${login} > 403 (not in allowed users)`)
return res.status(403).send("Forbidden: username not in allowed list")
}
//Prevent multiples requests
if ((!debug) && (!mock) && (pending.has(login))) {
console.debug(`metrics/app/${login} > awaiting pending request`)
await pending.get(login)
}
else
pending.set(login, new Promise(_solve => solve = _solve))
//Read cached data if possible
if ((!debug) && (cached) && (cache.get(login))) {
console.debug(`metrics/app/${login} > using cached image`)
const {rendered, mime} = cache.get(login)
res.header("Content-Type", mime)
return res.send(rendered)
}
//Maximum simultaneous users
if ((maxusers) && (cache.size() + 1 > maxusers)) {
console.debug(`metrics/app/${login} > 503 (maximum users reached)`)
return res.status(503).send("Service Unavailable: maximum number of users reached, only cached metrics are available")
}
//Repository alias
if (repository) {
console.debug(`metrics/app/${login} > compute repository metrics`)
if (!req.query.template)
req.query.template = "repository"
req.query.repo = repository
}
//Compute rendering
try {
//Render
const q = req.query
console.debug(`metrics/app/${login} > ${util.inspect(q, {depth:Infinity, maxStringLength:256})}`)
const {rendered, mime} = await metrics({login, q}, {
graphql,
rest,
plugins,
conf,
die:q["plugins.errors.fatal"] ?? false,
verify:q.verify ?? false,
convert:["svg", "jpeg", "png", "json", "markdown", "markdown-pdf"].includes(q["config.output"]) ? q["config.output"] : null,
}, {Plugins, Templates})
//Cache
if ((!debug) && (cached)) {
const maxage = Math.round(Number(req.query.cache))
cache.put(login, {rendered, mime}, maxage > 0 ? maxage : cached)
}
//Send response
res.header("Content-Type", mime)
return res.send(rendered)
}
//Internal error
catch (error) {
//Not found user
if ((error instanceof Error) && (/^user not found$/.test(error.message))) {
console.debug(`metrics/app/${login} > 404 (user/organization not found)`)
return res.status(404).send("Not found: unknown user or organization")
}
//Invalid template
if ((error instanceof Error) && (/^unsupported template$/.test(error.message))) {
console.debug(`metrics/app/${login} > 400 (bad request)`)
return res.status(400).send("Bad request: unsupported template")
}
//Unsupported output format or account type
if ((error instanceof Error) && (/^not supported for: [\s\S]*$/.test(error.message))) {
console.debug(`metrics/app/${login} > 406 (Not Acceptable)`)
return res.status(406).send("Not Acceptable: unsupported output format or account type for specified parameters")
}
//GitHub failed request
if ((error instanceof Error) && (/this may be the result of a timeout, or it could be a GitHub bug/i.test(error.errors?.[0]?.message))) {
console.debug(`metrics/app/${login} > 502 (bad gateway from GitHub)`)
const request = encodeURIComponent(error.errors[0].message.match(/`(?<request>[\w:]+)`/)?.groups?.request ?? "").replace(/%3A/g, ":")
return res.status(500).send(`Internal Server Error: failed to execute request ${request} (this may be the result of a timeout, or it could be a GitHub bug)`)
}
//General error
console.error(error)
return res.status(500).send("Internal Server Error: failed to process metrics correctly")
}
finally {
//After rendering
solve?.()
}
})
//Listen
app.listen(port, () => console.log([
`Listening on port │ ${port}`,
`Debug mode │ ${debug}`,
`Mocked data │ ${conf.settings.mocked ?? false}`,
`Restricted to users │ ${restricted.size ? [...restricted].join(", ") : "(unrestricted)"}`,
`Cached time │ ${cached} seconds`,
`Rate limiter │ ${ratelimiter ? util.inspect(ratelimiter, {depth:Infinity, maxStringLength:256}) : "(enabled)"}`,
`Max simultaneous users │ ${maxusers ? `${maxusers} users` : "(unrestricted)"}`,
`Plugins enabled │ ${enabled.map(({name}) => name).join(", ")}`,
`SVG optimization │ ${conf.settings.optimize ?? false}`,
"Server ready !",
].join("\n")))
}

View File

@@ -1,143 +1,145 @@
;(async function() {
//App
return new Vue({
//Initialization
el:"main",
async mounted() {
//Palette
try {
this.palette = (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light")
} catch (error) {}
//User
const user = location.pathname.split("/").pop()
if ((user)&&(user !== "about")) {
this.user = user
await this.search()
}
else
this.searchable = true
//Embed
this.embed = !!(new URLSearchParams(location.search).get("embed"))
//Init
await Promise.all([
//GitHub limit tracker
(async () => {
const {data:requests} = await axios.get("/.requests")
this.requests = requests
})(),
//Version
(async () => {
const {data:version} = await axios.get("/.version")
this.version = `v${version}`
})(),
//Hosted
(async () => {
const {data:hosted} = await axios.get("/.hosted")
this.hosted = hosted
})(),
])
return new Vue({
//Initialization
el: "main",
async mounted() {
//Palette
try {
this.palette = (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light")
}
catch (error) {}
//User
const user = location.pathname.split("/").pop()
if ((user) && (user !== "about")) {
this.user = user
await this.search()
}
else {
this.searchable = true
}
//Embed
this.embed = !!(new URLSearchParams(location.search).get("embed"))
//Init
await Promise.all([
//GitHub limit tracker
(async () => {
const { data: requests } = await axios.get("/.requests")
this.requests = requests
})(),
//Version
(async () => {
const { data: version } = await axios.get("/.version")
this.version = `v${version}`
})(),
//Hosted
(async () => {
const { data: hosted } = await axios.get("/.hosted")
this.hosted = hosted
})(),
])
},
//Watchers
watch: {
palette: {
immediate: true,
handler(current, previous) {
document.querySelector("body").classList.remove(previous)
document.querySelector("body").classList.add(current)
},
//Watchers
watch:{
palette:{
immediate:true,
handler(current, previous) {
document.querySelector("body").classList.remove(previous)
document.querySelector("body").classList.add(current)
}
}
},
//Methods
methods:{
format(type, value, options) {
switch (type) {
case "number":
return new Intl.NumberFormat(navigator.lang, options).format(value)
case "date":
return new Intl.DateTimeFormat(navigator.lang, options).format(new Date(value))
case "comment":
const baseUrl = String.raw`https?:\/\/(?:www\.)?github.com\/([\w.-]+\/[\w.-]+)\/`
return value
.replace(
RegExp(baseUrl + String.raw`(?:issues|pull|discussions)\/(\d+)(?:\?\S+)?(#\S+)?`, 'g'),
(_, repo, id, comment) => (options?.repo === repo ? '' : repo) + `#${id}` + (comment ? ` (comment)` : '')
) // -> 'lowlighter/metrics#123'
.replace(
RegExp(baseUrl + String.raw`commit\/([\da-f]+)`, 'g'),
(_, repo, sha) => (options?.repo === repo ? '' : repo + '@') + sha
) // -> 'lowlighter/metrics@123abc'
.replace(
RegExp(baseUrl + String.raw`compare\/(\S+...\S+)`, 'g'),
(_, repo, tags) => (options?.repo === repo ? '' : repo + '@') + tags
) // -> 'lowlighter/metrics@1.0...1.1'
}
},
},
//Methods
methods: {
format(type, value, options) {
switch (type) {
case "number":
return new Intl.NumberFormat(navigator.lang, options).format(value)
case "date":
return new Intl.DateTimeFormat(navigator.lang, options).format(new Date(value))
case "comment":
const baseUrl = String.raw`https?:\/\/(?:www\.)?github.com\/([\w.-]+\/[\w.-]+)\/`
return value
},
async search() {
try {
this.error = null
this.metrics = null
this.pending = true
this.metrics = (await axios.get(`/about/query/${this.user}`)).data
}
catch (error) {
this.error = {code:error.response.status, message:error.response.data}
}
finally {
this.pending = false
}
}
},
//Computed properties
computed:{
ranked() {
return this.metrics?.rendered.plugins.achievements.list?.filter(({leaderboard}) => leaderboard).sort((a, b) => a.leaderboard.type.localeCompare(b.leaderboard.type)) ?? []
},
achievements() {
return this.metrics?.rendered.plugins.achievements.list?.filter(({leaderboard}) => !leaderboard).filter(({title}) => !/(?:automater|octonaut|infographile)/i.test(title)) ?? []
},
isocalendar() {
return (this.metrics?.rendered.plugins.isocalendar.svg ?? "")
.replace(/#ebedf0/gi, "var(--color-calendar-graph-day-bg)")
.replace(/#9be9a8/gi, "var(--color-calendar-graph-day-L1-bg)")
.replace(/#40c463/gi, "var(--color-calendar-graph-day-L2-bg)")
.replace(/#30a14e/gi, "var(--color-calendar-graph-day-L3-bg)")
.replace(/#216e39/gi, "var(--color-calendar-graph-day-L4-bg)")
},
languages() {
return this.metrics?.rendered.plugins.languages.favorites ?? []
},
activity() {
return this.metrics?.rendered.plugins.activity.events ?? []
},
contributions() {
return this.metrics?.rendered.plugins.notable.contributions ?? []
},
account() {
if (!this.metrics)
return null
const {login, name} = this.metrics.rendered.user
return {login, name, avatar:this.metrics.rendered.computed.avatar, type:this.metrics?.rendered.account}
},
url() {
return `${window.location.protocol}//${window.location.host}/about/${this.user}`
},
preview() {
return /-preview$/.test(this.version)
}
},
//Data initialization
data:{
version:"",
hosted:null,
user:"",
embed:false,
searchable:false,
requests:{limit:0, used:0, remaining:0, reset:0},
palette:"light",
metrics:null,
pending:false,
error:null,
.replace(
RegExp(baseUrl + String.raw`(?:issues|pull|discussions)\/(\d+)(?:\?\S+)?(#\S+)?`, "g"),
(_, repo, id, comment) => (options?.repo === repo ? "" : repo) + `#${id}` + (comment ? ` (comment)` : ""),
) // -> 'lowlighter/metrics#123'
.replace(
RegExp(baseUrl + String.raw`commit\/([\da-f]+)`, "g"),
(_, repo, sha) => (options?.repo === repo ? "" : repo + "@") + sha,
) // -> 'lowlighter/metrics@123abc'
.replace(
RegExp(baseUrl + String.raw`compare\/(\S+...\S+)`, "g"),
(_, repo, tags) => (options?.repo === repo ? "" : repo + "@") + tags,
) // -> 'lowlighter/metrics@1.0...1.1'
}
})
return value
},
async search() {
try {
this.error = null
this.metrics = null
this.pending = true
this.metrics = (await axios.get(`/about/query/${this.user}`)).data
}
catch (error) {
this.error = { code: error.response.status, message: error.response.data }
}
finally {
this.pending = false
}
},
},
//Computed properties
computed: {
ranked() {
return this.metrics?.rendered.plugins.achievements.list?.filter(({ leaderboard }) => leaderboard).sort((a, b) => a.leaderboard.type.localeCompare(b.leaderboard.type)) ?? []
},
achievements() {
return this.metrics?.rendered.plugins.achievements.list?.filter(({ leaderboard }) => !leaderboard).filter(({ title }) => !/(?:automater|octonaut|infographile)/i.test(title)) ?? []
},
isocalendar() {
return (this.metrics?.rendered.plugins.isocalendar.svg ?? "")
.replace(/#ebedf0/gi, "var(--color-calendar-graph-day-bg)")
.replace(/#9be9a8/gi, "var(--color-calendar-graph-day-L1-bg)")
.replace(/#40c463/gi, "var(--color-calendar-graph-day-L2-bg)")
.replace(/#30a14e/gi, "var(--color-calendar-graph-day-L3-bg)")
.replace(/#216e39/gi, "var(--color-calendar-graph-day-L4-bg)")
},
languages() {
return this.metrics?.rendered.plugins.languages.favorites ?? []
},
activity() {
return this.metrics?.rendered.plugins.activity.events ?? []
},
contributions() {
return this.metrics?.rendered.plugins.notable.contributions ?? []
},
account() {
if (!this.metrics)
return null
const { login, name } = this.metrics.rendered.user
return { login, name, avatar: this.metrics.rendered.computed.avatar, type: this.metrics?.rendered.account }
},
url() {
return `${window.location.protocol}//${window.location.host}/about/${this.user}`
},
preview() {
return /-preview$/.test(this.version)
},
},
//Data initialization
data: {
version: "",
hosted: null,
user: "",
embed: false,
searchable: false,
requests: { limit: 0, used: 0, remaining: 0, reset: 0 },
palette: "light",
metrics: null,
pending: false,
error: null,
},
})
})()

View File

@@ -1,256 +1,264 @@
;(async function() {
//Init
const {data:metadata} = await axios.get("/.plugins.metadata")
delete metadata.core.web.output
delete metadata.core.web.twemojis
const { data: metadata } = await axios.get("/.plugins.metadata")
delete metadata.core.web.output
delete metadata.core.web.twemojis
//App
return new Vue({
//Initialization
el:"main",
async mounted() {
//Interpolate config from browser
try {
this.config.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
this.palette = (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light")
} catch (error) {}
//Init
await Promise.all([
//GitHub limit tracker
(async () => {
const {data:requests} = await axios.get("/.requests")
this.requests = requests
})(),
//Templates
(async () => {
const {data:templates} = await axios.get("/.templates")
templates.sort((a, b) => (a.name.startsWith("@") ^ b.name.startsWith("@")) ? (a.name.startsWith("@") ? 1 : -1) : a.name.localeCompare(b.name))
this.templates.list = templates
this.templates.selected = templates[0]?.name||"classic"
})(),
//Plugins
(async () => {
const {data:plugins} = await axios.get("/.plugins")
this.plugins.list = plugins
})(),
//Base
(async () => {
const {data:base} = await axios.get("/.plugins.base")
this.plugins.base = base
this.plugins.enabled.base = Object.fromEntries(base.map(key => [key, true]))
})(),
//Version
(async () => {
const {data:version} = await axios.get("/.version")
this.version = `v${version}`
})(),
//Hosted
(async () => {
const {data:hosted} = await axios.get("/.hosted")
this.hosted = hosted
})(),
])
//Generate placeholder
this.mock({timeout:200})
setInterval(() => {
const marker = document.querySelector("#metrics-end")
if (marker) {
this.mockresize()
marker.remove()
}
}, 100)
return new Vue({
//Initialization
el: "main",
async mounted() {
//Interpolate config from browser
try {
this.config.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
this.palette = (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light")
}
catch (error) {}
//Init
await Promise.all([
//GitHub limit tracker
(async () => {
const { data: requests } = await axios.get("/.requests")
this.requests = requests
})(),
//Templates
(async () => {
const { data: templates } = await axios.get("/.templates")
templates.sort((a, b) => (a.name.startsWith("@") ^ b.name.startsWith("@")) ? (a.name.startsWith("@") ? 1 : -1) : a.name.localeCompare(b.name))
this.templates.list = templates
this.templates.selected = templates[0]?.name || "classic"
})(),
//Plugins
(async () => {
const { data: plugins } = await axios.get("/.plugins")
this.plugins.list = plugins
})(),
//Base
(async () => {
const { data: base } = await axios.get("/.plugins.base")
this.plugins.base = base
this.plugins.enabled.base = Object.fromEntries(base.map(key => [key, true]))
})(),
//Version
(async () => {
const { data: version } = await axios.get("/.version")
this.version = `v${version}`
})(),
//Hosted
(async () => {
const { data: hosted } = await axios.get("/.hosted")
this.hosted = hosted
})(),
])
//Generate placeholder
this.mock({ timeout: 200 })
setInterval(() => {
const marker = document.querySelector("#metrics-end")
if (marker) {
this.mockresize()
marker.remove()
}
}, 100)
},
components: { Prism: PrismComponent },
//Watchers
watch: {
palette: {
immediate: true,
handler(current, previous) {
document.querySelector("body").classList.remove(previous)
document.querySelector("body").classList.add(current)
},
components:{Prism:PrismComponent},
//Watchers
watch:{
palette:{
immediate:true,
handler(current, previous) {
document.querySelector("body").classList.remove(previous)
document.querySelector("body").classList.add(current)
}
}
},
},
//Data initialization
data: {
version: "",
user: "",
mode: "metrics",
tab: "overview",
palette: "light",
requests: { limit: 0, used: 0, remaining: 0, reset: 0 },
cached: new Map(),
config: Object.fromEntries(Object.entries(metadata.core.web).map(([key, { defaulted }]) => [key, defaulted])),
metadata: Object.fromEntries(Object.entries(metadata).map(([key, { web }]) => [key, web])),
hosted: null,
plugins: {
base: {},
list: [],
enabled: {},
descriptions: {
base: "🗃️ Base content",
"base.header": "Header",
"base.activity": "Account activity",
"base.community": "Community stats",
"base.repositories": "Repositories metrics",
"base.metadata": "Metadata",
...Object.fromEntries(Object.entries(metadata).map(([key, { name }]) => [key, name])),
},
//Data initialization
data:{
version:"",
user:"",
mode:"metrics",
tab:"overview",
palette:"light",
requests:{limit:0, used:0, remaining:0, reset:0},
cached:new Map(),
config:Object.fromEntries(Object.entries(metadata.core.web).map(([key, {defaulted}]) => [key, defaulted])),
metadata:Object.fromEntries(Object.entries(metadata).map(([key, {web}]) => [key, web])),
hosted:null,
plugins:{
base:{},
list:[],
enabled:{},
descriptions:{
base:"🗃️ Base content",
"base.header":"Header",
"base.activity":"Account activity",
"base.community":"Community stats",
"base.repositories":"Repositories metrics",
"base.metadata":"Metadata",
...Object.fromEntries(Object.entries(metadata).map(([key, {name}]) => [key, name]))
},
options:{
descriptions:{...(Object.assign({}, ...Object.entries(metadata).flatMap(([key, {web}]) => web)))},
...(Object.fromEntries(Object.entries(
Object.assign({}, ...Object.entries(metadata).flatMap(([key, {web}]) => web)))
.map(([key, {defaulted}]) => [key, defaulted])
))
},
},
templates:{
list:[],
selected:"classic",
placeholder:{
timeout:null,
image:""
},
descriptions:{
classic:"Classic template",
terminal:"Terminal template",
markdown:"(hidden)",
repository:"(hidden)",
},
},
generated:{
pending:false,
content:"",
error:false,
},
options: {
descriptions: { ...(Object.assign({}, ...Object.entries(metadata).flatMap(([key, { web }]) => web))) },
...(Object.fromEntries(
Object.entries(
Object.assign({}, ...Object.entries(metadata).flatMap(([key, { web }]) => web)),
)
.map(([key, { defaulted }]) => [key, defaulted]),
)),
},
//Computed data
computed:{
//Unusable plugins
unusable() {
return this.plugins.list.filter(({name}) => this.plugins.enabled[name]).filter(({enabled}) => !enabled).map(({name}) => name)
},
//User's avatar
avatar() {
return this.generated.content ? `https://github.com/${this.user}.png` : null
},
//User's repository
repo() {
return `https://github.com/${this.user}/${this.user}`
},
//Endpoint to use for computed metrics
url() {
//Plugins enabled
const plugins = Object.entries(this.plugins.enabled)
.flatMap(([key, value]) => key === "base" ? Object.entries(value).map(([key, value]) => [`base.${key}`, value]) : [[key, value]])
.filter(([key, value]) => /^base[.]\w+$/.test(key) ? !value : value)
.map(([key, value]) => `${key}=${+value}`)
//Plugins options
const options = Object.entries(this.plugins.options)
.filter(([key, value]) => `${value}`.length)
.filter(([key, value]) => this.plugins.enabled[key.split(".")[0]])
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
//Base options
const base = Object.entries(this.plugins.options).filter(([key, value]) => (key in metadata.base.web)&&(value !== metadata.base.web[key]?.defaulted)).map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
//Config
const config = Object.entries(this.config).filter(([key, value]) => (value)&&(value !== metadata.core.web[key]?.defaulted)).map(([key, value]) => `config.${key}=${encodeURIComponent(value)}`)
//Template
const template = (this.templates.selected !== this.templates.list[0]) ? [`template=${this.templates.selected}`] : []
//Generated url
const params = [...template, ...base, ...plugins, ...options, ...config].join("&")
return `${window.location.protocol}//${window.location.host}/${this.user}${params.length ? `?${params}` : ""}`
},
//Embedded generated code
embed() {
return `![Metrics](${this.url})`
},
//GitHub action auto-generated code
action() {
return [
`# Visit https://github.com/lowlighter/metrics/blob/master/action.yml for full reference`,
`name: Metrics`,
`on:`,
` # Schedule updates (each hour)`,
` schedule: [{cron: "0 * * * *"}]`,
` # Lines below let you run workflow manually and on each commit`,
` workflow_dispatch:`,
` push: {branches: ["master", "main"]}`,
`jobs:`,
` github-metrics:`,
` runs-on: ubuntu-latest`,
` steps:`,
` - uses: lowlighter/metrics@latest`,
` with:`,
` # Your GitHub token`,
` token: ${"$"}{{ secrets.METRICS_TOKEN }}`,
``,
` # Options`,
` user: ${this.user }`,
` template: ${this.templates.selected}`,
` base: ${Object.entries(this.plugins.enabled.base).filter(([key, value]) => value).map(([key]) => key).join(", ")||'""'}`,
...[
...Object.entries(this.plugins.options).filter(([key, value]) => (key in metadata.base.web)&&(value !== metadata.base.web[key]?.defaulted)).map(([key, value]) => ` ${key.replace(/[.]/, "_")}: ${typeof value === "boolean" ? {true:"yes", false:"no"}[value] : value}`),
...Object.entries(this.plugins.enabled).filter(([key, value]) => (key !== "base")&&(value)).map(([key]) => ` plugin_${key}: yes`),
...Object.entries(this.plugins.options).filter(([key, value]) => value).filter(([key, value]) => this.plugins.enabled[key.split(".")[0]]).map(([key, value]) => ` plugin_${key.replace(/[.]/, "_")}: ${typeof value === "boolean" ? {true:"yes", false:"no"}[value] : value}`),
...Object.entries(this.config).filter(([key, value]) => (value)&&(value !== metadata.core.web[key]?.defaulted)).map(([key, value]) => ` config_${key.replace(/[.]/, "_")}: ${typeof value === "boolean" ? {true:"yes", false:"no"}[value] : value}`),
].sort(),
].join("\n")
},
//Configurable plugins
configure() {
//Check enabled plugins
const enabled = Object.entries(this.plugins.enabled).filter(([key, value]) => (value)&&(key !== "base")).map(([key, value]) => key)
const filter = new RegExp(`^(?:${enabled.join("|")})[.]`)
//Search related options
const entries = Object.entries(this.plugins.options.descriptions).filter(([key, value]) => filter.test(key))
entries.push(...enabled.map(key => [key, this.plugins.descriptions[key]]))
entries.sort((a, b) => a[0].localeCompare(b[0]))
//Return object
const configure = Object.fromEntries(entries)
return Object.keys(configure).length ? configure : null
},
//Is in preview mode
preview() {
return /-preview$/.test(this.version)
}
},
templates: {
list: [],
selected: "classic",
placeholder: {
timeout: null,
image: "",
},
//Methods
methods:{
//Load and render placeholder image
async mock({timeout = 600} = {}) {
clearTimeout(this.templates.placeholder.timeout)
this.templates.placeholder.timeout = setTimeout(async () => {
this.templates.placeholder.image = await placeholder(this)
this.generated.content = ""
this.generated.error = null
}, timeout)
},
//Resize mock image
mockresize() {
const svg = document.querySelector(".preview .image svg")
if ((svg)&&(svg.getAttribute("height") == 99999)) {
const height = svg.querySelector("#metrics-end")?.getBoundingClientRect()?.y-svg.getBoundingClientRect()?.y
if (Number.isFinite(height))
svg.setAttribute("height", height)
}
},
//Generate metrics and flush cache
async generate() {
//Avoid requests spamming
if (this.generated.pending)
return
this.generated.pending = true
//Compute metrics
try {
await axios.get(`/.uncache?&token=${(await axios.get(`/.uncache?user=${this.user}`)).data.token}`)
this.generated.content = (await axios.get(this.url)).data
this.generated.error = null
} catch (error) {
this.generated.error = {code:error.response.status, message:error.response.data}
}
finally {
this.generated.pending = false
}
},
descriptions: {
classic: "Classic template",
terminal: "Terminal template",
markdown: "(hidden)",
repository: "(hidden)",
},
})
})()
},
generated: {
pending: false,
content: "",
error: false,
},
},
//Computed data
computed: {
//Unusable plugins
unusable() {
return this.plugins.list.filter(({ name }) => this.plugins.enabled[name]).filter(({ enabled }) => !enabled).map(({ name }) => name)
},
//User's avatar
avatar() {
return this.generated.content ? `https://github.com/${this.user}.png` : null
},
//User's repository
repo() {
return `https://github.com/${this.user}/${this.user}`
},
//Endpoint to use for computed metrics
url() {
//Plugins enabled
const plugins = Object.entries(this.plugins.enabled)
.flatMap(([key, value]) => key === "base" ? Object.entries(value).map(([key, value]) => [`base.${key}`, value]) : [[key, value]])
.filter(([key, value]) => /^base[.]\w+$/.test(key) ? !value : value)
.map(([key, value]) => `${key}=${+value}`)
//Plugins options
const options = Object.entries(this.plugins.options)
.filter(([key, value]) => `${value}`.length)
.filter(([key, value]) => this.plugins.enabled[key.split(".")[0]])
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
//Base options
const base = Object.entries(this.plugins.options).filter(([key, value]) => (key in metadata.base.web) && (value !== metadata.base.web[key]?.defaulted)).map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
//Config
const config = Object.entries(this.config).filter(([key, value]) => (value) && (value !== metadata.core.web[key]?.defaulted)).map(([key, value]) => `config.${key}=${encodeURIComponent(value)}`)
//Template
const template = (this.templates.selected !== this.templates.list[0]) ? [`template=${this.templates.selected}`] : []
//Generated url
const params = [...template, ...base, ...plugins, ...options, ...config].join("&")
return `${window.location.protocol}//${window.location.host}/${this.user}${params.length ? `?${params}` : ""}`
},
//Embedded generated code
embed() {
return `![Metrics](${this.url})`
},
//GitHub action auto-generated code
action() {
return [
`# Visit https://github.com/lowlighter/metrics/blob/master/action.yml for full reference`,
`name: Metrics`,
`on:`,
` # Schedule updates (each hour)`,
` schedule: [{cron: "0 * * * *"}]`,
` # Lines below let you run workflow manually and on each commit`,
` workflow_dispatch:`,
` push: {branches: ["master", "main"]}`,
`jobs:`,
` github-metrics:`,
` runs-on: ubuntu-latest`,
` steps:`,
` - uses: lowlighter/metrics@latest`,
` with:`,
` # Your GitHub token`,
` token: ${"$"}{{ secrets.METRICS_TOKEN }}`,
``,
` # Options`,
` user: ${this.user}`,
` template: ${this.templates.selected}`,
` base: ${Object.entries(this.plugins.enabled.base).filter(([key, value]) => value).map(([key]) => key).join(", ") || '""'}`,
...[
...Object.entries(this.plugins.options).filter(([key, value]) => (key in metadata.base.web) && (value !== metadata.base.web[key]?.defaulted)).map(([key, value]) =>
` ${key.replace(/[.]/, "_")}: ${typeof value === "boolean" ? { true: "yes", false: "no" }[value] : value}`
),
...Object.entries(this.plugins.enabled).filter(([key, value]) => (key !== "base") && (value)).map(([key]) => ` plugin_${key}: yes`),
...Object.entries(this.plugins.options).filter(([key, value]) => value).filter(([key, value]) => this.plugins.enabled[key.split(".")[0]]).map(([key, value]) =>
` plugin_${key.replace(/[.]/, "_")}: ${typeof value === "boolean" ? { true: "yes", false: "no" }[value] : value}`
),
...Object.entries(this.config).filter(([key, value]) => (value) && (value !== metadata.core.web[key]?.defaulted)).map(([key, value]) => ` config_${key.replace(/[.]/, "_")}: ${typeof value === "boolean" ? { true: "yes", false: "no" }[value] : value}`),
].sort(),
].join("\n")
},
//Configurable plugins
configure() {
//Check enabled plugins
const enabled = Object.entries(this.plugins.enabled).filter(([key, value]) => (value) && (key !== "base")).map(([key, value]) => key)
const filter = new RegExp(`^(?:${enabled.join("|")})[.]`)
//Search related options
const entries = Object.entries(this.plugins.options.descriptions).filter(([key, value]) => filter.test(key))
entries.push(...enabled.map(key => [key, this.plugins.descriptions[key]]))
entries.sort((a, b) => a[0].localeCompare(b[0]))
//Return object
const configure = Object.fromEntries(entries)
return Object.keys(configure).length ? configure : null
},
//Is in preview mode
preview() {
return /-preview$/.test(this.version)
},
},
//Methods
methods: {
//Load and render placeholder image
async mock({ timeout = 600 } = {}) {
clearTimeout(this.templates.placeholder.timeout)
this.templates.placeholder.timeout = setTimeout(async () => {
this.templates.placeholder.image = await placeholder(this)
this.generated.content = ""
this.generated.error = null
}, timeout)
},
//Resize mock image
mockresize() {
const svg = document.querySelector(".preview .image svg")
if ((svg) && (svg.getAttribute("height") == 99999)) {
const height = svg.querySelector("#metrics-end")?.getBoundingClientRect()?.y - svg.getBoundingClientRect()?.y
if (Number.isFinite(height))
svg.setAttribute("height", height)
}
},
//Generate metrics and flush cache
async generate() {
//Avoid requests spamming
if (this.generated.pending)
return
this.generated.pending = true
//Compute metrics
try {
await axios.get(`/.uncache?&token=${(await axios.get(`/.uncache?user=${this.user}`)).data.token}`)
this.generated.content = (await axios.get(this.url)).data
this.generated.error = null
}
catch (error) {
this.generated.error = { code: error.response.status, message: error.response.data }
}
finally {
this.generated.pending = false
}
},
},
})
})()

File diff suppressed because it is too large Load Diff